code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package com.weffle.table.payment; import com.weffle.object.BaseObject; public class Payment extends BaseObject<PaymentData> { public Payment() { super(PaymentData.id); setAutoKey(); } public Payment(int id) { super(PaymentData.id, id); setAutoKey(); } }
DrPrykhodko/Marro
src/com/weffle/table/payment/Payment.java
Java
gpl-3.0
305
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.frontend.client.extension.event; /** * HasNavigatorEvent * * * @author jllort * */ public interface HasNavigatorEvent { /** * NavigatorEventConstant * * @author jllort * */ public static class NavigatorEventConstant { static final int EVENT_STACK_CHANGED = 1; private int type = 0; /** * ToolBarEventConstant * * @param type */ private NavigatorEventConstant(int type) { this.type = type; } public int getType(){ return type; } } NavigatorEventConstant STACK_CHANGED = new NavigatorEventConstant(NavigatorEventConstant.EVENT_STACK_CHANGED); /** * @param event */ void fireEvent(NavigatorEventConstant event); }
papamas/DMS-KANGREG-XI-MANADO
src/main/java/com/openkm/frontend/client/extension/event/HasNavigatorEvent.java
Java
gpl-3.0
1,665
/** * GetIntervalValueThroughput.java This file is part of WattDepot. * * Copyright (C) 2014 Cam Moore * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.wattdepot.client.http.api.performance; import java.util.Timer; import java.util.TimerTask; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.wattdepot.common.exception.BadCredentialException; import org.wattdepot.common.exception.BadSensorUriException; import org.wattdepot.common.exception.IdNotFoundException; /** * GetIntervalValueThroughput - Attempts to determine the maximum rate of * getting the value for an interval for a Sensor in a WattDepot installation. * * @author Cam Moore * */ public class GetIntervalValueThroughput extends TimerTask { /** Manages the GetIntervalValueTasks. */ private Timer timer; /** The GetIntervalValueTask we will sample. */ private GetIntervalValueTask sampleTask; /** The WattDepot server's URI. */ private String serverUri; /** The WattDepot User. */ private String username; /** The WattDepot User's organization. */ private String orgId; /** The WattDepot User's password. */ private String password; /** Flag for debugging. */ private boolean debug; /** The number of times we've checked the stats. */ private Integer numChecks; private DescriptiveStatistics averageGetTime; private DescriptiveStatistics averageMinGetTime; private DescriptiveStatistics averageMaxGetTime; private Long getsPerSec; private Long calculatedGetsPerSec; /** * Initializes the GetIntervalValueThroughput instance. * * @param serverUri The URI for the WattDepot server. * @param username The name of a user defined in the WattDepot server. * @param orgId the id of the organization the user is in. * @param password The password for the user. * @param debug flag for debugging messages. * @throws BadCredentialException if the user or password don't match the * credentials in WattDepot. * @throws IdNotFoundException if the processId is not defined. * @throws BadSensorUriException if the Sensor's URI isn't valid. */ public GetIntervalValueThroughput(String serverUri, String username, String orgId, String password, boolean debug) throws BadCredentialException, IdNotFoundException, BadSensorUriException { this.serverUri = serverUri; this.username = username; this.orgId = orgId; this.password = password; this.debug = debug; this.numChecks = 0; this.getsPerSec = 1l; this.calculatedGetsPerSec = 1l; this.averageMaxGetTime = new DescriptiveStatistics(); this.averageMinGetTime = new DescriptiveStatistics(); this.averageGetTime = new DescriptiveStatistics(); this.timer = new Timer("throughput"); this.sampleTask = new GetIntervalValueTask(serverUri, username, orgId, password, debug); // Starting at 1 get/second this.timer.schedule(sampleTask, 0, 1000); } /** * @param args command line arguments -s <server uri> -u <username> -p * <password> -o <orgId> -n <numSamples> [-d]. * @throws BadSensorUriException if there is a problem with the WattDepot * sensor definition. * @throws IdNotFoundException if there is a problem with the organization id. * @throws BadCredentialException if the credentials are not valid. */ public static void main(String[] args) throws BadCredentialException, IdNotFoundException, BadSensorUriException { Options options = new Options(); CommandLine cmd = null; String serverUri = null; String username = null; String organizationId = null; String password = null; Integer numSamples = null; boolean debug = false; options.addOption("h", false, "Usage: GetIntervalValueThroughput -s <server uri> -u <username>" + " -p <password> -o <orgId> [-d]"); options.addOption("s", "server", true, "WattDepot Server URI. (http://server.wattdepot.org)"); options.addOption("u", "username", true, "Username"); options.addOption("o", "organizationId", true, "User's Organization id."); options.addOption("p", "password", true, "Password"); options.addOption("n", "numSamples", true, "Number of puts to sample."); options.addOption("d", "debug", false, "Displays statistics as the Gets are made."); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Command line parsing failed. Reason: " + e.getMessage() + ". Exiting."); System.exit(1); } if (cmd.hasOption("h")) { formatter.printHelp("GetIntervalValueThroughput", options); System.exit(0); } if (cmd.hasOption("s")) { serverUri = cmd.getOptionValue("s"); } else { serverUri = "http://server.wattdepot.org/"; } if (cmd.hasOption("u")) { username = cmd.getOptionValue("u"); } else { username = "user"; } if (cmd.hasOption("p")) { password = cmd.getOptionValue("p"); } else { password = "default"; } if (cmd.hasOption("o")) { organizationId = cmd.getOptionValue("o"); } else { organizationId = "organization"; } if (cmd.hasOption("n")) { numSamples = Integer.parseInt(cmd.getOptionValue("n")); } else { numSamples = 13; } debug = cmd.hasOption("d"); if (debug) { System.out.println("GetLatestValue Throughput:"); System.out.println(" WattDepotServer: " + serverUri); System.out.println(" Username: " + username); System.out.println(" OrganizationId: " + organizationId); System.out.println(" Password: ********"); System.out.println(" Samples: " + numSamples); } Timer t = new Timer("monitoring"); t.schedule( new GetIntervalValueThroughput(serverUri, username, organizationId, password, debug), 0, numSamples * 1000); } /* * (non-Javadoc) * * @see java.util.TimerTask#run() */ @Override public void run() { // wake up to check the stats. if (this.numChecks == 0) { // haven't actually run so do nothing. this.numChecks++; // should I put a bogus first rate so we don't start too fast? this.averageGetTime.addValue(1.0); // took 1 second per so we start with a // low average. } else { this.timer.cancel(); this.numChecks++; Double aveTime = sampleTask.getAverageTime(); this.averageGetTime.addValue(aveTime / 1E9); this.averageMinGetTime.addValue(sampleTask.getMinTime() / 1E9); this.averageMaxGetTime.addValue(sampleTask.getMaxTime() / 1E9); this.calculatedGetsPerSec = calculateGetRate(averageGetTime); this.getsPerSec = calculatedGetsPerSec; // System.out.println("Min put time = " + (sampleTask.getMinGetTime() / // 1E9)); System.out.println("Ave get value (date, date) time = " + (aveTime / 1E9) + " => " + Math.round(1.0 / (aveTime / 1E9)) + " gets/sec."); // System.out.println("Max put time = " + (sampleTask.getMaxGetTime() / // 1E9)); // System.out.println("Max put rate = " + // calculateGetRate(averageMinGetTime)); System.out.println("Setting rate to " + this.calculatedGetsPerSec); // System.out.println("Min put rate = " + // calculateGetRate(averageMaxGetTime)); this.timer = new Timer("throughput"); this.sampleTask = null; // if (debug) { // System.out.println("Starting " + this.measPerSec + // " threads @ 1 meas/s"); // } for (int i = 0; i < getsPerSec; i++) { try { if (sampleTask == null) { this.sampleTask = new GetIntervalValueTask(serverUri, username, orgId, password, debug); timer.schedule(sampleTask, 0, 1000); if (debug) { System.out.println("Starting task " + i); } } else { timer.schedule(new GetIntervalValueTask(serverUri, username, orgId, password, debug), 0, 1000); if (debug) { System.out.println("Starting task " + i); } } Thread.sleep(10); } catch (BadCredentialException e) { // NOPMD // should not happen. e.printStackTrace(); } catch (IdNotFoundException e) { // NOPMD // should not happen. e.printStackTrace(); } catch (BadSensorUriException e) { // NOPMD // should not happen e.printStackTrace(); } catch (InterruptedException e) { // NOPMD // should not happen e.printStackTrace(); } } } } /** * @param stats the DescriptiveStatistics to calculate the mean put time. * @return The estimated put rate based upon the time it takes to put a single * measurement. */ private Long calculateGetRate(DescriptiveStatistics stats) { double putTime = stats.getMean(); Long ret = null; double numPuts = 1.0 / putTime; ret = Math.round(numPuts); return ret; } }
wattdepot/wattdepot
src/main/java/org/wattdepot/client/http/api/performance/GetIntervalValueThroughput.java
Java
gpl-3.0
10,140
/****************************************************************************** * * Project: ISIS Version 3 Driver * Purpose: Implementation of ISIS3Dataset * Author: Trent Hare (thare@usgs.gov) * Frank Warmerdam (warmerdam@pobox.com) * Even Rouault (even.rouault at spatialys.com) * * NOTE: Original code authored by Trent and placed in the public domain as * per US government policy. I have (within my rights) appropriated it and * placed it under the following license. This is not intended to diminish * Trents contribution. ****************************************************************************** * Copyright (c) 2007, Frank Warmerdam <warmerdam@pobox.com> * Copyright (c) 2009-2010, Even Rouault <even.rouault at spatialys.com> * Copyright (c) 2017 Hobu Inc * Copyright (c) 2017, Dmitry Baryshnikov <polimax@mail.ru> * Copyright (c) 2017, NextGIS <info@nextgis.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "cpl_json.h" #include "cpl_string.h" #include "cpl_time.h" #include "cpl_vsi_error.h" #include "gdal_frmts.h" #include "gdal_proxy.h" #include "nasakeywordhandler.h" #include "ogrgeojsonreader.h" #include "ogr_spatialref.h" #include "rawdataset.h" #include "vrtdataset.h" #include "cpl_safemaths.hpp" // For gethostname() #ifdef _WIN32 #include <winsock2.h> #else #include <unistd.h> #endif #include <algorithm> #include <map> #include <utility> // pair #include <vector> // Constants coming from ISIS3 source code // in isis/src/base/objs/SpecialPixel/SpecialPixel.h //There are several types of special pixels // * Isis::Null Pixel has no data available // * Isis::Lis Pixel was saturated on the instrument // * Isis::His Pixel was saturated on the instrument // * Isis::Lrs Pixel was saturated during a computation // * Isis::Hrs Pixel was saturated during a computation // 1-byte special pixel values const unsigned char NULL1 = 0; const unsigned char LOW_REPR_SAT1 = 0; const unsigned char LOW_INSTR_SAT1 = 0; const unsigned char HIGH_INSTR_SAT1 = 255; const unsigned char HIGH_REPR_SAT1 = 255; // 2-byte unsigned special pixel values const unsigned short NULLU2 = 0; const unsigned short LOW_REPR_SATU2 = 1; const unsigned short LOW_INSTR_SATU2 = 2; const unsigned short HIGH_INSTR_SATU2 = 65534; const unsigned short HIGH_REPR_SATU2 = 65535; // 2-byte signed special pixel values const short NULL2 = -32768; const short LOW_REPR_SAT2 = -32767; const short LOW_INSTR_SAT2 = -32766; const short HIGH_INSTR_SAT2 = -32765; const short HIGH_REPR_SAT2 = -32764; // Define 4-byte special pixel values for IEEE floating point const float NULL4 = -3.4028226550889045e+38f; // 0xFF7FFFFB; const float LOW_REPR_SAT4 = -3.4028228579130005e+38f; // 0xFF7FFFFC; const float LOW_INSTR_SAT4 = -3.4028230607370965e+38f; // 0xFF7FFFFD; const float HIGH_INSTR_SAT4 = -3.4028232635611926e+38f; // 0xFF7FFFFE; const float HIGH_REPR_SAT4 = -3.4028234663852886e+38f; // 0xFF7FFFFF; // Must be large enough to hold an integer static const char* const pszSTARTBYTE_PLACEHOLDER = "!*^STARTBYTE^*!"; // Must be large enough to hold an integer static const char* const pszLABEL_BYTES_PLACEHOLDER = "!*^LABEL_BYTES^*!"; // Must be large enough to hold an integer static const char* const pszHISTORY_STARTBYTE_PLACEHOLDER = "!*^HISTORY_STARTBYTE^*!"; CPL_CVSID("$Id: isis3dataset.cpp c04e0ea92cfb521061e84b9c3ba75b0e30345ffd 2020-07-02 22:27:16 +0200 Even Rouault $") /************************************************************************/ /* ==================================================================== */ /* ISISDataset */ /* ==================================================================== */ /************************************************************************/ class ISIS3Dataset final: public RawDataset { friend class ISIS3RawRasterBand; friend class ISISTiledBand; friend class ISIS3WrapperRasterBand; class NonPixelSection { public: CPLString osSrcFilename; CPLString osDstFilename; // empty for same file vsi_l_offset nSrcOffset; vsi_l_offset nSize; CPLString osPlaceHolder; // empty if not same file }; VSILFILE *m_fpLabel; // label file (only used for writing) VSILFILE *m_fpImage; // image data file. May be == fpLabel GDALDataset *m_poExternalDS; // external dataset (GeoTIFF) bool m_bGeoTIFFAsRegularExternal; // creation only bool m_bGeoTIFFInitDone; // creation only CPLString m_osExternalFilename; bool m_bIsLabelWritten; // creation only bool m_bIsTiled; bool m_bInitToNodata; // creation only NASAKeywordHandler m_oKeywords; bool m_bGotTransform; double m_adfGeoTransform[6]; bool m_bHasSrcNoData; // creation only double m_dfSrcNoData; // creation only OGRSpatialReference m_oSRS; // creation only variables CPLString m_osComment; CPLString m_osLatitudeType; CPLString m_osLongitudeDirection; CPLString m_osTargetName; bool m_bForce360; bool m_bWriteBoundingDegrees; CPLString m_osBoundingDegrees; CPLJSONObject m_oJSonLabel; CPLString m_osHistory; // creation only bool m_bUseSrcLabel; // creation only bool m_bUseSrcMapping; // creation only bool m_bUseSrcHistory; // creation only bool m_bAddGDALHistory; // creation only CPLString m_osGDALHistory; // creation only std::vector<NonPixelSection> m_aoNonPixelSections; // creation only CPLJSONObject m_oSrcJSonLabel; // creation only CPLStringList m_aosISIS3MD; CPLStringList m_aosAdditionalFiles; CPLString m_osFromFilename; // creation only RawBinaryLayout m_sLayout{}; const char *GetKeyword( const char *pszPath, const char *pszDefault = ""); double FixLong( double dfLong ); void BuildLabel(); void BuildHistory(); void WriteLabel(); void InvalidateLabel(); static CPLString SerializeAsPDL( const CPLJSONObject& oObj ); static void SerializeAsPDL( VSILFILE* fp, const CPLJSONObject& oObj, int nDepth = 0 ); public: ISIS3Dataset(); virtual ~ISIS3Dataset(); virtual int CloseDependentDatasets() override; virtual CPLErr GetGeoTransform( double * padfTransform ) override; virtual CPLErr SetGeoTransform( double * padfTransform ) override; const OGRSpatialReference* GetSpatialRef() const override; CPLErr SetSpatialRef(const OGRSpatialReference* poSRS) override; virtual char **GetFileList() override; virtual char **GetMetadataDomainList() override; virtual char **GetMetadata( const char* pszDomain = "" ) override; virtual CPLErr SetMetadata( char** papszMD, const char* pszDomain = "" ) override; bool GetRawBinaryLayout(GDALDataset::RawBinaryLayout&) override; static int Identify( GDALOpenInfo * ); static GDALDataset *Open( GDALOpenInfo * ); static GDALDataset *Create( const char * pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, char ** papszOptions ); static GDALDataset* CreateCopy( const char *pszFilename, GDALDataset *poSrcDS, int bStrict, char ** papszOptions, GDALProgressFunc pfnProgress, void * pProgressData ); }; /************************************************************************/ /* ==================================================================== */ /* ISISTiledBand */ /* ==================================================================== */ /************************************************************************/ class ISISTiledBand final: public GDALPamRasterBand { friend class ISIS3Dataset; VSILFILE *m_fpVSIL; GIntBig m_nFirstTileOffset; GIntBig m_nXTileOffset; GIntBig m_nYTileOffset; int m_bNativeOrder; bool m_bHasOffset; bool m_bHasScale; double m_dfOffset; double m_dfScale; double m_dfNoData; public: ISISTiledBand( GDALDataset *poDS, VSILFILE *fpVSIL, int nBand, GDALDataType eDT, int nTileXSize, int nTileYSize, GIntBig nFirstTileOffset, GIntBig nXTileOffset, GIntBig nYTileOffset, int bNativeOrder ); virtual ~ISISTiledBand() {} virtual CPLErr IReadBlock( int, int, void * ) override; virtual CPLErr IWriteBlock( int, int, void * ) override; virtual double GetOffset( int *pbSuccess = nullptr ) override; virtual double GetScale( int *pbSuccess = nullptr ) override; virtual CPLErr SetOffset( double dfNewOffset ) override; virtual CPLErr SetScale( double dfNewScale ) override; virtual double GetNoDataValue( int *pbSuccess = nullptr ) override; virtual CPLErr SetNoDataValue( double dfNewNoData ) override; void SetMaskBand(GDALRasterBand* poMaskBand); }; /************************************************************************/ /* ==================================================================== */ /* ISIS3RawRasterBand */ /* ==================================================================== */ /************************************************************************/ class ISIS3RawRasterBand final: public RawRasterBand { friend class ISIS3Dataset; bool m_bHasOffset; bool m_bHasScale; double m_dfOffset; double m_dfScale; double m_dfNoData; public: ISIS3RawRasterBand( GDALDataset *l_poDS, int l_nBand, VSILFILE * l_fpRaw, vsi_l_offset l_nImgOffset, int l_nPixelOffset, int l_nLineOffset, GDALDataType l_eDataType, int l_bNativeOrder ); virtual ~ISIS3RawRasterBand() {} virtual CPLErr IReadBlock( int, int, void * ) override; virtual CPLErr IWriteBlock( int, int, void * ) override; virtual CPLErr IRasterIO( GDALRWFlag, int, int, int, int, void *, int, int, GDALDataType, GSpacing nPixelSpace, GSpacing nLineSpace, GDALRasterIOExtraArg* psExtraArg ) override; virtual double GetOffset( int *pbSuccess = nullptr ) override; virtual double GetScale( int *pbSuccess = nullptr ) override; virtual CPLErr SetOffset( double dfNewOffset ) override; virtual CPLErr SetScale( double dfNewScale ) override; virtual double GetNoDataValue( int *pbSuccess = nullptr ) override; virtual CPLErr SetNoDataValue( double dfNewNoData ) override; void SetMaskBand(GDALRasterBand* poMaskBand); }; /************************************************************************/ /* ==================================================================== */ /* ISIS3WrapperRasterBand */ /* */ /* proxy for bands stored in other formats. */ /* ==================================================================== */ /************************************************************************/ class ISIS3WrapperRasterBand final: public GDALProxyRasterBand { friend class ISIS3Dataset; GDALRasterBand* m_poBaseBand; bool m_bHasOffset; bool m_bHasScale; double m_dfOffset; double m_dfScale; double m_dfNoData; protected: virtual GDALRasterBand* RefUnderlyingRasterBand() override { return m_poBaseBand; } public: explicit ISIS3WrapperRasterBand( GDALRasterBand* poBaseBandIn ); ~ISIS3WrapperRasterBand() {} void InitFile(); virtual CPLErr Fill(double dfRealValue, double dfImaginaryValue = 0) override; virtual CPLErr IWriteBlock( int, int, void * ) override; virtual CPLErr IRasterIO( GDALRWFlag, int, int, int, int, void *, int, int, GDALDataType, GSpacing nPixelSpace, GSpacing nLineSpace, GDALRasterIOExtraArg* psExtraArg ) override; virtual double GetOffset( int *pbSuccess = nullptr ) override; virtual double GetScale( int *pbSuccess = nullptr ) override; virtual CPLErr SetOffset( double dfNewOffset ) override; virtual CPLErr SetScale( double dfNewScale ) override; virtual double GetNoDataValue( int *pbSuccess = nullptr ) override; virtual CPLErr SetNoDataValue( double dfNewNoData ) override; int GetMaskFlags() override { return nMaskFlags; } GDALRasterBand* GetMaskBand() override { return poMask; } void SetMaskBand(GDALRasterBand* poMaskBand); }; /************************************************************************/ /* ==================================================================== */ /* ISISMaskBand */ /* ==================================================================== */ class ISISMaskBand final: public GDALRasterBand { GDALRasterBand *m_poBaseBand; void *m_pBuffer; public: explicit ISISMaskBand( GDALRasterBand* poBaseBand ); ~ISISMaskBand(); virtual CPLErr IReadBlock( int, int, void * ) override; }; /************************************************************************/ /* ISISTiledBand() */ /************************************************************************/ ISISTiledBand::ISISTiledBand( GDALDataset *poDSIn, VSILFILE *fpVSILIn, int nBandIn, GDALDataType eDT, int nTileXSize, int nTileYSize, GIntBig nFirstTileOffsetIn, GIntBig nXTileOffsetIn, GIntBig nYTileOffsetIn, int bNativeOrderIn ) : m_fpVSIL(fpVSILIn), m_nFirstTileOffset(0), m_nXTileOffset(nXTileOffsetIn), m_nYTileOffset(nYTileOffsetIn), m_bNativeOrder(bNativeOrderIn), m_bHasOffset(false), m_bHasScale(false), m_dfOffset(0.0), m_dfScale(1.0), m_dfNoData(0.0) { poDS = poDSIn; nBand = nBandIn; eDataType = eDT; nBlockXSize = nTileXSize; nBlockYSize = nTileYSize; nRasterXSize = poDSIn->GetRasterXSize(); nRasterYSize = poDSIn->GetRasterYSize(); const int l_nBlocksPerRow = DIV_ROUND_UP(nRasterXSize, nBlockXSize); const int l_nBlocksPerColumn = DIV_ROUND_UP(nRasterYSize, nBlockYSize); if( m_nXTileOffset == 0 && m_nYTileOffset == 0 ) { m_nXTileOffset = static_cast<GIntBig>(GDALGetDataTypeSizeBytes(eDT)) * nTileXSize; if( m_nXTileOffset > GINTBIG_MAX / nTileYSize ) { CPLError(CE_Failure, CPLE_AppDefined, "Integer overflow"); return; } m_nXTileOffset *= nTileYSize; if( m_nXTileOffset > GINTBIG_MAX / l_nBlocksPerRow ) { CPLError(CE_Failure, CPLE_AppDefined, "Integer overflow"); return; } m_nYTileOffset = m_nXTileOffset * l_nBlocksPerRow; } m_nFirstTileOffset = nFirstTileOffsetIn; if( nBand > 1 ) { if( m_nYTileOffset > GINTBIG_MAX / (nBand - 1) || (nBand-1) * m_nYTileOffset > GINTBIG_MAX / l_nBlocksPerColumn || m_nFirstTileOffset > GINTBIG_MAX - (nBand-1) * m_nYTileOffset * l_nBlocksPerColumn ) { CPLError(CE_Failure, CPLE_AppDefined, "Integer overflow"); return; } m_nFirstTileOffset += (nBand-1) * m_nYTileOffset * l_nBlocksPerColumn; } } /************************************************************************/ /* IReadBlock() */ /************************************************************************/ CPLErr ISISTiledBand::IReadBlock( int nXBlock, int nYBlock, void *pImage ) { ISIS3Dataset* poGDS = reinterpret_cast<ISIS3Dataset*>(poDS); if( poGDS->m_osExternalFilename.empty() ) { if( !poGDS->m_bIsLabelWritten ) poGDS->WriteLabel(); } const GIntBig nOffset = m_nFirstTileOffset + nXBlock * m_nXTileOffset + nYBlock * m_nYTileOffset; const int nDTSize = GDALGetDataTypeSizeBytes(eDataType); const size_t nBlockSize = static_cast<size_t>(nDTSize) * nBlockXSize * nBlockYSize; if( VSIFSeekL( m_fpVSIL, nOffset, SEEK_SET ) != 0 ) { CPLError( CE_Failure, CPLE_FileIO, "Failed to seek to offset %d to read tile %d,%d.", static_cast<int>( nOffset ), nXBlock, nYBlock ); return CE_Failure; } if( VSIFReadL( pImage, 1, nBlockSize, m_fpVSIL ) != nBlockSize ) { CPLError( CE_Failure, CPLE_FileIO, "Failed to read %d bytes for tile %d,%d.", static_cast<int>( nBlockSize ), nXBlock, nYBlock ); return CE_Failure; } if( !m_bNativeOrder && eDataType != GDT_Byte ) GDALSwapWords( pImage, nDTSize, nBlockXSize*nBlockYSize, nDTSize ); return CE_None; } /************************************************************************/ /* RemapNoDataT() */ /************************************************************************/ template<class T> static void RemapNoDataT( T* pBuffer, int nItems, T srcNoData, T dstNoData ) { for( int i = 0; i < nItems; i++ ) { if( pBuffer[i] == srcNoData ) pBuffer[i] = dstNoData; } } /************************************************************************/ /* RemapNoData() */ /************************************************************************/ static void RemapNoData( GDALDataType eDataType, void* pBuffer, int nItems, double dfSrcNoData, double dfDstNoData ) { if( eDataType == GDT_Byte ) { RemapNoDataT( reinterpret_cast<GByte*>(pBuffer), nItems, static_cast<GByte>(dfSrcNoData), static_cast<GByte>(dfDstNoData) ); } else if( eDataType == GDT_UInt16 ) { RemapNoDataT( reinterpret_cast<GUInt16*>(pBuffer), nItems, static_cast<GUInt16>(dfSrcNoData), static_cast<GUInt16>(dfDstNoData) ); } else if( eDataType == GDT_Int16) { RemapNoDataT( reinterpret_cast<GInt16*>(pBuffer), nItems, static_cast<GInt16>(dfSrcNoData), static_cast<GInt16>(dfDstNoData) ); } else { CPLAssert( eDataType == GDT_Float32 ); RemapNoDataT( reinterpret_cast<float*>(pBuffer), nItems, static_cast<float>(dfSrcNoData), static_cast<float>(dfDstNoData) ); } } /** * Get or create CPLJSONObject. * @param oParent Parent CPLJSONObject. * @param osKey Key name. * @return CPLJSONObject class instance. */ static CPLJSONObject GetOrCreateJSONObject(CPLJSONObject &oParent, const std::string &osKey) { CPLJSONObject oChild = oParent[osKey]; if( oChild.IsValid() && oChild.GetType() != CPLJSONObject::Type::Object ) { oParent.Delete( osKey ); oChild.Deinit(); } if( !oChild.IsValid() ) { oChild = CPLJSONObject(); oParent.Add( osKey, oChild ); } return oChild; } /************************************************************************/ /* IReadBlock() */ /************************************************************************/ CPLErr ISISTiledBand::IWriteBlock( int nXBlock, int nYBlock, void *pImage ) { ISIS3Dataset* poGDS = reinterpret_cast<ISIS3Dataset*>(poDS); if( poGDS->m_osExternalFilename.empty() ) { if( !poGDS->m_bIsLabelWritten ) poGDS->WriteLabel(); } if( poGDS->m_bHasSrcNoData && poGDS->m_dfSrcNoData != m_dfNoData ) { RemapNoData( eDataType, pImage, nBlockXSize * nBlockYSize, poGDS->m_dfSrcNoData, m_dfNoData ); } const GIntBig nOffset = m_nFirstTileOffset + nXBlock * m_nXTileOffset + nYBlock * m_nYTileOffset; const int nDTSize = GDALGetDataTypeSizeBytes(eDataType); const size_t nBlockSize = static_cast<size_t>(nDTSize) * nBlockXSize * nBlockYSize; const int l_nBlocksPerRow = DIV_ROUND_UP(nRasterXSize, nBlockXSize); const int l_nBlocksPerColumn = DIV_ROUND_UP(nRasterYSize, nBlockYSize); // Pad partial blocks to nodata value if( nXBlock == l_nBlocksPerRow - 1 && (nRasterXSize % nBlockXSize) != 0 ) { GByte* pabyImage = static_cast<GByte*>(pImage); int nXStart = nRasterXSize % nBlockXSize; for( int iY = 0; iY < nBlockYSize; iY++ ) { GDALCopyWords( &m_dfNoData, GDT_Float64, 0, pabyImage + (iY * nBlockXSize + nXStart) * nDTSize, eDataType, nDTSize, nBlockXSize - nXStart ); } } if( nYBlock == l_nBlocksPerColumn - 1 && (nRasterYSize % nBlockYSize) != 0 ) { GByte* pabyImage = static_cast<GByte*>(pImage); for( int iY = nRasterYSize % nBlockYSize; iY < nBlockYSize; iY++ ) { GDALCopyWords( &m_dfNoData, GDT_Float64, 0, pabyImage + iY * nBlockXSize * nDTSize, eDataType, nDTSize, nBlockXSize ); } } if( VSIFSeekL( m_fpVSIL, nOffset, SEEK_SET ) != 0 ) { CPLError( CE_Failure, CPLE_FileIO, "Failed to seek to offset %d to read tile %d,%d.", static_cast<int>( nOffset ), nXBlock, nYBlock ); return CE_Failure; } if( !m_bNativeOrder && eDataType != GDT_Byte ) GDALSwapWords( pImage, nDTSize, nBlockXSize*nBlockYSize, nDTSize ); if( VSIFWriteL( pImage, 1, nBlockSize, m_fpVSIL ) != nBlockSize ) { CPLError( CE_Failure, CPLE_FileIO, "Failed to write %d bytes for tile %d,%d.", static_cast<int>( nBlockSize ), nXBlock, nYBlock ); return CE_Failure; } if( !m_bNativeOrder && eDataType != GDT_Byte ) GDALSwapWords( pImage, nDTSize, nBlockXSize*nBlockYSize, nDTSize ); return CE_None; } /************************************************************************/ /* SetMaskBand() */ /************************************************************************/ void ISISTiledBand::SetMaskBand(GDALRasterBand* poMaskBand) { bOwnMask = true; poMask = poMaskBand; nMaskFlags = 0; } /************************************************************************/ /* GetOffset() */ /************************************************************************/ double ISISTiledBand::GetOffset( int *pbSuccess ) { if( pbSuccess ) *pbSuccess = m_bHasOffset; return m_dfOffset; } /************************************************************************/ /* GetScale() */ /************************************************************************/ double ISISTiledBand::GetScale( int *pbSuccess ) { if( pbSuccess ) *pbSuccess = m_bHasScale; return m_dfScale; } /************************************************************************/ /* SetOffset() */ /************************************************************************/ CPLErr ISISTiledBand::SetOffset( double dfNewOffset ) { m_dfOffset = dfNewOffset; m_bHasOffset = true; return CE_None; } /************************************************************************/ /* SetScale() */ /************************************************************************/ CPLErr ISISTiledBand::SetScale( double dfNewScale ) { m_dfScale = dfNewScale; m_bHasScale = true; return CE_None; } /************************************************************************/ /* GetNoDataValue() */ /************************************************************************/ double ISISTiledBand::GetNoDataValue( int *pbSuccess ) { if( pbSuccess ) *pbSuccess = true; return m_dfNoData; } /************************************************************************/ /* SetNoDataValue() */ /************************************************************************/ CPLErr ISISTiledBand::SetNoDataValue( double dfNewNoData ) { m_dfNoData = dfNewNoData; return CE_None; } /************************************************************************/ /* ISIS3RawRasterBand() */ /************************************************************************/ ISIS3RawRasterBand::ISIS3RawRasterBand( GDALDataset *l_poDS, int l_nBand, VSILFILE * l_fpRaw, vsi_l_offset l_nImgOffset, int l_nPixelOffset, int l_nLineOffset, GDALDataType l_eDataType, int l_bNativeOrder ) : RawRasterBand(l_poDS, l_nBand, l_fpRaw, l_nImgOffset, l_nPixelOffset, l_nLineOffset, l_eDataType, l_bNativeOrder, RawRasterBand::OwnFP::NO), m_bHasOffset(false), m_bHasScale(false), m_dfOffset(0.0), m_dfScale(1.0), m_dfNoData(0.0) { } /************************************************************************/ /* IReadBlock() */ /************************************************************************/ CPLErr ISIS3RawRasterBand::IReadBlock( int nXBlock, int nYBlock, void *pImage ) { ISIS3Dataset* poGDS = reinterpret_cast<ISIS3Dataset*>(poDS); if( poGDS->m_osExternalFilename.empty() ) { if( !poGDS->m_bIsLabelWritten ) poGDS->WriteLabel(); } return RawRasterBand::IReadBlock( nXBlock, nYBlock, pImage ); } /************************************************************************/ /* IWriteBlock() */ /************************************************************************/ CPLErr ISIS3RawRasterBand::IWriteBlock( int nXBlock, int nYBlock, void *pImage ) { ISIS3Dataset* poGDS = reinterpret_cast<ISIS3Dataset*>(poDS); if( poGDS->m_osExternalFilename.empty() ) { if( !poGDS->m_bIsLabelWritten ) poGDS->WriteLabel(); } if( poGDS->m_bHasSrcNoData && poGDS->m_dfSrcNoData != m_dfNoData ) { RemapNoData( eDataType, pImage, nBlockXSize * nBlockYSize, poGDS->m_dfSrcNoData, m_dfNoData ); } return RawRasterBand::IWriteBlock( nXBlock, nYBlock, pImage ); } /************************************************************************/ /* IRasterIO() */ /************************************************************************/ CPLErr ISIS3RawRasterBand::IRasterIO( GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, void * pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, GSpacing nPixelSpace, GSpacing nLineSpace, GDALRasterIOExtraArg* psExtraArg ) { ISIS3Dataset* poGDS = reinterpret_cast<ISIS3Dataset*>(poDS); if( poGDS->m_osExternalFilename.empty() ) { if( !poGDS->m_bIsLabelWritten ) poGDS->WriteLabel(); } if( eRWFlag == GF_Write && poGDS->m_bHasSrcNoData && poGDS->m_dfSrcNoData != m_dfNoData ) { const int nDTSize = GDALGetDataTypeSizeBytes(eDataType); if( eBufType == eDataType && nPixelSpace == nDTSize && nLineSpace == nPixelSpace * nBufXSize ) { RemapNoData( eDataType, pData, nBufXSize * nBufYSize, poGDS->m_dfSrcNoData, m_dfNoData ); } else { const GByte* pabySrc = reinterpret_cast<GByte*>(pData); GByte* pabyTemp = reinterpret_cast<GByte*>( VSI_MALLOC3_VERBOSE(nDTSize, nBufXSize, nBufYSize)); for( int i = 0; i < nBufYSize; i++ ) { GDALCopyWords( pabySrc + i * nLineSpace, eBufType, static_cast<int>(nPixelSpace), pabyTemp + i * nBufXSize * nDTSize, eDataType, nDTSize, nBufXSize ); } RemapNoData( eDataType, pabyTemp, nBufXSize * nBufYSize, poGDS->m_dfSrcNoData, m_dfNoData ); CPLErr eErr = RawRasterBand::IRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize, pabyTemp, nBufXSize, nBufYSize, eDataType, nDTSize, nDTSize*nBufXSize, psExtraArg ); VSIFree(pabyTemp); return eErr; } } return RawRasterBand::IRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize, eBufType, nPixelSpace, nLineSpace, psExtraArg ); } /************************************************************************/ /* SetMaskBand() */ /************************************************************************/ void ISIS3RawRasterBand::SetMaskBand(GDALRasterBand* poMaskBand) { bOwnMask = true; poMask = poMaskBand; nMaskFlags = 0; } /************************************************************************/ /* GetOffset() */ /************************************************************************/ double ISIS3RawRasterBand::GetOffset( int *pbSuccess ) { if( pbSuccess ) *pbSuccess = m_bHasOffset; return m_dfOffset; } /************************************************************************/ /* GetScale() */ /************************************************************************/ double ISIS3RawRasterBand::GetScale( int *pbSuccess ) { if( pbSuccess ) *pbSuccess = m_bHasScale; return m_dfScale; } /************************************************************************/ /* SetOffset() */ /************************************************************************/ CPLErr ISIS3RawRasterBand::SetOffset( double dfNewOffset ) { m_dfOffset = dfNewOffset; m_bHasOffset = true; return CE_None; } /************************************************************************/ /* SetScale() */ /************************************************************************/ CPLErr ISIS3RawRasterBand::SetScale( double dfNewScale ) { m_dfScale = dfNewScale; m_bHasScale = true; return CE_None; } /************************************************************************/ /* GetNoDataValue() */ /************************************************************************/ double ISIS3RawRasterBand::GetNoDataValue( int *pbSuccess ) { if( pbSuccess ) *pbSuccess = true; return m_dfNoData; } /************************************************************************/ /* SetNoDataValue() */ /************************************************************************/ CPLErr ISIS3RawRasterBand::SetNoDataValue( double dfNewNoData ) { m_dfNoData = dfNewNoData; return CE_None; } /************************************************************************/ /* ISIS3WrapperRasterBand() */ /************************************************************************/ ISIS3WrapperRasterBand::ISIS3WrapperRasterBand( GDALRasterBand* poBaseBandIn ) : m_poBaseBand(poBaseBandIn), m_bHasOffset(false), m_bHasScale(false), m_dfOffset(0.0), m_dfScale(1.0), m_dfNoData(0.0) { eDataType = m_poBaseBand->GetRasterDataType(); m_poBaseBand->GetBlockSize(&nBlockXSize, &nBlockYSize); } /************************************************************************/ /* SetMaskBand() */ /************************************************************************/ void ISIS3WrapperRasterBand::SetMaskBand(GDALRasterBand* poMaskBand) { bOwnMask = true; poMask = poMaskBand; nMaskFlags = 0; } /************************************************************************/ /* GetOffset() */ /************************************************************************/ double ISIS3WrapperRasterBand::GetOffset( int *pbSuccess ) { if( pbSuccess ) *pbSuccess = m_bHasOffset; return m_dfOffset; } /************************************************************************/ /* GetScale() */ /************************************************************************/ double ISIS3WrapperRasterBand::GetScale( int *pbSuccess ) { if( pbSuccess ) *pbSuccess = m_bHasScale; return m_dfScale; } /************************************************************************/ /* SetOffset() */ /************************************************************************/ CPLErr ISIS3WrapperRasterBand::SetOffset( double dfNewOffset ) { m_dfOffset = dfNewOffset; m_bHasOffset = true; ISIS3Dataset* poGDS = reinterpret_cast<ISIS3Dataset*>(poDS); if( poGDS->m_poExternalDS && eAccess == GA_Update ) poGDS->m_poExternalDS->GetRasterBand(nBand)->SetOffset(dfNewOffset); return CE_None; } /************************************************************************/ /* SetScale() */ /************************************************************************/ CPLErr ISIS3WrapperRasterBand::SetScale( double dfNewScale ) { m_dfScale = dfNewScale; m_bHasScale = true; ISIS3Dataset* poGDS = reinterpret_cast<ISIS3Dataset*>(poDS); if( poGDS->m_poExternalDS && eAccess == GA_Update ) poGDS->m_poExternalDS->GetRasterBand(nBand)->SetScale(dfNewScale); return CE_None; } /************************************************************************/ /* GetNoDataValue() */ /************************************************************************/ double ISIS3WrapperRasterBand::GetNoDataValue( int *pbSuccess ) { if( pbSuccess ) *pbSuccess = true; return m_dfNoData; } /************************************************************************/ /* SetNoDataValue() */ /************************************************************************/ CPLErr ISIS3WrapperRasterBand::SetNoDataValue( double dfNewNoData ) { m_dfNoData = dfNewNoData; ISIS3Dataset* poGDS = reinterpret_cast<ISIS3Dataset*>(poDS); if( poGDS->m_poExternalDS && eAccess == GA_Update ) poGDS->m_poExternalDS->GetRasterBand(nBand)->SetNoDataValue(dfNewNoData); return CE_None; } /************************************************************************/ /* InitFile() */ /************************************************************************/ void ISIS3WrapperRasterBand::InitFile() { ISIS3Dataset* poGDS = reinterpret_cast<ISIS3Dataset*>(poDS); if( poGDS->m_bGeoTIFFAsRegularExternal && !poGDS->m_bGeoTIFFInitDone ) { poGDS->m_bGeoTIFFInitDone = true; const int nBands = poGDS->GetRasterCount(); // We need to make sure that blocks are written in the right order for( int i = 0; i < nBands; i++ ) { poGDS->m_poExternalDS->GetRasterBand(i+1)->Fill(m_dfNoData); } poGDS->m_poExternalDS->FlushCache(); // Check that blocks are effectively written in expected order. const int nBlockSizeBytes = nBlockXSize * nBlockYSize * GDALGetDataTypeSizeBytes(eDataType); GIntBig nLastOffset = 0; bool bGoOn = true; const int l_nBlocksPerRow = DIV_ROUND_UP(nRasterXSize, nBlockXSize); const int l_nBlocksPerColumn = DIV_ROUND_UP(nRasterYSize, nBlockYSize); for( int i = 0; i < nBands && bGoOn; i++ ) { for( int y = 0; y < l_nBlocksPerColumn && bGoOn; y++ ) { for( int x = 0; x < l_nBlocksPerRow && bGoOn; x++ ) { const char* pszBlockOffset = poGDS->m_poExternalDS-> GetRasterBand(i+1)->GetMetadataItem( CPLSPrintf("BLOCK_OFFSET_%d_%d", x, y), "TIFF"); if( pszBlockOffset ) { GIntBig nOffset = CPLAtoGIntBig(pszBlockOffset); if( i != 0 || x != 0 || y != 0 ) { if( nOffset != nLastOffset + nBlockSizeBytes ) { CPLError(CE_Warning, CPLE_AppDefined, "Block %d,%d band %d not at expected " "offset", x, y, i+1); bGoOn = false; poGDS->m_bGeoTIFFAsRegularExternal = false; } } nLastOffset = nOffset; } else { CPLError(CE_Warning, CPLE_AppDefined, "Block %d,%d band %d not at expected " "offset", x, y, i+1); bGoOn = false; poGDS->m_bGeoTIFFAsRegularExternal = false; } } } } } } /************************************************************************/ /* Fill() */ /************************************************************************/ CPLErr ISIS3WrapperRasterBand::Fill(double dfRealValue, double dfImaginaryValue) { ISIS3Dataset* poGDS = reinterpret_cast<ISIS3Dataset*>(poDS); if( poGDS->m_bHasSrcNoData && poGDS->m_dfSrcNoData == dfRealValue ) { dfRealValue = m_dfNoData; } if( poGDS->m_bGeoTIFFAsRegularExternal && !poGDS->m_bGeoTIFFInitDone ) { InitFile(); } return GDALProxyRasterBand::Fill( dfRealValue, dfImaginaryValue ); } /************************************************************************/ /* IWriteBlock() */ /************************************************************************/ CPLErr ISIS3WrapperRasterBand::IWriteBlock( int nXBlock, int nYBlock, void *pImage ) { ISIS3Dataset* poGDS = reinterpret_cast<ISIS3Dataset*>(poDS); if( poGDS->m_bHasSrcNoData && poGDS->m_dfSrcNoData != m_dfNoData ) { RemapNoData( eDataType, pImage, nBlockXSize * nBlockYSize, poGDS->m_dfSrcNoData, m_dfNoData ); } if( poGDS->m_bGeoTIFFAsRegularExternal && !poGDS->m_bGeoTIFFInitDone ) { InitFile(); } return GDALProxyRasterBand::IWriteBlock( nXBlock, nYBlock, pImage ); } /************************************************************************/ /* IRasterIO() */ /************************************************************************/ CPLErr ISIS3WrapperRasterBand::IRasterIO( GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, void * pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, GSpacing nPixelSpace, GSpacing nLineSpace, GDALRasterIOExtraArg* psExtraArg ) { ISIS3Dataset* poGDS = reinterpret_cast<ISIS3Dataset*>(poDS); if( eRWFlag == GF_Write && poGDS->m_bGeoTIFFAsRegularExternal && !poGDS->m_bGeoTIFFInitDone ) { InitFile(); } if( eRWFlag == GF_Write && poGDS->m_bHasSrcNoData && poGDS->m_dfSrcNoData != m_dfNoData ) { const int nDTSize = GDALGetDataTypeSizeBytes(eDataType); if( eBufType == eDataType && nPixelSpace == nDTSize && nLineSpace == nPixelSpace * nBufXSize ) { RemapNoData( eDataType, pData, nBufXSize * nBufYSize, poGDS->m_dfSrcNoData, m_dfNoData ); } else { const GByte* pabySrc = reinterpret_cast<GByte*>(pData); GByte* pabyTemp = reinterpret_cast<GByte*>( VSI_MALLOC3_VERBOSE(nDTSize, nBufXSize, nBufYSize)); for( int i = 0; i < nBufYSize; i++ ) { GDALCopyWords( pabySrc + i * nLineSpace, eBufType, static_cast<int>(nPixelSpace), pabyTemp + i * nBufXSize * nDTSize, eDataType, nDTSize, nBufXSize ); } RemapNoData( eDataType, pabyTemp, nBufXSize * nBufYSize, poGDS->m_dfSrcNoData, m_dfNoData ); CPLErr eErr = GDALProxyRasterBand::IRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize, pabyTemp, nBufXSize, nBufYSize, eDataType, nDTSize, nDTSize*nBufXSize, psExtraArg ); VSIFree(pabyTemp); return eErr; } } return GDALProxyRasterBand::IRasterIO( eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize, eBufType, nPixelSpace, nLineSpace, psExtraArg ); } /************************************************************************/ /* ISISMaskBand() */ /************************************************************************/ ISISMaskBand::ISISMaskBand( GDALRasterBand* poBaseBand ) : m_poBaseBand(poBaseBand) , m_pBuffer(nullptr) { eDataType = GDT_Byte; poBaseBand->GetBlockSize(&nBlockXSize, &nBlockYSize); nRasterXSize = poBaseBand->GetXSize(); nRasterYSize = poBaseBand->GetYSize(); } /************************************************************************/ /* ~ISISMaskBand() */ /************************************************************************/ ISISMaskBand::~ISISMaskBand() { VSIFree(m_pBuffer); } /************************************************************************/ /* FillMask() */ /************************************************************************/ template<class T> static void FillMask (void* pvBuffer, GByte* pabyDst, int nReqXSize, int nReqYSize, int nBlockXSize, T NULL_VAL, T LOW_REPR_SAT, T LOW_INSTR_SAT, T HIGH_INSTR_SAT, T HIGH_REPR_SAT) { const T* pSrc = static_cast<T*>(pvBuffer); for( int y = 0; y < nReqYSize; y++ ) { for( int x = 0; x < nReqXSize; x++ ) { const T nSrc = pSrc[y * nBlockXSize + x]; if( nSrc == NULL_VAL || nSrc == LOW_REPR_SAT || nSrc == LOW_INSTR_SAT || nSrc == HIGH_INSTR_SAT || nSrc == HIGH_REPR_SAT ) { pabyDst[y * nBlockXSize + x] = 0; } else { pabyDst[y * nBlockXSize + x] = 255; } } } } /************************************************************************/ /* IReadBlock() */ /************************************************************************/ CPLErr ISISMaskBand::IReadBlock( int nXBlock, int nYBlock, void *pImage ) { const GDALDataType eSrcDT = m_poBaseBand->GetRasterDataType(); const int nSrcDTSize = GDALGetDataTypeSizeBytes(eSrcDT); if( m_pBuffer == nullptr ) { m_pBuffer = VSI_MALLOC3_VERBOSE(nBlockXSize, nBlockYSize, nSrcDTSize); if( m_pBuffer == nullptr ) return CE_Failure; } int nXOff = nXBlock * nBlockXSize; int nReqXSize = nBlockXSize; if( nXOff + nReqXSize > nRasterXSize ) nReqXSize = nRasterXSize - nXOff; int nYOff = nYBlock * nBlockYSize; int nReqYSize = nBlockYSize; if( nYOff + nReqYSize > nRasterYSize ) nReqYSize = nRasterYSize - nYOff; if( m_poBaseBand->RasterIO( GF_Read, nXOff, nYOff, nReqXSize, nReqYSize, m_pBuffer, nReqXSize, nReqYSize, eSrcDT, nSrcDTSize, nSrcDTSize * nBlockXSize, nullptr ) != CE_None ) { return CE_Failure; } GByte* pabyDst = static_cast<GByte*>(pImage); if( eSrcDT == GDT_Byte ) { FillMask<GByte>(m_pBuffer, pabyDst, nReqXSize, nReqYSize, nBlockXSize, NULL1, LOW_REPR_SAT1, LOW_INSTR_SAT1, HIGH_INSTR_SAT1, HIGH_REPR_SAT1); } else if( eSrcDT == GDT_UInt16 ) { FillMask<GUInt16>(m_pBuffer, pabyDst, nReqXSize, nReqYSize, nBlockXSize, NULLU2, LOW_REPR_SATU2, LOW_INSTR_SATU2, HIGH_INSTR_SATU2, HIGH_REPR_SATU2); } else if( eSrcDT == GDT_Int16 ) { FillMask<GInt16>(m_pBuffer, pabyDst, nReqXSize, nReqYSize, nBlockXSize, NULL2, LOW_REPR_SAT2, LOW_INSTR_SAT2, HIGH_INSTR_SAT2, HIGH_REPR_SAT2); } else { CPLAssert( eSrcDT == GDT_Float32 ); FillMask<float>(m_pBuffer, pabyDst, nReqXSize, nReqYSize, nBlockXSize, NULL4, LOW_REPR_SAT4, LOW_INSTR_SAT4, HIGH_INSTR_SAT4, HIGH_REPR_SAT4); } return CE_None; } /************************************************************************/ /* ISIS3Dataset() */ /************************************************************************/ ISIS3Dataset::ISIS3Dataset() : m_fpLabel(nullptr), m_fpImage(nullptr), m_poExternalDS(nullptr), m_bGeoTIFFAsRegularExternal(false), m_bGeoTIFFInitDone(true), m_bIsLabelWritten(true), m_bIsTiled(false), m_bInitToNodata(false), m_bGotTransform(false), m_bHasSrcNoData(false), m_dfSrcNoData(0.0), m_bForce360(false), m_bWriteBoundingDegrees(true), m_bUseSrcLabel(true), m_bUseSrcMapping(false), m_bUseSrcHistory(true), m_bAddGDALHistory(true) { m_oKeywords.SetStripSurroundingQuotes(true); m_adfGeoTransform[0] = 0.0; m_adfGeoTransform[1] = 1.0; m_adfGeoTransform[2] = 0.0; m_adfGeoTransform[3] = 0.0; m_adfGeoTransform[4] = 0.0; m_adfGeoTransform[5] = 1.0; // Deinit JSON objects m_oJSonLabel.Deinit(); m_oSrcJSonLabel.Deinit(); } /************************************************************************/ /* ~ISIS3Dataset() */ /************************************************************************/ ISIS3Dataset::~ISIS3Dataset() { if( !m_bIsLabelWritten ) WriteLabel(); if( m_poExternalDS && m_bGeoTIFFAsRegularExternal && !m_bGeoTIFFInitDone ) { reinterpret_cast<ISIS3WrapperRasterBand*>(GetRasterBand(1))-> InitFile(); } ISIS3Dataset::FlushCache(); if( m_fpLabel != nullptr ) VSIFCloseL( m_fpLabel ); if( m_fpImage != nullptr && m_fpImage != m_fpLabel ) VSIFCloseL( m_fpImage ); ISIS3Dataset::CloseDependentDatasets(); } /************************************************************************/ /* CloseDependentDatasets() */ /************************************************************************/ int ISIS3Dataset::CloseDependentDatasets() { int bHasDroppedRef = GDALPamDataset::CloseDependentDatasets(); if( m_poExternalDS ) { bHasDroppedRef = FALSE; delete m_poExternalDS; m_poExternalDS = nullptr; } for( int iBand = 0; iBand < nBands; iBand++ ) { delete papoBands[iBand]; } nBands = 0; return bHasDroppedRef; } /************************************************************************/ /* GetFileList() */ /************************************************************************/ char **ISIS3Dataset::GetFileList() { char **papszFileList = GDALPamDataset::GetFileList(); if( !m_osExternalFilename.empty() ) papszFileList = CSLAddString( papszFileList, m_osExternalFilename ); for( int i = 0; i < m_aosAdditionalFiles.Count(); ++i ) { if( CSLFindString(papszFileList, m_aosAdditionalFiles[i]) < 0 ) { papszFileList = CSLAddString( papszFileList, m_aosAdditionalFiles[i] ); } } return papszFileList; } /************************************************************************/ /* GetSpatialRef() */ /************************************************************************/ const OGRSpatialReference* ISIS3Dataset::GetSpatialRef() const { if( !m_oSRS.IsEmpty() ) return &m_oSRS; return GDALPamDataset::GetSpatialRef(); } /************************************************************************/ /* SetSpatialRef() */ /************************************************************************/ CPLErr ISIS3Dataset::SetSpatialRef( const OGRSpatialReference* poSRS ) { if( eAccess == GA_ReadOnly ) return GDALPamDataset::SetSpatialRef( poSRS ); if( poSRS ) m_oSRS = *poSRS; else m_oSRS.Clear(); if( m_poExternalDS ) m_poExternalDS->SetSpatialRef(poSRS); InvalidateLabel(); return CE_None; } /************************************************************************/ /* GetGeoTransform() */ /************************************************************************/ CPLErr ISIS3Dataset::GetGeoTransform( double * padfTransform ) { if( m_bGotTransform ) { memcpy( padfTransform, m_adfGeoTransform, sizeof(double) * 6 ); return CE_None; } return GDALPamDataset::GetGeoTransform( padfTransform ); } /************************************************************************/ /* SetGeoTransform() */ /************************************************************************/ CPLErr ISIS3Dataset::SetGeoTransform( double * padfTransform ) { if( eAccess == GA_ReadOnly ) return GDALPamDataset::SetGeoTransform( padfTransform ); if( padfTransform[1] <= 0.0 || padfTransform[1] != -padfTransform[5] || padfTransform[2] != 0.0 || padfTransform[4] != 0.0 ) { CPLError(CE_Failure, CPLE_NotSupported, "Only north-up geotransform with square pixels supported"); return CE_Failure; } m_bGotTransform = true; memcpy( m_adfGeoTransform, padfTransform, sizeof(double) * 6 ); if( m_poExternalDS ) m_poExternalDS->SetGeoTransform(padfTransform); InvalidateLabel(); return CE_None; } /************************************************************************/ /* GetMetadataDomainList() */ /************************************************************************/ char **ISIS3Dataset::GetMetadataDomainList() { return BuildMetadataDomainList( nullptr, FALSE, "", "json:ISIS3", nullptr); } /************************************************************************/ /* GetMetadata() */ /************************************************************************/ char **ISIS3Dataset::GetMetadata( const char* pszDomain ) { if( pszDomain != nullptr && EQUAL( pszDomain, "json:ISIS3" ) ) { if( m_aosISIS3MD.empty() ) { if( eAccess == GA_Update && !m_oJSonLabel.IsValid() ) { BuildLabel(); } CPLAssert( m_oJSonLabel.IsValid() ); const CPLString osJson = m_oJSonLabel.Format(CPLJSONObject::PrettyFormat::Pretty); m_aosISIS3MD.InsertString(0, osJson.c_str()); } return m_aosISIS3MD.List(); } return GDALPamDataset::GetMetadata(pszDomain); } /************************************************************************/ /* InvalidateLabel() */ /************************************************************************/ void ISIS3Dataset::InvalidateLabel() { m_oJSonLabel.Deinit(); m_aosISIS3MD.Clear(); } /************************************************************************/ /* SetMetadata() */ /************************************************************************/ CPLErr ISIS3Dataset::SetMetadata( char** papszMD, const char* pszDomain ) { if( m_bUseSrcLabel && eAccess == GA_Update && pszDomain != nullptr && EQUAL( pszDomain, "json:ISIS3" ) ) { m_oSrcJSonLabel.Deinit(); InvalidateLabel(); if( papszMD != nullptr && papszMD[0] != nullptr ) { CPLJSONDocument oJSONDocument; const GByte *pabyData = reinterpret_cast<const GByte *>(papszMD[0]); if( !oJSONDocument.LoadMemory( pabyData ) ) { return CE_Failure; } m_oSrcJSonLabel = oJSONDocument.GetRoot(); if( !m_oSrcJSonLabel.IsValid() ) { return CE_Failure; } } return CE_None; } return GDALPamDataset::SetMetadata(papszMD, pszDomain); } /************************************************************************/ /* Identify() */ /************************************************************************/ int ISIS3Dataset::Identify( GDALOpenInfo * poOpenInfo ) { if( poOpenInfo->fpL != nullptr && poOpenInfo->pabyHeader != nullptr && strstr((const char *)poOpenInfo->pabyHeader,"IsisCube") != nullptr ) return TRUE; return FALSE; } /************************************************************************/ /* GetRawBinaryLayout() */ /************************************************************************/ bool ISIS3Dataset::GetRawBinaryLayout(GDALDataset::RawBinaryLayout& sLayout) { if( m_sLayout.osRawFilename.empty() ) return false; sLayout = m_sLayout; return true; } /************************************************************************/ /* GetValueAndUnits() */ /************************************************************************/ static void GetValueAndUnits(const CPLJSONObject& obj, std::vector<double>& adfValues, std::vector<std::string>& aosUnits, int nExpectedVals) { if( obj.GetType() == CPLJSONObject::Type::Integer || obj.GetType() == CPLJSONObject::Type::Double ) { adfValues.push_back(obj.ToDouble()); } else if( obj.GetType() == CPLJSONObject::Type::Object ) { auto oValue = obj.GetObj("value"); auto oUnit = obj.GetObj("unit"); if( oValue.IsValid() && (oValue.GetType() == CPLJSONObject::Type::Integer || oValue.GetType() == CPLJSONObject::Type::Double || oValue.GetType() == CPLJSONObject::Type::Array) && oUnit.IsValid() && oUnit.GetType() == CPLJSONObject::Type::String ) { if( oValue.GetType() == CPLJSONObject::Type::Array ) { GetValueAndUnits(oValue, adfValues, aosUnits, nExpectedVals); } else { adfValues.push_back(oValue.ToDouble()); } aosUnits.push_back(oUnit.ToString()); } } else if( obj.GetType() == CPLJSONObject::Type::Array ) { auto oArray = obj.ToArray(); if( oArray.Size() == nExpectedVals ) { for( int i = 0; i < nExpectedVals; i++ ) { if( oArray[i].GetType() == CPLJSONObject::Type::Integer || oArray[i].GetType() == CPLJSONObject::Type::Double ) { adfValues.push_back(oArray[i].ToDouble()); } else { adfValues.clear(); return; } } } } } /************************************************************************/ /* Open() */ /************************************************************************/ GDALDataset *ISIS3Dataset::Open( GDALOpenInfo * poOpenInfo ) { /* -------------------------------------------------------------------- */ /* Does this look like a CUBE dataset? */ /* -------------------------------------------------------------------- */ if( !Identify( poOpenInfo ) ) return nullptr; /* -------------------------------------------------------------------- */ /* Open the file using the large file API. */ /* -------------------------------------------------------------------- */ ISIS3Dataset *poDS = new ISIS3Dataset(); if( ! poDS->m_oKeywords.Ingest( poOpenInfo->fpL, 0 ) ) { VSIFCloseL( poOpenInfo->fpL ); poOpenInfo->fpL = nullptr; delete poDS; return nullptr; } poDS->m_oJSonLabel = poDS->m_oKeywords.GetJsonObject(); poDS->m_oJSonLabel.Add( "_filename", poOpenInfo->pszFilename ); // Find additional files from the label for( const CPLJSONObject& oObj : poDS->m_oJSonLabel.GetChildren() ) { if( oObj.GetType() == CPLJSONObject::Type::Object ) { CPLString osContainerName = oObj.GetName(); CPLJSONObject oContainerName = oObj.GetObj( "_container_name" ); if( oContainerName.GetType() == CPLJSONObject::Type::String ) { osContainerName = oContainerName.ToString(); } CPLJSONObject oFilename = oObj.GetObj( "^" + osContainerName ); if( oFilename.GetType() == CPLJSONObject::Type::String ) { VSIStatBufL sStat; CPLString osFilename( CPLFormFilename( CPLGetPath(poOpenInfo->pszFilename), oFilename.ToString().c_str(), nullptr ) ); if( VSIStatL( osFilename, &sStat ) == 0 ) { poDS->m_aosAdditionalFiles.AddString(osFilename); } else { CPLDebug("ISIS3", "File %s referenced but not foud", osFilename.c_str()); } } } } VSIFCloseL( poOpenInfo->fpL ); poOpenInfo->fpL = nullptr; /* -------------------------------------------------------------------- */ /* Assume user is pointing to label (i.e. .lbl) file for detached option */ /* -------------------------------------------------------------------- */ // Image can be inline or detached and point to an image name // the Format can be Tiled or Raw // Object = Core // StartByte = 65537 // Format = Tile // TileSamples = 128 // TileLines = 128 //OR----- // Object = Core // StartByte = 1 // ^Core = r0200357_detatched.cub // Format = BandSequential //OR----- // Object = Core // StartByte = 1 // ^Core = r0200357_detached_tiled.cub // Format = Tile // TileSamples = 128 // TileLines = 128 //OR----- // Object = Core // StartByte = 1 // ^Core = some.tif // Format = GeoTIFF /* -------------------------------------------------------------------- */ /* What file contains the actual data? */ /* -------------------------------------------------------------------- */ const char *pszCore = poDS->GetKeyword( "IsisCube.Core.^Core" ); CPLString osQubeFile; if( EQUAL(pszCore,"") ) osQubeFile = poOpenInfo->pszFilename; else { CPLString osPath = CPLGetPath( poOpenInfo->pszFilename ); osQubeFile = CPLFormFilename( osPath, pszCore, nullptr ); poDS->m_osExternalFilename = osQubeFile; } /* -------------------------------------------------------------------- */ /* Check if file an ISIS3 header file? Read a few lines of text */ /* searching for something starting with nrows or ncols. */ /* -------------------------------------------------------------------- */ /************* Skipbytes *****************************/ int nSkipBytes = atoi(poDS->GetKeyword("IsisCube.Core.StartByte", "1")); if( nSkipBytes <= 1 ) nSkipBytes = 0; else nSkipBytes -= 1; /******* Grab format type (BandSequential, Tiled) *******/ CPLString osFormat = poDS->GetKeyword( "IsisCube.Core.Format" ); int tileSizeX = 0; int tileSizeY = 0; if (EQUAL(osFormat,"Tile") ) { poDS->m_bIsTiled = true; /******* Get Tile Sizes *********/ tileSizeX = atoi(poDS->GetKeyword("IsisCube.Core.TileSamples")); tileSizeY = atoi(poDS->GetKeyword("IsisCube.Core.TileLines")); if (tileSizeX <= 0 || tileSizeY <= 0) { CPLError( CE_Failure, CPLE_OpenFailed, "Wrong tile dimensions : %d x %d", tileSizeX, tileSizeY); delete poDS; return nullptr; } } else if (!EQUAL(osFormat,"BandSequential") && !EQUAL(osFormat,"GeoTIFF") ) { CPLError( CE_Failure, CPLE_OpenFailed, "%s format not supported.", osFormat.c_str()); delete poDS; return nullptr; } /*********** Grab samples lines band ************/ const int nCols = atoi(poDS->GetKeyword("IsisCube.Core.Dimensions.Samples")); const int nRows = atoi(poDS->GetKeyword("IsisCube.Core.Dimensions.Lines")); const int nBands = atoi(poDS->GetKeyword("IsisCube.Core.Dimensions.Bands")); /****** Grab format type - ISIS3 only supports 8,U16,S16,32 *****/ GDALDataType eDataType = GDT_Byte; double dfNoData = 0.0; const char *itype = poDS->GetKeyword( "IsisCube.Core.Pixels.Type" ); if (EQUAL(itype,"UnsignedByte") ) { eDataType = GDT_Byte; dfNoData = NULL1; } else if (EQUAL(itype,"UnsignedWord") ) { eDataType = GDT_UInt16; dfNoData = NULLU2; } else if (EQUAL(itype,"SignedWord") ) { eDataType = GDT_Int16; dfNoData = NULL2; } else if (EQUAL(itype,"Real") || EQUAL(itype,"") ) { eDataType = GDT_Float32; dfNoData = NULL4; } else { CPLError( CE_Failure, CPLE_OpenFailed, "%s pixel type not supported.", itype); delete poDS; return nullptr; } /*********** Grab samples lines band ************/ //default to MSB const bool bIsLSB = EQUAL( poDS->GetKeyword( "IsisCube.Core.Pixels.ByteOrder"),"Lsb"); /*********** Grab Cellsize ************/ double dfXDim = 1.0; double dfYDim = 1.0; const char* pszRes = poDS->GetKeyword("IsisCube.Mapping.PixelResolution"); if (strlen(pszRes) > 0 ) { dfXDim = CPLAtof(pszRes); /* values are in meters */ dfYDim = -CPLAtof(pszRes); } /*********** Grab UpperLeftCornerY ************/ double dfULYMap = 0.5; const char* pszULY = poDS->GetKeyword("IsisCube.Mapping.UpperLeftCornerY"); if (strlen(pszULY) > 0) { dfULYMap = CPLAtof(pszULY); } /*********** Grab UpperLeftCornerX ************/ double dfULXMap = 0.5; const char* pszULX = poDS->GetKeyword("IsisCube.Mapping.UpperLeftCornerX"); if( strlen(pszULX) > 0 ) { dfULXMap = CPLAtof(pszULX); } /*********** Grab TARGET_NAME ************/ /**** This is the planets name i.e. Mars ***/ const char *target_name = poDS->GetKeyword("IsisCube.Mapping.TargetName"); #ifdef notdef const double dfLongitudeMulFactor = EQUAL(poDS->GetKeyword( "IsisCube.Mapping.LongitudeDirection", "PositiveEast"), "PositiveEast") ? 1 : -1; #else const double dfLongitudeMulFactor = 1; #endif /*********** Grab MAP_PROJECTION_TYPE ************/ const char *map_proj_name = poDS->GetKeyword( "IsisCube.Mapping.ProjectionName"); /*********** Grab SEMI-MAJOR ************/ const double semi_major = CPLAtof(poDS->GetKeyword( "IsisCube.Mapping.EquatorialRadius")); /*********** Grab semi-minor ************/ const double semi_minor = CPLAtof(poDS->GetKeyword( "IsisCube.Mapping.PolarRadius")); /*********** Grab CENTER_LAT ************/ const double center_lat = CPLAtof(poDS->GetKeyword( "IsisCube.Mapping.CenterLatitude")); /*********** Grab CENTER_LON ************/ const double center_lon = CPLAtof(poDS->GetKeyword( "IsisCube.Mapping.CenterLongitude")) * dfLongitudeMulFactor; /*********** Grab 1st std parallel ************/ const double first_std_parallel = CPLAtof(poDS->GetKeyword( "IsisCube.Mapping.FirstStandardParallel")); /*********** Grab 2nd std parallel ************/ const double second_std_parallel = CPLAtof(poDS->GetKeyword( "IsisCube.Mapping.SecondStandardParallel")); /*********** Grab scaleFactor ************/ const double scaleFactor = CPLAtof(poDS->GetKeyword( "IsisCube.Mapping.scaleFactor", "1.0")); /*** grab LatitudeType = Planetographic ****/ // Need to further study how ocentric/ographic will effect the gdal library // So far we will use this fact to define a sphere or ellipse for some // projections // Frank - may need to talk this over bool bIsGeographic = true; if (EQUAL( poDS->GetKeyword("IsisCube.Mapping.LatitudeType"), "Planetocentric" )) bIsGeographic = false; //Set oSRS projection and parameters //############################################################ //ISIS3 Projection types // Equirectangular // LambertConformal // Mercator // ObliqueCylindrical // Orthographic // PolarStereographic // SimpleCylindrical // Sinusoidal // TransverseMercator #ifdef DEBUG CPLDebug( "ISIS3", "using projection %s", map_proj_name); #endif OGRSpatialReference oSRS; bool bProjectionSet = true; if ((EQUAL( map_proj_name, "Equirectangular" )) || (EQUAL( map_proj_name, "SimpleCylindrical" )) ) { oSRS.SetEquirectangular2 ( 0.0, center_lon, center_lat, 0, 0 ); } else if (EQUAL( map_proj_name, "Orthographic" )) { oSRS.SetOrthographic ( center_lat, center_lon, 0, 0 ); } else if (EQUAL( map_proj_name, "Sinusoidal" )) { oSRS.SetSinusoidal ( center_lon, 0, 0 ); } else if (EQUAL( map_proj_name, "Mercator" )) { oSRS.SetMercator ( center_lat, center_lon, scaleFactor, 0, 0 ); } else if (EQUAL( map_proj_name, "PolarStereographic" )) { oSRS.SetPS ( center_lat, center_lon, scaleFactor, 0, 0 ); } else if (EQUAL( map_proj_name, "TransverseMercator" )) { oSRS.SetTM ( center_lat, center_lon, scaleFactor, 0, 0 ); } else if (EQUAL( map_proj_name, "LambertConformal" )) { oSRS.SetLCC ( first_std_parallel, second_std_parallel, center_lat, center_lon, 0, 0 ); } else if (EQUAL( map_proj_name, "PointPerspective" )) { // Distance parameter is the distance to the center of the body, and is given in km const double distance = CPLAtof(poDS->GetKeyword( "IsisCube.Mapping.Distance")) * 1000.0; const double height_above_ground = distance - semi_major; oSRS.SetVerticalPerspective(center_lat, center_lon, 0, height_above_ground, 0, 0); } else if (EQUAL( map_proj_name, "ObliqueCylindrical" )) { const double poleLatitude = CPLAtof(poDS->GetKeyword( "IsisCube.Mapping.PoleLatitude")); const double poleLongitude = CPLAtof(poDS->GetKeyword( "IsisCube.Mapping.PoleLongitude")) * dfLongitudeMulFactor; const double poleRotation = CPLAtof(poDS->GetKeyword( "IsisCube.Mapping.PoleRotation")); CPLString oProj4String; // ISIS3 rotated pole doesn't use the same conventions than PROJ ob_tran // Compare the sign difference in https://github.com/USGS-Astrogeology/ISIS3/blob/3.8.0/isis/src/base/objs/ObliqueCylindrical/ObliqueCylindrical.cpp#L244 // and https://github.com/OSGeo/PROJ/blob/6.2/src/projections/ob_tran.cpp#L34 // They can be compensated by modifying the poleLatitude to 180-poleLatitude // There's also a sign difference for the poleRotation parameter // The existence of those different conventions is acknowledged in // https://pds-imaging.jpl.nasa.gov/documentation/Cassini_BIDRSIS.PDF in the middle of page 10 oProj4String.Printf( "+proj=ob_tran +o_proj=eqc +o_lon_p=%.18g +o_lat_p=%.18g +lon_0=%.18g", -poleRotation, 180-poleLatitude, poleLongitude); oSRS.SetFromUserInput(oProj4String); } else { CPLDebug( "ISIS3", "Dataset projection %s is not supported. Continuing...", map_proj_name ); bProjectionSet = false; } if (bProjectionSet) { //Create projection name, i.e. MERCATOR MARS and set as ProjCS keyword CPLString osProjTargetName(map_proj_name); osProjTargetName += " "; osProjTargetName += target_name; oSRS.SetProjCS(osProjTargetName); //set ProjCS keyword //The geographic/geocentric name will be the same basic name as the body name //'GCS' = Geographic/Geocentric Coordinate System CPLString osGeogName("GCS_"); osGeogName += target_name; //The datum name will be the same basic name as the planet CPLString osDatumName("D_"); osDatumName += target_name; CPLString osSphereName(target_name); //strcat(osSphereName, "_IAU_IAG"); //Might not be IAU defined so don't add //calculate inverse flattening from major and minor axis: 1/f = a/(a-b) double iflattening = 0.0; if ((semi_major - semi_minor) < 0.0000001) iflattening = 0; else iflattening = semi_major / (semi_major - semi_minor); //Set the body size but take into consideration which proj is being used to help w/ proj4 compatibility //The use of a Sphere, polar radius or ellipse here is based on how ISIS does it internally if ( ( (EQUAL( map_proj_name, "Stereographic" ) && (fabs(center_lat) == 90)) ) || (EQUAL( map_proj_name, "PolarStereographic" )) ) { if (bIsGeographic) { //Geograpraphic, so set an ellipse oSRS.SetGeogCS( osGeogName, osDatumName, osSphereName, semi_major, iflattening, "Reference_Meridian", 0.0 ); } else { //Geocentric, so force a sphere using the semi-minor axis. I hope... osSphereName += "_polarRadius"; oSRS.SetGeogCS( osGeogName, osDatumName, osSphereName, semi_minor, 0.0, "Reference_Meridian", 0.0 ); } } else if ( (EQUAL( map_proj_name, "SimpleCylindrical" )) || (EQUAL( map_proj_name, "Orthographic" )) || (EQUAL( map_proj_name, "Stereographic" )) || (EQUAL( map_proj_name, "Sinusoidal" )) || (EQUAL( map_proj_name, "PointPerspective" )) ) { // ISIS uses the spherical equation for these projections // so force a sphere. oSRS.SetGeogCS( osGeogName, osDatumName, osSphereName, semi_major, 0.0, "Reference_Meridian", 0.0 ); } else if (EQUAL( map_proj_name, "Equirectangular" )) { //Calculate localRadius using ISIS3 simple elliptical method // not the more standard Radius of Curvature method //PI = 4 * atan(1); const double radLat = center_lat * M_PI / 180; // in radians const double meanRadius = sqrt( pow( semi_minor * cos( radLat ), 2) + pow( semi_major * sin( radLat ), 2) ); const double localRadius = ( meanRadius == 0.0 ) ? 0.0 : semi_major * semi_minor / meanRadius; osSphereName += "_localRadius"; oSRS.SetGeogCS( osGeogName, osDatumName, osSphereName, localRadius, 0.0, "Reference_Meridian", 0.0 ); } else { //All other projections: Mercator, Transverse Mercator, Lambert Conformal, etc. //Geographic, so set an ellipse if (bIsGeographic) { oSRS.SetGeogCS( osGeogName, osDatumName, osSphereName, semi_major, iflattening, "Reference_Meridian", 0.0 ); } else { //Geocentric, so force a sphere. I hope... oSRS.SetGeogCS( osGeogName, osDatumName, osSphereName, semi_major, 0.0, "Reference_Meridian", 0.0 ); } } // translate back into a projection string. poDS->m_oSRS = oSRS; poDS->m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); } /* END ISIS3 Label Read */ /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /* -------------------------------------------------------------------- */ /* Did we get the required keywords? If not we return with */ /* this never having been considered to be a match. This isn't */ /* an error! */ /* -------------------------------------------------------------------- */ if( !GDALCheckDatasetDimensions(nCols, nRows) || !GDALCheckBandCount(nBands, false) ) { delete poDS; return nullptr; } /* -------------------------------------------------------------------- */ /* Capture some information from the file that is of interest. */ /* -------------------------------------------------------------------- */ poDS->nRasterXSize = nCols; poDS->nRasterYSize = nRows; /* -------------------------------------------------------------------- */ /* Open target binary file. */ /* -------------------------------------------------------------------- */ if( EQUAL(osFormat,"GeoTIFF") ) { if( nSkipBytes != 0 ) { CPLError(CE_Warning, CPLE_NotSupported, "Ignoring StartByte=%d for format=GeoTIFF", 1+nSkipBytes); } if( osQubeFile == poOpenInfo->pszFilename ) { CPLError( CE_Failure, CPLE_AppDefined, "A ^Core file must be set"); delete poDS; return nullptr; } poDS->m_poExternalDS = reinterpret_cast<GDALDataset *>( GDALOpen( osQubeFile, poOpenInfo->eAccess ) ); if( poDS->m_poExternalDS == nullptr ) { delete poDS; return nullptr; } if( poDS->m_poExternalDS->GetRasterXSize() != poDS->nRasterXSize || poDS->m_poExternalDS->GetRasterYSize() != poDS->nRasterYSize || poDS->m_poExternalDS->GetRasterCount() != nBands || poDS->m_poExternalDS->GetRasterBand(1)->GetRasterDataType() != eDataType ) { CPLError( CE_Failure, CPLE_AppDefined, "%s has incompatible characteristics with the ones " "declared in the label.", osQubeFile.c_str() ); delete poDS; return nullptr; } } else { if( poOpenInfo->eAccess == GA_ReadOnly ) poDS->m_fpImage = VSIFOpenL( osQubeFile, "r" ); else poDS->m_fpImage = VSIFOpenL( osQubeFile, "r+" ); if( poDS->m_fpImage == nullptr ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to open %s: %s.", osQubeFile.c_str(), VSIStrerror( errno ) ); delete poDS; return nullptr; } // Sanity checks in case the external raw file appears to be a // TIFF file if( EQUAL(CPLGetExtension(osQubeFile), "tif") ) { GDALDataset* poTIF_DS = reinterpret_cast<GDALDataset*>( GDALOpen(osQubeFile, GA_ReadOnly)); if( poTIF_DS ) { bool bWarned = false; if( poTIF_DS->GetRasterXSize() != poDS->nRasterXSize || poTIF_DS->GetRasterYSize() != poDS->nRasterYSize || poTIF_DS->GetRasterCount() != nBands || poTIF_DS->GetRasterBand(1)->GetRasterDataType() != eDataType || poTIF_DS->GetMetadataItem("COMPRESSION", "IMAGE_STRUCTURE") != nullptr ) { bWarned = true; CPLError( CE_Warning, CPLE_AppDefined, "%s has incompatible characteristics with the ones " "declared in the label.", osQubeFile.c_str() ); } int nBlockXSize = 1, nBlockYSize = 1; poTIF_DS->GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize); if( (poDS->m_bIsTiled && (nBlockXSize != tileSizeX || nBlockYSize != tileSizeY) ) || (!poDS->m_bIsTiled && (nBlockXSize != nCols || (nBands > 1 && nBlockYSize != 1))) ) { if( !bWarned ) { bWarned = true; CPLError( CE_Warning, CPLE_AppDefined, "%s has incompatible characteristics with the ones " "declared in the label.", osQubeFile.c_str() ); } } // to please Clang Static Analyzer nBlockXSize = std::max(1, nBlockXSize); nBlockYSize = std::max(1, nBlockYSize); // Check that blocks are effectively written in expected order. const int nBlockSizeBytes = nBlockXSize * nBlockYSize * GDALGetDataTypeSizeBytes(eDataType); bool bGoOn = !bWarned; const int l_nBlocksPerRow = DIV_ROUND_UP(nCols, nBlockXSize); const int l_nBlocksPerColumn = DIV_ROUND_UP(nRows, nBlockYSize); int nBlockNo = 0; for( int i = 0; i < nBands && bGoOn; i++ ) { for( int y = 0; y < l_nBlocksPerColumn && bGoOn; y++ ) { for( int x = 0; x < l_nBlocksPerRow && bGoOn; x++ ) { const char* pszBlockOffset = poTIF_DS-> GetRasterBand(i+1)->GetMetadataItem( CPLSPrintf("BLOCK_OFFSET_%d_%d", x, y), "TIFF"); if( pszBlockOffset ) { GIntBig nOffset = CPLAtoGIntBig(pszBlockOffset); if( nOffset != nSkipBytes + nBlockNo * nBlockSizeBytes ) { //bWarned = true; CPLError( CE_Warning, CPLE_AppDefined, "%s has incompatible " "characteristics with the ones " "declared in the label.", osQubeFile.c_str() ); bGoOn = false; } } nBlockNo ++; } } } delete poTIF_DS; } } } poDS->eAccess = poOpenInfo->eAccess; /* -------------------------------------------------------------------- */ /* Compute the line offset. */ /* -------------------------------------------------------------------- */ int nLineOffset = 0; int nPixelOffset = 0; vsi_l_offset nBandOffset = 0; if( EQUAL(osFormat,"BandSequential") ) { const int nItemSize = GDALGetDataTypeSizeBytes(eDataType); nPixelOffset = nItemSize; try { nLineOffset = (CPLSM(nPixelOffset) * CPLSM(nCols)).v(); } catch( const CPLSafeIntOverflow& ) { delete poDS; return nullptr; } nBandOffset = static_cast<vsi_l_offset>(nLineOffset) * nRows; poDS->m_sLayout.osRawFilename = osQubeFile; if( nBands > 1 ) poDS->m_sLayout.eInterleaving = RawBinaryLayout::Interleaving::BSQ; poDS->m_sLayout.eDataType = eDataType; poDS->m_sLayout.bLittleEndianOrder = bIsLSB; poDS->m_sLayout.nImageOffset = nSkipBytes; poDS->m_sLayout.nPixelOffset = nPixelOffset; poDS->m_sLayout.nLineOffset = nLineOffset; poDS->m_sLayout.nBandOffset = static_cast<GIntBig>(nBandOffset); } /* else Tiled or external */ /* -------------------------------------------------------------------- */ /* Extract BandBin info. */ /* -------------------------------------------------------------------- */ std::vector<std::string> aosBandNames; std::vector<std::string> aosBandUnits; std::vector<double> adfWavelengths; std::vector<std::string> aosWavelengthsUnit; std::vector<double> adfBandwidth; std::vector<std::string> aosBandwidthUnit; const auto oBandBin = poDS->m_oJSonLabel.GetObj( "IsisCube/BandBin" ); if( oBandBin.IsValid() && oBandBin.GetType() == CPLJSONObject::Type::Object ) { for( const auto& child: oBandBin.GetChildren() ) { if( CPLString(child.GetName()).ifind("name") != std::string::npos ) { // Use "name" in priority if( EQUAL(child.GetName().c_str(), "name") ) { aosBandNames.clear(); } else if( !aosBandNames.empty() ) { continue; } if( child.GetType() == CPLJSONObject::Type::String && nBands == 1 ) { aosBandNames.push_back(child.ToString()); } else if( child.GetType() == CPLJSONObject::Type::Array ) { auto oArray = child.ToArray(); if( oArray.Size() == nBands ) { for( int i = 0; i < nBands; i++ ) { if( oArray[i].GetType() == CPLJSONObject::Type::String ) { aosBandNames.push_back(oArray[i].ToString()); } else { aosBandNames.clear(); break; } } } } } else if( EQUAL(child.GetName().c_str(), "BandSuffixUnit") && child.GetType() == CPLJSONObject::Type::Array ) { auto oArray = child.ToArray(); if( oArray.Size() == nBands ) { for( int i = 0; i < nBands; i++ ) { if( oArray[i].GetType() == CPLJSONObject::Type::String ) { aosBandUnits.push_back(oArray[i].ToString()); } else { aosBandUnits.clear(); break; } } } } else if( EQUAL(child.GetName().c_str(), "BandBinCenter") || EQUAL(child.GetName().c_str(), "Center") ) { GetValueAndUnits(child, adfWavelengths, aosWavelengthsUnit, nBands); } else if( EQUAL(child.GetName().c_str(), "BandBinUnit") && child.GetType() == CPLJSONObject::Type::String ) { CPLString unit(child.ToString()); if( STARTS_WITH_CI(unit, "micromet") || EQUAL(unit, "um") || STARTS_WITH_CI(unit, "nanomet") || EQUAL(unit, "nm") ) { aosWavelengthsUnit.push_back(child.ToString()); } } else if( EQUAL(child.GetName().c_str(), "Width") ) { GetValueAndUnits(child, adfBandwidth, aosBandwidthUnit, nBands); } } if( !adfWavelengths.empty() && aosWavelengthsUnit.size() == 1 ) { for( int i = 1; i < nBands; i++ ) { aosWavelengthsUnit.push_back(aosWavelengthsUnit[0]); } } if( !adfBandwidth.empty() && aosBandwidthUnit.size() == 1 ) { for( int i = 1; i < nBands; i++ ) { aosBandwidthUnit.push_back(aosBandwidthUnit[0]); } } } /* -------------------------------------------------------------------- */ /* Create band information objects. */ /* -------------------------------------------------------------------- */ #ifdef CPL_LSB const bool bNativeOrder = bIsLSB; #else const bool bNativeOrder = !bIsLSB; #endif for( int i = 0; i < nBands; i++ ) { GDALRasterBand *poBand = nullptr; if( poDS->m_poExternalDS != nullptr ) { ISIS3WrapperRasterBand* poISISBand = new ISIS3WrapperRasterBand( poDS->m_poExternalDS->GetRasterBand( i+1 ) ); poBand = poISISBand; poDS->SetBand( i+1, poBand ); poISISBand->SetMaskBand( new ISISMaskBand(poISISBand) ); } else if( poDS->m_bIsTiled ) { CPLErrorReset(); ISISTiledBand* poISISBand = new ISISTiledBand( poDS, poDS->m_fpImage, i+1, eDataType, tileSizeX, tileSizeY, nSkipBytes, 0, 0, bNativeOrder ); if( CPLGetLastErrorType() != CE_None ) { delete poISISBand; delete poDS; return nullptr; } poBand = poISISBand; poDS->SetBand( i+1, poBand ); poISISBand->SetMaskBand( new ISISMaskBand(poISISBand) ); } else { ISIS3RawRasterBand* poISISBand = new ISIS3RawRasterBand( poDS, i+1, poDS->m_fpImage, nSkipBytes + nBandOffset * i, nPixelOffset, nLineOffset, eDataType, bNativeOrder ); poBand = poISISBand; poDS->SetBand( i+1, poBand ); poISISBand->SetMaskBand( new ISISMaskBand(poISISBand) ); } if( i < static_cast<int>(aosBandNames.size()) ) { poBand->SetDescription(aosBandNames[i].c_str()); } if( i < static_cast<int>(adfWavelengths.size()) && i < static_cast<int>(aosWavelengthsUnit.size()) ) { poBand->SetMetadataItem("WAVELENGTH", CPLSPrintf("%f", adfWavelengths[i])); poBand->SetMetadataItem("WAVELENGTH_UNIT", aosWavelengthsUnit[i].c_str()); if( i < static_cast<int>(adfBandwidth.size()) && i < static_cast<int>(aosBandwidthUnit.size()) ) { poBand->SetMetadataItem("BANDWIDTH", CPLSPrintf("%f", adfBandwidth[i])); poBand->SetMetadataItem("BANDWIDTH_UNIT", aosBandwidthUnit[i].c_str()); } } if( i < static_cast<int>(aosBandUnits.size()) ) { poBand->SetUnitType(aosBandUnits[i].c_str()); } poBand->SetNoDataValue( dfNoData ); // Set offset/scale values. const double dfOffset = CPLAtofM(poDS->GetKeyword("IsisCube.Core.Pixels.Base","0.0")); const double dfScale = CPLAtofM(poDS->GetKeyword("IsisCube.Core.Pixels.Multiplier","1.0")); if( dfOffset != 0.0 || dfScale != 1.0 ) { poBand->SetOffset(dfOffset); poBand->SetScale(dfScale); } } /* -------------------------------------------------------------------- */ /* Check for a .prj file. For ISIS3 I would like to keep this in */ /* -------------------------------------------------------------------- */ const CPLString osPath = CPLGetPath( poOpenInfo->pszFilename ); const CPLString osName = CPLGetBasename(poOpenInfo->pszFilename); const char *pszPrjFile = CPLFormCIFilename( osPath, osName, "prj" ); VSILFILE *fp = VSIFOpenL( pszPrjFile, "r" ); if( fp != nullptr ) { VSIFCloseL( fp ); char **papszLines = CSLLoad( pszPrjFile ); OGRSpatialReference oSRS2; if( oSRS2.importFromESRI( papszLines ) == OGRERR_NONE ) { poDS->m_aosAdditionalFiles.AddString( pszPrjFile ); poDS->m_oSRS = oSRS2; poDS->m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); } CSLDestroy( papszLines ); } if( dfULXMap != 0.5 || dfULYMap != 0.5 || dfXDim != 1.0 || dfYDim != 1.0 ) { poDS->m_bGotTransform = true; poDS->m_adfGeoTransform[0] = dfULXMap; poDS->m_adfGeoTransform[1] = dfXDim; poDS->m_adfGeoTransform[2] = 0.0; poDS->m_adfGeoTransform[3] = dfULYMap; poDS->m_adfGeoTransform[4] = 0.0; poDS->m_adfGeoTransform[5] = dfYDim; } if( !poDS->m_bGotTransform ) { poDS->m_bGotTransform = CPL_TO_BOOL(GDALReadWorldFile( poOpenInfo->pszFilename, "cbw", poDS->m_adfGeoTransform )); if( poDS->m_bGotTransform ) { poDS->m_aosAdditionalFiles.AddString( CPLResetExtension(poOpenInfo->pszFilename, "cbw") ); } } if( !poDS->m_bGotTransform ) { poDS->m_bGotTransform = CPL_TO_BOOL(GDALReadWorldFile( poOpenInfo->pszFilename, "wld", poDS->m_adfGeoTransform )); if( poDS->m_bGotTransform ) { poDS->m_aosAdditionalFiles.AddString( CPLResetExtension(poOpenInfo->pszFilename, "wld") ); } } /* -------------------------------------------------------------------- */ /* Initialize any PAM information. */ /* -------------------------------------------------------------------- */ poDS->SetDescription( poOpenInfo->pszFilename ); poDS->TryLoadXML(); /* -------------------------------------------------------------------- */ /* Check for overviews. */ /* -------------------------------------------------------------------- */ poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename ); return poDS; } /************************************************************************/ /* GetKeyword() */ /************************************************************************/ const char *ISIS3Dataset::GetKeyword( const char *pszPath, const char *pszDefault ) { return m_oKeywords.GetKeyword( pszPath, pszDefault ); } /************************************************************************/ /* FixLong() */ /************************************************************************/ double ISIS3Dataset::FixLong( double dfLong ) { if( m_osLongitudeDirection == "PositiveWest" ) dfLong = -dfLong; if( m_bForce360 && dfLong < 0 ) dfLong += 360.0; return dfLong; } /************************************************************************/ /* BuildLabel() */ /************************************************************************/ void ISIS3Dataset::BuildLabel() { CPLJSONObject oLabel = m_oSrcJSonLabel; if( !oLabel.IsValid() ) { oLabel = CPLJSONObject(); } // If we have a source label, then edit it directly CPLJSONObject oIsisCube = GetOrCreateJSONObject(oLabel, "IsisCube"); oIsisCube.Set( "_type", "object"); if( !m_osComment.empty() ) oIsisCube.Set( "_comment", m_osComment ); CPLJSONObject oCore = GetOrCreateJSONObject(oIsisCube, "Core"); if( oCore.GetType() != CPLJSONObject::Type::Object ) { oIsisCube.Delete( "Core" ); oCore = CPLJSONObject(); oIsisCube.Add("Core", oCore); } oCore.Set( "_type", "object" ); if( !m_osExternalFilename.empty() ) { if( m_poExternalDS && m_bGeoTIFFAsRegularExternal ) { if( !m_bGeoTIFFInitDone ) { reinterpret_cast<ISIS3WrapperRasterBand*>(GetRasterBand(1))-> InitFile(); } const char* pszOffset = m_poExternalDS->GetRasterBand(1)-> GetMetadataItem("BLOCK_OFFSET_0_0", "TIFF"); if( pszOffset ) { oCore.Set( "StartByte", 1 + atoi(pszOffset) ); } else { // Shouldn't happen normally CPLError(CE_Warning, CPLE_AppDefined, "Missing BLOCK_OFFSET_0_0"); m_bGeoTIFFAsRegularExternal = false; oCore.Set( "StartByte", 1 ); } } else { oCore.Set( "StartByte", 1 ); } if( !m_osExternalFilename.empty() ) { const CPLString osExternalFilename = CPLGetFilename(m_osExternalFilename); oCore.Set( "^Core", osExternalFilename ); } } else { oCore.Set( "StartByte", pszSTARTBYTE_PLACEHOLDER ); oCore.Delete( "^Core" ); } if( m_poExternalDS && !m_bGeoTIFFAsRegularExternal ) { oCore.Set( "Format", "GeoTIFF" ); oCore.Delete( "TileSamples" ); oCore.Delete( "TileLines" ); } else if( m_bIsTiled ) { oCore.Set( "Format", "Tile"); int nBlockXSize = 1, nBlockYSize = 1; GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize); oCore.Set( "TileSamples", nBlockXSize ); oCore.Set( "TileLines", nBlockYSize ); } else { oCore.Set( "Format", "BandSequential" ); oCore.Delete( "TileSamples" ); oCore.Delete( "TileLines" ); } CPLJSONObject oDimensions = GetOrCreateJSONObject(oCore, "Dimensions"); oDimensions.Set( "_type", "group" ); oDimensions.Set( "Samples", nRasterXSize ); oDimensions.Set( "Lines", nRasterYSize ); oDimensions.Set( "Bands", nBands ); CPLJSONObject oPixels = GetOrCreateJSONObject(oCore, "Pixels"); oPixels.Set( "_type", "group" ); const GDALDataType eDT = GetRasterBand(1)->GetRasterDataType(); oPixels.Set( "Type", (eDT == GDT_Byte) ? "UnsignedByte" : (eDT == GDT_UInt16) ? "UnsignedWord" : (eDT == GDT_Int16) ? "SignedWord" : "Real" ); oPixels.Set( "ByteOrder", "Lsb" ); oPixels.Set( "Base", GetRasterBand(1)->GetOffset() ); oPixels.Set( "Multiplier", GetRasterBand(1)->GetScale() ); const OGRSpatialReference& oSRS = m_oSRS; if( !m_bUseSrcMapping ) { oIsisCube.Delete( "Mapping" ); } CPLJSONObject oMapping = GetOrCreateJSONObject(oIsisCube, "Mapping"); if( m_bUseSrcMapping && oMapping.IsValid() && oMapping.GetType() == CPLJSONObject::Type::Object ) { if( !m_osTargetName.empty() ) oMapping.Set( "TargetName", m_osTargetName ); if( !m_osLatitudeType.empty() ) oMapping.Set( "LatitudeType", m_osLatitudeType ); if( !m_osLongitudeDirection.empty() ) oMapping.Set( "LongitudeDirection", m_osLongitudeDirection ); } else if( !m_bUseSrcMapping && !m_oSRS.IsEmpty() ) { oMapping.Add( "_type", "group" ); if( oSRS.IsProjected() || oSRS.IsGeographic() ) { const char* pszDatum = oSRS.GetAttrValue("DATUM"); CPLString osTargetName( m_osTargetName ); if( osTargetName.empty() ) { if( pszDatum && STARTS_WITH(pszDatum, "D_") ) { osTargetName = pszDatum + 2; } else if( pszDatum ) { osTargetName = pszDatum; } } if( !osTargetName.empty() ) oMapping.Add( "TargetName", osTargetName ); oMapping.Add( "EquatorialRadius/value", oSRS.GetSemiMajor() ); oMapping.Add( "EquatorialRadius/unit", "meters" ); oMapping.Add( "PolarRadius/value", oSRS.GetSemiMinor() ); oMapping.Add( "PolarRadius/unit", "meters" ); if( !m_osLatitudeType.empty() ) oMapping.Add( "LatitudeType", m_osLatitudeType ); else oMapping.Add( "LatitudeType", "Planetocentric" ); if( !m_osLongitudeDirection.empty() ) oMapping.Add( "LongitudeDirection", m_osLongitudeDirection ); else oMapping.Add( "LongitudeDirection", "PositiveEast" ); double adfX[4] = {0}; double adfY[4] = {0}; bool bLongLatCorners = false; if( m_bGotTransform ) { for( int i = 0; i < 4; i++ ) { adfX[i] = m_adfGeoTransform[0] + (i%2) * nRasterXSize * m_adfGeoTransform[1]; adfY[i] = m_adfGeoTransform[3] + ( (i == 0 || i == 3) ? 0 : 1 ) * nRasterYSize * m_adfGeoTransform[5]; } if( oSRS.IsGeographic() ) { bLongLatCorners = true; } else { OGRSpatialReference* poSRSLongLat = oSRS.CloneGeogCS(); if( poSRSLongLat ) { poSRSLongLat->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); OGRCoordinateTransformation* poCT = OGRCreateCoordinateTransformation(&oSRS, poSRSLongLat); if( poCT ) { if( poCT->Transform(4, adfX, adfY) ) { bLongLatCorners = true; } delete poCT; } delete poSRSLongLat; } } } if( bLongLatCorners ) { for( int i = 0; i < 4; i++ ) { adfX[i] = FixLong(adfX[i]); } } if( bLongLatCorners && ( m_bForce360 || adfX[0] <- 180.0 || adfX[3] > 180.0) ) { oMapping.Add( "LongitudeDomain", 360 ); } else { oMapping.Add( "LongitudeDomain", 180 ); } if( m_bWriteBoundingDegrees && !m_osBoundingDegrees.empty() ) { char** papszTokens = CSLTokenizeString2(m_osBoundingDegrees, ",", 0); if( CSLCount(papszTokens) == 4 ) { oMapping.Add( "MinimumLatitude", CPLAtof(papszTokens[1]) ); oMapping.Add( "MinimumLongitude", CPLAtof(papszTokens[0]) ); oMapping.Add( "MaximumLatitude", CPLAtof(papszTokens[3]) ); oMapping.Add( "MaximumLongitude", CPLAtof(papszTokens[2]) ); } CSLDestroy(papszTokens); } else if( m_bWriteBoundingDegrees && bLongLatCorners ) { oMapping.Add( "MinimumLatitude", std::min( std::min(adfY[0], adfY[1]), std::min(adfY[2],adfY[3])) ); oMapping.Add( "MinimumLongitude", std::min( std::min(adfX[0], adfX[1]), std::min(adfX[2],adfX[3])) ); oMapping.Add( "MaximumLatitude", std::max( std::max(adfY[0], adfY[1]), std::max(adfY[2],adfY[3])) ); oMapping.Add( "MaximumLongitude", std::max( std::max(adfX[0], adfX[1]), std::max(adfX[2],adfX[3])) ); } const char* pszProjection = oSRS.GetAttrValue("PROJECTION"); if( pszProjection == nullptr ) { oMapping.Add( "ProjectionName", "SimpleCylindrical" ); oMapping.Add( "CenterLongitude", 0.0 ); oMapping.Add( "CenterLatitude", 0.0 ); oMapping.Add( "CenterLatitudeRadius", oSRS.GetSemiMajor() ); } else if( EQUAL(pszProjection, SRS_PT_EQUIRECTANGULAR) ) { oMapping.Add( "ProjectionName", "Equirectangular" ); if( oSRS.GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ) != 0.0 ) { CPLError(CE_Warning, CPLE_NotSupported, "Ignoring %s. Only 0 value supported", SRS_PP_LATITUDE_OF_ORIGIN); } oMapping.Add( "CenterLongitude", FixLong(oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0)) ); const double dfCenterLat = oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_1, 0.0); oMapping.Add( "CenterLatitude", dfCenterLat ); // in radians const double radLat = dfCenterLat * M_PI / 180; const double semi_major = oSRS.GetSemiMajor(); const double semi_minor = oSRS.GetSemiMinor(); const double localRadius = semi_major * semi_minor / sqrt( pow( semi_minor * cos( radLat ), 2) + pow( semi_major * sin( radLat ), 2) ); oMapping.Add( "CenterLatitudeRadius", localRadius ); } else if( EQUAL(pszProjection, SRS_PT_ORTHOGRAPHIC) ) { oMapping.Add( "ProjectionName", "Orthographic" ); oMapping.Add( "CenterLongitude", FixLong( oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0)) ); oMapping.Add( "CenterLatitude", oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0) ); } else if( EQUAL(pszProjection, SRS_PT_SINUSOIDAL) ) { oMapping.Add( "ProjectionName", "Sinusoidal" ); oMapping.Add( "CenterLongitude", FixLong( oSRS.GetNormProjParm(SRS_PP_LONGITUDE_OF_CENTER, 0.0)) ); } else if( EQUAL(pszProjection, SRS_PT_MERCATOR_1SP) ) { oMapping.Add( "ProjectionName", "Mercator" ); oMapping.Add( "CenterLongitude", FixLong( oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0)) ); oMapping.Add( "CenterLatitude", oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0) ); oMapping.Add( "scaleFactor", oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR, 1.0) ); } else if( EQUAL(pszProjection, SRS_PT_POLAR_STEREOGRAPHIC) ) { oMapping.Add( "ProjectionName", "PolarStereographic" ); oMapping.Add( "CenterLongitude", FixLong( oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0)) ); oMapping.Add( "CenterLatitude", oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0) ); oMapping.Add( "scaleFactor", oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR, 1.0) ); } else if( EQUAL(pszProjection, SRS_PT_TRANSVERSE_MERCATOR) ) { oMapping.Add( "ProjectionName", "TransverseMercator" ); oMapping.Add( "CenterLongitude", FixLong( oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0)) ); oMapping.Add( "CenterLatitude", oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0) ); oMapping.Add( "scaleFactor", oSRS.GetNormProjParm(SRS_PP_SCALE_FACTOR, 1.0) ); } else if( EQUAL(pszProjection, SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP) ) { oMapping.Add( "ProjectionName", "LambertConformal" ); oMapping.Add( "CenterLongitude", FixLong( oSRS.GetNormProjParm(SRS_PP_CENTRAL_MERIDIAN, 0.0)) ); oMapping.Add( "CenterLatitude", oSRS.GetNormProjParm(SRS_PP_LATITUDE_OF_ORIGIN, 0.0) ); oMapping.Add( "FirstStandardParallel", oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_1, 0.0) ); oMapping.Add( "SecondStandardParallel", oSRS.GetNormProjParm(SRS_PP_STANDARD_PARALLEL_2, 0.0) ); } else if( EQUAL(pszProjection, "Vertical Perspective") ) // PROJ 7 required { oMapping.Add( "ProjectionName", "PointPerspective" ); oMapping.Add( "CenterLongitude", FixLong( oSRS.GetNormProjParm("Longitude of topocentric origin", 0.0)) ); oMapping.Add( "CenterLatitude", oSRS.GetNormProjParm("Latitude of topocentric origin", 0.0) ); // ISIS3 value is the distance from center of ellipsoid, in km oMapping.Add( "Distance", (oSRS.GetNormProjParm("Viewpoint height", 0.0) + oSRS.GetSemiMajor()) / 1000.0 ); } else if( EQUAL(pszProjection, "custom_proj4") ) { const char* pszProj4 = oSRS.GetExtension("PROJCS", "PROJ4", nullptr); if( pszProj4 && strstr(pszProj4, "+proj=ob_tran" ) && strstr(pszProj4, "+o_proj=eqc") ) { const auto FetchParam = [](const char* pszProj4Str, const char* pszKey) { CPLString needle; needle.Printf("+%s=", pszKey); const char* pszVal = strstr(pszProj4Str, needle.c_str()); if( pszVal ) return CPLAtof(pszVal+needle.size()); return 0.0; }; double dfLonP = FetchParam(pszProj4, "o_lon_p"); double dfLatP = FetchParam(pszProj4, "o_lat_p"); double dfLon0 = FetchParam(pszProj4, "lon_0"); double dfPoleRotation = -dfLonP; double dfPoleLatitude = 180 - dfLatP; double dfPoleLongitude = dfLon0; oMapping.Add( "ProjectionName", "ObliqueCylindrical" ); oMapping.Add( "PoleLatitude", dfPoleLatitude ); oMapping.Add( "PoleLongitude", FixLong(dfPoleLongitude) ); oMapping.Add( "PoleRotation", dfPoleRotation ); } else { CPLError(CE_Warning, CPLE_NotSupported, "Projection %s not supported", pszProjection); } } else { CPLError(CE_Warning, CPLE_NotSupported, "Projection %s not supported", pszProjection); } if( oMapping["ProjectionName"].IsValid() ) { if( oSRS.GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ) != 0.0 ) { CPLError(CE_Warning, CPLE_NotSupported, "Ignoring %s. Only 0 value supported", SRS_PP_FALSE_EASTING); } if( oSRS.GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ) != 0.0 ) { CPLError(CE_Warning, CPLE_AppDefined, "Ignoring %s. Only 0 value supported", SRS_PP_FALSE_NORTHING); } } } else { CPLError(CE_Warning, CPLE_NotSupported, "SRS not supported"); } } if( !m_bUseSrcMapping && m_bGotTransform ) { oMapping.Add( "_type", "group" ); const double dfDegToMeter = oSRS.GetSemiMajor() * M_PI / 180.0; if( !m_oSRS.IsEmpty() && oSRS.IsProjected() ) { const double dfLinearUnits = oSRS.GetLinearUnits(); // Maybe we should deal differently with non meter units ? const double dfRes = m_adfGeoTransform[1] * dfLinearUnits; const double dfScale = dfDegToMeter / dfRes; oMapping.Add( "UpperLeftCornerX", m_adfGeoTransform[0] ); oMapping.Add( "UpperLeftCornerY", m_adfGeoTransform[3] ); oMapping.Add( "PixelResolution/value", dfRes ); oMapping.Add( "PixelResolution/unit", "meters/pixel" ); oMapping.Add( "Scale/value", dfScale ); oMapping.Add( "Scale/unit", "pixels/degree" ); } else if( !m_oSRS.IsEmpty() && oSRS.IsGeographic() ) { const double dfScale = 1.0 / m_adfGeoTransform[1]; const double dfRes = m_adfGeoTransform[1] * dfDegToMeter; oMapping.Add( "UpperLeftCornerX", m_adfGeoTransform[0] * dfDegToMeter ); oMapping.Add( "UpperLeftCornerY", m_adfGeoTransform[3] * dfDegToMeter ); oMapping.Add( "PixelResolution/value", dfRes ); oMapping.Add( "PixelResolution/unit", "meters/pixel" ); oMapping.Add( "Scale/value", dfScale ); oMapping.Add( "Scale/unit", "pixels/degree" ); } else { oMapping.Add( "UpperLeftCornerX", m_adfGeoTransform[0] ); oMapping.Add( "UpperLeftCornerY", m_adfGeoTransform[3] ); oMapping.Add( "PixelResolution", m_adfGeoTransform[1] ); } } CPLJSONObject oLabelLabel = GetOrCreateJSONObject(oLabel, "Label"); oLabelLabel.Set( "_type", "object" ); oLabelLabel.Set( "Bytes", pszLABEL_BYTES_PLACEHOLDER ); // Deal with History object BuildHistory(); oLabel.Delete( "History" ); if( !m_osHistory.empty() ) { CPLJSONObject oHistory; oHistory.Add( "_type", "object" ); oHistory.Add( "Name", "IsisCube" ); if( m_osExternalFilename.empty() ) oHistory.Add( "StartByte", pszHISTORY_STARTBYTE_PLACEHOLDER ); else oHistory.Add( "StartByte", 1 ); oHistory.Add( "Bytes", static_cast<GIntBig>(m_osHistory.size()) ); if( !m_osExternalFilename.empty() ) { CPLString osFilename(CPLGetBasename(GetDescription())); osFilename += ".History.IsisCube"; oHistory.Add( "^History", osFilename ); } oLabel.Add( "History", oHistory ); } // Deal with other objects that have StartByte & Bytes m_aoNonPixelSections.clear(); if( m_oSrcJSonLabel.IsValid() ) { CPLString osLabelSrcFilename; CPLJSONObject oFilename = oLabel["_filename"]; if( oFilename.GetType() == CPLJSONObject::Type::String ) { osLabelSrcFilename = oFilename.ToString(); } for( CPLJSONObject& oObj : oLabel.GetChildren() ) { CPLString osKey = oObj.GetName(); if( osKey == "History" ) { continue; } CPLJSONObject oBytes = oObj.GetObj( "Bytes" ); if( oBytes.GetType() != CPLJSONObject::Type::Integer || oBytes.ToInteger() <= 0 ) { continue; } CPLJSONObject oStartByte = oObj.GetObj( "StartByte" ); if( oStartByte.GetType() != CPLJSONObject::Type::Integer || oStartByte.ToInteger() <= 0 ) { continue; } if( osLabelSrcFilename.empty() ) { CPLError(CE_Warning, CPLE_AppDefined, "Cannot find _filename attribute in " "source ISIS3 metadata. Removing object " "%s from the label.", osKey.c_str()); oLabel.Delete( osKey ); continue; } NonPixelSection oSection; oSection.osSrcFilename = osLabelSrcFilename; oSection.nSrcOffset = static_cast<vsi_l_offset>( oObj.GetInteger("StartByte")) - 1U; oSection.nSize = static_cast<vsi_l_offset>( oObj.GetInteger("Bytes")); CPLString osName; CPLJSONObject oName = oObj.GetObj( "Name" ); if( oName.GetType() == CPLJSONObject::Type::String ) { osName = oName.ToString(); } CPLString osContainerName(osKey); CPLJSONObject oContainerName = oObj.GetObj( "_container_name" ); if( oContainerName.GetType() == CPLJSONObject::Type::String ) { osContainerName = oContainerName.ToString(); } const CPLString osKeyFilename( "^" + osContainerName ); CPLJSONObject oFilenameCap = oObj.GetObj( osKeyFilename ); if( oFilenameCap.GetType() == CPLJSONObject::Type::String ) { VSIStatBufL sStat; const CPLString osSrcFilename( CPLFormFilename( CPLGetPath(osLabelSrcFilename), oFilenameCap.ToString().c_str(), nullptr ) ); if( VSIStatL( osSrcFilename, &sStat ) == 0 ) { oSection.osSrcFilename = osSrcFilename; } else { CPLError(CE_Warning, CPLE_AppDefined, "Object %s points to %s, which does " "not exist. Removing this section " "from the label", osKey.c_str(), osSrcFilename.c_str()); oLabel.Delete( osKey ); continue; } } if( !m_osExternalFilename.empty() ) { oObj.Set( "StartByte", 1 ); } else { CPLString osPlaceHolder; osPlaceHolder.Printf( "!*^PLACEHOLDER_%d_STARTBYTE^*!", static_cast<int>(m_aoNonPixelSections.size()) + 1); oObj.Set( "StartByte", osPlaceHolder ); oSection.osPlaceHolder = osPlaceHolder; } if( !m_osExternalFilename.empty() ) { CPLString osDstFilename( CPLGetBasename(GetDescription()) ); osDstFilename += "."; osDstFilename += osContainerName; if( !osName.empty() ) { osDstFilename += "."; osDstFilename += osName; } oSection.osDstFilename = CPLFormFilename( CPLGetPath( GetDescription() ), osDstFilename, nullptr ); oObj.Set( osKeyFilename, osDstFilename ); } else { oObj.Delete( osKeyFilename ); } m_aoNonPixelSections.push_back(oSection); } } m_oJSonLabel = oLabel; } /************************************************************************/ /* BuildHistory() */ /************************************************************************/ void ISIS3Dataset::BuildHistory() { CPLString osHistory; if( m_oSrcJSonLabel.IsValid() && m_bUseSrcHistory ) { vsi_l_offset nHistoryOffset = 0; int nHistorySize = 0; CPLString osSrcFilename; CPLJSONObject oFilename = m_oSrcJSonLabel["_filename"]; if( oFilename.GetType() == CPLJSONObject::Type::String ) { osSrcFilename = oFilename.ToString(); } CPLString osHistoryFilename(osSrcFilename); CPLJSONObject oHistory = m_oSrcJSonLabel["History"]; if( oHistory.GetType() == CPLJSONObject::Type::Object ) { CPLJSONObject oHistoryFilename = oHistory["^History"]; if( oHistoryFilename.GetType() == CPLJSONObject::Type::String ) { osHistoryFilename = CPLFormFilename( CPLGetPath(osSrcFilename), oHistoryFilename.ToString().c_str(), nullptr ); } CPLJSONObject oStartByte = oHistory["StartByte"]; if( oStartByte.GetType() == CPLJSONObject::Type::Integer ) { if( oStartByte.ToInteger() > 0 ) { nHistoryOffset = static_cast<vsi_l_offset>( oStartByte.ToInteger()) - 1U; } } CPLJSONObject oBytes = oHistory["Bytes"]; if( oBytes.GetType() == CPLJSONObject::Type::Integer ) { nHistorySize = static_cast<int>( oBytes.ToInteger() ); } } if( osHistoryFilename.empty() ) { CPLDebug("ISIS3", "Cannot find filename for source history"); } else if( nHistorySize <= 0 || nHistorySize > 1000000 ) { CPLDebug("ISIS3", "Invalid or missing value for History.Bytes " "for source history"); } else { VSILFILE* fpHistory = VSIFOpenL(osHistoryFilename, "rb"); if( fpHistory != nullptr ) { VSIFSeekL(fpHistory, nHistoryOffset, SEEK_SET); osHistory.resize( nHistorySize ); if( VSIFReadL( &osHistory[0], nHistorySize, 1, fpHistory ) != 1 ) { CPLError(CE_Warning, CPLE_FileIO, "Cannot read %d bytes at offset " CPL_FRMT_GUIB "of %s: history will not be preserved", nHistorySize, nHistoryOffset, osHistoryFilename.c_str()); osHistory.clear(); } VSIFCloseL(fpHistory); } else { CPLError(CE_Warning, CPLE_FileIO, "Cannot open %s: history will not be preserved", osHistoryFilename.c_str()); } } } if( m_bAddGDALHistory && !m_osGDALHistory.empty() ) { if( !osHistory.empty() ) osHistory += "\n"; osHistory += m_osGDALHistory; } else if( m_bAddGDALHistory ) { if( !osHistory.empty() ) osHistory += "\n"; CPLJSONObject oHistoryObj; char szFullFilename[2048] = { 0 }; if( !CPLGetExecPath(szFullFilename, sizeof(szFullFilename) - 1) ) strcpy(szFullFilename, "unknown_program"); const CPLString osProgram(CPLGetBasename(szFullFilename)); const CPLString osPath(CPLGetPath(szFullFilename)); CPLJSONObject oObj; oHistoryObj.Add( osProgram, oObj ); oObj.Add( "_type", "object" ); oObj.Add( "GdalVersion", GDALVersionInfo("RELEASE_NAME") ); if( osPath != "." ) oObj.Add( "ProgramPath", osPath ); time_t nCurTime = time(nullptr); if( nCurTime != -1 ) { struct tm mytm; CPLUnixTimeToYMDHMS(nCurTime, &mytm); oObj.Add( "ExecutionDateTime", CPLSPrintf("%04d-%02d-%02dT%02d:%02d:%02d", mytm.tm_year + 1900, mytm.tm_mon + 1, mytm.tm_mday, mytm.tm_hour, mytm.tm_min, mytm.tm_sec) ); } char szHostname[256] = { 0 }; if( gethostname(szHostname, sizeof(szHostname)-1) == 0 ) { oObj.Add( "HostName", std::string(szHostname) ); } const char* pszUsername = CPLGetConfigOption("USERNAME", nullptr); if( pszUsername == nullptr ) pszUsername = CPLGetConfigOption("USER", nullptr); if( pszUsername != nullptr ) { oObj.Add( "UserName", pszUsername ); } oObj.Add( "Description", "GDAL conversion" ); CPLJSONObject oUserParameters; oObj.Add( "UserParameters", oUserParameters ); oUserParameters.Add( "_type", "group"); if( !m_osFromFilename.empty() ) { const CPLString osFromFilename = CPLGetFilename( m_osFromFilename ); oUserParameters.Add( "FROM", osFromFilename ); } if( nullptr != GetDescription() ) { const CPLString osToFileName = CPLGetFilename( GetDescription() ); oUserParameters.Add( "TO", osToFileName ); } if( m_bForce360 ) oUserParameters.Add( "Force_360", "true"); osHistory += SerializeAsPDL( oHistoryObj ); } m_osHistory = osHistory; } /************************************************************************/ /* WriteLabel() */ /************************************************************************/ void ISIS3Dataset::WriteLabel() { m_bIsLabelWritten = true; if( !m_oJSonLabel.IsValid() ) BuildLabel(); // Serialize label CPLString osLabel( SerializeAsPDL(m_oJSonLabel) ); osLabel += "End\n"; if( m_osExternalFilename.empty() && osLabel.size() < 65536 ) { // In-line labels have conventionally a minimize size of 65536 bytes // See #2741 osLabel.resize(65536); } char *pszLabel = &osLabel[0]; const int nLabelSize = static_cast<int>(osLabel.size()); // Hack back StartByte value { char *pszStartByte = strstr(pszLabel, pszSTARTBYTE_PLACEHOLDER); if( pszStartByte != nullptr ) { const char* pszOffset = CPLSPrintf("%d", 1 + nLabelSize); memcpy(pszStartByte, pszOffset, strlen(pszOffset)); memset(pszStartByte + strlen(pszOffset), ' ', strlen(pszSTARTBYTE_PLACEHOLDER) - strlen(pszOffset)); } } // Hack back Label.Bytes value { char* pszLabelBytes = strstr(pszLabel, pszLABEL_BYTES_PLACEHOLDER); if( pszLabelBytes != nullptr ) { const char* pszBytes = CPLSPrintf("%d", nLabelSize); memcpy(pszLabelBytes, pszBytes, strlen(pszBytes)); memset(pszLabelBytes + strlen(pszBytes), ' ', strlen(pszLABEL_BYTES_PLACEHOLDER) - strlen(pszBytes)); } } const GDALDataType eType = GetRasterBand(1)->GetRasterDataType(); const int nDTSize = GDALGetDataTypeSizeBytes(eType); vsi_l_offset nImagePixels = 0; if( m_poExternalDS == nullptr ) { if( m_bIsTiled ) { int nBlockXSize = 1, nBlockYSize = 1; GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize); nImagePixels = static_cast<vsi_l_offset>(nBlockXSize) * nBlockYSize * nBands * DIV_ROUND_UP(nRasterXSize, nBlockXSize) * DIV_ROUND_UP(nRasterYSize, nBlockYSize); } else { nImagePixels = static_cast<vsi_l_offset>(nRasterXSize) * nRasterYSize * nBands; } } // Hack back History.StartBytes value char* pszHistoryStartBytes = strstr(pszLabel, pszHISTORY_STARTBYTE_PLACEHOLDER); vsi_l_offset nHistoryOffset = 0; vsi_l_offset nLastOffset = 0; if( pszHistoryStartBytes != nullptr ) { CPLAssert( m_osExternalFilename.empty() ); nHistoryOffset = nLabelSize + nImagePixels * nDTSize; nLastOffset = nHistoryOffset + m_osHistory.size(); const char* pszStartByte = CPLSPrintf(CPL_FRMT_GUIB, nHistoryOffset + 1); CPLAssert(strlen(pszStartByte) < strlen(pszHISTORY_STARTBYTE_PLACEHOLDER)); memcpy(pszHistoryStartBytes, pszStartByte, strlen(pszStartByte)); memset(pszHistoryStartBytes + strlen(pszStartByte), ' ', strlen(pszHISTORY_STARTBYTE_PLACEHOLDER) - strlen(pszStartByte)); } // Replace placeholders in other sections for( size_t i = 0; i < m_aoNonPixelSections.size(); ++i ) { if( !m_aoNonPixelSections[i].osPlaceHolder.empty() ) { char* pszPlaceHolder = strstr(pszLabel, m_aoNonPixelSections[i].osPlaceHolder.c_str()); CPLAssert( pszPlaceHolder != nullptr ); const char* pszStartByte = CPLSPrintf(CPL_FRMT_GUIB, nLastOffset + 1); nLastOffset += m_aoNonPixelSections[i].nSize; CPLAssert(strlen(pszStartByte) < m_aoNonPixelSections[i].osPlaceHolder.size() ); memcpy(pszPlaceHolder, pszStartByte, strlen(pszStartByte)); memset(pszPlaceHolder + strlen(pszStartByte), ' ', m_aoNonPixelSections[i].osPlaceHolder.size() - strlen(pszStartByte)); } } // Write to final file VSIFSeekL( m_fpLabel, 0, SEEK_SET ); VSIFWriteL( pszLabel, 1, osLabel.size(), m_fpLabel); if( m_osExternalFilename.empty() ) { // Update image offset in bands if( m_bIsTiled ) { for(int i=0;i<nBands;i++) { ISISTiledBand* poBand = reinterpret_cast<ISISTiledBand*>(GetRasterBand(i+1)); poBand->m_nFirstTileOffset += nLabelSize; } } else { for(int i=0;i<nBands;i++) { ISIS3RawRasterBand* poBand = reinterpret_cast<ISIS3RawRasterBand*>(GetRasterBand(i+1)); poBand->nImgOffset += nLabelSize; } } } if( m_bInitToNodata ) { // Initialize the image to nodata const double dfNoData = GetRasterBand(1)->GetNoDataValue(); if( dfNoData == 0.0 ) { VSIFTruncateL( m_fpImage, VSIFTellL(m_fpImage) + nImagePixels * nDTSize ); } else if( nDTSize != 0 ) // to make Coverity not warn about div by 0 { const int nPageSize = 4096; // Must be multiple of 4 since // Float32 is the largest type CPLAssert( (nPageSize % nDTSize) == 0 ); const int nMaxPerPage = nPageSize / nDTSize; GByte* pabyTemp = static_cast<GByte*>(CPLMalloc(nPageSize)); GDALCopyWords( &dfNoData, GDT_Float64, 0, pabyTemp, eType, nDTSize, nMaxPerPage ); #ifdef CPL_MSB GDALSwapWords( pabyTemp, nDTSize, nMaxPerPage, nDTSize ); #endif for( vsi_l_offset i = 0; i < nImagePixels; i += nMaxPerPage ) { int n; if( i + nMaxPerPage <= nImagePixels ) n = nMaxPerPage; else n = static_cast<int>(nImagePixels - i); if( VSIFWriteL( pabyTemp, n * nDTSize, 1, m_fpImage ) != 1 ) { CPLError(CE_Failure, CPLE_FileIO, "Cannot initialize imagery to null"); break; } } CPLFree( pabyTemp ); } } // Write history if( !m_osHistory.empty() ) { if( m_osExternalFilename.empty() ) { VSIFSeekL( m_fpLabel, nHistoryOffset, SEEK_SET ); VSIFWriteL( m_osHistory.c_str(), 1, m_osHistory.size(), m_fpLabel); } else { CPLString osFilename(CPLGetBasename(GetDescription())); osFilename += ".History.IsisCube"; osFilename = CPLFormFilename(CPLGetPath(GetDescription()), osFilename, nullptr); VSILFILE* fp = VSIFOpenL(osFilename, "wb"); if( fp ) { m_aosAdditionalFiles.AddString(osFilename); VSIFWriteL( m_osHistory.c_str(), 1, m_osHistory.size(), fp ); VSIFCloseL(fp); } else { CPLError(CE_Warning, CPLE_FileIO, "Cannot write %s", osFilename.c_str()); } } } // Write other non pixel sections for( size_t i = 0; i < m_aoNonPixelSections.size(); ++i ) { VSILFILE* fpSrc = VSIFOpenL( m_aoNonPixelSections[i].osSrcFilename, "rb"); if( fpSrc == nullptr ) { CPLError(CE_Warning, CPLE_FileIO, "Cannot open %s", m_aoNonPixelSections[i].osSrcFilename.c_str()); continue; } VSILFILE* fpDest = m_fpLabel; if( !m_aoNonPixelSections[i].osDstFilename.empty() ) { fpDest = VSIFOpenL(m_aoNonPixelSections[i].osDstFilename, "wb"); if( fpDest == nullptr ) { CPLError(CE_Warning, CPLE_FileIO, "Cannot create %s", m_aoNonPixelSections[i].osDstFilename.c_str()); VSIFCloseL(fpSrc); continue; } m_aosAdditionalFiles.AddString( m_aoNonPixelSections[i].osDstFilename); } VSIFSeekL(fpSrc, m_aoNonPixelSections[i].nSrcOffset, SEEK_SET); GByte abyBuffer[4096]; vsi_l_offset nRemaining = m_aoNonPixelSections[i].nSize; while( nRemaining ) { size_t nToRead = 4096; if( nRemaining < nToRead ) nToRead = static_cast<size_t>(nRemaining); size_t nRead = VSIFReadL( abyBuffer, 1, nToRead, fpSrc ); if( nRead != nToRead ) { CPLError(CE_Warning, CPLE_FileIO, "Could not read " CPL_FRMT_GUIB " bytes from %s", m_aoNonPixelSections[i].nSize, m_aoNonPixelSections[i].osSrcFilename.c_str()); break; } VSIFWriteL( abyBuffer, 1, nRead, fpDest ); nRemaining -= nRead; } VSIFCloseL( fpSrc ); if( fpDest != m_fpLabel ) VSIFCloseL(fpDest); } } /************************************************************************/ /* SerializeAsPDL() */ /************************************************************************/ CPLString ISIS3Dataset::SerializeAsPDL( const CPLJSONObject &oObj ) { CPLString osTmpFile( CPLSPrintf("/vsimem/isis3_%p", oObj.GetInternalHandle()) ); VSILFILE* fpTmp = VSIFOpenL( osTmpFile, "wb+" ); SerializeAsPDL( fpTmp, oObj ); VSIFCloseL( fpTmp ); CPLString osContent( reinterpret_cast<char*>( VSIGetMemFileBuffer( osTmpFile, nullptr, FALSE )) ); VSIUnlink(osTmpFile); return osContent; } /************************************************************************/ /* SerializeAsPDL() */ /************************************************************************/ void ISIS3Dataset::SerializeAsPDL( VSILFILE* fp, const CPLJSONObject &oObj, int nDepth ) { CPLString osIndentation; for( int i = 0; i < nDepth; i++ ) osIndentation += " "; const size_t WIDTH = 79; std::vector<CPLJSONObject> aoChildren = oObj.GetChildren(); size_t nMaxKeyLength = 0; for( const CPLJSONObject& oChild : aoChildren ) { const CPLString osKey = oChild.GetName(); if( EQUAL(osKey, "_type") || EQUAL(osKey, "_container_name") || EQUAL(osKey, "_filename") ) { continue; } const auto eType = oChild.GetType(); if( eType == CPLJSONObject::Type::String || eType == CPLJSONObject::Type::Integer || eType == CPLJSONObject::Type::Double || eType == CPLJSONObject::Type::Array ) { if( osKey.size() > nMaxKeyLength ) { nMaxKeyLength = osKey.size(); } } else if( eType == CPLJSONObject::Type::Object ) { CPLJSONObject oValue = oChild.GetObj( "value" ); CPLJSONObject oUnit = oChild.GetObj( "unit" ); if( oValue.IsValid() && oUnit.GetType() == CPLJSONObject::Type::String ) { if( osKey.size() > nMaxKeyLength ) { nMaxKeyLength = osKey.size(); } } } } for( const CPLJSONObject& oChild : aoChildren ) { const CPLString osKey = oChild.GetName(); if( EQUAL(osKey, "_type") || EQUAL(osKey, "_container_name") || EQUAL(osKey, "_filename") ) { continue; } if( STARTS_WITH(osKey, "_comment") ) { if( oChild.GetType() == CPLJSONObject::Type::String ) { VSIFPrintfL(fp, "#%s\n", oChild.ToString().c_str() ); } continue; } CPLString osPadding; size_t nLen = osKey.size(); if( nLen < nMaxKeyLength ) { osPadding.append( nMaxKeyLength - nLen, ' ' ); } const auto eType = oChild.GetType(); if( eType == CPLJSONObject::Type::Object ) { CPLJSONObject oType = oChild.GetObj( "_type" ); CPLJSONObject oContainerName = oChild.GetObj( "_container_name" ); CPLString osContainerName = osKey; if( oContainerName.GetType() == CPLJSONObject::Type::String ) { osContainerName = oContainerName.ToString(); } if( oType.GetType() == CPLJSONObject::Type::String ) { const CPLString osType = oType.ToString(); if( EQUAL(osType, "Object") ) { if( nDepth == 0 && VSIFTellL(fp) != 0 ) VSIFPrintfL(fp, "\n"); VSIFPrintfL(fp, "%sObject = %s\n", osIndentation.c_str(), osContainerName.c_str()); SerializeAsPDL( fp, oChild, nDepth + 1 ); VSIFPrintfL(fp, "%sEnd_Object\n", osIndentation.c_str()); } else if( EQUAL(osType, "Group") ) { VSIFPrintfL(fp, "\n"); VSIFPrintfL(fp, "%sGroup = %s\n", osIndentation.c_str(), osContainerName.c_str()); SerializeAsPDL( fp, oChild, nDepth + 1 ); VSIFPrintfL(fp, "%sEnd_Group\n", osIndentation.c_str()); } } else { CPLJSONObject oValue = oChild.GetObj( "value" ); CPLJSONObject oUnit = oChild.GetObj( "unit" ); if( oValue.IsValid() && oUnit.GetType() == CPLJSONObject::Type::String ) { const CPLString osUnit = oUnit.ToString(); const auto eValueType = oValue.GetType(); if( eValueType == CPLJSONObject::Type::Integer ) { VSIFPrintfL(fp, "%s%s%s = %d <%s>\n", osIndentation.c_str(), osKey.c_str(), osPadding.c_str(), oValue.ToInteger(), osUnit.c_str()); } else if( eValueType == CPLJSONObject::Type::Double ) { const double dfVal = oValue.ToDouble(); if( dfVal >= INT_MIN && dfVal <= INT_MAX && static_cast<int>(dfVal) == dfVal ) { VSIFPrintfL(fp, "%s%s%s = %d.0 <%s>\n", osIndentation.c_str(), osKey.c_str(), osPadding.c_str(), static_cast<int>(dfVal), osUnit.c_str()); } else { VSIFPrintfL(fp, "%s%s%s = %.18g <%s>\n", osIndentation.c_str(), osKey.c_str(), osPadding.c_str(), dfVal, osUnit.c_str()); } } } } } else if( eType == CPLJSONObject::Type::String ) { CPLString osVal = oChild.ToString(); const char* pszVal = osVal.c_str(); if( pszVal[0] == '\0' || strchr(pszVal, ' ') || strstr(pszVal, "\\n") || strstr(pszVal, "\\r") ) { osVal.replaceAll("\\n", "\n"); osVal.replaceAll("\\r", "\r"); VSIFPrintfL(fp, "%s%s%s = \"%s\"\n", osIndentation.c_str(), osKey.c_str(), osPadding.c_str(), osVal.c_str()); } else { if( osIndentation.size() + osKey.size() + osPadding.size() + strlen(" = ") + strlen(pszVal) > WIDTH && osIndentation.size() + osKey.size() + osPadding.size() + strlen(" = ") < WIDTH ) { size_t nFirstPos = osIndentation.size() + osKey.size() + osPadding.size() + strlen(" = "); VSIFPrintfL(fp, "%s%s%s = ", osIndentation.c_str(), osKey.c_str(), osPadding.c_str()); size_t nCurPos = nFirstPos; for( int j = 0; pszVal[j] != '\0'; j++ ) { nCurPos ++; if( nCurPos == WIDTH && pszVal[j+1] != '\0' ) { VSIFPrintfL( fp, "-\n" ); for( size_t k=0;k<nFirstPos;k++ ) { const char chSpace = ' '; VSIFWriteL(&chSpace, 1, 1, fp); } nCurPos = nFirstPos + 1; } VSIFWriteL( &pszVal[j], 1, 1, fp ); } VSIFPrintfL(fp, "\n"); } else { VSIFPrintfL(fp, "%s%s%s = %s\n", osIndentation.c_str(), osKey.c_str(), osPadding.c_str(), pszVal); } } } else if( eType == CPLJSONObject::Type::Integer ) { const int nVal = oChild.ToInteger(); VSIFPrintfL(fp, "%s%s%s = %d\n", osIndentation.c_str(), osKey.c_str(), osPadding.c_str(), nVal); } else if( eType == CPLJSONObject::Type::Double ) { const double dfVal = oChild.ToDouble(); if( dfVal >= INT_MIN && dfVal <= INT_MAX && static_cast<int>(dfVal) == dfVal ) { VSIFPrintfL(fp, "%s%s%s = %d.0\n", osIndentation.c_str(), osKey.c_str(), osPadding.c_str(), static_cast<int>(dfVal)); } else { VSIFPrintfL(fp, "%s%s%s = %.18g\n", osIndentation.c_str(), osKey.c_str(), osPadding.c_str(), dfVal); } } else if( eType == CPLJSONObject::Type::Array ) { CPLJSONArray oArrayItem(oChild); const int nLength = oArrayItem.Size(); size_t nFirstPos = osIndentation.size() + osKey.size() + osPadding.size() + strlen(" = ("); VSIFPrintfL(fp, "%s%s%s = (", osIndentation.c_str(), osKey.c_str(), osPadding.c_str()); size_t nCurPos = nFirstPos; for( int idx = 0; idx < nLength; idx++ ) { CPLJSONObject oItem = oArrayItem[idx]; const auto eArrayItemType = oItem.GetType(); if( eArrayItemType == CPLJSONObject::Type::String ) { CPLString osVal = oItem.ToString(); const char* pszVal = osVal.c_str(); if( pszVal[0] == '\0' || strchr(pszVal, ' ') || strstr(pszVal, "\\n") || strstr(pszVal, "\\r") ) { osVal.replaceAll("\\n", "\n"); osVal.replaceAll("\\r", "\r"); VSIFPrintfL(fp, "\"%s\"", osVal.c_str()); } else if( nFirstPos < WIDTH && nCurPos + strlen(pszVal) > WIDTH ) { if( idx > 0 ) { VSIFPrintfL( fp, "\n" ); for( size_t j=0;j<nFirstPos;j++ ) { const char chSpace = ' '; VSIFWriteL(&chSpace, 1, 1, fp); } nCurPos = nFirstPos; } for( int j = 0; pszVal[j] != '\0'; j++ ) { nCurPos ++; if( nCurPos == WIDTH && pszVal[j+1] != '\0' ) { VSIFPrintfL( fp, "-\n" ); for( size_t k=0;k<nFirstPos;k++ ) { const char chSpace = ' '; VSIFWriteL(&chSpace, 1, 1, fp); } nCurPos = nFirstPos + 1; } VSIFWriteL( &pszVal[j], 1, 1, fp ); } } else { VSIFPrintfL( fp, "%s", pszVal ); nCurPos += strlen(pszVal); } } else if( eArrayItemType == CPLJSONObject::Type::Integer ) { const int nVal = oItem.ToInteger(); const char* pszVal = CPLSPrintf("%d", nVal); const size_t nValLen = strlen(pszVal); if( nFirstPos < WIDTH && idx > 0 && nCurPos + nValLen > WIDTH ) { VSIFPrintfL( fp, "\n" ); for( size_t j=0;j<nFirstPos;j++ ) { const char chSpace = ' '; VSIFWriteL(&chSpace, 1, 1, fp); } nCurPos = nFirstPos; } VSIFPrintfL( fp, "%d", nVal ); nCurPos += nValLen; } else if( eArrayItemType == CPLJSONObject::Type::Double ) { const double dfVal = oItem.ToDouble(); CPLString osVal; if( dfVal >= INT_MIN && dfVal <= INT_MAX && static_cast<int>(dfVal) == dfVal ) { osVal = CPLSPrintf("%d.0", static_cast<int>(dfVal)); } else { osVal = CPLSPrintf("%.18g", dfVal); } const size_t nValLen = osVal.size(); if( nFirstPos < WIDTH && idx > 0 && nCurPos + nValLen > WIDTH ) { VSIFPrintfL( fp, "\n" ); for( size_t j=0;j<nFirstPos;j++ ) { const char chSpace = ' '; VSIFWriteL(&chSpace, 1, 1, fp); } nCurPos = nFirstPos; } VSIFPrintfL( fp, "%s", osVal.c_str() ); nCurPos += nValLen; } if( idx < nLength - 1 ) { VSIFPrintfL( fp, ", " ); nCurPos += 2; } } VSIFPrintfL(fp, ")\n" ); } } } /************************************************************************/ /* Create() */ /************************************************************************/ GDALDataset *ISIS3Dataset::Create(const char* pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, char** papszOptions) { if( eType != GDT_Byte && eType != GDT_UInt16 && eType != GDT_Int16 && eType != GDT_Float32 ) { CPLError(CE_Failure, CPLE_NotSupported, "Unsupported data type"); return nullptr; } if( nBands == 0 || nBands > 32767 ) { CPLError(CE_Failure, CPLE_NotSupported, "Unsupported band count"); return nullptr; } const char* pszDataLocation = CSLFetchNameValueDef(papszOptions, "DATA_LOCATION", "LABEL"); const bool bIsTiled = CPLFetchBool(papszOptions, "TILED", false); const int nBlockXSize = std::max(1, atoi(CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", "256"))); const int nBlockYSize = std::max(1, atoi(CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", "256"))); if( !EQUAL(pszDataLocation, "LABEL") && !EQUAL( CPLGetExtension(pszFilename), "LBL") ) { CPLError(CE_Failure, CPLE_NotSupported, "For DATA_LOCATION=%s, " "the main filename should have a .lbl extension", pszDataLocation); return nullptr; } VSILFILE* fp = VSIFOpenExL(pszFilename, "wb", true); if( fp == nullptr ) { CPLError( CE_Failure, CPLE_FileIO, "Cannot create %s: %s", pszFilename, VSIGetLastErrorMsg() ); return nullptr; } VSILFILE* fpImage = nullptr; CPLString osExternalFilename; GDALDataset* poExternalDS = nullptr; bool bGeoTIFFAsRegularExternal = false; if( EQUAL(pszDataLocation, "EXTERNAL") ) { osExternalFilename = CSLFetchNameValueDef(papszOptions, "EXTERNAL_FILENAME", CPLResetExtension(pszFilename, "cub")); fpImage = VSIFOpenExL(osExternalFilename, "wb", true); if( fpImage == nullptr ) { CPLError( CE_Failure, CPLE_FileIO, "Cannot create %s: %s", osExternalFilename.c_str(), VSIGetLastErrorMsg() ); VSIFCloseL(fp); return nullptr; } } else if( EQUAL(pszDataLocation, "GEOTIFF") ) { osExternalFilename = CSLFetchNameValueDef(papszOptions, "EXTERNAL_FILENAME", CPLResetExtension(pszFilename, "tif")); GDALDriver* poDrv = static_cast<GDALDriver*>( GDALGetDriverByName("GTiff")); if( poDrv == nullptr ) { CPLError( CE_Failure, CPLE_AppDefined, "Cannot find GTiff driver" ); VSIFCloseL(fp); return nullptr; } char** papszGTiffOptions = nullptr; papszGTiffOptions = CSLSetNameValue(papszGTiffOptions, "ENDIANNESS", "LITTLE"); if( bIsTiled ) { papszGTiffOptions = CSLSetNameValue(papszGTiffOptions, "TILED", "YES"); papszGTiffOptions = CSLSetNameValue(papszGTiffOptions, "BLOCKXSIZE", CPLSPrintf("%d", nBlockXSize)); papszGTiffOptions = CSLSetNameValue(papszGTiffOptions, "BLOCKYSIZE", CPLSPrintf("%d", nBlockYSize)); } const char* pszGTiffOptions = CSLFetchNameValueDef(papszOptions, "GEOTIFF_OPTIONS", ""); char** papszTokens = CSLTokenizeString2( pszGTiffOptions, ",", 0 ); for( int i = 0; papszTokens[i] != nullptr; i++ ) { papszGTiffOptions = CSLAddString(papszGTiffOptions, papszTokens[i]); } CSLDestroy(papszTokens); // If the user didn't specify any compression and // GEOTIFF_AS_REGULAR_EXTERNAL is set (or unspecified), then the // GeoTIFF file can be seen as a regular external raw file, provided // we make some provision on its organization. if( CSLFetchNameValue(papszGTiffOptions, "COMPRESS") == nullptr && CPLFetchBool(papszOptions, "GEOTIFF_AS_REGULAR_EXTERNAL", true) ) { bGeoTIFFAsRegularExternal = true; papszGTiffOptions = CSLSetNameValue(papszGTiffOptions, "INTERLEAVE", "BAND"); // Will make sure that our blocks at nodata are not optimized // away but indeed well written papszGTiffOptions = CSLSetNameValue(papszGTiffOptions, "@WRITE_EMPTY_TILES_SYNCHRONOUSLY", "YES"); if( !bIsTiled && nBands > 1 ) { papszGTiffOptions = CSLSetNameValue(papszGTiffOptions, "BLOCKYSIZE", "1"); } } poExternalDS = poDrv->Create( osExternalFilename, nXSize, nYSize, nBands, eType, papszGTiffOptions ); CSLDestroy(papszGTiffOptions); if( poExternalDS == nullptr ) { CPLError( CE_Failure, CPLE_FileIO, "Cannot create %s", osExternalFilename.c_str() ); VSIFCloseL(fp); return nullptr; } } ISIS3Dataset* poDS = new ISIS3Dataset(); poDS->SetDescription( pszFilename ); poDS->eAccess = GA_Update; poDS->nRasterXSize = nXSize; poDS->nRasterYSize = nYSize; poDS->m_osExternalFilename = osExternalFilename; poDS->m_poExternalDS = poExternalDS; poDS->m_bGeoTIFFAsRegularExternal = bGeoTIFFAsRegularExternal; if( bGeoTIFFAsRegularExternal ) poDS->m_bGeoTIFFInitDone = false; poDS->m_fpLabel = fp; poDS->m_fpImage = fpImage ? fpImage: fp; poDS->m_bIsLabelWritten = false; poDS->m_bIsTiled = bIsTiled; poDS->m_bInitToNodata = (poDS->m_poExternalDS == nullptr); poDS->m_osComment = CSLFetchNameValueDef(papszOptions, "COMMENT", ""); poDS->m_osLatitudeType = CSLFetchNameValueDef(papszOptions, "LATITUDE_TYPE", ""); poDS->m_osLongitudeDirection = CSLFetchNameValueDef(papszOptions, "LONGITUDE_DIRECTION", ""); poDS->m_osTargetName = CSLFetchNameValueDef(papszOptions, "TARGET_NAME", ""); poDS->m_bForce360 = CPLFetchBool(papszOptions, "FORCE_360", false); poDS->m_bWriteBoundingDegrees = CPLFetchBool(papszOptions, "WRITE_BOUNDING_DEGREES", true); poDS->m_osBoundingDegrees = CSLFetchNameValueDef(papszOptions, "BOUNDING_DEGREES", ""); poDS->m_bUseSrcLabel = CPLFetchBool(papszOptions, "USE_SRC_LABEL", true); poDS->m_bUseSrcMapping = CPLFetchBool(papszOptions, "USE_SRC_MAPPING", false); poDS->m_bUseSrcHistory = CPLFetchBool(papszOptions, "USE_SRC_HISTORY", true); poDS->m_bAddGDALHistory = CPLFetchBool(papszOptions, "ADD_GDAL_HISTORY", true); if( poDS->m_bAddGDALHistory ) { poDS->m_osGDALHistory = CSLFetchNameValueDef(papszOptions, "GDAL_HISTORY", ""); } const double dfNoData = (eType == GDT_Byte) ? NULL1: (eType == GDT_UInt16) ? NULLU2: (eType == GDT_Int16) ? NULL2: /*(eType == GDT_Float32) ?*/ NULL4; for( int i = 0; i < nBands; i++ ) { GDALRasterBand *poBand = nullptr; if( poDS->m_poExternalDS != nullptr ) { ISIS3WrapperRasterBand* poISISBand = new ISIS3WrapperRasterBand( poDS->m_poExternalDS->GetRasterBand( i+1 ) ); poBand = poISISBand; } else if( bIsTiled ) { ISISTiledBand* poISISBand = new ISISTiledBand( poDS, poDS->m_fpImage, i+1, eType, nBlockXSize, nBlockYSize, 0, //nSkipBytes, to be hacked // afterwards for in-label imagery 0, 0, CPL_IS_LSB ); poBand = poISISBand; } else { const int nPixelOffset = GDALGetDataTypeSizeBytes(eType); const int nLineOffset = nPixelOffset * nXSize; const vsi_l_offset nBandOffset = static_cast<vsi_l_offset>(nLineOffset) * nYSize; ISIS3RawRasterBand* poISISBand = new ISIS3RawRasterBand( poDS, i+1, poDS->m_fpImage, nBandOffset * i, // nImgOffset, to be //hacked afterwards for in-label imagery nPixelOffset, nLineOffset, eType, CPL_IS_LSB ); poBand = poISISBand; } poDS->SetBand( i+1, poBand ); poBand->SetNoDataValue(dfNoData); } return poDS; } /************************************************************************/ /* GetUnderlyingDataset() */ /************************************************************************/ static GDALDataset* GetUnderlyingDataset( GDALDataset* poSrcDS ) { if( poSrcDS->GetDriver() != nullptr && poSrcDS->GetDriver() == GDALGetDriverByName("VRT") ) { VRTDataset* poVRTDS = reinterpret_cast<VRTDataset* >(poSrcDS); poSrcDS = poVRTDS->GetSingleSimpleSource(); } return poSrcDS; } /************************************************************************/ /* CreateCopy() */ /************************************************************************/ GDALDataset* ISIS3Dataset::CreateCopy( const char *pszFilename, GDALDataset *poSrcDS, int /*bStrict*/, char ** papszOptions, GDALProgressFunc pfnProgress, void * pProgressData ) { const char* pszDataLocation = CSLFetchNameValueDef(papszOptions, "DATA_LOCATION", "LABEL"); GDALDataset* poSrcUnderlyingDS = GetUnderlyingDataset(poSrcDS); if( poSrcUnderlyingDS == nullptr ) poSrcUnderlyingDS = poSrcDS; if( EQUAL(pszDataLocation, "GEOTIFF") && strcmp(poSrcUnderlyingDS->GetDescription(), CSLFetchNameValueDef(papszOptions, "EXTERNAL_FILENAME", CPLResetExtension(pszFilename, "tif")) ) == 0 ) { CPLError(CE_Failure, CPLE_NotSupported, "Output file has same name as input file"); return nullptr; } if( poSrcDS->GetRasterCount() == 0 ) { CPLError(CE_Failure, CPLE_NotSupported, "Unsupported band count"); return nullptr; } const int nXSize = poSrcDS->GetRasterXSize(); const int nYSize = poSrcDS->GetRasterYSize(); const int nBands = poSrcDS->GetRasterCount(); GDALDataType eType = poSrcDS->GetRasterBand(1)->GetRasterDataType(); ISIS3Dataset *poDS = reinterpret_cast<ISIS3Dataset*>( Create( pszFilename, nXSize, nYSize, nBands, eType, papszOptions )); if( poDS == nullptr ) return nullptr; poDS->m_osFromFilename = poSrcUnderlyingDS->GetDescription(); double adfGeoTransform[6] = { 0.0 }; if( poSrcDS->GetGeoTransform( adfGeoTransform ) == CE_None && (adfGeoTransform[0] != 0.0 || adfGeoTransform[1] != 1.0 || adfGeoTransform[2] != 0.0 || adfGeoTransform[3] != 0.0 || adfGeoTransform[4] != 0.0 || adfGeoTransform[5] != 1.0) ) { poDS->SetGeoTransform( adfGeoTransform ); } auto poSrcSRS = poSrcDS->GetSpatialRef(); if( poSrcSRS ) { poDS->SetSpatialRef( poSrcSRS ); } for(int i=1;i<=nBands;i++) { const double dfOffset = poSrcDS->GetRasterBand(i)->GetOffset(); if( dfOffset != 0.0 ) poDS->GetRasterBand(i)->SetOffset(dfOffset); const double dfScale = poSrcDS->GetRasterBand(i)->GetScale(); if( dfScale != 1.0 ) poDS->GetRasterBand(i)->SetScale(dfScale); } // Do we need to remap nodata ? int bHasNoData = FALSE; poDS->m_dfSrcNoData = poSrcDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData); poDS->m_bHasSrcNoData = CPL_TO_BOOL(bHasNoData); if( poDS->m_bUseSrcLabel ) { char** papszMD_ISIS3 = poSrcDS->GetMetadata("json:ISIS3"); if( papszMD_ISIS3 != nullptr ) { poDS->SetMetadata( papszMD_ISIS3, "json:ISIS3" ); } } // We don't need to initialize the imagery as we are going to copy it // completely poDS->m_bInitToNodata = false; CPLErr eErr = GDALDatasetCopyWholeRaster( poSrcDS, poDS, nullptr, pfnProgress, pProgressData ); poDS->FlushCache(); poDS->m_bHasSrcNoData = false; if( eErr != CE_None ) { delete poDS; return nullptr; } return poDS; } /************************************************************************/ /* GDALRegister_ISIS3() */ /************************************************************************/ void GDALRegister_ISIS3() { if( GDALGetDriverByName( "ISIS3" ) != nullptr ) return; GDALDriver *poDriver = new GDALDriver(); poDriver->SetDescription( "ISIS3" ); poDriver->SetMetadataItem( GDAL_DCAP_RASTER, "YES" ); poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, "USGS Astrogeology ISIS cube (Version 3)" ); poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "drivers/raster/isis3.html" ); poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" ); poDriver->SetMetadataItem( GDAL_DMD_EXTENSIONS, "lbl cub" ); poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES, "Byte UInt16 Int16 Float32" ); poDriver->SetMetadataItem( GDAL_DMD_OPENOPTIONLIST, "<OpenOptionList/>"); poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST, "<CreationOptionList>" " <Option name='DATA_LOCATION' type='string-select' " "description='Location of pixel data' default='LABEL'>" " <Value>LABEL</Value>" " <Value>EXTERNAL</Value>" " <Value>GEOTIFF</Value>" " </Option>" " <Option name='GEOTIFF_AS_REGULAR_EXTERNAL' type='boolean' " "description='Whether the GeoTIFF file, if uncompressed, should be " "registered as a regular raw file' default='YES'/>" " <Option name='GEOTIFF_OPTIONS' type='string' " "description='Comma separated list of KEY=VALUE tuples to forward " "to the GeoTIFF driver'/>" " <Option name='EXTERNAL_FILENAME' type='string' " "description='Override default external filename. " "Only for DATA_LOCATION=EXTERNAL or GEOTIFF'/>" " <Option name='TILED' type='boolean' " "description='Whether the pixel data should be tiled' default='NO'/>" " <Option name='BLOCKXSIZE' type='int' " "description='Tile width' default='256'/>" " <Option name='BLOCKYSIZE' type='int' " "description='Tile height' default='256'/>" " <Option name='COMMENT' type='string' " "description='Comment to add into the label'/>" " <Option name='LATITUDE_TYPE' type='string-select' " "description='Value of Mapping.LatitudeType' default='Planetocentric'>" " <Value>Planetocentric</Value>" " <Value>Planetographic</Value>" " </Option>" " <Option name='LONGITUDE_DIRECTION' type='string-select' " "description='Value of Mapping.LongitudeDirection' " "default='PositiveEast'>" " <Value>PositiveEast</Value>" " <Value>PositiveWest</Value>" " </Option>" " <Option name='TARGET_NAME' type='string' description='Value of " "Mapping.TargetName'/>" " <Option name='FORCE_360' type='boolean' " "description='Whether to force longitudes in [0,360] range' default='NO'/>" " <Option name='WRITE_BOUNDING_DEGREES' type='boolean' " "description='Whether to write Min/MaximumLong/Latitude values' " "default='YES'/>" " <Option name='BOUNDING_DEGREES' type='string' " "description='Manually set bounding box with the syntax " "min_long,min_lat,max_long,max_lat'/>" " <Option name='USE_SRC_LABEL' type='boolean' " "description='Whether to use source label in ISIS3 to ISIS3 conversions' " "default='YES'/>" " <Option name='USE_SRC_MAPPING' type='boolean' " "description='Whether to use Mapping group from source label in " "ISIS3 to ISIS3 conversions' " "default='NO'/>" " <Option name='USE_SRC_HISTORY' type='boolean' " "description='Whether to use content pointed by the History object in " "ISIS3 to ISIS3 conversions' " "default='YES'/>" " <Option name='ADD_GDAL_HISTORY' type='boolean' " "description='Whether to add GDAL specific history in the content pointed " "by the History object in " "ISIS3 to ISIS3 conversions' " "default='YES'/>" " <Option name='GDAL_HISTORY' type='string' " "description='Manually defined GDAL history. Must be formatted as ISIS3 " "PDL. If not specified, it is automatically composed.'/>" "</CreationOptionList>" ); poDriver->pfnOpen = ISIS3Dataset::Open; poDriver->pfnIdentify = ISIS3Dataset::Identify; poDriver->pfnCreate = ISIS3Dataset::Create; poDriver->pfnCreateCopy = ISIS3Dataset::CreateCopy; GetGDALDriverManager()->RegisterDriver( poDriver ); }
grueni75/GeoDiscoverer
Source/Platform/Target/Android/core/src/main/jni/gdal-3.2.1/frmts/pds/isis3dataset.cpp
C++
gpl-3.0
172,938
using System; using System.IO; using Nez; namespace Otiose2D.Input { public class MouseBindingSource : BindingSource { public Mouse Control { get; protected set; } public static float ScaleX = 0.2f; public static float ScaleY = 0.2f; public static float ScaleZ = 0.2f; internal MouseBindingSource() { } public MouseBindingSource(Mouse mouseControl) { Control = mouseControl; } // Unity doesn't allow mouse buttons above certain numbers on // some platforms. For example, the limit on Windows 7 appears // to be 6. internal static bool SafeGetMouseButton(int button) { try { //TODO: Mouse button possible problem. //return Input.GetMouseButton(button); } catch (ArgumentException) { } return false; } // This is necessary to maintain backward compatibility. :( readonly static int[] buttonTable = new[] { -1, 0, 1, 2, -1, -1, -1, -1, -1, -1, 3, 4, 5, 6, 7, 8 }; internal static bool ButtonIsPressed(Mouse control) { var button = buttonTable[(int)control]; if (button >= 0) { return SafeGetMouseButton(button); } return false; } public override float GetValue(InputDevice inputDevice) { var button = buttonTable[(int)Control]; if (button >= 0) { return SafeGetMouseButton(button) ? 1.0f : 0.0f; } switch (Control) { case Mouse.NegativeX: return -Math.Min(Nez.Input.scaledMousePosition.X, 0.0f); case Mouse.PositiveX: return Math.Max(0.0f, Nez.Input.scaledMousePosition.X); case Mouse.NegativeY: return -Math.Min(Nez.Input.scaledMousePosition.Y, 0.0f); case Mouse.PositiveY: return Math.Max(0.0f, Nez.Input.scaledMousePosition.Y); case Mouse.NegativeScrollWheel: return -Math.Min(Nez.Input.mouseWheel, 0.0f); case Mouse.PositiveScrollWheel: return Math.Max(0.0f, Nez.Input.mouseWheel); } return 0.0f; } public override bool GetState(InputDevice inputDevice) { return Utility.IsNotZero(GetValue(inputDevice)); } public override string Name { get { return Control.ToString(); } } public override string DeviceName { get { return "Mouse"; } } public override bool Equals(BindingSource other) { if (other == null) { return false; } var bindingSource = other as MouseBindingSource; if (bindingSource != null) { return Control == bindingSource.Control; } return false; } public override bool Equals(object other) { if (other == null) { return false; } var bindingSource = other as MouseBindingSource; if (bindingSource != null) { return Control == bindingSource.Control; } return false; } public override int GetHashCode() { return Control.GetHashCode(); } internal override BindingSourceType BindingSourceType { get { return BindingSourceType.MouseBindingSource; } } internal override void Save(BinaryWriter writer) { writer.Write((int)Control); } internal override void Load(BinaryReader reader) { Control = (Mouse)reader.ReadInt32(); } } }
Blucky87/Otiose2D
src/input/system/MouseBindingSource.cs
C#
gpl-3.0
4,207
"use strict"; let templatePad = function (n, padTemplate) { let str = (n).toString(); return (padTemplate + str).substring(str.length); }; let formatByte = function (n) { return templatePad(n.toString(16).toLocaleUpperCase(), '00'); }; let instructionProperties = [ 'note', 'instrument_high','instrument_low', 'volume', 'fx0_type','fx0_high','fx0_low', ]; let getInstruction = function(overrideChannel){ let editorState = app.editorState; let projectState = app.projectState; let channelIndex = overrideChannel != null ? overrideChannel : editorState.activeChannelIndex; let activeSong = projectState.songs[editorState.activeSongIndex]; let activePatternIndex = activeSong.orders[editorState.activeOrderIndex][channelIndex]; let activePattern = activeSong.patterns[channelIndex][activePatternIndex]; while(activePattern.length < activeSong.rows) { activePattern.push(hydration.newEmptyInstruction()); } let instruction = activePattern[editorState.activeRowIndex]; return JSON.parse(JSON.stringify(instruction)); // return a copy in case our caller decides to back out of changing the instruction }; let updateInstruction = function(newInstruction, overrideChannel){ let editorState = app.editorState; let projectState = app.projectState; let channelIndex = overrideChannel != null ? overrideChannel : editorState.activeChannelIndex; let activeSong = projectState.songs[editorState.activeSongIndex]; let activePatternIndex = activeSong.orders[editorState.activeOrderIndex][channelIndex]; let activePattern = activeSong.patterns[channelIndex][activePatternIndex]; let oldInstruction = activePattern[editorState.activeRowIndex]; for(let prop in newInstruction) { // in practice, this will always update a non-null fx if(oldInstruction[prop] != newInstruction[prop]) { oldInstruction[prop] = newInstruction[prop]; } } }; let eraseValue = function () { let instruction = getInstruction(); let property = app.editorState.activeProperty.match(/^[^_]*/)[0]; if(property.startsWith('fx')){ let fxIndex = parseInt(property.substring(2), 10); instruction.fx[fxIndex] = null; instruction.fx = instruction.fx.slice(); } else { instruction[property] = null; } updateInstruction(instruction); }; let togglePlayback = function() { if(app.editorState.playbackState == 'paused') { app.vue.changePlaybackState(app.editorState.playbackStateOnLastPause || 'playSong'); } else { app.vue.changePlaybackState('paused'); } event.preventDefault(); }; let keyHandlerMap = { 'Backspace': eraseValue, 'Delete': eraseValue, ' ': togglePlayback, }; let filterHexDigitKey = function(event) { if(event.key.match(/^[0-9A-Fa-f]$/)) return parseInt(event.key, 16); else return false; }; let applyAutoInstrument = function(instruction,channel) { if(!app.editorState.autoInstrument) return; let index = app.projectState.instruments.indexOf((app.editorState.respectMIDIInstruments && channel) ? channel.instrument : app.editorState.activeInstrument); if(index >= 0) instruction.instrument = index; } let autoAdvance = function() { if(app.editorState.autoAdvance && app.editorState.playbackState == 'paused') { app.editorState.activeRowIndex = (app.editorState.activeRowIndex + 1) % app.projectState.songs[app.editorState.activeSongIndex].rows; if(app.editorState.autoAdvanceOrder && app.editorState.activeRowIndex == 0) { app.editorState.activeOrderIndex = (app.editorState.activeOrderIndex + 1) % app.projectState.songs[app.editorState.activeSongIndex].orders.length; } } } let noteLetterMap = {C:0, D:2, E:4, F:5, G:7, A:9, B:11}; let octaveDigitMap = {Z:0, 0:12, 1:24, 2:36, 3:48, 4:60, 5:72, 6:84, 7:96, 8:108}; // this is the highest note whose frequency can actually be inputted into the ET209 let maximum_voice_note = 114; let instruction_has_note_on = function(instruction) { return instruction.note !== null && instruction.note !== 'cut' && instruction.note !== 'off'; } // filters return true if they fully handled the keypress let keyFilterMap = { 'note':function(event){ if(channels[app.editorState.activeChannelIndex].isNoise) { let digit = filterHexDigitKey(event); if(digit !== false) { let instruction = getInstruction(); if(instruction_has_note_on(instruction)) { instruction.note = ((instruction.note << 4) | digit) & 255; } else { instruction.note = digit; } applyAutoInstrument(instruction); updateInstruction(instruction); return true; } else if(event.key == ".") { let instruction = getInstruction(); applyAutoInstrument(instruction); let instrument; if(instruction.instrument != null) { instrument = app.projectState.instruments[instruction.instrument]; } else { instrument = app.editorState.activeInstrument; } if(instrument != null && instrument.autoperiod) { instruction.note = instrument.autoperiod; updateInstruction(instruction); return true; } } } else { let uppercase = event.key.toUpperCase(); if(uppercase in noteLetterMap) { let instruction = getInstruction(); if(!instruction_has_note_on(instruction)) { instruction.note = 60; } applyAutoInstrument(instruction); instruction.note = (instruction.note - instruction.note % 12) + noteLetterMap[uppercase]; if(instruction.note > maximum_voice_note) { instruction.note = maximum_voice_note; } updateInstruction(instruction); return true; } else if(uppercase in octaveDigitMap) { let instruction = getInstruction(); if(!instruction_has_note_on(instruction)) { instruction.note = 60; } applyAutoInstrument(instruction); instruction.note = octaveDigitMap[uppercase] + instruction.note % 12; if(instruction.note > maximum_voice_note) { instruction.note = maximum_voice_note; } updateInstruction(instruction); autoAdvance(); return true; } else if(event.key == "#") { let instruction = getInstruction(); if(!instruction_has_note_on(instruction)) { instruction.note = 60; } applyAutoInstrument(instruction); ++instruction.note; if(instruction.note > maximum_voice_note) { instruction.note = maximum_voice_note; } updateInstruction(instruction); return true; } } if(event.key == "x" || event.key == "X") { let instruction = getInstruction(); instruction.note = 'off'; updateInstruction(instruction); return true; } else if(event.key == "\\") { let instruction = getInstruction(); instruction.note = 'cut'; updateInstruction(instruction); return true; } }, 'instrument_high':function(event){ let digit = filterHexDigitKey(event); if(digit !== false) { let instruction = getInstruction(); if(instruction.instrument === null) { instruction.instrument = digit << 4; } else { instruction.instrument = (instruction.instrument & 0xF) | (digit << 4); } updateInstruction(instruction); return true; } }, 'instrument_low':function(event){ let digit = filterHexDigitKey(event); if(digit !== false) { let instruction = getInstruction(); if(instruction.instrument === null) { instruction.instrument = digit; } else { instruction.instrument = (instruction.instrument & 0xF0) | digit; } updateInstruction(instruction); return true; } }, 'volume':function(event){ let digit = filterHexDigitKey(event); if(digit !== false) { let instruction = getInstruction(); instruction.volume = digit; updateInstruction(instruction); return true; } }, }; for(let n = 0; n < 3; ++n) { let effectIndex = n; keyFilterMap["fx"+n+"_type"] = function(event){ let uppercase = event.key.toUpperCase(); if(letter_to_effect_name[uppercase]) { let instruction = getInstruction(); if(instruction.fx == null) { instruction.fx = []; } while(instruction.fx.length < effectIndex) { instruction.fx.push(null); } if(instruction.fx[effectIndex] == undefined) { instruction.fx[effectIndex] = {value:0}; } instruction.fx[effectIndex].type = letter_to_effect_name[uppercase]; updateInstruction(instruction); return true; } }; keyFilterMap["fx"+n+"_high"] = function(event){ let digit = filterHexDigitKey(event); if(digit !== false) { let instruction = getInstruction(); if(instruction.fx == null || instruction.fx[effectIndex] == undefined) { return false; } instruction.fx[effectIndex].value = (instruction.fx[effectIndex].value & 0xF) | (digit << 4) updateInstruction(instruction); return true; } }; keyFilterMap["fx"+n+"_low"] = function(event){ let digit = filterHexDigitKey(event); if(digit !== false) { let instruction = getInstruction(); if(instruction.fx == null || instruction.fx[effectIndex] == undefined) { return false; } instruction.fx[effectIndex].value = (instruction.fx[effectIndex].value & 0xF0) | digit; updateInstruction(instruction); return true; } }; } let recordNoteOn = function(noteValue, velocity, channel) { let instruction = getInstruction(channel); applyAutoInstrument(instruction, channels[channel]); instruction.note = noteValue; if(instruction.note > maximum_voice_note) { instruction.note = maximum_voice_note; } if(app.editorState.respectMIDIVelocities) { instruction.volume = (velocity+7)>>3; } updateInstruction(instruction, channel); if(!app.editorState.respectMIDIClocks) { autoAdvance(); } }; let recordNoteOff = function(channel) { if(app.editorState.noteOffMode == 'ignored') return; let instruction = getInstruction(channel); instruction.instrument = null; instruction.note = app.editorState.noteOffMode; updateInstruction(instruction, channel); if(!app.editorState.respectMIDIClocks) autoAdvance(); }; let recordInstrument = function(instrument, channel) { let instruction = getInstruction(channel); instruction.instrument = instrument; updateInstruction(instruction, channel); }; let recordAdvance = function() { autoAdvance(); }; Vue.component( 'pattern-editor', { props: { channels: Array, editorState: Object, activeOrder: Array, patterns: Array, rowCount: Number }, computed: { tableRows: function () { let rows = []; let rowCount = this.rowCount; let patterns = this.patterns; let activeOrder = this.activeOrder; activeOrder.forEach(function (channelOrderIndex, channelIndex) { while(channelOrderIndex >= patterns[channelIndex].length){ patterns[channelIndex].push([]); } let patternRows = patterns[channelIndex][channelOrderIndex]; for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) { let instruction = patternRows[rowIndex]; if(instruction == undefined) { instruction = hydration.newEmptyInstruction(); patternRows.push(instruction); } if(!rows[rowIndex]){ rows[rowIndex] = []; } rows[rowIndex][channelIndex] = instruction; } }); return rows; } }, data: function(){ return { noteOffModes: { 'off': 'Note Off→Off', 'cut': 'Note Off→Cut', 'ignored': 'Note Off Ignored' }, sppModes: { 'ignored': 'Ignore SPP', 'pattern': 'Pattern SPP', 'song': 'Song SPP', }, }; }, methods: { formatByte: formatByte, toggleChannel: function (channelIndex) { let polyphonyChannels = this.editorState.polyphonyChannels; let alreadyThere = polyphonyChannels.indexOf(channelIndex) !== -1; if(alreadyThere){ arrayRemove(polyphonyChannels, channelIndex); } else { polyphonyChannels.push(channelIndex); } }, setActive: function (rowIndex, channelIndex, property) { this.editorState.activeRowIndex = rowIndex; this.editorState.activeChannelIndex = channelIndex; this.editorState.activeProperty = property; }, moveUp: function(e){this.moveCursorRelative(e, 0, -1);}, moveDown: function(e){this.moveCursorRelative(e, 0, 1);}, moveLeft: function(e){this.moveCursorRelative(e, -1, 0);}, moveRight: function(e){this.moveCursorRelative(e, 1, 0);}, moveCursorRelative: function (keydownEvent, x, y) { keydownEvent.stopPropagation(); keydownEvent.stopImmediatePropagation(); keydownEvent.preventDefault(); let currentPropertyIndex = instructionProperties.indexOf(this.editorState.activeProperty); let propertyBeforeWrap = currentPropertyIndex + x; let channelWrapDirection = propertyBeforeWrap > instructionProperties.length -1 ? 1 : propertyBeforeWrap < 0 ? -1 : 0; let channelWrapped = this.wrapRange(this.editorState.activeChannelIndex + channelWrapDirection, channels.length); let propertyIndex = this.wrapRange(propertyBeforeWrap, instructionProperties.length); let propertyName = instructionProperties[propertyIndex]; let rowWrapped = this.wrapRange(this.editorState.activeRowIndex + y, this.rowCount); this.setActive( rowWrapped, channelWrapped, propertyName ); }, input: function (keydownEvent) { let filter = keyFilterMap[app.editorState.activeProperty]; if(filter && filter(keydownEvent)) { // The filter handled the event keydownEvent.preventDefault(); return; } let handler = keyHandlerMap[keydownEvent.key]; if(handler){ keydownEvent.preventDefault(); handler(keydownEvent); } }, wrapRange: function(n, max){ return (n + max) % max; }, changeNoteOffMode: function(newMode) { app.editorState.noteOffMode = newMode; }, changeSPPMode: function(newMode) { app.editorState.sppMode = newMode; } }, template: ` <div class="pattern-editor" tabindex="0" @keydown.capture.up="moveUp" @keydown.capture.down="moveDown" @keydown.capture.left="moveLeft" @keydown.capture.right="moveRight" @keydown="input" > <editor-state-styling :editorState="editorState" /> <ul class="tab-list"> <prop-checkbox :source="editorState" prop="autoAdvance" name="Auto Advance Row" /> <prop-checkbox :source="editorState" prop="autoAdvanceOrder" name="Auto Advance Order" /> <prop-checkbox :source="editorState" prop="autoInstrument" name="Auto-Instrument" /> </ul> <ul class="tab-list"> <prop-checkbox :source="editorState" prop="recordMIDI" name="Record MIDI" /> <prop-checkbox :source="editorState" prop="respectMIDIClocks" name="MIDI Clock" /> <prop-checkbox :source="editorState" prop="respectMIDIVelocities" name="MIDI Velocity" /> <prop-checkbox :source="editorState" prop="respectMIDIInstruments" name="MIDI Instrument" /> <prop-checkbox :source="editorState" prop="respectMIDIChannels" name="MIDI Channel" /> <prop-checkbox :source="editorState" prop="enablePolyphony" name="MIDI Auto-Polyphony" /> </ul> <ul class="tab-list"> <li class="noSelect buttons"> <button v-for="(symbol, name) in noteOffModes" @click="changeNoteOffMode(name)" :title="editorState.noteOffMode" :class="{active: name === editorState.noteOffMode}" > <span v-html="symbol"></span> </button> </li> <li class="noSelect buttons"> <button v-for="(symbol, name) in sppModes" @click="changeSPPMode(name)" :title="editorState.sppMode" :class="{active: name === editorState.sppMode}" > <span v-html="symbol"></span> </button> </li> </ul> <table> <thead> <th></th> <th class="channel" v-for="(item, index) in channels" > <channel :channel="item" :index="index" :toggleChannel="toggleChannel" /> </th> </thead> <tbody> <tr v-for="(row, rowIndex) in tableRows" :class="'perow_'+rowIndex" > <th>row {{formatByte(rowIndex)}}</th> <td v-for="(instruction, channelIndex) in row" :name="'channel'+channelIndex" > <instruction-editor :isNoise="channels[channelIndex].isNoise" :instruction="instruction" :cellName="'pecell_'+rowIndex+'_'+channelIndex+'_'" :setActive="function(property){setActive(rowIndex, channelIndex, property)}" /> </td> </tr> </tbody> </table> </div> ` } ); Vue.component( 'channel', { props: { channel: Channel, index: Number, toggleChannel: Function }, template: ` <button :class="{active: !channel.isMuted}" @click="channel.isMuted = !channel.isMuted"> <span class="checkbox"></span> <span>{{channel.isNoise ? 'Noise' : ('Voice ' + (index+1))}}</span> </button> ` } ); Vue.component( 'prop-checkbox', { props: { source: Object, prop: String, name: String }, template: ` <li class="noSelect buttons"> <button @click="source[prop] = !source[prop]" :class="{active: source[prop]}" > <span class="checkbox"></span> {{name}} </button> </li> ` } ); Vue.component( 'editor-state-styling', { props: { editorState: Object }, computed: { activeStyling: function(){ let editorState = this.editorState; return ` <style> tr.perow_${editorState.activeRowIndex}{ background-color: #226; } span.pecell_${editorState.activeRowIndex}_${editorState.activeChannelIndex}_${editorState.activeProperty}{ background-color: #264; } </style> `; } }, template: ` <div class="editor-state-styling" v-html="activeStyling"></div> ` } );
AdmiralPotato/ars-tracker
js/vue-channel.js
JavaScript
gpl-3.0
17,521
package se.nordicehealth.servlet.impl.request.user; import java.util.Map; import java.util.Map.Entry; import se.nordicehealth.common.impl.Packet; import se.nordicehealth.servlet.core.PPCDatabase; import se.nordicehealth.servlet.core.PPCLogger; import se.nordicehealth.servlet.impl.QuestionData; import se.nordicehealth.servlet.impl.io.IPacketData; import se.nordicehealth.servlet.impl.io.ListData; import se.nordicehealth.servlet.impl.io.MapData; import se.nordicehealth.servlet.impl.request.RequestProcesser; public class LoadQuestions extends RequestProcesser { private PPCDatabase db; public LoadQuestions(IPacketData packetData, PPCLogger logger, PPCDatabase db) { super(packetData, logger); this.db = db; } public MapData processRequest(MapData in) { MapData out = packetData.getMapData(); out.put(Packet.TYPE, Packet.LOAD_Q); MapData data = packetData.getMapData(); String result = packetData.getMapData().toString(); try { result = retrieveQuestions().toString(); } catch (Exception e) { } data.put(Packet.QUESTIONS, result); out.put(Packet.DATA, data.toString()); return out; } private MapData retrieveQuestions() throws Exception { Map<Integer, QuestionData> questions = db.loadQuestions(); MapData _questions = packetData.getMapData(); for (Entry<Integer, QuestionData> _e : questions.entrySet()) { QuestionData _q = _e.getValue(); MapData _question = packetData.getMapData(); ListData options = packetData.getListData(); for (String str : _q.options) { options.add(str); } _question.put(Packet.OPTIONS, options.toString()); _question.put(Packet.TYPE, _q.type); _question.put(Packet.ID, Integer.toString(_q.id)); _question.put(Packet.QUESTION, _q.question); _question.put(Packet.DESCRIPTION, _q.description); _question.put(Packet.OPTIONAL, _q.optional ? Packet.YES : Packet.NO); _question.put(Packet.MAX_VAL, Integer.toString(_q.max_val)); _question.put(Packet.MIN_VAL, Integer.toString(_q.min_val)); _questions.put(_e.getKey(), _question.toString()); } return _questions; } }
NIASC/PROM_PREM_Collector
src/main/java/se/nordicehealth/servlet/impl/request/user/LoadQuestions.java
Java
gpl-3.0
2,088
/* This file is part of Clementine. Copyright 2010, David Sansome <me@davidsansome.com> Clementine 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. Clementine 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 Clementine. If not, see <http://www.gnu.org/licenses/>. */ #include "screensaver.h" #include <QtGlobal> #include "config.h" #ifdef HAVE_DBUS #include <QDBusConnection> #include <QDBusConnectionInterface> #include "dbusscreensaver.h" #endif #ifdef Q_OS_DARWIN #include "macscreensaver.h" #endif #ifdef Q_OS_WIN32 #include "windowsscreensaver.h" #endif #include <QtDebug> const char* Screensaver::kGnomeService = "org.gnome.ScreenSaver"; const char* Screensaver::kGnomePath = "/"; const char* Screensaver::kGnomeInterface = "org.gnome.ScreenSaver"; const char* Screensaver::kKdeService = "org.kde.ScreenSaver"; const char* Screensaver::kKdePath = "/ScreenSaver/"; const char* Screensaver::kKdeInterface = "org.freedesktop.ScreenSaver"; Screensaver* Screensaver::screensaver_ = 0; Screensaver* Screensaver::GetScreensaver() { if (!screensaver_) { #if defined(HAVE_DBUS) if (QDBusConnection::sessionBus().interface()->isServiceRegistered( kGnomeService)) { screensaver_ = new DBusScreensaver(kGnomeService, kGnomePath, kGnomeInterface); } else if (QDBusConnection::sessionBus().interface()->isServiceRegistered( kKdeService)) { screensaver_ = new DBusScreensaver(kKdeService, kKdePath, kKdeInterface); } #elif defined(Q_OS_DARWIN) screensaver_ = new MacScreensaver(); #elif defined(Q_OS_WIN32) screensaver_ = new WindowsScreensaver(); #endif } return screensaver_; }
clementine-player/Clementine
src/ui/screensaver.cpp
C++
gpl-3.0
2,125
#include <iostream> #include <stdexcept> #include "game.h" int main() { try { Game game; game.run(); } catch (std::exception& e) { std::cout << "\nEXCEPTION: " << e.what() <<std::endl; } }
maltouzes/shadowland-rpg
main.cpp
C++
gpl-3.0
238
package org.wilson.telegram; public class BotConfig { public static final String TOKENNEWBOT = "99536655:AAG_uycvQeXgm-1Cdpk-zvBRUu2w_nz5p1Y"; public static final String USERNAMENEWBOT = "newbot"; public static final String CONSUMERKEY = "jb5Y4AYcwMgrTMCpBWC8JQ"; public static final String CONSUMERSECRET = "Gt8Yb4yXUIDo5nZh15ZIzOgmKBQ"; public static final String YELPTOKEN = "MLHPqPG7-pWg4VjmXTK-fDnAcb9lP5rt"; public static final String YELPTOKENSECRET = "yM4OG1_fewCqwmLyAszme59asx4"; public static final String SENDMESSAGEMARKDOWN = "HTML"; }
Snickersnack/TelegramBotAPI
src/org/wilson/telegram/BotConfig.java
Java
gpl-3.0
585
/* SoftTH, Software multihead solution for Direct3D Copyright (C) 2005-2012 Keijo Ruotsalainen, www.kegetys.fi 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 "d3dbuffer.h" #include "main.h" // These GUIDs are used to detect new interfaces to override back to originals to pass to D3D #include <INITGUID.H> DEFINE_GUID(IID_IDirect3DIndexBuffer9Managed, 0x7c9dd65e, 0xd3f7, 0x4529, 0xac, 0xee, 0x78, 0x58, 0xaa, 0xbb, 0xcc, 0xdd); DEFINE_GUID(IID_IDirect3DVertexBuffer9Quirk, 0x7c9dd65e, 0xd3f7, 0x4529, 0xac, 0xfe, 0x12, 0x34, 0xaa, 0xbb, 0xcc, 0xdd); DEFINE_GUID(IID_IDirect3DVertexBuffer9Managed, 0x7c9dd65e, 0xd3f7, 0x4529, 0xac, 0x00, 0xff, 0x23, 0xaa, 0xbb, 0xcc, 0xdd); #ifdef USE_DISCARD_FLAG #define FLOCKFLAGS D3DLOCK_DISCARD #else #ifdef RECREATE_ON_REUSE #define FLOCKFLAGS NULL #else #define FLOCKFLAGS D3DLOCK_NOOVERWRITE #endif #endif static const int recreateThreshold = 3; IDirect3DIndexBuffer9Managed::IDirect3DIndexBuffer9Managed(IDirect3DDevice9Ex* device, IDirect3DDevice9New* wantDevFake, UINT wantLength, DWORD wantUsage,D3DFORMAT wantFormat,D3DPOOL Pool,HANDLE* pSharedHandle) { ONCE dbg("Using Index buffer manage-emulation"); dbgf("IDirect3DIndexBuffer9Managed 0x%08X: %d bytes, %s %s %s share: 0x%08X", this, Length, getUsage(Usage), getMode(Format), getPool(Pool), pSharedHandle); bufSys = NULL; buf = NULL; #ifdef LATE_IB_UPDATE fullDirty = false; #endif lockSections.reserve(8); // Reserve a bit of space lastRecreate = 0; Length = wantLength; Usage = wantUsage; Format = wantFormat; devFake = wantDevFake; if(Pool != D3DPOOL_MANAGED) { dbg("IDirect3DIndexBuffer9Managed: Non-managed manage-emulation??"); exit(0); } Pool = D3DPOOL_DEFAULT; if(Usage & D3DUSAGE_DYNAMIC) Usage -= D3DUSAGE_DYNAMIC; Usage |= D3DUSAGE_WRITEONLY; /* Usage |= D3DUSAGE_DYNAMIC; */ dev = device; if(dev->CreateIndexBuffer(Length, Usage, Format, Pool, &buf, pSharedHandle) != D3D_OK) { dbg("IDirect3DIndexBuffer9Managed: CreateIndexBuffer failed!"); return; } bufSize = Length; bufSys = new BYTE[bufSize+BUF_EXTRA_BYTES]; ZeroMemory(bufSys, bufSize+BUF_EXTRA_BYTES); } bool IDirect3DIndexBuffer9Managed::ReCreate() { bool didRecreate = false; if(!buf) return didRecreate; if(devFake->getFrameNumber() - lastRecreate < recreateThreshold) { dbgf("IDirect3DIndexBuffer9Managed 0x%08X - Recreate at frame %d", this, devFake->getFrameNumber()); int r = buf->Release(); if(r!=0) { dbg("IDirect3DIndexBuffer9Managed::ReCreate() Warning: %d refs on old buffer, forcing release", r); while(buf->Release()) {}; } didRecreate = true; D3DCALL( dev->CreateIndexBuffer(Length, Usage, Format, D3DPOOL_DEFAULT, &buf, NULL) ); } lastRecreate = devFake->getFrameNumber(); return didRecreate; } HRESULT IDirect3DIndexBuffer9Managed::Lock(UINT OffsetToLock,UINT SizeToLock,void** ppbData,DWORD Flags) { dbgf("IDirect3DIndexBuffer9Managed 0x%08X: lock: off %d, %d bytes, %s", this, OffsetToLock, SizeToLock, getLock(Flags)); if(OffsetToLock+SizeToLock > bufSize) dbg("WARNING: Application attempted to lock too large indexbuffer (%d > %d)", OffsetToLock+SizeToLock, bufSize); if(!bufSys || !buf) return D3DERR_INVALIDCALL; // Return handle to system memory buffer *ppbData = bufSys+OffsetToLock; #ifdef RECREATE_ON_REUSE if(!fullDirty && lockSections.size() == 0) { // First lock if(ReCreate()) { fullDirty = true; } } #endif #ifndef LATE_IB_UPDATE LOCKSECTION l; l.lockOffset = OffsetToLock; l.lockSize = SizeToLock; lockSections.push_back(l); #else if((OffsetToLock == 0 && SizeToLock == 0) || (OffsetToLock == 0 && SizeToLock == bufSize)) { // Whole IB locked fullDirty = true; } else { LOCKSECTION l; // Dirty sections l.lockOffset = OffsetToLock; l.lockSize = SizeToLock; lockSections.push_back(l); } #endif return D3D_OK; } HRESULT IDirect3DIndexBuffer9Managed::Unlock() { dbgf("IDirect3DIndexBuffer9Managed 0x%08X: Unlock", this); if(!bufSys || !buf) return D3DERR_INVALIDCALL; /* DWORD lockOffset = lockSections[lockSections.size()-1].lockOffset; DWORD lockSize = lockSections[lockSections.size()-1].lockSize; // Copy sysmem to vidmem void *vb; if(buf->Lock(lockOffset, lockSize, &vb, D3DLOCK_NOOVERWRITE|D3DLOCK_DONOTWAIT) != D3D_OK) { dbg("IDirect3DVertexBuffer9Managed: Unlock: FAILED!"); return D3D_OK; } memcpy(vb, bufSys+lockOffset, lockSize?lockSize:bufSize); buf->Unlock(); lockSections.pop_back(); */ #ifndef LATE_IB_UPDATE /*DWORD flags = D3DLOCK_DISCARD; // Crashes A10-C if(config.main.debugD3D) { flags = NULL; // Debug D3D doesn't like discard here } */ DWORD flags = NULL; if(lockSections.size() == 0) { dbg("WARNING: Indexbuffer unlock without lock??"); return D3DERR_INVALIDCALL; } DWORD lockOffset = lockSections[lockSections.size()-1].lockOffset; DWORD lockSize = lockSections[lockSections.size()-1].lockSize; // Copy locked buffer to video memory void *ib; if(buf->Lock(lockOffset, lockSize, &ib, flags) != D3D_OK) { dbg("IDirect3DIndexBuffer9Managed: Unlock: Lock failed!"); return D3DERR_INVALIDCALL; } memcpy(ib, bufSys+lockOffset, lockSize?lockSize:bufSize); buf->Unlock(); lockSections.pop_back(); #endif return D3D_OK; } #ifdef LATE_IB_UPDATE IDirect3DIndexBuffer9* IDirect3DIndexBuffer9Managed::GetRealBuffer() { dbgf("IDirect3DIndexBuffer9Managed 0x%08X: GetRealBuffer", this); if(lockSections.size() || fullDirty) { #ifdef ALWAYS_FULL_UPDATE fullDirty = true; #endif //dbg("IDirect3DIndexBuffer9Managed 0x%08X: UPDATE"); if(!fullDirty) { // Partial lock for(int i=0;i<lockSections.size();i++) { DWORD lockOffset = lockSections[i].lockOffset; DWORD lockSize = lockSections[i].lockSize; #ifdef RECREATE_ON_REUSE const DWORD flags = NULL; //const DWORD flags = D3DLOCK_NOOVERWRITE; #else // Improves performance - but isn't safe and not allowed by D3D spec const DWORD flags = D3DLOCK_NOOVERWRITE; #endif // Copy sysmem to vidmem void *vb; if(buf->Lock(lockOffset, lockSize, &vb, flags) != D3D_OK) { dbg("IDirect3DIndexBuffer9Managed: Unlock: Lock failed!"); return buf; } memcpy(vb, bufSys+lockOffset, lockSize?lockSize:bufSize); buf->Unlock(); } } else { // Full buffer lock // Copy sysmem to vidmem void *vb; if(buf->Lock(0, 0, &vb, FLOCKFLAGS) != D3D_OK) { dbg("IDirect3DVertexBuffer9Managed: Unlock: Lock failed!"); return buf; } memcpy(vb, bufSys, bufSize); buf->Unlock(); } lockSections.clear(); fullDirty = false; } return buf; } #endif // Managed VB emulation IDirect3DVertexBuffer9Managed::IDirect3DVertexBuffer9Managed(IDirect3DDevice9Ex* wantDev, IDirect3DDevice9New* wantDevFake, UINT wantLength, DWORD wantUsage, DWORD wantFVF, D3DPOOL Pool, HANDLE* pSharedHandle) { ONCE dbg("Using Vertex buffer manage-emulation"); dev = wantDev; devFake = wantDevFake; bufSys = NULL; buf = NULL; HRESULT ret; fullDirty = false; locks = 0; Length = wantLength; Usage = wantUsage; FVF = wantFVF; lockSections.reserve(8); // Reserve a bit of space if(Pool != D3DPOOL_MANAGED) { dbg("IDirect3DIndexBuffer9Managed: Non-managed manage-emulation??"); exit(0); } Pool = D3DPOOL_DEFAULT; if(Usage & D3DUSAGE_DYNAMIC) Usage -= D3DUSAGE_DYNAMIC; Usage |= D3DUSAGE_WRITEONLY; ret = dev->CreateVertexBuffer(Length, Usage, FVF, Pool, &buf, pSharedHandle); if(ret != D3D_OK) { result = ret; dbg("WARNING: IDirect3DVertexBuffer9Managed: CreateVertexBuffer D3DPOOL_DEFAULT failed!"); return; } bufSize = Length; bufSys = new BYTE[bufSize+BUF_EXTRA_BYTES]; ZeroMemory(bufSys, bufSize+BUF_EXTRA_BYTES); result = D3D_OK; } bool IDirect3DVertexBuffer9Managed::ReCreate() { bool didRecreate = false; if(!buf) return didRecreate; if(devFake->getFrameNumber() - lastRecreate < recreateThreshold) { dbg("IDirect3DVertexBuffer9Managed 0x%08X - Recreate at frame %d (last recreate %d)", this, devFake->getFrameNumber(), lastRecreate); int r = buf->Release(); if(r!=0) { dbg("IDirect3DVertexBuffer9Managed::ReCreate() Warning: %d refs on old buffer, forcing release", r); while(buf->Release()) {}; } didRecreate = true; D3DCALL( dev->CreateVertexBuffer(Length, Usage, FVF, D3DPOOL_DEFAULT, &buf, NULL) ); } else dbg("IDirect3DVertexBuffer9Managed 0x%08X - NO recreate at frame %d (last recreate %d)", this, devFake->getFrameNumber(), lastRecreate); lastRecreate = devFake->getFrameNumber(); return didRecreate; } HRESULT IDirect3DVertexBuffer9Managed::Lock(UINT OffsetToLock,UINT SizeToLock,void** ppbData,DWORD Flags) { dbgf("IDirect3DVertexBuffer9Managed 0x%08X: lock: off %d, %d bytes, %s", this, OffsetToLock, SizeToLock, getLock(Flags)); if(OffsetToLock+SizeToLock > bufSize) dbg("WARNING: Application attempted to lock too large vertexbuffer (%d > %d)", OffsetToLock+SizeToLock, bufSize); if(!bufSys || !buf) return D3DERR_INVALIDCALL; // Return handle to system memory buffer *ppbData = bufSys+OffsetToLock; #ifdef RECREATE_ON_REUSE if(!fullDirty && lockSections.size() == 0) { // First lock if(ReCreate()) { fullDirty = true; } //fullDirty = true; } #endif if((OffsetToLock == 0 && SizeToLock == 0) || (OffsetToLock == 0 && SizeToLock == bufSize)) { // Whole VB locked fullDirty = true; } else { LOCKSECTION l; // Dirty sections l.lockOffset = OffsetToLock; l.lockSize = SizeToLock; lockSections.push_back(l); } locks++; return D3D_OK; } HRESULT IDirect3DVertexBuffer9Managed::Unlock() { dbgf("IDirect3DVertexBuffer9Managed 0x%08X: Unlock", this); if(!bufSys || !buf) return D3DERR_INVALIDCALL; locks--; /* DWORD lockOffset = lockSections[lockSections.size()-1].lockOffset; DWORD lockSize = lockSections[lockSections.size()-1].lockSize; // Copy sysmem to vidmem void *vb; if(buf->Lock(lockOffset, lockSize, &vb, D3DLOCK_NOOVERWRITE|D3DLOCK_DONOTWAIT) != D3D_OK) { dbg("IDirect3DVertexBuffer9Managed: Unlock: FAILED!"); return D3D_OK; } memcpy(vb, bufSys+lockOffset, lockSize?lockSize:bufSize); buf->Unlock(); lockSections.pop_back(); */ /* DWORD flags = D3DLOCK_NOOVERWRITE; if(lockSections.size() == 0) { dbg("WARNING: Vertexbuffer unlock without lock??"); return D3DERR_INVALIDCALL; } DWORD lockOffset = lockSections[lockSections.size()-1].lockOffset; DWORD lockSize = lockSections[lockSections.size()-1].lockSize; // Copy locked buffer to video memory void *ib; if(buf->Lock(lockOffset, lockSize, &ib, flags) != D3D_OK) { dbg("IDirect3DVertexBuffer9Managed: Unlock: Lock failed!"); return D3DERR_INVALIDCALL; } memcpy(ib, bufSys+lockOffset, lockSize?lockSize:bufSize); buf->Unlock(); lockSections.pop_back(); */ return D3D_OK; } IDirect3DVertexBuffer9* IDirect3DVertexBuffer9Managed::GetRealBuffer() { dbgf("IDirect3DVertexBuffer9Managed 0x%08X: GetRealBuffer", this); if(locks) dbg("WARNING: IDirect3DVertexBuffer9Managed 0x%08X: GetRealBuffer() with %d active locks", locks); if(lockSections.size() || fullDirty) { #ifdef ALWAYS_FULL_UPDATE fullDirty = true; #endif //dbg("IDirect3DVertexBuffer9Managed 0x%08X: UPDATE"); if(!fullDirty) { // Partial buffer lock for(int i=0;i<lockSections.size();i++) { DWORD lockOffset = lockSections[i].lockOffset; DWORD lockSize = lockSections[i].lockSize; #ifdef RECREATE_ON_REUSE const DWORD flags = NULL; #else // Improves performance - but isn't safe and not allowed by D3D spec const DWORD flags = D3DLOCK_NOOVERWRITE; #endif // Copy sysmem to vidmem void *vb; if(buf->Lock(lockOffset, lockSize, &vb, flags) != D3D_OK) { dbg("IDirect3DVertexBuffer9Managed: Unlock: Lock failed!"); return buf; } memcpy(vb, bufSys+lockOffset, lockSize?lockSize:bufSize); buf->Unlock(); } } else { // Full buffer lock // Copy sysmem to vidmem void *vb; if(buf->Lock(0, 0, &vb, FLOCKFLAGS/*|D3DLOCK_NOOVERWRITE*/) != D3D_OK) { dbg("IDirect3DVertexBuffer9Managed: Unlock: Lock failed!"); return buf; } memcpy(vb, bufSys, bufSize); buf->Unlock(); } lockSections.clear(); fullDirty = false; } return buf; }
born2beflyin/SoftTH
src/d3dbuffer.cpp
C++
gpl-3.0
13,308
function getURLVar(key) { var value = []; var query = String(document.location).split('?'); if (query[1]) { var part = query[1].split('&'); for (i = 0; i < part.length; i++) { var data = part[i].split('='); if (data[0] && data[1]) { value[data[0]] = data[1]; } } if (value[key]) { return value[key]; } else { return ''; } } } $(document).ready(function() { // Highlight any found errors $('.text-danger').each(function() { var element = $(this).parent().parent(); if (element.hasClass('form-group')) { element.addClass('has-error'); } }); // Currency $('#form-currency .currency-select').on('click', function(e) { e.preventDefault(); $('#form-currency input[name=\'code\']').attr('value', $(this).attr('name')); $('#form-currency').submit(); }); // Language $('#form-language .language-select').on('click', function(e) { e.preventDefault(); $('#form-language input[name=\'code\']').attr('value', $(this).attr('name')); $('#form-language').submit(); }) /* Search */ $('#search input[name=\'search\']').parent().find('button').on('click', function() { var url = $('base').attr('href') + 'index.php?route=product/search'; var value = $('header input[name=\'search\']').val(); if (value) { url += '&search=' + encodeURIComponent(value); } location = url; }); $('#search input[name=\'search\']').on('keydown', function(e) { if (e.keyCode == 13) { $('header input[name=\'search\']').parent().find('button').trigger('click'); } }); // Menu $('#menu .dropdown-menu').each(function() { var menu = $('#menu').offset(); var dropdown = $(this).parent().offset(); var i = (dropdown.left + $(this).outerWidth()) - (menu.left + $('#menu').outerWidth()); if (i > 0) { $(this).css('margin-left', '-' + (i + 5) + 'px'); } }); // Product List $('#list-view').click(function() { $('#content .product-grid > .clearfix').remove(); $('#content .row > .product-grid').attr('class', 'product-layout product-list col-xs-12'); localStorage.setItem('display', 'list'); }); // Product Grid $('#grid-view').click(function() { // What a shame bootstrap does not take into account dynamically loaded columns var cols = $('#column-right, #column-left').length; if (cols == 2) { $('#content .product-list').attr('class', 'product-layout product-grid col-lg-6 col-md-6 col-sm-12 col-xs-12'); } else if (cols == 1) { $('#content .product-list').attr('class', 'product-layout product-grid col-lg-4 col-md-4 col-sm-6 col-xs-12'); } else { $('#content .product-list').attr('class', 'product-layout product-grid col-lg-3 col-md-3 col-sm-6 col-xs-12'); } localStorage.setItem('display', 'grid'); }); if (localStorage.getItem('display') == 'list') { $('#list-view').trigger('click'); } else { $('#grid-view').trigger('click'); } // Checkout $(document).on('keydown', '#collapse-checkout-option input[name=\'email\'], #collapse-checkout-option input[name=\'password\']', function(e) { if (e.keyCode == 13) { $('#collapse-checkout-option #button-login').trigger('click'); } }); // tooltips on hover $('[data-toggle=\'tooltip\']').tooltip({container: 'body'}); // Makes tooltips work on ajax generated content $(document).ajaxStop(function() { $('[data-toggle=\'tooltip\']').tooltip({container: 'body'}); }); }); // Cart add remove functions var cart = { 'add': function(product_id, quantity) { $.ajax({ url: 'index.php?route=checkout/cart/add', type: 'post', data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1), dataType: 'json', beforeSend: function() { $('#cart > button').button('loading'); }, complete: function() { $('#cart > button').button('reset'); }, success: function(json) { $('.alert, .text-danger').remove(); if (json['redirect']) { location = json['redirect']; } if (json['success']) { $('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>'); // Need to set timeout otherwise it wont update the total setTimeout(function () { $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>'); }, 100); //TODO 不要捲動到最上方 //$('html, body').animate({ scrollTop: 0 }, 'slow'); $('#cart > ul').load('index.php?route=common/cart/info ul li'); } }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }, 'update': function(key, quantity) { $.ajax({ url: 'index.php?route=checkout/cart/edit', type: 'post', data: 'key=' + key + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1), dataType: 'json', beforeSend: function() { $('#cart > button').button('loading'); }, complete: function() { $('#cart > button').button('reset'); }, success: function(json) { // Need to set timeout otherwise it wont update the total setTimeout(function () { $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>'); }, 100); if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') { location = 'index.php?route=checkout/cart'; } else { $('#cart > ul').load('index.php?route=common/cart/info ul li'); } }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }, 'remove': function(key) { $.ajax({ url: 'index.php?route=checkout/cart/remove', type: 'post', data: 'key=' + key, dataType: 'json', beforeSend: function() { $('#cart > button').button('loading'); }, complete: function() { $('#cart > button').button('reset'); }, success: function(json) { // Need to set timeout otherwise it wont update the total setTimeout(function () { $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>'); }, 100); if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') { location = 'index.php?route=checkout/cart'; } else { $('#cart > ul').load('index.php?route=common/cart/info ul li'); } }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }, 'addAll': function(orders, callback) { $.ajax({ url: 'index.php?route=checkout/cart/addAll', type: 'post', data: 'orders=' + orders, dataType: 'json', beforeSend: function() { $('#cart > button').button('loading'); }, complete: function() { $('#cart > button').button('reset'); }, success: function(json) { $('.alert, .text-danger').remove(); if (json['redirect']) { location = json['redirect']; } if (json['success']) { $('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>'); // Need to set timeout otherwise it wont update the total setTimeout(function () { $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>'); }, 100); //不要捲動到最上方 //$('html, body').animate({ scrollTop: 0 }, 'slow'); $('#cart > ul').load('index.php?route=common/cart/info ul li'); callback(true); } }, error: function(xhr, ajaxOptions, thrownError) { callback(false); alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }, 'removeAll': function(callback) { $.ajax({ url: 'index.php?route=checkout/cart/removeAll', type: 'post', data: '', dataType: 'json', beforeSend: function() { $('#cart > button').button('loading'); }, complete: function() { $('#cart > button').button('reset'); }, success: function(json) { // Need to set timeout otherwise it wont update the total setTimeout(function () { $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>'); }, 100); if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') { location = 'index.php?route=checkout/cart'; } else { $('#cart > ul').load('index.php?route=common/cart/info ul li'); } callback(true); }, error: function(xhr, ajaxOptions, thrownError) { callback(false); alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); } } var voucher = { 'add': function() { }, 'remove': function(key) { $.ajax({ url: 'index.php?route=checkout/cart/remove', type: 'post', data: 'key=' + key, dataType: 'json', beforeSend: function() { $('#cart > button').button('loading'); }, complete: function() { $('#cart > button').button('reset'); }, success: function(json) { // Need to set timeout otherwise it wont update the total setTimeout(function () { $('#cart > button').html('<span id="cart-total"><i class="fa fa-shopping-cart"></i> ' + json['total'] + '</span>'); }, 100); if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') { location = 'index.php?route=checkout/cart'; } else { $('#cart > ul').load('index.php?route=common/cart/info ul li'); } }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); } } var wishlist = { 'add': function(product_id) { $.ajax({ url: 'index.php?route=account/wishlist/add', type: 'post', data: 'product_id=' + product_id, dataType: 'json', success: function(json) { $('.alert').remove(); if (json['redirect']) { location = json['redirect']; } if (json['success']) { $('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>'); } $('#wishlist-total span').html(json['total']); $('#wishlist-total').attr('title', json['total']); $('html, body').animate({ scrollTop: 0 }, 'slow'); }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }, 'remove': function() { } } var compare = { 'add': function(product_id) { $.ajax({ url: 'index.php?route=product/compare/add', type: 'post', data: 'product_id=' + product_id, dataType: 'json', success: function(json) { $('.alert').remove(); if (json['success']) { $('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">&times;</button></div>'); $('#compare-total').html(json['total']); $('html, body').animate({ scrollTop: 0 }, 'slow'); } }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }, 'remove': function() { } } /* Agree to Terms */ $(document).delegate('.agree', 'click', function(e) { e.preventDefault(); $('#modal-agree').remove(); var element = this; $.ajax({ url: $(element).attr('href'), type: 'get', dataType: 'html', success: function(data) { html = '<div id="modal-agree" class="modal">'; html += ' <div class="modal-dialog">'; html += ' <div class="modal-content">'; html += ' <div class="modal-header">'; html += ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>'; html += ' <h4 class="modal-title">' + $(element).text() + '</h4>'; html += ' </div>'; html += ' <div class="modal-body">' + data + '</div>'; html += ' </div'; html += ' </div>'; html += '</div>'; $('body').append(html); $('#modal-agree').modal('show'); } }); }); // Autocomplete */ (function($) { $.fn.autocomplete = function(option) { return this.each(function() { this.timer = null; this.items = new Array(); $.extend(this, option); $(this).attr('autocomplete', 'off'); // Focus $(this).on('focus', function() { this.request(); }); // Blur $(this).on('blur', function() { setTimeout(function(object) { object.hide(); }, 200, this); }); // Keydown $(this).on('keydown', function(event) { switch(event.keyCode) { case 27: // escape this.hide(); break; default: this.request(); break; } }); // Click this.click = function(event) { event.preventDefault(); value = $(event.target).parent().attr('data-value'); if (value && this.items[value]) { this.select(this.items[value]); } } // Show this.show = function() { var pos = $(this).position(); $(this).siblings('ul.dropdown-menu').css({ top: pos.top + $(this).outerHeight(), left: pos.left }); $(this).siblings('ul.dropdown-menu').show(); } // Hide this.hide = function() { $(this).siblings('ul.dropdown-menu').hide(); } // Request this.request = function() { clearTimeout(this.timer); this.timer = setTimeout(function(object) { object.source($(object).val(), $.proxy(object.response, object)); }, 200, this); } // Response this.response = function(json) { html = ''; if (json.length) { for (i = 0; i < json.length; i++) { this.items[json[i]['value']] = json[i]; } for (i = 0; i < json.length; i++) { if (!json[i]['category']) { html += '<li data-value="' + json[i]['value'] + '"><a href="#">' + json[i]['label'] + '</a></li>'; } } // Get all the ones with a categories var category = new Array(); for (i = 0; i < json.length; i++) { if (json[i]['category']) { if (!category[json[i]['category']]) { category[json[i]['category']] = new Array(); category[json[i]['category']]['name'] = json[i]['category']; category[json[i]['category']]['item'] = new Array(); } category[json[i]['category']]['item'].push(json[i]); } } for (i in category) { html += '<li class="dropdown-header">' + category[i]['name'] + '</li>'; for (j = 0; j < category[i]['item'].length; j++) { html += '<li data-value="' + category[i]['item'][j]['value'] + '"><a href="#">&nbsp;&nbsp;&nbsp;' + category[i]['item'][j]['label'] + '</a></li>'; } } } if (html) { this.show(); } else { this.hide(); } $(this).siblings('ul.dropdown-menu').html(html); } $(this).after('<ul class="dropdown-menu"></ul>'); $(this).siblings('ul.dropdown-menu').delegate('a', 'click', $.proxy(this.click, this)); }); } })(window.jQuery);
atFriendly/opencart
upload/catalog/view/javascript/common.js
JavaScript
gpl-3.0
15,343
package com.fuav.android.data.provider; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ProviderInfo; import android.content.res.XmlResourceParser; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.provider.OpenableColumns; import android.text.TextUtils; import android.webkit.MimeTypeMap; import org.xmlpull.v1.XmlPullParserException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * FileProvider is a special subclass of {@link ContentProvider} that facilitates secure sharing * of files associated with an app by creating a <code>content://</code> {@link Uri} for a file * instead of a <code>file:///</code> {@link Uri}. * <p> * A content URI allows you to grant read and write access using * temporary access permissions. When you create an {@link Intent} containing * a content URI, in order to send the content URI * to a client app, you can also call {@link Intent#setFlags(int) Intent.setFlags()} to add * permissions. These permissions are available to the client app for as long as the stack for * a receiving {@link android.app.Activity} is active. For an {@link Intent} going to a * {@link android.app.Service}, the permissions are available as long as the * {@link android.app.Service} is running. * <p> * In comparison, to control access to a <code>file:///</code> {@link Uri} you have to modify the * file system permissions of the underlying file. The permissions you provide become available to * <em>any</em> app, and remain in effect until you change them. This level of access is * fundamentally insecure. * <p> * The increased level of file access security offered by a content URI * makes FileProvider a key part of Android's security infrastructure. * <p> * This overview of FileProvider includes the following topics: * </p> * <ol> * <li><a href="#ProviderDefinition">Defining a FileProvider</a></li> * <li><a href="#SpecifyFiles">Specifying Available Files</a></li> * <li><a href="#GetUri">Retrieving the Content URI for a File</li> * <li><a href="#Permissions">Granting Temporary Permissions to a URI</a></li> * <li><a href="#ServeUri">Serving a Content URI to Another App</a></li> * </ol> * <h3 id="ProviderDefinition">Defining a FileProvider</h3> * <p> * Since the default functionality of FileProvider includes content URI generation for files, you * don't need to define a subclass in code. Instead, you can include a FileProvider in your app * by specifying it entirely in XML. To specify the FileProvider component itself, add a * <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></code> * element to your app manifest. Set the <code>android:name</code> attribute to * <code>android.support.v4.content.FileProvider</code>. Set the <code>android:authorities</code> * attribute to a URI authority based on a domain you control; for example, if you control the * domain <code>mydomain.com</code> you should use the authority * <code>com.mydomain.fileprovider</code>. Set the <code>android:exported</code> attribute to * <code>false</code>; the FileProvider does not need to be public. Set the * <a href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn" * >android:grantUriPermissions</a> attribute to <code>true</code>, to allow you * to grant temporary access to files. For example: * <pre class="prettyprint"> *&lt;manifest&gt; * ... * &lt;application&gt; * ... * &lt;provider * android:name="android.support.v4.content.FileProvider" * android:authorities="com.mydomain.fileprovider" * android:exported="false" * android:grantUriPermissions="true"&gt; * ... * &lt;/provider&gt; * ... * &lt;/application&gt; *&lt;/manifest&gt;</pre> * <p> * If you want to override any of the default behavior of FileProvider methods, extend * the FileProvider class and use the fully-qualified class name in the <code>android:name</code> * attribute of the <code>&lt;provider&gt;</code> element. * <h3 id="SpecifyFiles">Specifying Available Files</h3> * A FileProvider can only generate a content URI for files in directories that you specify * beforehand. To specify a directory, specify the its storage area and path in XML, using child * elements of the <code>&lt;paths&gt;</code> element. * For example, the following <code>paths</code> element tells FileProvider that you intend to * request content URIs for the <code>images/</code> subdirectory of your private file area. * <pre class="prettyprint"> *&lt;paths xmlns:android="http://schemas.android.com/apk/res/android"&gt; * &lt;files-path name="my_images" path="images/"/&gt; * ... *&lt;/paths&gt; *</pre> * <p> * The <code>&lt;paths&gt;</code> element must contain one or more of the following child elements: * </p> * <dl> * <dt> * <pre class="prettyprint"> *&lt;files-path name="<i>name</i>" path="<i>path</i>" /&gt; *</pre> * </dt> * <dd> * Represents files in the <code>files/</code> subdirectory of your app's internal storage * area. This subdirectory is the same as the value returned by {@link Context#getFilesDir() * Context.getFilesDir()}. * <dt> * <pre class="prettyprint"> *&lt;external-path name="<i>name</i>" path="<i>path</i>" /&gt; *</pre> * </dt> * <dd> * Represents files in the root of your app's external storage area. The path * {@link Context#getExternalFilesDir(String) Context.getExternalFilesDir()} returns the * <code>files/</code> subdirectory of this this root. * </dd> * <dt> * <pre> *&lt;cache-path name="<i>name</i>" path="<i>path</i>" /&gt; *</pre> * <dt> * <dd> * Represents files in the cache subdirectory of your app's internal storage area. The root path * of this subdirectory is the same as the value returned by {@link Context#getCacheDir() * getCacheDir()}. * </dd> * </dl> * <p> * These child elements all use the same attributes: * </p> * <dl> * <dt> * <code>name="<i>name</i>"</code> * </dt> * <dd> * A URI path segment. To enforce security, this value hides the name of the subdirectory * you're sharing. The subdirectory name for this value is contained in the * <code>path</code> attribute. * </dd> * <dt> * <code>path="<i>path</i>"</code> * </dt> * <dd> * The subdirectory you're sharing. While the <code>name</code> attribute is a URI path * segment, the <code>path</code> value is an actual subdirectory name. Notice that the * value refers to a <b>subdirectory</b>, not an individual file or files. You can't * share a single file by its file name, nor can you specify a subset of files using * wildcards. * </dd> * </dl> * <p> * You must specify a child element of <code>&lt;paths&gt;</code> for each directory that contains * files for which you want content URIs. For example, these XML elements specify two directories: * <pre class="prettyprint"> *&lt;paths xmlns:android="http://schemas.android.com/apk/res/android"&gt; * &lt;files-path name="my_images" path="images/"/&gt; * &lt;files-path name="my_docs" path="docs/"/&gt; *&lt;/paths&gt; *</pre> * <p> * Put the <code>&lt;paths&gt;</code> element and its children in an XML file in your project. * For example, you can add them to a new file called <code>res/xml/file_paths.xml</code>. * To link this file to the FileProvider, add a * <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">&lt;meta-data&gt;</a> element * as a child of the <code>&lt;provider&gt;</code> element that defines the FileProvider. Set the * <code>&lt;meta-data&gt;</code> element's "android:name" attribute to * <code>android.support.FILE_PROVIDER_PATHS</code>. Set the element's "android:resource" attribute * to <code>&#64;xml/file_paths</code> (notice that you don't specify the <code>.xml</code> * extension). For example: * <pre class="prettyprint"> *&lt;provider * android:name="android.support.v4.content.FileProvider" * android:authorities="com.mydomain.fileprovider" * android:exported="false" * android:grantUriPermissions="true"&gt; * &lt;meta-data * android:name="android.support.FILE_PROVIDER_PATHS" * android:resource="&#64;xml/file_paths" /&gt; *&lt;/provider&gt; *</pre> * <h3 id="GetUri">Generating the Content URI for a File</h3> * <p> * To share a file with another app using a content URI, your app has to generate the content URI. * To generate the content URI, create a new {@link File} for the file, then pass the {@link File} * to {@link #getUriForFile(Context, String, File) getUriForFile()}. You can send the content URI * returned by {@link #getUriForFile(Context, String, File) getUriForFile()} to another app in an * {@link android.content.Intent}. The client app that receives the content URI can open the file * and access its contents by calling * {@link android.content.ContentResolver#openFileDescriptor(Uri, String) * ContentResolver.openFileDescriptor} to get a {@link ParcelFileDescriptor}. * <p> * For example, suppose your app is offering files to other apps with a FileProvider that has the * authority <code>com.mydomain.fileprovider</code>. To get a content URI for the file * <code>default_image.jpg</code> in the <code>images/</code> subdirectory of your internal storage * add the following code: * <pre class="prettyprint"> *File imagePath = new File(Context.getFilesDir(), "images"); *File newFile = new File(imagePath, "default_image.jpg"); *Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile); *</pre> * As a result of the previous snippet, * {@link #getUriForFile(Context, String, File) getUriForFile()} returns the content URI * <code>content://com.mydomain.fileprovider/my_images/default_image.jpg</code>. * <h3 id="Permissions">Granting Temporary Permissions to a URI</h3> * To grant an access permission to a content URI returned from * {@link #getUriForFile(Context, String, File) getUriForFile()}, do one of the following: * <ul> * <li> * Call the method * {@link Context#grantUriPermission(String, Uri, int) * Context.grantUriPermission(package, Uri, mode_flags)} for the <code>content://</code> * {@link Uri}, using the desired mode flags. This grants temporary access permission for the * content URI to the specified package, according to the value of the * the <code>mode_flags</code> parameter, which you can set to * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION}, {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} * or both. The permission remains in effect until you revoke it by calling * {@link Context#revokeUriPermission(Uri, int) revokeUriPermission()} or until the device * reboots. * </li> * <li> * Put the content URI in an {@link Intent} by calling {@link Intent#setData(Uri) setData()}. * </li> * <li> * Next, call the method {@link Intent#setFlags(int) Intent.setFlags()} with either * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} or * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} or both. * </li> * <li> * Finally, send the {@link Intent} to * another app. Most often, you do this by calling * {@link android.app.Activity#setResult(int, android.content.Intent) setResult()}. * <p> * Permissions granted in an {@link Intent} remain in effect while the stack of the receiving * {@link android.app.Activity} is active. When the stack finishes, the permissions are * automatically removed. Permissions granted to one {@link android.app.Activity} in a client * app are automatically extended to other components of that app. * </p> * </li> * </ul> * <h3 id="ServeUri">Serving a Content URI to Another App</h3> * <p> * There are a variety of ways to serve the content URI for a file to a client app. One common way * is for the client app to start your app by calling * {@link android.app.Activity#startActivityForResult(Intent, int, Bundle) startActivityResult()}, * which sends an {@link Intent} to your app to start an {@link android.app.Activity} in your app. * In response, your app can immediately return a content URI to the client app or present a user * interface that allows the user to pick a file. In the latter case, once the user picks the file * your app can return its content URI. In both cases, your app returns the content URI in an * {@link Intent} sent via {@link android.app.Activity#setResult(int, Intent) setResult()}. * </p> * <p> * You can also put the content URI in a {@link android.content.ClipData} object and then add the * object to an {@link Intent} you send to a client app. To do this, call * {@link Intent#setClipData(ClipData) Intent.setClipData()}. When you use this approach, you can * add multiple {@link android.content.ClipData} objects to the {@link Intent}, each with its own * content URI. When you call {@link Intent#setFlags(int) Intent.setFlags()} on the {@link Intent} * to set temporary access permissions, the same permissions are applied to all of the content * URIs. * </p> * <p class="note"> * <strong>Note:</strong> The {@link Intent#setClipData(ClipData) Intent.setClipData()} method is * only available in platform version 16 (Android 4.1) and later. If you want to maintain * compatibility with previous versions, you should send one content URI at a time in the * {@link Intent}. Set the action to {@link Intent#ACTION_SEND} and put the URI in data by calling * {@link Intent#setData setData()}. * </p> * <h3 id="">More Information</h3> * <p> * To learn more about FileProvider, see the Android training class * <a href="{@docRoot}training/secure-file-sharing/index.html">Sharing Files Securely with URIs</a>. * </p> */ public class FileProvider extends ContentProvider { private static final String[] COLUMNS = { OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE }; private static final String META_DATA_FILE_PROVIDER_PATHS = "android.support.FILE_PROVIDER_PATHS"; private static final String TAG_ROOT_PATH = "root-path"; private static final String TAG_FILES_PATH = "files-path"; private static final String TAG_CACHE_PATH = "cache-path"; private static final String TAG_EXTERNAL = "external-path"; private static final String ATTR_NAME = "name"; private static final String ATTR_PATH = "path"; private static final File DEVICE_ROOT = new File("/"); // @GuardedBy("sCache") private static HashMap<String, PathStrategy> sCache = new HashMap<String, PathStrategy>(); private PathStrategy mStrategy; /** * The default FileProvider implementation does not need to be initialized. If you want to * override this method, you must provide your own subclass of FileProvider. */ @Override public boolean onCreate() { return true; } /** * After the FileProvider is instantiated, this method is called to provide the system with * information about the provider. * * @param context A {@link Context} for the current component. * @param info A {@link ProviderInfo} for the new provider. */ @Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); // Sanity check our security if (info.exported) { throw new SecurityException("Provider must not be exported"); } if (!info.grantUriPermissions) { throw new SecurityException("Provider must grant uri permissions"); } mStrategy = getPathStrategy(context, info.authority); } /** * Return a content URI for a given {@link File}. Specific temporary * permissions for the content URI can be set with * {@link Context#grantUriPermission(String, Uri, int)}, or added * to an {@link Intent} by calling {@link Intent#setData(Uri) setData()} and then * {@link Intent#setFlags(int) setFlags()}; in both cases, the applicable flags are * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. A FileProvider can only return a * <code>content</code> {@link Uri} for file paths defined in their <code>&lt;paths&gt;</code> * meta-data element. See the Class Overview for more information. * * @param context A {@link Context} for the current component. * @param authority The authority of a {@link FileProvider} defined in a * {@code &lt;provider&gt;} element in your app's manifest. * @param file A {@link File} pointing to the filename for which you want a * <code>content</code> {@link Uri}. * @return A content URI for the file. * @throws IllegalArgumentException When the given {@link File} is outside * the paths supported by the provider. */ public static Uri getUriForFile(Context context, String authority, File file) { final PathStrategy strategy = getPathStrategy(context, authority); return strategy.getUriForFile(file); } /** * Use a content URI returned by * {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file * managed by the FileProvider. * FileProvider reports the column names defined in {@link android.provider.OpenableColumns}: * <ul> * <li>{@link android.provider.OpenableColumns#DISPLAY_NAME}</li> * <li>{@link android.provider.OpenableColumns#SIZE}</li> * </ul> * For more information, see * {@link ContentProvider#query(Uri, String[], String, String[], String) * ContentProvider.query()}. * * @param uri A content URI returned by {@link #getUriForFile}. * @param projection The list of columns to put into the {@link Cursor}. If null all columns are * included. * @param selection Selection criteria to apply. If null then all data that matches the content * URI is returned. * @param selectionArgs An array of {@link java.lang.String}, containing arguments to bind to * the <i>selection</i> parameter. The <i>query</i> method scans <i>selection</i> from left to * right and iterates through <i>selectionArgs</i>, replacing the current "?" character in * <i>selection</i> with the value at the current position in <i>selectionArgs</i>. The * values are bound to <i>selection</i> as {@link java.lang.String} values. * @param sortOrder A {@link java.lang.String} containing the column name(s) on which to sort * the resulting {@link Cursor}. * @return A {@link Cursor} containing the results of the query. * */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // ContentProvider has already checked granted permissions final File file = mStrategy.getFileForUri(uri); if (projection == null) { projection = COLUMNS; } String[] cols = new String[projection.length]; Object[] values = new Object[projection.length]; int i = 0; for (String col : projection) { if (OpenableColumns.DISPLAY_NAME.equals(col)) { cols[i] = OpenableColumns.DISPLAY_NAME; values[i++] = file.getName(); } else if (OpenableColumns.SIZE.equals(col)) { cols[i] = OpenableColumns.SIZE; values[i++] = file.length(); } } cols = copyOf(cols, i); values = copyOf(values, i); final MatrixCursor cursor = new MatrixCursor(cols, 1); cursor.addRow(values); return cursor; } /** * Returns the MIME type of a content URI returned by * {@link #getUriForFile(Context, String, File) getUriForFile()}. * * @param uri A content URI returned by * {@link #getUriForFile(Context, String, File) getUriForFile()}. * @return If the associated file has an extension, the MIME type associated with that * extension; otherwise <code>application/octet-stream</code>. */ @Override public String getType(Uri uri) { // ContentProvider has already checked granted permissions final File file = mStrategy.getFileForUri(uri); final int lastDot = file.getName().lastIndexOf('.'); if (lastDot >= 0) { final String extension = file.getName().substring(lastDot + 1); final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if (mime != null) { return mime; } } return "application/octet-stream"; } /** * By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must * subclass FileProvider if you want to provide different functionality. */ @Override public Uri insert(Uri uri, ContentValues values) { throw new UnsupportedOperationException("No external inserts"); } /** * By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must * subclass FileProvider if you want to provide different functionality. */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { throw new UnsupportedOperationException("No external updates"); } /** * Deletes the file associated with the specified content URI, as * returned by {@link #getUriForFile(Context, String, File) getUriForFile()}. Notice that this * method does <b>not</b> throw an {@link java.io.IOException}; you must check its return value. * * @param uri A content URI for a file, as returned by * {@link #getUriForFile(Context, String, File) getUriForFile()}. * @param selection Ignored. Set to {@code null}. * @param selectionArgs Ignored. Set to {@code null}. * @return 1 if the delete succeeds; otherwise, 0. */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { // ContentProvider has already checked granted permissions final File file = mStrategy.getFileForUri(uri); return file.delete() ? 1 : 0; } /** * By default, FileProvider automatically returns the * {@link ParcelFileDescriptor} for a file associated with a <code>content://</code> * {@link Uri}. To get the {@link ParcelFileDescriptor}, call * {@link android.content.ContentResolver#openFileDescriptor(Uri, String) * ContentResolver.openFileDescriptor}. * * To override this method, you must provide your own subclass of FileProvider. * * @param uri A content URI associated with a file, as returned by * {@link #getUriForFile(Context, String, File) getUriForFile()}. * @param mode Access mode for the file. May be "r" for read-only access, "rw" for read and * write access, or "rwt" for read and write access that truncates any existing file. * @return A new {@link ParcelFileDescriptor} with which you can access the file. */ @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { // ContentProvider has already checked granted permissions final File file = mStrategy.getFileForUri(uri); final int fileMode = modeToMode(mode); return ParcelFileDescriptor.open(file, fileMode); } /** * Return {@link PathStrategy} for given authority, either by parsing or * returning from cache. */ private static PathStrategy getPathStrategy(Context context, String authority) { PathStrategy strat; synchronized (sCache) { strat = sCache.get(authority); if (strat == null) { try { strat = parsePathStrategy(context, authority); } catch (IOException e) { throw new IllegalArgumentException( "Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e); } catch (XmlPullParserException e) { throw new IllegalArgumentException( "Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e); } sCache.put(authority, strat); } } return strat; } /** * Parse and return {@link PathStrategy} for given authority as defined in * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code &lt;meta-data>}. * * @see #getPathStrategy(Context, String) */ private static PathStrategy parsePathStrategy(Context context, String authority) throws IOException, XmlPullParserException { final SimplePathStrategy strat = new SimplePathStrategy(authority); final ProviderInfo info = context.getPackageManager() .resolveContentProvider(authority, PackageManager.GET_META_DATA); final XmlResourceParser in = info.loadXmlMetaData( context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS); if (in == null) { throw new IllegalArgumentException( "Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data"); } int type; while ((type = in.next()) != END_DOCUMENT) { if (type == START_TAG) { final String tag = in.getName(); final String name = in.getAttributeValue(null, ATTR_NAME); String path = in.getAttributeValue(null, ATTR_PATH); File target = null; if (TAG_ROOT_PATH.equals(tag)) { target = buildPath(DEVICE_ROOT, path); } else if (TAG_FILES_PATH.equals(tag)) { target = buildPath(context.getFilesDir(), path); } else if (TAG_CACHE_PATH.equals(tag)) { target = buildPath(context.getCacheDir(), path); } else if (TAG_EXTERNAL.equals(tag)) { target = buildPath(context.getExternalFilesDir(null), path); } if (target != null) { strat.addRoot(name, target); } } } return strat; } /** * Strategy for mapping between {@link File} and {@link Uri}. * <p> * Strategies must be symmetric so that mapping a {@link File} to a * {@link Uri} and then back to a {@link File} points at the original * target. * <p> * Strategies must remain consistent across app launches, and not rely on * dynamic state. This ensures that any generated {@link Uri} can still be * resolved if your process is killed and later restarted. * * @see SimplePathStrategy */ interface PathStrategy { /** * Return a {@link Uri} that represents the given {@link File}. */ Uri getUriForFile(File file); /** * Return a {@link File} that represents the given {@link Uri}. */ File getFileForUri(Uri uri); } /** * Strategy that provides access to files living under a narrow whitelist of * filesystem roots. It will throw {@link SecurityException} if callers try * accessing files outside the configured roots. * <p> * For example, if configured with * {@code addRoot("myfiles", context.getFilesDir())}, then * {@code context.getFileStreamPath("foo.txt")} would map to * {@code content://myauthority/myfiles/foo.txt}. */ static class SimplePathStrategy implements PathStrategy { private final String mAuthority; private final HashMap<String, File> mRoots = new HashMap<String, File>(); public SimplePathStrategy(String authority) { mAuthority = authority; } /** * Add a mapping from a name to a filesystem root. The provider only offers * access to files that live under configured roots. */ public void addRoot(String name, File root) { if (TextUtils.isEmpty(name)) { throw new IllegalArgumentException("Name must not be empty"); } try { // Resolve to canonical path to keep path checking fast root = root.getCanonicalFile(); } catch (IOException e) { throw new IllegalArgumentException( "Failed to resolve canonical path for " + root, e); } mRoots.put(name, root); } @Override public Uri getUriForFile(File file) { String path; try { path = file.getCanonicalPath(); } catch (IOException e) { throw new IllegalArgumentException("Failed to resolve canonical path for " + file); } // Find the most-specific root path Map.Entry<String, File> mostSpecific = null; for (Map.Entry<String, File> root : mRoots.entrySet()) { final String rootPath = root.getValue().getPath(); if (path.startsWith(rootPath) && (mostSpecific == null || rootPath.length() > mostSpecific.getValue().getPath().length())) { mostSpecific = root; } } if (mostSpecific == null) { throw new IllegalArgumentException( "Failed to find configured root that contains " + path); } // Start at first char of path under root final String rootPath = mostSpecific.getValue().getPath(); if (rootPath.endsWith("/")) { path = path.substring(rootPath.length()); } else { path = path.substring(rootPath.length() + 1); } // Encode the tag and path separately path = Uri.encode(mostSpecific.getKey()) + '/' + Uri.encode(path, "/"); return new Uri.Builder().scheme("content") .authority(mAuthority).encodedPath(path).build(); } @Override public File getFileForUri(Uri uri) { String path = uri.getEncodedPath(); final int splitIndex = path.indexOf('/', 1); final String tag = Uri.decode(path.substring(1, splitIndex)); path = Uri.decode(path.substring(splitIndex + 1)); final File root = mRoots.get(tag); if (root == null) { throw new IllegalArgumentException("Unable to find configured root for " + uri); } File file = new File(root, path); try { file = file.getCanonicalFile(); } catch (IOException e) { throw new IllegalArgumentException("Failed to resolve canonical path for " + file); } if (!file.getPath().startsWith(root.getPath())) { throw new SecurityException("Resolved path jumped beyond configured root"); } return file; } } /** * Copied from ContentResolver.java */ private static int modeToMode(String mode) { int modeBits; if ("r".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_READ_ONLY; } else if ("w".equals(mode) || "wt".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE; } else if ("wa".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_APPEND; } else if ("rw".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_READ_WRITE | ParcelFileDescriptor.MODE_CREATE; } else if ("rwt".equals(mode)) { modeBits = ParcelFileDescriptor.MODE_READ_WRITE | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE; } else { throw new IllegalArgumentException("Invalid mode: " + mode); } return modeBits; } private static File buildPath(File base, String... segments) { File cur = base; for (String segment : segments) { if (segment != null) { cur = new File(cur, segment); } } return cur; } private static String[] copyOf(String[] original, int newLength) { final String[] result = new String[newLength]; System.arraycopy(original, 0, result, 0, newLength); return result; } private static Object[] copyOf(Object[] original, int newLength) { final Object[] result = new Object[newLength]; System.arraycopy(original, 0, result, 0, newLength); return result; } }
forgodsake/TowerPlus
Android/src/com/fuav/android/data/provider/FileProvider.java
Java
gpl-3.0
33,666
<?php require_once("check2.php"); //1.上传文件类型 $filetype = getFileType($_FILES["file"]["name"]); $filetype = strtolower($filetype); //2.上传文件大小 $filesize = ($_FILES["file"]["size"] / 1024); //3.当前日期 $showtime = date("Y-m-d"); //4.原input id赋值 $parentid = $_REQUEST["parentid"]; //5.原ID值是否叠加 $parentadd = $_REQUEST["parentadd"]; //定义允许上传的文件扩展名 $ext_arr = array('gif','jpg','png','bmp','zip','rar','doc','flv'); if (in_array($filetype, $ext_arr) === true && ($filesize < 50000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { //创建上传文件名 $create_file = createFileName().".".$filetype; //上传目录 $path = "../../upload/".$showtime."/"; //完整文件地址 $fullname = "upload/".$showtime."/".$create_file; //创建目录 if (!file_exists($path)) { mkdir($path); } if (file_exists($path . $create_file)) { //echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"],$path . $create_file); $realtype = file_type2($path . $create_file); //检查扩展名 if (in_array($realtype, $ext_arr) === false) { if(unlink($path . $create_file)){ echo "<script>"; echo "alert('上传文件含恶意代码,已删除!');"; if($parentadd){ }else{ echo "window.parent.document.getElementById('".$parentid."').value='';"; } echo "window.parent.ClosePop();"; //Response.Write("window.parent.closeWindow();"); echo "</script>"; } }else{ echo "<script>"; echo "alert('上传成功');"; if($parentadd=='true'){ echo "window.parent.document.getElementById('".$parentid."').value=window.parent.document.getElementById('".$parentid."').value+',".$fullname."';"; }else{ echo "window.parent.document.getElementById('".$parentid."').value='".$fullname."';"; } echo "window.parent.ClosePop();"; echo "</script>"; } //echo "Stored in: " . $path . $create_file; } } } else { echo "上传出错,请检测文件后重试"; } /** * 检测文件真实类型 * @param $filename */ function file_type2($filename) { $file = fopen($filename, "rb"); $bin = fread($file, 2); //只读2字节 fclose($file); $strInfo = @unpack("C2chars", $bin); $typeCode = intval($strInfo['chars1'].$strInfo['chars2']); $fileType = ''; switch ($typeCode) { case 7790: $fileType = 'exe'; break; case 7784: $fileType = 'midi'; break; case 8297: $fileType = 'rar'; break; case 8075: $fileType = 'zip'; break; case 255216: $fileType = 'jpg'; break; case 7173: $fileType = 'gif'; break; case 6677: $fileType = 'bmp'; break; case 13780: $fileType = 'png'; break; case 208207: $fileType = 'doc'; default: $fileType = 'unknown: '.$typeCode; } //Fix if ($strInfo['chars1']=='-1' AND $strInfo['chars2']=='-40' ) return 'jpg'; if ($strInfo['chars1']=='-119' AND $strInfo['chars2']=='80' ) return 'png'; return $fileType; } ?>
breakkdreams/youchu
core/manage/upload_file.php
PHP
gpl-3.0
3,610
<?php /* * Copyright 2014 REI Systems, Inc. * * This file is part of GovDashboard. * * GovDashboard 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. * * GovDashboard 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 GovDashboard. If not, see <http://www.gnu.org/licenses/>. */ class WebHDFS_CURLProxy extends CURLProxy { public function __construct(DataSourceMetaData $datasource) { $uri = "{$datasource->protocol}://{$datasource->host}:{$datasource->services->WebHDFS->port}"; parent::__construct($uri, new WebHDFS_CURLHandlerOutputFormatter()); } } class WebHDFS_CURLHandlerOutputFormatter extends CURLHandlerOutputFormatter { public function format($resourceId, $output) { $output = parent::format($resourceId, $output); if (isset($output)) { $parsedOutput = json_decode($output, TRUE); if (isset($parsedOutput)) { if (isset($parsedOutput['RemoteException'])) { $message = isset($parsedOutput['RemoteException']['message']) ? $parsedOutput['RemoteException']['message'] : 'Error message is not provided'; throw new IllegalStateException(t( 'Resource %resourceId executed with error: %error', array( '%resourceId' => $resourceId, '%error' => $message))); } } } return $output; } }
REI-Systems/GovDashboard-Community
webapp/sites/all/modules/platform/data_controller_datasource/nosql/hadoop/webhdfs/common/curl/WebHDFS_CURLProxy.php
PHP
gpl-3.0
1,982
# -*- coding: utf-8 -*- import gensim, logging class SemanticVector: model = '' def __init__(self, structure): self.structure = structure def model_word2vec(self, min_count=15, window=15, size=100): print 'preparing sentences list' sentences = self.structure.prepare_list_of_words_in_sentences() print 'start modeling' self.model = gensim.models.Word2Vec(sentences, size=size, window=window, min_count=min_count, workers=4, sample=0.001, sg=0) return self.model def save_model(self, name): self.model.save(name) def load_model(self, name): self.model = gensim.models.Word2Vec.load(name)
arashzamani/lstm_nlg_ver1
language_parser/SemanticVector.py
Python
gpl-3.0
679
/* * Copyright (C) 2020 Graylog, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. */ package org.graylog.schema; public class SessionFields { public static final String SESSION_ID = "session_id"; }
Graylog2/graylog2-server
graylog2-server/src/main/java/org/graylog/schema/SessionFields.java
Java
gpl-3.0
763
package org.renjin.gcc.codegen.expr; import org.renjin.gcc.InternalCompilerException; import org.renjin.gcc.codegen.MethodGenerator; import org.renjin.gcc.codegen.array.ArrayExpr; import org.renjin.gcc.codegen.array.ArrayTypeStrategy; import org.renjin.gcc.codegen.call.CallGenerator; import org.renjin.gcc.codegen.call.FunPtrCallGenerator; import org.renjin.gcc.codegen.condition.ConditionGenerator; import org.renjin.gcc.codegen.condition.ConstConditionGenerator; import org.renjin.gcc.codegen.condition.NullCheckGenerator; import org.renjin.gcc.codegen.fatptr.FatPtrPair; import org.renjin.gcc.codegen.type.PointerTypeStrategy; import org.renjin.gcc.codegen.type.TypeOracle; import org.renjin.gcc.codegen.type.TypeStrategy; import org.renjin.gcc.codegen.type.UnsupportedCastException; import org.renjin.gcc.codegen.type.complex.ComplexCmpGenerator; import org.renjin.gcc.codegen.type.complex.ComplexValue; import org.renjin.gcc.codegen.type.complex.ComplexValues; import org.renjin.gcc.codegen.type.fun.FunPtr; import org.renjin.gcc.codegen.type.primitive.*; import org.renjin.gcc.codegen.type.primitive.op.*; import org.renjin.gcc.codegen.type.record.RecordTypeStrategy; import org.renjin.gcc.gimple.GimpleOp; import org.renjin.gcc.gimple.expr.*; import org.renjin.gcc.gimple.type.*; import org.renjin.gcc.symbols.SymbolTable; import org.renjin.repackaged.asm.Type; import java.util.List; /** * Creates code-generating {@link GExpr}s from {@code GimpleExpr}s */ public class ExprFactory { private final TypeOracle typeOracle; private final SymbolTable symbolTable; private MethodGenerator mv; public ExprFactory(TypeOracle typeOracle, SymbolTable symbolTable, MethodGenerator mv) { this.typeOracle = typeOracle; this.symbolTable = symbolTable; this.mv = mv; } public GExpr findGenerator(GimpleExpr expr, GimpleType expectedType) { return maybeCast(findGenerator(expr), expectedType, expr.getType()); } public GExpr maybeCast(GExpr rhs, GimpleType lhsType, GimpleType rhsType) { if(lhsType.equals(rhsType)) { return rhs; } TypeStrategy leftStrategy = typeOracle.forType(lhsType); TypeStrategy rightStrategy = typeOracle.forType(rhsType); if(ConstantValue.isZero(rhs) && leftStrategy instanceof PointerTypeStrategy) { return ((PointerTypeStrategy) leftStrategy).nullPointer(); } try { return leftStrategy.cast(mv, rhs, rightStrategy); } catch (UnsupportedCastException e) { throw new InternalCompilerException(String.format("Unsupported cast to %s [%s] from %s [%s]", lhsType, leftStrategy.getClass().getSimpleName(), rhsType, rightStrategy.getClass().getSimpleName()), e); } } public GExpr findGenerator(GimpleExpr expr) { if(expr instanceof GimpleSymbolRef) { GExpr variable = symbolTable.getVariable((GimpleSymbolRef) expr); if(variable == null) { throw new InternalCompilerException("No such variable: " + expr); } return variable; } else if(expr instanceof GimpleConstant) { return forConstant((GimpleConstant) expr); } else if(expr instanceof GimpleConstructor) { return forConstructor((GimpleConstructor) expr); } else if(expr instanceof GimpleNopExpr) { return findGenerator(((GimpleNopExpr) expr).getValue(), expr.getType()); } else if(expr instanceof GimpleAddressOf) { GimpleAddressOf addressOf = (GimpleAddressOf) expr; if (addressOf.getValue() instanceof GimpleFunctionRef) { GimpleFunctionRef functionRef = (GimpleFunctionRef) addressOf.getValue(); return new FunPtr(symbolTable.findHandle(functionRef)); } else if(addressOf.getValue() instanceof GimplePrimitiveConstant) { // Exceptionally, gimple often contains to address of constants when // passing them to functions JExpr value = findPrimitiveGenerator(addressOf.getValue()); return new FatPtrPair(new PrimitiveValueFunction(value.getType()), Expressions.newArray(value)); } else { GExpr value = findGenerator(addressOf.getValue()); try { return value.addressOf(); } catch (ClassCastException | UnsupportedOperationException ignored) { throw new InternalCompilerException(addressOf.getValue() + " [" + value.getClass().getName() + "] is not addressable"); } } } else if(expr instanceof GimpleMemRef) { GimpleMemRef memRefExpr = (GimpleMemRef) expr; return memRef(memRefExpr, memRefExpr.getType()); } else if(expr instanceof GimpleArrayRef) { GimpleArrayRef arrayRef = (GimpleArrayRef) expr; ArrayTypeStrategy arrayStrategy = typeOracle.forArrayType(arrayRef.getArray().getType()); GExpr array = findGenerator(arrayRef.getArray()); GExpr index = findGenerator(arrayRef.getIndex()); return arrayStrategy.elementAt(array, index); } else if(expr instanceof GimpleConstantRef) { GimpleConstant constant = ((GimpleConstantRef) expr).getValue(); JExpr constantValue = findPrimitiveGenerator(constant); FatPtrPair address = new FatPtrPair( new PrimitiveValueFunction(constantValue.getType()), Expressions.newArray(constantValue)); return new PrimitiveValue(constantValue, address); } else if(expr instanceof GimpleComplexPartExpr) { GimpleExpr complexExpr = ((GimpleComplexPartExpr) expr).getComplexValue(); ComplexValue complexGenerator = (ComplexValue) findGenerator(complexExpr); if (expr instanceof GimpleRealPartExpr) { return complexGenerator.getRealGExpr(); } else { return complexGenerator.getImaginaryGExpr(); } } else if (expr instanceof GimpleComponentRef) { GimpleComponentRef ref = (GimpleComponentRef) expr; GExpr instance = findGenerator(((GimpleComponentRef) expr).getValue()); RecordTypeStrategy typeStrategy = (RecordTypeStrategy) typeOracle.forType(ref.getValue().getType()); TypeStrategy fieldTypeStrategy = typeOracle.forType(ref.getType()); return typeStrategy.memberOf(mv, instance, ref.getMember().getOffset(), ref.getMember().getSize(), fieldTypeStrategy); } else if (expr instanceof GimpleBitFieldRefExpr) { GimpleBitFieldRefExpr ref = (GimpleBitFieldRefExpr) expr; GExpr instance = findGenerator(ref.getValue()); RecordTypeStrategy recordTypeStrategy = (RecordTypeStrategy) typeOracle.forType(ref.getValue().getType()); TypeStrategy memberTypeStrategy = typeOracle.forType(expr.getType()); return recordTypeStrategy.memberOf(mv, instance, ref.getOffset(), ref.getSize(), memberTypeStrategy); } else if(expr instanceof GimpleCompoundLiteral) { return findGenerator(((GimpleCompoundLiteral) expr).getDecl()); } else if(expr instanceof GimpleObjectTypeRef) { GimpleObjectTypeRef typeRef = (GimpleObjectTypeRef) expr; return findGenerator(typeRef.getExpr()); } else if(expr instanceof GimplePointerPlus) { GimplePointerPlus pointerPlus = (GimplePointerPlus) expr; return pointerPlus(pointerPlus.getPointer(), pointerPlus.getOffset(), pointerPlus.getType()); } throw new UnsupportedOperationException(expr + " [" + expr.getClass().getSimpleName() + "]"); } private GExpr forConstructor(GimpleConstructor expr) { return typeOracle.forType(expr.getType()).constructorExpr(this, mv, expr); } public CallGenerator findCallGenerator(GimpleExpr functionExpr) { if(functionExpr instanceof GimpleAddressOf) { GimpleAddressOf addressOf = (GimpleAddressOf) functionExpr; if (addressOf.getValue() instanceof GimpleFunctionRef) { GimpleFunctionRef ref = (GimpleFunctionRef) addressOf.getValue(); return symbolTable.findCallGenerator(ref); } GimpleAddressOf address = (GimpleAddressOf) functionExpr; throw new UnsupportedOperationException("function ref: " + address.getValue() + " [" + address.getValue().getClass().getSimpleName() + "]"); } // Assume this is a function pointer ptr expression FunPtr expr = (FunPtr) findGenerator(functionExpr); return new FunPtrCallGenerator(typeOracle, (GimpleFunctionType) functionExpr.getType().getBaseType(), expr.unwrap()); } public ConditionGenerator findConditionGenerator(GimpleOp op, List<GimpleExpr> operands) { if(operands.size() == 2) { return findComparisonGenerator(op, operands.get(0), operands.get(1)); } else { throw new UnsupportedOperationException(); } } private ConditionGenerator findComparisonGenerator(GimpleOp op, GimpleExpr x, GimpleExpr y) { if(x.getType() instanceof org.renjin.gcc.gimple.type.GimpleComplexType) { return new ComplexCmpGenerator(op, findComplexGenerator(x), findComplexGenerator(y)); } else if(x.getType() instanceof GimplePrimitiveType) { if(x.getType() instanceof GimpleIntegerType && ((GimpleIntegerType) x.getType()).isUnsigned()) { return PrimitiveCmpGenerator.unsigned(op, findPrimitiveGenerator(x), findPrimitiveGenerator(y)); } else { return new PrimitiveCmpGenerator(op, findPrimitiveGenerator(x), findPrimitiveGenerator(y)); } } else if(x.getType() instanceof GimpleIndirectType) { return comparePointers(op, x, y); } else { throw new UnsupportedOperationException("Unsupported comparison " + op + " between types " + x.getType() + " and " + y.getType()); } } private ConditionGenerator comparePointers(GimpleOp op, GimpleExpr x, GimpleExpr y) { // First see if this is a null check if(isNull(x) && isNull(y)) { switch (op) { case EQ_EXPR: case GE_EXPR: case LE_EXPR: return new ConstConditionGenerator(true); case NE_EXPR: case LT_EXPR: case GT_EXPR: return new ConstConditionGenerator(false); default: throw new UnsupportedOperationException("op: " + op); } } else if(isNull(x)) { return new NullCheckGenerator(op, (PtrExpr) findGenerator(y)); } else if(isNull(y)) { return new NullCheckGenerator(op, (PtrExpr) findGenerator(x)); } // Shouldn't matter which we pointer we cast to the other, but if we have a choice, // cast away from a void* to a concrete pointer type GimpleType commonType; if(x.getType().isPointerTo(GimpleVoidType.class)) { commonType = y.getType(); } else { commonType = x.getType(); } PointerTypeStrategy typeStrategy = typeOracle.forPointerType(commonType); GExpr ptrX = findGenerator(x, commonType); GExpr ptrY = findGenerator(y, commonType); return typeStrategy.comparePointers(mv, op, ptrX, ptrY); } private boolean isNull(GimpleExpr expr) { return expr instanceof GimpleConstant && ((GimpleConstant) expr).isNull(); } public GExpr findGenerator(GimpleOp op, List<GimpleExpr> operands, GimpleType expectedType) { switch (op) { case PLUS_EXPR: case MINUS_EXPR: case MULT_EXPR: case RDIV_EXPR: case TRUNC_DIV_EXPR: case EXACT_DIV_EXPR: case TRUNC_MOD_EXPR: case BIT_IOR_EXPR: case BIT_XOR_EXPR: case BIT_AND_EXPR: return findBinOpGenerator(op, operands); case POINTER_PLUS_EXPR: return pointerPlus(operands.get(0), operands.get(1), expectedType); case BIT_NOT_EXPR: return primitive(new BitwiseNot(findPrimitiveGenerator(operands.get(0)))); case LSHIFT_EXPR: case RSHIFT_EXPR: return primitive(new BitwiseShift( op, operands.get(0).getType(), findPrimitiveGenerator(operands.get(0)), findPrimitiveGenerator(operands.get(1)))); case MEM_REF: // Cast the pointer type first, then dereference return memRef((GimpleMemRef) operands.get(0), expectedType); case CONVERT_EXPR: case FIX_TRUNC_EXPR: case FLOAT_EXPR: case PAREN_EXPR: case VAR_DECL: case PARM_DECL: case NOP_EXPR: case INTEGER_CST: case REAL_CST: case STRING_CST: case COMPLEX_CST: case ADDR_EXPR: case ARRAY_REF: case COMPONENT_REF: case BIT_FIELD_REF: case REALPART_EXPR: case IMAGPART_EXPR: return maybeCast(findGenerator(operands.get(0)), expectedType, operands.get(0).getType()); case COMPLEX_EXPR: return new ComplexValue(findPrimitiveGenerator(operands.get(0))); case NEGATE_EXPR: return primitive(new NegativeValue(findPrimitiveGenerator(operands.get(0)))); case TRUTH_NOT_EXPR: return primitive(new LogicalNot(findPrimitiveGenerator(operands.get(0)))); case TRUTH_AND_EXPR: return primitive(new LogicalAnd( findPrimitiveGenerator(operands.get(0)), findPrimitiveGenerator(operands.get(1)))); case TRUTH_OR_EXPR: return primitive(new LogicalOr( findPrimitiveGenerator(operands.get(0)), findPrimitiveGenerator(operands.get(1)))); case TRUTH_XOR_EXPR: return primitive(new LogicalXor( findPrimitiveGenerator(operands.get(0)), findPrimitiveGenerator(operands.get(1)))); case EQ_EXPR: case LT_EXPR: case LE_EXPR: case NE_EXPR: case GT_EXPR: case GE_EXPR: return primitive(new ConditionExpr( findComparisonGenerator(op,operands.get(0), operands.get(1)))); case MAX_EXPR: case MIN_EXPR: return primitive(new MinMaxValue(op, findPrimitiveGenerator(operands.get(0)), findPrimitiveGenerator(operands.get(1)))); case ABS_EXPR: return primitive(new AbsValue( findPrimitiveGenerator(operands.get(0)))); case UNORDERED_EXPR: return primitive(new UnorderedExpr( findPrimitiveGenerator(operands.get(0)), findPrimitiveGenerator(operands.get(1)))); case CONJ_EXPR: return findComplexGenerator(operands.get(0)).conjugate(); default: throw new UnsupportedOperationException("op: " + op); } } private PrimitiveValue primitive(JExpr expr) { return new PrimitiveValue(expr); } private GExpr memRef(GimpleMemRef gimpleExpr, GimpleType expectedType) { GimpleExpr pointer = gimpleExpr.getPointer(); // Case of *&x, which can be simplified to x if(pointer instanceof GimpleAddressOf) { GimpleAddressOf addressOf = (GimpleAddressOf) pointer; return findGenerator(addressOf.getValue(), expectedType); } GimpleIndirectType pointerType = (GimpleIndirectType) pointer.getType(); if(pointerType.getBaseType() instanceof GimpleVoidType) { // We can't dereference a null pointer, so cast the pointer first, THEN dereference return castThenDereference(gimpleExpr, expectedType); } else { return dereferenceThenCast(gimpleExpr, expectedType); } } private GExpr castThenDereference(GimpleMemRef gimpleExpr, GimpleType expectedType) { GimpleExpr pointer = gimpleExpr.getPointer(); GimpleIndirectType pointerType = (GimpleIndirectType) pointer.getType(); GimpleIndirectType expectedPointerType = expectedType.pointerTo(); // Cast from the void pointer type to the "expected" pointer type GExpr ptrExpr = maybeCast(findGenerator(pointer), expectedPointerType, pointerType); PointerTypeStrategy pointerStrategy = typeOracle.forPointerType(expectedPointerType); if(!gimpleExpr.isOffsetZero()) { JExpr offsetInBytes = findPrimitiveGenerator(gimpleExpr.getOffset()); ptrExpr = pointerStrategy.pointerPlus(mv, ptrExpr, offsetInBytes); } return ((PtrExpr) ptrExpr).valueOf(); } private GExpr dereferenceThenCast(GimpleMemRef gimpleExpr, GimpleType expectedType) { GimpleExpr pointer = gimpleExpr.getPointer(); GimpleIndirectType pointerType = (GimpleIndirectType) pointer.getType(); PointerTypeStrategy pointerStrategy = typeOracle.forPointerType(pointerType); GExpr ptrExpr = findGenerator(pointer); if(!gimpleExpr.isOffsetZero()) { JExpr offsetInBytes = findPrimitiveGenerator(gimpleExpr.getOffset()); ptrExpr = pointerStrategy.pointerPlus(mv, ptrExpr, offsetInBytes); } GExpr valueExpr = ((PtrExpr) ptrExpr).valueOf(); return maybeCast(valueExpr, pointerType.getBaseType(), expectedType); } private GExpr pointerPlus(GimpleExpr pointerExpr, GimpleExpr offsetExpr, GimpleType expectedType) { GExpr pointer = findGenerator(pointerExpr); JExpr offsetInBytes = findPrimitiveGenerator(offsetExpr); GimpleType pointerType = pointerExpr.getType(); GExpr result = typeOracle.forPointerType(pointerType).pointerPlus(mv, pointer, offsetInBytes); return maybeCast(result, expectedType, pointerType); } private <T extends GExpr> T findGenerator(GimpleExpr gimpleExpr, Class<T> exprClass) { GExpr expr = findGenerator(gimpleExpr); if(exprClass.isAssignableFrom(expr.getClass())) { return exprClass.cast(expr); } else { throw new InternalCompilerException(String.format("Expected %s for expr %s, found: %s", exprClass.getSimpleName(), gimpleExpr, expr.getClass().getName())); } } public JExpr findPrimitiveGenerator(GimpleExpr gimpleExpr) { // When looking specifically for a value generator, treat a null pointer as zero integer if(gimpleExpr instanceof GimplePrimitiveConstant && gimpleExpr.getType() instanceof GimpleIndirectType) { return Expressions.constantInt(((GimplePrimitiveConstant) gimpleExpr).getValue().intValue()); } PrimitiveValue primitive = findGenerator(gimpleExpr, PrimitiveValue.class); return primitive.getExpr(); } private ComplexValue findComplexGenerator(GimpleExpr gimpleExpr) { return findGenerator(gimpleExpr, ComplexValue.class); } private GExpr findBinOpGenerator(GimpleOp op, List<GimpleExpr> operands) { GimpleExpr x = operands.get(0); GimpleExpr y = operands.get(1); if( x.getType() instanceof GimpleComplexType && y.getType() instanceof GimpleComplexType) { return complexBinOp(op, findComplexGenerator(x), findComplexGenerator(y)); } else if( x.getType() instanceof GimplePrimitiveType && y.getType() instanceof GimplePrimitiveType) { return primitive(new PrimitiveBinOpGenerator(op, findPrimitiveGenerator(x), findPrimitiveGenerator(y))); } throw new UnsupportedOperationException(op.name() + ": " + x.getType() + ", " + y.getType()); } private GExpr complexBinOp(GimpleOp op, ComplexValue cx, ComplexValue cy) { switch (op) { case PLUS_EXPR: return ComplexValues.add(cx, cy); case MINUS_EXPR: return ComplexValues.subtract(cx, cy); case MULT_EXPR: return ComplexValues.multiply(cx, cy); default: throw new UnsupportedOperationException("complex operation: " + op); } } public GExpr forConstant(GimpleConstant constant) { if (constant.getType() instanceof GimpleIndirectType) { // TODO: Treat all pointer constants as null return typeOracle.forPointerType(constant.getType()).nullPointer(); } else if (constant instanceof GimplePrimitiveConstant) { return primitive(new ConstantValue((GimplePrimitiveConstant) constant)); } else if (constant instanceof GimpleComplexConstant) { GimpleComplexConstant complexConstant = (GimpleComplexConstant) constant; return new ComplexValue( forConstant(complexConstant.getReal()), forConstant(complexConstant.getIm())); } else if (constant instanceof GimpleStringConstant) { StringConstant array = new StringConstant(((GimpleStringConstant) constant).getValue()); ArrayExpr arrayExpr = new ArrayExpr(new PrimitiveValueFunction(Type.BYTE_TYPE), array.getLength(), array); return arrayExpr; } else { throw new UnsupportedOperationException("constant: " + constant); } } public TypeStrategy strategyFor(GimpleType type) { return typeOracle.forType(type); } }
jukiewiczm/renjin
tools/gcc-bridge/compiler/src/main/java/org/renjin/gcc/codegen/expr/ExprFactory.java
Java
gpl-3.0
20,321
import { LoremIpsum } from 'lorem-ipsum'; /** * 生成占位符的方法 */ export const lorem = new LoremIpsum({ sentencesPerParagraph: { max: 4, min: 2, }, wordsPerSentence: { max: 16, min: 4, }, });
TRPGEngine/Client
test/lorem.ts
TypeScript
gpl-3.0
230
#include "adminaddmemberwv.h" void AdminAddMemberWV::processItems(){ const QString & type = intro->cgetType(); const QString & nick = bio->cgetField("nick"); const QString & name = bio->cgetField("name"); const QString & surname = bio->cgetField("surname"); const QString & birthDay = bio->cgetField("birthDay"); const QString & phone = bio->cgetField("phone"); const QString & eMail = bio->cgetField("eMail"); const QVector<QString> & hobbyList = hobby->cgetHobby(); hobby->clear(); const QVector<QString> & interestsList = interests->cgetInterests(); interests->clear(); const QVector<Event> & experiencesList = experiences->cgetExperiences(); experiences->clear(); emit endAdd(type, nick, name, surname, birthDay, phone, eMail, hobbyList, interestsList, experiencesList); } AdminAddMemberWV::AdminAddMemberWV(QWidget * parent) : QWizard(parent), intro (new AdminAMWIntro), bio (new AdminAMWBio), hobby (new AdminAMWHobby), interests (new AdminAMWInterests), experiences(new AdminAMWExperiences), end (new AdminAMWEnd) { addPage(intro); addPage(bio); addPage(hobby); addPage(interests); addPage(experiences); addPage(end); setWindowTitle( tr("Wizard Aggiunta Iscritto") ); setFixedSize( sizeHint() ); /* * Devo passare gli argomenti ottenuti a chi se ne occuperà * dopo attraverso la signal */ connect (this, SIGNAL (accepted()), this, SLOT (processItems())); connect (this, SIGNAL (rejected()), this, SIGNAL (endAdd())); } AdminAddMemberWV::~AdminAddMemberWV(){ delete intro; delete bio; delete hobby; delete interests; delete experiences; delete end; }
Polpetta/LinQedIn
adminaddmemberwv.cpp
C++
gpl-3.0
1,979
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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. # # PySCAP 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 PySCAP. If not, see <http://www.gnu.org/licenses/>. import logging from scap.model.oval_5 import PE_SUBSYSTEM_ENUMERATION from scap.model.oval_5.defs.EntityStateType import EntityStateType logger = logging.getLogger(__name__) class EntityStatePeSubsystemType(EntityStateType): MODEL_MAP = { } def get_value_enum(self): return PE_SUBSYSTEM_ENUMERATION
cjaymes/pyscap
src/scap/model/oval_5/defs/windows/EntityStatePeSubsystemType.py
Python
gpl-3.0
1,004
<?php /** * Description * @author Jeff Tickle <jtickle at tux dot appstate dot edu> */ PHPWS_Core::initModClass('sdr', 'CommandMenu.php'); class BrowseOrganizationsMenu extends CommandMenu { protected function setupCommands() { $browse = CommandFactory::getCommand('ClubDirectory'); $this->addCommand('Club Directory', $browse); $create = CommandFactory::getCommand('CreateOrganization'); $this->addCommand('Create New', $create); $apply = CommandFactory::getCommand('ClubRegistrationFormCommand'); $this->addCommand('Register an Organization', $apply); } } ?>
AppStateESS/clubconnect
class/BrowseOrganizationsMenu.php
PHP
gpl-3.0
630
package gov.nasa.gsfc.seadas.processing.general; import com.bc.ceres.swing.TableLayout; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import gov.nasa.gsfc.seadas.processing.utilities.SheetCell; import gov.nasa.gsfc.seadas.processing.utilities.SpreadSheet; import org.esa.beam.framework.ui.ModalDialog; import org.esa.beam.visat.VisatApp; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.StringTokenizer; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 4/29/14 * Time: 1:22 PM * To change this template use File | Settings | File Templates. */ public class CallL3BinDumpAction extends CallCloProgramAction { @Override void displayOutput(final ProcessorModel processorModel) { String output = processorModel.getExecutionLogMessage(); StringTokenizer st = new StringTokenizer(output, "\n"); int numRows = st.countTokens(); String line = st.nextToken(); StringTokenizer stLine = new StringTokenizer(line, " "); String prodName = null; boolean skipFirstLine = false; if (stLine.countTokens() < 14) { prodName = stLine.nextToken(); numRows--; skipFirstLine = true; } if (!skipFirstLine) { st = new StringTokenizer(output, "\n"); } final SheetCell[][] cells = new SheetCell[numRows][14]; int i = 0; while (st.hasMoreElements()) { line = st.nextToken(); stLine = new StringTokenizer(line, " "); int j = 0; while (stLine.hasMoreElements()) { cells[i][j] = new SheetCell(i, j, stLine.nextToken(), null); j++; } i++; } if (skipFirstLine) { cells[0][10] = new SheetCell(0, 10, prodName + " " + cells[0][10].getValue(), null); cells[0][11] = new SheetCell(0, 11, prodName + " " + cells[0][11].getValue(), null); } SpreadSheet sp = new SpreadSheet(cells); final JFrame frame = new JFrame("l3bindump Output"); JPanel content = new JPanel(new BorderLayout()); JButton save = new JButton("Save"); JButton cancel = new JButton("Cancel"); TableLayout buttonPanelLayout = new TableLayout(2); JPanel buttonPanel = new JPanel(buttonPanelLayout); /* * Allows the user to exit the application * from the window manager's dressing. */ frame.addWindowListener(new WindowAdapter() { // public void windowClosing(WindowEvent e) { // System.exit(0); // } }); sp.getScrollPane().getVerticalScrollBar().setAutoscrolls(true); content.add(sp.getScrollPane(), BorderLayout.NORTH); buttonPanel.add(save); buttonPanel.add(cancel); save.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { //To change body of implemented methods use File | Settings | File Templates. String outputFileName = processorModel.getParamValue(processorModel.getPrimaryInputFileOptionName()) + "_l3bindump_output.txt"; saveForSpreadsheet(outputFileName, cells); String message = "l3bindump output is saved in file \n" + outputFileName +"\n" + " in spreadsheet format."; final ModalDialog modalDialog = new ModalDialog(VisatApp.getApp().getApplicationWindow(), "", message, ModalDialog.ID_OK, "test"); final int dialogResult = modalDialog.show(); if (dialogResult != ModalDialog.ID_OK) { } frame.setVisible(false); } }); cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { //To change body of implemented methods use File | Settings | File Templates. frame.setVisible(false); } }); content.add(buttonPanel, BorderLayout.SOUTH); //frame.getContentPane().add(sp.getScrollPane()); frame.getContentPane().add(content); frame.pack(); frame.setVisible(true); } private void saveForSpreadsheet(String outputFileName, SheetCell[][] cells) { String cell, all = new String(); for (int i = 0; i < cells.length; i++) { cell = new String(); for (int j = 0; j < cells[i].length; j++) { cell = cell + cells[i][j].getValue() + "\t"; } all = all + cell + "\n"; } try { final File excelFile = new File(outputFileName); FileWriter fileWriter = null; try { fileWriter = new FileWriter(excelFile); fileWriter.write(all); } finally { if (fileWriter != null) { fileWriter.close(); } } } catch (IOException e) { SeadasLogger.getLogger().warning(outputFileName + " is not created. " + e.getMessage()); } } // public void createSpreadsheet(SheetCell[][] cells) {//throws BiffException, IOException, WriteException { // WritableWorkbook wworkbook; // try { // wworkbook = Workbook.createWorkbook(new File("output.xls")); // WritableSheet wsheet = wworkbook.createSheet("l3bindump output", 0); // jxl.write.Label label; // jxl.write.Number number; // // /** // * Create labels for the worksheet // */ // for (int j = 0; j < cells[0].length; j++) { // label = new jxl.write.Label(0, j, (String) cells[0][j].getValue()); // wsheet.addCell(label); // } // /** // * Create cell values for the worksheet // */ // for (int i = 1; i < cells.length; i++) { // for (int j = 0; j < cells[i].length; j++) { // number = new jxl.write.Number(i, j, new Double((String) cells[i][j].getValue()).doubleValue()); // wsheet.addCell(number); // } // } // wworkbook.write(); // wworkbook.close(); // } catch (Exception ioe) { // //System.out.println(ioe.getMessage()); // // } // //// Workbook workbook = Workbook.getWorkbook(new File("output.xls")); //// //// Sheet sheet = workbook.getSheet(0); //// Cell cell1 = sheet.getCell(0, 2); //// System.out.println(cell1.getContents()); //// Cell cell2 = sheet.getCell(3, 4); //// System.out.println(cell2.getContents()); //// workbook.close(); // } }
marpet/seadas
seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/general/CallL3BinDumpAction.java
Java
gpl-3.0
7,144
<?php /** * Interface to verify results for the tests in codeigniter framework * if a new migration with the test is created, you must create a new test method */ class SigaTest extends PHPUnit_Framework_TestCase { //Contain the expected result with the total failed tests private $EXPECTED_RESULT = 0; /** * Method to create a html file with php code generated by shell script * @param $migration receive a string with the router to the tests */ private function createFileWithHtmlCode($migration) { //Save string results for shell script, this command execute a //php code and return a html code $result = shell_exec("php index.php " . $migration); //Create a html file $myfile = fopen("testfile.html", "w"); //Write shell script result in html created fwrite($myfile, $result); //Close html created fclose($myfile); } /** * Method to read a html code and return a specified line with the * number of tests failed * @param $migration receive a string with the router to the tests * @return an integer with the number of failed tests */ private function readLineWithNumbersOfFailedTests($migration) { //Open a html file with the total error indentified $myfile = fopen("testfile.html", "r"); //Read lines before the line with has failed tests for($i = 0; $i < 25; $i++) fgets($myfile); // Save line with total faileds tests $errorLine = fgets($myfile); //close the file fclose($myfile); //Destroy html file unlink("testfile.html"); //convert string to integer and return total failed tests return intval($errorLine); } /** * Method to create a html with the php script and read this file to search * a total number with errors * @param $migration receive a string with the router to the tests */ private function principalFunction($migration) { $this->createFileWithHtmlCode($migration); $this->assertEquals($this->readLineWithNumbersOfFailedTests($migration),$this->EXPECTED_RESULT); } /* Auth tests */ //@test public function testUser() { $this->principalFunction("user_test"); } //@test public function testLogin() { $this->principalFunction("login_test"); } //@test public function testPermission() { $this->principalFunction("permission_test"); } //@test public function testGroup() { $this->principalFunction("group_test"); } //@test public function testModule() { $this->principalFunction("module_test"); } /* Program tests */ //@test public function testDepartment() { $this->principalFunction("department_test"); } //@test public function testEmployee() { $this->principalFunction("employee_test"); } //@test public function testFunction() { $this->principalFunction("function_test"); } //@test public function testSector() { $this->principalFunction("sector_test"); } //@test public function testCourse() { $this->principalFunction("course_test"); } //@test public function testSelectionProcess() { $this->principalFunction("selection_process_test"); } //@test public function testSelectionSettings() { $this->principalFunction("process_settings_test"); } //@test public function testProcessPhase() { $this->principalFunction("process_phase_test"); } /* Notification tests */ //@test public function testEmailNotification() { $this->principalFunction("email_notification_test"); } //@test public function testRestorePasswordEmail() { $this->principalFunction("restore_password_email_test"); } //@test public function testEnrolled_student_email() { $this->principalFunction("enrolled_student_email_test"); } //@test public function testSecretaryEmailNotification() { $this->principalFunction("secretary_email_notification_test"); } //@test public function testBarNotification() { $this->principalFunction("bar_notification_test"); } /* Student tests */ //@test public function testStudentRegistration() { $this->principalFunction("student_registration_test"); } //@test public function testPhone() { $this->principalFunction("phone_test"); } /* Secretary tests */ //@test public function testClassHour() { $this->principalFunction("classHour_test"); } } ?>
Gerencia-de-Configuracao-Software/SiGA
www/SiGA/test.php
PHP
gpl-3.0
4,269
using System; using System.Drawing; using LeagueSharp.Common; using VayneHunter_Reborn.External; using VayneHunter_Reborn.External.Cleanser; using VayneHunter_Reborn.External.ProfileSelector; using VayneHunter_Reborn.External.Translation; using Activator = VayneHunter_Reborn.External.Activator.Activator; namespace VayneHunter_Reborn.Utility.MenuUtility { class MenuGenerator { public static void OnLoad() { var RootMenu = Variables.Menu; var OWMenu = new Menu("[VHR] Orbwalker", "dz191.vhr.orbwalker"); { Variables.Orbwalker = new Orbwalking.Orbwalker(OWMenu); RootMenu.AddSubMenu(OWMenu); } var TSMenu = new Menu("[VHR] TS", "dz191.vhr.ts"); { TargetSelector.AddToMenu(TSMenu); RootMenu.AddSubMenu(TSMenu); } var comboMenu = new Menu("[VHR] Combo", "dz191.vhr.combo"); { var manaMenu = new Menu("Mana Manager", "dz191.vhr.combo.mm"); { manaMenu.AddManaLimiter(Enumerations.Skills.Q, Orbwalking.OrbwalkingMode.Combo); manaMenu.AddManaLimiter(Enumerations.Skills.E, Orbwalking.OrbwalkingMode.Combo); manaMenu.AddManaLimiter(Enumerations.Skills.R, Orbwalking.OrbwalkingMode.Combo); comboMenu.AddSubMenu(manaMenu); } comboMenu.AddSkill(Enumerations.Skills.Q, Orbwalking.OrbwalkingMode.Combo); comboMenu.AddSkill(Enumerations.Skills.E, Orbwalking.OrbwalkingMode.Combo); comboMenu.AddSkill(Enumerations.Skills.R, Orbwalking.OrbwalkingMode.Combo, false); comboMenu.AddSlider("dz191.vhr.combo.r.minenemies", "Min. R Enemies", new Tuple<int, int, int>(2, 1, 5)).SetTooltip("Minimum enemies in range for R"); comboMenu.AddBool("dz191.vhr.combo.q.2wstacks", "Only Q if 2W Stacks on Target").SetTooltip("Will Q for 3rd proc only. Enable if you want AA AA Q AA"); RootMenu.AddSubMenu(comboMenu); } var harassMenu = new Menu("[VHR] Harass", "dz191.vhr.mixed"); { var manaMenu = new Menu("Mana Manager", "dz191.vhr.mixed.mm"); { manaMenu.AddManaLimiter(Enumerations.Skills.Q, Orbwalking.OrbwalkingMode.Mixed); manaMenu.AddManaLimiter(Enumerations.Skills.E, Orbwalking.OrbwalkingMode.Mixed); harassMenu.AddSubMenu(manaMenu); } harassMenu.AddSkill(Enumerations.Skills.Q, Orbwalking.OrbwalkingMode.Mixed); harassMenu.AddSkill(Enumerations.Skills.E, Orbwalking.OrbwalkingMode.Mixed); harassMenu.AddBool("dz191.vhr.mixed.q.2wstacks", "Only Q if 2W Stacks on Target").SetTooltip("Will Q for 3rd proc only. Enable if you want AA AA Q AA"); harassMenu.AddBool("dz191.vhr.mixed.ethird", "Use E for Third Proc").SetTooltip("Uses E for 3rd W proc. Enable if you want AA Q AA E"); RootMenu.AddSubMenu(harassMenu); } var farmMenu = new Menu("[VHR] Farm", "dz191.vhr.farm"); { farmMenu.AddSkill(Enumerations.Skills.Q, Orbwalking.OrbwalkingMode.LaneClear).SetTooltip("Q Laneclear"); farmMenu.AddManaLimiter(Enumerations.Skills.Q, Orbwalking.OrbwalkingMode.LaneClear, 45, true); farmMenu.AddSkill(Enumerations.Skills.Q, Orbwalking.OrbwalkingMode.LastHit); farmMenu.AddManaLimiter(Enumerations.Skills.Q, Orbwalking.OrbwalkingMode.LastHit, 45, true).SetTooltip("Q Lasthit"); farmMenu.AddBool("dz191.vhr.farm.condemnjungle", "Use E to condemn jungle mobs", true).SetTooltip("Use Condemn against jungle creeps"); farmMenu.AddBool("dz191.vhr.farm.qjungle", "Use Q against jungle mobs", true).SetTooltip("Use Tumble in the Jungle"); RootMenu.AddSubMenu(farmMenu); } var miscMenu = new Menu("[VHR] Misc", "dz191.vhr.misc"); { var miscQMenu = new Menu("Misc - Q (Tumble)", "dz191.vhr.misc.tumble"); { miscQMenu.AddStringList("dz191.vhr.misc.condemn.qlogic", "Q Logic", new[] { "Reborn", "Normal", "Kite melees", "Kurisu" }).SetTooltip("The Tumble Method. Reborn = Safest & Besto"); miscQMenu.AddBool("dz191.vhr.mixed.mirinQ", "Q to Wall when Possible (Mirin Mode)", true).SetTooltip("Will Q to walls when possible for really fast bursts!"); miscQMenu.AddBool("dz191.vhr.misc.tumble.smartq", "Try to QE when possible").SetTooltip("Will try to do the Tumble + Condemn combo when possible"); //Done miscQMenu.AddKeybind("dz191.vhr.misc.tumble.noaastealthex", "Don't AA while stealthed", new Tuple<uint, KeyBindType>('K', KeyBindType.Toggle)).SetTooltip("Will not AA while you are in Ult+Q"); //Done miscQMenu.AddBool("dz191.vhr.misc.tumble.noqenemies", "Don't Q into enemies").SetTooltip("If true it will not Q into 2 or more enemies"); //done miscQMenu.AddBool("dz191.vhr.misc.tumble.dynamicqsafety", "Use dynamic Q Safety Distance").SetTooltip("Use the enemy AA range as the 'Don't Q into enemies' safety distance?"); //done miscQMenu.AddBool("dz191.vhr.misc.tumble.qspam", "Ignore Q checks").SetTooltip("Ignores 'Safe Q' and 'Don't Q into enemies' checks"); //Done miscQMenu.AddBool("dz191.vhr.misc.tumble.qinrange", "Q For KS", true).SetTooltip("Uses Q to KS by Qing in range if you can kill with Q + AA"); //Done miscQMenu.AddText("dz191.vhr.misc.tumble.walltumble.warning", "Click and hold Walltumble") .SetFontStyle(FontStyle.Bold, SharpDX.Color.Red); miscQMenu.AddText("dz191.vhr.misc.tumble.walltumble.warning.2", "It will walk to the nearest Tumble spot and Tumble") .SetFontStyle(FontStyle.Bold, SharpDX.Color.Red); miscQMenu.AddKeybind("dz191.vhr.misc.tumble.walltumble", "Tumble Over Wall (WallTumble)", new Tuple<uint, KeyBindType>('Y', KeyBindType.Press)).SetTooltip("DISABLED! (For security reasons)! Tumbles over wall."); miscMenu.AddSubMenu(miscQMenu); } var miscEMenu = new Menu("Misc - E (Condemn)", "dz191.vhr.misc.condemn"); { miscEMenu.AddStringList("dz191.vhr.misc.condemn.condemnmethod", "Condemn Method", new[] { "VH Revolution", "VH Reborn", "Marksman/Gosu", "Shine#" }).SetTooltip("The condemn method. Recommended: Revolution > Shine/Reborn > Marksman"); miscEMenu.AddSlider("dz191.vhr.misc.condemn.pushdistance", "E Push Distance", new Tuple<int, int, int>(420, 350, 470)).SetTooltip("The E Knockback distance the script uses. Recommended: 400-430"); miscEMenu.AddSlider("dz191.vhr.misc.condemn.accuracy", "Accuracy (Revolution Only)", new Tuple<int, int, int>(33, 1, 100)).SetTooltip("The Condemn Accuracy. Recommended value: 25-45"); miscEMenu.AddItem( new MenuItem("dz191.vhr.misc.condemn.enextauto", "E Next Auto").SetValue( new KeyBind('T', KeyBindType.Toggle))).SetTooltip("If On it will fire E after the next Auto Attack is landed"); miscEMenu.AddBool("dz191.vhr.misc.condemn.onlystuncurrent", "Only stun current target").SetTooltip("Only uses E on the current orbwalker target"); //done miscEMenu.AddBool("dz191.vhr.misc.condemn.autoe", "Auto E").SetTooltip("Uses E whenever possible"); //Done miscEMenu.AddBool("dz191.vhr.misc.condemn.eks", "Smart E KS").SetTooltip("Uses E to KS when they have 2 W Stacks and they can be killed by W + E"); //Done miscEMenu.AddSlider("dz191.vhr.misc.condemn.noeaa", "Don't E if Target can be killed in X AA", new Tuple<int, int, int>(1, 0, 4)).SetTooltip("Does not condemn if you can kill the target in X Auto Attacks"); //Done miscEMenu.AddBool("dz191.vhr.misc.condemn.trinketbush", "Trinket Bush on Condemn", true).SetTooltip("Uses Blue / Yellow trinket on bush if you condemn in there."); miscEMenu.AddBool("dz191.vhr.misc.condemn.lowlifepeel", "Peel with E when low health").SetTooltip("Uses E on melee enemies if your health < 15%"); miscEMenu.AddBool("dz191.vhr.misc.condemn.condemnflag", "Condemn to J4 flag", true).SetTooltip("Tries to make the assembly condemn on J4 Flags"); miscEMenu.AddBool("dz191.vhr.misc.condemn.noeturret", "No E Under enemy turret").SetTooltip("Does not condemn if you are under their turret"); miscMenu.AddSubMenu(miscEMenu); } var miscGeneralSubMenu = new Menu("Misc - General", "dz191.vhr.misc.general"); //Done { miscGeneralSubMenu.AddBool("dz191.vhr.misc.general.antigp", "Anti Gapcloser").SetTooltip("Uses E to stop gapclosers"); miscGeneralSubMenu.AddBool("dz191.vhr.misc.general.interrupt", "Interrupter", true).SetTooltip("Uses E to interrupt skills"); miscGeneralSubMenu.AddSlider("dz191.vhr.misc.general.antigpdelay", "Anti Gapcloser Delay (ms)", new Tuple<int, int, int>(0, 0, 1000)).SetTooltip("Sets a delay before the Condemn for Antigapcloser is casted."); miscGeneralSubMenu.AddBool("dz191.vhr.misc.general.specialfocus", "Focus targets with 2 W marks").SetTooltip("Tries to focus targets that have 2W Rings on them"); miscGeneralSubMenu.AddBool("dz191.vhr.misc.general.reveal", "Stealth Reveal (Pink Ward / Lens)").SetTooltip("Reveals stealthed champions using Pink Wards / Lenses"); miscGeneralSubMenu.AddBool("dz191.vhr.misc.general.disablemovement", "Disable Orbwalker Movement").SetTooltip("Disables the Orbwalker movements as long as it's active"); miscGeneralSubMenu.AddBool("dz191.vhr.misc.general.disableattk", "Disable Orbwalker Attack").SetTooltip("Disables the Orbwalker attacks as long as it's active"); miscMenu.AddSubMenu(miscGeneralSubMenu); } RootMenu.AddSubMenu(miscMenu); } var drawMenu = new Menu("[VHR] Drawings", "dz191.vhr.draw"); { drawMenu.AddBool("dz191.vhr.draw.spots", "Draw Spots", true); drawMenu.AddBool("dz191.vhr.draw.range", "Draw Enemy Ranges", true); drawMenu.AddBool("dz191.vhr.draw.qpos", "Reborn Q Position (Debug)"); RootMenu.AddSubMenu(drawMenu); } CustomAntigapcloser.BuildMenu(RootMenu); Activator.LoadMenu(); Cleanser.LoadMenu(RootMenu); ProfileSelector.OnLoad(RootMenu); TranslationInterface.OnLoad(RootMenu); RootMenu.AddToMainMenu(); } } }
654955321/HY_Recommend
英雄脚本/【红叶推介】DZ191 薇恩 重做/Utility/MenuUtility/MenuGenerator.cs
C#
gpl-3.0
11,358
package com.dechcaudron.xtreaming.model; import com.dechcaudron.xtreaming.repositoryInterface.IRepositoryAuthToken; public class Repository { private final int repoLocalId; private final int repoTypeCode; private final String domainURL; private final int port; private final boolean requireSSL; private final String username; private final IRepositoryAuthToken authenticationToken; public Repository(int repoLocalId, int repoTypeCode, String domainURL, int port, boolean requireSSL, String username, IRepositoryAuthToken authenticationToken) { this.repoLocalId = repoLocalId; this.repoTypeCode = repoTypeCode; this.domainURL = domainURL; this.port = port; this.requireSSL = requireSSL; this.username = username; this.authenticationToken = authenticationToken; } public int getRepoLocalId() { return repoLocalId; } public int getRepoTypeCode() { return repoTypeCode; } public String getDomainURL() { return domainURL; } public int getPort() { return port; } public boolean requiresSSL() { return requireSSL; } public String getUsername() { return username; } public IRepositoryAuthToken getAuthenticationToken() { return authenticationToken; } @Override public String toString() { return "[LocalId " + repoLocalId + "] [RepoType " + repoTypeCode + "] " + domainURL + ":" + port +" "+ (requireSSL ? "" : "NO ") + "SSL Username: " + username; } }
Dechcaudron/xtreaming-app-android
Xtreaming/app/src/main/java/com/dechcaudron/xtreaming/model/Repository.java
Java
gpl-3.0
1,615
package com.badlogic.gdx.math; public class Interpolation$BounceOut extends Interpolation { final float[] heights; final float[] widths; public Interpolation$BounceOut(int paramInt) { if ((paramInt < 2) || (paramInt > 5)) throw new IllegalArgumentException("bounces cannot be < 2 or > 5: " + paramInt); this.widths = new float[paramInt]; this.heights = new float[paramInt]; this.heights[0] = 1.0F; switch (paramInt) { default: case 2: case 3: case 4: case 5: } while (true) { float[] arrayOfFloat = this.widths; arrayOfFloat[0] = (2.0F * arrayOfFloat[0]); return; this.widths[0] = 0.6F; this.widths[1] = 0.4F; this.heights[1] = 0.33F; continue; this.widths[0] = 0.4F; this.widths[1] = 0.4F; this.widths[2] = 0.2F; this.heights[1] = 0.33F; this.heights[2] = 0.1F; continue; this.widths[0] = 0.34F; this.widths[1] = 0.34F; this.widths[2] = 0.2F; this.widths[3] = 0.15F; this.heights[1] = 0.26F; this.heights[2] = 0.11F; this.heights[3] = 0.03F; continue; this.widths[0] = 0.3F; this.widths[1] = 0.3F; this.widths[2] = 0.2F; this.widths[3] = 0.1F; this.widths[4] = 0.1F; this.heights[1] = 0.45F; this.heights[2] = 0.3F; this.heights[3] = 0.15F; this.heights[4] = 0.06F; } } public Interpolation$BounceOut(float[] paramArrayOfFloat1, float[] paramArrayOfFloat2) { if (paramArrayOfFloat1.length != paramArrayOfFloat2.length) throw new IllegalArgumentException("Must be the same number of widths and heights."); this.widths = paramArrayOfFloat1; this.heights = paramArrayOfFloat2; } public float apply(float paramFloat) { float f1 = paramFloat + this.widths[0] / 2.0F; int i = this.widths.length; float f2 = f1; int j = 0; float f3 = 0.0F; while (true) { float f4 = 0.0F; if (j < i) { f3 = this.widths[j]; if (f2 <= f3) f4 = this.heights[j]; } else { float f5 = f2 / f3; float f6 = f5 * (f4 * (4.0F / f3)); return 1.0F - f3 * (f6 - f5 * f6); } f2 -= f3; j++; } } } /* Location: classes_dex2jar.jar * Qualified Name: com.badlogic.gdx.math.Interpolation.BounceOut * JD-Core Version: 0.6.2 */
isnuryusuf/ingress-indonesia-dev
apk/classes-ekstartk/com/badlogic/gdx/math/Interpolation$BounceOut.java
Java
gpl-3.0
2,430
<?php /** * Created by PhpStorm. * User: Jon * Date: 6/24/2016 * Time: 10:08 PM */ //usual post check. if ($_SERVER['REQUEST_METHOD'] != 'POST') { header('HTTP/1.1 405 Method not allowed'); header('Allow: POST'); header('Content-Type: text/html; charset=UTF-8'); exit('Invalid request, expecting POST.'); } require "../authentication/cookieHeaders.php"; $data = json_decode(file_get_contents('php://input'), true); if (isset($_FILES)) { $conn = require "../databaseManager_write.php"; //update DB with file info if (isset($_FILES['json'])) { if ($_FILES['json']['size'] > 0) { $pdfFile = $_FILES['json']; $pdfURL = doPDFUpload($pdfFile); if ($pdfURL != false) { try { //SQL to update the DB// echo "File was successfully uploaded. URL: $pdfURL"; } catch (PDOException $e) { echo "DB error: " . $e->getMessage(); } } else { echo "File upload returned as false. (Check filetype or image mime) \n"; } } else { echo "File had a size of zero. \n"; } } $conn = null; } function doPDFUpload($PDFFile) { //filter by allowed image types and MIMES $allowedExtensions = array("json", "JSON"); $allowedPDFMimes = array("application/json"); $pdfExtension = pathinfo($PDFFile['name'], PATHINFO_EXTENSION); $fileType = $PDFFile['type']; $fileName = pathinfo($PDFFile['name'], PATHINFO_BASENAME); if (in_array($pdfExtension, $allowedExtensions) && (in_array($fileType, $allowedPDFMimes))) { //assign the image to a location. //TODO: Pick a location in the server. //Location is what isstored in the DB and is a realitive URL to the pdf $fileLocation = "../../letterPDFs/" . $fileName; //an absolute route to the file. //TODO: finish this route up $uploadLocation = "C:/xampp/htdocs/" . $fileName; move_uploaded_file($PDFFile['tmp_name'], $uploadLocation); return $fileLocation; } else { return false; } }
WaddellEngineering/HarMANi
app/php/siteReview/currently unused/jsonFileUpload.php
PHP
gpl-3.0
2,173
<?php /** * Base class that represents a row from the 'sf_guard_user_group' table. * * * * This class was autogenerated by Propel 1.4.2 on: * * Tue Jan 8 23:27:28 2013 * * @package plugins.sfGuardPlugin.lib.model.om */ abstract class BasesfGuardUserGroup extends BaseObject implements Persistent { /** * The Peer class. * Instance provides a convenient way of calling static methods on a class * that calling code may not be able to identify. * @var sfGuardUserGroupPeer */ protected static $peer; /** * The value for the user_id field. * @var int */ protected $user_id; /** * The value for the group_id field. * @var int */ protected $group_id; /** * @var sfGuardUser */ protected $asfGuardUser; /** * @var sfGuardGroup */ protected $asfGuardGroup; /** * Flag to prevent endless save loop, if this object is referenced * by another object which falls in this transaction. * @var boolean */ protected $alreadyInSave = false; /** * Flag to prevent endless validation loop, if this object is referenced * by another object which falls in this transaction. * @var boolean */ protected $alreadyInValidation = false; // symfony behavior const PEER = 'sfGuardUserGroupPeer'; /** * Get the [user_id] column value. * * @return int */ public function getUserId() { return $this->user_id; } /** * Get the [group_id] column value. * * @return int */ public function getGroupId() { return $this->group_id; } /** * Set the value of [user_id] column. * * @param int $v new value * @return sfGuardUserGroup The current object (for fluent API support) */ public function setUserId($v) { if ($v !== null) { $v = (int) $v; } if ($this->user_id !== $v) { $this->user_id = $v; $this->modifiedColumns[] = sfGuardUserGroupPeer::USER_ID; } if ($this->asfGuardUser !== null && $this->asfGuardUser->getId() !== $v) { $this->asfGuardUser = null; } return $this; } // setUserId() /** * Set the value of [group_id] column. * * @param int $v new value * @return sfGuardUserGroup The current object (for fluent API support) */ public function setGroupId($v) { if ($v !== null) { $v = (int) $v; } if ($this->group_id !== $v) { $this->group_id = $v; $this->modifiedColumns[] = sfGuardUserGroupPeer::GROUP_ID; } if ($this->asfGuardGroup !== null && $this->asfGuardGroup->getId() !== $v) { $this->asfGuardGroup = null; } return $this; } // setGroupId() /** * Indicates whether the columns in this object are only set to default values. * * This method can be used in conjunction with isModified() to indicate whether an object is both * modified _and_ has some values set which are non-default. * * @return boolean Whether the columns in this object are only been set with default values. */ public function hasOnlyDefaultValues() { // otherwise, everything was equal, so return TRUE return true; } // hasOnlyDefaultValues() /** * Hydrates (populates) the object variables with values from the database resultset. * * An offset (0-based "start column") is specified so that objects can be hydrated * with a subset of the columns in the resultset rows. This is needed, for example, * for results of JOIN queries where the resultset row includes columns from two or * more tables. * * @param array $row The row returned by PDOStatement->fetch(PDO::FETCH_NUM) * @param int $startcol 0-based offset column which indicates which restultset column to start with. * @param boolean $rehydrate Whether this object is being re-hydrated from the database. * @return int next starting column * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. */ public function hydrate($row, $startcol = 0, $rehydrate = false) { try { $this->user_id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; $this->group_id = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null; $this->resetModified(); $this->setNew(false); if ($rehydrate) { $this->ensureConsistency(); } // FIXME - using NUM_COLUMNS may be clearer. return $startcol + 2; // 2 = sfGuardUserGroupPeer::NUM_COLUMNS - sfGuardUserGroupPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { throw new PropelException("Error populating sfGuardUserGroup object", $e); } } /** * Checks and repairs the internal consistency of the object. * * This method is executed after an already-instantiated object is re-hydrated * from the database. It exists to check any foreign keys to make sure that * the objects related to the current object are correct based on foreign key. * * You can override this method in the stub class, but you should always invoke * the base method from the overridden method (i.e. parent::ensureConsistency()), * in case your model changes. * * @throws PropelException */ public function ensureConsistency() { if ($this->asfGuardUser !== null && $this->user_id !== $this->asfGuardUser->getId()) { $this->asfGuardUser = null; } if ($this->asfGuardGroup !== null && $this->group_id !== $this->asfGuardGroup->getId()) { $this->asfGuardGroup = null; } } // ensureConsistency /** * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. * * This will only work if the object has been saved and has a valid primary key set. * * @param boolean $deep (optional) Whether to also de-associated any related objects. * @param PropelPDO $con (optional) The PropelPDO connection to use. * @return void * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db */ public function reload($deep = false, PropelPDO $con = null) { if ($this->isDeleted()) { throw new PropelException("Cannot reload a deleted object."); } if ($this->isNew()) { throw new PropelException("Cannot reload an unsaved object."); } if ($con === null) { $con = Propel::getConnection(sfGuardUserGroupPeer::DATABASE_NAME, Propel::CONNECTION_READ); } // We don't need to alter the object instance pool; we're just modifying this instance // already in the pool. $stmt = sfGuardUserGroupPeer::doSelectStmt($this->buildPkeyCriteria(), $con); $row = $stmt->fetch(PDO::FETCH_NUM); $stmt->closeCursor(); if (!$row) { throw new PropelException('Cannot find matching row in the database to reload object values.'); } $this->hydrate($row, 0, true); // rehydrate if ($deep) { // also de-associate any related objects? $this->asfGuardUser = null; $this->asfGuardGroup = null; } // if (deep) } /** * Removes this object from datastore and sets delete attribute. * * @param PropelPDO $con * @return void * @throws PropelException * @see BaseObject::setDeleted() * @see BaseObject::isDeleted() */ public function delete(PropelPDO $con = null) { if ($this->isDeleted()) { throw new PropelException("This object has already been deleted."); } if ($con === null) { $con = Propel::getConnection(sfGuardUserGroupPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); try { $ret = $this->preDelete($con); // symfony_behaviors behavior foreach (sfMixer::getCallables('BasesfGuardUserGroup:delete:pre') as $callable) { if (call_user_func($callable, $this, $con)) { $con->commit(); return; } } if ($ret) { sfGuardUserGroupPeer::doDelete($this, $con); $this->postDelete($con); // symfony_behaviors behavior foreach (sfMixer::getCallables('BasesfGuardUserGroup:delete:post') as $callable) { call_user_func($callable, $this, $con); } $this->setDeleted(true); $con->commit(); } else { $con->commit(); } } catch (PropelException $e) { $con->rollBack(); throw $e; } } /** * Persists this object to the database. * * If the object is new, it inserts it; otherwise an update is performed. * All modified related objects will also be persisted in the doSave() * method. This method wraps all precipitate database operations in a * single transaction. * * @param PropelPDO $con * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException * @see doSave() */ public function save(PropelPDO $con = null) { if ($this->isDeleted()) { throw new PropelException("You cannot save an object that has been deleted."); } if ($con === null) { $con = Propel::getConnection(sfGuardUserGroupPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); $isInsert = $this->isNew(); try { $ret = $this->preSave($con); // symfony_behaviors behavior foreach (sfMixer::getCallables('BasesfGuardUserGroup:save:pre') as $callable) { if (is_integer($affectedRows = call_user_func($callable, $this, $con))) { $con->commit(); return $affectedRows; } } if ($isInsert) { $ret = $ret && $this->preInsert($con); } else { $ret = $ret && $this->preUpdate($con); } if ($ret) { $affectedRows = $this->doSave($con); if ($isInsert) { $this->postInsert($con); } else { $this->postUpdate($con); } $this->postSave($con); // symfony_behaviors behavior foreach (sfMixer::getCallables('BasesfGuardUserGroup:save:post') as $callable) { call_user_func($callable, $this, $con, $affectedRows); } sfGuardUserGroupPeer::addInstanceToPool($this); } else { $affectedRows = 0; } $con->commit(); return $affectedRows; } catch (PropelException $e) { $con->rollBack(); throw $e; } } /** * Performs the work of inserting or updating the row in the database. * * If the object is new, it inserts it; otherwise an update is performed. * All related objects are also updated in this method. * * @param PropelPDO $con * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException * @see save() */ protected function doSave(PropelPDO $con) { $affectedRows = 0; // initialize var to track total num of affected rows if (!$this->alreadyInSave) { $this->alreadyInSave = true; // We call the save method on the following object(s) if they // were passed to this object by their coresponding set // method. This object relates to these object(s) by a // foreign key reference. if ($this->asfGuardUser !== null) { if ($this->asfGuardUser->isModified() || $this->asfGuardUser->isNew()) { $affectedRows += $this->asfGuardUser->save($con); } $this->setsfGuardUser($this->asfGuardUser); } if ($this->asfGuardGroup !== null) { if ($this->asfGuardGroup->isModified() || $this->asfGuardGroup->isNew()) { $affectedRows += $this->asfGuardGroup->save($con); } $this->setsfGuardGroup($this->asfGuardGroup); } // If this object has been modified, then save it to the database. if ($this->isModified()) { if ($this->isNew()) { $pk = sfGuardUserGroupPeer::doInsert($this, $con); $affectedRows += 1; // we are assuming that there is only 1 row per doInsert() which // should always be true here (even though technically // BasePeer::doInsert() can insert multiple rows). $this->setNew(false); } else { $affectedRows += sfGuardUserGroupPeer::doUpdate($this, $con); } $this->resetModified(); // [HL] After being saved an object is no longer 'modified' } $this->alreadyInSave = false; } return $affectedRows; } // doSave() /** * Array of ValidationFailed objects. * @var array ValidationFailed[] */ protected $validationFailures = array(); /** * Gets any ValidationFailed objects that resulted from last call to validate(). * * * @return array ValidationFailed[] * @see validate() */ public function getValidationFailures() { return $this->validationFailures; } /** * Validates the objects modified field values and all objects related to this table. * * If $columns is either a column name or an array of column names * only those columns are validated. * * @param mixed $columns Column name or an array of column names. * @return boolean Whether all columns pass validation. * @see doValidate() * @see getValidationFailures() */ public function validate($columns = null) { $res = $this->doValidate($columns); if ($res === true) { $this->validationFailures = array(); return true; } else { $this->validationFailures = $res; return false; } } /** * This function performs the validation work for complex object models. * * In addition to checking the current object, all related objects will * also be validated. If all pass then <code>true</code> is returned; otherwise * an aggreagated array of ValidationFailed objects will be returned. * * @param array $columns Array of column names to validate. * @return mixed <code>true</code> if all validations pass; array of <code>ValidationFailed</code> objets otherwise. */ protected function doValidate($columns = null) { if (!$this->alreadyInValidation) { $this->alreadyInValidation = true; $retval = null; $failureMap = array(); // We call the validate method on the following object(s) if they // were passed to this object by their coresponding set // method. This object relates to these object(s) by a // foreign key reference. if ($this->asfGuardUser !== null) { if (!$this->asfGuardUser->validate($columns)) { $failureMap = array_merge($failureMap, $this->asfGuardUser->getValidationFailures()); } } if ($this->asfGuardGroup !== null) { if (!$this->asfGuardGroup->validate($columns)) { $failureMap = array_merge($failureMap, $this->asfGuardGroup->getValidationFailures()); } } if (($retval = sfGuardUserGroupPeer::doValidate($this, $columns)) !== true) { $failureMap = array_merge($failureMap, $retval); } $this->alreadyInValidation = false; } return (!empty($failureMap) ? $failureMap : true); } /** * Retrieves a field from the object by name passed in as a string. * * @param string $name name * @param string $type The type of fieldname the $name is of: * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM * @return mixed Value of field. */ public function getByName($name, $type = BasePeer::TYPE_PHPNAME) { $pos = sfGuardUserGroupPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); $field = $this->getByPosition($pos); return $field; } /** * Retrieves a field from the object by Position as specified in the xml schema. * Zero-based. * * @param int $pos position in xml schema * @return mixed Value of field at $pos */ public function getByPosition($pos) { switch($pos) { case 0: return $this->getUserId(); break; case 1: return $this->getGroupId(); break; default: return null; break; } // switch() } /** * Exports the object as an array. * * You can specify the key type of the array by passing one of the class * type constants. * * @param string $keyType (optional) One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. Defaults to BasePeer::TYPE_PHPNAME. * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. * @return an associative array containing the field names (as keys) and field values */ public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true) { $keys = sfGuardUserGroupPeer::getFieldNames($keyType); $result = array( $keys[0] => $this->getUserId(), $keys[1] => $this->getGroupId(), ); return $result; } /** * Sets a field from the object by name passed in as a string. * * @param string $name peer name * @param mixed $value field value * @param string $type The type of fieldname the $name is of: * one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM * @return void */ public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) { $pos = sfGuardUserGroupPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); return $this->setByPosition($pos, $value); } /** * Sets a field from the object by Position as specified in the xml schema. * Zero-based. * * @param int $pos position in xml schema * @param mixed $value field value * @return void */ public function setByPosition($pos, $value) { switch($pos) { case 0: $this->setUserId($value); break; case 1: $this->setGroupId($value); break; } // switch() } /** * Populates the object using an array. * * This is particularly useful when populating an object from one of the * request arrays (e.g. $_POST). This method goes through the column * names, checking to see whether a matching key exists in populated * array. If so the setByName() method is called for that column. * * You can specify the key type of the array by additionally passing one * of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. * The default key type is the column's phpname (e.g. 'AuthorId') * * @param array $arr An array to populate the object from. * @param string $keyType The type of keys the array uses. * @return void */ public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) { $keys = sfGuardUserGroupPeer::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) $this->setUserId($arr[$keys[0]]); if (array_key_exists($keys[1], $arr)) $this->setGroupId($arr[$keys[1]]); } /** * Build a Criteria object containing the values of all modified columns in this object. * * @return Criteria The Criteria object containing all modified values. */ public function buildCriteria() { $criteria = new Criteria(sfGuardUserGroupPeer::DATABASE_NAME); if ($this->isColumnModified(sfGuardUserGroupPeer::USER_ID)) $criteria->add(sfGuardUserGroupPeer::USER_ID, $this->user_id); if ($this->isColumnModified(sfGuardUserGroupPeer::GROUP_ID)) $criteria->add(sfGuardUserGroupPeer::GROUP_ID, $this->group_id); return $criteria; } /** * Builds a Criteria object containing the primary key for this object. * * Unlike buildCriteria() this method includes the primary key values regardless * of whether or not they have been modified. * * @return Criteria The Criteria object containing value(s) for primary key(s). */ public function buildPkeyCriteria() { $criteria = new Criteria(sfGuardUserGroupPeer::DATABASE_NAME); $criteria->add(sfGuardUserGroupPeer::USER_ID, $this->user_id); $criteria->add(sfGuardUserGroupPeer::GROUP_ID, $this->group_id); return $criteria; } /** * Returns the composite primary key for this object. * The array elements will be in same order as specified in XML. * @return array */ public function getPrimaryKey() { $pks = array(); $pks[0] = $this->getUserId(); $pks[1] = $this->getGroupId(); return $pks; } /** * Set the [composite] primary key. * * @param array $keys The elements of the composite key (order must match the order in XML file). * @return void */ public function setPrimaryKey($keys) { $this->setUserId($keys[0]); $this->setGroupId($keys[1]); } /** * Sets contents of passed object to values from current object. * * If desired, this method can also make copies of all associated (fkey referrers) * objects. * * @param object $copyObj An object of sfGuardUserGroup (or compatible) type. * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. * @throws PropelException */ public function copyInto($copyObj, $deepCopy = false) { $copyObj->setUserId($this->user_id); $copyObj->setGroupId($this->group_id); $copyObj->setNew(true); } /** * Makes a copy of this object that will be inserted as a new row in table when saved. * It creates a new object filling in the simple attributes, but skipping any primary * keys that are defined for the table. * * If desired, this method can also make copies of all associated (fkey referrers) * objects. * * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. * @return sfGuardUserGroup Clone of current object. * @throws PropelException */ public function copy($deepCopy = false) { // we use get_class(), because this might be a subclass $clazz = get_class($this); $copyObj = new $clazz(); $this->copyInto($copyObj, $deepCopy); return $copyObj; } /** * Returns a peer instance associated with this om. * * Since Peer classes are not to have any instance attributes, this method returns the * same instance for all member of this class. The method could therefore * be static, but this would prevent one from overriding the behavior. * * @return sfGuardUserGroupPeer */ public function getPeer() { if (self::$peer === null) { self::$peer = new sfGuardUserGroupPeer(); } return self::$peer; } /** * Declares an association between this object and a sfGuardUser object. * * @param sfGuardUser $v * @return sfGuardUserGroup The current object (for fluent API support) * @throws PropelException */ public function setsfGuardUser(sfGuardUser $v = null) { if ($v === null) { $this->setUserId(NULL); } else { $this->setUserId($v->getId()); } $this->asfGuardUser = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the sfGuardUser object, it will not be re-added. if ($v !== null) { $v->addsfGuardUserGroup($this); } return $this; } /** * Get the associated sfGuardUser object * * @param PropelPDO Optional Connection object. * @return sfGuardUser The associated sfGuardUser object. * @throws PropelException */ public function getsfGuardUser(PropelPDO $con = null) { if ($this->asfGuardUser === null && ($this->user_id !== null)) { $this->asfGuardUser = sfGuardUserPeer::retrieveByPk($this->user_id); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->asfGuardUser->addsfGuardUserGroups($this); */ } return $this->asfGuardUser; } /** * Declares an association between this object and a sfGuardGroup object. * * @param sfGuardGroup $v * @return sfGuardUserGroup The current object (for fluent API support) * @throws PropelException */ public function setsfGuardGroup(sfGuardGroup $v = null) { if ($v === null) { $this->setGroupId(NULL); } else { $this->setGroupId($v->getId()); } $this->asfGuardGroup = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the sfGuardGroup object, it will not be re-added. if ($v !== null) { $v->addsfGuardUserGroup($this); } return $this; } /** * Get the associated sfGuardGroup object * * @param PropelPDO Optional Connection object. * @return sfGuardGroup The associated sfGuardGroup object. * @throws PropelException */ public function getsfGuardGroup(PropelPDO $con = null) { if ($this->asfGuardGroup === null && ($this->group_id !== null)) { $this->asfGuardGroup = sfGuardGroupPeer::retrieveByPk($this->group_id); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->asfGuardGroup->addsfGuardUserGroups($this); */ } return $this->asfGuardGroup; } /** * Resets all collections of referencing foreign keys. * * This method is a user-space workaround for PHP's inability to garbage collect objects * with circular references. This is currently necessary when using Propel in certain * daemon or large-volumne/high-memory operations. * * @param boolean $deep Whether to also clear the references on all associated objects. */ public function clearAllReferences($deep = false) { if ($deep) { } // if ($deep) $this->asfGuardUser = null; $this->asfGuardGroup = null; } // symfony_behaviors behavior /** * Calls methods defined via {@link sfMixer}. */ public function __call($method, $arguments) { if (!$callable = sfMixer::getCallable('BasesfGuardUserGroup:'.$method)) { throw new sfException(sprintf('Call to undefined method BasesfGuardUserGroup::%s', $method)); } array_unshift($arguments, $this); return call_user_func_array($callable, $arguments); } } // BasesfGuardUserGroup
joseortega/finance
plugins/sfGuardPlugin/lib/model/om/BasesfGuardUserGroup.php
PHP
gpl-3.0
26,055
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dp2; /** * * @author Marianna */ public class RSS { public static Pattern[] run(Pattern[] p, int k){ //Pesos dos exemplos positivos int[] pesos = new int[D.numeroExemplosPositivo]; //Atribuindo pesos iniciais for(int i = 0; i < pesos.length; i++){ pesos[i] = 1; } //PA: revisão! Pattern[] S = p.clone(); Pattern[] SS = new Pattern[k];//Inicializando array com os melhores patterns for(int i = 0; i < SS.length; i++){ //Identificando o maior pontuador int indiceMaximoPontuador = RSS.indiceMaiorPontuador(S, pesos); //Atribuindo maior pontuador ao array com os k melhores SS[i] = p[indiceMaximoPontuador]; //Atualizando vetor de pesos com base no maior pontuador RSS.atualizaPesos(p[indiceMaximoPontuador].getVrP(), pesos); //Excluir exemplo com maior pontuação S[indiceMaximoPontuador] = null; } return SS; } private static double pontuacao(boolean[] vetorResultantePattern, int[] pesos){ double pontuacao = 0.0; for(int i = 0; i < vetorResultantePattern.length; i++){ if(vetorResultantePattern[i]){ pontuacao += 1.0/(double)pesos[i]; } } return pontuacao; } private static int indiceMaiorPontuador(Pattern[] S, int[] pesos){ double pontuacaoMaxima = 0.0; int indiceMaiorPontuador = 0; for(int i = 0; i < S.length; i++){ if(S[i] != null){ double pontuacao = RSS.pontuacao(S[i].getVrP(), pesos); if(pontuacao > pontuacaoMaxima){ pontuacaoMaxima = pontuacao; indiceMaiorPontuador = i; } } } return indiceMaiorPontuador; } private static void atualizaPesos(boolean[] vetorResultantePositivo, int[] vetorPesosPositivo){ for(int i = 0; i < vetorPesosPositivo.length; i++){ if(vetorResultantePositivo[i]){ vetorPesosPositivo[i]++; } } } }
tarcisiodpl/ssdp
SSDP/src/dp2/RSS.java
Java
gpl-3.0
2,406
var globals_dup = [ [ "a", "globals.html", null ], [ "b", "globals_0x62.html", null ], [ "c", "globals_0x63.html", null ], [ "d", "globals_0x64.html", null ], [ "e", "globals_0x65.html", null ], [ "f", "globals_0x66.html", null ], [ "g", "globals_0x67.html", null ], [ "h", "globals_0x68.html", null ], [ "i", "globals_0x69.html", null ], [ "k", "globals_0x6b.html", null ], [ "l", "globals_0x6c.html", null ], [ "o", "globals_0x6f.html", null ], [ "p", "globals_0x70.html", null ], [ "r", "globals_0x72.html", null ], [ "s", "globals_0x73.html", null ], [ "u", "globals_0x75.html", null ], [ "v", "globals_0x76.html", null ], [ "x", "globals_0x78.html", null ] ];
gaganjyot/LibreDWG-API
doc/html/globals_dup.js
JavaScript
gpl-3.0
736
/** * Genji Scrum Tool and Issue Tracker * Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions * <a href="http://www.trackplus.com">Genji Scrum Tool</a> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* $Id:$ */ package com.aurel.track.admin.customize.category.filter; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import com.aurel.track.admin.customize.category.filter.tree.design.FieldExpressionInTreeTO; import com.aurel.track.admin.customize.category.filter.tree.design.FieldExpressionSimpleTO; import com.aurel.track.admin.customize.category.filter.tree.design.FilterSelectsListsLoader; import com.aurel.track.admin.customize.role.FieldsRestrictionsToRoleBL; import com.aurel.track.admin.project.ProjectBL; import com.aurel.track.beans.ILabelBean; import com.aurel.track.beans.TFieldConfigBean; import com.aurel.track.beans.TPersonBean; import com.aurel.track.beans.TProjectBean; import com.aurel.track.beans.TQueryRepositoryBean; import com.aurel.track.beans.TReportLayoutBean; import com.aurel.track.fieldType.constants.SystemFields; import com.aurel.track.fieldType.runtime.base.IFieldTypeRT; import com.aurel.track.fieldType.runtime.bl.FieldRuntimeBL; import com.aurel.track.fieldType.runtime.custom.text.CustomDoubleRT; import com.aurel.track.fieldType.runtime.matchers.MatchRelations; import com.aurel.track.fieldType.runtime.matchers.converter.AccountingTimeMatcherConverter; import com.aurel.track.fieldType.runtime.matchers.converter.DoubleMatcherConverter; import com.aurel.track.fieldType.runtime.matchers.converter.MatcherConverter; import com.aurel.track.fieldType.runtime.matchers.converter.SelectMatcherConverter; import com.aurel.track.fieldType.runtime.matchers.design.AccountingTimeMatcherDT; import com.aurel.track.fieldType.runtime.matchers.design.DoubleMatcherDT; import com.aurel.track.fieldType.runtime.matchers.design.IMatcherDT; import com.aurel.track.fieldType.runtime.matchers.design.IMatcherValue; import com.aurel.track.fieldType.runtime.matchers.design.MatcherDatasourceContext; import com.aurel.track.fieldType.runtime.matchers.design.SelectMatcherDT; import com.aurel.track.fieldType.runtime.matchers.run.MatcherContext; import com.aurel.track.fieldType.runtime.system.select.SystemManagerRT; import com.aurel.track.fieldType.types.FieldTypeManager; import com.aurel.track.item.consInf.RaciRole; import com.aurel.track.itemNavigator.layout.column.ColumnFieldsBL; import com.aurel.track.resources.LocalizeUtil; import com.aurel.track.util.GeneralUtils; import com.aurel.track.util.IntegerStringBean; public class FieldExpressionBL { //the following names should comply with the setter field names //in the filter actions which will be set as a result of a form submit public static String MATCHER_RELATION_BASE_NAME = "MatcherRelationMap"; public static String VALUE_BASE_NAME = "DisplayValueMap"; public static String VALUE_BASE_ITEM_ID = "DisplayValue"; public static String SIMPLE = "simple"; public static String IN_TREE = "inTree"; public static String CASCADING_PART = "CascadingPart"; public static String FIELD_NAME = "fieldMap"; public static String FIELD_MOMENT_NAME = "fieldMomentMap"; public static String OPERATION_NAME = "operationMap"; public static String PARENTHESIS_OPEN_NAME = "parenthesisOpenedMap"; public static String PARENTHESIS_CLOSED_NAME = "parenthesisClosedMap"; public static String NEGATION_NAME = "negationMap"; public static String MATCH_RELATION_PREFIX = "admin.customize.queryFilter.opt.relation."; /** * Prepares a JSON string after matcher relation change * @param baseName * @param stringValue * @param fieldID * @param matcherID * @param modifiable * @param personID * @param locale * @return */ static String selectMatcher(Integer[] projectIDs, Integer[] itemTypeIDs, String baseName, String baseItemId, Integer index, String stringValue, Integer fieldID, Integer matcherID, boolean modifiable, TPersonBean personBean, Locale locale) { FieldExpressionInTreeTO fieldExpressionInTreeTO = configureValueDetails(projectIDs, itemTypeIDs, baseName, baseItemId, index, stringValue, fieldID, matcherID, modifiable, personBean, locale); return FilterJSON.getFieldExpressionValueJSON(fieldExpressionInTreeTO.getValueItemId(), fieldExpressionInTreeTO.isNeedMatcherValue(), fieldExpressionInTreeTO.getValueRenderer(), fieldExpressionInTreeTO.getJsonConfig()); } /** * Reload part of the filter expression after a field change: possible matchers and the value part * @param baseName * @param stringValue * @param index * @param fieldID * @param matcherID * @param personID * @param locale * @param withParameter * @return */ static String selectField(Integer[] projectIDs, Integer[] itemTypeIDs, String baseName, String baseItemId, Integer index, String stringValue, Integer fieldID, Integer matcherID, boolean modifiable, TPersonBean personBean, Locale locale, boolean withParameter) { List<IntegerStringBean> matcherRelations = getMatchers(fieldID, withParameter, true, locale); if (matcherID == null) { //set the matcher relation to the first when not yet selected matcherID = matcherRelations.get(0).getValue(); } else { Iterator<IntegerStringBean> iterator = matcherRelations.iterator(); boolean found = false; while (iterator.hasNext()) { IntegerStringBean integerStringBean = iterator.next(); if (matcherID.equals(integerStringBean.getValue())) { found = true; break; } } if (!found) { //change the matcher relation to the first //only if the old one is not found among the new matcherRelations list matcherID = matcherRelations.get(0).getValue(); } } FieldExpressionInTreeTO fieldExpressionInTreeTO = configureValueDetails(projectIDs, itemTypeIDs, baseName, baseItemId, index, stringValue, fieldID, matcherID, modifiable, personBean, locale); String valueJSON = FilterJSON.getFieldExpressionValueBaseJSON(fieldExpressionInTreeTO.getValueItemId(), fieldExpressionInTreeTO.isNeedMatcherValue(), fieldExpressionInTreeTO.getValueRenderer(), fieldExpressionInTreeTO.getJsonConfig(), true); return FilterJSON.getFieldExpressionMatcherAndValueValueJSON(matcherRelations, matcherID, valueJSON); } /** * Prepares a JSON string after matcher relation or field change * @param name * @param stringValue * @param fieldID * @param matcherID * @param modifiable * @param personID * @param locale * @return */ private static FieldExpressionInTreeTO configureValueDetails(Integer[] projectIDs, Integer[] itemTypeIDs, String baseName, String baseItemId, Integer index, String stringValue, Integer fieldID, Integer matcherID, boolean modifiable, TPersonBean personBean, Locale locale) { FieldExpressionInTreeTO fieldExpressionInTreeTO = new FieldExpressionInTreeTO(); fieldExpressionInTreeTO.setField(fieldID); fieldExpressionInTreeTO.setSelectedMatcher(matcherID); MatcherConverter matcherConverter = null; if (fieldID>0) { //system or custom field IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID); if (fieldTypeRT!=null) { matcherConverter = fieldTypeRT.getMatcherConverter(); } } else { //pseudo field matcherConverter = getPseudoFieldMatcherConverter(fieldID); } Object value = null; if (matcherConverter!=null) { value = matcherConverter.fromValueString(stringValue, locale, matcherID); } fieldExpressionInTreeTO.setValue(value); Integer[] ancestorProjectIDs = null; if (projectIDs==null || projectIDs.length==0) { //none of the projects is selected -> get the other lists datasource as all available projects would be selected List<TProjectBean> projectBeans = ProjectBL.loadUsedProjectsFlat(personBean.getObjectID()); if (projectBeans!=null && !projectBeans.isEmpty()) { projectIDs = GeneralUtils.createIntegerArrFromCollection(GeneralUtils.createIntegerListFromBeanList(projectBeans)); ancestorProjectIDs = projectIDs; } } else { ancestorProjectIDs = ProjectBL.getAncestorProjects(projectIDs); } setExpressionValue(fieldExpressionInTreeTO, projectIDs, ancestorProjectIDs, itemTypeIDs, baseName, baseItemId, index, modifiable, personBean, locale); return fieldExpressionInTreeTO; } /** * Prepares a FieldExpressionSimpleTO for rendering: * Only the matcher and the value controls are "active", * field is fixed (only label is rendered for field) * @param fieldID * @param matcherID * @param modifiable * @param withParameter * @param personID * @param locale * @param value * @return */ public static FieldExpressionSimpleTO loadFilterExpressionSimple(Integer fieldID, Integer[] projectIDs, Integer[] itemTypeIDs, Integer matcherID, boolean modifiable, boolean withParameter, TPersonBean personBean, Locale locale, Map<Integer, String> fieldLabelsMap, Object value) { FieldExpressionSimpleTO fieldExpressionSimpleTO = new FieldExpressionSimpleTO(); fieldExpressionSimpleTO.setField(fieldID); fieldExpressionSimpleTO.setSelectedMatcher(matcherID); fieldExpressionSimpleTO.setValue(value); fieldExpressionSimpleTO.setFieldLabel(fieldLabelsMap.get(fieldID)); fieldExpressionSimpleTO.setMatcherName(getName(SIMPLE + MATCHER_RELATION_BASE_NAME, fieldID)); fieldExpressionSimpleTO.setMatcherItemId(getItemId(SIMPLE + MATCHER_RELATION_BASE_NAME, fieldID)); List<IntegerStringBean> matchers = getMatchers(fieldID, withParameter, false, locale); //add empty matcher for FieldExpressionSimpleTO to give the possibility to not filter by this field matchers.add(0, new IntegerStringBean("-", MatchRelations.NO_MATCHER)); fieldExpressionSimpleTO.setMatchersList(matchers); Integer[] ancestorProjectIDs = null; if (projectIDs==null || projectIDs.length==0) { //none of the projects is selected -> get the other lists datasource as all available projects would be selected List<TProjectBean> projectBeans = ProjectBL.loadUsedProjectsFlat(personBean.getObjectID()); if (projectBeans!=null && !projectBeans.isEmpty()) { projectIDs = GeneralUtils.createIntegerArrFromCollection(GeneralUtils.createIntegerListFromBeanList(projectBeans)); ancestorProjectIDs = projectIDs; } } else { ancestorProjectIDs = ProjectBL.getAncestorProjects(projectIDs); } setExpressionValue(fieldExpressionSimpleTO, projectIDs, ancestorProjectIDs, itemTypeIDs, SIMPLE + VALUE_BASE_NAME, SIMPLE + VALUE_BASE_ITEM_ID, fieldID, modifiable, personBean, locale); return fieldExpressionSimpleTO; } /** * Prepares a FieldExpressionSimpleTO created from a parameterized FieldExpressionInTreeTO for rendering: * @param fieldExpressionSimpleTO * @param projectIDs * @param showClosed * @param personID * @param locale * @param index * @return */ public static FieldExpressionSimpleTO loadFieldExpressionSimpleForInTreeParameter( FieldExpressionSimpleTO fieldExpressionSimpleTO, Integer[] projectIDs, Integer[] itemTypeIDs, TPersonBean personBean, Locale locale, Map<Integer, String> fieldLabelsMap, int index) { Integer fieldID = fieldExpressionSimpleTO.getField(); fieldExpressionSimpleTO.setIndex(index); fieldExpressionSimpleTO.setFieldLabel(fieldLabelsMap.get(fieldID)); setMatchers(fieldExpressionSimpleTO, true, locale); fieldExpressionSimpleTO.setMatcherName(getName(IN_TREE + MATCHER_RELATION_BASE_NAME, index)); fieldExpressionSimpleTO.setMatcherItemId(getItemId(IN_TREE + MATCHER_RELATION_BASE_NAME, index)); Integer[] ancestorProjectIDs = null; if (projectIDs==null || projectIDs.length==0) { //none of the projects is selected -> get the other lists datasource as all available projects would be selected List<TProjectBean> projectBeans = ProjectBL.loadUsedProjectsFlat(personBean.getObjectID()); if (projectBeans!=null && !projectBeans.isEmpty()) { projectIDs = GeneralUtils.createIntegerArrFromCollection(GeneralUtils.createIntegerListFromBeanList(projectBeans)); ancestorProjectIDs = projectIDs; } } else { ancestorProjectIDs = ProjectBL.getAncestorProjects(projectIDs); } setExpressionValue(fieldExpressionSimpleTO, projectIDs, ancestorProjectIDs, itemTypeIDs, IN_TREE + VALUE_BASE_NAME, IN_TREE + VALUE_BASE_ITEM_ID, index, true, personBean, locale); return fieldExpressionSimpleTO; } /** * Set the matchers for parameter fields * @param fieldExpressionSimpleTO * @param locale * @return */ public static FieldExpressionSimpleTO setMatchers(FieldExpressionSimpleTO fieldExpressionSimpleTO, boolean isTree, Locale locale) { List<IntegerStringBean> matcherRelations = getMatchers(fieldExpressionSimpleTO.getField(), false, isTree, locale); //add empty matcher for FieldExpressionSimpleTO to give the possibility to //not to set parameter for this field consequently do not filter by this field //TODO do we need this empty matcher for parameters or not? matcherRelations.add(0, new IntegerStringBean("", MatchRelations.NO_MATCHER)); fieldExpressionSimpleTO.setMatchersList(matcherRelations); Integer matcherID = fieldExpressionSimpleTO.getSelectedMatcher(); if (matcherID==null || matcherID.equals(MatcherContext.PARAMETER)) { //matcher was parameter, now set it to the first matcherID = matcherRelations.get(0).getValue(); fieldExpressionSimpleTO.setSelectedMatcher(matcherID); } return fieldExpressionSimpleTO; } /** * Prepares the "in tree" filter expressions for rendering * @param fieldExpressionInTreeList * @param modifiable * @param personID * @param locale * @param instant * @param withFieldMoment */ public static void loadFilterExpressionInTreeList(List<FieldExpressionInTreeTO> fieldExpressionInTreeList, Integer[] projectIDs, Integer[] itemTypeIDs, boolean modifiable, TPersonBean personBean, Locale locale, boolean withParameter, boolean withFieldMoment) { if (fieldExpressionInTreeList!=null && !fieldExpressionInTreeList.isEmpty()) { List<IntegerStringBean> fieldsWithMatcher = getAllMatcherColumns(projectIDs, personBean.getObjectID(), locale); List<IntegerStringBean> localizedOperationList = getLocalizedOperationList(locale); List<IntegerStringBean> parenthesisOpenList = createParenthesisOpenList(); List<IntegerStringBean> parenthesisClosedList = createParenthesisClosedList(); List<IntegerStringBean> fieldMoments = null; if (withFieldMoment) { fieldMoments = prepareFieldMomentList(locale); } Integer[] ancestorProjects = null; if (projectIDs==null || projectIDs.length==0) { //none of the projects is selected -> get the other lists datasource as all available projects would be selected List<TProjectBean> projectBeans = ProjectBL.loadUsedProjectsFlat(personBean.getObjectID()); if (projectBeans!=null && !projectBeans.isEmpty()) { projectIDs = GeneralUtils.createIntegerArrFromCollection(GeneralUtils.createIntegerListFromBeanList(projectBeans)); ancestorProjects = projectIDs; } } else { ancestorProjects = ProjectBL.getAncestorProjects(projectIDs); } int i=0; for (FieldExpressionInTreeTO fieldExpressionInTreeTO : fieldExpressionInTreeList) { fieldExpressionInTreeTO.setOperationsList(localizedOperationList); fieldExpressionInTreeTO.setParenthesisOpenList(parenthesisOpenList); fieldExpressionInTreeTO.setParenthesisClosedList(parenthesisClosedList); if (withFieldMoment) { fieldExpressionInTreeTO.setFieldMomentsList(fieldMoments); } loadFieldExpressionInTree(fieldExpressionInTreeTO, projectIDs, ancestorProjects, itemTypeIDs, fieldsWithMatcher, modifiable, personBean, locale, withParameter, withFieldMoment, i++); } } } /** * Prepares the "in tree" filter expressions for rendering * @param index * @param operation the default operation * @param modifiable * @param personID * @param locale * @param instant * @param withFieldMoment * @return */ static FieldExpressionInTreeTO loadFilterExpressionInTree(Integer[] projectIDs, Integer[] itemTypeIDs, Integer fieldID, Integer index, boolean modifiable, TPersonBean personBean, Locale locale, boolean withParameter, boolean withFieldMoment) { List<IntegerStringBean> fieldsWithMatcher = getAllMatcherColumns(projectIDs, personBean.getObjectID(), locale); FieldExpressionInTreeTO fieldExpressionInTreeTO = new FieldExpressionInTreeTO(); List<IntegerStringBean> operationList = getLocalizedOperationList(locale); fieldExpressionInTreeTO.setOperationsList(operationList); //if added from the first add (For adds from a filter expression //it takes the operation from the actual filter expression as default on the client side) fieldExpressionInTreeTO.setSelectedOperation(QNode.OR); fieldExpressionInTreeTO.setField(fieldID); fieldExpressionInTreeTO.setParenthesisOpenList(createParenthesisOpenList()); fieldExpressionInTreeTO.setParenthesisClosedList(createParenthesisClosedList()); if (withFieldMoment) { List<IntegerStringBean> fieldMoments = prepareFieldMomentList(locale); fieldExpressionInTreeTO.setFieldMomentsList(fieldMoments); fieldExpressionInTreeTO.setFieldMoment(fieldMoments.get(0).getValue()); } Integer[] ancestorProjects = null; if (projectIDs==null || projectIDs.length==0) { //none of the projects is selected -> get the other lists datasource as all available projects would be selected List<TProjectBean> projectBeans = ProjectBL.loadUsedProjectsFlat(personBean.getObjectID()); if (projectBeans!=null && !projectBeans.isEmpty()) { projectIDs = GeneralUtils.createIntegerArrFromCollection(GeneralUtils.createIntegerListFromBeanList(projectBeans)); ancestorProjects = projectIDs; } } else { ancestorProjects = ProjectBL.getAncestorProjects(projectIDs); } loadFieldExpressionInTree(fieldExpressionInTreeTO, projectIDs, ancestorProjects, itemTypeIDs, fieldsWithMatcher, modifiable, personBean, locale, withParameter, withFieldMoment, index); return fieldExpressionInTreeTO; } /** * Get all matcher columns * @param projectIDs * @param personID * @param locale * @return */ private static List<IntegerStringBean> getAllMatcherColumns(Integer[] projectIDs, Integer personID, Locale locale) { List<TFieldConfigBean> fieldConfigsWithMatcher = FieldRuntimeBL.getDefaultFieldConfigsWithMatcher(locale); List<IntegerStringBean> fieldsWithMatcher = new LinkedList<IntegerStringBean>(); for (TFieldConfigBean fieldConfigBean : fieldConfigsWithMatcher) { fieldsWithMatcher.add(new IntegerStringBean(fieldConfigBean.getLabel(), fieldConfigBean.getField())); } fieldsWithMatcher.addAll(getPseudoColumns(personID, locale)); Collections.sort(fieldsWithMatcher); return fieldsWithMatcher; } /** * Gets the pseudo columns allowed to see * @param projectIDs * @param locale * @return */ private static List<IntegerStringBean> getPseudoColumns(Integer personID, Locale locale) { boolean hasAccounting = ColumnFieldsBL.hasAccounting(personID); Map<Integer, Boolean> pseudoFieldsVisible = ColumnFieldsBL.getVisisblePseudoFields(personID, hasAccounting); List<IntegerStringBean> fieldsWithMatcher = new LinkedList<IntegerStringBean>(); Boolean watcherFieldsAllowed = pseudoFieldsVisible.get(FieldsRestrictionsToRoleBL.PSEUDO_COLUMNS.WATCHERS); if (watcherFieldsAllowed!=null && watcherFieldsAllowed.booleanValue()) { fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.CONSULTANT_LIST, locale), TReportLayoutBean.PSEUDO_COLUMNS.CONSULTANT_LIST)); fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.INFORMANT_LIST, locale), TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST)); } Boolean ownExpense = pseudoFieldsVisible.get(FieldsRestrictionsToRoleBL.PSEUDO_COLUMNS.MY_EXPENSES); if (ownExpense!=null && ownExpense.booleanValue()) { fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.MY_EXPENSE_TIME, locale), TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_TIME)); fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.MY_EXPENSE_COST, locale), TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_COST)); } Boolean viewAllExpenses = pseudoFieldsVisible.get(FieldsRestrictionsToRoleBL.PSEUDO_COLUMNS.ALL_EXPENSES); if (viewAllExpenses!=null && viewAllExpenses.booleanValue()) { fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.TOTAL_EXPENSE_TIME, locale), TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_TIME)); fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.TOTAL_EXPENSE_COST, locale), TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_COST)); } Boolean planVisible = pseudoFieldsVisible.get(FieldsRestrictionsToRoleBL.PSEUDO_COLUMNS.PLAN); if (planVisible!=null && planVisible.booleanValue()) { fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.TOTAL_PLANNED_TIME, locale), TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_TIME)); fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.TOTAL_PLANNED_COST, locale), TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_COST)); fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.REMAINING_PLANNED_TIME, locale), TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_TIME)); fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.REMAINING_PLANNED_COST, locale), TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_COST)); } Boolean budgetVisible = pseudoFieldsVisible.get(FieldsRestrictionsToRoleBL.PSEUDO_COLUMNS.BUDGET); if (budgetVisible!=null && budgetVisible) { fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.BUDGET_TIME, locale), TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_TIME)); fieldsWithMatcher.add(new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources(TReportLayoutBean.PSEUDO_COLUMN_LABELS.BUDGET_COST, locale), TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_COST)); } return fieldsWithMatcher; } /** * Populates an "in tree" filter expression * @param fieldExpressionInTreeTO * @param fieldsWithMatcher * @param modifiable * @param personID * @param locale * @param instant * @param withFieldMoment * @param index */ private static void loadFieldExpressionInTree(FieldExpressionInTreeTO fieldExpressionInTreeTO, Integer[] projectIDs, Integer[] ancestorProjectIDs, Integer[] itemTypeIDs, List<IntegerStringBean> fieldsWithMatcher, boolean modifiable, TPersonBean personBean, Locale locale, boolean withParameter, boolean withFieldMoment, int index) { fieldExpressionInTreeTO.setIndex(index); //field moment if (withFieldMoment) { Integer selectedFieldMoment = fieldExpressionInTreeTO.getFieldMoment(); if (selectedFieldMoment==null) { fieldExpressionInTreeTO.setFieldMoment(Integer.valueOf(TQueryRepositoryBean.FIELD_MOMENT.NEW)); } fieldExpressionInTreeTO.setFieldMomentName(getName(FIELD_MOMENT_NAME, index)); fieldExpressionInTreeTO.setWithFieldMoment(withFieldMoment); } //field Integer fieldID = fieldExpressionInTreeTO.getField(); if (fieldID==null && fieldsWithMatcher!=null && !fieldsWithMatcher.isEmpty()) { //new field expression: preselect the first available field fieldID = fieldsWithMatcher.get(0).getValue(); fieldExpressionInTreeTO.setField(fieldID); } fieldExpressionInTreeTO.setFieldsList(fieldsWithMatcher); fieldExpressionInTreeTO.setFieldName(getName(FIELD_NAME, index)); fieldExpressionInTreeTO.setFieldItemId(getItemId(FIELD_NAME, index)); //matcher List<IntegerStringBean> matcherList = getMatchers(fieldID, withParameter, true, locale); fieldExpressionInTreeTO.setMatchersList(matcherList); Integer matcherID = fieldExpressionInTreeTO.getSelectedMatcher(); if (matcherID==null) { //new field expression: preselect the first available matcher: //in FieldExpressionInTreeTO no empty matcher is available (like in FieldExpressionSimpleTO) if (matcherList!=null && !matcherList.isEmpty()) { matcherID = matcherList.get(0).getValue(); fieldExpressionInTreeTO.setSelectedMatcher(matcherID); } } fieldExpressionInTreeTO.setMatcherName(getName(IN_TREE + MATCHER_RELATION_BASE_NAME, index)); fieldExpressionInTreeTO.setMatcherItemId(getItemId(IN_TREE + MATCHER_RELATION_BASE_NAME, index)); //value setExpressionValue(fieldExpressionInTreeTO, projectIDs, ancestorProjectIDs, itemTypeIDs, IN_TREE + VALUE_BASE_NAME, IN_TREE + VALUE_BASE_ITEM_ID, index, modifiable, personBean, locale); fieldExpressionInTreeTO.setOperationName(getName(OPERATION_NAME, index)); fieldExpressionInTreeTO.setOperationItemId(getItemId(OPERATION_NAME, index)); fieldExpressionInTreeTO.setParenthesisOpenName(getName(PARENTHESIS_OPEN_NAME, index)); fieldExpressionInTreeTO.setParenthesisClosedName(getName(PARENTHESIS_CLOSED_NAME, index)); } /** * Set expression value attributes: needMatcherValue, matcherID, valueRenderer and JsonConfig string * The field, the matcher (if it is the case) and the value object should be already set for FieldExpressionSimpleTO * @param fieldExpressionSimpleTreeTO * @param projectIDs * @param ancestorProjectIDs * @param itemTypeIDs * @param baseName * @param baseItemId * @param index * @param modifiable * @param personID * @param locale */ private static void setExpressionValue(FieldExpressionSimpleTO fieldExpressionSimpleTreeTO, Integer[] projectIDs, Integer[] ancestorProjectIDs, Integer[] itemTypeIDs, String baseName, String baseItemId, Integer index, boolean modifiable, TPersonBean personBean, Locale locale) { Integer personID = personBean.getObjectID(); Integer matcherID = fieldExpressionSimpleTreeTO.getSelectedMatcher(); fieldExpressionSimpleTreeTO.setValueItemId(getItemId(baseItemId, index)); if (matcherID!=null) { //do not force the matcher to a value if not specified because no matcher means no filtering by that field //even if the field is always present (it is set as upper filter field) //(it was set already to a value if if was the case) boolean needMatcherValue = getNeedMatcherValue(matcherID); fieldExpressionSimpleTreeTO.setNeedMatcherValue(needMatcherValue); if (needMatcherValue) { Integer fieldID = fieldExpressionSimpleTreeTO.getField(); IMatcherDT matcherDT = null; Object possibleValues = null; //for field expressions the "withParameter" is false for getting the datasoucre, //because only the matcher is parameterized not the value //but "initValueIfNull" is true to preselect the first entry if nothing selected //do not show the closed entities in field expressions (typically used for release but it can be //interpreted also for person (deactivated), deleted custom entries etc.) MatcherDatasourceContext matcherDatasourceContext = new MatcherDatasourceContext(projectIDs, ancestorProjectIDs, itemTypeIDs, personBean, locale, false, true, false, false); if (fieldID.intValue()>0) { IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID); if (fieldTypeRT!=null) { matcherDT = fieldTypeRT.processLoadMatcherDT(fieldID); possibleValues = fieldTypeRT.getMatcherDataSource(fieldExpressionSimpleTreeTO, matcherDatasourceContext, null); } } else { matcherDT = getPseudoMatcherDT(fieldID); possibleValues = getPseudoFieldMatcherDataSource(fieldExpressionSimpleTreeTO, matcherDatasourceContext); } if (matcherDT!=null) { matcherDT.setRelation(matcherID); fieldExpressionSimpleTreeTO.setValueRenderer(matcherDT.getMatchValueControlClass()); fieldExpressionSimpleTreeTO.setJsonConfig(matcherDT.getMatchValueJsonConfig(fieldID, baseName, index, fieldExpressionSimpleTreeTO.getValue(), !modifiable, possibleValues, projectIDs, matcherID, locale, personID)); } } } } /** * Gets the datasource for pseudo fields (only for lists) * @param matcherValue * @param matcherDatasourceContext * @param parameterCode * @return */ private static Object getPseudoFieldMatcherDataSource(IMatcherValue matcherValue, MatcherDatasourceContext matcherDatasourceContext) { Integer fieldID = matcherValue.getField(); if (fieldID!=null) { String raciRole; switch (fieldID.intValue()) { case TReportLayoutBean.PSEUDO_COLUMNS.CONSULTANT_LIST: raciRole = RaciRole.CONSULTANT; break; case TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST: raciRole = RaciRole.INFORMANT; break; default: //expense/budget/plan return null; } Integer[] projects = matcherDatasourceContext.getProjectIDs(); Integer[] ancestorProjects = matcherDatasourceContext.getAncestorProjectIDs(); if (projects!=null && projects.length>0) { List<ILabelBean> watcherList = FilterSelectsListsLoader.getConsultantsInformants(projects, ancestorProjects, matcherDatasourceContext.getPersonBean().getObjectID(), false, raciRole, matcherDatasourceContext.getLocale()); if (matcherDatasourceContext.isInitValueIfNull() && matcherValue!=null && watcherList!=null && !watcherList.isEmpty()) { Object value = matcherValue.getValue(); if (value==null) { matcherValue.setValue(new Integer[] {watcherList.get(0).getObjectID()}); } } return watcherList; } } return null; } /** * Whether do we need a matcherValue field: for matcherRelations * IS_NULL NOT_IS_NULL and LATER_AS_LASTLOGIN we do not need it * @param matcherRelation * @return */ public static boolean getNeedMatcherValue(Integer matcherRelation) { if (matcherRelation==null) { return false; } if (matcherRelation.equals(MatcherContext.PARAMETER)) { return false; } switch(matcherRelation.intValue()) { case MatchRelations.IS_NULL: case MatchRelations.NOT_IS_NULL: case MatchRelations.LATER_AS_LASTLOGIN: case MatchRelations.SET: case MatchRelations.RESET: return false; default: return true; } } /** * Builds the name of the client side controls for submit * @param name * @param suffix * @return */ private static String getName(String name, Integer suffix) { StringBuilder stringBuilder = new StringBuilder(); return stringBuilder.append(name).append("[").append(suffix).append("]").toString(); } /** * Builds the name of the client side controls for submit * @param name * @param suffix * @return */ private static String getItemId(String name, Integer suffix) { StringBuilder stringBuilder = new StringBuilder(); return stringBuilder.append(name).append(suffix).toString(); } /** * Gets the localized operations * @param locale * @return */ private static List<IntegerStringBean> getLocalizedOperationList(Locale locale) { List<IntegerStringBean> operationList = new ArrayList<IntegerStringBean>(); operationList.add(new IntegerStringBean( LocalizeUtil.getLocalizedTextFromApplicationResources( "admin.customize.queryFilter.opt.operation.and", locale), QNode.AND)); operationList.add(new IntegerStringBean( LocalizeUtil.getLocalizedTextFromApplicationResources( "admin.customize.queryFilter.opt.operation.or", locale), QNode.OR)); operationList.add(new IntegerStringBean( LocalizeUtil.getLocalizedTextFromApplicationResources( "admin.customize.queryFilter.opt.operation.notAnd", locale), QNode.NOT_AND)); operationList.add(new IntegerStringBean( LocalizeUtil.getLocalizedTextFromApplicationResources( "admin.customize.queryFilter.opt.operation.notOr", locale), QNode.NOT_OR)); return operationList; } //max number of parenthesis private static final int MAX_PARENTHESIS_DEEP = 6; /** * Generate the parenthesisOpenList * @return */ private static List<IntegerStringBean> createParenthesisOpenList() { return getParenthesisList('(', MAX_PARENTHESIS_DEEP); } /** * Generate the parenthesisClosedList * @return */ private static List<IntegerStringBean> createParenthesisClosedList() { return getParenthesisList(')', MAX_PARENTHESIS_DEEP); } /** * Generate the parenthesis list * @param parenthesis * @param maxDeep * @return */ private static List<IntegerStringBean> getParenthesisList(char parenthesis, int maxDeep) { List<IntegerStringBean> parenthesisList = new ArrayList<IntegerStringBean>(); StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < maxDeep; i++) { parenthesisList.add(new IntegerStringBean(stringBuffer.toString(), Integer.valueOf(i))); stringBuffer.append(parenthesis); } return parenthesisList; } /** * Prepares the field moment list for notification filters * @param locale * @return */ private static List<IntegerStringBean> prepareFieldMomentList(Locale locale) { List<IntegerStringBean> fieldMomentList = new ArrayList<IntegerStringBean>(); fieldMomentList.add (new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources( "common.opt.fieldMoment.new", locale), Integer.valueOf(TQueryRepositoryBean.FIELD_MOMENT.NEW))); fieldMomentList.add (new IntegerStringBean(LocalizeUtil.getLocalizedTextFromApplicationResources( "common.opt.fieldMoment.old", locale), Integer.valueOf(TQueryRepositoryBean.FIELD_MOMENT.OLD))); return fieldMomentList; } /** * Get the matchers corresponding to the field * @param fieldID * @param withParameter * @param inTree * @param locale * @return */ public static List<IntegerStringBean> getMatchers(Integer fieldID, boolean withParameter, boolean inTree, Locale locale) { List<IntegerStringBean> localizedRelations = new ArrayList<IntegerStringBean>(); if (fieldID==null) { return localizedRelations; } else { IMatcherDT matcherDT = null; if (fieldID>0) { IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID); if (fieldTypeRT==null) { //for example the Keyword pseudo field return localizedRelations; } matcherDT = fieldTypeRT.processLoadMatcherDT(fieldID); } else { matcherDT = getPseudoMatcherDT(fieldID); } if (matcherDT!=null) { List<Integer> possibleRelations = matcherDT.getPossibleRelations(withParameter, inTree); if (possibleRelations!=null) { localizedRelations = LocalizeUtil.getLocalizedList( MATCH_RELATION_PREFIX, possibleRelations, locale); } } } return localizedRelations; } /** * Gets the pseudo field matcherDTs * @param fieldID * @return */ private static IMatcherDT getPseudoMatcherDT(Integer fieldID) { if (fieldID!=null) { switch (fieldID.intValue()) { case TReportLayoutBean.PSEUDO_COLUMNS.CONSULTANT_LIST: case TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST: return new SelectMatcherDT(fieldID); case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_TIME: return new AccountingTimeMatcherDT(fieldID); case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_COST: case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_COST: case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_COST: case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_COST: case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_COST: return new DoubleMatcherDT(fieldID); } } return null; } /** * Gets the pseudo fields matcher converter * @param fieldID * @return */ public static MatcherConverter getPseudoFieldMatcherConverter(Integer fieldID) { if (fieldID!=null) { switch (fieldID.intValue()) { case TReportLayoutBean.PSEUDO_COLUMNS.CONSULTANT_LIST: case TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST: return new SelectMatcherConverter(); case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_TIME: return new AccountingTimeMatcherConverter(); case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_COST: case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_COST: case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_COST: case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_COST: case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_COST: return new DoubleMatcherConverter(); } } return null; } /** * Gets the pseudo field matcherDTs * @param fieldID * @return */ public static IFieldTypeRT getPseudoFieldFieldTypeRT(Integer fieldID) { if (fieldID!=null) { switch (fieldID.intValue()) { case TReportLayoutBean.PSEUDO_COLUMNS.CONSULTANT_LIST: case TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST: return new SystemManagerRT(); case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_COST: case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_COST: case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_COST: case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_COST: case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_COST: return new CustomDoubleRT(); } } return null; } /** * Gets the pseudo field matcherDTs * @param fieldID * @return */ public static Integer getPseudoFieldSystemOption(Integer fieldID) { if (fieldID!=null) { switch (fieldID.intValue()) { case TReportLayoutBean.PSEUDO_COLUMNS.CONSULTANT_LIST: case TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST: return SystemFields.INTEGER_PERSON; case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_COST: case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_COST: case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_COST: case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_COST: case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_TIME: case TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_COST: return fieldID; } } return null; } }
trackplus/Genji
src/main/java/com/aurel/track/admin/customize/category/filter/FieldExpressionBL.java
Java
gpl-3.0
40,054
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Copyright (C) 2011-2019 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::fvMeshDistribute Description Sends/receives parts of mesh+fvfields to neighbouring processors. Used in load balancing. Input is per local cell the processor it should move to. Moves meshes and volFields/surfaceFields and returns map which can be used to distribute other. Notes: - does not handle cyclics. Will probably handle separated proc patches. - if all cells move off processor also all its processor patches will get deleted so comms might be screwed up (since e.g. globalMeshData expects procPatches on all) - initial mesh has to have procPatches last and all normal patches common to all processors and in the same order. This is checked. - faces are matched topologically but points on the faces are not. So expect problems -on separated patches (cyclics?) -on zero sized processor edges. SourceFiles fvMeshDistribute.C fvMeshDistributeTemplates.C \*---------------------------------------------------------------------------*/ #ifndef fvMeshDistribute_H #define fvMeshDistribute_H #include "Field.H" #include "fvMeshSubset.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // Forward declaration of classes class mapAddedPolyMesh; class mapDistributePolyMesh; /*---------------------------------------------------------------------------*\ Class fvMeshDistribute Declaration \*---------------------------------------------------------------------------*/ class fvMeshDistribute { // Private Data //- Underlying fvMesh fvMesh& mesh_; //- Absolute merging tolerance (constructing meshes gets done using // geometric matching) const scalar mergeTol_; // Private Member Functions static void inplaceRenumberWithFlip ( const labelUList& oldToNew, const bool oldToNewHasFlip, const bool lstHasFlip, labelUList& lst ); //- Find indices with value static labelList select ( const bool selectEqual, const labelList& values, const label value ); //- Check all procs have same names and in exactly same order. static void checkEqualWordList(const string&, const wordList&); //- Merge wordlists over all processors static wordList mergeWordList(const wordList&); // Patch handling //- Find patch to put exposed faces into. label findNonEmptyPatch() const; //- Save boundary fields template<class T, class Mesh> void saveBoundaryFields ( PtrList<FieldField<fvsPatchField, T>>& bflds ) const; //- Map boundary fields template<class T, class Mesh> void mapBoundaryFields ( const mapPolyMesh& map, const PtrList<FieldField<fvsPatchField, T>>& oldBflds ); //- Save internal fields of surfaceFields template<class T> void saveInternalFields(PtrList<Field<T>>& iflds) const; //- Set value of patch faces resulting from internal faces template<class T> void mapExposedFaces ( const mapPolyMesh& map, const PtrList<Field<T>>& oldFlds ); //- Init patch fields of certain type template<class GeoField, class PatchFieldType> void initPatchFields ( const typename GeoField::value_type& initVal ); //- Call correctBoundaryConditions on fields template<class GeoField> void correctBoundaryConditions(); //- Delete all processor patches. Move any processor faces into // patchi. autoPtr<mapPolyMesh> deleteProcPatches(const label patchi); //- Repatch the mesh. This is only necessary for the proc // boundary faces. newPatchID is over all boundary faces: -1 or // new patchID. constructFaceMap is being adapted for the // possible new face position (since proc faces get automatically // matched) autoPtr<mapPolyMesh> repatch ( const labelList& newPatchID, labelListList& constructFaceMap ); //- Merge any local points that were remotely coupled. // constructPointMap is adapted for the new point labels. autoPtr<mapPolyMesh> mergeSharedPoints ( const labelList& pointToGlobalMaster, labelListList& constructPointMap ); // Coupling information //- Construct the local environment of all boundary faces. void getCouplingData ( const labelList& distribution, labelList& sourceFace, labelList& sourceProc, labelList& sourcePatch, labelList& sourceNewProc, labelList& sourcePointMaster ) const; // Subset the neighbourCell/neighbourProc fields static void subsetCouplingData ( const fvMesh& mesh, const labelList& pointMap, const labelList& faceMap, const labelList& cellMap, const labelList& oldDistribution, const labelList& oldFaceOwner, const labelList& oldFaceNeighbour, const label oldInternalFaces, const labelList& sourceFace, const labelList& sourceProc, const labelList& sourcePatch, const labelList& sourceNewProc, const labelList& sourcePointMaster, labelList& subFace, labelList& subProc, labelList& subPatch, labelList& subNewProc, labelList& subPointMaster ); //- Find cells on mesh whose faceID/procID match the neighbour // cell/proc of domainMesh. Store the matching face. static void findCouples ( const primitiveMesh&, const labelList& sourceFace, const labelList& sourceProc, const labelList& sourcePatch, const label domain, const primitiveMesh& domainMesh, const labelList& domainFace, const labelList& domainProc, const labelList& domainPatch, labelList& masterCoupledFaces, labelList& slaveCoupledFaces ); //- Map data on boundary faces to new mesh (resulting from adding // two meshes) static labelList mapBoundaryData ( const primitiveMesh& mesh, // mesh after adding const mapAddedPolyMesh& map, const labelList& boundaryData0, // mesh before adding const label nInternalFaces1, const labelList& boundaryData1 // added mesh ); //- Map point data to new mesh (resulting from adding two meshes) static labelList mapPointData ( const primitiveMesh& mesh, // mesh after adding const mapAddedPolyMesh& map, const labelList& boundaryData0, // on mesh before adding const labelList& boundaryData1 // on added mesh ); // Other //- Remove cells. Add all exposed faces to patch oldInternalPatchi autoPtr<mapPolyMesh> doRemoveCells ( const labelList& cellsToRemove, const label oldInternalPatchi ); //- Add processor patches. Changes mesh and returns per neighbour // proc the processor patchID. void addProcPatches ( const labelList&, // processor that neighbour is now on const labelList&, // -1 or patch that face originated from List<Map<label>>& procPatchID ); //- Get boundary faces to be repatched. Is -1 or new patchID static labelList getBoundaryPatch ( const labelList& neighbourNewProc, // new processor per b. face const labelList& referPatchID, // -1 or original patch const List<Map<label>>& procPatchID // patchID ); //- Send mesh and coupling data. static void sendMesh ( const label domain, const fvMesh& mesh, const wordList& pointZoneNames, const wordList& facesZoneNames, const wordList& cellZoneNames, const labelList& sourceFace, const labelList& sourceProc, const labelList& sourcePatch, const labelList& sourceNewProc, const labelList& sourcePointMaster, Ostream& toDomain ); //- Send subset of fields template<class GeoField> static void sendFields ( const label domain, const wordList& fieldNames, const fvMeshSubset&, Ostream& toNbr ); //- Receive mesh. Opposite of sendMesh static autoPtr<fvMesh> receiveMesh ( const label domain, const wordList& pointZoneNames, const wordList& facesZoneNames, const wordList& cellZoneNames, const Time& runTime, labelList& domainSourceFace, labelList& domainSourceProc, labelList& domainSourcePatch, labelList& domainSourceNewProc, labelList& domainSourcePointMaster, Istream& fromNbr ); //- Receive fields. Opposite of sendFields template<class GeoField> static void receiveFields ( const label domain, const wordList& fieldNames, typename GeoField::Mesh&, PtrList<GeoField>&, const dictionary& fieldDicts ); public: ClassName("fvMeshDistribute"); // Constructors //- Construct from mesh and absolute merge tolerance fvMeshDistribute(fvMesh& mesh, const scalar mergeTol); //- Disallow default bitwise copy construction fvMeshDistribute(const fvMeshDistribute&) = delete; // Member Functions //- Helper function: count cells per processor in wanted distribution static labelList countCells(const labelList&); //- Send cells to neighbours according to distribution // (for every cell the new proc) autoPtr<mapDistributePolyMesh> distribute(const labelList& dist); // Debugging //- Print some info on coupling data static void printCoupleInfo ( const primitiveMesh&, const labelList&, const labelList&, const labelList&, const labelList& ); //- Print some field info template<class GeoField> static void printFieldInfo(const fvMesh&); //- Print some info on mesh. static void printMeshInfo(const fvMesh&); // Member Operators //- Disallow default bitwise assignment void operator=(const fvMeshDistribute&) = delete; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifdef NoRepository #include "fvMeshDistributeTemplates.C" #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
will-bainbridge/OpenFOAM-dev
src/dynamicMesh/fvMeshDistribute/fvMeshDistribute.H
C++
gpl-3.0
13,474
using System.ComponentModel; using System.Web.Script.Serialization; using MongoDB.Bson; namespace TitanicCrawler.Albums { public abstract class Album { private string artist; private string album; /// <summary> /// Creates a new Album class which takes all 6 arguments /// </summary> /// <param name="artist">The artist name of the album</param> /// <param name="albumTitle">The title of the album</param> protected Album(string artist, string albumTitle) { Artist = artist; AlbumTitle = albumTitle; } public Album(BsonDocument albumDocuement) { Artist = albumDocuement["Artist"].ToString(); AlbumTitle = albumDocuement["Album"].ToString(); } /// <summary> /// The artist name of the album /// </summary> [DisplayName("Artist")] public string Artist { get { return artist; } set { artist = value; } } /// <summary> /// The title of the album /// </summary> [DisplayName("Album Title")] public string AlbumTitle { get { return album; } set { album = value; } } /// <summary> /// Returns a JSON string of the object /// </summary> /// <returns></returns> public string toJSON() { return new JavaScriptSerializer().Serialize(this); } /// <summary> /// Returns a BSON Representation of the Album Object /// </summary> /// <returns>BSON representation of Album</returns> public abstract BsonDocument BsonDocument { get; } } }
Ramzy94/TitanicWebCrawler
TitanicCrawler/Albums/Album.cs
C#
gpl-3.0
1,792
/* Vuls - Vulnerability Scanner Copyright (C) 2016 Future Architect, Inc. Japan. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cache import ( "encoding/json" "fmt" "time" "github.com/Sirupsen/logrus" "github.com/boltdb/bolt" "github.com/future-architect/vuls/util" ) // Bolt holds a pointer of bolt.DB // boltdb is used to store a cache of Changelogs of Ubuntu/Debian type Bolt struct { Path string Log *logrus.Entry db *bolt.DB } // SetupBolt opens a boltdb and creates a meta bucket if not exists. func SetupBolt(path string, l *logrus.Entry) error { l.Infof("Open boltDB: %s", path) db, err := bolt.Open(path, 0600, nil) if err != nil { return err } b := Bolt{ Path: path, Log: l, db: db, } if err = b.createBucketIfNotExists(metabucket); err != nil { return err } DB = b return nil } // Close a db. func (b Bolt) Close() error { if b.db == nil { return nil } return b.db.Close() } // CreateBucketIfNotExists creates a buket that is specified by arg. func (b *Bolt) createBucketIfNotExists(name string) error { return b.db.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucketIfNotExists([]byte(name)) if err != nil { return fmt.Errorf("Failed to create bucket: %s", err) } return nil }) } // GetMeta gets a Meta Information os the servername to boltdb. func (b Bolt) GetMeta(serverName string) (meta Meta, found bool, err error) { err = b.db.View(func(tx *bolt.Tx) error { bkt := tx.Bucket([]byte(metabucket)) v := bkt.Get([]byte(serverName)) if len(v) == 0 { found = false return nil } if e := json.Unmarshal(v, &meta); e != nil { return e } found = true return nil }) return } // RefreshMeta gets a Meta Information os the servername to boltdb. func (b Bolt) RefreshMeta(meta Meta) error { meta.CreatedAt = time.Now() jsonBytes, err := json.Marshal(meta) if err != nil { return fmt.Errorf("Failed to marshal to JSON: %s", err) } return b.db.Update(func(tx *bolt.Tx) error { bkt := tx.Bucket([]byte(metabucket)) if err := bkt.Put([]byte(meta.Name), jsonBytes); err != nil { return err } b.Log.Debugf("Refreshed Meta: %s", meta.Name) return nil }) } // EnsureBuckets puts a Meta information and create a buket that holds changelogs. func (b Bolt) EnsureBuckets(meta Meta) error { jsonBytes, err := json.Marshal(meta) if err != nil { return fmt.Errorf("Failed to marshal to JSON: %s", err) } return b.db.Update(func(tx *bolt.Tx) error { b.Log.Debugf("Put to meta: %s", meta.Name) bkt := tx.Bucket([]byte(metabucket)) if err := bkt.Put([]byte(meta.Name), jsonBytes); err != nil { return err } // re-create a bucket (bucket name: servername) bkt = tx.Bucket([]byte(meta.Name)) if bkt != nil { b.Log.Debugf("Delete bucket: %s", meta.Name) if err := tx.DeleteBucket([]byte(meta.Name)); err != nil { return err } b.Log.Debugf("Bucket deleted: %s", meta.Name) } b.Log.Debugf("Create bucket: %s", meta.Name) if _, err := tx.CreateBucket([]byte(meta.Name)); err != nil { return err } b.Log.Debugf("Bucket created: %s", meta.Name) return nil }) } // PrettyPrint is for debug func (b Bolt) PrettyPrint(meta Meta) error { return b.db.View(func(tx *bolt.Tx) error { bkt := tx.Bucket([]byte(metabucket)) v := bkt.Get([]byte(meta.Name)) b.Log.Debugf("Meta: key:%s, value:%s", meta.Name, v) bkt = tx.Bucket([]byte(meta.Name)) c := bkt.Cursor() for k, v := c.First(); k != nil; k, v = c.Next() { b.Log.Debugf("key:%s, len: %d, %s...", k, len(v), util.Truncate(string(v), 30)) } return nil }) } // GetChangelog get the changelgo of specified packName from the Bucket func (b Bolt) GetChangelog(servername, packName string) (changelog string, err error) { err = b.db.View(func(tx *bolt.Tx) error { bkt := tx.Bucket([]byte(servername)) if bkt == nil { return fmt.Errorf("Faild to get Bucket: %s", servername) } v := bkt.Get([]byte(packName)) if v == nil { changelog = "" return nil } changelog = string(v) return nil }) return } // PutChangelog put the changelgo of specified packName into the Bucket func (b Bolt) PutChangelog(servername, packName, changelog string) error { return b.db.Update(func(tx *bolt.Tx) error { bkt := tx.Bucket([]byte(servername)) if bkt == nil { return fmt.Errorf("Faild to get Bucket: %s", servername) } if err := bkt.Put([]byte(packName), []byte(changelog)); err != nil { return err } return nil }) }
lapthorn/vuls
cache/bolt.go
GO
gpl-3.0
5,047
package com.queencastle.service.interf; import com.queencastle.dao.model.SysResourceInfo; public interface SysResourceInfoService { int insert(SysResourceInfo resourceInfo); }
AminLiu/Test
queencastle-all/queencastle-service/src/main/java/com/queencastle/service/interf/SysResourceInfoService.java
Java
gpl-3.0
182
using System; using System.Drawing; using System.Linq; using System.Windows.Forms; using System.IO; using TranslaTale.Renderers; using TranslaTale.Text; using TranslaTale.Projects; using TranslaTale.Settings; using TranslaTale.Bookmarks; namespace TranslaTale { public partial class MainForm : Form { private string FileSavePath; private bool DirtyFlag = false; private int EditedLines = 0; public MainForm() { InitializeComponent(); FontComboBox.SelectedIndex = 0; KeyPreview = true; MainMenuItemStrip.Renderer = new TTSystemRenderer(); MainToolStrip.Renderer = new TTSystemRenderer(); MainStatusStrip.Renderer = new TTSystemRenderer(); MainSpriteFontBox.FontPath = Application.StartupPath + "\\Resources\\Fonts.png"; } public void LoadItems(SearchMode selectionMode = SearchMode.Both) { MainListView.Items.Clear(); MainListView.Enabled = false; MainToolStrip.Enabled = false; MainMenuItemStrip.Enabled = false; int LineNum = Lines.Count; MainListView.BeginUpdate(); switch (selectionMode) { case SearchMode.Base: { var linesToAdd = from line in Lines.LineArray where !line.IsEdited() select line; foreach (var line in linesToAdd) { MainListView.Items.Add(line.ToListViewItem(true)); } EditedLines = LineNum - linesToAdd.Count(); } break; case SearchMode.Translation: { var linesToAdd = from line in Lines.LineArray where line.IsEdited() select line; foreach (var line in linesToAdd) { MainListView.Items.Add(line.ToListViewItem(true)); } EditedLines = linesToAdd.Count(); } break; case SearchMode.Both: foreach (var line in Lines.LineArray) { MainListView.Items.Add(line.ToListViewItem(true)); if (line.IsEdited()) EditedLines++; } break; } MainListView.EndUpdate(); MainListView.Enabled = true; MainToolStrip.Enabled = true; MainMenuItemStrip.Enabled = true; SelectItem(MiscSettings.LastVisitedLine); TotalStatusLabel.Text = LineNum.ToString(); TranslatedStatusLabel.Text = EditedLines.ToString(); UntranslatedStatusLabel.Text = (LineNum - EditedLines).ToString(); } private void UpdateEditedCount() { var editedLines = from line in Lines.LineArray where line.IsEdited() select line; TranslatedStatusLabel.Text = editedLines.Count().ToString(); UntranslatedStatusLabel.Text = (Lines.Count - editedLines.Count()).ToString(); } public void PromptReload() { switch (MessageBox.Show("Would you like to reload the current project?", "TranslaTale", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { case DialogResult.Yes: Hide(); Open(Project.CurrentProject); Show(); return; default: return; } } public void Open(string cleanFile, string transFile) { try { Lines.Open(cleanFile, transFile); LoadItems(); this.Text = "TranslaTale - " + Path.GetFileName(transFile); ProjectMenuItem.Enabled = false; CompileAndRunMenuItem.Enabled = false; FileSavePath = transFile; Project.CurrentProject = null; RecentFileSettings.SaveRecentBaseFile(cleanFile); } catch (Exception ex) when (ex is FileNotFoundException || ex is DifferentFileSizeException || ex is EmptyFileException) { MessageBox.Show(ex.Message, "TranslaTale", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { MainListView.Enabled = true; MainToolStrip.Enabled = true; MainMenuItemStrip.Enabled = true; } } public void Open(Project project) { try { Lines.Open(project.CleanFilePath, project.TransFilePath); LoadItems(); this.Text = "TranslaTale - " + project.Name; ProjectMenuItem.Enabled = true; Project.CurrentProject = project; RecentProjects.Add(project); FileSavePath = project.TransFilePath; } catch (Exception ex) when (ex is FileNotFoundException || ex is DifferentFileSizeException || ex is EmptyFileException) { MessageBox.Show(ex.Message, "TranslaTale", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { MainListView.Enabled = true; MainToolStrip.Enabled = true; MainMenuItemStrip.Enabled = true; } } private void Save(string path) { try { Lines.Save(path); FileSavePath = path; DirtyFlag = false; } catch (Exception ex) when (ex is FileNotFoundException) { var Dialog = new SaveFileDialog() { Title = "Save as...", Filter = "Text files (*.txt)|(*.txt)" }; if (Dialog.ShowDialog() == DialogResult.OK) { Save(Dialog.FileName); } } } public bool SelectItem(int index) { try { if (MainListView.Items[index].SubItems[0].Text == index.ToString()) { MainListView.Items[index].Selected = true; MainListView.EnsureVisible(index); MainListView.Focus(); return true; } return false; } catch { return false; } } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (!DirtyFlag) return; switch (MessageBox.Show("There are unsaved changes!\n" + "Would you like to save your file?", "TranslaTale", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation)) { case DialogResult.Yes: Save(FileSavePath); return; case DialogResult.No: return; case DialogResult.Cancel: e.Cancel = true; return; } } private void MainForm_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } private void MainListView_SelectedIndexChanged(object sender, EventArgs e) { if (MainListView.SelectedItems.Count > 0) { string SelectedString = MainListView.SelectedItems[0].SubItems[2].Text; MainTextBox.Text = SelectedString; MainSpriteFontBox.Text = SelectedString; AddBookmarkMenuItem.Enabled = true; MiscSettings.LastVisitedLine = MainListView.SelectedIndices[0]; } else { MainTextBox.Text = ""; MainSpriteFontBox.Text = ""; AddBookmarkMenuItem.Enabled = false; } } private void MainListView_SizeChanged(object sender, EventArgs e) { int ColumnWidth = (MainListView.Width - MainListView.Columns[0].Width - 25) / 2; MainListView.Columns[1].Width = ColumnWidth; MainListView.Columns[2].Width = ColumnWidth; } private void MainTextBox_TextChanged(object sender, EventArgs e) { if (MainListView.SelectedItems.Count > 0) { var SelectedItem = MainListView.SelectedItems[0]; var SelectedLine = Lines.Get(Int32.Parse(SelectedItem.SubItems[0].Text)); string TransLine = MainTextBox.Text; SelectedLine.TranslatedString = TransLine; MainSpriteFontBox.Text = TransLine; SelectedItem.SubItems[2].Text = TransLine; SelectedItem.BackColor = SelectedLine.IsEdited() ? Color.LightGreen : Color.LightSalmon; UpdateEditedCount(); } } private void MainTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { var SelectedIndex = MainListView.SelectedIndices[0]; MainListView.Items[SelectedIndex].Selected = false; MainListView.Items[++SelectedIndex].Selected = true; MainListView.EnsureVisible(SelectedIndex); MainTextBox.Focus(); return; } if (!DirtyFlag) { DirtyFlag = true; this.Text += " *"; } } private void OpenProjectMenuItem_Click(object sender, EventArgs e) { var Dialog = new OpenFileDialog() { Title = "Open a project file or a translation file", Filter = "TranslaTale Project files (*.ttp)|*.ttp|Text files (*.txt)|*.txt" }; if (Dialog.ShowDialog() == DialogResult.OK) { switch (Path.GetExtension(Dialog.FileName)) { case ".ttp": //Project File var OpenedProject = Project.Read(Dialog.FileName); Open(OpenedProject); break; case ".txt": //Text File string BaseTextFilePath = RecentFileSettings.GetRecentBaseFile(); if (!File.Exists(BaseTextFilePath)) { var TextFileDialog = new OpenFileDialog() { Title = "Open a clean text file", Filter = "Text files (*.txt)|*.txt" }; if (TextFileDialog.ShowDialog() == DialogResult.OK) { BaseTextFilePath = TextFileDialog.FileName; } else return; } Open(BaseTextFilePath, Dialog.FileName); break; } } } private void OpenToolStripButton_Click(object sender, EventArgs e) { OpenMenuItem.PerformClick(); } private void SaveMenuItem_Click(object sender, EventArgs e) { if (!DirtyFlag) return; if (Project.CurrentProject != null) { Save(Project.CurrentProject.TransFilePath); this.Text = "TranslaTale - " + Project.CurrentProject.Name; } else { Save(FileSavePath); this.Text = "TranslaTale - " + Path.GetFileName(FileSavePath); } } private void SaveToolStripButton_Click(object sender, EventArgs e) { SaveMenuItem.PerformClick(); } private void SearchMenuItem_Click(object sender, EventArgs e) { new SearchForm(this).Show(); } private void SearchToolStripButton_Click(object sender, EventArgs e) { SearchMenuItem.PerformClick(); } private void CompileMenuItem_Click(object sender, EventArgs e) { Save(FileSavePath); new CompileProgressDialog("Compiling...", false).Show(this); } private void CompileAndRunMenuItem_Click(object sender, EventArgs e) { Save(FileSavePath); new CompileProgressDialog("Compiling...", true).Show(this); } private void CompileToolStripButton_Click(object sender, EventArgs e) { CompileAndRunMenuItem.PerformClick(); } private void ProjectSettingsMenuItem_Click(object sender, EventArgs e) { new ProjectSettingsForm(this).Show(this); } private void AddBookmarkMenuItem_Click(object sender, EventArgs e) { if (Bookmark.GetList().Any(x => x.Line == MainListView.SelectedIndices[0])) { MessageBox.Show("There is a bookmark for that line already!", "TranslaTale", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return; } new AddBookmarkDialog(MainListView.SelectedIndices[0]).ShowDialog(); } private void ListBookmarksMenuItem_Click(object sender, EventArgs e) { new BookmarksForm(this).ShowDialog(); } private void GoToMenuItem_Click(object sender, EventArgs e) { new GoToLineDialog(this).ShowDialog(); } private void GoToToolStripButton_Click(object sender, EventArgs e) { GoToMenuItem.PerformClick(); } private void FontComboBox_SelectedIndexChanged(object sender, EventArgs e) { switch (FontComboBox.SelectedIndex) { case 0: MainSpriteFontBox.CurrentSpriteFont = UTSpriteFontBox.SpriteFontBox.SpriteFonts.BitOperator; return; case 1: MainSpriteFontBox.CurrentSpriteFont = UTSpriteFontBox.SpriteFontBox.SpriteFonts.ComicSans; return; case 2: MainSpriteFontBox.CurrentSpriteFont = UTSpriteFontBox.SpriteFontBox.SpriteFonts.Papyrus; return; } } private void NoFaceRadioButton_CheckedChanged(object sender, EventArgs e) { if (NoFaceRadioButton.Checked) MainSpriteFontBox.ShowFaces = false; else MainSpriteFontBox.ShowFaces = true; } private void TranslatedStatusLabel_Click(object sender, EventArgs e) { LoadItems(SearchMode.Translation); } private void UntranslatedStatusLabel_Click(object sender, EventArgs e) { LoadItems(SearchMode.Base); } private void TotalStatusLabel_Click(object sender, EventArgs e) { LoadItems(SearchMode.Both); } private void AboutMenuItem_Click(object sender, EventArgs e) { new AboutForm().Show(this); } private void MergeFilesToolStripMenuItem_Click(object sender, EventArgs e) { new FileMergeForm(this).Show(); } } }
CRefice/TranslaTale
Forms/MainForm.cs
C#
gpl-3.0
16,042
/****************************************************************************** ** Copyright (C) 2016 Yakup Ates <Yakup.Ates@rub.de> ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** any later version. ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ #include "cipherTWO.h" const char cipherTWO::SBox[] = { 6, 4, 12, 5, 0, 7, 2, 14, 1, 15, 3, 13, 8, 10, 9, 11 }; const char cipherTWO::SBox_inv[] = { 4, 8, 6, 10, 1, 3, 0, 5, 12, 14, 13, 15, 2, 11, 7, 9 }; const char* cipherTWO::version = "1.0"; char cipherTWO::getSBox(int index){ return SBox[index%16]; } char cipherTWO::getSBox_inv(int index){ return SBox_inv[index%16]; } int cipherTWO::get_k_cnt(){ return k_cnt; } const char* cipherTWO::get_version(){ return version; } int* cipherTWO::getKey(){ return k; } void cipherTWO::setKey(int* k_new){ for(int i=0; i<k_cnt; ++i){ k[i] = k_new[i] % 16; } } int cipherTWO::encrypt(int m, int k[k_cnt]){ char u, v, w, x, c; for(int i=0; i<k_cnt; ++i){ k[i] %= 16; } m %= 16; u = m ^ k[0]; u %= 16; v = getSBox(u); v %= 16; w = v ^ k[1]; w %= 16; x = getSBox(w); x %= 16; c = x ^ k[2]; c %= 16; std::cout << "Encrypting with:" << std::endl << "---" << std::endl << "m : " << int(m) << std::endl << "k0: " << int(k[0]) << std::endl << "k1: " << int(k[1]) << std::endl << "k2: " << int(k[2]) << std::endl << "---" << std::endl << std::endl << "Results:" << std::endl << "---" << std::endl << "u: " << int(u) << std::endl << "v: " << int(v) << std::endl << "w: " << int(w) << std::endl << "x: " << int(x) << std::endl << "c: " << int(c) << std::endl << "---" << std::endl; return int(c); } int cipherTWO::decrypt(int c, int k[k_cnt], int silent=0){ char u, v, w, x, m; for(int i=0; i<k_cnt; ++i){ k[i] %= 16; } c %= 16; x = c ^ k[2]; x %= 16; w = getSBox_inv(x); w %= 16; v = w ^ k[1]; v %= 16; u = getSBox_inv(v); u %= 16; m = u ^ k[0]; m %= 16; if(silent == 0){ std::cout << "Decrypting with:" << std::endl << "---" << std::endl << "c : " << int(c) << std::endl << "k0: " << int(k[0]) << std::endl << "k1: " << int(k[1]) << std::endl << "k2: " << int(k[2]) << std::endl << "---" << std::endl << std::endl << "Results:" << std::endl << "---" << std::endl << "u: " << int(u) << std::endl << "v: " << int(v) << std::endl << "w: " << int(w) << std::endl << "x: " << int(x) << std::endl << "m: " << int(m) << std::endl << "---" << std::endl; } return int(m); } std::vector<char> cipherTWO::get_influence_SBox(char diff=15){ std::ios state(NULL); state.copyfmt(std::cout); const int table_size = 16; const char sep = ' '; const int entry_width = 12; char v0[table_size], v1[table_size], u0[table_size], u1[table_size]; std::vector<char> v_diff(table_size); for(int i=0; i<table_size; ++i){ u0[i] = i; u0[i] %= 16; u1[i] = i ^ diff; u1[i] %= 16; v0[i] = getSBox(i); v1[i] = getSBox(u1[i]); v_diff[i] = v0[i] ^ v1[i]; } std::cout << std::left << std::setw(entry_width) << std::setfill(sep) << "u0"; std::cout << std::left << std::setw(entry_width) << std::setfill(sep) << "u1=u0^15"; std::cout << std::left << std::setw(entry_width) << std::setfill(sep) << "v0=S(u0)"; std::cout << std::left << std::setw(entry_width) << std::setfill(sep) << "v1=S(u1)"; std::cout << std::left << std::setw(entry_width) << std::setfill(sep) << "v1^v2" << std::endl; std::cout << "-------------------------------------------------------" << std::endl; for(int i=0; i<table_size; ++i){ std::cout << std::left << std::setw(entry_width) << std::setfill(sep) << int(u0[i]); std::cout << std::left << std::setw(entry_width) << std::setfill(sep) << int(u1[i]); std::cout << std::left << std::setw(entry_width) << std::setfill(sep) << int(v0[i]); std::cout << std::left << std::setw(entry_width) << std::setfill(sep) << int(v1[i]); std::cout << std::left << std::setw(entry_width) << std::setfill(sep) << int(v_diff[i]) << std::endl; } // reset std::cout state std::cout.copyfmt(state); //std::vector<int> v_diff_copy(v_diff); sbox_statistics(v_diff, table_size, 0); return v_diff; } std::vector<int> cipherTWO::sbox_statistics(std::vector<char> v_diff_copy, int table_size, int silent=1){ int max_occ[table_size] = {0}; int max = 0; int element = 0; std::vector<int> result(2); std::sort(v_diff_copy.begin(), v_diff_copy.end()); for(int i=0; i<table_size; ++i){ max_occ[int(v_diff_copy[i])] += 1; } for(int i=0; i<table_size; ++i){ if(max_occ[i] > max){ max = max_occ[i]; element = i; } } if(silent == 0){ std::cout << std::endl << "[+] NOTE: Element " << element << " occurs in " << max << "/" << table_size << " times." << std::endl; } result[0] = element; result[1] = max; return result; } std::vector<int> cipherTWO::attack(int* m, int* c, int silent=0){ const int table_size = 16; int v_diff = 0; int pair_cnt; std::vector<int> possible_keys; int m_size = sizeof(m)/sizeof(int); int c_size = sizeof(c)/sizeof(int); if(m_size == 0 || c_size == 0) return (std::vector<int>)1; if(m_size != c_size){ if(m_size > c_size){ pair_cnt = c_size; } else { pair_cnt = m_size; } } else { pair_cnt = m_size; } if(silent == 0){ std::cout << "Attacking with:" << std::endl << "---" << std::endl; for(int i=0; i<m_size; ++i){ std::cout << "m" << i << ": " << int(m[i]) << std::endl; std::cout << "c" << i << ": " << int(c[i]) << std::endl; } std::cout << "---" << std::endl; } for(int i=0; i<pair_cnt; ++i){ m[i] %= 16; c[i] %= 16; //m_diff ^= m[i]; } int v_[pair_cnt]; int u_[pair_cnt]; int w_[pair_cnt]; int x_[pair_cnt]; for(int i=0; i<table_size; ++i){ int c_diff = 0; for(int j=0; j<pair_cnt; ++j){ x_[j] = c[j] ^ i; w_[j] = getSBox_inv(v_[j]); } for(int j=0; j<pair_cnt; ++j){ c_diff ^= w_[j]; } if(c_diff == v_diff) possible_keys.push_back(i); } if(silent == 0){ int keys_size = possible_keys.size(); if(keys_size > 0){ std::cout << std::endl << "Results:" << std::endl << "---" << std::endl; if(keys_size == 1){ std::cout << "Possible key: "; } else { std::cout << "Possible keys: "; } for(int i=0; i<keys_size; ++i){ if(i != keys_size-1) std::cout << possible_keys[i] << ", "; else std::cout << possible_keys[i] << std::endl; } std::cout << "---" << std::endl; } else { std::cout << "[-]" << " Warning: " << "I found no possible keys... :-(" << std::endl; } } return possible_keys; } /* * Signals: * 0 - too few arguments * 1 - too many arguments, run if possible but return warning. * 2 - weird character type. Stop and return error. */ void cipherTWO::error_handler(char* programname, int signal){ switch(signal){ case 0: usage(programname); std::cout << std::endl; std::cout << "[-] Error:" << " You gave me too few arguments." << std::endl; break; case 1: //usage(programname); std::cout << std::endl; std::cout << "[-] Warning:" << " You entered more arguments than expected." << " I will only choose the first few..." << std::endl << std::endl; break; case 2: usage(programname); std::cout << std::endl; std::cout << "[-] Error:" << " You gave me weird characters." << " I can't handle these characters. Stopping." << std::endl; break; } } void cipherTWO::usage(char* programname){ std::cout << programname << " " << get_version() << " usage: " << std::endl << "###" << std::endl << "----" << std::endl << " [-e|--encrypt] <message byte> <key byte 0> <key byte 1> <key byte 2>:" << " Encrypt plaintext-byte with cipherTWO." << std::endl << " [-d|--decrypt] <cipher byte> <key byte 0> <key byte 1> <key byte 2>:" << " Decrypt cipher-byte with cipherTWO." << std::endl << " [-a|--attack] <message byte 0> <message byte 1> <cipher byte 0> <cipher byte 1>:" << " Attack cipherTWO via a differential attack. (Chosen-Plaintext Attack)" << std::endl << " [-as|--analyse-sbox] <character>:" << " Analyse S-Box for given character" << std::endl << " [-h|--help]:" << " Print this help message." << std::endl << "----" << std::endl; // << std::endl << std::endl // << "License" // << std::endl // << "###" // << std::endl // << "Copyright (C) 2016 Yakup Ates <Yakup Ates@rub.de>" // << std::endl // << programname << " " << get_version() // << " comes with ABSOLUTELY NO WARRANTY." // << std::endl // << "You may redistribute copies of " // << programname << " " << get_version() // << " under the terms of the GNU General Public License." // << std::endl; } int main(int argc, char** argv){ cipherTWO cipher; if(argc == 1){ cipher.usage(argv[0]); return 1; } if((std::string(argv[1]) == "-h") || (std::string(argv[1]) == "--help")){ cipher.usage(argv[0]); } else if((std::string(argv[1]) == "-e") || (std::string(argv[1]) == "--encrypt")){ int expect_arg_cnt = cipher.get_k_cnt()+3; if(argc < expect_arg_cnt){ cipher.error_handler(argv[0], 0); return 1; } else if(argc > expect_arg_cnt){ cipher.error_handler(argv[0], 1); } int key[cipher.get_k_cnt()] = {atoi(argv[3]), atoi(argv[4]), atoi(argv[5])}; //cipher.setKey(key); cipher.encrypt(atoi(argv[2]), key); } else if((std::string(argv[1]) == "-d") || (std::string(argv[1]) == "--decrypt")){ int expect_arg_cnt = cipher.get_k_cnt()+3; if(argc < expect_arg_cnt){ cipher.error_handler(argv[0], 0); return 1; } else if(argc > expect_arg_cnt){ cipher.error_handler(argv[0], 1); } int key[cipher.get_k_cnt()] = {atoi(argv[3]), atoi(argv[4]), atoi(argv[5])}; //cipher.setKey(key); cipher.decrypt(atoi(argv[2]), key); } else if((std::string(argv[1]) == "-a") || (std::string(argv[1]) == "--attack")){ int expect_arg_cnt = 6; int count_pair = 2; if(argc < expect_arg_cnt){ cipher.error_handler(argv[0], 0); return 1; } else if(argc > expect_arg_cnt){ cipher.error_handler(argv[0], 1); } int m[count_pair] = {atoi(argv[2]), atoi(argv[3])}; int c[count_pair] = {atoi(argv[4]), atoi(argv[5])}; cipher.attack(m, c); } else if((std::string(argv[1]) == "-as") || (std::string(argv[1]) == "--analyse-sbox")){ int expect_arg_cnt = 2; if(argc < expect_arg_cnt){ cipher.error_handler(argv[0], 0); return 1; } else if(argc > expect_arg_cnt){ int char_test = atoi(argv[2]); cipher.get_influence_SBox(char_test); } else if(argc > expect_arg_cnt+1){ cipher.error_handler(argv[0], 1); int char_test = atoi(argv[2]); cipher.get_influence_SBox(char_test); } else { cipher.get_influence_SBox(); } } else { cipher.usage(argv[0]); } return 0; }
y-ates/CryptAnalysis
symmetric/cipherTWO/cipherTWO.cpp
C++
gpl-3.0
11,805
# -*- coding: utf-8 -*- from sqlalchemy import create_engine from sqlalchemy import Column, Integer, String, UniqueConstraint from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('sqlite:///challenge.sqlite', echo=False) Session = sessionmaker(bind=engine) session = Session() Base = declarative_base() class Endereco(Base): __tablename__ = "endereco" #id = Column(Integer, primary_key=True) logradouro = Column(String) bairro = Column(String) cidade = Column(String) estado = Column(String) cep = Column(String, primary_key=True) __table_args__ = (UniqueConstraint('cep'),) def __repr__(self): return "{}".format(self.cep) Base.metadata.create_all(engine)
alfredocdmiranda/challenge-cep
models.py
Python
gpl-3.0
782
/* * Copyright (c) 2016 The Ontario Institute for Cancer Research. All rights reserved. * * This program and the accompanying materials are made available under the terms of the GNU Public License v3.0. * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.icgc.dcc.common.test.mongodb; import static com.google.common.base.Preconditions.checkState; import java.io.File; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.jongo.Jongo; import org.jongo.MongoCollection; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Charsets; import com.google.common.io.Files; import com.mongodb.DB; @Slf4j public class MongoExporter extends BaseMongoImportExport { public MongoExporter(File targetDirectory, DB targetDatabase) { super(targetDirectory, new Jongo(targetDatabase)); } @Override @SneakyThrows public void execute() { for(String collectionName : jongo.getDatabase().getCollectionNames()) { MongoCollection collection = jongo.getCollection(collectionName); String fileName = getFileName(collectionName); File collectionFile = new File(directory, fileName); log.info("Exporting to '{}' from '{}'...", collectionFile, collection); exportCollection(collectionFile, collection); } } @SneakyThrows private void exportCollection(File collectionFile, MongoCollection collection) { Files.createParentDirs(collectionFile); if(collectionFile.exists()) { checkState(collectionFile.delete(), "Collection file not deleted: %s", collectionFile); } checkState(collectionFile.createNewFile(), "Collection file not created: %s", collectionFile); ObjectMapper mapper = new ObjectMapper(); for(JsonNode jsonNode : collection.find().as(JsonNode.class)) { String json = mapper.writeValueAsString(jsonNode) + System.getProperty("line.separator"); Files.append(json, collectionFile, Charsets.UTF_8); } } }
icgc-dcc/dcc-common
dcc-common-test/src/main/java/org/icgc/dcc/common/test/mongodb/MongoExporter.java
Java
gpl-3.0
3,427
package net.minecraft.src; import java.util.Random; public class EntityExplodeFX extends EntityFX { public EntityExplodeFX(World par1World, double par2, double par4, double par6, double par8, double par10, double par12) { super(par1World, par2, par4, par6, par8, par10, par12); motionX = par8 + (double)((float)(Math.random() * 2D - 1.0D) * 0.05F); motionY = par10 + (double)((float)(Math.random() * 2D - 1.0D) * 0.05F); motionZ = par12 + (double)((float)(Math.random() * 2D - 1.0D) * 0.05F); particleRed = particleGreen = particleBlue = rand.nextFloat() * 0.3F + 0.7F; particleScale = rand.nextFloat() * rand.nextFloat() * 6F + 1.0F; particleMaxAge = (int)(16D / ((double)rand.nextFloat() * 0.80000000000000004D + 0.20000000000000001D)) + 2; } /** * Called to update the entity's position/logic. */ public void onUpdate() { prevPosX = posX; prevPosY = posY; prevPosZ = posZ; if (particleAge++ >= particleMaxAge) { setDead(); } setParticleTextureIndex(7 - (particleAge * 8) / particleMaxAge); motionY += 0.0040000000000000001D; moveEntity(motionX, motionY, motionZ); motionX *= 0.89999997615814209D; motionY *= 0.89999997615814209D; motionZ *= 0.89999997615814209D; if (onGround) { motionX *= 0.69999998807907104D; motionZ *= 0.69999998807907104D; } } }
sethten/MoDesserts
mcp50/src/minecraft/net/minecraft/src/EntityExplodeFX.java
Java
gpl-3.0
1,510
<?php /** * This configuration will be read and overlaid on top of the * default configuration. Command line arguments will be applied * after this file is read. */ return [ // A list of directories that should be parsed for class and // method information. After excluding the directories // defined in exclude_analysis_directory_list, the remaining // files will be statically analyzed for errors. // // Thus, both first-party and third-party code being used by // your application should be included in this list. 'directory_list' => [ 'src/', 'sample/inc/', 'tests/', 'vendor/filp/whoops/src/Whoops/', 'vendor/guzzlehttp/guzzle/src/', 'vendor/guzzlehttp/promises/src/', 'vendor/guzzlehttp/psr7/src/', 'vendor/monolog/monolog/src/Monolog/', 'vendor/phpunit/phpunit/src/', 'vendor/psr/http-message/src/', 'vendor/respect/validation/library/', 'vendor/symfony/var-dumper/', 'vendor/vlucas/phpdotenv/src/', 'vendor/zonuexe/objectsystem/src/', 'vendor/zonuexe/simple-routing/src/', ], 'file_list' => [ 'sample/public/index.php', 'src/functions.php', 'src/Entity/helpers.php', ], // A directory list that defines files that will be excluded // from static analysis, but whose class and method // information should be included. // // Generally, you'll want to include the directories for // third-party code (such as "vendor/") in this list. // // n.b.: If you'd like to parse but not analyze 3rd // party code, directories containing that code // should be added to the `directory_list` as // to `excluce_analysis_directory_list`. "exclude_analysis_directory_list" => [ 'vendor/' ], ];
BaguettePHP/mastodon-api
.phan/config.php
PHP
gpl-3.0
1,858
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Tool * @subpackage Framework * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Action.php 24594 2012-01-05 21:27:01Z matthew $ */ /** * @see Zend_Tool_Project_Provider_Abstract */ require_once 'Zend/Tool/Project/Provider/Abstract.php'; /** * @see Zend_Tool_Framework_Provider_Pretendable */ require_once 'Zend/Tool/Framework/Provider/Pretendable.php'; /** * @category Zend * @package Zend_Tool * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Tool_Project_Provider_Action extends Zend_Tool_Project_Provider_Abstract implements Zend_Tool_Framework_Provider_Pretendable { /** * createResource() * * @param Zend_Tool_Project_Profile $profile * @param string $actionName * @param string $controllerName * @param string $moduleName * @return Zend_Tool_Project_Profile_Resource */ public static function createResource(Zend_Tool_Project_Profile $profile, $actionName, $controllerName, $moduleName = null) { if (!is_string($actionName)) { throw new Zend_Tool_Project_Provider_Exception('Zend_Tool_Project_Provider_Action::createResource() expects \"actionName\" is the name of a action resource to create.'); } if (!is_string($controllerName)) { throw new Zend_Tool_Project_Provider_Exception('Zend_Tool_Project_Provider_Action::createResource() expects \"controllerName\" is the name of a controller resource to create.'); } $controllerFile = self::_getControllerFileResource($profile, $controllerName, $moduleName); $actionMethod = $controllerFile->createResource('ActionMethod', array('actionName' => $actionName)); return $actionMethod; } /** * hasResource() * * @param Zend_Tool_Project_Profile $profile * @param string $actionName * @param string $controllerName * @param string $moduleName * @return Zend_Tool_Project_Profile_Resource */ public static function hasResource(Zend_Tool_Project_Profile $profile, $actionName, $controllerName, $moduleName = null) { if (!is_string($actionName)) { throw new Zend_Tool_Project_Provider_Exception('Zend_Tool_Project_Provider_Action::createResource() expects \"actionName\" is the name of a action resource to create.'); } if (!is_string($controllerName)) { throw new Zend_Tool_Project_Provider_Exception('Zend_Tool_Project_Provider_Action::createResource() expects \"controllerName\" is the name of a controller resource to create.'); } $controllerFile = self::_getControllerFileResource($profile, $controllerName, $moduleName); if ($controllerFile == null) { throw new Zend_Tool_Project_Provider_Exception('Controller ' . $controllerName . ' was not found.'); } return (($controllerFile->search(array('actionMethod' => array('actionName' => $actionName)))) instanceof Zend_Tool_Project_Profile_Resource); } /** * _getControllerFileResource() * * @param Zend_Tool_Project_Profile $profile * @param string $controllerName * @param string $moduleName * @return Zend_Tool_Project_Profile_Resource */ protected static function _getControllerFileResource(Zend_Tool_Project_Profile $profile, $controllerName, $moduleName = null) { $profileSearchParams = array(); if ($moduleName != null && is_string($moduleName)) { $profileSearchParams = array('modulesDirectory', 'moduleDirectory' => array('moduleName' => $moduleName)); } $profileSearchParams[] = 'controllersDirectory'; $profileSearchParams['controllerFile'] = array('controllerName' => $controllerName); return $profile->search($profileSearchParams); } /** * create() * * @param string $name Action name for controller, in camelCase format. * @param string $controllerName Controller name action should be applied to. * @param bool $viewIncluded Whether the view should the view be included. * @param string $module Module name action should be applied to. */ public function create($name, $controllerName = 'Index', $viewIncluded = true, $module = null) { $this->_loadProfile(); // get request/response object $request = $this->_registry->getRequest(); $response = $this->_registry->getResponse(); // determine if testing is enabled in the project require_once 'Zend/Tool/Project/Provider/Test.php'; $testingEnabled = Zend_Tool_Project_Provider_Test::isTestingEnabled($this->_loadedProfile); if ($testingEnabled && !Zend_Tool_Project_Provider_Test::isPHPUnitAvailable()) { $testingEnabled = false; $response->appendContent( 'Note: PHPUnit is required in order to generate controller test stubs.', array('color' => array('yellow')) ); } // Check that there is not a dash or underscore, return if doesnt match regex if (preg_match('#[_-]#', $name)) { throw new Zend_Tool_Project_Provider_Exception('Action names should be camel cased.'); } $originalName = $name; $originalControllerName = $controllerName; // ensure it is camelCase (lower first letter) $name = strtolower(substr($name, 0, 1)) . substr($name, 1); // ensure controller is MixedCase $controllerName = ucfirst($controllerName); if (self::hasResource($this->_loadedProfile, $name, $controllerName, $module)) { throw new Zend_Tool_Project_Provider_Exception('This controller (' . $controllerName . ') already has an action named (' . $name . ')'); } $actionMethodResource = self::createResource($this->_loadedProfile, $name, $controllerName, $module); $testActionMethodResource = null; if ($testingEnabled) { $testActionMethodResource = Zend_Tool_Project_Provider_Test::createApplicationResource($this->_loadedProfile, $controllerName, $name, $module); } // alert the user about inline converted names $tense = (($request->isPretend()) ? 'would be' : 'is'); if ($name !== $originalName) { $response->appendContent( 'Note: The canonical action name that ' . $tense . ' used with other providers is "' . $name . '";' . ' not "' . $originalName . '" as supplied', array('color' => array('yellow')) ); } if ($controllerName !== $originalControllerName) { $response->appendContent( 'Note: The canonical controller name that ' . $tense . ' used with other providers is "' . $controllerName . '";' . ' not "' . $originalControllerName . '" as supplied', array('color' => array('yellow')) ); } unset($tense); if ($request->isPretend()) { $response->appendContent( 'Would create an action named ' . $name . ' inside controller at ' . $actionMethodResource->getParentResource()->getContext()->getPath() ); if ($testActionMethodResource) { $response->appendContent('Would create an action test in ' . $testActionMethodResource->getParentResource()->getContext()->getPath()); } } else { $response->appendContent( 'Creating an action named ' . $name . ' inside controller at ' . $actionMethodResource->getParentResource()->getContext()->getPath() ); $actionMethodResource->create(); if ($testActionMethodResource) { $response->appendContent('Creating an action test in ' . $testActionMethodResource->getParentResource()->getContext()->getPath()); $testActionMethodResource->create(); } $this->_storeProfile(); } if ($viewIncluded) { $viewResource = Zend_Tool_Project_Provider_View::createResource($this->_loadedProfile, $name, $controllerName, $module); if ($this->_registry->getRequest()->isPretend()) { $response->appendContent( 'Would create a view script for the ' . $name . ' action method at ' . $viewResource->getContext()->getPath() ); } else { $response->appendContent( 'Creating a view script for the ' . $name . ' action method at ' . $viewResource->getContext()->getPath() ); $viewResource->create(); $this->_storeProfile(); } } } }
basdog22/Qool
lib/Zend/Tool/Project/Provider/Action.php
PHP
gpl-3.0
9,863
Vue.http.options.emulateJSON = true; var profile_status = new Vue({ el: '#profile-status', data: { isSuggestShow: 0, suggest: [ {text: 'Предложение оплаты услуг, вирт за деньги, проституция, мошенничество, шантаж, спам', style: 'bg_ored'}, {text: 'Фото из интернета, парень под видои девушки, вымышленные данные, обман, фейк', style: 'bg_ored'}, {text: 'Оскорбления, хамство, троллинг, грубые сообщения, жалобы на интим фото, провокации', style: 'bg_oyel'}, {text: 'Пишет всем подряд, игнорирует анкетные данные, гей пишет натуралам, рассылки', style: 'bg_oyel'}, {text: 'Ложно, отклоненные жалобы, причина не ясна, ссора, выяснение отношений', style: 'bg_ogrn'}, ], text: 'Статус не установлен', style: '', user: '', }, created: function () { this.user = $('#profile-status__text').data('user'); var text = $('#profile-status__text').text().trim(); if (text) { this.text = text; } }, mounted: function () { this.set_style(); }, methods: { variant: function (event) { this.isSuggestShow = true; }, post: function () { if (this.user) { this.$http.post('/userinfo/setcomm/', { id: this.user, text: this.text }); } }, save: function (i) { this.text = this.suggest[i].text; this.style = this.suggest[i].style; this.isSuggestShow = false; this.post(); }, set_style: function () { if (this.text == this.suggest[0].text) { this.style = this.suggest[0].style; }; if (this.text == this.suggest[1].text) { this.style = this.suggest[0].style; }; if (this.text == this.suggest[2].text) { this.style = this.suggest[2].style; }; if (this.text == this.suggest[3].text) { this.style = this.suggest[2].style; }; if (this.text == this.suggest[4].text) { this.style = this.suggest[4].style; }; } } });
4FortyTwo2/sources
javascript/admin/src/profile-status.js
JavaScript
gpl-3.0
2,644
# xVector Engine Client # Copyright (c) 2011 James Buchwald # 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. """ Contains code for nicely reporting errors to the user. """ import logging import traceback from PyQt4 import QtGui from xVClient import ClientGlobals mainlog = logging.getLogger("") # Severity constants FatalError = 1 """Fatal error, forces termination of application.""" NormalError = 2 """Normal error, this has impact but does not crash the program.""" WarningError = 3 """Warning, this does not affect function but should cause concern.""" NoticeError = 4 """General information.""" def ShowError(message, severity=NormalError, parent=None): """ Displays an error message to the user and waits for a response. """ dlg = QtGui.QMessageBox(parent) dlg.setText(message) if severity == FatalError: dlg.setIcon(QtGui.QMessageBox.Critical) dlg.setWindowTitle("Fatal Error") elif severity == NormalError: dlg.setIcon(QtGui.QMessageBox.Critical) dlg.setWindowTitle("Error") elif severity == WarningError: dlg.setIcon(QtGui.QMessageBox.Warning) dlg.setWindowTitle("Warning") elif severity == NoticeError: dlg.setIcon(QtGui.QMessageBox.Information) dlg.setWindowTitle("Notice") else: dlg.setIcon(QtGui.QMessageBox.NoIcon) dlg.setWindowTitle("Message") dlg.exec_() def ShowException(severity=NormalError, start_msg='An error has occurred!', parent=None): ''' Displays the currently-handled exception in an error box. ''' msg = start_msg + "\n\n" + traceback.format_exc() ShowError(msg, severity, parent) class ErrorMessageHandler(logging.Handler): ''' Logging handler that displays messages in Qt message boxes. ''' def __init__(self, parent=None): ''' Creates a new handler. @type parent: QtGui.QWidget @param parent: Parent widget for errors to be displayed under. ''' super(ErrorMessageHandler,self).__init__() self.Parent = parent '''Parent widget for errors to be displayed under.''' def _ShowError(self, message): ''' Shows an error message and returns immediately. @type message: string @param message: Message to display. ''' app = ClientGlobals.Application wnd = QtGui.QMessageBox(parent=self.Parent) wnd.setIcon(QtGui.QMessageBox.Critical) wnd.setWindowTitle("Error") wnd.setStandardButtons(QtGui.QMessageBox.Ok) wnd.setText(message) wnd.exec_() def emit(self, record): self._ShowError(record.getMessage()) def ConfigureLogging(parent=None): ''' Configures the logging mechanism to report errors as dialog boxes. @type parent: QtGui.QWidget @param parent: Parent widget for errors to be displayed under. ''' # Set up the error handler (output to a message box). handler = ErrorMessageHandler(parent) formatter = logging.Formatter("%(message)s") handler.setFormatter(formatter) handler.setLevel(logging.ERROR) mainlog.addHandler(handler) # Send lower-level messages to stderr. lowhandler = logging.StreamHandler() lowhandler.setFormatter(formatter) lowhandler.setLevel(logging.DEBUG) mainlog.addHandler(lowhandler) # Make sure that the logger catches all levels of messages. mainlog.setLevel(logging.DEBUG)
buchwj/xvector
client/xVClient/ErrorReporting.py
Python
gpl-3.0
4,145
/*************************************************************************** * GFitsBinTable.hpp - FITS binary table class * * ----------------------------------------------------------------------- * * copyright (C) 2008-2018 by Juergen Knoedlseder * * ----------------------------------------------------------------------- * * * * 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/>. * * * ***************************************************************************/ /** * @file GFitsBinTable.hpp * @brief FITS binary table class definition * @author Juergen Knoedlseder */ #ifndef GFITSBINTABLE_HPP #define GFITSBINTABLE_HPP /* __ Includes ___________________________________________________________ */ #include "GFitsTable.hpp" /***********************************************************************//** * @class GFitsBinTable * * @brief FITS binary table class ***************************************************************************/ class GFitsBinTable : public GFitsTable { public: // Constructors and destructors GFitsBinTable(void); explicit GFitsBinTable(const int& nrows); GFitsBinTable(const GFitsBinTable& table); virtual ~GFitsBinTable(void); // Operators GFitsBinTable& operator=(const GFitsBinTable& table); // Implemented pure virtual methods virtual void clear(void); virtual GFitsBinTable* clone(void) const; virtual std::string classname(void) const; HDUType exttype(void) const; private: // Private methods void init_members(void); void copy_members(const GFitsBinTable& table); void free_members(void); void init_table_header(void); }; /***********************************************************************//** * @brief Return class name * * @return String containing the class name ("GFitsBinTable"). ***************************************************************************/ inline std::string GFitsBinTable::classname(void) const { return ("GFitsBinTable"); } /***********************************************************************//** * @brief Return extension type * * @return Extension type (HT_BIN_TABLE). ***************************************************************************/ inline GFitsHDU::HDUType GFitsBinTable::exttype(void) const { return (HT_BIN_TABLE); } #endif /* GFITSBINTABLE_HPP */
gammalib/gammalib
include/GFitsBinTable.hpp
C++
gpl-3.0
3,445
# # Test PM force parallelisation: # check force does not depend on number of MPI nodes import fs import numpy as np import h5py import pm_setup # read reference file # $ python3 create_force_h5.py to create file = h5py.File('force_%s.h5' % fs.config_precision(), 'r') ref_id = file['id'][:] ref_force = file['f'][:] file.close() # compute PM force fs.msg.set_loglevel(0) particles = pm_setup.force() particle_id = particles.id particle_force = particles.force # compare two forces if fs.comm.this_node() == 0: assert(np.all(particle_id == ref_id)) print('pm_force id OK') force_rms = np.std(ref_force) diff = particle_force - ref_force diff_rms = np.std(diff) print('pm_force rms error %e / %e' % (diff_rms, force_rms)) diff_max = np.max(np.abs(diff)) print('pm_force max error %e / %e' % (diff_max, force_rms)) eps = np.finfo(particle_force.dtype).eps assert(diff_rms < 20*eps) assert(diff_max < 1000*eps) print('pm_force OK')
junkoda/fs2
test/test_pm_force.py
Python
gpl-3.0
990
//Problem 5. Angle Unit Converter (Degrees ↔ Radians) //Write a method to convert from degrees to radians. Write a method to convert from radians to degrees. // You are given a number n and n queries for conversion. Each conversion query will consist of a // number + space + measure. Measures are "deg" and "rad". Convert all radians to degrees and all // degrees to radians. Print the results as n lines, each holding a number + space + measure. Format // all numbers with 6 digit after the decimal point. import java.util.ArrayList; import java.util.DoubleSummaryStatistics; import java.util.List; import java.util.Scanner; public class _5_AngleUnitConverterDegreesRadians { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter how many calculation you want to make"); int n = Integer.parseInt(input.nextLine()); List<String> result = new ArrayList<String>(); for (int i = 0; i < n; i++) { String[] cmd = input.nextLine().split(" "); String currentResult; if (cmd[1].equals("rad")) { currentResult = Math.toDegrees(Double.parseDouble(cmd[0])) + " deg"; } else { currentResult = Math.toDegrees(Double.parseDouble(cmd[0])) + " rad"; } result.add(currentResult); } System.out.println(String.join("\n", result)); } }
emrah-it/Softuni
Level 1/Java Basics/Loops Methods Classes/Loops Methods Classes/src/_5_AngleUnitConverterDegreesRadians.java
Java
gpl-3.0
1,330
/* 読み太(yomita), a USI shogi (Japanese chess) playing engine derived from Stockfish 7 & YaneuraOu mid 2016 V3.57 Copyright (C) 2004-2008 Tord Romstad (Glaurung author) Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad (Stockfish author) Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad (Stockfish author) Copyright (C) 2015-2016 Motohiro Isozaki(YaneuraOu author) Copyright (C) 2016-2017 Ryuzo Tukamoto 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/>. */ #define _CRT_SECURE_NO_WARNINGS 1 #ifdef _WIN32 #if _WIN32_WINNT < 0x0601 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0601 #endif #ifdef _MSC_VER #include <windows.h> #endif extern "C" { typedef bool(*fun1_t)(LOGICAL_PROCESSOR_RELATIONSHIP, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX, PDWORD); typedef bool(*fun2_t)(USHORT, PGROUP_AFFINITY); typedef bool(*fun3_t)(HANDLE, CONST GROUP_AFFINITY*, PGROUP_AFFINITY); } #endif #include <vector> #include <fstream> #include <iomanip> #include <sstream> #include <iostream> #include <codecvt> #ifndef _MSC_VER #include <sys/stat.h> #include <sys/types.h> #endif #include "common.h" #include "thread.h" using namespace std; namespace WinProcGroup { #ifndef _MSC_VER void bindThisThread(size_t) {}; #else int getGroup(size_t idx) { int threads = 0; int nodes = 0; int cores = 0; DWORD return_length = 0; DWORD byte_offset = 0; HMODULE k32 = GetModuleHandle(TEXT("Kernel32.dll")); auto fun1 = (fun1_t)GetProcAddress(k32, "GetLogicalProcessorInformationEx"); if (!fun1) return -1; if (fun1(RelationAll, nullptr, &return_length)) return -1; SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, *ptr; ptr = buffer = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)malloc(return_length); if (!fun1(RelationAll, buffer, &return_length)) { free(buffer); return -1; } while (ptr->Size > 0 && byte_offset + ptr->Size <= return_length) { if (ptr->Relationship == RelationNumaNode) nodes++; else if (ptr->Relationship == RelationProcessorCore) { cores++; threads += (ptr->Processor.Flags == LTP_PC_SMT) ? 2 : 1; } byte_offset += ptr->Size; ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)(((char*)ptr) + ptr->Size); } free(buffer); std::vector<int> groups; for (int n = 0; n < nodes; n++) for (int i = 0; i < cores / nodes; i++) groups.push_back(n); for (int t = 0; t < threads - cores; t++) groups.push_back(t % nodes); return idx < groups.size() ? groups[idx] : -1; } void bindThisThread(size_t idx) { if (Threads.size() < 8) return; int group = getGroup(idx); if (group == -1) return; HMODULE k32 = GetModuleHandle(TEXT("Kernel32.dll")); auto fun2 = (fun2_t)GetProcAddress(k32, "GetNumaNodeProcessorMaskEx"); auto fun3 = (fun3_t)GetProcAddress(k32, "SetThreadGroupAffinity"); if (!fun2 || !fun3) return; GROUP_AFFINITY affinity; if (fun2(group, &affinity)) fun3(GetCurrentThread(), &affinity, nullptr); } #endif } // namespace WinProcGroup // logging用のhack。streambufをこれでhookしてしまえば追加コードなしで普通に // cinからの入力とcoutへの出力をファイルにリダイレクトできる。 // cf. http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81 struct Tie : public streambuf { Tie(streambuf* buf_, streambuf* log_) : buf(buf_), log(log_) {} int sync() { return log->pubsync(), buf->pubsync(); } int overflow(int c) { return write(buf->sputc((char)c), "<< "); } int underflow() { return buf->sgetc(); } int uflow() { return write(buf->sbumpc(), ">> "); } int write(int c, const char* prefix) { static int last = '\n'; if (last == '\n') log->sputn(prefix, 3); return last = log->sputc((char)c); } streambuf *buf, *log; // 標準入出力 , ログファイル }; struct Logger { static void start(bool b) { static Logger log; if (b && !log.file.is_open()) { log.file.open("io_log.txt", ifstream::out); cin.rdbuf(&log.in); cout.rdbuf(&log.out); cout << "start logger" << endl; } else if (!b && log.file.is_open()) { cout << "end logger" << endl; cout.rdbuf(log.out.buf); cin.rdbuf(log.in.buf); log.file.close(); } } private: Tie in, out; // 標準入力とファイル、標準出力とファイルのひも付け ofstream file; // ログを書き出すファイル Logger() : in(cin.rdbuf(), file.rdbuf()), out(cout.rdbuf(), file.rdbuf()) {} ~Logger() { start(false); } }; void startLogger(bool b) { Logger::start(b); } // ファイルを丸読みする。ファイルが存在しなくともエラーにはならない。空行はスキップする。 int readAllLines(std::string filename, std::vector<std::string>& lines) { fstream fs(filename, ios::in); if (fs.fail()) return 1; // 読み込み失敗 while (!fs.fail() && !fs.eof()) { std::string line; getline(fs, line); if (line.length()) lines.push_back(line); } fs.close(); return 0; } // 現在の日にち、曜日、時刻を表す文字列を返す。 std::string localTime() { auto now = std::chrono::system_clock::now(); auto tp = std::chrono::system_clock::to_time_t(now); return std::ctime(&tp); } // YYYYMMDD形式で現在時刻を秒まで。 std::string timeStamp() { char buff[20] = ""; time_t now = time(NULL); struct tm *pnow = localtime(&now); sprintf(buff, "%04d%02d%02d%02d%02d%02d", pnow->tm_year + 1900, pnow->tm_mon + 1, pnow->tm_mday, pnow->tm_hour, pnow->tm_min, pnow->tm_sec); return std::string(buff); } std::string path(const std::string& folder, const std::string& filename) { if (folder.length() >= 1 && *folder.rbegin() != '/' && *folder.rbegin() != '\\') return folder + "/" + filename; return folder + filename; } void _mkdir(std::string dir) { #ifdef _MSC_VER std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cv; if (_wmkdir(cv.from_bytes(dir).c_str()) == -1) #else #ifdef _WIN32 if (mkdir(dir.c_str()) == -1) #else if (mkdir(dir.c_str(), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH | S_IXOTH ) == -1) #endif #endif { if (errno == EEXIST) std::cout << "ディレクトリは dirname が既存のファイル、ディレクトリ、またはデバイスの名前であるため生成されませんでした。" << std::endl; else if (errno == ENOENT) std::cout << "パスが見つかりませんでした。" << std::endl; } }
TukamotoRyuzo/Yomita
yomita/yomita/src/common.cpp
C++
gpl-3.0
7,828
package ch.awae.moba.core.operators; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Indicates whether an operator is enabled or not. * * Enabled operators are activated by default during startup. * * <p> * This annotation defaults to {@code enabled}; therefore {@code @Enabled} is * equivalent to {@code @Enabled(true)}. To disable an operator annotate it with * {@code @Enabled(false)}. * </p> * * @author Andreas Wälchli * @see IOperation */ @Retention(RetentionPolicy.RUNTIME) public @interface Enabled { boolean value() default true; }
ksmonkey123/ModellbahnCore
src/ch/awae/moba/core/operators/Enabled.java
Java
gpl-3.0
608
#!/usr/bin/env python from distutils.core import setup import os import sys def main(): SHARE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "share") data_files = [] # don't trash the users system icons!! black_list = ['index.theme', 'index.theme~'] for path, dirs, files in os.walk(SHARE_PATH): data_files.append(tuple((path.replace(SHARE_PATH,"share", 1), [os.path.join(path, file) for file in files if file not in black_list]))) setup(name="caffeine", version="2.4.1", description="""A status bar application able to temporarily prevent the activation of both the screensaver and the "sleep" powersaving mode.""", author="The Caffeine Developers", author_email="bnsmith@gmail.com", url="https://launchpad.net/caffeine", packages=["caffeine"], data_files=data_files, scripts=[os.path.join("bin", "caffeine")] ) if __name__ == "__main__": main()
ashh87/caffeine
setup.py
Python
gpl-3.0
1,042
<?php /** * @version $Id$ * @package Joomla * @subpackage NoK-PrjMgnt * @copyright Copyright (c) 2017 Norbert Kuemin. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE * @author Norbert Kuemin * @authorEmail momo_102@bluemail.ch */ // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); class NoKPrjMgntViewProjectComment extends JViewLegacy { protected $item; protected $pageHeading = 'COM_NOKPRJMGNT_PAGE_TITLE_DEFAULT'; protected $paramsComponent; protected $paramsMenuEntry; protected $user; protected $viewAccessLevels; protected $canDo; function display($tpl = null) { // Init variables $this->state = $this->get('State'); $this->user = JFactory::getUser(); $app = JFactory::getApplication(); $this->document = JFactory::getDocument(); $id = JFactory::getURI()->getVar('id'); if (!empty($id)) { $this->item = $this->getModel()->getItem($id); $this->canDo = JHelperContent::getActions('com_nokprjmgnt','project',$this->item->project_id); } else{ $this->canDo = JHelperContent::getActions('com_nokprjmgnt'); } $this->form = $this->get('Form'); $this->paramsComponent = $this->state->get('params'); $menu = $app->getMenu(); if (is_object($menu)) { $currentMenu = $menu->getActive(); if (is_object($currentMenu)) { $this->paramsMenuEntry = $currentMenu->params; } } // Init document JFactory::getDocument()->setMetaData('robots', 'noindex, nofollow'); parent::display($tpl); } } ?>
momo10216/nokprjmgnt
site/views/projectcomment/view.html.php
PHP
gpl-3.0
1,536
// {{{ GPL License // This file is part of gringo - a grounder for logic programs. // Copyright (C) 2013 Roland Kaminski // 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/>. // }}} #ifndef _GRINGO_UNIQUE_LIST_HH #define _GRINGO_UNIQUE_LIST_HH #include <functional> #include <algorithm> #include <memory> #include <cassert> #include <gringo/utility.hh> namespace Gringo { // {{{ declaration of unique_list template <class Value> struct unique_list_node { template <class... Args> explicit unique_list_node(Args&&... args) : value(std::forward<Args>(args)...) , hash(0) , succ(nullptr) , prev(nullptr) { } using node_type = unique_list_node; using node_ptr_type = std::unique_ptr<node_type>; Value value; size_t hash; unique_list_node *succ; unique_list_node *prev; node_ptr_type eqSucc; }; template <class Value> class unique_list_iterator : public std::iterator<std::bidirectional_iterator_tag, Value, int> { using iterator = std::iterator<std::bidirectional_iterator_tag, Value, int>; public: template <class V, class X, class H, class E> friend struct unique_list; template <class V> friend struct unique_list_const_iterator; unique_list_iterator() : _node(nullptr) { } unique_list_iterator(unique_list_iterator const &x) = default; unique_list_iterator& operator=(const unique_list_iterator&) = default; bool operator==(const unique_list_iterator &x) const { return _node == x._node; } bool operator!=(const unique_list_iterator &x) const { return _node != x._node; } unique_list_iterator& operator++() { _node = _node->succ; return *this; } unique_list_iterator operator++(int) { unique_list_iterator x = *this; ++(*this); return x; } unique_list_iterator& operator--() { _node = _node->prev; return *this; } unique_list_iterator operator--(int) { unique_list_iterator x = *this; --(*this); return x; } typename iterator::reference operator*() const { return _node->value; } typename iterator::pointer operator->() const { return &_node->value; } private: using node_type = unique_list_node<Value>; unique_list_iterator(node_type *node) : _node(node) { } node_type *_node; }; template <class Value> class unique_list_const_iterator : public std::iterator<std::bidirectional_iterator_tag, Value const, int> { using iterator = std::iterator<std::bidirectional_iterator_tag, Value const, int>; public: template <class V, class X, class H, class E> friend struct unique_list; unique_list_const_iterator() : _node(nullptr) { } unique_list_const_iterator(unique_list_const_iterator const &x) = default; unique_list_const_iterator(unique_list_iterator<Value> const &x) : _node(x._node) { } unique_list_const_iterator& operator=(const unique_list_const_iterator&) = default; bool operator==(const unique_list_const_iterator &x) const { return _node == x._node; } bool operator!=(const unique_list_const_iterator &x) const { return _node != x._node; } unique_list_const_iterator& operator++() { _node = _node->succ; return *this; } unique_list_const_iterator operator++(int) { unique_list_const_iterator x = *this; ++(*this); return x; } unique_list_const_iterator& operator--() { _node = _node->prev; return *this; } unique_list_const_iterator operator--(int) { unique_list_const_iterator x = *this; --(*this); return x; } typename iterator::reference operator*() const { return _node->value; } typename iterator::pointer operator->() const { return &_node->value; } private: using node_type = unique_list_node<Value>; unique_list_const_iterator(node_type *node) : _node(node) { } node_type *_node; }; template <class T> struct identity { using result_type = T; template <class U> T const &operator()(U const &x) const { return x; } }; template <class T> struct extract_first { using result_type = T; template <class U> T const &operator()(U const &x) const { return std::get<0>(x); } }; template < class Value, class ExtractKey = identity<Value>, class Hasher = std::hash<typename ExtractKey::result_type>, class EqualTo = std::equal_to<typename ExtractKey::result_type> > class unique_list : Hasher, EqualTo, ExtractKey { using node_type = unique_list_node<Value>; using node_ptr_type = typename node_type::node_ptr_type; using buckets_type = std::unique_ptr<node_ptr_type[]>; public: using hasher = Hasher; using key_equal = EqualTo; using key_extract = ExtractKey; using key_type = typename key_extract::result_type; using value_type = Value; using reference = Value &; using const_reference = Value const &; using difference_type = int; using size_type = unsigned; using iterator = unique_list_iterator<Value>; using reverse_iterator = std::reverse_iterator<iterator>; using const_iterator = unique_list_const_iterator<Value>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; unique_list() : _size(0) , _reserved(0) , _front(0) , _back(0) , _buckets(nullptr) { } unique_list(unique_list &&list) : hasher(std::move(list)) , key_equal(std::move(list)) , _size(list._size) , _reserved(list._reserved) , _front(list._front) , _back(list._back) , _buckets(std::move(list._buckets)) { list.clear(); } unique_list &operator=(unique_list &&list) { static_cast<Hasher&>(*this) = std::move(list); static_cast<EqualTo&>(*this) = std::move(list); _size = list._size; _reserved = list._reserved; _front = list._front; _back = list._back; _buckets = std::move(list._buckets); list.clear(); return *this; } unsigned reserved() const { return _reserved; } unsigned size() const { return _size; } bool empty() const { return !_size; } double max_load_factor() const { return 0.9; } double load_factor() const { return (size() + 1.0) / reserved(); } void clear() { _size = 0; _reserved = 0; _front = nullptr; _back = nullptr; _buckets.reset(nullptr); } void reserve(unsigned n) { if (_reserved < n) { unsigned reserved(_reserved * 1.5); if (n < 5 || (reserved <= n)) { reserved = n; } else { do { reserved *= 1.5; } while (reserved < n); } if (_buckets) { buckets_type buckets(new node_ptr_type[reserved]); std::swap(reserved, _reserved); std::swap(buckets, _buckets); for (auto it = buckets.get(), ie = buckets.get() + reserved; it != ie; ++it) { node_ptr_type pos{std::move(*it)}; while (pos) { node_ptr_type next{std::move(pos->eqSucc)}; move(std::move(pos)); pos = std::move(next); } } } else { _buckets.reset(new node_ptr_type[reserved]); _reserved = reserved; } } } template <class... Args> std::pair<iterator, bool> emplace_back(Args&&... args) { if (load_factor() >= max_load_factor()) { reserve(reserved() + 1); } node_ptr_type node(new node_type(std::forward<Args>(args)...)); node->hash = static_cast<hasher&>(*this)(static_cast<key_extract&>(*this)(node->value)); return push_back(std::move(node)); } iterator erase(const_iterator x) { (x._node->prev ? x._node->prev->succ : _front) = x._node->succ; (x._node->succ ? x._node->succ->prev : _back ) = x._node->prev; iterator ret(x._node->succ); std::reference_wrapper<node_ptr_type> pos{get_bucket(x._node->hash)}; while (pos.get().get() != x._node) { pos = pos.get()->eqSucc; } pos.get() = std::move(pos.get()->eqSucc); --_size; return ret; } size_type erase(key_type const &x) { auto it(static_cast<unique_list const*>(this)->find(x)); if (it != end()) { erase(it); return 1; } else { return 0; } } iterator erase(const_iterator a, const_iterator b) { if (a != b) { (a._node->prev ? a._node->prev->succ : _front) = b._node; (b._node ? b._node->prev : _back ) = a._node->prev; while (a != b) { auto c = a++; std::reference_wrapper<node_ptr_type> pos{get_bucket(c._node->hash)}; while (pos.get().get() != c._node) { pos = pos.get()->eqSucc; } pos.get() = std::move(pos.get()->eqSucc); --_size; } } return b._node; } void swap(unique_list &list) { std::swap(static_cast<hasher&>(*this), static_cast<hasher&>(list)); std::swap(static_cast<key_equal&>(*this), static_cast<key_equal&>(list)); std::swap(static_cast<key_extract&>(*this), static_cast<key_extract&>(list)); std::swap(_size, list._size); std::swap(_reserved, list._reserved); std::swap(_front, list._front); std::swap(_back, list._back); std::swap(_buckets, list._buckets); } iterator find(key_type const &x) { return static_cast<unique_list const*>(this)->find(x)._node; } const_iterator find(key_type const &x) const { if (!empty()) { std::reference_wrapper<node_ptr_type> pos{get_bucket((this->*(&Hasher::operator()))(x))}; while (pos.get()) { if (static_cast<key_equal const &>(*this)( static_cast<key_extract const &>(*this)(pos.get()->value), x )) { return pos.get().get(); } pos = pos.get()->eqSucc; } } return end(); } const_iterator begin() const { return const_iterator(_front); } const_iterator end() const { return const_iterator(); } iterator begin() { return iterator(_front); } iterator end() { return iterator(); } reverse_iterator rbegin() { return reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } value_type const &front() const { return _front->value; } value_type const &back() const { return _back->value; } value_type &front() { return _front->value; } value_type &back() { return _back->value; } private: std::pair<iterator, bool> push_back(node_ptr_type&& node) { std::reference_wrapper<node_ptr_type> pos{get_bucket(node)}; while (pos.get()) { if (static_cast<key_equal&>(*this)( static_cast<key_extract&>(*this)(pos.get()->value), static_cast<key_extract&>(*this)(node->value))) { return {iterator(pos.get().get()), false}; } pos = pos.get()->eqSucc; } pos.get() = std::move(node); ++_size; if (_back) { pos.get()->prev = _back; _back->succ = pos.get().get(); } else { _front = pos.get().get(); } _back = pos.get().get(); return {iterator(pos.get().get()), true}; } node_ptr_type& get_bucket(size_t hash) const { assert(_reserved); return _buckets[hash_mix(hash) % _reserved]; } node_ptr_type& get_bucket(node_ptr_type const &node) const { assert(_reserved); return get_bucket(node->hash); } void move(node_ptr_type&& node) { node_ptr_type& ret = get_bucket(node); node->eqSucc = std::move(ret); ret = std::move(node); } unsigned _size; unsigned _reserved; node_type *_front; node_type *_back; buckets_type _buckets; }; // }}} } // namespace Gringo #endif // _GRINGO_UNIQUE_LIST_HH
lc2casp/lc2casp
third_party/gringo/libgringo/gringo/unique_list.hh
C++
gpl-3.0
13,437
/* Copyright (C) 2013 Bryan Hughes <bryan@theoreticalideations.com> This file is part of Aquarium Control. Aquarium Control is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Aquarium Control is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Aquarium Control. If not, see <http://www.gnu.org/licenses/>. */ var path = require('path'), exec = require('child_process').exec, STATE_OFF = 'off', STATE_DAY = 'day', STATE_NIGHT = 'night', driverPath = path.join(__dirname, '..', '..', 'driver', 'driver.py'); function log(level, message) { process.send({ destination: 'master', type: 'log', data: { level: level, message: message } }); } exec(driverPath + ' off'); log('info', 'Controller started'); process.on('message', function (message) { if (message.type === 'lights.set') { process.send({ destination: 'master', type: 'log', data: { level: 'info', message: 'State change: ' + message.data } }); switch(message.data) { case STATE_OFF: exec(driverPath + ' off'); break; case STATE_DAY: exec(driverPath + ' day'); break; case STATE_NIGHT: exec(driverPath + ' night'); break; } } });
rakesh-mohanta/aquarium-control
server/src/controller.js
JavaScript
gpl-3.0
1,615
FactoryGirl.define do factory :exported_web_vuln, :parent => :mdm_web_vuln do blame { generate :mdm_web_vuln_blame } description { generate :mdm_web_vuln_description } end sequence :mdm_web_vuln_blame do |n| "Blame employee ##{n}" end sequence :mdm_web_vuln_description do |n| "Mdm::WebVuln#description #{n}" end end
cSploit/android.MSF
spec/factories/mdm/exported_web_vulns.rb
Ruby
gpl-3.0
347
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SitemapEvents.cs" company="Devbridge Group LLC"> // // Copyright (C) 2015,2016 Devbridge Group LLC // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> // // <summary> // Better CMS is a publishing focused and developer friendly .NET open source CMS. // // Website: https://www.bettercms.com // GitHub: https://github.com/devbridge/bettercms // Email: info@bettercms.com // </summary> // -------------------------------------------------------------------------------------------------------------------- using BetterCms.Module.Pages.Models; using BetterModules.Events; // ReSharper disable CheckNamespace namespace BetterCms.Events // ReSharper restore CheckNamespace { /// <summary> /// Attachable sitemap events container /// </summary> public partial class SitemapEvents : EventsBase<SitemapEvents> { /// <summary> /// Occurs when a sitemap is created. /// </summary> public event DefaultEventHandler<SingleItemEventArgs<Sitemap>> SitemapCreated; /// <summary> /// Occurs when a sitemap is updated. /// </summary> public event DefaultEventHandler<SingleItemEventArgs<Sitemap>> SitemapUpdated; /// <summary> /// Occurs when a sitemap is restored. /// </summary> public event DefaultEventHandler<SingleItemEventArgs<Sitemap>> SitemapRestored; /// <summary> /// Occurs when a sitemap is updated. /// </summary> public event DefaultEventHandler<SingleItemEventArgs<Sitemap>> SitemapDeleted; /// <summary> /// Occurs when a sitemap node is created. /// </summary> public event DefaultEventHandler<SingleItemEventArgs<SitemapNode>> SitemapNodeCreated; /// <summary> /// Occurs when a sitemap node is updated. /// </summary> public event DefaultEventHandler<SingleItemEventArgs<SitemapNode>> SitemapNodeUpdated; /// <summary> /// Occurs when a sitemap node is deleted. /// </summary> public event DefaultEventHandler<SingleItemEventArgs<SitemapNode>> SitemapNodeDeleted; /// <summary> /// Called when the sitemap is created. /// </summary> public void OnSitemapCreated(Sitemap sitemap) { if (SitemapCreated != null) { SitemapCreated(new SingleItemEventArgs<Sitemap>(sitemap)); } } /// <summary> /// Called when the sitemap is updated. /// </summary> public void OnSitemapUpdated(Sitemap sitemap) { if (SitemapUpdated != null) { SitemapUpdated(new SingleItemEventArgs<Sitemap>(sitemap)); } } /// <summary> /// Called when the sitemap is restored. /// </summary> public void OnSitemapRestored(Sitemap sitemap) { if (SitemapRestored != null) { SitemapRestored(new SingleItemEventArgs<Sitemap>(sitemap)); } } /// <summary> /// Called when the sitemap is deleted. /// </summary> public void OnSitemapDeleted(Sitemap sitemap) { if (SitemapDeleted != null) { SitemapDeleted(new SingleItemEventArgs<Sitemap>(sitemap)); } } /// <summary> /// Called when sitemap node is created. /// </summary> public void OnSitemapNodeCreated(SitemapNode node) { if (SitemapNodeCreated != null) { SitemapNodeCreated(new SingleItemEventArgs<SitemapNode>(node)); } } /// <summary> /// Called when sitemap node is updated. /// </summary> public void OnSitemapNodeUpdated(SitemapNode node) { if (SitemapNodeUpdated != null) { SitemapNodeUpdated(new SingleItemEventArgs<SitemapNode>(node)); } } /// <summary> /// Called when sitemap node is deleted. /// </summary> public void OnSitemapNodeDeleted(SitemapNode node) { if (SitemapNodeDeleted != null) { SitemapNodeDeleted(new SingleItemEventArgs<SitemapNode>(node)); } } } }
devbridge/BetterCMS
Modules/BetterCms.Module.Pages/Events/SitemapEvents.cs
C#
gpl-3.0
5,133
/* Stroke5 Chinese Input Method for Android Copyright (C) 2012 LinkOmnia Ltd. Author: Wan Leung Wong (wanleung@linkomnia.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/>. */ package com.linkomnia.android.Stroke5; import android.content.Context; import android.inputmethodservice.Keyboard; public class IMEKeyboard extends Keyboard { static final int KEYCODE_ENTER = 10; static final int KEYCODE_CAPLOCK = -200; static final int KEYCODE_MODE_CHANGE_CHAR = -300; static final int KEYCODE_MODE_CHANGE_SIMLEY = -400; static final int KEYCODE_MODE_CHANGE_CHSYMBOL = -500; static final int KEYCODE_MODE_CHANGE_LANG = -600; private boolean isCapLock; public IMEKeyboard(Context context, int xmlLayoutResId) { super(context, xmlLayoutResId); this.isCapLock = false; this.setShifted(false); } public IMEKeyboard(Context context, int layoutTemplateResId, CharSequence characters, int columns, int horizontalPadding) { super(context, layoutTemplateResId, characters, columns, horizontalPadding); this.isCapLock = false; this.setShifted(false); } public boolean isCapLock() { return this.isCapLock; } public void setCapLock(boolean b) { this.isCapLock = b; this.setShifted(b); } }
wanleung/Stroke5Keyboard-android
src/com/linkomnia/android/Stroke5/IMEKeyboard.java
Java
gpl-3.0
1,979
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2006-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::turbulentIntensityKineticEnergyInletFvPatchScalarField Description Calculate turbulent kinetic energy from the intensity provided as a fraction of the mean velocity Example of the boundary condition specification: @verbatim inlet { type turbulentIntensityKineticEnergyInlet; intensity 0.05; // 5% turbulence value uniform 1; // placeholder } @endverbatim SourceFiles turbulentIntensityKineticEnergyInletFvPatchScalarField.C \*---------------------------------------------------------------------------*/ #ifndef turbulentIntensityKineticEnergyInletFvPatchScalarField_H #define turbulentIntensityKineticEnergyInletFvPatchScalarField_H #include <finiteVolume/inletOutletFvPatchFields.H> // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class turbulentIntensityKineticEnergyInletFvPatch Declaration \*---------------------------------------------------------------------------*/ class turbulentIntensityKineticEnergyInletFvPatchScalarField : public inletOutletFvPatchScalarField { // Private data //- Turbulent intensity as fraction of mean velocity scalar intensity_; //- Name of the velocity field word UName_; //- Name of the flux field word phiName_; public: //- Runtime type information TypeName("turbulentIntensityKineticEnergyInlet"); // Constructors //- Construct from patch and internal field turbulentIntensityKineticEnergyInletFvPatchScalarField ( const fvPatch&, const DimensionedField<scalar, volMesh>& ); //- Construct from patch, internal field and dictionary turbulentIntensityKineticEnergyInletFvPatchScalarField ( const fvPatch&, const DimensionedField<scalar, volMesh>&, const dictionary& ); //- Construct by mapping given // turbulentIntensityKineticEnergyInletFvPatchScalarField // onto a new patch turbulentIntensityKineticEnergyInletFvPatchScalarField ( const turbulentIntensityKineticEnergyInletFvPatchScalarField&, const fvPatch&, const DimensionedField<scalar, volMesh>&, const fvPatchFieldMapper& ); //- Construct as copy turbulentIntensityKineticEnergyInletFvPatchScalarField ( const turbulentIntensityKineticEnergyInletFvPatchScalarField& ); //- Construct and return a clone virtual tmp<fvPatchScalarField> clone() const { return tmp<fvPatchScalarField> ( new turbulentIntensityKineticEnergyInletFvPatchScalarField ( *this ) ); } //- Construct as copy setting internal field reference turbulentIntensityKineticEnergyInletFvPatchScalarField ( const turbulentIntensityKineticEnergyInletFvPatchScalarField&, const DimensionedField<scalar, volMesh>& ); //- Construct and return a clone setting internal field reference virtual tmp<fvPatchScalarField> clone ( const DimensionedField<scalar, volMesh>& iF ) const { return tmp<fvPatchScalarField> ( new turbulentIntensityKineticEnergyInletFvPatchScalarField ( *this, iF ) ); } // Member functions //- Update the coefficients associated with the patch field virtual void updateCoeffs(); //- Write virtual void write(Ostream&) const; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************ vim: set sw=4 sts=4 et: ************************ //
themiwi/freefoam-debian
src/finiteVolume/fields/fvPatchFields/derived/turbulentIntensityKineticEnergyInlet/turbulentIntensityKineticEnergyInletFvPatchScalarField.H
C++
gpl-3.0
5,294
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::removeFaces Description Given list of faces to remove insert all the topology changes. Contains helper function to get consistent set of faces to remove. Not very well tested in parallel. SourceFiles removeFaces.C \*---------------------------------------------------------------------------*/ #ifndef removeFaces_H #define removeFaces_H #include <OpenFOAM/Pstream.H> #include <OpenFOAM/HashSet.H> #include <OpenFOAM/Map.H> #include <OpenFOAM/boolList.H> #include <OpenFOAM/indirectPrimitivePatch.H> // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // Forward declaration of classes class polyMesh; class polyTopoChange; class face; class mapPolyMesh; class mapDistributePolyMesh; /*---------------------------------------------------------------------------*\ Class removeFaces Declaration \*---------------------------------------------------------------------------*/ class removeFaces { // Private data //- Reference to mesh const polyMesh& mesh_; //- Cosine of angles between boundary faces. Boundary faces can be // merged only if angle between faces > minCos. const scalar minCos_; // Private Member Functions //- Change elements in cellRegion that are oldRegion to newRegion. // Recurses to cell neighbours. void changeCellRegion ( const label cellI, const label oldRegion, const label newRegion, labelList& cellRegion ) const; //- Changes region of connected set of faces label changeFaceRegion ( const labelList& cellRegion, const boolList& removedFace, const labelList& nFacesPerEdge, const label faceI, const label newRegion, const labelList& fEdges, labelList& faceRegion ) const; //- Get all affected faces (including faces marked for removal) boolList getFacesAffected ( const labelList& cellRegion, const labelList& cellRegionMaster, const labelList& facesToRemove, const labelHashSet& edgesToRemove, const labelHashSet& pointsToRemove ) const; // Topological changes //- Debug: write set of faces to file in obj format. static void writeOBJ ( const indirectPrimitivePatch&, const fileName& ); //- Merge faceLabels into single face. void mergeFaces ( const labelList& cellRegion, const labelList& cellRegionMaster, const labelHashSet& pointsToRemove, const labelList& faceLabels, polyTopoChange& meshMod ) const; //- Get patch, zone info for faceI void getFaceInfo ( const label faceI, label& patchID, label& zoneID, label& zoneFlip ) const; //- Return face with all pointsToRemove removed. face filterFace(const labelHashSet& pointsToRemove, const label) const; //- Wrapper for meshMod.modifyFace. Reverses face if own>nei. void modFace ( const face& f, const label masterFaceID, const label own, const label nei, const bool flipFaceFlux, const label newPatchID, const bool removeFromZone, const label zoneID, const bool zoneFlip, polyTopoChange& meshMod ) const; //- Disallow default bitwise copy construct removeFaces(const removeFaces&); //- Disallow default bitwise assignment void operator=(const removeFaces&); public: //- Runtime type information ClassName("removeFaces"); // Constructors //- Construct from mesh and min cos of angle for boundary faces // to be considered aligned. Set to >= 1 to disable checking // and always merge (if on same patch) removeFaces(const polyMesh&, const scalar minCos); // Member Functions //- Given set of faces to pierce calculates: // - region for connected cells // - mastercell for each region. This is the lowest numbered cell // of all cells that get merged. // - new set of faces which contains input set + additional ones // where cells on both sides would have same mastercell. // Returns number of regions. label compatibleRemoves ( const labelList& inPiercedFaces, labelList& cellRegion, labelList& cellRegionMaster, labelList& outPiercedFaces ) const; //- Play commands into polyTopoChange to remove faces. void setRefinement ( const labelList& piercedFaces, const labelList& cellRegion, const labelList& cellRegionMaster, polyTopoChange& ) const; //- Force recalculation of locally stored data on topological change void updateMesh(const mapPolyMesh&) {} //- Force recalculation of locally stored data for mesh distribution void distribute(const mapDistributePolyMesh&) {} }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************ vim: set sw=4 sts=4 et: ************************ //
themiwi/freefoam-debian
src/dynamicMesh/polyTopoChange/polyTopoChange/removeFaces.H
C++
gpl-3.0
6,911
package tmp.generated_cs; import cide.gast.*; import cide.gparser.*; import cide.greferences.*; import java.util.*; public class field_declarators extends GenASTNode { public field_declarators(field_declarator field_declarator, ArrayList<field_declarator> field_declarator1, Token firstToken, Token lastToken) { super(new Property[] { new PropertyOne<field_declarator>("field_declarator", field_declarator), new PropertyZeroOrMore<field_declarator>("field_declarator1", field_declarator1) }, firstToken, lastToken); } public field_declarators(Property[] properties, IToken firstToken, IToken lastToken) { super(properties,firstToken,lastToken); } public IASTNode deepCopy() { return new field_declarators(cloneProperties(),firstToken,lastToken); } public field_declarator getField_declarator() { return ((PropertyOne<field_declarator>)getProperty("field_declarator")).getValue(); } public ArrayList<field_declarator> getField_declarator1() { return ((PropertyZeroOrMore<field_declarator>)getProperty("field_declarator1")).getValue(); } }
ckaestne/CIDE
CIDE_Language_CS/src/tmp/generated_cs/field_declarators.java
Java
gpl-3.0
1,120
/* * 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 Library 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. * * StageProfiPlugin.cpp * The StageProfi plugin for ola * Copyright (C) 2006-2008 Simon Newton */ #include <stdlib.h> #include <stdio.h> #include <string> #include <vector> #include "ola/Logging.h" #include "olad/PluginAdaptor.h" #include "olad/Preferences.h" #include "plugins/stageprofi/StageProfiDevice.h" #include "plugins/stageprofi/StageProfiPlugin.h" /* * Entry point to this plugin */ extern "C" ola::AbstractPlugin* create( const ola::PluginAdaptor *plugin_adaptor) { return new ola::plugin::stageprofi::StageProfiPlugin(plugin_adaptor); } namespace ola { namespace plugin { namespace stageprofi { using std::string; const char StageProfiPlugin::STAGEPROFI_DEVICE_PATH[] = "/dev/ttyUSB0"; const char StageProfiPlugin::STAGEPROFI_DEVICE_NAME[] = "StageProfi Device"; const char StageProfiPlugin::PLUGIN_NAME[] = "StageProfi"; const char StageProfiPlugin::PLUGIN_PREFIX[] = "stageprofi"; const char StageProfiPlugin::DEVICE_KEY[] = "device"; /* * Start the plugin * * Multiple devices now supported */ bool StageProfiPlugin::StartHook() { vector<string> device_names; vector<string>::iterator it; StageProfiDevice *device; // fetch device listing device_names = m_preferences->GetMultipleValue(DEVICE_KEY); for (it = device_names.begin(); it != device_names.end(); ++it) { if (it->empty()) continue; device = new StageProfiDevice(this, STAGEPROFI_DEVICE_NAME, *it); if (!device->Start()) { delete device; continue; } m_plugin_adaptor->AddSocket(device->GetSocket()); m_plugin_adaptor->RegisterDevice(device); m_devices.insert(m_devices.end(), device); } return true; } /* * Stop the plugin * @return true on success, false on failure */ bool StageProfiPlugin::StopHook() { vector<StageProfiDevice*>::iterator iter; for (iter = m_devices.begin(); iter != m_devices.end(); ++iter) { m_plugin_adaptor->RemoveSocket((*iter)->GetSocket()); DeleteDevice(*iter); } m_devices.clear(); return true; } /* * Return the description for this plugin */ string StageProfiPlugin::Description() const { return "StageProfi Plugin\n" "----------------------------\n" "\n" "This plugin creates devices with one output port.\n" "\n" "--- Config file : ola-stageprofi.conf ---\n" "\n" "device = /dev/ttyUSB0\n" "device = 192.168.1.250\n" "The device to use either as a path for the USB version or an IP address\n" "for the LAN version. Multiple devices are supported.\n"; } /* * Called when the file descriptor is closed. */ int StageProfiPlugin::SocketClosed(ConnectedSocket *socket) { vector<StageProfiDevice*>::iterator iter; for (iter = m_devices.begin(); iter != m_devices.end(); ++iter) { if ((*iter)->GetSocket() == socket) break; } if (iter == m_devices.end()) { OLA_WARN << "unknown fd"; return -1; } DeleteDevice(*iter); m_devices.erase(iter); return 0; } /* * load the plugin prefs and default to sensible values * */ bool StageProfiPlugin::SetDefaultPreferences() { if (!m_preferences) return false; bool save = false; save |= m_preferences->SetDefaultValue(DEVICE_KEY, StringValidator(), STAGEPROFI_DEVICE_PATH); if (save) m_preferences->Save(); if (m_preferences->GetValue(DEVICE_KEY).empty()) return false; return true; } /* * Cleanup a single device */ void StageProfiPlugin::DeleteDevice(StageProfiDevice *device) { m_plugin_adaptor->UnregisterDevice(device); device->Stop(); delete device; } } // stageprofi } // plugin } // ola
syn2cat/syndilights
open-lighting-architecture/ola-0.8.4/plugins/stageprofi/StageProfiPlugin.cpp
C++
gpl-3.0
4,320
import numpy as np import cv2 from scipy import interpolate from random import randint import IPython from alan.rgbd.basic_imaging import cos,sin from alan.synthetic.synthetic_util import rand_sign from alan.core.points import Point """ generates rope using non-holonomic car model dynamics (moves with turn radius) generates labels at ends of rope parameters: h, w of image matrix l, w of rope returns: image matrix with rope drawn [left label, right label] """ def get_rope_car(h = 420, w = 420, rope_l_pixels = 800 , rope_w_pixels = 8, pix_per_step = 10, steps_per_curve = 10, lo_turn_delta = 5, hi_turn_delta = 10): #randomize start init_pos = np.array([randint(0, w - 1), randint(0, h - 1), randint(0, 360)]) all_positions = np.array([init_pos]) #dependent parameter (use float division) num_curves = int(rope_l_pixels/(steps_per_curve * pix_per_step * 1.0)) #point generation for c in range(num_curves): turn_delta = rand_sign() * randint(lo_turn_delta, hi_turn_delta) for s in range(steps_per_curve): curr_pos = all_positions[-1] delta_pos = np.array([pix_per_step * cos(curr_pos[2]), pix_per_step * sin(curr_pos[2]), turn_delta]) all_positions = np.append(all_positions, [curr_pos + delta_pos], axis = 0) #center the points (avoid leaving image bounds) mid_x_points = (min(all_positions[:,0]) + max(all_positions[:,0]))/2.0 mid_y_points = (min(all_positions[:,1]) + max(all_positions[:,1]))/2.0 for pos in all_positions: pos[0] -= (mid_x_points - w/2.0) pos[1] -= (mid_y_points - h/2.0) #draw rope image = np.zeros((h, w)) prev_pos = all_positions[0] for curr_pos in all_positions[1:]: cv2.line(image, (int(prev_pos[0]), int(prev_pos[1])), (int(curr_pos[0]), int(curr_pos[1])), 255, rope_w_pixels) prev_pos = curr_pos #get endpoint labels, sorted by x labels = [all_positions[0], all_positions[-1]] if labels[0][0] > labels[1][0]: labels = [labels[1], labels[0]] #labels = [[l[0], l[1], l[2] + 90] for l in labels] #Ignoring Rotation for Now labels = [[l[0], l[1], 0] for l in labels] #rejection sampling for num_label in range(2): c_label = labels[num_label] #case 1- endpoints not in image if check_bounds(c_label, [w, h]) == -1: return image, labels, -1 #case 2- endpoint on top of other rope segment if check_overlap(c_label, [w, h], image, rope_w_pixels) == -1: return image, labels, -1 return image, labels, 1 def check_bounds(label, bounds): bound_tolerance = 5 for dim in range(2): if label[dim] < bound_tolerance or label[dim] > (bounds[dim] - 1 - bound_tolerance): return -1 return 0 def check_overlap(label, bounds, image, rope_w_pixels): lb = [] ub = [] for dim in range(2): lb.append(int(max(0, label[dim] - rope_w_pixels))) ub.append(int(min(bounds[dim] - 1, label[dim] + rope_w_pixels))) pixel_sum = 0 for x in range(lb[0], ub[0]): for y in range(lb[1], ub[1]): pixel_sum += (image[y][x]/255.0) #if more than 60% of adjacent (2 * rope_w x 2 * rope_w) pixels are white, endpoint is probably lying on rope expected_sum = 0.6 * (ub[1] - lb[1]) * (ub[0] - lb[0]) if pixel_sum > expected_sum: return -1 return 0
mdlaskey/DeepLfD
src/deep_lfd/synthetic/synthetic_rope.py
Python
gpl-3.0
3,594
package com.uvasoftware.core.data.student; import com.uvasoftware.core.ISIFObject; import com.uvasoftware.core.data.common.BaseSIFObject; public class StudentSchoolEnrollment extends BaseSIFObject implements ISIFObject { @Override public Object getPrimitive() { // TODO Auto-generated method stub return null; } @Override public void setPrimitive(Object primitive) { // TODO Auto-generated method stub } }
rferreira/uva-core
src/com/uvasoftware/core/data/student/StudentSchoolEnrollment.java
Java
gpl-3.0
447
<?php /** * GWToolset * * @file * @ingroup Extensions * @license GNU General Public License 3.0 http://www.gnu.org/licenses/gpl.html */ namespace GWToolset\Jobs; use Job, GWToolset\Config, GWToolset\Helpers\GWTFileBackend, GWToolset\GWTException, User; class GWTFileBackendCleanupJob extends Job { /** * @param {Title} $title * @param {bool|array} $params * @param {int} $id */ public function __construct( $title, $params, $id = 0 ) { parent::__construct( 'gwtoolsetGWTFileBackendCleanupJob', $title, $params, $id ); } /** * @return {bool} */ protected function processJob() { $result = true; global $wgGWTFileBackend; $GWTFileBackend = new GWTFileBackend( array( 'container' => Config::$filebackend_metadata_container, 'file-backend-name' => $wgGWTFileBackend, 'User' => User::newFromName( $this->params['user-name'] ) ) ); $Status = $GWTFileBackend->deleteFileFromRelativePath( $this->params['gwtoolset-metadata-file-relative-path'] ); if ( !$Status->ok ) { $this->setLastError( __METHOD__ . ': ' . $Status->getMessage() ); $result = false; } return $result; } /** * entry point * @return {bool} */ public function run() { $result = false; if ( !$this->validateParams() ) { return $result; } try { $result = $this->processJob(); } catch ( GWTException $e ) { $this->setLastError( __METHOD__ . ': ' . $e->getMessage() ); } return $result; } /** * @return {bool} */ protected function validateParams() { $result = true; if ( empty( $this->params['gwtoolset-metadata-file-relative-path'] ) ) { $this->setLastError( __METHOD__ . ': no $this->params[\'gwtoolset-metadata-file-relative-path\'] provided' ); $result = false; } if ( empty( $this->params['user-name'] ) ) { $this->setLastError( __METHOD__ . ': no $this->params[\'user-name\'] provided' ); $result = false; } return $result; } }
dan-nl/GWToolset
includes/Jobs/GWTFileBackendCleanupJob.php
PHP
gpl-3.0
1,950
/* * Copyright (C) 2015 Securecom * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.securecomcode.voice.call; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.securecomcode.voice.ui.RecentCallListActivity; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class CallLogDatabase { private static final String DATABASE_NAME = "securecom_calllog.db"; private static final int DATABASE_VERSION = 1; private static final String TABLE_NAME = "call_log"; private static final String ID = "_id"; public static final String NUMBER = "number"; public static final String CONTACT_NAME = "contactName"; public static final String DATE = "date"; public static final String TYPE = "type"; public static final String NUMBER_LABEL = "numberLabel"; private RecentCallListActivity recentCallListActivity = null; private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY, " + NUMBER + " TEXT," + CONTACT_NAME + " TEXT," + DATE + " TEXT," + TYPE + " TEXT," + NUMBER_LABEL + " TEXT );"; private static final Object instanceLock = new Object(); private static volatile CallLogDatabase instance; public static CallLogDatabase getInstance(Context context) { if (instance == null) { synchronized (instanceLock) { if (instance == null) { instance = new CallLogDatabase(context); } } } return instance; } private final DatabaseHelper databaseHelper; private final Context context; private CallLogDatabase(Context context) { this.context = context; this.databaseHelper = new DatabaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION); } public void setCallLogEntryValues(ContentValues values) { SQLiteDatabase db = databaseHelper.getWritableDatabase(); Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null); if(cursor.getCount() == 200){ deleteFirstRow(db, cursor); } db.beginTransaction(); try { db.insert(TABLE_NAME, null, values); db.setTransactionSuccessful(); }finally { db.endTransaction(); } if(recentCallListActivity != null){ recentCallListActivity.databaseContentUpdated(); } } public void deleteFirstRow(SQLiteDatabase db, Cursor cursor){ db.beginTransaction(); try { if (cursor.moveToFirst()) { String rowId = cursor.getString(cursor.getColumnIndex(ID)); db.delete(TABLE_NAME, ID + "=?", new String[]{rowId}); db.setTransactionSuccessful(); } }finally { db.endTransaction(); } } public void doDatabaseReset(Context context) { context.deleteDatabase(DATABASE_NAME); instance = null; } public int getDatabaseTableRowCount(){ int count = 0; try { SQLiteDatabase db = databaseHelper.getWritableDatabase(); Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null); count = cursor.getCount(); }catch (Exception e){ } return count; } public ArrayList<CallDetail> getActiveCallLog(RecentCallListActivity recentCallListActivity) { this.recentCallListActivity = recentCallListActivity; final ArrayList<CallDetail> results = new ArrayList<CallDetail>(); Cursor cursor = null; try { cursor = databaseHelper.getReadableDatabase().query(TABLE_NAME, new String[]{NUMBER, CONTACT_NAME, DATE, TYPE, NUMBER_LABEL}, null, null, null, null, null); while (cursor != null && cursor.moveToNext()) { results.add(cursorToCallDetail(cursor)); } Collections.sort(results, new Comparator<CallDetail>() { @Override public int compare(CallDetail lhs, CallDetail rhs) { long date1 = Long.parseLong(lhs.getDate()); long date2 = Long.parseLong(rhs.getDate()); return (date1>date2 ? -1 : (date1 == date2 ? 0 : 1)); } }); return results; } finally { if (cursor != null) cursor.close(); } } private CallDetail cursorToCallDetail(Cursor cursor) { CallDetail callDetail = new CallDetail(); callDetail.setNumber(cursor.getString(0)); callDetail.setContactName(cursor.getString(1)); callDetail.setDate(cursor.getString(2)); callDetail.setType(cursor.getString(3)); callDetail.setNumberLabel(cursor.getString(4)); return callDetail; } private class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS call_log;"); onCreate(db); } } }
Securecom/Securecom-Voice
src/com/securecomcode/voice/call/CallLogDatabase.java
Java
gpl-3.0
6,364
<span tabindex="0" data-entry='{{ data.entry }}'>{{ data.text }}</span>
geminilabs/site-reviews
views/partials/translations/result.php
PHP
gpl-3.0
72
<?php $lang = array( 'cloudflare_mk_module_name' => 'CloudFlare MK', 'cloudflare_mk_module_description' => 'CloudFlare MK Remote Admin', // ''=>'' );
michellekondou/cloudlfare-module
system/expressionengine/third_party/cloudflare_mk/language/english/lang.cloudflare_mk.php
PHP
gpl-3.0
154
/** * Copyright (c) 2000-2005 Liferay, LLC. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.liferay.util.dao.hibernate; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import javax.sql.DataSource; import com.dotcms.repackage.hibernate2.net.sf.hibernate.HibernateException; import com.dotcms.repackage.hibernate2.net.sf.hibernate.connection.ConnectionProvider; import com.dotmarketing.db.DbConnectionFactory; /** * <a href="DSConnectionProvider.java.html"><b><i>View Source</i></b></a> * * @author Brian Wing Shun Chan * @version $Revision: 1.5 $ * */ public class DSConnectionProvider implements ConnectionProvider { public void configure(Properties props) throws HibernateException { try { _ds = DbConnectionFactory.getDataSource(); } catch (Exception e) { throw new HibernateException(e.getMessage()); } } public Connection getConnection() throws SQLException { //This forces liferay to use our connection manager return DbConnectionFactory.getConnection(); } public void closeConnection(Connection con) throws SQLException { //This condition is set to avoid closing connection when in middle of a transaction if(con != null && con.getAutoCommit()) DbConnectionFactory.closeConnection(); } public boolean isStatementCache() { return false; } public void close() { } private DataSource _ds; }
austindlawless/dotCMS
src/com/liferay/util/dao/hibernate/DSConnectionProvider.java
Java
gpl-3.0
2,530
__author__ = 'nicolas' # coding=utf-8 from os.path import expanduser from ordereddict import OrderedDict from Bio import SwissProt import time import MySQLdb as mdb """ Fuck! from ordereddict import OrderedDict import MySQLdb as mdb dicc = {} dictdebug_empty = OrderedDict() dictdebug = dictdebug_empty dictdebug['hola'] = 'chau' print(dictdebug.items()) print(dictdebug_empty.items()) dictdebug_empty.clear() print(dictdebug_empty.items()) print(dictdebug.items()) """ # Establecer el tiempo de inicio del script start_time = time.time() # Variables del script database = "ptmdb" tabla_cuentas = "sprot_count1" tabla_ptms = "sprot_ptms1" file_name = "uniprot_sprot.dat" desde = 0 hasta = 542783 # Hay 542782 entradas de AC?? # Conectar a la base de datos con = mdb.connect('localhost', 'nicolas', passwd="nicolaslfp", db=database) cur = con.cursor() cur.execute("SELECT VERSION()") cur.execute("USE " + database) print("USE ptmdb;") # Abrir el .dat de uniprot uniprot_file = expanduser("~") + '/QB9_Files/' + file_name output_file = expanduser("~") + '/QB9-git/QB9/resources/output.txt' def count_amino_acids_ext(seq): # Defino una función que toma una secuencia y los cuenta prot_dic2 = prot_dic for aa in prot_dic2: prot_dic2[aa] = seq.count(aa) return prot_dic2 # y devuelve un dict ordenado con pares AA, #AA # Armo un diccionario con los AAs que voy a contar abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' prot_dic = OrderedDict((k, 0) for k in abc) # Interesting feature types ptmrecords = ["MOD_RES", "LIPID", "CARBOHYD", "DISULFID", "CROSSLNK"] # Non-experimental qualifiers for feature annotations neqs = ["Probable", "Potential", "By similarity"] # Y "Experimental" # Las categorías están en un diccionario con su type de mysql todo volar categories = OrderedDict() categories['AC'] = "varchar(30) NOT NULL" # accesion number categories['FT'] = "varchar(30) NOT NULL" categories['STATUS'] = "varchar(30) NOT NULL" categories['PTM'] = "varchar(100) NOT NULL" categories['FROM_RES'] = "varchar(10) NOT NULL" categories['TO_RES'] = "varchar(10) NOT NULL" categories['FROM_AA'] = "varchar(10) NOT NULL" # vamo a implementar el target directamente!!!! =D categories['TO_AA'] = "varchar(10) NOT NULL" categories['SQ'] = "text(45000) NOT NULL" # SQ SEQUENCE XXXX AA; XXXXX MW; XXXXXXXXXXXXXXXX CRC64; categories['LENGTH'] = "varchar(200) NOT NULL" # SQ SEQUENCE XXXX AA; XXXXX MW; XXXXXXXXXXXXXXXX CRC64; categories['ORG'] = "text(500) NOT NULL" # organism categories['OC'] = "varchar(30) NOT NULL" # organism classification, vamos solo con el dominio categories['OX'] = "varchar(200) NOT NULL" # taxonomic ID categories['HO'] = "text(500)" # host organism categories['inumber'] = "varchar(200) NOT NULL" # categories['CC'] = "varchar(200)" # comments section, nos interesa el campo "PTM" # categories['SQi'] = "varchar(200)" # SQ SEQUENCE XXXX AA; XXXXX MW; XXXXXXXXXXXXXXXX CRC64; # Defino un diccionario modelo donde cargar los valores que voy a extraer de la lista empty_data = OrderedDict() for gato in categories: # usando las keys de categories y un valor por defecto todo vacío no es nulo ¿cómo hago? empty_data[gato] = 'NOFT' empty_data['FROM_RES'] = '?' empty_data['TO_RES'] = '?' empty_data['FROM_AA'] = '?' empty_data['TO_AA'] = '?' data = empty_data.copy() # este es el diccionario de registros vacío que voy a usar print("DROP TABLE " + tabla_cuentas + ";") print("DROP TABLE " + tabla_ptms + ";") # Crear la tabla de cuentas prot_dic_def_items = [] prot_dic_def = OrderedDict((k, 'SMALLINT') for k in abc) for cat, value in prot_dic_def.items(): # concatenaciones key y valor prot_dic_def_items.append(cat + ' ' + value) # guardadaes en la lista table_def = ', '.join(prot_dic_def_items) # definicion de la tabla print("CREATE TABLE IF NOT EXISTS " + tabla_cuentas + " (AC VARCHAR(30) UNIQUE, OC_ID VARCHAR(30), LENGTH MEDIUMINT," + table_def + ") ENGINE=InnoDB;") print("commit;") # con.commit() # Crear la tabla de ptms table_def_items = [] # lista para concatenaciones de key y valor for cat, value in categories.items(): # concatenaciones key y valor table_def_items.append(cat + ' ' + value) # guardadaes en la lista table_def_2 = ', '.join(table_def_items) # definicion de la tabla print("CREATE TABLE IF NOT EXISTS " + tabla_ptms + " (" + table_def_2 + ") ENGINE=InnoDB;") print("commit;") # con.commit() # Variables del loop i = 0 j = 0 ptm = '' out = [] listap = [] listaq = [] listar = [] olista = [] interes = [] with open(uniprot_file) as uniprot: # esto me abre y cierra el archivo al final for record in SwissProt.parse(uniprot): # parseando los records de uniprot i += 1 if i % 100 == 0: print("commit;") data = empty_data.copy() # en vez de vaciar el diccionario, le asigno el dafault sin enlazarlo al vacío # Acá cargo los datos generales para las PTMs de una proteína/entrada de uniprot (instancias de entradas) # tienen que cargarse en el orden de las columnas en la ptmdb y el del insert # print(record.accessions[0]) data['AC'] = record.accessions[0] # solo el principal, el resto nose. data['SQ'] = record.sequence data['LENGTH'] = record.sequence_length # todo acá hay un problema? no entran las de mas de 999 residuos data['ORG'] = record.organism # el bicho data['OC'] = record.organism_classification[0] # el dominio del bicho data['OX'] = record.taxonomy_id[0] # Id taxonomica del bicho del olista[:] if not record.host_organism: data['HO'] = 'No host' else: for o in record.host_organism: olista.append((o.split(";"))[0]) data['HO'] = ', '.join(olista) # y esto el host del virus ¿o parásito? data['inumber'] = str(i) # solo para debuguear =) ver hasta donde llegó # Generar y guardar el insert del #AA en la secuencia del listaq[:] contenido_aa = count_amino_acids_ext(record.sequence) # Guardo el dict con partes AA, #AA de la secuencia for q in contenido_aa.itervalues(): listaq.append(str(q)) # y los pongo en una lista sql_insert_values_q = ', '.join(listaq) if i >= desde: print("INSERT INTO " + tabla_cuentas + " VALUES ('" + record.accessions[0] + "', '" + record.organism_classification[0] + "', " + str(record.sequence_length) + ", " + sql_insert_values_q + ");") # print("commit;") # con.commit() # Acá empiezo con los features, hay alguno interesante? features = record.features # todo insertar los FTs en otra tabla junto con OC; OX, OR...? del out[:] del interes[:] for a in range(0, len(features)): # guardar los campos "candidato" del FT en una lista llamada out out.append(features[a][0]) interes = list(set(out).intersection(ptmrecords)) # armar un set con los interesantes y hacerlo lista interes if interes: # si interes no está vacía, entonces hay algo para cargar # todo evitar duplicados de secuencia, relacion via AC? # ahora cargo cada PTM en data (subinstancias de entrada) for feature in features: # iterar los features de la entrada if feature[0] in interes: # si el titulo del FT interesa, proseguir ¡mejora un poco! =D for tipo in interes: # iterear los tipos interesantes encontrados en el feature if feature[0] in tipo: # si el feature evaluado interesante, cargar los datos en data[] A = feature[1] # de el residuo tal (va a ser el mismo que el siguiente si está solo) B = feature[2] # hacia el otro. OJO hay algunos desconocidos indicados con un "?" C = feature[3] # este tiene la posta? D = feature[4] # este aparece a veces? todo wtf? # reiniciar FT, FROM y TO data['FT'] = 'NOFT' data['FROM_RES'] = '?' data['TO_RES'] = '?' data['FROM_AA'] = '?' data['TO_AA'] = '?' # Asignar FT data['FT'] = feature[0] data['FROM_RES'] = A data['TO_RES'] = B # reiniciar PTM y STATUS ptm = '' data['PTM'] = 'NOFT' data['STATUS'] = "Experimental" # Asignar STATUS y PTM if C: # si C (el que tiene el nombre de la PTM y el STATUS) contiene algo for neq in neqs: # iterar los STATUS posibles if neq in C: # si C contiene el STATUS pirulo data['STATUS'] = neq # asignar el valor a STATUS C = C.replace('(' + neq + ")", '') # hay que sacar esta porquería C = C.replace(neq, '') # hay que sacar esta porquería si no aparece con paréntesis break # esto corta con el loop más "cercano" en indentación ptm = ((C.split(" /"))[0].split(';')[0]). \ rstrip(" ").rstrip(".").rstrip(" ") # Obs: a veces las mods tienen identificadores estables que empiezan con "/" # así que hay que sacarlo. y otas cosas después de un ";" CHAU. # También hay CROSSLNKs con otras anotaciones, que los hace aparecer como únicas # al contarlas, pero en realidad son casi iguales todo quizás ocurre con otras? # Ver http://web.expasy.org/docs/userman.html#FT_line # También le saco espacios y puntos al final. # Odio esto del formato... todo no hay algo que lo haga mejor? if tipo == 'DISULFID': # si el tipo es disulfuro, no hay mucho que decir. ptm = "S-cysteinyl 3-(oxidosulfanyl)alanine (Cys-Cys)" data['FROM_AA'] = 'C' data['TO_AA'] = 'C' else: # pero si no lo es, guardamos cosas normalmente. # Asignar target residue if A != '?': data['FROM_AA'] = data['SQ'][int(data['FROM_RES'])-1] else: data['FROM_AA'] = '?' if B != '?': data['TO_AA'] = data['SQ'][int(data['TO_RES'])-1] else: data['TO_AA'] = '?' if ptm.find("with") != -1: # si la ptm contiene la palabra "with" (caso crosslink) ptm = ptm.split(" (with")[0].split(" (int")[0] # pero si la contiene, recortar data['PTM'] = ptm del listap[:] for p in data.itervalues(): # itero los valores de los datos que fui cargando al dict. listap.append(str(p).replace("'", "''")) # y los pongo en una lista sql_insert_values_p = '\'' + \ '\', \''.join(listap) + \ '\'' # Que después uno como van en el INSERT # El insert, en el que reemplazo ' por '', para escaparlas en sql if i >= desde: # para hacerlo en partes print(("INSERT INTO " + tabla_ptms + " VALUES (%r);" % sql_insert_values_p).replace("-...", "").replace("\"", '').replace('.', '')) # print("commit;") # con.commit() # unir los elementos de values con comas else: # Si, en cambio, la entrada no tiene FT insteresantes, solo cargo los datos generales y defaults del listar[:] for r in data.itervalues(): listar.append(str(r).replace("'", "''")) sql_insert_values_r = '\'' + '\', \''.join(listar) + '\'' if i >= desde: # para hacerlo en partes print(("INSERT INTO " + tabla_ptms + " VALUES (%r);" % sql_insert_values_r).replace("\"", '').replace('.', '')) # print("commit;") # con.commit() if i >= hasta: # segun uniprot el número de entradas de secuencias es 54247468 # print("\n") # print(i) break # The sequence counts 60 amino acids per line, in groups of 10 amino acids, beginning in position 6 of the line. # http://www.uniprot.org/manual/ # General Annotation: cofactores, mass spectrometry data, PTM (complementario al MOD_RES y otras PTMs..?) # Sequence Annotation (Features): Sites (cleavage sites?), non-standard residue, # MOD_RES (excluye lipidos, crosslinks y glycanos), lipidación, puente disulfuro, cross-link, glycosylation # todo consider PE "protein existence", KW contiene "glycoprotein" qué otros? # todo también dentro de FT # output.close() # print('\n') # print(time.time() - start_time) # """
naikymen/QB9
uniprot_parser/uniprot_parser_v01.py
Python
gpl-3.0
14,072
<?php /** * WP_Inci * * Main class for subclassing backend and frontend class. * * @package wp-inci * @author xlthlx <wp-inci@piccioni.london> * */ if ( ! class_exists( 'WP_Inci', false ) ) { class WP_Inci { /** * A static reference to track the single instance of this class. */ private static $instance; /** * Plugin version. * * @since 1.0 * @var string */ public $version = "1.5.1"; /** * release.minor.revision * See split below. * * @since 1.0 * @var string */ public $release = 1; public $minor = 5; public $revision = 1; /** * Plugin name * * @since 1.0 * @var string */ public $plugin_name = "WP INCI"; /** * Main plugin slug. * * @since 1.0 * @var string */ public $plugin_slug = "wp-inci"; /** * Setting from main file to __FILE__. * * @since 1.0 * @var string */ public $plugin_file = __DIR__ . '/wp-inci.php'; /** * Options array containing all options for this plugin. * * @since 1.0 * @var array */ public $options = array(); /** * This plugin url. * * @since 1.0 * @var string */ public $url = ""; /** * Constructor. * * @since 1.0 */ public function __construct() { $this->init(); /** * Split version for more detail. */ $split_version = explode( ".", $this->version ); $this->release = $split_version[0]; $this->minor = $split_version[1]; $this->revision = $split_version[2]; /** * Sets url for the plugin. */ $this->url = plugins_url( "", __DIR__ . '/wp-inci.php' ); } /** * Standard init. */ public function init() { /** * Add Custom Post Types and Taxonomies. */ add_action( 'init', [ $this, 'post_type_init' ] ); add_filter( 'post_updated_messages', [ $this, 'ingredient_updated_messages' ] ); add_filter( 'bulk_post_updated_messages', [ $this, 'ingredient_bulk_updated_messages' ], 10, 2 ); add_filter( 'post_updated_messages', [ $this, 'product_updated_messages' ] ); add_filter( 'bulk_post_updated_messages', [ $this, 'product_bulk_updated_messages' ], 10, 2 ); add_filter( 'term_updated_messages', [ $this, 'function_updated_messages' ] ); add_filter( 'term_updated_messages', [ $this, 'source_updated_messages' ] ); add_filter( 'term_updated_messages', [ $this, 'brand_updated_messages' ] ); } /** * Method used to provide a single instance of this class. * * @return WP_Inci|null */ public static function get_instance() { if ( null === self::$instance ) { self::$instance = new WP_Inci(); } return self::$instance; } /** * Add Custom Post Types and Taxonomies. */ public function post_type_init() { $this->ingredients_post_type(); $this->products_post_type(); } /** * Register Custom Post Type Ingredient and Functions and Source Taxonomy. */ public function ingredients_post_type() { $ingredients_labels = [ 'name' => __( 'Ingredients', 'wp-inci' ), 'singular_name' => __( 'Ingredient', 'wp-inci' ), 'all_items' => __( 'All Ingredients', 'wp-inci' ), 'archives' => __( 'Ingredient Archives', 'wp-inci' ), 'attributes' => __( 'Ingredient Attributes', 'wp-inci' ), 'insert_into_item' => __( 'Insert into Ingredient', 'wp-inci' ), 'uploaded_to_this_item' => __( 'Uploaded to this Ingredient', 'wp-inci' ), 'featured_image' => _x( 'Featured Image', 'ingredient', 'wp-inci' ), 'set_featured_image' => _x( 'Set featured image', 'ingredient', 'wp-inci' ), 'remove_featured_image' => _x( 'Remove featured image', 'ingredient', 'wp-inci' ), 'use_featured_image' => _x( 'Use as featured image', 'ingredient', 'wp-inci' ), 'filter_items_list' => __( 'Filter Ingredients list', 'wp-inci' ), 'items_list_navigation' => __( 'Ingredients list navigation', 'wp-inci' ), 'items_list' => __( 'Ingredients list', 'wp-inci' ), 'new_item' => __( 'New Ingredient', 'wp-inci' ), 'add_new' => __( 'Add New', 'wp-inci' ), 'add_new_item' => __( 'Add New Ingredient', 'wp-inci' ), 'edit_item' => __( 'Edit Ingredient', 'wp-inci' ), 'view_item' => __( 'View Ingredient', 'wp-inci' ), 'view_items' => __( 'View Ingredients', 'wp-inci' ), 'search_items' => __( 'Search Ingredients', 'wp-inci' ), 'not_found' => __( 'No Ingredients found', 'wp-inci' ), 'not_found_in_trash' => __( 'No Ingredients found in trash', 'wp-inci' ), 'parent_item_colon' => __( 'Parent Ingredient:', 'wp-inci' ), 'menu_name' => __( 'Ingredients', 'wp-inci' ), ]; register_extended_post_type( 'ingredient', array( 'publicly_queryable' => false, 'menu_icon' => 'dashicons-wi-menu', 'rewrite' => false, 'labels' => $ingredients_labels, 'capability_type' => 'page', 'has_archive' => false, 'hierarchical' => false, 'show_in_rest' => true, 'block_editor' => true, 'supports' => array( 'title', 'editor', 'author', 'revisions', ), 'admin_cols' => array( 'title' => array( 'title' => __( 'Ingredient', 'wp-inci' ), 'default' => 'ASC', ), 'safety' => array( 'title' => __( 'Safety', 'wp-inci' ), 'function' => function () { global $post; echo $this->get_safety_html( $post->ID ); }, ), 'functions' => array( 'title' => __( 'Functions', 'wp-inci' ), 'taxonomy' => 'functions' ), 'source' => array( 'title' => __( 'Source', 'wp-inci' ), 'taxonomy' => 'source' ), 'author' => array( 'title' => __( 'Author', 'wp-inci' ), 'post_field' => 'post_author', ), 'date' => array( 'title' => __( 'Date', 'wp-inci' ), ), ), 'admin_filters' => array( 'functions' => array( 'title' => __( 'All Functions', 'wp-inci' ), 'taxonomy' => 'functions', ), 'source' => array( 'title' => __( 'All Sources', 'wp-inci' ), 'taxonomy' => 'source', ), 'author' => array( 'title' => __( 'All Authors', 'wp-inci' ), 'post_author' => true, ), ), ), array( 'singular' => __( 'Ingredient', 'wp-inci' ), 'plural' => __( 'Ingredients', 'wp-inci' ), 'slug' => __( 'ingredient', 'wp-inci' ) ) ); $functions_labels = [ 'name' => __( 'Functions', 'wp-inci' ), 'singular_name' => _x( 'Function', 'taxonomy general name', 'wp-inci' ), 'search_items' => __( 'Search Functions', 'wp-inci' ), 'popular_items' => __( 'Popular Functions', 'wp-inci' ), 'all_items' => __( 'All Functions', 'wp-inci' ), 'parent_item' => __( 'Parent Function', 'wp-inci' ), 'parent_item_colon' => __( 'Parent Function:', 'wp-inci' ), 'edit_item' => __( 'Edit Function', 'wp-inci' ), 'update_item' => __( 'Update Function', 'wp-inci' ), 'view_item' => __( 'View Function', 'wp-inci' ), 'add_new_item' => __( 'Add New Function', 'wp-inci' ), 'new_item_name' => __( 'New Function', 'wp-inci' ), 'separate_items_with_commas' => __( 'Separate Functions with commas', 'wp-inci' ), 'add_or_remove_items' => __( 'Add or remove Functions', 'wp-inci' ), 'choose_from_most_used' => __( 'Choose from the most used Functions', 'wp-inci' ), 'not_found' => __( 'No Functions found.', 'wp-inci' ), 'no_terms' => __( 'No Functions', 'wp-inci' ), 'menu_name' => __( 'Functions', 'wp-inci' ), 'items_list_navigation' => __( 'Functions list navigation', 'wp-inci' ), 'items_list' => __( 'Functions list', 'wp-inci' ), 'most_used' => _x( 'Most Used', 'function', 'wp-inci' ), 'back_to_items' => __( '&larr; Back to Functions', 'wp-inci' ), ]; register_extended_taxonomy( 'functions', 'ingredient', array( 'hierarchical' => false, 'labels' => $functions_labels, 'public' => false, 'show_in_rest' => true, 'rewrite' => false, ), array( 'singular' => __( 'Function', 'wp-inci' ), 'plural' => __( 'Functions', 'wp-inci' ), 'slug' => __( 'functions', 'wp-inci' ) ) ); $source_labels = [ 'name' => __( 'Sources', 'wp-inci' ), 'singular_name' => _x( 'Source', 'taxonomy general name', 'wp-inci' ), 'search_items' => __( 'Search Sources', 'wp-inci' ), 'popular_items' => __( 'Popular Sources', 'wp-inci' ), 'all_items' => __( 'All Sources', 'wp-inci' ), 'parent_item' => __( 'Parent Source', 'wp-inci' ), 'parent_item_colon' => __( 'Parent Source:', 'wp-inci' ), 'edit_item' => __( 'Edit Source', 'wp-inci' ), 'update_item' => __( 'Update Source', 'wp-inci' ), 'view_item' => __( 'View Source', 'wp-inci' ), 'add_new_item' => __( 'Add New Source', 'wp-inci' ), 'new_item_name' => __( 'New Source', 'wp-inci' ), 'separate_items_with_commas' => __( 'Separate Sources with commas', 'wp-inci' ), 'add_or_remove_items' => __( 'Add or remove Sources', 'wp-inci' ), 'choose_from_most_used' => __( 'Choose from the most used Sources', 'wp-inci' ), 'not_found' => __( 'No Sources found.', 'wp-inci' ), 'no_terms' => __( 'No Sources', 'wp-inci' ), 'menu_name' => __( 'Sources', 'wp-inci' ), 'items_list_navigation' => __( 'Sources list navigation', 'wp-inci' ), 'items_list' => __( 'Sources list', 'wp-inci' ), 'most_used' => _x( 'Most Used', 'source', 'wp-inci' ), 'back_to_items' => __( '&larr; Back to Sources', 'wp-inci' ), ]; register_extended_taxonomy( 'source', 'ingredient', array( 'public' => false, 'labels' => $source_labels, 'rewrite' => false, 'show_in_rest' => true, 'hierarchical' => true, 'admin_cols' => array( 'url' => array( 'title' => __( 'Url', 'wp-inci' ), 'function' => function ( $term_id ) { $term = get_term_by( 'id', $term_id, 'source' ); $url = get_term_meta( $term_id, 'source_url', true ); echo '<a href="' . $url . '" target="_blank">' . $term->name . ' &#x2197;</a>'; }, ), ), ), array( 'singular' => __( 'Source', 'wp-inci' ), 'plural' => __( 'Sources', 'wp-inci' ), 'slug' => __( 'source', 'wp-inci' ) ) ); } /** * Returns the safety custom meta with HTML. * * @param int|false $post_id * * @return string */ public function get_safety_html( $post_id ) { $safety = $this->get_safety_value( $post_id ); return '<div class="' . $safety[0] . ' first">' . strtoupper( $safety[0] ) . '</div><div class="' . $safety[1] . ' second">' . strtoupper( $safety[1] ) . '</div>'; } /** * Gets the value of safety custom meta and fills the gaps. * * @param $post_id * * @return array $safety */ public function get_safety_value( $post_id ) { $safety = get_post_meta( $post_id, 'safety', true ); switch ( $safety ) { case '1' : $safety = array( 'g', 'g' ); break; case '2' : $safety = array( 'g', 'w' ); break; case '3' : $safety = array( 'y', 'w' ); break; case '4' : $safety = array( 'r', 'w' ); break; case '5' : $safety = array( 'r', 'r' ); break; case '' : $safety = array( 'w', 'w' ); break; default: $safety = array( 'w', 'w' ); } return $safety; } /** * Register Custom Post Type Product and Brand Taxonomy. */ public function products_post_type() { $product_labels = [ 'name' => __( 'Products', 'wp-inci' ), 'singular_name' => __( 'Product', 'wp-inci' ), 'all_items' => __( 'All Products', 'wp-inci' ), 'archives' => __( 'Product Archives', 'wp-inci' ), 'attributes' => __( 'Product Attributes', 'wp-inci' ), 'insert_into_item' => __( 'Insert into Product', 'wp-inci' ), 'uploaded_to_this_item' => __( 'Uploaded to this Product', 'wp-inci' ), 'featured_image' => _x( 'Featured Image', 'product', 'wp-inci' ), 'set_featured_image' => _x( 'Set featured image', 'product', 'wp-inci' ), 'remove_featured_image' => _x( 'Remove featured image', 'product', 'wp-inci' ), 'use_featured_image' => _x( 'Use as featured image', 'product', 'wp-inci' ), 'filter_items_list' => __( 'Filter Products list', 'wp-inci' ), 'items_list_navigation' => __( 'Products list navigation', 'wp-inci' ), 'items_list' => __( 'Products list', 'wp-inci' ), 'new_item' => __( 'New Product', 'wp-inci' ), 'add_new' => __( 'Add New', 'wp-inci' ), 'add_new_item' => __( 'Add New Product', 'wp-inci' ), 'edit_item' => __( 'Edit Product', 'wp-inci' ), 'view_item' => __( 'View Product', 'wp-inci' ), 'view_items' => __( 'View Products', 'wp-inci' ), 'search_items' => __( 'Search Products', 'wp-inci' ), 'not_found' => __( 'No Products found', 'wp-inci' ), 'not_found_in_trash' => __( 'No Products found in trash', 'wp-inci' ), 'parent_item_colon' => __( 'Parent Product:', 'wp-inci' ), 'menu_name' => __( 'Products', 'wp-inci' ), ]; register_extended_post_type( 'product', array( 'dashboard_activity' => true, 'menu_icon' => 'dashicons-wi-menu', 'labels' => $product_labels, 'capability_type' => 'page', 'show_in_feed' => true, 'show_in_rest' => true, 'block_editor' => true, 'rewrite' => true, 'supports' => array( 'title', 'editor', 'author', 'revisions', ), 'admin_cols' => array( 'title' => array( 'title' => __( 'Product', 'wp-inci' ), 'default' => 'ASC', ), 'brand' => array( 'title' => __( 'Brand', 'wp-inci' ), 'taxonomy' => 'brand' ), 'shortcode' => array( 'title' => __( 'Shortcode', 'wp-inci' ), 'function' => function () { global $post; echo '<input readonly="readonly" type="text" onclick="copyShort(this)" value="[wp_inci_product id=' . $post->ID . ']">'; }, ), 'author' => array( 'title' => __( 'Author', 'wp-inci' ), 'post_field' => 'post_author', ), 'date' => array( 'title' => __( 'Date', 'wp-inci' ), ), ), 'admin_filters' => array( 'brand' => array( 'title' => __( 'All Brands', 'wp-inci' ), 'taxonomy' => 'brand', ), 'author' => array( 'title' => __( 'All Authors', 'wp-inci' ), 'post_author' => true, ), ), ), array( 'singular' => __( 'Product', 'wp-inci' ), 'plural' => __( 'Products', 'wp-inci' ), 'slug' => __( 'product', 'wp-inci' ), ) ); $brand_labels = [ 'name' => __( 'Brands', 'wp-inci' ), 'singular_name' => _x( 'Brand', 'taxonomy general name', 'wp-inci' ), 'search_items' => __( 'Search Brands', 'wp-inci' ), 'popular_items' => __( 'Popular Brands', 'wp-inci' ), 'all_items' => __( 'All Brands', 'wp-inci' ), 'parent_item' => __( 'Parent Brand', 'wp-inci' ), 'parent_item_colon' => __( 'Parent Brand:', 'wp-inci' ), 'edit_item' => __( 'Edit Brand', 'wp-inci' ), 'update_item' => __( 'Update Brand', 'wp-inci' ), 'view_item' => __( 'View Brand', 'wp-inci' ), 'add_new_item' => __( 'Add New Brand', 'wp-inci' ), 'new_item_name' => __( 'New Brand', 'wp-inci' ), 'separate_items_with_commas' => __( 'Separate Brands with commas', 'wp-inci' ), 'add_or_remove_items' => __( 'Add or remove Brands', 'wp-inci' ), 'choose_from_most_used' => __( 'Choose from the most used Brands', 'wp-inci' ), 'not_found' => __( 'No Brands found.', 'wp-inci' ), 'no_terms' => __( 'No Brands', 'wp-inci' ), 'menu_name' => __( 'Brands', 'wp-inci' ), 'items_list_navigation' => __( 'Brands list navigation', 'wp-inci' ), 'items_list' => __( 'Brands list', 'wp-inci' ), 'most_used' => _x( 'Most Used', 'brand', 'wp-inci' ), 'back_to_items' => __( '&larr; Back to Brands', 'wp-inci' ), ]; register_extended_taxonomy( 'brand', 'product', array( 'public' => true, 'rewrite' => true, 'hierarchical' => false, 'show_in_rest' => false, 'labels' => $brand_labels, 'meta_box_cb' => false, ), array( 'singular' => __( 'Brand', 'wp-inci' ), 'plural' => __( 'Brands', 'wp-inci' ), 'slug' => __( 'brand', 'wp-inci' ) ) ); } /** * Sets text for default disclaimer. */ public function wi_default_disclaimer() { return __( "The evaluation of these ingredients reflects the opinion of the author, who is not a specialist in this field. This evaluation is based on some online databases (e.g. <a title=\"CosIng - Cosmetic ingredients database\" href=\"https://ec.europa.eu/growth/sectors/cosmetics/cosing/\" target=\"_blank\">CosIng</a>).", 'wp-inci' ); } /** * Sets the post updated messages for the `ingredient` post type. * * @param array $messages Post updated messages. * @return array Messages for the `ingredient` post type. */ public function ingredient_updated_messages( $messages ) { global $post; $permalink = get_permalink( $post ); $messages['ingredient'] = [ 0 => '', // Unused. Messages start at index 1. /* translators: %s: post permalink */ 1 => sprintf( __( 'Ingredient updated. <a target="_blank" href="%s">View Ingredient</a>', 'wp-inci' ), esc_url( $permalink ) ), 2 => __( 'Custom field updated.', 'wp-inci' ), 3 => __( 'Custom field deleted.', 'wp-inci' ), 4 => __( 'Ingredient updated.', 'wp-inci' ), /* translators: %s: date and time of the revision */ 5 => isset( $_GET['revision'] ) ? sprintf( __( 'Ingredient restored to revision from %s', 'wp-inci' ), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false, // phpcs:ignore WordPress.Security.NonceVerification.Recommended /* translators: %s: post permalink */ 6 => sprintf( __( 'Ingredient published. <a href="%s">View Ingredient</a>', 'wp-inci' ), esc_url( $permalink ) ), 7 => __( 'Ingredient saved.', 'wp-inci' ), /* translators: %s: post permalink */ 8 => sprintf( __( 'Ingredient submitted. <a target="_blank" href="%s">Preview Ingredient</a>', 'wp-inci' ), esc_url( add_query_arg( 'preview', 'true', $permalink ) ) ), /* translators: 1: Publish box date format, see https://secure.php.net/date 2: Post permalink */ 9 => sprintf( __( 'Ingredient scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Ingredient</a>', 'wp-inci' ), date_i18n( __( 'M j, Y @ G:i', 'wp-inci' ), strtotime( $post->post_date ) ), esc_url( $permalink ) ), /* translators: %s: post permalink */ 10 => sprintf( __( 'Ingredient draft updated. <a target="_blank" href="%s">Preview Ingredient</a>', 'wp-inci' ), esc_url( add_query_arg( 'preview', 'true', $permalink ) ) ), ]; return $messages; } /** * Sets the bulk post updated messages for the `ingredient` post type. * * @param array $bulk_messages Arrays of messages, each keyed by the corresponding post type. Messages are * keyed with 'updated', 'locked', 'deleted', 'trashed', and 'untrashed'. * @param int[] $bulk_counts Array of item counts for each message, used to build internationalized strings. * @return array Bulk messages for the `ingredient` post type. */ public function ingredient_bulk_updated_messages( $bulk_messages, $bulk_counts ) { $bulk_messages['ingredient'] = [ /* translators: %s: Number of Ingredients. */ 'updated' => _n( '%s Ingredient updated.', '%s Ingredients updated.', $bulk_counts['updated'], 'wp-inci' ), 'locked' => ( 1 === $bulk_counts['locked'] ) ? __( '1 Ingredient not updated, somebody is editing it.', 'wp-inci' ) : /* translators: %s: Number of Ingredients. */ _n( '%s Ingredient not updated, somebody is editing it.', '%s Ingredients not updated, somebody is editing them.', $bulk_counts['locked'], 'wp-inci' ), /* translators: %s: Number of Ingredients. */ 'deleted' => _n( '%s Ingredient permanently deleted.', '%s Ingredients permanently deleted.', $bulk_counts['deleted'], 'wp-inci' ), /* translators: %s: Number of Ingredients. */ 'trashed' => _n( '%s Ingredient moved to the Trash.', '%s Ingredients moved to the Trash.', $bulk_counts['trashed'], 'wp-inci' ), /* translators: %s: Number of Ingredients. */ 'untrashed' => _n( '%s Ingredient restored from the Trash.', '%s Ingredients restored from the Trash.', $bulk_counts['untrashed'], 'wp-inci' ), ]; return $bulk_messages; } /** * Sets the post updated messages for the `product` post type. * * @param array $messages Post updated messages. * @return array Messages for the `product` post type. */ public function product_updated_messages( $messages ) { global $post; $permalink = get_permalink( $post ); $messages['product'] = [ 0 => '', // Unused. Messages start at index 1. /* translators: %s: post permalink */ 1 => sprintf( __( 'Product updated. <a target="_blank" href="%s">View Product</a>', 'wp-inci' ), esc_url( $permalink ) ), 2 => __( 'Custom field updated.', 'wp-inci' ), 3 => __( 'Custom field deleted.', 'wp-inci' ), 4 => __( 'Product updated.', 'wp-inci' ), /* translators: %s: date and time of the revision */ 5 => isset( $_GET['revision'] ) ? sprintf( __( 'Product restored to revision from %s', 'wp-inci' ), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false, // phpcs:ignore WordPress.Security.NonceVerification.Recommended /* translators: %s: post permalink */ 6 => sprintf( __( 'Product published. <a href="%s">View Product</a>', 'wp-inci' ), esc_url( $permalink ) ), 7 => __( 'Product saved.', 'wp-inci' ), /* translators: %s: post permalink */ 8 => sprintf( __( 'Product submitted. <a target="_blank" href="%s">Preview Product</a>', 'wp-inci' ), esc_url( add_query_arg( 'preview', 'true', $permalink ) ) ), /* translators: 1: Publish box date format, see https://secure.php.net/date 2: Post permalink */ 9 => sprintf( __( 'Product scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Product</a>', 'wp-inci' ), date_i18n( __( 'M j, Y @ G:i', 'wp-inci' ), strtotime( $post->post_date ) ), esc_url( $permalink ) ), /* translators: %s: post permalink */ 10 => sprintf( __( 'Product draft updated. <a target="_blank" href="%s">Preview Product</a>', 'wp-inci' ), esc_url( add_query_arg( 'preview', 'true', $permalink ) ) ), ]; return $messages; } /** * Sets the bulk post updated messages for the `product` post type. * * @param array $bulk_messages Arrays of messages, each keyed by the corresponding post type. Messages are * keyed with 'updated', 'locked', 'deleted', 'trashed', and 'untrashed'. * @param int[] $bulk_counts Array of item counts for each message, used to build internationalized strings. * @return array Bulk messages for the `product` post type. */ public function product_bulk_updated_messages( $bulk_messages, $bulk_counts ) { global $post; $bulk_messages['product'] = [ /* translators: %s: Number of Products. */ 'updated' => _n( '%s Product updated.', '%s Products updated.', $bulk_counts['updated'], 'wp-inci' ), 'locked' => ( 1 === $bulk_counts['locked'] ) ? __( '1 Product not updated, somebody is editing it.', 'wp-inci' ) : /* translators: %s: Number of Products. */ _n( '%s Product not updated, somebody is editing it.', '%s Products not updated, somebody is editing them.', $bulk_counts['locked'], 'wp-inci' ), /* translators: %s: Number of Products. */ 'deleted' => _n( '%s Product permanently deleted.', '%s Products permanently deleted.', $bulk_counts['deleted'], 'wp-inci' ), /* translators: %s: Number of Products. */ 'trashed' => _n( '%s Product moved to the Trash.', '%s Products moved to the Trash.', $bulk_counts['trashed'], 'wp-inci' ), /* translators: %s: Number of Products. */ 'untrashed' => _n( '%s Product restored from the Trash.', '%s Products restored from the Trash.', $bulk_counts['untrashed'], 'wp-inci' ), ]; return $bulk_messages; } /** * Sets the post updated messages for the `function` taxonomy. * * @param array $messages Post updated messages. * @return array Messages for the `function` taxonomy. */ public function function_updated_messages( $messages ) { $messages['function'] = [ 0 => '', // Unused. Messages start at index 1. 1 => __( 'Function added.', 'wp-inci' ), 2 => __( 'Function deleted.', 'wp-inci' ), 3 => __( 'Function updated.', 'wp-inci' ), 4 => __( 'Function not added.', 'wp-inci' ), 5 => __( 'Function not updated.', 'wp-inci' ), 6 => __( 'Functions deleted.', 'wp-inci' ), ]; return $messages; } /** * Sets the post updated messages for the `source` taxonomy. * * @param array $messages Post updated messages. * @return array Messages for the `source` taxonomy. */ public function source_updated_messages( $messages ) { $messages['source'] = [ 0 => '', // Unused. Messages start at index 1. 1 => __( 'Source added.', 'wp-inci' ), 2 => __( 'Source deleted.', 'wp-inci' ), 3 => __( 'Source updated.', 'wp-inci' ), 4 => __( 'Source not added.', 'wp-inci' ), 5 => __( 'Source not updated.', 'wp-inci' ), 6 => __( 'Sources deleted.', 'wp-inci' ), ]; return $messages; } /** * Sets the post updated messages for the `brand` taxonomy. * * @param array $messages Post updated messages. * @return array Messages for the `brand` taxonomy. */ public function brand_updated_messages( $messages ) { $messages['brand'] = [ 0 => '', // Unused. Messages start at index 1. 1 => __( 'Brand added.', 'wp-inci' ), 2 => __( 'Brand deleted.', 'wp-inci' ), 3 => __( 'Brand updated.', 'wp-inci' ), 4 => __( 'Brand not added.', 'wp-inci' ), 5 => __( 'Brand not updated.', 'wp-inci' ), 6 => __( 'Brands deleted.', 'wp-inci' ), ]; return $messages; } } add_action( 'plugins_loaded', array( 'WP_Inci', 'get_instance' ) ); }
xlthlx/wp-inci
class-wp-inci.php
PHP
gpl-3.0
27,589
/* * This file is protected by Copyright. Please refer to the COPYRIGHT file * distributed with this source distribution. * * This file is part of GNUHAWK. * * GNUHAWK is free software: you can redistribute it and/or modify is 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. * * GNUHAWK 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 "burst_tagger_cc_base.h" /******************************************************************************************* AUTO-GENERATED CODE. DO NOT MODIFY The following class functions are for the base class for the component class. To customize any of these functions, do not modify them here. Instead, overload them on the child class ******************************************************************************************/ burst_tagger_cc_base::burst_tagger_cc_base(const char *uuid, const char *label) : GnuHawkBlock(uuid, label), serviceThread(0), noutput_items(0), _maintainTimeStamp(false), _throttle(false) { construct(); } void burst_tagger_cc_base::construct() { Resource_impl::_started = false; loadProperties(); serviceThread = 0; sentEOS = false; inputPortOrder.resize(0);; outputPortOrder.resize(0); PortableServer::ObjectId_var oid; complex_in = new bulkio::InFloatPort("complex_in"); complex_in->setNewStreamListener(this, &burst_tagger_cc_base::complex_in_newStreamCallback); oid = ossie::corba::RootPOA()->activate_object(complex_in); trigger_in = new bulkio::InShortPort("trigger_in"); trigger_in->setNewStreamListener(this, &burst_tagger_cc_base::trigger_in_newStreamCallback); oid = ossie::corba::RootPOA()->activate_object(trigger_in); complex_out = new bulkio::OutFloatPort("complex_out"); oid = ossie::corba::RootPOA()->activate_object(complex_out); registerInPort(complex_in); inputPortOrder.push_back("complex_in"); registerInPort(trigger_in); inputPortOrder.push_back("trigger_in"); registerOutPort(complex_out, complex_out->_this()); outputPortOrder.push_back("complex_out"); } /******************************************************************************************* Framework-level functions These functions are generally called by the framework to perform housekeeping. *******************************************************************************************/ void burst_tagger_cc_base::initialize() throw (CF::LifeCycle::InitializeError, CORBA::SystemException) { } void burst_tagger_cc_base::start() throw (CORBA::SystemException, CF::Resource::StartError) { boost::mutex::scoped_lock lock(serviceThreadLock); if (serviceThread == 0) { complex_in->unblock(); trigger_in->unblock(); serviceThread = new ProcessThread<burst_tagger_cc_base>(this, 0.1); serviceThread->start(); } if (!Resource_impl::started()) { Resource_impl::start(); } } void burst_tagger_cc_base::stop() throw (CORBA::SystemException, CF::Resource::StopError) { if ( complex_in ) complex_in->block(); if ( trigger_in ) trigger_in->block(); { boost::mutex::scoped_lock lock(_sriMutex); _sriQueue.clear(); } // release the child thread (if it exists) if (serviceThread != 0) { { boost::mutex::scoped_lock lock(serviceThreadLock); LOG_TRACE( burst_tagger_cc_base, "Stopping Service Function" ); serviceThread->stop(); } if ( !serviceThread->release()) { throw CF::Resource::StopError(CF::CF_NOTSET, "Processing thread did not die"); } boost::mutex::scoped_lock lock(serviceThreadLock); if ( serviceThread ) { delete serviceThread; } } serviceThread = 0; if (Resource_impl::started()) { Resource_impl::stop(); } LOG_TRACE( burst_tagger_cc_base, "COMPLETED STOP REQUEST" ); } CORBA::Object_ptr burst_tagger_cc_base::getPort(const char* _id) throw (CORBA::SystemException, CF::PortSupplier::UnknownPort) { std::map<std::string, Port_Provides_base_impl *>::iterator p_in = inPorts.find(std::string(_id)); if (p_in != inPorts.end()) { if (!strcmp(_id,"complex_in")) { bulkio::InFloatPort *ptr = dynamic_cast<bulkio::InFloatPort *>(p_in->second); if (ptr) { return ptr->_this(); } } if (!strcmp(_id,"trigger_in")) { bulkio::InShortPort *ptr = dynamic_cast<bulkio::InShortPort *>(p_in->second); if (ptr) { return ptr->_this(); } } } std::map<std::string, CF::Port_var>::iterator p_out = outPorts_var.find(std::string(_id)); if (p_out != outPorts_var.end()) { return CF::Port::_duplicate(p_out->second); } throw (CF::PortSupplier::UnknownPort()); } void burst_tagger_cc_base::releaseObject() throw (CORBA::SystemException, CF::LifeCycle::ReleaseError) { // This function clears the component running condition so main shuts down everything try { stop(); } catch (CF::Resource::StopError& ex) { // TODO - this should probably be logged instead of ignored } // deactivate ports releaseInPorts(); releaseOutPorts(); delete(complex_in); delete(trigger_in); delete(complex_out); Resource_impl::releaseObject(); } void burst_tagger_cc_base::loadProperties() { addProperty(itemsize, 8, "itemsize", "", "readonly", "", "external", "configure"); addProperty(true_tag, true_tag_struct(), "true_tag", "", "readwrite", "", "external", "configure"); addProperty(false_tag, false_tag_struct(), "false_tag", "", "readwrite", "", "external", "configure"); } // Destructor burst_tagger_cc_base::~burst_tagger_cc_base() { // Free input streams for (IStreamList::iterator iter = _istreams.begin(); iter != _istreams.end(); ++iter) { delete (*iter); } // Free output streams for (OStreamList::iterator iter = _ostreams.begin(); iter != _ostreams.end(); ++iter) { delete (*iter); } } // // Allow for logging // PREPARE_LOGGING(burst_tagger_cc_base); inline static unsigned int round_up (unsigned int n, unsigned int multiple) { return ((n + multiple - 1) / multiple) * multiple; } inline static unsigned int round_down (unsigned int n, unsigned int multiple) { return (n / multiple) * multiple; } uint32_t burst_tagger_cc_base::getNOutputStreams() { return 0; } void burst_tagger_cc_base::setupIOMappings( ) { int ninput_streams = 0; int noutput_streams = 0; std::string sid(""); int inMode=RealMode; if ( !validGRBlock() ) return; ninput_streams = gr_sptr->get_max_input_streams(); gr_io_signature_sptr g_isig = gr_sptr->input_signature(); noutput_streams = gr_sptr->get_max_output_streams(); gr_io_signature_sptr g_osig = gr_sptr->output_signature(); LOG_DEBUG( burst_tagger_cc_base, "GNUHAWK IO MAPPINGS IN/OUT " << ninput_streams << "/" << noutput_streams ); // // Someone reset the GR Block so we need to clean up old mappings if they exists // we need to reset the io signatures and check the vlens // if ( _istreams.size() > 0 || _ostreams.size() > 0 ) { LOG_DEBUG( burst_tagger_cc_base, "RESET INPUT SIGNATURE SIZE:" << _istreams.size() ); IStreamList::iterator istream; for ( int idx=0 ; istream != _istreams.end(); idx++, istream++ ) { // re-add existing stream definitons LOG_DEBUG( burst_tagger_cc_base, "ADD READ INDEX TO GNU RADIO BLOCK"); if ( ninput_streams == -1 ) gr_sptr->add_read_index(); // setup io signature (*istream)->associate( gr_sptr ); } LOG_DEBUG( burst_tagger_cc_base, "RESET OUTPUT SIGNATURE SIZE:" << _ostreams.size() ); OStreamList::iterator ostream; for ( int idx=0 ; ostream != _ostreams.end(); idx++, ostream++ ) { // need to evaluate new settings...??? (*ostream)->associate( gr_sptr ); } return; } int i = 0; // // Setup mapping of RH port to GNU RADIO Block input streams // For version 1, we are ignoring the GNU Radio input stream -1 case that allows multiple data // streams over a single connection. We are mapping a single RH Port to a single GNU Radio stream. // Stream Identifiers will be pass along as they are received // LOG_TRACE( burst_tagger_cc_base, "setupIOMappings INPUT PORTS: " << inPorts.size() ); RH_ProvidesPortMap::iterator p_in; i = 0; // grab ports based on their order in the scd.xml file p_in = inPorts.find("complex_in"); if ( p_in != inPorts.end() ) { bulkio::InFloatPort *port = dynamic_cast< bulkio::InFloatPort * >(p_in->second); int mode = inMode; sid = ""; // need to add read index to GNU Radio Block for processing streams when max_input == -1 if ( ninput_streams == -1 ) gr_sptr->add_read_index(); // check if we received SRI during setup BULKIO::StreamSRISequence_var sris = port->activeSRIs(); if ( sris->length() > 0 ) { BULKIO::StreamSRI sri = sris[sris->length()-1]; mode = sri.mode; } std::vector<int> in; io_mapping.push_back( in ); _istreams.push_back( new gr_istream< bulkio::InFloatPort > ( port, gr_sptr, i, mode, sid )); LOG_DEBUG( burst_tagger_cc_base, "ADDING INPUT MAP IDX:" << i << " SID:" << sid ); // increment port counter i++; } // grab ports based on their order in the scd.xml file p_in = inPorts.find("trigger_in"); if ( p_in != inPorts.end() ) { bulkio::InShortPort *port = dynamic_cast< bulkio::InShortPort * >(p_in->second); int mode = inMode; sid = ""; // need to add read index to GNU Radio Block for processing streams when max_input == -1 if ( ninput_streams == -1 ) gr_sptr->add_read_index(); // check if we received SRI during setup BULKIO::StreamSRISequence_var sris = port->activeSRIs(); if ( sris->length() > 0 ) { BULKIO::StreamSRI sri = sris[sris->length()-1]; mode = sri.mode; } std::vector<int> in; io_mapping.push_back( in ); _istreams.push_back( new gr_istream< bulkio::InShortPort > ( port, gr_sptr, i, mode, sid )); LOG_DEBUG( burst_tagger_cc_base, "ADDING INPUT MAP IDX:" << i << " SID:" << sid ); // increment port counter i++; } // // Setup mapping of RH port to GNU RADIO Block input streams // For version 1, we are ignoring the GNU Radio output stream -1 case that allows multiple data // streams over a single connection. We are mapping a single RH Port to a single GNU Radio stream. // LOG_TRACE( burst_tagger_cc_base, "setupIOMappings OutputPorts: " << outPorts.size() ); RH_UsesPortMap::iterator p_out; i = 0; // grab ports based on their order in the scd.xml file p_out = outPorts.find("complex_out"); if ( p_out != outPorts.end() ) { bulkio::OutFloatPort *port = dynamic_cast< bulkio::OutFloatPort * >(p_out->second); int idx = -1; BULKIO::StreamSRI sri = createOutputSRI( i, idx ); if (idx == -1) idx = i; if(idx < (int)io_mapping.size()) io_mapping[idx].push_back(i); int mode = sri.mode; sid = sri.streamID; _ostreams.push_back( new gr_ostream< bulkio::OutFloatPort > ( port, gr_sptr, i, mode, sid )); LOG_DEBUG( burst_tagger_cc_base, "ADDING OUTPUT MAP IDX:" << i << " SID:" << sid ); _ostreams[i]->setSRI(sri, i ); // increment port counter i++; } } void burst_tagger_cc_base::complex_in_newStreamCallback( BULKIO::StreamSRI &sri ) { LOG_TRACE( burst_tagger_cc_base, "START NotifySRI port:stream " << complex_in->getName() << "/" << sri.streamID); boost::mutex::scoped_lock lock(_sriMutex); _sriQueue.push_back( std::make_pair( complex_in, sri ) ); LOG_TRACE( burst_tagger_cc_base, "END NotifySRI QUEUE " << _sriQueue.size() << " port:stream " << complex_in->getName() << "/" << sri.streamID); } void burst_tagger_cc_base::trigger_in_newStreamCallback( BULKIO::StreamSRI &sri ) { LOG_TRACE( burst_tagger_cc_base, "START NotifySRI port:stream " << trigger_in->getName() << "/" << sri.streamID); boost::mutex::scoped_lock lock(_sriMutex); _sriQueue.push_back( std::make_pair( trigger_in, sri ) ); LOG_TRACE( burst_tagger_cc_base, "END NotifySRI QUEUE " << _sriQueue.size() << " port:stream " << trigger_in->getName() << "/" << sri.streamID); } void burst_tagger_cc_base::processStreamIdChanges() { boost::mutex::scoped_lock lock(_sriMutex); LOG_TRACE( burst_tagger_cc_base, "processStreamIDChanges QUEUE: " << _sriQueue.size() ); if ( _sriQueue.size() == 0 ) return; std::string sid(""); if ( validGRBlock() ) { IStreamList::iterator istream; int idx=0; std::string sid(""); int mode=0; SRIQueue::iterator item = _sriQueue.begin(); for ( ; item != _sriQueue.end(); item++ ) { idx = 0; sid = ""; mode= item->second.mode; sid = item->second.streamID; istream = _istreams.begin(); for ( ; istream != _istreams.end(); idx++, istream++ ) { if ( (*istream)->getPort() == item->first ) { LOG_DEBUG( burst_tagger_cc_base, " SETTING IN_STREAM ID/STREAM_ID :" << idx << "/" << sid ); (*istream)->sri(true); (*istream)->spe(mode); LOG_DEBUG( burst_tagger_cc_base, " SETTING OUT_STREAM ID/STREAM_ID :" << idx << "/" << sid ); setOutputStreamSRI( idx, item->second ); } } } _sriQueue.clear(); } else { LOG_WARN( burst_tagger_cc_base, " NEW STREAM ID, NO GNU RADIO BLOCK DEFINED, SRI QUEUE SIZE:" << _sriQueue.size() ); } } BULKIO::StreamSRI burst_tagger_cc_base::createOutputSRI( int32_t oidx ) { // for each output stream set the SRI context BULKIO::StreamSRI sri = BULKIO::StreamSRI(); sri.hversion = 1; sri.xstart = 0.0; sri.xdelta = 1; sri.xunits = BULKIO::UNITS_TIME; sri.subsize = 0; sri.ystart = 0.0; sri.ydelta = 0.0; sri.yunits = BULKIO::UNITS_NONE; sri.mode = 0; std::ostringstream t; t << naming_service_name.c_str() << "_" << oidx; std::string sid = t.str(); sri.streamID = CORBA::string_dup(sid.c_str()); return sri; } BULKIO::StreamSRI burst_tagger_cc_base::createOutputSRI( int32_t oidx, int32_t &in_idx) { return createOutputSRI( oidx ); } void burst_tagger_cc_base::adjustOutputRate(BULKIO::StreamSRI &sri ) { if ( validGRBlock() ) { double ret=sri.xdelta*gr_sptr->relative_rate(); /** **/ LOG_TRACE( burst_tagger_cc_base, "ADJUSTING SRI.XDELTA FROM/TO: " << sri.xdelta << "/" << ret ); sri.xdelta = ret; } } burst_tagger_cc_base::TimeDuration burst_tagger_cc_base::getTargetDuration() { TimeDuration t_drate;; uint64_t samps=0; double xdelta=1.0; double trate=1.0; if ( _ostreams.size() > 0 ) { samps= _ostreams[0]->nelems(); xdelta= _ostreams[0]->sri.xdelta; } trate = samps*xdelta; uint64_t sec = (uint64_t)trunc(trate); uint64_t usec = (uint64_t)((trate-sec)*1e6); t_drate = boost::posix_time::seconds(sec) + boost::posix_time::microseconds(usec); LOG_TRACE( burst_tagger_cc_base, " SEC/USEC " << sec << "/" << usec << "\n" << " target_duration " << t_drate ); return t_drate; } burst_tagger_cc_base::TimeDuration burst_tagger_cc_base::calcThrottle( TimeMark &start_time, TimeMark &end_time ) { TimeDuration delta; TimeDuration target_duration = getTargetDuration(); if ( start_time.is_not_a_date_time() == false ) { TimeDuration s_dtime= end_time - start_time; delta = target_duration - s_dtime; delta /= 4; LOG_TRACE( burst_tagger_cc_base, " s_time/t_dime " << s_dtime << "/" << target_duration << "\n" << " delta " << delta ); } return delta; } int burst_tagger_cc_base::_transformerServiceFunction( std::vector< gr_istream_base * > &istreams , std::vector< gr_ostream_base * > &ostreams ) { typedef std::vector< gr_istream_base * > _IStreamList; typedef std::vector< gr_ostream_base * > _OStreamList; boost::mutex::scoped_lock lock(serviceThreadLock); if ( validGRBlock() == false ) { // create our processing block, and setup property notifiers createBlock(); LOG_DEBUG( burst_tagger_cc_base, " FINISHED BUILDING GNU RADIO BLOCK"); } //process any Stream ID changes this could affect number of io streams processStreamIdChanges(); if ( !validGRBlock() || istreams.size() == 0 || ostreams.size() == 0 ) { LOG_WARN( burst_tagger_cc_base, "NO STREAMS ATTACHED TO BLOCK..." ); return NOOP; } _input_ready.resize( istreams.size() ); _ninput_items_required.resize( istreams.size() ); _ninput_items.resize( istreams.size() ); _input_items.resize( istreams.size() ); _output_items.resize( ostreams.size() ); // // RESOLVE: need to look at forecast strategy, // 1) see how many read items are necessary for N number of outputs // 2) read input data and see how much output we can produce // // // Grab available data from input streams // _OStreamList::iterator ostream; _IStreamList::iterator istream = istreams.begin(); int nitems=0; for ( int idx=0 ; istream != istreams.end() && serviceThread->threadRunning() ; idx++, istream++ ) { // note this a blocking read that can cause deadlocks nitems = (*istream)->read(); if ( (*istream)->overrun() ) { LOG_WARN( burst_tagger_cc_base, " NOT KEEPING UP WITH STREAM ID:" << (*istream)->streamID ); } if ( (*istream)->sriChanged() ) { // RESOLVE - need to look at how SRI changes can affect Gnu Radio BLOCK state LOG_DEBUG( burst_tagger_cc_base, "SRI CHANGED, STREAMD IDX/ID: " << idx << "/" << (*istream)->getPktStreamId() ); setOutputStreamSRI( idx, (*istream)->getPktSri() ); } } LOG_TRACE( burst_tagger_cc_base, "READ NITEMS: " << nitems ); if ( nitems <= 0 && !_istreams[0]->eos() ) { return NOOP; } bool eos = false; int nout = 0; bool workDone = false; while ( nout > -1 && serviceThread->threadRunning() ) { eos = false; nout = _forecastAndProcess( eos, istreams, ostreams ); if ( nout > -1 ) { workDone = true; // we chunked on data so move read pointer.. istream = istreams.begin(); for ( ; istream != istreams.end(); istream++ ) { int idx=std::distance( istreams.begin(), istream ); // if we processed data for this stream if ( _input_ready[idx] ) { size_t nitems = 0; try { nitems = gr_sptr->nitems_read( idx ); } catch(...){} if ( nitems > (*istream)->nitems() ) { LOG_WARN( burst_tagger_cc_base, "WORK CONSUMED MORE DATA THAN AVAILABLE, READ/AVAILABLE " << nitems << "/" << (*istream)->nitems() ); nitems = (*istream)->nitems(); } (*istream)->consume( nitems ); LOG_TRACE( burst_tagger_cc_base, " CONSUME READ DATA ITEMS/REMAIN " << nitems << "/" << (*istream)->nitems()); } } gr_sptr->reset_read_index(); } // check for not enough data return if ( nout == -1 ) { // check for end of stream istream = istreams.begin(); for ( ; istream != istreams.end() ; istream++) { if ( (*istream)->eos() ) { eos=true; } } if ( eos ) { LOG_TRACE( burst_tagger_cc_base, "EOS SEEN, SENDING DOWNSTREAM " ); _forecastAndProcess( eos, istreams, ostreams); } } } if ( eos ) { istream = istreams.begin(); for ( ; istream != istreams.end() ; istream++ ) { int idx=std::distance( istreams.begin(), istream ); LOG_DEBUG( burst_tagger_cc_base, " CLOSING INPUT STREAM IDX:" << idx ); (*istream)->close(); } // close remaining output streams ostream = ostreams.begin(); for ( ; eos && ostream != ostreams.end(); ostream++ ) { int idx=std::distance( ostreams.begin(), ostream ); LOG_DEBUG( burst_tagger_cc_base, " CLOSING OUTPUT STREAM IDX:" << idx ); (*ostream)->close(); } } // // set the read pointers of the GNU Radio Block to start at the beginning of the // supplied buffers // gr_sptr->reset_read_index(); LOG_TRACE( burst_tagger_cc_base, " END OF TRANSFORM SERVICE FUNCTION....." << noutput_items ); if ( nout == -1 && eos == false && !workDone ) { return NOOP; } else { return NORMAL; } } int burst_tagger_cc_base::_forecastAndProcess( bool &eos, std::vector< gr_istream_base * > &istreams , std::vector< gr_ostream_base * > &ostreams ) { typedef std::vector< gr_istream_base * > _IStreamList; typedef std::vector< gr_ostream_base * > _OStreamList; _OStreamList::iterator ostream; _IStreamList::iterator istream = istreams.begin(); int nout = 0; bool dataReady = false; if ( !eos ) { uint64_t max_items_avail = 0; for ( int idx=0 ; istream != istreams.end() && serviceThread->threadRunning() ; idx++, istream++ ) { LOG_TRACE( burst_tagger_cc_base, "GET MAX ITEMS: STREAM:"<< idx << " NITEMS/SCALARS:" << (*istream)->nitems() << "/" << (*istream)->nelems() ); max_items_avail = std::max( (*istream)->nitems(), max_items_avail ); } if ( max_items_avail == 0 ) { LOG_TRACE( burst_tagger_cc_base, "DATA CHECK - MAX ITEMS NOUTPUT/MAX_ITEMS:" << noutput_items << "/" << max_items_avail); return -1; } // // calc number of output elements based on input items available // noutput_items = 0; if ( !gr_sptr->fixed_rate() ) { noutput_items = round_down((int32_t) (max_items_avail * gr_sptr->relative_rate()), gr_sptr->output_multiple()); LOG_TRACE( burst_tagger_cc_base, " VARIABLE FORECAST NOUTPUT == " << noutput_items ); } else { istream = istreams.begin(); for ( int i=0; istream != istreams.end(); i++, istream++ ) { int t_noutput_items = gr_sptr->fixed_rate_ninput_to_noutput( (*istream)->nitems() ); if ( gr_sptr->output_multiple_set() ) { t_noutput_items = round_up(t_noutput_items, gr_sptr->output_multiple()); } if ( t_noutput_items > 0 ) { if ( noutput_items == 0 ) { noutput_items = t_noutput_items; } if ( t_noutput_items <= noutput_items ) { noutput_items = t_noutput_items; } } } LOG_TRACE( burst_tagger_cc_base, " FIXED FORECAST NOUTPUT/output_multiple == " << noutput_items << "/" << gr_sptr->output_multiple()); } // // ask the block how much input they need to produce noutput_items... // if enough data is available to process then set the dataReady flag // int32_t outMultiple = gr_sptr->output_multiple(); while ( !dataReady && noutput_items >= outMultiple ) { // // ask the block how much input they need to produce noutput_items... // gr_sptr->forecast(noutput_items, _ninput_items_required); LOG_TRACE( burst_tagger_cc_base, "--> FORECAST IN/OUT " << _ninput_items_required[0] << "/" << noutput_items ); istream = istreams.begin(); uint32_t dr_cnt=0; for ( int idx=0 ; noutput_items > 0 && istream != istreams.end(); idx++, istream++ ) { // check if buffer has enough elements _input_ready[idx] = false; if ( (*istream)->nitems() >= (uint64_t)_ninput_items_required[idx] ) { _input_ready[idx] = true; dr_cnt++; } LOG_TRACE( burst_tagger_cc_base, "ISTREAM DATACHECK NELMS/NITEMS/REQ/READY:" << (*istream)->nelems() << "/" << (*istream)->nitems() << "/" << _ninput_items_required[idx] << "/" << _input_ready[idx]); } if ( dr_cnt < istreams.size() ) { if ( outMultiple > 1 ) { noutput_items -= outMultiple; } else { noutput_items /= 2; } } else { dataReady = true; } LOG_TRACE( burst_tagger_cc_base, " TRIM FORECAST NOUTPUT/READY " << noutput_items << "/" << dataReady ); } // check if data is ready... if ( !dataReady ) { LOG_TRACE( burst_tagger_cc_base, "DATA CHECK - NOT ENOUGH DATA AVAIL/REQ:" << _istreams[0]->nitems() << "/" << _ninput_items_required[0] ); return -1; } // reset looping variables int ritems = 0; int nitems = 0; // reset caching vectors _output_items.clear(); _input_items.clear(); _ninput_items.clear(); istream = istreams.begin(); for ( int idx=0 ; istream != istreams.end(); idx++, istream++ ) { // check if the stream is ready if ( !_input_ready[idx] ) { continue; } // get number of items remaining try { ritems = gr_sptr->nitems_read( idx ); } catch(...){ // something bad has happened, we are missing an input stream LOG_ERROR( burst_tagger_cc_base, "MISSING INPUT STREAM FOR GR BLOCK, STREAM ID:" << (*istream)->streamID ); return -2; } nitems = (*istream)->nitems() - ritems; LOG_TRACE( burst_tagger_cc_base, " ISTREAM: IDX:" << idx << " ITEMS AVAIL/READ/REQ " << nitems << "/" << ritems << "/" << _ninput_items_required[idx] ); if ( nitems >= _ninput_items_required[idx] && nitems > 0 ) { //remove eos checks ...if ( nitems < _ninput_items_required[idx] ) nitems=0; _ninput_items.push_back( nitems ); _input_items.push_back( (*istream)->read_pointer(ritems) ); } } // // setup output buffer vector based on noutput.. // ostream = ostreams.begin(); for( ; ostream != ostreams.end(); ostream++ ) { (*ostream)->resize(noutput_items); _output_items.push_back( (*ostream)->write_pointer() ); } nout=0; if ( _input_items.size() != 0 && serviceThread->threadRunning() ) { LOG_TRACE( burst_tagger_cc_base, " CALLING WORK.....N_OUT:" << noutput_items << " N_IN:" << nitems << " ISTREAMS:" << _input_items.size() << " OSTREAMS:" << _output_items.size()); nout = gr_sptr->general_work( noutput_items, _ninput_items, _input_items, _output_items); LOG_TRACE( burst_tagger_cc_base, "RETURN WORK ..... N_OUT:" << nout); } // check for stop condition from work method if ( nout < gr_block::WORK_DONE ) { LOG_WARN( burst_tagger_cc_base, "WORK RETURNED STOP CONDITION..." << nout ); nout=0; eos = true; } } if (nout != 0 or eos ) { noutput_items = nout; LOG_TRACE( burst_tagger_cc_base, " WORK RETURNED: NOUT : " << nout << " EOS:" << eos); ostream = ostreams.begin(); for ( int idx=0 ; ostream != ostreams.end(); idx++, ostream++ ) { bool gotPkt = false; TimeStamp pktTs; int inputIdx = idx; if ( (size_t)(inputIdx) >= istreams.size() ) { for ( inputIdx= istreams.size()-1; inputIdx > -1; inputIdx--) { if ( not istreams[inputIdx]->pktNull() ) { gotPkt = true; pktTs = istreams[inputIdx]->getPktTimeStamp(); break; } } } else { pktTs = istreams[inputIdx]->getPktTimeStamp(); if ( not istreams[inputIdx]->pktNull() ){ gotPkt = true; } } LOG_TRACE( burst_tagger_cc_base, "PUSHING DATA ITEMS/STREAM_ID " << (*ostream)->nitems() << "/" << (*ostream)->streamID ); if ( _maintainTimeStamp ) { // set time stamp for output samples based on input time stamp if ( (*ostream)->nelems() == 0 ) { #ifdef TEST_TIME_STAMP LOG_DEBUG( burst_tagger_cc_base, "SEED - TS SRI: xdelta:" << std::setprecision(12) << ostream->sri.xdelta ); LOG_DEBUG( burst_tagger_cc_base, "OSTREAM WRITE: maint:" << _maintainTimeStamp ); LOG_DEBUG( burst_tagger_cc_base, " mode:" << ostream->tstamp.tcmode ); LOG_DEBUG( burst_tagger_cc_base, " status:" << ostream->tstamp.tcstatus ); LOG_DEBUG( burst_tagger_cc_base, " offset:" << ostream->tstamp.toff ); LOG_DEBUG( burst_tagger_cc_base, " whole:" << std::setprecision(10) << ostream->tstamp.twsec ); LOG_DEBUG( burst_tagger_cc_base, "SEED - TS frac:" << std::setprecision(12) << ostream->tstamp.tfsec ); #endif (*ostream)->setTimeStamp( pktTs, _maintainTimeStamp ); } // write out samples, and set next time stamp based on xdelta and noutput_items (*ostream)->write ( noutput_items, eos ); } else { // use incoming packet's time stamp to forward if ( gotPkt ) { #ifdef TEST_TIME_STAMP LOG_DEBUG( burst_tagger_cc_base, "OSTREAM SRI: items/xdelta:" << noutput_items << "/" << std::setprecision(12) << ostream->sri.xdelta ); LOG_DEBUG( burst_tagger_cc_base, "PKT - TS maint:" << _maintainTimeStamp ); LOG_DEBUG( burst_tagger_cc_base, " mode:" << pktTs.tcmode ); LOG_DEBUG( burst_tagger_cc_base, " status:" << pktTs.tcstatus ); LOG_DEBUG( burst_tagger_cc_base, " offset:" << pktTs.toff ); LOG_DEBUG( burst_tagger_cc_base, " whole:" << std::setprecision(10) << pktTs.twsec ); LOG_DEBUG( burst_tagger_cc_base, "PKT - TS frac:" << std::setprecision(12) << pktTs.tfsec ); #endif (*ostream)->write( noutput_items, eos, pktTs ); } else { #ifdef TEST_TIME_STAMP LOG_DEBUG( burst_tagger_cc_base, "OSTREAM SRI: items/xdelta:" << noutput_items << "/" << std::setprecision(12) << ostream->sri.xdelta ); LOG_DEBUG( burst_tagger_cc_base, "OSTREAM TOD maint:" << _maintainTimeStamp ); LOG_DEBUG( burst_tagger_cc_base, " mode:" << ostream->tstamp.tcmode ); LOG_DEBUG( burst_tagger_cc_base, " status:" << ostream->tstamp.tcstatus ); LOG_DEBUG( burst_tagger_cc_base, " offset:" << ostream->tstamp.toff ); LOG_DEBUG( burst_tagger_cc_base, " whole:" << std::setprecision(10) << ostream->tstamp.twsec ); LOG_DEBUG( burst_tagger_cc_base, "OSTREAM TOD frac:" << std::setprecision(12) << ostream->tstamp.tfsec ); #endif // use time of day as time stamp (*ostream)->write( noutput_items, eos, _maintainTimeStamp ); } } } // for ostreams } return nout; }
RedhawkSDR/integration-gnuhawk
components/burst_tagger_cc/cpp/burst_tagger_cc_base.cpp
C++
gpl-3.0
33,461
/****************************************************************************** * irrlamb - https://github.com/jazztickets/irrlamb * Copyright (C) 2019 Alan Witkowski * * 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 <campaign.h> #include <globals.h> #include <log.h> #include <framework.h> #include <level.h> #include <save.h> #include <tinyxml2/tinyxml2.h> _Campaign Campaign; using namespace tinyxml2; // Loads the campaign data int _Campaign::Init() { Campaigns.clear(); Log.Write("Loading campaign file main.xml"); // Open the XML file std::string LevelFile = std::string("levels/main.xml"); XMLDocument Document; if(Document.LoadFile(LevelFile.c_str()) != XML_SUCCESS) { Log.Write("Error loading level file with error id = %d", Document.ErrorID()); Log.Write("Error string: %s", Document.ErrorStr()); Close(); return 0; } // Check for level tag XMLElement *CampaignsElement = Document.FirstChildElement("campaigns"); if(!CampaignsElement) { Log.Write("Could not find campaigns tag"); return 0; } // Load campaigns XMLElement *CampaignElement = CampaignsElement->FirstChildElement("campaign"); for(; CampaignElement != 0; CampaignElement = CampaignElement->NextSiblingElement("campaign")) { _CampaignInfo Campaign; Campaign.Show = true; Campaign.Column = 1; Campaign.Row = 0; Campaign.Name = CampaignElement->Attribute("name"); CampaignElement->QueryBoolAttribute("show", &Campaign.Show); CampaignElement->QueryIntAttribute("column", &Campaign.Column); CampaignElement->QueryIntAttribute("row", &Campaign.Row); // Get levels XMLElement *LevelElement = CampaignElement->FirstChildElement("level"); for(; LevelElement != 0; LevelElement = LevelElement->NextSiblingElement("level")) { _LevelInfo Level; Level.File = LevelElement->GetText(); Level.DataPath = Framework.GetWorkingPath() + "levels/" + Level.File + "/"; Level.Unlocked = 0; LevelElement->QueryIntAttribute("unlocked", &Level.Unlocked); ::Level.Init(Level.File, true); Level.NiceName = ::Level.LevelNiceName; Campaign.Levels.push_back(Level); } Campaigns.push_back(Campaign); } return 1; } // Closes the campaign system int _Campaign::Close() { Campaigns.clear(); return 1; } // Get number of completed levels for a campaign int _Campaign::GetCompletedLevels(int CampaignIndex) { int Completed = 0; for(auto &Level : Campaigns[CampaignIndex].Levels) { if(Save.LevelStats[Level.File].WinCount) Completed++; } return Completed; } // Get next level or 1st level in next campaign, return false if no next level bool _Campaign::GetNextLevel(uint32_t &Campaign, uint32_t &Level, bool Update) { uint32_t NewCampaign = Campaign; uint32_t NewLevel = Level; if(NewCampaign >= Campaigns.size()) return false; if(NewLevel+1 >= Campaigns[NewCampaign].Levels.size()) { return false; } else { NewLevel++; } // Return values if(Update) { Campaign = NewCampaign; Level = NewLevel; } return true; }
jazztickets/irrlamb
src/campaign.cpp
C++
gpl-3.0
3,657
package be.nikiroo.utils.streams; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Arrays; /** * This {@link InputStream} can be separated into sub-streams (you can process * it as a normal {@link InputStream} but, when it is spent, you can call * {@link NextableInputStream#next()} on it to unlock new data). * <p> * The separation in sub-streams is done via {@link NextableInputStreamStep}. * * @author niki */ public class NextableInputStream extends BufferedInputStream { private NextableInputStreamStep step; private boolean started; private boolean stopped; /** * Create a new {@link NextableInputStream} that wraps the given * {@link InputStream}. * * @param in * the {@link InputStream} to wrap * @param step * how to separate it into sub-streams (can be NULL, but in that * case it will behave as a normal {@link InputStream}) */ public NextableInputStream(InputStream in, NextableInputStreamStep step) { super(in); this.step = step; } /** * Create a new {@link NextableInputStream} that wraps the given bytes array * as a data source. * * @param in * the array to wrap, cannot be NULL * @param step * how to separate it into sub-streams (can be NULL, but in that * case it will behave as a normal {@link InputStream}) */ public NextableInputStream(byte[] in, NextableInputStreamStep step) { this(in, step, 0, in.length); } /** * Create a new {@link NextableInputStream} that wraps the given bytes array * as a data source. * * @param in * the array to wrap, cannot be NULL * @param step * how to separate it into sub-streams (can be NULL, but in that * case it will behave as a normal {@link InputStream}) * @param offset * the offset to start the reading at * @param length * the number of bytes to take into account in the array, * starting from the offset * * @throws NullPointerException * if the array is NULL * @throws IndexOutOfBoundsException * if the offset and length do not correspond to the given array */ public NextableInputStream(byte[] in, NextableInputStreamStep step, int offset, int length) { super(in, offset, length); this.step = step; checkBuffer(true); } /** * Unblock the processing of the next sub-stream. * <p> * It can only be called when the "current" stream is spent (i.e., you must * first process the stream until it is spent). * <p> * {@link IOException}s can happen when we have no data available in the * buffer; in that case, we fetch more data to know if we can have a next * sub-stream or not. * <p> * This is can be a blocking call when data need to be fetched. * * @return TRUE if we unblocked the next sub-stream, FALSE if not (i.e., * FALSE when there are no more sub-streams to fetch) * * @throws IOException * in case of I/O error or if the stream is closed */ public boolean next() throws IOException { return next(false); } /** * Unblock the next sub-stream as would have done * {@link NextableInputStream#next()}, but disable the sub-stream systems. * <p> * That is, the next stream, if any, will be the last one and will not be * subject to the {@link NextableInputStreamStep}. * <p> * This is can be a blocking call when data need to be fetched. * * @return TRUE if we unblocked the next sub-stream, FALSE if not * * @throws IOException * in case of I/O error or if the stream is closed */ public boolean nextAll() throws IOException { return next(true); } /** * Check if this stream is totally spent (no more data to read or to * process). * <p> * Note: when the stream is divided into sub-streams, each sub-stream will * report its own eof when spent. * * @return TRUE if it is * * @throws IOException * in case of I/O error */ @Override public boolean eof() throws IOException { return super.eof(); } /** * Check if we still have some data in the buffer and, if not, fetch some. * * @return TRUE if we fetched some data, FALSE if there are still some in * the buffer * * @throws IOException * in case of I/O error */ @Override protected boolean preRead() throws IOException { if (!stopped) { boolean bufferChanged = super.preRead(); checkBuffer(bufferChanged); return bufferChanged; } if (start >= stop) { eof = true; } return false; } @Override protected boolean hasMoreData() { return started && super.hasMoreData(); } /** * Check that the buffer didn't overshot to the next item, and fix * {@link NextableInputStream#stop} if needed. * <p> * If {@link NextableInputStream#stop} is fixed, * {@link NextableInputStream#eof} and {@link NextableInputStream#stopped} * are set to TRUE. * * @param newBuffer * we changed the buffer, we need to clear some information in * the {@link NextableInputStreamStep} */ private void checkBuffer(boolean newBuffer) { if (step != null && stop >= 0) { if (newBuffer) { step.clearBuffer(); } int stopAt = step.stop(buffer, start, stop, eof); if (stopAt >= 0) { stop = stopAt; eof = true; stopped = true; } } } /** * The implementation of {@link NextableInputStream#next()} and * {@link NextableInputStream#nextAll()}. * <p> * This is can be a blocking call when data need to be fetched. * * @param all * TRUE for {@link NextableInputStream#nextAll()}, FALSE for * {@link NextableInputStream#next()} * * @return TRUE if we unblocked the next sub-stream, FALSE if not (i.e., * FALSE when there are no more sub-streams to fetch) * * @throws IOException * in case of I/O error or if the stream is closed */ private boolean next(boolean all) throws IOException { checkClose(); if (!started) { // First call before being allowed to read started = true; if (all) { step = null; } return true; } // If started, must be stopped and no more data to continue // i.e., sub-stream must be spent if (!stopped || hasMoreData()) { return false; } if (step != null) { stop = step.getResumeLen(); start += step.getResumeSkip(); eof = step.getResumeEof(); stopped = false; if (all) { step = null; } checkBuffer(false); return true; } return false; // // consider that if EOF, there is no next // if (start >= stop) { // // Make sure, block if necessary // preRead(); // // return hasMoreData(); // } // // return true; } /** * Display a DEBUG {@link String} representation of this object. * <p> * Do <b>not</b> use for release code. */ @Override public String toString() { String data = ""; if (stop > 0) { try { data = new String(Arrays.copyOfRange(buffer, 0, stop), "UTF-8"); } catch (UnsupportedEncodingException e) { } if (data.length() > 200) { data = data.substring(0, 197) + "..."; } } String rep = String.format( "Nextable %s: %d -> %d [eof: %s] [more data: %s]: %s", (stopped ? "stopped" : "running"), start, stop, "" + eof, "" + hasMoreData(), data); return rep; } }
nikiroo/fanfix
src/be/nikiroo/utils/streams/NextableInputStream.java
Java
gpl-3.0
7,444
function OpenReportOperations() { $("#report-operations-div").show(); $("#page-operations-div").hide(); $("#events-operations-div").hide(); $("#editandsave-operations-div").hide(); $("#report-operations-li").addClass('active'); $('#page-operations-li').removeClass('active'); $('#events-operations-li').removeClass('active'); $('#editandsave-operations-li').removeClass('active'); $("#report-operations-div .function-ul li.active").click() $("#selected-catogory-button").html("Report operations"); } function OpenPageOperations() { $("#page-operations-div").show(); $("#report-operations-div").hide(); $("#events-operations-div").hide(); $("#editandsave-operations-div").hide(); $("#page-operations-li").addClass('active'); $('#report-operations-li').removeClass('active'); $('#events-operations-li').removeClass('active'); $('#editandsave-operations-li').removeClass('active'); $("#page-operations-div .function-ul li.active").click(); $("#selected-catogory-button").html("Page operations"); } function OpenEventOperations() { $("#page-operations-div").hide(); $("#report-operations-div").hide(); $("#events-operations-div").show(); $("#editandsave-operations-div").hide(); $("#page-operations-li").removeClass('active'); $('#report-operations-li').removeClass('active'); $('#events-operations-li').addClass('active'); $('#editandsave-operations-li').removeClass('active'); $("#events-operations-div .function-ul li.active").click(); $("#selected-catogory-button").html("Events Listener"); } function OpenEditAndSaveOperations() { $("#page-operations-div").hide(); $("#report-operations-div").hide(); $("#events-operations-div").hide(); $("#editandsave-operations-div").show(); $("#page-operations-li").removeClass('active'); $('#report-operations-li').removeClass('active'); $('#events-operations-li').removeClass('active'); $('#editandsave-operations-li').addClass('active'); $("#editandsave-operations-div .function-ul li.active").click(); $("#selected-catogory-button").html("Edit and save operations"); } function SetToggleHandler(devId) { var selector = "#" + devId + " .function-ul li"; $(selector).each(function(index, li) { $(li).click(function() { $(selector).removeClass('active'); $(li).addClass('active'); }); }); }
CCAFS/MARLO
marlo-web/src/main/webapp/global/bower_components/powerbi-client/demo/code-demo/scripts/step_interact.js
JavaScript
gpl-3.0
2,466
package com.daniel_yc.moleculecraft.blocks.tileentity; import com.daniel_yc.moleculecraft.blocks.Compressor; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; public class TileEntityCompressor extends TileEntity implements ISidedInventory{ private static final int[] slotsTop = new int[] { 0 }; private static final int[] slotsBottom = new int[] { 2, 1 }; private static final int[] slotsSides = new int[] { 1 }; private ItemStack[] compressorItemStacks = new ItemStack[3]; public int compressorBurnTime; public int currentBurnTime; public int compressorCookTime; private String compressorName; public void compressorName(String string){ this.compressorName = string; } @Override public int getSizeInventory() { return this.compressorItemStacks.length; } @Override public ItemStack getStackInSlot(int slot) { return this.compressorItemStacks[slot]; } @Override public ItemStack decrStackSize(int par1, int par2) { if(this.compressorItemStacks[par1] != null){ ItemStack itemstack; if(this.compressorItemStacks[par1].stackSize <= par2){ itemstack = this.compressorItemStacks[par1]; this.compressorItemStacks[par1] = null; return itemstack; }else{ itemstack = this.compressorItemStacks[par1].splitStack(par2); if(this.compressorItemStacks[par1].stackSize == 0){ this.compressorItemStacks[par1] = null; } return itemstack; } }else{ return null; } } @Override public ItemStack getStackInSlotOnClosing(int slot) { if(this.compressorItemStacks[slot] != null){ ItemStack itemstack = this.compressorItemStacks[slot]; this.compressorItemStacks[slot] = null; return itemstack; }else{ return null; } } @Override public void setInventorySlotContents(int slot, ItemStack itemstack) { this.compressorItemStacks[slot] = itemstack; if(itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()){ itemstack.stackSize = this.getInventoryStackLimit(); } } @Override public String getInventoryName() { return this.hasCustomInventoryName() ? this.compressorName : "Compressor"; } @Override public boolean hasCustomInventoryName() { return this.compressorName != null && this.compressorName.length() > 0; } @Override public int getInventoryStackLimit() { return 64; } public void readFromNBT(NBTTagCompound tagCompound){ super.readFromNBT(tagCompound); NBTTagList tagList = tagCompound.getTagList("Items", 10); this.compressorItemStacks = new ItemStack[this.getSizeInventory()]; for (int i = 0; i < tagList.tagCount(); ++i){ NBTTagCompound tabCompound1 = tagList.getCompoundTagAt(i); byte byte0 = tabCompound1.getByte("slot"); if(byte0 >= 0 && byte0 < this.compressorItemStacks.length){ this.compressorItemStacks[byte0] = ItemStack.loadItemStackFromNBT(tabCompound1); } } this.compressorBurnTime = tagCompound.getShort("BurnTime"); this.compressorCookTime = tagCompound.getShort("CookTime"); this.currentBurnTime = getItemBurnTime(this.compressorItemStacks[1]); if(tagCompound.hasKey("CustumName", 8)){ this.compressorName = tagCompound.getString("CustomName"); } } public void writeToNBT(NBTTagCompound tagCompound){ super.writeToNBT(tagCompound); tagCompound.setShort("BurnTime", (short) this.compressorBurnTime); tagCompound.setShort("CookTime", (short) this.compressorBurnTime); NBTTagList tagList = new NBTTagList(); for(int i = 0; i < this.compressorItemStacks.length; ++i){ if(this.compressorItemStacks[1] != null){ NBTTagCompound tagCompound1 = new NBTTagCompound(); tagCompound1.setByte("slot", (byte) i); this.compressorItemStacks[1].writeToNBT(tagCompound1); tagList.appendTag(tagCompound1); } } tagCompound.setTag("Items", tagList); if(this.hasCustomInventoryName()){ tagCompound.setString("CustomName", this.compressorName); } } @SideOnly(Side.CLIENT) public int getCookProgressScaled(int par1){ return this.compressorCookTime * par1 / 200; } @SideOnly(Side.CLIENT) public int getBurnTimeRemainingScaled(int par1){ if(this.currentBurnTime == 0){ this.currentBurnTime = 200; } return this.compressorBurnTime * par1 / this.currentBurnTime; } public boolean isWorking(){ return this.compressorBurnTime > 0; } public void updateEntity(){ boolean flag = this.compressorBurnTime > 0; boolean flag1 = false; if(this.compressorBurnTime > 0){ --this.compressorBurnTime; } if(!this.worldObj.isRemote){ if(this.compressorBurnTime == 0 && this.canSmelt()){ this.currentBurnTime = this.compressorBurnTime = getItemBurnTime(this.compressorItemStacks[1]); if(this.compressorBurnTime > 0){ flag1 = true; if(this.compressorItemStacks[1] != null){ --this.compressorItemStacks[1].stackSize; if(this.compressorItemStacks[1].stackSize == 0){ this.compressorItemStacks[1] = compressorItemStacks[1].getItem().getContainerItem(this.compressorItemStacks[1]); } } } } if(this.isWorking() && this.canSmelt()){ ++this.compressorCookTime; if(this.compressorCookTime == 200){ this.compressorCookTime = 0; this.smeltItem(); flag1 = true; } }else{ this.compressorCookTime = 0; } } if(flag1 != this.compressorBurnTime > 0){ flag1 = true; Compressor.updateBlockState(this.compressorBurnTime > 0, this.worldObj, this.xCoord, this.yCoord, this.zCoord); } if (flag1){ this.markDirty(); } } private boolean canSmelt(){ if(this.compressorItemStacks[0] == null){ return false; }else{ ItemStack itemstack = FurnaceRecipes.smelting().getSmeltingResult(this.compressorItemStacks[0]); if(itemstack == null) return false; if(this.compressorItemStacks[2] == null) return true; if(!this.compressorItemStacks[2].isItemEqual(itemstack)) return false; int result = compressorItemStacks[2].stackSize + itemstack.stackSize; return result <= getInventoryStackLimit() && result <= this.compressorItemStacks[2].getMaxStackSize(); } } public void smeltItem(){ if(this.canSmelt()){ ItemStack itemstack = FurnaceRecipes.smelting().getSmeltingResult(this.compressorItemStacks[0]); if(this.compressorItemStacks[2] == null){ this.compressorItemStacks[2].copy(); }else if(this.compressorItemStacks[2].getItem() == itemstack.getItem()){ this.compressorItemStacks[2].stackSize += itemstack.stackSize; } } } public static int getItemBurnTime(ItemStack itemstack){ if(itemstack == null){ return 0; }else{ Item item = itemstack.getItem(); if(item instanceof ItemBlock && Block.getBlockFromItem(item) != Blocks.air){ Block block = Block.getBlockFromItem(item); if(block == Blocks.coal_block){ return 1600; } if(block.getMaterial() == Material.wood){ return 300; } } if(item == Items.coal) return 600; if(item instanceof ItemTool && ((ItemTool) item).getToolMaterialName().equals("WOOD")) return 300; return GameRegistry.getFuelValue(itemstack); } } public static boolean isItemFuel(ItemStack itemstack){ return getItemBurnTime(itemstack) > 0; } @Override public boolean isUseableByPlayer(EntityPlayer player) { return this.worldObj.getTileEntity(this.xCoord, this.yCoord, this.zCoord) != this ? false : player.getDistanceSq((double) this.xCoord + 0.5D, (double) this.yCoord + 0.5D, (double) this.zCoord + 0.5D) <= 64.0D; } @Override public void openInventory() { } @Override public void closeInventory() { } @Override public boolean isItemValidForSlot(int par1, ItemStack itemstack) { return par1 == 2 ? false : (par1 == 1 ? isItemFuel(itemstack) : true); } @Override public int[] getAccessibleSlotsFromSide(int par1) { return par1 == 0 ? slotsBottom : (par1 == 1 ? slotsTop : slotsSides); } @Override public boolean canInsertItem(int par1, ItemStack itemstack, int par3) { return this.isItemValidForSlot(par1, itemstack); } @Override public boolean canExtractItem(int par1, ItemStack itemstack, int par3) { return par3 != 0 || par1 != 1 || itemstack.getItem() == Items.bucket; } }
danielyc/MoleculeCraft-1.7.10
src/main/java/com/daniel_yc/moleculecraft/blocks/tileentity/TileEntityCompressor.java
Java
gpl-3.0
8,818
# -*- coding: utf-8 -*- # © 2013-2016 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models, fields, api, _ from odoo.exceptions import ValidationError, UserError class AccountInvoiceLine(models.Model): _inherit = 'account.invoice.line' start_date = fields.Date('Start Date') end_date = fields.Date('End Date') must_have_dates = fields.Boolean( related='product_id.must_have_dates', readonly=True) @api.multi @api.constrains('start_date', 'end_date') def _check_start_end_dates(self): for invline in self: if invline.start_date and not invline.end_date: raise ValidationError( _("Missing End Date for invoice line with " "Description '%s'.") % (invline.name)) if invline.end_date and not invline.start_date: raise ValidationError( _("Missing Start Date for invoice line with " "Description '%s'.") % (invline.name)) if invline.end_date and invline.start_date and \ invline.start_date > invline.end_date: raise ValidationError( _("Start Date should be before or be the same as " "End Date for invoice line with Description '%s'.") % (invline.name)) # Note : we can't check invline.product_id.must_have_dates # have start_date and end_date here, because it would # block automatic invoice generation/import. So we do the check # upon validation of the invoice (see below the function # action_move_create) class AccountInvoice(models.Model): _inherit = 'account.invoice' def inv_line_characteristic_hashcode(self, invoice_line): """Add start and end dates to hashcode used when the option "Group Invoice Lines" is active on the Account Journal""" code = super(AccountInvoice, self).inv_line_characteristic_hashcode( invoice_line) hashcode = '%s-%s-%s' % ( code, invoice_line.get('start_date', 'False'), invoice_line.get('end_date', 'False'), ) return hashcode @api.model def line_get_convert(self, line, part): """Copy from invoice to move lines""" res = super(AccountInvoice, self).line_get_convert(line, part) res['start_date'] = line.get('start_date', False) res['end_date'] = line.get('end_date', False) return res @api.model def invoice_line_move_line_get(self): """Copy from invoice line to move lines""" res = super(AccountInvoice, self).invoice_line_move_line_get() ailo = self.env['account.invoice.line'] for move_line_dict in res: iline = ailo.browse(move_line_dict['invl_id']) move_line_dict['start_date'] = iline.start_date move_line_dict['end_date'] = iline.end_date return res @api.multi def action_move_create(self): """Check that products with must_have_dates=True have Start and End Dates""" for invoice in self: for iline in invoice.invoice_line_ids: if iline.product_id and iline.product_id.must_have_dates: if not iline.start_date or not iline.end_date: raise UserError(_( "Missing Start Date and End Date for invoice " "line with Product '%s' which has the " "property 'Must Have Start and End Dates'.") % (iline.product_id.name)) return super(AccountInvoice, self).action_move_create()
stellaf/sales_rental
account_invoice_start_end_dates/models/account_invoice.py
Python
gpl-3.0
3,875
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('agentex', '0014_remove_decision_datacollect'), ] operations = [ migrations.AddField( model_name='datapoint', name='sorttimestamp', field=models.DateTimeField(null=True, blank=True), ), ]
tomasjames/citsciportal
app/agentex/migrations/0015_datapoint_sorttimestamp.py
Python
gpl-3.0
431
import numpy as np import struct import wave from winsound import PlaySound, SND_FILENAME, SND_ASYNC import matplotlib.pyplot as plt CHUNK = 1 << 8 def play(filename): PlaySound(filename, SND_FILENAME | SND_ASYNC) fn = r"D:\b.wav" f = wave.open(fn) print(f.getparams()) ch = f.getnchannels() sw = f.getsampwidth() n = f.getnframes() data = bytearray() while len(data) < n * ch * sw: data.extend(f.readframes(CHUNK)) data = np.array(struct.unpack('{n}h'.format(n=n * ch), data)) w = np.fft.fft(data) freqs = np.fft.fftfreq(len(w)) module = np.abs(w) idmax = module.argmax() print(abs(freqs[idmax]) * f.getframerate()) plt.specgram(data) plt.show()
DavideCanton/Python3
audio/freq.py
Python
gpl-3.0
663
import tensorflow as tf from tensorflow.python.ops import rnn_cell from tensorflow.python.ops import seq2seq import numpy as np class Model(): def __init__(self, args, infer=False): self.args = args if infer: args.batch_size = 1 args.seq_length = 1 if args.model == 'rnn': cell_fn = rnn_cell.BasicRNNCell elif args.model == 'gru': cell_fn = rnn_cell.GRUCell elif args.model == 'lstm': cell_fn = rnn_cell.BasicLSTMCell else: raise Exception("model type not supported: {}".format(args.model)) cell = cell_fn(args.rnn_size) self.cell = cell = rnn_cell.MultiRNNCell([cell] * args.num_layers) self.input_data = tf.placeholder(tf.float32, [args.batch_size, args.seq_length], name="input") self.targets = tf.placeholder(tf.int32, [args.batch_size, args.seq_length], name="targets") self.initial_state = cell.zero_state(args.batch_size, tf.float32) inputs_data = tf.split(1, args.seq_length, self.input_data) args.vocab_size = 1 with tf.variable_scope('rnnlm'): softmax_w = tf.get_variable("softmax_w", [args.rnn_size, args.vocab_size]) softmax_b = tf.get_variable("softmax_b", [args.vocab_size]) # with tf.device("/cpu:0"): # embedding = tf.get_variable("embedding", [args.vocab_size, args.rnn_size]) # inputs = tf.split(1, args.seq_length, tf.nn.embedding_lookup(embedding, self.input_data)) #inputs = tf.split(1, args.seq_length, self.input_data) # inputs = [tf.squeeze(input_, [1]) for input_ in inputs] #def loop(prev, _): # prev = tf.matmul(prev, softmax_w) + softmax_b # prev_symbol = tf.stop_gradient(tf.argmax(prev, 1)) # return tf.nn.embedding_lookup(embedding, prev_symbol) #outputs, last_state = seq2seq.rnn_decoder(inputs, self.initial_state, cell, loop_function=loop if infer else None, scope='rnnlm') outputs, last_state = seq2seq.rnn_decoder(inputs_data, self.initial_state, cell) output = tf.reshape(tf.concat(1, outputs), [-1, args.rnn_size]) self.logits = tf.matmul(output, softmax_w) + softmax_b self.probs = tf.nn.softmax(self.logits) #loss = seq2seq.sequence_loss_by_example([self.logits], # [tf.reshape(self.targets, [-1])], # [tf.ones([args.batch_size * args.seq_length])], # args.vocab_size) self.reg_cost = tf.reduce_sum(1e-1 * (tf.nn.l2_loss(softmax_w))) target = tf.cast(self.targets, tf.float32) self.target_vector = tf.reshape(target, [-1]) loss = tf.pow(self.logits / self.target_vector, 2) self.cost = tf.reduce_sum(loss) / args.batch_size / args.seq_length + self.reg_cost self.final_state = last_state self.lr = tf.Variable(0.0, trainable=False) tvars = tf.trainable_variables() grads, _ = tf.clip_by_global_norm(tf.gradients(self.cost, tvars), args.grad_clip) optimizer = tf.train.AdamOptimizer(self.lr) self.train_op = optimizer.apply_gradients(zip(grads, tvars)) def sample(self, sess, chars, vocab, num=200, prime='The ', sampling_type=1): state = self.cell.zero_state(1, tf.float32).eval() for char in prime[:-1]: x = np.zeros((1, 1)) x[0, 0] = vocab[char] feed = {self.input_data: x, self.initial_state:state} [state] = sess.run([self.final_state], feed) def weighted_pick(weights): t = np.cumsum(weights) s = np.sum(weights) return(int(np.searchsorted(t, np.random.rand(1)*s))) ret = prime char = prime[-1] for n in range(num): x = np.zeros((1, 1)) x[0, 0] = vocab[char] feed = {self.input_data: x, self.initial_state:state} [probs, state] = sess.run([self.probs, self.final_state], feed) p = probs[0] if sampling_type == 0: sample = np.argmax(p) elif sampling_type == 2: if char == ' ': sample = weighted_pick(p) else: sample = np.argmax(p) else: # sampling_type == 1 default: sample = weighted_pick(p) pred = chars[sample] ret += pred char = pred return ret
bottiger/Integer-Sequence-Learning
char/model.py
Python
gpl-3.0
4,473
# -*- coding: utf-8 -*- import terrariumLogging logger = terrariumLogging.logging.getLogger(__name__) from pathlib import Path import inspect from importlib import import_module import sys import statistics from hashlib import md5 from time import time, sleep from operator import itemgetter from func_timeout import func_timeout, FunctionTimedOut import RPi.GPIO as GPIO # pip install retry from retry import retry # For analog sensors from gpiozero import MCP3008 # For I2C sensors import smbus2 # Bluetooth sensors from bluepy.btle import Scanner from terrariumUtils import terrariumUtils, terrariumCache, classproperty class terrariumSensorException(TypeError): '''There is a problem with loading a hardware sensor.''' pass class terrariumSensorUnknownHardwareException(terrariumSensorException): pass class terrariumSensorInvalidSensorTypeException(terrariumSensorException): pass class terrariumSensorLoadingException(terrariumSensorException): pass class terrariumSensorUpdateException(terrariumSensorException): pass class terrariumSensor(object): HARDWARE = None TYPES = [] NAME = None _CACHE_TIMEOUT = 30 _UPDATE_TIME_OUT = 10 @classproperty def available_hardware(__cls__): __CACHE_KEY = 'known_sensors' cache = terrariumCache() known_sensors = cache.get_data(__CACHE_KEY) if known_sensors is None: known_sensors = {} all_types = [] # Start dynamically loading sensors (based on: https://www.bnmetrics.com/blog/dynamic-import-in-python3) for file in sorted(Path(__file__).parent.glob('*_sensor.py')): imported_module = import_module( '.' + file.stem, package='{}'.format(__name__)) for i in dir(imported_module): attribute = getattr(imported_module, i) if inspect.isclass(attribute) and attribute != __cls__ and issubclass(attribute, __cls__): setattr(sys.modules[__name__], file.stem, attribute) if attribute.HARDWARE is not None: known_sensors[attribute.HARDWARE] = attribute all_types += attribute.TYPES # Update sensors that do not have a known type. Those are remote and scripts sensors all_types = list(set(all_types)) for hardware in known_sensors: if len(known_sensors[hardware].TYPES) == 0: known_sensors[hardware].TYPES = all_types cache.set_data(__CACHE_KEY,known_sensors,-1) return known_sensors # Return a list with type and names of supported switches @classproperty def available_sensors(__cls__): data = [] all_types = ['conductivity'] # For now 'conductivity' is only available through script or remote for (hardware_type, sensor) in __cls__.available_hardware.items(): if sensor.NAME is not None: data.append({'hardware' : hardware_type, 'name' : sensor.NAME, 'types' : sensor.TYPES}) all_types += sensor.TYPES # Remote and script sensors can handle all the known types all_types = list(set(all_types)) for sensor in data: if len(sensor['types']) == 0: sensor['types'] = all_types return sorted(data, key=itemgetter('name')) @classproperty def sensor_types(__cls__): sensor_types = [] for sensor in __cls__.available_sensors: sensor_types += sensor['types'] return sorted(list(set(sensor_types))) # Return polymorph sensor.... def __new__(cls, sensor_id, hardware_type, sensor_type, address, name = '', unit_value_callback = None, trigger_callback = None): known_sensors = terrariumSensor.available_hardware if hardware_type not in known_sensors: raise terrariumSensorUnknownHardwareException(f'Trying to load an unknown hardware device {hardware_type} at address {address} with name {name}') if sensor_type not in known_sensors[hardware_type].TYPES: raise terrariumSensorInvalidSensorTypeException(f'Hardware does not have a {sensor_type} sensor at address {address} with name {name}') return super(terrariumSensor, cls).__new__(known_sensors[hardware_type]) def __init__(self, id, _, sensor_type, address, name = '', unit_value_callback = None, trigger_callback = None): self._device = {'id' : None, 'name' : None, 'address' : None, 'type' : sensor_type, # Readonly property 'device' : None, 'cache_key' : None, 'power_mngt' : None, 'erratic_errors' : 0, 'last_update' : 0, 'value' : None} self._sensor_cache = terrariumCache() self.__unit_value_callback = unit_value_callback self.__trigger_callback = trigger_callback # Set the properties self.id = id self.name = name self.address = address # Load hardware can update the address value that is used for making a unique ID when not set self.load_hardware() # REMINDER: We do not take a measurement at this point. That is up to the developer to explicit request an update. def __power_management(self, on): # Some kind of 'power management' with the last gpio pin number :) https://raspberrypi.stackexchange.com/questions/68123/preventing-corrosion-on-yl-69 if self._device['power_mngt'] is not None: logger.debug(f'Sensor {self} has power management enabled') if on: logger.debug('Enable power to the sensor {self} now.') GPIO.output(self._device['power_mngt'], GPIO.HIGH) sleep(1) else: logger.debug('Close power to the sensor {self} now.') GPIO.output(self._device['power_mngt'], GPIO.LOW) @property def __sensor_cache_key(self): if self._device['cache_key'] is None: self._device['cache_key'] = md5(f'{self.HARDWARE}{self.address}'.encode()).hexdigest() return self._device['cache_key'] @property def id(self): if self._device['id'] is None: self._device['id'] = md5(f'{self.HARDWARE}{self.address}{self.type}'.encode()).hexdigest() return self._device['id'] @id.setter def id(self, value): if value is not None: self._device['id'] = value.strip() @property def hardware(self): return self.HARDWARE @property def name(self): return self._device['name'] @name.setter def name(self, value): if '' != value.strip(): self._device['name'] = value.strip() @property def address(self): return self._device['address'] @property def _address(self): address = [ part.strip() for part in self.address.split(',') if '' != part.strip()] return address @address.setter def address(self, value): value = terrariumUtils.clean_address(value) if value is not None and '' != value: self._device['address'] = value # Readonly property @property def device(self): return self._device['device'] # Readonly property @property def sensor_type(self): return self._device['type'] # Readonly property @property def type(self): return self._device['type'] @property def value(self): return self._device['value'] @property def last_update(self): return self._device['last_update'] @property def erratic(self): return self._device['erratic_errors'] @erratic.setter def erratic(self, value): self._device['erratic_errors'] = value def get_hardware_state(self): pass @retry(terrariumSensorLoadingException, tries=3, delay=0.5, max_delay=2, logger=logger) def load_hardware(self, reload = False): # Get hardware cache key based on the combination of hardware and address hardware_cache_key = md5(f'HW-{self.HARDWARE}-{self.address}'.encode()).hexdigest() # Load hardware device from cache hardware = self._sensor_cache.get_data(hardware_cache_key) if reload or hardware is None: # Could not find valid hardware cache. So create a new hardware device try: hardware = func_timeout(self._UPDATE_TIME_OUT, self._load_hardware) if hardware is not None: # Store the hardware in the cache for unlimited of time self._sensor_cache.set_data(hardware_cache_key,hardware,-1) else: # Raise error that hard is not loaded with an unknown message :( raise terrariumSensorLoadingException(f'Unable to load sensor {self}: Did not return a device.') except FunctionTimedOut: # What ever fails... does not matter, as the data is still None and will raise a terrariumSensorUpdateException and trigger the retry raise terrariumSensorLoadingException(f'Unable to load sensor {self}: timed out ({self._UPDATE_TIME_OUT} seconds) during loading.') except Exception as ex: raise terrariumSensorLoadingException(f'Unable to load sensor {self}: {ex}') self._device['device'] = hardware # Check for power management features and enable it if set if self._device['power_mngt'] is not None: GPIO.setup(self._device['power_mngt'], GPIO.OUT) # When we get Runtime errors retry up to 3 times @retry(terrariumSensorUpdateException, tries=3, delay=0.5, max_delay=2, logger=logger) def get_data(self): data = None self.__power_management(True) try: data = func_timeout(self._UPDATE_TIME_OUT, self._get_data) except FunctionTimedOut: # What ever fails... does not matter, as the data is still None and will raise a terrariumSensorUpdateException and trigger the retry logger.error(f'Sensor {self} timed out after {self._UPDATE_TIME_OUT} seconds during updating...') except Exception as ex: logger.error(f'Sensor {self} has exception: {ex}') self.__power_management(False) if data is None: raise terrariumSensorUpdateException(f'Invalid reading from sensor {self}') return data def update(self, force = False): if self._device['device'] is None: raise terrariumSensorLoadingException(f'Sensor {self} is not loaded! Can not update!') starttime = time() data = self._sensor_cache.get_data(self.__sensor_cache_key) if (data is None or force) and self._sensor_cache.set_running(self.__sensor_cache_key): logger.debug(f'Start getting new data from sensor {self}') try: data = self.get_data() self._sensor_cache.set_data(self.__sensor_cache_key,data, self._CACHE_TIMEOUT) except Exception as ex: logger.error(f'Error updating sensor {self}. Check your hardware! {ex}') self._sensor_cache.clear_running(self.__sensor_cache_key) current = None if data is None or self.sensor_type not in data else data[self.sensor_type] if current is None: self._sensor_cache.clear_data(self.__sensor_cache_key) else: self._device['last_update'] = int(starttime) self._device['value'] = current return current def stop(self): if self._device['power_mngt'] is not None: GPIO.cleanup(self._device['power_mngt']) def __repr__(self): return f'{self.NAME} {self.type} named \'{self.name}\' at address \'{self.address}\'' # Auto discovery of known and connected sensors @staticmethod def scan_sensors(unit_value_callback = None, trigger_callback = None, **kwargs): for (hardware_type,sensor_device) in terrariumSensor.available_hardware.items(): try: for sensor in sensor_device._scan_sensors(unit_value_callback, trigger_callback, **kwargs): yield sensor except AttributeError as ex: # Scanning not supported, just ignore pass class terrariumAnalogSensor(terrariumSensor): HARDWARE = None TYPES = [] NAME = None __AMOUNT_OF_MEASUREMENTS = 5 def _load_hardware(self): address = self._address # Load the analog converter here device = MCP3008(channel=int(address[0]), device=0 if len(address) == 1 or int(address[1]) < 0 else int(address[1])) return device def _get_data(self): # This will return the measured voltage of the analog device. values = [] for counter in range(self.__AMOUNT_OF_MEASUREMENTS): value = self.device.value if terrariumUtils.is_float(value): values.append(float(value)) sleep(0.2) # sort values from low to high values.sort() # Calculate average. Exclude the min and max value. return statistics.mean(values[1:-1]) class terrariumI2CSensor(terrariumSensor): @property def _address(self): address = super()._address if type(address[0]) is str: if not address[0].startswith('0x'): address[0] = '0x' + address[0] address[0] = int(address[0],16) return address def _open_hardware(self): address = self._address return smbus2.SMBus(1 if len(address) == 1 or int(address[1]) < 1 else int(address[1])) def _load_hardware(self): address = self._address device = (address[0], smbus2.SMBus(1 if len(address) == 1 or int(address[1]) < 1 else int(address[1]))) return device # def __exit__(self): # print('I2C close with block') class terrariumI2CSensorMixin(): # control constants SOFTRESET = 0xFE SOFTRESET_TIMEOUT = 0.1 TEMPERATURE_TRIGGER_NO_HOLD = 0xF3 TEMPERATURE_WAIT_TIME = 0.1 HUMIDITY_TRIGGER_NO_HOLD = 0xF5 HUMIDITY_WAIT_TIME = 0.1 def __soft_reset(self, i2c_bus): i2c_bus.write_byte(self.device[0], self.SOFTRESET) sleep(self.SOFTRESET_TIMEOUT) def __get_data(self,i2c_bus, trigger, timeout): data1 = data2 = None # Send request for data i2c_bus.write_byte(self.device[0], trigger) sleep(timeout) data1 = i2c_bus.read_byte(self.device[0]) try: data2 = i2c_bus.read_byte(self.device[0]) except Exception as ex: data2 = data1 return (data1,data2) def _get_data(self): data = {} with self._open_hardware() as i2c_bus: # Datasheet recommend do Soft Reset before measurement: self.__soft_reset(i2c_bus) if 'temperature' in self.TYPES: bytedata = self.__get_data(i2c_bus, self.TEMPERATURE_TRIGGER_NO_HOLD,self.TEMPERATURE_WAIT_TIME) data['temperature'] = ((bytedata[0]*256.0+bytedata[1])*175.72/65536.0)-46.85 if 'humidity' in self.TYPES: bytedata = self.__get_data(i2c_bus, self.HUMIDITY_TRIGGER_NO_HOLD,self.HUMIDITY_WAIT_TIME) data['humidity'] = ((bytedata[0]*256.0+bytedata[1])*125.0/65536.0)-6.0 return data """ TCA9548A I2C switch driver, Texas instruments 8 bidirectional translating switches I2C SMBus protocol Manual: tca9548.pdf Source: https://github.com/IRNAS/tca9548a-python/blob/master/tca9548a.py Added option for different I2C bus """ # import smbus # import logging class TCA9548A(object): def __init__(self, address, bus = 1): """Init smbus channel and tca driver on specified address.""" try: self.PORTS_COUNT = 8 # number of switches self.i2c_bus = smbus2.SMBus(bus) self.i2c_address = address if self.get_control_register() is None: raise ValueError except ValueError: logger.error("No device found on specified address!") self.i2c_bus = None except: logger.error("Bus on channel {} is not available.".format(bus)) logger.info("Available busses are listed as /dev/i2c*") self.i2c_bus = None def get_control_register(self): """Read value (length: 1 byte) from control register.""" try: value = self.i2c_bus.read_byte(self.i2c_address) return value except: return None def get_channel(self, ch_num): """Get channel state (specified with ch_num), return 0=disabled or 1=enabled.""" if ch_num < 0 or ch_num > self.PORTS_COUNT - 1: return None register = self.get_control_register() if register is None: return None value = ((register >> ch_num) & 1) return value def set_control_register(self, value): """Write value (length: 1 byte) to control register.""" try: if value < 0 or value > 255: return False self.i2c_bus.write_byte(self.i2c_address, value) return True except: return False def set_channel(self, ch_num, state): """Change state (0=disable, 1=enable) of a channel specified in ch_num.""" if ch_num < 0 or ch_num > self.PORTS_COUNT - 1: return False if state != 0 and state != 1: return False current_value = self.get_control_register() if current_value is None: return False if state: new_value = current_value | 1 << ch_num else: new_value = current_value & (255 - (1 << ch_num)) return_value = self.set_control_register(new_value) return return_value def __del__(self): """Driver destructor.""" self.i2c_bus = None class terrariumBluetoothSensor(terrariumSensor): __MIN_DB = -90 __SCAN_TIME = 3 @property def _address(self): address = super()._address if len(address) == 1: address.append(0) elif len(address) == 2: address[1] = int(address[1]) if terrariumUtils.is_float(address[1]) and terrariumUtils.is_float(address[1]) > 0 else 0 return address @staticmethod def _scan_sensors(sensorclass, ids = [], unit_value_callback = None, trigger_callback = None): # Due to multiple bluetooth dongles, we are looping 10 times to see which devices can scan. Exit after first success ok = True for counter in range(10): try: devices = Scanner(counter).scan(terrariumBluetoothSensor.__SCAN_TIME) for device in devices: if device.rssi > terrariumBluetoothSensor.__MIN_DB and device.getValueText(9) is not None and device.getValueText(9).lower() in ids: for sensor_type in sensorclass.TYPES: logger.debug(sensor_type, sensorclass, device.addr) yield terrariumSensor(None, sensorclass.HARDWARE, sensor_type, device.addr + ('' if counter == 0 else f',{counter}'), f'{sensorclass.NAME} measuring {sensor_type}', unit_value_callback = unit_value_callback, trigger_callback = trigger_callback) # we found devices, so this device is ok! Stop trying more bluetooth devices break except Exception as ex: ok = False if not ok: logger.warning('Bluetooth scanning is not enabled for normal users or there are zero Bluetooth LE devices available.... bluetooth is disabled!') return []
theyosh/TerrariumPI
hardware/sensor/__init__.py
Python
gpl-3.0
18,830
# coding = utf-8 # import modules import os import matplotlib.pyplot as plt import numpy as np import scipy as sp import my_config path = my_config.ROOT_DIR # Please create your config file file = my_config.FILE # Please create your config file # get time series for ch0 and plot import wave def time_series(file, i_ch = 0): with wave.open(file,'r') as wav_file: # Extract Raw Audio from Wav File signal = wav_file.readframes(-1) signal = np.fromstring(signal, 'Int16') # Split the data into channels channels = [[] for channel in range(wav_file.getnchannels())] for index, datum in enumerate(signal): channels[index%len(channels)].append(datum) #Get time from indices fs = wav_file.getframerate() Time = np.linspace(0, len(signal)/len(channels)/fs, num=len(signal)/len(channels)) # return return fs, Time, channels[i_ch] fs, t, y = time_series(os.path.join(path, file), i_ch = 0) plt.figure(1) plt.plot(t, y) plt.title('Time series (Fs = {})'.format(fs)) plt.xlabel('Time [s]') plt.ylabel('Signal') plt.grid() # detrend and plot from scipy.signal import detrend y_detrend = detrend(y) plt.figure(2) plt.plot(t, y_detrend) plt.title('Time series (Fs = {})'.format(fs)) plt.xlabel('Time [s]') plt.ylabel('Signal-detrend') plt.grid() # get auto-correlation and plot from scipy.signal import correlate, convolve corr = correlate(y_detrend, y_detrend, mode = 'full') n_data = np.minimum(len(t), len(corr)) plt.figure(3) plt.plot(t[0:n_data], corr[0:n_data]) plt.title('Auto-Correlation (Fs = {})'.format(fs)) plt.xlabel('Time Lag [s]') plt.ylabel('Auto-Correlation') plt.grid() # get-filterred signal and plot from scipy.signal import butter, lfilter cutoff = 500 N = 4 # filter oder Wn = cutoff / (fs * 0.5) b, a = butter(N, Wn , btype = 'low', analog = False) y_filtered = lfilter(b, a, y_detrend) # low pass filter plt.figure(4) plt.plot(t, y_filtered) plt.title('Time series (Fs = {}) (Cutoff Freq. = {})'.format(fs, cutoff)) plt.xlabel('Time [s]') plt.ylabel('Signal - filtered') plt.grid() # get fft and plot T = 1.0 / fs # time interval n_sample = len(y_filtered) freq = np.linspace(0.0, 1.0/(2.0*T), n_sample//2) yf = sp.fft(y_filtered) plt.figure(5) plt.plot(freq, 2.0/n_sample * np.abs(yf[0:n_sample//2])) plt.title('FFT') plt.xlabel('Freq. [Hz]') plt.ylabel('Fourier Coef.') plt.grid() # get psd and plot from scipy.signal import welch nperseg = fs // 4 # size of sagment to fft noverlap = nperseg // 100 * 90 # segments overlaped rate 90% f, Pxx = welch(y_filtered, fs = fs, nperseg= nperseg, noverlap = noverlap, window = sp.signal.hamming(nperseg)) plt.figure(6) plt.plot(f, Pxx) plt.title('PSD') plt.xlabel('Freq. [Hz]') plt.ylabel('Power') plt.grid() # get spectrogram from scipy.signal import spectrogram nperseg = fs // 4 # size of sagment to fft noverlap = nperseg // 100 * 90 # segments overlaped at 90% f, t, Sxx = spectrogram(y_filtered, fs = fs, nperseg= nperseg, noverlap = noverlap, window = sp.signal.hamming(nperseg)) plt.figure(7) plt.pcolormesh(t, f, Sxx) plt.title('Spectrogram') plt.xlabel('Time [s]') plt.ylabel('Freq. [Hz]') plt.grid() plt.show()
ejoonie/heart_sound
main_waveform_20170517.py
Python
gpl-3.0
3,229
/*! \file \brief Test of class tetengo2::iterator::observable_forward_iteratorpolymorphic_forward_iterator. Copyright (C) 2007-2019 kaoru $Id$ */ #include <sstream> #include <string> #include <boost/operators.hpp> #include <boost/preprocessor.hpp> #include <boost/test/unit_test.hpp> #include <tetengo2/iterator/polymorphic_forward_iterator.h> namespace { // types using base_type = tetengo2::iterator::polymorphic_forward_iterator<std::string>; class concrete_iterator : public base_type { public: explicit concrete_iterator(const int first) : m_value(first, 'a') {} private: std::string m_value; virtual reference dereference() override { return m_value; } virtual bool equal(const base_type& another) const override { const concrete_iterator* const p_another = dynamic_cast<const concrete_iterator*>(&another); if (!p_another) return false; return m_value == p_another->m_value; } virtual void increment() override { m_value += "a"; } }; class other_concrete_iterator : public base_type { public: explicit other_concrete_iterator(const int first) : m_value(first, 'a') {} private: std::string m_value; virtual reference dereference() override { return m_value; } virtual bool equal(const base_type& another) const override { const other_concrete_iterator* const p_another = dynamic_cast<const other_concrete_iterator*>(&another); if (!p_another) return false; return m_value == p_another->m_value; } virtual void increment() override { m_value += "a"; } }; } BOOST_AUTO_TEST_SUITE(test_tetengo2) BOOST_AUTO_TEST_SUITE(iterator) BOOST_AUTO_TEST_SUITE(polymorphic_forward_iterator) // test cases BOOST_AUTO_TEST_CASE(construction) { BOOST_TEST_PASSPOINT(); const concrete_iterator iter{ 42 }; } BOOST_AUTO_TEST_CASE(operator_dereference) { BOOST_TEST_PASSPOINT(); { const concrete_iterator iter{ 42 }; BOOST_CHECK(*iter == std::string(42, 'a')); } { concrete_iterator iter{ 42 }; *iter = std::string(24, 'a'); BOOST_CHECK(*iter == std::string(24, 'a')); } } BOOST_AUTO_TEST_CASE(operator_arrow) { BOOST_TEST_PASSPOINT(); { const concrete_iterator iter{ 42 }; BOOST_TEST(iter->length() == 42U); } { const concrete_iterator iter{ 42 }; iter->append("a"); BOOST_TEST(iter->length() == 43U); } } BOOST_AUTO_TEST_CASE(operator_increment) { BOOST_TEST_PASSPOINT(); concrete_iterator iter{ 42 }; const base_type& incremented = ++iter; BOOST_CHECK(*iter == std::string(43, 'a')); BOOST_CHECK(*incremented == std::string(43, 'a')); } BOOST_AUTO_TEST_CASE(operator_postincrement) { BOOST_TEST_PASSPOINT(); concrete_iterator iter{ 42 }; iter++; BOOST_CHECK(*iter == std::string(43, 'a')); } BOOST_AUTO_TEST_CASE(operator_equal) { BOOST_TEST_PASSPOINT(); { const concrete_iterator iter1{ 42 }; const concrete_iterator iter2{ 42 }; BOOST_CHECK(iter1 == iter2); } { const concrete_iterator iter1{ 42 }; const concrete_iterator iter2{ 24 }; BOOST_CHECK(!(iter1 == iter2)); } { const concrete_iterator iter1{ 42 }; const other_concrete_iterator iter2{ 42 }; BOOST_CHECK(!(iter1 == iter2)); } } BOOST_AUTO_TEST_CASE(operator_not_equal) { BOOST_TEST_PASSPOINT(); { const concrete_iterator iter1{ 42 }; const concrete_iterator iter2{ 42 }; BOOST_CHECK(!(iter1 != iter2)); } { const concrete_iterator iter1{ 42 }; const concrete_iterator iter2{ 24 }; BOOST_CHECK(iter1 != iter2); } { const concrete_iterator iter1{ 42 }; const other_concrete_iterator iter2{ 42 }; BOOST_CHECK(iter1 != iter2); } } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
kaorut/tetengo2
tetengo2/test/test_tetengo2.iterator.polymorphic_forward_iterator.cpp
C++
gpl-3.0
5,532
#include "ribi_create_tally.h" #include <iostream> #include <fstream> // Boost.Test does not play well with -Weffc++ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" #include <boost/test/unit_test.hpp> using namespace ribi; BOOST_AUTO_TEST_CASE(test_ribi_create_tally) { { const std::vector<std::string> v = {}; const std::map<std::string, int> expected = {}; const auto result = ::create_tally(v); BOOST_CHECK(result == expected); } { const std::vector<std::string> v = { "A" }; const std::map<std::string, int> expected = { {"A", 1} }; const auto result = ::create_tally(v); BOOST_CHECK(result == expected); } { const std::vector<std::string> v = { "A", "A" }; const std::map<std::string, int> expected = { {"A", 2} }; const auto result = ::create_tally(v); BOOST_CHECK(result == expected); } { const std::vector<std::string> v = { "A", "B" }; const std::map<std::string, int> expected = { {"A", 1}, { "B", 1} }; const auto result = ::create_tally(v); BOOST_CHECK(result == expected); } { const std::vector<std::string> v = { "A", "A", "B" }; const std::map<std::string, int> expected = { {"A", 2}, {"B", 1} }; const auto result = ::create_tally(v); BOOST_CHECK(result == expected); } { const std::vector<std::string> v = { "B", "A", "A" }; const std::map<std::string, int> expected = { {"A", 2}, {"B", 1} }; const auto result = ::create_tally(v); BOOST_CHECK(result == expected); } } #pragma GCC diagnostic pop
richelbilderbeek/pbdmms
ribi_create_tally_test.cpp
C++
gpl-3.0
1,560
// Copyright (C) 2015 Fabio Petroni // Contact: http://www.fabiopetroni.com // // This file is part of CrawlFacebookPostTrees application. // // CrawlFacebookPostTrees 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. // // CrawlFacebookPostTrees 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 CrawlFacebookPostTrees. If not, see <http://www.gnu.org/licenses/>. // // If you use CrawlFacebookPostTrees please cite the following paper: // - Alessandro Bessi, Fabio Petroni, Michela Del Vicario, Fabiana Zollo, // Aris Anagnostopoulos, Antonio Scala, Guido Caldarelli, Walter Quattrociocchi: // Viral Misinformation: The Role of Homophily and Polarization. In Proceedings // of the 24th International Conference on World Wide Web Companion (WWW), 2015. package facebook; import application.Globals; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class Autenticate { public static void perform(WebDriver driver, String email, String password){ driver.get(Globals.START_PAGE); WebElement email_element = driver.findElement(By.xpath("//*[@id='email']")); email_element.sendKeys(email); WebElement password_element = driver.findElement(By.xpath("//*[@id='pass']")); password_element.sendKeys(password); WebElement click_element = driver.findElement(By.xpath("//*[@type='submit']")); click_element.click(); return; } }
fabiopetroni/CrawlFacebookPostTrees
src/facebook/Autenticate.java
Java
gpl-3.0
1,986
# # Python module to parse OMNeT++ vector files # # Currently only suitable for small vector files since # everything is loaded into RAM # # Authors: Florian Kauer <florian.kauer@tuhh.de> # # Copyright (c) 2015, Institute of Telematics, Hamburg University of Technology # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the Institute nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE INSTITUTE 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 INSTITUTE 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. import re import scipy.interpolate import numpy as np vectors = [] class OmnetVector: def __init__(self,file_input): self.vectors = {} self.dataTime = {} self.dataValues = {} self.maxtime = 0 self.attrs = {} for line in file_input: m = re.search("([0-9]+)\t([0-9]+)\t([0-9.e\-+]+)\t([0-9.e\-+na]+)",line) #m = re.search("([0-9]+)",line) if m: vector = int(m.group(1)) if not vector in self.dataTime: self.dataTime[vector] = [] self.dataValues[vector] = [] time = float(m.group(3)) self.dataTime[vector].append(time) self.maxtime = max(self.maxtime,time) self.dataValues[vector].append(float(m.group(4))) else: # vector 7 Net802154.host[0].ipApp[0] referenceChangeStat:vector ETV m = re.search("vector *([0-9]*) *([^ ]*) *(.*):vector",line) if m: number = int(m.group(1)) module = m.group(2) name = m.group(3) if not name in self.vectors: self.vectors[name] = {} self.vectors[name][module] = number else: m = re.search("attr ([^ ]*) ([^ ]*)\n",line) if m: self.attrs[m.group(1)] = m.group(2) def get_vector(self,name,module,resample=None): num = self.vectors[name][module] (time,values) = (self.dataTime[num],self.dataValues[num]) if resample != None: newpoints = np.arange(0,self.maxtime,resample) lastvalue = values[-1] return (newpoints, scipy.interpolate.interp1d(time,values,'zero',assume_sorted=True, bounds_error=False,fill_value=(0,lastvalue)).__call__(newpoints)) else: return (time,values) def get_attr(self,name): return self.attrs[name]
i-tek/inet_ncs
simulations/analysis_tools/python/omnet_vector.py
Python
gpl-3.0
3,886
/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana * * Copyright (C) 2006 Instituto de Desarrollo Regional and Generalitat Valenciana. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA. * * For more information, contact: * * Generalitat Valenciana * Conselleria d'Infraestructures i Transport * Av. Blasco Ibañez, 50 * 46010 VALENCIA * SPAIN * * +34 963862235 * gvsig@gva.es * www.gvsig.gva.es * * or * * Instituto de Desarrollo Regional (Universidad de Castilla La-Mancha) * Campus Universitario s/n * 02071 Alabacete * Spain * * +34 967 599 200 */ package org.gvsig.georeferencing.process; import java.awt.geom.AffineTransform; import java.io.IOException; import org.gvsig.fmap.raster.layers.FLyrRasterSE; import org.gvsig.georeferencing.process.geotransform.GeoTransformProcess; import org.gvsig.raster.IProcessActions; import org.gvsig.raster.RasterProcess; import org.gvsig.raster.buffer.BufferFactory; import org.gvsig.raster.buffer.RasterBuffer; import org.gvsig.raster.buffer.RasterBufferInvalidAccessException; import org.gvsig.raster.buffer.RasterBufferInvalidException; import org.gvsig.raster.buffer.WriterBufferServer; import org.gvsig.raster.dataset.GeoRasterWriter; import org.gvsig.raster.dataset.IBuffer; import org.gvsig.raster.dataset.IRasterDataSource; import org.gvsig.raster.dataset.NotSupportedExtensionException; import org.gvsig.raster.dataset.io.RasterDriverException; import org.gvsig.raster.datastruct.GeoPointList; import org.gvsig.raster.grid.Grid; import org.gvsig.raster.grid.GridExtent; import org.gvsig.raster.grid.GridInterpolated; import org.gvsig.raster.grid.OutOfGridException; import org.gvsig.raster.process.RasterTask; import org.gvsig.raster.process.RasterTaskQueue; import org.gvsig.raster.util.RasterToolsUtil; import com.iver.andami.PluginServices; /** * Clase que representa una proceso de georreferenciacion de un raster. * * @author Alejandro Muñoz Sanchez (alejandro.munoz@uclm.es) * @version 10/2/2008 **/ public class GeoreferencingProcess extends RasterProcess implements IProcessActions{ //Capa a georreferenciar private FLyrRasterSE rasterSE = null; //Grid resultante de georreferenciacion private Grid imageGrid = null; //Fichero de salida private String filename = null; // Lista puntos de control private GeoPointList gpcs = null; //Extend de imagen corregida GridExtent newExtend = null; // Metodo de resampleado utilizado private int rMethod = 0; //Indicador de progreso private int percent = 0; // Grid resultado private Grid gridResult = null; WriterBufferServer writerBufferServer = null; private int orden = 0; private int[] bands = null; //Tamaño de celda en X si es pasada por el usuario private double xCellSize = 0; //Tamaño de celda en Y si es pasada por el usuario private double yCellSize = 0; /** Metodo que recoge los parametros del proceso georreferenciacion de un raster * <LI>rasterSE: capa a georeferenciar</LI> * <LI>filename: path con el fichero de salida</LI> * <LI>method: metodo de resampleo </LI> */ public void init() { rasterSE = (FLyrRasterSE)getParam("fLayer"); filename = (String)getParam("filename"); rMethod = (int)getIntParam("method"); gpcs = (GeoPointList) getParam("gpcs"); orden= (int)getIntParam("orden"); bands = new int[rasterSE.getBandCount()]; xCellSize = (double)getDoubleParam("xCellSize"); yCellSize = (double)getDoubleParam("yCellSize"); for(int i=0; i<rasterSE.getBandCount(); i++) bands[i]= i; // Inicializacion del grid correspondiente a la imagen a corregir IRasterDataSource dsetCopy = null; dsetCopy = rasterSE.getDataSource().newDataset(); BufferFactory bufferFactory = new BufferFactory(dsetCopy); bufferFactory.setReadOnly(true); try { imageGrid = new Grid(bufferFactory); }catch (RasterBufferInvalidException e) { e.printStackTrace(); } } public void process() throws InterruptedException { RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString()); GeoTransformProcess transform = new GeoTransformProcess(); transform.setActions(this); transform.addParam("gpcs", gpcs); transform.addParam("orden",new Integer(orden)); transform.run(); // Obtenida la transformacion la aplicamos a los puntos extremos de la imagen double p1[]=transform.getCoordMap(0,0); double p2[]=transform.getCoordMap(rasterSE.getPxWidth(),0); double p3[]=transform.getCoordMap(0,rasterSE.getPxHeight()); double p4[]=transform.getCoordMap(rasterSE.getPxWidth(),rasterSE.getPxHeight()); double xmin=Math.min(p1[0],p3[0]); double ymin=Math.min(p3[1],p4[1]); double xmax=Math.max(p2[0],p4[0]); double ymax=Math.max(p1[1],p2[1]); if(xCellSize <= 1) xCellSize = (xmax - xmin) / (double)rasterSE.getPxWidth(); if(yCellSize <= 1) yCellSize = (ymax - ymin) / (double)rasterSE.getPxHeight(); newExtend= new GridExtent(xmin, ymin, xmax, ymax, xCellSize); int datatype= rasterSE.getBufferFactory().getRasterBuf().getDataType(); try { gridResult = new Grid(newExtend, newExtend, datatype, bands); } catch (RasterBufferInvalidException e) { RasterToolsUtil.messageBoxError("error_grid", this, e); } double minPointX=gridResult.getGridExtent().getMin().getX(); double maxPointY=gridResult.getGridExtent().getMax().getY(); double cellsize=gridResult.getCellSize(); GridInterpolated gridInterpolated=null; gridInterpolated = new GridInterpolated((RasterBuffer)imageGrid.getRasterBuf(),imageGrid.getGridExtent(),imageGrid.getGridExtent(),bands); // SE ESTABLECE EL METODO DE INTERPOLACION (por defecto vecino mas proximo) if(rMethod==GridInterpolated.INTERPOLATION_BicubicSpline) gridInterpolated.setInterpolationMethod(GridInterpolated.INTERPOLATION_BicubicSpline); else if(rMethod==GridInterpolated.INTERPOLATION_Bilinear) gridInterpolated.setInterpolationMethod(GridInterpolated.INTERPOLATION_Bilinear); else gridInterpolated.setInterpolationMethod(GridInterpolated.INTERPOLATION_NearestNeighbour); double coord[] = null; try { if(datatype==IBuffer.TYPE_BYTE) { byte values[]=new byte[bands.length]; int progress=0; // OPTIMIZACION. Se esta recorriendo secuencialmente cada banda. for(int band = 0; band < bands.length; band++) { gridResult.setBandToOperate(band); gridInterpolated.setBandToOperate(band); for(int row = 0; row < gridResult.getLayerNY(); row++) { progress++; for(int col = 0; col < gridResult.getLayerNX(); col++) { coord = transform.getCoordPixel(col * cellsize+minPointX, maxPointY - row * cellsize); values[band] = (byte)gridInterpolated._getValueAt(coord[0], coord[1]); gridResult.setCellValue(col,row,(byte)values[band]); } percent=(int)(progress * 100 / (gridResult.getLayerNY() * bands.length)); if(task.getEvent() != null) task.manageEvent(task.getEvent()); } } } if(datatype==IBuffer.TYPE_SHORT) { short values[] = new short[bands.length]; int progress = 0; // OPTIMIZACION. Se esta recorriendo secuencialmente cada banda. for(int band = 0; band < bands.length; band++) { gridResult.setBandToOperate(band); gridInterpolated.setBandToOperate(band); for(int row = 0; row < gridResult.getLayerNY(); row++) { progress++; for(int col = 0; col < gridResult.getLayerNX(); col++) { coord=transform.getCoordPixel(col * cellsize+minPointX, maxPointY - row * cellsize); values[band] = (short)gridInterpolated._getValueAt(coord[0], coord[1]); gridResult.setCellValue(col, row, (short)values[band]); } percent=(int)(progress * 100 / (gridResult.getLayerNY() * bands.length)); if(task.getEvent() != null) task.manageEvent(task.getEvent()); } } } if(datatype == IBuffer.TYPE_INT) { int values[] = new int[bands.length]; int progress = 0; // OPTIMIZACION. Se esta recorriendo secuencialmente cada banda. for(int band = 0; band < bands.length; band++) { gridResult.setBandToOperate(band); gridInterpolated.setBandToOperate(band); for(int row = 0; row < gridResult.getLayerNY(); row++){ progress++; for(int col = 0; col < gridResult.getLayerNX(); col++) { coord = transform.getCoordPixel(col * cellsize + minPointX, maxPointY - row * cellsize); values[band] = (int)gridInterpolated._getValueAt(coord[0], coord[1]); gridResult.setCellValue(col, row, (int)values[band]); } percent=(int)( progress*100/(gridResult.getLayerNY()*bands.length)); if(task.getEvent() != null) task.manageEvent(task.getEvent()); } } } if(datatype == IBuffer.TYPE_FLOAT) { float values[] = new float[bands.length]; int progress = 0; // OPTIMIZACION. Se esta recorriendo secuencialmente cada banda. for(int band = 0; band < bands.length; band++) { gridResult.setBandToOperate(band); gridInterpolated.setBandToOperate(band); for(int row = 0; row < gridResult.getLayerNY(); row++) { progress++; for(int col = 0; col < gridResult.getLayerNX(); col++) { coord = transform.getCoordPixel(col * cellsize + minPointX, maxPointY - row * cellsize); values[band] = (float)gridInterpolated._getValueAt(coord[0], coord[1]); gridResult.setCellValue(col, row, (float)values[band]); } percent=(int)(progress * 100 / (gridResult.getLayerNY() * bands.length)); if(task.getEvent() != null) task.manageEvent(task.getEvent()); } } } if(datatype == IBuffer.TYPE_DOUBLE) { double values[] = new double[bands.length]; int progress = 0; // OPTIMIZACION. Se esta recorriendo secuencialmente cada banda. for(int band = 0; band < bands.length; band++) { gridResult.setBandToOperate(band); gridInterpolated.setBandToOperate(band); for(int row = 0; row < gridResult.getLayerNY(); row++) { progress++; for(int col = 0; col < gridResult.getLayerNX(); col++) { coord = transform.getCoordPixel(col * cellsize + minPointX, maxPointY - row * cellsize); values[band] = (double)gridInterpolated._getValueAt(coord[0], coord[1]); gridResult.setCellValue(col, row, (double)values[band]); } percent=(int)( progress * 100 / (gridResult.getLayerNY() * bands.length)); if(task.getEvent() != null) task.manageEvent(task.getEvent()); } } } } catch (OutOfGridException e) { e.printStackTrace(); } catch (RasterBufferInvalidAccessException e) { e.printStackTrace(); } catch (RasterBufferInvalidException e) { e.printStackTrace(); } generateLayer(); if(externalActions!=null) externalActions.end(filename); } private void generateLayer(){ GeoRasterWriter grw = null; IBuffer buffer= gridResult.getRasterBuf(); writerBufferServer = new WriterBufferServer(buffer); AffineTransform aTransform = new AffineTransform(newExtend.getCellSize(),0.0,0.0,-newExtend.getCellSize(),newExtend.getMin().getX(),newExtend.getMax().getY()); int endIndex =filename.lastIndexOf("."); if (endIndex < 0) endIndex = filename.length(); try { grw = GeoRasterWriter.getWriter(writerBufferServer, filename,gridResult.getRasterBuf().getBandCount(),aTransform, gridResult.getRasterBuf().getWidth(),gridResult.getRasterBuf().getHeight(), gridResult.getRasterBuf().getDataType(), GeoRasterWriter.getWriter(filename).getParams(),null); grw.dataWrite(); grw.setWkt(rasterSE.getWktProjection()); grw.writeClose(); } catch (NotSupportedExtensionException e1) { RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer_notsupportedextension"), this, e1); } catch (RasterDriverException e1) { RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer"), this, e1); } catch (IOException e) { RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } /* * (non-Javadoc) * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle() */ public String getTitle() { return PluginServices.getText(this,"georreferenciacion_process"); } /* * (non-Javadoc) * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getLabel() */ public int getPercent() { if(writerBufferServer==null) return percent; else return writerBufferServer.getPercent(); } /* * (non-Javadoc) * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getLabel() */ public String getLog() { return PluginServices.getText(this,"georreferencing_log_message"); } public void interrupted() { // TODO Auto-generated method stub } public void end(Object param) { } }
iCarto/siga
extGeoreferencing/src/org/gvsig/georeferencing/process/GeoreferencingProcess.java
Java
gpl-3.0
13,937
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.sql.dialect.oracle.ast.expr; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.dialect.oracle.ast.OracleSQLObjectImpl; import com.alibaba.druid.sql.dialect.oracle.visitor.OracleASTVisitor; public class OracleSizeExpr extends OracleSQLObjectImpl implements OracleExpr { private SQLExpr value; private Unit unit; public OracleSizeExpr(){ } public OracleSizeExpr(SQLExpr value, Unit unit){ super(); this.value = value; this.unit = unit; } @Override public void accept0(OracleASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, value); } visitor.endVisit(this); } public SQLExpr getValue() { return value; } public void setValue(SQLExpr value) { this.value = value; } public Unit getUnit() { return unit; } public void setUnit(Unit unit) { this.unit = unit; } public static enum Unit { K, M, G, T, P, E } public OracleSizeExpr clone() { OracleSizeExpr x = new OracleSizeExpr(); if (value != null) { x.setValue(value.clone()); } x.unit = unit; return x; } }
zuonima/sql-utils
src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/expr/OracleSizeExpr.java
Java
gpl-3.0
1,888
<?php namespace Freesewing; abstract class Output { public static $headers = array(); public static $body; public static function reset() { self::$headers = array(); self::$body = null; } } function header($value) { Output::$headers[] = $value; } function printf($format,$string) { Output::$body .= $string; }
freesewing/core
tests/src/assets/testFunctions.php
PHP
gpl-3.0
359
<?php /** * Litotex - Browsergame Engine * Copyright 2017 Das litotex.info Team, All Rights Reserved * * Website: http://www.litotex.info * License: GNU GENERAL PUBLIC LICENSE v3 (https://litotex.info/showthread.php?tid=3) * */ /* ************************************************************ Litotex BrowsergameEngine http://www.Litotex.de http://www.freebg.de Copyright (c) 2008 FreeBG Team ************************************************************ Hinweis: Diese Software ist urheberechtlich geschützt. Für jegliche Fehler oder Schäden, die durch diese Software auftreten könnten, übernimmt der Autor keine Haftung. Alle Copyright - Hinweise Innerhalb dieser Datei dürfen NICHT entfernt und NICHT verändert werden. ************************************************************ Released under the GNU General Public License ************************************************************ */ session_start(); if (!isset($_SESSION['litotex_start_acp']) || !isset($_SESSION['userid'])) { header('LOCATION: ./../../index.php'); exit(); } $action = (isset($_REQUEST['action']) ? filter_var($_REQUEST['action'], FILTER_SANITIZE_STRING) : 'main'); $modul_name = "acp_perm"; $menu_name = "Gruppenmanager"; require ($_SESSION['litotex_start_acp'] . 'acp/includes/global.php'); require ($_SESSION['litotex_start_acp'] . 'acp/includes/perm.php'); $tpl->assign('menu_name', $menu_name); if ($action == "save_mod") { if (!isset($_POST['perm']) || !is_array($_POST['perm'])) { error_msg('Schwerer Fehler! Formulardaten wurden nicht übergeben!'); exit; } $sql = ''; foreach ($_POST['perm'] as $id => $perm) { $id = filter_var($id, FILTER_SANITIZE_NUMBER_INT); $perm = filter_var($perm, FILTER_SANITIZE_NUMBER_INT); $sql .= "UPDATE `cc" . $n . "_modul_admin` SET `perm_lvl` = '" . $perm . "' WHERE `modul_admin_id` = '" . $id . "';"; } $db->multi_query($sql); redirect($modul_name, 'perm', 'listmod'); } elseif ($action == "save_grp") { if ((!isset($_POST['perm']) || !isset($_POST['name'])) && (!isset($_POST['new_name']) || !isset($_POST['new_lvl'])) || ! is_array($_POST['perm'])) { error_msg('Schwerer Fehler! Formulardaten wurden nicht übergeben!'); exit; } if (isset($_POST['perm']) && isset($_POST['name'])) { $sql = ''; foreach ($_POST['perm'] as $id => $perm) { $id = filter_var($id, FILTER_SANITIZE_NUMBER_INT); $perm = filter_var($perm, FILTER_SANITIZE_NUMBER_INT); $sql .= "UPDATE `cc" . $n . "_user_groups` SET `perm_lvl` = '" . $perm . "', `name` = '" . $db->escape_string($_POST['name'][$id]) . "' WHERE `id` = '" . $id . "';"; } $db->multi_query($sql); } if (!empty($_POST['new_name']) && !empty($_POST['new_lvl'])) { $new_lvl = filter_var($_POST['new_lvl'], FILTER_SANITIZE_NUMBER_INT); $db->query("INSERT INTO `cc" . $n . "_user_groups` (`perm_lvl`, `name`) VALUES ('" . $new_lvl . "', '" . $db-> escape_string($_POST['new_name']) . "')"); } redirect('acp_perm', 'perm', 'listgroup'); } elseif ($action == "main") { template_out('main.html', $modul_name); } elseif ($action == "listmod") { $mods_q = $db->query("SELECT `modul_admin_id`, `modul_name`, `modul_description`, `acp_modul`, `perm_lvl` FROM `cc" . $n . "_modul_admin` WHERE `acp_modul` = '1'"); $mods = array(); $i = 0; while ($mod = $db->fetch_array($mods_q)) { $mods[$i]['id'] = $mod['modul_admin_id']; $mods[$i]['name'] = $mod['modul_name']; $mods[$i]['description'] = $mod['modul_description']; $mods[$i]['perm'] = $mod['perm_lvl']; $i++; } $tpl->assign('mods', $mods); template_out('listmod.html', $modul_name); } elseif ($action == "listgroup") { $groups_q = $db->query("SELECT `id`, `name`, `perm_lvl` FROM `cc" . $n . "_user_groups`"); $groups = array(); $i = 0; while ($group = $db->fetch_array($groups_q)) { $groups[$i]['id'] = $group['id']; $groups[$i]['name'] = $group['name']; $groups[$i]['perm'] = $group['perm_lvl']; $i++; } $tpl->assign('groups', $groups); template_out('listgroup.html', $modul_name); }
Kev5454/litotex
acp/modules/acp_perm/perm.php
PHP
gpl-3.0
4,460
window.jQuery = window.$ = require('jquery'); require('bootstrap'); var angular = require('angular'); var uirouter = require('angular-ui-router'); var uibootstrap = require('angular-ui-bootstrap'); var fileupload = require('ng-file-upload'); //TODO pretify these uris require('./css/main.css'); require('./css/theme.css'); require('./node_modules/bootstrap/dist/css/bootstrap.min.css'); require('./node_modules/bootstrap/dist/css/bootstrap-theme.min.css'); require('./node_modules/font-awesome/css/font-awesome.min.css'); angular.module('openstore', [uirouter, uibootstrap, fileupload]) .config(function($stateProvider, $urlRouterProvider, $locationProvider, $compileProvider) { $urlRouterProvider.otherwise('/'); $locationProvider.html5Mode(true); $stateProvider.state('main', { url: '/', templateUrl: '/app/partials/main.html', }) .state('docs', { url: '/docs', templateUrl: '/app/partials/docs.html', controller: 'docsCtrl' }) .state('submit', { url: '/submit', templateUrl: '/app/partials/submit.html', controller: 'submitCtrl' }) .state('apps', { url: '/apps', templateUrl: '/app/partials/apps.html', controller: 'appsCtrl' }) .state('app', { url: '/app/:name', templateUrl: '/app/partials/app.html', controller: 'appsCtrl' }) .state('manage', { url: '/manage', templateUrl: '/app/partials/manage.html', controller: 'manageCtrl' }); $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|scope|openstore):/); }) .controller('indexCtrl', require('./app/controllers/indexCtrl')) .controller('appsCtrl', require('./app/controllers/appsCtrl')) .controller('manageCtrl', require('./app/controllers/manageCtrl')) .controller('submitCtrl', require('./app/controllers/submitCtrl')) .controller('docsCtrl', require('./app/controllers/docsCtrl')) .directive('ngContent', require('./app/directives/ngContent')) .directive('types', require('./app/directives/types')) .filter('bytes', require('./app/filters/bytes')) .filter('versionFix', require('./app/filters/versionFix')) .filter('nl2br', require('./app/filters/nl2br')) .factory('api', require('./app/services/api')) .factory('info', require('./app/services/info'));
mariogrip/openappstore-web
www/app.js
JavaScript
gpl-3.0
2,324
<?php /** * Used for adding dated reminders. * * Copyright (C) 2012 tajemo.co.za <http://www.tajemo.co.za/> * Copyright (C) 2017 Brady Miller <brady.g.miller@gmail.com> * * LICENSE: This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 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://opensource.org/licenses/gpl-license.php>;. * * @package OpenEMR * @author Craig Bezuidenhout <http://www.tajemo.co.za/> * @author Brady Miller <brady.g.miller@gmail.com> * @link http://www.open-emr.org */ $fake_register_globals=false; $sanitize_all_escapes=true; require_once("../../globals.php"); require_once("$srcdir/dated_reminder_functions.php"); $dateRanges = array(); // $dateranges = array ( number_period => text to display ) == period is always in the singular // eg. $dateRanges['4_week'] = '4 Weeks From Now'; $dateRanges['1_day'] = xl('1 Day From Now'); $dateRanges['2_day'] = xl('2 Days From Now'); $dateRanges['3_day'] = xl('3 Days From Now'); $dateRanges['4_day'] = xl('4 Days From Now'); $dateRanges['5_day'] = xl('5 Days From Now'); $dateRanges['6_day'] = xl('6 Days From Now'); $dateRanges['1_week'] = xl('1 Week From Now'); $dateRanges['2_week'] = xl('2 Weeks From Now'); $dateRanges['3_week'] = xl('3 Weeks From Now'); $dateRanges['4_week'] = xl('4 Weeks From Now'); $dateRanges['5_week'] = xl('5 Weeks From Now'); $dateRanges['6_week'] = xl('6 Weeks From Now'); $dateRanges['1_month'] = xl('1 Month From Now'); $dateRanges['2_month'] = xl('2 Months From Now'); $dateRanges['3_month'] = xl('3 Months From Now'); $dateRanges['4_month'] = xl('4 Months From Now'); $dateRanges['5_month'] = xl('5 Months From Now'); $dateRanges['6_month'] = xl('6 Months From Now'); $dateRanges['7_month'] = xl('7 Months From Now'); $dateRanges['8_month'] = xl('8 Months From Now'); $dateRanges['9_month'] = xl('9 Months From Now'); $dateRanges['1_year'] = xl('1 Year From Now'); $dateRanges['2_year'] = xl('2 Years From Now'); // --- need to add a check to ensure the post is being sent from the correct location ??? // default values for $this_message $this_message = array('message'=>'','message_priority'=>3,'dueDate'=>''); $forwarding = false; // default values for Max words to input in a reminder $max_reminder_words=160; // ---------------- FOR FORWARDING MESSAGES -------------> if(isset($_GET['mID']) and is_numeric($_GET['mID'])){ $forwarding = true; $this_message = getReminderById($_GET['mID']); } // ---------------END FORWARDING MESSAGES ---------------- // --- add reminders if($_POST){ // --- initialize $output as blank $output = ''; // ------ fills an array with all recipients $sendTo = $_POST['sendTo']; // for incase of data error, this allows the previously entered data to re-populate the boxes $this_message['message'] = (isset($_POST['message']) ? $_POST['message'] : ''); $this_message['priority'] = (isset($_POST['priority']) ? $_POST['priority'] : ''); $this_message['dueDate'] = (isset($_POST['dueDate']) ? $_POST['dueDate'] : ''); // -------------------------------------------------------------------------------------------------------------------------- // --- check for the post, if it is valid, commit to the database, close this window and run opener.Handeler if( // ------- check sendTo is not empty !empty($sendTo) and // ------- check dueDate, only allow valid dates, todo -> enhance date checker isset($_POST['dueDate']) and preg_match('/\d{4}[-]\d{2}[-]\d{2}/',$_POST['dueDate']) and // ------- check priority, only allow 1-3 isset($_POST['priority']) and intval($_POST['priority']) <= 3 and // ------- check message, only up to 160 characters limited by Db isset($_POST['message']) and strlen($_POST['message']) <= $max_reminder_words and strlen($_POST['message']) > 0 and // ------- check if PatientID is set and in numeric isset($_POST['PatientID']) and is_numeric($_POST['PatientID']) ){ $dueDate = $_POST['dueDate']; $priority = intval($_POST['priority']); $message = $_POST['message']; $fromID = $_SESSION['authId']; $patID = $_POST['PatientID']; if(isset($_POST['sendSeperately']) and $_POST['sendSeperately']){ foreach($sendTo as $st){ $ReminderSent = sendReminder(array($st),$fromID,$message,$dueDate,$patID,$priority); } } else{ // -------- Send the reminder $ReminderSent = sendReminder($sendTo,$fromID,$message,$dueDate,$patID,$priority); } // -------------------------------------------------------------------------------------------------------------------------- if(!$ReminderSent){ $output .= '<div style="text-size:2em; text-align:center; color:red">* '.xlt('Please select a valid recipient').'</div> '; }else{ // --------- echo javascript echo '<html><body>' ."<script type=\"text/javascript\" src=\"". $webroot ."/interface/main/tabs/js/include_opener.js\"></script>" .'<script language="JavaScript">'; // ------------ 1) refresh parent window this updates if sent to self echo ' if (opener && !opener.closed && opener.updateme) opener.updateme("new");'; // ------------ 2) communicate with user echo ' alert("'.addslashes(xl('Message Sent')).'");'; // ------------ 3) close this window echo ' window.close();'; echo '</script></body></html>'; // --------- stop script from executing further exit; } // -------------------------------------------------------------------------------------------------------------------------- } // -------------------------------------------------------------------------------------------------------------------------- else{ // ------- if POST error $output .= '<div style="text-size:2em; text-align:center; color:red">* '.xlt('Data Error').'</div> '; } // ------- if any errors, communicate with the user echo $output; } // end add reminders // get current patient, first check if this is a forwarded message, if it is use the original pid if(isset($this_message['pid'])) $patientID = (isset($this_message['pid']) ? $this_message['pid'] : 0); else $patientID = (isset($pid) ? $pid : 0); ?> <html> <head> <title><?php echo xlt('Send a Reminder') ?></title> <link rel="stylesheet" href="<?php echo $css_header;?>" type="text/css"> <link rel="stylesheet" href="<?php echo $GLOBALS['assets_static_relative']; ?>/jquery-datetimepicker-2-5-4/build/jquery.datetimepicker.min.css"> <script type="text/javascript" src="<?php echo $webroot ?>/interface/main/tabs/js/include_opener.js?v=<?php echo $v_js_includes; ?>"></script> <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/topdialog.js?v=<?php echo $v_js_includes; ?>"></script> <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/dialog.js?v=<?php echo $v_js_includes; ?>"></script> <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/js/common.js?v=<?php echo $v_js_includes; ?>"></script> <script type="text/javascript" src="<?php echo $GLOBALS['assets_static_relative']; ?>/jquery-min-3-1-1/index.js"></script> <script type="text/javascript" src="<?php echo $GLOBALS['assets_static_relative']; ?>/jquery-datetimepicker-2-5-4/build/jquery.datetimepicker.full.min.js"></script> <script language="JavaScript"> $(document).ready(function (){ $('#timeSpan').change(function(){ var value = $(this).val(); var arr = value.split('_'); var span = arr[1]; var period = parseInt(arr[0]); var d=new Date(); if(span == 'day'){ d.setDate(d.getDate()+period); } else if(span == 'week'){ var weekInDays = period * 7; d.setDate(d.getDate()+weekInDays); } else if(span == 'month'){ d.setMonth(d.getMonth()+period); } else if(span == 'year'){ var yearsInMonths = period * 12; d.setMonth(d.getMonth()+yearsInMonths); } var curr_date = d.getDate().toString(); if(curr_date.length == 1){ curr_date = '0'+curr_date; } var curr_month = d.getMonth() + 1; //months are zero based curr_month = curr_month.toString(); if(curr_month.length == 1){ curr_month = '0'+curr_month; } var curr_year = d.getFullYear(); $('#dueDate').val(curr_year + "-" + curr_month + "-" + curr_date); }) $("#sendButton").click(function(){ $('#errorMessage').html(''); errorMessage = ''; var PatientID = $('#PatientID').val(); var dueDate = $('#dueDate').val(); var priority = $('#priority:checked').val(); var message = $("#message").val(); // todo : check if PatientID is numeric , no rush as this is checked in the php after the post // check to see if a recipient has been set // todo : check if they are all numeric , no rush as this is checked in the php after the post if (!$("#sendTo option:selected").length){ errorMessage = errorMessage + '* <?php echo xla('Please Select A Recipient') ?><br />'; } // Check if Date is set // todo : add check to see if dueDate is a valid date , no rush as this is checked in the php after the post if(dueDate == ''){ errorMessage = errorMessage + '* <?php echo xla('Please enter a due date') ?><br />'; } // check if message is set if(message == ''){ errorMessage = errorMessage + '* <?php echo xla('Please enter a message') ?><br />'; } if(errorMessage != ''){ // handle invalid queries $('#errorMessage').html(errorMessage); } else{ // handle valid queries // post the form to self top.restoreSession(); $("#addDR").submit(); } return false; }) $("#removePatient").click(function(){ $("#PatientID").val("0"); $("#patientName").val("<?php echo xla('Click to select patient'); ?>"); $(this).hide(); return false; }) // update word counter var messegeTextarea=$("#message")[0]; limitText(messegeTextarea.form.message,messegeTextarea.form.countdown,<?php echo $max_reminder_words ?>); $('.datepicker').datetimepicker({ <?php $datetimepicker_timepicker = false; ?> <?php $datetimepicker_showseconds = false; ?> <?php $datetimepicker_formatInput = false; ?> <?php require($GLOBALS['srcdir'] . '/js/xl/jquery-datetimepicker-2-5-4.js.php'); ?> <?php // can add any additional javascript settings to datetimepicker here; need to prepend first setting with a comma ?> }); }) function sel_patient(){ window.open('../../main/calendar/find_patient_popup.php', '_newDRPat', '' + ",width=" + 500 + ",height=" + 400 + ",left=" + 25 + ",top=" + 25 + ",screenX=" + 25 + ",screenY=" + 25); } function setpatient(pid, lname, fname, dob){ $("#patientName").val(fname +' '+ lname) $("#PatientID").val(pid); $("#removePatient").show(); return false; } function limitText(limitField, limitCount, limitNum) { if (limitField.value.length > limitNum) { limitField.value = limitField.value.substring(0, limitNum); } else { limitCount.value = limitNum - limitField.value.length; } } function selectAll(){ $("#sendTo").each(function(){$("#sendTo option").attr("selected","selected"); }); } </script> <link rel="stylesheet" href="<?php echo $css_header;?>" type="text/css"> </head> <body class="body_top"> <!-- Required for the popup date selectors --> <div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div> <h1><?php echo xlt('Send a Reminder') ?></h1> <form id="addDR" style="margin:0 0 10px 0;" id="newMessage" method="post" onsubmit="return top.restoreSession()"> <div style="text-align:center; color:red" id="errorMessage"></div> <fieldset> <?php echo xlt('Link To Patient') ?> : <input type='text' size='10' id='patientName' name='patientName' style='width:200px;cursor:pointer;cursor:hand' value='<?php echo ($patientID > 0 ? attr(getPatName($patientID)) : xla('Click to select patient')); ?>' onclick='sel_patient()' title='<?php xla('Click to select patient'); ?>' readonly /> <input type="hidden" name="PatientID" id="PatientID" value="<?php echo (isset($patientID) ? attr($patientID) : 0) ?>" /> <button <?php echo ($patientID > 0 ? '' : 'style="display:none"') ?> id="removePatient"><?php echo xlt('unlink patient') ?></button> </fieldset> <br /> <fieldset> <table style="width:100%;" cellpadding="5px"> <tr> <td style="width:20%; text-align:right" valign="top"> <?php echo xlt('Send to') ?> : <br /><?php echo xlt('([ctrl] + click to select multiple recipients)'); ?> </td> <td style="width:60%;"> <select style="width:100%" id="sendTo" name="sendTo[]" multiple="multiple"> <option value="<?php echo attr(intval($_SESSION['authId'])); ?>"><?php echo xlt('Myself') ?></option> <?php // $uSQL = sqlStatement('SELECT id, fname, mname, lname FROM `users` WHERE `active` = 1 AND `facility_id` > 0 AND id != ?',array(intval($_SESSION['authId']))); for($i=2; $uRow=sqlFetchArray($uSQL); $i++){ echo '<option value="',attr($uRow['id']),'">',text($uRow['fname'].' '.$uRow['mname'].' '.$uRow['lname']),'</option>'; } ?> </select> <br /> <input title="<?php echo xlt('Selecting this will create a message that needs to be processed by each recipient individually (this is not a group task).') ?>" type="checkbox" name="sendSeperately" id="sendSeperately" /> <label title="<?php echo xlt('Selecting this will create a message that needs to be processed by each recipient individually (this is not a group task).') ?>" for="sendSeperately">(<?php echo xlt('Each recipient must set their own messages as completed.') ?>)</label> </td> <td style="text-align:right"> <a class="css_button_small" style="cursor:pointer" onclick="selectAll();" ><span><?php echo xlt('Send to all') ?></span></a> </td> </table> </fieldset> <br /> <fieldset> <?php echo xlt('Due Date') ?> : <input type='text' class='datepicker' name='dueDate' id="dueDate" size='20' value="<?php echo ($this_message['dueDate'] == '' ? date('Y-m-d') : attr($this_message['dueDate'])); ?>" title='<?php echo htmlspecialchars( xl('yyyy-mm-dd'), ENT_QUOTES); ?>' /> <?php echo xlt('OR') ?> <?php echo xlt('Select a Time Span') ?> : <select id="timeSpan"> <option value="__BLANK__"> -- <?php echo xlt('Select a Time Span') ?> -- </option> <?php $optionTxt = ''; foreach($dateRanges as $val=>$txt){ $optionTxt .= '<option value="'.attr($val).'">'.text($txt).'</option>'; } echo $optionTxt; ?> </select> </td> </fieldset> <br /> <fieldset> <?php echo xlt('Priority') ?> : <input <?php echo ($this_message['message_priority'] == 3 ? 'checked="checked"' : '') ?> type="radio" name="priority" id="priority_3" value='3'> <label for="priority_3"><?php echo xlt('Low') ?></label> <input <?php echo ($this_message['message_priority'] == 2 ? 'checked="checked"' : '') ?> type="radio" name="priority" id="priority_2" value='2'> <label for="priority_2"><?php echo xlt('Medium') ?></label> <input <?php echo ($this_message['message_priority'] == 1 ? 'checked="checked"' : '') ?> type="radio" name="priority" id="priority_1" value='1'> <label for="priority_1"><?php echo xlt('High') ?></label> </fieldset> <br /> <fieldset> <table style="width:100%;"> <tr> <td valign="top" style="width:25%"> <?php echo xlt('Type Your message here') ?> :<br /><br /> <font size="1">(<?php echo xlt('Maximum characters') ?>: <?php echo $max_reminder_words ?>)<br /> </td> <td valign="top" style="width:75%"> <textarea onKeyDown="limitText(this.form.message,this.form.countdown,<?php echo $max_reminder_words ?>);" onKeyUp="limitText(this.form.message,this.form.countdown,<?php echo $max_reminder_words ?>);" style="width:100%; height:50px" name="message" id="message"><?php echo text($this_message['dr_message_text']); ?></textarea> <br /> <?php echo xlt('Characters Remaining') ?> : <input style="border:0; background:none;" readonly type="text" name="countdown" size="3" value="<?php echo $max_reminder_words ?>"> </font> </td> </tr> </table> </fieldset> <p align="center"> <input type="submit" id="sendButton" value="<?php echo xla('Send This Message') ?>" /> </p> </form> <?php $_GET['sentBy'] = array($_SESSION['authId']); $_GET['sd'] = date('Y/m/d'); $TempRemindersArray = logRemindersArray(); $remindersArray = array(); foreach($TempRemindersArray as $RA){ $remindersArray[$RA['messageID']]['messageID'] = $RA['messageID']; $remindersArray[$RA['messageID']]['ToName'] = ($remindersArray[$RA['messageID']]['ToName'] ? $remindersArray[$RA['messageID']]['ToName'].', '.$RA['ToName'] : $RA['ToName']); $remindersArray[$RA['messageID']]['PatientName'] = $RA['PatientName']; $remindersArray[$RA['messageID']]['message'] = $RA['message']; $remindersArray[$RA['messageID']]['dDate'] = $RA['dDate']; } echo '<h2>',xlt('Messages You have sent Today'),'</h2>'; echo '<table border="1" width="100%" cellpadding="5px" id="logTable"> <thead> <tr> <th>'.xlt('ID').'</th> <th>'.xlt('To').'</th> <th>'.xlt('Patient').'</th> <th>'.xlt('Message').'</th> <th>'.xlt('Due Date').'</th> </tr> </thead> <tbody>'; foreach($remindersArray as $RA){ echo '<tr class="heading"> <td>',text($RA['messageID']),'</td> <td>',text($RA['ToName']),'</td> <td>',text($RA['PatientName']),'</td> <td>',text($RA['message']),'</td> <td>',text($RA['dDate']),'</td> </tr>'; } echo '</tbody></table>'; ?> </body> </html>
georgetye/openemr
interface/main/dated_reminders/dated_reminders_add.php
PHP
gpl-3.0
20,320
package bio.overture.score.client.util; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.val; import java.io.File; import java.util.List; @RequiredArgsConstructor public class CsvParser<T> { private final Class<T> type; private final Character columnSep; @SneakyThrows public List<T> parseFile(File file){ val mapper = new CsvMapper(); mapper.addMixIn(type, type); val schema = mapper.schemaFor(type) .withHeader() .withColumnSeparator(columnSep); return mapper .readerFor(type) .with(schema) .<T>readValues(file) .readAll(); } }
icgc-dcc/dcc-storage
score-client/src/main/java/bio/overture/score/client/util/CsvParser.java
Java
gpl-3.0
700
#!/usr/bin/env python # coding=utf-8 """598. Split Divisibilities https://projecteuler.net/problem=598 Consider the number 48. There are five pairs of integers $a$ and $b$ ($a \leq b$) such that $a \times b=48$: (1,48), (2,24), (3,16), (4,12) and (6,8). It can be seen that both 6 and 8 have 4 divisors. So of those five pairs one consists of two integers with the same number of divisors. In general: Let $C(n)$ be the number of pairs of positive integers $a \times b=n$, ($a \leq b$) such that $a$ and $b$ have the same number of divisors; so $C(48)=1$. You are given $C(10!)=3$: (1680, 2160), (1800, 2016) and (1890,1920). Find $C(100!)$ """
openqt/algorithms
projecteuler/pe598-split-divisibilities.py
Python
gpl-3.0
660
using ProtoBuf; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Abstractions.SourceCode.VueJs { [ProtoContract] [Table("FieldsetFormGroupAssociations", Schema = nameof(VueJs))] public class FieldsetFormGroupAssociation { [Key] [ProtoMember(1)] public int FieldsetFormGroupAssociationId { get; set; } [ProtoMember(2)] public Fieldset Fieldset { get; set; } [ProtoMember(3)] public int FieldsetId { get; set; } [ProtoMember(4)] public FormGroup FormGroup { get; set; } [ProtoMember(5)] public int FormGroupId { get; set; } } }
cdorst/DevOps
src/Abstractions.SourceCode.VueJs/FieldsetFormGroupAssociation.cs
C#
gpl-3.0
696
<?php echo (isset($zf_error) ? $zf_error : (isset($error) ? $error : '')); if (isset($author)) { ?> <div class="row even"><?php echo $label_author . $author . $author_other?></div> <?php } ?> <div class="row"><?php echo $label_name . $name . $note_name?></div> <div class="row even"> <div class="cell number"><?php echo $label_height . $height?></div> <div class="cell number"><?php echo $label_width . $width?></div> <div class="cell number"><?php echo $label_weight . $weight?></div> <br /><br /><br /> <?php echo $note_height?> <div class="clear"></div> </div> <div class="row"> <div class="cell"> <?php echo $label_type?> <div class="cell"><?php echo $type_astral?></div> <div class="cell"><?php echo $label_type_astral?></div> <div class="clear"></div> <div class="cell"><?php echo $type_guardian?></div> <div class="cell"><?php echo $label_type_guardian?></div> <div class="clear"></div> <div class="cell"><?php echo $type_material?></div> <div class="cell"><?php echo $label_type_material?></div> <div class="clear"></div> <div class="cell"><?php echo $type_samus?></div> <div class="cell"><?php echo $label_type_samus?></div> <div class="clear"></div> </div> <div class="cell" style="margin-left: 20px"> <?php echo $label_gender?> <div class="cell"><?php echo $gender_aquatic?></div> <div class="cell"><?php echo $label_gender_aquatic?></div> <div class="clear"></div> <div class="cell"><?php echo $gender_terrestrial?></div> <div class="cell"><?php echo $label_gender_terrestrial?></div> <div class="clear"></div> <div class="cell"><?php echo $gender_vegetable?></div> <div class="cell"><?php echo $label_gender_vegetable?></div> <div class="clear"></div> <div class="cell"><?php echo $gender_flying?></div> <div class="cell"><?php echo $label_gender_flying?></div> <div class="clear"></div> </div> <div class="clear"></div> </div> <div class="row"> <?php echo $label_skills; if(isset($_POST["skill_total"])) { for($i=1; $i<=$_POST["skill_total"]; $i++) { if(isset($_POST["skill_".$i])) { echo '<input type="text" name="skill_'.$i.'" id="skill_'.$i.'" value="'.$_POST["skill_".$i].'" class="control text modifier-lowercase" style="display: inline; margin-bottom: 5px;"> '; echo '<select name="type_skill_'.$i.'" id="type_skill_'.$i.'" class="control" style="height: 28px; display: inline; margin-bottom: 5px;">'; if($_POST["type_skill_".$i] == 'attack') { echo '<option value="">- select -</option>'; echo '<option value="attack" selected="selected">Attack</option>'; echo '<option value="defense">Defense</option>'; } elseif($_POST["type_skill_".$i] == 'defense') { echo '<option value="">- select -</option>'; echo '<option value="attack">Attack</option>'; echo '<option value="defense" selected="selected">Defense</option>'; } else { echo '<option value="">- select -</option>'; echo '<option value="attack">Attack</option>'; echo '<option value="defense">Defense</option>'; } echo '</select> <br/>'; echo '<textarea name="desc_skill'.$i.'" id="desc_skill'.$i.'" rows="5" cols="80" class="control modifier-lowercase">'.$_POST["desc_skill".$i].'</textarea>'; } $count = $i; } echo '<script type="text/javascript">$(document).ready(function(){ $("#add_skill").generaNuevosCampos("skill_", '.$count.'); }); </script>'; echo '<input type="hidden" name="skill_total" id="skill_total" value="'.$count.'" />'; echo '<input type="button" name="add_skill" id="add_skill" value="'.__('Add Skill', 'wpinimat_languages').'" class="button">'; } else { echo '<script type="text/javascript">$(document).ready(function(){ $("#add_skill").generaNuevosCampos("skill_", '.(COUNT_SKILLS + 1).'); }); </script>'; for($i=1; $i<=COUNT_SKILLS; $i++) { $union_skill = 'skill_'.$i; $union_type_skill = 'type_skill_'.$i; $union_desc_skill = 'desc_skill_'.$i; $skill = $$union_skill; $type_skill = $$union_type_skill; $desc_skill = $$union_desc_skill; echo $skill . ' ' . $type_skill . $desc_skill . '<br />'; } echo '<input type="hidden" name="skill_total" id="skill_total" value="'.COUNT_SKILLS.'" />'; echo '<input type="button" name="add_skill" id="add_skill" value="'.__('Add Skill', 'wpinimat_languages').'" class="button">'; } ?> <div class="clear"></div> </div> <div class="row"><?php echo $label_habitat . $habitat?></div> <div class="row even"><?php echo $label_description . $description?></div> <div class="row"><?php echo $label_imgSketch; echo '<table><tr>'; if(defined('NAME_SKETCH') == TRUE) { echo '<td><img src="' . WPINIMAT_PLUGIN_URL . 'upload/th/' . NAME_SKETCH . '" width="100" height="100" /></td>'; } else { echo '<td><img src="' . WPINIMAT_PLUGIN_URL . 'img/not-img.png" width="100" height="100" /></td>'; } echo '<td style="vertical-align: inherit;">' . $imgSketch . $note_imgSketch . '</td></tr></table>'; ?></div> <div class="row even"><?php echo $label_imgModeled; echo '<table><tr>'; if(defined('NAME_MODELED') == TRUE) { echo '<td><img src="' . WPINIMAT_PLUGIN_URL . 'upload/th/' . NAME_MODELED . '" width="100" height="100" /></td>'; } else { echo '<td><img src="' . WPINIMAT_PLUGIN_URL . 'img/not-img.png" width="100" height="100" /></td>'; } echo '<td style="vertical-align: inherit;">' . $imgModeled . $note_imgModeled . '</td></tr></table>'; ?></div> <div class="row"><?php echo $label_imgTextured; echo '<table><tr>'; if(defined('NAME_TEXTURED') == TRUE) { echo '<td><img src="' . WPINIMAT_PLUGIN_URL . 'upload/th/' . NAME_TEXTURED . '" width="100" height="100" /></td>'; } else { echo '<td><img src="' . WPINIMAT_PLUGIN_URL . 'img/not-img.png" width="100" height="100" /></td>'; } echo '<td style="vertical-align: inherit;">' . $imgTextured . $note_imgTextured . '</td></tr></table>'; ?></div> <div class="row even"><?php echo $label_file; echo '<table><tr>'; if(defined('NAME_FILE') == TRUE) { echo '<td><a href="' . WPINIMAT_PLUGIN_URL . '/upload/' . NAME_FILE . '"><img src="' . WPINIMAT_PLUGIN_URL . 'img/zip.png" width="48" height="48" /></a></td>'; } else { echo '<td><img src="' . WPINIMAT_PLUGIN_URL . 'img/not-img.png" width="100" height="100" /></td>'; } echo '<td style="vertical-align: inherit;">' . $file . $note_file . '</td></tr></table>'; ?></div> <div class="row"> <div class="cell"><?php echo $license_1?></div> <div class="cell"><?php echo $label_license_1?></div> <div class="clear"></div> </div> <?php if (isset($finished_1)) { ?> <div class="row even"> <div class="cell"><?php echo $finished_1?></div> <div class="cell"><?php echo $label_finished_1?></div> <div class="clear"></div> </div> <?php } ?> <div class="row last"><?php echo $btnsubmit?></div>
WaKeMaTTa/wp-inimat
admin.classifier_creatures.edit.template.php
PHP
gpl-3.0
7,291
import pyes import os from models import * from sqlalchemy import select from downloader import download import utils import re import time class Search(object): def __init__(self,host,index,map_name,mapping=None,id_key=None): self.es = pyes.ES(host) self.index = index self.map_name = map_name self.mapping = mapping self.id_key = id_key def create_index(self): self.es.create_index_if_missing(self.index) if self.mapping: if self.id_key: self.es.put_mapping(self.map_name,{ self.map_name:{ '_id':{ 'path':self.id_key }, 'properties':self.mapping} },[self.index]) else: self.es.put_mapping(self.map_name,{ self.map_name:{ 'properties':self.mapping } },[self.index]) self.es.refresh(self.index) def index_item(self,item): self.es.index(item,self.index,self.map_name) self.es.refresh(self.index) def convert_to_document(revision): temp = {} rev_key = [ i for i in dir(revision) if not re.match('^_',i) ] bill_key = [ i for i in dir(revision.bill) if not re.match('^_',i) ] for key in rev_key: if key != 'metadata' and key != 'bill': temp[key] = getattr(revision,key) for key in bill_key: if key != 'metadata' and key!='id' and key!='bill_revs': temp[key] = getattr(revision.bill,key) full_path = download(temp['url']) if full_path: temp['document'] = pyes.file_to_attachment(full_path) return temp def initial_index(): host = '127.0.0.1:9200' index = 'bill-index' map_name = 'bill-type' mapping = { 'document':{ 'type':'attachment', 'fields':{ "title" : { "store" : "yes" }, "file" : { "term_vector":"with_positions_offsets", "store":"yes" } } }, 'name':{ 'type':'string', 'store':'yes', 'boost':1.0, 'index':'analyzed' }, 'long_name':{ 'type':'string', 'store':'yes', 'boost':1.0, 'index':'analyzed' }, 'status':{ 'type':'string', 'store':'yes', }, 'year':{ 'type':'integer', 'store':'yes' }, 'read_by':{ 'type':'string', 'store':'yes', 'index':'analyzed' }, 'date_presented':{ 'type':'date', 'store':'yes' }, 'bill_id':{ 'type':'integer', 'store':'yes' }, 'id':{ 'type':'integer', 'store':'yes' } } search = Search(host,index,map_name,mapping) search.create_index() initdb() session = DBSession() revision = (session.query(BillRevision) .join((BillRevision.bill,Bill)).all() ) for rev in revision: temp = convert_to_document(rev) search.index_item(temp) time.sleep(5) def index_single(rev_id): host = '127.0.0.1:9200' index = 'bill-index' map_name = 'bill-type' initdb() session = DBSession() revision = (session.query(BillRevision).get(rev_id) ) temp = convert_to_document(revision) search = Search(host,index,map_name) search.index_item(temp) if __name__ == '__main__': initial_index()
sweemeng/Malaysian-Bill-Watcher
billwatcher/indexer.py
Python
gpl-3.0
3,747
import requests from bs4 import BeautifulSoup def trade_spider(max_pages): page = 1 while page <= max_pages: url = "https://thenewboston.com/videos.php?cat=98&video=20144" #+ str(page) source_code = request.get(url) plain_text = source_code.text soup = BeautifulSoup(plain_text) for link in soup.findAll("a", {"class": "itemname"}): href = link.get("href") print("href") trade_spider(1) def get_single_item_data(item_url): source_code = request.get(item_url) plain_text = source_code.text soup = BeautifulSoup(plain_text) for item_name in soup.findAll("a", {"class": "i-name"}): print(item_name.string)
Tbear1981/bitcoin-overseer
files/webcrawler.py
Python
gpl-3.0
705
<?php /** * Storgman - Student Organizations Management * Copyright (C) 2014-2016, Dejan Angelov <angelovdejan92@gmail.com> * * This file is part of Storgman. * * Storgman 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. * * Storgman 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 Storgman. If not, see <http://www.gnu.org/licenses/>. * * @package Storgman * @copyright Copyright (C) 2014-2016, Dejan Angelov <angelovdejan92@gmail.com> * @license https://github.com/angelov/storgman/blob/master/LICENSE * @author Dejan Angelov <angelovdejan92@gmail.com> */ namespace Angelov\Storgman\Events\Comments\Http\Controllers; use Angelov\Storgman\Core\Http\Controllers\BaseController; use Angelov\Storgman\Events\Comments\Commands\StoreCommentCommand; use Angelov\Storgman\Events\Comments\Http\Requests\StoreCommentRequest; use Illuminate\Contracts\Auth\Guard; class CommentsController extends BaseController { public function store(StoreCommentRequest $request, Guard $auth) { $eventId = $request->get('event_id'); $authorId = $auth->user()->getId(); $content = $request->get('content'); dispatch(new StoreCommentCommand($authorId, $eventId, $content)); return redirect()->back(); } }
angelov/eestec-platform
app/Events/Comments/Http/Controllers/CommentsController.php
PHP
gpl-3.0
1,706
/* * SQLite.cpp * * Created on: Aug 1, 2012 * Author: lion */ #include "SQLite.h" #include "ifs/db.h" #include "DBResult.h" #include "Buffer.h" namespace fibjs { #define SQLITE_OPEN_FLAGS \ SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | \ SQLITE_OPEN_SHAREDCACHE | SQLITE_OPEN_NOMUTEX result_t db_base::openSQLite(const char *connString, obj_ptr<SQLite_base> &retVal, exlib::AsyncEvent *ac) { if (!ac) return CALL_E_NOSYNC; result_t hr; if (!qstrcmp(connString, "sqlite:", 7)) connString += 7; obj_ptr<SQLite> db = new SQLite(); hr = db->open(connString, ac); if (hr < 0) return hr; retVal = db; return 0; } result_t SQLite::open(const char *file, exlib::AsyncEvent *ac) { if (!ac) return CALL_E_NOSYNC; if (sqlite3_open_v2(file, &m_db, SQLITE_OPEN_FLAGS, 0)) { result_t hr = Runtime::setError(sqlite3_errmsg(m_db)); sqlite3_close(m_db); m_db = NULL; return hr; } m_file = file; return 0; } result_t SQLite::close(exlib::AsyncEvent *ac) { if (!ac) return CALL_E_NOSYNC; if (!m_db) return CALL_E_INVALID_CALL; sqlite3_close(m_db); m_db = NULL; return 0; } result_t SQLite::begin(exlib::AsyncEvent *ac) { if (!ac) return CALL_E_NOSYNC; obj_ptr<DBResult_base> retVal; return execute("BEGIN", 5, retVal, ac); } result_t SQLite::commit(exlib::AsyncEvent *ac) { if (!ac) return CALL_E_NOSYNC; obj_ptr<DBResult_base> retVal; return execute("COMMIT", 6, retVal, ac); } result_t SQLite::rollback(exlib::AsyncEvent *ac) { if (!ac) return CALL_E_NOSYNC; obj_ptr<DBResult_base> retVal; return execute("ROLLBACK", 8, retVal, ac); } int sqlite3_step_sleep(sqlite3_stmt *stmt, int ms) { while (true) { int r = sqlite3_step(stmt); if (r != SQLITE_LOCKED || ms <= 0) return r; sqlite3_sleep(1); ms --; } } #define SQLITE_SLEEP_TIME 10000 result_t SQLite::execute(const char *sql, int sLen, obj_ptr<DBResult_base> &retVal, exlib::AsyncEvent *ac) { if (!ac) return CALL_E_NOSYNC; if (!m_db) return CALL_E_INVALID_CALL; sqlite3_stmt *stmt = 0; const char *pStr1; if (sqlite3_prepare_v2(m_db, sql, sLen, &stmt, &pStr1)) { result_t hr = Runtime::setError(sqlite3_errmsg(m_db)); if (stmt) sqlite3_finalize(stmt); return hr; } if (!stmt) return Runtime::setError("Query was empty"); int columns = sqlite3_column_count(stmt); obj_ptr<DBResult> res; if (columns > 0) { int i; res = new DBResult(columns); for (i = 0; i < columns; i++) { std::string s = sqlite3_column_name(stmt, i); res->setField(i, s); } while (true) { int r = sqlite3_step_sleep(stmt, SQLITE_SLEEP_TIME); if (r == SQLITE_ROW) { res->beginRow(); for (i = 0; i < columns; i++) { Variant v; switch (sqlite3_column_type(stmt, i)) { case SQLITE_NULL: break; case SQLITE_INTEGER: v = (int64_t) sqlite3_column_int64(stmt, i); break; case SQLITE_FLOAT: v = sqlite3_column_double(stmt, i); break; default: const char *type = sqlite3_column_decltype(stmt, i); if (type && (!qstricmp(type, "blob") || !qstricmp(type, "tinyblob") || !qstricmp(type, "mediumblob") || !qstricmp(type, "longblob"))) { const char *data = (const char *) sqlite3_column_blob(stmt, i); int size = sqlite3_column_bytes(stmt, i); v = new Buffer(std::string(data, size)); } else if (type && (!qstricmp(type, "datetime") || !qstricmp(type, "date") || !qstricmp(type, "time"))) { const char *data = (const char *) sqlite3_column_text(stmt, i); int size = sqlite3_column_bytes(stmt, i); v.parseDate(data, size); } else { const char *data = (const char *) sqlite3_column_text(stmt, i); int size = sqlite3_column_bytes(stmt, i); v = std::string(data, size); } break; } res->rowValue(i, v); } res->endRow(); } else if (r == SQLITE_DONE) break; else { sqlite3_finalize(stmt); return Runtime::setError(sqlite3_errmsg(m_db)); } } } else { int r = sqlite3_step_sleep(stmt, SQLITE_SLEEP_TIME); if (r == SQLITE_DONE) res = new DBResult(sqlite3_changes(m_db), sqlite3_last_insert_rowid(m_db)); else { sqlite3_finalize(stmt); return Runtime::setError(sqlite3_errmsg(m_db)); } } sqlite3_finalize(stmt); retVal = res; return 0; } result_t SQLite::execute(const char *sql, obj_ptr<DBResult_base> &retVal, exlib::AsyncEvent *ac) { if (!ac) return CALL_E_NOSYNC; return execute(sql, (int) qstrlen(sql), retVal, ac); } result_t SQLite::execute(const char *sql, const v8::FunctionCallbackInfo<v8::Value> &args, obj_ptr<DBResult_base> &retVal) { std::string str; result_t hr = format(sql, args, str); if (hr < 0) return hr; v8::Local<v8::Value> v = args[args.Length() - 1]; return ac_execute(str.c_str(), retVal); } result_t SQLite::format(const char *sql, const v8::FunctionCallbackInfo<v8::Value> &args, std::string &retVal) { return db_base::format(sql, args, retVal); } result_t SQLite::get_fileName(std::string &retVal) { if (!m_db) return CALL_E_INVALID_CALL; retVal = m_file; return 0; } result_t SQLite::get_timeout(int32_t &retVal) { if (!m_db) return CALL_E_INVALID_CALL; retVal = m_nCmdTimeout; return 0; } result_t SQLite::set_timeout(int32_t newVal) { if (!m_db) return CALL_E_INVALID_CALL; m_nCmdTimeout = newVal; sqlite3_busy_timeout(m_db, m_nCmdTimeout); return 0; } result_t SQLite::backup(const char *fileName, exlib::AsyncEvent *ac) { if (!ac) return CALL_E_NOSYNC; if (!m_db) return CALL_E_INVALID_CALL; int rc; struct sqlite3 *db2 = NULL; sqlite3_backup *pBackup; if (sqlite3_open_v2(fileName, &db2, SQLITE_OPEN_FLAGS, 0)) { result_t hr = Runtime::setError(sqlite3_errmsg(db2)); sqlite3_close(m_db); return hr; } pBackup = sqlite3_backup_init(db2, "main", m_db, "main"); if (pBackup) { do { rc = sqlite3_backup_step(pBackup, 5); if (rc == SQLITE_LOCKED) sqlite3_sleep(1); } while (rc == SQLITE_OK || rc == SQLITE_BUSY || rc == SQLITE_LOCKED); sqlite3_backup_finish(pBackup); } else { result_t hr = Runtime::setError(sqlite3_errmsg(db2)); sqlite3_close(m_db); return hr; } sqlite3_close(m_db); return 0; } } /* namespace fibjs */
jiachenning/fibjs
fibjs/src/SQLite.cpp
C++
gpl-3.0
8,232
/* * Copyright(C) 2016-2017 Blitzker * * 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 "stdafx.h" #include "AssDebug.h" #include "AssFilter.h" #include "AssFilterAutoLoader.h" #include "registry.h" AFAutoLoaderDummyInputPin::AFAutoLoaderDummyInputPin(AssFilterAutoLoader *pFilter, CCritSec *pLock, HRESULT *pResult, LPCWSTR pName) : CBaseInputPin(NAME("DummyInputPin"), pFilter, pLock, pResult, pName) , m_filter(pFilter) { } HRESULT AFAutoLoaderDummyInputPin::CheckMediaType(const CMediaType* mt) { return m_filter->CheckInput(mt); } AssFilterAutoLoader::AssFilterAutoLoader(LPUNKNOWN pUnk, HRESULT* pResult) : CBaseFilter(NAME("AssFilterAutoLoader"), pUnk, &m_pLock, __uuidof(AssFilterAutoLoader)) { #ifdef DEBUG DbgSetModuleLevel(LOG_ERROR, 10); DbgSetModuleLevel(LOG_LOCKING, 10); DbgSetModuleLevel(LOG_TRACE, 10); DbgSetLogFileDesktop(L"AssFilterDbg.Log"); #endif m_pin = std::make_unique<AFAutoLoaderDummyInputPin>(this, &m_pLock, pResult, L""); m_loaded = false; } AssFilterAutoLoader::~AssFilterAutoLoader() { } CUnknown* WINAPI AssFilterAutoLoader::CreateInstance(LPUNKNOWN pUnk, HRESULT* pResult) { try { return new AssFilterAutoLoader(pUnk, pResult); } catch (std::bad_alloc&) { if (pResult) *pResult = E_OUTOFMEMORY; } return nullptr; } CBasePin* AssFilterAutoLoader::GetPin(int n) { if (n == 0) return m_pin.get(); return NULL; } int AssFilterAutoLoader::GetPinCount() { return 1; } STDMETHODIMP AssFilterAutoLoader::JoinFilterGraph(IFilterGraph* pGraph, LPCWSTR pName) { m_loaded = false; if(pGraph) { if (pName) { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::JoinFilterGraph() -> %s joined the graph!", pName)); } IEnumFiltersPtr pEnumFilters; if (SUCCEEDED(pGraph->EnumFilters(&pEnumFilters))) { for (IBaseFilterPtr pBaseFilter; pEnumFilters->Next(1, &pBaseFilter, 0) == S_OK; pBaseFilter = NULL) { //FILTER_INFO pInfo; //pBaseFilter->QueryFilterInfo(&pInfo); //DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::JoinFilterGraph() -> Filter name: %s", pInfo.achName)); //if (pInfo.pGraph != NULL) // pInfo.pGraph->Release(); if (pBaseFilter != (IBaseFilterPtr)this) { CLSID clsid; pBaseFilter->GetClassID(&clsid); if (clsid == __uuidof(AssFilterAutoLoader)) { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::JoinFilterGraph() -> AssFilterAutoLoader already in the graph")); return E_FAIL; } if (clsid == __uuidof(AssFilter)) { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::JoinFilterGraph() -> AssFilter already in the graph")); return E_FAIL; } } } } } return __super::JoinFilterGraph(pGraph, pName); } STDMETHODIMP AssFilterAutoLoader::QueryFilterInfo(FILTER_INFO* pInfo) { CheckPointer(pInfo, E_POINTER); ValidateReadWritePtr(pInfo, sizeof(FILTER_INFO)); HRESULT hr = __super::QueryFilterInfo(pInfo); if (SUCCEEDED(hr)) { wcscpy_s(pInfo->achName, _countof(pInfo->achName) - 1, L"AssFilterModAutoLoader"); } return hr; } bool AssFilterAutoLoader::AutoLoad(IFilterGraph* pGraph) { // Find subtitle pin (MEDIASUBTYPE_ASS or MEDIASUBTYPE_UTF8) on the graph splitter bool have_subtitle_pin = false; IEnumFiltersPtr pEnumFilters; if (SUCCEEDED(pGraph->EnumFilters(&pEnumFilters))) { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::AutoLoad -> Succeeded EnumFilters")); for (IBaseFilterPtr pBaseFilter; pEnumFilters->Next(1, &pBaseFilter, 0) == S_OK; pBaseFilter = NULL) { IFileSourceFilterPtr pFSF; if (SUCCEEDED(pBaseFilter->QueryInterface(IID_PPV_ARGS(&pFSF)))) { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::AutoLoad -> Succeeded QueryInterface")); IEnumPinsPtr pEnumPins; if (SUCCEEDED(pBaseFilter->EnumPins(&pEnumPins))) { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::AutoLoad -> Succeeded EnumPins")); for (IPinPtr pPin; pEnumPins->Next(1, &pPin, 0) == S_OK; pPin = NULL) { IEnumMediaTypesPtr pEnumMediaTypes; if (SUCCEEDED(pPin->EnumMediaTypes(&pEnumMediaTypes))) { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::AutoLoad -> Succeeded EnumMediaTypes")); AM_MEDIA_TYPE* pMediaType = NULL; for (; pEnumMediaTypes->Next(1, &pMediaType, NULL) == S_OK; DeleteMediaType(pMediaType), pMediaType = NULL) { if (pMediaType->majortype == MEDIATYPE_Subtitle && ((pMediaType->subtype == MEDIASUBTYPE_ASS) || (pMediaType->subtype == MEDIASUBTYPE_UTF8) || (pMediaType->subtype == MEDIASUBTYPE_VOBSUB) || (pMediaType->subtype == MEDIASUBTYPE_HDMVSUB))) { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::AutoLoad -> Found subtitle pin on source filter")); have_subtitle_pin = true; break; } } if (pMediaType) DeleteMediaType(pMediaType); } if (have_subtitle_pin) break; } } } if (have_subtitle_pin) break; } } return !have_subtitle_pin; } bool AssFilterAutoLoader::DisableAutoLoad() { HRESULT hr; BOOL bFlag; CRegistry reg = CRegistry(HKEY_CURRENT_USER, ASSFILTER_REGISTRY_KEY, hr, TRUE); if (SUCCEEDED(hr)) { bFlag = reg.ReadBOOL(L"DisableAutoLoad", hr); if (!SUCCEEDED(hr)) return false; } return bFlag ? true : false; } HRESULT AssFilterAutoLoader::CheckInput(const CMediaType* mt) { HRESULT hr = NOERROR; if (!m_loaded) { m_loaded = true; #ifdef DEBUG if (mt->majortype==MEDIATYPE_Video) { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::CheckInput() -> MEDIATYPE_Video")); } else if (mt->majortype==MEDIATYPE_Audio) { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::CheckInput() -> MEDIATYPE_Audio")); } else if (mt->majortype==MEDIATYPE_Subtitle) { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::CheckInput() -> MEDIATYPE_Subtitle")); } else { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::CheckInput() -> Other MEDIATYPE")); } #endif // DEBUG if (mt->majortype == MEDIATYPE_Audio || mt->majortype == MEDIATYPE_Subtitle || mt->majortype == MEDIATYPE_Video) { if (AutoLoad(m_pGraph) && !DisableAutoLoad()) { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::CheckInput() -> Autoload")); IBaseFilterPtr filter; hr = CoCreateInstance(__uuidof(AssFilter), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&filter)); if (FAILED(hr)) { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::CheckInput -> Failed to create AssFilterMod.")); return E_FAIL; } hr = m_pGraph->AddFilter(filter, L"AssFilterMod(AutoLoad)"); if (FAILED(hr)) { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::CheckInput -> Failed to AddFilter.")); return E_FAIL; } if (mt->majortype == MEDIATYPE_Subtitle) { IGraphConfigPtr graph; if (SUCCEEDED(filter->QueryInterface(IID_PPV_ARGS(&graph)))) { hr = graph->AddFilterToCache(filter); if (FAILED(hr)) { DbgLog((LOG_TRACE, 1, L"AssFilterAutoLoader::CheckInput -> Failed to add filter to cache.")); return E_FAIL; } } } } } } return E_FAIL; }
Blitzker/assfiltermod
assfilter/AssFilterAutoLoader.cpp
C++
gpl-3.0
9,496