repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
vividoranje/drupal6 | sites/all/modules/civicrm/CRM/Contribute/Import/Controller.php | 2618 | <?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 3.1 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2010 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2010
* $Id$
*
*/
require_once 'CRM/Core/Controller.php';
class CRM_Contribute_Import_Controller extends CRM_Core_Controller {
/**
* class constructor
*/
function __construct( $title = null, $action = CRM_Core_Action::NONE, $modal = true ) {
parent::__construct( $title, $modal );
// lets get around the time limit issue if possible, CRM-2113
if ( ! ini_get( 'safe_mode' ) ) {
set_time_limit( 0 );
}
require_once 'CRM/Contribute/Import/StateMachine.php';
$this->_stateMachine =& new CRM_Contribute_Import_StateMachine( $this, $action );
// create and instantiate the pages
$this->addPages( $this->_stateMachine, $action );
// add all the actions
$config =& CRM_Core_Config::singleton( );
$this->addActions( $config->uploadDir, array( 'uploadFile' ) );
}
}
| gpl-2.0 |
GeneSurvey/TcgaGSData | src/org/mda/bcb/tcgagsdata/CallFromR.java | 23047 | /*
TcgaGSData Copyright 2014, 2015, 2016 University of Texas MD Anderson Cancer Center
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mda.bcb.tcgagsdata;
import java.io.IOException;
import org.mda.bcb.tcgagsdata.neighbors.FN_Meth27;
import org.mda.bcb.tcgagsdata.neighbors.FN_Meth450;
import org.mda.bcb.tcgagsdata.neighbors.FN_RNASeq;
import org.mda.bcb.tcgagsdata.neighbors.FN_RNASeqV2;
import org.mda.bcb.tcgagsdata.neighbors.GS_HG18;
import org.mda.bcb.tcgagsdata.neighbors.GS_HG19;
import org.mda.bcb.tcgagsdata.retrieve.GeneSynonyms;
import org.mda.bcb.tcgagsdata.retrieve.GetDataClinical;
import org.mda.bcb.tcgagsdata.retrieve.GetDataMatrix;
import org.mda.bcb.tcgagsdata.retrieve.GetImputedNAsMatrix;
import org.mda.bcb.tcgagsdata.retrieve.GetMapGeneEq;
import org.mda.bcb.tcgagsdata.retrieve.GetMatrixPlatform;
import org.mda.bcb.tcgagsdata.retrieve.GetNamesGeneEq;
import org.mda.bcb.tcgagsdata.retrieve.GetTime;
import org.mda.bcb.tcgagsdata.retrieve.MetadataGene;
import org.mda.bcb.tcgagsdata.retrieve.MetadataMir;
import org.mda.bcb.tcgagsdata.retrieve.MetadataPop;
import org.mda.bcb.tcgagsdata.retrieve.MetadataProbe;
import org.mda.bcb.tcgagsdata.retrieve.MetadataTcgaNames;
import org.mda.bcb.tcgagsdata.retrieve.OneToOneUcscHgnc;
/**
*
* @author linux
*/
public class CallFromR
{
protected String mZipFile = null;
public CallFromR(String theZipFile)
{
mZipFile = theZipFile;
}
public String printVersion()
{
String version = TcgaGSData.printVersion();
System.out.println(version);
return version;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected String getValue_internal(String theInternalPath) throws IOException
{
GetTime call = new GetTime(mZipFile);
if (true==call.getTime(theInternalPath))
{
return call.mTime;
}
else
{
return null;
}
}
public String getValue_Time() throws IOException
{
return getValue_internal("combined/time.txt");
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected String [] getNames_internal(String theInternalPath) throws IOException
{
GetNamesGeneEq call = new GetNamesGeneEq(mZipFile);
if (true==call.getNamesGenes(theInternalPath))
{
return call.mGenes;
}
else
{
return null;
}
}
public String [] getNames_Mutations() throws IOException
{
return getNames_internal("combined/mutations/gene_list.tsv");
}
public String [] getNames_RnaSeq2() throws IOException
{
return getNames_internal("combined/illuminahiseq_rnaseqv2_gene/gene_list.tsv");
}
public String [] getNames_RnaSeq() throws IOException
{
return getNames_internal("combined/illuminahiseq_rnaseq_uncGeneRPKM/gene_list.tsv");
}
public String [] getNames_SNP6() throws IOException
{
return getNames_internal("combined/genome_wide_snp_6_hg19nocnvWxy/gene_list.tsv");
}
public String [] getNames_Meth450() throws IOException
{
return getNames_internal("combined/humanmethylation450_level3/gene_list.tsv");
}
public String [] getNames_Meth27() throws IOException
{
return getNames_internal("combined/humanmethylation27_hg19Wxy/gene_list.tsv");
}
public String [] getNames_miRNASeq() throws IOException
{
return getNames_internal("combined/illuminahiseq_mirnaseq_isoform/gene_list.tsv");
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public String [] getMapping_Meth450(String theGene) throws IOException
{
GetMapGeneEq call = new GetMapGeneEq(mZipFile);
return call.getMapping_Meth450(theGene, "data/meth450map.tsv");
}
public String [] getMapping_Meth27(String theGene) throws IOException
{
GetMapGeneEq call = new GetMapGeneEq(mZipFile);
return call.getMapping_Meth27(theGene, "data/meth27map.tsv");
}
public String [] getMappingGeneSymbols_Meth450() throws IOException
{
GetMapGeneEq call = new GetMapGeneEq(mZipFile);
return call.getMappingGeneSymbols_Meth450("data/meth450map.tsv");
}
public String [] getMappingGeneSymbols_Meth27() throws IOException
{
GetMapGeneEq call = new GetMapGeneEq(mZipFile);
return call.getMappingGeneSymbols_Meth27("data/meth27map.tsv");
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public GetDataClinical getDataClinical() throws Exception
{
GetDataClinical call = new GetDataClinical(mZipFile);
if (true==call.getDataClinical("combined/combined_clinical.tsv"))
{
return call;
}
else
{
return null;
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected GetDataMatrix getDataMatrix_internal(String [] theGenes, String theInternalPath, String theNamesInternalPath) throws IOException
{
GetDataMatrix call = new GetDataMatrix(mZipFile);
if (true==call.getDataMatrix(theGenes, theInternalPath, theNamesInternalPath))
{
return call;
}
else
{
return null;
}
}
public GetDataMatrix getDataMatrix_Mutations(String [] theGenes) throws IOException
{
return getDataMatrix_internal(theGenes, "combined/mutations", "combined/mutations/gene_list.tsv");
}
public GetDataMatrix getDataMatrix_RnaSeq2(String [] theGenes) throws IOException
{
return getDataMatrix_internal(theGenes, "combined/illuminahiseq_rnaseqv2_gene", "combined/illuminahiseq_rnaseqv2_gene/gene_list.tsv");
}
public GetDataMatrix getDataMatrix_RnaSeq(String [] theGenes) throws IOException
{
return getDataMatrix_internal(theGenes, "combined/illuminahiseq_rnaseq_uncGeneRPKM", "combined/illuminahiseq_rnaseq_uncGeneRPKM/gene_list.tsv");
}
public GetDataMatrix getDataMatrix_SNP6(String [] theGenes) throws IOException
{
return getDataMatrix_internal(theGenes, "combined/genome_wide_snp_6_hg19nocnvWxy", "combined/genome_wide_snp_6_hg19nocnvWxy/gene_list.tsv");
}
public GetDataMatrix getDataMatrix_Meth450(String [] theGenes) throws IOException
{
return getDataMatrix_internal(theGenes, "combined/humanmethylation450_level3", "combined/humanmethylation450_level3/gene_list.tsv");
}
public GetDataMatrix getDataMatrix_Meth27(String [] theGenes) throws IOException
{
return getDataMatrix_internal(theGenes, "combined/humanmethylation27_hg19Wxy", "combined/humanmethylation27_hg19Wxy/gene_list.tsv");
}
public GetDataMatrix getDataMatrix_miRNASeq(String [] theGenes) throws IOException
{
return getDataMatrix_internal(theGenes, "combined/illuminahiseq_mirnaseq_isoform", "combined/illuminahiseq_mirnaseq_isoform/gene_list.tsv");
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected GetMatrixPlatform getDataMatrixPlatform_internal(String thePlatformInternalPath, String theNamesInternalPath) throws IOException
{
GetMatrixPlatform call = new GetMatrixPlatform(mZipFile);
if (true==call.getDataMatrix(thePlatformInternalPath, theNamesInternalPath))
{
return call;
}
else
{
return null;
}
}
public GetMatrixPlatform getDataMatrix_MutationsPlatform() throws IOException
{
return getDataMatrixPlatform_internal("combined/mutations/platform.tsv", "combined/mutations/gene_list.tsv");
}
public GetMatrixPlatform getDataMatrix_RnaSeq2Platform() throws IOException
{
return getDataMatrixPlatform_internal("combined/illuminahiseq_rnaseqv2_gene/platform.tsv", "combined/illuminahiseq_rnaseqv2_gene/gene_list.tsv");
}
public GetMatrixPlatform getDataMatrix_RnaSeqPlatform() throws IOException
{
return getDataMatrixPlatform_internal("combined/illuminahiseq_rnaseq_uncGeneRPKM/platform.tsv", "combined/illuminahiseq_rnaseq_uncGeneRPKM/gene_list.tsv");
}
public GetMatrixPlatform getDataMatrix_SNP6Platform() throws IOException
{
return getDataMatrixPlatform_internal("combined/genome_wide_snp_6_hg19nocnvWxy/platform.tsv", "combined/genome_wide_snp_6_hg19nocnvWxy/gene_list.tsv");
}
public GetMatrixPlatform getDataMatrix_Meth450Platform() throws IOException
{
return getDataMatrixPlatform_internal("combined/humanmethylation450_level3/platform.tsv", "combined/humanmethylation450_level3/gene_list.tsv");
}
public GetMatrixPlatform getDataMatrix_Meth27Platform() throws IOException
{
return getDataMatrixPlatform_internal("combined/humanmethylation27_hg19Wxy/platform.tsv", "combined/humanmethylation27_hg19Wxy/gene_list.tsv");
}
public GetMatrixPlatform getDataMatrix_miRNASeqPlatform() throws IOException
{
return getDataMatrixPlatform_internal("combined/illuminahiseq_mirnaseq_isoform/platform.tsv", "combined/illuminahiseq_mirnaseq_isoform/gene_list.tsv");
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected GetImputedNAsMatrix getImputedNAsMatrix_internal(String [] theGenes, String theInternalPath, String theNamesInternalPath) throws IOException
{
GetImputedNAsMatrix call = new GetImputedNAsMatrix(mZipFile);
if (true==call.getImputedNAsMatrix(theGenes, theInternalPath, theNamesInternalPath))
{
return call;
}
else
{
return null;
}
}
public GetImputedNAsMatrix getImputedNAsMatrix_RnaSeq2(String [] theGenes) throws IOException
{
return getImputedNAsMatrix_internal(theGenes, "combined/illuminahiseq_rnaseqv2_gene", "combined/illuminahiseq_rnaseqv2_gene/gene_list.tsv");
}
public GetImputedNAsMatrix getImputedNAsMatrix_RnaSeq(String [] theGenes) throws IOException
{
return getImputedNAsMatrix_internal(theGenes, "combined/illuminahiseq_rnaseq_uncGeneRPKM", "combined/illuminahiseq_rnaseq_uncGeneRPKM/gene_list.tsv");
}
public GetImputedNAsMatrix getImputedNAsMatrix_SNP6(String [] theGenes) throws IOException
{
return getImputedNAsMatrix_internal(theGenes, "combined/genome_wide_snp_6_hg19nocnvWxy", "combined/genome_wide_snp_6_hg19nocnvWxy/gene_list.tsv");
}
public GetImputedNAsMatrix getImputedNAsMatrix_Meth450(String [] theGenes) throws IOException
{
return getImputedNAsMatrix_internal(theGenes, "combined/humanmethylation450_level3", "combined/humanmethylation450_level3/gene_list.tsv");
}
public GetImputedNAsMatrix getImputedNAsMatrix_Meth27(String [] theGenes) throws IOException
{
return getImputedNAsMatrix_internal(theGenes, "combined/humanmethylation27_hg19Wxy", "combined/humanmethylation27_hg19Wxy/gene_list.tsv");
}
public GetImputedNAsMatrix getImputedNAsMatrix_miRNASeq(String [] theGenes) throws IOException
{
return getImputedNAsMatrix_internal(theGenes, "combined/illuminahiseq_mirnaseq_isoform", "combined/illuminahiseq_mirnaseq_isoform/gene_list.tsv");
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public MetadataPop getMetadataPop_BarcodeDisease() throws IOException
{
MetadataPop call = new MetadataPop(mZipFile);
if (true==call.getMetadataPop_BarcodeDisease("data/barcode_disease.tsv"))
{
return call;
}
else
{
return null;
}
}
public MetadataPop getMetadataPop_BarcodeSamplecode() throws IOException
{
MetadataPop call = new MetadataPop(mZipFile);
if (true==call.getMetadataPop_BarcodeSamplecode("data/barcode_samplecode.tsv"))
{
return call;
}
else
{
return null;
}
}
public MetadataPop getMetadataPop_PatientDisease() throws IOException
{
MetadataPop call = new MetadataPop(mZipFile);
if (true==call.getMetadataPop_PatientDisease("data/patient_disease.tsv"))
{
return call;
}
else
{
return null;
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public String getMetadataTcga_DatasetName(String theId) throws IOException
{
return new MetadataTcgaNames(mZipFile).getMetadataTcga_DatasetName(theId, "data/dataset_names.tsv");
}
public String getMetadataTcga_DiseaseName(String theId) throws IOException
{
return new MetadataTcgaNames(mZipFile).getMetadataTcga_DiseaseName(theId, "data/disease_names.tsv");
}
public String getMetadataTcga_SampleTypeName(String theId) throws IOException
{
return new MetadataTcgaNames(mZipFile).getMetadataTcga_SampleTypeName(theId, "data/sampletype_names.tsv");
}
////////////////////////////////////////////////////////////////////////////
public String [] getMetadataTcga_Ids_DatasetName() throws IOException
{
return new MetadataTcgaNames(mZipFile).getMetadataTcga_Ids_DatasetName("data/dataset_names.tsv");
}
public String [] getMetadataTcga_Names_DatasetName() throws IOException
{
return new MetadataTcgaNames(mZipFile).getMetadataTcga_Names_DatasetName("data/dataset_names.tsv");
}
public String [] getMetadataTcga_Ids_DiseaseName() throws IOException
{
return new MetadataTcgaNames(mZipFile).getMetadataTcga_Ids_DiseaseName("data/disease_names.tsv");
}
public String [] getMetadataTcga_Names_DiseaseName() throws IOException
{
return new MetadataTcgaNames(mZipFile).getMetadataTcga_Names_DiseaseName("data/disease_names.tsv");
}
public String [] getMetadataTcga_Ids_SampleTypeName() throws IOException
{
return new MetadataTcgaNames(mZipFile).getMetadataTcga_Ids_SampleTypeName("data/sampletype_names.tsv");
}
public String [] getMetadataTcga_Names_SampleTypeName() throws IOException
{
return new MetadataTcgaNames(mZipFile).getMetadataTcga_Names_SampleTypeName("data/sampletype_names.tsv");
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public MetadataGene [] getMetadataList_Mutations(String theStandardizedDataId) throws IOException
{
return new MetadataGene(mZipFile).getMetadataList_HG19(theStandardizedDataId, "data/HG19map.tsv");
}
public MetadataGene [] getMetadataList_RNASeq(String theStandardizedDataId) throws IOException
{
return new MetadataGene(mZipFile).getMetadataList_RNASeq(theStandardizedDataId, "data/rnaseqMap.tsv");
}
public MetadataGene [] getMetadataList_RNASeqV2(String theStandardizedDataId) throws IOException
{
return new MetadataGene(mZipFile).getMetadataList_RNASeqV2(theStandardizedDataId, "data/rnaseqMap.tsv");
}
public MetadataGene [] getMetadataList_HG18(String theStandardizedDataId) throws IOException
{
return new MetadataGene(mZipFile).getMetadataList_HG18(theStandardizedDataId, "data/HG18map.tsv");
}
public MetadataGene [] getMetadataList_HG19(String theStandardizedDataId) throws IOException
{
return new MetadataGene(mZipFile).getMetadataList_HG19(theStandardizedDataId, "data/HG19map.tsv");
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public MetadataProbe getMetadata_Meth27(String theProbe) throws IOException
{
MetadataProbe call = new MetadataProbe(mZipFile);
if (true==call.getMetadata_Meth27(theProbe, "data/meth27map.tsv"))
{
return call;
}
else
{
return null;
}
}
public MetadataProbe getMetadata_Meth450(String theProbe) throws IOException
{
MetadataProbe call = new MetadataProbe(mZipFile);
if (true==call.getMetadata_Meth450(theProbe, "data/meth450map.tsv"))
{
return call;
}
else
{
return null;
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public String [] getMirList() throws IOException
{
return new MetadataMir(mZipFile).getMirList("data/mirHG19map.tsv");
}
public String [] getMimatList() throws IOException
{
return new MetadataMir(mZipFile).getMimatList("data/mirHG19map.tsv");
}
public MetadataMir [] getMetadata_miRNA_mir(String theMirId) throws IOException
{
return new MetadataMir(mZipFile).getMetadata_miRNA_mir(theMirId, "data/mirHG19map.tsv");
}
public MetadataMir [] getMetadata_miRNA_mimat(String theMimatId) throws IOException
{
return new MetadataMir(mZipFile).getMetadata_miRNA_mimat(theMimatId, "data/mirHG19map.tsv");
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public String [] getOneToOne_UCSC_List() throws IOException
{
return new OneToOneUcscHgnc(mZipFile).getOneToOne_UCSC_List("iddata/downloads/oneToOneUcscHgnc.tsv");
}
public String [] getOneToOne_GeneSymbol_List() throws IOException
{
return new OneToOneUcscHgnc(mZipFile).getOneToOne_GeneSymbol_List("iddata/downloads/oneToOneUcscHgnc.tsv");
}
public String getOneToOne_GeneSymbol_UCID(String theId) throws IOException
{
return new OneToOneUcscHgnc(mZipFile).getOneToOne_GeneSymbol_UCID(theId, "iddata/downloads/oneToOneUcscHgnc.tsv");
}
public String getOneToOne_UCID_GeneSymbol(String theId) throws IOException
{
return new OneToOneUcscHgnc(mZipFile).getOneToOne_UCID_GeneSymbol(theId, "iddata/downloads/oneToOneUcscHgnc.tsv");
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public String [] getList_GeneSymbol_Synonym(String theId) throws IOException
{
return new GeneSynonyms(mZipFile).getList_GeneSymbol_Synonym(theId, "iddata/downloads/geneSynonyms.tsv");
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public MetadataGene [] findNeighbors_RnaSeq(long theStart, long theStop, String theChromosome, String theStrand) throws IOException
{
try
{
return new FN_RNASeq(mZipFile).findNeighbors(theStart, theStop, theChromosome, theStrand);
}
catch(Exception exp)
{
exp.printStackTrace(System.err);
throw exp;
}
}
public MetadataGene [] findNeighbors_RnaSeq2(long theStart, long theStop, String theChromosome, String theStrand) throws IOException
{
try
{
return new FN_RNASeqV2(mZipFile).findNeighbors(theStart, theStop, theChromosome, theStrand);
}
catch(Exception exp)
{
exp.printStackTrace(System.err);
throw exp;
}
}
public MetadataProbe [] findNeighbors_Meth450(long theStart, long theStop, String theChromosome) throws IOException
{
try
{
return new FN_Meth450(mZipFile).findNeighbors(theStart, theStop, theChromosome);
}
catch(Exception exp)
{
exp.printStackTrace(System.err);
throw exp;
}
}
public MetadataProbe [] findNeighbors_Meth27(long theStart, long theStop, String theChromosome) throws IOException
{
try
{
return new FN_Meth27(mZipFile).findNeighbors(theStart, theStop, theChromosome);
}
catch(Exception exp)
{
exp.printStackTrace(System.err);
throw exp;
}
}
public MetadataGene [] findNeighbors_HG18(long theStart, long theStop, String theChromosome, String theStrand) throws IOException
{
try
{
return new GS_HG18(mZipFile).findNeighbors(theStart, theStop, theChromosome, theStrand);
}
catch(Exception exp)
{
exp.printStackTrace(System.err);
throw exp;
}
}
public MetadataGene [] findNeighbors_HG19(long theStart, long theStop, String theChromosome, String theStrand) throws IOException
{
try
{
return new GS_HG19(mZipFile).findNeighbors(theStart, theStop, theChromosome, theStrand);
}
catch(Exception exp)
{
exp.printStackTrace(System.err);
throw exp;
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
}
| gpl-2.0 |
phoenix19900219/publish_aar_or_jar_to_local_demo | alib/src/test/java/com/stone/alib/ExampleUnitTest.java | 392 | package com.stone.alib;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | gpl-2.0 |
d7415/merlin | Hooks/sms/__init__.py | 1145 | # This file is part of Merlin.
# Merlin is the Copyright (C)2008,2009,2010 of Robin K. Hansen, Elliot Rosemarine, Andreas Jacobsen.
# Individual portions may be copyright by individual contributors, and
# are included in this collective work with permission of the copyright
# owners.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# List of package modules
__all__ = [
"sms",
"smslog",
"showmethemoney",
"email",
"call",
]
| gpl-2.0 |
sergei-svistunov/gorpc | transport/http_json/swagger_json_test.go | 966 | package http_json
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/sergei-svistunov/gorpc"
"github.com/stretchr/testify/suite"
test_handler1 "github.com/sergei-svistunov/gorpc/test/handler1"
)
// Suite
type SwaggerJSONSute struct {
suite.Suite
server *httptest.Server
}
func (s *SwaggerJSONSute) SetupTest() {
hm := gorpc.NewHandlersManager("github.com/sergei-svistunov/gorpc", gorpc.HandlersManagerCallbacks{})
s.NoError(hm.RegisterHandler(test_handler1.NewHandler()))
s.server = httptest.NewUnstartedServer(NewSwaggerJSONHandler(hm, 0, SwaggerJSONCallbacks{}))
}
func TestRunSwaggerJSONSute(t *testing.T) {
suite.Run(t, new(SwaggerJSONSute))
}
// Tests
func (s *SwaggerJSONSute) TestSwaggerJSON_Call_Success() {
s.server.Start()
defer s.server.Close()
resp, err := http.Get(s.server.URL)
s.NoError(err)
s.Equal(200, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
s.NoError(err)
s.NotEmpty(body)
}
| gpl-2.0 |
freestyleinternet/oxford-cartographers | wp-content/themes/oxford-cartographers/sidebar.php | 2999 | <?php
$result = '';
$subscribeError = '';
if (isset($_POST['email']) AND $_POST['email'] != '')
{
include("lib/class.mailchimp.php");
// in mailchimp this is held in account > api
$api = new MCAPI('89d78b2b770f72e8b9e73052e56494c9-us5');
$merge_vars = array
(
'FNAME' => $_POST['lname'],
'LNAME' => $_POST['fname'],
'MPOSITION' => $_POST['position'],
'MCOMPANY' => $_POST['company'],
'MTEL' => $_POST['mtel'],
'EMAIL' => $_POST['email']
);
// in mailchimp this is held in the lists > settings > list settings and unique api
$result = $api->listSubscribe('ad51084415', $_POST['email'], $merge_vars);
$subscribeError = '';
if ($api->errorCode)
{
$subscribeError = $api->errorMessage;
}
}
?>
<aside>
<div class="sharethisbar"><?php get_template_part( 'templates/partials/inc-socialbuttons'); ?></div>
<div class="signup">
<h2>SIGN UP FOR OUR E-NEWS</h2>
<?php if ($subscribeError == TRUE) { ?><p class="errormsg"><?php echo $subscribeError; ?></p><?php } ?>
<?php if ($subscribeError !=='')
{
?>
<?php
}
?>
<?php if ($result == TRUE) { ?>
<div class="thankyou">
<p>
Thank you for signing up to our mailing list.<br /><br />
A confirmation email has been sent to the address provided.
Please click on the link in that email to confirm your subscription.
</p>
</div>
<?php
}
else
{
?>
<form method="post" action="" />
<label>First Name</label>
<input name="fname" type="text" required>
<label>Last Name</label>
<input name="lname" type="text" required>
<label>Position</label>
<input name="position" type="text">
<label>Company</label>
<input name="company" type="text">
<label>Email</label>
<input name="email" id="email" type="email" required/>
<label>Telephone</label>
<input name="mtel" type="text">
<input class="yellowimg rightarrow" type="submit" value="Submit">
</form>
<?php } ?>
</div>
<div class="col homeblock">
<a href="<?php the_field('link_to_page', 6); ?>">
<img class="absolute" src="<?php the_field('featured_image', 6); ?>">
<h2>OUR PRINCIPLES</h2>
<p><?php the_field('our_principles_introduction_text', 6); ?></p>
<span class="yellowimg thinner">Read More</span>
</a>
</div>
</aside>
| gpl-2.0 |
imadkaf/lsdoEZ4 | lib/ezpdf/classes/ezpdf.php | 44662 | <?php
//
// Created on: <26-Aug-2003 15:15:32 kk>
//
// ## BEGIN COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
// SOFTWARE NAME: eZ Publish Community Project
// SOFTWARE RELEASE: 4.2011
// COPYRIGHT NOTICE: Copyright (C) 1999-2011 eZ Systems AS
// SOFTWARE LICENSE: GNU General Public License v2.0
// NOTICE: >
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2.0 of the GNU General
// Public License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of version 2.0 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.
// ## END COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
//
/*! \file
*/
/*!
\defgroup eZPDF PDF generator library
*/
/*!
\class eZPDF ezpdf.php
\ingroup eZPDF
\brief eZPDF provides template operators for dealing with pdf generation
*/
class eZPDF
{
/*!
Initializes the object with the name $name, default is "attribute".
*/
function eZPDF( $name = "pdf" )
{
$this->Operators = array( $name );
$this->Config = eZINI::instance( 'pdf.ini' );
}
/*!
Returns the template operators.
*/
function operatorList()
{
return $this->Operators;
}
/*!
See eZTemplateOperator::namedParameterList()
*/
function namedParameterList()
{
return array( 'operation' => array( 'type' => 'string',
'required' => true,
'default' => '' ) );
}
/*!
Display the variable.
*/
function modify( $tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters )
{
$config = eZINI::instance( 'pdf.ini' );
switch ( $namedParameters['operation'] )
{
case 'toc':
{
$operatorValue = '<C:callTOC';
if ( count( $operatorParameters ) > 1 )
{
$params = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
$operatorValue .= isset( $params['size'] ) ? ':size:'. implode(',', $params['size'] ) : '';
$operatorValue .= isset( $params['dots'] ) ? ':dots:'. $params['dots'] : '';
$operatorValue .= isset( $params['contentText'] ) ? ':contentText:'. $params['contentText'] : '';
$operatorValue .= isset( $params['indent'] ) ? ':indent:'. implode(',', $params['indent'] ) : '';
}
$operatorValue .= '>';
eZDebug::writeNotice( 'PDF: Generating TOC', __METHOD__ );
} break;
case 'set_font':
{
$params = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
$operatorValue = '<ezCall:callFont';
foreach ( $params as $key => $value )
{
if ( $key == 'colorCMYK' )
{
$operatorValue .= ':cmyk:' . implode( ',', $value );
}
else if ( $key == 'colorRGB' )
{
$operatorValue .= ':cmyk:' . implode( ',', eZMath::rgbToCMYK2( $value[0]/255,
$value[1]/255,
$value[2]/255 ) );
}
else
{
$operatorValue .= ':' . $key . ':' . $value;
}
}
$operatorValue .= '>';
eZDebug::writeNotice( 'PDF: Changed font.' );
} break;
case 'table':
{
$operatorValue = '<ezGroup:callTable';
if ( count( $operatorParameters > 2 ) )
{
$tableSettings = $tpl->elementValue( $operatorParameters[2], $rootNamespace, $currentNamespace );
if ( is_array( $tableSettings ) )
{
foreach( array_keys( $tableSettings ) as $key )
{
switch( $key )
{
case 'headerCMYK':
case 'cellCMYK':
case 'textCMYK':
case 'titleCellCMYK':
case 'titleTextCMYK':
{
$operatorValue .= ':' . $key . ':' . implode( ',', $tableSettings[$key] );
} break;
default:
{
$operatorValue .= ':' . $key . ':' . $tableSettings[$key];
} break;
}
}
}
}
$operatorValue .= '>';
$rows = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
$rows = str_replace( array( ' ', "\t", "\r\n", "\n" ),
'',
$rows );
$httpCharset = eZTextCodec::internalCharset();
$outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
? $config->variable( 'PDFGeneral', 'OutputCharset' )
: 'iso-8859-1';
$codec = eZTextCodec::instance( $httpCharset, $outputCharset );
// Convert current text to $outputCharset (by default iso-8859-1)
$rows = $codec->convertString( $rows );
$operatorValue .= urlencode( $rows );
$operatorValue .= '</ezGroup:callTable><C:callNewLine>';
eZDebug::writeNotice( 'PDF: Added table to PDF', __METHOD__ );
} break;
case 'header':
{
$header = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
$header['text'] = str_replace( array( ' ', "\t", "\r\n", "\n" ),
'',
$header['text'] );
$operatorValue = '<ezCall:callHeader:level:'. $header['level'] .':size:'. $header['size'];
if ( isset( $header['align'] ) )
{
$operatorValue .= ':justification:'. $header['align'];
}
if ( isset( $header['font'] ) )
{
$operatorValue .= ':fontName:'. $header['font'];
}
$operatorValue .= ':label:'. rawurlencode( $header['text'] );
$operatorValue .= '><C:callNewLine>'. $header['text'] .'</ezCall:callHeader><C:callNewLine>';
eZDebug::writeNotice( 'PDF: Added header: '. $header['text'] .', size: '. $header['size'] .
', align: '. $header['align'] .', level: '. $header['level'],
__METHOD__ );
} break;
case 'create':
{
$this->createPDF();
} break;
case 'new_line':
case 'newline': // Deprecated
{
$operatorValue = '<C:callNewLine>';
} break;
case 'new_page':
case 'newpage': // Deprecated
{
$operatorValue = '<C:callNewPage><C:callNewLine>';
eZDebug::writeNotice( 'PDF: New page', __METHOD__ );
} break;
case 'image':
{
$image = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
$width = isset( $image['width'] ) ? $image['width']: 100;
$height = isset( $image['height'] ) ? $image['height']: 100;
$operatorValue = '<C:callImage:src:'. rawurlencode( $image['src'] ) .':width:'. $width .':height:'. $height;
if ( isset( $image['static'] ) )
{
$operatorValue .= ':static:' . $image['static'];
}
if ( isset ( $image['x'] ) )
{
$operatorValue .= ':x:' . $image['x'];
}
if ( isset( $image['y'] ) )
{
$operatorValue .= ':y:' . $image['y'];
}
if ( isset( $image['dpi'] ) )
{
$operatorValue .= ':dpi:' . $image['dpi'];
}
if ( isset( $image['align'] ) ) // left, right, center, full
{
$operatorValue .= ':align:' . $image['align'];
}
$operatorValue .= '>';
eZDebug::writeNotice( 'PDF: Added Image '.$image['src'].' to PDF file', __METHOD__ );
} break;
case 'anchor':
{
$name = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
$operatorValue = '<C:callAnchor:'. $name['name'] .':FitH:>';
eZDebug::writeNotice( 'PDF: Added anchor: '.$name['name'], __METHOD__ );
} break;
case 'link': // external link
{
$link = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
$link['text'] = str_replace( '"',
'"',
$link['text'] );
$operatorValue = '<c:alink:'. rawurlencode( $link['url'] ) .'>'. $link['text'] .'</c:alink>';
eZDebug::writeNotice( 'PDF: Added link: '. $link['text'] .', url: '.$link['url'], __METHOD__ );
} break;
case 'stream':
{
$this->PDF->ezStream();
}
case 'close':
{
$filename = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
eZDir::mkdir( eZDir::dirpath( $filename ), false, true );
$file = eZClusterFileHandler::instance( $filename );
$file->storeContents( $this->PDF->ezOutput(), 'viewcache', 'pdf' );
eZDebug::writeNotice( 'PDF file closed and saved to '. $filename, __METHOD__ );
} break;
case 'strike':
{
$text = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
$operatorValue = '<c:strike>'. $text .'</c:strike>';
eZDebug::writeNotice( 'Striked text added to PDF: "'. $text .'"', __METHOD__ );
} break;
/* usage : execute/add text to pdf file, pdf(execute,<text>) */
case 'execute':
{
$text = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
if ( count ( $operatorParameters ) > 2 )
{
$options = $tpl->elementValue( $operatorParameters[2], $rootNamespace, $currentNamespace );
$size = isset( $options['size'] ) ? $options['size'] : $config->variable( 'PDFGeneral', 'Format' );
$orientation = isset( $options['orientation'] ) ? $options['orientation'] : $config->variable( 'PDFGeneral', 'Orientation' );
$this->createPDF( $size, $orientation );
}
else
{
$this->createPDF( $config->variable( 'PDFGeneral', 'Format' ), $config->variable( 'PDFGeneral', 'Orientation' ) );
}
$text = str_replace( array( ' ', "\n", "\t" ), '', $text );
$httpCharset = eZTextCodec::internalCharset();
$outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
? $config->variable( 'PDFGeneral', 'OutputCharset' )
: 'iso-8859-1';
$codec = eZTextCodec::instance( $httpCharset, $outputCharset );
// Convert current text to $outputCharset (by default iso-8859-1)
$text = $codec->convertString( $text );
$this->PDF->ezText( $text );
eZDebug::writeNotice( 'Execute text in PDF, length: "'. strlen( $text ) .'"', __METHOD__ );
} break;
case 'page_number':
case 'pageNumber':
{
$numberDesc = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
if ( isset( $numberDesc['identifier'] ) )
{
$identifier = $numberDesc['identifier'];
}
else
{
$identifier = 'main';
}
if ( isset( $numberDesc['start'] ) )
{
$operatorValue = '<C:callStartPageCounter:start:'. $numberDesc['start'] .':identifier:'. $identifier .'>';
}
else if ( isset( $numberDesc['stop'] ) )
{
$operatorValue = '<C:callStartPageCounter:stop:1:identifier:'. $identifier .'>';
}
} break;
/* usage {pdf( line, hash( x1, <x>, y1, <y>, x2, <x2>, y2, <y2>, pages, <all|current>, thickness, <1..100>, ) )} */
case 'line':
{
$lineDesc = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
if ( isset( $lineDesc['pages']) and
$lineDesc['pages'] == 'all' )
{
$operatorValue = '<ezGroup:callLine';
}
else
{
$operatorValue = '<C:callDrawLine';
}
$operatorValue .= ':x1:' . $lineDesc['x1'];
$operatorValue .= ':x2:' . $lineDesc['x2'];
$operatorValue .= ':y1:' . $lineDesc['y1'];
$operatorValue .= ':y2:' . $lineDesc['y2'];
$operatorValue .= ':thickness:' . ( isset( $lineDesc['thickness'] ) ? $lineDesc['thickness'] : '1' );
$operatorValue .= '>';
if ( $lineDesc['pages'] == 'all' )
{
$operatorValue .= '___</ezGroup:callLine>';
}
return $operatorValue;
} break;
case 'footer_block':
case 'header_block':
{
$frameDesc = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
$operatorValue = '<ezGroup:callBlockFrame';
$operatorValue .= ':location:'. $namedParameters['operation'];
$operatorValue .= '>';
if ( isset( $frameDesc['block_code'] ) )
{
$httpCharset = eZTextCodec::internalCharset();
$outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
? $config->variable( 'PDFGeneral', 'OutputCharset' )
: 'iso-8859-1';
$codec = eZTextCodec::instance( $httpCharset, $outputCharset );
// Convert current text to $outputCharset (by default iso-8859-1)
$frameDesc['block_code'] = $codec->convertString( $frameDesc['block_code'] );
$operatorValue .= urlencode( $frameDesc['block_code'] );
}
$operatorValue .= '</ezGroup:callBlockFrame>';
eZDebug::writeNotice( 'PDF: Added Block '.$namedParameters['operation'] .': '.$operatorValue, __METHOD__ );
return $operatorValue;
} break;
/* deprecated */
case 'footer':
case 'frame_header':
{
$frameDesc = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
$operatorValue = '<ezGroup:callFrame';
$operatorValue .= ':location:'. $namedParameters['operation'];
if ( $namedParameters['operation'] == 'footer' )
{
$frameType = 'Footer';
}
else if( $namedParameters['operation'] == 'frame_header' )
{
$frameType = 'Header';
}
if ( isset( $frameDesc['align'] ) )
{
$operatorValue .= ':justification:'. $frameDesc['align'];
}
if ( isset( $frameDesc['page'] ) )
{
$operatorValue .= ':page:'. $frameDesc['page'];
}
else
{
$operatorValue .= ':page:all';
}
$operatorValue .= ':newline:' . ( isset( $frameDesc['newline'] ) ? $frameDesc['newline'] : 0 );
$operatorValue .= ':pageOffset:';
if ( isset( $frameDesc['pageOffset'] ) )
{
$operatorValue .= $frameDesc['pageOffset'];
}
else
{
$operatorValue .= $this->Config->variable( $frameType, 'PageOffset' );
}
if ( isset( $frameDesc['size'] ) )
{
$operatorValue .= ':size:'. $frameDesc['size'];
}
if ( isset( $frameDesc['font'] ) )
{
$operatorValue .= ':font:'. $frameDesc['font'];
}
$operatorValue .= '>';
if ( isset( $frameDesc['text'] ) )
{
$httpCharset = eZTextCodec::internalCharset();
$outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
? $config->variable( 'PDFGeneral', 'OutputCharset' )
: 'iso-8859-1';
$codec = eZTextCodec::instance( $httpCharset, $outputCharset );
// Convert current text to $outputCharset (by default iso-8859-1)
$frameDesc['text'] = $codec->convertString( $frameDesc['text'] );
$operatorValue .= urlencode( $frameDesc['text'] );
}
$operatorValue .= '</ezGroup:callFrame>';
if ( isset( $frameDesc['margin'] ) )
{
$operatorValue .= '<C:callFrameMargins';
$operatorValue .= ':identifier:'. $namedParameters['operation'];
$operatorValue .= ':topMargin:';
if ( isset( $frameDesc['margin']['top'] ) )
{
$operatorValue .= $frameDesc['margin']['top'];
}
else
{
$operatorValue .= $this->Config->variable( $frameType, 'TopMargin' );
}
$operatorValue .= ':bottomMargin:';
if ( isset( $frameDesc['margin']['bottom'] ) )
{
$operatorValue .= $frameDesc['margin']['bottom'];
}
else
{
$operatorValue .= $this->Config->variable( $frameType, 'BottomMargin' );
}
$operatorValue .= ':leftMargin:';
if ( isset( $frameDesc['margin']['left'] ) )
{
$operatorValue .= $frameDesc['margin']['left'];
}
else
{
$operatorValue .= $this->Config->variable( $frameType, 'LeftMargin' );
}
$operatorValue .= ':rightMargin:';
if ( isset( $frameDesc['margin']['right'] ) )
{
$operatorValue .= $frameDesc['margin']['right'];
}
else
{
$operatorValue .= $this->Config->variable( $frameType, 'RightMargin' );
}
$operatorValue .= ':height:';
if ( isset( $frameDesc['margin']['height'] ) )
{
$operatorValue .= $frameDesc['margin']['height'];
}
else
{
$operatorValue .= $this->Config->variable( $frameType, 'Height' );
}
$operatorValue .= '>';
}
if ( isset( $frameDesc['line'] ) )
{
$operatorValue .= '<C:callFrameLine';
$operatorValue .= ':location:'. $namedParameters['operation'];
$operatorValue .= ':margin:';
if( isset( $frameDesc['line']['margin'] ) )
{
$operatorValue .= $frameDesc['line']['margin'];
}
else
{
$operatorValue .= $this->Config->variable( $frameType, 'LineMargin' );
}
if ( isset( $frameDesc['line']['leftMargin'] ) )
{
$operatorValue .= ':leftMargin:'. $frameDesc['line']['leftMargin'];
}
if ( isset( $frameDesc['line']['rightMargin'] ) )
{
$operatorValue .= ':rightMargin:'. $frameDesc['line']['rightMargin'];
}
$operatorValue .= ':pageOffset:';
if ( isset( $frameDesc['line']['pageOffset'] ) )
{
$operatorValue .= $frameDesc['line']['pageOffset'];
}
else
{
$operatorValue .= $this->Config->variable( $frameType, 'PageOffset' );
}
$operatorValue .= ':page:';
if ( isset( $frameDesc['line']['page'] ) )
{
$operatorValue .= $frameDesc['line']['page'];
}
else
{
$operatorValue .= $this->Config->variable( $frameType, 'Page' );
}
$operatorValue .= ':thickness:';
if ( isset( $frameDesc['line']['thickness'] ) )
{
$operatorValue .= $frameDesc['line']['thickness'];
}
else
{
$operatorValue .= $this->Config->variable( $frameType, 'LineThickness' );
}
$operatorValue .= '>';
}
eZDebug::writeNotice( 'PDF: Added frame '.$frameType .': '.$operatorValue, __METHOD__ );
} break;
case 'frontpage':
{
$pageDesc = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
$align = isset( $pageDesc['align'] ) ? $pageDesc['align'] : 'center';
$text = isset( $pageDesc['text'] ) ? $pageDesc['text'] : '';
$top_margin = isset( $pageDesc['top_margin'] ) ? $pageDesc['top_margin'] : 100;
$operatorValue = '<ezGroup:callFrontpage:justification:'. $align .':top_margin:'. $top_margin;
if ( isset( $pageDesc['size'] ) )
{
$operatorValue .= ':size:'. $pageDesc['size'];
}
$text = str_replace( array( ' ', "\t", "\r\n", "\n" ),
'',
$text );
$httpCharset = eZTextCodec::internalCharset();
$outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
? $config->variable( 'PDFGeneral', 'OutputCharset' )
: 'iso-8859-1';
$codec = eZTextCodec::instance( $httpCharset, $outputCharset );
// Convert current text to $outputCharset (by default iso-8859-1)
$text = $codec->convertString( $text );
$operatorValue .= '>'. urlencode( $text ) .'</ezGroup:callFrontpage>';
eZDebug::writeNotice( 'Added content to frontpage: '. $operatorValue, __METHOD__ );
} break;
/* usage: pdf(set_margin( hash( left, <left_margin>,
right, <right_margin>,
x, <x offset>,
y, <y offset> )))
*/
case 'set_margin':
{
$operatorValue = '<C:callSetMargin';
$options = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
foreach( array_keys( $options ) as $key )
{
$operatorValue .= ':' . $key . ':' . $options[$key];
}
$operatorValue .= '>';
eZDebug::writeNotice( 'Added new margin/offset setup: ' . $operatorValue );
return $operatorValue;
} break;
/* add keyword to pdf document */
case 'keyword':
{
$text = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
$text = str_replace( array( ' ', "\n", "\t" ), '', $text );
$httpCharset = eZTextCodec::internalCharset();
$outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
? $config->variable( 'PDFGeneral', 'OutputCharset' )
: 'iso-8859-1';
$codec = eZTextCodec::instance( $httpCharset, $outputCharset );
// Convert current text to $outputCharset (by default iso-8859-1)
$text = $codec->convertString( $text );
$operatorValue = '<C:callKeyword:'. rawurlencode( $text ) .'>';
} break;
/* add Keyword index to pdf document */
case 'createIndex':
case 'create_index':
{
$operatorValue = '<C:callIndex>';
eZDebug::writeNotice( 'Adding Keyword index to PDF', __METHOD__ );
} break;
case 'ul':
{
$text = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
if ( count( $operatorParameters ) > 2 )
{
$params = $tpl->elementValue( $operatorParameters[2], $rootNamespace, $currentNamespace );
}
else
{
$params = array();
}
if ( isset( $params['rgb'] ) )
{
$params['rgb'] = eZMath::normalizeColorArray( $params['rgb'] );
$params['cmyk'] = eZMath::rgbToCMYK2( $params['rgb'][0]/255,
$params['rgb'][1]/255,
$params['rgb'][2]/255 );
}
if ( !isset( $params['cmyk'] ) )
{
$params['cmyk'] = eZMath::rgbToCMYK2( 0, 0, 0 );
}
if ( !isset( $params['radius'] ) )
{
$params['radius'] = 2;
}
if ( !isset ( $params['pre_indent'] ) )
{
$params['pre_indent'] = 0;
}
if ( !isset ( $params['indent'] ) )
{
$params['indent'] = 2;
}
if ( !isset ( $params['yOffset'] ) )
{
$params['yOffset'] = -1;
}
$operatorValue = '<C:callCircle' .
':pages:current' .
':x:-1' .
':yOffset:' . $params['yOffset'] .
':y:-1' .
':indent:' . $params['indent'] .
':pre_indent:' . $params['pre_indent'] .
':radius:' . $params['radius'] .
':cmyk:' . implode( ',', $params['cmyk'] ) .
'>';
$operatorValue .= '<C:callSetMargin' .
':delta_left:' . ( $params['indent'] + $params['radius'] * 2 + $params['pre_indent'] ) .
'>';
$operatorValue .= $text;
$operatorValue .= '<C:callSetMargin' .
':delta_left:' . -1 * ( $params['indent'] + $params['radius'] * 2 + $params['pre_indent'] ) .
'>';
} break;
case 'filled_circle':
{
$operatorValue = '';
$options = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
if ( !isset( $options['pages'] ) )
{
$options['pages'] = 'current';
}
if ( !isset( $options['x'] ) )
{
$options['x'] = -1;
}
if ( !isset( $options['y'] ) )
{
$options['y'] = -1;
}
if ( isset( $options['rgb'] ) )
{
$options['rgb'] = eZMath::normalizeColorArray( $options['rgb'] );
$options['cmyk'] = eZMath::rgbToCMYK2( $options['rgb'][0]/255,
$options['rgb'][1]/255,
$options['rgb'][2]/255 );
}
$operatorValue = '<C:callCircle' .
':pages:' . $options['pages'] .
':x:' . $options['x'] .
':y:' . $options['y'] .
':radius:' . $options['radius'];
if ( isset( $options['cmyk'] ) )
{
$operatorValue .= ':cmyk:' . implode( ',', $options['cmyk'] );
}
$operatorValue .= '>';
eZDebug::writeNotice( 'PDF Added circle: ' . $operatorValue );
return $operatorValue;
} break;
case 'rectangle':
{
$operatorValue = '';
$options = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
if ( !isset( $options['pages'] ) )
{
$options['pages'] = 'current';
}
if ( !isset( $options['line_width'] ) )
{
$options['line_width'] = 1;
}
if ( !isset( $options['round_corner'] ) )
{
$options['round_corner'] = false;
}
$operatorValue = '<C:callRectangle';
foreach ( $options as $key => $value )
{
if ( $key == 'rgb' )
{
$options['rgb'] = eZMath::normalizeColorArray( $options['rgb'] );
$operatorValue .= ':cmyk:' . implode( ',', eZMath::rgbToCMYK2( $options['rgb'][0]/255,
$options['rgb'][1]/255,
$options['rgb'][2]/255 ) );
}
else if ( $key == 'cmyk' )
{
$operatorValue .= ':cmyk:' . implode( ',', $value );
}
else
{
$operatorValue .= ':' . $key . ':' . $value;
}
}
$operatorValue .= '>';
eZDebug::writeNotice( 'PDF Added rectangle: ' . $operatorValue );
return $operatorValue;
} break;
/* usage: pdf( filled_rectangle, hash( 'x', <x offset>, 'y' => <y offset>, 'width' => <width>, 'height' => <height>,
'pages', <'all'|'current'|odd|even>, (supported, current)
'rgb', array( <r>, <g>, <b> ),
'cmyk', array( <c>, <m>, <y>, <k> ),
'rgbTop', array( <r>, <b>, <g> ),
'rgbBottom', array( <r>, <b>, <g> ),
'cmykTop', array( <c>, <m>, <y>, <k> ),
'cmykBottom', array( <c>, <m>, <y>, <k> ) ) ) */
case 'filled_rectangle':
{
$operatorValue = '';
$options = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
if ( !isset( $options['pages'] ) )
{
$options['pages'] = 'current';
}
if ( isset( $options['rgb'] ) )
{
$options['rgb'] = eZMath::normalizeColorArray( $options['rgb'] );
$options['cmyk'] = eZMath::rgbToCMYK2( $options['rgb'][0]/255,
$options['rgb'][1]/255,
$options['rgb'][2]/255 );
}
if ( isset( $options['cmyk'] ) )
{
$options['cmykTop'] = $options['cmyk'];
$options['cmykBottom'] = $options['cmyk'];
}
if ( !isset( $options['cmykTop'] ) )
{
if ( isset( $options['rgbTop'] ) )
{
$options['rgbTop'] = eZMath::normalizeColorArray( $options['rgbTop'] );
$options['cmykTop'] = eZMath::rgbToCMYK2( $options['rgbTop'][0]/255,
$options['rgbTop'][1]/255,
$options['rgbTop'][2]/255 );
}
else
{
$options['cmykTop'] = eZMath::rgbToCMYK2( 0, 0, 0 );
}
}
if ( !isset( $options['cmykBottom'] ) )
{
if ( isset( $options['rgbBottom'] ) )
{
$options['rgbBottom'] = eZMath::normalizeColorArray( $options['rgbBottom'] );
$options['cmykBottom'] = eZMath::rgbToCMYK2( $options['rgbBottom'][0]/255,
$options['rgbBottom'][1]/255,
$options['rgbBottom'][2]/255 );
}
else
{
$options['cmykBottom'] = eZMath::rgbToCMYK2( 0, 0, 0 );
}
}
if ( !isset( $options['pages'] ) )
{
$options['pages'] = 'current';
}
$operatorValue = '<C:callFilledRectangle' .
':pages:' . $options['pages'] .
':x:' . $options['x'] .
':y:' . $options['y'] .
':width:' . $options['width'] .
':height:' . $options['height'] .
':cmykTop:' . implode( ',', $options['cmykTop'] ) .
':cmykBottom:' . implode( ',', $options['cmykBottom'] ) .
'>';
eZDebug::writeNotice( 'Added rectangle: ' . $operatorValue );
} break;
/* usage : pdf(text, <text>, array( 'font' => <fontname>, 'size' => <fontsize> )) */
case 'text':
{
$text = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
$operatorValue = '';
$changeFont = false;
if ( count( $operatorParameters ) >= 3)
{
$textSettings = $tpl->elementValue( $operatorParameters[2], $rootNamespace, $currentNamespace );
if ( isset( $textSettings ) )
{
$operatorValue .= '<ezCall:callText';
$changeFont = true;
if ( isset( $textSettings['font'] ) )
{
$operatorValue .= ':font:'. $textSettings['font'];
}
if ( isset( $textSettings['size'] ) )
{
$operatorValue .= ':size:'. $textSettings['size'];
}
if ( isset( $textSettings['align'] ) )
{
$operatorValue .= ':justification:'. $textSettings['align'];
}
if ( isset( $textSettings['rgb'] ) )
{
$textSettings['cmyk'] = eZMath::rgbToCMYK2( $textSettings['rgb'][0]/255,
$textSettings['rgb'][1]/255,
$textSettings['rgb'][2]/255 );
}
if ( isset( $textSettings['cmyk'] ) )
{
$operatorValue .= ':cmyk:' . implode( ',', $textSettings['cmyk'] );
}
$operatorValue .= '>';
}
}
$operatorValue .= $text;
if ( $changeFont )
{
$operatorValue .= '</ezCall:callText>';
}
} break;
case 'text_box':
{
$parameters = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
$operatorValue = '<ezGroup:callTextBox';
foreach( array_keys( $parameters ) as $key )
{
if ( $key != 'text' )
{
$operatorValue .= ':' . $key . ':' . urlencode( $parameters[$key] );
}
}
$httpCharset = eZTextCodec::internalCharset();
$outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
? $config->variable( 'PDFGeneral', 'OutputCharset' )
: 'iso-8859-1';
$codec = eZTextCodec::instance( $httpCharset, $outputCharset );
// Convert current text to $outputCharset (by default iso-8859-1)
$parameters['text'] = $codec->convertString( $parameters['text'] );
$operatorValue .= '>';
$operatorValue .= urlencode( $parameters['text'] );
$operatorValue .= '</ezGroup:callTextBox>';
return $operatorValue;
} break;
case 'text_frame':
{
$text = $tpl->elementValue( $operatorParameters[1], $rootNamespace, $currentNamespace );
$operatorValue = '';
$changeFont = false;
if ( count( $operatorParameters ) >= 3)
{
$textSettings = $tpl->elementValue( $operatorParameters[2], $rootNamespace, $currentNamespace );
if ( isset( $textSettings ) )
{
$operatorValue .= '<ezGroup:callTextFrame';
$changeFont = true;
foreach ( array_keys( $textSettings ) as $key ) //settings, padding (left, right, top, bottom), textcmyk, framecmyk
{
if ( $key == 'frameCMYK' )
{
$operatorValue .= ':frameCMYK:' . implode( ',', $textSettings['frameCMYK'] );
}
else if ( $key == 'frameRGB' )
{
$operatorValue .= ':frameCMYK:' . implode( ',', eZMath::rgbToCMYK2( $textSettings['frameRGB'][0]/255,
$textSettings['frameRGB'][1]/255,
$textSettings['frameRGB'][2]/255 ) );
}
else if ( $key == 'textCMYK' )
{
$operatorValue .= ':textCMYK:' . implode( ',', $textSettings['textCMYK'] );
}
else if ( $key == 'textRGB' )
{
$operatorValue .= ':textCMYK:' . implode( ',', eZMath::rgbToCMYK2( $textSettings['textRGB'][0]/255,
$textSettings['textRGB'][1]/255,
$textSettings['textRGB'][2]/255 ) );
}
else
{
$operatorValue .= ':' . $key . ':' . $textSettings[$key];
}
}
$httpCharset = eZTextCodec::internalCharset();
$outputCharset = $config->hasVariable( 'PDFGeneral', 'OutputCharset' )
? $config->variable( 'PDFGeneral', 'OutputCharset' )
: 'iso-8859-1';
$codec = eZTextCodec::instance( $httpCharset, $outputCharset );
// Convert current text to $outputCharset (by default iso-8859-1)
$text = $codec->convertString( $text );
$operatorValue .= '>' . urlencode( $text ) . '</ezGroup::callTextFrame>';
}
}
eZDebug::writeNotice( 'Added TextFrame: ' . $operatorValue );
} break;
default:
{
eZDebug::writeError( 'PDF operation "'. $namedParameters['operation'] .'" undefined', __METHOD__ );
}
}
}
/*
\private
Create PDF object
*/
function createPDF( $paper = 'a4', $orientation = 'portrait' )
{
$this->PDF = new eZPDFTable( $paper, $orientation );
$this->PDF->selectFont( 'lib/ezpdf/classes/fonts/Helvetica' );
eZDebug::writeNotice( 'PDF: File created' );
}
/// The array of operators, used for registering operators
public $Operators;
public $PDF;
public $Config;
}
?>
| gpl-2.0 |
w2/ctb | modules/mod_login/tmpl/default.php | 5755 | <?php
/**
* @package Joomla.Site
* @subpackage mod_login
*
* @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
require_once JPATH_SITE . '/components/com_users/helpers/route.php';
JHtml::_('behavior.keepalive');
JHtml::_('bootstrap.tooltip');
?>
<form action="<?php echo JRoute::_('index.php', true, $params->get('usesecure')); ?>" method="post" id="login-form" class="form-inline">
<?php if ($params->get('pretext')) : ?>
<div class="pretext">
<p><?php echo $params->get('pretext'); ?></p>
</div>
<?php endif; ?>
<div class="userdata">
<div id="form-login-username" class="control-group">
<div class="controls">
<?php if (!$params->get('usetext')) : ?>
<div class="input-prepend">
<span class="add-on">
<span class="icon-user hasTooltip" title="<?php echo JText::_('MOD_LOGIN_VALUE_USERNAME') ?>"></span>
<label for="modlgn-username" class="element-invisible"><?php echo JText::_('MOD_LOGIN_VALUE_USERNAME'); ?></label>
</span>
<input id="modlgn-username" type="text" name="username" class="input-small" tabindex="0" size="18" placeholder="<?php echo JText::_('MOD_LOGIN_VALUE_USERNAME') ?>" />
</div>
<?php else: ?>
<label for="modlgn-username"><?php echo JText::_('MOD_LOGIN_VALUE_USERNAME') ?></label>
<input id="modlgn-username" type="text" name="username" class="input-small" tabindex="0" size="18" placeholder="<?php echo JText::_('MOD_LOGIN_VALUE_USERNAME') ?>" />
<?php endif; ?>
</div>
</div>
<div id="form-login-password" class="control-group">
<div class="controls">
<?php if (!$params->get('usetext')) : ?>
<div class="input-prepend">
<span class="add-on">
<span class="icon-lock hasTooltip" title="<?php echo JText::_('JGLOBAL_PASSWORD') ?>">
</span>
<label for="modlgn-passwd" class="element-invisible"><?php echo JText::_('JGLOBAL_PASSWORD'); ?>
</label>
</span>
<input id="modlgn-passwd" type="password" name="password" class="input-small" tabindex="0" size="18" placeholder="<?php echo JText::_('JGLOBAL_PASSWORD') ?>" />
</div>
<?php else: ?>
<label for="modlgn-passwd"><?php echo JText::_('JGLOBAL_PASSWORD') ?></label>
<input id="modlgn-passwd" type="password" name="password" class="input-small" tabindex="0" size="18" placeholder="<?php echo JText::_('JGLOBAL_PASSWORD') ?>" />
<?php endif; ?>
</div>
</div>
<?php if (count($twofactormethods) > 1): ?>
<div id="form-login-secretkey" class="control-group">
<div class="controls">
<?php if (!$params->get('usetext')) : ?>
<div class="input-prepend input-append">
<span class="add-on">
<span class="icon-star hasTooltip" title="<?php echo JText::_('JGLOBAL_SECRETKEY'); ?>">
</span>
<label for="modlgn-secretkey" class="element-invisible"><?php echo JText::_('JGLOBAL_SECRETKEY'); ?>
</label>
</span>
<input id="modlgn-secretkey" autocomplete="off" type="text" name="secretkey" class="input-small" tabindex="0" size="18" placeholder="<?php echo JText::_('JGLOBAL_SECRETKEY') ?>" />
<span class="btn width-auto hasTooltip" title="<?php echo JText::_('JGLOBAL_SECRETKEY_HELP'); ?>">
<span class="icon-help"></span>
</span>
</div>
<?php else: ?>
<label for="modlgn-secretkey"><?php echo JText::_('JGLOBAL_SECRETKEY') ?></label>
<input id="modlgn-secretkey" autocomplete="off" type="text" name="secretkey" class="input-small" tabindex="0" size="18" placeholder="<?php echo JText::_('JGLOBAL_SECRETKEY') ?>" />
<span class="btn width-auto hasTooltip" title="<?php echo JText::_('JGLOBAL_SECRETKEY_HELP'); ?>">
<span class="icon-help"></span>
</span>
<?php endif; ?>
</div>
</div>
<?php endif; ?>
<?php if (JPluginHelper::isEnabled('system', 'remember')) : ?>
<div id="form-login-remember" class="control-group checkbox">
<label for="modlgn-remember" class="control-label"><?php echo JText::_('MOD_LOGIN_REMEMBER_ME') ?></label> <input id="modlgn-remember" type="checkbox" name="remember" class="inputbox" value="yes"/>
</div>
<?php endif; ?>
<div id="form-login-submit" class="control-group">
<div class="controls">
<button type="submit" tabindex="0" name="Submit" class="btn btn-primary"><?php echo JText::_('JLOGIN') ?></button>
</div>
</div>
<?php
$usersConfig = JComponentHelper::getParams('com_users'); ?>
<ul class="unstyled">
<?php if ($usersConfig->get('allowUserRegistration')) : ?>
<!--<li>
<a href="<?php echo JRoute::_('index.php?option=com_users&view=registration&Itemid=' . UsersHelperRoute::getRegistrationRoute()); ?>">
<?php echo JText::_('MOD_LOGIN_REGISTER'); ?> <span class="icon-arrow-right"></span></a>
</li>
-->
<?php endif; ?>
<li>
<a href="<?php echo JRoute::_('index.php?option=com_users&view=remind&Itemid=' . UsersHelperRoute::getRemindRoute()); ?>">
<?php echo JText::_('MOD_LOGIN_FORGOT_YOUR_USERNAME'); ?></a>
</li>
<li>
<a href="<?php echo JRoute::_('index.php?option=com_users&view=reset&Itemid=' . UsersHelperRoute::getResetRoute()); ?>">
<?php echo JText::_('MOD_LOGIN_FORGOT_YOUR_PASSWORD'); ?></a>
</li>
</ul>
<input type="hidden" name="option" value="com_users" />
<input type="hidden" name="task" value="user.login" />
<input type="hidden" name="return" value="<?php echo $return; ?>" />
<?php echo JHtml::_('form.token'); ?>
</div>
<?php if ($params->get('posttext')) : ?>
<div class="posttext">
<p><?php echo $params->get('posttext'); ?></p>
</div>
<?php endif; ?>
</form>
| gpl-2.0 |
SermonDistributor/Joomla-3-Component | admin/views/help_document/tmpl/edit.php | 7609 | <?php
/*-------------------------------------------------------------------------------------------------------------| www.vdm.io |------/
____ ____ __ __ __
/\ _`\ /\ _`\ __ /\ \__ __/\ \ /\ \__
\ \,\L\_\ __ _ __ ___ ___ ___ ___ \ \ \/\ \/\_\ ____\ \ ,_\ _ __ /\_\ \ \____ __ __\ \ ,_\ ___ _ __
\/_\__ \ /'__`\/\`'__\/' __` __`\ / __`\ /' _ `\ \ \ \ \ \/\ \ /',__\\ \ \/ /\`'__\/\ \ \ '__`\/\ \/\ \\ \ \/ / __`\/\`'__\
/\ \L\ \/\ __/\ \ \/ /\ \/\ \/\ \/\ \L\ \/\ \/\ \ \ \ \_\ \ \ \/\__, `\\ \ \_\ \ \/ \ \ \ \ \L\ \ \ \_\ \\ \ \_/\ \L\ \ \ \/
\ `\____\ \____\\ \_\ \ \_\ \_\ \_\ \____/\ \_\ \_\ \ \____/\ \_\/\____/ \ \__\\ \_\ \ \_\ \_,__/\ \____/ \ \__\ \____/\ \_\
\/_____/\/____/ \/_/ \/_/\/_/\/_/\/___/ \/_/\/_/ \/___/ \/_/\/___/ \/__/ \/_/ \/_/\/___/ \/___/ \/__/\/___/ \/_/
/------------------------------------------------------------------------------------------------------------------------------------/
@version 2.0.x
@created 22nd October, 2015
@package Sermon Distributor
@subpackage edit.php
@author Llewellyn van der Merwe <https://www.vdm.io/>
@copyright Copyright (C) 2015. All Rights Reserved
@license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
A sermon distributor that links to Dropbox.
/----------------------------------------------------------------------------------------------------------------------------------*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
JHtml::addIncludePath(JPATH_COMPONENT.'/helpers/html');
JHtml::_('behavior.tooltip');
JHtml::_('behavior.formvalidation');
JHtml::_('formbehavior.chosen', 'select');
JHtml::_('behavior.keepalive');
$componentParams = $this->params; // will be removed just use $this->params instead
?>
<script type="text/javascript">
// waiting spinner
var outerDiv = jQuery('body');
jQuery('<div id="loading"></div>')
.css("background", "rgba(255, 255, 255, .8) url('components/com_sermondistributor/assets/images/import.gif') 50% 15% no-repeat")
.css("top", outerDiv.position().top - jQuery(window).scrollTop())
.css("left", outerDiv.position().left - jQuery(window).scrollLeft())
.css("width", outerDiv.width())
.css("height", outerDiv.height())
.css("position", "fixed")
.css("opacity", "0.80")
.css("-ms-filter", "progid:DXImageTransform.Microsoft.Alpha(Opacity = 80)")
.css("filter", "alpha(opacity = 80)")
.css("display", "none")
.appendTo(outerDiv);
jQuery('#loading').show();
// when page is ready remove and show
jQuery(window).load(function() {
jQuery('#sermondistributor_loader').fadeIn('fast');
jQuery('#loading').hide();
});
</script>
<div id="sermondistributor_loader" style="display: none;">
<form action="<?php echo JRoute::_('index.php?option=com_sermondistributor&layout=edit&id='. (int) $this->item->id . $this->referral); ?>" method="post" name="adminForm" id="adminForm" class="form-validate" enctype="multipart/form-data">
<?php echo JLayoutHelper::render('help_document.details_above', $this); ?>
<div class="form-horizontal">
<?php echo JHtml::_('bootstrap.startTabSet', 'help_documentTab', array('active' => 'details')); ?>
<?php echo JHtml::_('bootstrap.addTab', 'help_documentTab', 'details', JText::_('COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_DETAILS', true)); ?>
<div class="row-fluid form-horizontal-desktop">
<div class="span6">
<?php echo JLayoutHelper::render('help_document.details_left', $this); ?>
</div>
<div class="span6">
<?php echo JLayoutHelper::render('help_document.details_right', $this); ?>
</div>
</div>
<div class="row-fluid form-horizontal-desktop">
<div class="span12">
<?php echo JLayoutHelper::render('help_document.details_fullwidth', $this); ?>
</div>
</div>
<?php echo JHtml::_('bootstrap.endTab'); ?>
<?php $this->ignore_fieldsets = array('details','metadata','vdmmetadata','accesscontrol'); ?>
<?php $this->tab_name = 'help_documentTab'; ?>
<?php echo JLayoutHelper::render('joomla.edit.params', $this); ?>
<?php if ($this->canDo->get('core.edit.created_by') || $this->canDo->get('core.edit.created') || $this->canDo->get('help_document.edit.state') || ($this->canDo->get('help_document.delete') && $this->canDo->get('help_document.edit.state'))) : ?>
<?php echo JHtml::_('bootstrap.addTab', 'help_documentTab', 'publishing', JText::_('COM_SERMONDISTRIBUTOR_HELP_DOCUMENT_PUBLISHING', true)); ?>
<div class="row-fluid form-horizontal-desktop">
<div class="span6">
<?php echo JLayoutHelper::render('help_document.publishing', $this); ?>
</div>
<div class="span6">
<?php echo JLayoutHelper::render('help_document.metadata', $this); ?>
</div>
</div>
<?php echo JHtml::_('bootstrap.endTab'); ?>
<?php endif; ?>
<?php echo JHtml::_('bootstrap.endTabSet'); ?>
<div>
<input type="hidden" name="task" value="help_document.edit" />
<?php echo JHtml::_('form.token'); ?>
</div>
</div>
<div class="clearfix"></div>
<?php echo JLayoutHelper::render('help_document.details_under', $this); ?>
</form>
</div>
<script type="text/javascript">
// #jform_location listeners for location_vvvvvwx function
jQuery('#jform_location').on('keyup',function()
{
var location_vvvvvwx = jQuery("#jform_location input[type='radio']:checked").val();
vvvvvwx(location_vvvvvwx);
});
jQuery('#adminForm').on('change', '#jform_location',function (e)
{
e.preventDefault();
var location_vvvvvwx = jQuery("#jform_location input[type='radio']:checked").val();
vvvvvwx(location_vvvvvwx);
});
// #jform_location listeners for location_vvvvvwy function
jQuery('#jform_location').on('keyup',function()
{
var location_vvvvvwy = jQuery("#jform_location input[type='radio']:checked").val();
vvvvvwy(location_vvvvvwy);
});
jQuery('#adminForm').on('change', '#jform_location',function (e)
{
e.preventDefault();
var location_vvvvvwy = jQuery("#jform_location input[type='radio']:checked").val();
vvvvvwy(location_vvvvvwy);
});
// #jform_type listeners for type_vvvvvwz function
jQuery('#jform_type').on('keyup',function()
{
var type_vvvvvwz = jQuery("#jform_type").val();
vvvvvwz(type_vvvvvwz);
});
jQuery('#adminForm').on('change', '#jform_type',function (e)
{
e.preventDefault();
var type_vvvvvwz = jQuery("#jform_type").val();
vvvvvwz(type_vvvvvwz);
});
// #jform_type listeners for type_vvvvvxa function
jQuery('#jform_type').on('keyup',function()
{
var type_vvvvvxa = jQuery("#jform_type").val();
vvvvvxa(type_vvvvvxa);
});
jQuery('#adminForm').on('change', '#jform_type',function (e)
{
e.preventDefault();
var type_vvvvvxa = jQuery("#jform_type").val();
vvvvvxa(type_vvvvvxa);
});
// #jform_type listeners for type_vvvvvxb function
jQuery('#jform_type').on('keyup',function()
{
var type_vvvvvxb = jQuery("#jform_type").val();
vvvvvxb(type_vvvvvxb);
});
jQuery('#adminForm').on('change', '#jform_type',function (e)
{
e.preventDefault();
var type_vvvvvxb = jQuery("#jform_type").val();
vvvvvxb(type_vvvvvxb);
});
// #jform_target listeners for target_vvvvvxc function
jQuery('#jform_target').on('keyup',function()
{
var target_vvvvvxc = jQuery("#jform_target input[type='radio']:checked").val();
vvvvvxc(target_vvvvvxc);
});
jQuery('#adminForm').on('change', '#jform_target',function (e)
{
e.preventDefault();
var target_vvvvvxc = jQuery("#jform_target input[type='radio']:checked").val();
vvvvvxc(target_vvvvvxc);
});
</script>
| gpl-2.0 |
ngxuanmui/hanhphuc.vn | templates/hanhphuc/html/mod_hp_b_blogs/default.php | 1589 | <?php
/**
* @package Joomla.Site
* @subpackage mod_banners
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// no direct access
defined('_JEXEC') or die;
?>
<script type="text/javascript">
<!--
jQuery(document).ready(function(){
jQuery('.b_blogs').bxSlider({
pager: false,
maxSlides: 8,
minSlides: 8,
slideWidth: 70,
slideMargin: 0,
nextSelector: '#slider-next',
prevSelector: '#slider-prev'
});
});
//-->
</script>
<div class="module-business-blog <?php echo $moduleclass_sfx?> padding-5">
<h2><?php echo $moduleTitle ?></h2>
<div class="line-break-bussiness-blog"><span></span></div>
<div class="bussiness-blog-box box">
<?php if(!empty($blogs)): ?>
<a href="#" id="slider-prev"></a>
<ul class="b_blogs">
<?php
foreach($blogs as $blog):
$url = JRoute::_('index.php?option=com_jnt_hanhphuc&view=services&user='.$blog->userid.'-' . $blog->username);
?>
<li style="width: 100px;">
<a href="<?php echo $url; ?>" class="image float-left" title="<?php echo $blog->business_name; ?>">
<img src="<?php echo JURI::base() . 'images/business/' . $blog->business_logo ?>" />
</a>
<?php endforeach; ?>
<div class="clear"></div>
</li>
</ul>
<a href="#" id="slider-next"></a>
<?php endif; ?>
<div class="clr"></div>
</div>
</div>
| gpl-2.0 |
dherrerav/Azteca-Sonora | administrator/components/com_acymailing/views/cpanel/tmpl/mail.php | 14916 | <?php
/**
* @copyright Copyright (C) 2009-2012 ACYBA SARL - All rights reserved.
* @license http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL
*/
defined('_JEXEC') or die('Restricted access');
?>
<div id="page-mail">
<br style="font-size:1px;" />
<fieldset class="adminform" >
<legend><?php echo JText::_( 'SENDER_INFORMATIONS' ); ?></legend>
<table class="admintable" cellspacing="1">
<tr>
<td width="185" class="key">
<?php echo acymailing_tooltip(JText::_('FROM_NAME_DESC'), JText::_('FROM_NAME'), '', JText::_('FROM_NAME')); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[from_name]" size="40" value="<?php echo $this->escape($this->config->get('from_name')); ?>">
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('FROM_ADDRESS_DESC'), JText::_('FROM_ADDRESS'), '', JText::_('FROM_ADDRESS')); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[from_email]" size="40" value="<?php echo $this->escape($this->config->get('from_email')); ?>">
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('REPLYTO_NAME_DESC'), JText::_('REPLYTO_NAME'), '', JText::_('REPLYTO_NAME')); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[reply_name]" size="40" value="<?php echo $this->escape($this->config->get('reply_name')); ?>">
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('REPLYTO_ADDRESS_DESC'), JText::_('REPLYTO_ADDRESS'), '', JText::_('REPLYTO_ADDRESS')); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[reply_email]" size="40" value="<?php echo $this->escape($this->config->get('reply_email')); ?>">
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('BOUNCE_ADDRESS_DESC'), JText::_('BOUNCE_ADDRESS'), '', JText::_('BOUNCE_ADDRESS')); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[bounce_email]" size="40" value="<?php echo $this->escape($this->config->get('bounce_email')); ?>">
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('ADD_NAMES_DESC'), JText::_('ADD_NAMES'), '', JText::_('ADD_NAMES')); ?>
</td>
<td>
<?php echo $this->elements->add_names; ?>
</td>
</tr>
</table>
</fieldset>
<fieldset class="adminform">
<legend><?php echo JText::_( 'MAIL_CONFIG' ); ?></legend>
<table width="100%">
<tr>
<td width="50%" valign="top">
<table class="admintable" cellspacing="1">
<tr>
<td width="185" class="key">
<?php echo acymailing_tooltip(JText::_('MAILER_METHOD_DESC'), JText::_('MAILER_METHOD'), '', JText::_('MAILER_METHOD')); ?>
</td>
<td>
<?php $mailerMethod = $this->config->get('mailer_method','phpmail');
if(!in_array($mailerMethod,array('smtp_com','elasticemail','smtp','qmail','sendmail','phpmail'))) $mailerMethod = 'phpmail';
?>
<fieldset><legend style="font-size:13px;"><?php echo JText::_('SEND_SERVER'); ?></legend>
<span><input type="radio" name="config[mailer_method]" onclick="updateMailer('phpmail')" value="phpmail" <?php if($mailerMethod == 'phpmail') echo 'checked="checked"'; ?> id="mailer_phpmail" /><label for="mailer_phpmail"> PHP Mail Function</label></span>
<span><input type="radio" name="config[mailer_method]" onclick="updateMailer('sendmail')" value="sendmail" <?php if($mailerMethod == 'sendmail') echo 'checked="checked"'; ?> id="mailer_sendmail" /><label for="mailer_sendmail"> SendMail</label></span>
<span><input type="radio" name="config[mailer_method]" onclick="updateMailer('qmail')" value="qmail" <?php if($mailerMethod == 'qmail') echo 'checked="checked"'; ?> id="mailer_qmail" /><label for="mailer_qmail"> QMail</label></span>
</fieldset>
<fieldset><legend style="font-size:13px;"><?php echo JText::_('SEND_EXTERNAL'); ?></legend>
<span><input type="radio" name="config[mailer_method]" onclick="updateMailer('smtp')" value="smtp" <?php if($mailerMethod == 'smtp') echo 'checked="checked"'; ?> id="mailer_smtp" /><label for="mailer_smtp"> SMTP Server</label></span>
<span><input type="radio" name="config[mailer_method]" onclick="updateMailer('smtp_com')" value="smtp_com" <?php if($mailerMethod == 'smtp_com') echo 'checked="checked"'; ?> id="mailer_smtp_com" /><label for="mailer_smtp_com"> SMTP.com</label></span>
<span><input type="radio" name="config[mailer_method]" onclick="updateMailer('elasticemail')" value="elasticemail" <?php if($mailerMethod == 'elasticemail') echo 'checked="checked"'; ?> id="mailer_elasticemail" /><label for="mailer_elasticemail"> Elastic Email</label></span>
</fieldset>
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('ENCODING_FORMAT_DESC'), JText::_('ENCODING_FORMAT'), '', JText::_('ENCODING_FORMAT')); ?>
</td>
<td>
<?php echo $this->elements->encoding_format; ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('CHARSET_DESC'), JText::_('CHARSET'), '', JText::_('CHARSET')); ?>
</td>
<td>
<?php echo $this->elements->charset; ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('WORD_WRAPPING_DESC'), JText::_('WORD_WRAPPING'), '', JText::_('WORD_WRAPPING')); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[word_wrapping]" size="10" value="<?php echo $this->config->get('word_wrapping',0) ?>">
</td>
</tr>
<tr>
<td class="key">
<?php
$defaultHostName = !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost.localdomain';
echo acymailing_tooltip(JText::_('HOSTNAME_DESC').'<br/><br/>'.JText::_('FIELD_DEFAULT').' : '.$defaultHostName, JText::_('HOSTNAME'), '', JText::_('HOSTNAME')); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[hostname]" size="30" value="<?php echo $this->escape($this->config->get('hostname')); ?>">
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('EMBED_IMAGES_DESC'), JText::_('EMBED_IMAGES'), '', JText::_('EMBED_IMAGES')); ?>
</td>
<td>
<?php echo $this->elements->embed_images; ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip( JText::_('EMBED_ATTACHMENTS_DESC'), JText::_('EMBED_ATTACHMENTS'), '', JText::_('EMBED_ATTACHMENTS')); ?>
</td>
<td>
<?php echo $this->elements->embed_files; ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('MULTIPLE_PART_DESC'), JText::_('MULTIPLE_PART'), '', JText::_('MULTIPLE_PART')); ?>
</td>
<td>
<?php echo $this->elements->multiple_part; ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('ACY_DKIM_DESC'), JText::_('ACY_DKIM'), '', JText::_('ACY_DKIM')); ?>
</td>
<td>
<?php echo $this->elements->dkim; ?>
</td>
</tr>
</table>
</td>
<td valign="top">
<fieldset class="adminform" id="sendmail_config" style="display:none">
<legend>SendMail</legend>
<table class="admintable" cellspacing="1" >
<tr>
<td width="185" class="key">
<?php echo acymailing_tooltip(JText::_('SENDMAIL_PATH_DESC'), JText::_('SENDMAIL_PATH'), '', JText::_('SENDMAIL_PATH')); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[sendmail_path]" size="30" value="<?php echo $this->config->get('sendmail_path','/usr/sbin/sendmail') ?>">
</td>
</tr>
</table>
</fieldset>
<fieldset class="adminform" id="smtp_config" style="display:none">
<legend><?php echo JText::_( 'SMTP_CONFIG' ); ?></legend>
<table class="admintable" cellspacing="1">
<tr>
<td width="185" class="key">
<?php echo acymailing_tooltip(JText::_('SMTP_SERVER_DESC'), JText::_('SMTP_SERVER'), '', JText::_('SMTP_SERVER')); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[smtp_host]" size="30" value="<?php echo $this->escape($this->config->get('smtp_host')); ?>">
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('SMTP_PORT_DESC'), JText::_('SMTP_PORT'), '', JText::_('SMTP_PORT')); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[smtp_port]" size="10" value="<?php echo $this->escape($this->config->get('smtp_port')); ?>">
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('SMTP_SECURE_DESC'), JText::_('SMTP_SECURE'), '', JText::_('SMTP_SECURE')); ?>
</td>
<td>
<?php echo $this->elements->smtp_secured; ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('SMTP_ALIVE_DESC'), JText::_('SMTP_ALIVE'), '', JText::_('SMTP_ALIVE')); ?>
</td>
<td>
<?php echo $this->elements->smtp_keepalive; ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('SMTP_AUTHENT_DESC'), JText::_('SMTP_AUTHENT'), '', JText::_('SMTP_AUTHENT')); ?>
</td>
<td>
<?php echo $this->elements->smtp_auth; ?>
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('USERNAME_DESC'), JText::_('ACY_USERNAME'), '', JText::_('ACY_USERNAME')); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[smtp_username]" size="40" value="<?php echo $this->escape($this->config->get('smtp_username')); ?>">
</td>
</tr>
<tr>
<td class="key">
<?php echo acymailing_tooltip(JText::_('SMTP_PASSWORD_DESC'), JText::_('SMTP_PASSWORD'), '', JText::_('SMTP_PASSWORD')); ?>
</td>
<td>
<input class="inputbox" autocomplete="off" type="password" name="config[smtp_password]" size="40" value="<?php echo $this->escape($this->config->get('smtp_password')); ?>">
</td>
</tr>
</table>
</fieldset>
<fieldset class="adminform" id="smtp_com_config" style="display:none">
<legend>SMTP.com</legend>
<?php echo JText::sprintf('SMTP_DESC','SMTP.com'); ?>
<table class="admintable" cellspacing="1" >
<tr>
<td width="185" class="key">
<?php echo JText::_('ACY_USERNAME'); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[smtp_com_username]" size="30" value="<?php echo $this->config->get('smtp_com_username','') ?>">
</td>
</tr>
<tr>
<td width="185" class="key">
<?php echo JText::_('SMTP_PASSWORD'); ?>
</td>
<td>
<input class="inputbox" autocomplete="off" type="password" name="config[smtp_com_password]" size="30" value="<?php echo $this->config->get('smtp_com_password','') ?>">
</td>
</tr>
</table>
<?php echo JText::_('NO_ACCOUNT_YET').' <a href="'.ACYMAILING_REDIRECT.'smtp_com" target="_blank" >'.JText::_('CREATE_ACCOUNT').'</a>'; ?>
<?php echo '<br/><a href="'.ACYMAILING_REDIRECT.'smtp_services" target="_blank">'.JText::_('TELL_ME_MORE').'</a>'; ?>
</fieldset>
<fieldset class="adminform" id="elasticemail_config" style="display:none">
<legend>Elastic Email</legend>
<?php echo JText::sprintf('SMTP_DESC','Elastic Email'); ?>
<table class="admintable" cellspacing="1" >
<tr>
<td width="185" class="key">
<?php echo JText::_('ACY_USERNAME'); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[elasticemail_username]" size="30" value="<?php echo $this->config->get('elasticemail_username','') ?>">
</td>
</tr>
<tr>
<td width="185" class="key">
API Key
</td>
<td>
<input class="inputbox" autocomplete="off" type="password" name="config[elasticemail_password]" size="30" value="<?php echo $this->config->get('elasticemail_password','') ?>">
</td>
</tr>
</table>
<?php echo JText::_('NO_ACCOUNT_YET').' <a href="'.ACYMAILING_REDIRECT.'elasticemail" target="_blank" >'.JText::_('CREATE_ACCOUNT').'</a>'; ?>
<?php echo '<br/><a href="'.ACYMAILING_REDIRECT.'smtp_services" target="_blank">'.JText::_('TELL_ME_MORE').'</a>'; ?>
</fieldset>
<fieldset class="adminform" id="dkim_config" style="display:none">
<legend><?php echo JText::_('ACY_DKIM'); ?></legend>
<table class="admintable" cellspacing="1" >
<tr>
<td width="185" class="key">
<?php echo JText::_('DKIM_DOMAIN'); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[dkim_domain]" size="30" value="<?php echo $this->escape($this->config->get('dkim_domain','')); ?>"> *
</td>
</tr>
<tr>
<td width="185" class="key">
<?php echo JText::_('DKIM_SELECTOR'); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[dkim_selector]" size="30" value="<?php echo $this->escape($this->config->get('dkim_selector','')); ?>"> *
</td>
</tr>
<tr>
<td width="185" class="key">
<?php echo JText::_('DKIM_PRIVATE'); ?>
</td>
<td>
<textarea cols="65" rows="8" name="config[dkim_private]"><?php echo $this->config->get('dkim_private',''); ?></textarea> *
</td>
</tr>
<tr>
<td width="185" class="key">
<?php echo JText::_('DKIM_PASSPHRASE'); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[dkim_passphrase]" size="30" value="<?php echo $this->escape($this->config->get('dkim_passphrase','')); ?>">
</td>
</tr>
<tr>
<td width="185" class="key">
<?php echo JText::_('DKIM_IDENTITY'); ?>
</td>
<td>
<input class="inputbox" type="text" name="config[dkim_identity]" size="30" value="<?php echo $this->escape($this->config->get('dkim_identity','')); ?>">
</td>
</tr>
<tr>
<td width="185" class="key">
<?php echo JText::_('DKIM_PUBLIC'); ?>
</td>
<td>
<textarea cols="65" rows="5" name="config[dkim_public]"><?php echo $this->config->get('dkim_public',''); ?></textarea>
</td>
</tr>
</table>
<a href="http://www.acyba.com/index.php?option=com_content&view=article&catid=34:documentation-acymailing&Itemid=30&id=156:acymailing-dkim" target="_blank"><?php echo JText::_('ACY_HELP'); ?></a>
</fieldset>
</td>
</tr>
</table>
</fieldset>
</div> | gpl-2.0 |
osv/cose | thirdparty/clunk/contrib/ogg_stream.cpp | 2355 | #include "ogg_stream.h"
#include "../sample.h"
#include <assert.h>
#include <stdexcept>
//This example is the public domain
static size_t stream_read_func (void *ptr, size_t size, size_t nmemb, void *datasource) {
//LOG_DEBUG(("read(%p, %u, %u)", ptr, (unsigned)size, (unsigned)nmemb));
assert(datasource != NULL);
FILE *file = (FILE *)datasource;
int r = fread(ptr, size, nmemb, file);
if (r <= 0)
return r;
return r / size;
}
static int stream_seek_func (void *datasource, ogg_int64_t offset, int whence) {
//LOG_DEBUG(("seek(%u, %d)", (unsigned)offset, whence));
assert(datasource != NULL);
FILE *file = (FILE *)datasource;
return fseek(file, offset, whence);
}
static int stream_close_func (void *datasource) {
//LOG_DEBUG(("close()"));
assert(datasource != NULL);
FILE *file = (FILE *)datasource;
return fclose(file);
}
static long stream_tell_func (void *datasource) {
//LOG_DEBUG(("tell"));
assert(datasource != NULL);
FILE *file = (FILE *)datasource;
return ftell(file);
}
OggStream::OggStream(const std::string &fname) {
_file = fopen(fname.c_str(), "rb");
if (_file == NULL) {
perror("fopen");
throw std::runtime_error("cannot open file");
}
ov_callbacks ov_cb;
memset(&ov_cb, 0, sizeof(ov_cb));
ov_cb.read_func = stream_read_func;
ov_cb.seek_func = stream_seek_func;
ov_cb.tell_func = stream_tell_func;
ov_cb.close_func = stream_close_func;
int r = ov_open_callbacks(_file, &_ogg_stream, NULL, 0, ov_cb);
if (r < 0) {
throw std::runtime_error("ov_open_callbacks failed");
}
_vorbis_info = ov_info(&_ogg_stream, -1);
sample_rate = _vorbis_info->rate;
//LOG_DEBUG(("open(%s) : %d", fname.c_str(), sample_rate));
format = AUDIO_S16LSB;
channels = _vorbis_info->channels;
//_vorbis_comment = ov_comment(&_ogg_stream, -1);
assert(_vorbis_info != NULL);
}
void OggStream::rewind() {
int r = ov_raw_seek(&_ogg_stream, 0);
if (r != 0)
throw std::runtime_error("ov_raw_seek");
}
bool OggStream::read(clunk::Buffer &data, unsigned hint) {
if (hint == 0)
hint = 44100;
data.set_size(hint);
int section = 0;
int r = ov_read(&_ogg_stream, (char *)data.get_ptr(), hint, 0, 2, 1, & section);
//LOG_DEBUG(("ov_read(%d) = %d (section: %d)", hint, r, section));
if(r >= 0) {
data.set_size(r);
return r != 0;
}
return false; //:(
}
OggStream::~OggStream() {}
| gpl-2.0 |
christopher-johnson/cyto-rdf | helixsoft-commons/nl.helixsoft.gui/src/nl/helixsoft/param/ParameterPanel.java | 2986 | // PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2009 BiGCaT Bioinformatics
//
// 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 nl.helixsoft.param;
import java.awt.Component;
import java.io.File;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import nl.helixsoft.param.ParameterModel.ParameterModelListener;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
//copied from org.bridgedb.gui
@SuppressWarnings({ "serial", "deprecation" })
public class ParameterPanel extends JPanel implements ParameterModelListener
{
private final ParameterModel model;
public ParameterPanel (ParameterModel model)
{
this.model = model;
refreshModel();
}
private Editor[] editors;
private void refreshValue(int i)
{
editors[i].setValue(model.getValue(i));
}
private void refreshValues()
{
for (int i = 0; i < model.getNum(); ++i)
{
refreshValue(i);
}
}
private void refreshModel()
{
for (Component c : getComponents())
remove(c);
editors = new Editor[model.getNum()];
DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout(""), this);
builder.border(BorderFactory.createEmptyBorder(5, 5, 5, 5));
builder.appendColumn("right:pref");
builder.appendColumn("3dlu");
builder.appendColumn("fill:max(pref; 100px):grow");
builder.appendColumn("3dlu");
builder.appendColumn("right:pref");
for (int i = 0; i < model.getNum(); ++i)
{
if (model.getMetaData(i) instanceof FileParameter ||
model.getMetaData(i) instanceof File)
{
editors[i] = new FileEditor (model, i, this, builder);
}
else if (model.getMetaData(i) instanceof Boolean)
{
editors[i] = new BooleanEditor (model, i, this, builder);
}
else if (model.getMetaData(i) instanceof Integer)
{
editors[i] = new IntegerEditor (model, i, this, builder);
}
else if (model.getMetaData(i) instanceof List<?>)
{
editors[i] = new EnumEditor (model, i, this, builder);
}
else
{
editors[i] = new StringEditor (model, i, this, builder);
}
}
refreshValues();
}
public void parametersChanged(ParameterModelEvent e)
{
switch (e.getType())
{
case VALUE_CHANGED:
refreshValue(e.getIndex());
break;
case VALUES_CHANGED:
refreshValues();
break;
case MODEL_CHANGED:
refreshModel();
break;
}
}
}
| gpl-2.0 |
eugeis/eugeis-seminarman | site/views/tags/tmpl/default_courses.php | 5059 | <?php
/**
* @Copyright Copyright (C) 2010 www.profinvent.com. All rights reserved.
* Copyright (C) 2011 Open Source Group GmbH www.osg-gmbh.de
* @website http://www.profinvent.com
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
**/
defined('_JEXEC') or die('Restricted access');
jimport( 'joomla.html.parameter' );
$colspan = 7;
if (!$this->params->get('show_location'))
$colspan--;
if (!$this->params->get('enable_bookings'))
$colspan--;
$Itemid = JRequest::getInt('Itemid');
?>
<form action="<?php echo $this->action;?>" method="post" id="adminForm">
<?php if ($this->params->get('filter') || $this->params->get('display')):?>
<div id="qf_filter" class="floattext">
<?php if ($this->params->get('filter')):?>
<div class="qf_fleft"><?php echo JText::_('COM_SEMINARMAN_COURSE'). ':';?>
<input type="text" name="filter" id="filter" value="<?php echo $this->lists['filter']; ?>" class="text_area" size="15"/>
<label for="filter_experience_level"><?php echo JText::_('COM_SEMINARMAN_LEVEL') ?></label> <?php echo $this->lists['filter_experience_level'];?>
<button onclick="document.getElementById('adminForm').submit();"><?php echo JText::_('COM_SEMINARMAN_GO');?></button>
</div>
<?php endif;?>
<?php if ($this->params->get('display')):?>
<div class="qf_fright">
<label for="limit"><?php echo JText::_('COM_SEMINARMAN_DISPLAY_NUM') ?></label><?php echo $this->pageNav->getLimitBox(); ?>
</div>
<?php endif;?>
</div>
<?php endif;?>
<table class="seminarmancoursetable" summary="seminarman">
<thead>
<tr>
<th id="qf_code" class="sectiontableheader" nowrap="nowrap"><?php echo JHTML::_('grid.sort', 'COM_SEMINARMAN_COURSE_CODE', 'i.code', $this->lists['filter_order_Dir'], $this->lists['filter_order']); ?></th>
<th id="qf_title" class="sectiontableheader"><?php echo JHTML::_('grid.sort', 'COM_SEMINARMAN_COURSE_TITLE', 'i.title', $this->lists['filter_order_Dir'], $this->lists['filter_order']); ?></th>
<th id="qf_start_date" class="sectiontableheader" nowrap="nowrap"><?php echo JHTML::_('grid.sort', 'COM_SEMINARMAN_START_DATE', 'i.start_date', $this->lists['filter_order_Dir'], $this->lists['filter_order']); ?></th>
<th id="qf_finish_date" class="sectiontableheader" nowrap="nowrap"><?php echo JHTML::_('grid.sort', 'COM_SEMINARMAN_FINISH_DATE', 'i.finish_date', $this->lists['filter_order_Dir'], $this->lists['filter_order']); ?></th>
<?php if ($this->params->get('show_location')): ?>
<th id="qf_location" class="sectiontableheader"><?php echo JHTML::_('grid.sort', 'COM_SEMINARMAN_LOCATION', 'i.location', $this->lists['filter_order_Dir'], $this->lists['filter_order']); ?></th>
<?php endif; ?>
<th id="qf_price" class="sectiontableheader"><?php echo JHTML::_('grid.sort', 'COM_SEMINARMAN_PRICE', 'i.price', $this->lists['filter_order_Dir'], $this->lists['filter_order']); ?><?php echo ($this->params->get('show_gross_price') != 2) ? "*" : ""; ?></th>
<?php if ($this->params->get('enable_bookings')): ?>
<th id="qf_application" class="sectiontableheader"></th>
<?php endif; ?>
</tr>
</thead>
<tbody>
<?php
$i=0;
foreach ($this->courses as $course):
?>
<tr class="sectiontableentry" >
<td headers="qf_code" nowrap="nowrap"><?php echo $this->escape($course->code); ?></td>
<td headers="qf_title"><strong><a href="<?php echo JRoute::_('index.php?option=com_seminarman&view=courses&cid=' . $course->category->slug . '&id=' . $course->slug . '&Itemid=' . $Itemid); ?>"><?php echo $this->escape($course->title); ?></a></strong><?php echo $course->show_new_icon; echo $course->show_sale_icon; ?></td>
<td headers="qf_start_date" nowrap="nowrap"><?php echo $course->start_date; ?></td>
<td headers="qf_finish_date" nowrap="nowrap"><?php echo $course->finish_date; ?></td>
<?php if ($this->params->get('show_location')): ?>
<td headers="qf_location"><?php echo $course->location; ?></td>
<?php endif; ?>
<td headers="qf_price"><?php echo $course->price . ' '. $course->currency_price.' ' . $course->price_type; ?></td>
<?php if ($this->params->get('enable_bookings')): ?>
<td class="centered" headers="qf_book"><?php echo $course->book_link; ?></td>
<?php endif; ?>
</tr>
<?php
$i++;
endforeach;
?>
<?php if ($this->params->get('show_gross_price') != 2): ?>
<tr class="sectiontableentry" >
<td colspan="<?php echo $colspan; ?>" class="right">*<?php echo ($this->params->get('show_gross_price') == 1) ? JText::_('COM_SEMINARMAN_WITH_VAT') : JText::_('COM_SEMINARMAN_WITHOUT_VAT'); ?></td>
</tr>
<?php endif; ?>
</tbody>
</table>
<input type="hidden" name="option" value="com_seminarman" />
<input type="hidden" name="filter_order" value="<?php echo $this->lists['filter_order'];?>" />
<input type="hidden" name="filter_order_Dir" value="" />
<input type="hidden" name="view" value="tags" />
<input type="hidden" name="task" value="" />
<input type="hidden" name="id" value="<?php echo $this->tag->id;?>" />
</form>
<div class="pagination"><?php echo $this->pageNav->getPagesLinks(); ?></div> | gpl-2.0 |
donatellosantoro/freESBee | freesbeeGE/test/test/it/unibas/freesbee/ge/funzionali/i/Pubblicazione13.java | 4684 | package test.it.unibas.freesbee.ge.funzionali.i;
import it.unibas.freesbee.ge.messaggi.XmlJDomUtil;
import it.unibas.freesbee.ge.persistenza.hibernate.DAOCategoriaEventiEsternaHibernate;
import it.unibas.freesbee.ge.persistenza.hibernate.DAOCategoriaEventiInternaHibernate;
import it.unibas.freesbee.ge.persistenza.hibernate.DAOCostanti;
import it.unibas.freesbee.ge.persistenza.hibernate.DAOGestoreEventiHibernate;
import it.unibas.freesbee.ge.persistenza.hibernate.DAOPubblicatoreEsternoHibernate;
import it.unibas.freesbee.ge.persistenza.hibernate.DAOPubblicatoreInternoHibernate;
import it.unibas.freesbee.ge.persistenza.hibernate.DAOSottoscrittoreHibernate;
import it.unibas.freesbee.ge.processor.ProcessorGestioneSottoscrizioni;
import it.unibas.freesbee.ge.processor.ProcessorHibernateBegin;
import it.unibas.freesbee.ge.processor.ProcessorHibernateCommit;
import it.unibas.freesbee.ge.processor.ProcessorSOAPReader;
import it.unibas.freesbee.utilita.ClientPD;
import it.unibas.springfreesbee.ge.ConfigurazioneStatico;
import java.io.FileWriter;
import java.net.URL;
import junit.framework.Assert;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import test.it.unibas.freesbee.ge.dao.DAOMock;
public class Pubblicazione13 extends ContextTestSupport {
protected Log logger = LogFactory.getLog(this.getClass());
protected MockEndpoint resultEndpoint;
public void testPubblicazione13Init() throws Exception {
logger.info("TEST - 13");
logger.info("Init");
Thread.currentThread().sleep(5000);
FileWriter f = new FileWriter(DAOMock.CONSEGNA);
String s = "<root><ok/></root>";
f.append(s.subSequence(0, s.length()));
f.flush();
}
public void testPubblicazione13() throws Exception {
logger.info("TEST - 13");
logger.info("Nessuna sottoscrizione");
try {
//Carico il messaggio che verebbe generato dal GE
URL url = this.getClass().getResource("/dati/i/test1.xml");
Document doc = XmlJDomUtil.caricaXML(url.getFile(), false);
String m = XmlJDomUtil.convertiDocumentToString(doc);
ClientPD clientPD = new ClientPD();
String indirizzo = "http://" + ConfigurazioneStatico.getInstance().getWebservicesIndirizzo() + ":" + ConfigurazioneStatico.getInstance().getWebservicesPort() + DAOCostanti.URL_WSDL_GESTORE_EVENTI;
logger.info("url: " + indirizzo);
logger.debug(m);
clientPD.invocaPortaDelegata(indirizzo, m);
} catch (Exception ex) {
logger.error(ex.getMessage());
Assert.fail("La pubblicazione ha lanciato eccezione");
}
}
public void testPubblicazione13VerificaConsegnaComunicazione() {
try {
logger.info("TEST - 13");
logger.info("Verifica Consegna");
Thread.currentThread().sleep(5000);
//Comunicazione inviata
org.jdom.Document doc = XmlJDomUtil.caricaXML(DAOMock.CONSEGNA, false);
String s = XmlJDomUtil.convertiDocumentToString(doc);
//Comunicazione di test
String m = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><ok/></root>";
logger.info("Comunicazione inviata: ");
logger.info(XmlJDomUtil.formattaXML(s));
logger.info("Comunicazione di test:");
logger.info(XmlJDomUtil.formattaXML(m));
assertEquals(XmlJDomUtil.formattaXML(m), XmlJDomUtil.formattaXML(s));
} catch (Exception ex) {
logger.error(ex.getMessage());
Assert.fail(ex.getMessage());
}
}
@Override
protected void setUp() throws Exception {
super.setUp();
resultEndpoint = (MockEndpoint) resolveMandatoryEndpoint("mock:result");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start").process(new ProcessorHibernateBegin()).process(new ProcessorSOAPReader()).process(new ProcessorGestioneSottoscrizioni(DAOMock.CATEGORIA_EVENTI_INTERNA_ATTIVA_2, new DAOCategoriaEventiInternaHibernate(), new DAOCategoriaEventiEsternaHibernate(), new DAOSottoscrittoreHibernate(), new DAOPubblicatoreInternoHibernate(), new DAOPubblicatoreEsternoHibernate(), new DAOGestoreEventiHibernate())).process(new ProcessorHibernateCommit()).to("mock:result");
}
};
}
}
| gpl-2.0 |
tintintti/qt-software-project | db/20160616072144_fix_topic_column_names.rb | 339 | class FixTopicColumnNames < ActiveRecord::Migration
def change
rename_column :topics, :mainpid, :mainPid
rename_column :topics, :isquestion, :isQuestion
rename_column :topics, :issolved, :isSolved
rename_column :topics, :relativetime, :relativeTime
rename_column :topics, :lastposttimeiso, :lastposttimeISO
end
end
| gpl-2.0 |
christianchristensen/resin | modules/quercus/src/com/caucho/quercus/lib/i18n/Utf8Encoder.java | 3434 | /*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Nam Nguyen
*/
package com.caucho.quercus.lib.i18n;
import java.util.logging.Logger;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.StringValue;
import com.caucho.util.L10N;
public class Utf8Encoder
extends Encoder
{
private static final Logger log
= Logger.getLogger(Utf8Encoder.class.getName());
private static final L10N L = new L10N(Utf8Encoder.class);
public Utf8Encoder()
{
super("utf-8");
}
@Override
public boolean isUtf8()
{
return true;
}
public boolean isEncodable(Env env, StringValue str)
{
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch <= 0x7F)
continue;
if (0xD800 <= ch && ch <= 0xDBFF) {
char ch2;
if (i + 1 < len
&& 0xDC00 <= (ch2 = str.charAt(i + 1)) && ch2 <= 0xDFFF) {
i++;
}
else
return false;
}
}
return true;
}
@Override
public StringValue encode(Env env, CharSequence str)
{
StringValue sb = env.createBinaryBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch <= 0x7F) {
sb.appendByte(ch);
continue;
}
int code = ch;
if (0xD800 <= ch && ch <= 0xDBFF) {
char ch2;
if (i + 1 < len
&& 0xDC00 <= (ch2 = str.charAt(i + 1)) && ch2 <= 0xDFFF) {
i++;
code = 0x10000 + ((ch - 0xD800) << 10) + (ch2 - 0xDC00);
}
else {
if (_isIgnore) {
}
else if (_replacement != null)
sb.append(_replacement);
else
return sb;
continue;
}
}
if (0x80 <= code && code <= 0x7FF) {
sb.appendByte(0xC0 | (code >> 6));
sb.appendByte(0x80 | (code & 0x3F));
}
else if (0x800 <= code && code <= 0xFFFF) {
sb.appendByte(0xE0 | (code >> 12));
sb.appendByte(0x80 | ((code >> 6) & 0x3F));
sb.appendByte(0x80 | (code & 0x3F));
}
else {
sb.appendByte(0xF0 | (code >> 18));
sb.appendByte(0x80 | ((code >> 12) & 0x3F));
sb.appendByte(0x80 | ((code >> 6) & 0x3F));
sb.appendByte(0x80 | (code & 0x3F));
}
}
return sb;
}
}
| gpl-2.0 |
gwupe/Gwupe | BlitsMeAgent/UI/WPF/Utils/ImageStreamReader.cs | 1347 | using System;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using Gwupe.Agent.Properties;
namespace Gwupe.Agent.UI.WPF.Utils
{
class ImageStreamReader : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return CreateBitmapImage((byte[])value);
}
public String DefaultImageUri { get; set; }
internal BitmapImage CreateBitmapImage(byte[] value)
{
var image = new BitmapImage();
image.BeginInit();
if (value == null)
{
// default image
if (DefaultImageUri != null)
{
image.UriSource = new Uri(DefaultImageUri, UriKind.RelativeOrAbsolute);
image.CacheOption = BitmapCacheOption.OnLoad;
}
}
else
{
image.StreamSource = new MemoryStream(value);
}
image.EndInit();
return image;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| gpl-2.0 |
mviitanen/marsmod | mcp/src/minecraft/net/minecraft/block/BlockVine.java | 15507 | package net.minecraft.block;
import java.util.Random;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.stats.StatList;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.Direction;
import net.minecraft.world.ColorizerFoliage;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class BlockVine extends Block
{
private static final String __OBFID = "CL_00000330";
public BlockVine()
{
super(Material.vine);
this.setTickRandomly(true);
this.setCreativeTab(CreativeTabs.tabDecorations);
}
/**
* Sets the block's bounds for rendering it as an item
*/
public void setBlockBoundsForItemRender()
{
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
}
/**
* The type of render function that is called for this block
*/
public int getRenderType()
{
return 20;
}
public boolean isOpaqueCube()
{
return false;
}
public boolean renderAsNormalBlock()
{
return false;
}
public void setBlockBoundsBasedOnState(IBlockAccess p_149719_1_, int p_149719_2_, int p_149719_3_, int p_149719_4_)
{
float var5 = 0.0625F;
int var6 = p_149719_1_.getBlockMetadata(p_149719_2_, p_149719_3_, p_149719_4_);
float var7 = 1.0F;
float var8 = 1.0F;
float var9 = 1.0F;
float var10 = 0.0F;
float var11 = 0.0F;
float var12 = 0.0F;
boolean var13 = var6 > 0;
if ((var6 & 2) != 0)
{
var10 = Math.max(var10, 0.0625F);
var7 = 0.0F;
var8 = 0.0F;
var11 = 1.0F;
var9 = 0.0F;
var12 = 1.0F;
var13 = true;
}
if ((var6 & 8) != 0)
{
var7 = Math.min(var7, 0.9375F);
var10 = 1.0F;
var8 = 0.0F;
var11 = 1.0F;
var9 = 0.0F;
var12 = 1.0F;
var13 = true;
}
if ((var6 & 4) != 0)
{
var12 = Math.max(var12, 0.0625F);
var9 = 0.0F;
var7 = 0.0F;
var10 = 1.0F;
var8 = 0.0F;
var11 = 1.0F;
var13 = true;
}
if ((var6 & 1) != 0)
{
var9 = Math.min(var9, 0.9375F);
var12 = 1.0F;
var7 = 0.0F;
var10 = 1.0F;
var8 = 0.0F;
var11 = 1.0F;
var13 = true;
}
if (!var13 && this.func_150093_a(p_149719_1_.getBlock(p_149719_2_, p_149719_3_ + 1, p_149719_4_)))
{
var8 = Math.min(var8, 0.9375F);
var11 = 1.0F;
var7 = 0.0F;
var10 = 1.0F;
var9 = 0.0F;
var12 = 1.0F;
}
this.setBlockBounds(var7, var8, var9, var10, var11, var12);
}
/**
* Returns a bounding box from the pool of bounding boxes (this means this box can change after the pool has been
* cleared to be reused)
*/
public AxisAlignedBB getCollisionBoundingBoxFromPool(World p_149668_1_, int p_149668_2_, int p_149668_3_, int p_149668_4_)
{
return null;
}
/**
* checks to see if you can place this block can be placed on that side of a block: BlockLever overrides
*/
public boolean canPlaceBlockOnSide(World p_149707_1_, int p_149707_2_, int p_149707_3_, int p_149707_4_, int p_149707_5_)
{
switch (p_149707_5_)
{
case 1:
return this.func_150093_a(p_149707_1_.getBlock(p_149707_2_, p_149707_3_ + 1, p_149707_4_));
case 2:
return this.func_150093_a(p_149707_1_.getBlock(p_149707_2_, p_149707_3_, p_149707_4_ + 1));
case 3:
return this.func_150093_a(p_149707_1_.getBlock(p_149707_2_, p_149707_3_, p_149707_4_ - 1));
case 4:
return this.func_150093_a(p_149707_1_.getBlock(p_149707_2_ + 1, p_149707_3_, p_149707_4_));
case 5:
return this.func_150093_a(p_149707_1_.getBlock(p_149707_2_ - 1, p_149707_3_, p_149707_4_));
default:
return false;
}
}
private boolean func_150093_a(Block p_150093_1_)
{
return p_150093_1_.renderAsNormalBlock() && p_150093_1_.blockMaterial.blocksMovement();
}
private boolean func_150094_e(World p_150094_1_, int p_150094_2_, int p_150094_3_, int p_150094_4_)
{
int var5 = p_150094_1_.getBlockMetadata(p_150094_2_, p_150094_3_, p_150094_4_);
int var6 = var5;
if (var5 > 0)
{
for (int var7 = 0; var7 <= 3; ++var7)
{
int var8 = 1 << var7;
if ((var5 & var8) != 0 && !this.func_150093_a(p_150094_1_.getBlock(p_150094_2_ + Direction.offsetX[var7], p_150094_3_, p_150094_4_ + Direction.offsetZ[var7])) && (p_150094_1_.getBlock(p_150094_2_, p_150094_3_ + 1, p_150094_4_) != this || (p_150094_1_.getBlockMetadata(p_150094_2_, p_150094_3_ + 1, p_150094_4_) & var8) == 0))
{
var6 &= ~var8;
}
}
}
if (var6 == 0 && !this.func_150093_a(p_150094_1_.getBlock(p_150094_2_, p_150094_3_ + 1, p_150094_4_)))
{
return false;
}
else
{
if (var6 != var5)
{
p_150094_1_.setBlockMetadataWithNotify(p_150094_2_, p_150094_3_, p_150094_4_, var6, 2);
}
return true;
}
}
public int getBlockColor()
{
return ColorizerFoliage.getFoliageColorBasic();
}
/**
* Returns the color this block should be rendered. Used by leaves.
*/
public int getRenderColor(int p_149741_1_)
{
return ColorizerFoliage.getFoliageColorBasic();
}
/**
* Returns a integer with hex for 0xrrggbb with this color multiplied against the blocks color. Note only called
* when first determining what to render.
*/
public int colorMultiplier(IBlockAccess p_149720_1_, int p_149720_2_, int p_149720_3_, int p_149720_4_)
{
return p_149720_1_.getBiomeGenForCoords(p_149720_2_, p_149720_4_).getBiomeFoliageColor(p_149720_2_, p_149720_3_, p_149720_4_);
}
public void onNeighborBlockChange(World p_149695_1_, int p_149695_2_, int p_149695_3_, int p_149695_4_, Block p_149695_5_)
{
if (!p_149695_1_.isClient && !this.func_150094_e(p_149695_1_, p_149695_2_, p_149695_3_, p_149695_4_))
{
this.dropBlockAsItem(p_149695_1_, p_149695_2_, p_149695_3_, p_149695_4_, p_149695_1_.getBlockMetadata(p_149695_2_, p_149695_3_, p_149695_4_), 0);
p_149695_1_.setBlockToAir(p_149695_2_, p_149695_3_, p_149695_4_);
}
}
/**
* Ticks the block if it's been scheduled
*/
public void updateTick(World p_149674_1_, int p_149674_2_, int p_149674_3_, int p_149674_4_, Random p_149674_5_)
{
if (!p_149674_1_.isClient && p_149674_1_.rand.nextInt(4) == 0)
{
byte var6 = 4;
int var7 = 5;
boolean var8 = false;
int var9;
int var10;
int var11;
label134:
for (var9 = p_149674_2_ - var6; var9 <= p_149674_2_ + var6; ++var9)
{
for (var10 = p_149674_4_ - var6; var10 <= p_149674_4_ + var6; ++var10)
{
for (var11 = p_149674_3_ - 1; var11 <= p_149674_3_ + 1; ++var11)
{
if (p_149674_1_.getBlock(var9, var11, var10) == this)
{
--var7;
if (var7 <= 0)
{
var8 = true;
break label134;
}
}
}
}
}
var9 = p_149674_1_.getBlockMetadata(p_149674_2_, p_149674_3_, p_149674_4_);
var10 = p_149674_1_.rand.nextInt(6);
var11 = Direction.facingToDirection[var10];
int var13;
if (var10 == 1 && p_149674_3_ < 255 && p_149674_1_.isAirBlock(p_149674_2_, p_149674_3_ + 1, p_149674_4_))
{
if (var8)
{
return;
}
int var15 = p_149674_1_.rand.nextInt(16) & var9;
if (var15 > 0)
{
for (var13 = 0; var13 <= 3; ++var13)
{
if (!this.func_150093_a(p_149674_1_.getBlock(p_149674_2_ + Direction.offsetX[var13], p_149674_3_ + 1, p_149674_4_ + Direction.offsetZ[var13])))
{
var15 &= ~(1 << var13);
}
}
if (var15 > 0)
{
p_149674_1_.setBlock(p_149674_2_, p_149674_3_ + 1, p_149674_4_, this, var15, 2);
}
}
}
else
{
Block var12;
int var14;
if (var10 >= 2 && var10 <= 5 && (var9 & 1 << var11) == 0)
{
if (var8)
{
return;
}
var12 = p_149674_1_.getBlock(p_149674_2_ + Direction.offsetX[var11], p_149674_3_, p_149674_4_ + Direction.offsetZ[var11]);
if (var12.blockMaterial == Material.air)
{
var13 = var11 + 1 & 3;
var14 = var11 + 3 & 3;
if ((var9 & 1 << var13) != 0 && this.func_150093_a(p_149674_1_.getBlock(p_149674_2_ + Direction.offsetX[var11] + Direction.offsetX[var13], p_149674_3_, p_149674_4_ + Direction.offsetZ[var11] + Direction.offsetZ[var13])))
{
p_149674_1_.setBlock(p_149674_2_ + Direction.offsetX[var11], p_149674_3_, p_149674_4_ + Direction.offsetZ[var11], this, 1 << var13, 2);
}
else if ((var9 & 1 << var14) != 0 && this.func_150093_a(p_149674_1_.getBlock(p_149674_2_ + Direction.offsetX[var11] + Direction.offsetX[var14], p_149674_3_, p_149674_4_ + Direction.offsetZ[var11] + Direction.offsetZ[var14])))
{
p_149674_1_.setBlock(p_149674_2_ + Direction.offsetX[var11], p_149674_3_, p_149674_4_ + Direction.offsetZ[var11], this, 1 << var14, 2);
}
else if ((var9 & 1 << var13) != 0 && p_149674_1_.isAirBlock(p_149674_2_ + Direction.offsetX[var11] + Direction.offsetX[var13], p_149674_3_, p_149674_4_ + Direction.offsetZ[var11] + Direction.offsetZ[var13]) && this.func_150093_a(p_149674_1_.getBlock(p_149674_2_ + Direction.offsetX[var13], p_149674_3_, p_149674_4_ + Direction.offsetZ[var13])))
{
p_149674_1_.setBlock(p_149674_2_ + Direction.offsetX[var11] + Direction.offsetX[var13], p_149674_3_, p_149674_4_ + Direction.offsetZ[var11] + Direction.offsetZ[var13], this, 1 << (var11 + 2 & 3), 2);
}
else if ((var9 & 1 << var14) != 0 && p_149674_1_.isAirBlock(p_149674_2_ + Direction.offsetX[var11] + Direction.offsetX[var14], p_149674_3_, p_149674_4_ + Direction.offsetZ[var11] + Direction.offsetZ[var14]) && this.func_150093_a(p_149674_1_.getBlock(p_149674_2_ + Direction.offsetX[var14], p_149674_3_, p_149674_4_ + Direction.offsetZ[var14])))
{
p_149674_1_.setBlock(p_149674_2_ + Direction.offsetX[var11] + Direction.offsetX[var14], p_149674_3_, p_149674_4_ + Direction.offsetZ[var11] + Direction.offsetZ[var14], this, 1 << (var11 + 2 & 3), 2);
}
else if (this.func_150093_a(p_149674_1_.getBlock(p_149674_2_ + Direction.offsetX[var11], p_149674_3_ + 1, p_149674_4_ + Direction.offsetZ[var11])))
{
p_149674_1_.setBlock(p_149674_2_ + Direction.offsetX[var11], p_149674_3_, p_149674_4_ + Direction.offsetZ[var11], this, 0, 2);
}
}
else if (var12.blockMaterial.isOpaque() && var12.renderAsNormalBlock())
{
p_149674_1_.setBlockMetadataWithNotify(p_149674_2_, p_149674_3_, p_149674_4_, var9 | 1 << var11, 2);
}
}
else if (p_149674_3_ > 1)
{
var12 = p_149674_1_.getBlock(p_149674_2_, p_149674_3_ - 1, p_149674_4_);
if (var12.blockMaterial == Material.air)
{
var13 = p_149674_1_.rand.nextInt(16) & var9;
if (var13 > 0)
{
p_149674_1_.setBlock(p_149674_2_, p_149674_3_ - 1, p_149674_4_, this, var13, 2);
}
}
else if (var12 == this)
{
var13 = p_149674_1_.rand.nextInt(16) & var9;
var14 = p_149674_1_.getBlockMetadata(p_149674_2_, p_149674_3_ - 1, p_149674_4_);
if (var14 != (var14 | var13))
{
p_149674_1_.setBlockMetadataWithNotify(p_149674_2_, p_149674_3_ - 1, p_149674_4_, var14 | var13, 2);
}
}
}
}
}
}
public int onBlockPlaced(World p_149660_1_, int p_149660_2_, int p_149660_3_, int p_149660_4_, int p_149660_5_, float p_149660_6_, float p_149660_7_, float p_149660_8_, int p_149660_9_)
{
byte var10 = 0;
switch (p_149660_5_)
{
case 2:
var10 = 1;
break;
case 3:
var10 = 4;
break;
case 4:
var10 = 8;
break;
case 5:
var10 = 2;
}
return var10 != 0 ? var10 : p_149660_9_;
}
public Item getItemDropped(int p_149650_1_, Random p_149650_2_, int p_149650_3_)
{
return null;
}
/**
* Returns the quantity of items to drop on block destruction.
*/
public int quantityDropped(Random p_149745_1_)
{
return 0;
}
public void harvestBlock(World p_149636_1_, EntityPlayer p_149636_2_, int p_149636_3_, int p_149636_4_, int p_149636_5_, int p_149636_6_)
{
if (!p_149636_1_.isClient && p_149636_2_.getCurrentEquippedItem() != null && p_149636_2_.getCurrentEquippedItem().getItem() == Items.shears)
{
p_149636_2_.addStat(StatList.mineBlockStatArray[Block.getIdFromBlock(this)], 1);
this.dropBlockAsItem_do(p_149636_1_, p_149636_3_, p_149636_4_, p_149636_5_, new ItemStack(Blocks.vine, 1, 0));
}
else
{
super.harvestBlock(p_149636_1_, p_149636_2_, p_149636_3_, p_149636_4_, p_149636_5_, p_149636_6_);
}
}
}
| gpl-2.0 |
protyposis/SRC.NET | SRC.NET/LibSampleRate/SrcData.cs | 2744 | /*
** Copyright (C) 2002-2011 Erik de Castro Lopo <erikd@mega-nerd.com>
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace LibSampleRate {
/// <summary>
/// SRC_DATA is used to pass data to src_simple() and src_process().
/// Copied from http://www.mega-nerd.com/SRC/api_misc.html#SRC_DATA
/// </summary>
[StructLayoutAttribute(LayoutKind.Sequential)]
internal unsafe struct SRC_DATA {
/// <summary>
/// A pointer to the input data samples.
/// </summary>
public float* data_in;
/// <summary>
/// A pointer to the output data samples.
/// </summary>
public float* data_out;
/// <summary>
/// The number of frames of data pointed to by data_in.
/// </summary>
public int input_frames;
/// <summary>
/// Maximum number of frames pointer to by data_out.
/// </summary>
public int output_frames;
/// <summary>
/// When the src_process function returns output_frames_gen will be set to the number of output frames
/// generated and input_frames_used will be set to the number of input frames consumed to generate the
/// provided number of output frames.
/// </summary>
public int input_frames_used;
/// <summary>
/// When the src_process function returns output_frames_gen will be set to the number of output frames
/// generated and input_frames_used will be set to the number of input frames consumed to generate the
/// provided number of output frames.
/// </summary>
public int output_frames_gen;
/// <summary>
/// Equal to 0 if more input data is available and 1 otherwise.
/// </summary>
public int end_of_input;
/// <summary>
/// Equal to output_sample_rate / input_sample_rate.
/// </summary>
public double src_ratio;
}
}
| gpl-2.0 |
ravikr9096/wcg | wp-content/themes/arch/template-fullwidth.php | 427 | <?php
/*
Template Name: Fullwidth
*/
?>
<?php get_header(); ?>
<div class="inside load-item">
<div class="page-content fullwidth">
<!--FULLWIDTH-->
<?php get_theme_page_title(); ?>
<div class="theme-pages">
<?php
if (have_posts()) :
while (have_posts()) : the_post();
the_content();
endwhile;
endif;
?>
</div>
</div>
</div>
<?php get_footer(); ?> | gpl-2.0 |
rinkuvantage/puyangantemples | wp-content/plugins/temple/listdistricts.php | 5915 | <?php
global $wpdb;
$prefix=$wpdb->base_prefix;
$totalrec=20;
if(isset($_REQUEST['pagedid']) && $_REQUEST['pagedid']>1)
{
$pageid=$_REQUEST['pagedid'];
$limitstart=$totalrec*($pageid-1);
}
else
{
$pageid=1;
$limitstart=0;
$limitsend=$totalrec;
}
$cnd='';
$state_id='';
$district_id='';
if(isset($_REQUEST['state_id']) && trim($_REQUEST['state_id'])!='')
{
$state_id=$_REQUEST['state_id'];
$cnd.=" and state_id = '$state_id'";
}
if(isset($_REQUEST['district_id']) && trim($_REQUEST['district_id'])!='')
{
$district_id=$_REQUEST['district_id'];
$cnd.=" and district_id = '$district_id'";
}
$where=" where id!='' $cnd order by state_id";
$querystr = "SELECT * FROM ".$prefix."temple_districts $where limit $limitstart, $totalrec";
$cities = $wpdb->get_results($querystr, OBJECT);
$querystr = "SELECT * FROM ".$prefix."temple_districts $where";
$totalphotos = $wpdb->get_results($querystr, OBJECT);
?>
<link href="<?php echo get_option('home');?>/wp-content/plugins/temple/css/pagedesign.css" rel="stylesheet"/>
<?php $url=get_option('home').'/wp-admin/admin.php?page=TempleState'; ?>
<div class="wrap">
<div style="margin:15px;">
<?php echo "<div style='color: #222; font-size: 1.5em; font-weight: 400; margin: 0.83em 0; float:left;'>" . __( 'Manage Districts', 'webserve_trdom' ) . "</div>"; ?>
<a href="<?php _e($url.'&ho=adddistrict&state_id='.$state_id); ?>"><div class="add-new" style="margin: 0.83em 0.5em;">Add District</div></a>
<a href="<?php _e($url.'&ho=listcity&state_id='.$state_id); ?>"><div class="add-new" style="margin: 0.83em 0.5em;">Manage Cities</div></a>
</div>
<div class="clr"></div>
<?php if(isset($_REQUEST['del'])){if($_REQUEST['del']=='succ'){ ?>
<div class="updated"><p><strong><?php _e('Deleted successfully.' ); ?></strong></p></div>
<?php }} ?>
<?php if(isset($_REQUEST['add'])){if($_REQUEST['add']=='succ'){ ?>
<div class="updated"><p><strong><?php _e('Added successfully.' ); ?></strong></p></div>
<?php }} ?>
<?php if(isset($_REQUEST['update'])){if($_REQUEST['update']=='succ'){ ?>
<div class="updated"><p><strong><?php _e('Update successfully.' ); ?></strong></p></div>
<?php }} ?>
<div class="clr"></div>
<form name="ques_form" method="post" onSubmit="return check_blank();" action="<?php echo $url; ?>">
<input type="hidden" name="quiz" value="filter" />
<div style="clear:both; height:20px;"></div>
<?php if(count($cities)>0){ ?>
<table width="100%" align="center" border="0" cellpadding="0" cellspacing="0" style="border:1px solid #ccc;">
<tr>
<th valign="top" align="left" width="60"> <?php _e("Sr. No." ); ?></th>
<th valign="top" align="left" style="border-left:1px solid #ccc;"><?php _e("State" ); ?></th>
<th valign="top" align="left" style="border-left:1px solid #ccc;"><?php _e("District" ); ?></th>
<th valign="top" align="left" style="border-left:1px solid #ccc;"><?php _e("Actions" ); ?></th>
</tr>
<?php
$cnt=$limitstart+1;
foreach($cities as $city)
{
$st = Statedetail($city->state_id);
?>
<tr>
<td valign="top" align="left" style="border-top:1px solid #ccc;"> <?php _e($cnt); ?></td>
<td valign="top" align="left" style="border-top:1px solid #ccc; border-left:1px solid #ccc;"><?php _e($st[0]->state); ?></td>
<td valign="top" align="left" style="border-top:1px solid #ccc; border-left:1px solid #ccc;"><?php _e($city->district); ?></td>
<td valign="top" align="left" style="border-top:1px solid #ccc; border-left:1px solid #ccc;">
<a href="<?php _e($url); ?>&ho=editdistrict&id=<?php _e($city->id); ?>">View and Edit</a>
<a href="javascript:if(confirm('Please confirm that you would like to delete this?')) {window.location='<?php _e($url); ?>&ho=deletedistrict&id=<?php _e($city->id); ?>';}">Delete</a>
</td>
</tr>
<?php $cnt++; } ?>
</table>
<?php
}
else
{
echo "<strong>No District Found!</strong>" ;
}
?>
</form>
<?php if(count($totalphotos)>$totalrec){ ?>
<div style="float:left; margin-top:10px;" class="pagination">
<?php if($pageid>1){ ?><a href="<?php _e($url); ?>" title="First" class="fl">
<img src="<?php echo get_option('home');?>/wp-content/plugins/quiz-contest/images/first.png" alt="First" title="First" /></a><?php } ?>
<?php $totalcities=ceil(count($totalphotos)/$totalrec);
$previous = $pageid-1;
if($previous>0)
{
?>
<a class="fl" href="<?php _e($url.'&pagedid='.$previous);?>"><img src="<?php echo get_option('home');?>/wp-content/plugins/quiz-contest/images/previous.png" alt="Previous" title="Previous" /></a>
<?php
}
?>
<div class="fl ml5 mr10">Page Number:</div>
<div class="fl mr5">
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready( function(){
jQuery('#paginate').live('change', function(){
var pagedid=jQuery(this).val();
window.location='<?php _e($url); ?>&pagedid='+pagedid;
});
})
//]]>
</script>
<select style="float:left;" id="paginate" name="pagedid">
<?php for($k=1;$k<=$totalcities;$k++){ ?>
<option value="<?php _e($k); ?>" <?php if($k==$pageid){ _e('selected="selected"');}?>><?php _e($k); ?></option>
<?php } ?>
</select>
</div>
<?php
$next = $pageid+1;
if($totalcities>=$next)
{
?>
<a class="fl" href="<?php _e($url.'&pagedid='.$next);?>"><img src="<?php echo get_option('home');?>/wp-content/plugins/quiz-contest/images/next.png" alt="Next" title="Next" /></a>
<?php
}
?>
<?php if($totalcities>$pageid){ ?><a href="<?php _e($url.'&pagedid='.$totalcities); ?>" title="Last" class="fl"><img src="<?php echo get_option('home');?>/wp-content/plugins/quiz-contest/images/last.png" alt="Last" title="Last" /></a><?php } ?>
</div>
<?php } ?>
</div> | gpl-2.0 |
leoloso/PoP | layers/Legacy/Schema/packages/migrate-everythingelse/migrate/migrate-packages/migrate-media/initialize.php | 584 | <?php
$class = (new class() extends \PoP\Root\Component\AbstractComponent
{
/**
* Classes from PoP components that must be initialized before this component
*
* @return string[]
*/
public function getDependedComponentClasses(): array
{
return [];
}
/**
* Boot component
*/
public function beforeBoot(): void
{
parent::beforeBoot();
// Initialize code
require_once 'migrate/pop-media.php';
}
});
\PoP\Root\StateManagers\ComponentManager::register(get_class($class));
$class::initialize();
| gpl-2.0 |
Cide424/cidewebpage | components/com_eventgallery/views/snippets/tmpl/event/simple.php | 1619 | <?php
/**
* @package Sven.Bluege
* @subpackage com_eventgallery
*
* @copyright Copyright (C) 2005 - 2013 Sven Bluege All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
?>
<div itemscope itemtype="http://schema.org/Event" id="event">
<?php IF ($this->params->get('show_date', 1) == 1): ?>
<h4 class="date">
<?php echo JHTML::Date($this->folder->getDate()); ?>
</h4>
<?php ENDIF ?>
<h1 itemprop="name" class="displayname">
<?php echo $this->folder->getDisplayName(); ?>
</h1>
<?php echo $this->loadSnippet('event/inc/paging_top'); ?>
<div itemprop="description" class="text">
<?php echo JHtml::_('content.prepare', $this->folder->getText(), '', 'com_eventgallery.event'); ?>
</div>
<div style="display:none">
<?php
if (isset($this->titleEntries[0])) {
echo '<meta itemprop="image" content="'. $this->titleEntries[0]->getSharingImageUrl() .'" />';
echo '<link rel="image_src" tpe="image/jpeg" href="'. $this->titleEntries[0]->getSharingImageUrl() .'" />';
}
?>
<span itemprop="startDate" content="<?php echo $this->folder->getDate(); ?>">
<?php echo JHTML::Date($this->folder->getDate()); ?>
</span>
</div>
<?php echo $this->loadSnippet('imageset/imagesetselection'); ?>
<?php echo $this->loadSnippet('event/simple_thumbnails'); ?>
<?php echo $this->loadSnippet('event/inc/paging_bottom'); ?>
</div>
| gpl-2.0 |
dudemanvox/Dawn-of-Light-Server | DOLDatabase/Tables/Artifact.cs | 7708 | /*
* DAWN OF LIGHT - The first free open source DAoC server emulator
*
* 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.
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using DOL.Database.Attributes;
namespace DOL.Database
{
/// <summary>
/// An artifact.
/// </summary>
/// <author>Aredhel</author>
[DataTable(TableName = "Artifact")]
public class Artifact : DataObject
{
private String m_artifactID;
private String m_encounterID;
private String m_questID;
private String m_zone;
private String m_scholarID;
private int m_reuseTimer;
private int m_xpRate;
private String m_bookID;
private int m_bookModel;
private String m_scroll1, m_scroll2, m_scroll3;
private String m_scroll12, m_scroll13, m_scroll23;
private int m_scrollModel1, m_scrollModel2;
private int m_scrollLevel;
private String m_messageUse;
private String m_messageCombineScrolls, m_messageCombineBook;
private String m_messageReceiveScrolls, m_messageReceiveBook;
private String m_credit;
/// <summary>
/// Create a new artifact object.
/// </summary>
public Artifact()
: base() { }
/// <summary>
/// Whether to auto-save this object or not.
/// </summary>
public override bool AllowAdd
{
get { return false; }
set { }
}
/// <summary>
/// The artifact ID.
/// </summary>
[DataElement(AllowDbNull = false)]
public String ArtifactID
{
get { return m_artifactID; }
set
{
Dirty = true;
m_artifactID = value;
}
}
/// <summary>
/// The ID for the encounter required to get the quest for
/// this artifact.
/// </summary>
[DataElement(AllowDbNull = false)]
public String EncounterID
{
get { return m_encounterID; }
set
{
Dirty = true;
m_encounterID = value;
}
}
/// <summary>
/// The ID for the quest that needs to be completed in order
/// to unlock this artifact.
/// </summary>
[DataElement(AllowDbNull = false)]
public String QuestID
{
get { return m_questID; }
set
{
Dirty = true;
m_questID = value;
}
}
/// <summary>
/// The zone this artifact belongs to.
/// </summary>
[DataElement(AllowDbNull = false)]
public String Zone
{
get { return m_zone; }
set
{
Dirty = true;
m_zone = value;
}
}
/// <summary>
/// The scholar(s) studying this artifact.
/// </summary>
[DataElement(AllowDbNull = false)]
public String ScholarID
{
get { return m_scholarID; }
set
{
Dirty = true;
m_scholarID = value;
}
}
/// <summary>
/// The reuse timer for the artifact.
/// </summary>
[DataElement(AllowDbNull = false)]
public int ReuseTimer
{
get { return m_reuseTimer; }
set
{
Dirty = true;
m_reuseTimer = value;
}
}
/// <summary>
/// The rate at which this artifact gains xp (in percent).
/// </summary>
[DataElement(AllowDbNull = false)]
public int XPRate
{
get { return m_xpRate; }
set
{
Dirty = true;
m_xpRate = value;
}
}
/// <summary>
/// The book ID.
/// </summary>
[DataElement(AllowDbNull = false)]
public String BookID
{
get { return m_bookID; }
set
{
Dirty = true;
m_bookID = value;
}
}
/// <summary>
/// The book model (icon).
/// </summary>
[DataElement(AllowDbNull = false)]
public int BookModel
{
get { return m_bookModel; }
set
{
Dirty = true;
m_bookModel = value;
}
}
/// <summary>
/// Scroll 1 name.
/// </summary>
[DataElement(AllowDbNull = false)]
public String Scroll1
{
get { return m_scroll1; }
set
{
Dirty = true;
m_scroll1 = value;
}
}
/// <summary>
/// Scroll 2 name.
/// </summary>
[DataElement(AllowDbNull = false)]
public String Scroll2
{
get { return m_scroll2; }
set
{
Dirty = true;
m_scroll2 = value;
}
}
/// <summary>
/// Scroll 3 name.
/// </summary>
[DataElement(AllowDbNull = false)]
public String Scroll3
{
get { return m_scroll3; }
set
{
Dirty = true;
m_scroll3 = value;
}
}
/// <summary>
/// Scrolls 1+2 name.
/// </summary>
[DataElement(AllowDbNull = false)]
public String Scroll12
{
get { return m_scroll12; }
set
{
Dirty = true;
m_scroll12 = value;
}
}
/// <summary>
/// Scrolls 1+3 name.
/// </summary>
[DataElement(AllowDbNull = false)]
public String Scroll13
{
get { return m_scroll13; }
set
{
Dirty = true;
m_scroll13 = value;
}
}
/// <summary>
/// Scrolls 2+3 name.
/// </summary>
[DataElement(AllowDbNull = false)]
public String Scroll23
{
get { return m_scroll23; }
set
{
Dirty = true;
m_scroll23 = value;
}
}
/// <summary>
/// Scroll model (icon) for a single scroll.
/// </summary>
[DataElement(AllowDbNull = false)]
public int ScrollModel1
{
get { return m_scrollModel1; }
set
{
Dirty = true;
m_scrollModel1 = value;
}
}
/// <summary>
/// Scroll model (icon) for 2 combined scrolls.
/// </summary>
[DataElement(AllowDbNull = false)]
public int ScrollModel2
{
get { return m_scrollModel2; }
set
{
Dirty = true;
m_scrollModel2 = value;
}
}
/// <summary>
/// Scroll level.
/// </summary>
[DataElement(AllowDbNull = false)]
public int ScrollLevel
{
get { return m_scrollLevel; }
set
{
Dirty = true;
m_scrollLevel = value;
}
}
/// <summary>
/// Message issued when scroll is used.
/// </summary>
[DataElement(AllowDbNull = false)]
public String MessageUse
{
get { return m_messageUse; }
set
{
Dirty = true;
m_messageUse = value;
}
}
/// <summary>
/// Message issued when scrolls are combined.
/// </summary>
[DataElement(AllowDbNull = false)]
public String MessageCombineScrolls
{
get { return m_messageCombineScrolls; }
set
{
Dirty = true;
m_messageCombineScrolls = value;
}
}
/// <summary>
/// Message issued when book is combined.
/// </summary>
[DataElement(AllowDbNull = false)]
public String MessageCombineBook
{
get { return m_messageCombineBook; }
set
{
Dirty = true;
m_messageCombineBook = value;
}
}
/// <summary>
/// Message issued when player receives scrolls.
/// </summary>
[DataElement(AllowDbNull = false)]
public String MessageReceiveScrolls
{
get { return m_messageReceiveScrolls; }
set
{
Dirty = true;
m_messageReceiveScrolls = value;
}
}
/// <summary>
/// Message issued when player receives the book.
/// </summary>
[DataElement(AllowDbNull = false)]
public String MessageReceiveBook
{
get { return m_messageReceiveBook; }
set
{
Dirty = true;
m_messageReceiveBook = value;
}
}
/// <summary>
/// The bounty point credit for this artifact.
/// </summary>
[DataElement(AllowDbNull = true)]
public String Credit
{
get { return m_credit; }
set
{
Dirty = true;
m_credit = value;
}
}
}
}
| gpl-2.0 |
kydrenw/boca | wp-content/themes/boca/templates/header.php | 2063 | <section id="top-header">
<div class="container">
<div class="content row">
<div class="col-sm-12">
<div id="logo-content">
<div><a href="#"><img src="<?php echo bloginfo('template_url'); ?>/assets/img/main-logo.png" alt="Boca"></a></div>
<h1>Bristol Owners Club</h1>
<div><h3>Australia</h3></div>
</div><!--end logo-content-->
<div id="account-box">
<div class="account-content">
<?php if(is_user_logged_in()){ ?>
<?php
//if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('login-sidebar') ) :
//endif;
?>
<?php dynamic_sidebar('sidebar-header'); ?>
<a id="username" href="<?php bloginfo('url'); ?>/my-account"><?php echo S2MEMBER_CURRENT_USER_DISPLAY_NAME; ?></a> | <a class="logoutlink" href="<?php echo wp_logout_url( home_url() ); ?>">Logout</a>
<?php } else { ?>
<a class="signinlink" data-turn="0" href="<?php bloginfo('url'); ?>/wp-login.php">Sign in</a><span class="devide">|</span><a class="registerlink" href="<?php bloginfo('url'); ?>/registration">Register 123 123</a>
<div id="quick-login">
<?php
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('login-sidebar') ) :
endif;
?>
</div>
<?php } ?>
</div><!--end account-content -->
</div><!--end account-box -->
</div>
</div>
</div>
</section><!--end top header -->
<header class="banner container" role="banner">
<div class="row">
<div class="col-lg-12">
<a class="brand" href="<?php echo home_url('/') ?>"><?php bloginfo('name'); ?></a>
<nav class="nav-main" role="navigation">
<?php
if (has_nav_menu('primary_navigation')) :
wp_nav_menu(array('theme_location' => 'primary_navigation', 'menu_class' => 'nav nav-pills'));
endif;
?>
</nav>
</div>
</div>
</header>
| gpl-2.0 |
hashfunktion/icingaweb2-module-director | library/Director/Web/Table/SyncruleTable.php | 1838 | <?php
namespace Icinga\Module\Director\Web\Table;
use dipl\Html\Link;
use dipl\Web\Table\ZfQueryBasedTable;
class SyncruleTable extends ZfQueryBasedTable
{
protected $searchColumns = [
'rule_name',
'description',
];
protected function assemble()
{
$this->getAttributes()->add('class', 'syncstate');
parent::assemble();
}
public function renderRow($row)
{
$caption = [Link::create(
$row->rule_name,
'director/syncrule',
['id' => $row->id]
)];
if ($row->description !== null) {
$caption[] = ': ' . $row->description;
}
if ($row->sync_state === 'failing' && $row->last_error_message) {
$caption[] = ' (' . $row->last_error_message . ')';
}
$tr = $this::row([$caption, $row->object_type]);
$tr->getAttributes()->add('class', $row->sync_state);
return $tr;
}
public function getColumnsToBeRendered()
{
return [
$this->translate('Rule name'),
$this->translate('Object type'),
];
}
public function prepareQuery()
{
return $this->db()->select()->from(
['s' => 'sync_rule'],
[
'id' => 's.id',
'rule_name' => 's.rule_name',
'sync_state' => 's.sync_state',
'object_type' => 's.object_type',
'update_policy' => 's.update_policy',
'purge_existing' => 's.purge_existing',
'filter_expression' => 's.filter_expression',
'last_error_message' => 's.last_error_message',
'description' => 's.description',
]
)->order('rule_name');
}
}
| gpl-2.0 |
Baaleos/nwnx2-linux | plugins/jvm/java/src/org/nwnx/nwnx2/jvm/constants/FeatGreaterSpell.java | 1751 | package org.nwnx.nwnx2.jvm.constants;
/**
* This class contains all unique constants beginning with "FEAT_GREATER_SPELL".
* Non-distinct keys are filtered; only the LAST appearing was
* kept.
*/
public final class FeatGreaterSpell {
private FeatGreaterSpell() {}
public final static int FOCUS_ABJURATION = 393;
public final static int FOCUS_CONJURATION = 394;
public final static int FOCUS_DIVINATION = 395;
public final static int FOCUS_DIVINIATION = 395;
public final static int FOCUS_ENCHANTMENT = 396;
public final static int FOCUS_EVOCATION = 397;
public final static int FOCUS_ILLUSION = 398;
public final static int FOCUS_NECROMANCY = 399;
public final static int FOCUS_TRANSMUTATION = 400;
public final static int PENETRATION = 401;
public static String nameOf(int value) {
if (value == 393) return "FeatGreaterSpell.FOCUS_ABJURATION";
if (value == 394) return "FeatGreaterSpell.FOCUS_CONJURATION";
if (value == 395) return "FeatGreaterSpell.FOCUS_DIVINATION";
if (value == 395) return "FeatGreaterSpell.FOCUS_DIVINIATION";
if (value == 396) return "FeatGreaterSpell.FOCUS_ENCHANTMENT";
if (value == 397) return "FeatGreaterSpell.FOCUS_EVOCATION";
if (value == 398) return "FeatGreaterSpell.FOCUS_ILLUSION";
if (value == 399) return "FeatGreaterSpell.FOCUS_NECROMANCY";
if (value == 400) return "FeatGreaterSpell.FOCUS_TRANSMUTATION";
if (value == 401) return "FeatGreaterSpell.PENETRATION";
return "FeatGreaterSpell.(not found: " + value + ")";
}
public static String nameOf(float value) {
return "FeatGreaterSpell.(not found: " + value + ")";
}
public static String nameOf(String value) {
return "FeatGreaterSpell.(not found: " + value + ")";
}
}
| gpl-2.0 |
Wikia/OldStructuredDataPrototype | extensions/VisualEditor/modules/ve/init/sa/ve.init.sa.Target.js | 1281 | /*!
* VisualEditor Standalone Initialization Target class.
*
* @copyright 2011-2013 VisualEditor Team and others; see AUTHORS.txt
* @license The MIT License (MIT); see LICENSE.txt
*/
/**
* Initialization Standalone target.
*
* @example
* new ve.init.sa.Target(
* $( '<div>' ).appendTo( 'body' ), ve.createDocumentFromHtml( '<p>Hello world.</p>' )
* );
*
* @class
* @extends ve.init.Target
*
* @constructor
* @param {jQuery} $container Container to render target into
* @param {ve.dm.Document} doc Document model
*/
ve.init.sa.Target = function VeInitSaTarget( $container, doc ) {
// Parent constructor
ve.init.Target.call( this, $container );
// Properties
this.surface = new ve.ui.Surface( doc );
this.toolbar = new ve.ui.TargetToolbar( this, this.surface, { 'shadow': true } );
// Initialization
this.toolbar.$element.addClass( 've-init-sa-target-toolbar' );
this.toolbar.setup( this.constructor.static.toolbarGroups );
this.toolbar.enableFloatable();
this.$element.append( this.toolbar.$element, this.surface.$element );
this.toolbar.initialize();
this.surface.addCommands( this.constructor.static.surfaceCommands );
this.surface.initialize();
};
/* Inheritance */
OO.inheritClass( ve.init.sa.Target, ve.init.Target );
| gpl-2.0 |
Voskrese/mipsonqemu | user/uc/home/source/unused/cp_domain.php | 2150 | <?php
/*
[UCenter Home] (C) 2007-2008 Comsenz Inc.
$Id: cp_domain.php 12141 2009-05-12 07:07:52Z zhengqingpeng $
*/
if(!defined('IN_UCHOME')) {
exit('Access Denied');
}
//¶þ¼¶ÓòÃû
$domainlength = checkperm('domainlength');
if($_SCONFIG['allowdomain'] && $_SCONFIG['domainroot'] && $domainlength) {
$reward = getreward('modifydomain', 0);
} else {
showmessage('no_privilege');
}
if(submitcheck('domainsubmit')) {
$setarr = array();
//¶þ¼¶ÓòÃû
$_POST['domain'] = strtolower(trim($_POST['domain']));
if($_POST['domain'] != $space['domain']) {
//»ý·Ö
if($space['domain'] && ($reward['credit'] || $reward['experience'])) {
if($space['experience'] >= $reward['experience']) {
$setarr['experience'] = $space['experience'] - $reward['experience'];
} else {
showmessage('experience_inadequate', '', 1, array($space['experience'], $reward['experience']));
}
if($space['credit'] >= $reward['credit']) {
$setarr['credit'] = $space['credit'] - $reward['credit'];
} else {
showmessage('integral_inadequate', '', 1, array($space['credit'], $reward['credit']));
}
}
if(empty($domainlength) || empty($_POST['domain'])) {
$setarr['domain'] = '';
} else {
if(strlen($_POST['domain']) < $domainlength) {
showmessage('domain_length_error', '', 1, array($domainlength));
}
if(strlen($_POST['domain']) > 30) {
showmessage('two_domain_length_not_more_than_30_characters');
}
if(!preg_match("/^[a-z][a-z0-9]*$/", $_POST['domain'])) {
showmessage('only_two_names_from_english_composition_and_figures');
}
if(isholddomain($_POST['domain'])) {
showmessage('domain_be_retained');//debug
}
$count = getcount('space', array('domain'=>$_POST['domain']));
if($count) {
showmessage('two_domain_have_been_occupied');
}
$setarr['domain'] = $_POST['domain'];
}
}
if($setarr) updatetable('space', $setarr, array('uid'=>$_SGLOBAL['supe_uid']));
showmessage('do_success', 'cp.php?ac=domain');
}
$actives = array($ac => ' class="active"');
include_once template("cp_domain");
?> | gpl-2.0 |
gamenew09/GMod-Jailbreak | entities/weapons/weapon_weaponchecker/shared.lua | 2031 | -- First some standard GMod stuff
if SERVER then
AddCSLuaFile( )
end
if CLIENT then
SWEP.PrintName = "Weapon Checker"
SWEP.Slot = 0 -- add 1 to get the slot number key
SWEP.ViewModelFOV = 72
SWEP.ViewModelFlip = true
end
SWEP.IllegalWeapons = {
"ptp_cs"
}
-- Always derive from weapon_tttbase.
SWEP.Base = "weapon_base"
--- Standard GMod values
SWEP.HoldType = "ar2"
SWEP.Primary.ClipSize = -1
SWEP.Primary.Damage = 100
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo ="none"
SWEP.IronSightsPos = Vector( 6.05, -5, 2.4 )
SWEP.IronSightsAng = Vector( 2.2, -0.1, 0 )
SWEP.ViewModel = "models/weapons/v_c4.mdl"
SWEP.WorldModel = "models/weapons/w_c4.mdl"
local deb = false
function SWEP:PrimaryAttack()
if deb then return end
deb = true
local tr = {}
tr.start = self.Owner:GetShootPos()
tr.endpos = self.Owner:GetShootPos() + ( self.Owner:GetAimVector() * 100 )
tr.filter = self.Owner
tr.mask = MASK_SHOT
local trace = util.TraceLine( tr )
self.Weapon:SetNextPrimaryFire(CurTime() + 0.9)
self.Owner:SetAnimation( PLAYER_ATTACK1 )
if(trace.Hit)then
if trace.Entity:IsPlayer() then
local ilWeapons = {}
local ply = trace.Entity
local weaps = ply:GetWeapons()
for i,v in pairs(weaps)do
for i2, v2 in pairs(self.IllegalWeapons)do
if(v2 == v:GetClass() or string.find(v:GetClass(), v2) ~= nil)then
table.insert(ilWeapons, v)
end
end
end
local ilWeaponsStr = ""
for i,v in pairs(ilWeapons)do
ilWeaponsStr = ilWeaponsStr .. v:GetPrintName().."\n"
end
ply:PrintMessage(HUD_PRINTTALK, "Illegal Weapons: \n"..ilWeaponsStr)
end
end
deb = false
end
/*---------------------------------------------------------
Reload
---------------------------------------------------------*/
function SWEP:SecondaryAttack()
end
/*---------------------------------------------------------
Reload
---------------------------------------------------------*/
function SWEP:Reload()
return false
end
| gpl-2.0 |
enixdark/Project_Class_Management | src/DTO/New_DTO.java | 494 | package DTO;
public class New_DTO {
private int manew;
private String news;
public int getManew() {
return manew;
}
public void setManew(int manew) {
this.manew = manew;
}
public String getNews() {
return news;
}
public void setNews(String news) {
this.news = news;
}
public New_DTO(int manew){
this.manew = manew;
}
public New_DTO(int manew,String news){
this.manew = manew;
this.news = news;
}
public New_DTO() {
// TODO Auto-generated constructor stub
}
}
| gpl-2.0 |
apoorvingle/tango-with-django | tango_with_django_project/populate_rango.py | 1763 | import os
def populate():
python_cat = add_cat('Python')
add_page(cat=python_cat,
title="Official Python Tutorial",
url="http://docs.python.org/2/tutorial/")
add_page(cat=python_cat,
title="How to Think like a Computer Scientist",
url="http://www.greenteapress.com/thinkpython/")
add_page(cat=python_cat,
title="Learn Python in 10 Minutes",
url="http://www.korokithakis.net/tutorials/python/")
django_cat = add_cat("Django")
add_page(cat=django_cat,
title="Official Django Tutorial",
url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/")
add_page(cat=django_cat,
title="Django Rocks",
url="http://www.djangorocks.com/")
add_page(cat=django_cat,
title="How to Tango with Django",
url="http://www.tangowithdjango.com/")
frame_cat = add_cat("Other Frameworks")
add_page(cat=frame_cat,
title="Bottle",
url="http://bottlepy.org/docs/dev/")
add_page(cat=frame_cat,
title="Flask",
url="http://flask.pocoo.org")
# Print out what we have added to the user.
for c in Category.objects.all():
for p in Page.objects.filter(category=c):
print "- {0} - {1}".format(str(c), str(p))
def add_page(cat, title, url, views=0):
p = Page.objects.get_or_create(category=cat, title=title, url=url, views=views)[0]
return p
def add_cat(name):
c = Category.objects.get_or_create(name=name)[0]
return c
# Start execution here!
if __name__ == '__main__':
print "Starting Rango population script..."
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')
from rango.models import Category, Page
populate()
| gpl-2.0 |
freeenergy/review | wp-content/themes/review_engine_developer/processing/single_product_processing.php | 10138 | <?php
global $current_user, $user_ID, $post, $wpdb, $helper, $wp_query;
/**
* show product
*/
$product = array(
'rating' => array(
'user' => array(
'count' => 0,
'rating' => 0
),
'editor' => array(
'count' => 0,
'rating' => 0
)
));
$product['rating']['user']['count'] = get_post_meta($post->ID, PRODUCT_RATING_COUNT, true);
$product['rating']['user']['rating'] = get_post_meta($post->ID, PRODUCT_RATING, true);
$product['rating']['editor']['count'] = get_post_meta($post->ID, PRODUCT_EDITOR_RATING_COUNT, true);
$product['rating']['editor']['rating'] = get_post_meta($post->ID, PRODUCT_EDITOR_RATING, true);
///////*** review
///////***
/**
* check user role, if user is an reviewer enable rich text document for him
*/
$user_have_editor = get_option('tgt_user_have_editor');
$editor_enable = false;
$curr_user = new WP_User ( $user_ID );
$role = empty ( $curr_user->roles[0] ) ? '' : $curr_user->roles[0];
if ( !empty($role) && $role != ROLE_MEMBER ){
$editor_enable = true;
}
if ($role == ROLE_MEMBER && !empty($user_have_editor)) {
$editor_enable = true;
}
/**
* check if user has review this or not
*/
$has_reviewed = has_reviewed( $user_ID, $post->ID );
/**
* error message define
*/
$error_title_empty = __('Title can not be empty','re');
$error_title_short = __('Title is too short','re');
$error_con_empty = __('Please tell us what make you like about this product','re');
$error_con_short = __('Your reason is too short','re');
$error_pro_empty = __('Please tell us what make you dislike about this product','re');
$error_pro_short = __('Your reason is too short','re');
$error_not_rating = __('You have forgotten rating for this product ','re');
$error_username_empty = __('Your name can not be empty','re');
$error_useremail_empty = __('Your email can not be empty','re');
$error_useremail_invalid = __('Your email invalid.','re');
$limitation = array();
$limitation['title'] = get_option('tgt_title_limit');
$limitation['pro'] = get_option('tgt_pro_limit');
$limitation['con'] = get_option('tgt_con_limit');
$limitation['bottomline'] = get_option('tgt_bottom_line_limit');
$limitation['review'] = get_option('tgt_review_limit');
/**
* post processing
*/
$error = '';
$review = array();
$success = false;
$allowed_tags = '<p><a><table><tr><td><th><ul><ol><li><dt><dl><br><img><b><i><u><strong><h1><h2><h3><h4><h5><h6><code><pre><span><em>';
if (!empty($_POST['submit_review'])){
try{
if ($has_reviewed)
throw new Exception(__('You have reviewed this product already ','re'));
$review['title'] = empty($_POST['title']) ? '' : strip_tags( $_POST['title'] );
$review['pro'] = empty($_POST['pro']) ? '' : strip_tags( $_POST['pro'] );
$review['con'] = empty($_POST['con']) ? '' : strip_tags( $_POST['con'] );
$review['bottomline'] = empty($_POST['bottomline']) ? '' : strip_tags( $_POST['bottomline'] );
$review['review'] = empty($_POST['review']) ? '' : strip_tags( $_POST['review'], $allowed_tags );
$review['username'] = empty($_POST['user_name']) ? '' : strip_tags( $_POST['user_name'] );
$review['user_email'] = empty($_POST['user_email']) ? '' : strip_tags( $_POST['user_email'] );
//set post id
$review['id'] = '';
if (!empty ( $post->ID) )
$review['id'] = $post->ID;
else {
throw new Exception(__('There is error occurred, please try again later','re'));
}
//set author
if (empty ($current_user))
throw new Exception(__('There is error occurred, please try again later','re'));
$review['author'] = $current_user;
// get rating
$rates = array();
if (isset($_POST['rating'])){
$rates = $_POST['rating'];
}
$rating = array();
$rating['rates'] = array();
$rating['sum'] = 0;
$total_rate = 0;
$count = 0;
if (is_array($rates) && !empty($rates)){
foreach ( (array)$rates as $key => $rate){
$rating['rates'][$key] = floatval($rate);
$total_rate += floatval($rate);
$count++;
}}
if ($count)
$rating['sum'] = $total_rate / $count;
else
$rating['sum'] = 0;
/**
* validate
*/
if ( isset($_POST['title']) && empty ($review['title'] )){
$error .= ' - ' . $error_title_empty . '<br />';
}
if ( isset($_POST['pro']) && empty ( $review['pro'] )){
$error .= ' - ' . $error_pro_empty . '<br />';
}
if ( isset($_POST['con']) && empty ( $review['con'] )){
$error .= ' - ' . $error_con_empty . '<br />';
}
/**
* get limitation for validate
*/
$limit_validate = array(
'title' => __('Title is too long','re'),
'pro' => __('"The Good" of product is too long','re'),
'con' => __('"The Bad" of product is too long','re'),
'bottomline' => __('"Bottom line" of product is too long','re'),
'review' => __('Review content of prroduct is too long','re')
);
foreach( $limit_validate as $key => $msg )
{
if ( count($review[ $key ]) > $limitation[ $key ] )
$error .= ' - ' . $msg . '<br />';
}
if (empty($error)){
// if there is no wrong
// add review conetnt
$time = current_time('mysql');
$type = '';
if ($role == ROLE_EDITOR){
$type = 'editor_review';
}
else {
$type = 'review';
}
$author_comment = '';
$author_email = '';
$author_url = '';
if($current_user->ID < 1)
{
$author_comment = $review['username'];
$author_email = $review['user_email'];
}
else {
$author_comment = $current_user->display_name;
$author_email = $current_user->user_email;
$author_url = $current_user->user_url;
}
$data = array(
'comment_post_ID' => $review['id'],
'comment_author' => $author_comment,
'comment_author_email' => $author_email,
'comment_author_url' => $current_user->user_url,
'comment_content' => nl2br($review['bottomline']),
'comment_type' => $type,
'comment_parent' => 0,
'comment_approved' => 0,
'user_id' => $user_ID
);
$review_ID = wp_insert_comment($data);
if (!empty($review_ID)){
//insert
$review_data = array(
'title' => nl2br( $review['title'] ),
'pro' => nl2br( $review['pro'] ),
'con' => nl2br( $review['con'] ),
'review' => nl2br( $review['review'] )
);
update_comment_meta( $review_ID ,'tgt_review_data', $review_data);
//insert rating for review
update_comment_meta( $review_ID ,'tgt_review_rating', $rating);
// if auto publish
$is_auto_publish = get_option( SETTING_AUTO_PUBLISH );
if ($is_auto_publish && is_trusted_user($user_ID)) {
wp_set_comment_status($review_ID, 'approve');
}
}
else {
throw new Exception(__('There is error occurred, please try again later','re'));
}
}
}catch (Exception $ex){
if ( !$ex->getMessage() )
$error .= $ex->getMessage();
$success = false;
}
/**
* Display message to user
*/
$link = $helper->link('here', get_permalink($post->ID) );
$back_link = '<br />' . __('click ','re') . $link . __(" to go back product's page",'re');
if (!empty($error)){
$message = $error . $back_link;
setMessage($message, 'error');
}
else{
$message = __('You have submit a review successfully', 're') . $back_link;
setMessage($message);
}
}
// Submit comment for product
if (!empty($_POST['submit_comment'])){
try{
global $current_user;
$review['username'] = empty($_POST['user_name']) ? '' : strip_tags( $_POST['user_name'] );
$review['user_email'] = empty($_POST['user_email']) ? '' : strip_tags( $_POST['user_email'] );
$review['comment_pro'] = empty($_POST['comment_pro']) ? '' : strip_tags( $_POST['comment_pro'] );
//set post id
$review['id'] = '';
if (!empty ( $post->ID) )
$review['id'] = $post->ID;
else {
throw new Exception(__('There is error occurred, please try again later','re'));
}
//set author
$review['author'] = 0;
if(!empty($current_user))
$review['author'] = $current_user;
/**
* validate
*/
if ( isset($_POST['comment_pro']) && empty ( $review['comment_pro'] )){
$error .= ' - ' . $error_pro_empty . '<br />';
}
/**
* get limitation for validate
*/
if (empty($error)){
// if there is no wrong
// add review conetnt
$time = current_time('mysql');
$type = 'comment';
$author_comment = '';
$author_email = '';
$author_url = '';
if($current_user->ID < 1)
{
$author_comment = $review['username'];
$author_email = $review['user_email'];
}
else {
$author_comment = $current_user->display_name;
$author_email = $current_user->user_email;
$author_url = $current_user->user_url;
}
$data = array(
'comment_post_ID' => $review['id'],
'comment_author' => $author_comment,
'comment_author_email' => $author_email,
'comment_author_url' => ($current_user->user_url != '')?$current_user->user_url:'',
'comment_content' => nl2br($review['comment_pro']),
'comment_type' => $type,
'comment_parent' => (isset($_POST['parent_id']) && $_POST['parent_id'] > 0)?$_POST['parent_id']:0,
'comment_approved' => 0,
'user_id' => $user_ID
);
$review_ID = wp_insert_comment($data);
if (!empty($review_ID)){
$is_auto_publish = get_option( SETTING_AUTO_PUBLISH );
if ($is_auto_publish && is_trusted_user($user_ID)) {
wp_set_comment_status($review_ID, 'approve');
}
}
else {
throw new Exception(__('There is error occurred, please try again later','re'));
}
}
}catch (Exception $ex){
if ( !$ex->getMessage() )
$error .= $ex->getMessage();
$success = false;
}
/**
* Display message to user
*/
if (!empty($error)){
$message = $error . $back_link;
setMessage($message, 'error');
}
}
?> | gpl-2.0 |
nattthebear/dolphin-avsync | Source/Core/VideoCommon/Src/HiresTextures.cpp | 4296 | // Copyright (C) 2003 Dolphin Project.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 2.0.
// 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 2.0 for more details.
// A copy of the GPL 2.0 should have been included with the program.
// If not, see http://www.gnu.org/licenses/
// Official SVN repository and contact information can be found at
// http://code.google.com/p/dolphin-emu/
#include "HiresTextures.h"
#include <cstring>
#include <utility>
#include <algorithm>
#include <SOIL/SOIL.h>
#include "CommonPaths.h"
#include "FileUtil.h"
#include "FileSearch.h"
#include "StringUtil.h"
namespace HiresTextures
{
std::map<std::string, std::string> textureMap;
void Init(const char *gameCode)
{
textureMap.clear();
CFileSearch::XStringVector Directories;
//Directories.push_back(File::GetUserPath(D_HIRESTEXTURES_IDX));
char szDir[MAX_PATH];
sprintf(szDir, "%s%s", File::GetUserPath(D_HIRESTEXTURES_IDX).c_str(), gameCode);
Directories.push_back(std::string(szDir));
for (u32 i = 0; i < Directories.size(); i++)
{
File::FSTEntry FST_Temp;
File::ScanDirectoryTree(Directories[i], FST_Temp);
for (u32 j = 0; j < FST_Temp.children.size(); j++)
{
if (FST_Temp.children.at(j).isDirectory)
{
bool duplicate = false;
for (u32 k = 0; k < Directories.size(); k++)
{
if (strcmp(Directories[k].c_str(), FST_Temp.children.at(j).physicalName.c_str()) == 0)
{
duplicate = true;
break;
}
}
if (!duplicate)
Directories.push_back(FST_Temp.children.at(j).physicalName.c_str());
}
}
}
CFileSearch::XStringVector Extensions;
Extensions.push_back("*.png");
Extensions.push_back("*.bmp");
Extensions.push_back("*.tga");
Extensions.push_back("*.dds");
Extensions.push_back("*.jpg"); // Why not? Could be useful for large photo-like textures
CFileSearch FileSearch(Extensions, Directories);
const CFileSearch::XStringVector& rFilenames = FileSearch.GetFileNames();
char code[MAX_PATH];
sprintf(code, "%s_", gameCode);
if (rFilenames.size() > 0)
{
for (u32 i = 0; i < rFilenames.size(); i++)
{
std::string FileName;
SplitPath(rFilenames[i], NULL, &FileName, NULL);
if (FileName.substr(0, strlen(code)).compare(code) == 0 && textureMap.find(FileName) == textureMap.end())
textureMap.insert(std::map<std::string, std::string>::value_type(FileName, rFilenames[i]));
}
}
}
bool HiresTexExists(const char* filename)
{
std::string key(filename);
return textureMap.find(key) != textureMap.end();
}
PC_TexFormat GetHiresTex(const char *fileName, unsigned int *pWidth, unsigned int *pHeight, unsigned int *required_size, int texformat, unsigned int data_size, u8 *data)
{
std::string key(fileName);
if (textureMap.find(key) == textureMap.end())
return PC_TEX_FMT_NONE;
int width;
int height;
int channels;
u8 *temp = SOIL_load_image(textureMap[key].c_str(), &width, &height, &channels, SOIL_LOAD_RGBA);
if (temp == NULL)
{
ERROR_LOG(VIDEO, "Custom texture %s failed to load", textureMap[key].c_str());
return PC_TEX_FMT_NONE;
}
*pWidth = width;
*pHeight = height;
int offset = 0;
PC_TexFormat returnTex = PC_TEX_FMT_NONE;
switch (texformat)
{
case GX_TF_I4:
case GX_TF_I8:
case GX_TF_IA4:
case GX_TF_IA8:
*required_size = width * height * 8;
if (data_size < *required_size)
goto cleanup;
for (int i = 0; i < width * height * 4; i += 4)
{
// Rather than use a luminosity function, just use the most intense color for luminance
// TODO(neobrain): Isn't this kind of.. stupid?
data[offset++] = *std::max_element(temp+i, temp+i+3);
data[offset++] = temp[i+3];
}
returnTex = PC_TEX_FMT_IA8;
break;
default:
*required_size = width * height * 4;
if (data_size < *required_size)
goto cleanup;
memcpy(data, temp, width * height * 4);
returnTex = PC_TEX_FMT_RGBA32;
break;
}
INFO_LOG(VIDEO, "loading custom texture from %s", textureMap[key].c_str());
cleanup:
SOIL_free_image_data(temp);
return returnTex;
}
}
| gpl-2.0 |
fahadhatib/KwaMoja | Z_CheckGLTransBalance.php | 1414 | <?php
include('includes/session.inc');
$Title = _('Check Period Sales Ledger Control Account');
include('includes/header.inc');
echo '<table>';
$Header = '<tr>
<th>' . _('Type') . '</th>
<th>' . _('Number') . '</th>
<th>' . _('Period') . '</th>
<th>' . _('Difference') . '</th>
</tr>';
echo $Header;
$SQL = "SELECT gltrans.type,
systypes.typename,
gltrans.typeno,
periodno,
SUM(amount) AS nettot
FROM gltrans,
systypes
WHERE gltrans.type = systypes.typeid
GROUP BY gltrans.type,
systypes.typename,
typeno,
periodno
HAVING ABS(SUM(amount))>= " . 1/pow(10,$_SESSION['CompanyRecord']['decimalplaces']) . "
ORDER BY gltrans.counterindex";
$OutOfWackResult = DB_query($SQL);
$RowCounter = 0;
while ($OutOfWackRow = DB_fetch_array($OutOfWackResult)) {
if ($RowCounter == 18) {
$RowCounter = 0;
echo $Header;
} else {
$RowCounter++;
}
echo '<tr>
<td><a href="' . $RootPath . '/GLTransInquiry.php?TypeID=' . urlencode($OutOfWackRow['type']) . '&TransNo=' . urlencode($OutOfWackRow['typeno']) . '">' . $OutOfWackRow['typename'] . '</a></td>
<td class="number">' . $OutOfWackRow['typeno'] . '</td>
<td class="number">' . $OutOfWackRow['periodno'] . '</td>
<td class="number">' . locale_number_format($OutOfWackRow['nettot'], $_SESSION['CompanyRecord']['decimalplaces']) . '</td>
</tr>';
}
echo '</table>';
include('includes/footer.inc');
?> | gpl-2.0 |
WillyXJ/facileManager | server/fm-modules/fmFirewall/variables.inc.php | 6880 | <?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2013-2019 The facileManager Team |
| |
| 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. |
+-------------------------------------------------------------------------+
| facileManager: Easy System Administration |
| fmFirewall: Easily manage one or more software firewalls |
+-------------------------------------------------------------------------+
| http://www.facilemanager.com/modules/fmfirewall/ |
+-------------------------------------------------------------------------+
*/
/**
* Contains variables for fmFirewall
*
* @package fmFirewall
*
*/
if (!@is_array($__FM_CONFIG)) $__FM_CONFIG = array();
/** Module Version */
$__FM_CONFIG['fmFirewall'] = array(
'version' => '2.1.0',
'client_version' => '1.8',
'description' => __('Managing software firewalls should not be difficult. Manage one or more software firewall servers (iptables, ipfw, ipf, pf) through a web interface rather than configuration files individually.', 'fmFirewall'),
'prefix' => 'fw_',
'required_fm_version' => '4.1.0',
'min_client_auto_upgrade_version' => '1.3'
);
/** Images */
if (isset($__FM_CONFIG['module']['path'])) {
$__FM_CONFIG['module']['icons']['action']['pass'] = '<i class="fa fa-arrow-up __action__" alt="__Action__" title="__Action__"></i>';
$__FM_CONFIG['module']['icons']['action']['block'] = '<i class="fa fa-times __action__" alt="__Action__" title="__Action__"></i>';
$__FM_CONFIG['module']['icons']['action']['reject'] = '<i class="fa fa-times __action__" alt="__Action__" title="__Action__"></i>';
$__FM_CONFIG['module']['icons']['action']['log'] = '<i class="fa fa-file-text-o __action__" alt="__Action__" title="__Action__"></i>';
$__FM_CONFIG['module']['icons']['negated'] = sprintf('<a href="JavaScript:void(0);" class="tooltip-bottom" data-tooltip="%s"><i class="fa fa-exclamation-circle block" aria-hidden="true"></i></a>', __('Negated'));
}
$__FM_CONFIG['icons'] = @array_merge($__FM_CONFIG['module']['icons'], $__FM_CONFIG['icons']);
/** TCP Flags */
$__FM_CONFIG['tcp_flags'] = array('URG' => 1, 'ACK' => 2, 'PSH' => 4,
'RST' => 8, 'SYN' => 16, 'FIN' => 32);
/** Weekdays */
$__FM_CONFIG['weekdays'] = array(__('Mon') => 1, __('Tue') => 2, __('Wed') => 4,
__('Thu') => 8, __('Fri') => 16, __('Sat') => 32, __('Sun') => 64);
/** Policy options */
$__FM_CONFIG['fw']['policy_options'] = array(
'log' => array(
'firewalls' => array('iptables', 'ipfw', 'ipfilter', 'pf'),
'bit' => 1,
'desc' => __('Log packets processed by this rule')
),
'established' => array(
'firewalls' => array('ipfw', 'ipfilter'),
'bit' => 2,
'desc' => __('Established connection packets')
),
'frag' => array(
'firewalls' => array('iptables', 'ipfw', 'ipfilter'),
'bit' => 4,
'desc' => __('Matches packets that are fragments and not the first fragment of an IP datagram')
),
'quick' => array(
'firewalls' => array('pf'),
'bit' => 8,
'desc' => __('Cancel further rule processing with the "quick" keyword')
)
);
/** Policy states */
$__FM_CONFIG['fw']['policy_states'] = array(
'pf' => array('no state', 'keep state', 'modulate state', 'synproxy state'),
'ipfw' => array('keep-state'),
'iptables' => array('INVALID', 'ESTABLISHED', 'NEW', 'RELATED', 'UNTRACKED'),
'ipfilter' => array('keep state')
);
/** Default values */
$__FM_CONFIG['fw']['config_file'] = array(
'pf' => '/etc/pf.conf',
'ipfw' => '/etc/ipfw.rules',
'iptables' => array(
'Arch' => '/etc/iptables/iptables.rules',
'Fedora' => '/etc/sysconfig/iptables',
'Redhat' => '/etc/sysconfig/iptables',
'CentOS' => '/etc/sysconfig/iptables',
'ClearOS' => '/etc/sysconfig/iptables',
'Oracle' => '/etc/sysconfig/iptables',
'Gentoo' => '/var/lib/iptables/rules-save',
'Slackware' => '/etc/rc.d/rc.firewall'
),
'ipfilter' => array(
'FreeBSD' => '/etc/ipf.rules',
'SunOS' => '/etc/ipf/ipf.conf'
),
'default' => '/usr/local/facileManager/fmFirewall/fw.rules'
);
/** Firewall notes */
$__FM_CONFIG['fw']['notes'] = array(
'iptables' => __('Rules are evaluated on a first-match basis and everything that isn\'t explicitly blocked will be passed by default. So make sure you take care with your rule order.'),
'pf' => __('Rules are evaluated on a last-match basis and everything that isn\'t explicitly blocked will be allowed by default. So make sure you take care with your rule order.'),
'ipfw' => __('Rules are evaluated on a first-match basis and everything that isn\'t explicitly passed will be blocked by default. So make sure you take care with your rule order.'),
'ipfilter' => __('Rules are evaluated on a first-match basis and everything that isn\'t explicitly blocked will be passed by default. So make sure you take care with your rule order.')
);
$__FM_CONFIG['policy']['avail_types'] = array('filter' => 'Filter', 'nat' => 'NAT');
/** Cleanup options */
$__FM_CONFIG['module']['clean']['prefixes'] = array('fm_' . $__FM_CONFIG['fmFirewall']['prefix'] . 'groups'=>'group', 'fm_' . $__FM_CONFIG['fmFirewall']['prefix'] . 'objects'=>'object',
'fm_' . $__FM_CONFIG['fmFirewall']['prefix'] . 'policies'=>'policy', 'fm_' . $__FM_CONFIG['fmFirewall']['prefix'] . 'servers'=>'server',
'fm_' . $__FM_CONFIG['fmFirewall']['prefix'] . 'services'=>'service', 'fm_' . $__FM_CONFIG['fmFirewall']['prefix'] . 'time'=>'time'
);
$__FM_CONFIG['clean']['prefixes'] = @array_merge($__FM_CONFIG['clean']['prefixes'], $__FM_CONFIG['module']['clean']['prefixes']);
?>
| gpl-2.0 |
Josemurillo/frokTinkel | src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/instance_ruby_sanctum.cpp | 22665 | /*
* Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* AuraEmu
*/
#include "ScriptPCH.h"
#include "ruby_sanctum.h"
class instance_ruby_sanctum : public InstanceMapScript
{
public:
instance_ruby_sanctum() : InstanceMapScript("instance_ruby_sanctum", 724) { }
InstanceScript* GetInstanceScript(InstanceMap* pMap) const
{
return new instance_ruby_sanctum_InstanceMapScript(pMap);
}
struct instance_ruby_sanctum_InstanceMapScript : public InstanceScript
{
instance_ruby_sanctum_InstanceMapScript(Map* pMap) : InstanceScript(pMap) {Initialize();};
std::string strSaveData;
//Creatures GUID
uint32 m_auiEncounter[MAX_ENCOUNTERS+1];
uint32 m_auiEventTimer;
uint32 m_auiHalionEvent;
uint32 m_auiOrbDirection;
uint32 m_auiOrbNState;
uint32 m_auiOrbSState;
uint64 m_uiHalion_pGUID;
uint64 m_uiHalion_tGUID;
uint64 m_uiHalionControlGUID;
uint64 m_uiRagefireGUID;
uint64 m_uiZarithianGUID;
uint64 m_uiBaltharusGUID;
uint64 m_uiCloneGUID;
uint64 m_uiXerestraszaGUID;
uint64 m_uiOrbNGUID;
uint64 m_uiOrbSGUID;
uint64 m_uiOrbFocusGUID;
uint64 m_uiOrbCarrierGUID;
//object GUID
uint64 m_uiHalionPortal1GUID;
uint64 m_uiHalionPortal2GUID;
uint64 m_uiHalionPortal3GUID;
uint64 m_uiHalionFireWallSGUID;
uint64 m_uiHalionFireWallMGUID;
uint64 m_uiHalionFireWallLGUID;
uint64 m_uiBaltharusTargetGUID;
uint64 m_uiFireFieldGUID;
uint64 m_uiFlameWallsGUID;
uint64 m_uiFlameRingGUID;
uint64 m_uiArbolGUID;
uint64 m_uiArbol1GUID;
uint64 m_uiArbol2GUID;
uint64 m_uiArbol3GUID;
void Initialize()
{
for (uint8 i = 0; i < MAX_ENCOUNTERS; ++i)
m_auiEncounter[i] = NOT_STARTED;
m_auiEventTimer = 1000;
m_uiHalion_pGUID = 0;
m_uiHalion_tGUID = 0;
m_uiRagefireGUID = 0;
m_uiZarithianGUID = 0;
m_uiBaltharusGUID = 0;
m_uiCloneGUID = 0;
m_uiHalionPortal1GUID = 0;
m_uiHalionPortal2GUID = 0;
m_uiHalionPortal3GUID = 0;
m_uiArbolGUID = 0;
m_uiArbol1GUID = 0;
m_uiArbol2GUID = 0;
m_uiArbol3GUID = 0;
m_uiXerestraszaGUID = 0;
m_uiHalionFireWallSGUID = 0;
m_uiHalionFireWallMGUID = 0;
m_uiHalionFireWallLGUID = 0;
m_uiBaltharusTargetGUID = 0;
m_auiOrbDirection = 0;
m_uiOrbNGUID = 0;
m_uiOrbSGUID = 0;
m_uiOrbFocusGUID = 0;
m_auiOrbNState = NOT_STARTED;
m_auiOrbSState = NOT_STARTED;
}
bool IsEncounterInProgress() const
{
for(uint8 i = 1; i < MAX_ENCOUNTERS ; ++i)
if (m_auiEncounter[i] == IN_PROGRESS)
return true;
return false;
}
void OpenDoor(uint64 guid)
{
if(!guid)
return;
GameObject* pGo = instance->GetGameObject(guid);
if(pGo)
pGo->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE);
}
void CloseDoor(uint64 guid)
{
if(!guid)
return;
GameObject* pGo = instance->GetGameObject(guid);
if(pGo)
pGo->SetGoState(GO_STATE_READY);
}
void OpenAllDoors()
{
if (m_auiEncounter[TYPE_RAGEFIRE] == DONE &&
m_auiEncounter[TYPE_BALTHARUS] == DONE &&
m_auiEncounter[TYPE_XERESTRASZA] == DONE)
OpenDoor(m_uiFlameWallsGUID);
else
CloseDoor(m_uiFlameWallsGUID);
}
void UpdateWorldState(bool command, uint32 value)
{
Map::PlayerList const &players = instance->GetPlayers();
if (command)
{
for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i)
if(Player* pPlayer = i->getSource())
if(pPlayer->isAlive())
{
pPlayer->SendUpdateWorldState(UPDATE_STATE_UI_SHOW,0);
if (pPlayer->HasAura(74807))
pPlayer->SendUpdateWorldState(UPDATE_STATE_UI_COUNT_T, 100 - value);
else pPlayer->SendUpdateWorldState(UPDATE_STATE_UI_COUNT_R, value);
pPlayer->SendUpdateWorldState(UPDATE_STATE_UI_SHOW,1);
}
}
else
{
for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i)
if(Player* pPlayer = i->getSource())
if(pPlayer->isAlive())
pPlayer->SendUpdateWorldState(UPDATE_STATE_UI_SHOW,0);
}
}
void OnCreatureCreate(Creature* pCreature)
{
switch(pCreature->GetEntry())
{
case NPC_HALION_REAL:
m_uiHalion_pGUID = pCreature->GetGUID();
break;
case NPC_HALION_TWILIGHT:
m_uiHalion_tGUID = pCreature->GetGUID();
break;
case NPC_HALION_CONTROL:
m_uiHalionControlGUID = pCreature->GetGUID();
break;
case NPC_RAGEFIRE:
m_uiRagefireGUID = pCreature->GetGUID();
break;
case NPC_ZARITHIAN:
m_uiZarithianGUID = pCreature->GetGUID();
break;
case NPC_BALTHARUS:
m_uiBaltharusGUID = pCreature->GetGUID();
break;
case NPC_BALTHARUS_TARGET:
m_uiBaltharusTargetGUID = pCreature->GetGUID();
break;
case NPC_CLONE:
m_uiCloneGUID = pCreature->GetGUID();
break;
case NPC_XERESTRASZA:
m_uiXerestraszaGUID = pCreature->GetGUID();
break;
case NPC_SHADOW_PULSAR_N:
m_uiOrbNGUID = pCreature->GetGUID();
break;
case NPC_SHADOW_PULSAR_S:
m_uiOrbSGUID = pCreature->GetGUID();
break;
case NPC_ORB_ROTATION_FOCUS:
m_uiOrbFocusGUID = pCreature->GetGUID();
break;
case NPC_ORB_CARRIER:
m_uiOrbCarrierGUID = pCreature->GetGUID();
break;
}
}
void OnGameObjectCreate(GameObject* pGo)
{
switch(pGo->GetEntry())
{
case GO_HALION_PORTAL_1:
m_uiHalionPortal1GUID = pGo->GetGUID();
break;
case GO_HALION_PORTAL_2:
m_uiHalionPortal2GUID = pGo->GetGUID();
break;
case GO_HALION_PORTAL_3:
m_uiHalionPortal3GUID = pGo->GetGUID();
break;
case GO_FLAME_WALLS:
m_uiFlameWallsGUID = pGo->GetGUID();
break;
case GO_FLAME_RING:
m_uiFlameRingGUID = pGo->GetGUID();
break;
case GO_FIRE_FIELD:
m_uiFireFieldGUID = pGo->GetGUID();
break;
case GO_ARBOL:
m_uiArbolGUID = pGo->GetGUID();
break;
case GO_ARBOL1:
m_uiArbol1GUID = pGo->GetGUID();
break;
case GO_ARBOL2:
m_uiArbol2GUID = pGo->GetGUID();
break;
case GO_ARBOL3:
m_uiArbol3GUID = pGo->GetGUID();
break;
}
OpenAllDoors();
}
void SetData(uint32 uiType, uint32 uiData)
{
switch(uiType)
{
case TYPE_EVENT:
m_auiEncounter[uiType] = uiData;
uiData = NOT_STARTED;
break;
case TYPE_RAGEFIRE:
m_auiEncounter[uiType] = uiData;
OpenAllDoors();
break;
case TYPE_BALTHARUS:
m_auiEncounter[uiType] = uiData;
OpenAllDoors();
break;
case TYPE_XERESTRASZA:
m_auiEncounter[uiType] = uiData;
if (uiData == IN_PROGRESS)
OpenDoor(m_uiFireFieldGUID);
else if (uiData == NOT_STARTED)
{
CloseDoor(m_uiFireFieldGUID);
OpenAllDoors();
}
else if (uiData == DONE)
{
OpenAllDoors();
if (m_auiEncounter[TYPE_ZARITHRIAN] == DONE)
{
m_auiEncounter[TYPE_EVENT] = 200;
m_auiEventTimer = 30000;
};
}
break;
case TYPE_ZARITHRIAN:
m_auiEncounter[uiType] = uiData;
if (uiData == DONE)
{
OpenDoor(m_uiFlameWallsGUID);
m_auiEncounter[TYPE_EVENT] = 200;
m_auiEventTimer = 30000;
}
else if (uiData == IN_PROGRESS)
CloseDoor(m_uiFlameWallsGUID);
else if (uiData == FAIL)
OpenDoor(m_uiFlameWallsGUID);
break;
case TYPE_HALION:
m_auiEncounter[uiType] = uiData;
if (uiData == IN_PROGRESS)
CloseDoor(m_uiFlameRingGUID);
else
OpenDoor(m_uiFlameRingGUID);
break;
case TYPE_HALION_EVENT:
m_auiHalionEvent = uiData;
uiData = NOT_STARTED;
break;
case TYPE_EVENT_TIMER:
m_auiEventTimer = uiData;
uiData = NOT_STARTED;
break;
case DATA_ORB_DIRECTION:
m_auiOrbDirection = uiData;
uiData = NOT_STARTED;
break;
case DATA_ORB_N:
m_auiOrbNState = uiData;
uiData = NOT_STARTED;
break;
case DATA_ORB_S:
m_auiOrbSState = uiData;
uiData = NOT_STARTED;
break;
case TYPE_COUNTER:
if (uiData == 0)
UpdateWorldState(false,0);
else UpdateWorldState(true,uiData);
uiData = NOT_STARTED;
break;
}
if (uiData == DONE)
{
OUT_SAVE_INST_DATA;
std::ostringstream saveStream;
for(uint8 i = 0; i < MAX_ENCOUNTERS; ++i)
saveStream << m_auiEncounter[i] << " ";
strSaveData = saveStream.str();
SaveToDB();
OUT_SAVE_INST_DATA_COMPLETE;
}
}
std::string GetSaveData()
{
return strSaveData;
}
uint32 GetData(uint32 uiType)
{
switch(uiType)
{
case TYPE_RAGEFIRE:
return m_auiEncounter[uiType];
case TYPE_BALTHARUS:
return m_auiEncounter[uiType];
case TYPE_XERESTRASZA:
return m_auiEncounter[uiType];
case TYPE_ZARITHRIAN:
return m_auiEncounter[uiType];
case TYPE_HALION:
return m_auiEncounter[uiType];
case TYPE_EVENT:
return m_auiEncounter[uiType];
case TYPE_HALION_EVENT:
return m_auiHalionEvent;
case TYPE_EVENT_TIMER:
return m_auiEventTimer;
case DATA_ORB_DIRECTION:
return m_auiOrbDirection;
case DATA_ORB_N:
return m_auiOrbNState;
case DATA_ORB_S:
return m_auiOrbSState;
case TYPE_EVENT_NPC:
switch (m_auiEncounter[TYPE_EVENT])
{
case 10:
case 20:
case 30:
case 40:
case 50:
case 60:
case 70:
case 80:
case 90:
case 100:
case 110:
case 200:
case 210:
return NPC_XERESTRASZA;
break;
default:
break;
}
return 0;
}
return 0;
}
uint64 GetData64(uint32 uiData)
{
switch(uiData)
{
case NPC_BALTHARUS:
return m_uiBaltharusGUID;
case NPC_CLONE:
return m_uiCloneGUID;
case NPC_ZARITHIAN:
return m_uiZarithianGUID;
case NPC_RAGEFIRE:
return m_uiRagefireGUID;
case NPC_HALION_REAL:
return m_uiHalion_pGUID;
case NPC_HALION_TWILIGHT:
return m_uiHalion_tGUID;
case NPC_HALION_CONTROL:
return m_uiHalionControlGUID;
case NPC_XERESTRASZA:
return m_uiXerestraszaGUID;
case NPC_BALTHARUS_TARGET:
return m_uiBaltharusTargetGUID;
case GO_FLAME_WALLS:
return m_uiFlameWallsGUID;
case GO_FLAME_RING:
return m_uiFlameRingGUID;
case GO_FIRE_FIELD:
return m_uiFireFieldGUID;
case GO_HALION_PORTAL_1:
return m_uiHalionPortal1GUID;
case GO_HALION_PORTAL_2:
return m_uiHalionPortal2GUID;
case GO_HALION_PORTAL_3:
return m_uiHalionPortal3GUID;
case NPC_SHADOW_PULSAR_N:
return m_uiOrbNGUID;
case NPC_SHADOW_PULSAR_S:
return m_uiOrbSGUID;
case NPC_ORB_ROTATION_FOCUS:
return m_uiOrbFocusGUID;
case NPC_ORB_CARRIER:
return m_uiOrbCarrierGUID;
case GO_ARBOL:
return m_uiArbolGUID;
case GO_ARBOL1:
return m_uiArbol1GUID;
case GO_ARBOL2:
return m_uiArbol2GUID;
case GO_ARBOL3:
return m_uiArbol3GUID;
}
return 0;
}
void Load(const char* chrIn)
{
if (!chrIn)
{
OUT_LOAD_INST_DATA_FAIL;
return;
}
OUT_LOAD_INST_DATA(chrIn);
std::istringstream loadStream(chrIn);
for(uint8 i = 0; i < MAX_ENCOUNTERS; ++i)
{
loadStream >> m_auiEncounter[i];
if (m_auiEncounter[i] == IN_PROGRESS
|| m_auiEncounter[i] == FAIL)
m_auiEncounter[i] = NOT_STARTED;
}
m_auiEncounter[TYPE_XERESTRASZA] = NOT_STARTED;
OUT_LOAD_INST_DATA_COMPLETE;
OpenAllDoors();
}
};
};
/*##############################
# npc_convocadora_carboescala (40417)
# Gracias Aura
###############################*/
enum ConvocadoraSpells
{
SPELL_AGOSTAR = 75412,
SPELL_OLA_LLAMAS = 75413
};
class npc_convocadora_carboescala : public CreatureScript
{
public:
npc_convocadora_carboescala() : CreatureScript("npc_convocadora_carboescala") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_convocadora_carboescalaAI(creature);
}
struct npc_convocadora_carboescalaAI : public ScriptedAI
{
npc_convocadora_carboescalaAI(Creature* creature) : ScriptedAI(creature)
{
}
uint32 uiAgostarTimer;
uint32 uiOlaTimer;
void Reset()
{
uiAgostarTimer = 3000;
uiOlaTimer = urand(8*IN_MILLISECONDS,13*IN_MILLISECONDS);
me->SetRespawnDelay(7*DAY);
}
void UpdateAI(const uint32 uiDiff)
{
if (!UpdateVictim())
return;
if (uiAgostarTimer <= uiDiff)
{
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM,0))
{
if (pTarget && pTarget->isAlive())
DoCast(pTarget, SPELL_AGOSTAR);
}
uiAgostarTimer = 8000;
}else uiAgostarTimer -= uiDiff;
if (uiOlaTimer <= uiDiff)
{
DoCast(me, SPELL_OLA_LLAMAS);
uiOlaTimer = urand(8*IN_MILLISECONDS,13*IN_MILLISECONDS);
}else uiOlaTimer -= uiDiff;
DoMeleeAttackIfReady();
}
void JustDied(Unit* pKiller) { }
};
};
/*##############################
# npc_acometedor_carboescala (40419)
# Gracias Aura
###############################*/
enum AcometedorSpells
{
SPELL_RAJAR = 15284,
SPELL_OLA_CHOQUE = 75417
};
class npc_acometedor_carboescala : public CreatureScript
{
public:
npc_acometedor_carboescala() : CreatureScript("npc_acometedor_carboescala") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_acometedor_carboescalaAI(creature);
}
struct npc_acometedor_carboescalaAI : public ScriptedAI
{
npc_acometedor_carboescalaAI(Creature* creature) : ScriptedAI(creature)
{
}
uint32 uiRajarTimer;
uint32 uiOlaChoqueTimer;
void Reset()
{
uiRajarTimer = 5000;
uiOlaChoqueTimer = 9000;
me->SetRespawnDelay(7*DAY);
}
void UpdateAI(const uint32 uiDiff)
{
if (!UpdateVictim())
return;
if (uiRajarTimer <= uiDiff)
{
DoCast(me->getVictim(), SPELL_RAJAR);
uiRajarTimer = 11000;
}else uiRajarTimer -= uiDiff;
if (uiOlaChoqueTimer <= uiDiff)
{
DoCast(me, SPELL_OLA_CHOQUE);
uiOlaChoqueTimer = 17000;
}else uiOlaChoqueTimer -= uiDiff;
DoMeleeAttackIfReady();
}
void JustDied(Unit* pKiller) { }
};
};
/*##############################
# npc_elite_carboescala (40421)
# Gracias Aura
###############################*/
enum EliteSpells
{
SPELL_MACHACAR_CRANEOS = 15621
};
class npc_elite_carboescala : public CreatureScript
{
public:
npc_elite_carboescala() : CreatureScript("npc_elite_carboescala") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_elite_carboescalaAI(creature);
}
struct npc_elite_carboescalaAI : public ScriptedAI
{
npc_elite_carboescalaAI(Creature* creature) : ScriptedAI(creature)
{
}
uint32 uiMachaqueTimer;
void Reset()
{
uiMachaqueTimer = 5000;
me->SetRespawnDelay(7*DAY);
}
void UpdateAI(const uint32 uiDiff)
{
if (!UpdateVictim())
return;
if (uiMachaqueTimer <= uiDiff)
{
DoCast(me->getVictim(), SPELL_MACHACAR_CRANEOS);
uiMachaqueTimer = 12000;
}else uiMachaqueTimer -= uiDiff;
DoMeleeAttackIfReady();
}
void JustDied(Unit* pKiller) { }
};
};
/*##############################
# npc_comandante_carboescala (40423)
# Gracias Aura
###############################*/
enum ComandanteSpells
{
SPELL_GOLPE_MORTAL = 13737,
SPELL_GRITO_CONVOCACION = 75414
};
class npc_comandante_carboescala : public CreatureScript
{
public:
npc_comandante_carboescala() : CreatureScript("npc_comandante_carboescala") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_comandante_carboescalaAI(creature);
}
struct npc_comandante_carboescalaAI : public ScriptedAI
{
npc_comandante_carboescalaAI(Creature* creature) : ScriptedAI(creature)
{
}
uint32 uiGolpeTimer;
uint32 uiGritoTimer;
void Reset()
{
uiGolpeTimer = 9000;
uiGritoTimer = 1000;
me->SetRespawnDelay(7*DAY);
}
void UpdateAI(const uint32 uiDiff)
{
if (!UpdateVictim())
return;
if (uiGolpeTimer <= uiDiff)
{
DoCast(me->getVictim(), SPELL_GOLPE_MORTAL);
uiGolpeTimer = 9000;
}else uiGolpeTimer -= uiDiff;
if (uiGritoTimer <= uiDiff)
{
DoCast(me, SPELL_GRITO_CONVOCACION);
uiGritoTimer = 100000;
}else uiGritoTimer -= uiDiff;
DoMeleeAttackIfReady();
}
void JustDied(Unit* pKiller) { }
};
};
void AddSC_instance_ruby_sanctum()
{
new instance_ruby_sanctum;
new npc_convocadora_carboescala;
new npc_acometedor_carboescala;
new npc_elite_carboescala;
new npc_comandante_carboescala;
}
| gpl-2.0 |
sniezekjp/prod-fs | wp-content/themes/fairfax-stars/woocommerce/single-product/product-image.php | 1406 | <?php
/**
* Single Product Image
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 2.0.14
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
global $post, $woocommerce, $product;
?>
<div class="images">
<?php
if ( has_post_thumbnail() ) {
$image_title = esc_attr( get_the_title( get_post_thumbnail_id() ) );
$image_caption = get_post( get_post_thumbnail_id() )->post_excerpt;
$image_link = wp_get_attachment_url( get_post_thumbnail_id() );
$image = get_the_post_thumbnail( $post->ID, apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ), array(
'title' => $image_title,
'alt' => $image_title
) );
$attachment_count = count( $product->get_gallery_attachment_ids() );
if ( $attachment_count > 0 ) {
$gallery = '[product-gallery]';
} else {
$gallery = '';
}
echo apply_filters( 'woocommerce_single_product_image_html', sprintf( '<a href="%s" itemprop="image" class="woocommerce-main-image zoom" title="%s" data-rel="prettyPhoto' . $gallery . '">%s</a>', $image_link, $image_caption, $image ), $post->ID );
} else {
echo apply_filters( 'woocommerce_single_product_image_html', sprintf( '<img src="%s" alt="%s" />', wc_placeholder_img_src(), __( 'Placeholder', 'woocommerce' ) ), $post->ID );
}
?>
<?php do_action( 'woocommerce_product_thumbnails' ); ?>
</div>
| gpl-2.0 |
bonfil1/masmuscular | wp-content/themes/sportexx/templates/sections/team-member.php | 785 | <?php
/**
* Team Member
*
* @author Transvelo
* @package Sportexx/Templates
* @version 1.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
?>
<div class="team">
<?php
$args = array(
'post_type' => 'team-member',
'post__in' => array($id),
);
query_posts( $args );
?>
<?php while ( have_posts() ) : the_post(); ?>
<div class="team-member">
<?php
/**
* team_members_loop_content hook
*
* @hooked our_team_archive_post_thumbnail - 10
* @hooked our_team_archive_post_title - 20
* @hooked our_team_member_role - 30
* @hooked our_team_post_excerpt - 40
* @hooked our_team_member_social_links - 50
*/
do_action( 'team_members_loop_content' );
?>
</div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</div> | gpl-2.0 |
hroncok/devassistant | test/dapi/test_dapicli.py | 6671 | # -*- coding: utf-8 -*-
import pytest
import glob
import os
import six
import sys
import yaml
from flexmock import flexmock
from devassistant import dapi
from devassistant.dapi import dapicli
class TestDapicli(object):
'''Test if the Dapi CLI works'''
users_yaml = '''
count: 2
next: null
previous: null
results:
- api_link: http://api/api/users/miro/
codap_set: []
fedora_username: churchyard
full_name: Miro Hroncok
github_username: hroncok
human_link: http://api/user/miro/
id: 1
metadap_set: ['http://api/api/metadaps/python/', 'http://api/api/metadaps/bar/',
'http://api/api/metadaps/foo/']
username: miro
- api_link: http://api/api/users/user/
codap_set: ['http://api/api/metadaps/python/']
fedora_username: null
full_name: ''
github_username: null
human_link: http://api/user/user/
id: 2
metadap_set: []
username: user
'''
search_yaml = '''
count: 1
next: null
previous: null
results:
- content_object:
active: true
api_link: http://dapi/api/metadaps/python/
average_rank: 5.0
comaintainers: ['http://dapi/api/users/dummy1/']
dap_set: []
human_link: http://dapi/dap/python/
id: 1
latest: null
latest_stable: null
package_name: python
rank_count: 1
reports: 0
similar_daps: ['http://dapi/api/metadaps/bar/']
tags: [all, python 2, python 3]
user: http://dapi/api/users/miro/
content_type: metadap
'''
def test_print_users(self, capfd):
'''Test the print of users'''
desired = 'miro (Miro Hroncok)\nuser\n'
flexmock(dapicli).should_receive('data').and_return(yaml.load(TestDapicli.users_yaml))
dapicli.print_users()
out, err = capfd.readouterr()
assert out == desired
def test_search(self, capfd):
'''Test the print of a search results'''
desired = 'python\n'
flexmock(dapicli).should_receive('data').and_return(yaml.load(TestDapicli.search_yaml))
dapicli.print_search('python')
out, err = capfd.readouterr()
assert out == desired
def test_get_installed_version_of_missing_package(self):
'''Testing updating a DAP'''
flexmock(dapicli).should_receive('get_installed_daps').and_return(['foo'])
assert dapicli.get_installed_version_of('bar') is None
def test_get_installed_version_of(self, capsys):
install_path = '/foo/bar'
yaml_path = install_path + 'meta/baz.yaml'
version = '123'
flexmock(dapicli).should_receive('get_installed_daps').and_return(['foo'])
flexmock(dapicli).should_receive('_install_path').and_return(install_path)
flexmock(yaml).should_receive('load').and_return({'version': version})
# Everything goes fine
flexmock(six.moves.builtins).should_receive('open').and_return(
flexmock(read=lambda: u'qux'))
assert dapicli.get_installed_version_of('foo') == version
# File does not exist
ioerror = IOError("[Errno 2] No such file or directory: '{0}'".format(yaml_path))
flexmock(six.moves.builtins).should_receive('open').and_raise(ioerror)
with pytest.raises(Exception): # TODO maybe change to IOError
dapicli.get_installed_version_of('foo')
def test_strip_version_from_dependency(self):
'''Test a helper funcion _strip_version_from_dependency(dep)'''
s = dapicli._strip_version_from_dependency
assert s('foo >= 1') == 'foo'
assert s('foo>=1') == 'foo'
assert s('foo == 1') == 'foo'
assert s('foo==1') == 'foo'
assert s('foo <=1 ') == 'foo'
assert s('foo<=1') == 'foo'
def test_install_from_path_nodeps(self):
# Functional mocks
fakedap = flexmock(meta={
'package_name': 'foo',
'version': '1.0',
'dependencies': ['bar-1.0'],
}, check=lambda: True, extract=lambda x: None)
flexmock(dapi.Dap).new_instances(fakedap)
flexmock(dapicli).should_receive('get_installed_daps').and_return([])
flexmock(dapicli).should_receive('_install_path').and_return('.')
flexmock(dapicli).should_call('install_dap').with_args('bar').never()
# Filtering off details
flexmock(os).should_receive('mkdir').and_return()
flexmock(os).should_receive('rename').and_return()
dapicli.install_dap_from_path('/foo', nodeps=True)
def test_get_installed_daps_detailed(self):
'''Test function get_installed_daps_detailed()'''
flexmock(dapicli).should_receive('_data_dirs').and_return(['/1', '/2', '/3'])
flexmock(glob).should_receive('glob').with_args('/1/meta/*.yaml').and_return(
['/1/meta/a.yaml', '/1/meta/b.yaml', '/1/meta/c.yaml'])
flexmock(glob).should_receive('glob').with_args('/2/meta/*.yaml').and_return(
['/2/meta/a.yaml', '/2/meta/b.yaml'])
flexmock(glob).should_receive('glob').with_args('/3/meta/*.yaml').and_return(
['/3/meta/a.yaml'])
builtin = 'builtins' if six.PY3 else '__builtin__'
flexmock(sys.modules[builtin]).should_receive('open').and_return(None)
flexmock(yaml).should_receive('load').and_return(
{'version': 1.0})
expected = {
'a': [
{'version': '1.0', 'location': '/1'},
{'version': '1.0', 'location': '/2'},
{'version': '1.0', 'location': '/3'},
],
'b': [
{'version': '1.0', 'location': '/1'},
{'version': '1.0', 'location': '/2'},
],
'c': [
{'version': '1.0', 'location': '/1'},
],
}
details = dapicli.get_installed_daps_detailed()
assert details == expected
class TestUninstall(object):
def setup_class(self):
self.installed_daps = ['foo', 'bar', 'baz']
def test_uninstall_prompt_works(self, monkeypatch):
inp = 'input' if six.PY3 else 'raw_input'
monkeypatch.setattr(six.moves.builtins, inp, lambda x: 'y') # Putting 'y' on fake stdin
flexmock(dapicli).should_receive('get_installed_daps').and_return(self.installed_daps)
flexmock(dapicli).should_receive('_get_dependencies_of').and_return([])
flexmock(dapicli).should_receive('_install_path').and_return('.')
flexmock(os).should_receive('remove').and_return(None)
assert dapicli.uninstall_dap('foo', True) == ['foo']
monkeypatch.setattr(six.moves.builtins, inp, lambda x: 'n') # Putting 'n' on fake stdin
with pytest.raises(Exception):
dapicli.uninstall_dap('foo', True)
| gpl-2.0 |
reparosemlagrima/producao | components/com_jcart/admin/language/en-gb/module/special.php | 902 | <?php
/**
* @package jCart
* @copyright Copyright (C) 2009 - 2016 softPHP,http://www.soft-php.com
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
// Heading
$_['heading_title'] = 'Specials';
// Text
$_['text_module'] = 'Modules';
$_['text_success'] = 'Success: You have modified module specials!';
$_['text_edit'] = 'Edit Specials Module';
// Entry
$_['entry_name'] = 'Module Name';
$_['entry_limit'] = 'Limit';
$_['entry_width'] = 'Width';
$_['entry_height'] = 'Height';
$_['entry_status'] = 'Status';
// Error
$_['error_permission'] = 'Warning: You do not have permission to modify specials module!';
$_['error_name'] = 'Module Name must be between 3 and 64 characters!';
$_['error_width'] = 'Width required!';
$_['error_height'] = 'Height required!'; | gpl-2.0 |
quamen/enki | vendor/ruby-openid-2.0.2/test/test_cryptutil.rb | 3199 | require 'test/unit'
require "openid/cryptutil"
class CryptUtilTestCase < Test::Unit::TestCase
BIG = 2 ** 256
def test_rand
# If this is not true, the rest of our test won't work
assert(BIG.is_a?(Bignum))
# It's possible that these will be small enough for fixnums, but
# extraorindarily unlikely.
a = OpenID::CryptUtil.rand(BIG)
b = OpenID::CryptUtil.rand(BIG)
assert(a.is_a?(Bignum))
assert(b.is_a?(Bignum))
assert_not_equal(a, b)
end
def test_rand_doesnt_depend_on_srand
Kernel.srand(1)
a = OpenID::CryptUtil.rand(BIG)
Kernel.srand(1)
b = OpenID::CryptUtil.rand(BIG)
assert_not_equal(a, b)
end
def test_random_binary_convert
(0..500).each do
n = (0..10).inject(0) {|sum, element| sum + OpenID::CryptUtil.rand(BIG) }
s = OpenID::CryptUtil.num_to_binary n
assert(s.is_a?(String))
n_converted_back = OpenID::CryptUtil.binary_to_num(s)
assert_equal(n, n_converted_back)
end
end
def test_enumerated_binary_convert
{
"\x00" => 0,
"\x01" => 1,
"\x7F" => 127,
"\x00\xFF" => 255,
"\x00\x80" => 128,
"\x00\x81" => 129,
"\x00\x80\x00" => 32768,
"OpenID is cool" => 1611215304203901150134421257416556,
}.each do |str, num|
num_prime = OpenID::CryptUtil.binary_to_num(str)
str_prime = OpenID::CryptUtil.num_to_binary(num)
assert_equal(num, num_prime)
assert_equal(str, str_prime)
end
end
def with_n2b64
test_dir = Pathname.new(__FILE__).dirname
filename = test_dir.join('data', 'n2b64')
File.open(filename) do |file|
file.each_line do |line|
base64, base10 = line.chomp.split
yield base64, base10.to_i
end
end
end
def test_base64_to_num
with_n2b64 do |base64, num|
assert_equal(num, OpenID::CryptUtil.base64_to_num(base64))
end
end
def test_base64_to_num_invalid
assert_raises(ArgumentError) {
OpenID::CryptUtil.base64_to_num('!@#$')
}
end
def test_num_to_base64
with_n2b64 do |base64, num|
assert_equal(base64, OpenID::CryptUtil.num_to_base64(num))
end
end
def test_randomstring
s1 = OpenID::CryptUtil.random_string(42)
assert_equal(42, s1.length)
s2 = OpenID::CryptUtil.random_string(42)
assert_equal(42, s2.length)
assert_not_equal(s1, s2)
end
def test_randomstring_population
s1 = OpenID::CryptUtil.random_string(42, "XO")
assert_match(/[XO]{42}/, s1)
end
def test_sha1
assert_equal("\x11\xf6\xad\x8e\xc5*)\x84\xab\xaa\xfd|;Qe\x03x\\ r",
OpenID::CryptUtil.sha1('x'))
end
def test_hmac_sha1
assert_equal("\x8bo\xf7O\xa7\x18*\x90\xac ah\x16\xf7\xb8\x81JB\x9f|",
OpenID::CryptUtil.hmac_sha1('x', 'x'))
end
def test_sha256
assert_equal("-q\x16B\xb7&\xb0D\x01b|\xa9\xfb\xac2\xf5\xc8S\x0f\xb1\x90<\xc4\xdb\x02%\x87\x17\x92\x1aH\x81",
OpenID::CryptUtil.sha256('x'))
end
def test_hmac_sha256
assert_equal("\x94{\xd2w\xb2\xd3\\\xfc\x07\xfb\xc7\xe3b\xf2iuXz1\xf8:}\xffx\x8f\xda\xc1\xfaC\xc4\xb2\x87",
OpenID::CryptUtil.hmac_sha256('x', 'x'))
end
end
| gpl-2.0 |
diatem-net/framework-jin | jin/image/imagepart.php | 2048 | <?php
/**
* Jin FrameWork
*/
namespace jin\image;
use jin\image\Image;
/**
* Classe permettant d'exploiter une portion d'un objet Image Jin.
* @author Loïc Gerard
*/
class ImagePart {
/**
* Ressource image contenant la portion coupée
* @var resource
*/
private $cuttedRessource;
/**
* Objet jin\image\Image source
* @var \jin\image\Image
*/
private $srcImage;
/**
* Constructeur
* @param integer $x Coordonnée X du point supérieur gauche où débuter la découpe
* @param integer $y Coordonnée Y du point supérieur gauche où débuter la découpe
* @param integer $width Largeur (en pixels) de la zone à découper
* @param integer $height Hauteur (en pixels) de la zone à découper
* @param \jin\image\Image $image Objet image source
*/
public function __construct($x, $y, $width, $height, Image $image) {
$this->srcImage = $image;
$this->cuttedRessource = $image->getEmptyContainer($width, $height);
imagecopy($this->cuttedRessource, $image->getImageRessource(), 0, 0, $x, $y, $width, $height);
}
/**
* Ecrit la portion d'image dans un fichier
* @param string $path Chemin du fichier
* @throws \Exception
*/
public function write($path) {
if ($this->srcImage->getExtension() == 'jpg') {
imagejpeg($this->cuttedRessource, $path, $this->srcImage->getJpgQuality());
} else if ($this->srcImage->getExtension() == 'png') {
imagepng($this->cuttedRessource, $path, $this->srcImage->getPngCompression());
} else {
throw new \Exception('Impossible de générer l\'image : extension non supportée');
}
}
/**
* Retourne la ressource image resultante
* @return resource
*/
public function getRessource(){
return $this->cuttedRessource;
}
}
| gpl-2.0 |
chrisjihee/java_toolkit | src/test/kr/ac/kaist/ir/java_toolkit/lang/TestLang.java | 7868 | /**
* Utility package
*/
package kr.ac.kaist.ir.java_toolkit.lang;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Random;
import java.util.Stack;
import java.util.Vector;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import kr.ac.kaist.ir.java_toolkit.lang.JFunction.JOperatorPipe;
import kr.ac.kaist.ir.java_toolkit.lang.JObject.ListCaster;
import kr.ac.kaist.ir.java_toolkit.lang.JObject.MapCaster;
import kr.ac.kaist.ir.java_toolkit.lang.JObject.TupleCaster;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.javatuples.Pair;
import org.javatuples.Tuple;
import org.junit.Ignore;
import org.junit.Test;
/**
* Test cases for Language package
*
* @author Jihee
*/
public class TestLang {
static Logger log = LogManager.getLogger(Test.class);
static Function<Object, String> info = x -> x == null ? "null" : String.format("%s\t|\t%s", x, x.getClass().getName());
static BiConsumer<String, Object> out = (l, o) -> System.out.printf("%s\t|\t%s\n", l, info.apply(o));
/**
* JString Test
*/
@Test
@Ignore
public void testJString() {
log.debug("START testJString()");
String obj_join = JString.join(", ", "A", "B", "C", 1, 2, 3);
String obj_join_with = JString.joinWith("[%s]", ", ", "A", "B", "C", 1, 2, 3);
String int_join = JString.join(", ", IntStream.range(0, 4));
String dbl_join_with = JString.joinWith("%.4f", ", ", DoubleStream.generate(Math::random).limit(4));
out.accept("obj_join", obj_join);
out.accept("obj_join_with", obj_join_with);
out.accept("int_join", int_join);
out.accept("dbl_join_with", dbl_join_with);
assertTrue(obj_join.length() > 0);
assertTrue(obj_join_with.length() > 0);
assertTrue(int_join.length() > 0);
assertTrue(dbl_join_with.length() > 0);
String s = "http://jihee.kr:27017";
out.accept("to substring", s);
out.accept("substring(s, 7)", JString.substring(s, 7));
assertEquals("jihee.kr:27017", JString.substring(s, 7));
out.accept("substring(s, 7, 12)", JString.substring(s, 7, 12));
assertEquals("jihee", JString.substring(s, 7, 12));
out.accept("substring(s, ., false)", JString.substring(s, ".", false));
assertEquals("kr:27017", JString.substring(s, ".", false));
out.accept("substring(s, .)", JString.substring(s, "."));
assertEquals(".kr:27017", JString.substring(s, "."));
out.accept("substring(s, ., :, false)", JString.substring(s, ".", ":", false));
assertEquals("kr", JString.substring(s, ".", ":", false));
out.accept("substring(s, ., :, false)", JString.substring(s, ".", ":"));
assertEquals(".kr:", JString.substring(s, ".", ":"));
out.accept("substring(s, 0, :, false)", JString.substring(s, 0, ":", false));
assertEquals("http", JString.substring(s, 0, ":", false));
out.accept("substring(s, 0, :, false)", JString.substring(s, 0, ":"));
assertEquals("http:", JString.substring(s, 0, ":"));
out.accept("part(s, :, 2)", JString.part(s, ":", 2));
assertEquals("27017", JString.part(s, ":", 2));
s = "jihee.kr:27017";
out.accept("to substring", s);
out.accept("part0(s, :)", JString.part0(s, ":"));
assertEquals("jihee.kr", JString.part0(s, ":"));
out.accept("part1(s, :)", JString.part1(s, ":"));
assertEquals("27017", JString.part1(s, ":"));
log.debug("PASSED testJString()");
}
/**
* JObject Test
*/
@Test
@Ignore
public void testJObject() {
log.debug("START testJObject()");
Pair<Integer, Integer> given = Pair.with(1, 2);
Pair<Integer, Integer> swaped = JObject.swap(given);
out.accept("given", given);
out.accept("swaped", swaped);
assertEquals(given, JObject.swap(swaped));
Pair<Integer, Integer> sorted = JObject.sort(swaped);
assertTrue(sorted.getValue0() <= sorted.getValue1());
out.accept("sorted", sorted);
assertEquals(given, sorted);
JMap person = JMap.of("timestamp", Date.from(Instant.now()));
person.append("name", "John");
person.append("physical", JMap.of("height", 175, "weight", 70));
out.accept("person", person);
out.accept("#entry(person)", person.entrySet().size());
log.debug("PASSED testJObject()");
}
/**
* JObject.Caster Test
*/
@Test
@Ignore
public void testCaster() {
log.debug("START testCaster()");
Stack<String> obj1 = new Stack<String>();
obj1.push("data");
out.accept("to cast", obj1);
assertNotNull(obj1);
Vector<String> casted1 = ListCaster.to(obj1);
Vector<String> casted1i = ListCaster.to(JMap.empty());
Vector<String> casted1e = null;
try {
casted1e = ListCaster.to(new LinkedList<>());
} catch (Throwable e) {
}
out.accept("casted(1)", casted1);
out.accept("casted(1i)", casted1i);
out.accept("casted(1e)", casted1e);
assertNotNull(casted1);
assertNull(casted1i);
assertNull(casted1e);
HashMap<String, Object> obj2 = JMap.of("name", "Jihee");
out.accept("to cast", obj2);
assertNotNull(obj2);
LinkedHashMap<String, Object> casted2 = MapCaster.to(obj2);
LinkedHashMap<String, Object> casted2i = MapCaster.to(obj1);
out.accept("casted(2)", casted2);
out.accept("casted(2i)", casted2i);
assertNotNull(casted2);
assertNull(casted2i);
Tuple obj3 = Pair.with("name", "Jihee");
out.accept("to cast", obj3);
assertNotNull(obj3);
Pair<String, String> casted3 = TupleCaster.to(obj3);
Pair<String, String> casted3i = TupleCaster.to(obj2);
out.accept("casted(3)", casted3);
out.accept("casted(3i)", casted3i);
assertNotNull(casted3);
assertNull(casted3i);
log.debug("PASSED testCaster()");
}
@Test
@Ignore
public void testJTuple() {
log.debug("START testJTuple()");
boolean test_null = true;
out.accept("test_null", test_null);
Object[] vargs = test_null ? null : new Object[] { "A", 4 };
Pair<String, Integer> t1 = JTuple.of(vargs);
Pair<String, Integer> t2 = JTuple.of(Pair.with("X", 1), vargs);
out.accept("t1", t1);
out.accept("t2", t2);
out.accept("t2.getValue0()", t2.getValue0());
out.accept("t2.getValue1()", t2.getValue1());
assertEquals(test_null, JTuple.of(vargs) == null);
assertNotNull(JTuple.of(Pair.with("X", 1), vargs));
assertEquals(2, t2.getSize());
log.debug("PASSED testJTuple()");
}
@Test
@Ignore
public void testJOperatorPipe() {
log.debug("START testJOperatorPipe()");
String text = "feature";
out.accept("to apply", "[" + text + "]");
JOperatorPipe<String> trim = JOperatorPipe.of(s -> s.replace(" ", " "), String::trim);
JOperatorPipe<String> pipe = JOperatorPipe.of();
pipe.add(s -> s + " = B ");
pipe.add(s -> s + " = 5 ");
pipe.link(trim);
out.accept("apply(1)", "[" + pipe.apply(text) + "]");
pipe.add(s -> s + " -> new ");
out.accept("apply(2)", "[" + pipe.apply(text) + "]");
pipe.add(s -> s + " -> innovative ");
out.accept("apply(3)", "[" + pipe.apply(text) + "]");
pipe.link(trim);
out.accept("apply(4)", "[" + pipe.apply(text) + "]");
pipe.add(String::toUpperCase);
out.accept("apply(5)", "[" + pipe.apply(text) + "]");
log.debug("PASSED testJOperatorPipe()");
}
@Test
@Ignore
public void testJStream() {
log.debug("START testJStream()");
Supplier<Boolean> hasNext = () -> new Random().nextInt(20) != 0;
Supplier<Integer> next = () -> 1;
System.out.println(JStream.by(hasNext, next).limit(100).collect(Collectors.toList()));
System.out.println(JStream.by(hasNext, next).limit(100).count());
System.out.println(JStream.by(hasNext, next).limit(100).count());
log.debug("PASSED testJStream()");
}
}
| gpl-2.0 |
stevezuoli/BooxApp | sdk/code/examples/sys/battery_test.cpp | 424 |
#include <QtGui/QtGui>
#include "onyx/sys/sys.h"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
SysStatus & sys_status = SysStatus::instance();
int left = 0;
int status = BATTERY_STATUS_DANGEROUS;
if (argc >= 3)
{
left = app.arguments().at(1).toInt();
status = app.arguments().at(2).toInt();
}
sys_status.dbgUpdateBattery(left, status);
return 0;
}
| gpl-2.0 |
cameronscott137/rustbuilt | wp-content/themes/rustbuilt/core/model/modx/processors/element/plugin/create.class.php | 2744 | <?php
require_once (dirname(dirname(__FILE__)).'/create.class.php');
/**
* Creates a plugin
*
* @param string $name The name of the plugin
* @param string $plugincode The code of the plugin.
* @param string $description (optional) A description of the plugin.
* @param integer $category (optional) The category for the plugin. Defaults to
* no category.
* @param boolean $locked (optional) If true, can only be accessed by
* administrators. Defaults to false.
* @param boolean $disabled (optional) If true, the plugin does not execute.
* @param json $events (optional) A json array of system events to associate
* this plugin with.
* @param json $propdata (optional) A json array of properties
*
* @package modx
* @subpackage processors.element.plugin
*/
class modPluginCreateProcessor extends modElementCreateProcessor {
public $classKey = 'modPlugin';
public $languageTopics = array('chunk');
public $permission = 'new_plugin';
public $elementType = 'plugin';
public $objectType = 'plugin';
public $beforeSaveEvent = 'OnBeforePluginFormSave';
public $afterSaveEvent = 'OnPluginFormSave';
public function afterSave() {
$this->saveEvents();
return parent::afterSave();
}
/**
* Save system events
*
* @return void
*/
public function saveEvents() {
$events = $this->getProperty('events',null);
if ($events != null) {
$events = is_array($events) ? $events : $this->modx->fromJSON($events);
foreach ($events as $id => $event) {
if (!empty($event['enabled'])) {
/** @var modPluginEvent $pluginEvent */
$pluginEvent = $this->modx->getObject('modPluginEvent',array(
'pluginid' => $this->object->get('id'),
'event' => $event['name'],
));
if (empty($pluginEvent)) {
$pluginEvent = $this->modx->newObject('modPluginEvent');
}
$pluginEvent->set('pluginid',$this->object->get('id'));
$pluginEvent->set('event',$event['name']);
$pluginEvent->set('priority',$event['priority']);
$pluginEvent->save();
} else {
$pluginEvent = $this->modx->getObject('modPluginEvent',array(
'pluginid' => $this->object->get('id'),
'event' => $event['name'],
));
if (!empty($pluginEvent)) {
$pluginEvent->remove();
}
}
}
}
}
}
return 'modPluginCreateProcessor';
| gpl-2.0 |
mfournier/puppet | lib/puppet/provider/service/init.rb | 3943 | # The standard init-based service type. Many other service types are
# customizations of this module.
Puppet::Type.type(:service).provide :init, :parent => :base do
desc "Standard init service management.
This provider assumes that the init script has no ``status`` command,
because so few scripts do, so you need to either provide a status
command or specify via ``hasstatus`` that one already exists in the
init script.
"
class << self
attr_accessor :defpath
end
case Facter["operatingsystem"].value
when "FreeBSD"
@defpath = ["/etc/rc.d", "/usr/local/etc/rc.d"]
when "HP-UX"
@defpath = "/sbin/init.d"
else
@defpath = "/etc/init.d"
end
# We can't confine this here, because the init path can be overridden.
#confine :exists => @defpath
# List all services of this type.
def self.instances
self.defpath = [self.defpath] unless self.defpath.is_a? Array
instances = []
self.defpath.each do |path|
unless FileTest.directory?(path)
Puppet.debug "Service path %s does not exist" % path
next
end
check = [:ensure]
if public_method_defined? :enabled?
check << :enable
end
Dir.entries(path).each do |name|
fullpath = File.join(path, name)
next if name =~ /^\./
next if not FileTest.executable?(fullpath)
instances << new(:name => name, :path => path)
end
end
instances
end
# Mark that our init script supports 'status' commands.
def hasstatus=(value)
case value
when true, "true"; @parameters[:hasstatus] = true
when false, "false"; @parameters[:hasstatus] = false
else
raise Puppet::Error, "Invalid 'hasstatus' value %s" %
value.inspect
end
end
# Where is our init script?
def initscript
if defined? @initscript
return @initscript
else
@initscript = self.search(@resource[:name])
end
end
def restart
if @resource[:hasrestart] == :true
command = [self.initscript, :restart]
texecute("restart", command)
else
super
end
end
def search(name)
@resource[:path].each { |path|
fqname = File.join(path,name)
begin
stat = File.stat(fqname)
rescue
# should probably rescue specific errors...
self.debug("Could not find %s in %s" % [name,path])
next
end
# if we've gotten this far, we found a valid script
return fqname
}
@resource[:path].each { |path|
fqname_sh = File.join(path,"#{name}.sh")
begin
stat = File.stat(fqname_sh)
rescue
# should probably rescue specific errors...
self.debug("Could not find %s.sh in %s" % [name,path])
next
end
# if we've gotten this far, we found a valid script
return fqname_sh
}
raise Puppet::Error, "Could not find init script for '%s'" % name
end
# The start command is just the init scriptwith 'start'.
def startcmd
[self.initscript, :start]
end
# If it was specified that the init script has a 'status' command, then
# we just return that; otherwise, we return false, which causes it to
# fallback to other mechanisms.
def statuscmd
if @resource[:hasstatus] == :true
return [self.initscript, :status]
else
return false
end
end
# The stop command is just the init script with 'stop'.
def stopcmd
[self.initscript, :stop]
end
end
| gpl-2.0 |
oniiru/html | sendy/includes/campaigns/check_sns.php | 3735 | <?php
include('../config.php');
include('../helpers/class.phpmailer.php');
include('../helpers/ses.php');
//--------------------------------------------------------------//
function dbConnect() { //Connect to database
//--------------------------------------------------------------//
// Access global variables
global $mysqli;
global $dbHost;
global $dbUser;
global $dbPass;
global $dbName;
// Attempt to connect to database server
if(isset($dbPort)) $mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbName, $dbPort);
else $mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
// If connection failed...
if ($mysqli->connect_error) {
fail();
}
global $charset; mysqli_set_charset($mysqli, isset($charset) ? $charset : "utf8");
return $mysqli;
}
//--------------------------------------------------------------//
function fail() { //Database connection fails
//--------------------------------------------------------------//
print 'Database error';
exit;
}
// connect to database
dbConnect();
?>
<?php
//Init
$from_email = isset($_POST['from_email']) ? mysqli_real_escape_string($mysqli, $_POST['from_email']) : '';
$aws_key = isset($_POST['aws_key']) ? $_POST['aws_key'] : '';
$aws_secret = isset($_POST['aws_secret']) ? $_POST['aws_secret'] : '';
$bounce_simulator_email = 'bounce@simulator.amazonses.com';
$complaint_simulator_email = 'complaint@simulator.amazonses.com';
//Send email to bounce mailbox simulator
$mail = new PHPMailer();
$mail->IsAmazonSES();
$mail->AddAmazonSESKey($aws_key, $aws_secret);
$mail->CharSet = "UTF-8";
$mail->From = $from_email;
$mail->FromName = 'Sendy';
$mail->Subject = 'Test bounce setup';
$mail->AltBody = 'Test';
$mail->MsgHTML('Test');
$mail->AddAddress($bounce_simulator_email, '');
$mail->Send();
//Send email to complaint mailbox simulator
$mail2 = new PHPMailer();
$mail2->IsAmazonSES();
$mail2->AddAmazonSESKey($aws_key, $aws_secret);
$mail2->CharSet = "UTF-8";
$mail2->From = $from_email;
$mail2->FromName = 'Sendy';
$mail2->Subject = 'Test complaint setup';
$mail2->AltBody = 'Test';
$mail2->MsgHTML('Test');
$mail2->AddAddress($complaint_simulator_email, '');
$mail2->Send();
//Wait 10 seconds for emails to reach Amazon and for Amazon to process them
sleep(10);
//Then check if bounces and complaints SNS notifications have been setup
$q = 'SELECT bounce_setup, complaint_setup FROM apps WHERE from_email = "'.$from_email.'"';
$r = mysqli_query($mysqli, $q);
if (mysqli_num_rows($r) > 0)
{
while($row = mysqli_fetch_array($r))
{
$bounce_setup = $row['bounce_setup'];
$complaint_setup = $row['complaint_setup'];
$bounce_n_complaint_setup = $bounce_setup && $complaint_setup ? true : false;
//If true, set email forwardinig to false
if($bounce_n_complaint_setup)
{
$ses = new SimpleEmailService($aws_key, $aws_secret);
$ses->setIdentityFeedbackForwardingEnabled($from_email, 'false');
}
echo $bounce_n_complaint_setup;
}
}
else
{
$q2 = 'SELECT bounce_setup, complaint_setup FROM campaigns WHERE from_email = "'.$from_email.'"';
$r2 = mysqli_query($mysqli, $q2);
if (mysqli_num_rows($r2) > 0)
{
while($row = mysqli_fetch_array($r2))
{
$bounce_setup = $row['bounce_setup'];
$complaint_setup = $row['complaint_setup'];
//If true, set email forwardinig to false
if($bounce_n_complaint_setup)
{
$ses = new SimpleEmailService($aws_key, $aws_secret);
$ses->setIdentityFeedbackForwardingEnabled($from_email, 'false');
}
echo $bounce_n_complaint_setup;
}
}
}
?> | gpl-2.0 |
liningwang/camera-beijing | android-php-weibo/client/src/com/app/demos/test/TestProxy.java | 1012 | package com.app.demos.test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.app.demos.util.AppUtil;
public class TestProxy implements InvocationHandler {
Object testObj;
public TestProxy (Object obj) {
testObj = obj;
}
public static Object init (Object obj) {
return Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
new TestProxy(obj));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object methodResult;
try {
System.out.println("method name : " + method.getName());
long startTime = AppUtil.getTimeMillis();
methodResult = method.invoke(testObj, args);
long endTime = AppUtil.getTimeMillis();
System.out.println("method time : " + (endTime - startTime) + "ms");
} catch (Exception e) {
throw new RuntimeException("TestHandler Exception : " + e.getMessage());
}
return methodResult;
}
} | gpl-2.0 |
yakuzmenko/bereg | templates/berehynya/html/com_k2/default/item.php | 29209 | <?php
/**
* @version $Id: item.php 1812 2013-01-14 18:45:06Z lefteris.kavadas $
* @package K2
* @author JoomlaWorks http://www.joomlaworks.net
* @copyright Copyright (c) 2006 - 2013 JoomlaWorks Ltd. All rights reserved.
* @license GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
*/
// no direct access
defined('_JEXEC') or die;
?>
<?php if(JRequest::getInt('print')==1): ?>
<!-- Print button at the top of the print page only -->
<a class="itemPrintThisPage" rel="nofollow" href="#" onclick="window.print();return false;">
<span><?php echo JText::_('K2_PRINT_THIS_PAGE'); ?></span>
</a>
<?php endif; ?>
<!-- Start K2 Item Layout -->
<span id="startOfPageId<?php echo JRequest::getInt('id'); ?>"></span>
<div id="k2Container" class="itemView<?php echo ($this->item->featured) ? ' itemIsFeatured' : ''; ?><?php if($this->item->params->get('pageclass_sfx')) echo ' '.$this->item->params->get('pageclass_sfx'); ?>">
<!-- Plugins: BeforeDisplay -->
<?php echo $this->item->event->BeforeDisplay; ?>
<!-- K2 Plugins: K2BeforeDisplay -->
<?php echo $this->item->event->K2BeforeDisplay; ?>
<div class="itemHeader">
<?php if($this->item->params->get('itemTitle')): ?>
<!-- Item title -->
<h2 class="itemTitle">
<?php if(isset($this->item->editLink)): ?>
<!-- Item edit link -->
<span class="itemEditLink">
<a class="modal" rel="{handler:'iframe',size:{x:990,y:550}}" href="<?php echo $this->item->editLink; ?>">
<?php echo JText::_('K2_EDIT_ITEM'); ?>
</a>
</span>
<?php endif; ?>
<?php echo $this->item->title; ?>
<?php if($this->item->params->get('itemFeaturedNotice') && $this->item->featured): ?>
<!-- Featured flag -->
<span>
<sup>
<?php echo JText::_('K2_FEATURED'); ?>
</sup>
</span>
<?php endif; ?>
</h2>
<?php endif; ?>
<?php if($this->item->params->get('itemDateCreated')): ?>
<!-- Date created -->
<span class="itemDateCreated">
<?php echo JHTML::_('date', $this->item->created , JText::_('K2_DATE_FORMAT_LC2')); ?>
</span>
<?php endif; ?>
<?php if($this->item->params->get('itemAuthor')): ?>
<!-- Item Author -->
<span class="itemAuthor">
<?php echo K2HelperUtilities::writtenBy($this->item->author->profile->gender); ?>
<?php if(empty($this->item->created_by_alias)): ?>
<a rel="author" href="<?php echo $this->item->author->link; ?>"><?php echo $this->item->author->name; ?></a>
<?php else: ?>
<?php echo $this->item->author->name; ?>
<?php endif; ?>
</span>
<?php endif; ?>
</div>
<!-- Plugins: AfterDisplayTitle -->
<?php echo $this->item->event->AfterDisplayTitle; ?>
<!-- K2 Plugins: K2AfterDisplayTitle -->
<?php echo $this->item->event->K2AfterDisplayTitle; ?>
<?php if(
$this->item->params->get('itemFontResizer') ||
$this->item->params->get('itemPrintButton') ||
$this->item->params->get('itemEmailButton') ||
$this->item->params->get('itemSocialButton') ||
$this->item->params->get('itemVideoAnchor') ||
$this->item->params->get('itemImageGalleryAnchor') ||
$this->item->params->get('itemCommentsAnchor')
): ?>
<div class="itemToolbar">
<ul>
<?php if($this->item->params->get('itemFontResizer')): ?>
<!-- Font Resizer -->
<li>
<span class="itemTextResizerTitle"><?php echo JText::_('K2_FONT_SIZE'); ?></span>
<a href="#" id="fontDecrease">
<span><?php echo JText::_('K2_DECREASE_FONT_SIZE'); ?></span>
<img src="<?php echo JURI::root(true); ?>/components/com_k2/images/system/blank.gif" alt="<?php echo JText::_('K2_DECREASE_FONT_SIZE'); ?>" />
</a>
<a href="#" id="fontIncrease">
<span><?php echo JText::_('K2_INCREASE_FONT_SIZE'); ?></span>
<img src="<?php echo JURI::root(true); ?>/components/com_k2/images/system/blank.gif" alt="<?php echo JText::_('K2_INCREASE_FONT_SIZE'); ?>" />
</a>
</li>
<?php endif; ?>
<?php if($this->item->params->get('itemPrintButton') && !JRequest::getInt('print')): ?>
<!-- Print Button -->
<li>
<a class="itemPrintLink" rel="nofollow" href="<?php echo $this->item->printLink; ?>" onclick="window.open(this.href,'printWindow','width=900,height=600,location=no,menubar=no,resizable=yes,scrollbars=yes'); return false;">
<span><?php echo JText::_('K2_PRINT'); ?></span>
</a>
</li>
<?php endif; ?>
<?php if($this->item->params->get('itemEmailButton') && !JRequest::getInt('print')): ?>
<!-- Email Button -->
<li>
<a class="itemEmailLink" rel="nofollow" href="<?php echo $this->item->emailLink; ?>" onclick="window.open(this.href,'emailWindow','width=400,height=350,location=no,menubar=no,resizable=no,scrollbars=no'); return false;">
<span><?php echo JText::_('K2_EMAIL'); ?></span>
</a>
</li>
<?php endif; ?>
<?php if($this->item->params->get('itemSocialButton') && !is_null($this->item->params->get('socialButtonCode', NULL))): ?>
<!-- Item Social Button -->
<li>
<?php echo $this->item->params->get('socialButtonCode'); ?>
</li>
<?php endif; ?>
<?php if($this->item->params->get('itemVideoAnchor') && !empty($this->item->video)): ?>
<!-- Anchor link to item video below - if it exists -->
<li>
<a class="itemVideoLink k2Anchor" href="<?php echo $this->item->link; ?>#itemVideoAnchor"><?php echo JText::_('K2_MEDIA'); ?></a>
</li>
<?php endif; ?>
<?php if($this->item->params->get('itemImageGalleryAnchor') && !empty($this->item->gallery)): ?>
<!-- Anchor link to item image gallery below - if it exists -->
<li>
<a class="itemImageGalleryLink k2Anchor" href="<?php echo $this->item->link; ?>#itemImageGalleryAnchor"><?php echo JText::_('K2_IMAGE_GALLERY'); ?></a>
</li>
<?php endif; ?>
<?php if($this->item->params->get('itemCommentsAnchor') && $this->item->params->get('itemComments') && ( ($this->item->params->get('comments') == '2' && !$this->user->guest) || ($this->item->params->get('comments') == '1')) ): ?>
<!-- Anchor link to comments below - if enabled -->
<li>
<?php if(!empty($this->item->event->K2CommentsCounter)): ?>
<!-- K2 Plugins: K2CommentsCounter -->
<?php echo $this->item->event->K2CommentsCounter; ?>
<?php else: ?>
<?php if($this->item->numOfComments > 0): ?>
<a class="itemCommentsLink k2Anchor" href="<?php echo $this->item->link; ?>#itemCommentsAnchor">
<span><?php echo $this->item->numOfComments; ?></span> <?php echo ($this->item->numOfComments>1) ? JText::_('K2_COMMENTS') : JText::_('K2_COMMENT'); ?>
</a>
<?php else: ?>
<a class="itemCommentsLink k2Anchor" href="<?php echo $this->item->link; ?>#itemCommentsAnchor">
<?php echo JText::_('K2_BE_THE_FIRST_TO_COMMENT'); ?>
</a>
<?php endif; ?>
<?php endif; ?>
</li>
<?php endif; ?>
</ul>
<div class="clr"></div>
</div>
<?php endif; ?>
<div class="itemBody">
<!-- Plugins: BeforeDisplayContent -->
<?php echo $this->item->event->BeforeDisplayContent; ?>
<!-- K2 Plugins: K2BeforeDisplayContent -->
<?php echo $this->item->event->K2BeforeDisplayContent; ?>
<?php if($this->item->params->get('itemImage') && !empty($this->item->image)): ?>
<!-- Item Image -->
<div class="itemImageBlock">
<span class="itemImage">
<a class="modal" rel="{handler: 'image'}" href="<?php echo $this->item->imageXLarge; ?>" title="<?php echo JText::_('K2_CLICK_TO_PREVIEW_IMAGE'); ?>">
<img src="<?php echo $this->item->image; ?>" alt="<?php if(!empty($this->item->image_caption)) echo K2HelperUtilities::cleanHtml($this->item->image_caption); else echo K2HelperUtilities::cleanHtml($this->item->title); ?>" style="width:<?php echo $this->item->imageWidth; ?>px; height:auto;" />
</a>
</span>
<?php if($this->item->params->get('itemImageMainCaption') && !empty($this->item->image_caption)): ?>
<!-- Image caption -->
<span class="itemImageCaption"><?php echo $this->item->image_caption; ?></span>
<?php endif; ?>
<?php if($this->item->params->get('itemImageMainCredits') && !empty($this->item->image_credits)): ?>
<!-- Image credits -->
<span class="itemImageCredits"><?php echo $this->item->image_credits; ?></span>
<?php endif; ?>
<div class="clr"></div>
</div>
<?php endif; ?>
<?php if(!empty($this->item->fulltext)): ?>
<?php if($this->item->params->get('itemIntroText')): ?>
<!-- Item introtext -->
<div class="itemIntroText">
<?php echo $this->item->introtext; ?>
</div>
<?php endif; ?>
<?php if($this->item->params->get('itemFullText')): ?>
<!-- Item fulltext -->
<div class="itemFullText">
<?php echo $this->item->fulltext; ?>
</div>
<?php endif; ?>
<?php else: ?>
<!-- Item text -->
<div class="itemFullText">
<?php echo $this->item->introtext; ?>
</div>
<?php endif; ?>
<div class="clr"></div>
<?php if($this->item->params->get('itemExtraFields') && count($this->item->extra_fields)): ?>
<!-- Item extra fields -->
<div class="itemExtraFields">
<h3><?php echo JText::_('K2_ADDITIONAL_INFO'); ?></h3>
<ul>
<?php foreach ($this->item->extra_fields as $key=>$extraField): ?>
<?php if($extraField->value != ''): ?>
<li class="<?php echo ($key%2) ? "odd" : "even"; ?> type<?php echo ucfirst($extraField->type); ?> group<?php echo $extraField->group; ?>">
<?php if($extraField->type == 'header'): ?>
<h4 class="itemExtraFieldsHeader"><?php echo $extraField->name; ?></h4>
<?php else: ?>
<span class="itemExtraFieldsLabel"><?php echo $extraField->name; ?>:</span>
<span class="itemExtraFieldsValue"><?php echo $extraField->value; ?></span>
<?php endif; ?>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
<div class="clr"></div>
</div>
<?php endif; ?>
<?php if($this->item->params->get('itemHits') || ($this->item->params->get('itemDateModified') && intval($this->item->modified)!=0)): ?>
<div class="itemContentFooter">
<?php if($this->item->params->get('itemHits')): ?>
<!-- Item Hits -->
<span class="itemHits">
<?php echo JText::_('K2_READ'); ?> <b><?php echo $this->item->hits; ?></b> <?php echo JText::_('K2_TIMES'); ?>
</span>
<?php endif; ?>
<?php if($this->item->params->get('itemDateModified') && intval($this->item->modified)!=0): ?>
<!-- Item date modified -->
<span class="itemDateModified">
<?php echo JText::_('K2_LAST_MODIFIED_ON'); ?> <?php echo JHTML::_('date', $this->item->modified, JText::_('K2_DATE_FORMAT_LC2')); ?>
</span>
<?php endif; ?>
<div class="clr"></div>
</div>
<?php endif; ?>
<!-- Plugins: AfterDisplayContent -->
<?php echo $this->item->event->AfterDisplayContent; ?>
<!-- K2 Plugins: K2AfterDisplayContent -->
<?php echo $this->item->event->K2AfterDisplayContent; ?>
<div class="clr"></div>
<?php if($this->item->params->get('itemRating')): ?>
<!-- Item Rating -->
<div class="itemRatingBlock">
<span><?php echo JText::_('K2_RATE_THIS_ITEM'); ?></span>
<div class="itemRatingForm">
<ul class="itemRatingList">
<li class="itemCurrentRating" id="itemCurrentRating<?php echo $this->item->id; ?>" style="width:<?php echo $this->item->votingPercentage; ?>%;"></li>
<li><a href="#" rel="<?php echo $this->item->id; ?>" title="<?php echo JText::_('K2_1_STAR_OUT_OF_5'); ?>" class="one-star">1</a></li>
<li><a href="#" rel="<?php echo $this->item->id; ?>" title="<?php echo JText::_('K2_2_STARS_OUT_OF_5'); ?>" class="two-stars">2</a></li>
<li><a href="#" rel="<?php echo $this->item->id; ?>" title="<?php echo JText::_('K2_3_STARS_OUT_OF_5'); ?>" class="three-stars">3</a></li>
<li><a href="#" rel="<?php echo $this->item->id; ?>" title="<?php echo JText::_('K2_4_STARS_OUT_OF_5'); ?>" class="four-stars">4</a></li>
<li><a href="#" rel="<?php echo $this->item->id; ?>" title="<?php echo JText::_('K2_5_STARS_OUT_OF_5'); ?>" class="five-stars">5</a></li>
</ul>
<div id="itemRatingLog<?php echo $this->item->id; ?>" class="itemRatingLog"><?php echo $this->item->numOfvotes; ?></div>
<div class="clr"></div>
</div>
<div class="clr"></div>
</div>
<?php endif; ?>
</div>
<?php if($this->item->params->get('itemTwitterButton',1) || $this->item->params->get('itemFacebookButton',1) || $this->item->params->get('itemGooglePlusOneButton',1)): ?>
<!-- Social sharing -->
<div class="itemSocialSharing">
<?php if($this->item->params->get('itemTwitterButton',1)): ?>
<!-- Twitter Button -->
<div class="itemTwitterButton">
<a href="https://twitter.com/share" class="twitter-share-button" data-count="horizontal"<?php if($this->item->params->get('twitterUsername')): ?> data-via="<?php echo $this->item->params->get('twitterUsername'); ?>"<?php endif; ?>>
<?php echo JText::_('K2_TWEET'); ?>
</a>
<script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>
</div>
<?php endif; ?>
<?php if($this->item->params->get('itemFacebookButton',1)): ?>
<!-- Facebook Button -->
<div class="itemFacebookButton">
<div id="fb-root"></div>
<script type="text/javascript">
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<div class="fb-like" data-send="false" data-width="200" data-show-faces="true"></div>
</div>
<?php endif; ?>
<?php if($this->item->params->get('itemGooglePlusOneButton',1)): ?>
<!-- Google +1 Button -->
<div class="itemGooglePlusOneButton">
<g:plusone annotation="inline" width="120"></g:plusone>
<script type="text/javascript">
(function() {
window.___gcfg = {lang: 'en'}; // Define button default language here
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
</div>
<?php endif; ?>
<div class="clr"></div>
</div>
<?php endif; ?>
<?php if($this->item->params->get('itemCategory') || $this->item->params->get('itemTags') || $this->item->params->get('itemAttachments')): ?>
<div class="itemLinks">
<?php if($this->item->params->get('itemCategory')): ?>
<!-- Item category -->
<div class="itemCategory">
<span><?php echo JText::_('K2_PUBLISHED_IN'); ?></span>
<a href="<?php echo $this->item->category->link; ?>"><?php echo $this->item->category->name; ?></a>
</div>
<?php endif; ?>
<?php if($this->item->params->get('itemTags') && count($this->item->tags)): ?>
<!-- Item tags -->
<div class="itemTagsBlock">
<span><?php echo JText::_('K2_TAGGED_UNDER'); ?></span>
<ul class="itemTags">
<?php foreach ($this->item->tags as $tag): ?>
<li><a href="<?php echo $tag->link; ?>"><?php echo $tag->name; ?></a></li>
<?php endforeach; ?>
</ul>
<div class="clr"></div>
</div>
<?php endif; ?>
<?php if($this->item->params->get('itemAttachments') && count($this->item->attachments)): ?>
<!-- Item attachments -->
<div class="itemAttachmentsBlock">
<span><?php echo JText::_('K2_DOWNLOAD_ATTACHMENTS'); ?></span>
<ul class="itemAttachments">
<?php foreach ($this->item->attachments as $attachment): ?>
<li>
<a title="<?php echo K2HelperUtilities::cleanHtml($attachment->titleAttribute); ?>" href="<?php echo $attachment->link; ?>"><?php echo $attachment->title; ?></a>
<?php if($this->item->params->get('itemAttachmentsCounter')): ?>
<span>(<?php echo $attachment->hits; ?> <?php echo ($attachment->hits==1) ? JText::_('K2_DOWNLOAD') : JText::_('K2_DOWNLOADS'); ?>)</span>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<div class="clr"></div>
</div>
<?php endif; ?>
<?php if($this->item->params->get('itemAuthorBlock') && empty($this->item->created_by_alias)): ?>
<!-- Author Block -->
<div class="itemAuthorBlock">
<?php if($this->item->params->get('itemAuthorImage') && !empty($this->item->author->avatar)): ?>
<img class="itemAuthorAvatar" src="<?php echo $this->item->author->avatar; ?>" alt="<?php echo K2HelperUtilities::cleanHtml($this->item->author->name); ?>" />
<?php endif; ?>
<div class="itemAuthorDetails">
<h3 class="itemAuthorName">
<a rel="author" href="<?php echo $this->item->author->link; ?>"><?php echo $this->item->author->name; ?></a>
</h3>
<?php if($this->item->params->get('itemAuthorDescription') && !empty($this->item->author->profile->description)): ?>
<p><?php echo $this->item->author->profile->description; ?></p>
<?php endif; ?>
<?php if($this->item->params->get('itemAuthorURL') && !empty($this->item->author->profile->url)): ?>
<span class="itemAuthorUrl"><?php echo JText::_('K2_WEBSITE'); ?> <a rel="me" href="<?php echo $this->item->author->profile->url; ?>" target="_blank"><?php echo str_replace('http://','',$this->item->author->profile->url); ?></a></span>
<?php endif; ?>
<?php if($this->item->params->get('itemAuthorEmail')): ?>
<span class="itemAuthorEmail"><?php echo JText::_('K2_EMAIL'); ?> <?php echo JHTML::_('Email.cloak', $this->item->author->email); ?></span>
<?php endif; ?>
<div class="clr"></div>
<!-- K2 Plugins: K2UserDisplay -->
<?php echo $this->item->event->K2UserDisplay; ?>
</div>
<div class="clr"></div>
</div>
<?php endif; ?>
<?php if($this->item->params->get('itemAuthorLatest') && empty($this->item->created_by_alias) && isset($this->authorLatestItems)): ?>
<!-- Latest items from author -->
<div class="itemAuthorLatest">
<h3><?php echo JText::_('K2_LATEST_FROM'); ?> <?php echo $this->item->author->name; ?></h3>
<ul>
<?php foreach($this->authorLatestItems as $key=>$item): ?>
<li class="<?php echo ($key%2) ? "odd" : "even"; ?>">
<a href="<?php echo $item->link ?>"><?php echo $item->title; ?></a>
</li>
<?php endforeach; ?>
</ul>
<div class="clr"></div>
</div>
<?php endif; ?>
<?php
/*
Note regarding 'Related Items'!
If you add:
- the CSS rule 'overflow-x:scroll;' in the element div.itemRelated {…} in the k2.css
- the class 'k2Scroller' to the ul element below
- the classes 'k2ScrollerElement' and 'k2EqualHeights' to the li element inside the foreach loop below
- the style attribute 'style="width:<?php echo $item->imageWidth; ?>px;"' to the li element inside the foreach loop below
...then your Related Items will be transformed into a vertical-scrolling block, inside which, all items have the same height (equal column heights). This can be very useful if you want to show your related articles or products with title/author/category/image etc., which would take a significant amount of space in the classic list-style display.
*/
?>
<?php if($this->item->params->get('itemRelated') && isset($this->relatedItems)): ?>
<!-- Related items by tag -->
<div class="itemRelated">
<h3><?php echo JText::_("K2_RELATED_ITEMS_BY_TAG"); ?></h3>
<ul>
<?php foreach($this->relatedItems as $key=>$item): ?>
<li class="<?php echo ($key%2) ? "odd" : "even"; ?>">
<?php if($this->item->params->get('itemRelatedTitle', 1)): ?>
<a class="itemRelTitle" href="<?php echo $item->link ?>"><?php echo $item->title; ?></a>
<?php endif; ?>
<?php if($this->item->params->get('itemRelatedCategory')): ?>
<div class="itemRelCat"><?php echo JText::_("K2_IN"); ?> <a href="<?php echo $item->category->link ?>"><?php echo $item->category->name; ?></a></div>
<?php endif; ?>
<?php if($this->item->params->get('itemRelatedAuthor')): ?>
<div class="itemRelAuthor"><?php echo JText::_("K2_BY"); ?> <a rel="author" href="<?php echo $item->author->link; ?>"><?php echo $item->author->name; ?></a></div>
<?php endif; ?>
<?php if($this->item->params->get('itemRelatedImageSize')): ?>
<img style="width:<?php echo $item->imageWidth; ?>px;height:auto;" class="itemRelImg" src="<?php echo $item->image; ?>" alt="<?php K2HelperUtilities::cleanHtml($item->title); ?>" />
<?php endif; ?>
<?php if($this->item->params->get('itemRelatedIntrotext')): ?>
<div class="itemRelIntrotext"><?php echo $item->introtext; ?></div>
<?php endif; ?>
<?php if($this->item->params->get('itemRelatedFulltext')): ?>
<div class="itemRelFulltext"><?php echo $item->fulltext; ?></div>
<?php endif; ?>
<?php if($this->item->params->get('itemRelatedMedia')): ?>
<?php if($item->videoType=='embedded'): ?>
<div class="itemRelMediaEmbedded"><?php echo $item->video; ?></div>
<?php else: ?>
<div class="itemRelMedia"><?php echo $item->video; ?></div>
<?php endif; ?>
<?php endif; ?>
<?php if($this->item->params->get('itemRelatedImageGallery')): ?>
<div class="itemRelImageGallery"><?php echo $item->gallery; ?></div>
<?php endif; ?>
</li>
<?php endforeach; ?>
<li class="clr"></li>
</ul>
<div class="clr"></div>
</div>
<?php endif; ?>
<div class="clr"></div>
<?php if($this->item->params->get('itemVideo') && !empty($this->item->video)): ?>
<!-- Item video -->
<a name="itemVideoAnchor" id="itemVideoAnchor"></a>
<div class="itemVideoBlock">
<h3><?php echo JText::_('K2_MEDIA'); ?></h3>
<?php if($this->item->videoType=='embedded'): ?>
<div class="itemVideoEmbedded">
<?php echo $this->item->video; ?>
</div>
<?php else: ?>
<span class="itemVideo"><?php echo $this->item->video; ?></span>
<?php endif; ?>
<?php if($this->item->params->get('itemVideoCaption') && !empty($this->item->video_caption)): ?>
<span class="itemVideoCaption"><?php echo $this->item->video_caption; ?></span>
<?php endif; ?>
<?php if($this->item->params->get('itemVideoCredits') && !empty($this->item->video_credits)): ?>
<span class="itemVideoCredits"><?php echo $this->item->video_credits; ?></span>
<?php endif; ?>
<div class="clr"></div>
</div>
<?php endif; ?>
<?php if($this->item->params->get('itemImageGallery') && !empty($this->item->gallery)): ?>
<!-- Item image gallery -->
<a name="itemImageGalleryAnchor" id="itemImageGalleryAnchor"></a>
<div class="itemImageGallery">
<h3><?php echo JText::_('K2_IMAGE_GALLERY'); ?></h3>
<?php echo $this->item->gallery; ?>
</div>
<?php endif; ?>
<?php if($this->item->params->get('itemNavigation') && !JRequest::getCmd('print') && (isset($this->item->nextLink) || isset($this->item->previousLink))): ?>
<!-- Item navigation -->
<div class="itemNavigation">
<span class="itemNavigationTitle"><?php echo JText::_('K2_MORE_IN_THIS_CATEGORY'); ?></span>
<?php if(isset($this->item->previousLink)): ?>
<a class="itemPrevious" href="<?php echo $this->item->previousLink; ?>">
« <?php echo $this->item->previousTitle; ?>
</a>
<?php endif; ?>
<?php if(isset($this->item->nextLink)): ?>
<a class="itemNext" href="<?php echo $this->item->nextLink; ?>">
<?php echo $this->item->nextTitle; ?> »
</a>
<?php endif; ?>
</div>
<?php endif; ?>
<!-- Plugins: AfterDisplay -->
<?php echo $this->item->event->AfterDisplay; ?>
<!-- K2 Plugins: K2AfterDisplay -->
<?php echo $this->item->event->K2AfterDisplay; ?>
<?php if($this->item->params->get('itemComments') && ( ($this->item->params->get('comments') == '2' && !$this->user->guest) || ($this->item->params->get('comments') == '1'))): ?>
<!-- K2 Plugins: K2CommentsBlock -->
<?php echo $this->item->event->K2CommentsBlock; ?>
<?php endif; ?>
<?php if($this->item->params->get('itemComments') && ($this->item->params->get('comments') == '1' || ($this->item->params->get('comments') == '2')) && empty($this->item->event->K2CommentsBlock)): ?>
<!-- Item comments -->
<a name="itemCommentsAnchor" id="itemCommentsAnchor"></a>
<div class="itemComments">
<?php if($this->item->params->get('commentsFormPosition')=='above' && $this->item->params->get('itemComments') && !JRequest::getInt('print') && ($this->item->params->get('comments') == '1' || ($this->item->params->get('comments') == '2' && K2HelperPermissions::canAddComment($this->item->catid)))): ?>
<!-- Item comments form -->
<div class="itemCommentsForm">
<?php echo $this->loadTemplate('comments_form'); ?>
</div>
<?php endif; ?>
<?php if($this->item->numOfComments>0 && $this->item->params->get('itemComments') && ($this->item->params->get('comments') == '1' || ($this->item->params->get('comments') == '2'))): ?>
<!-- Item user comments -->
<h3 class="itemCommentsCounter">
<span><?php echo $this->item->numOfComments; ?></span> <?php echo ($this->item->numOfComments>1) ? JText::_('K2_COMMENTS') : JText::_('K2_COMMENT'); ?>
</h3>
<ul class="itemCommentsList">
<?php foreach ($this->item->comments as $key=>$comment): ?>
<li class="<?php echo ($key%2) ? "odd" : "even"; echo (!$this->item->created_by_alias && $comment->userID==$this->item->created_by) ? " authorResponse" : ""; echo($comment->published) ? '':' unpublishedComment'; ?>">
<span class="commentLink">
<a href="<?php echo $this->item->link; ?>#comment<?php echo $comment->id; ?>" name="comment<?php echo $comment->id; ?>" id="comment<?php echo $comment->id; ?>">
<?php echo JText::_('K2_COMMENT_LINK'); ?>
</a>
</span>
<?php if($comment->userImage): ?>
<img src="<?php echo $comment->userImage; ?>" alt="<?php echo JFilterOutput::cleanText($comment->userName); ?>" width="<?php echo $this->item->params->get('commenterImgWidth'); ?>" />
<?php endif; ?>
<span class="commentDate">
<?php echo JHTML::_('date', $comment->commentDate, JText::_('K2_DATE_FORMAT_LC2')); ?>
</span>
<span class="commentAuthorName">
<?php echo JText::_('K2_POSTED_BY'); ?>
<?php if(!empty($comment->userLink)): ?>
<a href="<?php echo JFilterOutput::cleanText($comment->userLink); ?>" title="<?php echo JFilterOutput::cleanText($comment->userName); ?>" target="_blank" rel="nofollow">
<?php echo $comment->userName; ?>
</a>
<?php else: ?>
<?php echo $comment->userName; ?>
<?php endif; ?>
</span>
<p><?php echo $comment->commentText; ?></p>
<?php if($this->inlineCommentsModeration || ($comment->published && ($this->params->get('commentsReporting')=='1' || ($this->params->get('commentsReporting')=='2' && !$this->user->guest)))): ?>
<span class="commentToolbar">
<?php if($this->inlineCommentsModeration): ?>
<?php if(!$comment->published): ?>
<a class="commentApproveLink" href="<?php echo JRoute::_('index.php?option=com_k2&view=comments&task=publish&commentID='.$comment->id.'&format=raw')?>"><?php echo JText::_('K2_APPROVE')?></a>
<?php endif; ?>
<a class="commentRemoveLink" href="<?php echo JRoute::_('index.php?option=com_k2&view=comments&task=remove&commentID='.$comment->id.'&format=raw')?>"><?php echo JText::_('K2_REMOVE')?></a>
<?php endif; ?>
<?php if($comment->published && ($this->params->get('commentsReporting')=='1' || ($this->params->get('commentsReporting')=='2' && !$this->user->guest))): ?>
<a class="modal" rel="{handler:'iframe',size:{x:560,y:480}}" href="<?php echo JRoute::_('index.php?option=com_k2&view=comments&task=report&commentID='.$comment->id)?>"><?php echo JText::_('K2_REPORT')?></a>
<?php endif; ?>
<?php if($comment->reportUserLink): ?>
<a class="k2ReportUserButton" href="<?php echo $comment->reportUserLink; ?>"><?php echo JText::_('K2_FLAG_AS_SPAMMER'); ?></a>
<?php endif; ?>
</span>
<?php endif; ?>
<div class="clr"></div>
</li>
<?php endforeach; ?>
</ul>
<div class="itemCommentsPagination">
<?php echo $this->pagination->getPagesLinks(); ?>
<div class="clr"></div>
</div>
<?php endif; ?>
<?php if($this->item->params->get('commentsFormPosition')=='below' && $this->item->params->get('itemComments') && !JRequest::getInt('print') && ($this->item->params->get('comments') == '1' || ($this->item->params->get('comments') == '2' && K2HelperPermissions::canAddComment($this->item->catid)))): ?>
<!-- Item comments form -->
<div class="itemCommentsForm">
<?php echo $this->loadTemplate('comments_form'); ?>
</div>
<?php endif; ?>
<?php $user = JFactory::getUser(); if ($this->item->params->get('comments') == '2' && $user->guest): ?>
<div><?php echo JText::_('K2_LOGIN_TO_POST_COMMENTS'); ?></div>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if(!JRequest::getCmd('print')): ?>
<div class="itemBackToTop">
<a class="k2Anchor" href="<?php echo $this->item->link; ?>#startOfPageId<?php echo JRequest::getInt('id'); ?>">
<?php echo JText::_('K2_BACK_TO_TOP'); ?>
</a>
</div>
<?php endif; ?>
<div class="clr"></div>
</div>
<!-- End K2 Item Layout -->
| gpl-2.0 |
rogoznik/test | sample2/function.cpp | 1814 | #include <function.h>
int qwe(std::string s1, std::string s2){
int result=0;
int k,n;
if (s1.length() >= s2.length()){
for (int i=0; i < s1.length(); i++){
k=0;
n=i;
if (result > (s1.length()-i)) break;
if ((s1.length()-i) >= s2.length()){
for (int j=0; j < s2.length(); j++){
if (s1[n] == s2[j]) k++;
n++;
}
}else{
for (int j=0; j<(s1.length()-i); j++){
if (s1[n] == s2[j]) k++;
n++;
}
}
if (result < k) result = k;
}
}
if (s2.length() > s1.length()){
for (int i=0; i < s2.length(); i++){
k=0;
n=i;
if (result > (s2.length()-i)) break;
if ((s2.length()-i) >= s1.length()){
for (int j=0; j < s1.length(); j++){
if (s2[n] == s1[j]) k++;
n++;
}
}else{
for (int j=0; j<(s2.length()-i); j++){
if (s2[n] == s1[j]) k++;
n++;
}
}
if (result < k) result = k;
}
}
return result;
}
double asd(int k, std::string s1, std::string s2){
double result=0.0;
result=(double)k/((s1.length()+s2.length())/2);
return result;
}
double asdf(std::string s, std::vector<std::string> arr){
double result=0.0, aver_summ=0.0;
int k=0, summ_l=0;
for (int i=0; i < arr.size(); i++){
if (k < qwe(s,arr[i])){
k=qwe(s,arr[i]);
}
summ_l =+ arr[i].length();
}
aver_summ=(double)summ_l/arr.size();
result = (double)k/aver_summ;
return result;
}
| gpl-2.0 |
lewurm/graal | graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/calc/OrNode.java | 3038 | /*
* Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.nodes.calc;
import com.oracle.graal.api.code.*;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.compiler.common.type.*;
import com.oracle.graal.compiler.common.type.ArithmeticOpTable.BinaryOp.Or;
import com.oracle.graal.graph.spi.*;
import com.oracle.graal.lir.gen.*;
import com.oracle.graal.nodeinfo.*;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.spi.*;
import com.oracle.graal.nodes.util.*;
@NodeInfo(shortName = "|")
public class OrNode extends BinaryArithmeticNode<Or> {
public static OrNode create(ValueNode x, ValueNode y) {
return new OrNode(x, y);
}
protected OrNode(ValueNode x, ValueNode y) {
super(ArithmeticOpTable::getOr, x, y);
}
@Override
public ValueNode canonical(CanonicalizerTool tool, ValueNode forX, ValueNode forY) {
ValueNode ret = super.canonical(tool, forX, forY);
if (ret != this) {
return ret;
}
if (GraphUtil.unproxify(forX) == GraphUtil.unproxify(forY)) {
return forX;
}
if (forX.isConstant() && !forY.isConstant()) {
return create(forY, forX);
}
if (forY.isConstant()) {
Constant c = forY.asConstant();
if (getOp(forX, forY).isNeutral(c)) {
return forX;
}
if (c.getKind().isNumericInteger()) {
long rawY = c.asLong();
long mask = CodeUtil.mask(PrimitiveStamp.getBits(stamp()));
if ((rawY & mask) == mask) {
return ConstantNode.forIntegerStamp(stamp(), mask);
}
}
return reassociate(this, ValueNode.isConstantPredicate(), forX, forY);
}
return this;
}
@Override
public void generate(NodeMappableLIRBuilder builder, ArithmeticLIRGenerator gen) {
builder.setResult(this, gen.emitOr(builder.operand(getX()), builder.operand(getY())));
}
}
| gpl-2.0 |
ptidej/SmellDetectionCaller | PADL/src/padl/kernel/impl/Relationship.java | 2917 | /*******************************************************************************
* Copyright (c) 2001-2014 Yann-Gaël Guéhéneuc and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* Yann-Gaël Guéhéneuc and others, see in file; API and its implementation
******************************************************************************/
package padl.kernel.impl;
import padl.kernel.Constants;
import padl.kernel.IElementMarker;
import padl.kernel.IFirstClassEntity;
import padl.kernel.IRelationship;
import padl.kernel.IUseRelationship;
import padl.kernel.exception.ModelDeclarationException;
import padl.util.Util;
import util.io.ProxyConsole;
import util.lang.Modifier;
import util.multilingual.MultilingualManager;
abstract class Relationship extends Element implements IElementMarker,
IRelationship {
private static final long serialVersionUID = -5857707891166836532L;
private int cardinality;
private IFirstClassEntity targetEntity;
public Relationship(final char[] anID) {
super(anID);
}
public int getCardinality() {
return this.cardinality;
}
public IFirstClassEntity getTargetEntity() {
return this.targetEntity;
}
public void performCloneSession() {
super.performCloneSession();
final IUseRelationship clone = (IUseRelationship) this.getClone();
clone.setTargetEntity((IFirstClassEntity) this.targetEntity.getClone());
}
public void setCardinality(int aCardinality) {
if (aCardinality < 1) {
throw new ModelDeclarationException(MultilingualManager.getString(
"CARDINALITY",
IRelationship.class,
new Object[] { new Integer(this.cardinality) }));
}
this.cardinality = aCardinality;
}
public void setTargetEntity(final IFirstClassEntity anEntity) {
this.targetEntity = anEntity;
}
public String toString() {
if (Constants.DEBUG) {
ProxyConsole.getInstance().debugOutput().print("// ");
ProxyConsole.getInstance().debugOutput().print(this.getClass());
ProxyConsole.getInstance().debugOutput().println(".toString()");
}
return this.toString(0);
}
public String toString(final int tab) {
final StringBuffer buffer = new StringBuffer();
Util.addTabs(tab, buffer);
buffer.append(this.getClass().getName());
buffer.append("\nName: ");
buffer.append(this.getName());
buffer.append("\nWith: ");
buffer.append(this.getTargetEntity().getName());
buffer.append("\nVisibility: ");
buffer.append(Modifier.toString(this.getVisibility()));
buffer.append(", cadinality: ");
buffer.append(this.getCardinality());
buffer.append('\n');
return buffer.toString();
}
}
| gpl-2.0 |
mafru/icms2 | system/controllers/admin/forms/form_ctypes_basic.php | 23399 | <?php
class formAdminCtypesBasic extends cmsForm {
public function init($do, $ctype) {
$template = new cmsTemplate(cmsConfig::get('template'));
$meta_ctype_fields = [
'ctype_title' => LANG_CONTENT_TYPE . ': ' . LANG_TITLE,
'ctype_description' => LANG_CONTENT_TYPE . ': ' . LANG_DESCRIPTION,
'ctype_label1' => LANG_CP_NUMERALS_1_LABEL,
'ctype_label2' => LANG_CP_NUMERALS_2_LABEL,
'ctype_label10' => LANG_CP_NUMERALS_10_LABEL,
'filter_string' => LANG_FILTERS
];
$meta_item_fields = [
'title' => LANG_TITLE,
'description' => LANG_DESCRIPTION,
'ctype_title' => LANG_CONTENT_TYPE . ': ' . LANG_TITLE,
'ctype_description' => LANG_CONTENT_TYPE . ': ' . LANG_DESCRIPTION,
'ctype_label1' => LANG_CP_NUMERALS_1_LABEL,
'ctype_label2' => LANG_CP_NUMERALS_2_LABEL,
'ctype_label10' => LANG_CP_NUMERALS_10_LABEL,
'filter_string' => LANG_FILTERS
];
$item_fields = [
'category' => LANG_CATEGORY,
'hits_count' => LANG_HITS,
'comments' => LANG_COMMENTS,
'rating' => LANG_RATING,
'tags' => LANG_TAGS
];
if(!empty($ctype['name'])){
$_item_fields = cmsCore::getModel('content')->orderBy('ordering')->getContentFields($ctype['name']);
foreach ($_item_fields as $field) {
$item_fields[$field['name']] = $field['title'];
}
}
$this->setData('meta_item_fields', $meta_item_fields);
$this->setData('meta_ctype_fields', $meta_ctype_fields);
$this->setData('item_fields', $item_fields);
return array(
'titles' => array(
'title' => LANG_BASIC_OPTIONS,
'type' => 'fieldset',
'childs' => array(
new fieldString('name', array(
'title' => LANG_SYSTEM_NAME,
'hint' => LANG_CP_SYSTEM_NAME_HINT,
'options'=>array(
'max_length' => 32,
'show_symbol_count' => true
),
'rules' => array(
array('required'),
array('sysname'),
$do == 'add' ? array('unique', 'content_types', 'name') : false
)
)),
new fieldString('title', array(
'title' => LANG_TITLE,
'options'=>array(
'max_length' => 100,
'show_symbol_count' => true
),
'rules' => array(
array('required')
)
)),
new fieldHtml('description', array(
'title' => LANG_DESCRIPTION
)),
)
),
'pub' => array(
'type' => 'fieldset',
'is_collapsed' => true,
'title' => LANG_CP_PUBLICATION,
'childs' => array(
new fieldCheckbox('is_date_range', array(
'title' => LANG_CP_IS_PUB_CONTROL,
'hint' => LANG_CP_IS_PUB_CONTROL_HINT
)),
new fieldList('options:is_date_range_process', array(
'title' => LANG_CP_IS_PUB_CONTROL_PROCESS,
'default' => 'hide',
'items' => array(
'hide' => LANG_CP_IS_PUB_CONTROL_PROCESS_HIDE,
'delete' => LANG_CP_IS_PUB_CONTROL_PROCESS_DEL,
'in_basket' => LANG_BASKET_DELETE
),
'visible_depend' => array('is_date_range' => array('show' => array('1')))
)),
new fieldNumber('options:notify_end_date_days', array(
'title' => LANG_CP_NOTIFY_END_DATE_DAYS,
'units' => LANG_DAYS,
'default' => 1,
'visible_depend' => array('is_date_range' => array('show' => array('1')))
)),
new fieldString('options:notify_end_date_notice', array(
'title' => LANG_MESSAGE,
'multilanguage' => true,
'is_clean_disable' => true,
'default' => 'Через %s публикация вашего контента <a href="%s">%s</a> будет прекращена.',
'visible_depend' => array('is_date_range' => array('show' => array('1')))
)),
new fieldCheckbox('options:disable_drafts', array(
'title' => LANG_CP_DISABLE_DRAFTS
))
)
),
'categories' => array(
'type' => 'fieldset',
'is_collapsed' => true,
'title' => LANG_CATEGORIES,
'childs' => array(
new fieldCheckbox('is_cats', array(
'title' => LANG_CP_CATEGORIES_ON
)),
new fieldCheckbox('is_cats_recursive', array(
'title' => LANG_CP_CATEGORIES_RECURSIVE,
'visible_depend' => array('is_cats' => array('show' => array('1')))
)),
new fieldCheckbox('options:is_empty_root', array(
'title' => LANG_CP_CATEGORIES_EMPTY_ROOT,
'visible_depend' => array('is_cats' => array('show' => array('1')))
)),
new fieldCheckbox('options:is_cats_multi', array(
'title' => LANG_CP_CATEGORIES_MULTI,
'visible_depend' => array('is_cats' => array('show' => array('1')))
)),
new fieldCheckbox('options:is_cats_change', array(
'title' => LANG_CP_CATEGORIES_CHANGE,
'default' => true,
'visible_depend' => array('is_cats' => array('show' => array('1')))
)),
new fieldCheckbox('options:is_cats_open_root', array(
'title' => LANG_CP_CATEGORIES_OPEN_ROOT,
'visible_depend' => array('is_cats' => array('show' => array('1')))
)),
new fieldCheckbox('options:is_cats_only_last', array(
'title' => LANG_CP_CATEGORIES_ONLY_LAST,
'visible_depend' => array('is_cats' => array('show' => array('1')))
)),
new fieldCheckbox('options:is_show_cats', array(
'title' => LANG_CP_CATEGORIES_SHOW,
'visible_depend' => array('is_cats' => array('show' => array('1')))
)),
new fieldListMultiple('options:cover_sizes', array(
'title' => LANG_CP_CAT_COVER_SIZES,
'default' => array(),
'generator' => function (){
$presets = cmsCore::getModel('images')->getPresetsList();
$presets['original'] = LANG_PARSER_IMAGE_SIZE_ORIGINAL;
return $presets;
},
'visible_depend' => array('is_cats' => array('show' => array('1')))
)),
new fieldList('options:context_list_cover_sizes', array(
'title' => LANG_CP_CAT_CONTEXT_LIST_COVER_SIZES,
'is_multiple' => true,
'dynamic_list' => true,
'select_title' => LANG_CP_CONTEXT_SELECT_LIST,
'generator' => function($ctype) use ($template){
return $template->getAvailableContentListStyles();
},
'values_generator' => function() {
$presets = cmsCore::getModel('images')->getPresetsList();
$presets['original'] = LANG_PARSER_IMAGE_SIZE_ORIGINAL;
return $presets;
},
'visible_depend' => array('is_cats' => array('show' => array('1')))
))
)
),
'folders' => array(
'type' => 'fieldset',
'is_collapsed' => true,
'title' => LANG_CP_FOLDERS,
'childs' => array(
new fieldCheckbox('is_folders', array(
'title' => LANG_CP_FOLDERS_ON,
'hint' => LANG_CP_FOLDERS_HINT
)),
)
),
'listview' => array(
'type' => 'fieldset',
'is_collapsed' => true,
'title' => LANG_CP_LISTVIEW_OPTIONS,
'childs' => array(
new fieldCheckbox('options:list_off_breadcrumb', array(
'title' => LANG_CP_LIST_OFF_BREADCRUMB
)),
new fieldCheckbox('options:list_on', array(
'title' => LANG_CP_LISTVIEW_ON,
'default' => true
)),
new fieldCheckbox('options:profile_on', array(
'title' => LANG_CP_PROFILELIST_ON,
'default' => true
)),
new fieldCheckbox('options:list_show_filter', array(
'title' => LANG_CP_LISTVIEW_FILTER
)),
new fieldCheckbox('options:list_expand_filter', array(
'title' => LANG_CP_LISTVIEW_FILTER_EXPAND,
'visible_depend' => array('options:list_show_filter' => array('show' => array('1')))
)),
new fieldList('options:privacy_type', array(
'title' => LANG_CP_PRIVACY_TYPE,
'default' => 'hide',
'items' => array(
'hide' => LANG_CP_PRIVACY_TYPE_HIDE,
'show_title' => LANG_CP_PRIVACY_TYPE_SHOW_TITLE,
'show_all' => LANG_CP_PRIVACY_TYPE_SHOW_ALL
)
)),
new fieldNumber('options:limit', array(
'title' => LANG_LIST_LIMIT,
'default' => 15,
'rules' => array(
array('required')
)
)),
new fieldList('options:list_style', array(
'title' => LANG_CP_LISTVIEW_STYLE,
'is_chosen_multiple' => true,
'hint' => sprintf(LANG_CP_LISTVIEW_STYLE_HINT, $template->getName()),
'generator' => function() use($template){
return $template->getAvailableContentListStyles();
}
)),
new fieldList('options:list_style_names', array(
'title' => LANG_CP_LIST_STYLE_NAMES,
'is_multiple' => true,
'dynamic_list' => true,
'select_title' => LANG_CP_CONTEXT_SELECT_LIST,
'multiple_keys' => array(
'name' => 'field', 'value' => 'field_value'
),
'generator' => function($ctype) use ($template){
return $template->getAvailableContentListStyles();
}
)),
new fieldList('options:context_list_style', array(
'title' => LANG_CP_CONTEXT_LIST_STYLE,
'is_multiple' => true,
'dynamic_list' => true,
'select_title' => LANG_CP_CONTEXT_SELECT_LIST,
'generator' => function($item) use ($do, $ctype){
$lists = cmsEventsManager::hookAll('ctype_lists_context', 'template'.($do != 'add' ? ':'.$ctype['name'] : ''));
$items = [];
if($lists){
foreach ($lists as $list) {
$items = array_merge($items, $list);
}
}
return $items;
},
'values_generator' => function() use($template){
return $template->getAvailableContentListStyles();
}
))
)
),
'itemview' => array(
'type' => 'fieldset',
'is_collapsed' => true,
'title' => LANG_CP_ITEMVIEW_OPTIONS,
'childs' => array(
new fieldCheckbox('options:item_off_breadcrumb', array(
'title' => LANG_CP_LIST_OFF_BREADCRUMB
)),
new fieldCheckbox('options:item_on', array(
'title' => LANG_CP_ITEMVIEW_ON,
'default' => true
)),
new fieldCheckbox('options:is_show_fields_group', array(
'title' => LANG_CP_ITEMVIEW_FIELDS_GROUP,
'visible_depend' => array('options:item_on' => array('show' => array('1')))
)),
new fieldCheckbox('options:hits_on', array(
'title' => LANG_CP_ITEMVIEW_HITS_ON,
'visible_depend' => array('options:item_on' => array('show' => array('1')))
)),
new fieldText('options:share_code', array(
'title' => LANG_CP_ITEMVIEW_SHARE_CODE,
'visible_depend' => array('options:item_on' => array('show' => array('1')))
)),
new fieldText('item_append_html', array(
'title' => LANG_CP_ITEMVIEW_APPEND_HTML,
'hint' => LANG_CP_ITEMVIEW_APPEND_HTML_HINT,
'visible_depend' => array('options:item_on' => array('show' => array('1')))
)),
)
),
'seo-items' => array(
'type' => 'fieldset',
'is_collapsed' => true,
'title' => LANG_CP_SEOMETA,
'childs' => array(
new fieldCheckbox('options:is_manual_title', array(
'title' => LANG_CP_SEOMETA_MANUAL_TITLE,
)),
new fieldCheckbox('is_auto_keys', array(
'title' => LANG_CP_SEOMETA_AUTO_KEYS,
'default' => true
)),
new fieldCheckbox('is_auto_desc', array(
'title' => LANG_CP_SEOMETA_AUTO_DESC,
'default' => true
)),
new fieldCheckbox('is_auto_url', array(
'title' => LANG_CP_AUTO_URL,
'default' => true
)),
new fieldCheckbox('is_fixed_url', array(
'title' => LANG_CP_FIXED_URL
)),
new fieldString('url_pattern', array(
'title' => LANG_CP_URL_PATTERN,
'prefix' => '/'.(!empty($ctype['name']) ? $ctype['name'] : '').'/',
'suffix' => '.html',
'default' => '{id}-{title}',
'options'=>array(
'max_length' => 255,
'show_symbol_count' => true
),
'rules' => array(
array('required')
)
)),
new fieldString('options:seo_title_pattern', array(
'title' => LANG_CP_SEOMETA_ITEM_TITLE,
'patterns_hint' => [
'patterns' => $item_fields
]
)),
new fieldString('options:seo_keys_pattern', array(
'title' => LANG_CP_SEOMETA_ITEM_KEYS,
'patterns_hint' => [
'patterns' => $item_fields
]
)),
new fieldString('options:seo_desc_pattern', array(
'title' => LANG_CP_SEOMETA_ITEM_DESC,
'patterns_hint' => [
'patterns' => $item_fields
]
))
)
),
'seo-cats' => array(
'type' => 'fieldset',
'is_collapsed' => true,
'title' => LANG_CP_SEOMETA_CATS,
'childs' => array(
new fieldCheckbox('options:is_cats_title', array(
'title' => LANG_CP_SEOMETA_CATS_TITLE
)),
new fieldCheckbox('options:is_cats_h1', array(
'title' => LANG_CP_SEOMETA_CATS_H1
)),
new fieldCheckbox('options:is_cats_keys', array(
'title' => LANG_CP_SEOMETA_CATS_KEYS
)),
new fieldCheckbox('options:is_cats_desc', array(
'title' => LANG_CP_SEOMETA_CATS_DESC
)),
new fieldCheckbox('options:is_cats_auto_url', array(
'title' => LANG_CP_CATS_AUTO_URL,
'default' => true
)),
new fieldString('options:seo_cat_h1_pattern', array(
'title' => LANG_CP_SEOMETA_ITEM_H1,
'patterns_hint' => [
'patterns' => $meta_item_fields
]
)),
new fieldString('options:seo_cat_title_pattern', array(
'title' => LANG_CP_SEOMETA_ITEM_TITLE,
'patterns_hint' => [
'patterns' => $meta_item_fields
]
)),
new fieldString('options:seo_cat_keys_pattern', array(
'title' => LANG_CP_SEOMETA_ITEM_KEYS,
'patterns_hint' => [
'patterns' => $meta_item_fields
]
)),
new fieldString('options:seo_cat_desc_pattern', array(
'title' => LANG_CP_SEOMETA_ITEM_DESC,
'patterns_hint' => [
'patterns' => $meta_item_fields
]
))
)
),
'seo' => array(
'type' => 'fieldset',
'is_collapsed' => true,
'title' => LANG_CP_SEOMETA_DEFAULT,
'childs' => array(
new fieldString('options:seo_ctype_h1_pattern', array(
'title' => LANG_CP_SEOMETA_ITEM_H1,
'patterns_hint' => [
'patterns' => $meta_ctype_fields
]
)),
new fieldString('seo_title', array(
'title' => LANG_CP_SEOMETA_ITEM_TITLE,
'patterns_hint' => [
'patterns' => $meta_ctype_fields
],
'options'=>array(
'max_length'=> 256,
'show_symbol_count'=>true
)
)),
new fieldString('seo_keys', array(
'title' => LANG_CP_SEOMETA_ITEM_KEYS,
'patterns_hint' => [
'patterns' => $meta_ctype_fields
],
'options'=>array(
'max_length'=> 256,
'show_symbol_count'=>true
)
)),
new fieldText('seo_desc', array(
'title' => LANG_CP_SEOMETA_ITEM_DESC,
'is_strip_tags' => true,
'patterns_hint' => [
'patterns' => $meta_ctype_fields
],
'options'=>array(
'max_length'=> 256,
'show_symbol_count'=>true
)
))
)
),
'collapsed' => array(
'type' => 'fieldset',
'is_collapsed' => true,
'title' => LANG_CP_IS_COLLAPSED,
'childs' => array(
new fieldListMultiple('options:is_collapsed', array(
'generator' => function ($item) use($do, $ctype){
$items = array(
'folder' => LANG_CP_FOLDERS,
'group_wrap' => LANG_CP_CT_GROUPS
);
if($do != 'add'){
$model = cmsCore::getModel('content');
$fieldset_titles = $model->orderBy('ordering')->getContentFieldsets($ctype['id']);
if($fieldset_titles){
foreach ($fieldset_titles as $fieldset) {
$items[md5($fieldset)] = $fieldset;
}
}
}
return $items + array(
'tags_wrap' => LANG_TAGS,
'privacy_wrap' => LANG_CP_FIELD_PRIVACY,
'is_comment' => LANG_CP_COMMENTS,
'seo_wrap' => LANG_SEO,
'pub_wrap' => LANG_CP_PUBLICATION,
);
}
))
)
)
);
}
}
| gpl-2.0 |
paulkarlik/Standards | wp-content/themes/skeleton/checkout/form.php | 629 | <?php do_action('before_checkout_form'); ?>
<form name="checkout" method="post" class="checkout" action="<?php echo jigoshop_cart::get_checkout_url(); ?>">
<div class="col2-set" id="customer_details">
<div class="one_half">
<?php do_action('jigoshop_checkout_billing'); ?>
</div>
<div class="one_half last">
<?php do_action('jigoshop_checkout_shipping'); ?>
</div>
</div>
<div class="clear"></div>
<h3 id="order_review_heading"><?php _e('Your order', 'jigoshop'); ?></h3>
<?php jigoshop_get_template('checkout/review_order.php'); ?>
</form>
<?php do_action('after_checkout_form'); ?> | gpl-2.0 |
Frankenhooker/FCore | src/server/shared/Database/Implementation/LoginDatabase.cpp | 13876 | /*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "LoginDatabase.h"
void LoginDatabaseConnection::DoPrepareStatements()
{
if (!m_reconnecting)
m_stmts.resize(MAX_LOGINDATABASE_STATEMENTS);
PrepareStatement(LOGIN_SEL_REALMLIST, "SELECT id, name, address, localAddress, localSubnetMask, port, icon, flag, timezone, allowedSecurityLevel, population, gamebuild FROM realmlist WHERE flag <> 3 ORDER BY name", CONNECTION_SYNCH);
PrepareStatement(LOGIN_DEL_EXPIRED_IP_BANS, "DELETE FROM ip_banned WHERE unbandate<>bandate AND unbandate<=UNIX_TIMESTAMP()", CONNECTION_ASYNC);
PrepareStatement(LOGIN_UPD_EXPIRED_ACCOUNT_BANS, "UPDATE account_banned SET active = 0 WHERE active = 1 AND unbandate<>bandate AND unbandate<=UNIX_TIMESTAMP()", CONNECTION_ASYNC);
PrepareStatement(LOGIN_SEL_IP_BANNED, "SELECT * FROM ip_banned WHERE ip = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_INS_IP_AUTO_BANNED, "INSERT INTO ip_banned (ip, bandate, unbandate, bannedby, banreason) VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, 'Trinity realmd', 'Failed login autoban')", CONNECTION_ASYNC);
PrepareStatement(LOGIN_SEL_IP_BANNED_ALL, "SELECT ip, bandate, unbandate, bannedby, banreason FROM ip_banned WHERE (bandate = unbandate OR unbandate > UNIX_TIMESTAMP()) ORDER BY unbandate", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_IP_BANNED_BY_IP, "SELECT ip, bandate, unbandate, bannedby, banreason FROM ip_banned WHERE (bandate = unbandate OR unbandate > UNIX_TIMESTAMP()) AND ip LIKE CONCAT('%%', ?, '%%') ORDER BY unbandate", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_ACCOUNT_BANNED, "SELECT bandate, unbandate FROM account_banned WHERE id = ? AND active = 1", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_ACCOUNT_BANNED_ALL, "SELECT account.id, username FROM account, account_banned WHERE account.id = account_banned.id AND active = 1 GROUP BY account.id", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_ACCOUNT_BANNED_BY_USERNAME, "SELECT account.id, username FROM account, account_banned WHERE account.id = account_banned.id AND active = 1 AND username LIKE CONCAT('%%', ?, '%%') GROUP BY account.id", CONNECTION_SYNCH);
PrepareStatement(LOGIN_INS_ACCOUNT_AUTO_BANNED, "INSERT INTO account_banned VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, 'Trinity realmd', 'Failed login autoban', 1)", CONNECTION_ASYNC);
PrepareStatement(LOGIN_DEL_ACCOUNT_BANNED, "DELETE FROM account_banned WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_SEL_SESSIONKEY, "SELECT a.sessionkey, a.id, aa.gmlevel FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE username = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_UPD_VS, "UPDATE account SET v = ?, s = ? WHERE username = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_UPD_LOGONPROOF, "UPDATE account SET sessionkey = ?, last_ip = ?, last_login = NOW(), locale = ?, failed_logins = 0, os = ? WHERE username = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_LOGONCHALLENGE, "SELECT a.sha_pass_hash, a.id, a.locked, a.lock_country, a.last_ip, aa.gmlevel, a.v, a.s, a.token_key FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.username = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_LOGON_COUNTRY, "SELECT country FROM ip2nation WHERE ip < ? ORDER BY ip DESC LIMIT 0,1", CONNECTION_SYNCH);
PrepareStatement(LOGIN_UPD_FAILEDLOGINS, "UPDATE account SET failed_logins = failed_logins + 1 WHERE username = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_SEL_FAILEDLOGINS, "SELECT id, failed_logins FROM account WHERE username = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_ACCOUNT_ID_BY_NAME, "SELECT id FROM account WHERE username = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_ACCOUNT_LIST_BY_NAME, "SELECT id, username FROM account WHERE username = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_ACCOUNT_INFO_BY_NAME, "SELECT id, sessionkey, last_ip, locked, expansion, mutetime, locale, recruiter, os FROM account WHERE username = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_ACCOUNT_LIST_BY_EMAIL, "SELECT id, username FROM account WHERE email = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_NUM_CHARS_ON_REALM, "SELECT numchars FROM realmcharacters WHERE realmid = ? AND acctid= ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_ACCOUNT_BY_IP, "SELECT id, username FROM account WHERE last_ip = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_ACCOUNT_BY_ID, "SELECT 1 FROM account WHERE id = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_INS_IP_BANNED, "INSERT INTO ip_banned (ip, bandate, unbandate, bannedby, banreason) VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(LOGIN_DEL_IP_NOT_BANNED, "DELETE FROM ip_banned WHERE ip = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_INS_ACCOUNT_BANNED, "INSERT INTO account_banned VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, ?, ?, 1)", CONNECTION_ASYNC);
PrepareStatement(LOGIN_UPD_ACCOUNT_NOT_BANNED, "UPDATE account_banned SET active = 0 WHERE id = ? AND active != 0", CONNECTION_ASYNC);
PrepareStatement(LOGIN_DEL_REALM_CHARACTERS_BY_REALM, "DELETE FROM realmcharacters WHERE acctid = ? AND realmid = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_DEL_REALM_CHARACTERS, "DELETE FROM realmcharacters WHERE acctid = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_INS_REALM_CHARACTERS, "INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(LOGIN_SEL_SUM_REALM_CHARACTERS, "SELECT SUM(numchars) FROM realmcharacters WHERE acctid = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_INS_ACCOUNT, "INSERT INTO account(username, sha_pass_hash, reg_mail, email, joindate) VALUES(?, ?, ?, ?, NOW())", CONNECTION_SYNCH);
PrepareStatement(LOGIN_INS_REALM_CHARACTERS_INIT, "INSERT INTO realmcharacters (realmid, acctid, numchars) SELECT realmlist.id, account.id, 0 FROM realmlist, account LEFT JOIN realmcharacters ON acctid=account.id WHERE acctid IS NULL", CONNECTION_ASYNC);
PrepareStatement(LOGIN_UPD_EXPANSION, "UPDATE account SET expansion = ? WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_UPD_ACCOUNT_LOCK, "UPDATE account SET locked = ? WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_UPD_ACCOUNT_LOCK_CONTRY, "UPDATE account SET lock_country = ? WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_INS_LOG, "INSERT INTO logs (time, realm, type, level, string) VALUES (?, ?, ?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(LOGIN_UPD_USERNAME, "UPDATE account SET v = 0, s = 0, username = ?, sha_pass_hash = ? WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_UPD_PASSWORD, "UPDATE account SET v = 0, s = 0, sha_pass_hash = ? WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_UPD_EMAIL, "UPDATE account SET email = ? WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_UPD_REG_EMAIL, "UPDATE account SET reg_mail = ? WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_UPD_MUTE_TIME, "UPDATE account SET mutetime = ? , mutereason = ? , muteby = ? WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_UPD_MUTE_TIME_LOGIN, "UPDATE account SET mutetime = ? WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_UPD_LAST_IP, "UPDATE account SET last_ip = ? WHERE username = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_UPD_ACCOUNT_ONLINE, "UPDATE account SET online = 1 WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_UPD_UPTIME_PLAYERS, "UPDATE uptime SET uptime = ?, maxplayers = ? WHERE realmid = ? AND starttime = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_DEL_OLD_LOGS, "DELETE FROM logs WHERE (time + ?) < ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_DEL_ACCOUNT_ACCESS, "DELETE FROM account_access WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_DEL_ACCOUNT_ACCESS_BY_REALM, "DELETE FROM account_access WHERE id = ? AND (RealmID = ? OR RealmID = -1)", CONNECTION_ASYNC);
PrepareStatement(LOGIN_INS_ACCOUNT_ACCESS, "INSERT INTO account_access (id,gmlevel,RealmID) VALUES (?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(LOGIN_GET_ACCOUNT_ID_BY_USERNAME, "SELECT id FROM account WHERE username = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_GET_ACCOUNT_ACCESS_GMLEVEL, "SELECT gmlevel FROM account_access WHERE id = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_GET_GMLEVEL_BY_REALMID, "SELECT gmlevel FROM account_access WHERE id = ? AND (RealmID = ? OR RealmID = -1)", CONNECTION_SYNCH);
PrepareStatement(LOGIN_GET_USERNAME_BY_ID, "SELECT username FROM account WHERE id = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_CHECK_PASSWORD, "SELECT 1 FROM account WHERE id = ? AND sha_pass_hash = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_CHECK_PASSWORD_BY_NAME, "SELECT 1 FROM account WHERE username = ? AND sha_pass_hash = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_PINFO, "SELECT a.username, aa.gmlevel, a.email, a.reg_mail, a.last_ip, DATE_FORMAT(a.last_login, '%Y-%m-%d %T'), a.mutetime, a.mutereason, a.muteby, a.failed_logins, a.locked, a.OS FROM account a LEFT JOIN account_access aa ON (a.id = aa.id AND (aa.RealmID = ? OR aa.RealmID = -1)) WHERE a.id = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_PINFO_BANS, "SELECT unbandate, bandate = unbandate, bannedby, banreason FROM account_banned WHERE id = ? AND active ORDER BY bandate ASC LIMIT 1", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_GM_ACCOUNTS, "SELECT a.username, aa.gmlevel FROM account a, account_access aa WHERE a.id=aa.id AND aa.gmlevel >= ? AND (aa.realmid = -1 OR aa.realmid = ?)", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_ACCOUNT_INFO, "SELECT a.username, a.last_ip, aa.gmlevel, a.expansion FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.id = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_ACCOUNT_ACCESS_GMLEVEL_TEST, "SELECT 1 FROM account_access WHERE id = ? AND gmlevel > ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_ACCOUNT_ACCESS, "SELECT a.id, aa.gmlevel, aa.RealmID FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.username = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_ACCOUNT_RECRUITER, "SELECT 1 FROM account WHERE recruiter = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_BANS, "SELECT 1 FROM account_banned WHERE id = ? AND active = 1 UNION SELECT 1 FROM ip_banned WHERE ip = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_ACCOUNT_WHOIS, "SELECT username, email, last_ip FROM account WHERE id = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_REALMLIST_SECURITY_LEVEL, "SELECT allowedSecurityLevel from realmlist WHERE id = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_DEL_ACCOUNT, "DELETE FROM account WHERE id = ?", CONNECTION_ASYNC);
PrepareStatement(LOGIN_SEL_IP2NATION_COUNTRY, "SELECT c.country FROM ip2nationcountries c, ip2nation i WHERE i.ip < ? AND c.code = i.country ORDER BY i.ip DESC LIMIT 0,1", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_AUTOBROADCAST, "SELECT id, weight, text FROM autobroadcast WHERE realmid = ? OR realmid = -1", CONNECTION_SYNCH);
PrepareStatement(LOGIN_GET_EMAIL_BY_ID, "SELECT email FROM account WHERE id = ?", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_ACCOUNT_ACCESS_BY_ID, "SELECT gmlevel, RealmID FROM account_access WHERE id = ? and (RealmID = ? OR RealmID = -1) ORDER BY gmlevel desc", CONNECTION_SYNCH);
PrepareStatement(LOGIN_SEL_RBAC_ACCOUNT_GROUPS, "SELECT groupId FROM rbac_account_groups WHERE accountId = ? AND (realmId = ? OR realmId = -1) GROUP BY groupId", CONNECTION_SYNCH);
PrepareStatement(LOGIN_INS_RBAC_ACCOUNT_GROUP, "INSERT INTO rbac_account_groups (accountId, groupId, realmId) VALUES (?, ?, ?)", CONNECTION_ASYNC);
PrepareStatement(LOGIN_DEL_RBAC_ACCOUNT_GROUP, "DELETE FROM rbac_account_groups WHERE accountId = ? AND groupId = ? AND (realmId = ? OR realmId = -1)", CONNECTION_ASYNC);
PrepareStatement(LOGIN_SEL_RBAC_ACCOUNT_ROLES, "SELECT roleId, granted FROM rbac_account_roles WHERE accountId = ? AND (realmId = ? OR realmId = -1) ORDER BY roleId, realmId", CONNECTION_SYNCH);
PrepareStatement(LOGIN_INS_RBAC_ACCOUNT_ROLE, "INSERT INTO rbac_account_roles (accountId, roleId, granted, realmId) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE granted = VALUES(granted)", CONNECTION_ASYNC);
PrepareStatement(LOGIN_DEL_RBAC_ACCOUNT_ROLE, "DELETE FROM rbac_account_roles WHERE accountId = ? AND roleId = ? AND (realmId = ? OR realmId = -1)", CONNECTION_ASYNC);
PrepareStatement(LOGIN_SEL_RBAC_ACCOUNT_PERMISSIONS, "SELECT permissionId, granted FROM rbac_account_permissions WHERE accountId = ? AND (realmId = ? OR realmId = -1) ORDER BY permissionId, realmId", CONNECTION_SYNCH);
PrepareStatement(LOGIN_INS_RBAC_ACCOUNT_PERMISSION, "INSERT INTO rbac_account_permissions (accountId, permissionId, granted, realmId) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE granted = VALUES(granted)", CONNECTION_ASYNC);
PrepareStatement(LOGIN_DEL_RBAC_ACCOUNT_PERMISSION, "DELETE FROM rbac_account_permissions WHERE accountId = ? AND permissionId = ? AND (realmId = ? OR realmId = -1)", CONNECTION_ASYNC);
}
| gpl-2.0 |
yakuzmenko/bereg | administrator/components/com_users/views/debuguser/view.html.php | 1386 | <?php
/**
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* View class for a list of users.
*
* @package Joomla.Administrator
* @subpackage com_users
* @since 1.6
*/
class UsersViewDebugUser extends JViewLegacy
{
protected $actions;
protected $items;
protected $pagination;
protected $state;
/**
* Display the view
*/
public function display($tpl = null)
{
$this->actions = $this->get('DebugActions');
$this->items = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->state = $this->get('State');
$this->user = $this->get('User');
$this->levels = UsersHelperDebug::getLevelsOptions();
$this->components = UsersHelperDebug::getComponents();
// Check for errors.
if (count($errors = $this->get('Errors'))) {
JError::raiseError(500, implode("\n", $errors));
return false;
}
$this->addToolbar();
parent::display($tpl);
}
/**
* Add the page title and toolbar.
*
* @since 1.6
*/
protected function addToolbar()
{
JToolBarHelper::title(JText::sprintf('COM_USERS_VIEW_DEBUG_USER_TITLE', $this->user->id, $this->user->name), 'user');
JToolBarHelper::help('JHELP_USERS_DEBUG_USERS');
}
}
| gpl-2.0 |
twistedvisions/anaximander | lib/parser/writers/getSubTypes.js | 5608 | var when = require("when"),
guard = require("when/guard"),
_ = require("underscore"),
winston = require("winston"),
utils = require("../utils"),
lock = require("../acquireLock"),
db = require("../raw_db");
lock.start();
var getSubtypeIdQuery = _.template([
"SELECT id",
"FROM type",
"WHERE name = '<%= name %>'"
].join(" "));
var createSubtypeQuery = _.template([
"INSERT INTO type (name, type_id, parent_type_id, creator_id)",
"VALUES ('<%= name %>', 4, <%= type_id %>, 1)",
"RETURNING id"
].join(" "));
var createImportanceQuery = _.template([
"INSERT INTO importance (name, description, value, type_id, creator_id)",
"VALUES ('nominal', '<%= description %>', 5, <%= type_id %>, 1)",
"RETURNING id"
].join(" "));
var setDefaultImportanceQuery = _.template([
"UPDATE type SET default_importance_id = <%= importance_id %> ",
"WHERE id = <%= type_id %>"
].join(" "));
var setDefaultImportance = function (job, typeId, importanceId) {
var d = when.defer();
var query = setDefaultImportanceQuery({
type_id: typeId,
importance_id: importanceId
});
job.log(query);
db.runQuery(query).then(
function (/*result*/) {
job.log("set default importance for " + typeId + " as " + importanceId);
d.resolve();
},
function (err) {
job.log("could not set default importance");
job.log(err);
winston.error("could not set default importance", err);
d.resolve();
}
);
return d.promise;
};
var createImportance = function (job, name, typeId) {
var d = when.defer();
var query = createImportanceQuery({
description: "a default value of importance for " + name,
type_id: typeId
});
job.log(query);
db.runQuery(query).then(
function (result) {
var id = result.rows.length ? result.rows[0].id : null;
if (id) {
job.log("created importance for " + name + " with id " + id);
setDefaultImportance(job, typeId, id).then(function () {
d.resolve();
});
} else {
job.log("could not create an importance ... odd!");
d.resolve();
}
},
function (err) {
job.log("could not create importance");
job.log(err);
winston.error("could not create importance", err);
d.resolve();
}
);
return d.promise;
};
var createSubType = function (job, typeId, name) {
var d = when.defer();
var query = createSubtypeQuery({
name: name,
type_id: typeId
});
job.log(query);
db.runQuery(query).then(
function (result) {
var id = result.rows.length ? result.rows[0].id : null;
if (id) {
job.log("created type for " + name + " with id " + id);
createImportance(job, name, id).then(function () {
d.resolve(id);
});
} else {
job.log("could not create a subtype ... odd!");
d.resolve();
}
},
function (err) {
job.log("could not create thing type");
job.log(err);
winston.error("could not create thing type", err);
d.resolve();
}
);
return d.promise;
};
var lookups = require("../../../config/subtype_lookups.json");
var regexes = require("../../../config/subtype_regexes.json");
var lookupSubTypeName = function (typeId, name) {
var hasRegexMatch = function (typeId, name) {
var potentials = regexes[typeId];
if (!potentials) {
return false;
}
var match = _.find(_.pairs(potentials), function (potential) {
return _.any(potential[1], function (regex) {
return new RegExp(regex, "i").test(name);
});
});
if (match) {
return match[0];
}
};
var regexMatch;
name = name.replace("''", "'");
if (lookups[typeId] && lookups[typeId][name] !== undefined) {
return lookups[typeId][name];
} else {
regexMatch = hasRegexMatch(typeId, name);
if (regexMatch) {
return regexMatch;
}
}
return name;
};
var getSubType = function (job, typeId, subTypeName) {
var d = when.defer();
var lockName = typeId.toString() + "_" + subTypeName;
winston.debug("get lock " + lockName);
lock.acquireLock(lockName).then(function (releaseLock) {
winston.debug("got lock " + lockName);
d.promise.then(function () {
winston.debug("release lock " + lockName);
releaseLock();
});
db.runQuery(getSubtypeIdQuery({name: subTypeName})).then(
function (result) {
var id = result.rows.length ? result.rows[0].id : null;
if (id) {
job.log("found id " + id + " for subtype " + subTypeName);
d.resolve(id);
} else {
createSubType(job, typeId, subTypeName).then(function (typeId) {
d.resolve(typeId);
});
}
},
function (e) {
job.log("could not get thing type for name " + subTypeName);
job.log(e);
winston.error("could not get thing type for name " + subTypeName,
utils.getError(e, job));
d.resolve();
}
);
});
return d.promise;
};
var getSubTypes = function (job, typeId, values) {
var deferred = when.defer();
if (values && values.length > 0) {
values = _.map(values, function (value) {
return lookupSubTypeName(typeId, value);
});
values = _.filter(values, function (value) {
return !!value;
});
var results = _.map(_.uniq(values), guard(guard.n(1), function (value) {
return getSubType(job, typeId, value);
}));
deferred.resolve(when.all(results));
} else {
deferred.resolve([]);
}
return deferred.promise;
};
module.exports = getSubTypes; | gpl-2.0 |
sunmoyi/ACM | ACM 2015/The Doors.cpp | 17607 | #include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
using namespace std;
#define PI acos(-1.0)
#define TWO_PI 2 * acos(-1.0)
const double eps = 1e-8;
double dcmp(double x) {
if (fabs(x) < eps) return 0; else return x < 0 ? -1 : 1;
}
struct Point {
double x, y;
Point(double x = 0, double y = 0) :x(x), y(y) { }
};
typedef Point Vector;
struct LineB {
Point a, b;
LineB(Point A, Point B) :a(A), b(B) {}
LineB() {}
};
Vector operator + (const Vector& A, const Vector& B) {
return Vector(A.x + B.x, A.y + B.y);
}
Vector operator - (const Point& A, const Point& B) {
return Vector(A.x - B.x, A.y - B.y);
}
Vector operator * (const Vector& A, double p) {
return Vector(A.x*p, A.y*p);
}
Vector operator / (const Vector& A, double p) {
return Vector(A.x / p, A.y / p);
}
double Dot(const Vector& A, const Vector& B) {
return A.x*B.x + A.y*B.y;
}
double Length(const Vector& A) {
return sqrt(Dot(A, A));
}
//ÏòÁ¿A, B¼Ð½Ç
double Angle(const Vector& A, const Vector& B) {
return acos(Dot(A, B) / Length(A) / Length(B));
}
//²æ³Ë
double Cross(const Vector& A, const Vector& B) {
return A.x*B.y - A.y*B.x;
}
//µã³Ë
bool operator < (const Point& p1, const Point& p2) {
return p1.x < p2.x || (p1.x == p2.x && p1.y < p2.y);
}
bool operator == (const Point& p1, const Point& p2) {
return p1.x == p2.x && p1.y == p2.y;
}
Vector Normal(Vector A) {
double L = Length(A);
return Vector(-A.y / L, A.x / L);
}
struct Line {
Point P;
Vector v;
double ang; // ¼«½Ç£¬¼´´ÓxÕý°ëÖáÐýתµ½ÏòÁ¿vËùÐèÒªµÄ½Ç£¨»¡¶È£©
Line() {}
Line(Point p, Vector v) :P(p), v(v) { ang = atan2(v.y, v.x); }
Point point(double t) {
return P + v*t;
}
Line move(double d) {
return Line(P + Normal(v)*d, v);
}
bool operator < (const Line& L) const {
return ang < L.ang;
}
};
//ÇóÖ±Ïß½»µã
Point GetLineIntersection(const Point& A, const Point& B, const Point& C, const Point& D) {
double a1 = A.y - B.y;
double b1 = B.x - A.x;
double c1 = A.x*B.y - B.x*A.y;
double a2 = C.y - D.y;
double b2 = D.x - C.x;
double c2 = C.x*D.y - D.x*C.y;
double x = (b1*c2 - b2*c1) / (a1*b2 - a2*b1);
double y = (a2*c1 - a1*c2) / (a1*b2 - a2*b1);
return Point(x, y);
}
//ÅжÏÏß¶ÎÏཻÓë·ñ
bool inter(LineB l1, LineB l2)
{
return
max(l1.a.x, l1.b.x) >= min(l2.a.x, l2.b.x) &&
max(l2.a.x, l2.b.x) >= min(l1.a.x, l1.b.x) &&
max(l1.a.y, l1.b.y) >= min(l2.a.y, l2.b.y) &&
max(l2.a.y, l2.b.y) >= min(l1.a.y, l1.b.y) &&
dcmp(Cross((l2.a - l1.a), (l1.b - l1.a)))* dcmp(Cross((l2.b - l1.a), (l1.b - l1.a))) <= 0 &&
dcmp(Cross((l1.a - l2.a), (l2.b - l2.a)))* dcmp(Cross((l1.b - l2.a), (l2.b - l2.a))) <= 0;
}
//µãÔÚÖ±ÏßÉϵÄͶӰ
Point GetLineProjection(Point P, Point A, Point B) {
Vector v = B - A;
return A + v*(Dot(v, P - A) / Dot(v, v));
}
//ÏòÁ¿A ÄæÊ±ÕëÐýתrad¶È
Vector Rotate(const Vector& A, double rad) {
return Vector(A.x*cos(rad) - A.y*sin(rad), A.x*sin(rad) + A.y*cos(rad));
}
//¹æ·¶Ïཻ
bool SegmentProperIntersection(const Point& a1, const Point& a2, const Point& b1, const Point& b2) {
double c1 = Cross(a2 - a1, b1 - a1), c2 = Cross(a2 - a1, b2 - a1),
c3 = Cross(b2 - b1, a1 - b1), c4 = Cross(b2 - b1, a2 - b1);
return dcmp(c1)*dcmp(c2)<0 && dcmp(c3)*dcmp(c4)<0;
}
bool OnSegment(const Point& p, const Point& a1, const Point& a2) {
return dcmp(Cross(a1 - p, a2 - p)) == 0 && dcmp(Dot(a1 - p, a2 - p)) < 0;
}
bool SegmentIntersects(Point a1, Point a2, Point b1, Point b2)
{
double c1 = Cross(a2 - a1, b1 - a1);
double c2 = Cross(a2 - a1, b2 - a1);
double c3 = Cross(b2 - b1, a1 - b1);
double c4 = Cross(b2 - b1, a2 - b1);
if (dcmp(c1)*dcmp(c2) == 0 && dcmp(c3)*dcmp(c4) == 0)
{
if (OnSegment(a1, b1, b2) || OnSegment(a2, b1, b2) || a1 == b1 || a2 == b1)
return true;
else
return false;
}
return dcmp(c1)*dcmp(c2) <= 0 && dcmp(c3)*dcmp(c4) <= 0;
}
//µãµ½Ö±ÏߵľàÀë
double DistanceToSegment(const Point& P, const Point& A, const Point& B) {
if (A == B) return Length(P - A);
Vector v1 = B - A, v2 = P - A, v3 = P - B;
if (dcmp(Dot(v1, v2)) < 0) return Length(v2);
else if (dcmp(Dot(v1, v3)) > 0) return Length(v3);
else return fabs(Cross(v1, v2)) / Length(v1); // Èç¹û²»È¡¾ø¶ÔÖµ£¬µÃµ½µÄÊÇÓÐÏò¾àÀë
}
// µã¼¯Í¹°ü
// Èç¹û²»Ï£ÍûÔÚ͹°üµÄ±ßÉÏÓÐÊäÈëµã£¬°ÑÁ½¸ö <= ¸Ä³É <
// Èç¹û²»½éÒâµã¼¯±»Ð޸ģ¬¿ÉÒԸijɴ«µÝÒýÓÃ
vector<Point> ConvexHull(vector<Point> p) {
// Ô¤´¦Àí£¬É¾³ýÖØ¸´µã
sort(p.begin(), p.end());
p.erase(unique(p.begin(), p.end()), p.end());
int n = p.size();
int m = 0;
vector<Point> ch(n + 1);
for (int i = 0; i < n; i++) {
while (m > 1 && Cross(ch[m - 1] - ch[m - 2], p[i] - ch[m - 2]) <= 0) m--;
ch[m++] = p[i];
}
int k = m;
for (int i = n - 2; i >= 0; i--) {
while (m > k && Cross(ch[m - 1] - ch[m - 2], p[i] - ch[m - 2]) <= 0) m--;
ch[m++] = p[i];
}
if (n > 1) m--;
ch.resize(m);
return ch;
}
//µãpÊÇ·ñÔÚ͹°üÄÚ²¿
int IsPointInPolygon(const Point& p, const vector<Point>& poly) {
int wn = 0;
int n = poly.size();
for (int i = 0; i < n; i++) {
const Point& p1 = poly[i];
const Point& p2 = poly[(i + 1) % n];
if (p1 == p || p2 == p || OnSegment(p, p1, p2)) return -1; // Ôڱ߽çÉÏ
int k = dcmp(Cross(p2 - p1, p - p1));
int d1 = dcmp(p1.y - p.y);
int d2 = dcmp(p2.y - p.y);
if (k > 0 && d1 <= 0 && d2 > 0) wn++;
if (k < 0 && d2 <= 0 && d1 > 0) wn--;
}
if (wn != 0) return 1; // ÄÚ²¿
return 0; // Íⲿ
}
//Á½¸ö͹°üÊÇ·ñÏཻ
bool ConvexPolygonDisjoint(const vector<Point> ch1, const vector<Point> ch2) {
int c1 = ch1.size();
int c2 = ch2.size();
for (int i = 0; i < c1; i++)
if (IsPointInPolygon(ch1[i], ch2) != 0) return false; // ÄÚ²¿»ò±ß½çÉÏ
for (int i = 0; i < c2; i++)
if (IsPointInPolygon(ch2[i], ch1) != 0) return false; // ÄÚ²¿»ò±ß½çÉÏ
for (int i = 0; i < c1; i++)
for (int j = 0; j < c2; j++)
if (SegmentProperIntersection(ch1[i], ch1[(i + 1) % c1], ch2[j], ch2[(j + 1) % c2])) return false;
return true;
}
// ¶à±ßÐεÄÓÐÏòÃæ»ý
double PolygonArea(vector<Point> p) {
double area = 0;
int n = p.size();
for (int i = 1; i < n - 1; i++)
area += Cross(p[i] - p[0], p[i + 1] - p[0]);
return area / 2;
}
int Dist2(const Point& A, const Point& B) {
return (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y);
}
// ·µ»Øµã¼¯Ö±¾¶µÄƽ·½
int diameter2(vector<Point>& points) {
vector<Point> p = ConvexHull(points);
int n = p.size();
if (n == 1) return 0;
if (n == 2) return Dist2(p[0], p[1]);
p.push_back(p[0]); // ÃâµÃȡģ
int ans = 0;
for (int u = 0, v = 1; u < n; u++) {
// Ò»ÌõÖ±ÏßÌùס±ßp[u]-p[u+1]
for (;;) {
// µ±Area(p[u], p[u+1], p[v+1]) <= Area(p[u], p[u+1], p[v])ʱֹͣÐýת
// ¼´Cross(p[u+1]-p[u], p[v+1]-p[u]) - Cross(p[u+1]-p[u], p[v]-p[u]) <= 0
// ¸ù¾ÝCross(A,B) - Cross(A,C) = Cross(A,B-C)
// »¯¼òµÃCross(p[u+1]-p[u], p[v+1]-p[v]) <= 0
int diff = Cross(p[u + 1] - p[u], p[v + 1] - p[v]);
if (diff <= 0) {
ans = max(ans, Dist2(p[u], p[v])); // uºÍvÊǶÔõàµã
if (diff == 0) ans = max(ans, Dist2(p[u], p[v + 1])); // diff == 0ʱuºÍv+1Ò²ÊǶÔõàµã
break;
}
v = (v + 1) % n;
}
}
return ans;
}
// ¹ýÁ½µãp1, p2µÄÖ±ÏßÒ»°ã·½³Ìax+by+c=0
// (x2-x1)(y-y1) = (y2-y1)(x-x1)
//µãµ½Ö±ÏߵľàÀëfabs(a*x + b*y + c) / sqrt(a*a + b*b)
void getLineGeneralEquation(const Point& p1, const Point& p2, double& a, double& b, double &c) {
a = p2.y - p1.y;
b = p1.x - p2.x;
c = -a*p1.x - b*p1.y;
}
/********************************************************************************************/
bool iszero(double x)
{
return fabs(x) < eps;
}
double Crossleft(Point A, Point B, Point C)
{
return (B.x - A.x) * (C.y - A.y) - (B.y - A.y)*(C.x - A.x);
}
//µãp1Ôٵ㼯pÄÚ
int InPolygon(Point p1, int n, Point *p)
{
const int offset = 1000;
int cnt, i = 0;
Point p2;
p[n] = p[0];
while (i < n)
{
p2.x = rand() + offset;
p2.y = rand() + offset;
for (i = cnt = 0; i < n; i++)
{
if (iszero(Crossleft(p1, p[i], p[i + 1])) &&
(p[i].x - p1.x) * (p[i + 1].x - p1.x) < eps &&
(p[i].y - p1.y) * (p[i + 1].y - p1.y) < eps)
return true;
else if (iszero(Crossleft(p1, p2, p[i])))
break;
else if (Crossleft(p[i], p[i + 1], p1) * Crossleft(p[i], p2, p[i + 1]) > eps &&
Crossleft(p1, p2, p[i + 1]) * Crossleft(p1, p[i], p2) > eps)
cnt++;
}
}
return cnt & 1;
}
/**********************************************************************************************/
double angle(Vector v)
{
return atan2(v.y, v.x);
}
struct Circle {
Point c;
double r;
Circle(Point c, double r) :c(c), r(r) {}
Point point(double a) {
return Point(c.x + cos(a)*r, c.y + sin(a)*r);
}
};
//Ö±ÏßLºÍÔ²CµÄ¹ØÏµt1ºÍt2±íʾÇеãµÄλÖÃ
int getLineCircleIntersection(Line L, Circle C, double& t1, double& t2, vector<Point>& sol)
{
double a = L.v.x, b = L.P.x - C.c.x, c = L.v.y, d = L.P.y - C.c.y;
double e = a*a + c*c, f = 2 * (a*b + c*d), g = b*b + d*d - C.r*C.r;
double delta = f*f - 4 * e*g; // Åбðʽ
if (dcmp(delta) < 0)
return 0; // ÏàÀë
if (dcmp(delta) == 0)
{ // ÏàÇÐ
t1 = t2 = -f / (2 * e);
sol.push_back(L.point(t1));
return 1;
}
// Ïཻ
t1 = (-f - sqrt(delta)) / (2 * e);
sol.push_back(L.point(t1));
t2 = (-f + sqrt(delta)) / (2 * e);
sol.push_back(L.point(t2));
return 2;
}
//ÇóÔ²c1 & c2 µÄ½»µã²åÈëµ½sol vector ÖÐ ×¢ÒâÕâ¸övector²»ÇåÁ㣬 º¯Êý·µ»ØÖµn´ú±íǰn¸öÊÇ´ð°¸
int getCircleCircleIntersection(Circle C1, Circle C2, vector<Point>& sol) {
double d = Length(C1.c - C2.c);
if (dcmp(d) == 0)
{
if (dcmp(C1.r - C2.r) == 0)
return -1; // ÖØºÏ£¬ÎÞÇî¶à½»µã
return 0;
}
if (dcmp(C1.r + C2.r - d) < 0)
return 0;
if (dcmp(fabs(C1.r - C2.r) - d) > 0)
return 0;
double a = angle(C2.c - C1.c);
double da = acos((C1.r*C1.r + d*d - C2.r*C2.r) / (2 * C1.r*d));
Point p1 = C1.point(a - da), p2 = C1.point(a + da);
sol.push_back(p1);
if (p1 == p2)
return 1;
sol.push_back(p2);
return 2;
}
double NormalizeAngle(double rad, double center = PI) {
return rad - TWO_PI * floor((rad + PI - center) / TWO_PI);
}
// ½»µãÏà¶ÔÓÚÔ²1µÄ¼«½Ç±£´æÔÚradÖÐ
void getCircleCircleIntersection(Point c1, double r1, Point c2, double r2, vector<double>& rad) {
double d = Length(c1 - c2);
if (dcmp(d) == 0) return; // ²»¹ÜÊÇÄÚº¬»¹ÊÇÖØºÏ£¬¶¼²»Ïཻ
if (dcmp(r1 + r2 - d) < 0) return;
if (dcmp(fabs(r1 - r2) - d) > 0) return;
double a = angle(c2 - c1);
double da = acos((r1*r1 + d*d - r2*r2) / (2 * r1*d));
rad.push_back(NormalizeAngle(a - da));
rad.push_back(NormalizeAngle(a + da));
}
//ÇóÈý½ÇÐÎÍâ½ÓÔ²
Circle CircumscribedCircle(Point p1, Point p2, Point p3) {
double Bx = p2.x - p1.x, By = p2.y - p1.y;
double Cx = p3.x - p1.x, Cy = p3.y - p1.y;
double D = 2 * (Bx*Cy - By*Cx);
double cx = (Cy*(Bx*Bx + By*By) - By*(Cx*Cx + Cy*Cy)) / D + p1.x;
double cy = (Bx*(Cx*Cx + Cy*Cy) - Cx*(Bx*Bx + By*By)) / D + p1.y;
Point p = Point(cx, cy);
return Circle(p, Length(p1 - p));
}
//ÇóÈý½ÇÐÎÄÚ½ÓÔ²
Circle InscribedCircle(Point p1, Point p2, Point p3) {
double a = Length(p2 - p3);
double b = Length(p3 - p1);
double c = Length(p1 - p2);
Point p = (p1*a + p2*b + p3*c) / (a + b + c);
return Circle(p, DistanceToSegment(p, p1, p2));
}
//¸ø³öÔ²µÄÔ²ÐÄPoint(xc, yc), °ë¾¶r Çó¹ýµã(xp, yp)µÄËùÓÐÇÐÏß
// ¹ýµãpµ½Ô²CµÄÇÐÏß¡£v[i]ÊǵÚiÌõÇÐÏßµÄÏòÁ¿¡£·µ»ØÇÐÏßÌõÊý
int getTangents(Point p, Circle C, Vector* v) {
Vector u = C.c - p;
double dist = Length(u);
if (dist < C.r)
return 0;
else if (dcmp(dist - C.r) == 0)
{ // pÔÚÔ²ÉÏ£¬Ö»ÓÐÒ»ÌõÇÐÏß
v[0] = Rotate(u, PI / 2);
return 1;
}
else
{
double ang = asin(C.r / dist);
v[0] = Rotate(u, -ang);
v[1] = Rotate(u, +ang);
return 2;
}
}
Point GetLineIntersection(const Line& a, const Line& b) {
Vector u = a.P - b.P;
double t = Cross(b.v, u) / Cross(a.v, b.v);
return a.P + a.v*t;
}
//Çó¹ýµã(xp, yp)°ë¾¶Îªr ²¢ÇÒÓëµã(x1, y1)&&µã(x2, y2)Ëù¹¹³ÉµÄÖ±ÏßÏàÇеÄÔ°
vector<Point> CircleThroughPointTangentToLineGivenRadius(Point p, Line L, double r)
{
vector<Point> ans;
double t1, t2;
getLineCircleIntersection(L.move(-r), Circle(p, r), t1, t2, ans);
getLineCircleIntersection(L.move(r), Circle(p, r), t1, t2, ans);
return ans;
}
//ÇóÓëÖ±Ïߣ¨(x1,y1),(x2,y2)£©ºÍÖ±Ïߣ¨(x3, y3),(x4, y4)£©ÏàÇÐ ÇҰ뾶ΪrµÄÔ²
vector<Point> CircleTangentToLinesGivenRadius(Line a, Line b, double r)
{
vector<Point> ans;
Line L1 = a.move(-r), L2 = a.move(r);
Line L3 = b.move(-r), L4 = b.move(r);
ans.push_back(GetLineIntersection(L1, L3));
ans.push_back(GetLineIntersection(L1, L4));
ans.push_back(GetLineIntersection(L2, L3));
ans.push_back(GetLineIntersection(L2, L4));
return ans;
}
//¸ø¶¨Ô²£¨(x1,y1),r1£©ºÍÔ²£¨(x2,y2), r2£©ÇóÓëÉÏÊöÁ½Ô²ÏàÍâÇв¢ÇҰ뾶ΪrµÄÔ²
vector<Point> CircleTangentToTwoDisjointCirclesWithRadius(Circle c1, Circle c2, double r) {
vector<Point> ans;
Vector v = c2.c - c1.c;
double dist = Length(v);
int d = dcmp(dist - c1.r - c2.r - r * 2);
if (d > 0)
return ans;
getCircleCircleIntersection(Circle(c1.c, c1.r + r), Circle(c2.c, c2.r + r), ans);
return ans;
}
// µãpÔÚÓÐÏòÖ±ÏßLµÄ×ó±ß£¨ÏßÉϲ»Ë㣩
bool OnLeft(const Line& L, const Point& p) {
return Cross(L.v, p - L.P) > 0;
}
// ¶þÖ±Ïß½»µã£¬¼Ù¶¨½»µãΩһ´æÔÚ
const double INF = 1e8;
// °ëÆ½Ãæ½»Ö÷¹ý³Ì
vector<Point> HalfplaneIntersection(vector<Line> L) {
int n = L.size();
sort(L.begin(), L.end()); // °´¼«½ÇÅÅÐò
int first, last; // Ë«¶Ë¶ÓÁеĵÚÒ»¸öÔªËØºÍ×îºóÒ»¸öÔªËØµÄϱê
vector<Point> p(n); // p[i]Ϊq[i]ºÍq[i+1]µÄ½»µã
vector<Line> q(n); // Ë«¶Ë¶ÓÁÐ
vector<Point> ans; // ½á¹û
q[first = last = 0] = L[0]; // Ë«¶Ë¶ÓÁгõʼ»¯ÎªÖ»ÓÐÒ»¸ö°ëÆ½ÃæL[0]
for (int i = 1; i < n; i++) {
while (first < last && !OnLeft(L[i], p[last - 1])) last--;
while (first < last && !OnLeft(L[i], p[first])) first++;
q[++last] = L[i];
if (fabs(Cross(q[last].v, q[last - 1].v)) < eps) { // Á½ÏòÁ¿Æ½ÐÐÇÒͬÏò£¬È¡ÄÚ²àµÄÒ»¸ö
last--;
if (OnLeft(q[last], L[i].P)) q[last] = L[i];
}
if (first < last) p[last - 1] = GetLineIntersection(q[last - 1], q[last]);
}
while (first < last && !OnLeft(q[first], p[last - 1])) last--; // ɾ³ýÎÞÓÃÆ½Ãæ
if (last - first <= 1) return ans; // ¿Õ¼¯
p[last] = GetLineIntersection(q[last], q[first]); // ¼ÆËãÊ×βÁ½¸ö°ëÆ½ÃæµÄ½»µã
// ´Ódeque¸´ÖƵ½Êä³öÖÐ
for (int i = first; i <= last; i++) ans.push_back(p[i]);
return ans;
}
LineB line[110];
int n;
/********************************************************************************************/
double Multi(Point p1, Point p2, Point p0) {
return (p1.x - p0.x) * (p2.y - p0.y) - (p1.y - p0.y) * (p2.x - p0.x);
}
bool Check(LineB B) {
if (fabs(B.a.x - B.b.x) < eps && fabs(B.a.y - B.b.y) < eps) return false;
for (int i = 0; i < n; i++)
if (Multi(line[i].a, B.b, B.a) * Multi(line[i].b, B.b, B.a) > eps) return false;
return true;
}
/*******************************************************************************************/
#define maxn 110
double dis[maxn][maxn];
#define INF 1e20
int main(void)
{
int n;
double x, y1, y2, y3, y4;
while (scanf("%d", &n) != EOF && n != -1)
{
for (int i = 1; i <= n; i++)
{
scanf("%lf %lf %lf %lf %lf", &x, &y1, &y2, &y3, &y4);
line[2 * i - 1] = LineB(Point(x, y1), Point(x, y2));
line[2 * i] = LineB(Point(x, y3), Point(x, y4));
}
for (int i = 0; i <= 4 * n + 1; i++)
{
for (int j = 0; j <= 4 * n + 1; j++)
{
if (i == j)
dis[i][j] = 0;
else
dis[i][j] = INF;
}
}
for (int i = 1; i <= 4 * n; i++)
{
int lid = (i + 3) / 4;
bool flag = true;
Point tmp;
if (i & 1)
tmp = line[(i + 1) / 2].a;
else
tmp = line[(i + 1) / 2].b;
for (int j = 1; j < lid; j++)
if (inter(line[2 * j - 1], LineB(Point(0, 5), tmp)) == false
&& inter(line[2 * j], LineB(Point(0, 5), tmp)) == false)
flag = false;
if (flag)
dis[0][i] = dis[i][0] = Length(Point(0, 5) - tmp);
flag = true;
for (int j = lid + 1; j <= n; j++)
if (inter(line[2 * j - 1], LineB(Point(10, 5), tmp)) == false
&& inter(line[2 * j], LineB(Point(10, 5), tmp)) == false)
flag = false;
if (flag)
dis[i][4 * n + 1] = dis[4 * n + 1][i] = Length(Point(10, 5) - tmp);
}
for (int i = 1; i <= 4 * n; i++)
{
for (int j = i + 1; j <= 4 * n; j++)
{
int lid1 = (i + 3) / 4;
int lid2 = (j + 3) / 4;
bool flag = true;
Point p1, p2;
if (i & 1)
p1 = line[(i + 1) / 2].a;
else
p1 = line[(i + 1) / 2].b;
if (j & 1)
p2 = line[(j + 1) / 2].a;
else
p2 = line[(j + 1) / 2].b;
for (int k = lid1 + 1; k < lid2; k++)
{
if (inter(line[2 * k - 1], LineB(p1, p2)) == false
&& inter(line[2 * k], LineB(p1, p2)) == false)
flag = false;
}
if (flag)
dis[i][j] = dis[j][i] = Length(p1 - p2);
}
}
bool flag = true;
for (int i = 1; i <= n; i++)
{
if (inter(line[(2 * i) - 1], LineB(Point(0, 5), Point(10, 5))) == false &&
inter(line[2 * i], LineB(Point(0, 5), Point(10, 5))) == false)
flag = false;
}
if (flag)
dis[0][4 * n + 1] = dis[4 * n + 1][0] = 10;
for (int k = 0; k <= 4 * n + 1; k++)
for (int i = 0; i <= 4 * n + 1; i++)
for (int j = 0; j <= 4 * n + 1; j++)
if (dis[i][k] + dis[k][j] < dis[i][j])
dis[i][j] = dis[i][k] + dis[k][j];
printf("%.2lf\n", dis[0][4 * n + 1]);
}
return 0;
} | gpl-2.0 |
ValkyrieUK/habitatSMP-Forum | app/assets/javascripts/discourse/views/header_view.js | 4522 | /**
This view handles rendering of the header of the site
@class HeaderView
@extends Discourse.View
@namespace Discourse
@module Discourse
**/
Discourse.HeaderView = Discourse.View.extend({
tagName: 'header',
classNames: ['d-header', 'clearfix'],
classNameBindings: ['editingTopic'],
templateName: 'header',
showDropdown: function($target) {
var elementId = $target.data('dropdown') || $target.data('notifications'),
$dropdown = $("#" + elementId),
$li = $target.closest('li'),
$ul = $target.closest('ul'),
$html = $('html'),
self = this;
var controller = self.get('controller');
if(controller && !controller.isDestroyed){
controller.set('visibleDropdown', elementId);
}
// we need to ensure we are rendered,
// this optimises the speed of the initial render
var render = $target.data('render');
if(render){
if(!this.get(render)){
this.set(render, true);
Em.run.next(this, function(){
this.showDropdown.apply(self, [$target]);
});
return;
}
}
var hideDropdown = function() {
$dropdown.fadeOut('fast');
$li.removeClass('active');
$html.data('hide-dropdown', null);
var controller = self.get('controller');
if(controller && !controller.isDestroyed){
controller.set('visibleDropdown', null);
}
return $html.off('click.d-dropdown');
};
// if a dropdown is active and the user clicks on it, close it
if($li.hasClass('active')) { return hideDropdown(); }
// otherwhise, mark it as active
$li.addClass('active');
// hide the other dropdowns
$('li', $ul).not($li).removeClass('active');
$('.d-dropdown').not($dropdown).fadeOut('fast');
// fade it fast
$dropdown.fadeIn('fast');
// autofocus any text input field
$dropdown.find('input[type=text]').focus().select();
$html.on('click.d-dropdown', function(e) {
return $(e.target).closest('.d-dropdown').length > 0 ? true : hideDropdown.apply(self);
});
$html.data('hide-dropdown', hideDropdown);
return false;
},
showDropdownBySelector: function(selector) {
this.showDropdown($(selector));
},
showNotifications: function() {
this.get("controller").send("showNotifications", this);
},
examineDockHeader: function() {
var headerView = this;
// Check the dock after the current run loop. While rendering,
// it's much slower to calculate `outlet.offset()`
Em.run.next(function () {
if (!headerView.docAt) {
var outlet = $('#main-outlet');
if (!(outlet && outlet.length === 1)) return;
headerView.docAt = outlet.offset().top;
}
var offset = window.pageYOffset || $('html').scrollTop();
if (offset >= headerView.docAt) {
if (!headerView.dockedHeader) {
$('body').addClass('docked');
headerView.dockedHeader = true;
}
} else {
if (headerView.dockedHeader) {
$('body').removeClass('docked');
headerView.dockedHeader = false;
}
}
});
},
willDestroyElement: function() {
$(window).unbind('scroll.discourse-dock');
$(document).unbind('touchmove.discourse-dock');
this.$('a.unread-private-messages, a.unread-notifications, a[data-notifications]').off('click.notifications');
this.$('a[data-dropdown]').off('click.dropdown');
},
didInsertElement: function() {
var self = this;
this.$('a[data-dropdown]').on('click.dropdown', function(e) {
self.showDropdown.apply(self, [$(e.currentTarget)]);
return false;
});
this.$('a.unread-private-messages, a.unread-notifications, a[data-notifications]').on('click.notifications', function(e) {
self.showNotifications(e);
return false;
});
$(window).bind('scroll.discourse-dock', function() {
self.examineDockHeader();
});
$(document).bind('touchmove.discourse-dock', function() {
self.examineDockHeader();
});
self.examineDockHeader();
// Delegate ESC to the composer
$('body').on('keydown.header', function(e) {
// Hide dropdowns
if (e.which === 27) {
self.$('li').removeClass('active');
self.$('.d-dropdown').fadeOut('fast');
}
if (self.get('editingTopic')) {
if (e.which === 13) {
self.finishedEdit();
}
if (e.which === 27) {
return self.cancelEdit();
}
}
});
}
});
| gpl-2.0 |
evernote/pootle | tests/fixtures/models/user.py | 2023 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2014 Evernote Corporation
#
# This file is part of Pootle.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
import pytest
def _require_user(username, fullname, password=None,
is_superuser=False, is_staff=False):
"""Helper to get/create a new user."""
from django.contrib.auth import get_user_model
User = get_user_model()
criteria = {
'username': username,
'full_name': fullname,
'is_active': True,
'is_superuser': is_superuser,
}
user, created = User.objects.get_or_create(**criteria)
if created:
if password is None:
user.set_unusable_password()
else:
user.set_password(password)
user.save()
return user
@pytest.fixture
def nobody(db):
"""Require the default anonymous user."""
return _require_user('nobody', 'any anonymous user')
@pytest.fixture
def default(db):
"""Require the default authenticated user."""
return _require_user('default', 'any authenticated user',
password='')
@pytest.fixture
def system(db):
"""Require the system user."""
return _require_user('system', 'system user')
@pytest.fixture
def admin(db):
"""Require the admin user."""
return _require_user('admin', 'Administrator', password='admin',
is_superuser=True, is_staff=True)
| gpl-2.0 |
sufism/qucs_chs | qucs-core/src/vector.cpp | 31021 | /*
* vector.cpp - vector class implementation
*
* Copyright (C) 2003, 2004, 2005, 2006, 2007 Stefan Jahn <stefan@lkcc.org>
* Copyright (C) 2006, 2007 Gunther Kraut <gn.kraut@t-online.de>
*
* This 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, or (at your option)
* any later version.
*
* This software 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 package; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
* Boston, MA 02110-1301, USA.
*
* $Id$
*
*/
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <assert.h>
#include "complex.h"
#include "object.h"
#include "logging.h"
#include "strlist.h"
#include "vector.h"
#include "consts.h"
// Constructor creates an unnamed instance of the vector class.
vector::vector () : object () {
capacity = size = 0;
data = NULL;
dependencies = NULL;
origin = NULL;
requested = 0;
}
/* Constructor creates an unnamed instance of the vector class with a
given initial size. */
vector::vector (int s) : object () {
assert (s >= 0);
capacity = size = s;
data = s > 0 ? (nr_complex_t *)
calloc (capacity, sizeof (nr_complex_t)) : NULL;
dependencies = NULL;
origin = NULL;
requested = 0;
}
/* Constructor creates an unnamed instance of the vector class with a
given initial size and content. */
vector::vector (int s, nr_complex_t val) : object () {
assert (s >= 0);
capacity = size = s;
data = s > 0 ? (nr_complex_t *)
calloc (capacity, sizeof (nr_complex_t)) : NULL;
for (int i = 0; i < s; i++) data[i] = val;
dependencies = NULL;
origin = NULL;
requested = 0;
}
// Constructor creates an named instance of the vector class.
vector::vector (const char * n) : object (n) {
capacity = size = 0;
data = NULL;
dependencies = NULL;
origin = NULL;
requested = 0;
}
/* This constructor creates a named instance of the vector class with
a given initial size. */
vector::vector (const char * n, int s) : object (n) {
assert (s >= 0);
capacity = size = s;
data = s > 0 ? (nr_complex_t *)
calloc (capacity, sizeof (nr_complex_t)) : NULL;
dependencies = NULL;
origin = NULL;
requested = 0;
}
/* The copy constructor creates a new instance based on the given
vector object. */
vector::vector (const vector & v) : object (v) {
size = v.size;
capacity = v.capacity;
data = (nr_complex_t *) malloc (sizeof (nr_complex_t) * capacity);
memcpy (data, v.data, sizeof (nr_complex_t) * size);
dependencies = v.dependencies ? new strlist (*v.dependencies) : NULL;
origin = v.origin ? strdup (v.origin) : NULL;
requested = v.requested;
}
/* The assignment copy constructor creates a new instance based on the
given vector object. It copies the data only and leaves any other
properties untouched. */
const vector& vector::operator=(const vector & v) {
if (&v != this) {
size = v.size;
capacity = v.capacity;
if (data) { free (data); data = NULL; }
if (capacity > 0) {
data = (nr_complex_t *) malloc (sizeof (nr_complex_t) * capacity);
if (size > 0) memcpy (data, v.data, sizeof (nr_complex_t) * size);
}
}
return *this;
}
// Destructor deletes a vector object.
vector::~vector () {
if (data) free (data);
if (dependencies) delete dependencies;
if (origin) free (origin);
}
// Returns data dependencies.
strlist * vector::getDependencies (void) {
return dependencies;
}
// Sets the data dependencies.
void vector::setDependencies (strlist * s) {
if (dependencies) delete dependencies;
dependencies = s;
}
/* The function appends a new complex data item to the end of the
vector and ensures that the vector can hold the increasing number
of data items. */
void vector::add (nr_complex_t c) {
if (data == NULL) {
size = 0; capacity = 64;
data = (nr_complex_t *) malloc (sizeof (nr_complex_t) * capacity);
}
else if (size >= capacity) {
capacity *= 2;
data = (nr_complex_t *) realloc (data, sizeof (nr_complex_t) * capacity);
}
data[size++] = c;
}
/* This function appends the given vector to the vector. */
void vector::add (vector * v) {
if (v != NULL) {
if (data == NULL) {
size = 0; capacity = v->getSize ();
data = (nr_complex_t *) malloc (sizeof (nr_complex_t) * capacity);
}
else if (size + v->getSize () > capacity) {
capacity += v->getSize ();
data = (nr_complex_t *) realloc (data, sizeof (nr_complex_t) * capacity);
}
for (int i = 0; i < v->getSize (); i++) data[size++] = v->get (i);
}
}
// Returns the complex data item at the given position.
nr_complex_t vector::get (int i) {
return data[i];
}
void vector::set (nr_double_t d, int i) {
data[i] = nr_complex_t (d);
}
void vector::set (const nr_complex_t z, int i) {
data[i] = nr_complex_t (z);
}
// The function returns the current size of the vector.
int vector::getSize (void) {
return size;
}
int vector::checkSizes (vector v1, vector v2) {
if (v1.getSize () != v2.getSize ()) {
logprint (LOG_ERROR, "vector '%s' and '%s' have different sizes\n",
v1.getName (), v2.getName ());
return 0;
}
return 1;
}
// searches the maximum value of the vector elements.
// complex numbers in the 1. and 4. quadrant are counted as "abs(c)".
// complex numbers in the 2. and 3. quadrant are counted as "-abs(c)".
nr_double_t vector::maximum (void) {
nr_complex_t c;
nr_double_t d, max_D = -NR_MAX;
for (int i = 0; i < getSize (); i++) {
c = data[i];
d = fabs (arg (c)) < M_PI_2 ? abs (c) : -abs (c);
if (d > max_D) max_D = d;
}
return max_D;
}
// searches the minimum value of the vector elements.
// complex numbers in the 1. and 4. quadrant are counted as "abs(c)".
// complex numbers in the 2. and 3. quadrant are counted as "-abs(c)".
nr_double_t vector::minimum (void) {
nr_complex_t c;
nr_double_t d, min_D = +NR_MAX;
for (int i = 0; i < getSize (); i++) {
c = data[i];
d = fabs (arg (c)) < M_PI_2 ? abs (c) : -abs (c);
if (d < min_D) min_D = d;
}
return min_D;
}
/* Unwraps a phase vector in radians. Adds +/- 2*Pi if consecutive
values jump about |Pi|. */
vector unwrap (vector v, nr_double_t tol, nr_double_t step) {
vector result (v.getSize ());
nr_double_t add = 0;
result (0) = v (0);
for (int i = 1; i < v.getSize (); i++) {
nr_double_t diff = real (v (i) - v (i-1));
if (diff > +tol) {
add -= step;
} else if (diff < -tol) {
add += step;
}
result (i) = v (i) + add;
}
return result;
}
nr_complex_t sum (vector v) {
nr_complex_t result (0.0);
for (int i = 0; i < v.getSize (); i++) result += v.get (i);
return result;
}
nr_complex_t prod (vector v) {
nr_complex_t result (1.0);
for (int i = 0; i < v.getSize (); i++) result *= v.get (i);
return result;
}
nr_complex_t avg (vector v) {
nr_complex_t result (0.0);
for (int i = 0; i < v.getSize (); i++) result += v.get (i);
return result / (nr_double_t) v.getSize ();
}
vector signum (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (signum (v.get (i)), i);
return result;
}
vector sign (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (sign (v.get (i)), i);
return result;
}
vector xhypot (vector v, const nr_complex_t z) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (xhypot (v.get(i), z), i);
return result;
}
vector xhypot (vector v, const nr_double_t d) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (xhypot (v.get(i), d), i);
return result;
}
vector xhypot (const nr_complex_t z, vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (xhypot (z, v.get (i)), i);
return result;
}
vector xhypot (const nr_double_t d, vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (xhypot (d, v.get (i)), i);
return result;
}
vector xhypot (vector v1, vector v2) {
int j, i, n, len, len1 = v1.getSize (), len2 = v2.getSize ();
if (len1 >= len2) {
assert (len1 % len2 == 0);
len = len1;
} else {
assert (len2 % len1 == 0);
len = len2;
}
vector res (len);
for (j = i = n = 0; n < len; n++) {
res (n) = xhypot (v1 (i), v2 (j));
if (++i >= len1) i = 0; if (++j >= len2) j = 0;
}
return res;
}
vector sinc (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (sinc (v.get (i)), i);
return result;
}
vector abs (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (abs (v.get (i)), i);
return result;
}
vector norm (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (norm (v.get (i)), i);
return result;
}
vector arg (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (arg (v.get (i)), i);
return result;
}
vector real (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (real (v.get (i)), i);
return result;
}
vector imag (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (imag (v.get (i)), i);
return result;
}
vector conj (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (conj (v.get (i)), i);
return result;
}
vector dB (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++)
result.set (10.0 * log10 (norm (v.get (i))), i);
return result;
}
vector sqrt (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (sqrt (v.get (i)), i);
return result;
}
vector exp (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (exp (v.get (i)), i);
return result;
}
vector limexp (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (limexp (v.get (i)), i);
return result;
}
vector log (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (log (v.get (i)), i);
return result;
}
vector log10 (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (log10 (v.get (i)), i);
return result;
}
vector log2 (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (log2 (v.get (i)), i);
return result;
}
vector pow (vector v, const nr_complex_t z) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (pow (v.get(i), z), i);
return result;
}
vector pow (vector v, const nr_double_t d) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (pow (v.get(i), d), i);
return result;
}
vector pow (const nr_complex_t z, vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (pow (z, v.get (i)), i);
return result;
}
vector pow (const nr_double_t d, vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (pow (d, v.get (i)), i);
return result;
}
vector pow (vector v1, vector v2) {
int j, i, n, len, len1 = v1.getSize (), len2 = v2.getSize ();
if (len1 >= len2) {
assert (len1 % len2 == 0);
len = len1;
} else {
assert (len2 % len1 == 0);
len = len2;
}
vector res (len);
for (j = i = n = 0; n < len; n++) {
res (n) = pow (v1 (i), v2 (j));
if (++i >= len1) i = 0; if (++j >= len2) j = 0;
}
return res;
}
vector sin (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (sin (v.get (i)), i);
return result;
}
vector asin (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (asin (v.get (i)), i);
return result;
}
vector acos (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (acos (v.get (i)), i);
return result;
}
vector cos (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (cos (v.get (i)), i);
return result;
}
vector tan (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (tan (v.get (i)), i);
return result;
}
vector atan (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (atan (v.get (i)), i);
return result;
}
vector cot (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (cot (v.get (i)), i);
return result;
}
vector acot (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (acot (v.get (i)), i);
return result;
}
vector sinh (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (sinh (v.get (i)), i);
return result;
}
vector asinh (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (asinh (v.get (i)), i);
return result;
}
vector cosh (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (cosh (v.get (i)), i);
return result;
}
vector acosh (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (acosh (v.get (i)), i);
return result;
}
vector asech (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (asech (v.get (i)), i);
return result;
}
vector tanh (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (tanh (v.get (i)), i);
return result;
}
vector atanh (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (atanh (v.get (i)), i);
return result;
}
vector coth (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (coth (v.get (i)), i);
return result;
}
vector acoth (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (acoth (v.get (i)), i);
return result;
}
// converts impedance to reflexion coefficient
vector ztor (vector v, nr_complex_t zref) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result (i) = ztor (v (i), zref);
return result;
}
// converts admittance to reflexion coefficient
vector ytor (vector v, nr_complex_t zref) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result (i) = ytor (v (i), zref);
return result;
}
// converts reflexion coefficient to impedance
vector rtoz (vector v, nr_complex_t zref) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result (i) = rtoz (v (i), zref);
return result;
}
// converts reflexion coefficient to admittance
vector rtoy (vector v, nr_complex_t zref) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result (i) = rtoy (v (i), zref);
return result;
}
// differentiates 'var' with respect to 'dep' exactly 'n' times
vector diff (vector var, vector dep, int n) {
int k, xi, yi, exchange = 0;
vector x, y;
// exchange dependent and independent variable if necessary
if (var.getSize () < dep.getSize ()) {
x = vector (var);
y = vector (dep);
exchange++;
}
else {
x = vector (dep);
y = vector (var);
}
assert (y.getSize () % x.getSize () == 0 && x.getSize () >= 2);
vector result (y);
nr_complex_t c;
for (k = 0; k < n; k++) { // differentiate n times
for (yi = xi = 0; yi < y.getSize (); yi++, xi++) {
if (xi == x.getSize ()) xi = 0; // roll through independent vector
if (xi == 0) {
c = (y.get (yi + 1) - y.get (yi)) / (x.get (xi + 1) - x.get (xi));
} else if (xi == x.getSize () - 1) {
c = (y.get (yi) - y.get (yi - 1)) / (x.get (xi) - x.get (xi - 1));
}
else {
c =
((y.get (yi) - y.get (yi - 1)) / (x.get (xi) - x.get (xi - 1)) +
(y.get (yi + 1) - y.get (yi)) / (x.get (xi + 1) - x.get (xi))) /
2.0;
}
result.set (exchange ? 1.0 / c : c, yi);
}
y = result;
}
return result;
}
vector vector::operator=(const nr_complex_t c) {
for (int i = 0; i < size; i++) data[i] = c;
return *this;
}
vector vector::operator=(const nr_double_t d) {
for (int i = 0; i < size; i++) data[i] = d;
return *this;
}
vector vector::operator+=(vector v) {
int i, n, len = v.getSize ();
assert (size % len == 0);
for (i = n = 0; i < size; i++) { data[i] += v (n); if (++n >= len) n = 0; }
return *this;
}
vector vector::operator+=(const nr_complex_t c) {
for (int i = 0; i < size; i++) data[i] += c;
return *this;
}
vector vector::operator+=(const nr_double_t d) {
for (int i = 0; i < size; i++) data[i] += d;
return *this;
}
vector operator+(vector v1, vector v2) {
int len1 = v1.getSize (), len2 = v2.getSize ();
vector result;
if (len1 >= len2) {
result = v1;
result += v2;
} else {
result = v2;
result += v1;
}
return result;
}
vector operator+(vector v, const nr_complex_t c) {
vector result (v);
result += c;
return result;
}
vector operator+(const nr_complex_t c, vector v) {
return v + c;
}
vector operator+(vector v, const nr_double_t d) {
vector result (v);
result += d;
return result;
}
vector operator+(const nr_double_t d, vector v) {
return v + d;
}
vector vector::operator-() {
vector result (size);
for (int i = 0; i < size; i++) result (i) = -data[i];
return result;
}
vector vector::operator-=(vector v) {
int i, n, len = v.getSize ();
assert (size % len == 0);
for (i = n = 0; i < size; i++) { data[i] -= v (n); if (++n >= len) n = 0; }
return *this;
}
vector vector::operator-=(const nr_complex_t c) {
for (int i = 0; i < size; i++) data[i] -= c;
return *this;
}
vector vector::operator-=(const nr_double_t d) {
for (int i = 0; i < size; i++) data[i] -= d;
return *this;
}
vector operator-(vector v1, vector v2) {
int len1 = v1.getSize (), len2 = v2.getSize ();
vector result;
if (len1 >= len2) {
result = v1;
result -= v2;
} else {
result = -v2;
result += v1;
}
return result;
}
vector operator-(vector v, const nr_complex_t c) {
vector result (v);
result -= c;
return result;
}
vector operator-(vector v, const nr_double_t d) {
vector result (v);
result -= d;
return result;
}
vector operator-(const nr_complex_t c, vector v) {
vector result (-v);
result += c;
return result;
}
vector operator-(const nr_double_t d, vector v) {
vector result (-v);
result += d;
return result;
}
vector vector::operator*=(vector v) {
int i, n, len = v.getSize ();
assert (size % len == 0);
for (i = n = 0; i < size; i++) { data[i] *= v (n); if (++n >= len) n = 0; }
return *this;
}
vector vector::operator*=(const nr_complex_t c) {
for (int i = 0; i < size; i++) data[i] *= c;
return *this;
}
vector vector::operator*=(const nr_double_t d) {
for (int i = 0; i < size; i++) data[i] *= d;
return *this;
}
vector operator*(vector v1, vector v2) {
int len1 = v1.getSize (), len2 = v2.getSize ();
vector result;
if (len1 >= len2) {
result = v1;
result *= v2;
} else {
result = v2;
result *= v1;
}
return result;
}
vector operator*(vector v, const nr_complex_t c) {
vector result (v);
result *= c;
return result;
}
vector operator*(vector v, const nr_double_t d) {
vector result (v);
result *= d;
return result;
}
vector operator*(const nr_complex_t c, vector v) {
return v * c;
}
vector operator*(const nr_double_t d, vector v) {
return v * d;
}
vector vector::operator/=(vector v) {
int i, n, len = v.getSize ();
assert (size % len == 0);
for (i = n = 0; i < size; i++) { data[i] /= v (n); if (++n >= len) n = 0; }
return *this;
}
vector vector::operator/=(const nr_complex_t c) {
for (int i = 0; i < size; i++) data[i] /= c;
return *this;
}
vector vector::operator/=(const nr_double_t d) {
for (int i = 0; i < size; i++) data[i] /= d;
return *this;
}
vector operator/(vector v1, vector v2) {
int len1 = v1.getSize (), len2 = v2.getSize ();
vector result;
if (len1 >= len2) {
assert (len1 % len2 == 0);
result = v1;
result /= v2;
} else {
assert (len2 % len1 == 0);
result = 1 / v2;
result *= v1;
}
return result;
}
vector operator/(vector v, const nr_complex_t c) {
vector result (v);
result /= c;
return result;
}
vector operator/(vector v, const nr_double_t d) {
vector result (v);
result /= d;
return result;
}
vector operator/(const nr_complex_t c, vector v) {
vector result (v);
result = c;
result /= v;
return result;
}
vector operator/(const nr_double_t d, vector v) {
vector result (v);
result = d;
result /= v;
return result;
}
vector operator%(vector v, const nr_complex_t z) {
int len = v.getSize ();
vector result (len);
for (int i = 0; i < len; i++) result (i) = v (i) % z;
return result;
}
vector operator%(vector v, const nr_double_t d) {
int len = v.getSize ();
vector result (len);
for (int i = 0; i < len; i++) result (i) = v (i) % d;
return result;
}
vector operator%(const nr_complex_t z, vector v) {
int len = v.getSize ();
vector result (len);
for (int i = 0; i < len; i++) result (i) = z % v (i);
return result;
}
vector operator%(const nr_double_t d, vector v) {
int len = v.getSize ();
vector result (len);
for (int i = 0; i < len; i++) result (i) = d % v (i);
return result;
}
vector operator%(vector v1, vector v2) {
int j, i, n, len, len1 = v1.getSize (), len2 = v2.getSize ();
if (len1 >= len2) {
assert (len1 % len2 == 0);
len = len1;
} else {
assert (len2 % len1 == 0);
len = len2;
}
vector res (len);
for (j = i = n = 0; n < len; n++) {
res (n) = v1 (i) % v2 (j);
if (++i >= len1) i = 0; if (++j >= len2) j = 0;
}
return res;
}
/* This function reverses the order of the data list. */
void vector::reverse (void) {
nr_complex_t * buffer = (nr_complex_t *)
malloc (sizeof (nr_complex_t) * size);
for (int i = 0; i < size; i++) buffer[i] = data[size - 1 - i];
free (data);
data = buffer;
capacity = size;
}
// Sets the origin (the analysis) of the vector.
void vector::setOrigin (char * n) {
if (origin) free (origin);
origin = n ? strdup (n) : NULL;
}
// Returns the origin (the analysis) of the vector.
char * vector::getOrigin (void) {
return origin;
}
/* The function returns the number of entries with the given value
deviating no more than the given epsilon. */
int vector::contains (nr_complex_t val, nr_double_t eps) {
int count = 0;
for (int i = 0; i < size; i++) {
if (abs (data[i] - val) <= eps) count++;
}
return count;
}
// Sorts the vector either in ascending or descending order.
void vector::sort (bool ascending) {
nr_complex_t t;
for (int i = 0; i < size; i++) {
for (int n = 0; n < size - 1; n++) {
if (ascending ? data[n] > data[n+1] : data[n] < data[n+1]) {
t = data[n];
data[n] = data[n+1];
data[n+1] = t;
}
}
}
}
/* The function creates a linear stepped vector of values starting at
the given start value, ending with the given stop value and
containing points elements. */
vector linspace (nr_double_t start, nr_double_t stop, int points) {
vector result (points);
nr_double_t val, step = (stop - start) / (points - 1);
for (int i = 0; i < points; i++) {
val = start + (i * step);
if (i != 0 && fabs (val) < fabs (step) / 4 && fabs (val) < NR_EPSI)
val = 0.0;
result.set (val, i);
}
return result;
}
/* The function creates a logarithmic stepped vector of values
starting at the given start value, ending with the given stop value
and containing points elements. */
vector logspace (nr_double_t start, nr_double_t stop, int points) {
assert (start * stop > 0);
vector result (points);
nr_double_t step, first, last, d;
// ensure the last value being larger than the first
if (fabs (start) > fabs (stop)) {
first = fabs (stop);
last = fabs (start);
}
else {
first = fabs (start);
last = fabs (stop);
}
// check direction and sign of values
d = fabs (start) > fabs (stop) ? -1 : 1;
// compute logarithmic step size
step = (log (last) - log (first)) / (points - 1);
for (int i = 0, j = points - 1; i < points; i++, j--) {
if (d > 0)
result.set (start * exp (step * i), i);
else
result.set (stop * exp (step * i), j);
}
return result;
}
vector cumsum (vector v) {
vector result (v);
nr_complex_t val (0.0);
for (int i = 0; i < v.getSize (); i++) {
val += v.get (i);
result.set (val, i);
}
return result;
}
vector cumavg (vector v) {
vector result (v);
nr_complex_t val (0.0);
for (int i = 0; i < v.getSize (); i++) {
val = (val * (nr_double_t) i + v.get (i)) / (i + 1.0);
result.set (val, i);
}
return result;
}
vector cumprod (vector v) {
vector result (v);
nr_complex_t val (1.0);
for (int i = 0; i < v.getSize (); i++) {
val *= v.get (i);
result.set (val, i);
}
return result;
}
vector ceil (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (ceil (v.get (i)), i);
return result;
}
vector fix (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (fix (v.get (i)), i);
return result;
}
vector floor (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (floor (v.get (i)), i);
return result;
}
vector round (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (round (v.get (i)), i);
return result;
}
vector sqr (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (sqr (v.get (i)), i);
return result;
}
vector step (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (step (v.get (i)), i);
return result;
}
static nr_double_t integrate_n (vector v) { /* using trapezoidal rule */
nr_double_t result = 0.0;
for (int i = 1; i < v.getSize () - 1; i++) result += norm (v.get (i));
result += 0.5 * norm (v.get (0));
result += 0.5 * norm (v.get (v.getSize () - 1));
return result;
}
nr_double_t vector::rms (void) {
nr_double_t result = sqrt (integrate_n (*this) / getSize ());
return result;
}
nr_double_t vector::variance (void) {
nr_double_t result = 0.0;
nr_complex_t average = avg (*this);
for (int i = 0; i < getSize (); i++) result += norm (get (i) - average);
if (getSize () > 1)
return result / (getSize () - 1);
return 0.0;
}
nr_double_t vector::stddev (void) {
return sqrt (variance ());
}
vector erf (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (erf (v.get (i)), i);
return result;
}
vector erfc (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (erfc (v.get (i)), i);
return result;
}
vector erfinv (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (erfinv (v.get (i)), i);
return result;
}
vector erfcinv (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (erfcinv (v.get (i)), i);
return result;
}
vector i0 (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (i0 (v.get (i)), i);
return result;
}
vector jn (const int n, vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (jn (n, v.get (i)), i);
return result;
}
vector yn (const int n, vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (yn (n, v.get (i)), i);
return result;
}
vector polar (const nr_complex_t a, vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (polar (a, v.get (i)), i);
return result;
}
vector polar (vector v, const nr_complex_t p) {
vector result (v);
for (int i = 0; i < v.getSize (); i++) result.set (polar (v.get (i), p), i);
return result;
}
vector polar (vector a, vector p) {
int j, i, n, len, len1 = a.getSize (), len2 = p.getSize ();
if (len1 >= len2) {
assert (len1 % len2 == 0);
len = len1;
} else {
assert (len2 % len1 == 0);
len = len2;
}
vector res (len);
for (j = i = n = 0; n < len; n++) {
res (n) = polar (a (i), p (j));
if (++i >= len1) i = 0; if (++j >= len2) j = 0;
}
return res;
}
vector atan2 (const nr_double_t y, vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++)
result.set (atan2 (y, v.get (i)), i);
return result;
}
vector atan2 (vector v, const nr_double_t x) {
vector result (v);
for (int i = 0; i < v.getSize (); i++)
result.set (atan2 (v.get (i), x) , i);
return result;
}
vector atan2 (vector y, vector x) {
int j, i, n, len, len1 = y.getSize (), len2 = x.getSize ();
if (len1 >= len2) {
assert (len1 % len2 == 0);
len = len1;
} else {
assert (len2 % len1 == 0);
len = len2;
}
vector res (len);
for (j = i = n = 0; n < len; n++) {
res (n) = atan2 (y (i), x (j));
if (++i >= len1) i = 0; if (++j >= len2) j = 0;
}
return res;
}
vector w2dbm (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++)
result.set (10.0 * log10 (v.get (i) / 0.001), i);
return result;
}
vector dbm2w (vector v) {
vector result (v);
for (int i = 0; i < v.getSize (); i++)
result.set (0.001 * pow (10.0 , v.get (i) / 10.0), i);
return result;
}
nr_double_t integrate (vector v, const nr_double_t h) {
nr_double_t s = real (v.get (0) ) / 2;
for (int i = 1; i < v.getSize () - 1; i++)
s += real (v.get (i));
return (s + real (v.get (v.getSize () - 1) ) / 2) * h;
}
nr_complex_t integrate (vector v, const nr_complex_t h) {
nr_complex_t s;
s = v.get (0) / 2.0;
for (int i = 1; i < v.getSize () - 1; i++)
s += v.get (i);
return (s + v.get (v.getSize () - 1) / 2.0) * h;
}
vector dbm (vector v, const nr_complex_t z) {
vector result (v);
for (int i = 0; i < v.getSize (); i++)
result.set (10.0 * log10 (norm (v.get (i)) / conj (z) / 0.001), i);
return result;
}
vector runavg (const nr_complex_t x, const int n) {
vector result (n);
for (int i = 0; i < n; i++) result.set (x, i);
return result;
}
vector runavg (vector v, const int n) {
nr_complex_t s (0.0), y;
int len = v.getSize () - n + 1, i;
vector result (len);
for (i = 0; i < n; i++) s += v.get (i);
y = s / (nr_double_t) n; // first running average value
result.set (y, 0);
for (i = 0; i < len - 1; i++) {
y += (v.get (i + n) - v.get (i)) / (nr_double_t) n;
result.set (y, i + 1);
}
return result;
}
#ifdef DEBUG
// Debug function: Prints the vector object.
void vector::print (void) {
for (int r = 0; r < size; r++) {
fprintf (stderr, "%+.2e%+.2ei\n", (double) real (get (r)),
(double) imag (get (r)));
}
}
#endif /* DEBUG */
| gpl-2.0 |
BiglySoftware/BiglyBT | core/src/com/biglybt/core/networkmanager/admin/NetworkAdminProgressListener.java | 984 | /*
* Created on Feb 1, 2008
* Created by Paul Gardner
*
* Copyright (C) Azureus Software, Inc, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.biglybt.core.networkmanager.admin;
public interface
NetworkAdminProgressListener
{
public void
reportProgress(
String task );
}
| gpl-2.0 |
MicroTrustRepos/microkernel | src/l4/pkg/l4re/util/libs/dataspace_svr.cc | 6162 | // vi:ft=cpp
/*
* (c) 2008-2009 Adam Lackorzynski <adam@os.inf.tu-dresden.de>,
* Alexander Warg <warg@os.inf.tu-dresden.de>,
* Torsten Frenzel <frenzel@os.inf.tu-dresden.de>
* economic rights: Technische Universität Dresden (Germany)
*
* This file is part of TUD:OS and distributed under the terms of the
* GNU General Public License 2.
* Please see the COPYING-GPL-2 file for details.
*
* As a special exception, you may use this file as part of a free software
* library without restriction. Specifically, if other files instantiate
* templates or use macros or inline functions from this file, or you compile
* this file and link it with other files to produce an executable, this
* file does not by itself cause the resulting executable to be covered by
* the GNU General Public License. This exception does not however
* invalidate any other reasons why the executable file might be covered by
* the GNU General Public License.
*/
#include <cstring>
#include <cstddef>
#include <cstdio>
#include <l4/sys/types.h>
#include <l4/cxx/list>
#include <l4/cxx/ipc_server>
#include <l4/cxx/ipc_stream>
#include <l4/cxx/minmax>
#include <l4/re/dataspace>
#include <l4/re/dataspace-sys.h>
#include <l4/re/protocols>
#include <l4/re/util/dataspace_svr>
#if 0
inline
L4::Ipc::Ostream &operator << (L4::Ipc_ostream &s,
L4Re::Dataspace::Stats const &st)
{ s.put(st); return s; }
#endif
namespace L4Re { namespace Util {
int
Dataspace_svr::map(l4_addr_t offs, l4_addr_t hot_spot, unsigned long flags,
l4_addr_t min, l4_addr_t max, L4::Ipc::Snd_fpage &memory)
{
int err = map_hook(offs, flags, min, max);
if (err < 0)
return err;
memory = L4::Ipc::Snd_fpage();
offs = l4_trunc_page(offs);
hot_spot = l4_trunc_page(hot_spot);
if (!check_limit(offs))
{
#if 0
printf("limit failed: off=%lx sz=%lx\n", offs, size());
#endif
return -L4_ERANGE;
}
min = l4_trunc_page(min);
max = l4_round_page(max);
l4_addr_t adr = _ds_start + offs;
unsigned char order = L4_PAGESHIFT;
while (order < 30 /* limit to 1GB flexpage */)
{
l4_addr_t map_base = l4_trunc_size(adr, order + 1);
if (map_base < _ds_start)
break;
if (map_base + (1UL << (order + 1)) -1 > (_ds_start + round_size() - 1))
break;
map_base = l4_trunc_size(hot_spot, order + 1);
if (map_base < min)
break;
if (map_base + (1UL << (order + 1)) -1 > max -1)
break;
l4_addr_t mask = ~(~0UL << (order + 1));
if (hot_spot == ~0UL || ((adr ^ hot_spot) & mask))
break;
++order;
}
l4_addr_t map_base = l4_trunc_size(adr, order);
//l4_addr_t map_offs = adr & ~(~0UL << order);
l4_fpage_t fpage = l4_fpage(map_base, order, flags && is_writable() ? L4_FPAGE_RWX : L4_FPAGE_RX);
memory = L4::Ipc::Snd_fpage(fpage, hot_spot, _map_flags, _cache_flags);
return L4_EOK;
}
long
Dataspace_svr::clear(l4_addr_t offs, unsigned long _size) const throw()
{
if (!check_limit(offs))
return -L4_ERANGE;
unsigned long sz = _size = cxx::min(_size, round_size()-offs);
while (sz)
{
unsigned long b_adr = _ds_start + offs;
unsigned long b_sz = cxx::min(_size - offs, sz);
memset((void *)b_adr, 0, b_sz);
offs += b_sz;
sz -= b_sz;
}
return _size;
}
int
Dataspace_svr::phys(l4_addr_t /*offset*/, l4_addr_t &/*phys_addr*/, l4_size_t &/*phys_size*/) throw()
{
return -L4_EINVAL;
}
int
Dataspace_svr::dispatch(l4_umword_t obj, L4::Ipc::Iostream &ios)
{
L4::Opcode op;
ios >> op;
#if 0
L4::cout << "Dataspace_svr: DS: op=" << L4::n_hex(op) << "\n";
#endif
l4_msgtag_t tag;
ios >> tag;
if (tag.label() != L4Re::Protocol::Dataspace)
return -L4_EBADPROTO;
switch (op)
{
case L4Re::Dataspace_::Map:
{
// L4_FPAGE_X means writable for DSs!
bool read_only = !is_writable() || !(obj & L4_FPAGE_X);
l4_addr_t offset, spot;
unsigned long flags;
L4::Ipc::Snd_fpage fp;
ios >> offset >> spot >> flags;
#if 0
L4::cout << "MAPrq: " << L4::hex << offset << ", " << spot << ", "
<< flags << "\n";
#endif
if (read_only && (flags & 1))
return -L4_EPERM;
long int ret = map(offset, spot, flags & 1, 0, ~0, fp);
#if 0
L4::cout << "MAP: " << L4::hex << reinterpret_cast<unsigned long *>(&fp)[0]
<< ", " << reinterpret_cast<unsigned long *>(&fp)[1]
<< ", " << flags << ", " << (!read_only && (flags & 1))
<< ", ret=" << ret << '\n';
#endif
if (ret == L4_EOK)
ios << fp;
return ret;
}
case L4Re::Dataspace_::Clear:
{
if ((obj & 1) /* read only*/
|| is_static() || !is_writable())
return -L4_EACCESS;
l4_addr_t offs;
unsigned long sz;
ios >> offs >> sz;
return clear(offs, sz);
}
case L4Re::Dataspace_::Stats:
{
L4Re::Dataspace::Stats s;
s.size = size();
// only return writable if really writable
s.flags = (rw_flags() & ~Writable) | (!(obj & 1) && is_writable());
ios << s;
return L4_EOK;
}
case L4Re::Dataspace_::Copy:
{
l4_addr_t dst_offs;
l4_addr_t src_offs;
unsigned long sz;
L4::Ipc::Snd_fpage src_cap;
ios >> dst_offs >> src_offs >> sz >> src_cap;
if (!src_cap.id_received())
return -L4_EINVAL;
if (!(obj & 1))
return -L4_EACCESS;
if (sz == 0)
return L4_EOK;
copy(dst_offs, src_cap.data(), src_offs, sz);
return L4_EOK;
}
case L4Re::Dataspace_::Phys:
{
l4_addr_t offset;
l4_addr_t phys_addr;
l4_size_t phys_size;
ios >> offset;
int ret = phys(offset, phys_addr, phys_size);
if (ret)
return -L4_EINVAL;
ios << phys_addr << phys_size;
return L4_EOK;
}
case L4Re::Dataspace_::Take:
take();
//L4::cout << "Dataspace_svr: T[" << this << "]: refs=" << ref_cnt() << '\n';
return L4_EOK;
case L4Re::Dataspace_::Release:
if ((release() == 0) && !is_static())
{
//L4::cout << "Dataspace_svr: R[" << this << "]: refs=" << ref_cnt() << '\n';
delete this;
return 0;
}
//L4::cout << "Dataspace_svr: R[" << this << "]: refs=" << ref_cnt() << '\n';
return 1;
default:
return -L4_ENOSYS;
}
}
}}
| gpl-2.0 |
serghei/kde3-kdelibs | kdeprint/lpr/klprfactory.cpp | 1141 | /*
* This file is part of the KDE libraries
* Copyright (c) 2001 Michael Goffioul <kdeprint@swing.be>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License version 2 as published by the Free Software Foundation.
*
* This library 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 Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
**/
#include "kmlprmanager.h"
#include "kmlpruimanager.h"
#include "kmlprjobmanager.h"
#include "klprprinterimpl.h"
#include <kgenericfactory.h>
typedef K_TYPELIST_4(KMLprManager, KMLprUiManager, KMLprJobManager, KLprPrinterImpl) Products;
K_EXPORT_COMPONENT_FACTORY(kdeprint_lpr, KGenericFactory< Products >)
| gpl-2.0 |
paranoiasystem/Java-RMI-projects | FERRAIOLIMARCO/src/Messaggio.java | 408 |
public class Messaggio {
private int id;
private String username;
private int count;
public Messaggio(int id, String username) {
this.id = id;
this.username = username;
this.count = 0;
}
public int getId() {
return this.id;
}
public String getUsername() {
return this.username;
}
public int getCount() {
return this.count;
}
public void mipiaceplus() {
this.count++;
}
}
| gpl-2.0 |
cpuzzuol/library-wordpress | wp-content/plugins/libhours/includes/class.libhours.php | 13215 | <?php
class Libhours {
public static function cp_libhours_plugin_activation(){
$options = array(
);
add_option('cp_libhours_options', $options);
}
public static function cp_libhours_plugin_deactivation(){
}
public static function cp_libhours_init(){
add_action( 'wp_enqueue_scripts', array( 'Libhours', 'cp_libhours_load_resources' ) );
}
public static function cp_libhours_load_resources(){
wp_register_style( 'libhours.css', LIBHOURS__PLUGIN_URL . 'css/jquery.timepicker.min.css', array(), LIBHOURS_VERSION );
wp_enqueue_style( 'libhours.css');
wp_register_style( 'jquery_ui.css', '//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css', array(), LIBHOURS_VERSION );
wp_enqueue_style( 'jquery_ui.css');
wp_register_style( 'timepicker.css', LIBHOURS__PLUGIN_URL . 'css/libhours.css', array(), LIBHOURS_VERSION );
wp_enqueue_style( 'timepicker.css');
wp_register_script( 'libhours.js', LIBHOURS__PLUGIN_URL . 'js/libhours.js', array('jquery','postbox'), LIBHOURS_VERSION );
wp_enqueue_script( 'libhours.js' );
wp_register_script( 'jquery_ui', '//code.jquery.com/ui/1.11.2/jquery-ui.min.js', array('jquery'), LIBHOURS_VERSION );
wp_enqueue_script( 'jquery_ui' );
wp_register_script( 'moment.js', LIBHOURS__PLUGIN_URL . 'js/moment.js', array(), LIBHOURS_VERSION );
wp_enqueue_script( 'moment.js' );
wp_register_script( 'timepicker.js', LIBHOURS__PLUGIN_URL . 'js/jquery.timepicker.min.js', array(), LIBHOURS_VERSION );
wp_enqueue_script( 'timepicker.js' );
}
public static function cp_libhours_sanitize_url($url){
if($url == '' || filter_var($url, FILTER_VALIDATE_URL)){
return true;
}
return false;
}
public static function cp_libhours_is_year($year){
if(is_numeric($year) && (strlen($year) == 4)){
return true;
}
return false;
}
// $to_mysql_date_format (TRUE if going from mm/dd/yyyy to YYYY-mm-dd, FALSE if going from YYYY-mm-dd to mm/dd/YYYY)
public static function cp_libhours_date_format($date, $to_mysql_date_format = TRUE){
if($to_mysql_date_format){
$formatted_date = date('Y-m-d', strtotime($date));
} else {
$formatted_date = date('m/d/Y', strtotime($date));
}
return $formatted_date;
}
// convert YYYY-mm-dd hh:ii:ss to hh:ii A
public static function cp_libhours_timestamp_to_ampm($date){
$formatted_date = date('g:i A', strtotime($date));
return $formatted_date;
}
/*
* Display library hours on the front end of the website (shortcode defined in libhours.php)
*/
public static function cp_libhours_frontend_display(){
global $wpdb, $table_prefix, $wp_query;
$hours_options = get_option('libhours_plugin_options');
$displayed_areas = $hours_options['areas_checkbox'];
$selfclass = new self();
$plugin_options = get_option('libhours_plugin_options');
$week_dates = $selfclass->__getDates($_GET['week']); //dates of the selected week
$today = date('Y-m-d');
//list of special categories for display below all the hours tables
$special_events = $selfclass->__getSpecialCategories($week_dates);
?>
<div id="hours-navigator">
<p class="libhours-bold">
<a href="<?php echo add_query_arg( 'week', $_GET['week']-1, get_permalink() ); ?>" class="libhours-leftlink"><?php esc_html_e('<< Previous', 'libhours') ?></a>
<a href="<?php echo add_query_arg( 'week', 0, get_permalink() ); ?>" class="libhours-leftlink">This Week</a>
<a href="<?php echo add_query_arg( 'week', $_GET['week']+1, get_permalink() ); ?>"><?php esc_html_e('Next >>', 'libhours') ?></a>
</p>
<input type="text" class="form-control" name="datepicker" id="datepicker-jump" onChange="jumpWeek(this.value)" placeholder="jump to date">
<span class="input-group-btn">
<button class="btn btn-default" id="datepicker-jump-glyph" type="button"><span class="ui-icon ui-icon-calendar"></span></button>
</span>
<p class="libhours-current-week libhours-bold"><?php esc_html_e('Week of ' . Libhours::cp_libhours_date_format($week_dates[0], FALSE) . ' to ' . Libhours::cp_libhours_date_format($week_dates[6], FALSE)); ?></p>
</div>
<div id="libhours-table-holder clearfix">
<?php
//get a list of all areas and display them in a table if the is_display field is set to 1
$locations = $wpdb->get_results("SELECT * FROM ".$table_prefix."library_areas ORDER BY displayOrder ASC");
foreach($locations as $location):
if(in_array($location->id, $displayed_areas)):
?>
<div class="area-hours-container clearfix">
<table class="area-hours-table">
<caption><?php echo $location->location; ?></caption>
<?php
$day_of_week = 0;
foreach($week_dates as $day):
switch($day_of_week){
case 0:
if($week_dates[$day_of_week] != $today){
echo _e( '<tr><td>Sunday</td>', 'libhours' );
} else {
echo _e( '<tr class="libhours-today" style="background:'.$plugin_options['bg_color_picker'].'; color:'.$plugin_options['text_color_picker'].'"><td>Sunday</td>', 'libhours' );
}
break;
case 1:
if($week_dates[$day_of_week] != $today){
echo _e( '<tr><td>Monday</td>', 'libhours' );
} else {
echo _e( '<tr class="libhours-today" style="background:'.$plugin_options['bg_color_picker'].'; color:'.$plugin_options['text_color_picker'].'"><td>Monday</td>', 'libhours' );
}
break;
case 2:
if($week_dates[$day_of_week] != $today){
echo _e( '<tr><td>Tuesday</td>', 'libhours' );
} else {
echo _e( '<tr class="libhours-today" style="background:'.$plugin_options['bg_color_picker'].'; color:'.$plugin_options['text_color_picker'].'"><td>Tuesday</td>', 'libhours' );
}
break;
case 3:
if($week_dates[$day_of_week] != $today){
echo _e( '<tr><td>Wednesday</td>', 'libhours' );
} else {
echo _e( '<tr class="libhours-today" style="background:'.$plugin_options['bg_color_picker'].'; color:'.$plugin_options['text_color_picker'].'"><td>Wednesday</td>', 'libhours' );
}
break;
case 4:
if($week_dates[$day_of_week] != $today){
echo _e( '<tr><td>Thursday</td>', 'libhours' );
} else {
echo _e( '<tr class="libhours-today" style="background:'.$plugin_options['bg_color_picker'].'; color:'.$plugin_options['text_color_picker'].'"><td>Thursday</td>', 'libhours' );
}
break;
case 5:
if($week_dates[$day_of_week] != $today){
echo _e( '<tr><td>Friday</td>', 'libhours' );
} else {
echo _e( '<tr class="libhours-today" style="background:'.$plugin_options['bg_color_picker'].'; color:'.$plugin_options['text_color_picker'].'"><td>Friday</td>', 'libhours' );
}
break;
case 6:
if($week_dates[$day_of_week] != $today){
echo _e( '<tr><td>Saturday</td>', 'libhours' );
} else {
echo _e( '<tr class="libhours-today" style="background:'.$plugin_options['bg_color_picker'].'; color:'.$plugin_options['text_color_picker'].'"><td>Saturday</td>', 'libhours' );
}
break;
}
$special_hour = Libhours_Database::getSpecialHours($location->id, $day);
//if a special hour was returned, display that hour
if($special_hour){
//show the hours as long as the area is not closed or 24 hours
if(($special_hour->is_24hour == 0) && ($special_hour->is_closed == 0)){
echo '<td class="libhours-cell-right">' . Libhours::cp_libhours_timestamp_to_ampm($special_hour->timeOpen) . ' - ' . Libhours::cp_libhours_timestamp_to_ampm($special_hour->timeClose) . '</td></tr>';
}
//display '24 hours' if area is marked as such
if($special_hour->is_24hour == 1){
echo _e('<td class="libhours-cell-right">24 Hours</td></tr>', 'libhours');
}
//display 'closed' if area is marked as such
if($special_hour->is_closed == 1){
echo _e('<td class="libhours-cell-right">Closed</td></tr>', 'libhours');
}
}
//if no special hour was returned, look for the regular hour
else {
$regular_hour = Libhours_Database::getRegularHour($location->id, $day, $day_of_week);
if($regular_hour){
//show the hours as long as the area is not closed or 24 hours
if(($regular_hour->is_24hour == 0) && ($regular_hour->is_closed == 0)){
echo '<td class="libhours-cell-right">' . Libhours::cp_libhours_timestamp_to_ampm($regular_hour->timeOpen) . ' - ' . Libhours::cp_libhours_timestamp_to_ampm($regular_hour->timeClose) . '</td></tr>';
}
//display '24 hours' if area is marked as such
if($regular_hour->is_24hour == 1){
echo _e('<td class="libhours-cell-right">24 Hours</td></tr>', 'libhours');
}
//display 'closed' if area is marked as such
if($regular_hour->is_closed == 1){
echo _e('<td class="libhours-cell-right">Closed</td></tr>', 'libhours');
}
} else {
echo _e('<td class="libhours-cell-right">not set</td></tr>');
}
}
$day_of_week++;
endforeach;
?>
</table>
</div>
<?php
endif;
endforeach;
?>
</div><!--END #libhours-table-holder-->
<div style="clear:both"></div>
<div id="special-hours-container">
<?php
//SPECIAL EVENTS LIST
if(!empty($special_events)){
echo _e('<h3>Special Hours this Week</h3>', 'libhours');
echo '<ul id="libhours-speical-categories-list">';
$asterisk = '*';
foreach($special_events as $special_event){
echo _e('<li>'. $asterisk . $special_event['description'] . ' | ' . Libhours::cp_libhours_date_format($special_event['start'], FALSE) . ' - ' . Libhours::cp_libhours_date_format($special_event['end'], FALSE) . '</li>', 'libhours');
$asterisk .= '*';
}
echo "</ul>";
}
?>
</div>
<script>
jQuery(document).ready(function(){
jQuery('#datepicker-jump').datepicker({
changeMonth: true,
changeYear: true
});
jQuery('#datepicker-jump-glyph').click(function(){jQuery('#datepicker-jump').trigger('focus');});
});
function jumpWeek(selectedDate){
var today = moment();
var startOfThisWeek = today.startOf('week').unix();
var targetDate = moment(selectedDate);
var startOfTargetWeek = targetDate.startOf('week').unix();
var secondsInAWeek = 604800;
var weekOffset = Math.ceil((startOfTargetWeek-startOfThisWeek)/secondsInAWeek);
window.location.href = '<?php echo site_url('hours/?week='); ?>' + weekOffset;
}
</script>
<?php
}
private function __getDates($weekOffset){
$week_number = date('w');
for ($i=0; $i<7; $i++) {
$date_array[$i] = (date("Y-m-d", mktime(0,0,0,date("m"), date("d") - $week_number +$i + ($weekOffset*7), date("Y"))));
}
return $date_array;
}
private function __weekOffset($date){
//take the user to the specified week
}
public function load_frontend_resources(){
wp_register_style( 'libhours.css', LIBHOURS__PLUGIN_URL . 'css/libhours.css', array(), LIBHOURS_VERSION );
wp_enqueue_style( 'libhours.css');
}
/*
* Get all special hours categories that fall under the specified week range
*
* @param array $week_range The seven-day date range for the given week
* @return array $special_categories An array of special categories (or an empty array if none were found)
*/
public function __getSpecialCategories($week_range) {
global $wpdb, $table_prefix;
$special_categories = array();
$query = "SELECT * FROM ". $table_prefix . "library_specialhours_categories WHERE startDate >= '". $week_range[0] . "' AND endDate <= '" . $week_range[6] . "' ORDER BY startDate ASC";
$results = $wpdb->get_results($query);
$count = 0;
foreach($results as $category){
$special_categories[$count]['description'] = $category->description;
$special_categories[$count]['start'] = $category->startDate;
$special_categories[$count]['end'] = $category->endDate;
$count++;
}
return $special_categories;
}
}
| gpl-2.0 |
alejob/mdanalysis | testsuite/MDAnalysisTests/topology/test_gms.py | 2322 | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# MDAnalysis --- http://www.mdanalysis.org
# Copyright (c) 2006-2016 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under the GNU Public Licence, v2 or any higher version
#
# Please cite your use of MDAnalysis in published work:
#
# R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler,
# D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein.
# MDAnalysis: A Python package for the rapid analysis of molecular dynamics
# simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th
# Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy.
#
# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein.
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
from numpy.testing import (
assert_,
assert_array_equal,
)
import MDAnalysis as mda
from MDAnalysisTests.topology.base import ParserBase
from MDAnalysisTests.datafiles import (
GMS_ASYMOPT, # c1opt.gms.gz
GMS_SYMOPT, # symopt.gms
GMS_ASYMSURF, # surf2wat.gms
)
class GMSBase(ParserBase):
parser = mda.topology.GMSParser.GMSParser
expected_attrs = ['names', 'atomiccharges']
guessed_attrs = ['masses', 'types']
expected_n_residues = 1
expected_n_segments = 1
class TestGMSASYMOPT(GMSBase):
filename = GMS_ASYMOPT
expected_n_atoms = 6
def test_names(self):
assert_array_equal(self.top.names.values,
['O', 'H', 'H', 'O', 'H', 'H'])
def test_types(self):
assert_array_equal(self.top.atomiccharges.values,
[8, 1, 1, 8, 1, 1])
class TestGMSSYMOPT(GMSBase):
filename = GMS_SYMOPT
expected_n_atoms = 4
def test_names(self):
assert_array_equal(self.top.names.values,
['CARBON', 'CARBON', 'HYDROGEN', 'HYDROGEN'])
def test_types(self):
assert_array_equal(self.top.atomiccharges.values,
[6, 6, 1, 1])
class TestGMSASYMSURF(TestGMSASYMOPT):
filename = GMS_ASYMSURF
| gpl-2.0 |
chiadem/YET | YAF.Types/Interfaces/Data/IDbSortableOperation.cs | 1285 | /* Yet Another Forum.NET
* Copyright (C) 2006-2013 Jaben Cargman
* http://www.yetanotherforum.net/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
namespace YAF.Types.Interfaces.Data
{
public interface IDbSortableOperation : IHaveSortOrder
{
#region Public Methods and Operators
/// <summary>
/// The supported operation.
/// </summary>
/// <param name="operationName"> The operation name. </param>
/// <returns> True if the operation is supported. </returns>
bool IsSupportedOperation(string operationName);
#endregion
}
} | gpl-2.0 |
cmj123/medtechdevs_meetup | medtech_doctor_portal/client_pusher/client_pusher/ServerProxy.py | 277 | import requests
import json
class ServerProxy(object):
URL = 'someurl.com'
USERNAME = 'user'
PASSWORD = 'pass'
def __init__(self):
pass
def send_data(self, data):
result = requests.post(self.URL, data, auth=(self.USERNAME, self.PASSWORD)) | gpl-2.0 |
arafathnihar/esy | administrator/components/com_j2store/j2store.php | 2938 | <?php
/*------------------------------------------------------------------------
# com_j2store - J2Store
# ------------------------------------------------------------------------
# author Sasi varna kumar - Weblogicx India http://www.weblogicxindia.com
# copyright Copyright (C) 2012 Weblogicxindia.com. All Rights Reserved.
# @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://j2store.org
# Technical Support: Forum - http://j2store.org/forum/index.html
-------------------------------------------------------------------------*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
JHTML::_('behavior.tooltip');
jimport('joomla.application.component.controller');
$app = JFactory::getApplication();
//j3 compatibility
if(!defined('DS')){
define('DS',DIRECTORY_SEPARATOR);
}
JLoader::register('J2StoreController', JPATH_ADMINISTRATOR.'/components/com_j2store/controllers/controller.php');
JLoader::register('J2StoreView',JPATH_ADMINISTRATOR.'/components/com_j2store/views/view.php');
JLoader::register('J2StoreModel', JPATH_ADMINISTRATOR.'/components/com_j2store/models/model.php');
require_once (JPATH_SITE.'/components/com_j2store/helpers/utilities.php');
require_once (JPATH_ADMINISTRATOR.'/components/com_j2store/helpers/toolbar.php');
require_once (JPATH_ADMINISTRATOR.'/components/com_j2store/helpers/version.php');
require_once (JPATH_ADMINISTRATOR.'/components/com_j2store/helpers/strapper.php');
$version = new J2StoreVersion();
$version->load_version_defines();
J2StoreStrapper::addJS();
J2StoreStrapper::addCSS();
//handle live update
require_once JPATH_ADMINISTRATOR.'/components/com_j2store/liveupdate/liveupdate.php';
if($app->input->getCmd('view','') == 'liveupdate') {
LiveUpdate::handleRequest();
return;
}
/*
* Make sure the user is authorized to view this page
*/
$controller = $app->input->getWord('view', 'cpanel');
if (JFile::exists(JPATH_ADMINISTRATOR.'/components/com_j2store/controllers/'.$controller.'.php')
&& $controller !='countries' && $controller !='zones'
&& $controller !='country' && $controller !='zone'
&& $controller !='taxprofiles' && $controller !='taxprofile'
&& $controller !='taxrates' && $controller !='taxrate'
&& $controller !='geozones' && $controller !='geozone'
&& $controller !='geozonerules' && $controller !='geozonerule'
&& $controller !='storeprofiles' && $controller !='storeprofile'
&& $controller !='lengths' && $controller !='length'
&& $controller !='weights' && $controller !='weight'
&& $controller !='emailtemplates' && $controller !='emailtemplate'
)
{
require_once (JPATH_ADMINISTRATOR.'/components/com_j2store/controllers/'.$controller.'.php');
$classname = 'J2StoreController'.ucwords($controller);
$controller = new $classname();
} else {
$controller = JControllerLegacy::getInstance('J2Store');
}
$controller->execute($app->input->getCmd('task'));
$controller->redirect();
| gpl-2.0 |
ShimShtein/katello | engines/bastion_katello/test/errata/details/errata-content-hosts.controller.test.js | 4363 | /**
* Copyright 2014 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public
* License as published by the Free Software Foundation; either version
* 2 of the License (GPLv2) or (at your option) any later version.
* There is NO WARRANTY for this software, express or implied,
* including the implied warranties of MERCHANTABILITY,
* NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should
* have received a copy of GPLv2 along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
**/
describe('Controller: ErrataContentHostsController', function() {
var $scope, translate, Nutupane, ContentHost, ContentHostBulkAction,
CurrentOrganization;
beforeEach(module('Bastion.errata', 'Bastion.test-mocks'));
beforeEach(inject(function($injector) {
var $controller = $injector.get('$controller'),
MockResource = $injector.get('MockResource');
translate = function (string) {
return string;
};
Nutupane = function() {
this.table = {
params: {},
showColumns: function () {},
allResultsSelectCount: function () {}
};
this.enableSelectAllResults = function () {};
this.getAllSelectedResults = function () {
return {include: [1, 2, 3]};
};
this.setParams = function (params) {
this.table.params = params;
};
this.refresh = function () {};
this.load = function () {
return {then: function () {}}
};
};
ContentHost = {};
ContentHostBulkAction = {
failed: false,
installContent: function (params, success, error) {
if (this.failed) {
error({errors: ['error']});
} else {
success();
}
}
};
Environment = MockResource.$new();
CurrentOrganization = 'foo';
$scope = $injector.get('$rootScope').$new();
$scope.$stateParams = {errataId: 1};
$scope.checkIfIncrementalUpdateRunning = function () {};
$controller('ErrataContentHostsController', {
$scope: $scope,
translate: translate,
Nutupane: Nutupane,
ContentHost: ContentHost,
Environment: Environment,
ContentHostBulkAction: ContentHostBulkAction,
CurrentOrganization: CurrentOrganization
});
}));
it("puts the errata content hosts table object on the scope", function() {
expect($scope.detailsTable).toBeDefined();
});
it("allows the filtering of installable errata only", function () {
$scope.errata = {
showInstallable: true
};
$scope.toggleInstallable();
expect($scope.detailsTable.params['erratum_restrict_installable']).toBe(true)
});
it("provides a way to filter on environment", function () {
var nutupane = $scope.nutupane;
spyOn(nutupane, 'setParams').andCallThrough();
spyOn(nutupane, 'refresh');
$scope.selectEnvironment('foo');
expect(nutupane.setParams).toHaveBeenCalled();
expect(nutupane.refresh).toHaveBeenCalled();
expect($scope.detailsTable.params['environment_id']).toBe('foo');
});
describe("provides a way to go to the next apply step", function () {
beforeEach(function () {
spyOn($scope.nutupane, 'getAllSelectedResults');
spyOn($scope, 'transitionTo');
});
afterEach(function() {
expect($scope.nutupane.getAllSelectedResults).toHaveBeenCalled();
});
it("and goes to the errata details apply page if there is an errata", function () {
$scope.errata = {id: 1};
$scope.goToNextStep();
expect($scope.transitionTo).toHaveBeenCalledWith('errata.details.apply', {errataId: $scope.errata.id})
});
it("and goes to the errata apply page if there is not an errata", function () {
$scope.goToNextStep();
expect($scope.transitionTo).toHaveBeenCalledWith('errata.apply.confirm');
});
});
});
| gpl-2.0 |
rex-xxx/mt6572_x201 | packages/apps/Contacts/src/com/android/contacts/list/LegacyPostalAddressListAdapter.java | 4226 | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.list;
import android.content.ContentUris;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Contacts.ContactMethods;
import android.provider.Contacts.People;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.view.View;
import android.view.ViewGroup;
/**
* A cursor adapter for the ContactMethods.CONTENT_TYPE content type.
*/
@SuppressWarnings("deprecation")
public class LegacyPostalAddressListAdapter extends ContactEntryListAdapter {
static final String[] POSTALS_PROJECTION = new String[] {
ContactMethods._ID, // 0
ContactMethods.TYPE, // 1
ContactMethods.LABEL, // 2
ContactMethods.DATA, // 3
People.DISPLAY_NAME, // 4
People.PHONETIC_NAME, // 5
};
public static final int POSTAL_ID_COLUMN_INDEX = 0;
public static final int POSTAL_TYPE_COLUMN_INDEX = 1;
public static final int POSTAL_LABEL_COLUMN_INDEX = 2;
public static final int POSTAL_NUMBER_COLUMN_INDEX = 3;
public static final int POSTAL_DISPLAY_NAME_COLUMN_INDEX = 4;
public static final int POSTAL_PHONETIC_NAME_COLUMN_INDEX = 5;
private CharSequence mUnknownNameText;
public LegacyPostalAddressListAdapter(Context context) {
super(context);
mUnknownNameText = context.getText(android.R.string.unknownName);
}
@Override
public void configureLoader(CursorLoader loader, long directoryId) {
loader.setUri(ContactMethods.CONTENT_URI);
loader.setProjection(POSTALS_PROJECTION);
loader.setSortOrder(People.DISPLAY_NAME);
loader.setSelection(ContactMethods.KIND + "=" + android.provider.Contacts.KIND_POSTAL);
}
@Override
public String getContactDisplayName(int position) {
return ((Cursor)getItem(position)).getString(POSTAL_DISPLAY_NAME_COLUMN_INDEX);
}
public Uri getContactMethodUri(int position) {
Cursor cursor = ((Cursor)getItem(position));
long id = cursor.getLong(POSTAL_ID_COLUMN_INDEX);
return ContentUris.withAppendedId(ContactMethods.CONTENT_URI, id);
}
@Override
protected View newView(Context context, int partition, Cursor cursor, int position,
ViewGroup parent) {
final ContactListItemView view = new ContactListItemView(context, null);
view.setUnknownNameText(mUnknownNameText);
return view;
}
@Override
protected void bindView(View itemView, int partition, Cursor cursor, int position) {
ContactListItemView view = (ContactListItemView)itemView;
bindName(view, cursor);
bindPostalAddress(view, cursor);
}
protected void bindName(final ContactListItemView view, Cursor cursor) {
view.showDisplayName(cursor, POSTAL_DISPLAY_NAME_COLUMN_INDEX,
getContactNameDisplayOrder());
view.showPhoneticName(cursor, POSTAL_PHONETIC_NAME_COLUMN_INDEX);
}
protected void bindPostalAddress(ContactListItemView view, Cursor cursor) {
CharSequence label = null;
if (!cursor.isNull(POSTAL_TYPE_COLUMN_INDEX)) {
final int type = cursor.getInt(POSTAL_TYPE_COLUMN_INDEX);
final String customLabel = cursor.getString(POSTAL_LABEL_COLUMN_INDEX);
// TODO cache
label = StructuredPostal.getTypeLabel(getContext().getResources(), type, customLabel);
}
view.setLabel(label);
view.showData(cursor, POSTAL_NUMBER_COLUMN_INDEX);
}
}
| gpl-2.0 |
gerryDreamer/dreamerLib | src/com/dreamer/data/structures/ExtendedStackFunctions.java | 8229 | /*
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2017 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [2017] [Gerishom Muzembi]"
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s): Gerishom Muzembi (Gerry Dreamer Ventures)
*/
package com.dreamer.data.structures;
/**
*
* @author gerry dreamer
*/
public class ExtendedStackFunctions {
/**
* this method checks for operator precedence between two operators
* @param operator1 the first operator
* @param operator2 the second operator
* @return returns true if operator1 has a lower precedence
* and false if operator1 has a higher precedence
*/
public boolean precedence(Object operator1, Object operator2){
// int charValue1 = 0, charValue2 = 0;
if(isOperator(operator1) == true && isOperator(operator2) == true){//first validates if the string value parameters are really operators
//determine the operator precedence
if(findCharValue(operator1) <= findCharValue(operator2))
{
//higher precedence
return false;
}//end inner if
else if(findCharValue(operator1) >= findCharValue(operator2))
{
return true;//lower precedence
}//end inner else if
}//if both the first and second operators are truly arithmetic operators
return false;//default: a lower precedence
}//end method precedence
/**
* this method is bundled with the precedence method
* @param operator1 the current operator
* @return the integer value of the operator
*/
public int findCharValue(Object operator1)
{
Object[] operators = {"%","^","/","*","+","-"};//the current char array of operators
int charValue = 0;
for(int i=0; i<operators.length; i++)
{
if(operator1 == operators[i])
charValue = i;//asssign char value the index number
}//end for loop
return charValue;
}//end method findCharValue
/**
* this method checks for operator precedence between two operators
* @param operator1 the first operator
* @param operator2 the second operator
* @return returns true if operator1 has a lower precedence
* and false if operator1 has a higher precedence
*/
public boolean precedence(String operator1, String operator2){
// int charValue1 = 0, charValue2 = 0;
if(isOperator(operator1) == true && isOperator(operator2) == true){//first validates if the string value parameters are really operators
//determine the operator precedence
if(findCharValue(operator1) <= findCharValue(operator2))
{
//higher precedence
return false;
}//end inner if
else if(findCharValue(operator1) >= findCharValue(operator2))
{
return true;//lower precedence
}//end inner else if
}//if both the first and second operators are truly arithmetic operators
return false;//default: a lower precedence
}//end method precedence
/**
* this method is bundled with the precedence method
* @param operator1 the current operator
* @return the integer value of the operator
*/
public int findCharValue(String operator1)
{
String[] operators = {"%","^","/","*","+","-"};//the current char array of operators
int charValue = 0;
for(int i=0; i<operators.length; i++)
{
if(operator1 == operators[i])
charValue = i;//asssign char value the index number
}//end for loop
return charValue;
}//end method findCharValue
/**
* this method checks for the next operator in a string token
* @param val the current string token
* @return
*/
public boolean isOperator(String val)
{
String op = "%^/*+-";
char c = val.charAt(0);
char operators[] = op.toCharArray();
int counter = 0;
while(counter < operators.length)
{
if(c == operators[counter])
return true;
++counter;
}
return false;
}
/**
* this method checks for the next operator in an object token
* @param val the current string token
* @return
*/
public boolean isOperator(Object val)
{
String op = "%^/*+-";
String valString = val.toString();
char c = valString.charAt(0);
char operators[] = op.toCharArray();
int counter = 0;
while(counter < operators.length)
{
if(c == operators[counter])
return true;
++counter;
}
return false;
}
/**
* this method determines whether a String value is a digit
* @param x the current String value
* @return returns true if x is a digit, and false if x is otherwise
*/
public boolean isDigit(String x){
//first convert the char to a string
String stringValue = x;
//now convert the string to an integer
try
{
int intValue = Integer.parseInt(String.valueOf(stringValue));
if(intValue > 0 || intValue < 0)
return true;
}
catch(NumberFormatException e)
{
return false;
}
return false;
}//end method isDigit
/**
* this method determines whether a char value is a digit
* @param x the current object value
* @return returns true if x is a digit, and false if x is otherwise
*/
public boolean isDigit(Object x){
//first convert the char to a string
String stringValue = x.toString();
//now convert the string to an integer
try
{
int intValue = Integer.parseInt(String.valueOf(stringValue));
if(intValue > 0 || intValue < 0)
return true;
}
catch(NumberFormatException e)
{
return false;
}
return false;
}//end method isDigit
}
| gpl-2.0 |
JohannesBuchner/HIntLib | share/convert_matrix.cpp | 1873 | /*
* HIntLib - Library for High-dimensional Numerical Integration
*
* Copyright (C) 2002,03,04,05 Rudolf Schuerer <rudolf.schuerer@sbg.ac.at>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include <memory>
#include <iostream>
#include <fstream>
#include <exception>
#include <HIntLib/generatormatrixgen.h>
using std::cerr;
using std::endl;
int main (int argc, char** argv)
{
if (argc != 3)
{
cerr << "Usage: convert libSeqMatrix BinaryMatirx\n\n";
exit (1);
}
try
{
// Read matrix from input file
std::ifstream ifs (argv[1]);
std::auto_ptr<HIntLib::GeneratorMatrix> m (HIntLib::loadLibSeq (ifs));
if (! ifs)
{
cerr << "Error reading input file '" << argv[1] << "'!\n\n";
return 1;
}
// Write matrix to output file
std::ofstream ofs (argv[2]);
m->binaryExport (ofs);
if (! ofs)
{
cerr << "Error writing output file '" << argv[2] << "'!\n\n";
return 1;
}
}
catch (std::exception &e)
{
cerr << "Exception: " << e.what() << endl;
}
catch (...)
{
cerr << "Unknown exception!" << endl;
}
return 0;
}
| gpl-2.0 |
rickli/Java | Day2/com/darwinsys/database/GenericDAO.java | 987 | package com.darwinsys.database;
import java.io.Serializable;
/**
* Interface to be implemented by DAOs; using Java 5 Generics.
* @author Per Mellqvist, http://www.ibm.com/developerworks/java/library/j-genericdao.html
*/
public interface GenericDAO<T, PK extends Serializable> {
/** Persist the newInstance object into database
* @param newInstance The object to be persisted
* @return The primary key of the newly inserted object
*/
PK create(T newInstance);
/** Retrieve an object that was previously saved in the database
* under the given primary key (id).
* @param id The id to be read
* @return The found object
*/
T read(PK id);
/** Save changes made to a persistent object.
* @param transientObject The object to be updated.
*/
void update(T transientObject);
/** Remove an object from persistent storage in the database
* @param persistentObject the object to be deleted.
*/
void delete(T persistentObject);
}
| gpl-2.0 |
lamsfoundation/lams | 3rdParty_sources/spring/org/springframework/beans/factory/NoSuchBeanDefinitionException.java | 4944 | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory;
import org.springframework.beans.BeansException;
import org.springframework.core.ResolvableType;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* Exception thrown when a {@code BeanFactory} is asked for a bean instance for which it
* cannot find a definition. This may point to a non-existing bean, a non-unique bean,
* or a manually registered singleton instance without an associated bean definition.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Stephane Nicoll
* @see BeanFactory#getBean(String)
* @see BeanFactory#getBean(Class)
* @see NoUniqueBeanDefinitionException
*/
@SuppressWarnings("serial")
public class NoSuchBeanDefinitionException extends BeansException {
private String beanName;
private ResolvableType resolvableType;
/**
* Create a new {@code NoSuchBeanDefinitionException}.
* @param name the name of the missing bean
*/
public NoSuchBeanDefinitionException(String name) {
super("No bean named '" + name + "' available");
this.beanName = name;
}
/**
* Create a new {@code NoSuchBeanDefinitionException}.
* @param name the name of the missing bean
* @param message detailed message describing the problem
*/
public NoSuchBeanDefinitionException(String name, String message) {
super("No bean named '" + name + "' available: " + message);
this.beanName = name;
}
/**
* Create a new {@code NoSuchBeanDefinitionException}.
* @param type required type of the missing bean
*/
public NoSuchBeanDefinitionException(Class<?> type) {
this(ResolvableType.forClass(type));
}
/**
* Create a new {@code NoSuchBeanDefinitionException}.
* @param type required type of the missing bean
* @param message detailed message describing the problem
*/
public NoSuchBeanDefinitionException(Class<?> type, String message) {
this(ResolvableType.forClass(type), message);
}
/**
* Create a new {@code NoSuchBeanDefinitionException}.
* @param type full type declaration of the missing bean
* @since 4.3.4
*/
public NoSuchBeanDefinitionException(ResolvableType type) {
super("No qualifying bean of type '" + type + "' available");
this.resolvableType = type;
}
/**
* Create a new {@code NoSuchBeanDefinitionException}.
* @param type full type declaration of the missing bean
* @param message detailed message describing the problem
* @since 4.3.4
*/
public NoSuchBeanDefinitionException(ResolvableType type, String message) {
super("No qualifying bean of type '" + type + "' available: " + message);
this.resolvableType = type;
}
/**
* Create a new {@code NoSuchBeanDefinitionException}.
* @param type required type of the missing bean
* @param dependencyDescription a description of the originating dependency
* @param message detailed message describing the problem
* @deprecated as of 4.3.4, in favor of {@link #NoSuchBeanDefinitionException(ResolvableType, String)}
*/
@Deprecated
public NoSuchBeanDefinitionException(Class<?> type, String dependencyDescription, String message) {
super("No qualifying bean" + (!StringUtils.hasLength(dependencyDescription) ?
" of type '" + ClassUtils.getQualifiedName(type) + "'" : "") + " found for dependency" +
(StringUtils.hasLength(dependencyDescription) ? " [" + dependencyDescription + "]" : "") +
": " + message);
this.resolvableType = ResolvableType.forClass(type);
}
/**
* Return the name of the missing bean, if it was a lookup <em>by name</em> that failed.
*/
public String getBeanName() {
return this.beanName;
}
/**
* Return the required type of the missing bean, if it was a lookup <em>by type</em>
* that failed.
*/
public Class<?> getBeanType() {
return (this.resolvableType != null ? this.resolvableType.resolve() : null);
}
/**
* Return the required {@link ResolvableType} of the missing bean, if it was a lookup
* <em>by type</em> that failed.
* @since 4.3.4
*/
public ResolvableType getResolvableType() {
return this.resolvableType;
}
/**
* Return the number of beans found when only one matching bean was expected.
* For a regular NoSuchBeanDefinitionException, this will always be 0.
* @see NoUniqueBeanDefinitionException
*/
public int getNumberOfBeansFound() {
return 0;
}
}
| gpl-2.0 |
GoldenGnu/jeveassets | src/main/java/net/nikr/eve/jeveasset/gui/dialogs/update/TaskDialog.java | 17457 | /*
* Copyright 2009-2021 Contributors (see credits.txt)
*
* This file is part of jEveAssets.
*
* jEveAssets 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.
*
* jEveAssets 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 jEveAssets; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
package net.nikr.eve.jeveasset.gui.dialogs.update;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.swing.*;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;
import net.nikr.eve.jeveasset.Program;
import net.nikr.eve.jeveasset.data.settings.Colors;
import net.nikr.eve.jeveasset.gui.frame.StatusPanel;
import net.nikr.eve.jeveasset.gui.frame.StatusPanel.Progress;
import net.nikr.eve.jeveasset.gui.frame.StatusPanel.UpdateType;
import net.nikr.eve.jeveasset.gui.shared.Formater;
import net.nikr.eve.jeveasset.gui.shared.components.JLockWindow;
import net.nikr.eve.jeveasset.gui.shared.components.JLockWindow.LockWorkerAdaptor;
import net.nikr.eve.jeveasset.i18n.DialoguesUpdate;
import net.nikr.eve.jeveasset.i18n.GuiShared;
public class TaskDialog {
private enum TaskAction {
OK, CANCEL, MINIMIZE
}
private static final int WIDTH_LOG = 280;
//GUI
private final JDialog jWindow;
private final JLabel jIcon;
private final JProgressBar jProgressBar;
private final JProgressBar jTotalProgressBar;
private final JButton jOK;
private final JButton jCancel;
private final JButton jMinimize;
private final JTextPane jErrorMessage;
private final JLabel jErrorName;
private final JScrollPane jErrorScroll;
private final JLockWindow jLockWindow;
private final ListenerClass listener;
private final Program program;
//Data
private List<UpdateTask> updateTasks;
private int index;
private UpdateTask updateTask;
private Progress progress;
private final TasksCompleted completed;
private final boolean auto;
public TaskDialog(final Program program, final UpdateTask updateTask, boolean totalProgress, boolean minimized, boolean auto, UpdateType updateType, TasksCompleted completed) {
this(program, Collections.singletonList(updateTask), totalProgress, minimized, auto, updateType, completed);
}
public TaskDialog(final Program program, final List<UpdateTask> updateTasks, boolean totalProgress, boolean minimized, boolean auto, UpdateType updateType, TasksCompleted completed) {
this.program = program;
this.updateTasks = updateTasks;
this.completed = completed;
this.auto = auto;
listener = new ListenerClass();
jWindow = new JDialog(program.getMainWindow().getFrame(), JDialog.DEFAULT_MODALITY_TYPE);
jWindow.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
jWindow.setResizable(false);
jWindow.addWindowListener(listener);
jLockWindow = new JLockWindow(jWindow);
JPanel jPanel = new JPanel();
GroupLayout layout = new GroupLayout(jPanel);
jPanel.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
jWindow.add(jPanel);
JLabel jUpdate = new JLabel(DialoguesUpdate.get().updating());
jUpdate.setFont(new Font(jUpdate.getFont().getName(), Font.BOLD, 15));
jMinimize = new JButton(DialoguesUpdate.get().minimize());
jMinimize.setActionCommand(TaskAction.MINIMIZE.name());
jMinimize.addActionListener(listener);
jMinimize.setVisible(updateType != null);
if (updateType != null) {
progress = program.getStatusPanel().addProgress(updateType, new StatusPanel.ProgressControl() {
@Override
public void show() {
progress.setVisible(false);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
jWindow.setVisible(true); //Blocking - do later
}
});
if (progress.isDone()) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
done(); //Needs to be done after showing the dialog (add to EDT queue)
}
});
}
}
@Override
public void cancel() {
cancelUpdate();
}
@Override
public void setPause(boolean pause) {
updateTask.setPause(pause);
}
@Override
public boolean isAuto() {
return auto;
}
});
}
jIcon = new JLabel(new UpdateTask.EmptyIcon());
jProgressBar = new JProgressBar(0, 100);
jTotalProgressBar = new JProgressBar(0, 100);
jTotalProgressBar.setIndeterminate(true);
jOK = new JButton(DialoguesUpdate.get().ok());
jOK.setActionCommand(TaskAction.OK.name());
jOK.addActionListener(listener);
jCancel = new JButton(DialoguesUpdate.get().cancel());
jCancel.setActionCommand(TaskAction.CANCEL.name());
jCancel.addActionListener(listener);
jErrorName = new JLabel("");
jErrorName.setFont(new Font(jErrorName.getFont().getName(), Font.BOLD, 15));
jErrorName.setVisible(false);
jErrorMessage = new JTextPane();
jErrorMessage.setText("");
jErrorMessage.setEditable(false);
jErrorMessage.setFocusable(true);
jErrorMessage.setOpaque(false);
jErrorMessage.setBackground(Colors.COMPONENT_TRANSPARENT.getColor());
jErrorScroll = new JScrollPane(jErrorMessage);
jErrorScroll.setVisible(false);
ParallelGroup horizontalGroup = layout.createParallelGroup(GroupLayout.Alignment.CENTER);
horizontalGroup.addGroup(layout.createSequentialGroup()
.addComponent(jUpdate)
.addGap(0, 0, Integer.MAX_VALUE)
.addComponent(jMinimize)
);
int taskWidth = 230;
for (UpdateTask updateTaskLoop : updateTasks) {
horizontalGroup.addGroup(layout.createSequentialGroup()
.addComponent(updateTaskLoop.getTextLabel(), 100, 100, Integer.MAX_VALUE)
.addComponent(updateTaskLoop.getShowButton(), 20, 20, 20)
.addGap(5)
);
updateTaskLoop.addErrorListener(new ErrorListener(updateTaskLoop));
taskWidth = Math.max(taskWidth, updateTaskLoop.getWidth() + 25);
}
horizontalGroup.addGroup(layout.createSequentialGroup()
.addComponent(jIcon, 16, 16, 16)
.addGap(5)
.addComponent(jProgressBar, taskWidth, taskWidth, taskWidth)
);
if (totalProgress) {
horizontalGroup.addComponent(jTotalProgressBar);
}
horizontalGroup.addGroup(layout.createSequentialGroup()
.addComponent(jOK, Program.getButtonsWidth(), Program.getButtonsWidth(), Program.getButtonsWidth())
.addComponent(jCancel, Program.getButtonsWidth(), Program.getButtonsWidth(), Program.getButtonsWidth())
);
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addGroup(horizontalGroup)
.addGap(5)
.addGroup(layout.createParallelGroup()
.addComponent(jErrorName)
.addComponent(jErrorScroll, WIDTH_LOG, WIDTH_LOG, WIDTH_LOG)
)
);
SequentialGroup verticalGroup = layout.createSequentialGroup();
verticalGroup.addGroup(layout.createParallelGroup()
.addComponent(jUpdate, Program.getButtonsHeight(), Program.getButtonsHeight(), Program.getButtonsHeight())
.addComponent(jMinimize, Program.getButtonsHeight(), Program.getButtonsHeight(), Program.getButtonsHeight())
);
for (UpdateTask updateTaskLoop : updateTasks) {
verticalGroup.addGroup(layout.createParallelGroup()
.addComponent(updateTaskLoop.getTextLabel(), Program.getButtonsHeight(), Program.getButtonsHeight(), Program.getButtonsHeight())
.addComponent(updateTaskLoop.getShowButton(), Program.getButtonsHeight(), Program.getButtonsHeight(), Program.getButtonsHeight())
);
}
verticalGroup.addGroup(
layout.createParallelGroup()
.addComponent(jIcon, Program.getButtonsHeight(), Program.getButtonsHeight(), Program.getButtonsHeight())
.addComponent(jProgressBar, Program.getButtonsHeight(), Program.getButtonsHeight(), Program.getButtonsHeight())
);
if (totalProgress) {
verticalGroup.addComponent(jTotalProgressBar, Program.getButtonsHeight(), Program.getButtonsHeight(), Program.getButtonsHeight());
}
verticalGroup.addGroup(layout.createParallelGroup()
.addComponent(jOK, Program.getButtonsHeight(), Program.getButtonsHeight(), Program.getButtonsHeight())
.addComponent(jCancel, Program.getButtonsHeight(), Program.getButtonsHeight(), Program.getButtonsHeight())
);
layout.setVerticalGroup(
layout.createParallelGroup()
.addGroup(verticalGroup)
.addGroup(layout.createSequentialGroup()
.addComponent(jErrorName)
.addComponent(jErrorScroll)
)
);
if (!updateTasks.isEmpty()) {
index = 0;
update();
setVisible(true, minimized);
}
}
public JDialog getDialog() {
return jWindow;
}
private void update() {
if (index < updateTasks.size()) {
jOK.setEnabled(false);
if (updateTask != null) { //Remove PropertyChangeListener from last updateTask
updateTask.removePropertyChangeListener(listener);
}
updateTask = updateTasks.get(index);
updateTask.addPropertyChangeListener(listener);
updateTask.execute();
} else { //Done
jIcon.setIcon(new UpdateTask.EmptyIcon());
jCancel.setEnabled(false);
if (!auto && progress != null && progress.isVisible()) {
progress.setDone(true);
} else {
done();
}
}
}
private void done() {
if (!auto || jWindow.isVisible()) {
jLockWindow.show(GuiShared.get().updating(), new LockWorkerAdaptor() {
@Override
public void task() {
completed.tasksCompleted(TaskDialog.this);
}
@Override
public void gui() {
jOK.setEnabled(true);
jMinimize.setEnabled(false); //Should not minimize after completed
if (completed instanceof TasksCompletedAdvanced) {
StyledDocument doc = ((TasksCompletedAdvanced) completed).getStyledDocument();
updateErrorDocument(doc);
}
}
@Override
public void hidden() {
if (completed instanceof TasksCompletedAdvanced) {
((TasksCompletedAdvanced) completed).tasksHidden(TaskDialog.this);
}
}
});
} else {
JLockWindow jLockMainFrame = new JLockWindow(getTopWindow(program.getMainWindow().getFrame()));
jLockMainFrame.show(GuiShared.get().updating(), new LockWorkerAdaptor() {
@Override
public void task() {
completed.tasksCompleted(TaskDialog.this);
}
@Override
public void gui() {
setVisible(false);
if (completed instanceof TasksCompletedAdvanced) {
StyledDocument doc = ((TasksCompletedAdvanced) completed).getStyledDocument();
updateErrorDocument(doc);
}
}
@Override
public void hidden() {
if (completed instanceof TasksCompletedAdvanced) {
((TasksCompletedAdvanced) completed).tasksHidden(TaskDialog.this);
}
}
});
}
}
private void updateErrorDocument(StyledDocument doc) {
if (doc == null) {
return;
}
int length = doc.getLength();
for (UpdateTask task : updateTasks) {
task.insertLog(doc);
}
if (doc.getLength() > length) { //If changed
try {
doc.insertString(length, Formater.columnDate(new Date()) + "\n\r", null);
if (length > 0) {
doc.insertString(length, "\n\r", null);
}
} catch (BadLocationException ex) {
//Shouldn't be possible....
}
}
}
private Window getTopWindow(Window in) {
for (Window window : in.getOwnedWindows()) {
if (window.isVisible()) {
return getTopWindow(window);
}
}
return in;
}
private void centerWindow() {
jWindow.pack();
jWindow.setLocationRelativeTo(jWindow.getParent());
}
private void setVisible(final boolean b) {
setVisible(b, false);
}
private void setVisible(final boolean b, boolean minimized) {
if (b) {
centerWindow();
if (minimized) {
if (progress != null) {
progress.setVisible(true);
}
jWindow.setVisible(false);
} else {
if (progress != null) {
progress.setVisible(false);
}
jWindow.setVisible(true);
}
} else { //Memory
for (UpdateTask task : updateTasks) {
for (MouseListener mouseListener : task.getTextLabel().getMouseListeners()) {
task.getTextLabel().removeMouseListener(mouseListener);
}
}
jWindow.removeWindowListener(listener);
jOK.removeActionListener(listener);
jCancel.removeActionListener(listener);
jMinimize.removeActionListener(listener);
updateTask.removePropertyChangeListener(listener);
for (UpdateTask updateTaskLoop : updateTasks) {
updateTaskLoop.removeErrorListener();
}
if (progress != null) {
program.getStatusPanel().removeProgress(progress);
}
jWindow.setVisible(false);
}
}
private void cancelUpdate() {
int cancelledIndex = index;
index = updateTasks.size();
updateTask.addWarning("Update", "Cancelled");
updateTask.cancel(true);
for (int i = cancelledIndex; i < updateTasks.size(); i++) {
updateTasks.get(i).cancelled();
}
jProgressBar.setIndeterminate(false);
jProgressBar.setValue(0);
jIcon.setIcon(new UpdateTask.EmptyIcon());
jMinimize.setEnabled(false); //Should not minimize after cancel
}
private class ListenerClass implements PropertyChangeListener, ActionListener, WindowListener {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
Integer totalProgress = updateTask.getTotalProgress();
if (totalProgress != null && totalProgress > 0 && totalProgress <= 100) {
jTotalProgressBar.setValue(totalProgress);
jTotalProgressBar.setIndeterminate(false);
} else {
jTotalProgressBar.setIndeterminate(true);
}
if (progress != null) {
if (totalProgress != null && totalProgress > 0 && totalProgress <= 100) {
progress.setValue(totalProgress);
progress.setIndeterminate(false);
} else {
progress.setIndeterminate(true);
}
}
int value = updateTask.getProgress();
jIcon.setIcon(updateTask.getIcon());
if (value == 100 && updateTask.isTaskDone()) {
updateTask.setTaskDone(false);
jProgressBar.setValue(100);
jProgressBar.setIndeterminate(false);
index++;
update();
} else if (value > 1) {
jProgressBar.setIndeterminate(false);
jProgressBar.setValue(value);
} else {
jProgressBar.setIndeterminate(true);
}
}
@Override
public void actionPerformed(final ActionEvent e) {
if (TaskAction.OK.name().equals(e.getActionCommand())) {
setVisible(false);
} else if (TaskAction.CANCEL.name().equals(e.getActionCommand())) {
cancelUpdate();
} else if (TaskAction.MINIMIZE.name().equals(e.getActionCommand())) {
progress.setVisible(true);
jWindow.setVisible(false);
}
}
@Override
public void windowOpened(final WindowEvent e) { }
@Override
public void windowClosing(final WindowEvent e) {
if (index >= updateTasks.size()) {
setVisible(false);
} else {
int value = JOptionPane.showConfirmDialog(jWindow, DialoguesUpdate.get().cancelQuestion(), DialoguesUpdate.get().cancelQuestionTitle(), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (value == JOptionPane.YES_OPTION) {
cancelUpdate();
setVisible(false);
}
}
}
@Override
public void windowClosed(final WindowEvent e) { }
@Override
public void windowIconified(final WindowEvent e) { }
@Override
public void windowDeiconified(final WindowEvent e) { }
@Override
public void windowActivated(final WindowEvent e) { }
@Override
public void windowDeactivated(final WindowEvent e) { }
}
public class ErrorListener implements MouseListener, ActionListener {
private final UpdateTask mouseTask;
public ErrorListener(final UpdateTask mouseTask) {
this.mouseTask = mouseTask;
}
@Override
public void actionPerformed(ActionEvent e) {
handleEvent();
}
@Override
public void mouseClicked(final MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
handleEvent();
}
}
@Override
public void mousePressed(final MouseEvent e) { }
@Override
public void mouseReleased(final MouseEvent e) { }
@Override
public void mouseEntered(final MouseEvent e) { }
@Override
public void mouseExited(final MouseEvent e) { }
private void handleEvent() {
if (mouseTask.hasLog()) {
jErrorMessage.setText("");
jErrorName.setText("");
boolean shown = mouseTask.isErrorShown();
for (UpdateTask task : updateTasks) {
task.showLog(false);
}
if (shown) {
mouseTask.showLog(false);
jErrorScroll.setVisible(false);
jErrorName.setVisible(false);
jWindow.pack();
} else {
jErrorScroll.setVisible(true);
jErrorName.setVisible(true);
jWindow.pack();
mouseTask.showLog(true);
mouseTask.insertLog(jErrorMessage);
jErrorName.setText(mouseTask.getName());
}
}
}
}
public static interface TasksCompleted {
public void tasksCompleted(TaskDialog taskDialog);
}
public static interface TasksCompletedAdvanced extends TasksCompleted {
public void tasksHidden(TaskDialog taskDialog);
public StyledDocument getStyledDocument();
}
}
| gpl-2.0 |
PDavid/aTunes | aTunes/src/main/java/net/sourceforge/atunes/model/ILocalAudioObject.java | 2239 | /*
* aTunes
* Copyright (C) Alex Aranda, Sylvain Gaudard and contributors
*
* See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors
*
* http://www.atunes.org
* http://sourceforge.net/projects/atunes
*
* 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.
*/
package net.sourceforge.atunes.model;
import java.io.Serializable;
/**
* An audio object located in disk
*
* @author alex
*
*/
public interface ILocalAudioObject extends IAudioObject,
Comparable<ILocalAudioObject>, Serializable {
/**
* Gets the tag.
*
* @return the tag
*/
ITag getTag();
/**
* Sets the tag.
*
* @param tag
* the new tag
*/
void setTag(ITag tag);
/**
* Gets the name without extension.
*
* @return the name without extension
*/
String getNameWithoutExtension();
/**
* Checks for internal picture.
*
* @return true, if successful
*/
boolean hasInternalPicture();
/**
* Sets duration
*
* @param trackLength
*/
void setDuration(int trackLength);
/**
* Set bitrate
*
* @param bitRateAsNumber
*/
void setBitrate(long bitRateAsNumber);
/**
* @param variable
* bitrate
*/
void setVariableBitrate(boolean variable);
/**
* @return if bitrate is variable
*/
boolean isVariableBitrate();
/**
* Set frequency
*
* @param sampleRateAsNumber
*/
void setFrequency(int sampleRateAsNumber);
/**
* Set when object is read
*
* @param currentTimeMillis
*/
void setReadTime(long currentTimeMillis);
/**
* @return size in bytes
*/
long getSize();
/**
* @return time when audio object was read
*/
long getReadTime();
}
| gpl-2.0 |
ronal2do/fonda56-theme | wp-content/plugins/smio-push-notification/class.controller.php | 10299 | <?php
class smpush_controller extends smpush_helper{
public static $apisetting;
public static $defconnection;
public static $pushdb;
public static $history;
public function __construct(){
$this->get_api_setting();
$this->set_def_connection();
$this->add_rewrite_rules();
$this->cron_setup();
if(self::$defconnection['dbtype'] == 'remote'){
self::$pushdb = new wpdb(self::$defconnection['dbuser'], self::$defconnection['dbpass'], self::$defconnection['dbname'], self::$defconnection['dbhost']);
if(!self::$pushdb){
$this->output(0, 'Connecting with the remote push notification database is failed');
}
}
else{
global $wpdb;
self::$pushdb = $wpdb;
}
self::$pushdb->hide_errors();
}
public function set_def_connection(){
global $wpdb;
self::$defconnection = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."push_connection WHERE id='".self::$apisetting['def_connection']."'", 'ARRAY_A');
}
public static function parse_query($query){
if(preg_match_all("/{([a-zA-Z0-9_]+)}/", $query, $matches)){
foreach($matches[1] AS $match){
if($match == 'ios_name' OR $match == 'android_name')
$query = str_replace('{'.$match.'}', self::$defconnection[$match] , $query);
elseif($match == 'tbname_temp')
$query = str_replace('{'.$match.'}', '`'.self::$defconnection['tbname'].'_temp'.'`' , $query);
else
$query = str_replace('{'.$match.'}', '`'.self::$defconnection[$match].'`' , $query);
}
}
$query = str_replace('{wp_prefix}', SMPUSHTBPRE, $query);
return $query;
}
public static function setting(){
if($_POST){
self::saveOptions();
}
else{
global $wpdb;
$connections = $wpdb->get_results("SELECT id,title FROM ".$wpdb->prefix."push_connection ORDER BY id ASC");
self::loadpage('setting', 1, $connections);
}
}
public static function documentation(){
include(smpush_dir.'/class.documentation.php');
self::load_jsplugins();
$document = new smpush_documentation();
$document = $document->build();
$smpushexurl['auth_key'] = (self::$apisetting['complex_auth']==1)?md5(date('m/d/Y').self::$apisetting['auth_key'].date('H:i')):self::$apisetting['auth_key'];
$smpushexurl['push_basename'] = site_url().'/'.self::$apisetting['push_basename'];
include(smpush_dir.'/pages/documentation.php');
}
public static function loadpage($template, $noheader=0, $params=0){
self::load_jsplugins();
$noheader = ($noheader == 0)?'':'&noheader=1';
$page_url = admin_url().'admin.php?page=smpush_'.$template.$noheader;
include(smpush_dir.'/pages/'.$template.'.php');
}
public static function load_jsplugins(){
wp_enqueue_style('smpush-style');
if(is_rtl()){
wp_enqueue_style('smpush-rtl');
}
wp_enqueue_script('smpush-mainscript');
wp_enqueue_script('smpush-plugins');
}
public static function saveOptions(){
$newsetting = array();
foreach($_POST AS $key=>$value){
if(!in_array($key, array('submit','apple_cert_upload'))){
$newsetting[$key] = $value;
unset(self::$apisetting[$key]);
}
}
$checkbox = array('complex_auth','apple_sandbox','android_titanium_payload','ios_titanium_payload','e_post_chantocats','e_apprpost','e_appcomment','e_newcomment','e_usercomuser','e_postupdated','e_newpost');
foreach($checkbox AS $inptname){
if(!isset($_POST[$inptname]))
self::$apisetting[$inptname] = 0;
}
if(!empty($_FILES['apple_cert_upload']['tmp_name'])){
if(strtolower(substr($_FILES['apple_cert_upload']['name'], strrpos($_FILES['apple_cert_upload']['name'], '.') + 1)) == 'pem'){
$target_path = realpath(dirname(__FILE__)).'/cert_connection_'.$newsetting['def_connection'].'.pem';
if(move_uploaded_file($_FILES['apple_cert_upload']['tmp_name'], $target_path)){
unset(self::$apisetting['apple_cert_path']);
$newsetting['apple_cert_path'] = addslashes($target_path);
}
}
}
self::$apisetting = array_map('addslashes', self::$apisetting);
self::$apisetting = array_merge($newsetting, self::$apisetting);
update_option('smpush_options', self::$apisetting);
echo 1;
die();
}
public static function loadHistory($field, $index=false){
if($index === false){
if(isset(self::$history[$field])){
return self::$history[$field];
}
}
else{
if(isset(self::$history[$field][$index])){
return self::$history[$field][$index];
}
}
return '';
}
public function build_menus(){
add_menu_page('Setting', 'Push Notification', 'activate_plugins', 'smpush_setting', array('smpush_controller', 'setting'), 'div', 4);
add_submenu_page('smpush_setting', 'Send Push Notification', 'Sending Dashboard', 'activate_plugins', 'smpush_send_notification', array('smpush_sendpush', 'send_notification'));
add_submenu_page('smpush_setting', 'Starting Feedback Service', 'Feedback Service', 'activate_plugins', 'smpush_start_feedback', array('smpush_sendpush', 'start_feedback'));
add_submenu_page('smpush_setting', 'Message Archive', 'Message Archive', 'activate_plugins', 'smpush_archive', array('smpush_modules', 'archive'));
add_submenu_page('smpush_setting', 'Manage Connections', 'Manage Connections', 'activate_plugins', 'smpush_connections', array('smpush_modules', 'connections'));
add_submenu_page('smpush_setting', 'Manage Device Token', 'Manage Device Token', 'activate_plugins', 'smpush_tokens', array('smpush_modules', 'tokens'));
add_submenu_page('smpush_setting', 'Push Notification Channels', 'Manage Channels', 'activate_plugins', 'smpush_channel', array('smpush_modules', 'push_channel'));
add_submenu_page('smpush_setting', 'Test Dashboard', 'Test Dashboard', 'activate_plugins', 'smpush_test_sending', array('smpush_modules', 'testing'));
add_submenu_page('smpush_setting', 'Developer Documentation', 'Documentation', 'activate_plugins', 'smpush_documentation', array('smpush_controller', 'documentation'));
add_submenu_page(NULL, 'Sending Push Notification', 'Sending Push Notification', 'activate_plugins', 'smpush_send_process', array('smpush_sendpush', 'send_process'));
add_submenu_page(NULL, 'Queue Push', 'Queue Push', 'activate_plugins', 'smpush_runqueue', array('smpush_sendpush', 'RunQueue'));
add_submenu_page(NULL, 'Cancel Queue Push', 'Cancel Queue Push', 'activate_plugins', 'smpush_cancelqueue', array('smpush_sendpush', 'smpush_cancelqueue'));
add_submenu_page(NULL, 'Active invalid tokens', 'Active invalid tokens', 'activate_plugins', 'smpush_active_tokens', array('smpush_sendpush', 'activateTokens'));
}
public static function register_cron($schedules){
$schedules['smpush_few_days'] = array(
'interval' => 259200,
'display' => __('Once every 3 days')
);
return $schedules;
}
public function cron_setup(){
if(!wp_next_scheduled('smpush_update_counters')){
wp_schedule_event(mktime(3,0,0,date('m'),date('d'),date('Y')), 'daily', 'smpush_update_counters');
}
if(! wp_next_scheduled('smpush_cron_fewdays')){
wp_schedule_event(mktime(15,0,0,date('m'),date('d'),date('Y')), 'smpush_few_days', 'smpush_cron_fewdays');
}
if(get_transient('smpush_update_notice') !== false){
add_action('admin_notices', array('smpush_controller', 'update_notice'));
}
}
public function check_update_notify(){
if(function_exists('curl_init')){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://smartiolabs.com/update/push_notification");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
$data = json_decode(curl_exec($ch));
curl_close($ch);
if($data !== NULL){
if($data->version > SMPUSHVERSION){
set_transient('smpush_update_notice', $data, 60);
}
}
}
}
public static function update_notice(){
$data = get_transient('smpush_update_notice');
delete_transient('smpush_update_notice');
echo '<div class="update-nag"><p><a href="'.$data->link.'" target="_blank">'.$data->plugin.' '.$data->version.'</a> is available! Please download your free update from your Envato account and update now.</p></div>';
}
public static function update_counters(){
global $wpdb;
$defconid = self::$apisetting['def_connection'];
$counter = self::$pushdb->get_var(self::parse_query("SELECT COUNT({id_name}) FROM {tbname} WHERE {active_name}='1'"));
$wpdb->query("UPDATE ".$wpdb->prefix."push_connection SET `counter`='$counter' WHERE id='$defconid'");
}
public static function update_all_counters(){
global $wpdb;
self::update_counters();
$channels = $wpdb->get_results("SELECT id FROM ".$wpdb->prefix."push_channels");
if($channels){
foreach($channels as $channel){
$count = $wpdb->get_var("SELECT COUNT(token_id) FROM ".$wpdb->prefix."push_relation WHERE channel_id='$channel->id'");
$wpdb->query("UPDATE ".$wpdb->prefix."push_channels SET `count`='$count' WHERE id='$channel->id'");
}
}
}
public function get_option($index){
return self::$apisetting[$index];
}
public function get_api_setting(){
self::$apisetting = get_option('smpush_options');
self::$apisetting = array_map('stripslashes', self::$apisetting);
}
public function add_rewrite_rules(){
$apiname = self::$apisetting['push_basename'];
add_rewrite_rule($apiname.'/?$', 'index.php?smpushcontrol=debug', 'top');
add_rewrite_rule($apiname.'/(.+)$', 'index.php?smpushcontrol=$matches[1]', 'top');
}
public function start_fetch_method(){
$method = get_query_var('smpushcontrol');
if(!empty($method))
$smpush_method = new smpush_api($method);
}
public function register_vars($vars){
$vars[] = 'smpushcontrol';
return $vars;
}
}
?> | gpl-2.0 |
milowg/Par-N-Rar | SettingsDlg.cpp | 20833 | // This file is part of Par-N-Rar
// http://www.milow.net/site/projects/parnrar.html
//
// Copyright (c) Gil Milow
//
// Par-N-Rar 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.
//
// Par-N-Rar 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
//
// This code may not be used to develop a RAR (WinRAR) compatible archiver.
//
// SettingsDlg.cpp : implementation file
//
#include "stdafx.h"
#include "resource.h" // main symbols
#include "SettingsDlg.h"
#include <afxhtml.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog dialog
CSettingsDialog::CSettingsDialog(CWnd* pParent /*=NULL*/)
: CDialog(CSettingsDialog::IDD, pParent)
{
//{{AFX_DATA_INIT(CSettingsDialog)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
m_pInfo.RemoveAll(); // Empty the page info
m_csTitle = _T("");
m_pParent = pParent; // Parent wnd pointer, must be null for modal dialog
}
/////////////////////////////////////////////////////////////////////////////
//
CSettingsDialog::~CSettingsDialog()
{
// Clean up garbage
for (int i=0; i<m_pInfo.GetSize(); i++)
{
PAGE_INFO *pInfo = (PAGE_INFO *)m_pInfo.GetAt(i);
if (pInfo)
{
delete pInfo;
}
}
m_pInfo.RemoveAll();
}
void CSettingsDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CSettingsDialog)
DDX_Control(pDX, IDC_PAGE_FRAME, m_PageFrame);
DDX_Control(pDX, IDC_TREE_CTRL, m_TreeCtrl);
DDX_Control(pDX, IDC_CAPTION_BAR, m_CaptionBarCtrl);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CSettingsDialog, CDialog)
//{{AFX_MSG_MAP(CSettingsDialog)
ON_NOTIFY(TVN_SELCHANGED, IDC_TREE_CTRL, OnTreeSelChanged)
//ON_BN_CLICKED(IDC_PREFHELP, OnPreferenceHelp)
ON_BN_CLICKED(IDAPPLY, OnApply)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog message handlers
//
BOOL CSettingsDialog::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
m_PageFrame.GetWindowRect(m_FrameRect);
ScreenToClient(m_FrameRect);
m_FrameRect.DeflateRect(2,2);
SetWindowText(m_csTitle);
// Set some styles for indicator bar
m_CaptionBarCtrl.m_textClr = ::GetSysColor(COLOR_3DFACE);
m_CaptionBarCtrl.m_fontWeight = FW_BOLD;
m_CaptionBarCtrl.m_fontSize = 14;
m_CaptionBarCtrl.m_csFontName = "Verdana";
m_CaptionBarCtrl.SetConstantText(m_csLogoText);
InitTreeCtrl(); // Initialize the tree control with options
ExpandTree();
if (m_pInfo.GetAt(0)) ShowPage(m_pInfo.GetAt(0));
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
/////////////////////////////////////////////////////////////////////////////
//
void CSettingsDialog::InitTreeCtrl()
{
// Fill the tree. we'll create the pages as we need them
for (int i=0; i < m_pInfo.GetSize(); i++)
{
PAGE_INFO *pInfo = (PAGE_INFO *)m_pInfo.GetAt(i);
if (!pInfo) continue;
TV_INSERTSTRUCT tvi;
if (pInfo->pWndParent) tvi.hParent = FindItem(pInfo->pWndParent);
else tvi.hParent = FindItem(pInfo->csParentCaption);
tvi.hInsertAfter = TVI_LAST;
tvi.item.cchTextMax = 0;
tvi.item.pszText = new char[pInfo->csCaption.GetLength() + 1];
strncpy(tvi.item.pszText, pInfo->csCaption.GetBuffer(0), pInfo->csCaption.GetLength());
tvi.item.pszText[pInfo->csCaption.GetLength()] = NULL;
tvi.item.lParam = (long)pInfo;
tvi.item.mask = TVIF_PARAM | TVIF_TEXT;
HTREEITEM hTree = m_TreeCtrl.InsertItem(&tvi);
// Keep track of the pages we've added (for parent selection)
if (hTree && pInfo->pPropPage)
{
DWORD dwTree = (DWORD)hTree;
m_wndMap.SetAt(pInfo->pPropPage, dwTree);
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::AddPage(...)
//
// Description: Add a page specified by CRuntimeClass.
// If pWndClass = NULL, the corresponding tree item has no page
// The page identified by pCaption on the tree control will be inserted
// under the parent tree item identified by pWndParent.
// If pWndParent is NULL, them the page becomes a root item on the
// tree control
// Return value: A CWnd type pointer to the page created if successful,
// otherwise return NULL
//
CWnd* CSettingsDialog::AddPage(CRuntimeClass *pWndClass,
const char *pCaption, UINT nID /* = 0 */,
CWnd *pWndParent /* = NULL */)
{
CPropertyPage* pPropPage = NULL;
if (m_hWnd)
{
// Can't add once the window has been created
ASSERT(0);
return pPropPage;
}
// Create the specified page object
if (pWndClass) pPropPage = (CPropertyPage*) pWndClass->CreateObject();
PAGE_INFO *pInfo = new PAGE_INFO;
pInfo->bViewClass = TRUE; // Default to generic CWnd or CView class
if (pPropPage) // If it is a dialog or dialog-derived class
{ // Set bViewClass = FALSE
if (pPropPage->IsKindOf(RUNTIME_CLASS(CDialog))) pInfo->bViewClass = FALSE;
}
pInfo->nID = nID; // ID of the page
pInfo->pPropPage = pPropPage; // Pointer to the page
pInfo->csCaption = pCaption; // Caption of page in the tree control
pInfo->pWndParent = pWndParent; // Parent of the page if it has one
pInfo->csParentCaption.Empty(); // Parent caption ignored
m_pInfo.Add(pInfo); // Add to the page list
return pPropPage;
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::AddPage(...)
//
// Description: Add a page specified by CRuntimeClass.
// If pWndClass = NULL, the corresponding tree item has no page
// The page identified by pCaption on the tree control will be inserted
// under the parent tree item identified by pParentCaption.
// If pParentCaption is empty, them the page becomes a root item on the
// tree control
// Return value: A CWnd type pointer to the page created if successful,
// otherwise return NULL
//
CWnd* CSettingsDialog::AddPage(CRuntimeClass *pWndClass, const char *pCaption,
UINT nID, const char *pParentCaption)
{
CPropertyPage* pPropPage = NULL;
if (m_hWnd)
{
// Can't add once the window has been created
ASSERT(0);
return pPropPage;
}
// Create the specified page object
if (pWndClass) pPropPage = (CPropertyPage*) pWndClass->CreateObject();
PAGE_INFO *pInfo = new PAGE_INFO;
pInfo->bViewClass = TRUE; // Default to generic CWnd or CView class
if (pPropPage) // If it is a dialog or dialog-derived class
{ // Set bViewClass = FALSE
if (pPropPage->IsKindOf(RUNTIME_CLASS(CDialog))) pInfo->bViewClass = FALSE;
}
pInfo->nID = nID; // ID of the page
pInfo->pPropPage = pPropPage; // Point to the page
pInfo->csCaption = pCaption; // Caption of page in the tree control
pInfo->pWndParent = NULL; // Parent page is not specified yet
pInfo->csParentCaption = pParentCaption; // Parent caption to be inserted under
m_pInfo.Add(pInfo); // Add to to page list
return pPropPage;
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::FindItem(CWnd *pWnd)
//
// Description: Find the tree item indexed by the page pointer pWnd.
//
// Return value: An HTREEITEM is returned. If pWnd = NULL, TVI_ROOT returned
//
HTREEITEM CSettingsDialog::FindItem(CWnd *pWnd)
{
// If you didn't specify a parent in AddPage(...) , the
// dialog becomes a root-level entry
if (pWnd == NULL) return TVI_ROOT;
else
{
DWORD dwHTree;
if (m_wndMap.Lookup(pWnd, dwHTree)) return (HTREEITEM)dwHTree;
else
{
// Specified a parent that has not
// been added to the tree - can't do that.
ASSERT(FALSE);
return (TVI_ROOT);
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::FindItem(const CString &csCaption)
//
// Description: Find the tree item indexed by tree item text csCaption.
//
// Return value: An HTREEITEM is returned.
// TVI_ROOT is returned
// if (1) csCaption = Empty, TVI_ROOT returned
// If (2) the is no match of csCaption on the tree control,
//
HTREEITEM CSettingsDialog::FindItem(const CString &csCaption)
{
if(m_TreeCtrl.GetCount() == 0) return TVI_ROOT; // If the tree is empty
if(csCaption.IsEmpty()) return TVI_ROOT; // If no item text specified
HTREEITEM hCurrent = m_TreeCtrl.GetRootItem();
while(hCurrent)
{
CString strText = m_TreeCtrl.GetItemText(hCurrent);
if(!strText.CompareNoCase(csCaption)) return hCurrent;
hCurrent = GetNextItemCOrS(hCurrent);
}
return TVI_ROOT;
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::GetNextItemCOrS(HTREEITEM hItem)
//
// Description: Get handle of the child or sibling tree item
// indexed by current tree item handle.
//
// Return value: An HTREEITEM is returned.
//
HTREEITEM CSettingsDialog::GetNextItemCOrS(HTREEITEM hItem)
{
HTREEITEM hti;
if( m_TreeCtrl.ItemHasChildren( hItem ) )
return m_TreeCtrl.GetChildItem( hItem ); // return first child
else
{
// Return next sibling item
// Go up the tree to find a parent's sibling if needed.
while( (hti = m_TreeCtrl.GetNextSiblingItem( hItem )) == NULL )
{
if( (hItem = m_TreeCtrl.GetParentItem( hItem ) ) == NULL )
return NULL;
}
}
return hti;
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::ShowPage(const PAGE_INFO *pInfo, UINT nShow /* = SW_SHOW */)
// Description: Display or hide the page if the associated tree item is selected.
// nShow determines whether to display or hide the page.
// pInfo identifies the page to be displayed.
// Note, if the window of the page has not yet ben created
// it will create the page window before the page gets displayed
// Return value: NULL
//
void CSettingsDialog::ShowPage(const PAGE_INFO *pInfo, UINT nShow /* = SW_SHOW */)
{
if (!pInfo) return;
m_CaptionBarCtrl.SetWindowText(""); // Clear the caption bar
if (pInfo->pPropPage) // If the page is valid
{
if (!::IsWindow(pInfo->pPropPage->m_hWnd))
{ // Window has not been created, create it
CreatePage(pInfo);
pInfo->pPropPage->SetWindowPos (&m_TreeCtrl,0,0,0,0,0);
pInfo->pPropPage->MoveWindow(m_FrameRect.left, m_FrameRect.top, m_FrameRect.Width(), m_FrameRect.Height());
if( pInfo->pPropPage->IsKindOf( RUNTIME_CLASS(CView) ) )
((CView*)pInfo->pPropPage)->OnInitialUpdate();
}
pInfo->pPropPage->ShowWindow(nShow); // Show or hide the window
if (nShow == SW_SHOW) // Change the tree selection
{
pInfo->pPropPage->SetFocus();
HTREEITEM hItem = FindItem(pInfo->pPropPage);
if (hItem) m_TreeCtrl.SelectItem(hItem);
}
}
if (nShow == SW_SHOW) // Update caption bar
m_CaptionBarCtrl.SetWindowText(pInfo->csCaption);
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::CreatePage(const PAGE_INFO *pInfo)
// Description: Create the Window of the page specified by the page info.
// Return value: TRUE if successful, or FALSE if failed
//
BOOL CSettingsDialog::CreatePage(const PAGE_INFO *pInfo)
{
BOOL bCode = FALSE;
if (!pInfo || !pInfo->pPropPage) return(FALSE); // If no page is specified, return NULL
if (!::IsWindow(pInfo->pPropPage->m_hWnd)) // If the window has not yet been created,
{
if (pInfo->pPropPage->IsKindOf(RUNTIME_CLASS(CDialog))) // If the page indow is kind of dialog window
{
CDialog *pDlg = (CDialog*)pInfo->pPropPage;
bCode = pDlg->Create(pInfo->nID, this);
pDlg->ModifyStyle(WS_CAPTION, 0);
}
else if (pInfo->pPropPage->IsKindOf(RUNTIME_CLASS(CWnd))) // generic CWnd derived Window
{
CWnd *pWnd = (CWnd*)pInfo->pPropPage;
bCode = CreateWnd(pInfo->pPropPage); // Create Window
pWnd->ModifyStyle(WS_BORDER|WS_THICKFRAME, 0); // Remoce border and thick frame styles
}
}
return(bCode);
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::CreateWnd(CWnd *pWnd, CCreateContext *pContext /* = NULL */)
// Description: Create generic CWnd based Window of a page
// Return value: TRUE if successful, NULL if failed
//
BOOL CSettingsDialog::CreateWnd(CWnd *pWnd, CCreateContext *pContext /* = NULL */)
{
CCreateContext context;
if (pContext == NULL)
{
// If no context specified, generate one from the currently selected
// client if possible
context.m_pCurrentFrame = (CFrameWnd*) this;
context.m_pCurrentDoc = NULL;
context.m_pNewViewClass = NULL;
pContext = &context;
}
ASSERT_KINDOF(CWnd, pWnd);
ASSERT(pWnd->m_hWnd == NULL); // Not yet created
DWORD dwStyle = AFX_WS_DEFAULT_VIEW;
CRect rect;
// Create with the right size and position
if (!pWnd->Create(NULL, NULL, dwStyle, rect, this, 0, pContext))
{
TRACE0("Warning: couldn't create wnd in CSettingsDialog.\n");
// pWnd will be cleaned up by PostNcDestroy
return FALSE;
}
return(TRUE);
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::OnTreeSelChanged(NMHDR* pNMHDR, LRESULT* pResult)
// Description: Notification Handler for selection change of the tree control
// Return value: NULL
//
void CSettingsDialog::OnTreeSelChanged(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
// TODO: Add your control notification handler code here
if (pNMTreeView->itemNew.lParam)
{ // Get previous selected page
PAGE_INFO *pInfo = (PAGE_INFO *) pNMTreeView->itemOld.lParam;
ShowPage(pInfo, SW_HIDE); // Hide the page
// Get current selected page
pInfo = (PAGE_INFO *) pNMTreeView->itemNew.lParam;
ShowPage(pInfo, SW_SHOW); // Show the page
}
*pResult = 0;
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::OnCancel()
// Description: Handler of the Cancel button of the dialog
//
void CSettingsDialog::OnCancel()
{
// TODO: Add extra cleanup here
if ( m_pParent != NULL ) // Modaless dialog case
{
// Inform the parent, the modaless case
m_pParent->PostMessage( WM_SETTINGSDIALOG_CLOSE, IDCANCEL, 0 );
}
else // Modal dialog case
{
DestroyPages(); // Destroy the Windows of the setting pages
CDialog::OnCancel();
}
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::OnApply()
// Description: Handler of the Apply button. When the Apply botton is click, the dialog
// is still displayed, but the IDAPPLY message is sent to its parent window
// to update the settings of the project.
//
void CSettingsDialog::OnApply()
{
// TODO: Add your control notification handler code here
if (RefreshData() == FALSE)
return;
if (m_pParent) // Modaless dialog case
{
// Inform the parent, the modaless case
m_pParent->PostMessage( WM_SETTINGSDIALOG_CLOSE, IDAPPLY, 0 );
}
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::OnOK()
// Description: Handler of the OK button
//
void CSettingsDialog::OnOK()
{
// TODO: Add extra validation here
if (RefreshData() == FALSE)
return;
if ( m_pParent != NULL ) // Modaless dialog case
{
// Inform the parent, the modaless case
m_pParent->PostMessage( WM_SETTINGSDIALOG_CLOSE, IDOK, 0 );
}
else // Modal dialog case
{
DestroyPages(); // First destroy all the pages
CDialog::OnOK();
}
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::RefreshData()
// Description: Clean up function if OK and Apply buttons are clicked
// Return value: TRUE if successful, or FALSE if failed
//
BOOL CSettingsDialog::RefreshData()
{
PAGE_INFO *pInfoErr = NULL, *pInfo;
//First check data
for (int i = 0; i < m_pInfo.GetSize(); i++)
{
pInfo = (PAGE_INFO *)m_pInfo.GetAt(i);
if (pInfo && pInfo->pPropPage)
{
if (::IsWindow(pInfo->pPropPage->m_hWnd))
if (pInfo->pPropPage->OnWizardFinish() == FALSE)
return FALSE;
}
}
//Do actual updates
for (int i = 0; i < m_pInfo.GetSize(); i++)
{
pInfo = (PAGE_INFO *)m_pInfo.GetAt(i);
if (pInfo && pInfo->pPropPage)
{
if (::IsWindow(pInfo->pPropPage->m_hWnd))
pInfo->pPropPage->OnApply();
}
}
return (TRUE);
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::DestroyPages()
// Destoy all the page Windows if the dialog is dismissed
// Return value: TRUE if successful, or FALSE if failed
//
BOOL CSettingsDialog::DestroyPages()
{
for (int i=0; i<m_pInfo.GetSize(); i++)
{
PAGE_INFO *pInfo = (PAGE_INFO *)m_pInfo.GetAt(i);
if (pInfo && pInfo->pPropPage)
{
if (::IsWindow(pInfo->pPropPage->m_hWnd))
{
pInfo->pPropPage->DestroyWindow();
if (!(pInfo->bViewClass))
{
delete(pInfo->pPropPage);
pInfo->pPropPage=NULL;
}
}
else
{
delete(pInfo->pPropPage);
pInfo->pPropPage=NULL;
}
}
delete pInfo;//delete
pInfo=NULL;
}
m_pInfo.RemoveAll();
return(true);
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::OnPreferenceHelp()
// Description: Handler for Help button
//
void CSettingsDialog::OnPreferenceHelp()
{
// TODO: Add your control notification handler code here
HTREEITEM hItem = m_TreeCtrl.GetSelectedItem();
if (!hItem) return;
PAGE_INFO *pInfo = (PAGE_INFO *) m_TreeCtrl.GetItemData(hItem);
if (!pInfo || !pInfo->pPropPage) return;
if (::IsWindow(pInfo->pPropPage->m_hWnd))
{
// Help!
NMHDR nm;
nm.code = PSN_HELP;
nm.hwndFrom = m_hWnd;
nm.idFrom = CSettingsDialog::IDD;
pInfo->pPropPage->SendMessage(WM_NOTIFY, 0, (long)&nm);
}
}
/////////////////////////////////////////////////////////////////////////////
//
BOOL CSettingsDialog::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
ASSERT(pMsg != NULL);
ASSERT_VALID(this);
ASSERT(m_hWnd != NULL);
// Don't let CDialog process the Escape key.
if ((pMsg->message == WM_KEYDOWN) && (pMsg->wParam == VK_ESCAPE))
return TRUE;
if (CWnd::PreTranslateMessage(pMsg)) return TRUE;
// Don't translate dialog messages when
// application is in help mode
CFrameWnd* pFrameWnd = GetTopLevelFrame();
if (pFrameWnd != NULL && pFrameWnd->m_bHelpMode) return FALSE;
// Ensure the dialog messages will not
// eat frame accelerators
pFrameWnd = GetParentFrame();
while (pFrameWnd != NULL)
{
if (pFrameWnd->PreTranslateMessage(pMsg)) return TRUE;
pFrameWnd = pFrameWnd->GetParentFrame();
}
return PreTranslateInput(pMsg);
// return CDialog::PreTranslateMessage(pMsg);
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::SetTitle(CString sTitle)
// Description: Change the title of the dialog
void CSettingsDialog::SetTitle(CString sTitle)
{
m_csTitle = sTitle;
}
/////////////////////////////////////////////////////////////////////////////
// CSettingsDialog::SetLogoText(CString sText)
// Description: Set the logo text in caption window
//
void CSettingsDialog::SetLogoText(CString sText)
{
m_csLogoText= sText;
}
/////////////////////////////////////////////////////////////////////////////
//
void CSettingsDialog::ExpandTree()
{
HTREEITEM hti = m_TreeCtrl.GetRootItem();
while (hti)
{
ExpandBranch(hti);
hti = m_TreeCtrl.GetNextSiblingItem(hti);
}
}
/////////////////////////////////////////////////////////////////////////////
//
void CSettingsDialog::ExpandBranch(HTREEITEM hti)
{
if( m_TreeCtrl.ItemHasChildren( hti ) )
{
m_TreeCtrl.Expand( hti, TVE_EXPAND );
hti = m_TreeCtrl.GetChildItem( hti );
do
{
ExpandBranch( hti );
} while( (hti = m_TreeCtrl.GetNextSiblingItem( hti )) != NULL );
}
m_TreeCtrl.EnsureVisible( m_TreeCtrl.GetSelectedItem() );
}
/////////////////////////////////////////////////////////////////////////////
//
BOOL CSettingsDialog::Create()
{
return CDialog::Create(CSettingsDialog::IDD);
}
| gpl-2.0 |
murraycu/prefixsuffix | src/string_renamer.cc | 3449 | /** Copyright (C) 2002-2015 The PrefixSuffix Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#include "string_renamer.h"
#include <iostream>
#include <glibmm/i18n.h>
namespace PrefixSuffix {
StringRenamer::StringRenamer(const Glib::ustring& prefix_replace,
const Glib::ustring prefix_with, const Glib::ustring& suffix_replace,
const Glib::ustring suffix_with)
: m_prefix_replace(prefix_replace)
, m_prefix_with(prefix_with)
, m_suffix_replace(suffix_replace)
, m_suffix_with(suffix_with)
, m_prefix(!prefix_replace.empty() || !prefix_with.empty())
, m_suffix(!suffix_replace.empty() || !suffix_with.empty())
{
}
StringRenamer::~StringRenamer()
{
}
Glib::ustring
StringRenamer::get_new_basename(const Glib::ustring& basename) const
{
Glib::ustring filename_new;
// Prefix:
if (m_prefix) {
if (!m_prefix_replace.empty()) // If an old prefix was specified
{
// If the old prefix is there:
Glib::ustring::size_type posPrefix = basename.find(m_prefix_replace);
if (posPrefix == 0) {
// Remove old prefix:
filename_new = basename.substr(m_prefix_replace.size());
// Add new prefix:
filename_new = m_prefix_with + filename_new;
} else {
// No change:
filename_new = basename;
}
} else {
// There's no old prefix to find, so just add the new prefix:
filename_new = m_prefix_with + basename;
}
}
// Suffix:
if (m_suffix) {
// If the old suffix is there:
if (!m_suffix_replace.empty()) // if an old suffix was specified
{
const Glib::ustring::size_type posSuffix =
basename.rfind(m_suffix_replace);
if (posSuffix != Glib::ustring::npos &&
((basename.size() - posSuffix) ==
m_suffix_replace.size())) // if it was found, and if these were the
// last characters in the string.
{
// Remove old suffix:
filename_new = basename.substr(0, posSuffix);
// Add new suffix:
filename_new += m_suffix_with;
} else {
// No change:
filename_new = basename;
}
} else {
// There's no old suffix to find, so just add the new suffix:
filename_new += m_suffix_with;
}
}
return filename_new;
}
void
StringRenamer::debug_cout() const
{
std::cout << G_STRFUNC << ":" << std::endl
<< " m_prefix: " << m_prefix << std::endl
<< " m_suffix: " << m_suffix << std::endl
<< " m_prefix_replace: " << m_prefix_replace << std::endl
<< " m_prefix_with: " << m_prefix_with << std::endl
<< " m_suffix_replace: " << m_suffix_replace << std::endl
<< " m_suffix_with: " << m_suffix_with << std::endl;
}
} // namespace PrefixSuffix
| gpl-2.0 |
joshalbrecht/memdam | memdam/recorder/collector/osx/webcam.py | 896 |
import os
import tempfile
import subprocess
import memdam.common.event
import memdam.recorder.collector.collector
class WebcamCollector(memdam.recorder.collector.collector.Collector):
'''
Collects snapshots from webcam by using external universal (osx) binary wacaw
'''
def _collect(self, limit):
handle, screenshot_file = tempfile.mkstemp('')
#TODO: when packaging, make this path correct...
exe = './bin/wacaw'
if not os.path.exists(exe):
exe = './wacaw'
command = '%s %s && mv %s.jpeg %s.jpg' % (exe, screenshot_file, screenshot_file, screenshot_file)
subprocess.check_call(command, shell=True)
screenshot_file += '.jpg'
screenshot = self._save_file(screenshot_file, consume_file=True)
os.close(handle)
return [memdam.common.event.new(u'com.memdam.webcam', data__file=screenshot)]
| gpl-2.0 |
Voskrese/mipsonqemu | user/uc/home/114/admin/controllers/ctl_trade_class.php | 4673 | <?php
/**
* 行业分类管理控制器
*
* @author eric <0o0zzyZ@gmail.com>
* @version $Id: ctl_trade_class.php 1542 2009-12-11 08:03:41Z syh $
*/
!defined('PATH_ADMIN') && exit('Forbidden');
class ctl_trade_class
{
/**
* 分类列表
*/
public function index()
{
try
{
app_tpl::assign( 'npa', array('专题管理', '行业分类列表') );
if( isset($_POST['commit']) && $_POST['commit'] == 1)
{
if( $_GET['type'] == 'home' )
{
$_POST['io'] = true;
}
mod_trade_class::update_class( $_POST, $_POST['action'] );
mod_login::message("保存成功!");
}
$class_id = isset($_GET['classid']) ? $_GET['classid'] : '';
$class_list = mod_trade_class::get_subclass_list(0);
app_tpl::assign( 'classid', $class_id );
app_tpl::assign( 'type', $type );
app_tpl::assign( 'class_list', $class_list );
app_tpl::assign( 'option_toggle', array( 0 => '否', 1 => '是' ) );
}
catch( Exception $e )
{
app_tpl::assign('error', $e->getMessage());
}
}
/**
* 添加分类
*/
public function add()
{
try
{
app_tpl::assign( 'npa', array('专题管理', '新增行业分类') );
if(isset($_POST['classnewname']))
{
mod_trade_class::add_class( $_POST );
if(!empty($_POST['mkhtml']))
{
//同时生成页面
}
}
app_tpl::assign( 'action', 'add' );
}
catch( Exception $e )
{
app_tpl::assign('error', $e->getMessage());
}
}
/**
* 修改分类
*/
public function edit()
{
try
{
app_tpl::assign( 'npa', array('专题管理', '编辑行业分类') );
$id = isset($_GET['id']) ? intval($_GET['id']) : '';
if( $_POST )
{
mod_trade_class::edit_class( $_POST );
if(!empty($_POST['mkhtml']))
{
//同时生成页面
}
$_GET['classid'] = isset($_POST['classid']) ? $_POST['classid'] : '';
}
app_tpl::assign( 'action', 'edit' );
app_tpl::assign( 'classid', $_GET['classid']);
app_tpl::assign( 'type', $_GET['type'] );
app_tpl::assign( 'returnid', $_GET['classid'] );
app_tpl::assign( 'info', mod_trade_class::get_a_class( $id ) );
}
catch( Exception $e )
{
app_tpl::assign('error', $e->getMessage());
}
}
/**
* 删除分类
*/
public function del()
{
try
{
if( !isset($_GET['id']) )
{
throw new Exception('id不能为空');
}
mod_trade_class::delete_class_and_update_cache( intval($_GET['id']) );
}
catch( Exception $e )
{
app_tpl::assign('error', $e->getMessage());
}
}
/**
* 搜索分类
*/
public function search()
{
try
{
if( isset($_GET['k']) )
{
header("Content-type: text/html; charset=utf-8");
echo json_encode(mod_trade_class::search_class($_GET['k']));
}
exit;
}
catch( Exception $e )
{
app_tpl::assign('error', $e->getMessage());
}
}
/**
* ajax获取分类列表
*/
public function ajax_get_list()
{
if( isset($_GET['id']) )
{
$id = intval($_GET['id']);
$varname = isset($_GET['var']) ? trim($_GET['var']) : 'list';
header("Content-type: text/html; charset=utf-8");
$result = mod_trade_class::get_subclass_list($_GET['id']);
if(empty($result))
{
echo json_encode($result);
exit;
}
foreach($result as &$tmp)
{
$tmp['classname'] = $tmp['classname'];
}
echo 'var ',$varname,'=',json_encode($result);
}
exit;
}
/**
* post钩子方法
*/
public function post()
{
try
{
app_tpl::display( 'trade_class_list.tpl' );
}
catch( Exception $e )
{
app_tpl::assign('error', $e->getMessage());
}
}
}
?>
| gpl-2.0 |
germaaan/trabajos_universidad | 2GII/PDOO/practica_02/java/Jugador.java | 1382 | package munchkin_cthulhu;
import java.util.ArrayList;
import java.util.Iterator;
/**
*
* @author Germán Martínez Maldonado
* @author José Rubén Sánchez Iruela
* @author Pablo Sánchez Robles
*/
public class Jugador {
private String nombre;
private int nivel;
private ArrayList<Tesoro> visibles;
private ArrayList<Tesoro> ocultos;
public Jugador(String unNombre) {
this.nombre = unNombre;
this.nivel = 1;
this.visibles = new ArrayList<Tesoro>();
this.ocultos = new ArrayList<Tesoro>();
}
public void modificarNivel(int incDec) {
this.nivel += incDec;
//Si un jugador muere, pierde todos sus tesoros y se queda a nivel 1.
if (this.nivel <= 0) {
this.visibles.clear();
this.ocultos.clear();
this.nivel = 1;
}
}
public int obtenerNivel() {
return this.nivel;
}
public String obtenerNombre() {
return this.nombre;
}
int nivelDeCombate() {
int nivelDeCombate = nivel;
//Se suma a su nivel básico el nivel de todos sus tesoros.
Iterator<Tesoro> itrVisibles = visibles.iterator();
while (itrVisibles.hasNext()) {
Tesoro elemento = itrVisibles.next();
nivelDeCombate += elemento.obtenerBonus();
}
return nivelDeCombate;
}
}
| gpl-2.0 |
lavigor/QuickReply | language/es/quickreply.php | 1617 | <?php
/**
*
* @package QuickReply Reloaded
* @copyright (c) 2014 - 2016 Tatiana5 and LavIgor
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2
*
*/
/**
* DO NOT CHANGE
*/
if (!defined('IN_PHPBB'))
{
exit;
}
if (empty($lang) || !is_array($lang))
{
$lang = array();
}
$lang = array_merge($lang, array(
'QR_BBPOST' => 'Fuente del Mensaje',
'QR_INSERT_TEXT' => 'Insertar cita en el formulario de Respuesta Rápida',
'QR_PROFILE' => 'Ir al Perfil',
'QR_QUICKNICK' => 'Referir el nombre de usuario',
'QR_QUICKNICK_TITLE' => 'Insertar nombre de usuario en el formulario de Respuesta Rápida',
'QR_REPLY_IN_PM' => 'Responder en MP',
//begin mod Translit
'QR_TRANSLIT_TEXT' => 'Traducir',
'QR_TRANSLIT_TEXT_TO_RU' => 'a Ruso',
'QR_TRANSLIT_TEXT_TOOLTIP' => 'Para visión instantánea en Ruso haga clic en el botón',
//end mod Translit
//begin mod CapsLock Transform
'QR_TRANSFORM_TEXT' => 'Cambiar caso del texto:',
'QR_TRANSFORM_TEXT_TOOLTIP' => 'Presione un botón para cambiar el caso del texto seleccionado',
'QR_TRANSFORM_TEXT_LOWER' => '▼ abc',
'QR_TRANSFORM_TEXT_UPPER' => '▲ ABC',
'QR_TRANSFORM_TEXT_INVERS' => '▼▲ aBC',
'QR_TRANSFORM_TEXT_LOWER_TOOLTIP' => 'minúscula',
'QR_TRANSFORM_TEXT_UPPER_TOOLTIP' => 'MAYÚSCULAS',
'QR_TRANSFORM_TEXT_INVERS_TOOLTIP' => 'cSASO iNVERTIDO',
//end mod CapsLock Transform
));
| gpl-2.0 |
blablack/ams-lv2 | src/lfo2_freq_ttl.hpp | 690 | #ifndef ams_lv__lfo__freq_ttl_hpp
#define ams_lv__lfo__freq_ttl_hpp
#ifndef PEG_STRUCT
#define PEG_STRUCT
typedef struct {
float min;
float max;
float default_value;
char toggled;
char integer;
char logarithmic;
} peg_data_t;
#endif
/* <http://github.com/blablack/ams-lv2/lfo2_freq> */
static const char p_uri[] = "http://github.com/blablack/ams-lv2/lfo2_freq";
enum p_port_enum {
p_reset,
p_waveForm,
p_freq,
p_phi0,
p_output,
p_n_ports
};
static const peg_data_t p_ports[] = {
{ -1, 1, 0, 0, 0, 0 },
{ 0, 5, 0, 0, 0, 0 },
{ 0.0001, 100, 5, 0, 0, 0 },
{ 0, 6.28, 0, 0, 0, 0 },
{ -1, 1, 0, 0, 0, 0 },
};
#endif /* ams_lv__lfo__freq_ttl_hpp */
| gpl-2.0 |
pavanratnakar/selebrations.pavanratnakar.com | wp-content/themes/abundance/js/aviaslider-dev.js | 22622 | /**
* AviaSlider - A jQuery image slider
* (c) Copyright Christian "Kriesi" Budschedl
* http://www.kriesi.at
* http://www.twitter.com/kriesi/
* For sale on ThemeForest.net
*/
/* this prevents dom flickering, needs to be outside of dom.ready event: */
document.documentElement.className += ' js_active ';
/*end dom flickering =) */
(function($)
{
$.fn.aviaSlider= function(variables)
{
var defaults =
{
blockSize: {height: 'full', width:'full'},
autorotationSpeed:3, // duration between autorotation switch in Seconds
slides: 'li', // wich element inside the container should serve as slide
animationSpeed: 900, // animation duration
autorotation: true, // autorotation true or false?
appendControlls: '', // element to apply controlls to
slideControlls: 'items', // controlls, yes or no?
betweenBlockDelay:60,
display: 'topleft',
switchMovement: false,
showText: true,
captionReplacement: false, //if this is set the element will be used for caption instead of the alt tag
transition: 'fade', //slide, fade or drop
backgroundOpacity:0.8, // opacity for background
transitionOrder: ['diagonaltop', 'diagonalbottom','topleft', 'bottomright', 'random'],
hideArrows: true
};
return this.each(function()
{
var options = $.extend(defaults, variables);
var slideWrapper = $(this), //wrapper element
optionsWrapper = slideWrapper.parents('.slideshow_container'), //optionswrapper: contains classnames that override passed js values
slides = slideWrapper.find(options.slides), //single slide container
slideImages = slides.find('img'), //slide image within container
slideCount = slides.length, //number of slides
slideWidth = slides.width(), //width of slidecontainer
slideHeight= slides.height(), //height of slidecontainer
blockNumber = 0, //how many blocks do we need
currentSlideNumber = 0, //which slide is currently shown
reverseSwitch = false, //var to set the starting point of the transition
currentTransition = 0, //var to set which transition to display when rotating with 'all'
current_class = 'active_item', //currently active controller item
controlls = '',
controllThumbs = optionsWrapper.find('.thumbnails_container li'),
skipSwitch = true, //var to check if performing transition is allowed
interval ='',
blockSelection ='',
blockSelectionJQ ='',
arrowControlls = '',
blockOrder = [];
//slider methods that controll the whole behaviour of the slideshow
slideWrapper.methods = {
options_overwrite: function()
{
if(optionsWrapper.length)
{
var block_width = /block_width__(\d+|full)/,
block_height = /block_height__(\d+|full)/,
transition = /transition_type__(slide|fade|drop)/,
autoInterval = /autoslidedelay__(\d+)/;
direction = /direction__(\w+)/;
var matchWidth = block_width.exec(optionsWrapper[0].className),
matchHeight = block_height.exec(optionsWrapper[0].className),
matchTrans = transition.exec(optionsWrapper[0].className),
matchInterval = autoInterval.exec(optionsWrapper[0].className),
matchDirection = direction.exec(optionsWrapper[0].className);
if(matchWidth != null) { options.blockSize.width = matchWidth[1]; }
if(matchHeight != null) { options.blockSize.height = matchHeight[1]; }
if(matchTrans != null) { options.transition = matchTrans[1]; }
if(matchInterval != null) { options.autorotationSpeed = matchInterval[1]; }
if(matchDirection != null)
{
if(matchDirection[1] == 'all') options.transitionOrder = ['diagonaltop', 'diagonalbottom','topleft', 'bottomright', 'random'];
if(matchDirection[1] == 'diagonal') options.transitionOrder = ['diagonaltop', 'diagonalbottom'];
if(matchDirection[1] == 'winding') options.transitionOrder = ['topleft', 'bottomright'];
if(matchDirection[1] == 'random') options.transitionOrder = ['random'];
}
if(optionsWrapper.is('.autoslide_false')) options.autorotation = false;
if(optionsWrapper.is('.autoslide_true')) options.autorotation = true;
}
},
//initialize slider and create the block with the size set in the default/options object
init: function()
{
slideWrapper.methods.options_overwrite();
//check if either width or height should be full container width
if (options.blockSize.height == 'full')
{
options.blockSize.height = slideHeight;
}
else
{
options.blockSize.height = parseInt(options.blockSize.height)
}
if (options.blockSize.width == 'full')
{
options.blockSize.width = slideWidth;
}
else
{
options.blockSize.width = parseInt(options.blockSize.width)
}
var posX = 0,
posY = 0,
generateBlocks = true,
bgOffset = '';
// make sure to display the first image in the list at the top
slides.filter(':first').css({'z-index':'3',display:'block'});
// start generating the blocks and add them until the whole image area
// is filled. Depending on the options that can be only one div or quite many ;)
while(generateBlocks)
{
blockNumber ++;
bgOffset = "-"+posX +"px -"+posY+"px";
$('<div class="kBlock"></div>').appendTo(slideWrapper).css({
zIndex:20,
position:'absolute',
display:'none',
left:posX,
top:posY,
height:options.blockSize.height,
width:options.blockSize.width,
backgroundPosition:bgOffset
});
posX += options.blockSize.width;
if(posX >= slideWidth)
{
posX = 0;
posY += options.blockSize.height;
}
if(posY >= slideHeight)
{
//end adding Blocks
generateBlocks = false;
}
}
//setup directions
blockSelection = slideWrapper.find('.kBlock');
blockOrder['topleft'] = blockSelection;
blockOrder['bottomright'] = $(blockSelection.get().reverse());
blockOrder['diagonaltop'] = slideWrapper.methods.kcubit(blockSelection);
blockOrder['diagonalbottom'] = slideWrapper.methods.kcubit(blockOrder['bottomright']);
blockOrder['random'] = slideWrapper.methods.fyrandomize(blockSelection);
//save image in case of flash replacements, will be available in the the next script version
slides.each(function()
{
$.data(this, "data", { img: $(this).find('img').attr('src')});
});
if(slideCount <= 1)
{
slideWrapper.aviaImagePreloader();
}
else
{
slideWrapper.aviaImagePreloader({},slideWrapper.methods.preloadingDone);
slideWrapper.methods.appendControlls();
slideWrapper.methods.appendControllArrows();
}
slideWrapper.methods.addDescription();
slideWrapper.methods.videoBehaviour();
},
videoBehaviour: function()
{
var videoItem, videoSlide, imageSlide;
slides.each(function()
{
imageSlide= $('img', this);
videoItem = $('.slideshow_video', this);
embedVideo = $('.avia_video, iframe, embed, object', this);
videoSlide = $(this);
if((imageSlide.length && videoItem.length) || (imageSlide.length && embedVideo.length))
{
videoSlide.addClass('comboslide').append('<span class="slideshow_overlay"></span>');
}
if(videoItem.length)
{
videoSlide.addClass('videoSlideContainer');
}
else if(embedVideo.length)
{
videoSlide.addClass('videoSlideContainerEmbed');
}
});
$('.videoSlideContainer img, .videoSlideContainer .slideshow_overlay', slideWrapper).bind('click', function()
{
var parent = $(this).parents('li:eq(0)');
parent.find('img, .slideshow_overlay').fadeOut();
parent.find('.slideshow_video').stop().fadeIn();
});
},
//appends the click controlls after an element, if that was set in the options array
appendControlls: function()
{
if (options.slideControlls == 'items')
{
var elementToAppend = options.appendControlls || slideWrapper[0];
controlls = $('<div></div>').addClass('slidecontrolls').insertAfter(elementToAppend);
slides.each(function(i)
{
var controller = $('<a href="#" class="ie6fix '+current_class+'"></a>').appendTo(controlls);
controller.bind('click', {currentSlideNumber: i}, slideWrapper.methods.switchSlide);
current_class = "";
});
controlls.width(controlls.width()).css('float','none');
}
return this;
},
appendControllArrows: function()
{
var elementToAppend = options.appendControlls || slideWrapper[0];
arrowControlls = $('<div></div>').insertAfter(elementToAppend)
.addClass('arrowslidecontrolls');
arrowControlls.html('<a class="ctrl_fwd ctrl_arrow" href=""></a><a class="ctrl_back ctrl_arrow" href=""></a>');
$('.ctrl_back', arrowControlls).bind('click', {currentSlideNumber: 'prev'}, slideWrapper.methods.switchSlide);
$('.ctrl_fwd', arrowControlls).bind('click', {currentSlideNumber: 'next'}, slideWrapper.methods.switchSlide);
if(options.hideArrows)
{
var arrowItems = arrowControlls.find('a');
arrowItems.css({opacity:0});
slideWrapper.hover(
function()
{
arrowItems.stop().animate({'opacity':1});
},
function(event)
{
if(!$(event.relatedTarget).is('.ctrl_arrow'))
{
arrowItems.stop().animate({'opacity':0});
}
}
);
}
},
// adds the image description from an alttag
addDescription: function()
{
if(options.showText)
{
slides.each(function()
{
var currentSlide = $(this);
if(options.captionReplacement)
{
var description = currentSlide.find(options.captionReplacement).css({display:'block','opacity':options.backgroundOpacity});
}
else
{
var description = currentSlide.find('img').attr('alt'),
splitdesc = description.split('::');
if(splitdesc[0] != "" )
{
if(splitdesc[1] != undefined )
{
description = "<strong>"+splitdesc[0] +"</strong>"+splitdesc[1];
}
else
{
description = splitdesc[0];
}
}
if(description != "")
{
$('<div></div>').addClass('slideshow_caption')
.html(description)
.css({display:'block', 'opacity':options.backgroundOpacity})
.appendTo(currentSlide.find('a'));
}
}
});
}
},
preloadingDone: function()
{
skipSwitch = false;
optionsWrapper.data('animationActive', false);
if($.browser.msie)
{
slides.css({'backgroundColor':'#000000','backgroundImage':'none'});
}
else
{
slides.css({'backgroundImage':'none'});
}
if(options.autorotation && options.autorotation != 2)
{
slideWrapper.methods.autorotate();
slideImages.bind("click", function(){ clearInterval(interval); });
}
},
autorotate: function()
{
var time = parseInt(options.autorotationSpeed) * 1000 + parseInt(options.animationSpeed) + (parseInt(options.betweenBlockDelay) * blockNumber);
interval = setInterval(function()
{
currentSlideNumber ++;
if(currentSlideNumber == slideCount) currentSlideNumber = 0;
slideWrapper.methods.switchSlide();
},
time);
},
switchSlide: function(passed)
{
var noAction = false;
if(passed != undefined && !skipSwitch)
{
if(currentSlideNumber != passed.data.currentSlideNumber)
{
if(passed.data.currentSlideNumber == 'next')
{
currentSlideNumber = currentSlideNumber + 1;
if(currentSlideNumber > slideCount-1 ) currentSlideNumber = 0;
}
else if(passed.data.currentSlideNumber == 'prev')
{
currentSlideNumber = currentSlideNumber - 1;
if (currentSlideNumber < 0) currentSlideNumber = slideCount -1;
}
else
{
currentSlideNumber = passed.data.currentSlideNumber;
}
}
else
{
noAction = true;
optionsWrapper.data('animationActive', true);
}
}
if(passed != undefined) clearInterval(interval);
if(!skipSwitch && noAction == false)
{
optionsWrapper.data('animationActive', true);
skipSwitch = true;
var currentSlide = slides.filter(':visible'),
nextSlide = slides.filter(':eq('+currentSlideNumber+')'),
nextURL = $.data(nextSlide[0], "data").img,
nextImageBG = 'url('+nextURL+')';
if(options.slideControlls)
{
controlls.find('.active_item').removeClass('active_item');
controlls.find('a:eq('+currentSlideNumber+')').addClass('active_item');
}
controllThumbs.filter('.activeslideThumb').removeClass('activeslideThumb').find('img').css({opacity:0.7});
controllThumbs.filter(':eq('+currentSlideNumber+')').addClass('activeslideThumb').find('img').css({opacity:1});
blockSelectionJQ = blockOrder[options.display];
//workarround to make more than one flash movies with the same classname possible
slides.find('>a>img').css({opacity:1,visibility:'visible'});
//switchmovement
if(options.switchMovement && (options.display == "topleft" || options.display == "diagonaltop"))
{
if(reverseSwitch == false)
{
blockSelectionJQ = blockOrder[options.display];
reverseSwitch = true;
}
else
{
if(options.display == "topleft") blockSelectionJQ = blockOrder['bottomright'];
if(options.display == "diagonaltop") blockSelectionJQ = blockOrder['diagonalbottom'];
reverseSwitch = false;
}
}
if(options.display == 'random')
{
blockSelectionJQ = slideWrapper.methods.fyrandomize(blockSelection);
}
if(options.display == 'all')
{
blockSelectionJQ = blockOrder[options.transitionOrder[currentTransition]];
currentTransition ++;
if(currentTransition >= options.transitionOrder.length) currentTransition = 0;
}
//fire transition
blockSelectionJQ.css({backgroundImage: nextImageBG, backgroundColor: '#000000'}).each(function(i)
{
var currentBlock = $(this);
setTimeout(function()
{
var transitionObject = new Array();
if(options.transition == 'drop')
{
transitionObject['css'] = {height:1, width:options.blockSize.width, display:'block',opacity:0};
transitionObject['anim'] = {height:options.blockSize.height,width:options.blockSize.width,opacity:1};
}
else if(options.transition == 'fade')
{
transitionObject['css'] = {display:'block',opacity:0};
transitionObject['anim'] = {opacity:1};
}
else
{
transitionObject['css'] = {height:1, width:1, display:'block',opacity:0};
transitionObject['anim'] = {height:options.blockSize.height,width:options.blockSize.width,opacity:1};
}
currentBlock
.css(transitionObject['css'])
.animate(transitionObject['anim'],options.animationSpeed, function()
{
if(i+1 == blockNumber)
{
slideWrapper.methods.changeImage(currentSlide, nextSlide);
}
});
}, i*options.betweenBlockDelay);
});
} // end if(!skipSwitch && noAction == false)
return false;
},
changeImage: function(currentSlide, nextSlide)
{
currentSlide.css({zIndex:0, display:'none'});
if(currentSlide.is('.videoSlideContainer'))
{
currentSlide.wrapInner('<div class="videowrap_temp" />');
var videwrap = $('.videowrap_temp', currentSlide),
clone = videwrap.clone(true);
videwrap.remove();
currentSlide.append(clone);
}
nextSlide.css({zIndex:3, display:'block'});
nextSlide.find('img').css({display:'block',opacity:1});
blockSelectionJQ.fadeOut(800, function(){ skipSwitch = false; optionsWrapper.data('animationActive', false); });
},
// array sorting
fyrandomize: function(object)
{
var length = object.length,
objectSorted = $(object);
if ( length == 0 ) return false;
while ( --length )
{
var newObject = Math.floor( Math.random() * ( length + 1 ) ),
temp1 = objectSorted[length],
temp2 = objectSorted[newObject];
objectSorted[length] = temp2;
objectSorted[newObject] = temp1;
}
return objectSorted;
},
kcubit: function(object)
{
var length = object.length,
objectSorted = $(object),
currentIndex = 0, //index of the object that should get the object in "i" applied
rows = Math.ceil(slideHeight / options.blockSize.height),
columns = Math.ceil(slideWidth / options.blockSize.width),
oneColumn = blockNumber/columns,
oneRow = blockNumber/rows,
modX = 0,
modY = 0,
i = 0,
rowend = 0,
endreached = false,
onlyOne = false;
if ( length == 0 ) return false;
for (i = 0; i<length; i++ )
{
objectSorted[i] = object[currentIndex];
if((currentIndex % oneRow == 0 && blockNumber - i > oneRow)|| (modY + 1) % oneColumn == 0)
{
currentIndex -= (((oneRow - 1) * modY) - 1); modY = 0; modX ++; onlyOne = false;
if (rowend > 0)
{
modY = rowend; currentIndex += (oneRow -1) * modY;
}
}
else
{
currentIndex += oneRow -1; modY ++;
}
if((modX % (oneRow-1) == 0 && modX != 0 && rowend == 0) || (endreached == true && onlyOne == false) )
{
modX = 0.1; rowend ++; endreached = true; onlyOne = true;
}
}
return objectSorted;
}
};
slideWrapper.methods.init();
});
};
})(jQuery);
// -------------------------------------------------------------------------------------------
// image preloader
// -------------------------------------------------------------------------------------------
/*allow external controlls like thumbnails*/
(function($)
{
$.fn.aviaSlider_externalControlls = function(options)
{
return this.each(function()
{
var defaults =
{
slideControllContainer: '.slidecontrolls',
newControllContainer: '.thumbnails_container',
newControllElement: '.slideThumb',
scrolling:'vertical',
easing: 'easeInOutCirc',
itemOpacity: 0.7,
transitionTime: 2000
};
var options = $.extend(defaults, options);
//click events
var container = $(this).parent('div'),
element_container = $(options.newControllContainer, container).css({left:0, top:0}),
element_container_wrap = element_container.parent('div'),
elements_new = element_container.find(options.newControllElement).css({cursor:'pointer'}),
elements_old = $(options.slideControllContainer, container).find('a');
elements_new.find('img').css({opacity: options.itemOpacity});
elements_new.filter(':eq(0)').find('img').css({opacity: 1});
element_container.find('.style_border').css({opacity: 0.4});
elements_new.bind('click', function()
{
if(container.data('animationActive') == true || $(this).is('.activeslideThumb')) return;
var index = elements_new.index(this);
elements_old.filter(':eq('+index+')').trigger('click');
elements_new.removeClass('activeslideThumb').find('img').css({opacity: options.itemOpacity});
$(this).addClass('activeslideThumb').find('img').css({opacity: 1});
return false;
});
//add scroll event
if(!options.scrolling) return false;
if((options.scrolling == 'vertical' && element_container.height() > element_container_wrap.height()) || (options.scrolling == 'horizontal' && element_container.width() > element_container_wrap.width()))
{
var el_height = elements_new.outerHeight(true),
el_width = elements_new.outerWidth(true),
button_prev = $('<a href="#" class="thumb_prev thumb_button">Previous</a>').css('opacity',0).appendTo(element_container_wrap),
button_next = $('<a href="#" class="thumb_next thumb_button">Next</a>').css('opacity',0).appendTo(element_container_wrap),
buttons = $('.thumb_button');
button_prev.bind('click', {direction: -1}, slide);
button_next.bind('click', {direction: 1}, slide);
element_container_wrap.hover(
function(){ buttons.stop().animate({opacity:1}); },
function(){ buttons.stop().animate({opacity:0}); }
);
}
function slide(obj)
{
var multiplier = obj.data.direction,
maxScroll = "",
animate = {};
if(options.scrolling == 'vertical')
{
maxScroll = element_container_wrap.height() - element_container.height();
animate = {top: '-='+ (el_height * multiplier)};
if((maxScroll > parseInt(element_container.css('top'),10) - (el_height * multiplier)) && multiplier === 1)
{
animate = {top: 0};
}
else if(parseInt(element_container.css('top'),10) >= 0 && multiplier === -1)
{
animate = {top: maxScroll};
}
}
if(options.scrolling == 'horizontal')
{
maxScroll = element_container_wrap.width() - element_container.width();
animate = {left:'-='+ (el_width * multiplier)};
if((maxScroll > parseInt(element_container.css('left'),10) - (el_width * multiplier)) && multiplier === 1)
{
animate = {left: 0};
}
else if(parseInt(element_container.css('left'),10) >= 0 && multiplier === -1)
{
animate = {left: maxScroll};
}
}
element_container.animate(animate, options.easing);
return false;
}
});
}
})(jQuery);
| gpl-2.0 |
arobbins/wp-shopify | classes/factories/db/class-db-factory.php | 300 | <?php
namespace WPS\Factories\DB;
use WPS\DB;
if (!defined('ABSPATH')) {
exit;
}
class DB_Factory {
protected static $instantiated = null;
public static function build() {
if (is_null(self::$instantiated)) {
self::$instantiated = new DB();
}
return self::$instantiated;
}
}
| gpl-2.0 |
yixu34/Mastrix | clviewport.cpp | 5288 | #include "mastrix.hpp"
//#define SCREEN_WIDTH 1024
//#define SCREEN_HEIGHT 768
//TODO: get the viewports to change resolutions correctly
static int screenWidth = 1024;//graphics.getScreenWidth();
static int screenHeight = 768;//graphics.getScreenHeight();
const ClientViewport viewport_full (0, -1, 0, -1, screenWidth, screenHeight);
static const int viewportMargin = 1;
//initialize the viewports to default resolution of 1024x768
static ClientViewport viewport_top(
0,
-1,
0,
screenHeight / 2 - viewportMargin,
screenWidth,
screenHeight);
static ClientViewport viewport_bottom(
0,
-1,
screenHeight / 2 + viewportMargin,
-1,
screenWidth,
screenHeight);
static ClientViewport viewport_left(
0,
screenWidth / 2 - viewportMargin,
0,
-1,
screenWidth,
screenHeight);
static ClientViewport viewport_right(
screenWidth / 2 +viewportMargin,
-1,
0,
-1,
screenWidth,
screenHeight);
static ClientViewport viewport_topleft(
0,
screenWidth / 2 - viewportMargin,
0,
screenHeight / 2 - viewportMargin,
screenWidth,
screenHeight);
static ClientViewport viewport_topright(
screenWidth / 2 + viewportMargin,
-1,
0,
screenHeight / 2 - viewportMargin,
screenWidth,
screenHeight);
static ClientViewport viewport_bottomleft(
0,
screenWidth / 2 - viewportMargin,
screenHeight / 2 + viewportMargin,
-1,
screenWidth,
screenHeight);
static ClientViewport viewport_bottomright(
screenWidth / 2 + viewportMargin,
-1,
screenHeight / 2 + viewportMargin,
-1,
screenWidth,
screenHeight);
ClientViewport::ClientViewport(
float left,
float right,
float top,
float bottom,
int width,
int height)
{
reset(
left,
right,
top,
bottom,
width,
height);
}
void ClientViewport::setClip(void) const
{
//GameX.SetView(left, top, right+1, bottom+1);
glViewport(0, 0, right+1,bottom+1);
}
void ClientViewport::reset(
float left,
float right,
float top,
float bottom,
int width,
int height)
{
if(left < 0) left += width;
if(right < 0) right += width;
if(top < 0) top += height;
if(bottom < 0) bottom += height;
this->left = left;
this->right = right;
this->top = top;
this->bottom = bottom;
this->center_x = (this->left+right)/2;
this->center_y = (top+bottom)/2;
}
void updateViewports(bool vertical) { assignViewports(); }
ClientConsoleVar<bool> splitVertically ("split_vertically", true, updateViewports);
ClientConsoleVar<bool> viewAdvantage ("view_advantage", false, updateViewports);
void Client::resetViewports(int width, int height)
{
viewport_top.reset(
viewport_top.left,
viewport_top.right,
viewport_top.top,
viewport_top.bottom,
width,
height);
viewport_left.reset(
viewport_left.left,
viewport_left.right,
viewport_left.top,
viewport_left.bottom,
width,
height);
viewport_right.reset(
viewport_right.left,
viewport_right.right,
viewport_right.top,
viewport_right.bottom,
width,
height);
viewport_bottom.reset(
viewport_bottom.left,
viewport_bottom.right,
viewport_bottom.top,
viewport_bottom.bottom,
width,
height);
viewport_topleft.reset(
viewport_topleft.left,
viewport_topleft.right,
viewport_topleft.top,
viewport_topleft.bottom,
width,
height);
viewport_topright.reset(
viewport_topright.left,
viewport_topright.right,
viewport_topright.top,
viewport_topright.bottom,
width,
height);
viewport_bottomleft.reset(
viewport_bottomleft.left,
viewport_bottomleft.right,
viewport_bottomleft.top,
viewport_bottomleft.bottom,
width,
height);
viewport_bottomright.reset(
viewport_bottomright.left,
viewport_bottomright.right,
viewport_bottomright.top,
viewport_bottomright.bottom,
width,
height);
}
void assignViewports(void)
{
ClientPool::iterator ii = clients.begin();
switch(clients.size())
{
case 1:
ii->second->setViewport(&viewport_full);
break;
case 2:
if(splitVertically) {
ii->second->setViewport(&viewport_left); ii++;
ii->second->setViewport(&viewport_right); ii++;
} else {
ii->second->setViewport(&viewport_top); ii++;
ii->second->setViewport(&viewport_bottom); ii++;
}
break;
case 3:
ii->second->setViewport(&viewport_topleft); ii++;
ii->second->setViewport(&viewport_topright); ii++;
if(viewAdvantage) {
ii->second->setViewport(&viewport_bottom); ii++;
} else {
ii->second->setViewport(&viewport_bottomleft); ii++;
}
break;
case 4:
ii->second->setViewport(&viewport_topleft); ii++;
ii->second->setViewport(&viewport_topright); ii++;
ii->second->setViewport(&viewport_bottomleft); ii++;
ii->second->setViewport(&viewport_bottomright); ii++;
break;
}
}
| gpl-2.0 |
mitchbasetwo/wordpress-test | wp-content/plugins/give/includes/payments/functions.php | 43115 | <?php
/**
* Payment Functions
*
* @package Give
* @subpackage Payments
* @copyright Copyright (c) 2015, WordImpress
* @license http://opensource.org/licenses/gpl-1.0.php GNU Public License
* @since 1.0
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Get Payments
*
* Retrieve payments from the database.
*
* Since 1.0, this function takes an array of arguments, instead of individual
* parameters. All of the original parameters remain, but can be passed in any
* order via the array.
*
* $offset = 0, $number = 20, $mode = 'live', $orderby = 'ID', $order = 'DESC',
* $user = null, $status = 'any', $meta_key = null
*
* @since 1.0
*
* @param array $args Arguments passed to get payments
*
* @return object $payments Payments retrieved from the database
*/
function give_get_payments( $args = array() ) {
// Fallback to post objects to ensure backwards compatibility
if ( ! isset( $args['output'] ) ) {
$args['output'] = 'posts';
}
$args = apply_filters( 'give_get_payments_args', $args );
$payments = new Give_Payments_Query( $args );
return $payments->get_payments();
}
/**
* Retrieve payment by a given field
*
* @since 1.0
*
* @param string $field The field to retrieve the payment with
* @param mixed $value The value for $field
*
* @return mixed
*/
function give_get_payment_by( $field = '', $value = '' ) {
if ( empty( $field ) || empty( $value ) ) {
return false;
}
switch ( strtolower( $field ) ) {
case 'id':
$payment = get_post( $value );
if ( get_post_type( $payment ) != 'give_payment' ) {
return false;
}
break;
case 'key':
$payment = give_get_payments( array(
'meta_key' => '_give_payment_purchase_key',
'meta_value' => $value,
'posts_per_page' => 1
) );
if ( $payment ) {
$payment = $payment[0];
}
break;
case 'payment_number':
$payment = give_get_payments( array(
'meta_key' => '_give_payment_number',
'meta_value' => $value,
'posts_per_page' => 1
) );
if ( $payment ) {
$payment = $payment[0];
}
break;
default:
return false;
}
if ( $payment ) {
return $payment;
}
return false;
}
/**
* Insert Payment
*
* @since 1.0
*
* @param array $payment_data
*
* @return int|bool Payment ID if payment is inserted, false otherwise
*/
function give_insert_payment( $payment_data = array() ) {
if ( empty( $payment_data ) ) {
return false;
}
// Make sure the payment is inserted with the correct timezone
date_default_timezone_set( give_get_timezone_id() );
// Construct the payment title
if ( isset( $payment_data['user_info']['first_name'] ) || isset( $payment_data['user_info']['last_name'] ) ) {
$payment_title = $payment_data['user_info']['first_name'] . ' ' . $payment_data['user_info']['last_name'];
} else {
$payment_title = $payment_data['user_email'];
}
// Find the next payment number, if enabled
if ( give_get_option( 'enable_sequential' ) ) {
$number = give_get_next_payment_number();
}
$args = apply_filters( 'give_insert_payment_args', array(
'post_title' => $payment_title,
'post_status' => isset( $payment_data['status'] ) ? $payment_data['status'] : 'pending',
'post_type' => 'give_payment',
'post_parent' => isset( $payment_data['parent'] ) ? $payment_data['parent'] : null,
'post_date' => isset( $payment_data['post_date'] ) ? $payment_data['post_date'] : null,
'post_date_gmt' => isset( $payment_data['post_date'] ) ? get_gmt_from_date( $payment_data['post_date'] ) : null
), $payment_data );
// Create a blank payment
$payment = wp_insert_post( $args );
if ( $payment ) {
$payment_meta = array(
'currency' => $payment_data['currency'],
'form_title' => $payment_data['give_form_title'],
'form_id' => $payment_data['give_form_id'],
'price_id' => give_get_price_id( $payment_data['give_form_id'], $payment_data['price'] ),
'user_info' => $payment_data['user_info'],
);
$mode = give_is_test_mode() ? 'test' : 'live';
$gateway = ! empty( $payment_data['gateway'] ) ? $payment_data['gateway'] : '';
$gateway = empty( $gateway ) && isset( $_POST['give-gateway'] ) ? $_POST['give-gateway'] : $gateway;
if ( ! $payment_data['price'] ) {
// Ensures the _give_payment_total meta key is created for donations with an amount of 0
$payment_data['price'] = '0.00';
}
// Create or update a donor
$donor_id = Give()->customers->add( array(
'name' => $payment_data['user_info']['first_name'] . ' ' . $payment_data['user_info']['last_name'],
'email' => $payment_data['user_email'],
'user_id' => $payment_data['user_info']['id'],
'payment_ids' => $payment
) );
// Record the payment details
give_update_payment_meta( $payment, '_give_payment_meta', apply_filters( 'give_payment_meta', $payment_meta, $payment_data ) );
give_update_payment_meta( $payment, '_give_payment_user_id', $payment_data['user_info']['id'] );
give_update_payment_meta( $payment, '_give_payment_donor_id', $donor_id );
give_update_payment_meta( $payment, '_give_payment_user_email', $payment_data['user_email'] );
give_update_payment_meta( $payment, '_give_payment_user_ip', give_get_ip() );
give_update_payment_meta( $payment, '_give_payment_purchase_key', $payment_data['purchase_key'] );
give_update_payment_meta( $payment, '_give_payment_total', $payment_data['price'] );
give_update_payment_meta( $payment, '_give_payment_mode', $mode );
give_update_payment_meta( $payment, '_give_payment_gateway', $gateway );
if ( give_get_option( 'enable_sequential' ) ) {
give_update_payment_meta( $payment, '_give_payment_number', $number );
}
// Clear the user's purchased cache
delete_transient( 'give_user_' . $payment_data['user_info']['id'] . '_purchases' );
do_action( 'give_insert_payment', $payment, $payment_data );
return $payment; // Return the ID
}
// Return false if no payment was inserted
return false;
}
/**
* Updates a payment status.
*
* @since 1.0
*
* @param int $payment_id Payment ID
* @param string $new_status New Payment Status (default: publish)
*
* @return void
*/
function give_update_payment_status( $payment_id, $new_status = 'publish' ) {
if ( $new_status == 'completed' || $new_status == 'complete' ) {
$new_status = 'publish';
}
if ( empty( $payment_id ) ) {
return;
}
$payment = get_post( $payment_id );
if ( is_wp_error( $payment ) || ! is_object( $payment ) ) {
return;
}
$old_status = $payment->post_status;
if ( $old_status === $new_status ) {
return; // Don't permit status changes that aren't changes
}
$do_change = apply_filters( 'give_should_update_payment_status', true, $payment_id, $new_status, $old_status );
if ( $do_change ) {
do_action( 'give_before_payment_status_change', $payment_id, $new_status, $old_status );
$update_fields = array(
'ID' => $payment_id,
'post_status' => $new_status,
'edit_date' => current_time( 'mysql' )
);
wp_update_post( apply_filters( 'give_update_payment_status_fields', $update_fields ) );
do_action( 'give_update_payment_status', $payment_id, $new_status, $old_status );
}
}
/**
* Deletes a Donation
*
* @since 1.0
* @global $give_logs
* @uses Give_Logging::delete_logs()
*
* @param int $payment_id Payment ID (default: 0)
*
* @return void
*/
function give_delete_purchase( $payment_id = 0 ) {
global $give_logs;
$post = get_post( $payment_id );
if ( ! $post ) {
return;
}
$form_id = give_get_payment_form_id( $payment_id );
give_undo_purchase( $form_id, $payment_id );
$amount = give_get_payment_amount( $payment_id );
$status = $post->post_status;
$donor_id = give_get_payment_customer_id( $payment_id );
if ( $status == 'revoked' || $status == 'publish' ) {
// Only decrease earnings if they haven't already been decreased (or were never increased for this payment)
give_decrease_total_earnings( $amount );
// Clear the This Month earnings (this_monththis_month is NOT a typo)
delete_transient( md5( 'give_earnings_this_monththis_month' ) );
if ( $donor_id ) {
// Decrement the stats for the donor
Give()->customers->decrement_stats( $donor_id, $amount );
}
}
do_action( 'give_payment_delete', $payment_id );
if ( $donor_id ) {
// Remove the payment ID from the donor
Give()->customers->remove_payment( $donor_id, $payment_id );
}
// Remove the payment
wp_delete_post( $payment_id, true );
// Remove related sale log entries
$give_logs->delete_logs(
null,
'sale',
array(
array(
'key' => '_give_log_payment_id',
'value' => $payment_id
)
)
);
do_action( 'give_payment_deleted', $payment_id );
}
/**
* Undoes a donation, including the decrease of donations and earning stats. Used for when refunding or deleting a donation
*
* @since 1.0
*
* @param int $form_id Form (Post) ID
* @param int $payment_id Payment ID
*
* @return void
*/
function give_undo_purchase( $form_id, $payment_id ) {
if ( give_is_test_mode() ) {
return;
}
$amount = give_get_payment_amount( $payment_id );
// decrease earnings
give_decrease_earnings( $form_id, $amount );
// decrease purchase count
give_decrease_purchase_count( $form_id );
}
/**
* Count Payments
*
* Returns the total number of payments recorded.
*
* @since 1.0
*
* @param array $args
*
* @return array $count Number of payments sorted by payment status
*/
function give_count_payments( $args = array() ) {
global $wpdb;
$defaults = array(
'user' => null,
's' => null,
'start-date' => null,
'end-date' => null,
);
$args = wp_parse_args( $args, $defaults );
$join = '';
$where = "WHERE p.post_type = 'give_payment'";
// Count payments for a specific user
if ( ! empty( $args['user'] ) ) {
if ( is_email( $args['user'] ) ) {
$field = 'email';
} elseif ( is_numeric( $args['user'] ) ) {
$field = 'id';
} else {
$field = '';
}
$join = "LEFT JOIN $wpdb->postmeta m ON (p.ID = m.post_id)";
if ( ! empty( $field ) ) {
$where .= "
AND m.meta_key = '_give_payment_user_{$field}'
AND m.meta_value = '{$args['user']}'";
}
// Count payments for a search
} elseif ( ! empty( $args['s'] ) ) {
if ( is_email( $args['s'] ) || strlen( $args['s'] ) == 32 ) {
if ( is_email( $args['s'] ) ) {
$field = '_give_payment_user_email';
} else {
$field = '_give_payment_purchase_key';
}
$join = "LEFT JOIN $wpdb->postmeta m ON (p.ID = m.post_id)";
$where .= "
AND m.meta_key = '{$field}'
AND m.meta_value = '{$args['s']}'";
} elseif ( is_numeric( $args['s'] ) ) {
$join = "LEFT JOIN $wpdb->postmeta m ON (p.ID = m.post_id)";
$where .= "
AND m.meta_key = '_give_payment_user_id'
AND m.meta_value = '{$args['s']}'";
} else {
$where .= "AND ((p.post_title LIKE '%{$args['s']}%') OR (p.post_content LIKE '%{$args['s']}%'))";
}
}
// Limit payments count by date
if ( ! empty( $args['start-date'] ) ) {
$date = new DateTime( $args['start-date'] );
$where .= "
AND p.post_date >= '" . $date->format( 'Y-m-d' ) . "'";
}
if ( ! empty ( $args['end-date'] ) ) {
$date = new DateTime( $args['end-date'] );
$where .= "
AND p.post_date <= '" . $date->format( 'Y-m-d' ) . "'";
}
$where = apply_filters( 'give_count_payments_where', $where );
$join = apply_filters( 'give_count_payments_join', $join );
$cache_key = md5( implode( '|', $args ) . $where );
$query = "SELECT p.post_status,count( * ) AS num_posts
FROM $wpdb->posts p
$join
$where
GROUP BY p.post_status
";
$count = wp_cache_get( $cache_key, 'counts' );
if ( false !== $count ) {
return $count;
}
$count = $wpdb->get_results( $query, ARRAY_A );
$stats = array();
$statuses = get_post_stati();
if ( isset( $statuses['private'] ) && empty( $args['s'] ) ) {
unset( $statuses['private'] );
}
foreach ( $statuses as $state ) {
$stats[ $state ] = 0;
}
foreach ( (array) $count as $row ) {
if ( 'private' == $row['post_status'] && empty( $args['s'] ) ) {
continue;
}
$stats[ $row['post_status'] ] = $row['num_posts'];
}
$stats = (object) $stats;
wp_cache_set( $cache_key, $stats, 'counts' );
return $stats;
}
/**
* Check For Existing Payment
*
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return bool true if payment exists, false otherwise
*/
function give_check_for_existing_payment( $payment_id ) {
$payment = get_post( $payment_id );
if ( $payment && $payment->post_status == 'publish' ) {
return true; // Payment exists
}
return false; // This payment doesn't exist
}
/**
* Get Payment Status
*
* @since 1.0
*
* @param WP_Post $payment
* @param bool $return_label Whether to return the donation status or not
*
* @return bool|mixed if payment status exists, false otherwise
*/
function give_get_payment_status( $payment, $return_label = false ) {
if ( ! is_object( $payment ) || ! isset( $payment->post_status ) ) {
return false;
}
$statuses = give_get_payment_statuses();
if ( ! is_array( $statuses ) || empty( $statuses ) ) {
return false;
}
if ( array_key_exists( $payment->post_status, $statuses ) ) {
if ( true === $return_label ) {
return $statuses[ $payment->post_status ];
} else {
return array_search( $payment->post_status, $statuses );
}
}
return false;
}
/**
* Retrieves all available statuses for payments.
*
* @since 1.0
* @return array $payment_status All the available payment statuses
*/
function give_get_payment_statuses() {
$payment_statuses = array(
'pending' => __( 'Pending', 'give' ),
'publish' => __( 'Complete', 'give' ),
'refunded' => __( 'Refunded', 'give' ),
'failed' => __( 'Failed', 'give' ),
'cancelled' => __( 'Cancelled', 'give' ),
'abandoned' => __( 'Abandoned', 'give' ),
'preapproval' => __( 'Pre-Approved', 'give' ),
'revoked' => __( 'Revoked', 'give' )
);
return apply_filters( 'give_payment_statuses', $payment_statuses );
}
/**
* Get Payment Status Keys
*
* @description Retrieves keys for all available statuses for payments
*
* @since 1.0
* @return array $payment_status All the available payment statuses
*/
function give_get_payment_status_keys() {
$statuses = array_keys( give_get_payment_statuses() );
asort( $statuses );
return array_values( $statuses );
}
/**
* Get Earnings By Date
*
* @since 1.0
*
* @param int $day Day number
* @param int $month_num Month number
* @param int $year Year
* @param int $hour Hour
*
* @return int $earnings Earnings
*/
function give_get_earnings_by_date( $day = null, $month_num, $year = null, $hour = null ) {
// This is getting deprecated soon. Use Give_Payment_Stats with the get_earnings() method instead
global $wpdb;
$args = array(
'post_type' => 'give_payment',
'nopaging' => true,
'year' => $year,
'monthnum' => $month_num,
'post_status' => array( 'publish', 'revoked' ),
'fields' => 'ids',
'update_post_term_cache' => false
);
if ( ! empty( $day ) ) {
$args['day'] = $day;
}
if ( ! empty( $hour ) ) {
$args['hour'] = $hour;
}
$args = apply_filters( 'give_get_earnings_by_date_args', $args );
$key = md5( serialize( $args ) );
$earnings = get_transient( $key );
if ( false === $earnings ) {
$sales = get_posts( $args );
$earnings = 0;
if ( $sales ) {
$sales = implode( ',', $sales );
$earnings += $wpdb->get_var( "SELECT SUM(meta_value) FROM $wpdb->postmeta WHERE meta_key = '_give_payment_total' AND post_id IN({$sales})" );
}
// Cache the results for one hour
set_transient( $key, $earnings, 60 * 60 );
}
return round( $earnings, 2 );
}
/**
* Get Donations (sales) By Date
*
* @since 1.0
*
* @param int $day Day number
* @param int $month_num Month number
* @param int $year Year
* @param int $hour Hour
*
* @return int $count Sales
*/
function give_get_sales_by_date( $day = null, $month_num = null, $year = null, $hour = null ) {
// This is getting deprecated soon. Use Give_Payment_Stats with the get_sales() method instead
$args = array(
'post_type' => 'give_payment',
'nopaging' => true,
'year' => $year,
'fields' => 'ids',
'post_status' => array( 'publish', 'revoked' ),
'update_post_meta_cache' => false,
'update_post_term_cache' => false
);
if ( ! empty( $month_num ) ) {
$args['monthnum'] = $month_num;
}
if ( ! empty( $day ) ) {
$args['day'] = $day;
}
if ( ! empty( $hour ) ) {
$args['hour'] = $hour;
}
$args = apply_filters( 'give_get_sales_by_date_args', $args );
$key = md5( serialize( $args ) );
$count = get_transient( $key );
if ( false === $count ) {
$sales = new WP_Query( $args );
$count = (int) $sales->post_count;
// Cache the results for one hour
set_transient( $key, $count, 60 * 60 );
}
return $count;
}
/**
* Checks whether a payment has been marked as complete.
*
* @since 1.0
*
* @param int $payment_id Payment ID to check against
*
* @return bool true if complete, false otherwise
*/
function give_is_payment_complete( $payment_id ) {
$payment = get_post( $payment_id );
$ret = false;
if ( $payment && $payment->post_status == 'publish' ) {
$ret = true;
}
return apply_filters( 'give_is_payment_complete', $ret, $payment_id, $payment->post_status );
}
/**
* Get Total Sales (Donations)
*
* @since 1.0
* @return int $count Total sales
*/
function give_get_total_sales() {
$payments = give_count_payments();
return $payments->revoked + $payments->publish;
}
/**
* Get Total Earnings
*
* @since 1.0
* @return float $total Total earnings
*/
function give_get_total_earnings() {
$total = get_option( 'give_earnings_total', 0 );
// If no total stored in DB, use old method of calculating total earnings
if ( ! $total ) {
global $wpdb;
$total = get_transient( 'give_earnings_total' );
if ( false === $total ) {
$total = (float) 0;
$args = apply_filters( 'give_get_total_earnings_args', array(
'offset' => 0,
'number' => - 1,
'status' => array( 'publish', 'revoked' ),
'fields' => 'ids'
) );
$payments = give_get_payments( $args );
if ( $payments ) {
/*
* If performing a purchase, we need to skip the very last payment in the database, since it calls
* give_increase_total_earnings() on completion, which results in duplicated earnings for the very
* first purchase
*/
if ( did_action( 'give_update_payment_status' ) ) {
array_pop( $payments );
}
if ( ! empty( $payments ) ) {
$payments = implode( ',', $payments );
$total += $wpdb->get_var( "SELECT SUM(meta_value) FROM $wpdb->postmeta WHERE meta_key = '_give_payment_total' AND post_id IN({$payments})" );
}
}
// Cache results for 1 day. This cache is cleared automatically when a payment is made
set_transient( 'give_earnings_total', $total, 86400 );
// Store the total for the first time
update_option( 'give_earnings_total', $total );
}
}
if ( $total < 0 ) {
$total = 0; // Don't ever show negative earnings
}
return apply_filters( 'give_total_earnings', round( $total, give_currency_decimal_filter() ) );
}
/**
* Increase the Total Earnings
*
* @since 1.0
*
* @param $amount int The amount you would like to increase the total earnings by.
*
* @return float $total Total earnings
*/
function give_increase_total_earnings( $amount = 0 ) {
$total = give_get_total_earnings();
$total += $amount;
update_option( 'give_earnings_total', $total );
return $total;
}
/**
* Decrease the Total Earnings
*
* @since 1.0
*
* @param $amount int The amount you would like to decrease the total earnings by.
*
* @return float $total Total earnings
*/
function give_decrease_total_earnings( $amount = 0 ) {
$total = give_get_total_earnings();
$total -= $amount;
if ( $total < 0 ) {
$total = 0;
}
update_option( 'give_earnings_total', $total );
return $total;
}
/**
* Get Payment Meta for a specific Payment
*
* @since 1.0
*
* @param int $payment_id Payment ID
* @param string $meta_key The meta key to pull
* @param bool $single Pull single meta entry or as an object
*
* @return mixed $meta Payment Meta
*/
function give_get_payment_meta( $payment_id = 0, $meta_key = '_give_payment_meta', $single = true ) {
$meta = get_post_meta( $payment_id, $meta_key, $single );
if ( $meta_key === '_give_payment_meta' ) {
if ( empty( $meta['key'] ) ) {
$meta['key'] = give_get_payment_key( $payment_id );
}
if ( empty( $meta['email'] ) ) {
$meta['email'] = give_get_payment_user_email( $payment_id );
}
if ( empty( $meta['date'] ) ) {
$meta['date'] = get_post_field( 'post_date', $payment_id );
}
}
$meta = apply_filters( 'give_get_payment_meta_' . $meta_key, $meta, $payment_id );
return apply_filters( 'give_get_payment_meta', $meta, $payment_id, $meta_key );
}
/**
* Update the meta for a payment
*
* @param integer $payment_id Payment ID
* @param string $meta_key Meta key to update
* @param string $meta_value Value to update to
* @param string $prev_value Previous value
*
* @return mixed Meta ID if successful, false if unsuccessful
*/
function give_update_payment_meta( $payment_id = 0, $meta_key = '', $meta_value = '', $prev_value = '' ) {
if ( empty( $payment_id ) || empty( $meta_key ) ) {
return;
}
if ( $meta_key == 'key' || $meta_key == 'date' ) {
$current_meta = give_get_payment_meta( $payment_id );
$current_meta[ $meta_key ] = $meta_value;
$meta_key = '_give_payment_meta';
$meta_value = $current_meta;
} else if ( $meta_key == 'email' || $meta_key == '_give_payment_user_email' ) {
$meta_value = apply_filters( 'give_give_update_payment_meta_' . $meta_key, $meta_value, $payment_id );
update_post_meta( $payment_id, '_give_payment_user_email', $meta_value );
$current_meta = give_get_payment_meta( $payment_id );
$current_meta['user_info']['email'] = $meta_value;
$meta_key = '_give_payment_meta';
$meta_value = $current_meta;
}
$meta_value = apply_filters( 'give_give_update_payment_meta_' . $meta_key, $meta_value, $payment_id );
return update_post_meta( $payment_id, $meta_key, $meta_value, $prev_value );
}
/**
* Get the user_info Key from Payment Meta
*
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return array $user_info User Info Meta Values
*/
function give_get_payment_meta_user_info( $payment_id ) {
$payment_meta = give_get_payment_meta( $payment_id );
$user_info = isset( $payment_meta['user_info'] ) ? maybe_unserialize( $payment_meta['user_info'] ) : false;
return apply_filters( 'give_payment_meta_user_info', $user_info );
}
/**
* Get the donations Key from Payment Meta
*
* @description Retrieves the form_id from a (Previously title give_get_payment_meta_donations)
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return array $donations Downloads Meta Values
*/
function give_get_payment_form_id( $payment_id ) {
$payment_meta = give_get_payment_meta( $payment_id );
$form_id = isset( $payment_meta['form_id'] ) ? $payment_meta['form_id'] : 0;
return apply_filters( 'give_get_payment_form_id', $form_id );
}
/**
* Get the user email associated with a payment
*
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return string $email User Email
*/
function give_get_payment_user_email( $payment_id ) {
$email = give_get_payment_meta( $payment_id, '_give_payment_user_email', true );
return apply_filters( 'give_payment_user_email', $email );
}
/**
* Get the user ID associated with a payment
*
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return string $user_id User ID
*/
function give_get_payment_user_id( $payment_id ) {
$user_id = give_get_payment_meta( $payment_id, '_give_payment_user_id', true );
return apply_filters( 'give_payment_user_id', $user_id );
}
/**
* Get the donor ID associated with a payment
*
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return string $donor_id Donor ID
*/
function give_get_payment_customer_id( $payment_id ) {
$donor_id = get_post_meta( $payment_id, '_give_payment_donor_id', true );
return apply_filters( 'give_payment_donor_id', $donor_id );
}
/**
* Get the IP address used to make a purchase
*
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return string $ip User IP
*/
function give_get_payment_user_ip( $payment_id ) {
$ip = give_get_payment_meta( $payment_id, '_give_payment_user_ip', true );
return apply_filters( 'give_payment_user_ip', $ip );
}
/**
* Get the date a payment was completed
*
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return string $date The date the payment was completed
*/
function give_get_payment_completed_date( $payment_id = 0 ) {
$payment = get_post( $payment_id );
if ( 'pending' == $payment->post_status || 'preapproved' == $payment->post_status ) {
return false; // This payment was never completed
}
$date = ( $date = give_get_payment_meta( $payment_id, '_give_completed_date', true ) ) ? $date : $payment->modified_date;
return apply_filters( 'give_payment_completed_date', $date, $payment_id );
}
/**
* Get the gateway associated with a payment
*
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return string $gateway Gateway
*/
function give_get_payment_gateway( $payment_id ) {
$gateway = give_get_payment_meta( $payment_id, '_give_payment_gateway', true );
return apply_filters( 'give_payment_gateway', $gateway );
}
/**
* Get the currency code a payment was made in
*
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return string $currency The currency code
*/
function give_get_payment_currency_code( $payment_id = 0 ) {
$meta = give_get_payment_meta( $payment_id );
$currency = isset( $meta['currency'] ) ? $meta['currency'] : give_get_currency();
return apply_filters( 'give_payment_currency_code', $currency, $payment_id );
}
/**
* Get the currency name a payment was made in
*
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return string $currency The currency name
*/
function give_get_payment_currency( $payment_id = 0 ) {
$currency = give_get_payment_currency_code( $payment_id );
return apply_filters( 'give_payment_currency', give_get_currency_name( $currency ), $payment_id );
}
/**
* Get the purchase key for a purchase
*
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return string $key Purchase key
*/
function give_get_payment_key( $payment_id = 0 ) {
$key = give_get_payment_meta( $payment_id, '_give_payment_purchase_key', true );
return apply_filters( 'give_payment_key', $key, $payment_id );
}
/**
* Get the payment order number
*
* This will return the payment ID if sequential order numbers are not enabled or the order number does not exist
*
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return string $number Payment order number
*/
function give_get_payment_number( $payment_id = 0 ) {
$number = $payment_id;
if ( give_get_option( 'enable_sequential' ) ) {
$number = give_get_payment_meta( $payment_id, '_give_payment_number', true );
if ( ! $number ) {
$number = $payment_id;
}
}
return apply_filters( 'give_payment_number', $number, $payment_id );
}
/**
* Gets the next available order number
*
* This is used when inserting a new payment
*
* @since 1.0
* @return string $number The next available payment number
*/
function give_get_next_payment_number() {
if ( ! give_get_option( 'enable_sequential' ) ) {
return false;
}
$prefix = give_get_option( 'sequential_prefix' );
$postfix = give_get_option( 'sequential_postfix' );
$start = give_get_option( 'sequential_start', 1 );
$payments = new Give_Payments_Query( array(
'number' => 1,
'order' => 'DESC',
'orderby' => 'ID',
'output' => 'posts',
'fields' => 'ids'
) );
$last_payment = $payments->get_payments();
if ( $last_payment ) {
$number = give_get_payment_number( $last_payment[0] );
if ( empty( $number ) ) {
$number = $prefix . $start . $postfix;
} else {
// Remove prefix and postfix
$number = str_replace( $prefix, '', $number );
$number = str_replace( $postfix, '', $number );
// Ensure it's a whole number
$number = intval( $number );
// Increment the payment number
$number ++;
// Re-add the prefix and postfix
$number = $prefix . $number . $postfix;
}
} else {
$number = $prefix . $start . $postfix;
}
return apply_filters( 'give_get_next_payment_number', $number );
}
/**
* Get Payment Amount
*
* @description Get the fully formatted payment amount. The payment amount is retrieved using give_get_payment_amount() and is then sent through give_currency_filter() and give_format_amount() to format the amount correctly.
*
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return string $amount Fully formatted payment amount
*/
function give_payment_amount( $payment_id = 0 ) {
$amount = give_get_payment_amount( $payment_id );
return give_currency_filter( give_format_amount( $amount ), give_get_payment_currency_code( $payment_id ) );
}
/**
* Get the amount associated with a payment
*
* @access public
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return mixed|void
*/
function give_get_payment_amount( $payment_id ) {
$amount = give_get_payment_meta( $payment_id, '_give_payment_total', true );
if ( empty( $amount ) && '0.00' != $amount ) {
$meta = give_get_payment_meta( $payment_id, '_give_payment_meta', true );
$meta = maybe_unserialize( $meta );
if ( isset( $meta['amount'] ) ) {
$amount = $meta['amount'];
}
}
return apply_filters( 'give_payment_amount', floatval( $amount ), $payment_id );
}
/**
* Retrieves the transaction ID for the given payment
*
* @since 1.0
*
* @param int $payment_id Payment ID
*
* @return string The Transaction ID
*/
function give_get_payment_transaction_id( $payment_id = 0 ) {
$transaction_id = false;
$transaction_id = give_get_payment_meta( $payment_id, '_give_payment_transaction_id', true );
if ( empty( $transaction_id ) ) {
$gateway = give_get_payment_gateway( $payment_id );
$transaction_id = apply_filters( 'give_get_payment_transaction_id-' . $gateway, $payment_id );
}
return apply_filters( 'give_get_payment_transaction_id', $transaction_id, $payment_id );
}
/**
* Sets a Transaction ID in post meta for the given Payment ID
*
* @since 1.0
*
* @param int $payment_id Payment ID
* @param string $transaction_id The transaction ID from the gateway
*
* @return bool|mixed
*/
function give_set_payment_transaction_id( $payment_id = 0, $transaction_id = '' ) {
if ( empty( $payment_id ) || empty( $transaction_id ) ) {
return false;
}
$transaction_id = apply_filters( 'give_set_payment_transaction_id', $transaction_id, $payment_id );
return give_update_payment_meta( $payment_id, '_give_payment_transaction_id', $transaction_id );
}
/**
* Retrieve the purchase ID based on the purchase key
*
* @since 1.0
* @global object $wpdb Used to query the database using the WordPress
* Database API
*
* @param string $key the purchase key to search for
*
* @return int $purchase Purchase ID
*/
function give_get_purchase_id_by_key( $key ) {
global $wpdb;
$purchase = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_give_payment_purchase_key' AND meta_value = %s LIMIT 1", $key ) );
if ( $purchase != null ) {
return $purchase;
}
return 0;
}
/**
* Retrieve all notes attached to a purchase
*
* @since 1.0
*
* @param int $payment_id The payment ID to retrieve notes for
* @param string $search Search for notes that contain a search term
*
* @return array $notes Payment Notes
*/
function give_get_payment_notes( $payment_id = 0, $search = '' ) {
if ( empty( $payment_id ) && empty( $search ) ) {
return false;
}
remove_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
remove_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10, 2 );
$notes = get_comments( array( 'post_id' => $payment_id, 'order' => 'ASC', 'search' => $search ) );
add_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
add_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10, 2 );
return $notes;
}
/**
* Add a note to a payment
*
* @since 1.0
*
* @param int $payment_id The payment ID to store a note for
* @param string $note The note to store
*
* @return int The new note ID
*/
function give_insert_payment_note( $payment_id = 0, $note = '' ) {
if ( empty( $payment_id ) ) {
return false;
}
do_action( 'give_pre_insert_payment_note', $payment_id, $note );
$note_id = wp_insert_comment( wp_filter_comment( array(
'comment_post_ID' => $payment_id,
'comment_content' => $note,
'user_id' => is_admin() ? get_current_user_id() : 0,
'comment_date' => current_time( 'mysql' ),
'comment_date_gmt' => current_time( 'mysql', 1 ),
'comment_approved' => 1,
'comment_parent' => 0,
'comment_author' => '',
'comment_author_IP' => '',
'comment_author_url' => '',
'comment_author_email' => '',
'comment_type' => 'give_payment_note'
) ) );
do_action( 'give_insert_payment_note', $note_id, $payment_id, $note );
return $note_id;
}
/**
* Deletes a payment note
*
* @since 1.0
*
* @param int $comment_id The comment ID to delete
* @param int $payment_id The payment ID the note is connected to
*
* @return bool True on success, false otherwise
*/
function give_delete_payment_note( $comment_id = 0, $payment_id = 0 ) {
if ( empty( $comment_id ) ) {
return false;
}
do_action( 'give_pre_delete_payment_note', $comment_id, $payment_id );
$ret = wp_delete_comment( $comment_id, true );
do_action( 'give_post_delete_payment_note', $comment_id, $payment_id );
return $ret;
}
/**
* Gets the payment note HTML
*
* @since 1.0
*
* @param object /int $note The comment object or ID
* @param int $payment_id The payment ID the note is connected to
*
* @return string
*/
function give_get_payment_note_html( $note, $payment_id = 0 ) {
if ( is_numeric( $note ) ) {
$note = get_comment( $note );
}
if ( ! empty( $note->user_id ) ) {
$user = get_userdata( $note->user_id );
$user = $user->display_name;
} else {
$user = __( 'System', 'give' );
}
$date_format = get_option( 'date_format' ) . ', ' . get_option( 'time_format' );
$delete_note_url = wp_nonce_url( add_query_arg( array(
'give-action' => 'delete_payment_note',
'note_id' => $note->comment_ID,
'payment_id' => $payment_id
) ), 'give_delete_payment_note_' . $note->comment_ID );
$note_html = '<div class="give-payment-note" id="give-payment-note-' . $note->comment_ID . '">';
$note_html .= '<p>';
$note_html .= '<strong>' . $user . '</strong> – <span style="color:#aaa;font-style:italic;">' . date_i18n( $date_format, strtotime( $note->comment_date ) ) . '</span><br/>';
$note_html .= $note->comment_content;
$note_html .= ' – <a href="' . esc_url( $delete_note_url ) . '" class="give-delete-payment-note" data-note-id="' . absint( $note->comment_ID ) . '" data-payment-id="' . absint( $payment_id ) . '" title="' . __( 'Delete this payment note', 'give' ) . '">' . __( 'Delete', 'give' ) . '</a>';
$note_html .= '</p>';
$note_html .= '</div>';
return $note_html;
}
/**
* Exclude notes (comments) on give_payment post type from showing in Recent
* Comments widgets
*
* @since 1.0
*
* @param obj $query WordPress Comment Query Object
*
* @return void
*/
function give_hide_payment_notes( $query ) {
global $wp_version;
if ( version_compare( floatval( $wp_version ), '4.1', '>=' ) ) {
$types = isset( $query->query_vars['type__not_in'] ) ? $query->query_vars['type__not_in'] : array();
if ( ! is_array( $types ) ) {
$types = array( $types );
}
$types[] = 'give_payment_note';
$query->query_vars['type__not_in'] = $types;
}
}
add_action( 'pre_get_comments', 'give_hide_payment_notes', 10 );
/**
* Exclude notes (comments) on give_payment post type from showing in Recent Comments widgets
*
* @since 1.0
*
* @param array $clauses Comment clauses for comment query
* @param obj $wp_comment_query WordPress Comment Query Object
*
* @return array $clauses Updated comment clauses
*/
function give_hide_payment_notes_pre_41( $clauses, $wp_comment_query ) {
global $wpdb, $wp_version;
if ( version_compare( floatval( $wp_version ), '4.1', '<' ) ) {
$clauses['where'] .= ' AND comment_type != "give_payment_note"';
}
return $clauses;
}
add_filter( 'comments_clauses', 'give_hide_payment_notes_pre_41', 10, 2 );
/**
* Exclude notes (comments) on give_payment post type from showing in comment feeds
*
* @since 1.0
*
* @param array $where
* @param obj $wp_comment_query WordPress Comment Query Object
*
* @return array $where
*/
function give_hide_payment_notes_from_feeds( $where, $wp_comment_query ) {
global $wpdb;
$where .= $wpdb->prepare( " AND comment_type != %s", 'give_payment_note' );
return $where;
}
add_filter( 'comment_feed_where', 'give_hide_payment_notes_from_feeds', 10, 2 );
/**
* Remove Give Comments from the wp_count_comments function
*
* @access public
* @since 1.0
*
* @param array $stats (empty from core filter)
* @param int $post_id Post ID
*
* @return array Array of comment counts
*/
function give_remove_payment_notes_in_comment_counts( $stats, $post_id ) {
global $wpdb, $pagenow;
if ( 'index.php' != $pagenow ) {
return $stats;
}
$post_id = (int) $post_id;
if ( apply_filters( 'give_count_payment_notes_in_comments', false ) ) {
return $stats;
}
$stats = wp_cache_get( "comments-{$post_id}", 'counts' );
if ( false !== $stats ) {
return $stats;
}
$where = 'WHERE comment_type != "give_payment_note"';
if ( $post_id > 0 ) {
$where .= $wpdb->prepare( " AND comment_post_ID = %d", $post_id );
}
$count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
$total = 0;
$approved = array(
'0' => 'moderated',
'1' => 'approved',
'spam' => 'spam',
'trash' => 'trash',
'post-trashed' => 'post-trashed'
);
foreach ( (array) $count as $row ) {
// Don't count post-trashed toward totals
if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) {
$total += $row['num_comments'];
}
if ( isset( $approved[ $row['comment_approved'] ] ) ) {
$stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments'];
}
}
$stats['total_comments'] = $total;
foreach ( $approved as $key ) {
if ( empty( $stats[ $key ] ) ) {
$stats[ $key ] = 0;
}
}
$stats = (object) $stats;
wp_cache_set( "comments-{$post_id}", $stats, 'counts' );
return $stats;
}
add_filter( 'wp_count_comments', 'give_remove_payment_notes_in_comment_counts', 10, 2 );
/**
* Filter where older than one week
*
* @access public
* @since 1.0
*
* @param string $where Where clause
*
* @return string $where Modified where clause
*/
function give_filter_where_older_than_week( $where = '' ) {
// Payments older than one week
$start = date( 'Y-m-d', strtotime( '-7 days' ) );
$where .= " AND post_date <= '{$start}'";
return $where;
}
/**
* Get Price ID
*
* @description Retrieves the Price ID given a proper form ID and price (donation) total
*
* @param $form_id
* @param $price
*
* @return string $price_id
*/
function give_get_price_id( $form_id, $price ) {
$price_id = 0;
if ( give_has_variable_prices( $form_id ) ) {
$levels = maybe_unserialize( get_post_meta( $form_id, '_give_donation_levels', true ) );
foreach ( $levels as $level ) {
$level_amount = (float) give_sanitize_amount( $level['_give_amount'] );
//check that this indeed the recurring price
if ( $level_amount == $price ) {
$price_id = $level['_give_id']['level_id'];
}
}
}
return $price_id;
}
/**
* Retrieves arbitrary fees for the donation (Currently not in use!!)
* @TODO - Incorporate a fee-based functionality similar to below
* @since 1.0
*
* @param int $payment_id Payment ID
* @param string $type Fee type
*
* @return mixed array if payment fees found, false otherwise
*/
function give_get_payment_fees( $payment_id = 0, $type = 'all' ) {
$payment_meta = give_get_payment_meta( $payment_id );
$fees = array();
$payment_fees = isset( $payment_meta['fees'] ) ? $payment_meta['fees'] : false;
if ( ! empty( $payment_fees ) && is_array( $payment_fees ) ) {
foreach ( $payment_fees as $fee_id => $fee ) {
if ( 'all' != $type && ! empty( $fee['type'] ) && $type != $fee['type'] ) {
unset( $payment_fees[ $fee_id ] );
} else {
$fees[] = array(
'id' => $fee_id,
'amount' => $fee['amount'],
'label' => $fee['label']
);
}
}
}
return apply_filters( 'give_get_payment_fees', $fees, $payment_id );
} | gpl-2.0 |
leocockroach/JasperServer5.6 | jasperserver-remote-tests/src/test/java/com/jaspersoft/jasperserver/ws/axis/authority/UserAndRoleManagement.java | 1358 | /**
* UserAndRoleManagement.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.3 Oct 05, 2005 (05:23:37 EDT) WSDL2Java emitter.
*/
package com.jaspersoft.jasperserver.ws.axis.authority;
public interface UserAndRoleManagement extends java.rmi.Remote {
public com.jaspersoft.jasperserver.ws.authority.WSUser[] findUsers(com.jaspersoft.jasperserver.ws.authority.WSUserSearchCriteria criteria) throws java.rmi.RemoteException;
public com.jaspersoft.jasperserver.ws.authority.WSUser putUser(com.jaspersoft.jasperserver.ws.authority.WSUser user) throws java.rmi.RemoteException;
public void deleteUser(com.jaspersoft.jasperserver.ws.authority.WSUser user) throws java.rmi.RemoteException;
public com.jaspersoft.jasperserver.ws.authority.WSRole[] findRoles(com.jaspersoft.jasperserver.ws.authority.WSRoleSearchCriteria criteria) throws java.rmi.RemoteException;
public com.jaspersoft.jasperserver.ws.authority.WSRole putRole(com.jaspersoft.jasperserver.ws.authority.WSRole role) throws java.rmi.RemoteException;
public com.jaspersoft.jasperserver.ws.authority.WSRole updateRoleName(com.jaspersoft.jasperserver.ws.authority.WSRole oldRole, java.lang.String newName) throws java.rmi.RemoteException;
public void deleteRole(com.jaspersoft.jasperserver.ws.authority.WSRole role) throws java.rmi.RemoteException;
}
| gpl-2.0 |
tonygambone/henricocrime | tools/fetch.php | 182 | #!/usr/bin/env php
<?php
require_once("HenricoCrime.php");
$date = $argv[1];
$h=new HenricoCrime($date);
echo $h->get_incidents()." incidents found.\n";
$h->save_incidents();
?>
| gpl-2.0 |
shizus/farhatguitar | plugins/list-category-posts/include/lcp-catlistdisplayer.php | 17547 | <?php
/**
* This is an auxiliary class to help display the info
* on your CatList instance.
* @author fernando@picandocodigo.net
*/
require_once 'lcp-catlist.php';
class CatListDisplayer {
private $catlist;
private $params = array();
private $lcp_output;
public static function getTemplatePaths(){
$template_path = TEMPLATEPATH . "/list-category-posts/";
$stylesheet_path = STYLESHEETPATH . "/list-category-posts/";
return array($template_path, $stylesheet_path);
}
public function __construct($atts) {
$this->params = $atts;
$this->catlist = new CatList($atts);
$this->select_template();
}
public function display(){
return $this->lcp_output;
}
private function select_template(){
// Check if we got a template param:
if (isset($this->params['template']) &&
!empty($this->params['template'])){
// The default values for ul, ol and div:
if (preg_match('/^ul$|^div$|^ol$/i', $this->params['template'], $matches)){
$this->build_output($matches[0]);
} else {
// Else try an actual template from the params
$this->template();
}
} else {
// Default:
$this->build_output('ul');
}
}
/**
* Template code
*/
private function template(){
$tplFileName = null;
$template_param = $this->params['template'];
$templates = array();
// Get templates paths and add the incoming parameter to search
// for the php file:
if($template_param){
$paths = self::getTemplatePaths();
foreach($paths as $path){
$templates[] = $path . $template_param . '.php';
}
}
// Check if we can read the template file:
foreach ($templates as $file) :
if ( is_file($file) && is_readable($file) ) :
$tplFileName = $file;
endif;
endforeach;
if($tplFileName){
require($tplFileName);
} else {
$this->build_output('ul');
}
}
public static function get_templates($param = null){
$templates = array();
$paths = self::getTemplatePaths();
foreach ($paths as $templatePath){
if (is_dir($templatePath) && scandir($templatePath)){
foreach (scandir($templatePath) as $file){
// Check that the files found are well formed
if ( ($file[0] != '.') && (substr($file, -4) == '.php') &&
is_file($templatePath.$file) && is_readable($templatePath.$file) ){
$templateName = substr($file, 0, strlen($file)-4);
// Add the template only if necessary
if (!in_array($templateName, $templates)){
$templates[] = $templateName;
}
}
}
}
}
return $templates;
}
private function build_output($tag){
$this->category_title();
$this->lcp_output .= '<' . $tag;
// Follow the numner of posts in an ordered list with pagination
if( $tag == 'ol' && $this->catlist->get_page() > 1 ){
$start = $this->catlist->get_number_posts() * ($this->catlist->get_page() - 1) + 1;
$this->lcp_output .= ' start="' . $start . '" ';
}
//Give a class to wrapper tag
if (isset($this->params['class'])):
$this->lcp_output .= ' class="' . $this->params['class'] . '"';
endif;
//Give id to wrapper tag
if (isset($this->params['instance'])){
$this->lcp_output .= ' id="lcp_instance_' . $this->params['instance'] . '"';
}
$this->lcp_output .= '>';
$inner_tag = ( ($tag == 'ul') || ($tag == 'ol') ) ? 'li' : 'p';
//Posts loop
foreach ($this->catlist->get_categories_posts() as $single) :
if ( !post_password_required($single) ||
( post_password_required($single) && (
isset($this->params['show_protected']) &&
$this->params['show_protected'] == 'yes' ) )):
$this->lcp_output .= $this->lcp_build_post($single, $inner_tag);
endif;
endforeach;
if ( ($this->catlist->get_posts_count() == 0) &&
($this->params["no_posts_text"] != '') ) {
$this->lcp_output .= $this->params["no_posts_text"];
}
//Close wrapper tag
$this->lcp_output .= '</' . $tag . '>';
// More link
$this->lcp_output .= $this->get_morelink();
$this->lcp_output .= $this->get_pagination();
}
public function get_pagination(){
$pag_output = '';
if (!empty($this->params['pagination']) && $this->params['pagination'] == "yes"):
$lcp_paginator = '';
$number_posts = $this->catlist->get_number_posts();
$pages_count = ceil (
$this->catlist->get_posts_count() /
# Avoid dividing by 0 (pointed out by @rhj4)
max( array( 1, $number_posts ) )
);
if ($pages_count > 1){
for($i = 1; $i <= $pages_count; $i++){
$lcp_paginator .= $this->lcp_page_link($i);
}
$pag_output .= "<ul class='lcp_paginator'>";
// Add "Previous" link
if ($this->catlist->get_page() > 1){
$pag_output .= $this->lcp_page_link( intval($this->catlist->get_page()) - 1, $this->params['pagination_prev'] );
}
$pag_output .= $lcp_paginator;
// Add "Next" link
if ($this->catlist->get_page() < $pages_count){
$pag_output .= $this->lcp_page_link( intval($this->catlist->get_page()) + 1, $this->params['pagination_next']);
}
$pag_output .= "</ul>";
}
endif;
return $pag_output;
}
private function lcp_page_link($page, $char = null){
$current_page = $this->catlist->get_page();
$link = '';
if ($page == $current_page){
$link = "<li>$current_page</li>";
} else {
$request_uri = $_SERVER['REQUEST_URI'];
$query = $_SERVER['QUERY_STRING'];
$amp = ( strpos( $request_uri, "?") ) ? "&" : "";
$pattern = "/[&|?]?lcp_page" . preg_quote($this->catlist->get_instance()) . "=([0-9]+)/";
$query = preg_replace($pattern, '', $query);
$url = strtok($request_uri,'?');
$url = rtrim($url, '/');
$protocol = "http";
$port = $_SERVER['SERVER_PORT'];
if ( (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $port == 443){
$protocol = "https";
}
$http_host = $_SERVER['HTTP_HOST'];
$page_link = "$protocol://$http_host$url?$query" .
$amp . "lcp_page" . $this->catlist->get_instance() . "=". $page .
"#lcp_instance_" . $this->catlist->get_instance();
$link .= "<li><a href='$page_link' title='$page'>";
($char != null) ? ($link .= $char) : ($link .= $page);
$link .= "</a></li>";
}
// WA: Replace '?&' by '?' to avoid potential redirection problems later on
$link = str_replace('?&', '?', $link );
return $link;
}
/**
* This function should be overriden for template system.
* @param post $single
* @param HTML tag to display $tag
* @return string
*/
private function lcp_build_post($single, $tag){
global $post;
$class ='';
if ( is_object($post) && is_object($single) && $post->ID == $single->ID ){
$class = " class = current ";
}
$lcp_display_output = '<'. $tag . $class . '>';
if ( empty($this->params['no_post_titles']) || !empty($this->params['no_post_titles']) && $this->params['no_post_titles'] !== 'yes' ) {
$lcp_display_output .= $this->get_post_title($single);
}
// Comments count
$lcp_display_output .= $this->get_stuff_with_tags_and_classes('comments', $single);
// Date
if (!empty($this->params['date_tag']) || !empty($this->params['date_class'])):
$lcp_display_output .= $this->get_date($single,
$this->params['date_tag'],
$this->params['date_class']);
else:
$lcp_display_output .= $this->get_date($single);
endif;
// Date Modified
if (!empty($this->params['date_modified_tag']) || !empty($this->params['date_modified_class'])):
$lcp_display_output .= $this->get_modified_date($single,
$this->params['date_modified_tag'],
$this->params['date_modified_class']);
else:
$lcp_display_output .= $this->get_modified_date($single);
endif;
// Author
$lcp_display_output .= $this->get_stuff_with_tags_and_classes('author', $single);
// Display ID
if (!empty($this->params['display_id']) && $this->params['display_id'] == 'yes'){
$lcp_display_output .= $single->ID;
}
// Custom field display
$lcp_display_output .= $this->get_custom_fields($single);
$lcp_display_output .= $this->get_thumbnail($single);
$lcp_display_output .= $this->get_stuff_with_tags_and_classes('content', $single);
if (!empty($this->params['excerpt_tag'])):
if (!empty($this->params['excerpt_class'])):
$lcp_display_output .= $this->get_excerpt($single,
$this->params['excerpt_tag'],
$this->params['excerpt_class']);
else:
$lcp_display_output .= $this->get_excerpt($single, $this->params['excerpt_tag']);
endif;
else:
$lcp_display_output .= $this->get_excerpt($single);
endif;
$lcp_display_output .= $this->get_posts_morelink($single);
$lcp_display_output .= '</' . $tag . '>';
return $lcp_display_output;
}
private function get_stuff_with_tags_and_classes($entity, $single){
$result = '';
$stuffFunction = 'get_' . $entity;
if (!empty($this->params[$entity . '_tag'])):
if (!empty($this->params[$entity . '_class'])):
$result = $this->$stuffFunction($single, $this->params[$entity . '_tag'], $this->params[$entity . '_class']);
else:
$result = $this->$stuffFunction($single, $this->params[$entity . '_tag']);
endif;
else:
$result = $this->$stuffFunction($single);
endif;
return $result;
}
private function category_title(){
// More link
if (!empty($this->params['catlink_tag'])):
if (!empty($this->params['catlink_class'])):
$this->lcp_output .= $this->get_category_link(
$this->params['catlink_tag'],
$this->params['catlink_class']
);
else:
$this->lcp_output .= $this->get_category_link($this->params['catlink_tag']);
endif;
else:
$this->lcp_output .= $this->get_category_link("strong");
endif;
}
/**
* Auxiliary functions for templates
*/
private function get_comments($single, $tag = null, $css_class = null){
return $this->content_getter('comments', $single, $tag, $css_class);
}
private function get_author($single, $tag = null, $css_class = null){
return $this->content_getter('author', $single, $tag, $css_class);
}
private function get_content($single, $tag = null, $css_class = null){
return $this->content_getter('content', $single, $tag, $css_class);
}
private function get_excerpt($single, $tag = null, $css_class = null){
return $this->content_getter('excerpt', $single, $tag, $css_class);
}
/*
* These used to be separate functions, now starting to get the code
* in the same function for less repetition.
*/
private function content_getter($type, $post, $tag = null, $css_class = null) {
$info = '';
switch( $type ){
case 'comments':
$info = $this->catlist->get_comments_count($post);
break;
case 'author':
$info = $this->catlist->get_author_to_show($post);
break;
case 'content':
$info = $this->catlist->get_content($post);
break;
case 'excerpt':
$info = $this->catlist->get_excerpt($post);
$info = preg_replace('/\[.*\]/', '', $info);
}
return $this->assign_style($info, $tag, $css_class);
}
private function get_custom_fields($single){
if(!empty($this->params['customfield_display'])){
$info = $this->catlist->get_custom_fields($this->params['customfield_display'], $single->ID);
if(empty($this->params['customfield_tag']) || $this->params['customfield_tag'] == null)
$tag = 'div';
if(empty($this->params['customfield_class']) || $this->params['customfield_class'] == null)
$css_class = 'lcp_customfield';
return $this->assign_style($info, $tag, $css_class);
}
}
private function get_date($single, $tag = null, $css_class = null){
$info = " " . $this->catlist->get_date_to_show($single);
return $this->assign_style($info, $tag, $css_class);
}
private function get_modified_date($single, $tag = null, $css_class = null){
$info = " " . $this->catlist->get_modified_date_to_show($single);
return $this->assign_style($info, $tag, $css_class);
}
private function get_thumbnail($single, $tag = null){
if ( !empty($this->params['thumbnail_class']) ) :
$lcp_thumb_class = $this->params['thumbnail_class'];
$info = $this->catlist->get_thumbnail($single, $lcp_thumb_class);
else:
$info = $this->catlist->get_thumbnail($single);
endif;
return $this->assign_style($info, $tag);
}
// Link is a parameter here in case you want to use it on a template
// and not show the links for all the shortcodes using this template:
private function get_post_title($single, $tag = null, $css_class = null, $link = true){
$lcp_post_title = apply_filters('the_title', $single->post_title, $single->ID);
if ( !empty($this->params['title_limit']) && $this->params['title_limit'] !== "0" ):
$title_limit = intval($this->params['title_limit']);
if( function_exists('mb_strlen') && function_exists('mb_substr') ):
if( mb_strlen($lcp_post_title) > $title_limit ):
$lcp_post_title = mb_substr($lcp_post_title, 0, $title_limit) . "…";
endif;
else:
if( strlen($lcp_post_title) > $title_limit ):
$lcp_post_title = substr($lcp_post_title, 0, $title_limit) . "…";
endif;
endif;
endif;
if (!empty($this->params['title_tag'])){
$pre = "<" . $this->params['title_tag'];
if (!empty($this->params['title_class'])){
$pre .= ' class="' . $this->params['title_class'] . '"';
}
$pre .= '>';
$post = "</" . $this->params['title_tag'] . ">";
}else{
$pre = $post = '';
}
if ( !$link ||
(!empty($this->params['link_titles']) &&
( $this->params['link_titles'] === "false" || $this->params['link_titles'] === "no" ) ) ) {
return $pre . $lcp_post_title . $post;
}
$info = '<a href="' . get_permalink($single->ID) . '" title="' . wptexturize($single->post_title) . '"';
if (!empty($this->params['link_target'])):
$info .= ' target="' . $this->params['link_target'] . '" ';
endif;
if ( !empty($this->params['title_class'] ) &&
empty($this->params['title_tag']) ):
$info .= ' class="' . $this->params['title_class'] . '"';
endif;
$info .= '>' . $lcp_post_title . '</a>';
if( !empty($this->params['post_suffix']) ):
$info .= " " . $this->params['post_suffix'];
endif;
$info = $pre . $info . $post;
if( $tag !== null || $css_class !== null){
$info = $this->assign_style($info, $tag, $css_class);
}
return $info;
}
private function get_posts_morelink($single){
if(!empty($this->params['posts_morelink'])){
$href = 'href="' . get_permalink($single->ID) . '"';
$class = "";
if ( !empty($this->params['posts_morelink_class']) ):
$class = 'class="' . $this->params['posts_morelink_class'] . '" ';
endif;
$readmore = $this->params['posts_morelink'];
return ' <a ' . $href . ' ' . $class . ' >' . $readmore . '</a>';
}
}
private function get_category_link($tag = null, $css_class = null){
$info = $this->catlist->get_category_link();
return $this->assign_style($info, $tag, $css_class);
}
private function get_morelink(){
$info = $this->catlist->get_morelink();
if ( !empty($this->params['morelink_tag'])){
if( !empty($this->params['morelink_class']) ){
return "<" . $this->params['morelink_tag'] . " class='" .
$this->params['morelink_class'] . "'>" . $info .
"</" . $this->params["morelink_tag"] . ">";
} else {
return "<" . $this->params['morelink_tag'] . ">" .
$info . "</" . $this->params["morelink_tag"] . ">";
}
} else{
if ( !empty($this->params['morelink_class']) ){
return str_replace("<a", "<a class='" . $this->params['morelink_class'] . "' ", $info);
}
}
return $info;
}
private function get_category_count(){
return $this->catlist->get_category_count();
}
/**
* Assign style to the info delivered by CatList. Tag is an HTML tag
* which is passed and will sorround the info. Css_class is the css
* class we want to assign to this tag.
* @param string $info
* @param string $tag
* @param string $css_class
* @return string
*/
private function assign_style($info, $tag = null, $css_class = null){
if (!empty($info)):
if (empty($tag) && !empty($css_class)):
$tag = "span";
elseif (empty($tag)):
return $info;
elseif (!empty($tag) && empty($css_class)) :
return '<' . $tag . '>' . $info . '</' . $tag . '>';
endif;
$css_class = sanitize_html_class($css_class);
return '<' . $tag . ' class="' . $css_class . '">' . $info . '</' . $tag . '>';
endif;
}
}
| gpl-2.0 |
LulzJs/DaDumpster | random/code/classExample.js | 1521 | 'use strict'
//Abstractiun type 1
function Apple (type, color) {
this.type = type;
this.color = color;
this.ToString = function() {
return 'Apple: ' + this.type + ' ' + this.color;
};
}
//Abstractiun type 2
function Pear (type, color){
this.type = type;
this.color = color;
}
Pear.prototype.ToString = function() {
return 'Pear: ' + this.type + ' ' + this.color;
};
//Abstractiun type 3
class fruit {
constructor(type, color) {
this.type = type;
this.color = color;
}
ToString() {
return this.type + ' ' + this.color;
}
}
class Melon extends fruit {
constructor(type, color, extra) {
super(type, color);
this.extra = extra;
}
get Extra() {
return this.extra;
}
set Extra(extra) {
this.extra = extra;
}
ToString() {
return 'Melon '+ this.extra +': ' + super.ToString();
}
static Join(first, second) {
var hibrid = new Melon(first.type, second.color, 'whatever');
return hibrid;
}
}
//Test
var apple = new Apple('normal', 'red');
var pear = new Pear('normal', 'green');
var melon1 = new Melon('normal', 'yellow', 'sand');
console.log(apple.ToString());
console.log(pear.ToString());
console.log(melon1.ToString());
//Test Class
var melon2 = new Melon('rear', 'pink', 'water');
var melon3 = Melon.Join(melon1, melon2);
console.log(melon1.ToString());
console.log(melon2.ToString());
console.log(melon3.ToString());
console.log(melon3.Extra);
melon3.Extra = 'water';
console.log(melon3.Extra);
| gpl-2.0 |
fritids/embroideryadvertisers | wp-content/plugins/mailpress/mp-includes/js/fileupload/si.files.js | 1284 | // STYLING FILE INPUTS 1.0 | Shaun Inman <http://www.shauninman.com/> | 2007-09-07
if (!window.SI) { var SI = {}; };
SI.Files =
{
htmlClass : 'SI-FILES-STYLIZED',
fileClass : 'file',
wrapClass : 'cabinet',
fini : false,
able : false,
stylize : function(elem)
{
if (!this.fini) { this.init(); };
if (!this.able) { return; };
elem.parentNode.file = elem;
},
stylizeById : function(id)
{
this.stylize(document.getElementById(id));
},
stylizeAll : function()
{
if (!this.fini) { this.init(); };
if (!this.able) { return; };
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++)
{
var input = inputs[i];
if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass) != -1)
{
this.stylize(input);
};
};
},
init : function()
{
this.fini = true;
var ie = 0 //@cc_on + @_jscript_version
if (window.opera || (ie && ie < 5.5) || !document.getElementsByTagName) { return; } // no support for opacity or the DOM
this.able = true;
var html = document.getElementsByTagName('html')[0];
html.className += (html.className != '' ? ' ' : '') + this.htmlClass;
}
}; | gpl-2.0 |
timofeysie/myra | .c9/metadata/workspace/config/application.rb | 431 | {"filter":false,"title":"application.rb","tooltip":"/config/application.rb","undoManager":{"mark":0,"position":-1,"stack":[]},"ace":{"folds":[],"scrolltop":0,"scrollleft":0,"selection":{"start":{"row":23,"column":0},"end":{"row":23,"column":0},"isBackwards":false},"options":{"guessTabSize":true,"useWrapMode":false,"wrapToView":true},"firstLineState":0},"timestamp":1410173277000,"hash":"bded8db1b445236e1e9bfec6d1f18b93ae56a842"} | gpl-2.0 |
Automattic/simplenote-electron | lib/icons/simplenote.tsx | 855 | import React from 'react';
export default function SimplenoteLogo() {
return (
<svg className="logo" width="96" height="96" viewBox="0 0 176 176">
<g fillRule="evenodd" clipRule="evenodd">
<circle cx="88" cy="88" r="88" fill="#fff" />
<path
d="M152.37 87.885c0-34.066-27.182-63.42-59.45-64.854-6.416-.284-12.647 1.432-17.58 5.573-5.002 4.196-8.07 10.09-8.638 16.595C65.43 59.73 78.537 68.618 91.225 72.09c30.69 8.398 48.462 30.086 46.655 56.757 9.057-11.194 14.49-25.442 14.49-40.962zM84.345 97.24c-28.696-7.853-45.817-29.174-43.62-54.317.027-.287.073-.567.102-.852C29.19 53.846 22 70.023 22 87.886c0 34.348 27.955 63.828 60.277 64.933 7.227.248 14.214-1.685 19.766-6.344 5.67-4.757 9.146-11.435 9.79-18.808 1.703-19.463-16.492-27.417-27.488-30.426z"
fill="#4895d9"
/>
</g>
</svg>
);
}
| gpl-2.0 |
DB-SE/isp2014.anne.reich | task2/MangaDB/src/isp1415/ar/guiPack/Bibo.java | 33036 | package isp1415.ar.guiPack;
import isp1415.ar.Main;
import isp1415.ar.dbPack.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.BadLocationException;
public class Bibo {
private JFrame fenster;
private static JLabel lName;
private static String sName;
private static JLabel lZeichner;
private static JLabel lVerlag;
private static JLabel lHab;
private static JLabel lAnz;
private static JLabel lStatus;
private static JLabel lKosten;
private static JLabel lNext;
private static JScrollPane gesamtList;
private static JTextField textField;
private static JList<String> list;
private static int searchAuswahl = 0;
private static ArrayList<String> treffer;
private static DB db;
private static XML xml;
private static boolean[] features = Main.features;
private static String[][] mangaList;
private String[][] mangaListSort;
private static String[] mangaDetail;
public Bibo(DB dao) throws SQLException{
db = dao;
getTitelColorList();
fensterErzeugen();
}
public Bibo(XML xml) throws SQLException{
Bibo.xml = xml;
getTitelColorList();
fensterErzeugen();
}
private void fensterErzeugen() throws SQLException {
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// TODO START
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//JFrame fenster erstellen
fenster = new JFrame("Anne's Manga Bibliothek");
//Größe bestimmen
fenster.setSize(500, 600);
fenster.setLocationRelativeTo(null);
fenster.setResizable(false);
//Gesamtfläche die das Fenster abdeckt
JPanel flaeche = new JPanel();
flaeche.setLayout(new BorderLayout());
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// TODO BUTTON-SORTIERUNG + SUCHE (oben)
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
JPanel obenAll = new JPanel();
obenAll.setLayout(new BorderLayout());
// TODO Buchstaben Buttons
if(features[2]){
JPanel abcPanel = new JPanel();
abcPanel.setLayout(new GridLayout(4,0));
abcPanel.setPreferredSize(new Dimension(0,70));
abcPanel.setBorder(new EmptyBorder(5,3,0,3));
JButton sonder = new JButton("+.0-9");
sonder.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("^[A-Z]");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(sonder);
JButton a = new JButton("A");
a.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("A");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(a);
JButton b = new JButton("B");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("B");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(b);
JButton c = new JButton("C");
c.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("C");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(c);
JButton d = new JButton("D");
d.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("D");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(d);
JButton e = new JButton("E");
e.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("E");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(e);
JButton f = new JButton("F");
f.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("F");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(f);
JButton g = new JButton("G");
g.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("G");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(g);
JButton h = new JButton("H");
h.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("H");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(h);
JButton i = new JButton("I");
i.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("I");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(i);
JButton j = new JButton("J");
j.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("J");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(j);
JButton k = new JButton("K");
k.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("K");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(k);
JButton l = new JButton("L");
l.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("L");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(l);
JButton m = new JButton("M");
m.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("M");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(m);
JButton n = new JButton("N");
n.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("N");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(n);
JButton o = new JButton("O");
o.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("O");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(o);
JButton p = new JButton("P");
p.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("P");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(p);
JButton q = new JButton("Q");
q.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("Q");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(q);
JButton r = new JButton("R");
r.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("R");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(r);
JButton s = new JButton("S");
s.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("S");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(s);
JButton t = new JButton("T");
t.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("T");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(t);
JButton u = new JButton("U");
u.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("U");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(u);
JButton v = new JButton("V");
v.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("V");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(v);
JButton w = new JButton("W");
w.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("W");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(w);
JButton x = new JButton("X");
x.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("X");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(x);
JButton y = new JButton("Y");
y.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("Y");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(y);
JButton z = new JButton("Z");
z.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try {
sortierung("Z");
klick();
gesamtList.getViewport().setView(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
abcPanel.add(z);
JButton az = new JButton("A-Z");
az.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
sammlung();
klick();
gesamtList.getViewport().setView(list);
}
});
abcPanel.add(az);
obenAll.add(abcPanel, BorderLayout.PAGE_START);
}
// TODO Suche-Bereich
if(!features[2]){
JPanel suchePanel = new JPanel();
suchePanel.setLayout(new BorderLayout());
suchePanel.setBorder(new EmptyBorder(0,3,5,3));
//Combo-Box
String[] nachList = {"nach Titel:", "nach Autor:", "nach Verlag:"};
final JComboBox<String> nach = new JComboBox<String>(nachList);
nach.setPreferredSize(new Dimension(112, 25));
setTrefferList(searchAuswahl);
//erkennt, welche Suche-Auswahl aktiviert ist (nach Zahlen)
nach.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try {
searchAuswahl = nach.getSelectedIndex();
setTrefferList(searchAuswahl);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
suchePanel.add(nach, BorderLayout.LINE_START);
//Textfeld
textField = new JTextField(50);
suchePanel.add(textField, BorderLayout.CENTER);
autoComplete();
//Suchen-Button
JButton suchButton = new JButton();
suchButton.addActionListener(new ActionListener(){
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent arg0) {
String match = textField.getText();
ArrayList<String> matchTitelDmy = new ArrayList<String>();
//alle Möglichkeiten abfangen
if(searchAuswahl == 0){
matchTitelDmy.add(match);
}
else{
try {
if(searchAuswahl == 1)
matchTitelDmy = getTitelByAutor(match);
else
matchTitelDmy = getTitelByVerlag(match);
} catch (SQLException e) {
e.printStackTrace();
}
}
//diese in String[] packen
String[] matchTitel = new String[matchTitelDmy.size()];
for(int j = 0; j < matchTitelDmy.size(); j++){
matchTitel[j] = matchTitelDmy.get(j);
}
list = new JList<String>(matchTitel);
String[] farbe = getFarbe(matchTitel);
list.setCellRenderer(new TitelFarbe(farbe));
klick();
gesamtList.getViewport().setView(list);
}
});
try {
BufferedImage bi = ImageIO.read(ImageIO.class.getResource("/suchenIcon.gif"));
suchButton.setIcon(new ImageIcon(bi));
} catch (IOException e2) {
e2.printStackTrace();
}
suchButton.setPreferredSize(new Dimension(25, 25));
suchePanel.add(suchButton, BorderLayout.LINE_END);
obenAll.add(suchePanel, BorderLayout.CENTER);
}
// TODO zurück + neuerManga-Button
JPanel backnewPanel = new JPanel();
backnewPanel.setLayout(new BorderLayout());
backnewPanel.setBorder(new EmptyBorder(0,3,5,3));
//back-Button führt zur Startseite zurück
JButton back = new JButton();
back.setPreferredSize(new Dimension(25,25));
try {
BufferedImage bi = ImageIO.read(ImageIO.class.getResource("/backIcon.gif"));
back.setIcon(new ImageIcon(bi));
} catch (IOException e2) {
e2.printStackTrace();
}
back.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try {
if(db != null)
new Start(db,2);
else
new Start(xml);
fenster.setVisible(false);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
backnewPanel.add(back, BorderLayout.LINE_START);
//neu-Button öffnet die manga-erstell-seite
JButton neu = new JButton("Neuer Manga");
neu.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(db != null)
new NeuEditDetail(db, "neu", "-");
else
new NeuEditDetail(xml, "neu", "-");
fenster.setVisible(false);
}
});
neu.setPreferredSize(new Dimension(112,20));
backnewPanel.add(neu, BorderLayout.LINE_END);
obenAll.add(backnewPanel, BorderLayout.PAGE_END);
flaeche.add(obenAll, BorderLayout.PAGE_START);
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// TODO SAMMLUNG (mitte)
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
JPanel samml = new JPanel();
samml.setLayout(new BorderLayout());
samml.setBorder(new EmptyBorder(0,3,0,3));
sammlung();
klick();
gesamtList = new JScrollPane(list);
samml.add(gesamtList, BorderLayout.CENTER);
flaeche.add(samml, BorderLayout.CENTER);
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// TODO DATEN + BUTTON (unten)
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
JPanel detailseditPanel = new JPanel();
detailseditPanel.setLayout(new BorderLayout());
detailseditPanel.setBorder(new EmptyBorder(5,0,5,0));
if(features[3]){
JPanel detailPanel = new JPanel();
detailPanel.setLayout(new GridLayout(0,2));
detailPanel.setBorder(new EmptyBorder(0,3,0,3));
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BorderLayout());
JPanel leftText = new JPanel();
leftText.setPreferredSize(new Dimension(60, 65));
leftText.setLayout(new GridLayout(4,0));
JLabel name = new JLabel("Titel:");
leftText.add(name);
JLabel autor = new JLabel("Zeichner:");
leftText.add(autor);
JLabel verlag = new JLabel("Verlag:");
leftText.add(verlag);
JLabel status = new JLabel("Status:");
leftText.add(status);
leftPanel.add(leftText, BorderLayout.LINE_START);
JPanel leftValue = new JPanel();
leftValue.setLayout(new GridLayout(4,0));
lName = new JLabel();
leftValue.add(lName);
lZeichner = new JLabel();
leftValue.add(lZeichner);
lVerlag = new JLabel();
leftValue.add(lVerlag);
lStatus = new JLabel();
leftValue.add(lStatus);
leftPanel.add(leftValue, BorderLayout.CENTER);
detailPanel.add(leftPanel);
//-------
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BorderLayout());
JPanel rightText = new JPanel();
rightText.setPreferredSize(new Dimension(95, 65));
rightText.setLayout(new GridLayout(4,0));
JLabel hab = new JLabel("Habe ich:");
rightText.add(hab);
JLabel gibt = new JLabel("Gibt es:");
rightText.add(gibt);
JLabel kosten = new JLabel("Gesamtkosten:");
rightText.add(kosten);
JLabel next = new JLabel("Naechster Band:");
rightText.add(next);
rightPanel.add(rightText, BorderLayout.LINE_START);
JPanel rightValue = new JPanel();
rightValue.setLayout(new GridLayout(4,0));
lHab = new JLabel();
rightValue.add(lHab);
lAnz = new JLabel();
rightValue.add(lAnz);
lKosten = new JLabel();
rightValue.add(lKosten);
lNext = new JLabel();
rightValue.add(lNext);
rightPanel.add(rightValue, BorderLayout.CENTER);
detailPanel.add(rightPanel);
detailseditPanel.add(detailPanel, BorderLayout.CENTER);
}
//TODO: Edit + Detail Button
JPanel edButtonsPanel = new JPanel();
edButtonsPanel.setLayout(new GridLayout(0,2));
JPanel buttonEdit = new JPanel();
buttonEdit.setBorder(new EmptyBorder(0,3,0,155));
JButton edit = new JButton("Editieren");
edit.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{
if(sName != null){
if(db != null)
new NeuEditDetail(db, "Edit" ,sName);
else
new NeuEditDetail(xml, "Edit" ,sName);
fenster.setVisible(false);
}
}
} );
buttonEdit.add(edit);
edButtonsPanel.add(buttonEdit);
JPanel buttonDetail = new JPanel();
buttonDetail.setBorder(new EmptyBorder(0,0,0,110));
JButton details = new JButton("Baender Uebersicht");
details.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent evt)
{
if(sName != null)
if(db != null)
new NeuEditDetail(db, "Detail", sName);
else
new NeuEditDetail(xml, "Detail", sName);
}
});
buttonDetail.add(details);
edButtonsPanel.add(buttonDetail);
detailseditPanel.add(edButtonsPanel, BorderLayout.PAGE_END);
//------------
flaeche.add(detailseditPanel, BorderLayout.PAGE_END);
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// TODO ENDE
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
fenster.add(flaeche);
fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Fenster sichtbar machen
fenster.setVisible(true);
}
private static void autoComplete() {
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent arg0) {}
public void insertUpdate(DocumentEvent ev) {
String completion;
int pos = ev.getOffset();
String content = null;
try {
content = textField.getText(0, pos+1);
} catch (BadLocationException ex) {
ex.printStackTrace();
}
int w;
for (w = pos; w >= 0; w--) {
}
if (pos - w < 2) {
return;
}
final String prefix = content.substring(w + 1);
int n = Collections.binarySearch(treffer, prefix);
if (n < 0 && -n <= treffer.size()) {
final String match = treffer.get(-n-1);
if (match.startsWith(prefix)) {
completion = match.substring(pos - w);
SwingUtilities.invokeLater(new CompletionTask(completion, pos + 1));
textField.addKeyListener(new KeyListener() {
@SuppressWarnings("unchecked")
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyCode() == KeyEvent.VK_ENTER) {
if(textField.getText().length()!=0){
ArrayList<String> matchTitelDmy = new ArrayList<String>();
//alle Möglichkeiten abfangen
if(searchAuswahl == 0){
for(int i = 0; i < treffer.size(); i++){
if(treffer.get(i).startsWith(prefix))
matchTitelDmy.add(treffer.get(i));
}
}
else{
try {
if(searchAuswahl == 1)
matchTitelDmy = getTitelByAutor(match);
else
matchTitelDmy = getTitelByVerlag(match);
} catch (SQLException e) {
e.printStackTrace();
}
}
//diese in String[] packen
String[] matchTitel = new String[matchTitelDmy.size()];
for(int j = 0; j < matchTitelDmy.size(); j++){
matchTitel[j] = matchTitelDmy.get(j);
}
list = new JList<String>(matchTitel);
String[] farbe = getFarbe(matchTitel);
list.setCellRenderer(new TitelFarbe(farbe));
klick();
gesamtList.getViewport().setView(list);
}
else{
String[] liste = new String[mangaList.length];
for(int i = 0; i < mangaList.length; i++){
liste[i] = mangaList[i][0];
}
list = new JList<String>(liste);
String[] farbe = getFarbe(liste);
list.setCellRenderer(new TitelFarbe(farbe));
klick();
gesamtList.getViewport().setView(list);
}
}
else if(arg0.getKeyCode() == KeyEvent.VK_RIGHT){
ArrayList<String> matchTitelDmy = new ArrayList<String>();
//alle Möglichkeiten abfangen
if(searchAuswahl == 0){
matchTitelDmy.add(match);
}
else{
try {
if(searchAuswahl == 1)
matchTitelDmy = getTitelByAutor(match);
else
matchTitelDmy = getTitelByVerlag(match);
} catch (SQLException e) {
e.printStackTrace();
}
}
//diese in String[] packen
String[] matchTitel = new String[matchTitelDmy.size()];
for(int j = 0; j < matchTitelDmy.size(); j++){
matchTitel[j] = matchTitelDmy.get(j);
}
list = new JList<String>(matchTitel);
String[] farbe = getFarbe(matchTitel);
list.setCellRenderer(new TitelFarbe(farbe));
klick();
gesamtList.getViewport().setView(list);
}
}
public void keyReleased(KeyEvent arg0) {}
public void keyTyped(KeyEvent arg0) {}
});
}
}
}
public void removeUpdate(DocumentEvent arg0) {}
});
}
private static class CompletionTask implements Runnable {
String completion;
int position;
CompletionTask(String completion, int position) {
this.completion = completion;
this.position = position;
}
public void run() {
textField.setText(textField.getText() + completion);
textField.setCaretPosition(position + completion.length());
textField.moveCaretPosition(position);
}
}
@SuppressWarnings("unchecked")
private void sammlung(){
String[] samml = new String[mangaList.length];
String[] farbe = new String[mangaList.length];
for(int i = 0; i < mangaList.length; i++){
samml[i] = mangaList[i][0];
farbe[i] = mangaList[i][1];
}
list = new JList<String>(samml);
list.setCellRenderer(new TitelFarbe(farbe));
}
@SuppressWarnings("unchecked")
private void sortierung(String letter) throws SQLException{
getTitelColorListSort(letter);
String[] samml = new String[mangaListSort.length];
String[] farbe = new String[mangaListSort.length];
for(int i = 0; i < mangaListSort.length; i++){
samml[i] = mangaListSort[i][0];
farbe[i] = mangaListSort[i][1];
}
list = new JList<String>(samml);
list.setCellRenderer(new TitelFarbe(farbe));
}
private static void klick(){
list.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e) {
try {
if(list.getSelectedValue() != null){
String select = list.getSelectedValue().toString();
getMangaInfo(select);
sName = mangaDetail[0];
if(features[3]){
lName.setText(mangaDetail[0]);
lName.setToolTipText(mangaDetail[0]);
lZeichner.setText(mangaDetail[1]);
lZeichner.setToolTipText(mangaDetail[1]);
lVerlag.setText(mangaDetail[2]);
lVerlag.setToolTipText(mangaDetail[2]);
lHab.setText(mangaDetail[3]);
lAnz.setText(mangaDetail[4]);
lStatus.setText(mangaDetail[5]);
lKosten.setText(mangaDetail[6]);
lNext.setText(mangaDetail[7]);
}
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
list.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2){
if(db != null)
new NeuEditDetail(db, "Detail", list.getSelectedValue().toString());
else
new NeuEditDetail(xml, "Detail", list.getSelectedValue().toString());
}
}
});
}
private void setTrefferList(int auswahl) throws SQLException{
treffer = new ArrayList<String>();
if(auswahl == 0){
String[] titelListe = getOnlyTitelList();
for(int i = 0; i < titelListe.length; i++){
treffer.add(titelListe[i]);
}
Collections.sort(treffer);
}
else if(auswahl == 1){
String[] autorListe = getAutorList();
//fülle Treffer aus
for(int i = 0; i < autorListe.length; i++){
treffer.add(autorListe[i]);
}
Collections.sort(treffer);
}
else{
String[] verlagListe = getVerlagList();
for(int i = 0; i < verlagListe.length; i++){
treffer.add(verlagListe[i]);
}
Collections.sort(treffer);
}
}
private static String[] getFarbe(String[] matchList){
String[] matchFarbe = new String[matchList.length];
for(int i = 0; i < matchList.length; i++){
for(int j = 0; j < mangaList.length; j++){
if(matchList[i] != null && matchList[i].equals(mangaList[j][0]) ){
matchFarbe[i] = mangaList[j][1];
}
}
}
return matchFarbe;
}
private void getTitelColorList() throws SQLException {
if(db != null)
mangaList = db.getMangareiheTitel();
else
mangaList = xml.getMangareiheTitel();
}
private void getTitelColorListSort(String letter) throws SQLException{
if(db != null)
mangaListSort = db.getReiheStartsWith(letter);
else
mangaListSort = xml.getReiheStartsWith(letter);
}
private static void getMangaInfo(String mangaTitel) throws SQLException{
if(db != null)
mangaDetail = db.getBiboDetails(mangaTitel);
else
mangaDetail = xml.getBiboDetails(mangaTitel);
}
private String[] getAutorList() throws SQLException{
if(db != null)
return db.getAutor();
else
return xml.getAutor();
}
private static ArrayList<String> getTitelByAutor(String autor) throws SQLException{
String[] titel;
if(db != null)
titel = db.getTitelByAutor(autor);
else
titel = xml.getTitelByAutor(autor);
ArrayList<String> arrTitel = new ArrayList<String>();
Collections.sort(arrTitel);
for(int i = 0; i < titel.length; i++){
arrTitel.add(titel[i]);
}
return arrTitel;
}
private String[] getVerlagList() throws SQLException{
if(db != null)
return db.getVerlag();
else
return xml.getVerlag();
}
private static ArrayList<String> getTitelByVerlag(String verlag) throws SQLException{
String[] titel;
if(db != null)
titel = db.getTitelByVerlag(verlag);
else
titel = xml.getTitelByVerlag(verlag);
ArrayList<String> arrTitel = new ArrayList<String>();
Collections.sort(arrTitel);
for(int i = 0; i < titel.length; i++){
arrTitel.add(titel[i]);
}
return arrTitel;
}
private String[] getOnlyTitelList() throws SQLException{
String[][] titelListe;
if(db != null)
titelListe = db.getMangareiheTitel();
else
titelListe = xml.getMangareiheTitel();
String[] titel = new String[titelListe.length];
for(int i = 0; i < titelListe.length; i++){
titel[i] = titelListe[i][0];
}
return titel;
}
@SuppressWarnings({ "serial", "rawtypes" })
static class TitelFarbe extends JLabel implements ListCellRenderer{
private String[] color;
public TitelFarbe(String[] color){
setOpaque(true);
this.color = color;
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if(value != null){
setText(value.toString());
if(isSelected){
setBorder(BorderFactory.createLineBorder(Color.black));
}
else{
setBorder(new EmptyBorder(0,0,0,0));
}
if(color[index].equals("gruen")){
setBackground(Color.GREEN);
}
else if(color[index].equals("rot")){
setBackground(Color.RED);
}
else{
setBackground(Color.YELLOW);
}
return this;
}
else{
setBackground(Color.WHITE);
setText("");
return this;
}
}
}
}
| gpl-2.0 |