code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
/*!
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2002-2013 Pentaho Corporation.. All rights reserved.
*/
package org.pentaho.reporting.designer.core.actions.report.export;
import org.pentaho.reporting.engine.classic.core.modules.gui.csv.CSVTableExportPlugin;
/**
* Todo: Document Me
*
* @author Ezequiel Cuellar
*/
public final class ExportCsvAction extends AbstractExportAction {
public ExportCsvAction() {
super( new CSVTableExportPlugin() );
}
}
| EgorZhuk/pentaho-reporting | designer/report-designer/src/main/java/org/pentaho/reporting/designer/core/actions/report/export/ExportCsvAction.java | Java | lgpl-2.1 | 1,180 |
# -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# ####################################################################
""" Loaders plugin manager """
from __future__ import print_function
import os.path
from fife import fife
from fife.extensions.serializers.xmlmap import XMLMapLoader
mapFileMapping = { 'xml' : XMLMapLoader}
fileExtensions = set(['xml'])
def loadMapFile(path, engine, callback=None, debug=True, extensions={}):
""" load map file and get (an optional) callback if major stuff is done:
- map creation
- parsed imports
- parsed layers
- parsed cameras
the callback will send both a string and a float (which shows
the overall process), callback(string, float)
@type engine: object
@param engine: FIFE engine instance
@type callback: function
@param callback: callback for maploading progress
@type debug: bool
@param debug: flag to activate / deactivate print statements
@rtype object
@return FIFE map object
"""
(filename, extension) = os.path.splitext(path)
map_loader = mapFileMapping[extension[1:]](engine, callback, debug, extensions)
map = map_loader.loadResource(path)
if debug: print("--- Loading map took: ", map_loader.time_to_load, " seconds.")
return map
def addMapLoader(fileExtension, loaderClass):
"""Add a new loader for fileextension
@type fileExtension: string
@param fileExtension: The file extension the loader is registered for
@type loaderClass: object
@param loaderClass: A fife.ResourceLoader implementation that loads maps
from files with the given fileExtension
"""
mapFileMapping[fileExtension] = loaderClass
_updateMapFileExtensions()
def _updateMapFileExtensions():
global fileExtensions
fileExtensions = set(mapFileMapping.keys())
| fifengine/fifengine | engine/python/fife/extensions/loaders.py | Python | lgpl-2.1 | 2,646 |
/*
===============================================================================
FILE: pulsedescriptor.hpp
CONTENTS:
Describes the way that outgoing and returning waveform of a pulse is stored
in the PulseWaves. There can be multiple pulsedescriptors each describing a
different composition of samplings.
PROGRAMMERS:
martin.isenburg@rapidlasso.com - http://rapidlasso.com
COPYRIGHT:
(c) 2007-2013, martin isenburg, rapidlasso - fast tools to catch reality
This is free software; you can redistribute and/or modify it under the
terms of the GNU Lesser General Licence as published by the Free Software
Foundation. See the COPYING.txt file for more information.
This software is distributed WITHOUT ANY WARRANTY and without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
CHANGE HISTORY:
02 March 2012 -- created before celebrating Silke's birthday at Hafen 2
===============================================================================
*/
#ifndef PULSE_DESCRIPTOR_HPP
#define PULSE_DESCRIPTOR_HPP
#include "mydefs.hpp"
#include "pulsewavesdefinitions.hpp"
class ByteStreamIn;
class ByteStreamOut;
class PULSEsampling
{
public:
// start of attributes
U32 size; // byte-aligned size from start to end of attributes (including the PULSEWAVES_DESCRIPTION_SIZE bytes for description)
U32 reserved; // must be zero
U8 type; // 0 - undefined, 1 - outgoing, 2 - returning
U8 channel;
U8 unused; // must be zero
U8 bits_for_duration_from_anchor; // 0, 8, 16, or 32
F32 scale_for_duration_from_anchor; // default is 1.0f
F32 offset_for_duration_from_anchor; // default is 0.0f
U8 bits_for_number_of_segments; // 0 or 8 or 16
U8 bits_for_number_of_samples; // 0 or 8 or 16
U16 number_of_segments;
U32 number_of_samples;
U16 bits_per_sample; // 8 or 16
U16 lookup_table_index; // index of 1 or higher to PULSEtable stored in VLR/AVLR, 0 means no lookup table.
F32 sample_units; // [nanoseconds]
U32 compression; // must be zero
// space for new attributes
// ...
// space for new attributes
CHAR description[PULSEWAVES_DESCRIPTION_SIZE];
// end of attributes
U32 size_of_attributes() const;
BOOL load(ByteStreamIn* stream);
BOOL save(ByteStreamOut* stream) const;
BOOL is_equal(const PULSEsampling* sampling) const;
PULSEsampling();
};
class PULSEcomposition
{
public:
// start of attributes
U32 size; // byte-aligned size from start to end of attributes (including the PULSEWAVES_DESCRIPTION_SIZE bytes for description)
U32 reserved; // must be zero
I32 optical_center_to_anchor_point; // a fixed offset between the two [sampling units]
U16 number_of_extra_waves_bytes; // must be zero
U16 number_of_samplings;
U32 scanner_index;
F32 sample_units; // [nanoseconds]
U32 compression; // must be zero
// space for new attributes
// ...
// space for new attributes
CHAR description[PULSEWAVES_DESCRIPTION_SIZE];
// end of attributes
U32 size_of_attributes() const;
BOOL load(ByteStreamIn* stream);
BOOL save(ByteStreamOut* stream) const;
BOOL is_equal(const PULSEcomposition* composition) const;
PULSEcomposition();
};
class PULSEdescriptor
{
public:
PULSEcomposition* composition;
PULSEsampling* samplings;
BOOL load(ByteStreamIn* stream);
BOOL save(ByteStreamOut* stream) const;
BOOL is_equal(const PULSEcomposition* composition, const PULSEsampling* sampling) const;
BOOL is_equal(const PULSEdescriptor* descriptor) const;
PULSEdescriptor();
};
#endif
| PulseWaves/PulseWaves | inc/pulsedescriptor.hpp | C++ | lgpl-2.1 | 3,964 |
//
// BaseTiffFile.cs:
//
// Author:
// Mike Gemuende (mike@gemuende.de)
//
// Copyright (C) 2010 Mike Gemuende
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
using System;
using TagLib.Image;
using TagLib.IFD;
namespace TagLib.Tiff
{
/// <summary>
/// This class extends <see cref="TagLib.Image.File" /> to provide some basic behavior
/// for Tiff based file formats.
/// </summary>
public abstract class BaseTiffFile : TagLib.Image.File
{
#region Public Properties
/// <summary>
/// Indicates if the current file is in big endian or little endian format.
/// </summary>
/// <remarks>
/// The method <see cref="ReadHeader()"/> must be called from a subclass to
/// properly initialize this property.
/// </remarks>
public bool IsBigEndian {
get; private set;
}
#endregion
#region Protected Properties
/// <summary>
/// The identifier used to recognize the file. This is 42 for most TIFF files.
/// </summary>
protected ushort Magic {
get; set;
}
#endregion
#region Constructors
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified file abstraction.
/// </summary>
/// <param name="abstraction">
/// A <see cref="File.IFileAbstraction" /> object to use when
/// reading from and writing to the file.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="abstraction" /> is <see langword="null"
/// />.
/// </exception>
protected BaseTiffFile (IFileAbstraction abstraction) : base (abstraction)
{
Magic = 42;
}
#endregion
#region Protected Methods
/// <summary>
/// Reads and validates the TIFF header at the current position.
/// </summary>
/// <returns>
/// A <see cref="System.UInt32"/> with the offset value to the first
/// IFD contained in the file.
/// </returns>
/// <remarks>
/// This method should only be called, when the current read position is
/// the beginning of the file.
/// </remarks>
protected uint ReadHeader ()
{
// TIFF header:
//
// 2 bytes Indicating the endianess (II or MM)
// 2 bytes Tiff Magic word (usually 42)
// 4 bytes Offset to first IFD
ByteVector header = ReadBlock (8);
if (header.Count != 8)
throw new CorruptFileException ("Unexpected end of header");
string order = header.Mid (0, 2).ToString ();
if (order == "II") {
IsBigEndian = false;
} else if (order == "MM") {
IsBigEndian = true;
} else {
throw new CorruptFileException ("Unknown Byte Order");
}
if (header.Mid (2, 2).ToUShort (IsBigEndian) != Magic)
throw new CorruptFileException (String.Format ("TIFF Magic ({0}) expected", Magic));
uint first_ifd_offset = header.Mid (4, 4).ToUInt (IsBigEndian);
return first_ifd_offset;
}
/// <summary>
/// Reads IFDs starting from the given offset.
/// </summary>
/// <param name="offset">
/// A <see cref="System.UInt32"/> with the IFD offset to start
/// reading from.
/// </param>
protected void ReadIFD (uint offset)
{
ReadIFD (offset, -1);
}
/// <summary>
/// Reads a certain number of IFDs starting from the given offset.
/// </summary>
/// <param name="offset">
/// A <see cref="System.UInt32"/> with the IFD offset to start
/// reading from.
/// </param>
/// <param name="ifd_count">
/// A <see cref="System.Int32"/> with the number of IFDs to read.
/// </param>
protected void ReadIFD (uint offset, int ifd_count)
{
long length = 0;
try {
length = Length;
} catch (Exception) {
// Use a safety-value of 4 gigabyte.
length = 1073741824L * 4;
}
var ifd_tag = GetTag (TagTypes.TiffIFD, true) as IFDTag;
var reader = CreateIFDReader (this, IsBigEndian, ifd_tag.Structure, 0, offset, (uint) length);
reader.Read (ifd_count);
}
/// <summary>
/// Creates an IFD reader to parse the file.
/// </summary>
/// <param name="file">
/// A <see cref="File"/> to read from.
/// </param>
/// <param name="is_bigendian">
/// A <see cref="System.Boolean"/>, it must be true, if the data of the IFD should be
/// read as bigendian, otherwise false.
/// </param>
/// <param name="structure">
/// A <see cref="IFDStructure"/> that will be populated.
/// </param>
/// <param name="base_offset">
/// A <see cref="System.Int64"/> value describing the base were the IFD offsets
/// refer to. E.g. in Jpegs the IFD are located in an Segment and the offsets
/// inside the IFD refer from the beginning of this segment. So <paramref
/// name="base_offset"/> must contain the beginning of the segment.
/// </param>
/// <param name="ifd_offset">
/// A <see cref="System.UInt32"/> value with the beginning of the IFD relative to
/// <paramref name="base_offset"/>.
/// </param>
/// <param name="max_offset">
/// A <see cref="System.UInt32"/> value with maximal possible offset. This is to limit
/// the size of the possible data;
/// </param>
protected virtual IFDReader CreateIFDReader (BaseTiffFile file, bool is_bigendian, IFDStructure structure, long base_offset, uint ifd_offset, uint max_offset)
{
return new IFDReader (file, is_bigendian, structure, base_offset, ifd_offset, max_offset);
}
/// <summary>
/// Renders a TIFF header with the given offset to the first IFD.
/// The returned data has length 8.
/// </summary>
/// <param name="first_ifd_offset">
/// A <see cref="System.UInt32"/> with the offset to the first IFD
/// to be included in the header.
/// </param>
/// <returns>
/// A <see cref="ByteVector"/> with the rendered header of length 8.
/// </returns>
protected ByteVector RenderHeader (uint first_ifd_offset)
{
ByteVector data = new ByteVector ();
if (IsBigEndian)
data.Add ("MM");
else
data.Add ("II");
data.Add (ByteVector.FromUShort (Magic, IsBigEndian));
data.Add (ByteVector.FromUInt (first_ifd_offset, IsBigEndian));
return data;
}
#endregion
}
}
| timheuer/taglib-sharp-portable | src/TagLib.Shared/TagLib/Tiff/BaseTiffFile.cs | C# | lgpl-2.1 | 6,758 |
/* tests/test-det.C
* Copyright (C) 2002 Bradford Hovinen
*
* Written by Bradford Hovinen <hovinen@cis.udel.edu>
*
* --------------------------------------------------------
*
*
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*
*/
/*! @file tests/test-rational-matrix-factory.C
* @ingroup tests
* @brief no doc.
* @test no doc.
*/
#include <linbox/linbox-config.h>
#include <iostream>
#include <fstream>
#include <cstdio>
#include "linbox/linbox-config.h"
#include "linbox/util/commentator.h"
#include "givaro/zring.h"
#include "linbox/field/gmp-rational.h"
#include "linbox/matrix/dense-matrix.h"
#include "linbox/blackbox/rational-matrix-factory.h"
#include "test-common.h"
using namespace LinBox;
/* Test : For a diagonal rational matrix A = diag(1,1/2,1/3,...) compute
* -> rational norm |A|_r = n
* -> number of non-zero elements = n
* -> number of truly rational elements = n-1
* -> denA - the common denominator of A = lcm(1,...,n)
* -> d[i] - the common denominator for ith row = i
* -> Atilde = Id
* -> Aprim[j,j] = denA / j
*
* n - Dimension to which to make matrix
*
* Return true on success and false on failure
*/
static bool testDiagonalMatrix (uint64_t n)
{
commentator().start ("Testing rational matrix factory for dense matrix", "testRationalMatrixFactory");
bool ret = true;
uint64_t j;
GMPRationalField Q;
BlasMatrix<GMPRationalField > A(Q,n,n);
integer lcm_n=1;
for (j = 0; j < n; j++) {
GMPRationalField::Element tmp;
Q.init(tmp, 1,j+1);
A.setEntry(j,j,tmp);
//Q.init(A.refEntry(j,j),1,j+1);
lcm(lcm_n,lcm_n,j+1);
}
RationalMatrixFactory<Givaro::ZRing<Integer>, GMPRationalField, BlasMatrix<GMPRationalField > > FA(&A);
integer ratnorm,aprimnorm,atildenorm;
FA.getNorms(ratnorm,aprimnorm,atildenorm);
ostream &report = commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);
report << "True rational norm: " << n << endl;
report << "Computed rational norm: " << ratnorm << endl;
report << "True norm of A': " << lcm_n << endl;
report << "Computed norm of A': " << aprimnorm << endl;
report << "True norm of Atilde: " << 1 << endl;
report << "Computed norm of Atilde: " << atildenorm << endl;
if ( (ratnorm != (Integer)n) || ( aprimnorm != lcm_n) || (atildenorm != 1) ) {
ret = false;
commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)
<< "ERROR: Norms are incorrect" << endl;
}
size_t omega, rat_omega;
FA.getOmega(omega,rat_omega);
report << "True Omega: " << n << endl;
report << "Computed Omega: " << omega << endl;
report << "True Rational Omega: " << n-1 << endl;
report << "Computed Rational Omega: " << rat_omega << endl;
if ( (omega != n) || (rat_omega != n-1) ) {
ret = false;
commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)
<< "ERROR: Number of rational/non-zero elements is incorrect" << endl;
}
integer d;
FA.denominator(d);
report << "True common denominator: " << lcm_n << endl;
report << "Computed common denominator: " << d << endl;
if (d != lcm_n) {
ret = false;
commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)
<< "ERROR: Common denominator is incorrect" << endl;
}
for (j=0; j < n; ++j) {
FA.denominator(d,(int)j);
report << "True common denominator for " << j+1 << "th row: " << j+1 << endl;
report << "Computed common denominator for " << j+1 << "th row: " << d << endl;
if (d != (integer)(j+1)) {
ret = false;
commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)
<< "ERROR: Common denominator for " << j+1 << "th row is incorrect" << endl;
}
}
Givaro::ZRing<Integer> Z;
BlasMatrix<Givaro::ZRing<Integer> > Aprim(Z,n,n);
BlasMatrix<Givaro::ZRing<Integer> > Atilde(Z,n,n);
FA.makeAprim(Aprim);
FA.makeAtilde(Atilde);
Aprim.write(report);
Atilde.write(report);
for (j=0; j <n; ++j) {
if (Aprim.getEntry(j,j) != lcm_n/(j+1)) {
ret = false;
commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)
<< "ERROR: Aprim is bad at " << j+1 << "diagonal entry" << endl;
}
if (Atilde.getEntry(j,j) != 1) {
ret = false;
commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)
<< "ERROR: Atilde is bad at " << j+1 << "diagonal entry" << endl;
}
}
commentator().stop (MSG_STATUS (ret), (const char *) 0, "testRationalMatrixFactory");
return ret;
}
int main (int argc, char **argv)
{
bool pass = true;
static size_t n = 10;
//static integer q = 4093U;
//static int iterations = 2;
static Argument args[] = {
{ 'n', "-n N", "Set dimension of test matrices to NxN", TYPE_INT, &n },
//{ 'q', "-q Q", "Operate over the \"field\" GF(Q) [1]", TYPE_INTEGER, &q },
//{ 'i', "-i I", "Perform each test for I iterations", TYPE_INT, &iterations },
END_OF_ARGUMENTS
};
parseArguments (argc, argv, args);
commentator().start("Rational Matrix Factory test suite", "rmf");
// Make sure some more detailed messages get printed
commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (3);
commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDetailLevel (Commentator::LEVEL_UNIMPORTANT);
if (!testDiagonalMatrix( n )) pass = false;
commentator().stop("Rational Matrix Factory test suite");
return pass ? 0 : -1;
}
// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
| linbox-team/linbox | tests/test-rational-matrix-factory.C | C++ | lgpl-2.1 | 6,279 |
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
/*
* CompositingVisualLoop.cpp
*
* Created on: 16 janv. 2012
* Author: Jeremy Ringard
*/
//#define DEBUG_DRAW
#include <SofaOpenglVisual/CompositingVisualLoop.h>
#include <sofa/core/ObjectFactory.h>
#include <SofaBaseVisual/VisualStyle.h>
#include <sofa/core/visual/DisplayFlags.h>
#include <sofa/simulation/VisualVisitor.h>
#include <sofa/helper/AdvancedTimer.h>
namespace sofa
{
namespace component
{
namespace visualmodel
{
SOFA_DECL_CLASS(CompositingVisualLoop)
int CompositingVisualLoopClass = core::RegisterObject("Visual loop enabling multipass rendering. Needs multiple fbo data and a compositing shader")
.add< CompositingVisualLoop >()
;
CompositingVisualLoop::CompositingVisualLoop(simulation::Node* _gnode)
: simulation::DefaultVisualManagerLoop(_gnode),
vertFilename(initData(&vertFilename, (std::string) "shaders/compositing.vert", "vertFilename", "Set the vertex shader filename to load")),
fragFilename(initData(&fragFilename, (std::string) "shaders/compositing.frag", "fragFilename", "Set the fragment shader filename to load"))
{
//assert(gRoot);
}
CompositingVisualLoop::~CompositingVisualLoop()
{}
void CompositingVisualLoop::initVisual()
{}
void CompositingVisualLoop::init()
{
if (!gRoot)
gRoot = dynamic_cast<simulation::Node*>(this->getContext());
}
//should not be called if scene file is well formed
void CompositingVisualLoop::defaultRendering(sofa::core::visual::VisualParams* vparams)
{
vparams->pass() = sofa::core::visual::VisualParams::Std;
sofa::simulation::VisualDrawVisitor act ( vparams );
gRoot->execute ( &act );
vparams->pass() = sofa::core::visual::VisualParams::Transparent;
sofa::simulation::VisualDrawVisitor act2 ( vparams );
gRoot->execute ( &act2 );
}
void CompositingVisualLoop::drawStep(sofa::core::visual::VisualParams* vparams)
{
if ( !gRoot ) return;
sofa::core::visual::tristate renderingState;
//vparams->displayFlags().setShowRendering(false);
component::visualmodel::VisualStyle::SPtr visualStyle = NULL;
gRoot->get(visualStyle);
const sofa::core::visual::DisplayFlags &backupFlags = vparams->displayFlags();
const sofa::core::visual::DisplayFlags ¤tFlags = visualStyle->displayFlags.getValue();
vparams->displayFlags() = sofa::core::visual::merge_displayFlags(backupFlags, currentFlags);
renderingState = vparams->displayFlags().getShowRendering();
if (!(vparams->displayFlags().getShowRendering()))
{
#ifdef DEBUG_DRAW
std::cout << "Advanced Rendering is OFF" << std::endl;
#endif
defaultRendering(vparams);
return;
}
#ifdef DEBUG_DRAW
else
std::cout << "Advanced Rendering is ON" << std::endl;
#endif
//should not happen: the compositing loop relies on one or more rendered passes done by the VisualManagerPass component
if (gRoot->visualManager.empty())
{
serr << "CompositingVisualLoop: no VisualManagerPass found. Disable multipass rendering." << sendl;
defaultRendering(vparams);
}
//rendering sequence: call each VisualManagerPass elements, then composite the frames
else
{
#ifdef SOFA_HAVE_GLEW
if (renderingState == sofa::core::visual::tristate::false_value || renderingState == sofa::core::visual::tristate::neutral_value) return;
sofa::simulation::Node::Sequence<core::visual::VisualManager>::iterator begin = gRoot->visualManager.begin(), end = gRoot->visualManager.end(), it;
//preDraw sequence
it=begin;
for (it = begin; it != end; ++it)
{
(*it)->preDrawScene(vparams);
VisualManagerPass* currentVMP=dynamic_cast<VisualManagerPass*>(*it);
if( currentVMP!=NULL && !currentVMP->isPrerendered())
{
#ifdef DEBUG_DRAW
std::cout<<"final pass is "<<currentVMP->getName()<< "end of predraw loop" <<std::endl;
#endif
break;
}
}
//Draw sequence
bool rendered = false; // true if a manager did the rendering
for (it = begin; it != end; ++it)
if ((*it)->drawScene(vparams)) { rendered = true; break; }
if (!rendered) // do the rendering
{
msg_error() << "No visualManager rendered the scene. Please make sure the final visualManager(Secondary)Pass has a renderToScreen=\"true\" attribute" ;
}
//postDraw sequence
sofa::simulation::Node::Sequence<core::visual::VisualManager>::reverse_iterator rbegin = gRoot->visualManager.rbegin(), rend = gRoot->visualManager.rend(), rit;
for (rit = rbegin; rit != rend; ++rit)
(*rit)->postDrawScene(vparams);
// cleanup OpenGL state
for (int i=0; i<4; ++i)
{
glActiveTexture(GL_TEXTURE0+i);
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
}
glDisable(GL_LIGHTING);
glUseProgramObjectARB(0);
glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBufferARB(GL_ARRAY_BUFFER, 0);
//glViewport(vparams->viewport()[0],vparams->viewport()[1],vparams->viewport()[2],vparams->viewport()[3]);
#endif
}
}
} // namespace visualmodel
} // namespace component
} //sofa
| hdeling/sofa | modules/SofaOpenglVisual/CompositingVisualLoop.cpp | C++ | lgpl-2.1 | 6,947 |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "formclasswizarddialog.h"
#include "formclasswizardpage.h"
#include "formclasswizardparameters.h"
#include <designer/formtemplatewizardpage.h>
#include <coreplugin/basefilewizardfactory.h>
#include <QDebug>
enum { FormPageId, ClassPageId };
namespace Designer {
namespace Internal {
// ----------------- FormClassWizardDialog
FormClassWizardDialog::FormClassWizardDialog(const WizardPageList &extensionPages,
QWidget *parent) :
Core::BaseFileWizard(parent),
m_formPage(new FormTemplateWizardPage),
m_classPage(new FormClassWizardPage)
{
setWindowTitle(tr("Qt Designer Form Class"));
setPage(FormPageId, m_formPage);
setPage(ClassPageId, m_classPage);
foreach (QWizardPage *p, extensionPages)
addPage(p);
}
QString FormClassWizardDialog::path() const
{
return m_classPage->path();
}
void FormClassWizardDialog::setPath(const QString &p)
{
m_classPage->setPath(p);
}
bool FormClassWizardDialog::validateCurrentPage()
{
return QWizard::validateCurrentPage();
}
void FormClassWizardDialog::initializePage(int id)
{
QWizard::initializePage(id);
// Switching from form to class page: store XML template and set a suitable
// class name in the class page based on the form base class
if (id == ClassPageId) {
QString formBaseClass;
QString uiClassName;
m_rawFormTemplate = m_formPage->templateContents();
// Strip namespaces from the ui class and suggest it as a new class
// name
if (FormTemplateWizardPage::getUIXmlData(m_rawFormTemplate, &formBaseClass, &uiClassName))
m_classPage->setClassName(FormTemplateWizardPage::stripNamespaces(uiClassName));
}
}
FormClassWizardParameters FormClassWizardDialog::parameters() const
{
FormClassWizardParameters rc;
m_classPage->getParameters(&rc);
// Name the ui class in the Ui namespace after the class specified
rc.uiTemplate = FormTemplateWizardPage::changeUiClassName(m_rawFormTemplate, rc.className);
return rc;
}
} // namespace Internal
} // namespace Designer
| maui-packages/qt-creator | src/plugins/designer/cpp/formclasswizarddialog.cpp | C++ | lgpl-2.1 | 3,572 |
<?php
namespace wcf\data\like;
use wcf\data\object\type\ObjectTypeCache;
use wcf\system\cache\runtime\UserProfileRuntimeCache;
use wcf\system\like\IViewableLikeProvider;
/**
* Represents a list of viewable likes.
*
* @author Marcel Werk
* @copyright 2001-2018 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\Data\Like
*
* @method ViewableLike current()
* @method ViewableLike[] getObjects()
* @method ViewableLike|null search($objectID)
* @property ViewableLike[] $objects
*/
class ViewableLikeList extends LikeList {
/**
* @inheritDoc
*/
public $className = Like::class;
/**
* @inheritDoc
*/
public $decoratorClassName = ViewableLike::class;
/**
* @inheritDoc
*/
public $sqlLimit = 20;
/**
* @inheritDoc
*/
public $sqlOrderBy = 'like_table.time DESC';
/**
* @inheritDoc
*/
public function readObjects() {
parent::readObjects();
$userIDs = [];
$likeGroups = [];
foreach ($this->objects as $like) {
$userIDs[] = $like->userID;
if (!isset($likeGroups[$like->objectTypeID])) {
$objectType = ObjectTypeCache::getInstance()->getObjectType($like->objectTypeID);
$likeGroups[$like->objectTypeID] = [
'provider' => $objectType->getProcessor(),
'objects' => []
];
}
$likeGroups[$like->objectTypeID]['objects'][] = $like;
}
// set user profiles
if (!empty($userIDs)) {
UserProfileRuntimeCache::getInstance()->cacheObjectIDs(array_unique($userIDs));
}
// parse like
foreach ($likeGroups as $likeData) {
if ($likeData['provider'] instanceof IViewableLikeProvider) {
/** @noinspection PhpUndefinedMethodInspection */
$likeData['provider']->prepare($likeData['objects']);
}
}
// validate permissions
foreach ($this->objects as $index => $like) {
if (!$like->isAccessible()) {
unset($this->objects[$index]);
}
}
$this->indexToObject = array_keys($this->objects);
}
/**
* Returns timestamp of oldest like fetched.
*
* @return integer
*/
public function getLastLikeTime() {
$lastLikeTime = 0;
foreach ($this->objects as $like) {
if (!$lastLikeTime) {
$lastLikeTime = $like->time;
}
$lastLikeTime = min($lastLikeTime, $like->time);
}
return $lastLikeTime;
}
}
| Morik/WCF | wcfsetup/install/files/lib/data/like/ViewableLikeList.class.php | PHP | lgpl-2.1 | 2,340 |
#include "CmdReceiver.h"
#include <cstdio>
#include "Engine.h"
using namespace adv;
CommandReceiver::CommandReceiver() : mStopRequested(false), mMultiline(false){
}
CommandReceiver::~CommandReceiver(){
while (!mQueue.empty()){
Command c = mQueue.front();
if (c.type == SCRIPT)
free(c.str);
mQueue.pop();
}
}
void CommandReceiver::start(){
mThread.create(start_routine, this);
}
void CommandReceiver::stop(){
requestStop();
mThread.join();
}
void CommandReceiver::start_routine(void* data){
CommandReceiver* that = (CommandReceiver*)data;
that->threadLoop();
}
void CommandReceiver::threadLoop(){
mSocket.create();
mSocket.bind(28406);
mSocket.listen();
mSocket.set_non_blocking(true);
while(!mStopRequested){
if (!mSocket.accept(mConnSocket)){
CGE::Thread::sleep(100);
continue;
}
mConnSocket.set_non_blocking(true);
std::string msg;
msg = "cge "+toStr(Engine::instance()->getResolution().x+32)+" "+toStr(Engine::instance()->getResolution().y+32)+"\n";
mConnSocket.send(msg);
msg.clear();
std::string cmd;
while(!mStopRequested){
if (mConnSocket.recv(msg) < 0)
break;
if (msg.length() > 0){
cmd += msg;
size_t pos = cmd.find('\n');
while (pos != cmd.npos){
std::string begin = cmd.substr(0, pos-1);
cmd = cmd.substr(pos+1);
pos = cmd.find('\n');
parseCommand(begin);
}
cmd.clear();
}
CGE::Thread::sleep(20);
}
//mConnSocket.close();
}
}
void CommandReceiver::parseCommand(const std::string& cmd){
char cmdid[4];
cmdid[3] = '\0';
int x; int y;
if (mMultiline){
if (cmd == "***"){
mMultiline = false;
Command c;
c.type = SCRIPT;
c.str = strdup(mMsg.c_str());
mQueue.push(c);
mMsg.clear();
}
else{
mMsg += cmd+"\n";
}
}
else if (cmd[0] == 'm'){
sscanf(cmd.c_str(), "%s %i %i", cmdid, &x, &y);
if (strcmp(cmdid, "mps") == 0){
Command c;
c.type = MOUSE_MOVE;
c.x = x;
c.y = y;
mQueue.push(c);
}
else if (strcmp(cmdid, "mcl") == 0){
Command c;
c.type = MOUSE_CLICK;
c.x = x;
c.y = y;
mQueue.push(c);
}
else if (strcmp(cmdid, "mcr") == 0){
Command c;
c.type = MOUSE_RIGHTCLICK;
c.x = x;
c.y = y;
mQueue.push(c);
}
}
else if (cmd[0] == 's'){
sscanf(cmd.c_str(), "%s\n", cmdid);
if (strcmp(cmdid, "scr") == 0){
mMultiline = true;
}
}
return;
}
void CommandReceiver::processCommands(){
while (!mQueue.empty()){
Command c = mQueue.front();
mQueue.pop();
switch(c.type){
case MOUSE_MOVE:
Engine::instance()->setCursorPos(Vec2i(c.x, c.y));
break;
case MOUSE_CLICK:
Engine::instance()->leftClick(Vec2i(c.x, c.y));
break;
case MOUSE_RIGHTCLICK:
Engine::instance()->rightClick(Vec2i(c.x, c.y));
break;
case SCRIPT:{
ExecutionContext* ctx = Engine::instance()->getInterpreter()->parseProgram(c.str);
if (ctx){
Engine::instance()->getInterpreter()->execute(ctx, true);
}
free(c.str);
}
}
}
}
| captain-mayhem/captainsengine | Adventure/AdvEngine/Engine/CmdReceiver.cpp | C++ | lgpl-2.1 | 3,397 |
/* Copyright (C) 2006-2007 Egon Willighagen <egonw@users.sf.net>
*
* Contact: cdk-devel@lists.sourceforge.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
* All we ask is that proper credit is given for our work, which includes
* - but is not limited to - adding the above copyright notice to the beginning
* of your source code files, and to any copyright notice that you may distribute
* with programs based on this work.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
namespace NCDK
{
/// <summary>
/// Represents the idea of a non-chemical atom-like entity, like Me, R, X, Phe, His, etc.
/// <para>This should be replaced by the mechanism explained in RFC #8.</para>
/// </summary>
/// <seealso cref="IAtom"/>
// @cdk.module interfaces
public interface IPseudoAtom
: IAtom
{
/// <summary>
/// The label of this <see cref="IPseudoAtom"/>.
/// </summary>
string Label { get; set; }
/// <summary>
/// The attachment point number.
/// </summary>
/// <value>The default, 0, indicates this atom is not an attachment point.</value>
int AttachPointNum { get; set; }
/// <inheritdoc/>
new IPseudoAtom Clone();
}
}
| kazuyaujihara/NCDK | NCDK/IPseudoAtom.cs | C# | lgpl-2.1 | 1,902 |
package org.cytoscape.cg.model;
import java.awt.Image;
public class CustomGraphicsUtil {
public static Image getResizedImage(Image original, Integer w, Integer h, boolean keepAspectRatio) {
if (original == null)
throw new IllegalArgumentException("Original image cannot be null.");
if (w == null && h == null)
return original;
int currentW = original.getWidth(null);
int currentH = original.getHeight(null);
float ratio;
int converted;
if (keepAspectRatio == false) {
return original.getScaledInstance(w, h, Image.SCALE_AREA_AVERAGING);
} else if (h == null) {
ratio = ((float) currentH) / ((float) currentW);
converted = (int) (w * ratio);
return original.getScaledInstance(w, converted, Image.SCALE_AREA_AVERAGING);
} else {
ratio = ((float) currentW) / ((float) currentH);
converted = (int) (h * ratio);
return original.getScaledInstance(converted, h, Image.SCALE_AREA_AVERAGING);
}
}
}
| cytoscape/cytoscape-impl | custom-graphics-internal/src/main/java/org/cytoscape/cg/model/CustomGraphicsUtil.java | Java | lgpl-2.1 | 945 |
package com.camp.block;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import com.camp.creativetabs.CreativeTabsManager;
import com.camp.item.ItemManager;
//import com.bedrockminer.tutorial.Main;
import com.camp.lib.StringLibrary;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class NetherLapis extends Block {
//"LapisItem" = new ItemStack(Items.dye, 1, 4);
private ItemStack drop;
private int meta;
private int least_quantity;
private int most_quantity;
//("gemLapis", new ItemStack(Items.dye, 1, 4)
protected NetherLapis(String unlocalizedName, Material mat, ItemStack gemLapisGem2, int meta, int least_quantity, int most_quantity) {
super(mat);
this.drop = gemLapisGem2;
this.meta = meta;
this.least_quantity = 1;
this.most_quantity = 2;
this.setLightLevel(0.0F);
this.setBlockName(unlocalizedName);
this.setBlockTextureName(StringLibrary.MODID + ":" + "nether_lapis");
this.setCreativeTab(CreativeTabsManager.tabBlock);
}
//ItemStack gemLapis = new ItemStack(Items.dye,1);
///ItemStack gemLapis = new ItemStack(Items.dye, 1, 4); setItemDamage(4);
ItemStack gemLapisGem = new ItemStack(Items.dye, 1, 4);
protected NetherLapis(String unlocalizedName, Material mat, ItemStack gemLapisGem2, int least_quantity, int most_quantity) {
this(unlocalizedName, mat, gemLapisGem2, 0, least_quantity, most_quantity);
}
protected NetherLapis(String unlocalizedName, Material mat, net.minecraft.item.ItemStack drop) {
this(unlocalizedName, mat, drop, 1, 1);
}
public ItemStack ItemStack (int meta, Random random, int fortune) {
return gemLapisGem;
}
@Override
public int damageDropped(int meta) {
return meta;
}
@Override
public int quantityDropped(int meta, int fortune, Random random) {
if (this.least_quantity >= this.most_quantity)
return this.least_quantity;
return this.least_quantity + random.nextInt(this.most_quantity - this.least_quantity + fortune + 1);
}
} | trainboy2019/1.7modrecove4r2 | src/main/java/com/camp/block/NetherLapis.java | Java | lgpl-2.1 | 2,215 |
#include <iostream>
#include <sys/stat.h>
#include <libgen.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "copyrequest.h"
#include "urlencode.h"
using namespace std;
CopyRequest::CopyRequest(WebdavServer& owner, bool deleteSource) :
Request(owner),
m_deleteSource(deleteSource)
{
}
int CopyRequest::handleRequest(struct MHD_Connection* connection, const char* url, const char* version, const char* uploadData, size_t* uploadDataSize)
{
const char* contentLength = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "content-length");
struct MHD_Response* response = MHD_create_response_from_data(0, 0, MHD_NO, MHD_NO);
m_owner.initRequest(response);
int ret;
if (contentLength && strcmp(contentLength, "0") != 0)
{
ret = MHD_queue_response(connection, 415, response);
MHD_destroy_response(response);
return ret;
}
if (m_deleteSource && !checkLock(connection, url, ret))
{
return ret;
}
const char* depth = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "depth");
if (!depth)
depth = "infinity";
int iDepth = strcasecmp(depth, "infinity") == 0 ? -1 : atoi(depth);
const char* _destination = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "destination");
const char* host = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "host");
// check for other destination
string self("http://");
self.append(host);
if (self.compare(0, self.length(), _destination, self.length()) != 0)
{
ret = MHD_queue_response(connection, 502, response);
MHD_destroy_response(response);
return ret;
}
string destination(_destination);
cout << "Moving file to: " << destination << endl;
destination = destination.substr(self.length());
const char* _overwrite = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "overwrite");
bool overwrite = _overwrite && strcmp(_overwrite, "T") == 0;
string source = m_owner.getRoot() + url;
if (!m_owner.checkPath(source))
{
ret = MHD_queue_response(connection, 404, response);
MHD_destroy_response(response);
return ret;
}
string destUrl = destination;
if (!checkLock(connection, destUrl.c_str(), ret))
{
return ret;
}
destination = m_owner.getRoot() + Util::UriDecode(destination);
bool newResource = !m_owner.checkPath(destination);
struct stat st;
bool destIsDir = stat(destination.c_str(), &st)==0 && S_ISDIR(st.st_mode);
if (!newResource && m_deleteSource && destIsDir && !overwrite)
{
ret = MHD_queue_response(connection, 412, response);
MHD_destroy_response(response);
return ret;
}
bool existingCol = false;
if (!newResource && m_deleteSource && destIsDir)
{
char* dup = strdup(url);
destination.append(basename(dup));
free(dup);
if (stat(destination.c_str(), &st) != 0)
{
newResource = true;
existingCol = true;
}
}
if (!newResource && !overwrite)
{
ret = MHD_queue_response(connection, 412, response);
MHD_destroy_response(response);
return ret;
}
else if (!newResource && overwrite)
{
WebdavServer::recursiveDelete(destination);
}
char* dup = strdup(destination.c_str());
string destDirname = dirname(dup);
free(dup);
if (!m_owner.checkPath(destDirname))
{
ret = MHD_queue_response(connection, 409, response);
MHD_destroy_response(response);
return ret;
}
else if (m_deleteSource && !rename(source.c_str(), destination.c_str()))
{
m_owner.moveProperties(url, destUrl);
}
else if (!m_deleteSource)
{
// TODO: copy properties
WebdavServer::recursiveCopy(source, destination, iDepth);
}
ret = MHD_queue_response(connection, newResource && !existingCol ? 201 : 204, response);
MHD_destroy_response(response);
return ret;
}
| woutervdm/wdserver | webdav/server/copyrequest.cpp | C++ | lgpl-2.1 | 3,661 |
/*
* JaspertReports JSF Plugin Copyright (C) 2011 A. Alonso Dominguez
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at
* your option) any later version. This 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 Lesser General Public License for more details. You should have
* received a copy of the GNU Lesser General Public License along with this
* library; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA A.
*
* Alonso Dominguez
* alonsoft@users.sf.net
*/
package net.sf.jasperreports.jsf.context;
import java.util.Collection;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import net.sf.jasperreports.jsf.component.UIOutputReport;
import net.sf.jasperreports.jsf.component.UIReport;
import net.sf.jasperreports.jsf.convert.ReportConverter;
import net.sf.jasperreports.jsf.convert.SourceConverter;
import net.sf.jasperreports.jsf.engine.Exporter;
import net.sf.jasperreports.jsf.engine.Filler;
import net.sf.jasperreports.jsf.resource.Resource;
/**
*
* @author A. Alonso Dominguez
*/
public abstract class JRFacesContextWrapper extends JRFacesContext {
@Override
public ReportConverter createReportConverter(FacesContext context, UIReport component) {
return getWrapped().createReportConverter(context, component);
}
@Override
public Resource createResource(FacesContext context, UIComponent component, String name) {
return getWrapped().createResource(context, component, name);
}
@Override
public SourceConverter createSourceConverter(FacesContext context, UIComponent component) {
return getWrapped().createSourceConverter(context, component);
}
@Override
public Collection<String> getAvailableExportFormats() {
return getWrapped().getAvailableExportFormats();
}
@Override
public Collection<String> getAvailableSourceTypes() {
return getWrapped().getAvailableSourceTypes();
}
@Override
public Exporter getExporter(FacesContext context, UIOutputReport component) {
return getWrapped().getExporter(context, component);
}
@Override
public ExternalContextHelper getExternalContextHelper(FacesContext context) {
return getWrapped().getExternalContextHelper(context);
}
@Override
public Filler getFiller(FacesContext context, UIOutputReport component) {
return getWrapped().getFiller(context, component);
}
@Override
public Collection<ContentType> getSupportedContentTypes() {
return getWrapped().getSupportedContentTypes();
}
protected abstract JRFacesContext getWrapped();
}
| cristhiank/jasperreportsjsf | plugin/src/main/java/net/sf/jasperreports/jsf/context/JRFacesContextWrapper.java | Java | lgpl-2.1 | 3,019 |
/**
* EditorUpload.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* Handles image uploads, updates undo stack and patches over various internal functions.
*
* @private
* @class tinymce.EditorUpload
*/
define("tinymce/EditorUpload", [
"tinymce/util/Arr",
"tinymce/file/Uploader",
"tinymce/file/ImageScanner",
"tinymce/file/BlobCache"
], function(Arr, Uploader, ImageScanner, BlobCache) {
return function(editor) {
var blobCache = new BlobCache();
// Replaces strings without regexps to avoid FF regexp to big issue
function replaceString(content, search, replace) {
var index = 0;
do {
index = content.indexOf(search, index);
if (index !== -1) {
content = content.substring(0, index) + replace + content.substr(index + search.length);
index += replace.length - search.length + 1;
}
} while (index !== -1);
return content;
}
function replaceImageUrl(content, targetUrl, replacementUrl) {
content = replaceString(content, 'src="' + targetUrl + '"', 'src="' + replacementUrl + '"');
content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
return content;
}
function replaceUrlInUndoStack(targetUrl, replacementUrl) {
Arr.each(editor.undoManager.data, function(level) {
level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
});
}
function uploadImages(callback) {
var uploader = new Uploader({
url: editor.settings.images_upload_url,
basePath: editor.settings.images_upload_base_path,
credentials: editor.settings.images_upload_credentials,
handler: editor.settings.images_upload_handler
});
function imageInfosToBlobInfos(imageInfos) {
return Arr.map(imageInfos, function(imageInfo) {
return imageInfo.blobInfo;
});
}
return scanForImages().then(imageInfosToBlobInfos).then(uploader.upload).then(function(result) {
result = Arr.map(result, function(uploadInfo) {
var image;
image = editor.dom.select('img[src="' + uploadInfo.blobInfo.blobUri() + '"]')[0];
if (image) {
replaceUrlInUndoStack(image.src, uploadInfo.url);
editor.$(image).attr({
src: uploadInfo.url,
'data-mce-src': editor.convertURL(uploadInfo.url, 'src')
});
}
return {
element: image,
status: uploadInfo.status
};
});
if (callback) {
callback(result);
}
return result;
}, function() {
// Silent
// TODO: Maybe execute some failure callback here?
});
}
function scanForImages() {
return ImageScanner.findAll(editor.getBody(), blobCache).then(function(result) {
Arr.each(result, function(resultItem) {
replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
resultItem.image.src = resultItem.blobInfo.blobUri();
});
return result;
});
}
function destroy() {
blobCache.destroy();
}
function replaceBlobWithBase64(content) {
return content.replace(/src="(blob:[^"]+)"/g, function(match, blobUri) {
var blobInfo = blobCache.getByUri(blobUri);
if (!blobInfo) {
blobInfo = Arr.reduce(editor.editorManager.editors, function(result, editor) {
return result || editor.editorUpload.blobCache.getByUri(blobUri);
}, null);
}
if (blobInfo) {
return 'src="data:' + blobInfo.blob().type + ';base64,' + blobInfo.base64() + '"';
}
return match[0];
});
}
editor.on('setContent paste', scanForImages);
editor.on('RawSaveContent', function(e) {
e.content = replaceBlobWithBase64(e.content);
});
editor.on('getContent', function(e) {
if (e.source_view || e.format == 'raw') {
return;
}
e.content = replaceBlobWithBase64(e.content);
});
return {
blobCache: blobCache,
uploadImages: uploadImages,
scanForImages: scanForImages,
destroy: destroy
};
};
}); | VioletLife/tinymce | js/tinymce/classes/EditorUpload.js | JavaScript | lgpl-2.1 | 4,051 |
# -*- coding: utf-8 -*-
#--------------------------------------------------------------------#
# This file is part of Py-cnotify. #
# #
# Copyright (C) 2007, 2008 Paul Pogonyshev. #
# #
# This library is free software; you can redistribute it and/or #
# modify it under the terms of the GNU Lesser General Public License #
# as published by the Free Software Foundation; either version 2.1 #
# of the License, or (at your option) any later version. #
# #
# This 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 #
# Lesser General Public License for more details. #
# #
# You should have received a copy of the GNU Lesser General Public #
# License along with this library; if not, write to the Free #
# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, #
# Boston, MA 02110-1301 USA #
#--------------------------------------------------------------------#
"""
cNotify package provides three main concepts: I{L{signals <signal>}}, I{L{conditions
<condition>}} and I{L{variables <variable>}}. Signals are basically lists of callables
that can be I{emitted} and then will call all contained callables (I{handler} of a signal)
in turn. Conditions are boolean values complemented with a signal that is emitted when
condition’s I{state} changes. Variables are akin to conditions but can hold arbitrary
I{values}, not just booleans. Conditions, unlike variables, can also be combined using
standard logic operators, like negation, conjunction and so on.
All three concepts provide separation between providers (writers, setters) and listeners
(readers, getters) of some entity. Conditions and variables make the entity explicit—it
is a boolean state for the former and arbitrary Python object for the latter (though
derived variable classes can restrict the set of allowed values.)
Here is a quick example:
>>> from cnotify.variable import *
... name = Variable ()
...
... import sys
... name.changed.connect (
... lambda string: sys.stdout.write ('Hello there, %s!\\n' % string))
...
... name.value = 'Chuk'
Note that when setting the C{name} variable, you don’t need to know who, if anyone,
listens to changes to it. Interested parties take care to express their interest
themselves and are informed upon a change automatically.
Here is a little more elaborate example with the same functionality (it requires U{PyGTK
<http://pygtk.org/>}):
>>> from cnotify.variable import *
... import gtk
...
... name = Variable ()
...
... def welcome_user (name_string):
... dialog = gtk.MessageDialog (None, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK,
... 'Hello there, %s!' % name_string)
... dialog.run ()
... dialog.destroy ()
...
... name.changed.connect (welcome_user)
...
... def set_name_from_entry (entry):
... name.value = entry.get_text ()
...
... window = gtk.Window ()
... window.set_title ('Enter name')
...
... entry = gtk.Entry ()
... entry.show ()
... window.add (entry)
...
... entry.connect ('activate', set_name_from_entry)
... window.connect ('destroy', lambda window: gtk.main_quit ())
...
... window.present ()
...
... gtk.main ()
Note that C{window} knows absolutely nothing about how changes to C{name} variable are
handled. If you play with this example, you will notice one thing: pressing C{Enter} in
the main window twice doesn’t pop the welcoming dialog twice. That is because both
conditions and variables emit their ‘changed’ signal I{only} when their state/value
actually changes, not on every assignment.
Now a final, quite complicated, example introducing conditions and some other features:
>>> from cnotify.all import *
...
... pilots = Variable ()
... fuel = Variable ()
...
... import sys
...
... pilots.changed.connect (
... lambda pilots: sys.stdout.write ('Pilots are %s\\n' % pilots))
... fuel.changed.connect (
... lambda amount: sys.stdout.write ('Got %d litres of fuel\\n' % amount))
...
... def ready_state_changed (ready):
... if ready:
... sys.stdout.write ('Ready to get off!\\n')
... else:
... sys.stdout.write ('Missing pilots or fuel\\n')
...
... ready = pilots.is_true () & fuel.predicate (lambda amount: amount > 0)
... ready.store (ready_state_changed)
...
... pilots.value = 'Jen and Jim'
... fuel.value = 500
...
... fuel.value = 0
First line of example shows a way to save typing by importing all package contents at
once. Whether to use this technique is up to you. Following lines up to C{ready = ...}
should be familiar.
Now let’s consider that assignment closer. First, C{L{pilots.is_true ()
<variable.AbstractVariable.is_true>}} code creates a condition that is true depending on
C{pilots} value (true for non-empty sequences in our case.) It is just a convenience
wrapper over C{L{AbstractVariable.predicate <variable.AbstractVariable.predicate>}}
method. Now, the latter is also used directly in this line of code. It creates a
condition that is true as long as variable’s value conforms to the passed in predicate.
In particular, C{fuel.predicate (lambda amount: amount > 0)} creates a condition that is
true if C{fuel}’s value is greater than zero. Predicate conditions will recompute their
state each time variable’s value changes and that’s the point in using them.
Finally, two just constructed conditions are combined into a third condition using ‘and’
operator (C{&}). This third condition will be true if and only if I{both} its term
conditions are true. Conditions support four logic operations: negation, conjunction,
disjunction and xoring (with these operators: C{~}, C{&}, C{|} and C{^}.) In addition,
each condition has C{L{if_else <condition.AbstractCondition.if_else>}} method, which is
much like Python’s C{if} operator.
The next line introduces one more new method: C{L{store
<base.AbstractValueObject.store>}}. It is really just like connecting its only argument
to the ‘changed’ signal, except that it is also called once with the current state of the
condition (or value of a variable.)
The example should produce this output::
Missing pilots or fuel
Pilots are Jen and Jim
Got 500 litres of fuel
Ready to get off!
Got 0 litres of fuel
Missing pilots or fuel
Notable here is the output from C{ready_state_changed} function. It is called once at the
beginning from the C{store} method with the state of C{ready} condition (then C{False}.)
Both later calls correspond to changes in C{ready}’s state. When both C{pilots} and
C{fuel} variables are set, corresponding predicate conditions become true and so does the
C{ready} condition. However, when one of the predicate conditions becomes false (as the
result of C{fuel} being set to zero), C{ready} turns false again. Note that
C{ready_state_changed} is not called in between of setting C{pilots} and C{fuel} variable.
C{ready} state is recomputed, but since it remains the same, ‘changed’ signal is not
emitted.
G{packagetree}
"""
__docformat__ = 'epytext en'
# CONFIGURATION
__version__ = '0.3.2.1'
"""
Version of Py-cnotify, as a string.
"""
version_tuple = (0, 3, 2, 1)
"""
Version of Py-cnotify, as a tuple of integers. It is guaranteed that version tuples of
later versions will compare greater that those of earlier versions.
"""
# /CONFIGURATION
# Local variables:
# mode: python
# python-indent: 4
# indent-tabs-mode: nil
# fill-column: 90
# End:
| kived/py-cnotify | cnotify/__init__.py | Python | lgpl-2.1 | 8,208 |
using System;
namespace CabiNet
{
/// <summary>
/// When a table is missing
/// </summary>
public class MissingTableException : Exception
{
private readonly string _tableName;
/// <summary>
/// When a table is missing
/// </summary>
/// <param name="tableName">The table name</param>
public MissingTableException(string tableName)
{
_tableName = tableName;
}
public override string Message
{
get
{
return "Missing table: " + _tableName;
}
}
}
}
| bltavares/CabiNet | CabiNet/CabiNet/Exceptions/MissingTableException.cs | C# | lgpl-3.0 | 656 |
package nova
import (
"fmt"
"net/http"
"gopkg.in/goose.v2/client"
"gopkg.in/goose.v2/errors"
goosehttp "gopkg.in/goose.v2/http"
)
// The following API requests found in this file are officially deprecated by
// the upstream openstack project.
// The API requests will be left as is, but marked as deprecated and will be
// removed in the v3 release of goose. Migrating API calls to the new API
// requests is recommended.
const (
// Deprecated.
// https://docs.openstack.org/api-ref/compute/?expanded=list-security-groups-detail#list-security-groups
apiSecurityGroups = "os-security-groups"
// Deprecated.
// https://docs.openstack.org/api-ref/compute/?expanded=list-security-groups-detail#create-security-group-rule
apiSecurityGroupRules = "os-security-group-rules"
// Deprecated.
// https://docs.openstack.org/api-ref/compute/?expanded=list-security-groups-detail#show-fixed-ip-details
apiFloatingIPs = "os-floating-ips"
)
// SecurityGroupRef refers to an existing named security group
type SecurityGroupRef struct {
TenantId string `json:"tenant_id"`
Name string `json:"name"`
}
// SecurityGroupRule describes a rule of a security group. There are 2
// basic rule types: ingress and group rules (see RuleInfo struct).
type SecurityGroupRule struct {
FromPort *int `json:"from_port"` // Can be nil
IPProtocol *string `json:"ip_protocol"` // Can be nil
ToPort *int `json:"to_port"` // Can be nil
ParentGroupId string `json:"-"`
IPRange map[string]string `json:"ip_range"` // Can be empty
Id string `json:"-"`
Group SecurityGroupRef
}
// SecurityGroup describes a single security group in OpenStack.
type SecurityGroup struct {
Rules []SecurityGroupRule
TenantId string `json:"tenant_id"`
Id string `json:"-"`
Name string
Description string
}
// ListSecurityGroups lists IDs, names, and other details for all security groups.
func (c *Client) ListSecurityGroups() ([]SecurityGroup, error) {
var resp struct {
Groups []SecurityGroup `json:"security_groups"`
}
requestData := goosehttp.RequestData{RespValue: &resp}
err := c.client.SendRequest(client.GET, "compute", "v2", apiSecurityGroups, &requestData)
if err != nil {
return nil, errors.Newf(err, "failed to list security groups")
}
return resp.Groups, nil
}
// SecurityGroupByName returns the named security group.
// Note: due to lack of filtering support when querying security groups, this is not an efficient implementation
// but it's all we can do for now.
func (c *Client) SecurityGroupByName(name string) (*SecurityGroup, error) {
// OpenStack does not support group filtering, so we need to load them all and manually search by name.
groups, err := c.ListSecurityGroups()
if err != nil {
return nil, err
}
for _, group := range groups {
if group.Name == name {
return &group, nil
}
}
return nil, errors.NewNotFoundf(nil, "", "Security group %s not found.", name)
}
// GetServerSecurityGroups list security groups for a specific server.
func (c *Client) GetServerSecurityGroups(serverId string) ([]SecurityGroup, error) {
var resp struct {
Groups []SecurityGroup `json:"security_groups"`
}
url := fmt.Sprintf("%s/%s/%s", apiServers, serverId, apiSecurityGroups)
requestData := goosehttp.RequestData{RespValue: &resp}
err := c.client.SendRequest(client.GET, "compute", "v2", url, &requestData)
if err != nil {
// Sadly HP Cloud lacks the necessary API and also doesn't provide full SecurityGroup lookup.
// The best we can do for now is to use just the Name from the group entities.
if errors.IsNotFound(err) {
serverDetails, err := c.GetServer(serverId)
if err == nil && serverDetails.Groups != nil {
result := make([]SecurityGroup, len(*serverDetails.Groups))
for i, e := range *serverDetails.Groups {
result[i] = SecurityGroup{Name: e.Name}
}
return result, nil
}
}
return nil, errors.Newf(err, "failed to list server (%s) security groups", serverId)
}
return resp.Groups, nil
}
// CreateSecurityGroup creates a new security group.
func (c *Client) CreateSecurityGroup(name, description string) (*SecurityGroup, error) {
var req struct {
SecurityGroup struct {
Name string `json:"name"`
Description string `json:"description"`
} `json:"security_group"`
}
req.SecurityGroup.Name = name
req.SecurityGroup.Description = description
var resp struct {
SecurityGroup SecurityGroup `json:"security_group"`
}
requestData := goosehttp.RequestData{ReqValue: req, RespValue: &resp, ExpectedStatus: []int{http.StatusOK}}
err := c.client.SendRequest(client.POST, "compute", "v2", apiSecurityGroups, &requestData)
if err != nil {
return nil, errors.Newf(err, "failed to create a security group with name: %s", name)
}
return &resp.SecurityGroup, nil
}
// DeleteSecurityGroup deletes the specified security group.
func (c *Client) DeleteSecurityGroup(groupId string) error {
url := fmt.Sprintf("%s/%s", apiSecurityGroups, groupId)
requestData := goosehttp.RequestData{ExpectedStatus: []int{http.StatusAccepted}}
err := c.client.SendRequest(client.DELETE, "compute", "v2", url, &requestData)
if err != nil {
err = errors.Newf(err, "failed to delete security group with id: %s", groupId)
}
return err
}
// UpdateSecurityGroup updates the name and description of the given group.
func (c *Client) UpdateSecurityGroup(groupId, name, description string) (*SecurityGroup, error) {
var req struct {
SecurityGroup struct {
Name string `json:"name"`
Description string `json:"description"`
} `json:"security_group"`
}
req.SecurityGroup.Name = name
req.SecurityGroup.Description = description
var resp struct {
SecurityGroup SecurityGroup `json:"security_group"`
}
url := fmt.Sprintf("%s/%s", apiSecurityGroups, groupId)
requestData := goosehttp.RequestData{ReqValue: req, RespValue: &resp, ExpectedStatus: []int{http.StatusOK}}
err := c.client.SendRequest(client.PUT, "compute", "v2", url, &requestData)
if err != nil {
return nil, errors.Newf(err, "failed to update security group with Id %s to name: %s", groupId, name)
}
return &resp.SecurityGroup, nil
}
// RuleInfo allows the callers of CreateSecurityGroupRule() to
// create 2 types of security group rules: ingress rules and group
// rules. The difference stems from how the "source" is defined.
// It can be either:
// 1. Ingress rules - specified directly with any valid subnet mask
// in CIDR format (e.g. "192.168.0.0/16");
// 2. Group rules - specified indirectly by giving a source group,
// which can be any user's group (different tenant ID).
//
// Every rule works as an iptables ACCEPT rule, thus a group/ with no
// rules does not allow ingress at all. Rules can be added and removed
// while the server(s) are running. The set of security groups that
// apply to a server is changed only when the server is
// started. Adding or removing a security group on a running server
// will not take effect until that server is restarted. However,
// changing rules of existing groups will take effect immediately.
//
// For more information:
// http://docs.openstack.org/developer/nova/nova.concepts.html#concept-security-groups
// Nova source: https://github.com/openstack/nova.git
type RuleInfo struct {
/// IPProtocol is optional, and if specified must be "tcp", "udp" or
// "icmp" (in this case, both FromPort and ToPort can be -1).
IPProtocol string `json:"ip_protocol"`
// FromPort and ToPort are both optional, and if specifed must be
// integers between 1 and 65535 (valid TCP port numbers). -1 is a
// special value, meaning "use default" (e.g. for ICMP).
FromPort int `json:"from_port"`
ToPort int `json:"to_port"`
// Cidr cannot be specified with GroupId. Ingress rules need a valid
// subnet mast in CIDR format here, while if GroupID is specifed, it
// means you're adding a group rule, specifying source group ID, which
// must exist already and can be equal to ParentGroupId).
// need Cidr, while
Cidr string `json:"cidr"`
GroupId *string `json:"-"`
// ParentGroupId is always required and specifies the group to which
// the rule is added.
ParentGroupId string `json:"-"`
}
// CreateSecurityGroupRule creates a security group rule.
// It can either be an ingress rule or group rule (see the
// description of RuleInfo).
func (c *Client) CreateSecurityGroupRule(ruleInfo RuleInfo) (*SecurityGroupRule, error) {
var req struct {
SecurityGroupRule RuleInfo `json:"security_group_rule"`
}
req.SecurityGroupRule = ruleInfo
var resp struct {
SecurityGroupRule SecurityGroupRule `json:"security_group_rule"`
}
requestData := goosehttp.RequestData{ReqValue: req, RespValue: &resp}
err := c.client.SendRequest(client.POST, "compute", "v2", apiSecurityGroupRules, &requestData)
if err != nil {
return nil, errors.Newf(err, "failed to create a rule for the security group with id: %v", ruleInfo.GroupId)
}
return &resp.SecurityGroupRule, nil
}
// DeleteSecurityGroupRule deletes the specified security group rule.
func (c *Client) DeleteSecurityGroupRule(ruleId string) error {
url := fmt.Sprintf("%s/%s", apiSecurityGroupRules, ruleId)
requestData := goosehttp.RequestData{ExpectedStatus: []int{http.StatusAccepted}}
err := c.client.SendRequest(client.DELETE, "compute", "v2", url, &requestData)
if err != nil {
err = errors.Newf(err, "failed to delete security group rule with id: %s", ruleId)
}
return err
}
// FloatingIP describes a floating (public) IP address, which can be
// assigned to a server, thus allowing connections from outside.
type FloatingIP struct {
// FixedIP holds the private IP address of the machine (when assigned)
FixedIP *string `json:"fixed_ip"`
Id string `json:"-"`
// InstanceId holds the instance id of the machine, if this FIP is assigned to one
InstanceId *string `json:"-"`
IP string `json:"ip"`
Pool string `json:"pool"`
}
// ListFloatingIPs lists floating IP addresses associated with the tenant or account.
func (c *Client) ListFloatingIPs() ([]FloatingIP, error) {
var resp struct {
FloatingIPs []FloatingIP `json:"floating_ips"`
}
requestData := goosehttp.RequestData{RespValue: &resp}
err := c.client.SendRequest(client.GET, "compute", "v2", apiFloatingIPs, &requestData)
if err != nil {
return nil, errors.Newf(err, "failed to list floating ips")
}
return resp.FloatingIPs, nil
}
// GetFloatingIP lists details of the floating IP address associated with specified id.
func (c *Client) GetFloatingIP(ipId string) (*FloatingIP, error) {
var resp struct {
FloatingIP FloatingIP `json:"floating_ip"`
}
url := fmt.Sprintf("%s/%s", apiFloatingIPs, ipId)
requestData := goosehttp.RequestData{RespValue: &resp}
err := c.client.SendRequest(client.GET, "compute", "v2", url, &requestData)
if err != nil {
return nil, errors.Newf(err, "failed to get floating ip %s details", ipId)
}
return &resp.FloatingIP, nil
}
// AllocateFloatingIP allocates a new floating IP address to a tenant or account.
func (c *Client) AllocateFloatingIP() (*FloatingIP, error) {
var resp struct {
FloatingIP FloatingIP `json:"floating_ip"`
}
requestData := goosehttp.RequestData{RespValue: &resp}
err := c.client.SendRequest(client.POST, "compute", "v2", apiFloatingIPs, &requestData)
if err != nil {
return nil, errors.Newf(err, "failed to allocate a floating ip")
}
return &resp.FloatingIP, nil
}
// DeleteFloatingIP deallocates the floating IP address associated with the specified id.
func (c *Client) DeleteFloatingIP(ipId string) error {
url := fmt.Sprintf("%s/%s", apiFloatingIPs, ipId)
requestData := goosehttp.RequestData{ExpectedStatus: []int{http.StatusAccepted}}
err := c.client.SendRequest(client.DELETE, "compute", "v2", url, &requestData)
if err != nil {
err = errors.Newf(err, "failed to delete floating ip %s details", ipId)
}
return err
}
| go-goose/goose | nova/deprecated.go | GO | lgpl-3.0 | 11,939 |
package eu.europa.echa.iuclid6.namespaces.flexible_record_estimatedquantities._6;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the eu.europa.echa.iuclid6.namespaces.flexible_record_estimatedquantities._6 package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _FLEXIBLERECORDEstimatedQuantitiesTotalTonnageImported_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "Imported");
private final static QName _FLEXIBLERECORDEstimatedQuantitiesTotalTonnageManufacturer_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "Manufacturer");
private final static QName _FLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageImportedArticles_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageImportedArticles");
private final static QName _FLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageProducedArticles_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageProducedArticles");
private final static QName _FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageOwnUser_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageOwnUser");
private final static QName _FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateTransporter_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageIntermediateTransporter");
private final static QName _FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageDirectlyExported_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageDirectlyExported");
private final static QName _FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateOnsite_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageIntermediateOnsite");
private final static QName _FLEXIBLERECORDEstimatedQuantitiesYear_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "Year");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: eu.europa.echa.iuclid6.namespaces.flexible_record_estimatedquantities._6
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link FLEXIBLERECORDEstimatedQuantities }
*
*/
public FLEXIBLERECORDEstimatedQuantities createFLEXIBLERECORDEstimatedQuantities() {
return new FLEXIBLERECORDEstimatedQuantities();
}
/**
* Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.DataProtection }
*
*/
public FLEXIBLERECORDEstimatedQuantities.DataProtection createFLEXIBLERECORDEstimatedQuantitiesDataProtection() {
return new FLEXIBLERECORDEstimatedQuantities.DataProtection();
}
/**
* Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.TotalTonnage }
*
*/
public FLEXIBLERECORDEstimatedQuantities.TotalTonnage createFLEXIBLERECORDEstimatedQuantitiesTotalTonnage() {
return new FLEXIBLERECORDEstimatedQuantities.TotalTonnage();
}
/**
* Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.DetailsTonnage }
*
*/
public FLEXIBLERECORDEstimatedQuantities.DetailsTonnage createFLEXIBLERECORDEstimatedQuantitiesDetailsTonnage() {
return new FLEXIBLERECORDEstimatedQuantities.DetailsTonnage();
}
/**
* Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles }
*
*/
public FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles createFLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticles() {
return new FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles();
}
/**
* Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.AdditionalInformation }
*
*/
public FLEXIBLERECORDEstimatedQuantities.AdditionalInformation createFLEXIBLERECORDEstimatedQuantitiesAdditionalInformation() {
return new FLEXIBLERECORDEstimatedQuantities.AdditionalInformation();
}
/**
* Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.DataProtection.Legislation }
*
*/
public FLEXIBLERECORDEstimatedQuantities.DataProtection.Legislation createFLEXIBLERECORDEstimatedQuantitiesDataProtectionLegislation() {
return new FLEXIBLERECORDEstimatedQuantities.DataProtection.Legislation();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "Imported", scope = FLEXIBLERECORDEstimatedQuantities.TotalTonnage.class)
public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesTotalTonnageImported(BigDecimal value) {
return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesTotalTonnageImported_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.TotalTonnage.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "Manufacturer", scope = FLEXIBLERECORDEstimatedQuantities.TotalTonnage.class)
public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesTotalTonnageManufacturer(BigDecimal value) {
return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesTotalTonnageManufacturer_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.TotalTonnage.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageImportedArticles", scope = FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles.class)
public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageImportedArticles(BigDecimal value) {
return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageImportedArticles_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageProducedArticles", scope = FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles.class)
public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageProducedArticles(BigDecimal value) {
return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageProducedArticles_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageOwnUser", scope = FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class)
public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageOwnUser(BigDecimal value) {
return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageOwnUser_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageIntermediateTransporter", scope = FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class)
public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateTransporter(BigDecimal value) {
return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateTransporter_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageDirectlyExported", scope = FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class)
public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageDirectlyExported(BigDecimal value) {
return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageDirectlyExported_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageIntermediateOnsite", scope = FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class)
public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateOnsite(BigDecimal value) {
return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateOnsite_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link BigInteger }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "Year", scope = FLEXIBLERECORDEstimatedQuantities.class)
public JAXBElement<BigInteger> createFLEXIBLERECORDEstimatedQuantitiesYear(BigInteger value) {
return new JAXBElement<BigInteger>(_FLEXIBLERECORDEstimatedQuantitiesYear_QNAME, BigInteger.class, FLEXIBLERECORDEstimatedQuantities.class, value);
}
}
| ideaconsult/i5 | iuclid_6_4-io/src/main/java/eu/europa/echa/iuclid6/namespaces/flexible_record_estimatedquantities/_6/ObjectFactory.java | Java | lgpl-3.0 | 11,538 |
/**
*
*/
package com.github.nicosensei.batch.elasticsearch;
import org.apache.log4j.Level;
import com.github.nicosensei.batch.BatchException;
/**
* @author nicolas
*
*/
public class SkipLimitExceededException extends BatchException {
/**
*
*/
private static final long serialVersionUID = 1095268691743122833L;
public SkipLimitExceededException(final int skipLimit) {
super(
"OVER_SKIP_LIMIT",
"Exceeded skip limit of {0}",
new String[] { Integer.toString(skipLimit) },
Level.FATAL);
}
}
| nicosensei/batch-tools | batch-tools-elasticsearch/src/main/java/com/github/nicosensei/batch/elasticsearch/SkipLimitExceededException.java | Java | lgpl-3.0 | 525 |
package com.ash6390.jarcraft.utility;
import com.ash6390.jarcraft.reference.References;
import cpw.mods.fml.common.FMLLog;
import org.apache.logging.log4j.Level;
public class LogHelper
{
public static void log(Level logLevel, Object object)
{
FMLLog.log(References.NAME, logLevel, String.valueOf(object));
}
public static void all(Object object) { log(Level.ALL, object); }
public static void debug(Object object) { log(Level.DEBUG, object); }
public static void error(Object object) { log(Level.ERROR, object); }
public static void fatal(Object object) { log(Level.FATAL, object); }
public static void info(Object object) { log(Level.INFO, object); }
public static void off(Object object) { log(Level.OFF, object); }
public static void trace(Object object) { log(Level.TRACE, object); }
public static void warn(Object object) { log(Level.WARN, object); }
}
| Ash6390/JarCraft | src/main/java/com/ash6390/jarcraft/utility/LogHelper.java | Java | lgpl-3.0 | 920 |
// This file is part of VSTGUI. It is subject to the license terms
// in the LICENSE file found in the top-level directory of this
// distribution and at http://github.com/steinbergmedia/vstgui/LICENSE
#include "uicrosslines.h"
#if VSTGUI_LIVE_EDITING
#include "../../lib/cviewcontainer.h"
#include "../../lib/cdrawcontext.h"
#include "uiselection.h"
namespace VSTGUI {
//----------------------------------------------------------------------------------------------------
UICrossLines::UICrossLines (CViewContainer* editView, int32_t style, const CColor& background, const CColor& foreground)
: CView (CRect (0, 0, 0, 0))
, editView (editView)
, style (style)
, background (background)
, foreground (foreground)
{
setMouseEnabled (false);
viewSizeChanged (editView, CRect (0, 0, 0, 0));
editView->registerViewListener (this);
}
//----------------------------------------------------------------------------------------------------
UICrossLines::~UICrossLines ()
{
editView->unregisterViewListener (this);
}
//----------------------------------------------------------------------------------------------------
void UICrossLines::viewSizeChanged (CView* view, const CRect& oldSize)
{
CRect r = editView->getVisibleViewSize ();
r.originize ();
CPoint p;
editView->getParentView ()->localToFrame (p);
r.offset (p.x, p.y);
if (getViewSize () != r)
{
invalidRect (getViewSize ());
setViewSize (r);
}
}
//----------------------------------------------------------------------------------------------------
void UICrossLines::update (UISelection* selection)
{
invalid ();
CPoint p;
currentRect = selection->getBounds ();
localToFrame (p);
currentRect.offset (-p.x, -p.y);
invalid ();
}
//----------------------------------------------------------------------------------------------------
void UICrossLines::update (const CPoint& point)
{
invalid ();
currentRect.left = point.x-1;
currentRect.top = point.y-1;
currentRect.setWidth (1);
currentRect.setHeight (1);
editView->getTransform ().transform (currentRect);
CPoint p;
getParentView ()->frameToLocal (p);
currentRect.offset (p.x, p.y);
editView->localToFrame (p);
currentRect.offset (p.x, p.y);
invalid ();
}
//----------------------------------------------------------------------------------------------------
void UICrossLines::invalid ()
{
CRect frameRect = getViewSize ();
invalidRect (CRect (currentRect.left-3, frameRect.top, currentRect.left+3, frameRect.bottom));
invalidRect (CRect (frameRect.left, currentRect.top-3, frameRect.right, currentRect.top+3));
if (style == kSelectionStyle)
{
invalidRect (CRect (currentRect.right-3, frameRect.top, currentRect.right+3, frameRect.bottom));
invalidRect (CRect (frameRect.left, currentRect.bottom-3, frameRect.right, currentRect.bottom+3));
}
}
//----------------------------------------------------------------------------------------------------
void UICrossLines::drawLines (CDrawContext* pContext, const CRect& size, const CRect& selectionSize)
{
pContext->drawLine (CPoint (size.left, selectionSize.top), CPoint (size.right, selectionSize.top));
pContext->drawLine (CPoint (selectionSize.left, size.top), CPoint (selectionSize.left, size.bottom));
if (style == kSelectionStyle)
{
pContext->drawLine (CPoint (size.left, selectionSize.bottom - 1), CPoint (size.right, selectionSize.bottom - 1));
pContext->drawLine (CPoint (selectionSize.right-1, size.top), CPoint (selectionSize.right-1, size.bottom));
}
}
//----------------------------------------------------------------------------------------------------
void UICrossLines::draw (CDrawContext* pContext)
{
CRect size = getViewSize ();
CRect selectionSize (currentRect);
pContext->setDrawMode (kAliasing);
pContext->setLineStyle (kLineSolid);
pContext->setFrameColor (background);
pContext->setLineWidth (1);
drawLines (pContext, size, selectionSize);
static const CCoord dashLength [] = {3,3};
static const CLineStyle lineStyle (CLineStyle::kLineCapButt, CLineStyle::kLineJoinMiter, 0, 2, dashLength);
pContext->setLineStyle (lineStyle);
pContext->setFrameColor (foreground);
drawLines (pContext, size, selectionSize);
}
}
#endif // VSTGUI_LIVE_EDITING
| surikov/riffshare | wrapper/vst/i/vstgui4/vstgui/uidescription/editing/uicrosslines.cpp | C++ | lgpl-3.0 | 4,201 |
/* -*-coding: mule-utf-8-unix; fill-column: 58; -*-
Copyright (C) 2009, 2013 Sergei Lodyagin
This file is part of the Cohors Concurro library.
This library is free software: you can redistribute it
and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your
option) any later version.
This 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 Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this program. If not, see
<http://www.gnu.org/licenses/>.
*/
/**
* @file
*
* @author Sergei Lodyagin
*/
#include "Guard.h"
namespace curr {
DEFINE_AXIS(
NReaders1WriterAxis,
{
"free",
"reader_entering",
"readers_entered", // read operations on an object in
// progress
"reader_exiting",
"writer_entered" // write operation on an object
// in progress
},
{
{ "free", "reader_entering" },
{ "reader_entering", "readers_entered" },
// more readers
{ "readers_entered", "reader_entering" },
{ "readers_entered", "reader_exiting" },
{ "reader_exiting", "readers_entered" },
{ "reader_exiting", "free" },
// <NB> only one writer
{ "free", "writer_entered" },
{ "writer_entered", "free" }
});
}
| lodyagin/concurro | C++/Guard.cpp | C++ | lgpl-3.0 | 1,580 |
class Substitution < ApplicationRecord
belongs_to :tutor
has_one :absence
has_one :meeting
end
| tuliglowicz/resource-substitution | app/models/substitution.rb | Ruby | lgpl-3.0 | 101 |
package jcl.lang;
import jcl.lang.internal.stream.SynonymStreamStructImpl;
/**
* The {@link SynonymStreamStruct} is the object representation of a Lisp 'synonym-stream' type.
*/
public interface SynonymStreamStruct extends IOStreamStruct {
/**
* Returns the {@link SymbolStruct} stream symbol.
*
* @return the {@link SymbolStruct} stream symbol
*/
SymbolStruct synonymStreamSymbol();
/**
* Returns a new Synonym-Stream instance that will delegate stream operations to the value of the provided {@link
* SymbolStruct}.
*
* @param symbol
* the {@link SymbolStruct} containing a {@link StreamStruct} value
*
* @return a new Synonym-Stream instance
*/
static SynonymStreamStruct toSynonymStream(final SymbolStruct symbol) {
return new SynonymStreamStructImpl(symbol);
}
}
| scodynelson/JCL | jcl-core/src/main/java/jcl/lang/SynonymStreamStruct.java | Java | lgpl-3.0 | 807 |
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2011 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* Sonar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.api.utils;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
public class ServerHttpClientTest {
private String serverUrl = "http://test";
private ServerHttpClient serverHttpClient;
@Before
public void before() {
serverHttpClient = new ServerHttpClient(serverUrl);
}
@Test
public void shouldReturnAValidResult() throws IOException {
final String validContent = "valid";
ServerHttpClient serverHttpClient = new ServerHttpClient(serverUrl) {
@Override
protected String getRemoteContent(String url) {
return (validContent);
}
};
assertThat(serverHttpClient.executeAction("an action"), is(validContent));
}
@Test
public void shouldRemoveLastUrlSlash() {
ServerHttpClient serverHttpClient = new ServerHttpClient(serverUrl + "/");
assertThat(serverHttpClient.getUrl(), is(serverUrl));
}
@Test(expected = ServerHttpClient.ServerApiEmptyContentException.class)
public void shouldThrowAnExceptionIfResultIsEmpty() throws IOException {
final String invalidContent = " ";
ServerHttpClient serverHttpClient = new ServerHttpClient(serverUrl) {
@Override
protected String getRemoteContent(String url) {
return (invalidContent);
}
};
serverHttpClient.executeAction("an action");
}
@Test
public void shouldReturnMavenRepositoryUrl() {
String sonarRepo = serverHttpClient.getMavenRepositoryUrl();
assertThat(sonarRepo, is(serverUrl + ServerHttpClient.MAVEN_PATH));
}
@Test(expected = ServerHttpClient.ServerConnectionException.class)
public void shouldFailIfCanNotConnectToServer() {
ServerHttpClient serverHttpClient = new ServerHttpClient("fake") {
@Override
protected String getRemoteContent(String url) {
throw new ServerConnectionException("");
}
};
serverHttpClient.checkUp();
}
}
| leodmurillo/sonar | sonar-plugin-api/src/test/java/org/sonar/api/utils/ServerHttpClientTest.java | Java | lgpl-3.0 | 2,855 |
/*
* This file is part of Spoutcraft (http://wiki.getspout.org/).
*
* Spoutcraft is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Spoutcraft is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.getspout.spout.packet;
public enum ScreenAction {
Open(0),
Close(1),
;
private final byte id;
ScreenAction(int id) {
this.id = (byte)id;
}
public int getId() {
return id;
}
public static ScreenAction getScreenActionFromId(int id) {
for (ScreenAction action : values()) {
if (action.getId() == id) {
return action;
}
}
return null;
}
}
| copyliu/Spoutcraft_CJKPatch | src/minecraft/org/getspout/spout/packet/ScreenAction.java | Java | lgpl-3.0 | 1,122 |
package net.minecraft.entity.ai;
import net.minecraft.entity.ai.EntityAIBase;
import net.minecraft.entity.passive.EntityVillager;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
public class EntityAITradePlayer extends EntityAIBase {
private EntityVillager field_75276_a;
public EntityAITradePlayer(EntityVillager p_i1658_1_) {
this.field_75276_a = p_i1658_1_;
this.func_75248_a(5);
}
public boolean func_75250_a() {
if(!this.field_75276_a.func_70089_S()) {
return false;
} else if(this.field_75276_a.func_70090_H()) {
return false;
} else if(!this.field_75276_a.field_70122_E) {
return false;
} else if(this.field_75276_a.field_70133_I) {
return false;
} else {
EntityPlayer var1 = this.field_75276_a.func_70931_l_();
return var1 == null?false:(this.field_75276_a.func_70068_e(var1) > 16.0D?false:var1.field_71070_bA instanceof Container);
}
}
public void func_75249_e() {
this.field_75276_a.func_70661_as().func_75499_g();
}
public void func_75251_c() {
this.field_75276_a.func_70932_a_((EntityPlayer)null);
}
}
| HATB0T/RuneCraftery | forge/mcp/temp/src/minecraft/net/minecraft/entity/ai/EntityAITradePlayer.java | Java | lgpl-3.0 | 1,206 |
package org.molgenis.data.annotation.core.entity.impl.hpo;
import au.com.bytecode.opencsv.CSVParser;
import au.com.bytecode.opencsv.CSVReader;
import com.google.common.collect.Iterables;
import org.molgenis.data.Entity;
import org.molgenis.data.MolgenisDataException;
import org.molgenis.data.Query;
import org.molgenis.data.QueryRule.Operator;
import org.molgenis.data.RepositoryCapability;
import org.molgenis.data.meta.model.AttributeFactory;
import org.molgenis.data.meta.model.EntityType;
import org.molgenis.data.meta.model.EntityTypeFactory;
import org.molgenis.data.support.AbstractRepository;
import org.molgenis.data.support.DynamicEntity;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Stream;
import static org.molgenis.data.meta.model.EntityType.AttributeRole.ROLE_ID;
public class HPORepository extends AbstractRepository
{
public static final String HPO_DISEASE_ID_COL_NAME = "diseaseId";
public static final String HPO_GENE_SYMBOL_COL_NAME = "gene-symbol";
public static final String HPO_ID_COL_NAME = "HPO-ID";
public static final String HPO_TERM_COL_NAME = "HPO-term-name";
private final EntityTypeFactory entityTypeFactory;
private final AttributeFactory attributeFactory;
private Map<String, List<Entity>> entitiesByGeneSymbol;
private final File file;
public HPORepository(File file, EntityTypeFactory entityTypeFactory, AttributeFactory attributeFactory)
{
this.file = file;
this.entityTypeFactory = entityTypeFactory;
this.attributeFactory = attributeFactory;
}
@Override
public Set<RepositoryCapability> getCapabilities()
{
return Collections.emptySet();
}
@Override
public EntityType getEntityType()
{
EntityType entityType = entityTypeFactory.create().setSimpleName("HPO");
entityType.addAttribute(attributeFactory.create().setName(HPO_DISEASE_ID_COL_NAME));
entityType.addAttribute(attributeFactory.create().setName(HPO_GENE_SYMBOL_COL_NAME));
entityType.addAttribute(attributeFactory.create().setName(HPO_ID_COL_NAME), ROLE_ID);
entityType.addAttribute(attributeFactory.create().setName(HPO_TERM_COL_NAME));
return entityType;
}
@Override
public Iterator<Entity> iterator()
{
return getEntities().iterator();
}
@Override
public Stream<Entity> findAll(Query<Entity> q)
{
if (q.getRules().isEmpty()) return getEntities().stream();
if ((q.getRules().size() != 1) || (q.getRules().get(0).getOperator() != Operator.EQUALS))
{
throw new MolgenisDataException("The only query allowed on this Repository is gene EQUALS");
}
String geneSymbol = (String) q.getRules().get(0).getValue();
List<Entity> entities = getEntitiesByGeneSymbol().get(geneSymbol);
return entities != null ? entities.stream() : Stream.empty();
}
@Override
public long count()
{
return Iterables.size(this);
}
private List<Entity> getEntities()
{
List<Entity> entities = new ArrayList<>();
getEntitiesByGeneSymbol().forEach((geneSymbol, geneSymbolEntities) -> entities.addAll(geneSymbolEntities));
return entities;
}
private Map<String, List<Entity>> getEntitiesByGeneSymbol()
{
if (entitiesByGeneSymbol == null)
{
entitiesByGeneSymbol = new LinkedHashMap<>();
try (CSVReader csvReader = new CSVReader(
new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")), '\t',
CSVParser.DEFAULT_QUOTE_CHARACTER, 1))
{
String[] values = csvReader.readNext();
while (values != null)
{
String geneSymbol = values[1];
Entity entity = new DynamicEntity(getEntityType());
entity.set(HPO_DISEASE_ID_COL_NAME, values[0]);
entity.set(HPO_GENE_SYMBOL_COL_NAME, geneSymbol);
entity.set(HPO_ID_COL_NAME, values[3]);
entity.set(HPO_TERM_COL_NAME, values[4]);
List<Entity> entities = entitiesByGeneSymbol.get(geneSymbol);
if (entities == null)
{
entities = new ArrayList<>();
entitiesByGeneSymbol.put(geneSymbol, entities);
}
entities.add(entity);
values = csvReader.readNext();
}
}
catch (IOException e)
{
throw new UncheckedIOException(e);
}
}
return entitiesByGeneSymbol;
}
}
| jjettenn/molgenis | molgenis-data-annotators/src/main/java/org/molgenis/data/annotation/core/entity/impl/hpo/HPORepository.java | Java | lgpl-3.0 | 4,146 |
package org.opennaas.extensions.genericnetwork.model.circuit.request;
/*
* #%L
* OpenNaaS :: Generic Network
* %%
* Copyright (C) 2007 - 2014 Fundació Privada i2CAT, Internet i Innovació a Catalunya
* %%
* 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.
* #L%
*/
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.opennaas.extensions.genericnetwork.model.circuit.QoSPolicy;
/**
*
* @author Adrian Rosello Rey (i2CAT)
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"source",
"destination",
"label",
"qosPolicy"
})
@XmlRootElement(name = "qos_policy_request", namespace = "opennaas.api")
public class CircuitRequest {
@XmlAttribute(name = "atomic")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
private String atomic;
@XmlElement(required = true)
private Source source;
@XmlElement(required = true)
private Destination destination;
@XmlElement(required = true)
private String label;
@XmlElement(name = "qos_policy")
private QoSPolicy qosPolicy;
public String getAtomic() {
return atomic;
}
public void setAtomic(String atomic) {
this.atomic = atomic;
}
public Source getSource() {
return source;
}
public void setSource(Source source) {
this.source = source;
}
public Destination getDestination() {
return destination;
}
public void setDestination(Destination destination) {
this.destination = destination;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public QoSPolicy getQosPolicy() {
return qosPolicy;
}
public void setQosPolicy(QoSPolicy qosPolicy) {
this.qosPolicy = qosPolicy;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((atomic == null) ? 0 : atomic.hashCode());
result = prime * result + ((destination == null) ? 0 : destination.hashCode());
result = prime * result + ((label == null) ? 0 : label.hashCode());
result = prime * result + ((qosPolicy == null) ? 0 : qosPolicy.hashCode());
result = prime * result + ((source == null) ? 0 : source.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CircuitRequest other = (CircuitRequest) obj;
if (atomic == null) {
if (other.atomic != null)
return false;
} else if (!atomic.equals(other.atomic))
return false;
if (destination == null) {
if (other.destination != null)
return false;
} else if (!destination.equals(other.destination))
return false;
if (label == null) {
if (other.label != null)
return false;
} else if (!label.equals(other.label))
return false;
if (qosPolicy == null) {
if (other.qosPolicy != null)
return false;
} else if (!qosPolicy.equals(other.qosPolicy))
return false;
if (source == null) {
if (other.source != null)
return false;
} else if (!source.equals(other.source))
return false;
return true;
}
}
| dana-i2cat/opennaas | extensions/bundles/genericnetwork/src/main/java/org/opennaas/extensions/genericnetwork/model/circuit/request/CircuitRequest.java | Java | lgpl-3.0 | 3,943 |
package de.klickreform.dropkit.dao;
import de.klickreform.dropkit.exception.DuplicateEntryException;
import de.klickreform.dropkit.exception.NotFoundException;
import de.klickreform.dropkit.models.DomainModel;
import java.io.Serializable;
import java.util.Collection;
/**
* Interface for Data Access Object (DAO) implementations that provide basic CRUD operations for a
* Data Access Layer.
*
* @author Benjamin Bestmann
*/
public interface Dao<E extends DomainModel,K extends Serializable> {
public Collection<E> findAll();
public E findById(K id) throws NotFoundException;
public String create(E entity) throws DuplicateEntryException;
public String createOrUpdate(E entity);
public String update(E entity) throws NotFoundException, DuplicateEntryException;
public void delete(E entity) throws NotFoundException;
}
| KlickReform/dropkit | src/main/java/de/klickreform/dropkit/dao/Dao.java | Java | lgpl-3.0 | 856 |
<?php
include_once('PaymentTest.php');
ClassLoader::import('library.payment.method.VCS');
/**
*
* @package library.payment.test
* @author Integry Systems
*/
class VCSTest extends PaymentTest
{
private function getPaymentHandler()
{
$payment = new VCS($this->details);
$payment->setConfigValue('account', 111);
$payment->setConfigValue('description', 'test');
$payment->setSiteUrl('http://localhost');
return $payment;
}
function testPayment()
{
$payment = $this->getPaymentHandler();
$postParams = $payment->getPostParams();
$data['p1'] = $postParams['p1'];
$data['p2'] = rand(1, 100000);
$data['p3'] = '123456 APPROVED';
$data['p5'] = 'Cardholder name';
$data['p6'] = $postParams['p4'];
$data['p7'] = 'Visa';
$data['p8'] = $postParams['p3'];
$data['p9'] = $postParams['p'];
$data['test'] = true;
$notify = $payment->notify($data);
$this->assertEquals($notify->gatewayTransactionID->get(), $data['p2']);
$this->assertEquals($notify->amount->get(), $data['p6']);
$this->assertEquals($notify->getTransactionType(), TransactionResult::TYPE_SALE);
}
}
?> | integry/integry-payments | test/VCSTest.php | PHP | lgpl-3.0 | 1,158 |
/*******************************************************************************
* Copyright (c) 2010 Robert "Unlogic" Olofsson (unlogic@unlogic.se).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0-standalone.html
******************************************************************************/
package se.unlogic.hierarchy.core.beans;
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import se.unlogic.hierarchy.core.interfaces.BundleDescriptor;
import se.unlogic.hierarchy.core.interfaces.ForegroundModuleDescriptor;
import se.unlogic.hierarchy.core.interfaces.MenuItemDescriptor;
import se.unlogic.standardutils.xml.XMLUtils;
public class Bundle extends MenuItem implements Cloneable {
private final Integer moduleID;
private String uniqueID;
private ArrayList<ModuleMenuItem> moduleMenuItems;
public Bundle(BundleDescriptor bundleDescriptor, ForegroundModuleDescriptor descriptor) {
this.name = bundleDescriptor.getName();
this.description = bundleDescriptor.getDescription();
this.url = bundleDescriptor.getUrl();
this.urlType = bundleDescriptor.getUrlType();
this.itemType = bundleDescriptor.getItemType();
this.allowedGroupIDs = bundleDescriptor.getAllowedGroupIDs();
this.allowedUserIDs = bundleDescriptor.getAllowedUserIDs();
this.adminAccess = bundleDescriptor.allowsAdminAccess();
this.userAccess = bundleDescriptor.allowsUserAccess();
this.anonymousAccess = bundleDescriptor.allowsAnonymousAccess();
this.moduleMenuItems = new ArrayList<ModuleMenuItem>();
if(bundleDescriptor.getMenuItemDescriptors() != null){
List<? extends MenuItemDescriptor> tempMenuItemDescriptors = bundleDescriptor.getMenuItemDescriptors();
for (MenuItemDescriptor menuItemDescriptor : tempMenuItemDescriptors) {
this.moduleMenuItems.add(new ModuleMenuItem(menuItemDescriptor, descriptor, true));
}
}
this.sectionID = descriptor.getSectionID();
this.moduleID = descriptor.getModuleID();
this.uniqueID = bundleDescriptor.getUniqueID();
}
public ArrayList<ModuleMenuItem> getModuleMenuItems() {
return this.moduleMenuItems;
}
public Integer getModuleID() {
return moduleID;
}
@Override
public void setMenuIndex(Integer menuIndex) {
this.menuIndex = menuIndex;
}
public void setUniqueID(String uniqueID) {
this.uniqueID = uniqueID;
}
public String getUniqueID() {
return uniqueID;
}
@Override
protected void getAdditionalXML(Document doc, Element menuItemElement) {
Element bundleElement = doc.createElement("bundle");
bundleElement.appendChild(XMLUtils.createCDATAElement("moduleID", this.moduleID.toString(), doc));
bundleElement.appendChild(XMLUtils.createCDATAElement("uniqueID", this.uniqueID, doc));
menuItemElement.appendChild(bundleElement);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((moduleID == null) ? 0 : moduleID.hashCode());
result = prime * result + ((uniqueID == null) ? 0 : uniqueID.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Bundle other = (Bundle) obj;
if (moduleID == null) {
if (other.moduleID != null) {
return false;
}
} else if (!moduleID.equals(other.moduleID)) {
return false;
}
if (uniqueID == null) {
if (other.uniqueID != null) {
return false;
}
} else if (!uniqueID.equals(other.uniqueID)) {
return false;
}
return true;
}
@Override
public Bundle clone() {
try {
Bundle bundle = (Bundle) super.clone();
bundle.moduleMenuItems = new ArrayList<ModuleMenuItem>(this.moduleMenuItems);
return bundle;
} catch (CloneNotSupportedException e) {
// This can never happen since we implement clonable...
throw new RuntimeException(e);
}
}
public Element toFullXML(Document doc) {
Element bundleElement = doc.createElement("bundle");
bundleElement.appendChild(XMLUtils.createCDATAElement("moduleID", this.moduleID.toString(), doc));
if (this.name != null) {
bundleElement.appendChild(XMLUtils.createCDATAElement("name", this.name, doc));
}
if (this.description != null) {
bundleElement.appendChild(XMLUtils.createCDATAElement("description", this.description, doc));
}
if (this.menuIndex != null) {
bundleElement.appendChild(XMLUtils.createCDATAElement("menuIndex", this.menuIndex.toString(), doc));
}
if (this.url != null) {
bundleElement.appendChild(XMLUtils.createCDATAElement("url", this.url, doc));
}
if (this.urlType != null) {
bundleElement.appendChild(XMLUtils.createCDATAElement("urlType", this.urlType.toString(), doc));
}
if (this.itemType != null) {
bundleElement.appendChild(XMLUtils.createCDATAElement("itemType", this.itemType.toString(), doc));
}
if (this.sectionID != null) {
bundleElement.appendChild(XMLUtils.createCDATAElement("sectionID", this.sectionID.toString(), doc));
}
if(uniqueID != null){
bundleElement.appendChild(XMLUtils.createCDATAElement("uniqueID", this.uniqueID.toString(), doc));
}
Element adminAccess = doc.createElement("adminAccess");
adminAccess.appendChild(doc.createTextNode(Boolean.toString(this.adminAccess)));
bundleElement.appendChild(adminAccess);
Element userAccess = doc.createElement("userAccess");
userAccess.appendChild(doc.createTextNode(Boolean.toString(this.userAccess)));
bundleElement.appendChild(userAccess);
Element anonymousAccess = doc.createElement("anonymousAccess");
anonymousAccess.appendChild(doc.createTextNode(Boolean.toString(this.anonymousAccess)));
bundleElement.appendChild(anonymousAccess);
XMLUtils.append(doc, bundleElement, "menuitems", this.moduleMenuItems);
return bundleElement;
}
}
| SvenssonWeb/OpenHierarchy | src/main/java/se/unlogic/hierarchy/core/beans/Bundle.java | Java | lgpl-3.0 | 6,040 |
package clearvolume.utils;
import java.awt.Image;
import java.awt.Window;
import java.lang.reflect.Method;
public class AppleMac
{
// final static com.apple.eawt.Application cApplication =
// com.apple.eawt.Application.getApplication();
static Class<?> cClass;
static Object cApplication;
static
{
try
{
cClass = Class.forName("com.apple.eawt.Application");
Method lMethod = cClass.getDeclaredMethod("getApplication");
cApplication = lMethod.invoke(null);
}
catch (Throwable e)
{
System.err.println(e.getLocalizedMessage());
}
}
private static String OS = System.getProperty("os.name")
.toLowerCase();
public static boolean isMac()
{
return (OS.indexOf("mac") >= 0);
}
public static final boolean setApplicationIcon(final Image pImage)
{
if (!isMac())
return false;
try
{
final Thread lThread = new Thread("Apple Set Application Icon")
{
@Override
public void run()
{
try
{
Method lMethod = cClass.getDeclaredMethod( "setDockIconImage",
Image.class);
lMethod.invoke(cApplication, pImage);
// cApplication.setDockIconImage(pImage);
}
catch (final Throwable e)
{
System.out.println(AppleMac.class.getSimpleName() + ": Could not set Dock Icon (not on osx?)");
}
super.run();
}
};
lThread.start();
return true;
}
catch (final Throwable e)
{
System.err.println(e.getMessage());
return false;
}
}
public static final boolean setApplicationName(final String pString)
{
if (!isMac())
return false;
try
{
System.setProperty( "com.apple.mrj.application.apple.menu.about.name",
pString);
return true;
}
catch (final Throwable e)
{
System.err.println(e.getMessage());
return false;
}
}
@SuppressWarnings(
{ "unchecked", "rawtypes" })
public static boolean enableOSXFullscreen(final Window window)
{
if (!isMac())
return false;
if (window == null)
return false;
try
{
final Class util = Class.forName("com.apple.eawt.FullScreenUtilities");
final Class params[] = new Class[]
{ Window.class, Boolean.TYPE };
final Method method = util.getMethod( "setWindowCanFullScreen",
params);
method.invoke(util, window, true);
return true;
}
catch (final Throwable e)
{
System.err.println(e.getLocalizedMessage());
return false;
}
}
public final static boolean requestFullscreen(final Window pWindow)
{
if (!isMac())
return false;
try
{
// cApplication.requestToggleFullScreen(pWindow);
Method lMethod = cClass.getDeclaredMethod( "requestToggleFullScreen",
Window.class);
lMethod.invoke(cApplication, pWindow);
return true;
}
catch (final Throwable e)
{
System.err.println(e.getLocalizedMessage());
return false;
}
}
}
| ClearVolume/ClearVolume | src/java/clearvolume/utils/AppleMac.java | Java | lgpl-3.0 | 2,849 |
/*
* $Id$
*
* Copyright 2009 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package org.jdesktop.swingx.plaf;
import javax.swing.BorderFactory;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.plaf.BorderUIResource;
import javax.swing.plaf.metal.MetalBorders;
/**
* Addon for JXTableHeader.
*
* Implemented to hack around core issue ??: Metal header renderer appears squeezed.
*
* @author Jeanette Winzenburg
*/
public class TableHeaderAddon extends AbstractComponentAddon {
/**
* @param name
*/
public TableHeaderAddon() {
super("JXTableHeader");
}
@Override
protected void addMetalDefaults(LookAndFeelAddons addon,
DefaultsList defaults) {
super.addMetalDefaults(addon, defaults);
String key = "TableHeader.cellBorder";
Border border = UIManager.getBorder(key);
if (border instanceof MetalBorders.TableHeaderBorder) {
border = new BorderUIResource.CompoundBorderUIResource(border,
BorderFactory.createEmptyBorder());
// PENDING JW: this is fishy ... adding to lookAndFeelDefaults is taken
UIManager.getLookAndFeelDefaults().put(key, border);
// adding to defaults is not
// defaults.add(key, border);
}
}
}
| Mindtoeye/Hoop | src/org/jdesktop/swingx/plaf/TableHeaderAddon.java | Java | lgpl-3.0 | 2,161 |
package com.iblowuptnt.tntMods.item;
import com.google.common.collect.Sets;
import com.iblowuptnt.tntMods.creativetab.CreativeTab;
import com.iblowuptnt.tntMods.reference.Material;
import com.iblowuptnt.tntMods.reference.Name;
import com.iblowuptnt.tntMods.reference.Textures;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.ItemSpade;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import java.util.Set;
public class ItemCompShovel extends ItemSpade
{
public ItemCompShovel()
{
super(Material.Tools.COMP_DIAMOND);
this.setCreativeTab(CreativeTab.TNT_TAB);
this.setUnlocalizedName(Name.Tools.COMP_SHOVEL);
this.maxStackSize = 1;
}
protected String getUnwrappedUnlocalizedName(String unlocalizedName)
{
return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1);
}
@Override
public String getUnlocalizedName()
{
return String.format("item.%s%s", Textures.MOD_ID_PREFIX, getUnwrappedUnlocalizedName(super.getUnlocalizedName()));
}
@Override
public String getUnlocalizedName(ItemStack itemStack)
{
return String.format("item.%s%s", Textures.MOD_ID_PREFIX, getUnwrappedUnlocalizedName(super.getUnlocalizedName()));
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister iconRegister)
{
itemIcon = iconRegister.registerIcon(this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf(".") + 1));
}
}
| IblowUpTnT/tntMods | src/main/java/com/iblowuptnt/tntMods/item/ItemCompShovel.java | Java | lgpl-3.0 | 1,656 |
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.rule;
import com.google.common.collect.Sets;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.rule.RulesDefinition;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import org.sonar.core.persistence.AbstractDaoTestCase;
import org.sonar.core.persistence.DbSession;
import org.sonar.core.qualityprofile.db.QualityProfileDao;
import org.sonar.core.rule.RuleDto;
import org.sonar.core.rule.RuleParamDto;
import org.sonar.core.technicaldebt.db.CharacteristicDao;
import org.sonar.server.db.DbClient;
import org.sonar.server.qualityprofile.RuleActivator;
import org.sonar.server.qualityprofile.db.ActiveRuleDao;
import org.sonar.server.rule.db.RuleDao;
import java.util.Date;
import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class RegisterRulesTest extends AbstractDaoTestCase {
static final Date DATE1 = DateUtils.parseDateTime("2014-01-01T19:10:03+0100");
static final Date DATE2 = DateUtils.parseDateTime("2014-02-01T12:10:03+0100");
static final Date DATE3 = DateUtils.parseDateTime("2014-03-01T12:10:03+0100");
RuleActivator ruleActivator = mock(RuleActivator.class);
System2 system;
DbClient dbClient;
DbSession dbSession;
@Before
public void before() {
system = mock(System2.class);
when(system.now()).thenReturn(DATE1.getTime());
RuleDao ruleDao = new RuleDao(system);
ActiveRuleDao activeRuleDao = new ActiveRuleDao(new QualityProfileDao(getMyBatis(), system), ruleDao, system);
dbClient = new DbClient(getDatabase(), getMyBatis(), ruleDao, activeRuleDao,
new QualityProfileDao(getMyBatis(), system), new CharacteristicDao(getMyBatis()));
dbSession = dbClient.openSession(false);
}
@After
public void after() throws Exception {
dbSession.close();
}
@Test
public void insert_new_rules() {
execute(new FakeRepositoryV1());
// verify db
assertThat(dbClient.ruleDao().findAll(dbSession)).hasSize(2);
RuleKey ruleKey1 = RuleKey.of("fake", "rule1");
RuleDto rule1 = dbClient.ruleDao().getNullableByKey(dbSession, ruleKey1);
assertThat(rule1.getName()).isEqualTo("One");
assertThat(rule1.getDescription()).isEqualTo("Description of One");
assertThat(rule1.getSeverityString()).isEqualTo(Severity.BLOCKER);
assertThat(rule1.getTags()).isEmpty();
assertThat(rule1.getSystemTags()).containsOnly("tag1", "tag2", "tag3");
assertThat(rule1.getConfigKey()).isEqualTo("config1");
assertThat(rule1.getStatus()).isEqualTo(RuleStatus.BETA);
assertThat(rule1.getCreatedAt()).isEqualTo(DATE1);
assertThat(rule1.getUpdatedAt()).isEqualTo(DATE1);
// TODO check characteristic and remediation function
List<RuleParamDto> params = dbClient.ruleDao().findRuleParamsByRuleKey(dbSession, ruleKey1);
assertThat(params).hasSize(2);
RuleParamDto param = getParam(params, "param1");
assertThat(param.getDescription()).isEqualTo("parameter one");
assertThat(param.getDefaultValue()).isEqualTo("default1");
}
@Test
public void do_not_update_rules_when_no_changes() {
execute(new FakeRepositoryV1());
assertThat(dbClient.ruleDao().findAll(dbSession)).hasSize(2);
when(system.now()).thenReturn(DATE2.getTime());
execute(new FakeRepositoryV1());
RuleKey ruleKey1 = RuleKey.of("fake", "rule1");
RuleDto rule1 = dbClient.ruleDao().getNullableByKey(dbSession, ruleKey1);
assertThat(rule1.getCreatedAt()).isEqualTo(DATE1);
assertThat(rule1.getUpdatedAt()).isEqualTo(DATE1);
}
@Test
public void update_and_remove_rules_on_changes() {
execute(new FakeRepositoryV1());
assertThat(dbClient.ruleDao().findAll(dbSession)).hasSize(2);
// user adds tags and sets markdown note
RuleKey ruleKey1 = RuleKey.of("fake", "rule1");
RuleDto rule1 = dbClient.ruleDao().getNullableByKey(dbSession, ruleKey1);
rule1.setTags(Sets.newHashSet("usertag1", "usertag2"));
rule1.setNoteData("user *note*");
rule1.setNoteUserLogin("marius");
dbClient.ruleDao().update(dbSession, rule1);
dbSession.commit();
when(system.now()).thenReturn(DATE2.getTime());
execute(new FakeRepositoryV2());
// rule1 has been updated
rule1 = dbClient.ruleDao().getNullableByKey(dbSession, ruleKey1);
assertThat(rule1.getName()).isEqualTo("One v2");
assertThat(rule1.getDescription()).isEqualTo("Description of One v2");
assertThat(rule1.getSeverityString()).isEqualTo(Severity.INFO);
assertThat(rule1.getTags()).containsOnly("usertag1", "usertag2");
assertThat(rule1.getSystemTags()).containsOnly("tag1", "tag4");
assertThat(rule1.getConfigKey()).isEqualTo("config1 v2");
assertThat(rule1.getNoteData()).isEqualTo("user *note*");
assertThat(rule1.getNoteUserLogin()).isEqualTo("marius");
assertThat(rule1.getStatus()).isEqualTo(RuleStatus.READY);
assertThat(rule1.getCreatedAt()).isEqualTo(DATE1);
assertThat(rule1.getUpdatedAt()).isEqualTo(DATE2);
// TODO check characteristic and remediation function
List<RuleParamDto> params = dbClient.ruleDao().findRuleParamsByRuleKey(dbSession, ruleKey1);
assertThat(params).hasSize(2);
RuleParamDto param = getParam(params, "param1");
assertThat(param.getDescription()).isEqualTo("parameter one v2");
assertThat(param.getDefaultValue()).isEqualTo("default1 v2");
// rule2 has been removed -> status set to REMOVED but db row is not deleted
RuleDto rule2 = dbClient.ruleDao().getNullableByKey(dbSession, RuleKey.of("fake", "rule2"));
assertThat(rule2.getStatus()).isEqualTo(RuleStatus.REMOVED);
assertThat(rule2.getUpdatedAt()).isEqualTo(DATE2);
// rule3 has been created
RuleDto rule3 = dbClient.ruleDao().getNullableByKey(dbSession, RuleKey.of("fake", "rule3"));
assertThat(rule3).isNotNull();
assertThat(rule3.getStatus()).isEqualTo(RuleStatus.READY);
}
@Test
public void do_not_update_already_removed_rules() {
execute(new FakeRepositoryV1());
assertThat(dbClient.ruleDao().findAll(dbSession)).hasSize(2);
RuleDto rule2 = dbClient.ruleDao().getByKey(dbSession, RuleKey.of("fake", "rule2"));
assertThat(rule2.getStatus()).isEqualTo(RuleStatus.READY);
when(system.now()).thenReturn(DATE2.getTime());
execute(new FakeRepositoryV2());
// On MySQL, need to update a rule otherwise rule2 will be seen as READY, but why ???
dbClient.ruleDao().update(dbSession, dbClient.ruleDao().getByKey(dbSession, RuleKey.of("fake", "rule1")));
dbSession.commit();
// rule2 is removed
rule2 = dbClient.ruleDao().getNullableByKey(dbSession, RuleKey.of("fake", "rule2"));
assertThat(rule2.getStatus()).isEqualTo(RuleStatus.REMOVED);
when(system.now()).thenReturn(DATE3.getTime());
execute(new FakeRepositoryV2());
dbSession.commit();
// -> rule2 is still removed, but not update at DATE3
rule2 = dbClient.ruleDao().getNullableByKey(dbSession, RuleKey.of("fake", "rule2"));
assertThat(rule2.getStatus()).isEqualTo(RuleStatus.REMOVED);
assertThat(rule2.getUpdatedAt()).isEqualTo(DATE2);
}
@Test
public void mass_insert() {
execute(new BigRepository());
assertThat(dbClient.ruleDao().findAll(dbSession)).hasSize(BigRepository.SIZE);
assertThat(dbClient.ruleDao().findAllRuleParams(dbSession)).hasSize(BigRepository.SIZE * 20);
}
@Test
public void manage_repository_extensions() {
execute(new FindbugsRepository(), new FbContribRepository());
List<RuleDto> rules = dbClient.ruleDao().findAll(dbSession);
assertThat(rules).hasSize(2);
for (RuleDto rule : rules) {
assertThat(rule.getRepositoryKey()).isEqualTo("findbugs");
}
}
private void execute(RulesDefinition... defs) {
RuleDefinitionsLoader loader = new RuleDefinitionsLoader(mock(RuleRepositories.class), defs);
Languages languages = mock(Languages.class);
when(languages.get("java")).thenReturn(mock(Language.class));
RegisterRules task = new RegisterRules(loader, ruleActivator, dbClient, languages, system);
task.start();
}
private RuleParamDto getParam(List<RuleParamDto> params, String key) {
for (RuleParamDto param : params) {
if (param.getName().equals(key)) {
return param;
}
}
return null;
}
static class FakeRepositoryV1 implements RulesDefinition {
@Override
public void define(Context context) {
NewRepository repo = context.createRepository("fake", "java");
NewRule rule1 = repo.createRule("rule1")
.setName("One")
.setHtmlDescription("Description of One")
.setSeverity(Severity.BLOCKER)
.setInternalKey("config1")
.setTags("tag1", "tag2", "tag3")
.setStatus(RuleStatus.BETA)
.setDebtSubCharacteristic("MEMORY_EFFICIENCY")
.setEffortToFixDescription("squid.S115.effortToFix");
rule1.setDebtRemediationFunction(rule1.debtRemediationFunctions().linearWithOffset("5d", "10h"));
rule1.createParam("param1").setDescription("parameter one").setDefaultValue("default1");
rule1.createParam("param2").setDescription("parameter two").setDefaultValue("default2");
repo.createRule("rule2")
.setName("Two")
.setHtmlDescription("Minimal rule");
repo.done();
}
}
/**
* FakeRepositoryV1 with some changes
*/
static class FakeRepositoryV2 implements RulesDefinition {
@Override
public void define(Context context) {
NewRepository repo = context.createRepository("fake", "java");
// almost all the attributes of rule1 are changed
NewRule rule1 = repo.createRule("rule1")
.setName("One v2")
.setHtmlDescription("Description of One v2")
.setSeverity(Severity.INFO)
.setInternalKey("config1 v2")
// tag2 and tag3 removed, tag4 added
.setTags("tag1", "tag4")
.setStatus(RuleStatus.READY)
.setDebtSubCharacteristic("MEMORY_EFFICIENCY")
.setEffortToFixDescription("squid.S115.effortToFix.v2");
rule1.setDebtRemediationFunction(rule1.debtRemediationFunctions().linearWithOffset("6d", "2h"));
rule1.createParam("param1").setDescription("parameter one v2").setDefaultValue("default1 v2");
rule1.createParam("param2").setDescription("parameter two v2").setDefaultValue("default2 v2");
// rule2 is dropped, rule3 is new
repo.createRule("rule3")
.setName("Three")
.setHtmlDescription("Rule Three");
repo.done();
}
}
static class BigRepository implements RulesDefinition {
static final int SIZE = 500;
@Override
public void define(Context context) {
NewRepository repo = context.createRepository("big", "java");
for (int i = 0; i < SIZE; i++) {
NewRule rule = repo.createRule("rule" + i)
.setName("name of " + i)
.setHtmlDescription("description of " + i);
for (int j = 0; j < 20; j++) {
rule.createParam("param" + j);
}
}
repo.done();
}
}
static class FindbugsRepository implements RulesDefinition {
@Override
public void define(Context context) {
NewRepository repo = context.createRepository("findbugs", "java");
repo.createRule("rule1")
.setName("Rule One")
.setHtmlDescription("Description of Rule One");
repo.done();
}
}
static class FbContribRepository implements RulesDefinition {
@Override
public void define(Context context) {
NewExtendedRepository repo = context.extendRepository("findbugs", "java");
repo.createRule("rule2")
.setName("Rule Two")
.setHtmlDescription("Description of Rule Two");
repo.done();
}
}
}
| teryk/sonarqube | server/sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesTest.java | Java | lgpl-3.0 | 12,879 |
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QtAws is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "modifyvolumeresponse.h"
#include "modifyvolumeresponse_p.h"
#include <QDebug>
#include <QNetworkReply>
#include <QXmlStreamReader>
namespace QtAws {
namespace EC2 {
/*!
* \class QtAws::EC2::ModifyVolumeResponse
* \brief The ModifyVolumeResponse class provides an interace for EC2 ModifyVolume responses.
*
* \inmodule QtAwsEC2
*
* <fullname>Amazon Elastic Compute Cloud</fullname>
*
* Amazon Elastic Compute Cloud (Amazon EC2) provides secure and resizable computing capacity in the AWS Cloud. Using
* Amazon EC2 eliminates the need to invest in hardware up front, so you can develop and deploy applications faster. Amazon
* Virtual Private Cloud (Amazon VPC) enables you to provision a logically isolated section of the AWS Cloud where you can
* launch AWS resources in a virtual network that you've defined. Amazon Elastic Block Store (Amazon EBS) provides block
* level storage volumes for use with EC2 instances. EBS volumes are highly available and reliable storage volumes that can
* be attached to any running instance and used like a hard
*
* drive>
*
* To learn more, see the following
*
* resources> <ul> <li>
*
* Amazon EC2: <a href="http://aws.amazon.com/ec2">AmazonEC2 product page</a>, <a
* href="http://aws.amazon.com/documentation/ec2">Amazon EC2 documentation</a>
*
* </p </li> <li>
*
* Amazon EBS: <a href="http://aws.amazon.com/ebs">Amazon EBS product page</a>, <a
* href="http://aws.amazon.com/documentation/ebs">Amazon EBS documentation</a>
*
* </p </li> <li>
*
* Amazon VPC: <a href="http://aws.amazon.com/vpc">Amazon VPC product page</a>, <a
* href="http://aws.amazon.com/documentation/vpc">Amazon VPC documentation</a>
*
* </p </li> <li>
*
* AWS VPN: <a href="http://aws.amazon.com/vpn">AWS VPN product page</a>, <a
* href="http://aws.amazon.com/documentation/vpn">AWS VPN documentation</a>
*
* \sa Ec2Client::modifyVolume
*/
/*!
* Constructs a ModifyVolumeResponse object for \a reply to \a request, with parent \a parent.
*/
ModifyVolumeResponse::ModifyVolumeResponse(
const ModifyVolumeRequest &request,
QNetworkReply * const reply,
QObject * const parent)
: Ec2Response(new ModifyVolumeResponsePrivate(this), parent)
{
setRequest(new ModifyVolumeRequest(request));
setReply(reply);
}
/*!
* \reimp
*/
const ModifyVolumeRequest * ModifyVolumeResponse::request() const
{
Q_D(const ModifyVolumeResponse);
return static_cast<const ModifyVolumeRequest *>(d->request);
}
/*!
* \reimp
* Parses a successful EC2 ModifyVolume \a response.
*/
void ModifyVolumeResponse::parseSuccess(QIODevice &response)
{
//Q_D(ModifyVolumeResponse);
QXmlStreamReader xml(&response);
/// @todo
}
/*!
* \class QtAws::EC2::ModifyVolumeResponsePrivate
* \brief The ModifyVolumeResponsePrivate class provides private implementation for ModifyVolumeResponse.
* \internal
*
* \inmodule QtAwsEC2
*/
/*!
* Constructs a ModifyVolumeResponsePrivate object with public implementation \a q.
*/
ModifyVolumeResponsePrivate::ModifyVolumeResponsePrivate(
ModifyVolumeResponse * const q) : Ec2ResponsePrivate(q)
{
}
/*!
* Parses a EC2 ModifyVolume response element from \a xml.
*/
void ModifyVolumeResponsePrivate::parseModifyVolumeResponse(QXmlStreamReader &xml)
{
Q_ASSERT(xml.name() == QLatin1String("ModifyVolumeResponse"));
Q_UNUSED(xml) ///< @todo
}
} // namespace EC2
} // namespace QtAws
| pcolby/libqtaws | src/ec2/modifyvolumeresponse.cpp | C++ | lgpl-3.0 | 4,191 |
// -*- mode: c++; tab-width: 4; indent-tabs-mode: t; eval: (progn (c-set-style "stroustrup") (c-set-offset 'innamespace 0)); -*-
// vi:set ts=4 sts=4 sw=4 noet :
//
// Copyright 2010, 2012 wkhtmltopdf authors
//
// This file is part of wkhtmltopdf.
//
// wkhtmltopdf is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// wkhtmltopdf is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with wkhtmltopdf. If not, see <http://www.gnu.org/licenses/>.
#ifndef __LOADSETTINGS_HH__
#define __LOADSETTINGS_HH__
#ifdef __WKHTMLTOX_UNDEF_QT_DLL__
#ifdef QT_DLL
#undef QT_DLL
#endif
#endif
#include <QNetworkProxy>
#include <QString>
#include <wkhtmltox/dllbegin.inc>
namespace wkhtmltopdf {
namespace settings {
/*! \brief Settings considering proxy */
struct DLL_PUBLIC Proxy {
Proxy();
//! Type of proxy to use
QNetworkProxy::ProxyType type;
//! The port of the proxy to use
int port;
//! The host name of the proxy to use or NULL
QString host;
//! Username for the said proxy or NULL
QString user;
//! Password for the said proxy or NULL
QString password;
};
struct DLL_PUBLIC PostItem {
QString name;
QString value;
bool file;
};
struct DLL_PUBLIC LoadGlobal {
LoadGlobal();
//! Path of the cookie jar file
QString cookieJar;
};
struct DLL_PUBLIC LoadPage {
LoadPage();
enum LoadErrorHandling {
abort,
skip,
ignore
};
//! Username used for http auth login
QString username;
//! Password used for http auth login
QString password;
//! How many milliseconds should we wait for a Javascript redirect
int jsdelay;
//! What window.status value should we wait for
QString windowStatus;
//! Dump rendered HTML to file
QString dumpHtml;
//! What zoom factor should we apply when printing
// TODO MOVE
float zoomFactor;
//! Map of custom header variables
QList< QPair<QString, QString> > customHeaders;
//! Set if the custom header should be repeated for each resource request
bool repeatCustomHeaders;
//! Map of cookies
QList< QPair<QString, QString> > cookies;
QList< PostItem > post;
//! Block access to local files for the given page
bool blockLocalFileAccess;
//! If access to local files is not allowed in general, allow it for these files
QList< QString > allowed;
//! Stop Javascript from running too long
bool stopSlowScripts;
//! Output Javascript debug messages
bool debugJavascript;
//! What should we do about load errors
LoadErrorHandling loadErrorHandling;
LoadErrorHandling mediaLoadErrorHandling;
//! Proxy related settings
Proxy proxy;
//! Additional javascript to run on a page once it has loaded
QList< QString > runScript;
QString checkboxSvg;
QString checkboxCheckedSvg;
QString radiobuttonSvg;
QString radiobuttonCheckedSvg;
QString cacheDir;
static QList<QString> mediaFilesExtensions;
};
DLL_PUBLIC LoadPage::LoadErrorHandling strToLoadErrorHandling(const char * s, bool * ok=0);
DLL_PUBLIC QString loadErrorHandlingToStr(LoadPage::LoadErrorHandling leh);
DLL_PUBLIC Proxy strToProxy(const char * s, bool * ok=0);
DLL_PUBLIC QString proxyToStr(const Proxy & proxy);
}
}
#include <wkhtmltox/dllend.inc>
#endif //__LOADSETTINGS_HH__
| mkdgs/wkhtmltopdf | src/lib/loadsettings.hh | C++ | lgpl-3.0 | 3,602 |
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.cismet.cismap.commons.internaldb;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
/**
* DOCUMENT ME!
*
* @author therter
* @version $Revision$, $Date$
*/
public class DBTransferable implements Transferable {
//~ Instance fields --------------------------------------------------------
private DataFlavor TREEPATH_FLAVOR = new DataFlavor(
DataFlavor.javaJVMLocalObjectMimeType,
"SelectionAndCapabilities"); // NOI18N
private DBTableInformation[] transferObjects;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new DBTransferable object.
*
* @param transferObjects DOCUMENT ME!
*/
public DBTransferable(final DBTableInformation[] transferObjects) {
this.transferObjects = transferObjects;
}
//~ Methods ----------------------------------------------------------------
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { TREEPATH_FLAVOR };
}
@Override
public boolean isDataFlavorSupported(final DataFlavor flavor) {
return flavor.equals(TREEPATH_FLAVOR);
}
@Override
public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor)) {
return transferObjects;
}
return null;
}
}
| cismet/cismap-commons | src/main/java/de/cismet/cismap/commons/internaldb/DBTransferable.java | Java | lgpl-3.0 | 1,839 |
/* Copyright (c) 2014 James King [metapyziks@gmail.com]
*
* This file is part of FacePuncher.
*
* FacePuncher is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* FacePuncher is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with FacePuncher. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using FacePuncher.Graphics;
namespace FacePuncher.Entities
{
/// <summary>
/// Component for entities that should be drawn using one specific
/// symbol, foreground color and background color.
/// </summary>
class StaticDrawable : Drawable
{
private EntityAppearance _appearance;
/// <summary>
/// Gets or sets the layer the owning entity should be drawn on.
/// </summary>
[ScriptDefinable]
public DrawableLayer Layer { get; set; }
/// <summary>
/// Gets or sets the character representing this entity.
/// </summary>
[ScriptDefinable]
public char Symbol
{
get { return _appearance[0].Symbol; }
set
{
_appearance[0] = new EntityAppearance.Frame(value, ForeColor, BackColor, 1);
}
}
/// <summary>
/// Gets or sets the foreground color of this entity.
/// </summary>
[ScriptDefinable]
public ConsoleColor ForeColor
{
get { return _appearance[0].ForeColor; }
set
{
_appearance[0] = new EntityAppearance.Frame(Symbol, value, BackColor, 1);
}
}
/// <summary>
/// Gets or sets the background color of this entity.
/// </summary>
[ScriptDefinable]
public ConsoleColor BackColor
{
get { return _appearance[0].BackColor; }
set
{
_appearance[0] = new EntityAppearance.Frame(Symbol, ForeColor, value, 1);
}
}
/// <summary>
/// Constructs a new StaticDrawable component.
/// </summary>
public StaticDrawable()
{
Layer = DrawableLayer.Items;
_appearance = new EntityAppearance { '?' };
}
/// <summary>
/// Gets the layer the owning entity should be drawn on.
/// </summary>
public override DrawableLayer GetLayer()
{
return Layer;
}
/// <summary>
/// Gets appearance information for the entity.
/// </summary>
/// <returns>Appearance information for the entity.</returns>
public override EntityAppearance GetAppearance()
{
return _appearance;
}
}
}
| Metapyziks/FacePuncher | FacePuncher.Server/Entities/StaticDrawable.cs | C# | lgpl-3.0 | 3,160 |
#include "dbmanager.h"
//=============================================================================================================================
//=================================================CONSTUCTOR==================================================================
//=============================================================================================================================
DbManager::DbManager(const QString& db_name)
/*Provided the database path db_name, it constructs the database and creates the file if it doesnt exist according
to these standards :
- Table game containing games
- Table platform containing platforms
- Table emulator containing emulators
*/
{
QSqlDatabase db = QSqlDatabase::database();
if(db.connectionName()=="")
{
initDb(db_name);
}
else
{
m_db = db;
qDebug(qUtf8Printable("Db:nice"));
}
}
void DbManager::initDb(const QString& db_name)
{
m_db = QSqlDatabase::addDatabase("QSQLITE");
m_db.setDatabaseName(db_name);
m_db.open();
m_db_name = db_name;
QSqlQuery query1;
query1.exec("create table if not exists game ("
"id integer primary key, "
"game_title varchar(1000), "
"platform varchar(1000), "
"emulator_name varchar(1000), "
"path varchar(1000), "
"release_date varchar(100), "
"image BLOB, "
"game_info text, "
"time_played integer, "
"last_played text, "
"game_favorited integer, "
"state text, "
"game_steam integer,"
"steamid integer,"
"opened_counter integer)");
QSqlQuery query2;
query2.exec("create table if not exists platform ("
"platform varchar(1000) primary key, "
"emulator_name varchar(1000), "
"image BLOB, "
"platform_info text, "
"time_played integer, "
"last_played text,"
"game_counter integer,"
"opened_counter integer)");
QSqlQuery query3;
query3.exec("create table if not exists emulator ("
"emulator_name varchar(1000) primary key, "
"image BLOB, "
"path varchar(1000), "
"emulator_info text, "
"time_played integer, "
"last_played text,"
"opened_counter integer)");
QSqlQuery query4;
query4.exec("create table if not exists extsoft ("
"software_name varchar(1000) primary key,"
"image BLOB,"
"path varchar(1000),"
"supported_extsoft integer,"
"multi_instance integer,"
"opened_counter integer,"
"games_off_list text,"
"games_whitelist text,"
"platforms_on_list text)");
}
void DbManager::close()
{
m_db.close();
}
void DbManager::setDatabaseName(const QString& path)
{
m_db.setDatabaseName(path);
}
bool DbManager::checkAddGamePossible(int id)
{
bool success = false;
QSqlQuery query;
query.prepare("SELECT EXISTS(SELECT 1 FROM game WHERE id=:id LIMIT 1);");
query.bindValue(":id",id);
if(query.exec())
{
while (query.next())
{
success = query.value(0).toBool();
success = !success;
}
}
else
{
qDebug() << "checkAddGamePossible error: " << query.lastError().text();
}
return success;
}
bool DbManager::checkAddExternalSoftwarePossible(QString externalSoftwareName)
{
bool success = false;
QSqlQuery query;
query.prepare("SELECT EXISTS(SELECT 1 FROM extsoft WHERE software_name=:software_name LIMIT 1);");
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
while (query.next())
{
success = query.value(0).toBool();
success = !success;
}
}
else
{
qDebug() << "checkAddExternalSoftwareEntry error: " << query.lastError().text();
}
return success;
}
//=============================================================================================================================
//=================================================GAME TABLE OPERATIONS=======================================================
//=============================================================================================================================
bool DbManager::addGameEntry(int id, QString gameTitle, QString platform, int steamid)
/*Provided a game, this function adds it to the game table.
*/
{
bool success = false;
QSqlQuery query;
query.prepare("INSERT INTO game (id,game_title,platform,time_played,steamid,opened_counter,state,last_played) VALUES(:id,:game_title,:platform,:time_played,:steamid,:opened_counter,:state,:last_played)");
query.bindValue(":id",id);
query.bindValue(":game_title",gameTitle);
query.bindValue(":platform",platform);
query.bindValue(":time_played",0);
query.bindValue(":steamid",steamid);
query.bindValue(":opened_counter",0);
query.bindValue(":state","");
query.bindValue(":last_played","");
if(query.exec())
{
success = true;
}
else
{
qDebug() << "addGameEntry error: " << query.lastError().text();
}
return success;
}
bool DbManager::deleteGameEntry(int id)
/*Provided a game id, this function removes it from the game table(and therefore from the database).
*/
{
bool success = false;
QSqlQuery query;
query.prepare("DELETE FROM game WHERE id = :id;");
query.bindValue(":id",id);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "deleteGameEntry error: " << query.lastError().text();
}
return success;
}
//=============================================================================================================================
//=================================================GET OPERATIONS==============================================================
//=============================================================================================================================
QList<int> DbManager::getAllGames()
{
QList<int> AllGames;
QSqlQuery query;
query.prepare("SELECT id FROM game;");
if(query.exec())
{
while (query.next())
{
AllGames.append(query.value(0).toInt());
}
}
else
{
qDebug() << "getAllGames error: " << query.lastError().text();
}
return AllGames;
}
int DbManager::getGameId(QString gameTitle, QString platform)
/*Provided a game_title and platform, this function returns its id.
*/
{
int id(-1);
QSqlQuery query;
query.prepare("SELECT id FROM game WHERE game_title=:game_title AND platform=:platform;");
query.bindValue(":game_title",gameTitle);
query.bindValue(":platform",platform);
if(query.exec())
{
while (query.next())
{
id = query.value(0).toInt();
qDebug(qUtf8Printable(QString::number(id)));
}
}
else
{
qDebug() << "getGameId error: " << query.lastError().text();
}
return id;
}
int DbManager::getGameSteamId(QString gameTitle, QString platform)
{
/*Provided a game_title and platform, this function returns its id.
*/
int steamid(-1);
QSqlQuery query;
query.prepare("SELECT steamid FROM game WHERE game_title=:game_title AND platform=:platform;");
query.bindValue(":game_title",gameTitle);
query.bindValue(":platform",platform);
if(query.exec())
{
while (query.next())
{
steamid = query.value(0).toInt();
qDebug(qUtf8Printable(QString::number(steamid)));
}
}
else
{
qDebug() << "getGameSteamId error: " << query.lastError().text();
}
return steamid;
}
QString DbManager::getGameTitle(int id)
/*Provided a game id, this function returns its game_title.
*/
{
QString gameTitle("");
QSqlQuery query;
query.prepare("SELECT game_title FROM game WHERE id=:id;");
query.bindValue(":id",id);
if(query.exec())
{
while (query.next())
{
gameTitle = query.value(0).toString();
qDebug(qUtf8Printable(gameTitle));
}
}
else
{
qDebug() << "getGameTitle error: " << query.lastError().text();
}
return gameTitle;
}
QString DbManager::getGamePlatform(int id)
/*Provided a game id, this function returns its platform.
*/
{
QString platform("");
QSqlQuery query;
query.prepare("SELECT platform FROM game WHERE id=:id;");
query.bindValue(":id",id);
if(query.exec())
{
while (query.next())
{
platform = query.value(0).toString();
qDebug(qUtf8Printable(platform));
}
}
else
{
qDebug() << "getGamePlatform error: " << query.lastError().text();
}
return platform;
}
QString DbManager::getGamePath(int id)
/*Provided a game id, this function returns its path.
*/
{
QString path("");
QSqlQuery query;
query.prepare("SELECT path FROM game WHERE id=:id;");
query.bindValue(":id",id);
if(query.exec())
{
while (query.next())
{
path = query.value(0).toString();
qDebug(qUtf8Printable(path));
}
}
else
{
qDebug() << "getGamePath error: " << query.lastError().text();
}
return path;
}
QByteArray DbManager::getGameImage(int id)
/*Provided a game id, this function returns its image byte array.
*/
{
QByteArray gameImage;
QSqlQuery query;
query.prepare("SELECT image FROM game WHERE id=:id;");
query.bindValue(":id",id);
if(query.exec())
{
while (query.next())
{
gameImage = query.value(0).toByteArray();
}
}
else
{
qDebug() << "getGameImage error: " << query.lastError().text();
}
return gameImage;
}
QString DbManager::getGameInfo(int id)
/*Provided a game id, this function returns its game_info.
*/
{
QString game_info("");
QSqlQuery query;
query.prepare("SELECT game_info FROM game WHERE id=:id;");
query.bindValue(":id",id);
if(query.exec())
{
while (query.next())
{
game_info = query.value(0).toString();
qDebug(qUtf8Printable(game_info));
}
}
else
{
qDebug() << "getGameInfo error: " << query.lastError().text();
}
return game_info;
}
QString DbManager::getGameEmulator(int id)
/*Provided a game id, this function returns its emulator_name.
*/
{
QString emulatorName("");
QSqlQuery query;
query.prepare("SELECT emulator_name FROM game WHERE id=:id;");
query.bindValue(":id",id);
if(query.exec())
{
while (query.next())
{
emulatorName = query.value(0).toString();
qDebug(qUtf8Printable(emulatorName));
}
}
else
{
qDebug() << "getGameEmulator error: " << query.lastError().text();
}
return emulatorName;
}
QString DbManager::getGameReleaseDate(int id)
/*Provided a game id, this function returns its release_date.
*/
{
QString releaseDate("");
QSqlQuery query;
query.prepare("SELECT release_date FROM game WHERE id=:id;");
query.bindValue(":id",id);
if(query.exec())
{
while (query.next())
{
releaseDate = query.value(0).toString();
qDebug(qUtf8Printable(releaseDate));
}
}
else
{
qDebug() << "getGameReleaseDate error: " << query.lastError().text();
}
return releaseDate;
}
int DbManager::getGameTimePlayed(int id)
/*Provided a game id, this function returns its time_played.
*/
{
int time = -1;
QSqlQuery query;
query.prepare("SELECT time_played FROM game WHERE id=:id;");
query.bindValue(":id",id);
if(query.exec())
{
while (query.next())
{
time = query.value(0).toInt();
qDebug(qUtf8Printable("time played on database : "+QString::number(time)));
}
}
else
{
qDebug() << "getGameTimePlayed error: " << query.lastError().text();
}
return time;
}
QString DbManager::getGameLastPlayed(int id)
/*Provided a game id, this function returns its last_played.
*/
{
QString lastPlayed("Never Played");
QSqlQuery query;
query.prepare("SELECT last_played FROM game WHERE id=:id;");
query.bindValue(":id",id);
if(query.exec())
{
while (query.next())
{
lastPlayed = query.value(0).toString();
qDebug(qUtf8Printable(lastPlayed));
}
}
else
{
qDebug() << "getGameLastPlayed error: " << query.lastError().text();
}
qDebug(qUtf8Printable("debug20"));
return lastPlayed;
}
int DbManager::getGameOpenedCounter(int id)
{
int openedCounter=-1;
QSqlQuery query;
query.prepare("SELECT opened_counter FROM game WHERE id=:id;");
query.bindValue(":id",id);
if(query.exec())
{
while (query.next())
{
openedCounter = query.value(0).toInt();
qDebug(qUtf8Printable(QString::number(openedCounter)));
}
}
else
{
qDebug() << "getGameOpenedCounter error: " << query.lastError().text();
}
return openedCounter;
}
QString DbManager::getGameState(int id)
{
QString state("");
QSqlQuery query;
query.prepare("SELECT state FROM game WHERE id=:id;");
query.bindValue(":id",id);
if(query.exec())
{
while (query.next())
{
state = query.value(0).toString();
}
}
else
{
qDebug() << "getGameState error: " << query.lastError().text();
}
return state;
}
QDateTime DbManager::stringToDate(QString dateString)
{
qDebug(qUtf8Printable("debug21"));
if (dateString==""||dateString=="Never Played")
{
return QDateTime();
}
qDebug(qUtf8Printable(dateString));
QStringList yyyymmddPLUShhmmss = dateString.split(" ");
qDebug(qUtf8Printable("debug22"));
QString yyyymmddstring = yyyymmddPLUShhmmss.at(0);
QString hhmmssstring = yyyymmddPLUShhmmss.at(1);
qDebug(qUtf8Printable("debug23"));
QStringList yyyymmdd = yyyymmddstring.split("-");
QStringList hhmmss = hhmmssstring.split(":");
qDebug(qUtf8Printable("debug24"));
QDateTime date;
QString year = yyyymmdd.at(0);
qDebug(qUtf8Printable("debug30"));
QString month = yyyymmdd.at(1);
qDebug(qUtf8Printable("debug25"));
QString days = yyyymmdd.at(2);
qDebug(qUtf8Printable("debug26"));
QString hours = hhmmss.at(0);
QString minutes = hhmmss.at(1);
qDebug(qUtf8Printable("debug27"));
QString seconds = hhmmss.at(2);
qDebug(qUtf8Printable("debug28"));
date.setDate(QDate(year.toInt(),month.toInt(),days.toInt()));
date.setTime(QTime(hours.toInt(),minutes.toInt(),seconds.toInt()));
return date;
}
//=============================================================================================================================
//=================================================SET OPERATIONS==============================================================
//=============================================================================================================================
bool DbManager::setGameImage(int id, QByteArray imageData)
//Provided a game id and image data, this function sets the game image.
{
bool success = false;
QSqlQuery query;
query.prepare("UPDATE game SET image=:image WHERE id=:id;");
query.bindValue(":image",imageData);
query.bindValue(":id",id);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setGameImage error: " << query.lastError().text();
}
return success;
}
bool DbManager::setGameInfo(int id, QString gameInfo)
//Provided a game id and game_info, this function sets the game_info.
{
bool success = false;
QSqlQuery query;
query.prepare("UPDATE game SET game_info=:game_info WHERE id=:id;");
query.bindValue(":game_info",gameInfo);
query.bindValue(":id",id);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setGameInfo error: " << query.lastError().text();
}
return success;
}
bool DbManager::setGamePath(int id, QString gamePath)
//Provided a game id and game_path, this function sets the game_path.
{
bool success = false;
QSqlQuery query;
query.prepare("UPDATE game SET path=:path WHERE id=:id;");
query.bindValue(":path",gamePath);
query.bindValue(":id",id);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setGamePath error: " << query.lastError().text();
}
return success;
}
bool DbManager::setGameTimePlayed(int id, int timePlayed)
//Provided a game id and timePlayed, this function sets the time_played.
{
bool success = false;
QSqlQuery query;
query.prepare("UPDATE game SET time_played=:time_played WHERE id=:id;");
query.bindValue(":time_played",timePlayed);
query.bindValue(":id",id);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setGameTimePlayed error: " << query.lastError().text();
}
return success;
}
bool DbManager::updateGameLastPlayed(int id)
{
bool success = false;
QString date("");
QSqlQuery query1,query2;
query1.prepare("SELECT DATETIME('now','localtime');");
query2.prepare("UPDATE game SET last_played=:last_played WHERE id=:id;");
if(query1.exec())
{
while(query1.next())
{
date = query1.value(0).toString();
}
}
else
{
qDebug() << "updateGameLastPlayed error : " << query1.lastError().text();
return success;
}
if (date == "")
{
return success;
}
query2.bindValue(":last_played",date);
query2.bindValue(":id",id);
if(query2.exec())
{
success = true;
}
else
{
qDebug() << "updateGameLastPlayed error : " << query2.lastError().text();
}
return success;
}
bool DbManager::setGameState(int id, QString state)
{
bool success = false;
QSqlQuery query;
query.prepare("UPDATE game SET state=:state WHERE id=:id;");
query.bindValue(":state",state);
query.bindValue(":id",id);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setGameState error: " << query.lastError().text();
}
return success;
}
bool DbManager::setGameOpenedCounter(int id, int openedCounter)
//Provided a game id and timePlayed, this function sets the time_played.
{
bool success = false;
QSqlQuery query;
query.prepare("UPDATE game SET opened_counter=:opened_counter WHERE id=:id;");
query.bindValue(":opened_counter",openedCounter);
query.bindValue(":id",id);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setGameOpenedCounter error: " << query.lastError().text();
}
return success;
}
//=============================================================================================================================
//=================================================PLATFORM TABLE OPERATIONS===================================================
//=============================================================================================================================
QString DbManager::PlatformToSupportedEmulator(QString platform)
{
if (platform=="Nintendo Entertainment System (NES)")
{
return "nestopia";
}
else if (platform=="Super Nintendo (SNES)")
{
return "snes9x";
}
else if (platform=="Nintendo 64")
{
return "Project64";
}
else if (platform=="Nintendo GameCube"||platform=="Nintendo Wii")
{
return "Dolphin";
}
else if (platform=="Nintendo Wii U")
{
return "Cemu";
}
else if (platform=="Nintendo Game Boy"||platform=="Nintendo Game Boy Color"||platform =="Nintendo Game Boy Advance")
{
return "VisualBoyAdvance";
}
else if (platform=="Nintendo DS")
{
return "DeSmuME";
}
else if (platform=="Nintendo 3DS")
{
return "citra";
}
else if (platform=="Sony Playstation")
{
return "ePSXe";
}
else if (platform=="Sony Playstation 2")
{
return "pcsx2";
}
else if (platform=="Sony Playstation 3")
{
return "rpcs3";
}
else if (platform=="Sony Playstation Portable")
{
return "PPSSPP";
}
else if (platform=="PC")
{
return "PC";
}
return platform;
}
QStringList DbManager::SupportedEmulatorToPlatforms(QString emulatorName)
{
QStringList platforms;
if (emulatorName=="nestopia")
{
platforms.append("Nintendo Entertainment System (NES)");
}
else if (emulatorName=="snes9x")
{
platforms.append("Super Nintendo (SNES)");
}
else if (emulatorName=="Project64")
{
platforms.append("Nintendo 64");
}
else if (emulatorName=="Dolphin")
{
platforms.append("Nintendo GameCube");
platforms.append("Nintendo Wii");
}
else if (emulatorName=="Cemu")
{
platforms.append("Nintendo Wii U");
}
else if (emulatorName=="VisualBoyAdvance")
{
platforms.append("Nintendo Game Boy");
platforms.append("Nintendo Game Boy Color");
platforms.append("Nintendo Game Boy Advance");
}
else if (emulatorName=="DeSmuME")
{
platforms.append("Nintendo DS");
}
else if (emulatorName=="citra")
{
platforms.append("Nintendo 3DS");
}
else if (emulatorName=="ePSXe")
{
platforms.append("Sony Playstation");
}
else if (emulatorName=="pcsx2")
{
platforms.append("Sony Playstation 2");
}
else if (emulatorName=="rpcs3")
{
platforms.append("Sony Playstation 3");
}
else if (emulatorName=="PPSSPP")
{
platforms.append("Sony Playstation Portable");
}
return platforms;
}
bool DbManager::addPlatformEntry(QString platform)
/*Provided a platform, this function adds it to the platform table.
*/
{
bool success = false;
QSqlQuery query;
query.prepare("INSERT INTO platform (platform,game_counter,opened_counter) VALUES (:platform,:game_counter,:opened_counter)");
query.bindValue(":platform",platform);
query.bindValue(":game_counter",0);
query.bindValue(":opened_counter",0);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "addPlatformEntry error: " << query.lastError().text();
}
setPlatformEmulator(platform,PlatformToSupportedEmulator(platform));
return success;
}
bool DbManager::deletePlatformEntry(QString platform)
/*Provided a platform name, this function removes it from the platform table(and therefore from the database).
*/
{
bool success = false;
QSqlQuery query;
query.prepare("DELETE FROM platform WHERE platform = :platform;");
query.bindValue(":platform",platform);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "deletePlatformEntry error: " << query.lastError().text();
}
return success;
}
bool DbManager::incrementPlatformGameCounter(QString platform, bool plus)
//Provided a platform, increments its game_counter by 1.
{
bool success = false;
QSqlQuery query;
query.prepare("UPDATE platform SET game_counter=:game_counter WHERE platform=:platform;");
if (plus)
{
query.bindValue(":game_counter",getPlatformGameCounter(platform)+1);
}
else
{
query.bindValue(":game_counter",getPlatformGameCounter(platform)-1);
}
query.bindValue(":platform",platform);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "incrementPlatformGameCounter error: " << query.lastError().text();
}
return success;
}
QStringList DbManager::getAllPlatforms()
{
QStringList allPlatforms;
QSqlQuery query;
query.prepare("SELECT platform FROM platform;");
if(query.exec())
{
while (query.next())
{
allPlatforms.append(query.value(0).toString());
}
}
else
{
qDebug() << "getAllPlatforms error: " << query.lastError().text();
}
return allPlatforms;
}
QByteArray DbManager::getPlatformImage(QString platform)
/*Provided a platform name, this function returns its image byte array.
*/
{
QByteArray PlatformImage;
QSqlQuery query;
query.prepare("SELECT image_path FROM platform WHERE platform=:platform;");
query.bindValue(":platform",platform);
if(query.exec())
{
while (query.next())
{
PlatformImage = query.value(0).toByteArray();
}
}
else
{
qDebug() << "getPlatformImage error: " << query.lastError().text();
}
return PlatformImage;
}
QString DbManager::getPlatformInfo(QString platform)
/*Provided a platform name, this function returns its platform_info.
*/
{
QString PlatformInfo("");
QSqlQuery query;
query.prepare("SELECT platform_info FROM platform WHERE platform=:platform;");
query.bindValue(":platform",platform);
if(query.exec())
{
while (query.next())
{
PlatformInfo = query.value(0).toString();
qDebug(qUtf8Printable(PlatformInfo));
}
}
else
{
qDebug() << "getPlatformInfo error: " << query.lastError().text();
}
return PlatformInfo;
}
int DbManager::getPlatformGameCounter(QString platform)
/*Provided a platform name, this function returns its game_counter.
*/
{
int gameCounter;
QSqlQuery query;
query.prepare("SELECT game_counter FROM platform WHERE platform=:platform;");
query.bindValue(":platform",platform);
if(query.exec())
{
while (query.next())
{
gameCounter = query.value(0).toInt();
qDebug(qUtf8Printable(QString::number(gameCounter)));
}
}
else
{
qDebug() << "getPlatformGameCounter error: " << query.lastError().text();
}
return gameCounter;
}
QString DbManager::getPlatformEmulator(QString platform)
/*Provided a platform name, this function returns its emulator_name.
*/
{
QString PlatformEmulator("");
QSqlQuery query;
query.prepare("SELECT emulator_name FROM platform WHERE platform=:platform;");
query.bindValue(":platform",platform);
if(query.exec())
{
while (query.next())
{
PlatformEmulator = query.value(0).toString();
qDebug(qUtf8Printable(PlatformEmulator));
}
}
else
{
qDebug() << "getPlatformEmulator error: " << query.lastError().text();
}
return PlatformEmulator;
}
QString DbManager::getPlatformTimePlayed(QString platform)
/*Provided a platform name, this function returns its time_played.
*/
{
QString timePlayed("");
QSqlQuery query;
query.prepare("SELECT time_played FROM platform WHERE platform=:platform;");
query.bindValue(":platform",platform);
if(query.exec())
{
while (query.next())
{
timePlayed = query.value(0).toString();
qDebug(qUtf8Printable(timePlayed));
}
}
else
{
qDebug() << "getPlatformTimePlayed error: " << query.lastError().text();
}
return timePlayed;
}
QString DbManager::getPlatformLastPlayed(QString platform)
/*Provided a platform name, this function returns its last_played.
*/
{
QString lastPlayed("");
QSqlQuery query;
query.prepare("SELECT last_played FROM platform WHERE platform=:platform;");
query.bindValue(":platform",platform);
if(query.exec())
{
while (query.next())
{
lastPlayed = query.value(0).toString();
qDebug(qUtf8Printable(lastPlayed));
}
}
else
{
qDebug() << "getPlatformLastPlayed error: " << query.lastError().text();
}
return lastPlayed;
}
int DbManager::getPlatformOpenedCounter(QString platform)
{
int openedCounter=-1;
QSqlQuery query;
query.prepare("SELECT opened_counter FROM platform WHERE platform=:platform;");
query.bindValue(":platform",platform);
if(query.exec())
{
while (query.next())
{
openedCounter = query.value(0).toInt();
qDebug(qUtf8Printable(QString::number(openedCounter)));
}
}
else
{
qDebug() << "getPlatformOpenedCounter error: " << query.lastError().text();
}
return openedCounter;
}
bool DbManager::setPlatformEmulator(QString platform, QString emulatorName)
//Provided a platform and an emulator_name, this function sets it.
{
if (platform=="PC")
{
return true;
}
bool success = false;
QSqlQuery query;
query.prepare("UPDATE platform SET emulator_name=:emulator_name WHERE platform=:platform;");
query.bindValue(":platform",platform);
query.bindValue(":emulator_name",emulatorName);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setPlatformEmulator error: " << query.lastError().text();
}
return success;
}
bool DbManager::setPlatformOpenedCounter(QString platform, int openedCounter)
//Provided a game id and timePlayed, this function sets the time_played.
{
bool success = false;
QSqlQuery query;
query.prepare("UPDATE platform SET opened_counter=:opened_counter WHERE platform=:platform;");
query.bindValue(":opened_counter",openedCounter);
query.bindValue(":platform",platform);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setPlatformOpenedCounter error: " << query.lastError().text();
}
return success;
}
//=============================================================================================================================
//=================================================EMULATOR TABLE OPERATIONS===================================================
//=============================================================================================================================
bool DbManager::addEmulatorEntry(QString emulatorName,QString emulatorPath)
/*Provided an emulator, this function adds it to the emulator table.
*/
{
bool success = false;
QSqlQuery query;
query.prepare("INSERT INTO emulator (emulator_name,path,opened_counter) VALUES (:emulator_name,:path,:opened_counter)");
query.bindValue(":emulator_name",emulatorName);
query.bindValue(":path",emulatorPath);
query.bindValue(":opened_counter",0);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "addEmulatorEntry error: " << query.lastError().text();
}
return success;
}
bool DbManager::deleteEmulatorEntry(QString emulatorName)
/*Provided an emulator name, this function removes it from the emulator table(and therefore from the database).
*/
{
bool success = false;
QSqlQuery query;
query.prepare("DELETE FROM emulator WHERE emulator_name = :emulator_name;");
query.bindValue(":emulator_name",emulatorName);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "deleteEmulatorEntry error: " << query.lastError().text();
}
return success;
}
QByteArray DbManager::getEmulatorImage(QString emulatorName)
{
/*Provided a emulator_name, this function returns its image byte array.
*/
{
QByteArray EmulatorImage;
QSqlQuery query;
query.prepare("SELECT image_path FROM emulator WHERE emulator_name=:emulator_name;");
query.bindValue(":emulator_name",emulatorName);
if(query.exec())
{
while (query.next())
{
EmulatorImage = query.value(0).toByteArray();
}
}
else
{
qDebug() << "getEmulatorImage error: " << query.lastError().text();
}
return EmulatorImage;
}
}
QString DbManager::getEmulatorInfo(QString emulatorName)
{
/*Provided a emulator_name, this function returns its emulator_info.
*/
{
QString EmulatorInfo("");
QSqlQuery query;
query.prepare("SELECT emulator_info FROM emulator WHERE emulator_name=:emulator_name;");
query.bindValue(":emulator_name",emulatorName);
if(query.exec())
{
while (query.next())
{
EmulatorInfo = query.value(0).toString();
qDebug(qUtf8Printable(EmulatorInfo));
}
}
else
{
qDebug() << "getEmulatorInfo error: " << query.lastError().text();
}
return EmulatorInfo;
}
}
QString DbManager::getEmulatorPath(QString emulatorName)
/*Provided a emulator_name, this function returns its path.
*/
{
QString EmulatorPath("");
QSqlQuery query;
query.prepare("SELECT path FROM emulator WHERE emulator_name=:emulator_name;");
query.bindValue(":emulator_name",emulatorName);
if(query.exec())
{
while (query.next())
{
EmulatorPath = query.value(0).toString();
qDebug(qUtf8Printable(EmulatorPath));
}
}
else
{
qDebug() << "getEmulatorPath error: " << query.lastError().text();
}
return EmulatorPath;
}
QString DbManager::getEmulatorTimePlayed(QString emulatorName)
/*Provided a emulator_name, this function returns its timeplayed.
*/
{
QString timePlayed("");
QSqlQuery query;
query.prepare("SELECT time_played FROM emulator WHERE emulator_name=:emulator_name;");
query.bindValue(":emulator_name",emulatorName);
if(query.exec())
{
while (query.next())
{
timePlayed = query.value(0).toString();
qDebug(qUtf8Printable(timePlayed));
}
}
else
{
qDebug() << "getEmulatorTimePlayed error: " << query.lastError().text();
}
return timePlayed;
}
QString DbManager::getEmulatorLastPlayed(QString emulatorName)
/*Provided a emulator_name, this function returns its last_played.
*/
{
QString lastPlayed("");
QSqlQuery query;
query.prepare("SELECT last_played FROM emulator WHERE emulator_name=:emulator_name;");
query.bindValue(":emulator_name",emulatorName);
if(query.exec())
{
while (query.next())
{
lastPlayed = query.value(0).toString();
qDebug(qUtf8Printable(lastPlayed));
}
}
else
{
qDebug() << "getEmulatorLastPlayed error: " << query.lastError().text();
}
return lastPlayed;
}
QStringList DbManager::getAllEmulators()
{
QStringList allEmulators;
QSqlQuery query;
query.prepare("SELECT emulator_name FROM emulator;");
if(query.exec())
{
while (query.next())
{
allEmulators.append(query.value(0).toString());
}
}
else
{
qDebug() << "getAllEmulators error: " << query.lastError().text();
}
return allEmulators;
}
int DbManager::getEmulatorOpenedCounter(QString emulatorName)
{
int openedCounter=-1;
QSqlQuery query;
query.prepare("SELECT opened_counter FROM emulator WHERE emulator_name=:emulator_name;");
query.bindValue(":emulator_name",emulatorName);
if(query.exec())
{
while (query.next())
{
openedCounter = query.value(0).toInt();
qDebug(qUtf8Printable(QString::number(openedCounter)));
}
}
else
{
qDebug() << "getEmulatorOpenedCounter error: " << query.lastError().text();
}
return openedCounter;
}
bool DbManager::setEmulatorPath(QString emulatorName, QString path)
//Provided an emulator_name and its path, this function sets it.
{
bool success = false;
QSqlQuery query;
query.prepare("UPDATE emulator SET path=:path WHERE emulator_name=:emulator_name");
query.bindValue(":path",path);
query.bindValue(":emulator_name",emulatorName);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setEmulatorPath error: " << query.lastError().text();
}
return success;
}
bool DbManager::setEmulatorOpenedCounter(QString emulatorName, int openedCounter)
//Provided a game id and timePlayed, this function sets the time_played.
{
bool success = false;
QSqlQuery query;
query.prepare("UPDATE emulator SET opened_counter=:opened_counter WHERE emulator_name=:emulator_name;");
query.bindValue(":opened_counter",openedCounter);
query.bindValue(":emulator_name",emulatorName);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setEmulatorOpenedCounter error: " << query.lastError().text();
}
return success;
}
bool DbManager::addExternalSoftwareEntry(QString externalSoftwareName)
/*Provided an emulator, this function adds it to the emulator table.
*/
{
bool success = false;
QSqlQuery query;
query.prepare("INSERT INTO extsoft (software_name,opened_counter) VALUES (:software_name,:opened_counter)");
query.bindValue(":software_name",externalSoftwareName);
query.bindValue(":opened_counter",0);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "addExternalSoftwareEntry error: " << query.lastError().text();
}
return success;
}
bool DbManager::deleteExternalSoftwareEntry(QString externalSoftwareName)
/*Provided an emulator name, this function removes it from the emulator table(and therefore from the database).
*/
{
bool success = false;
QSqlQuery query;
query.prepare("DELETE FROM extsoft WHERE software_name = :software_name;");
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "deleteExternalSoftwareEntry error: " << query.lastError().text();
}
return success;
}
QStringList DbManager::getAllExternalSoftwares()
{
QStringList allSoftwares;
QSqlQuery query;
query.prepare("SELECT software_name FROM extsoft;");
if(query.exec())
{
while (query.next())
{
allSoftwares.append(query.value(0).toString());
}
}
else
{
qDebug() << "getAllExternalSoftwares error: " << query.lastError().text();
}
return allSoftwares;
}
QString DbManager::getExternalSoftwarePath(QString externalSoftwareName)
/*Provided a game id, this function returns its path.
*/
{
QString path("");
QSqlQuery query;
query.prepare("SELECT path FROM extsoft WHERE software_name=:software_name;");
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
while (query.next())
{
path = query.value(0).toString();
qDebug(qUtf8Printable(path));
}
}
else
{
qDebug() << "getExternalSoftwarePath error: " << query.lastError().text();
}
return path;
}
bool DbManager::getExternalSoftwareSupportedBool(QString externalSoftwareName)
{
bool supported = false;
QSqlQuery query;
query.prepare("SELECT supported_extsoft FROM extsoft WHERE software_name=:software_name;");
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
while(query.next())
{
supported = query.value(0).toBool();
qDebug(qUtf8Printable(QString::number(supported)));
}
}
else
{
qDebug() << "getExternalSoftwareSupportedBool error : " << query.lastError().text();
}
return supported;
}
int DbManager::getExternalSoftwareOpenedCounter(QString externalSoftwareName)
{
int openedCounter=-1;
QSqlQuery query;
query.prepare("SELECT opened_counter FROM extsoft WHERE software_name=:software_name;");
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
while (query.next())
{
openedCounter = query.value(0).toInt();
qDebug(qUtf8Printable(QString::number(openedCounter)));
}
}
else
{
qDebug() << "getExternalSoftwareOpenedCounter error: " << query.lastError().text();
}
return openedCounter;
}
QList<int> DbManager::getExternalSoftwareGamesWhitelist(QString externalSoftwareName)
{
QList<int> gamesWhitelist;
QString result;
QSqlQuery query;
query.prepare("SELECT games_whitelist FROM extsoft WHERE software_name=:software_name;");
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
while(query.next())
{
result = query.value(0).toString();
foreach(QString gameId,result.split('|'))
{
gamesWhitelist.append(gameId.toInt());
}
}
}
else
{
qDebug() << "getExternalSoftwareGamesWhitelist error : " << query.lastError().text();
}
return gamesWhitelist;
}
QList<int> DbManager::getExternalSoftwareGamesOffList(QString externalSoftwareName)
{
QList<int> gamesOffList;
QString result;
QSqlQuery query;
query.prepare("SELECT games_off_list FROM extsoft WHERE software_name=:software_name;");
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
while(query.next())
{
result = query.value(0).toString();
foreach(QString gameId,result.split('|'))
{
gamesOffList.append(gameId.toInt());
}
}
}
else
{
qDebug() << "getExternalSoftwareGamesOffList error : " << query.lastError().text();
}
return gamesOffList;
}
QStringList DbManager::getExternalSoftwarePlatformsOnList(QString externalSoftwareName)
{
QStringList platformsOnList;
QSqlQuery query;
query.prepare("SELECT platforms_on_list FROM extsoft WHERE software_name=:software_name;");
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
while(query.next())
{
platformsOnList = query.value(0).toString().split('|');
}
}
else
{
qDebug() << "getExternalSoftwarePlatormsOnList error : " << query.lastError().text();
}
return platformsOnList;
}
bool DbManager::getExternalSoftwareGameCanRun(QString extSoftName, int gameId){
bool gameswhitelisted = getExternalSoftwareGamesWhitelist(extSoftName).contains(gameId);
bool gamesoff = getExternalSoftwareGamesOffList(extSoftName).contains(gameId);
bool platformon = getExternalSoftwarePlatformsOnList(extSoftName).contains(getGamePlatform(gameId));
if (gameswhitelisted){
return true;
}
else if(gamesoff){
return false;
}
else if(platformon){
return true;
}
return false;
}
bool DbManager::getExternalSoftwareMutliInstance(QString externalSoftwareName){
bool state = false;
QSqlQuery query;
query.prepare("SELECT multi_instance FROM extsoft WHERE software_name=:software_name;");
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
while (query.next())
{
state = query.value(0).toBool();
}
}
else
{
qDebug() << "getExternalSoftwareMultiInstance error: " << query.lastError().text();
}
return state;
}
bool DbManager::setExternalSoftwareGamesWhitelist(QString externalSoftwareName, QList<int> gamesWhitelist)
{
QString gamesWhitelistDB;
foreach(int gameId, gamesWhitelist)
{
gamesWhitelistDB += QString::number(gameId)+"|";
}
gamesWhitelistDB.chop(1);
bool success = false;
QSqlQuery query;
query.prepare("UPDATE extsoft SET games_whitelist=:games_whitelist WHERE software_name=:software_name;");
query.bindValue(":games_whitelist",gamesWhitelistDB);
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setExternalSoftwareGamesWhitelist error: " << query.lastError().text();
}
return success;
}
bool DbManager::setExternalSoftwareGamesOffList(QString externalSoftwareName, QList<int> gamesOffList)
{
QString gamesOffListDB;
foreach(int gameId, gamesOffList)
{
gamesOffListDB += QString::number(gameId)+"|";
}
gamesOffListDB.chop(1);
bool success = false;
QSqlQuery query;
query.prepare("UPDATE extsoft SET games_off_list=:games_off_list WHERE software_name=:software_name;");
query.bindValue(":games_off_list",gamesOffListDB);
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setExternalSoftwareGamesOffList error: " << query.lastError().text();
}
return success;
}
bool DbManager::setExternalSoftwarePlatformsOnList(QString externalSoftwareName, QStringList platformsOnList)
{
QStringList list;
bool success = false;
QSqlQuery query;
query.prepare("UPDATE extsoft SET platforms_on_list=:platforms_on_list WHERE software_name=:software_name;");
query.bindValue(":platforms_on_list",QString(platformsOnList.join('|')));
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setExternalSoftwarePlatformsOnList error: " << query.lastError().text();
}
return success;
}
bool DbManager::setExternalSoftwarePath(QString externalSoftwareName, QString path)
//Provided an emulator_name and its path, this function sets it.
{
bool success = false;
QSqlQuery query;
query.prepare("UPDATE extsoft SET path=:path WHERE software_name=:software_name;");
query.bindValue(":path",path);
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setExternalSoftwarePath error: " << query.lastError().text();
}
return success;
}
bool DbManager::setExternalSoftwareSupportedBool(QString externalSoftwareName, bool supported)
{
bool success = false;
QSqlQuery query;
query.prepare("UPDATE extsoft SET supported_extsoft=:supported_extsoft WHERE software_name=:software_name;");
query.bindValue(":supported_extsoft",supported);
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setExternalSoftwareSupportedBool error: " << query.lastError().text();
}
return success;
}
bool DbManager::setExternalSoftwareOpenedCounter(QString externalSoftwareName, int openedCounter)
//Provided a game id and timePlayed, this function sets the time_played.
{
bool success = false;
QSqlQuery query;
query.prepare("UPDATE extsoft SET opened_counter=:opened_counter WHERE software_name=:software_name;");
query.bindValue(":opened_counter",openedCounter);
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setExternalSoftwareOpenedCounter error: " << query.lastError().text();
}
return success;
}
bool DbManager::setExternalSoftwareMutliInstance(QString externalSoftwareName, bool state){
bool success = false;
QSqlQuery query;
query.prepare("UPDATE extsoft SET multi_instance=:multi_instance WHERE software_name=:software_name;");
query.bindValue(":multi_instance",state);
query.bindValue(":software_name",externalSoftwareName);
if(query.exec())
{
success = true;
}
else
{
qDebug() << "setExternalSoftwareMultiInstance error: " << query.lastError().text();
}
return success;
}
| Roukira/Ludibrary | src/dbmanager.cpp | C++ | lgpl-3.0 | 50,325 |
/*
* Copyright (C) EntityAPI Team
*
* This file is part of EntityAPI.
*
* EntityAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EntityAPI 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 EntityAPI. If not, see <http://www.gnu.org/licenses/>.
*/
package org.entityapi.api.entity.type.nms;
import org.bukkit.entity.Slime;
import org.entityapi.api.entity.ControllableEntityHandle;
public interface ControllableSlimeHandle extends ControllableEntityHandle<Slime> {
} | EntityAPIDev/EntityAPI | modules/API/src/main/java/org/entityapi/api/entity/type/nms/ControllableSlimeHandle.java | Java | lgpl-3.0 | 938 |
/**
*
*/
package com.sqsoft.mars.qyweixin.client.cgibin.message;
import com.sqsoft.mars.qyweixin.client.QyweixinDefaultClient;
/**
* @author lenovo
*
*/
public class QyweixinMessageClient extends QyweixinDefaultClient {
/**
*
*/
private String access_token;
/**
*
* @param access_token
*/
public QyweixinMessageClient(String access_token) {
super();
this.access_token = access_token;
}
/* (non-Javadoc)
* @see com.sqsoft.mars.qyweixin.client.DefaultQyweixinClient#getUrl()
*/
@Override
protected String getUrl() {
return "https://qyapi.weixin.qq.com/cgi-bin/message/{method}?access_token=" + access_token;
}
}
| anndy201/mars-framework | com.sqsoft.mars.qyweixin.client/src/main/java/com/sqsoft/mars/qyweixin/client/cgibin/message/QyweixinMessageClient.java | Java | lgpl-3.0 | 656 |
<?php
/**
* TOP API: taobao.fenxiao.distributor.procuct.static.get request
*
* @author auto create
* @since 1.0, 2014-02-20 17:02:53
*/
class FenxiaoDistributorProcuctStaticGetRequest
{
/**
* 分销商淘宝店主nick
**/
private $distributorUserNick;
/**
* 供应商商品id,一次可以传多个,每次最多40个。
以,(英文)作为分隔符。
**/
private $productIdArray;
private $apiParas = array();
public function setDistributorUserNick($distributorUserNick)
{
$this->distributorUserNick = $distributorUserNick;
$this->apiParas["distributor_user_nick"] = $distributorUserNick;
}
public function getDistributorUserNick()
{
return $this->distributorUserNick;
}
public function setProductIdArray($productIdArray)
{
$this->productIdArray = $productIdArray;
$this->apiParas["product_id_array"] = $productIdArray;
}
public function getProductIdArray()
{
return $this->productIdArray;
}
public function getApiMethodName()
{
return "taobao.fenxiao.distributor.procuct.static.get";
}
public function getApiParas()
{
return $this->apiParas;
}
public function check()
{
RequestCheckUtil::checkNotNull($this->distributorUserNick,"distributorUserNick");
RequestCheckUtil::checkNotNull($this->productIdArray,"productIdArray");
}
public function putOtherTextParam($key, $value) {
$this->apiParas[$key] = $value;
$this->$key = $value;
}
}
| jnuzh/nidama | taobao_sdk/top/request/FenxiaoDistributorProcuctStaticGetRequest.php | PHP | lgpl-3.0 | 1,482 |
package jcl.compiler.sa.analyzer.lambdalistparser;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Predicate;
import jcl.compiler.environment.Environment;
import jcl.compiler.environment.binding.Binding;
import jcl.compiler.environment.binding.lambdalist.AuxParameter;
import jcl.compiler.environment.binding.lambdalist.BodyParameter;
import jcl.compiler.environment.binding.lambdalist.DestructuringLambdaList;
import jcl.compiler.environment.binding.lambdalist.EnvironmentParameter;
import jcl.compiler.environment.binding.lambdalist.KeyParameter;
import jcl.compiler.environment.binding.lambdalist.OptionalParameter;
import jcl.compiler.environment.binding.lambdalist.RequiredParameter;
import jcl.compiler.environment.binding.lambdalist.RestParameter;
import jcl.compiler.environment.binding.lambdalist.SuppliedPParameter;
import jcl.compiler.environment.binding.lambdalist.WholeParameter;
import jcl.compiler.sa.FormAnalyzer;
import jcl.compiler.struct.specialoperator.declare.DeclareStruct;
import jcl.compiler.struct.specialoperator.declare.SpecialDeclarationStruct;
import jcl.lang.KeywordStruct;
import jcl.lang.LispStruct;
import jcl.lang.ListStruct;
import jcl.lang.NILStruct;
import jcl.lang.PackageStruct;
import jcl.lang.PackageSymbolStruct;
import jcl.lang.SymbolStruct;
import jcl.lang.condition.exception.ProgramErrorException;
import jcl.lang.statics.CommonLispSymbols;
import jcl.lang.statics.CompilerConstants;
import jcl.lang.statics.GlobalPackageStruct;
import lombok.experimental.UtilityClass;
@UtilityClass
public final class LambdaListParser {
public static WholeParseResult parseWholeBinding(final Environment environment,
final Iterator<LispStruct> iterator,
final DeclareStruct declareElement) {
final LispStruct currentElement = iterator.next();
if (!(currentElement instanceof SymbolStruct)) {
throw new ProgramErrorException("LambdaList &whole parameters must be a symbol: " + currentElement);
}
final SymbolStruct currentParam = (SymbolStruct) currentElement;
final boolean isSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(currentParam));
final Binding binding = new Binding(currentParam, CommonLispSymbols.T);
if (isSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
final WholeParameter wholeBinding = new WholeParameter(currentParam, isSpecial);
return new WholeParseResult(wholeBinding);
}
public static EnvironmentParseResult parseEnvironmentBinding(final Environment environment,
final Iterator<LispStruct> iterator,
final boolean isAfterRequired) {
LispStruct currentElement = iterator.next();
if (!(currentElement instanceof SymbolStruct)) {
throw new ProgramErrorException("LambdaList &environment parameters must be a symbol: " + currentElement);
}
final SymbolStruct currentParam = (SymbolStruct) currentElement;
if (iterator.hasNext() && isAfterRequired) {
currentElement = iterator.next();
if (!isLambdaListKeyword(currentElement)) {
throw new ProgramErrorException("LambdaList &environment parameter must only have 1 parameter: " + currentElement);
}
}
final Binding binding = new Binding(currentParam, CommonLispSymbols.T);
environment.addDynamicBinding(binding);
final EnvironmentParameter environmentBinding = new EnvironmentParameter(currentParam);
return new EnvironmentParseResult(currentElement, environmentBinding);
}
public static RequiredParseResult parseRequiredBindings(final Environment environment,
final Iterator<LispStruct> iterator,
final DeclareStruct declareElement,
final boolean isDotted,
final boolean isDestructuringAllowed) {
final List<RequiredParameter> requiredBindings = new ArrayList<>();
LispStruct currentElement;
do {
currentElement = iterator.next();
if (!iterator.hasNext() && isDotted) {
return new RequiredParseResult(currentElement, requiredBindings);
}
if (isLambdaListKeyword(currentElement)) {
return new RequiredParseResult(currentElement, requiredBindings);
}
final SymbolStruct currentParam;
DestructuringLambdaList destructuringForm = null;
if (currentElement instanceof SymbolStruct) {
currentParam = (SymbolStruct) currentElement;
} else {
if (isDestructuringAllowed) {
if (currentElement instanceof ListStruct) {
final String destructuringName = "DestructuringSymbolName-" + System.nanoTime();
currentParam = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol();
final ListStruct destructuringFormList = (ListStruct) currentElement;
destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement);
} else {
throw new ProgramErrorException("LambdaList required parameter must be a symbol or a destructuring list: " + currentElement);
}
} else {
throw new ProgramErrorException("LambdaList required parameters must be a symbol: " + currentElement);
}
}
final boolean isSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(currentParam));
final Binding binding = new Binding(currentParam, CommonLispSymbols.T);
if (isSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
final RequiredParameter requiredBinding = new RequiredParameter(currentParam, destructuringForm, isSpecial);
requiredBindings.add(requiredBinding);
} while (iterator.hasNext());
return new RequiredParseResult(currentElement, requiredBindings);
}
public static OptionalParseResult parseOptionalBindings(final Environment environment,
final Iterator<LispStruct> iterator,
final DeclareStruct declareElement,
final boolean isDotted,
final boolean isDestructuringAllowed) {
final List<OptionalParameter> optionalBindings = new ArrayList<>();
if (!iterator.hasNext()) {
return new OptionalParseResult(null, optionalBindings);
}
LispStruct currentElement;
do {
currentElement = iterator.next();
if (isLambdaListKeyword(currentElement)) {
return new OptionalParseResult(currentElement, optionalBindings);
}
if (!iterator.hasNext() && isDotted) {
return new OptionalParseResult(currentElement, optionalBindings);
}
if (currentElement instanceof SymbolStruct) {
final SymbolStruct currentParam = (SymbolStruct) currentElement;
final boolean isSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(currentParam));
Binding binding = new Binding(currentParam, CommonLispSymbols.T);
if (isSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
final String paramName = currentParam.getName();
final String customSuppliedPName = paramName + "-P-" + System.nanoTime();
final PackageStruct currentParamPackage = currentParam.getSymbolPackage();
final SymbolStruct customSuppliedPCurrent = currentParamPackage.intern(customSuppliedPName).getSymbol();
final boolean isSuppliedPSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(customSuppliedPCurrent));
binding = new Binding(customSuppliedPCurrent, CommonLispSymbols.T);
if (isSuppliedPSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
final SuppliedPParameter suppliedPBinding = new SuppliedPParameter(customSuppliedPCurrent, isSuppliedPSpecial);
final OptionalParameter optionalBinding = new OptionalParameter(currentParam, null, NILStruct.INSTANCE, isSpecial, suppliedPBinding);
optionalBindings.add(optionalBinding);
} else if (currentElement instanceof ListStruct) {
final ListStruct currentParam = (ListStruct) currentElement;
final long currentParamLength = currentParam.length().toJavaPLong();
if ((currentParamLength < 1) || (currentParamLength > 3)) {
if (isDestructuringAllowed) {
final String destructuringName = "DestructuringSymbolName-" + System.nanoTime();
final SymbolStruct varNameCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol();
final ListStruct destructuringFormList = (ListStruct) currentElement;
final DestructuringLambdaList destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement);
final String customSuppliedPName = destructuringName + "-P-" + System.nanoTime();
final SymbolStruct customSuppliedPCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(customSuppliedPName).getSymbol();
final SuppliedPParameter suppliedPBinding = new SuppliedPParameter(customSuppliedPCurrent);
final OptionalParameter optionalBinding = new OptionalParameter(varNameCurrent, destructuringForm, NILStruct.INSTANCE, false, suppliedPBinding);
optionalBindings.add(optionalBinding);
} else {
throw new ProgramErrorException("LambdaList &optional parameters must have between 1 and 3 parameters: " + currentParam);
}
} else {
final Iterator<LispStruct> currentIterator = currentParam.iterator();
final LispStruct firstInCurrent = currentIterator.next();
final LispStruct secondInCurrent;
if (currentIterator.hasNext()) {
secondInCurrent = currentIterator.next();
} else {
secondInCurrent = NILStruct.INSTANCE;
}
final LispStruct thirdInCurrent;
if (currentIterator.hasNext()) {
thirdInCurrent = currentIterator.next();
} else {
thirdInCurrent = NILStruct.INSTANCE;
}
final SymbolStruct varNameCurrent;
DestructuringLambdaList destructuringForm = null;
if (firstInCurrent instanceof SymbolStruct) {
varNameCurrent = (SymbolStruct) firstInCurrent;
} else {
if (isDestructuringAllowed) {
if (firstInCurrent instanceof ListStruct) {
final String destructuringName = "DestructuringSymbolName-" + System.nanoTime();
varNameCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol();
final ListStruct destructuringFormList = (ListStruct) firstInCurrent;
destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement);
} else {
throw new ProgramErrorException("LambdaList &optional var name parameter must be a symbol or a destructuring list: " + firstInCurrent);
}
} else {
throw new ProgramErrorException("LambdaList &optional var name parameters must be a symbol: " + firstInCurrent);
}
}
LispStruct initForm = NILStruct.INSTANCE;
if (!secondInCurrent.eq(NILStruct.INSTANCE)) {
initForm = secondInCurrent;
}
final LispStruct parameterValueInitForm = FormAnalyzer.analyze(initForm, environment);
final boolean isSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(varNameCurrent));
Binding binding = new Binding(varNameCurrent, CommonLispSymbols.T);
if (isSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
final SuppliedPParameter suppliedPBinding;
if (thirdInCurrent.eq(NILStruct.INSTANCE)) {
final String paramName = varNameCurrent.getName();
final String customSuppliedPName = paramName + "-P-" + System.nanoTime();
final PackageStruct currentParamPackage = varNameCurrent.getSymbolPackage();
final SymbolStruct customSuppliedPCurrent = currentParamPackage.intern(customSuppliedPName).getSymbol();
final boolean isSuppliedPSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(customSuppliedPCurrent));
binding = new Binding(customSuppliedPCurrent, CommonLispSymbols.T);
if (isSuppliedPSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
suppliedPBinding = new SuppliedPParameter(customSuppliedPCurrent, isSuppliedPSpecial);
} else {
if (!(thirdInCurrent instanceof SymbolStruct)) {
throw new ProgramErrorException("LambdaList &optional supplied-p parameters must be a symbol: " + thirdInCurrent);
}
final SymbolStruct suppliedPCurrent = (SymbolStruct) thirdInCurrent;
final boolean isSuppliedPSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(suppliedPCurrent));
binding = new Binding(suppliedPCurrent, CommonLispSymbols.T);
if (isSuppliedPSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
suppliedPBinding = new SuppliedPParameter(suppliedPCurrent, isSuppliedPSpecial);
}
final OptionalParameter optionalBinding = new OptionalParameter(varNameCurrent, destructuringForm, parameterValueInitForm, isSpecial, suppliedPBinding);
optionalBindings.add(optionalBinding);
}
} else {
throw new ProgramErrorException("LambdaList &optional parameters must be a symbol or a list: " + currentElement);
}
} while (iterator.hasNext());
return new OptionalParseResult(currentElement, optionalBindings);
}
public static RestParseResult parseRestBinding(final Environment environment,
final Iterator<LispStruct> iterator,
final DeclareStruct declareElement,
final boolean isDestructuringAllowed) {
if (!iterator.hasNext()) {
throw new ProgramErrorException("LambdaList &rest parameter must be provided.");
}
LispStruct currentElement = iterator.next();
final SymbolStruct currentParam;
DestructuringLambdaList destructuringForm = null;
if (currentElement instanceof SymbolStruct) {
currentParam = (SymbolStruct) currentElement;
} else {
if (isDestructuringAllowed) {
if (currentElement instanceof ListStruct) {
final String destructuringName = "DestructuringSymbolName-" + System.nanoTime();
currentParam = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol();
final ListStruct destructuringFormList = (ListStruct) currentElement;
destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement);
} else {
throw new ProgramErrorException("LambdaList &rest parameters must be a symbol or a destructuring list: " + currentElement);
}
} else {
throw new ProgramErrorException("LambdaList &rest parameters must be a symbol: " + currentElement);
}
}
if (iterator.hasNext()) {
currentElement = iterator.next();
if (!isLambdaListKeyword(currentElement)) {
throw new ProgramErrorException("LambdaList &rest parameter must only have 1 parameter: " + currentElement);
}
}
final boolean isSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(currentParam));
final Binding binding = new Binding(currentParam, CommonLispSymbols.T);
if (isSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
final RestParameter restBinding = new RestParameter(currentParam, destructuringForm, isSpecial);
return new RestParseResult(currentElement, restBinding);
}
public static RestParseResult parseDottedRestBinding(final Environment environment,
final LispStruct dottedRest,
final DeclareStruct declareElement,
final boolean isDestructuringAllowed) {
final SymbolStruct currentParam;
DestructuringLambdaList destructuringForm = null;
if (dottedRest instanceof SymbolStruct) {
currentParam = (SymbolStruct) dottedRest;
} else {
if (isDestructuringAllowed) {
if (dottedRest instanceof ListStruct) {
final String destructuringName = "DestructuringSymbolName-" + System.nanoTime();
currentParam = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol();
final ListStruct destructuringFormList = (ListStruct) dottedRest;
destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement);
} else {
throw new ProgramErrorException("LambdaList &rest parameters must be a symbol or a destructuring list: " + dottedRest);
}
} else {
throw new ProgramErrorException("LambdaList &rest parameters must be a symbol: " + dottedRest);
}
}
final boolean isSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(currentParam));
final Binding binding = new Binding(currentParam, CommonLispSymbols.T);
if (isSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
final RestParameter restBinding = new RestParameter(currentParam, destructuringForm, isSpecial);
return new RestParseResult(dottedRest, restBinding);
}
public static BodyParseResult parseBodyBinding(final Environment environment,
final Iterator<LispStruct> iterator,
final DeclareStruct declareElement,
final boolean isDestructuringAllowed) {
if (!iterator.hasNext()) {
throw new ProgramErrorException("LambdaList &body parameter must be provided.");
}
LispStruct currentElement = iterator.next();
final SymbolStruct currentParam;
DestructuringLambdaList destructuringForm = null;
if (currentElement instanceof SymbolStruct) {
currentParam = (SymbolStruct) currentElement;
} else {
if (isDestructuringAllowed) {
if (currentElement instanceof ListStruct) {
final String destructuringName = "DestructuringSymbolName-" + System.nanoTime();
currentParam = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol();
final ListStruct destructuringFormList = (ListStruct) currentElement;
destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement);
} else {
throw new ProgramErrorException("LambdaList &rest parameters must be a symbol or a destructuring list: " + currentElement);
}
} else {
throw new ProgramErrorException("LambdaList &rest parameters must be a symbol: " + currentElement);
}
}
if (iterator.hasNext()) {
currentElement = iterator.next();
if (!isLambdaListKeyword(currentElement)) {
throw new ProgramErrorException("LambdaList &body parameter must only have 1 parameter: " + currentElement);
}
}
final boolean isSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(currentParam));
final Binding binding = new Binding(currentParam, CommonLispSymbols.T);
if (isSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
final BodyParameter bodyBinding = new BodyParameter(currentParam, destructuringForm, isSpecial);
return new BodyParseResult(currentElement, bodyBinding);
}
public static KeyParseResult parseKeyBindings(final Environment environment,
final Iterator<LispStruct> iterator,
final DeclareStruct declareElement,
final boolean isDestructuringAllowed) {
final List<KeyParameter> keyBindings = new ArrayList<>();
if (!iterator.hasNext()) {
return new KeyParseResult(null, keyBindings);
}
LispStruct currentElement;
do {
currentElement = iterator.next();
if (isLambdaListKeyword(currentElement)) {
return new KeyParseResult(currentElement, keyBindings);
}
if (currentElement instanceof SymbolStruct) {
final SymbolStruct currentParam = (SymbolStruct) currentElement;
final KeywordStruct keyName = getKeywordStruct(currentParam.getName());
final boolean isSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(currentParam));
Binding binding = new Binding(currentParam, CommonLispSymbols.T);
if (isSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
final String paramName = currentParam.getName();
final String customSuppliedPName = paramName + "-P-" + System.nanoTime();
final PackageStruct currentParamPackage = currentParam.getSymbolPackage();
final SymbolStruct customSuppliedPCurrent = currentParamPackage.intern(customSuppliedPName).getSymbol();
final boolean isSuppliedPSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(customSuppliedPCurrent));
binding = new Binding(customSuppliedPCurrent, CommonLispSymbols.T);
if (isSuppliedPSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
final SuppliedPParameter suppliedPBinding = new SuppliedPParameter(customSuppliedPCurrent, isSuppliedPSpecial);
final KeyParameter keyBinding = new KeyParameter(currentParam, null, NILStruct.INSTANCE, isSpecial, keyName, suppliedPBinding);
keyBindings.add(keyBinding);
} else if (currentElement instanceof ListStruct) {
final ListStruct currentParam = (ListStruct) currentElement;
final long currentParamLength = currentParam.length().toJavaPLong();
if ((currentParamLength < 1) || (currentParamLength > 3)) {
if (isDestructuringAllowed) {
final String destructuringName = "DestructuringSymbolName-" + System.nanoTime();
final SymbolStruct varNameCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol();
final SymbolStruct varKeyNameCurrent = getKeywordStruct(varNameCurrent.getName());
final ListStruct destructuringFormList = (ListStruct) currentElement;
final DestructuringLambdaList destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement);
final String customSuppliedPName = destructuringName + "-P-" + System.nanoTime();
final SymbolStruct customSuppliedPCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(customSuppliedPName).getSymbol();
final SuppliedPParameter suppliedPBinding = new SuppliedPParameter(customSuppliedPCurrent);
final KeyParameter keyBinding = new KeyParameter(varNameCurrent, destructuringForm, NILStruct.INSTANCE, false, varKeyNameCurrent, suppliedPBinding);
keyBindings.add(keyBinding);
} else {
throw new ProgramErrorException("LambdaList &key parameters must have between 1 and 3 parameters: " + currentParam);
}
} else {
final Iterator<LispStruct> currentIterator = currentParam.iterator();
final LispStruct firstInCurrent = currentIterator.next();
final LispStruct secondInCurrent;
if (currentIterator.hasNext()) {
secondInCurrent = currentIterator.next();
} else {
secondInCurrent = NILStruct.INSTANCE;
}
final LispStruct thirdInCurrent;
if (currentIterator.hasNext()) {
thirdInCurrent = currentIterator.next();
} else {
thirdInCurrent = NILStruct.INSTANCE;
}
final SymbolStruct varNameCurrent;
final SymbolStruct varKeyNameCurrent;
DestructuringLambdaList destructuringForm = null;
if (firstInCurrent instanceof SymbolStruct) {
varNameCurrent = (SymbolStruct) firstInCurrent;
varKeyNameCurrent = getKeywordStruct(varNameCurrent.getName());
} else if (firstInCurrent instanceof ListStruct) {
final ListStruct currentVar = (ListStruct) firstInCurrent;
final long currentVarLength = currentVar.length().toJavaPLong();
if (currentVarLength == 2) {
final LispStruct firstInCurrentVar = currentVar.car();
if (firstInCurrentVar instanceof SymbolStruct) {
varKeyNameCurrent = (SymbolStruct) firstInCurrentVar;
} else {
throw new ProgramErrorException("LambdaList &key var name list key-name parameters must be a symbol: " + firstInCurrentVar);
}
final LispStruct secondInCurrentVar = ((ListStruct) currentVar.cdr()).car();
if (!(secondInCurrentVar instanceof SymbolStruct)) {
throw new ProgramErrorException("LambdaList &key var name list name parameters must be a symbol: " + secondInCurrentVar);
}
varNameCurrent = (SymbolStruct) secondInCurrentVar;
} else {
if (isDestructuringAllowed) {
final String destructuringName = "DestructuringSymbolName-" + System.nanoTime();
varNameCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol();
varKeyNameCurrent = getKeywordStruct(varNameCurrent.getName());
final ListStruct destructuringFormList = (ListStruct) currentElement;
destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement);
} else {
throw new ProgramErrorException("LambdaList &key var name list parameters must have 2 parameters: " + currentVar);
}
}
} else {
throw new ProgramErrorException("LambdaList &key var name parameters must be a symbol or a list: " + firstInCurrent);
}
LispStruct initForm = NILStruct.INSTANCE;
if (!secondInCurrent.eq(NILStruct.INSTANCE)) {
initForm = secondInCurrent;
}
final LispStruct parameterValueInitForm = FormAnalyzer.analyze(initForm, environment);
final boolean isSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(varNameCurrent));
Binding binding = new Binding(varNameCurrent, CommonLispSymbols.T);
if (isSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
final SuppliedPParameter suppliedPBinding;
if (thirdInCurrent.eq(NILStruct.INSTANCE)) {
final String paramName = varNameCurrent.getName();
final String customSuppliedPName = paramName + "-P-" + System.nanoTime();
final PackageStruct currentParamPackage = varNameCurrent.getSymbolPackage();
final SymbolStruct customSuppliedPCurrent = currentParamPackage.intern(customSuppliedPName).getSymbol();
final boolean isSuppliedPSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(customSuppliedPCurrent));
binding = new Binding(customSuppliedPCurrent, CommonLispSymbols.T);
if (isSuppliedPSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
suppliedPBinding = new SuppliedPParameter(customSuppliedPCurrent, isSuppliedPSpecial);
} else {
if (!(thirdInCurrent instanceof SymbolStruct)) {
throw new ProgramErrorException("LambdaList &key supplied-p parameters must be a symbol: " + thirdInCurrent);
}
final SymbolStruct suppliedPCurrent = (SymbolStruct) thirdInCurrent;
final boolean isSuppliedPSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(suppliedPCurrent));
binding = new Binding(suppliedPCurrent, CommonLispSymbols.T);
if (isSuppliedPSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
suppliedPBinding = new SuppliedPParameter(suppliedPCurrent, isSuppliedPSpecial);
}
final KeyParameter keyBinding = new KeyParameter(varNameCurrent, destructuringForm, parameterValueInitForm, isSpecial, varKeyNameCurrent, suppliedPBinding);
keyBindings.add(keyBinding);
}
} else {
throw new ProgramErrorException("LambdaList &key parameters must be a symbol or a list: " + currentElement);
}
} while (iterator.hasNext());
return new KeyParseResult(currentElement, keyBindings);
}
public static AuxParseResult parseAuxBindings(final Environment environment,
final Iterator<LispStruct> iterator,
final DeclareStruct declareElement,
final boolean isDestructuringAllowed) {
final List<AuxParameter> auxBindings = new ArrayList<>();
if (!iterator.hasNext()) {
return new AuxParseResult(null, auxBindings);
}
LispStruct currentElement;
do {
currentElement = iterator.next();
if (isLambdaListKeyword(currentElement)) {
return new AuxParseResult(currentElement, auxBindings);
}
if (currentElement instanceof SymbolStruct) {
final SymbolStruct currentParam = (SymbolStruct) currentElement;
final boolean isSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(currentParam));
final Binding binding = new Binding(currentParam, CommonLispSymbols.T);
if (isSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
final AuxParameter auxBinding = new AuxParameter(currentParam, null, NILStruct.INSTANCE, isSpecial);
auxBindings.add(auxBinding);
} else if (currentElement instanceof ListStruct) {
final ListStruct currentParam = (ListStruct) currentElement;
final long currentParamLength = currentParam.length().toJavaPLong();
if ((currentParamLength < 1) || (currentParamLength > 2)) {
if (isDestructuringAllowed) {
final String destructuringName = "DestructuringSymbolName-" + System.nanoTime();
final SymbolStruct varNameCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol();
final ListStruct destructuringFormList = (ListStruct) currentElement;
final DestructuringLambdaList destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement);
final AuxParameter auxBinding = new AuxParameter(varNameCurrent, destructuringForm, NILStruct.INSTANCE);
auxBindings.add(auxBinding);
} else {
throw new ProgramErrorException("LambdaList &aux parameters must have between 1 and 2 parameters: " + currentParam);
}
} else {
final Iterator<LispStruct> currentIterator = currentParam.iterator();
final LispStruct firstInCurrent = currentIterator.next();
final LispStruct secondInCurrent;
if (currentIterator.hasNext()) {
secondInCurrent = currentIterator.next();
} else {
secondInCurrent = NILStruct.INSTANCE;
}
final SymbolStruct varNameCurrent;
DestructuringLambdaList destructuringForm = null;
if (firstInCurrent instanceof SymbolStruct) {
varNameCurrent = (SymbolStruct) firstInCurrent;
} else {
if (isDestructuringAllowed) {
if (firstInCurrent instanceof ListStruct) {
final String destructuringName = "DestructuringSymbolName-" + System.nanoTime();
varNameCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol();
final ListStruct destructuringFormList = (ListStruct) firstInCurrent;
destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement);
} else {
throw new ProgramErrorException("LambdaList &aux var name parameter must be a symbol or a destructuring list: " + firstInCurrent);
}
} else {
throw new ProgramErrorException("LambdaList &aux var name parameters must be a symbol: " + firstInCurrent);
}
}
LispStruct initForm = NILStruct.INSTANCE;
if (!secondInCurrent.eq(NILStruct.INSTANCE)) {
initForm = secondInCurrent;
}
final LispStruct parameterValueInitForm = FormAnalyzer.analyze(initForm, environment);
final boolean isSpecial = declareElement.getSpecialDeclarations()
.stream()
.map(SpecialDeclarationStruct::getVar)
.anyMatch(Predicate.isEqual(varNameCurrent));
final Binding binding = new Binding(varNameCurrent, CommonLispSymbols.T);
if (isSpecial) {
environment.addDynamicBinding(binding);
} else {
environment.addLexicalBinding(binding);
}
final AuxParameter auxBinding = new AuxParameter(varNameCurrent, destructuringForm, parameterValueInitForm, isSpecial);
auxBindings.add(auxBinding);
}
} else {
throw new ProgramErrorException("LambdaList &aux parameters must be a symbol or a list: " + currentElement);
}
} while (iterator.hasNext());
return new AuxParseResult(currentElement, auxBindings);
}
private static boolean isLambdaListKeyword(final LispStruct lispStruct) {
return lispStruct.eq(CompilerConstants.AUX)
|| lispStruct.eq(CompilerConstants.ALLOW_OTHER_KEYS)
|| lispStruct.eq(CompilerConstants.KEY)
|| lispStruct.eq(CompilerConstants.OPTIONAL)
|| lispStruct.eq(CompilerConstants.REST)
|| lispStruct.eq(CompilerConstants.WHOLE)
|| lispStruct.eq(CompilerConstants.ENVIRONMENT)
|| lispStruct.eq(CompilerConstants.BODY);
}
private static KeywordStruct getKeywordStruct(final String symbolName) {
final PackageSymbolStruct symbol = GlobalPackageStruct.KEYWORD.findSymbol(symbolName);
if (symbol.notFound()) {
return KeywordStruct.toLispKeyword(symbolName);
}
// NOTE: This should be a safe cast because we're finding the symbol in the Keyword Package and they are only
// this type of symbol.
return (KeywordStruct) symbol.getSymbol();
}
}
| scodynelson/JCL | jcl-compiler/src/main/java/jcl/compiler/sa/analyzer/lambdalistparser/LambdaListParser.java | Java | lgpl-3.0 | 37,554 |
require 'cirras-management/helper/string-helper'
module CirrASManagement
describe StringHelper do
before(:each) do
@helper = StringHelper.new
end
it "should return true because there is an empty line on the end" do
@helper.is_last_line_empty?("asd\nasd\nasdasd\n").should == true
end
it "should return false because there is an empty line on the end but with whitespaces" do
@helper.is_last_line_empty?("asd\nasd\nasdasd\n ").should == false
end
it "should return false because there is no empty line on the end" do
@helper.is_last_line_empty?("asd\nasd\nasdasd").should == false
end
end
end
| stormgrind/cirras-management | spec/helpers/string-helper-spec.rb | Ruby | lgpl-3.0 | 661 |
/****************************************************************************
**
** Copyright (C) 2016 Christian Gagneraud <chgans@gna.org>
** All rights reserved.
**
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 3 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL3 included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 3 requirements will be met:
** https://www.gnu.org/licenses/lgpl-3.0.html.
**
****************************************************************************/
#include "invalidinstruction.h"
#include "errorinstructionresult.h"
InvalidInstruction::InvalidInstruction(const QString &instructionId, const QString &operationName):
Instruction(instructionId),
m_operationName(operationName)
{
}
InstructionResult *InvalidInstruction::execute(InstructionExecutor *executor) const
{
Q_UNUSED(executor);
return new ErrorInstructionResult(instructionId(), QString("%1: Invalid instruction").arg(m_operationName));
}
QString InvalidInstruction::toString() const
{
return QString("%1: !INVALID_INSTRUCTION!")
.arg(instructionId());
}
| chgans/QtSlim | lib/instructions/invalidinstruction.cpp | C++ | lgpl-3.0 | 1,292 |
/*
* Attr.java
* Copyright (c) Radim Kocman
*/
package org.fit.cssbox.jsdombox.global.core;
import org.fit.cssbox.jsdombox.global.misc.JSAdapterFactory;
import org.fit.cssbox.jsdombox.global.misc.JSAdapter;
import org.fit.cssbox.jsdombox.global.misc.JSAdapterType;
/**
* DOM Interface Attr Adapter
*
* @author Radim Kocman
*/
public class Attr extends Node
{
protected org.w3c.dom.Attr source;
public Attr(org.w3c.dom.Attr source, JSAdapterFactory jsaf)
{
super(source, jsaf);
this.source = source;
}
// DOM Level 1 Implementation
public String getName()
{
return source.getName().toLowerCase();
}
public boolean getSpecified()
{
return source.getSpecified();
}
public String getValue()
{
return source.getValue();
}
public void setValue(String value)
{
source.setValue(value);
jsaf.cssEvent.recomputeStyles(source);
}
// DOM Level 2 Implementation
public JSAdapter getOwnerElement()
{
Object result = source.getOwnerElement();
return jsaf.create(result, JSAdapterType.ELEMENT);
}
}
| Gals42/JSDOMBox | src/main/java/org/fit/cssbox/jsdombox/global/core/Attr.java | Java | lgpl-3.0 | 1,112 |
<?php
namespace pocketmine\network\protocol\v120;
use pocketmine\network\protocol\Info120;
use pocketmine\network\protocol\PEPacket;
class CommandRequestPacket extends PEPacket {
const NETWORK_ID = Info120::COMMAND_REQUEST_PACKET;
const PACKET_NAME = "COMMAND_REQUEST_PACKET";
const TYPE_PLAYER = 0;
const TYPE_COMMAND_BLOCK = 1;
const TYPE_MINECART_COMMAND_BLOCK = 2;
const TYPE_DEV_CONSOLE = 3;
const TYPE_AUTOMATION_PLAYER = 4;
const TYPE_CLIENT_AUTOMATION = 5;
const TYPE_DEDICATED_SERVER = 6;
const TYPE_ENTITY = 7;
const TYPE_VIRTUAL = 8;
const TYPE_GAME_ARGUMENT = 9;
const TYPE_INTERNAL = 10;
/** @var string */
public $command = '';
/** @var unsigned integer */
public $commandType = self::TYPE_PLAYER;
/** @var string */
public $requestId = '';
/** @var integer */
public $playerId = '';
public function decode($playerProtocol) {
$this->getHeader($playerProtocol);
$this->command = $this->getString();
$this->commandType = $this->getVarInt();
$this->requestId = $this->getString();
if ($this->commandType == self::TYPE_DEV_CONSOLE) {
$this->playerId = $this->getSignedVarInt();
}
}
public function encode($playerProtocol) {
}
}
| Apollo-SoftwareTeam/Apollo-Legacy | src/pocketmine/network/protocol/v120/CommandRequestPacket.php | PHP | lgpl-3.0 | 1,192 |
#include "pst05.h"
PST05::PST05(QSettings *settings)
{
this->settings = settings;
qDebug() << "Reading up the device's serial id...";
QFile procInfo("/proc/cpuinfo");
if (!procInfo.open(QFile::ReadOnly))
{
qDebug() << "Failed to read \"/proc/cpuinfo\"";
exit(2);
}
mDeviceId = DEFAULT_DEVICE_ID;
foreach (QByteArray line, procInfo.readAll().split('\n')) {
QList<QByteArray> pair = line.split(':');
if (pair[0].trimmed() == "Serial")
{
mDeviceId = pair[1].trimmed();
}
}
mDeviceId = "raspberry";
qDebug() << "Device ID is: " << mDeviceId;
procInfo.close();
QList<QSerialPortInfo> ports = QSerialPortInfo::availablePorts();
foreach (const QSerialPortInfo &info, ports) {
qDebug() << info.portName();
qDebug() << info.isBusy();
serial = new QSerialPort(info);
break;
}
//serial = new QSerialPort(settings->value("portName", "ttyS0").toString());
if (serial->open(QSerialPort::ReadWrite))
{
serial->setBaudRate((QSerialPort::BaudRate) settings->value("baudRate", QSerialPort::Baud9600).toInt());
serial->setDataBits((QSerialPort::DataBits) settings->value("dataBits", QSerialPort::Data8).toInt());
serial->setFlowControl((QSerialPort::FlowControl) settings->value("flowControl", QSerialPort::NoFlowControl).toInt());
serial->setParity((QSerialPort::Parity) settings->value("parity", QSerialPort::NoParity).toInt());
serial->setStopBits((QSerialPort::StopBits) settings->value("stopBits", QSerialPort::OneStop).toInt());
qDebug() << serial->baudRate();
qDebug() << serial->dataBits();
qDebug() << serial->flowControl();
qDebug() << serial->parity();
qDebug() << serial->stopBits();
}
}
PST05::~PST05()
{
if (serial)
{
if (serial->isOpen()) serial->close();
serial->deleteLater();
}
}
void PST05::writeTestDataToSerial(uint cbytes)
{
QByteArray data;
qsrand(QTime::currentTime().msec());
for (uint i = 0; i < cbytes; i++)
{
data.append((char) (qrand() % 256));
}
data[2] = 49; // data bytes count...
serial->write(data);
serial->flush();
}
// Possibly make it asynchronously some day
PST05Data PST05::queryDevice()
{
char res;
char queryAddress[] = {(char) 0xFA};
char queryCommand[] = {(char) 0x82};
if (!serial->isOpen()) return PST05Data(true);
// address
serial->write(queryAddress, 1);
serial->flush();
if (!serial->waitForReadyRead(30000))
{
// writeTestDataToSerial(54);
goto rs232read;
}
serial->read(&res, 1);
if (res != queryAddress[0])
{
// writeTestDataToSerial(54);
goto rs232read;
}
// command
serial->write(queryCommand, 1);
serial->flush();
if (!serial->waitForReadyRead(30000))
{
// writeTestDataToSerial(54);
goto rs232read;
}
serial->read(&res, 1);
if (res != queryCommand[0])
{
// writeTestDataToSerial(54);
goto rs232read;
}
rs232read:
QByteArray data;
uint bytesRemaining = 5, i = 0;
// Wait 2 seconds for data at MOST
while (serial->waitForReadyRead(60000))
{
QByteArray read = serial->read(bytesRemaining);
data += read;
bytesRemaining -= read.size();
if (i++ == 0 && data.size() > 3)
{
// The address or the command returned is wrong (first 2 bits are 0)
if (data[0] != (queryAddress[0] & (char) 63)) break;
if (data[1] != (queryCommand[0] & (char) 63)) break;
// The third byte contains the number of bytes that will be available after the first 4
bytesRemaining += data[2];
}
qDebug() << QString::number(bytesRemaining);
if (!bytesRemaining) break;
}
// The data wasn't received OR incorrect checksum (not added)
if (bytesRemaining > 0 || !checkCRC(data))
{
return PST05Data(true);
}
// We got it all
data = data.right(data.size() - 5);
PST05Data pstdata(false);
pstdata.U1 = (((float)data[0] * 128 + (float)data[1]) / 10 ) * 220 / 57.7;
pstdata.U2 = (((float)data[2] * 128 + (float)data[3]) / 10 ) * 220 / 57.7 ;
pstdata.U3 = (((float)data[4] * 128 + (float)data[5]) / 10 ) * 220 / 57.7;
pstdata.I1 = ((float)data[6] * 128 + (float)data[7]) / 1000;
pstdata.I2 = ((float)data[8] * 128 + (float)data[9]) / 1000;
pstdata.I3 = ((float)data[10] * 128 + (float)data[11]) / 1000;
pstdata.P = ((float)data[12] * 128 + (float)data[13]) / 10;
if (pstdata.P > 64*128) pstdata.P -= 128*128;
pstdata.Q = ((float)data[14] * 128 + (float)data[15]) / 10;
if (pstdata.Q > 64*128) pstdata.Q -= 128*128;
pstdata.F = ((float)data[16] * 128 + (float)data[17]) / 100;
return pstdata;
}
QByteArray PST05::deviceId()
{
return mDeviceId;
}
bool PST05::checkCRC(const QByteArray &data) {
unsigned short calcCRC = 0;
for (int i = 5; i < data.length(); i++)
{
calcCRC += data[i];
}
QByteArray crc((const char *) calcCRC, 2);
return data.mid(3, 2) == crc;
}
| nasplachkov/remote-electricity-monitoring-rpi | src/pst05.cpp | C++ | lgpl-3.0 | 5,229 |
package com.sqsoft.mars.weixin.client.cgibin.template;
import java.io.Serializable;
import org.springframework.http.HttpMethod;
import com.sqsoft.mars.core.common.utils.JsonUtils;
import com.sqsoft.mars.weixin.client.WeixinRequest;
/**
* 设置所属行业
* @author whai888
*
*/
public class ApiSetIndustryRequest implements WeixinRequest<ApiSetIndustryResponse>, Serializable{
public ApiSetIndustryRequest(ApiSetIndustryPostVo apiSetIndustryPostVo) {
super();
this.apiSetIndustryPostVo = apiSetIndustryPostVo;
}
/**
*
*/
private static final long serialVersionUID = 1L;
private ApiSetIndustryPostVo apiSetIndustryPostVo ;
@Override
public HttpMethod getHttpMethod() {
// TODO Auto-generated method stub
return HttpMethod.POST;
}
@Override
public String getMethodScope() {
// TODO Auto-generated method stub
return null;
}
@Override
public Class<ApiSetIndustryResponse> getResponseClass() {
// TODO Auto-generated method stub
return ApiSetIndustryResponse.class;
}
@Override
public Object getRequestMessage() {
// TODO Auto-generated method stub
return JsonUtils.toJson(apiSetIndustryPostVo);
}
public ApiSetIndustryPostVo getApiSetIndustryPostVo() {
return apiSetIndustryPostVo;
}
public void setApiSetIndustryPostVo(ApiSetIndustryPostVo apiSetIndustryPostVo) {
this.apiSetIndustryPostVo = apiSetIndustryPostVo;
}
}
| anndy201/mars-framework | com.sqsoft.mars.weixin.client/src/main/java/com/sqsoft/mars/weixin/client/cgibin/template/ApiSetIndustryRequest.java | Java | lgpl-3.0 | 1,454 |
/*
This source file is part of KBEngine
For the latest info, see http://www.kbengine.org/
Copyright (c) 2008-2016 KBEngine.
KBEngine is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
KBEngine is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with KBEngine. If not, see <http://www.gnu.org/licenses/>.
*/
#include "forward_messagebuffer.h"
#include "network/bundle.h"
#include "network/channel.h"
#include "network/event_dispatcher.h"
#include "network/network_interface.h"
namespace KBEngine {
KBE_SINGLETON_INIT(ForwardComponent_MessageBuffer);
KBE_SINGLETON_INIT(ForwardAnywhere_MessageBuffer);
//-------------------------------------------------------------------------------------
ForwardComponent_MessageBuffer::ForwardComponent_MessageBuffer(Network::NetworkInterface & networkInterface) :
Task(),
networkInterface_(networkInterface),
start_(false)
{
// dispatcher().addTask(this);
}
//-------------------------------------------------------------------------------------
ForwardComponent_MessageBuffer::~ForwardComponent_MessageBuffer()
{
//dispatcher().cancelTask(this);
clear();
}
//-------------------------------------------------------------------------------------
void ForwardComponent_MessageBuffer::clear()
{
MSGMAP::iterator iter = pMap_.begin();
for(; iter != pMap_.end(); ++iter)
{
std::vector<ForwardItem*>::iterator itervec = iter->second.begin();
for(; itervec != iter->second.end(); ++itervec)
{
SAFE_RELEASE((*itervec)->pBundle);
SAFE_RELEASE((*itervec)->pHandler);
SAFE_RELEASE((*itervec));
}
}
pMap_.clear();
}
//-------------------------------------------------------------------------------------
Network::EventDispatcher & ForwardComponent_MessageBuffer::dispatcher()
{
return networkInterface_.dispatcher();
}
//-------------------------------------------------------------------------------------
void ForwardComponent_MessageBuffer::push(COMPONENT_ID componentID, ForwardItem* pHandler)
{
if(!start_)
{
dispatcher().addTask(this);
start_ = true;
}
pMap_[componentID].push_back(pHandler);
}
//-------------------------------------------------------------------------------------
bool ForwardComponent_MessageBuffer::process()
{
if(pMap_.size() <= 0)
{
start_ = false;
return false;
}
MSGMAP::iterator iter = pMap_.begin();
for(; iter != pMap_.end(); )
{
Components::ComponentInfos* cinfos = Components::getSingleton().findComponent(iter->first);
if(cinfos == NULL || cinfos->pChannel == NULL)
return true;
// 如果是mgr类组件需要判断是否已经初始化完成
if(g_componentType == CELLAPPMGR_TYPE || g_componentType == BASEAPPMGR_TYPE)
{
if(cinfos->state != COMPONENT_STATE_RUN)
return true;
}
if(iter->second.size() == 0)
{
pMap_.erase(iter++);
}
else
{
int icount = 5;
std::vector<ForwardItem*>::iterator itervec = iter->second.begin();
for(; itervec != iter->second.end(); )
{
if (!(*itervec)->isOK())
return true;
cinfos->pChannel->send((*itervec)->pBundle);
(*itervec)->pBundle = NULL;
if((*itervec)->pHandler != NULL)
{
(*itervec)->pHandler->process();
SAFE_RELEASE((*itervec)->pHandler);
}
SAFE_RELEASE((*itervec));
itervec = iter->second.erase(itervec);
if(--icount <= 0)
return true;
}
DEBUG_MSG(fmt::format("ForwardComponent_MessageBuffer::process(): size:{}.\n", iter->second.size()));
iter->second.clear();
++iter;
}
}
return true;
}
//-------------------------------------------------------------------------------------
ForwardAnywhere_MessageBuffer::ForwardAnywhere_MessageBuffer(Network::NetworkInterface & networkInterface, COMPONENT_TYPE forwardComponentType) :
Task(),
networkInterface_(networkInterface),
forwardComponentType_(forwardComponentType),
start_(false)
{
// dispatcher().addTask(this);
}
//-------------------------------------------------------------------------------------
ForwardAnywhere_MessageBuffer::~ForwardAnywhere_MessageBuffer()
{
//dispatcher().cancelTask(this);
clear();
}
//-------------------------------------------------------------------------------------
void ForwardAnywhere_MessageBuffer::clear()
{
std::vector<ForwardItem*>::iterator iter = pBundles_.begin();
for(; iter != pBundles_.end(); )
{
SAFE_RELEASE((*iter)->pBundle);
SAFE_RELEASE((*iter)->pHandler);
}
pBundles_.clear();
}
//-------------------------------------------------------------------------------------
Network::EventDispatcher & ForwardAnywhere_MessageBuffer::dispatcher()
{
return networkInterface_.dispatcher();
}
//-------------------------------------------------------------------------------------
void ForwardAnywhere_MessageBuffer::push(ForwardItem* pHandler)
{
if(!start_)
{
dispatcher().addTask(this);
start_ = true;
}
pBundles_.push_back(pHandler);
}
//-------------------------------------------------------------------------------------
bool ForwardAnywhere_MessageBuffer::process()
{
if(pBundles_.size() <= 0)
{
start_ = false;
return false;
}
Components::COMPONENTS& cts = Components::getSingleton().getComponents(forwardComponentType_);
size_t idx = 0;
if(cts.size() > 0)
{
bool hasEnabled = (g_componentType != CELLAPPMGR_TYPE && g_componentType != BASEAPPMGR_TYPE);
Components::COMPONENTS::iterator ctiter = cts.begin();
for(; ctiter != cts.end(); ++ctiter)
{
// 必须所有的组件频道都被设置,如果不是则等待。
if((*ctiter).pChannel == NULL)
return true;
if((*ctiter).state == COMPONENT_STATE_RUN)
hasEnabled = true;
}
// 必须有可用的进程
if(!hasEnabled)
return true;
// 最多每个tick处理5个
int icount = 5;
std::vector<ForwardItem*>::iterator iter = pBundles_.begin();
for (; iter != pBundles_.end(); ++iter)
{
if ((*iter)->isOK())
break;
}
// 必须所有的ForwardItem都处于ok状态
// 何时不处于ok状态?例如:cellappmgr中的ForwardItem需要等待cellapp初始化完毕之后才ok
if (iter == pBundles_.end())
return true;
for(; iter != pBundles_.end(); )
{
Network::Channel* pChannel = NULL;
if(g_componentType != CELLAPPMGR_TYPE && g_componentType != BASEAPPMGR_TYPE)
{
pChannel = cts[idx++].pChannel;
if(idx >= cts.size())
idx = 0;
}
else
{
while(pChannel == NULL)
{
if(cts[idx].state != COMPONENT_STATE_RUN)
{
if(++idx >= cts.size())
idx = 0;
continue;
}
pChannel = cts[idx++].pChannel;
if(idx >= cts.size())
idx = 0;
}
}
pChannel->send((*iter)->pBundle);
(*iter)->pBundle = NULL;
if((*iter)->pHandler != NULL)
{
(*iter)->pHandler->process();
SAFE_RELEASE((*iter)->pHandler);
}
SAFE_RELEASE((*iter));
iter = pBundles_.erase(iter);
if(--icount <= 0)
return true;
}
DEBUG_MSG(fmt::format("ForwardAnywhere_MessageBuffer::process(): size:{}.\n", pBundles_.size()));
start_ = false;
return false;
}
return true;
}
//-------------------------------------------------------------------------------------
}
| Orav/kbengine | kbe/src/lib/server/forward_messagebuffer.cpp | C++ | lgpl-3.0 | 7,868 |
package org.lolongo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A container of Functions.
*
* @author Xavier Courangon
*/
public class FunctionContainer implements Iterable<Function> {
private static Logger logger = LoggerFactory.getLogger(FunctionContainer.class);
final List<Function> functions = new ArrayList<>();
public FunctionContainer() {
}
// public FunctionContainer(Collection<Function> functions) {
// for (final Function function : functions) {
// this.functions.add(function);
// }
// }
public void add(Function function) {
if (function == null) {
throw new IllegalArgumentException("function is null");
} else {
logger.debug("adding Function {} into {}", function, this);
functions.add(function);
}
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer(getClass().getSimpleName());
return sb.toString();
}
@Override
public Iterator<Function> iterator() {
return functions.iterator();
};
}
| xcourangon/lolongo | src/main/java/org/lolongo/FunctionContainer.java | Java | lgpl-3.0 | 1,080 |
/*
* Copyright 2000-2004 The Apache Software Foundation
*
* 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 benchmark.bcel.classfile;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import benchmark.bcel.Constants;
/**
* This class represents the table of exceptions that are thrown by a
* method. This attribute may be used once per method. The name of
* this class is <em>ExceptionTable</em> for historical reasons; The
* Java Virtual Machine Specification, Second Edition defines this
* attribute using the name <em>Exceptions</em> (which is inconsistent
* with the other classes).
*
* @version $Id: ExceptionTable.java 386056 2006-03-15 11:31:56Z tcurdt $
* @author <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A>
* @see Code
*/
public final class ExceptionTable extends Attribute {
private int number_of_exceptions; // Table of indices into
private int[] exception_index_table; // constant pool
/**
* Initialize from another object. Note that both objects use the same
* references (shallow copy). Use copy() for a physical copy.
*/
public ExceptionTable(ExceptionTable c) {
this(c.getNameIndex(), c.getLength(), c.getExceptionIndexTable(), c.getConstantPool());
}
/**
* @param name_index Index in constant pool
* @param length Content length in bytes
* @param exception_index_table Table of indices in constant pool
* @param constant_pool Array of constants
*/
public ExceptionTable(int name_index, int length, int[] exception_index_table,
ConstantPool constant_pool) {
super(Constants.ATTR_EXCEPTIONS, name_index, length, constant_pool);
setExceptionIndexTable(exception_index_table);
}
/**
* Construct object from file stream.
* @param name_index Index in constant pool
* @param length Content length in bytes
* @param file Input stream
* @param constant_pool Array of constants
* @throws IOException
*/
ExceptionTable(int name_index, int length, DataInputStream file, ConstantPool constant_pool)
throws IOException {
this(name_index, length, (int[]) null, constant_pool);
number_of_exceptions = file.readUnsignedShort();
exception_index_table = new int[number_of_exceptions];
for (int i = 0; i < number_of_exceptions; i++) {
exception_index_table[i] = file.readUnsignedShort();
}
}
/**
* Called by objects that are traversing the nodes of the tree implicitely
* defined by the contents of a Java class. I.e., the hierarchy of methods,
* fields, attributes, etc. spawns a tree of objects.
*
* @param v Visitor object
*/
public void accept( Visitor v ) {
v.visitExceptionTable(this);
}
/**
* Dump exceptions attribute to file stream in binary format.
*
* @param file Output file stream
* @throws IOException
*/
public final void dump( DataOutputStream file ) throws IOException {
super.dump(file);
file.writeShort(number_of_exceptions);
for (int i = 0; i < number_of_exceptions; i++) {
file.writeShort(exception_index_table[i]);
}
}
/**
* @return Array of indices into constant pool of thrown exceptions.
*/
public final int[] getExceptionIndexTable() {
return exception_index_table;
}
/**
* @return Length of exception table.
*/
public final int getNumberOfExceptions() {
return number_of_exceptions;
}
/**
* @return class names of thrown exceptions
*/
public final String[] getExceptionNames() {
String[] names = new String[number_of_exceptions];
for (int i = 0; i < number_of_exceptions; i++) {
names[i] = constant_pool.getConstantString(exception_index_table[i],
Constants.CONSTANT_Class).replace('/', '.');
}
return names;
}
/**
* @param exception_index_table the list of exception indexes
* Also redefines number_of_exceptions according to table length.
*/
public final void setExceptionIndexTable( int[] exception_index_table ) {
this.exception_index_table = exception_index_table;
number_of_exceptions = (exception_index_table == null) ? 0 : exception_index_table.length;
}
/**
* @return String representation, i.e., a list of thrown exceptions.
*/
public final String toString() {
StringBuffer buf = new StringBuffer("");
String str;
for (int i = 0; i < number_of_exceptions; i++) {
str = constant_pool.getConstantString(exception_index_table[i],
Constants.CONSTANT_Class);
buf.append(Utility.compactClassName(str, false));
if (i < number_of_exceptions - 1) {
buf.append(", ");
}
}
return buf.toString();
}
/**
* @return deep copy of this attribute
*/
public Attribute copy( ConstantPool _constant_pool ) {
ExceptionTable c = (ExceptionTable) clone();
if (exception_index_table != null) {
c.exception_index_table = new int[exception_index_table.length];
System.arraycopy(exception_index_table, 0, c.exception_index_table, 0,
exception_index_table.length);
}
c.constant_pool = _constant_pool;
return c;
}
}
| Xyene/JBL | src/test/java/benchmark/bcel/classfile/ExceptionTable.java | Java | lgpl-3.0 | 6,030 |
/*
* This file is part of the Voodoo Shader Framework.
*
* Copyright (c) 2010-2013 by Sean Sube
*
* The Voodoo Shader Framework is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option)
* any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to
* the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 US
*
* Support and more information may be found at
* http://www.voodooshader.com
* or by contacting the lead developer at
* peachykeen@voodooshader.com
*/
#pragma once
#include "VoodooInternal.hpp"
namespace VoodooShader
{
/**
* @clsid e6f312a0-05af-11e1-9e05-005056c00008
*/
VOODOO_CLASS(VSPluginServer, IPluginServer, ({0xA0, 0x12, 0xF3, 0xE6, 0xAF, 0x05, 0xE1, 0x11, 0x9E, 0x05, 0x00, 0x50, 0x56, 0xC0, 0x00, 0x08}))
{
public:
VSPluginServer();
VOODOO_METHOD_(uint32_t, AddRef)() CONST;
VOODOO_METHOD_(uint32_t, Release)() CONST;
VOODOO_METHOD(QueryInterface)(_In_ CONST Uuid refid, _Outptr_result_maybenull_ IObject ** ppOut);
VOODOO_METHOD_(String, ToString)() CONST;
VOODOO_METHOD_(ICore *, GetCore)() CONST;
VOODOO_METHOD_(IPlugin *, GetPlugin)(_In_ CONST String & name) CONST;
VOODOO_METHOD_(IPlugin *, GetPlugin)(_In_ CONST Uuid libid) CONST;
VOODOO_METHOD_(bool, IsLoaded)(_In_ CONST String & name) CONST;
VOODOO_METHOD_(bool, IsLoaded)(_In_ CONST Uuid & libid) CONST;
VOODOO_METHOD(LoadPath)(_In_ ICore * pCore, _In_ CONST String & path, _In_ CONST String & filter);
VOODOO_METHOD(LoadPlugin)(_In_ ICore * pCore, _In_ IFile * pFile);
VOODOO_METHOD(LoadPlugin)(_In_ ICore * pCore, _In_ CONST String & name);
VOODOO_METHOD(UnloadPlugin)(_In_ ICore * pCore, _In_ CONST String & name);
VOODOO_METHOD(UnloadPlugin)(_In_ ICore * pCore, _In_ CONST Uuid libid);
VOODOO_METHOD_(bool, ClassExists)(_In_ CONST Uuid refid) CONST;
VOODOO_METHOD_(bool, ClassExists)(_In_ CONST String & name) CONST;
_Check_return_ VOODOO_METHOD_(IObject *, CreateObject)(_In_ ICore * pCore, _In_ CONST Uuid refid) CONST;
_Check_return_ VOODOO_METHOD_(IObject *, CreateObject)(_In_ ICore * pCore, _In_ CONST String & name) CONST;
private:
// Private these to prevent copying internally (external libs never will).
VSPluginServer(CONST VSPluginServer & other);
VSPluginServer & operator=(CONST VSPluginServer & other);
~VSPluginServer();
mutable uint32_t m_Refs;
LoggerRef m_Logger;
ParserRef m_Parser;
StrongPluginMap m_Plugins;
StrongNameMap m_PluginNames;
ClassMap m_Classes;
StrongNameMap m_ClassNames;
};
}
| ssube/VoodooShader | Framework/Core/VSPluginServer.hpp | C++ | lgpl-3.0 | 3,214 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ricloud")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ricloud")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d07387d1-c3c0-44c6-86a9-2b4e889b42cf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| reincubate/ricloud-csharp | Properties/AssemblyInfo.cs | C# | lgpl-3.0 | 1,390 |
package org.protocoderrunner.apprunner;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.os.Looper;
import android.support.v4.app.NotificationCompat;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;
import org.protocoderrunner.R;
import org.protocoderrunner.apprunner.api.PApp;
import org.protocoderrunner.apprunner.api.PBoards;
import org.protocoderrunner.apprunner.api.PConsole;
import org.protocoderrunner.apprunner.api.PDashboard;
import org.protocoderrunner.apprunner.api.PDevice;
import org.protocoderrunner.apprunner.api.PFileIO;
import org.protocoderrunner.apprunner.api.PMedia;
import org.protocoderrunner.apprunner.api.PNetwork;
import org.protocoderrunner.apprunner.api.PProtocoder;
import org.protocoderrunner.apprunner.api.PSensors;
import org.protocoderrunner.apprunner.api.PUI;
import org.protocoderrunner.apprunner.api.PUtil;
import org.protocoderrunner.apprunner.api.other.WhatIsRunning;
import org.protocoderrunner.events.Events;
import org.protocoderrunner.project.Project;
import org.protocoderrunner.project.ProjectManager;
import org.protocoderrunner.utils.MLog;
import de.greenrobot.event.EventBus;
//stopService
//stopSelf
public class AppRunnerService extends Service {
private static final String SERVICE_CLOSE = "service_close";
private AppRunnerInterpreter interp;
private final String TAG = "AppRunnerService";
private Project currentProject;
public PApp pApp;
public PBoards pBoards;
public PConsole pConsole;
public PDashboard pDashboard;
public PDevice pDevice;
public PFileIO pFileIO;
public PMedia pMedia;
public PNetwork pNetwork;
public PProtocoder pProtocoder;
public PSensors pSensors;
public PUI pUi;
public PUtil pUtil;
private WindowManager windowManager;
private RelativeLayout parentScriptedLayout;
private RelativeLayout mainLayout;
private BroadcastReceiver mReceiver;
private NotificationManager mNotifManager;
private PendingIntent mRestartPendingIntent;
private Toast mToast;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Can be called twice
interp = new AppRunnerInterpreter(this);
interp.createInterpreter(false);
pApp = new PApp(this);
//pApp.initForParentFragment(this);
pBoards = new PBoards(this);
pConsole = new PConsole(this);
pDashboard = new PDashboard(this);
pDevice = new PDevice(this);
//pDevice.initForParentFragment(this);
pFileIO = new PFileIO(this);
pMedia = new PMedia(this);
//pMedia.initForParentFragment(this);
pNetwork = new PNetwork(this);
//pNetwork.initForParentFragment(this);
pProtocoder = new PProtocoder(this);
pSensors = new PSensors(this);
//pSensors.initForParentFragment(this);
pUi = new PUI(this);
pUi.initForParentService(this);
//pUi.initForParentFragment(this);
pUtil = new PUtil(this);
interp.interpreter.addObjectToInterface("app", pApp);
interp.interpreter.addObjectToInterface("boards", pBoards);
interp.interpreter.addObjectToInterface("console", pConsole);
interp.interpreter.addObjectToInterface("dashboard", pDashboard);
interp.interpreter.addObjectToInterface("device", pDevice);
interp.interpreter.addObjectToInterface("fileio", pFileIO);
interp.interpreter.addObjectToInterface("media", pMedia);
interp.interpreter.addObjectToInterface("network", pNetwork);
interp.interpreter.addObjectToInterface("protocoder", pProtocoder);
interp.interpreter.addObjectToInterface("sensors", pSensors);
interp.interpreter.addObjectToInterface("ui", pUi);
interp.interpreter.addObjectToInterface("util", pUtil);
mainLayout = initLayout();
String projectName = intent.getStringExtra(Project.NAME);
String projectFolder = intent.getStringExtra(Project.FOLDER);
currentProject = ProjectManager.getInstance().get(projectFolder, projectName);
ProjectManager.getInstance().setCurrentProject(currentProject);
MLog.d(TAG, "launching " + projectName + " in " + projectFolder);
AppRunnerSettings.get().project = currentProject;
String script = ProjectManager.getInstance().getCode(currentProject);
interp.evalFromService(script);
//audio
//AudioManager audio = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
//int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
//this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
boolean isTouchable = true;
int touchParam;
if (isTouchable) {
touchParam = WindowManager.LayoutParams.TYPE_PHONE;
} else {
touchParam = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
}
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
touchParam,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 0;
windowManager.addView(mainLayout, params);
// TEST
//if (!EventBus.getDefault().isRegistered(this)) {
// EventBus.getDefault().register(this);
//}
mNotifManager = (NotificationManager) AppRunnerService.this.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = (int) Math.ceil(100000 * Math.random());
createNotification(notificationId, projectFolder, projectName);
//just in case it crash
Intent restartIntent = new Intent("org.protocoder.LauncherActivity"); //getApplicationContext(), AppRunnerActivity.class);
restartIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
restartIntent.putExtra("wasCrash", true);
// intent.setPackage("org.protocoder");
//intent.setClassName("org.protocoder", "MainActivity");
mRestartPendingIntent = PendingIntent.getActivity(AppRunnerService.this, 0, restartIntent, 0);
mToast = Toast.makeText(AppRunnerService.this, "Crash :(", Toast.LENGTH_LONG);
return Service.START_NOT_STICKY;
}
private void createNotification(final int notificationId, String scriptFolder, String scriptName) {
IntentFilter filter = new IntentFilter();
filter.addAction(SERVICE_CLOSE);
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SERVICE_CLOSE)) {
AppRunnerService.this.stopSelf();
mNotifManager.cancel(notificationId);
}
}
};
registerReceiver(mReceiver, filter);
//RemoteViews remoteViews = new RemoteViews(getPackageName(),
// R.layout.widget);
Intent stopIntent = new Intent(SERVICE_CLOSE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, stopIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.app_icon)
.setContentTitle(scriptName).setContentText("Running service: " + scriptFolder + " > " + scriptName)
.setOngoing(false)
.addAction(R.drawable.protocoder_icon, "stop", pendingIntent)
.setDeleteIntent(pendingIntent);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, AppRunnerActivity.class);
// The stack builder object will contain an artificial back stack for
// navigating backward from the Activity leads out your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(AppRunnerActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(this.NOTIFICATION_SERVICE);
mNotificationManager.notify(notificationId, mBuilder.build());
Thread.setDefaultUncaughtExceptionHandler(handler);
}
Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(AppRunnerService.this, "lalll", Toast.LENGTH_LONG);
Looper.loop();
}
}.start();
// handlerToast.post(runnable);
AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mRestartPendingIntent);
mNotifManager.cancelAll();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
throw new RuntimeException(ex);
}
};
public void addScriptedLayout(RelativeLayout scriptedUILayout) {
parentScriptedLayout.addView(scriptedUILayout);
}
public RelativeLayout initLayout() {
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
// set the parent
parentScriptedLayout = new RelativeLayout(this);
parentScriptedLayout.setLayoutParams(layoutParams);
parentScriptedLayout.setGravity(Gravity.BOTTOM);
parentScriptedLayout.setBackgroundColor(getResources().getColor(R.color.transparent));
return parentScriptedLayout;
}
@Override
public IBinder onBind(Intent intent) {
// TODO for communication return IBinder implementation
return null;
}
@Override
public void onCreate() {
super.onCreate();
MLog.d(TAG, "onCreate");
// interp.callJsFunction("onCreate");
// its called only once
}
@Override
public void onDestroy() {
super.onDestroy();
MLog.d(TAG, "onDestroy");
interp.callJsFunction("onDestroy");
windowManager.removeView(mainLayout);
unregisterReceiver(mReceiver);
WhatIsRunning.getInstance().stopAll();
interp = null;
//EventBus.getDefault().unregister(this);
}
public void onEventMainThread(Events.ProjectEvent evt) {
// Using transaction so the view blocks
MLog.d(TAG, "event -> " + evt.getAction());
if (evt.getAction() == "stop") {
stopSelf();
}
}
// execute lines
public void onEventMainThread(Events.ExecuteCodeEvent evt) {
String code = evt.getCode(); // .trim();
MLog.d(TAG, "event -> q " + code);
interp.evalFromService(code);
}
} | josejuansanchez/protocoder-mvd | protocoder_apprunner/src/main/java/org/protocoderrunner/apprunner/AppRunnerService.java | Java | lgpl-3.0 | 11,875 |
/*
* descripten - ECMAScript to native compiler
* Copyright (C) 2011-2014 Christian Kindahl
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "conversion.hh"
#include "error.hh"
#include "frame.hh"
#include "global.hh"
#include "property.hh"
#include "prototype.hh"
#include "standard.hh"
#include "utility.hh"
EsFunction::NativeFunction EsError::default_fun_ = es_std_err;
EsFunction *EsError::default_constr_ = NULL;
EsObject *EsError::prototype()
{
return es_proto_err();
}
EsError::EsError()
: name_(_ESTR("Error")) // VERIFIED: 15.11.4.2
{
}
EsError::EsError(const EsString *message)
: name_(_ESTR("Error"))
, message_(message)
{
}
EsError::EsError(const EsString *name, const EsString *message)
: name_(name)
, message_(message)
{
}
EsError::~EsError()
{
}
void EsError::make_proto()
{
prototype_ = es_proto_obj(); // VERIFIED: 15.11.4
class_ = _USTR("Error"); // VERIFIED: 15.11.4
extensible_ = true;
// 15.11.4
define_new_own_property(property_keys.constructor,
EsPropertyDescriptor(false, true, true,
EsValue::from_obj(default_constr()))); // VERIFIED: 15.11.4.1
define_new_own_property(property_keys.name,
EsPropertyDescriptor(false, true, true,
EsValue::from_str(_ESTR("Error")))); // VERIFIED: 15.11.4.2
define_new_own_property(property_keys.message,
EsPropertyDescriptor(false, true, true,
EsValue::from_str(EsString::create()))); // VERIFIED: 15.11.4.3
define_new_own_property(property_keys.to_string,
EsPropertyDescriptor(false, true, true,
EsValue::from_obj(EsBuiltinFunction::create_inst(es_global_env(),
es_std_err_proto_to_str, 0)))); // VERIFIED: 15.11.4.4
}
EsError *EsError::create_raw()
{
return new (GC)EsError();
}
EsError *EsError::create_inst(const EsString *message)
{
EsError *e = new (GC)EsError(message);
e->prototype_ = es_proto_err(); // VERIFIED: 15.11.5
e->class_ = _USTR("Error"); // VERIFIED: 15.11.5
e->extensible_ = true;
if (!message->empty())
{
e->define_new_own_property(property_keys.message,
EsPropertyDescriptor(false, true, true,
EsValue::from_str(message)));
}
return e;
}
EsFunction *EsError::default_constr()
{
if (default_constr_ == NULL)
default_constr_ = EsErrorConstructor<EsError>::create_inst();
return default_constr_;
}
template <typename T>
EsFunction *EsNativeError<T>::default_constr_ = NULL;
template <typename T>
EsNativeError<T>::EsNativeError(const EsString *name, const EsString *message)
: EsError(name, message)
{
}
template <typename T>
EsNativeError<T>::~EsNativeError()
{
}
template <typename T>
void EsNativeError<T>::make_proto()
{
prototype_ = es_proto_err(); // VERIFIED: 15.11.7.7
class_ = _USTR("Error"); // VERIFIED: 15.11.7.7
extensible_ = true;
// 15.11.7
define_new_own_property(property_keys.constructor,
EsPropertyDescriptor(false, true, true,
EsValue::from_obj(default_constr()))); // VERIFIED: 15.11.7.8
define_new_own_property(property_keys.name,
EsPropertyDescriptor(false, true, true,
EsValue::from_str(name()))); // VERIFIED: 15.11.7.9
define_new_own_property(property_keys.message,
EsPropertyDescriptor(false, true, true,
EsValue::from_str(EsString::create()))); // VERIFIED: 15.11.7.10
}
template <typename T>
T *EsNativeError<T>::create_raw()
{
return new (GC)T(EsString::create());
}
template <typename T>
T *EsNativeError<T>::create_inst(const EsString *message)
{
T *e = new (GC)T(message);
e->prototype_ = T::prototype(); // VERIFIED: 15.11.7.2
e->class_ = _USTR("Error"); // VERIFIED: 15.11.7.2
e->extensible_ = true; // VERIFIED: 15.11.7.2
if (!message->empty())
{
e->define_new_own_property(property_keys.message,
EsPropertyDescriptor(false, true, true,
EsValue::from_str(message)));
}
return e;
}
template <typename T>
EsFunction *EsNativeError<T>::default_constr()
{
if (default_constr_ == NULL)
default_constr_ = EsErrorConstructor<T>::create_inst();
return default_constr_;
}
template <typename T>
EsErrorConstructor<T>::EsErrorConstructor(EsLexicalEnvironment *scope,
NativeFunction fun, int len, bool strict)
: EsFunction(scope, fun, strict, 1, false)
{
}
template <typename T>
EsFunction *EsErrorConstructor<T>::create_inst()
{
EsErrorConstructor *f = new (GC)EsErrorConstructor(es_global_env(), T::default_fun_, 1, false);
f->prototype_ = es_proto_fun(); // VERIFIED: 15.11.7.5
f->class_ = _USTR("Function");
f->extensible_ = true;
// 15.11.7
f->define_new_own_property(property_keys.length,
EsPropertyDescriptor(false, false, false,
EsValue::from_u32(1))); // VERIFIED: 15.11.7.5
f->define_new_own_property(property_keys.prototype,
EsPropertyDescriptor(false, false, false,
EsValue::from_obj(T::prototype()))); // VERIFIED: 15.11.7.6
return f;
}
template <typename T>
bool EsErrorConstructor<T>::constructT(EsCallFrame &frame)
{
const EsString *msg_str = EsString::create();
EsValue msg = frame.arg(0);
if (!msg.is_undefined())
{
msg_str = msg.to_stringT();
if (!msg_str)
return false;
}
frame.set_result(EsValue::from_obj(T::create_inst(msg_str)));
return true;
}
EsObject *EsEvalError::prototype()
{
return es_proto_eval_err();
}
EsObject *EsRangeError::prototype()
{
return es_proto_range_err();
}
EsObject *EsReferenceError::prototype()
{
return es_proto_ref_err();
}
EsObject *EsSyntaxError::prototype()
{
return es_proto_syntax_err();
}
EsObject *EsTypeError::prototype()
{
return es_proto_type_err();
}
EsObject *EsUriError::prototype()
{
return es_proto_uri_err();
}
// Template specialization.
template <>
EsFunction::NativeFunction EsNativeError<EsEvalError>::default_fun_ = es_std_eval_err;
template <>
EsFunction::NativeFunction EsNativeError<EsRangeError>::default_fun_ = es_std_range_err;
template <>
EsFunction::NativeFunction EsNativeError<EsReferenceError>::default_fun_ = es_std_ref_err;
template <>
EsFunction::NativeFunction EsNativeError<EsSyntaxError>::default_fun_ = es_std_syntax_err;
template <>
EsFunction::NativeFunction EsNativeError<EsTypeError>::default_fun_ = es_std_type_err;
template <>
EsFunction::NativeFunction EsNativeError<EsUriError>::default_fun_ = es_std_uri_err;
// Explicit template instantiation.
template class EsNativeError<EsEvalError>;
template class EsNativeError<EsRangeError>;
template class EsNativeError<EsReferenceError>;
template class EsNativeError<EsSyntaxError>;
template class EsNativeError<EsTypeError>;
template class EsNativeError<EsUriError>;
| kindahl/descripten | runtime/error.cc | C++ | lgpl-3.0 | 8,323 |
/**
* Copyright 2012-2013 University Of Southern California
*
* 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.workflowsim.scheduling;
import java.util.ArrayList;
import java.util.List;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.Vm;
/**
* The base scheduler has implemented the basic features. Every other scheduling method
* should extend from BaseSchedulingAlgorithm but should not directly use it.
*
* @author Weiwei Chen
* @since WorkflowSim Toolkit 1.0
* @date Apr 9, 2013
*/
public abstract class BaseSchedulingAlgorithm implements SchedulingAlgorithmInterface {
/**
* the job list.
*/
private List<? extends Cloudlet> cloudletList;
/**
* the vm list.
*/
private List<? extends Vm> vmList;
/**
* the scheduled job list.
*/
private List< Cloudlet> scheduledList;
/**
* Initialize a BaseSchedulingAlgorithm
*/
public BaseSchedulingAlgorithm() {
this.scheduledList = new ArrayList();
}
/**
* Sets the job list.
*
* @param list
*/
@Override
public void setCloudletList(List list) {
this.cloudletList = list;
}
/**
* Sets the vm list
*
* @param list
*/
@Override
public void setVmList(List list) {
this.vmList = new ArrayList(list);
}
/**
* Gets the job list.
*
* @return the job list
*/
@Override
public List getCloudletList() {
return this.cloudletList;
}
/**
* Gets the vm list
*
* @return the vm list
*/
@Override
public List getVmList() {
return this.vmList;
}
/**
* The main function
*/
public abstract void run() throws Exception;
/**
* Gets the scheduled job list
*
* @return job list
*/
@Override
public List getScheduledList() {
return this.scheduledList;
}
}
| Farisllwaah/WorkflowSim-1.0 | sources/org/workflowsim/scheduling/BaseSchedulingAlgorithm.java | Java | lgpl-3.0 | 2,456 |
/**
* OnionCoffee - Anonymous Communication through TOR Network
* Copyright (C) 2005-2007 RWTH Aachen University, Informatik IV
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
package cf.monteux.silvertunnel.netlib.layer.tor.circuit.cells;
import cf.monteux.silvertunnel.netlib.layer.tor.circuit.Stream;
/**
* sends an END cell, needed to close a tcp-stream.
*
* @author Lexi Pimenidis
*/
public class CellRelayEnd extends CellRelay
{
/**
* constructor to build a ENDCELL.
*
* @param s
* the stream that shall be closed
* @param reason
* a reason
*/
public CellRelayEnd(final Stream s, final byte reason)
{
// initialize a new Relay-cell
super(s, CellRelay.RELAY_END);
// set length
setLength(1);
data[0] = reason;
}
}
| rovemonteux/silvertunnel-monteux | src/main/java/cf/monteux/silvertunnel/netlib/layer/tor/circuit/cells/CellRelayEnd.java | Java | lgpl-3.0 | 1,395 |
<?php
class CRM_Countrymanager_BAO_Country extends CRM_Countrymanager_DAO_Country{
static function retrieve(&$params, &$defaults) {
$country = new CRM_Countrymanager_DAO_Country();
$country->copyValues($params);
if ($country->find(TRUE)) {
CRM_Core_DAO::storeValues($country, $defaults);
return $country;
}
return NULL;
}
static function addAndSave($params) {
$country = new CRM_Countrymanager_DAO_Country();
$country->copyValues($params);
$country->save();
CRM_Core_DAO::storeValues($country, $defaults);
if ($country->find(TRUE)) {
return $country;
}
}
static function getListCountry($region_id = 0) {
$params = array();
$sql = "SELECT * FROM `civicrm_country`";
if($region_id != 0) {
$sql .= "WHERE region_id = %1";
$params[1] = array($region_id, 'Integer');
}
$dao = CRM_Core_DAO::executeQuery($sql, $params);
$country = array();
while($dao->fetch()) {
$country[$dao->id] = array("id" => $dao->id,"name" => $dao->name);
}
return $country;
}
} | ixiam/com.ixiam.modules.countrymanager | CRM/Countrymanager/BAO/Country.php | PHP | lgpl-3.0 | 1,056 |
package com.ashokgelal.samaya;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
Implements the <tt>toString</tt> method for some common cases.
<P>This class is intended only for cases where <tt>toString</tt> is used in
an informal manner (usually for logging and stack traces). It is especially
suited for <tt>public</tt> classes which model domain objects.
Here is an example of a return value of the {@link #getText} method :
<PRE>
hirondelle.web4j.model.MyUser {
LoginName: Bob
LoginPassword: ****
EmailAddress: bob@blah.com
StarRating: 1
FavoriteTheory: Quantum Chromodynamics
SendCard: true
Age: 42
DesiredSalary: 42000
BirthDate: Sat Feb 26 13:45:43 EST 2005
}
</PRE>
(Previous versions of this classes used indentation within the braces. That has
been removed, since it displays poorly when nesting occurs.)
<P>Here are two more examples, using classes taken from the JDK :
<PRE>
java.util.StringTokenizer {
nextElement: This
hasMoreElements: true
countTokens: 3
nextToken: is
hasMoreTokens: true
}
java.util.ArrayList {
size: 3
toArray: [blah, blah, blah]
isEmpty: false
}
</PRE>
There are two use cases for this class. The typical use case is :
<PRE>
public String toString() {
return ToStringUtil.getText(this);
}
</PRE>
<span class="highlight">However, there is a case where this typical style can
fail catastrophically</span> : when two objects reference each other, and each
has <tt>toString</tt> implemented as above, then the program will loop
indefinitely!
<P>As a remedy for this problem, the following variation is provided :
<PRE>
public String toString() {
return ToStringUtil.getTextAvoidCyclicRefs(this, Product.class, "getId");
}
</PRE>
Here, the usual behavior is overridden for any method
which returns a <tt>Product</tt> : instead of calling <tt>Product.toString</tt>,
the return value of <tt>Product.getId()</tt> is used to textually represent
the object.
*/
final class ToStringUtil {
/**
Return an informal textual description of an object.
<P>It is highly recommened that the caller <em>not</em> rely on details
of the returned <tt>String</tt>. See class description for examples of return
values.
<P><span class="highlight">WARNING</span>: If two classes have cyclic references
(that is, each has a reference to the other), then infinite looping will result
if <em>both</em> call this method! To avoid this problem, use <tt>getText</tt>
for one of the classes, and {@link #getTextAvoidCyclicRefs} for the other class.
<P>The only items which contribute to the result are the class name, and all
no-argument <tt>public</tt> methods which return a value. As well, methods
defined by the <tt>Object</tt> class, and factory methods which return an
<tt>Object</tt> of the native class ("<tt>getInstance</tt>" methods) do not contribute.
<P>Items are converted to a <tt>String</tt> simply by calling their
<tt>toString method</tt>, with these exceptions :
<ul>
<li>{@link Util#getArrayAsString(Object)} is used for arrays
<li>a method whose name contain the text <tt>"password"</tt> (not case-sensitive) have
their return values hard-coded to <tt>"****"</tt>.
</ul>
<P>If the method name follows the pattern <tt>getXXX</tt>, then the word 'get'
is removed from the presented result.
@param aObject the object for which a <tt>toString</tt> result is required.
*/
static String getText(Object aObject) {
return getTextAvoidCyclicRefs(aObject, null, null);
}
/**
As in {@link #getText}, but, for return values which are instances of
<tt>aSpecialClass</tt>, then call <tt>aMethodName</tt> instead of <tt>toString</tt>.
<P> If <tt>aSpecialClass</tt> and <tt>aMethodName</tt> are <tt>null</tt>, then the
behavior is exactly the same as calling {@link #getText}.
*/
static String getTextAvoidCyclicRefs(Object aObject, Class aSpecialClass, String aMethodName) {
StringBuilder result = new StringBuilder();
addStartLine(aObject, result);
Method[] methods = aObject.getClass().getDeclaredMethods();
for(Method method: methods){
if ( isContributingMethod(method, aObject.getClass()) ){
addLineForGetXXXMethod(aObject, method, result, aSpecialClass, aMethodName);
}
}
addEndLine(result);
return result.toString();
}
// PRIVATE //
/*
Names of methods in the <tt>Object</tt> class which are ignored.
*/
private static final String fGET_CLASS = "getClass";
private static final String fCLONE = "clone";
private static final String fHASH_CODE = "hashCode";
private static final String fTO_STRING = "toString";
private static final String fGET = "get";
private static final Object[] fNO_ARGS = new Object[0];
private static final Class[] fNO_PARAMS = new Class[0];
/*
Previous versions of this class indented the data within a block.
That style breaks when one object references another. The indentation
has been removed, but this variable has been retained, since others might
prefer the indentation anyway.
*/
private static final String fINDENT = "";
private static final String fAVOID_CIRCULAR_REFERENCES = "[circular reference]";
private static final Logger fLogger = Util.getLogger(ToStringUtil.class);
private static final String NEW_LINE = System.getProperty("line.separator");
private static Pattern PASSWORD_PATTERN = Pattern.compile("password", Pattern.CASE_INSENSITIVE);
private static String HIDDEN_PASSWORD_VALUE = "****";
//prevent construction by the caller
private ToStringUtil() {
//empty
}
private static void addStartLine(Object aObject, StringBuilder aResult){
aResult.append( aObject.getClass().getName() );
aResult.append(" {");
aResult.append(NEW_LINE);
}
private static void addEndLine(StringBuilder aResult){
aResult.append("}");
aResult.append(NEW_LINE);
}
/**
Return <tt>true</tt> only if <tt>aMethod</tt> is public, takes no args,
returns a value whose class is not the native class, is not a method of
<tt>Object</tt>.
*/
private static boolean isContributingMethod(Method aMethod, Class aNativeClass){
boolean isPublic = Modifier.isPublic( aMethod.getModifiers() );
boolean hasNoArguments = aMethod.getParameterTypes().length == 0;
boolean hasReturnValue = aMethod.getReturnType() != Void.TYPE;
boolean returnsNativeObject = aMethod.getReturnType() == aNativeClass;
boolean isMethodOfObjectClass =
aMethod.getName().equals(fCLONE) ||
aMethod.getName().equals(fGET_CLASS) ||
aMethod.getName().equals(fHASH_CODE) ||
aMethod.getName().equals(fTO_STRING)
;
return
isPublic &&
hasNoArguments &&
hasReturnValue &&
! isMethodOfObjectClass &&
! returnsNativeObject;
}
private static void addLineForGetXXXMethod(
Object aObject,
Method aMethod,
StringBuilder aResult,
Class aCircularRefClass,
String aCircularRefMethodName
){
aResult.append(fINDENT);
aResult.append( getMethodNameMinusGet(aMethod) );
aResult.append(": ");
Object returnValue = getMethodReturnValue(aObject, aMethod);
if ( returnValue != null && returnValue.getClass().isArray() ) {
aResult.append( Util.getArrayAsString(returnValue) );
}
else {
if (aCircularRefClass == null) {
aResult.append( returnValue );
}
else {
if (aCircularRefClass == returnValue.getClass()) {
Method method = getMethodFromName(aCircularRefClass, aCircularRefMethodName);
if ( isContributingMethod(method, aCircularRefClass)){
returnValue = getMethodReturnValue(returnValue, method);
aResult.append( returnValue );
}
else {
aResult.append(fAVOID_CIRCULAR_REFERENCES);
}
}
}
}
aResult.append( NEW_LINE );
}
private static String getMethodNameMinusGet(Method aMethod){
String result = aMethod.getName();
if (result.startsWith(fGET) ) {
result = result.substring(fGET.length());
}
return result;
}
/** Return value is possibly-null. */
private static Object getMethodReturnValue(Object aObject, Method aMethod){
Object result = null;
try {
result = aMethod.invoke(aObject, fNO_ARGS);
}
catch (IllegalAccessException ex){
vomit(aObject, aMethod);
}
catch (InvocationTargetException ex){
vomit(aObject, aMethod);
}
result = dontShowPasswords(result, aMethod);
return result;
}
private static Method getMethodFromName(Class aSpecialClass, String aMethodName){
Method result = null;
try {
result = aSpecialClass.getMethod(aMethodName, fNO_PARAMS);
}
catch ( NoSuchMethodException ex){
vomit(aSpecialClass, aMethodName);
}
return result;
}
private static void vomit(Object aObject, Method aMethod){
fLogger.severe(
"Cannot get return value using reflection. Class: " +
aObject.getClass().getName() +
" Method: " +
aMethod.getName()
);
}
private static void vomit(Class aSpecialClass, String aMethodName){
fLogger.severe(
"Reflection fails to get no-arg method named: " +
Util.quote(aMethodName) +
" for class: " +
aSpecialClass.getName()
);
}
private static Object dontShowPasswords(Object aReturnValue, Method aMethod){
Object result = aReturnValue;
Matcher matcher = PASSWORD_PATTERN.matcher(aMethod.getName());
if ( matcher.find()) {
result = HIDDEN_PASSWORD_VALUE;
}
return result;
}
/*
Two informal classes with cyclic references, used for testing.
*/
private static final class Ping {
public void setPong(Pong aPong){fPong = aPong; }
public Pong getPong(){ return fPong; }
public Integer getId() { return new Integer(123); }
public String getUserPassword(){ return "blah"; }
public String toString() {
return getText(this);
}
private Pong fPong;
}
private static final class Pong {
public void setPing(Ping aPing){ fPing = aPing; }
public Ping getPing() { return fPing; }
public String toString() {
return getTextAvoidCyclicRefs(this, Ping.class, "getId");
//to see the infinite looping, use this instead :
//return getText(this);
}
private Ping fPing;
}
/**
Informal test harness.
*/
public static void main (String... args) {
List<String> list = new ArrayList<String>();
list.add("blah");
list.add("blah");
list.add("blah");
System.out.println( ToStringUtil.getText(list) );
StringTokenizer parser = new StringTokenizer("This is the end.");
System.out.println( ToStringUtil.getText(parser) );
Ping ping = new Ping();
Pong pong = new Pong();
ping.setPong(pong);
pong.setPing(ping);
System.out.println( ping );
System.out.println( pong );
}
}
| iehudiel/nadia | src/com/ashokgelal/samaya/ToStringUtil.java | Java | lgpl-3.0 | 11,583 |
<?php
namespace ch\metanet\cms\common;
use ch\metanet\cms\controller\common\FrontendController;
use ch\metanet\cms\model\PageModel;
use ch\metanet\cms\module\layout\LayoutElement;
/**
* This represents a CMS frontend page
*
* @author Pascal Muenst <entwicklung@metanet.ch>
* @copyright Copyright (c) 2013, METANET AG
*/
class CmsPage
{
const CACHE_MODE_NONE = 0;
const CACHE_MODE_PRIVATE = 1;
const CACHE_MODE_PUBLIC = 2;
const ROLE_TEMPLATE = 'tpl';
const ROLE_ERROR = 'error';
const ROLE_STANDARD = 'page';
const ROLE_MODULE = 'module';
const PAGE_AREA_HEAD = 'head';
const PAGE_AREA_BODY = 'body';
/** @var int The ID of the page */
protected $ID;
/** @var LayoutElement $layout */
protected $layout;
/** @var int|null The ID of the layout element */
protected $layoutID;
/** @var string Title of the page */
protected $title;
/** @var string Description of the page (a.k.a. meta description) */
protected $description;
/** @var string Language code (e.x. de, en, ...) */
protected $language;
/** @var CmsPage|null $basePage The parent page or null if there is any */
protected $parentPage;
/** @var string Role of this page (one of the ROLE_ constants in this class) */
protected $role;
/** @var int|null The error code of this page (if it's of type error -> ROLE_ERROR) */
protected $errorCode;
/** @var string[] The groups and their rights to access this page */
protected $rights;
/** @var string|null The last modified date as ISO date string */
protected $lastModified;
/** @var int|null The last modifiers user ID or null if page never has been modified till now */
protected $modifierID;
/** @var string|null The last modifiers user ID or null if page never has been modified till now */
protected $modifierName;
/** @var string The create date as ISO date string */
protected $created;
/** @var int The user ID of the page creator */
protected $creatorID;
/** @var string The user name of the page creator */
protected $creatorName;
/** @var int Should the page inherit rights from its parent page (1) or not (0) */
protected $inheritRights;
/** @var null Cache mode (not in use atm) */
protected $cacheMode = self::CACHE_MODE_NONE;
/** @var string[] JS code to include in this page (inline or as <script src="..." /> */
protected $javascript;
/** @var string[] CSS code to include in this page (inline or as <link href="...">) */
protected $css;
public function __construct()
{
$this->layoutID = null;
$this->layout = null;
$this->inheritRights = 0;
$this->role = self::ROLE_STANDARD;
$this->css = array();
$this->javascript = array();
}
/**
* Renders the page with a specific view
*
* @param FrontendController $frontendController
* @param CmsView $view
* @throws CMSException
* @return string The rendered html
*/
public function render(FrontendController $frontendController, CmsView $view)
{
if($this->layout === null && $this->layoutID !== null)
throw new CMSException('Modules not loaded for page #' . $this->ID);
return ($this->layout !== null)?$this->layout->render($frontendController, $view):null;
}
/**
* @return int|null
*/
public function getID()
{
return $this->ID;
}
/**
* @param int|null $ID
*/
public function setID($ID)
{
$this->ID = $ID;
}
/**
* @return string|null
*/
public function getTitle()
{
return $this->title;
}
/**
* @param string|null $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* @return string|null
*/
public function getDescription()
{
return $this->description;
}
/**
* @param string|null $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* @return string|null
*/
public function getLanguage()
{
return $this->language;
}
/**
* @param string|null $language
*/
public function setLanguage($language)
{
$this->language = $language;
}
/**
* Set the layout of the page
*
* @param LayoutElement $layout
*/
public function setLayout(LayoutElement $layout)
{
$this->layout = $layout;
}
/**
* @return int
*/
public function getLayoutID()
{
return $this->layoutID;
}
/**
* @param int $layoutID
*/
public function setLayoutID($layoutID)
{
$this->layoutID = $layoutID;
}
/**
* @return LayoutElement
*/
public function getLayout()
{
return $this->layout;
}
/**
* Returns the CmsPage object which this page is based on
* @return CmsPage|null
*/
public function getParentPage()
{
return $this->parentPage;
}
/**
* @return bool
*/
public function hasParentPage()
{
return ($this->parentPage !== null);
}
/**
* @param CmsPage $basePage
*/
public function setParentPage($basePage)
{
$this->parentPage = $basePage;
}
public function setRights($rights)
{
$this->rights = $rights;
}
public function getRights()
{
return $this->rights;
}
public function getLastModified()
{
return $this->lastModified;
}
/**
* @param string $lastModified Date in ISO-Format (Y-m-d H:i:s)
*/
public function setLastModified($lastModified)
{
if($lastModified !== null && ($this->lastModified === null || $this->lastModified < $lastModified)) {
$this->lastModified = $lastModified;
}
}
public function getCreated()
{
return $this->created;
}
public function setCreated($created)
{
$this->created = $created;
}
public function getModifierID()
{
return $this->modifierID;
}
public function getModifierName()
{
return $this->modifierName;
}
public function setModifierID($modifierID)
{
$this->modifierID = $modifierID;
}
public function setModifierName($modifierName)
{
$this->modifierName = $modifierName;
}
public function getCreatorID()
{
return $this->creatorID;
}
public function getCreatorName()
{
return $this->creatorName;
}
public function setCreatorID($creatorID)
{
$this->creatorID = $creatorID;
}
public function setCreatorName($creatorName)
{
$this->creatorName = $creatorName;
}
public function setInheritRights($inheritRights)
{
$this->inheritRights = $inheritRights;
}
public function getInheritRights()
{
return $this->inheritRights;
}
/**
* @param int $cacheMode The cache mode of this page
*/
public function setCacheMode($cacheMode)
{
$this->cacheMode = $cacheMode;
}
/**
* @return int The cache mode of this page
*/
public function getCacheMode()
{
return $this->cacheMode;
}
/**
* @param string $role
*/
public function setRole($role)
{
$this->role = $role;
}
/**
* @return string
*/
public function getRole()
{
return $this->role;
}
/**
* @param int|null $errorCode
*/
public function setErrorCode($errorCode)
{
$this->errorCode = $errorCode;
}
/**
* @return int|null
*/
public function getErrorCode()
{
return $this->errorCode;
}
/**
* Adds JavaScript to a specified page area (e.x. head or body)
*
* @param string $javaScriptStr
* @param string $pageArea
* @param string|null $key
* @param string $group
*/
public function addJs($javaScriptStr, $pageArea = self::PAGE_AREA_BODY, $key = null, $group = 'default')
{
if(isset($this->javascript[$pageArea]) === false)
$this->javascript[$pageArea] = array();
if(isset($this->javascript[$pageArea][$group]) === false)
$this->javascript[$pageArea][$group] = array();
if($key === null)
$this->javascript[$pageArea][$group][] = $javaScriptStr;
else
$this->javascript[$pageArea][$group][$key] = $javaScriptStr;
}
/**
* @param string $key
* @param string $pageArea
* @param string $group
*
* @return bool
*/
public function removeJs($key, $pageArea = self::PAGE_AREA_BODY, $group = 'default')
{
if(isset($this->javascript[$pageArea][$group][$key]) === false)
return false;
unset($this->javascript[$pageArea][$group][$key]);
return true;
}
/**
* @param string|null $pageArea
*
* @return string[]
*/
public function getJs($pageArea = null)
{
if($pageArea === null)
return $this->javascript;
if(isset($this->javascript[$pageArea]) === false)
return array();
return $this->javascript[$pageArea];
}
/**
* @param string $cssStr
* @param null $group
* @param null $key
*/
public function addCss($cssStr, $group = null, $key = null)
{
$this->css[] = $cssStr;
}
}
/* EOF */ | METANETAG/meta-cms | src/ch/metanet/cms/common/CmsPage.php | PHP | lgpl-3.0 | 8,384 |
#!/usr/bin/env python
"""
RSS Reader for C-Power 1200
Copyright 2010-2012 Michael Farrell <http://micolous.id.au/>
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from cpower1200 import *
import feedparser
from sys import argv
FEED = 'http://news.google.com.au/news?pz=1&cf=all&ned=au&hl=en&output=rss'
d = feedparser.parse(FEED)
s = CPower1200(argv[1])
# Define one window at the top of the screen, and one in the lower part of the screen
s.send_window(dict(x=0, y=0, h=8, w=64), dict(x=0, y=8, h=8, w=64))
header = s.format_text(d.feed.title, RED, 0)
articles = ''
for i, article in enumerate(d.entries[:4]):
print "entry %d: %s" % (i, article.title)
colour = YELLOW if i % 2 == 0 else GREEN
articles += s.format_text(article.title + ' ', colour)
# send to sign
#s.send_text(0, header, effect=EFFECT_NONE)
s.send_clock(0, display_year=False, display_month=False, display_day=False, display_hour=True, display_minute=True, display_second=True, multiline=False, red=255,green=0,blue=0)
s.send_text(1, articles, speed=10)
| micolous/ledsign | cpower1200_rss.py | Python | lgpl-3.0 | 1,615 |
<?php
class Netlogiq_AddRemoveLink_Model_Source_Remove {
public function toOptionArray() {
$array = array(
array('label' => 'Account Dashboard','value' => 'account'),
array('label' => 'Account Edit','value' => 'account_edit'),
array('label' => 'Address Book','value' => 'address_book'),
array('label' => 'My Orders','value' => 'orders'),
array('label' => 'Billing Agreements','value' => 'billing_agreements'),
array('label' => 'Recurring Profiles','value' => 'recurring_profiles'),
array('label' => 'My Product Reviews','value' => 'reviews'),
array('label' => 'My Wishlist','value' => 'wishlist'),
array('label' => 'My Applications','value' => 'OAuth Customer Tokens'),
array('label' => 'Newsletter Subscriptions','value' => 'newsletter'),
array('label' => 'My Downloadable Products','value' => 'downloadable_products'),
);
return $array;
}
}
| dbashyal/MagentoStarterBase | trunk/app/code/community/Netlogiq/AddRemoveLink/Model/Source/Remove.php | PHP | lgpl-3.0 | 888 |
<?php
/**
* Aomebo - a module-based MVC framework for PHP 5.3 and higher
*
* Copyright 2010 - 2015 by Christian Johansson <christian@cvj.se>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
* @license LGPL version 3
* @see http://www.aomebo.org/ or https://github.com/cjohansson/Aomebo-Framework
*/
/**
*
*/
namespace Aomebo\Database\Adapters
{
/**
*
*/
class TableColumn
{
/**
* @var string
*/
public $name = '';
/**
* @var string
*/
public $specification = '';
/**
* @var bool
*/
public $isString = false;
/**
* @param string [$name = '']
* @param string [$specification = '']
* @param bool [$isString = false]
*/
public function __construct($name = '',
$specification = '',
$isString = false)
{
$this->name = $name;
$this->specification = $specification;
$this->isString = $isString;
}
/**
*
*/
public function __toString()
{
return \Aomebo\Database\Adapter::backquote(
$this->name
);
}
}
}
| cjohansson/Aomebo-Framework | Database/Adapters/TableColumn.php | PHP | lgpl-3.0 | 1,870 |
/*
* Copyright (C) 2019 Ondrej Starek
*
* This file is part of OTest2.
*
* OTest2 is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OTest2 is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with OTest2. If not, see <http://www.gnu.org/licenses/>.
*/
#include <testmarkint.h>
#include <assert.h>
#include <iostream>
#include <testmarkhash.h>
#include <testmarkin.h>
#include <testmarkout.h>
namespace OTest2 {
namespace {
const char SERIALIZE_TYPE_MARK[] = "ot2:int";
} /* -- namespace */
TestMarkInt::TestMarkInt(
int64_t value_) :
value(value_) {
}
TestMarkInt::TestMarkInt(
const CtorMark*) :
value(0) {
}
TestMarkInt::~TestMarkInt() {
}
const char* TestMarkInt::typeMark() {
return SERIALIZE_TYPE_MARK;
}
TestMarkHashCode TestMarkInt::doGetHashCode() const noexcept {
return TestMarkHash::hashBasicType(SERIALIZE_TYPE_MARK, value);
}
bool TestMarkInt::doIsEqual(
const TestMark& other_,
long double precision_) const {
return value == static_cast<const TestMarkInt*>(&other_)->value;
}
bool TestMarkInt::doIsEqualValue(
const TestMark& other_,
long double precision_) const {
return doIsEqual(other_, precision_);
}
void TestMarkInt::doDiffArray(
int level_,
std::vector<LinearizedRecord>& array_) const
{
/* -- there are no children */
}
void TestMarkInt::doLinearizedMark(
int level_,
const std::string& label_,
std::vector<LinearizedRecord>& array_) const {
array_.push_back({level_, this, label_});
}
void TestMarkInt::doPrintOpen(
std::ostream& os_,
const std::string& prefix_) const {
os_ << prefix_ << value << '\n';
}
void TestMarkInt::doPrintClose(
std::ostream& os_,
const std::string& prefix_) const {
/* -- nothing to do */
}
void TestMarkInt::doSerializeMark(
TestMarkOut& serializer_) const {
serializer_.writeTypeMark(SERIALIZE_TYPE_MARK);
serializer_.writeInt(value);
}
void TestMarkInt::doDeserializeMark(
TestMarkFactory& factory_,
TestMarkIn& deserializer_) {
value = deserializer_.readInt();
}
} /* namespace OTest2 */
| Staon/otest2 | lib/testmarkint.cpp | C++ | lgpl-3.0 | 2,543 |
/*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.issue;
import java.util.Collections;
import java.util.List;
import javax.annotation.CheckForNull;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public class ComponentIssuesRepositoryImpl implements MutableComponentIssuesRepository {
@CheckForNull
private List<DefaultIssue> issues;
@CheckForNull
private Component component;
@Override
public void setIssues(Component component, List<DefaultIssue> issues) {
this.issues = requireNonNull(issues, "issues cannot be null");
this.component = requireNonNull(component, "component cannot be null");
}
@Override
public List<DefaultIssue> getIssues(Component component) {
if (component.getType() == Component.Type.DIRECTORY) {
// No issues on directories
return Collections.emptyList();
}
checkState(this.component != null && this.issues != null, "Issues have not been initialized");
checkArgument(component.equals(this.component),
"Only issues from component '%s' are available, but wanted component is '%s'.",
this.component.getReportAttributes().getRef(), component.getReportAttributes().getRef());
return issues;
}
}
| Godin/sonar | server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesRepositoryImpl.java | Java | lgpl-3.0 | 2,261 |
// Copyright 2016 The daxxcoreAuthors
// This file is part of the daxxcore library.
//
// The daxxcore library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The daxxcore 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the daxxcore library. If not, see <http://www.gnu.org/licenses/>.
package http
import (
"io/ioutil"
"net/http"
"strings"
"testing"
"time"
)
const port = "3222"
func TestRoundTripper(t *testing.T) {
serveMux := http.NewServeMux()
serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
w.Header().Set("Content-Type", "text/plain")
http.ServeContent(w, r, "", time.Unix(0, 0), strings.NewReader(r.RequestURI))
} else {
http.Error(w, "Method "+r.Method+" is not supported.", http.StatusMethodNotAllowed)
}
})
go http.ListenAndServe(":"+port, serveMux)
rt := &RoundTripper{Port: port}
trans := &http.Transport{}
trans.RegisterProtocol("bzz", rt)
client := &http.Client{Transport: trans}
resp, err := client.Get("bzz://test.com/path")
if err != nil {
t.Errorf("expected no error, got %v", err)
return
}
defer func() {
if resp != nil {
resp.Body.Close()
}
}()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Errorf("expected no error, got %v", err)
return
}
if string(content) != "/HTTP/1.1:/test.com/path" {
t.Errorf("incorrect response from http server: expected '%v', got '%v'", "/HTTP/1.1:/test.com/path", string(content))
}
}
| daxxcoin/daxxcore | swarm/api/http/roundtripper_test.go | GO | lgpl-3.0 | 1,949 |
# -*- coding: utf-8 -*-
from distutils.core import setup
import os.path
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
]
def read(fname):
fname = os.path.join(os.path.dirname(__file__), fname)
return open(fname).read().strip()
def read_files(*fnames):
return '\r\n\r\n\r\n'.join(map(read, fnames))
setup(
name = 'icall',
version = '0.3.4',
py_modules = ['icall'],
description = 'Parameters call function, :-)',
long_description = read_files('README.rst', 'CHANGES.rst'),
author = 'huyx',
author_email = 'ycyuxin@gmail.com',
url = 'https://github.com/huyx/icall',
keywords = ['functools', 'function', 'call'],
classifiers = classifiers,
)
| huyx/icall | setup.py | Python | lgpl-3.0 | 1,026 |
#include "KxDesktopServices.h"
#include <QDesktopServices>
#include <QUrl>
KxDesktopServices::KxDesktopServices(QObject *parent)
: QObject(parent)
{
}
void KxDesktopServices::openUrl(const QString &url)
{
QDesktopServices::openUrl(QUrl(url));
}
| kxtry/czys | kxmob/KxDesktopServices.cpp | C++ | lgpl-3.0 | 259 |
package com.MatofSteel1.soulglassmod.item;
import com.MatofSteel1.soulglassmod.creativetab.CreativeTabSGM;
import com.MatofSteel1.soulglassmod.inventory.ItemInventory;
import com.MatofSteel1.soulglassmod.reference.Reference;
import com.MatofSteel1.soulglassmod.utility.InventoryUtils;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.event.entity.player.EntityItemPickupEvent;
public class ItemSoulGlassMod extends Item {
public ItemSoulGlassMod() {
super();
this.setCreativeTab(CreativeTabSGM.SoulGlassMod_TAB);
}
@Override
public String getUnlocalizedName()
{
return String.format("item.%s%s", Reference.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName()));
}
@Override
public String getUnlocalizedName(ItemStack itemStack)
{
return String.format("item.%s%s", Reference.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName()));
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister iconRegister)
{
itemIcon = iconRegister.registerIcon(this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf(".") + 1));
}
protected String getUnwrappedUnlocalizedName(String unlocalizedName)
{
return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1);
}
@SubscribeEvent
public void onItemPickUp(EntityItemPickupEvent evt) {
final EntityPlayer player = evt.entityPlayer;
final ItemStack pickedStack = evt.item.getEntityItem();
if (pickedStack == null || player == null) return;
boolean foundMatchingContainer = false;
for (int i = 0; i < player.inventory.getSizeInventory(); i++) {
ItemStack stack = player.inventory.getStackInSlot(i);
if (stack != null && stack.getItem() == (this)) {
ItemInventory inventory = new ItemInventory(stack, 1);
ItemStack containedStack = inventory.getStackInSlot(0);
if (containedStack != null) {
boolean isMatching = InventoryUtils.areItemAndTagEqual(pickedStack, containedStack);
if (isMatching) {
foundMatchingContainer = true;
InventoryUtils.tryInsertStack(inventory, 0, pickedStack, true);
}
}
}
}
if (foundMatchingContainer) pickedStack.stackSize = 0;
}
public boolean placeBlockAt(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int metadata) {
stack.stackSize++;
return true;
}
} | MatofSteel1/SoulGlassModv1.0 | src/main/java/com/MatofSteel1/soulglassmod/item/ItemSoulGlassMod.java | Java | lgpl-3.0 | 3,035 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using ClientDependency.Core;
namespace ClientDependency.Web.Test.Controls
{
/// <summary>
/// This simply demonstrates using attributes to register file dependencies.
/// </summary>
[ClientDependency(ClientDependencyType.Css, "~/Css/CustomControl.css")]
public class MyCustomControl : Control
{
private HtmlGenericControl m_MainDiv;
protected override void CreateChildControls()
{
base.CreateChildControls();
m_MainDiv = new HtmlGenericControl();
m_MainDiv.ID = "myControl";
m_MainDiv.Attributes.Add("class", "myControl");
m_MainDiv.Controls.Add(new LiteralControl("<div>My Custom Control</div>"));
this.Controls.Add(m_MainDiv);
}
}
}
| aozora/arashi | src/ThirdPartyLibraries/ClientDependency/ClientDependency.Web.Test/Controls/MyCustomControl.cs | C# | lgpl-3.0 | 926 |
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
**/
/**
* @file mesh2heightfield.cpp
* @ingroup converters
* @author Bertrand Kerautret (\c kerautre@loria.fr )
* LORIA (CNRS, UMR 7503), University of Nancy, France
*
* @date 2015/04/08
*
*
*
* This file is part of the DGtalTools.
*/
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include "DGtal/base/Common.h"
#include "DGtal/helpers/StdDefs.h"
#include "DGtal/images/ImageContainerBySTLVector.h"
#include "DGtal/io/writers/GenericWriter.h"
#include "DGtal/io/readers/MeshReader.h"
#include "DGtal/io/writers/MeshWriter.h"
#include "DGtal/images/ConstImageAdapter.h"
#include "DGtal/kernel/BasicPointFunctors.h"
#include "DGtal/math/linalg/SimpleMatrix.h"
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
using namespace std;
using namespace DGtal;
///////////////////////////////////////////////////////////////////////////////
namespace po = boost::program_options;
template<typename TPoint, typename TEmbeder>
TPoint
getNormal(const TPoint &vect, const TEmbeder &emb ){
Z3i::RealPoint p0 = emb(Z2i::RealPoint(0.0,0.0), false);
Z3i::RealPoint px = emb(Z2i::RealPoint(10.0,0.0), false);
Z3i::RealPoint py = emb(Z2i::RealPoint(0.0,10.0), false);
Z3i::RealPoint u = px-p0; u /= u.norm();
Z3i::RealPoint v = py-p0; v /= v.norm();
Z3i::RealPoint w = u.crossProduct(v); w /= w.norm();
SimpleMatrix<double, 3, 3> t;
t.setComponent(0,0, u[0]); t.setComponent(0,1, v[0]); t.setComponent(0, 2, w[0]);
t.setComponent(1,0, u[1]); t.setComponent(1,1, v[1]); t.setComponent(1, 2, w[1]);
t.setComponent(2,0, u[2]); t.setComponent(2,1, v[2]); t.setComponent(2, 2, w[2]);
return ((t.inverse())*vect);
}
template<typename TImage, typename TVectorField, typename TPoint>
void
fillPointArea(TImage &anImage, TVectorField &imageVectorField,
const TPoint aPoint, const unsigned int size, const unsigned int value, const Z3i::RealPoint &n){
typename TImage::Domain aDom(aPoint-TPoint::diagonal(size), aPoint+TPoint::diagonal(size));
for(typename TImage::Domain::ConstIterator it= aDom.begin(); it != aDom.end(); it++){
if (anImage.domain().isInside(*it)){
anImage.setValue(*it, value);
imageVectorField.setValue(*it, n);
}
}
}
int main( int argc, char** argv )
{
typedef ImageContainerBySTLVector < Z3i::Domain, Z3i::RealPoint > VectorFieldImage3D;
typedef ImageContainerBySTLVector < Z2i::Domain, Z3i::RealPoint > VectorFieldImage2D;
typedef ImageContainerBySTLVector < Z3i::Domain, unsigned char > Image3D;
typedef ImageContainerBySTLVector < Z2i::Domain, unsigned char> Image2D;
typedef DGtal::ConstImageAdapter<Image3D, Z2i::Domain, DGtal::functors::Point2DEmbedderIn3D<DGtal::Z3i::Domain>,
Image3D::Value, DGtal::functors::Identity > ImageAdapterExtractor;
// parse command line ----------------------------------------------
po::options_description general_opt("Allowed options are: ");
general_opt.add_options()
("help,h", "display this message")
("input,i", po::value<std::string>(), "mesh file (.off) " )
("meshScale,s", po::value<double>()->default_value(1.0),
"change the default mesh scale (each vertex multiplied by the scale) " )
("output,o", po::value<std::string>(), "sequence of discrete point file (.sdp) ")
("orientAutoFrontX", "automatically orients the camera in front according the x axis." )
("orientAutoFrontY", "automatically orients the camera in front according the y axis." )
("orientAutoFrontZ", "automatically orients the camera in front according the z axis." )
("orientBack", "change the camera direction to back instead front as given in orientAutoFront{X,Y,Z} options." )
("nx", po::value<double>()->default_value(0), "set the x component of the projection direction." )
("ny", po::value<double>()->default_value(0), "set the y component of the projection direction." )
("nz", po::value<double>()->default_value(1), "set the z component of the projection direction." )
("centerX,x", po::value<unsigned int>()->default_value(0), "choose x center of the projected image." )
("centerY,y", po::value<unsigned int>()->default_value(0), "choose y center of the projected image." )
("centerZ,z", po::value<unsigned int>()->default_value(1), "choose z center of the projected image." )
("width", po::value<unsigned int>()->default_value(100), "set the width of the area to be extracted as an height field image." )
("height", po::value<unsigned int>()->default_value(100), "set the height of the area to extracted as an height field image." )
("heightFieldMaxScan", po::value<unsigned int>()->default_value(255), "set the maximal scan deep." )
("exportNormals", "export mesh normal vectors (given in the image height field basis)." )
("backgroundNormalBack", "set the normals of background in camera opposite direction (to obtain a black background in rendering). " )
("setBackgroundLastDepth", "change the default background (black with the last filled intensity).");
double triangleAreaUnit = 0.5;
bool parseOK=true;
po::variables_map vm;
try{
po::store(po::parse_command_line(argc, argv, general_opt), vm);
}catch(const std::exception& ex){
parseOK=false;
trace.info()<< "Error checking program options: "<< ex.what()<< endl;
}
po::notify(vm);
if( !parseOK || vm.count("help")||argc<=1)
{
std::cout << "Usage: " << argv[0] << " [input] [output]\n"
<< "Convert a mesh file into a projected 2D image given from a normal direction N and from a starting point P. The 3D mesh discretized and scanned in the normal direction N, starting from P with a step 1."
<< general_opt << "\n";
std::cout << "Example:\n"
<< "mesh2heightfield -i ${DGtal}/examples/samples/tref.off --orientAutoFrontZ --width 25 --height 25 -o heighMap.pgm -s 10 \n";
return 0;
}
if(! vm.count("input") ||! vm.count("output"))
{
trace.error() << " Input and output filename are needed to be defined" << endl;
return 0;
}
string inputFilename = vm["input"].as<std::string>();
string outputFilename = vm["output"].as<std::string>();
double meshScale = vm["meshScale"].as<double>();
trace.info() << "Reading input file " << inputFilename ;
Mesh<Z3i::RealPoint> inputMesh(true);
DGtal::MeshReader<Z3i::RealPoint>::importOFFFile(inputFilename, inputMesh);
std::pair<Z3i::RealPoint, Z3i::RealPoint> b = inputMesh.getBoundingBox();
double diagDist = (b.first-b.second).norm();
if(diagDist<2.0*sqrt(2.0)){
inputMesh.changeScale(2.0*sqrt(2.0)/diagDist);
}
inputMesh.quadToTriangularFaces();
inputMesh.changeScale(meshScale);
trace.info() << " [done] " << std::endl ;
double maxArea = triangleAreaUnit+1.0 ;
while(maxArea> triangleAreaUnit)
{
trace.info()<< "Iterating mesh subdivision ... "<< maxArea;
maxArea = inputMesh.subDivideTriangularFaces(triangleAreaUnit);
trace.info() << " [done]"<< std::endl;
}
std::pair<Z3i::RealPoint, Z3i::RealPoint> bb = inputMesh.getBoundingBox();
Image3D::Domain meshDomain( bb.first-Z3i::Point::diagonal(1),
bb.second+Z3i::Point::diagonal(1));
// vol image filled from the mesh vertex.
Image3D meshVolImage(meshDomain);
VectorFieldImage3D meshNormalImage(meshDomain);
Z3i::RealPoint z(0.0,0.0,0.0);
for(Image3D::Domain::ConstIterator it = meshVolImage.domain().begin();
it != meshVolImage.domain().end(); it++)
{
meshVolImage.setValue(*it, 0);
meshNormalImage.setValue(*it, z);
}
// Filling mesh faces in volume.
for(unsigned int i =0; i< inputMesh.nbFaces(); i++)
{
trace.progressBar(i, inputMesh.nbFaces());
typename Mesh<Z3i::RealPoint>::MeshFace aFace = inputMesh.getFace(i);
if(aFace.size()==3)
{
Z3i::RealPoint p1 = inputMesh.getVertex(aFace[0]);
Z3i::RealPoint p2 = inputMesh.getVertex(aFace[1]);
Z3i::RealPoint p3 = inputMesh.getVertex(aFace[2]);
Z3i::RealPoint n = (p2-p1).crossProduct(p3-p1);
n /= n.norm();
Z3i::RealPoint c = (p1+p2+p3)/3.0;
fillPointArea(meshVolImage, meshNormalImage, p1, 1, 1, n);
fillPointArea(meshVolImage, meshNormalImage, p2, 1, 1, n);
fillPointArea(meshVolImage, meshNormalImage, p3, 1, 1, n);
fillPointArea(meshVolImage, meshNormalImage, c, 1, 1, n);
}
}
unsigned int widthImageScan = vm["height"].as<unsigned int>()*meshScale;
unsigned int heightImageScan = vm["width"].as<unsigned int>()*meshScale;
int maxScan = vm["heightFieldMaxScan"].as<unsigned int>()*meshScale;
int centerX = vm["centerX"].as<unsigned int>()*meshScale;
int centerY = vm["centerY"].as<unsigned int>()*meshScale;
int centerZ = vm["centerZ"].as<unsigned int>()*meshScale;
double nx = vm["nx"].as<double>();
double ny = vm["ny"].as<double>();
double nz = vm["nz"].as<double>();
if(vm.count("orientAutoFrontX")|| vm.count("orientAutoFrontY") ||
vm.count("orientAutoFrontZ"))
{
Z3i::Point ptL = meshVolImage.domain().lowerBound();
Z3i::Point ptU = meshVolImage.domain().upperBound();
Z3i::Point ptC = (ptL+ptU)/2;
centerX=ptC[0]; centerY=ptC[1]; centerZ=ptC[2];
nx=0; ny=0; nz=0;
}
bool opp = vm.count("orientBack");
if(vm.count("orientAutoFrontX"))
{
nx=(opp?-1.0:1.0);
maxScan = meshVolImage.domain().upperBound()[0]- meshVolImage.domain().lowerBound()[0];
centerX = centerX + (opp? maxScan/2: -maxScan/2) ;
}
if(vm.count("orientAutoFrontY"))
{
ny=(opp?-1.0:1.0);
maxScan = meshVolImage.domain().upperBound()[1]- meshVolImage.domain().lowerBound()[1];
centerY = centerY + (opp? maxScan/2: -maxScan/2);
}
if(vm.count("orientAutoFrontZ"))
{
nz=(opp?-1.0:1.0);
maxScan = meshVolImage.domain().upperBound()[2]-meshVolImage.domain().lowerBound()[2];
centerZ = centerZ + (opp? maxScan/2: -maxScan/2);
}
functors::Rescaling<unsigned int, Image2D::Value> scaleFctDepth(0, maxScan, 0, 255);
if(maxScan > std::numeric_limits<Image2D::Value>::max())
{
trace.info()<< "Max depth value outside image intensity range: " << maxScan
<< " (use a rescaling functor which implies a loss of precision)" << std::endl;
}
trace.info() << "Processing image to output file " << outputFilename;
Image2D::Domain aDomain2D(DGtal::Z2i::Point(0,0),
DGtal::Z2i::Point(widthImageScan, heightImageScan));
Z3i::Point ptCenter (centerX, centerY, centerZ);
Z3i::RealPoint normalDir (nx, ny, nz);
Image2D resultingImage(aDomain2D);
VectorFieldImage2D resultingVectorField(aDomain2D);
for(Image2D::Domain::ConstIterator it = resultingImage.domain().begin();
it != resultingImage.domain().end(); it++){
resultingImage.setValue(*it, 0);
resultingVectorField.setValue(*it, z);
}
DGtal::functors::Identity idV;
unsigned int maxDepthFound = 0;
for(unsigned int k=0; k < maxScan; k++)
{
trace.progressBar(k, maxScan);
DGtal::functors::Point2DEmbedderIn3D<DGtal::Z3i::Domain > embedder(meshVolImage.domain(),
ptCenter+normalDir*k,
normalDir,
widthImageScan);
ImageAdapterExtractor extractedImage(meshVolImage, aDomain2D, embedder, idV);
for(Image2D::Domain::ConstIterator it = extractedImage.domain().begin();
it != extractedImage.domain().end(); it++)
{
if(resultingImage(*it)== 0 && extractedImage(*it)!=0)
{
maxDepthFound = k;
resultingImage.setValue(*it, scaleFctDepth(maxScan-k));
resultingVectorField.setValue(*it, getNormal(meshNormalImage(embedder(*it)), embedder));
}
}
}
if (vm.count("setBackgroundLastDepth"))
{
for(Image2D::Domain::ConstIterator it = resultingImage.domain().begin();
it != resultingImage.domain().end(); it++){
if( resultingImage(*it)== 0 )
{
resultingImage.setValue(*it, scaleFctDepth(maxScan-maxDepthFound));
}
}
}
bool inverBgNormal = vm.count("backgroundNormalBack");
for(Image2D::Domain::ConstIterator it = resultingImage.domain().begin();
it != resultingImage.domain().end(); it++){
if(resultingVectorField(*it)==Z3i::RealPoint(0.0, 0.0, 0.0))
{
resultingVectorField.setValue(*it,Z3i::RealPoint(0, 0, inverBgNormal?-1: 1));
}
}
resultingImage >> outputFilename;
if(vm.count("exportNormals")){
std::stringstream ss;
ss << outputFilename << ".normals";
std::ofstream outN;
outN.open(ss.str().c_str(), std::ofstream::out);
for(Image2D::Domain::ConstIterator it = resultingImage.domain().begin();
it != resultingImage.domain().end(); it++){
outN << (*it)[0] << " " << (*it)[1] << " " << 0 << std::endl;
outN <<(*it)[0]+ resultingVectorField(*it)[0] << " "
<<(*it)[1]+resultingVectorField(*it)[1] << " "
<< resultingVectorField(*it)[2];
outN << std::endl;
}
}
return 0;
}
| jlevallois/DGtalTools | converters/mesh2heightfield.cpp | C++ | lgpl-3.0 | 14,290 |
<?php
namespace Mesour\DataGrid\Extensions;
use \Nette\Application\UI\Control;
/**
* @author mesour <matous.nemec@mesour.com>
* @package Mesour DataGrid
*/
class BaseControl extends Control {
/**
* @var \Nette\Http\SessionSection
*/
private $private_session;
/**
* @persistent Array
*/
public $settings = array();
public function getSession() {
if (!$this->private_session) {
$this->private_session = $this->presenter->getSession()->getSection($this->parent->getGridName() . $this->getName());
}
return $this->private_session;
}
public function loadState(array $params) {
$session = $this->getSession();
if (!empty($params) && isset($params['settings'])) {
$settings = array();
foreach ($params['settings'] as $key => $val) {
$settings[$key] = $val;
}
$session['settings'] = $settings;
} elseif (!empty($session['settings'])) {
foreach ($session['settings'] as $key => $val) {
$params['settings'][$key] = $val;
}
}
if($this->getName() === 'ordering') {
//echo $this->parent->getGridName() . $this->getName();
//print_r($params);
}
parent::loadState($params);
}
protected function createTemplate($class = NULL) {
$template = parent::createTemplate($class);
$template->setTranslator($this->parent["translator"]);
return $template;
}
} | weprove/titan | vendor/mesour/datagrid/src/Extensions/BaseControl.php | PHP | lgpl-3.0 | 1,322 |
/*
* Copyright (C) 2013 Raquel Pau and Albert Coroleu.
*
* Walkmod is free software: you can redistribute it and/or modify it under the terms of the GNU
* Lesser General Public License as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* Walkmod is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with Walkmod. If
* not, see <http://www.gnu.org/licenses/>.
*/
package org.walkmod.javalang.ast;
import org.walkmod.javalang.visitors.GenericVisitor;
import org.walkmod.javalang.visitors.VoidVisitor;
/**
* <p>
* AST node that represent line comments.
* </p>
* Line comments are started with "//" and finish at the end of the line ("\n").
*
* @author Julio Vilmar Gesser
*/
public final class LineComment extends Comment {
public LineComment() {}
public LineComment(String content) {
super(content);
}
public LineComment(int beginLine, int beginColumn, int endLine, int endColumn, String content) {
super(beginLine, beginColumn, endLine, endColumn, content);
}
@Override
public <R, A> R accept(GenericVisitor<R, A> v, A arg) {
if (!check()) {
return null;
}
return v.visit(this, arg);
}
@Override
public <A> void accept(VoidVisitor<A> v, A arg) {
if (check()) {
v.visit(this, arg);
}
}
@Override
public LineComment clone() throws CloneNotSupportedException {
return new LineComment(getContent());
}
}
| rpau/javalang | src/main/java/org/walkmod/javalang/ast/LineComment.java | Java | lgpl-3.0 | 1,807 |
package org.sahsu.rif.generic.presentation;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import org.sahsu.rif.generic.system.Messages;
/**
*
* A generic button control panel that supports navigation through a work flow. Only buttons that
* can be pressed appear in any state. For example, if the work flow is set on the first state,
* the previous and first button will not show. It also suggests the distinction between "First" and
* "Start Again" buttons. The "First" button is meant to move the work flow to the first step in the
* work flow. In a workflow, it is meant to suggest that if you go back to the first step, you will
* preserve the work you've done in that step. "Start Again" suggests that when the work flow moves
* to the first step, but all changed all the work done before will be discarded.
*
* <hr>
* Copyright 2017 Imperial College London, developed by the Small Area
* Health Statistics Unit.
*
* <pre>
* This file is part of the Rapid Inquiry Facility (RIF) project.
* RIF is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* RIF is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with RIF. If not, see <http://www.gnu.org/licenses/>.
* </pre>
*
* <hr>
* Kevin Garwood
* @author kgarwood
*/
/*
* Code Road Map:
* --------------
* Code is organised into the following sections. Wherever possible,
* methods are classified based on an order of precedence described in
* parentheses (..). For example, if you're trying to find a method
* 'getName(...)' that is both an interface method and an accessor
* method, the order tells you it should appear under interface.
*
* Order of
* Precedence Section
* ========== ======
* (1) Section Constants
* (2) Section Properties
* (3) Section Construction
* (7) Section Accessors and Mutators
* (6) Section Errors and Validation
* (5) Section Interfaces
* (4) Section Override
*
*/
public final class WorkflowNavigationButtonPanel
extends AbstractNavigationPanel {
// ==========================================
// Section Constants
// ==========================================
private static final Messages GENERIC_MESSAGES = Messages.genericMessages();
// ==========================================
// Section Properties
// ==========================================
private JPanel panel;
private JButton startAgainButton;
private JButton submitButton;
private JButton quitButton;
// ==========================================
// Section Construction
// ==========================================
public WorkflowNavigationButtonPanel(
final UserInterfaceFactory userInterfaceFactory) {
super(userInterfaceFactory);
String submitButtonText
= GENERIC_MESSAGES.getMessage("buttons.submit.label");
submitButton
= userInterfaceFactory.createButton(submitButtonText);
String quitButtonText
= GENERIC_MESSAGES.getMessage("buttons.quit.label");
quitButton
= userInterfaceFactory.createButton(quitButtonText);
panel = userInterfaceFactory.createBorderLayoutPanel();
}
public void startAgainButton(JButton startAgainButton) {
this.startAgainButton = startAgainButton;
}
public boolean isStartAgainButton(Object item) {
if (startAgainButton == null) {
return false;
}
return startAgainButton.equals(item);
}
// ==========================================
// Section Accessors and Mutators
// ==========================================
public boolean isQuitButton(
final Object item) {
if (item == null) {
return false;
}
return quitButton.equals(item);
}
public boolean isSubmitButton(
final Object item) {
if (item == null) {
return false;
}
return submitButton.equals(item);
}
public void showStartState() {
panel.removeAll();
JPanel rightPanel = userInterfaceFactory.createPanel();
GridBagConstraints rightPanelGC = userInterfaceFactory.createGridBagConstraints();
rightPanel.add(nextButton, rightPanelGC);
rightPanelGC.gridx++;
rightPanel.add(quitButton, rightPanelGC);
rightPanelGC.anchor = GridBagConstraints.SOUTHEAST;
panel.add(rightPanel, BorderLayout.EAST);
panel.updateUI();
}
public void showMiddleState() {
panel.removeAll();
panel.add(createLeftPanel(), BorderLayout.WEST);
JPanel rightPanel = userInterfaceFactory.createPanel();
GridBagConstraints rightPanelGC = userInterfaceFactory.createGridBagConstraints();
rightPanel.add(firstButton, rightPanelGC);
rightPanelGC.gridx++;
rightPanel.add(previousButton, rightPanelGC);
rightPanelGC.gridx++;
rightPanel.add(nextButton, rightPanelGC);
rightPanelGC.gridx++;
rightPanel.add(quitButton, rightPanelGC);
rightPanelGC.anchor = GridBagConstraints.SOUTHEAST;
panel.add(rightPanel, BorderLayout.EAST);
panel.updateUI();
}
public void showEndState() {
panel.removeAll();
panel.add(createLeftPanel(), BorderLayout.WEST);
JPanel rightPanel = userInterfaceFactory.createPanel();
GridBagConstraints rightPanelGC = userInterfaceFactory.createGridBagConstraints();
rightPanelGC.anchor = GridBagConstraints.SOUTHEAST;
rightPanel.add(firstButton, rightPanelGC);
rightPanelGC.gridx++;
rightPanel.add(previousButton, rightPanelGC);
rightPanelGC.gridx++;
rightPanel.add(submitButton, rightPanelGC);
panel.add(rightPanel, BorderLayout.EAST);
panel.updateUI();
}
private JPanel createLeftPanel() {
JPanel panel = userInterfaceFactory.createPanel();
if (startAgainButton != null) {
GridBagConstraints panelGC
= userInterfaceFactory.createGridBagConstraints();
panelGC.anchor = GridBagConstraints.SOUTHWEST;
panel.add(startAgainButton, panelGC);
}
return panel;
}
public JPanel getPanel() {
return panel;
}
public void addActionListener(
final ActionListener actionListener) {
super.addActionListener(actionListener);
startAgainButton.addActionListener(actionListener);
submitButton.addActionListener(actionListener);
quitButton.addActionListener(actionListener);
}
// ==========================================
// Section Errors and Validation
// ==========================================
// ==========================================
// Section Interfaces
// ==========================================
// ==========================================
// Section Override
// ==========================================
}
| smallAreaHealthStatisticsUnit/rapidInquiryFacility | rifGenericLibrary/src/main/java/org/sahsu/rif/generic/presentation/WorkflowNavigationButtonPanel.java | Java | lgpl-3.0 | 7,055 |
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QtAws is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "sendannouncementrequest.h"
#include "sendannouncementrequest_p.h"
#include "sendannouncementresponse.h"
#include "alexaforbusinessrequest_p.h"
namespace QtAws {
namespace AlexaForBusiness {
/*!
* \class QtAws::AlexaForBusiness::SendAnnouncementRequest
* \brief The SendAnnouncementRequest class provides an interface for AlexaForBusiness SendAnnouncement requests.
*
* \inmodule QtAwsAlexaForBusiness
*
* Alexa for Business helps you use Alexa in your organization. Alexa for Business provides you with the tools to manage
* Alexa devices, enroll your users, and assign skills, at scale. You can build your own context-aware voice skills using
* the Alexa Skills Kit and the Alexa for Business API operations. You can also make these available as private skills for
* your organization. Alexa for Business makes it efficient to voice-enable your products and services, thus providing
* context-aware voice experiences for your customers. Device makers building with the Alexa Voice Service (AVS) can create
* fully integrated solutions, register their products with Alexa for Business, and manage them as shared devices in their
* organization.
*
* \sa AlexaForBusinessClient::sendAnnouncement
*/
/*!
* Constructs a copy of \a other.
*/
SendAnnouncementRequest::SendAnnouncementRequest(const SendAnnouncementRequest &other)
: AlexaForBusinessRequest(new SendAnnouncementRequestPrivate(*other.d_func(), this))
{
}
/*!
* Constructs a SendAnnouncementRequest object.
*/
SendAnnouncementRequest::SendAnnouncementRequest()
: AlexaForBusinessRequest(new SendAnnouncementRequestPrivate(AlexaForBusinessRequest::SendAnnouncementAction, this))
{
}
/*!
* \reimp
*/
bool SendAnnouncementRequest::isValid() const
{
return false;
}
/*!
* Returns a SendAnnouncementResponse object to process \a reply.
*
* \sa QtAws::Core::AwsAbstractClient::send
*/
QtAws::Core::AwsAbstractResponse * SendAnnouncementRequest::response(QNetworkReply * const reply) const
{
return new SendAnnouncementResponse(*this, reply);
}
/*!
* \class QtAws::AlexaForBusiness::SendAnnouncementRequestPrivate
* \brief The SendAnnouncementRequestPrivate class provides private implementation for SendAnnouncementRequest.
* \internal
*
* \inmodule QtAwsAlexaForBusiness
*/
/*!
* Constructs a SendAnnouncementRequestPrivate object for AlexaForBusiness \a action,
* with public implementation \a q.
*/
SendAnnouncementRequestPrivate::SendAnnouncementRequestPrivate(
const AlexaForBusinessRequest::Action action, SendAnnouncementRequest * const q)
: AlexaForBusinessRequestPrivate(action, q)
{
}
/*!
* Constructs a copy of \a other, with public implementation \a q.
*
* This copy-like constructor exists for the benefit of the SendAnnouncementRequest
* class' copy constructor.
*/
SendAnnouncementRequestPrivate::SendAnnouncementRequestPrivate(
const SendAnnouncementRequestPrivate &other, SendAnnouncementRequest * const q)
: AlexaForBusinessRequestPrivate(other, q)
{
}
} // namespace AlexaForBusiness
} // namespace QtAws
| pcolby/libqtaws | src/alexaforbusiness/sendannouncementrequest.cpp | C++ | lgpl-3.0 | 3,810 |
package com.chuidiang.ejemplos.subscription;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.StreamSerializer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class MyDataSerializer implements StreamSerializer<Object>{
@Override
public void write(ObjectDataOutput objectDataOutput, Object data) throws IOException {
Kryo kryo = new Kryo();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Output output = new Output(bos);
kryo.writeClassAndObject(output, data);
objectDataOutput.writeByteArray(output.getBuffer());
}
@Override
public Object read(ObjectDataInput objectDataInput) throws IOException {
Kryo kryo = new Kryo();
byte [] buffer = objectDataInput.readByteArray();
Input input = new Input(buffer);
Object data = kryo.readClassAndObject(input);
return data;
}
@Override
public int getTypeId() {
return 1;
}
@Override
public void destroy() {
}
}
| chuidiang/chuidiang-ejemplos | JAVA/hazelcast-example/src/main/java/com/chuidiang/ejemplos/subscription/MyDataSerializer.java | Java | lgpl-3.0 | 1,236 |
<?php
namespace Google\AdsApi\Dfp\v201711;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class performReconciliationOrderReportActionResponse
{
/**
* @var \Google\AdsApi\Dfp\v201711\UpdateResult $rval
*/
protected $rval = null;
/**
* @param \Google\AdsApi\Dfp\v201711\UpdateResult $rval
*/
public function __construct($rval = null)
{
$this->rval = $rval;
}
/**
* @return \Google\AdsApi\Dfp\v201711\UpdateResult
*/
public function getRval()
{
return $this->rval;
}
/**
* @param \Google\AdsApi\Dfp\v201711\UpdateResult $rval
* @return \Google\AdsApi\Dfp\v201711\performReconciliationOrderReportActionResponse
*/
public function setRval($rval)
{
$this->rval = $rval;
return $this;
}
}
| advanced-online-marketing/AOM | vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201711/performReconciliationOrderReportActionResponse.php | PHP | lgpl-3.0 | 828 |
// Copyright 2019 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package rawdb
import (
"encoding/binary"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sync"
"sync/atomic"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/metrics"
"github.com/golang/snappy"
)
var (
// errClosed is returned if an operation attempts to read from or write to the
// freezer table after it has already been closed.
errClosed = errors.New("closed")
// errOutOfBounds is returned if the item requested is not contained within the
// freezer table.
errOutOfBounds = errors.New("out of bounds")
// errNotSupported is returned if the database doesn't support the required operation.
errNotSupported = errors.New("this operation is not supported")
)
// indexEntry contains the number/id of the file that the data resides in, aswell as the
// offset within the file to the end of the data
// In serialized form, the filenum is stored as uint16.
type indexEntry struct {
filenum uint32 // stored as uint16 ( 2 bytes)
offset uint32 // stored as uint32 ( 4 bytes)
}
const indexEntrySize = 6
// unmarshallBinary deserializes binary b into the rawIndex entry.
func (i *indexEntry) unmarshalBinary(b []byte) error {
i.filenum = uint32(binary.BigEndian.Uint16(b[:2]))
i.offset = binary.BigEndian.Uint32(b[2:6])
return nil
}
// marshallBinary serializes the rawIndex entry into binary.
func (i *indexEntry) marshallBinary() []byte {
b := make([]byte, indexEntrySize)
binary.BigEndian.PutUint16(b[:2], uint16(i.filenum))
binary.BigEndian.PutUint32(b[2:6], i.offset)
return b
}
// freezerTable represents a single chained data table within the freezer (e.g. blocks).
// It consists of a data file (snappy encoded arbitrary data blobs) and an indexEntry
// file (uncompressed 64 bit indices into the data file).
type freezerTable struct {
// WARNING: The `items` field is accessed atomically. On 32 bit platforms, only
// 64-bit aligned fields can be atomic. The struct is guaranteed to be so aligned,
// so take advantage of that (https://golang.org/pkg/sync/atomic/#pkg-note-BUG).
items uint64 // Number of items stored in the table (including items removed from tail)
noCompression bool // if true, disables snappy compression. Note: does not work retroactively
maxFileSize uint32 // Max file size for data-files
name string
path string
head *os.File // File descriptor for the data head of the table
files map[uint32]*os.File // open files
headId uint32 // number of the currently active head file
tailId uint32 // number of the earliest file
index *os.File // File descriptor for the indexEntry file of the table
// In the case that old items are deleted (from the tail), we use itemOffset
// to count how many historic items have gone missing.
itemOffset uint32 // Offset (number of discarded items)
headBytes uint32 // Number of bytes written to the head file
readMeter metrics.Meter // Meter for measuring the effective amount of data read
writeMeter metrics.Meter // Meter for measuring the effective amount of data written
sizeGauge metrics.Gauge // Gauge for tracking the combined size of all freezer tables
logger log.Logger // Logger with database path and table name ambedded
lock sync.RWMutex // Mutex protecting the data file descriptors
}
// NewFreezerTable opens the given path as a freezer table.
func NewFreezerTable(path, name string, disableSnappy bool) (*freezerTable, error) {
return newTable(path, name, metrics.NilMeter{}, metrics.NilMeter{}, metrics.NilGauge{}, disableSnappy)
}
// newTable opens a freezer table with default settings - 2G files
func newTable(path string, name string, readMeter metrics.Meter, writeMeter metrics.Meter, sizeGauge metrics.Gauge, disableSnappy bool) (*freezerTable, error) {
return newCustomTable(path, name, readMeter, writeMeter, sizeGauge, 2*1000*1000*1000, disableSnappy)
}
// openFreezerFileForAppend opens a freezer table file and seeks to the end
func openFreezerFileForAppend(filename string) (*os.File, error) {
// Open the file without the O_APPEND flag
// because it has differing behaviour during Truncate operations
// on different OS's
file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return nil, err
}
// Seek to end for append
if _, err = file.Seek(0, io.SeekEnd); err != nil {
return nil, err
}
return file, nil
}
// openFreezerFileForReadOnly opens a freezer table file for read only access
func openFreezerFileForReadOnly(filename string) (*os.File, error) {
return os.OpenFile(filename, os.O_RDONLY, 0644)
}
// openFreezerFileTruncated opens a freezer table making sure it is truncated
func openFreezerFileTruncated(filename string) (*os.File, error) {
return os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
}
// truncateFreezerFile resizes a freezer table file and seeks to the end
func truncateFreezerFile(file *os.File, size int64) error {
if err := file.Truncate(size); err != nil {
return err
}
// Seek to end for append
if _, err := file.Seek(0, io.SeekEnd); err != nil {
return err
}
return nil
}
// newCustomTable opens a freezer table, creating the data and index files if they are
// non existent. Both files are truncated to the shortest common length to ensure
// they don't go out of sync.
func newCustomTable(path string, name string, readMeter metrics.Meter, writeMeter metrics.Meter, sizeGauge metrics.Gauge, maxFilesize uint32, noCompression bool) (*freezerTable, error) {
// Ensure the containing directory exists and open the indexEntry file
if err := os.MkdirAll(path, 0755); err != nil {
return nil, err
}
var idxName string
if noCompression {
// Raw idx
idxName = fmt.Sprintf("%s.ridx", name)
} else {
// Compressed idx
idxName = fmt.Sprintf("%s.cidx", name)
}
offsets, err := openFreezerFileForAppend(filepath.Join(path, idxName))
if err != nil {
return nil, err
}
// Create the table and repair any past inconsistency
tab := &freezerTable{
index: offsets,
files: make(map[uint32]*os.File),
readMeter: readMeter,
writeMeter: writeMeter,
sizeGauge: sizeGauge,
name: name,
path: path,
logger: log.New("database", path, "table", name),
noCompression: noCompression,
maxFileSize: maxFilesize,
}
if err := tab.repair(); err != nil {
tab.Close()
return nil, err
}
// Initialize the starting size counter
size, err := tab.sizeNolock()
if err != nil {
tab.Close()
return nil, err
}
tab.sizeGauge.Inc(int64(size))
return tab, nil
}
// repair cross checks the head and the index file and truncates them to
// be in sync with each other after a potential crash / data loss.
func (t *freezerTable) repair() error {
// Create a temporary offset buffer to init files with and read indexEntry into
buffer := make([]byte, indexEntrySize)
// If we've just created the files, initialize the index with the 0 indexEntry
stat, err := t.index.Stat()
if err != nil {
return err
}
if stat.Size() == 0 {
if _, err := t.index.Write(buffer); err != nil {
return err
}
}
// Ensure the index is a multiple of indexEntrySize bytes
if overflow := stat.Size() % indexEntrySize; overflow != 0 {
truncateFreezerFile(t.index, stat.Size()-overflow) // New file can't trigger this path
}
// Retrieve the file sizes and prepare for truncation
if stat, err = t.index.Stat(); err != nil {
return err
}
offsetsSize := stat.Size()
// Open the head file
var (
firstIndex indexEntry
lastIndex indexEntry
contentSize int64
contentExp int64
)
// Read index zero, determine what file is the earliest
// and what item offset to use
t.index.ReadAt(buffer, 0)
firstIndex.unmarshalBinary(buffer)
t.tailId = firstIndex.filenum
t.itemOffset = firstIndex.offset
t.index.ReadAt(buffer, offsetsSize-indexEntrySize)
lastIndex.unmarshalBinary(buffer)
t.head, err = t.openFile(lastIndex.filenum, openFreezerFileForAppend)
if err != nil {
return err
}
if stat, err = t.head.Stat(); err != nil {
return err
}
contentSize = stat.Size()
// Keep truncating both files until they come in sync
contentExp = int64(lastIndex.offset)
for contentExp != contentSize {
// Truncate the head file to the last offset pointer
if contentExp < contentSize {
t.logger.Warn("Truncating dangling head", "indexed", common.StorageSize(contentExp), "stored", common.StorageSize(contentSize))
if err := truncateFreezerFile(t.head, contentExp); err != nil {
return err
}
contentSize = contentExp
}
// Truncate the index to point within the head file
if contentExp > contentSize {
t.logger.Warn("Truncating dangling indexes", "indexed", common.StorageSize(contentExp), "stored", common.StorageSize(contentSize))
if err := truncateFreezerFile(t.index, offsetsSize-indexEntrySize); err != nil {
return err
}
offsetsSize -= indexEntrySize
t.index.ReadAt(buffer, offsetsSize-indexEntrySize)
var newLastIndex indexEntry
newLastIndex.unmarshalBinary(buffer)
// We might have slipped back into an earlier head-file here
if newLastIndex.filenum != lastIndex.filenum {
// Release earlier opened file
t.releaseFile(lastIndex.filenum)
if t.head, err = t.openFile(newLastIndex.filenum, openFreezerFileForAppend); err != nil {
return err
}
if stat, err = t.head.Stat(); err != nil {
// TODO, anything more we can do here?
// A data file has gone missing...
return err
}
contentSize = stat.Size()
}
lastIndex = newLastIndex
contentExp = int64(lastIndex.offset)
}
}
// Ensure all reparation changes have been written to disk
if err := t.index.Sync(); err != nil {
return err
}
if err := t.head.Sync(); err != nil {
return err
}
// Update the item and byte counters and return
t.items = uint64(t.itemOffset) + uint64(offsetsSize/indexEntrySize-1) // last indexEntry points to the end of the data file
t.headBytes = uint32(contentSize)
t.headId = lastIndex.filenum
// Close opened files and preopen all files
if err := t.preopen(); err != nil {
return err
}
t.logger.Debug("Chain freezer table opened", "items", t.items, "size", common.StorageSize(t.headBytes))
return nil
}
// preopen opens all files that the freezer will need. This method should be called from an init-context,
// since it assumes that it doesn't have to bother with locking
// The rationale for doing preopen is to not have to do it from within Retrieve, thus not needing to ever
// obtain a write-lock within Retrieve.
func (t *freezerTable) preopen() (err error) {
// The repair might have already opened (some) files
t.releaseFilesAfter(0, false)
// Open all except head in RDONLY
for i := t.tailId; i < t.headId; i++ {
if _, err = t.openFile(i, openFreezerFileForReadOnly); err != nil {
return err
}
}
// Open head in read/write
t.head, err = t.openFile(t.headId, openFreezerFileForAppend)
return err
}
// truncate discards any recent data above the provided threshold number.
func (t *freezerTable) truncate(items uint64) error {
t.lock.Lock()
defer t.lock.Unlock()
// If our item count is correct, don't do anything
existing := atomic.LoadUint64(&t.items)
if existing <= items {
return nil
}
// We need to truncate, save the old size for metrics tracking
oldSize, err := t.sizeNolock()
if err != nil {
return err
}
// Something's out of sync, truncate the table's offset index
log := t.logger.Debug
if existing > items+1 {
log = t.logger.Warn // Only loud warn if we delete multiple items
}
log("Truncating freezer table", "items", existing, "limit", items)
if err := truncateFreezerFile(t.index, int64(items+1)*indexEntrySize); err != nil {
return err
}
// Calculate the new expected size of the data file and truncate it
buffer := make([]byte, indexEntrySize)
if _, err := t.index.ReadAt(buffer, int64(items*indexEntrySize)); err != nil {
return err
}
var expected indexEntry
expected.unmarshalBinary(buffer)
// We might need to truncate back to older files
if expected.filenum != t.headId {
// If already open for reading, force-reopen for writing
t.releaseFile(expected.filenum)
newHead, err := t.openFile(expected.filenum, openFreezerFileForAppend)
if err != nil {
return err
}
// Release any files _after the current head -- both the previous head
// and any files which may have been opened for reading
t.releaseFilesAfter(expected.filenum, true)
// Set back the historic head
t.head = newHead
atomic.StoreUint32(&t.headId, expected.filenum)
}
if err := truncateFreezerFile(t.head, int64(expected.offset)); err != nil {
return err
}
// All data files truncated, set internal counters and return
atomic.StoreUint64(&t.items, items)
atomic.StoreUint32(&t.headBytes, expected.offset)
// Retrieve the new size and update the total size counter
newSize, err := t.sizeNolock()
if err != nil {
return err
}
t.sizeGauge.Dec(int64(oldSize - newSize))
return nil
}
// Close closes all opened files.
func (t *freezerTable) Close() error {
t.lock.Lock()
defer t.lock.Unlock()
var errs []error
if err := t.index.Close(); err != nil {
errs = append(errs, err)
}
t.index = nil
for _, f := range t.files {
if err := f.Close(); err != nil {
errs = append(errs, err)
}
}
t.head = nil
if errs != nil {
return fmt.Errorf("%v", errs)
}
return nil
}
// openFile assumes that the write-lock is held by the caller
func (t *freezerTable) openFile(num uint32, opener func(string) (*os.File, error)) (f *os.File, err error) {
var exist bool
if f, exist = t.files[num]; !exist {
var name string
if t.noCompression {
name = fmt.Sprintf("%s.%04d.rdat", t.name, num)
} else {
name = fmt.Sprintf("%s.%04d.cdat", t.name, num)
}
f, err = opener(filepath.Join(t.path, name))
if err != nil {
return nil, err
}
t.files[num] = f
}
return f, err
}
// releaseFile closes a file, and removes it from the open file cache.
// Assumes that the caller holds the write lock
func (t *freezerTable) releaseFile(num uint32) {
if f, exist := t.files[num]; exist {
delete(t.files, num)
f.Close()
}
}
// releaseFilesAfter closes all open files with a higher number, and optionally also deletes the files
func (t *freezerTable) releaseFilesAfter(num uint32, remove bool) {
for fnum, f := range t.files {
if fnum > num {
delete(t.files, fnum)
f.Close()
if remove {
os.Remove(f.Name())
}
}
}
}
// Append injects a binary blob at the end of the freezer table. The item number
// is a precautionary parameter to ensure data correctness, but the table will
// reject already existing data.
//
// Note, this method will *not* flush any data to disk so be sure to explicitly
// fsync before irreversibly deleting data from the database.
func (t *freezerTable) Append(item uint64, blob []byte) error {
// Read lock prevents competition with truncate
t.lock.RLock()
// Ensure the table is still accessible
if t.index == nil || t.head == nil {
t.lock.RUnlock()
return errClosed
}
// Ensure only the next item can be written, nothing else
if atomic.LoadUint64(&t.items) != item {
t.lock.RUnlock()
return fmt.Errorf("appending unexpected item: want %d, have %d", t.items, item)
}
// Encode the blob and write it into the data file
if !t.noCompression {
blob = snappy.Encode(nil, blob)
}
bLen := uint32(len(blob))
if t.headBytes+bLen < bLen ||
t.headBytes+bLen > t.maxFileSize {
// we need a new file, writing would overflow
t.lock.RUnlock()
t.lock.Lock()
nextID := atomic.LoadUint32(&t.headId) + 1
// We open the next file in truncated mode -- if this file already
// exists, we need to start over from scratch on it
newHead, err := t.openFile(nextID, openFreezerFileTruncated)
if err != nil {
t.lock.Unlock()
return err
}
// Close old file, and reopen in RDONLY mode
t.releaseFile(t.headId)
t.openFile(t.headId, openFreezerFileForReadOnly)
// Swap out the current head
t.head = newHead
atomic.StoreUint32(&t.headBytes, 0)
atomic.StoreUint32(&t.headId, nextID)
t.lock.Unlock()
t.lock.RLock()
}
defer t.lock.RUnlock()
if _, err := t.head.Write(blob); err != nil {
return err
}
newOffset := atomic.AddUint32(&t.headBytes, bLen)
idx := indexEntry{
filenum: atomic.LoadUint32(&t.headId),
offset: newOffset,
}
// Write indexEntry
t.index.Write(idx.marshallBinary())
t.writeMeter.Mark(int64(bLen + indexEntrySize))
t.sizeGauge.Inc(int64(bLen + indexEntrySize))
atomic.AddUint64(&t.items, 1)
return nil
}
// getBounds returns the indexes for the item
// returns start, end, filenumber and error
func (t *freezerTable) getBounds(item uint64) (uint32, uint32, uint32, error) {
buffer := make([]byte, indexEntrySize)
var startIdx, endIdx indexEntry
// Read second index
if _, err := t.index.ReadAt(buffer, int64((item+1)*indexEntrySize)); err != nil {
return 0, 0, 0, err
}
endIdx.unmarshalBinary(buffer)
// Read first index (unless it's the very first item)
if item != 0 {
if _, err := t.index.ReadAt(buffer, int64(item*indexEntrySize)); err != nil {
return 0, 0, 0, err
}
startIdx.unmarshalBinary(buffer)
} else {
// Special case if we're reading the first item in the freezer. We assume that
// the first item always start from zero(regarding the deletion, we
// only support deletion by files, so that the assumption is held).
// This means we can use the first item metadata to carry information about
// the 'global' offset, for the deletion-case
return 0, endIdx.offset, endIdx.filenum, nil
}
if startIdx.filenum != endIdx.filenum {
// If a piece of data 'crosses' a data-file,
// it's actually in one piece on the second data-file.
// We return a zero-indexEntry for the second file as start
return 0, endIdx.offset, endIdx.filenum, nil
}
return startIdx.offset, endIdx.offset, endIdx.filenum, nil
}
// Retrieve looks up the data offset of an item with the given number and retrieves
// the raw binary blob from the data file.
func (t *freezerTable) Retrieve(item uint64) ([]byte, error) {
t.lock.RLock()
// Ensure the table and the item is accessible
if t.index == nil || t.head == nil {
t.lock.RUnlock()
return nil, errClosed
}
if atomic.LoadUint64(&t.items) <= item {
t.lock.RUnlock()
return nil, errOutOfBounds
}
// Ensure the item was not deleted from the tail either
if uint64(t.itemOffset) > item {
t.lock.RUnlock()
return nil, errOutOfBounds
}
startOffset, endOffset, filenum, err := t.getBounds(item - uint64(t.itemOffset))
if err != nil {
t.lock.RUnlock()
return nil, err
}
dataFile, exist := t.files[filenum]
if !exist {
t.lock.RUnlock()
return nil, fmt.Errorf("missing data file %d", filenum)
}
// Retrieve the data itself, decompress and return
blob := make([]byte, endOffset-startOffset)
if _, err := dataFile.ReadAt(blob, int64(startOffset)); err != nil {
t.lock.RUnlock()
return nil, err
}
t.lock.RUnlock()
t.readMeter.Mark(int64(len(blob) + 2*indexEntrySize))
if t.noCompression {
return blob, nil
}
return snappy.Decode(nil, blob)
}
// has returns an indicator whether the specified number data
// exists in the freezer table.
func (t *freezerTable) has(number uint64) bool {
return atomic.LoadUint64(&t.items) > number
}
// size returns the total data size in the freezer table.
func (t *freezerTable) size() (uint64, error) {
t.lock.RLock()
defer t.lock.RUnlock()
return t.sizeNolock()
}
// sizeNolock returns the total data size in the freezer table without obtaining
// the mutex first.
func (t *freezerTable) sizeNolock() (uint64, error) {
stat, err := t.index.Stat()
if err != nil {
return 0, err
}
total := uint64(t.maxFileSize)*uint64(t.headId-t.tailId) + uint64(t.headBytes) + uint64(stat.Size())
return total, nil
}
// Sync pushes any pending data from memory out to disk. This is an expensive
// operation, so use it with care.
func (t *freezerTable) Sync() error {
if err := t.index.Sync(); err != nil {
return err
}
return t.head.Sync()
}
// printIndex is a debug print utility function for testing
func (t *freezerTable) printIndex() {
buf := make([]byte, indexEntrySize)
fmt.Printf("|-----------------|\n")
fmt.Printf("| fileno | offset |\n")
fmt.Printf("|--------+--------|\n")
for i := uint64(0); ; i++ {
if _, err := t.index.ReadAt(buf, int64(i*indexEntrySize)); err != nil {
break
}
var entry indexEntry
entry.unmarshalBinary(buf)
fmt.Printf("| %03d | %03d | \n", entry.filenum, entry.offset)
if i > 100 {
fmt.Printf(" ... \n")
break
}
}
fmt.Printf("|-----------------|\n")
}
| tailingchen/go-ethereum | core/rawdb/freezer_table.go | GO | lgpl-3.0 | 21,471 |
#include "../../include/model/model.h"
/*
*residual for high order boundary condition
*/
template <class T, int dim>
void model<T, dim>::residualForHighOrderBC(knotSpan<dim>& cell, IGAValues<dim>& fe_values, dealii::Table<1, T >& ULocal, dealii::Table<1, T >& R)
{
//Weak dirichlet condition grad(u).n=0
unsigned int dofs_per_cell= fe_values.dofs_per_cell;
for (unsigned int faceID=0; faceID<2*dim; faceID++){
if ((cell.boundaryFlags[faceID]==(dim-1)*2+1) or (cell.boundaryFlags[faceID]==(dim-1)*2+2)){
//compute face normal (logic for computing n like this only works for cube geometries)
std::vector<double> n(dim, 0);
n[(cell.boundaryFlags[faceID]-1)/2]=std::pow(-1.0, (int)cell.boundaryFlags[faceID]%2);
//Temporary arrays
dealii::Table<3,Sacado::Fad::DFad<double> > PFace (fe_values.n_face_quadrature_points, dim, dim);
dealii::Table<4,Sacado::Fad::DFad<double> > BetaFace (fe_values.n_face_quadrature_points, dim, dim, dim);
evaluateStress(fe_values, ULocal, PFace, BetaFace,faceID);
//evaluate gradients on the faces
dealii::Table<3,Sacado::Fad::DFad<double> > uij(fe_values.n_face_quadrature_points, dim, dim); //uij.fill(0.0);
dealii::Table<4,Sacado::Fad::DFad<double> > uijk(fe_values.n_face_quadrature_points, dim, dim, dim); //uijk.fill(0.0);
for (unsigned int q=0; q<fe_values.n_face_quadrature_points; ++q){
for (unsigned int i=0; i<dim; ++i){
for (unsigned int j=0; j<dim; ++j){
uij[q][i][j]=0.0;
for (unsigned int k=0; k<dim; ++k){
uijk[q][i][j][k]=0.0;
}
}
}
}
//Loop over quadrature points
for (unsigned int q=0; q<fe_values.n_face_quadrature_points; ++q){
for (unsigned int d=0; d<dofs_per_cell; ++d){
unsigned int i = fe_values.system_to_component_index(d) - DOF;
for (unsigned int j=0; j<dim; ++j){
uij[q][i][j]+=ULocal[d]*fe_values.shape_grad_face(d, q, faceID)[j];
for (unsigned int k=0; k<dim; ++k){
uijk[q][i][j][k]+=ULocal[d]*fe_values.shape_grad_grad_face(d, q, faceID)[j][k];
}
}
}
}
//evaluate tensor multiplications
dealii::Table<2,Sacado::Fad::DFad<double> > uijn(fe_values.n_face_quadrature_points, dim); //uijn.fill(0.0);
dealii::Table<2,Sacado::Fad::DFad<double> > Betaijknn(fe_values.n_face_quadrature_points, dim);// Betaijknn.fill(0.0);
dealii::Table<2,double> wijn(fe_values.n_face_quadrature_points, dofs_per_cell); //wijn.fill(0.0);
dealii::Table<2,double> wijknn(fe_values.n_face_quadrature_points, dofs_per_cell); //wijknn.fill(0.0);
for (unsigned int q=0; q<fe_values.n_face_quadrature_points; ++q){
for (unsigned int i=0; i<dim; ++i){
uijn[q][i]=0.0;
Betaijknn[q][i]=0.0;
}
for(unsigned int j=0;j<dofs_per_cell;j++){
wijn[q][j]=0.0;
wijknn[q][j]=0.0;
}
}
//evaluate uijn, Betaijknn
for (unsigned int q=0; q<fe_values.n_face_quadrature_points; ++q){
double tempdirchletBC=0.0;
for (unsigned int i=0; i<dim; ++i){
for (unsigned int j=0; j<dim; ++j){
uijn[q][i]+=uij[q][i][j]*n[j];
for (unsigned int k=0; k<dim; ++k){
Betaijknn[q][i]+=BetaFace[q][i][j][k]*n[j]*n[k];
}
}
//tempdirchletBC+=std::pow(uijn[q][i].val(),2.0);
}
//dirchletBC=std::max(dirchletBC, std::pow(tempdirchletBC,0.5));
//gradun(fe_values.cell->id,q,i)= uijn[q][i].val();
}
//evaluate wijn, wijknn
for (unsigned int q=0; q<fe_values.n_face_quadrature_points; ++q){
for (unsigned int d=0; d<dofs_per_cell; ++d){
for (unsigned int j=0; j<dim; ++j){
wijn[q][d]+= fe_values.shape_grad_face(d, q, faceID)[j]*n[j];
for (unsigned int k=0; k<dim; ++k){
wijknn[q][d]+= fe_values.shape_grad_grad_face(d, q, faceID)[j][k]*n[j]*n[k];
}
}
}
}
//Add the weak dirichlet terms
for (unsigned int d=0; d<dofs_per_cell; ++d) {
unsigned int i = fe_values.system_to_component_index(d) - DOF;
if (i==dim-1){ //enforcing weak dirichlet only along dim direction
for (unsigned int q=0; q<fe_values.n_face_quadrature_points; ++q){
//-mu*l*l*w_(ij)n_j*Beta_(ijk)n_jn_k
R[d] += -wijn[q][d]*Betaijknn[q][i]*fe_values.JxW_face(q, faceID);
//-mu*l*l*gamma*wijknn*uijn //WRONG form curretnly. Not used now as there is no point trying to make an unsymmetric euqation adjoint consistent. So gamma is always set to zero.
gamma=0.0;
R[d] += -gamma*wijknn[q][d]*uijn[q][i]*fe_values.JxW_face(q, faceID);
//mu*l*l*(C/he)*wijn*uijn
R[d] += (C/he)*wijn[q][d]*uijn[q][i]*fe_values.JxW_face(q, faceID);
}
}
}
}
}
}
template class model<Sacado::Fad::DFad<double>,1>;
template class model<Sacado::Fad::DFad<double>,2>;
template class model<Sacado::Fad::DFad<double>,3>; | mechanoChem/openIGA | src/model/residualForHighOrderBC.cc | C++ | lgpl-3.0 | 4,925 |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE file at the root of the source
* tree and available online at
*
* https://github.com/keeps/roda
*/
package org.roda.wui.client.planning;
import java.util.Arrays;
import java.util.List;
import org.roda.core.data.common.RodaConstants;
import org.roda.core.data.exceptions.NotFoundException;
import org.roda.core.data.v2.formats.Format;
import org.roda.core.data.v2.index.select.SelectedItemsList;
import org.roda.wui.client.browse.BrowserService;
import org.roda.wui.client.common.UserLogin;
import org.roda.wui.client.common.utils.AsyncCallbackUtils;
import org.roda.wui.client.common.utils.JavascriptUtils;
import org.roda.wui.client.management.MemberManagement;
import org.roda.wui.common.client.HistoryResolver;
import org.roda.wui.common.client.tools.HistoryUtils;
import org.roda.wui.common.client.tools.ListUtils;
import org.roda.wui.common.client.widgets.Toast;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import config.i18n.client.ClientMessages;
public class EditFormat extends Composite {
public static final HistoryResolver RESOLVER = new HistoryResolver() {
@Override
public void resolve(List<String> historyTokens, final AsyncCallback<Widget> callback) {
if (historyTokens.size() == 1) {
String formatId = historyTokens.get(0);
BrowserService.Util.getInstance().retrieve(Format.class.getName(), formatId, fieldsToReturn,
new AsyncCallback<Format>() {
@Override
public void onFailure(Throwable caught) {
callback.onFailure(caught);
}
@Override
public void onSuccess(Format format) {
EditFormat editFormat = new EditFormat(format);
callback.onSuccess(editFormat);
}
});
} else {
HistoryUtils.newHistory(FormatRegister.RESOLVER);
callback.onSuccess(null);
}
}
@Override
public void isCurrentUserPermitted(AsyncCallback<Boolean> callback) {
UserLogin.getInstance().checkRoles(new HistoryResolver[] {MemberManagement.RESOLVER}, false, callback);
}
@Override
public List<String> getHistoryPath() {
return ListUtils.concat(FormatRegister.RESOLVER.getHistoryPath(), getHistoryToken());
}
@Override
public String getHistoryToken() {
return "edit_format";
}
};
interface MyUiBinder extends UiBinder<Widget, EditFormat> {
}
private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
private static ClientMessages messages = GWT.create(ClientMessages.class);
private Format format;
private static final List<String> fieldsToReturn = Arrays.asList(RodaConstants.INDEX_UUID, RodaConstants.FORMAT_ID,
RodaConstants.FORMAT_NAME, RodaConstants.FORMAT_DEFINITION, RodaConstants.FORMAT_CATEGORY,
RodaConstants.FORMAT_LATEST_VERSION, RodaConstants.FORMAT_DEVELOPER, RodaConstants.FORMAT_POPULARITY,
RodaConstants.FORMAT_INITIAL_RELEASE, RodaConstants.FORMAT_IS_OPEN_FORMAT, RodaConstants.FORMAT_STANDARD,
RodaConstants.FORMAT_WEBSITE, RodaConstants.FORMAT_PROVENANCE_INFORMATION, RodaConstants.FORMAT_EXTENSIONS,
RodaConstants.FORMAT_MIMETYPES, RodaConstants.FORMAT_PRONOMS, RodaConstants.FORMAT_UTIS,
RodaConstants.FORMAT_ALTERNATIVE_DESIGNATIONS, RodaConstants.FORMAT_VERSIONS);
@UiField
Button buttonApply;
@UiField
Button buttonRemove;
@UiField
Button buttonCancel;
@UiField(provided = true)
FormatDataPanel formatDataPanel;
/**
* Create a new panel to create a user
*
* @param user
* the user to create
*/
public EditFormat(Format format) {
this.format = format;
this.formatDataPanel = new FormatDataPanel(true, true, format);
initWidget(uiBinder.createAndBindUi(this));
}
@Override
protected void onLoad() {
super.onLoad();
JavascriptUtils.stickSidebar();
}
@UiHandler("buttonApply")
void buttonApplyHandler(ClickEvent e) {
if (formatDataPanel.isChanged() && formatDataPanel.isValid()) {
String formatId = format.getId();
format = formatDataPanel.getFormat();
format.setId(formatId);
BrowserService.Util.getInstance().updateFormat(format, new AsyncCallback<Void>() {
@Override
public void onFailure(Throwable caught) {
errorMessage(caught);
}
@Override
public void onSuccess(Void result) {
HistoryUtils.newHistory(ShowFormat.RESOLVER, format.getId());
}
});
} else {
HistoryUtils.newHistory(ShowFormat.RESOLVER, format.getId());
}
}
@UiHandler("buttonRemove")
void buttonRemoveHandler(ClickEvent e) {
BrowserService.Util.getInstance().deleteFormat(
new SelectedItemsList<Format>(Arrays.asList(format.getUUID()), Format.class.getName()),
new AsyncCallback<Void>() {
@Override
public void onFailure(Throwable caught) {
errorMessage(caught);
}
@Override
public void onSuccess(Void result) {
Timer timer = new Timer() {
@Override
public void run() {
HistoryUtils.newHistory(FormatRegister.RESOLVER);
}
};
timer.schedule(RodaConstants.ACTION_TIMEOUT);
}
});
}
@UiHandler("buttonCancel")
void buttonCancelHandler(ClickEvent e) {
cancel();
}
private void cancel() {
HistoryUtils.newHistory(ShowFormat.RESOLVER, format.getId());
}
private void errorMessage(Throwable caught) {
if (caught instanceof NotFoundException) {
Toast.showError(messages.editFormatNotFound(format.getName()));
cancel();
} else {
AsyncCallbackUtils.defaultFailureTreatment(caught);
}
}
protected void enableApplyButton(boolean enabled) {
buttonApply.setVisible(enabled);
}
}
| rui-castro/roda | roda-ui/roda-wui/src/main/java/org/roda/wui/client/planning/EditFormat.java | Java | lgpl-3.0 | 6,316 |
package ch.loway.oss.ari4java.generated.ari_1_7_0.models;
// ----------------------------------------------------
// THIS CLASS WAS GENERATED AUTOMATICALLY
// PLEASE DO NOT EDIT
// Generated on: Sat Sep 19 08:50:54 CEST 2015
// ----------------------------------------------------
import ch.loway.oss.ari4java.generated.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**********************************************************
* Info about Asterisk
*
* Defined in file: asterisk.json
* Generated by: Model
*********************************************************/
public class SystemInfo_impl_ari_1_7_0 implements SystemInfo, java.io.Serializable {
private static final long serialVersionUID = 1L;
/** */
private String entity_id;
public String getEntity_id() {
return entity_id;
}
@JsonDeserialize( as=String.class )
public void setEntity_id(String val ) {
entity_id = val;
}
/** Asterisk version. */
private String version;
public String getVersion() {
return version;
}
@JsonDeserialize( as=String.class )
public void setVersion(String val ) {
version = val;
}
/** No missing signatures from interface */
}
| korvus81/ari4java | classes/ch/loway/oss/ari4java/generated/ari_1_7_0/models/SystemInfo_impl_ari_1_7_0.java | Java | lgpl-3.0 | 1,302 |
{
'name' : 'Signature templates for user emails',
'version' : '1.0.0',
'author' : 'IT-Projects LLC, Ivan Yelizariev',
'license': 'LGPL-3',
'category' : 'Social Network',
'website' : 'https://yelizariev.github.io',
'depends' : ['base'],
'data':[
'res_users_signature_views.xml',
'security/res_users_signature_security.xml',
'security/ir.model.access.csv',
],
'installable': False
}
| iledarn/addons-yelizariev | res_users_signature/__openerp__.py | Python | lgpl-3.0 | 445 |
//
// GCM.hpp
// OrbSlam
//
// Created by Manuel Deneu on 16/02/2017.
// Copyright © 2017 FlyLab. All rights reserved.
//
#ifndef GCM_h
#define GCM_h
#include "GCMDefinitions.hpp"
#endif /* GCM_h */
| manu88/ORB_SLAM | GCM/include/GCM.hpp | C++ | lgpl-3.0 | 210 |
var searchData=
[
['fan2para',['Fan2Para',['../classrisa_1_1cuda_1_1_fan2_para.html',1,'risa::cuda']]],
['filter',['Filter',['../classrisa_1_1cuda_1_1_filter.html',1,'risa::cuda']]]
];
| HZDR-FWDF/RISA | docs/search/classes_4.js | JavaScript | lgpl-3.0 | 189 |
'use strict';
/**
* Module dependencies.
*/
var passport = require('passport'),
url = require('url'),
config = require('../../config'),
GitHubStrategy = require('passport-github').Strategy;
module.exports = function() {
// Use github strategy
passport.use(new GitHubStrategy({
clientID: config.github.clientID,
clientSecret: config.github.clientSecret,
callbackURL: config.github.callbackURL,
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, done) {
req.session.gitToken = accessToken;
process.nextTick(function () {
return done(null, profile);
});
}
));
};
| ClearcodeHQ/angular-collective | config/strategies/github/github.js | JavaScript | lgpl-3.0 | 663 |
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QtAws is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "xrayrequest.h"
#include "xrayrequest_p.h"
namespace QtAws {
namespace XRay {
/*!
* \class QtAws::XRay::XRayRequest
* \brief The XRayRequest class provides an interface for XRay requests.
*
* \inmodule QtAwsXRay
*/
/*!
* \enum XRayRequest::Action
*
* This enum describes the actions that can be performed as XRay
* requests.
*
* \value BatchGetTracesAction XRay BatchGetTraces action.
* \value CreateGroupAction XRay CreateGroup action.
* \value CreateSamplingRuleAction XRay CreateSamplingRule action.
* \value DeleteGroupAction XRay DeleteGroup action.
* \value DeleteSamplingRuleAction XRay DeleteSamplingRule action.
* \value GetEncryptionConfigAction XRay GetEncryptionConfig action.
* \value GetGroupAction XRay GetGroup action.
* \value GetGroupsAction XRay GetGroups action.
* \value GetInsightAction XRay GetInsight action.
* \value GetInsightEventsAction XRay GetInsightEvents action.
* \value GetInsightImpactGraphAction XRay GetInsightImpactGraph action.
* \value GetInsightSummariesAction XRay GetInsightSummaries action.
* \value GetSamplingRulesAction XRay GetSamplingRules action.
* \value GetSamplingStatisticSummariesAction XRay GetSamplingStatisticSummaries action.
* \value GetSamplingTargetsAction XRay GetSamplingTargets action.
* \value GetServiceGraphAction XRay GetServiceGraph action.
* \value GetTimeSeriesServiceStatisticsAction XRay GetTimeSeriesServiceStatistics action.
* \value GetTraceGraphAction XRay GetTraceGraph action.
* \value GetTraceSummariesAction XRay GetTraceSummaries action.
* \value ListTagsForResourceAction XRay ListTagsForResource action.
* \value PutEncryptionConfigAction XRay PutEncryptionConfig action.
* \value PutTelemetryRecordsAction XRay PutTelemetryRecords action.
* \value PutTraceSegmentsAction XRay PutTraceSegments action.
* \value TagResourceAction XRay TagResource action.
* \value UntagResourceAction XRay UntagResource action.
* \value UpdateGroupAction XRay UpdateGroup action.
* \value UpdateSamplingRuleAction XRay UpdateSamplingRule action.
*/
/*!
* Constructs a XRayRequest object for XRay \a action.
*/
XRayRequest::XRayRequest(const Action action)
: QtAws::Core::AwsAbstractRequest(new XRayRequestPrivate(action, this))
{
}
/*!
* Constructs a copy of \a other.
*/
XRayRequest::XRayRequest(const XRayRequest &other)
: QtAws::Core::AwsAbstractRequest(new XRayRequestPrivate(*other.d_func(), this))
{
}
/*!
* Sets the XRayRequest object to be equal to \a other.
*/
XRayRequest& XRayRequest::operator=(const XRayRequest &other)
{
Q_D(XRayRequest);
d->action = other.d_func()->action;
d->apiVersion = other.d_func()->apiVersion;
d->parameters = other.d_func()->parameters;
return *this;
}
/*!
* Constructs aa XRayRequest object with private implementation \a d.
*
* This overload allows derived classes to provide their own private class
* implementation that inherits from XRayRequestPrivate.
*/
XRayRequest::XRayRequest(XRayRequestPrivate * const d) : QtAws::Core::AwsAbstractRequest(d)
{
}
/*!
* Returns the XRay action to be performed by this request.
*/
XRayRequest::Action XRayRequest::action() const
{
Q_D(const XRayRequest);
return d->action;
}
/*!
* Returns the name of the XRay action to be performed by this request.
*/
QString XRayRequest::actionString() const
{
return XRayRequestPrivate::toString(action());
}
/*!
* Returns the XRay API version implemented by this request.
*/
QString XRayRequest::apiVersion() const
{
Q_D(const XRayRequest);
return d->apiVersion;
}
/*!
* Sets the XRay action to be performed by this request to \a action.
*/
void XRayRequest::setAction(const Action action)
{
Q_D(XRayRequest);
d->action = action;
}
/*!
* Sets the XRay API version to include in this request to \a version.
*/
void XRayRequest::setApiVersion(const QString &version)
{
Q_D(XRayRequest);
d->apiVersion = version;
}
/*!
* Returns \c true if this request is equal to \a other; \c false otherwise.
*
* Note, most derived *Request classes do not need to provider their own
* implementations of this function, since most such request classes rely on
* this class' parameters functionality for all request parameters, and that
* parameters map is already checked via this implementation.
*/
bool XRayRequest::operator==(const XRayRequest &other) const
{
return ((action() == other.action()) &&
(apiVersion() == other.apiVersion()) &&
(parameters() == other.parameters()) &&
(QtAws::Core::AwsAbstractRequest::operator ==(other)));
}
/*
* Returns \c tue if \a queueName is a valid XRay queue name.
*
* @par From XRay FAQs:
* Queue names are limited to 80 characters. Alphanumeric characters plus
* hyphens (-) and underscores (_) are allowed.
*
* @param queueName Name to check for validity.
*
* @return \c true if \a queueName is a valid XRay queue name, \c false otherwise.
*
* @see http://aws.amazon.com/sqs/faqs/
*/
/*bool XRayRequest::isValidQueueName(const QString &queueName)
{
const QRegExp pattern(QLatin1String("[a-zA-Z0-9-_]{1,80}"));
return pattern.exactMatch(queueName);
}*/
/*!
* Removes the a \a name parameter from the request, then returns the number of
* paramters removed (typically \c 0 or \c 1).
*/
int XRayRequest::clearParameter(const QString &name)
{
Q_D(XRayRequest);
return d->parameters.remove(name);
}
/*!
* Removes all parameters from the request.
*/
void XRayRequest::clearParameters()
{
Q_D(XRayRequest);
d->parameters.clear();
}
/*!
* Returns the value of the \a name pararemter if set; \a defaultValue otherwise.
*/
QVariant XRayRequest::parameter(const QString &name, const QVariant &defaultValue) const
{
Q_D(const XRayRequest);
return d->parameters.value(name, defaultValue);
}
/*!
* Returns the parameters included in this request.
*/
const QVariantMap &XRayRequest::parameters() const
{
Q_D(const XRayRequest);
return d->parameters;
}
/*!
* Sets the \a name parameter to \a value.
*/
void XRayRequest::setParameter(const QString &name, const QVariant &value)
{
Q_D(XRayRequest);
d->parameters.insert(name, value);
}
/*!
* Sets the paramters for this request to \a parameters. Any request parameters
* set previously will be discarded.
*/
void XRayRequest::setParameters(const QVariantMap ¶meters)
{
Q_D(XRayRequest);
d->parameters = parameters;
}
/*!
* Returns a network request for the XRay request using the given
* \a endpoint.
*
* This XRay implementation builds request URLs by combining the
* common query parameters (such as Action and Version), with any that have
* been added (via setParameter) by child classes.
*/
QNetworkRequest XRayRequest::unsignedRequest(const QUrl &endpoint) const
{
//Q_D(const XRayRequest);
QUrl url(endpoint);
/// @todo url.setQuery(d->urlQuery());
return QNetworkRequest(url);
}
/*!
* \class QtAws::XRay::XRayRequestPrivate
* \brief The XRayRequestPrivate class provides private implementation for XRayRequest.
* \internal
*
* \inmodule QtAwsXRay
*/
/*!
* Constructs a XRayRequestPrivate object for XRay \a action,
* with public implementation \a q.
*/
XRayRequestPrivate::XRayRequestPrivate(const XRayRequest::Action action, XRayRequest * const q)
: QtAws::Core::AwsAbstractRequestPrivate(q), action(action), apiVersion(QLatin1String("2012-11-05"))
{
}
/*!
* Constructs a copy of \a other, with public implementation \a q.
*
* This copy-like constructor copies everything from \a other, except for the
* the object's pointer to its public instance - for that, \a q is used instead.
*
* This is required to support the XRayRequest class's copy constructor.
*/
XRayRequestPrivate::XRayRequestPrivate(const XRayRequestPrivate &other,
XRayRequest * const q)
: QtAws::Core::AwsAbstractRequestPrivate(q), action(other.action),
apiVersion(other.apiVersion), parameters(other.parameters)
{
}
/*!
* Returns a string represention of \a action, or a null string if \a action is
* invalid.
*
* This function converts XRayRequest::Action enumerator values to their respective
* string representations, appropriate for use with the XRay service's Action
* query parameters.
*/
QString XRayRequestPrivate::toString(const XRayRequest::Action &action)
{
#define ActionToString(action) \
case XRayRequest::action##Action: return QStringLiteral(#action)
switch (action) {
ActionToString(BatchGetTraces);
ActionToString(CreateGroup);
ActionToString(CreateSamplingRule);
ActionToString(DeleteGroup);
ActionToString(DeleteSamplingRule);
ActionToString(GetEncryptionConfig);
ActionToString(GetGroup);
ActionToString(GetGroups);
ActionToString(GetInsight);
ActionToString(GetInsightEvents);
ActionToString(GetInsightImpactGraph);
ActionToString(GetInsightSummaries);
ActionToString(GetSamplingRules);
ActionToString(GetSamplingStatisticSummaries);
ActionToString(GetSamplingTargets);
ActionToString(GetServiceGraph);
ActionToString(GetTimeSeriesServiceStatistics);
ActionToString(GetTraceGraph);
ActionToString(GetTraceSummaries);
ActionToString(ListTagsForResource);
ActionToString(PutEncryptionConfig);
ActionToString(PutTelemetryRecords);
ActionToString(PutTraceSegments);
ActionToString(TagResource);
ActionToString(UntagResource);
ActionToString(UpdateGroup);
ActionToString(UpdateSamplingRule);
default:
Q_ASSERT_X(false, Q_FUNC_INFO, "invalid action");
}
#undef ActionToString
return QString();
}
} // namespace XRay
} // namespace QtAws
| pcolby/libqtaws | src/xray/xrayrequest.cpp | C++ | lgpl-3.0 | 10,576 |
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QtAws is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "listdeploymentinstancesrequest.h"
#include "listdeploymentinstancesrequest_p.h"
#include "listdeploymentinstancesresponse.h"
#include "codedeployrequest_p.h"
namespace QtAws {
namespace CodeDeploy {
/*!
* \class QtAws::CodeDeploy::ListDeploymentInstancesRequest
* \brief The ListDeploymentInstancesRequest class provides an interface for CodeDeploy ListDeploymentInstances requests.
*
* \inmodule QtAwsCodeDeploy
*
* <fullname>AWS CodeDeploy</fullname>
*
* AWS CodeDeploy is a deployment service that automates application deployments to Amazon EC2 instances, on-premises
* instances running in your own facility, serverless AWS Lambda functions, or applications in an Amazon ECS
*
* service>
*
* You can deploy a nearly unlimited variety of application content, such as an updated Lambda function, updated
* applications in an Amazon ECS service, code, web and configuration files, executables, packages, scripts, multimedia
* files, and so on. AWS CodeDeploy can deploy application content stored in Amazon S3 buckets, GitHub repositories, or
* Bitbucket repositories. You do not need to make changes to your existing code before you can use AWS
*
* CodeDeploy>
*
* AWS CodeDeploy makes it easier for you to rapidly release new features, helps you avoid downtime during application
* deployment, and handles the complexity of updating your applications, without many of the risks associated with
* error-prone manual
*
* deployments>
*
* <b>AWS CodeDeploy Components</b>
*
* </p
*
* Use the information in this guide to help you work with the following AWS CodeDeploy
*
* components> <ul> <li>
*
* <b>Application</b>: A name that uniquely identifies the application you want to deploy. AWS CodeDeploy uses this name,
* which functions as a container, to ensure the correct combination of revision, deployment configuration, and deployment
* group are referenced during a
*
* deployment> </li> <li>
*
* <b>Deployment group</b>: A set of individual instances, CodeDeploy Lambda deployment configuration settings, or an
* Amazon ECS service and network details. A Lambda deployment group specifies how to route traffic to a new version of a
* Lambda function. An Amazon ECS deployment group specifies the service created in Amazon ECS to deploy, a load balancer,
* and a listener to reroute production traffic to an updated containerized application. An EC2/On-premises deployment
* group contains individually tagged instances, Amazon EC2 instances in Amazon EC2 Auto Scaling groups, or both. All
* deployment groups can specify optional trigger, alarm, and rollback
*
* settings> </li> <li>
*
* <b>Deployment configuration</b>: A set of deployment rules and deployment success and failure conditions used by AWS
* CodeDeploy during a
*
* deployment> </li> <li>
*
* <b>Deployment</b>: The process and the components used when updating a Lambda function, a containerized application in
* an Amazon ECS service, or of installing content on one or more instances.
*
* </p </li> <li>
*
* <b>Application revisions</b>: For an AWS Lambda deployment, this is an AppSpec file that specifies the Lambda function
* to be updated and one or more functions to validate deployment lifecycle events. For an Amazon ECS deployment, this is
* an AppSpec file that specifies the Amazon ECS task definition, container, and port where production traffic is rerouted.
* For an EC2/On-premises deployment, this is an archive file that contains source content—source code, webpages,
* executable files, and deployment scripts—along with an AppSpec file. Revisions are stored in Amazon S3 buckets or GitHub
* repositories. For Amazon S3, a revision is uniquely identified by its Amazon S3 object key and its ETag, version, or
* both. For GitHub, a revision is uniquely identified by its commit
*
* ID> </li> </ul>
*
* This guide also contains information to help you get details about the instances in your deployments, to make
* on-premises instances available for AWS CodeDeploy deployments, to get details about a Lambda function deployment, and
* to get details about Amazon ECS service
*
* deployments>
*
* <b>AWS CodeDeploy Information Resources</b>
*
* </p <ul> <li>
*
* <a href="https://docs.aws.amazon.com/codedeploy/latest/userguide">AWS CodeDeploy User Guide</a>
*
* </p </li> <li>
*
* <a href="https://docs.aws.amazon.com/codedeploy/latest/APIReference/">AWS CodeDeploy API Reference Guide</a>
*
* </p </li> <li>
*
* <a href="https://docs.aws.amazon.com/cli/latest/reference/deploy/index.html">AWS CLI Reference for AWS CodeDeploy</a>
*
* </p </li> <li>
*
* <a href="https://forums.aws.amazon.com/forum.jspa?forumID=179">AWS CodeDeploy Developer Forum</a>
*
* \sa CodeDeployClient::listDeploymentInstances
*/
/*!
* Constructs a copy of \a other.
*/
ListDeploymentInstancesRequest::ListDeploymentInstancesRequest(const ListDeploymentInstancesRequest &other)
: CodeDeployRequest(new ListDeploymentInstancesRequestPrivate(*other.d_func(), this))
{
}
/*!
* Constructs a ListDeploymentInstancesRequest object.
*/
ListDeploymentInstancesRequest::ListDeploymentInstancesRequest()
: CodeDeployRequest(new ListDeploymentInstancesRequestPrivate(CodeDeployRequest::ListDeploymentInstancesAction, this))
{
}
/*!
* \reimp
*/
bool ListDeploymentInstancesRequest::isValid() const
{
return false;
}
/*!
* Returns a ListDeploymentInstancesResponse object to process \a reply.
*
* \sa QtAws::Core::AwsAbstractClient::send
*/
QtAws::Core::AwsAbstractResponse * ListDeploymentInstancesRequest::response(QNetworkReply * const reply) const
{
return new ListDeploymentInstancesResponse(*this, reply);
}
/*!
* \class QtAws::CodeDeploy::ListDeploymentInstancesRequestPrivate
* \brief The ListDeploymentInstancesRequestPrivate class provides private implementation for ListDeploymentInstancesRequest.
* \internal
*
* \inmodule QtAwsCodeDeploy
*/
/*!
* Constructs a ListDeploymentInstancesRequestPrivate object for CodeDeploy \a action,
* with public implementation \a q.
*/
ListDeploymentInstancesRequestPrivate::ListDeploymentInstancesRequestPrivate(
const CodeDeployRequest::Action action, ListDeploymentInstancesRequest * const q)
: CodeDeployRequestPrivate(action, q)
{
}
/*!
* Constructs a copy of \a other, with public implementation \a q.
*
* This copy-like constructor exists for the benefit of the ListDeploymentInstancesRequest
* class' copy constructor.
*/
ListDeploymentInstancesRequestPrivate::ListDeploymentInstancesRequestPrivate(
const ListDeploymentInstancesRequestPrivate &other, ListDeploymentInstancesRequest * const q)
: CodeDeployRequestPrivate(other, q)
{
}
} // namespace CodeDeploy
} // namespace QtAws
| pcolby/libqtaws | src/codedeploy/listdeploymentinstancesrequest.cpp | C++ | lgpl-3.0 | 7,587 |
/*
* ((e)) emite: A pure Google Web Toolkit XMPP library
* Copyright (c) 2008-2011 The Emite development team
*
* This file is part of Emite.
*
* Emite is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* Emite is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Emite. If not, see <http://www.gnu.org/licenses/>.
*/
package com.calclab.emite.example.echo.client;
import com.calclab.emite.browser.EmiteBrowserModule;
import com.calclab.emite.core.EmiteCoreModule;
import com.calclab.emite.core.session.XmppSession;
import com.calclab.emite.im.EmiteIMModule;
import com.calclab.emite.im.chat.PairChatManager;
import com.google.gwt.inject.client.GinModules;
import com.google.gwt.inject.client.Ginjector;
@GinModules({ EmiteCoreModule.class, EmiteIMModule.class, EmiteBrowserModule.class })
interface ExampleEchoGinjector extends Ginjector {
XmppSession getXmppSession();
PairChatManager getPairChatManager();
} | EmiteGWT/emite | examples/src/main/java/com/calclab/emite/example/echo/client/ExampleEchoGinjector.java | Java | lgpl-3.0 | 1,434 |
/* $Id$
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
*/
/// @file ID1server_request.hpp
/// User-defined methods of the data storage class.
///
/// This file was originally generated by application DATATOOL
/// using the following specifications:
/// 'id1.asn'.
///
/// New methods or data members can be added to it if needed.
/// See also: ID1server_request_.hpp
#ifndef OBJECTS_ID1_ID1SERVER_REQUEST_HPP
#define OBJECTS_ID1_ID1SERVER_REQUEST_HPP
// generated includes
#include <objects/id1/ID1server_request_.hpp>
// generated classes
BEGIN_NCBI_SCOPE
BEGIN_objects_SCOPE // namespace ncbi::objects::
/////////////////////////////////////////////////////////////////////////////
class NCBI_ID1_EXPORT CID1server_request : public CID1server_request_Base
{
typedef CID1server_request_Base Tparent;
public:
// constructor
CID1server_request(void);
// destructor
~CID1server_request(void);
private:
// Prohibit copy constructor and assignment operator
CID1server_request(const CID1server_request& value);
CID1server_request& operator=(const CID1server_request& value);
};
/////////////////// CID1server_request inline methods
// constructor
inline
CID1server_request::CID1server_request(void)
{
}
/////////////////// end of CID1server_request inline methods
END_objects_SCOPE // namespace ncbi::objects::
END_NCBI_SCOPE
#endif // OBJECTS_ID1_ID1SERVER_REQUEST_HPP
/* Original file checksum: lines: 86, chars: 2544, CRC32: 2b307884 */
| kyungtaekLIM/PSI-BLASTexB | src/ncbi-blast-2.5.0+/c++/include/objects/id1/ID1server_request.hpp | C++ | lgpl-3.0 | 2,700 |
/*
* ShortTimeProcess.cpp
* Copyright 2016 (c) Jordi Adell
* Created on: 2015
* Author: Jordi Adell - adellj@gmail.com
*
* This file is part of DSPONE
*
* DSPONE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DSPONE 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
* alogn with DSPONE. If not, see <http://www.gnu.org/licenses/>.
*/
#include <dspone/rt/ShortTimeProcessImpl.h>
#include <dspone/rt/ShortTimeProcess.h>
namespace dsp {
ShortTimeProcessImpl::ShortTimeProcessImpl(ShortTimeProcess *frameProcessor,
int windowSize,
int analysisLength,
int nchannels,
Mode mode) :
_frameProcessor(frameProcessor),
_windowSize (windowSize),
_windowShift (_windowSize/2),
_halfWindowSize (_windowSize/2),
_nchannels(nchannels),
_nDataChannels(10),
_analysisLength((analysisLength == 0) ? _windowSize + 2 : analysisLength),
_window(new BaseType[_windowSize+1]), // Needs to be of odd length in order to preserve the original energy.
_iwindow(new BaseType[_windowSize]),
_mode(mode),
_doSynthesis(_mode == ShortTimeProcess::ANALYSIS_SYNTHESIS)
{
initVariableMembers();
initWindowBuffers();
initBuffers();
}
double ShortTimeProcessImpl::getRate() const
{
return _windowShift;
}
int ShortTimeProcessImpl::getNumberOfChannels() const
{
return _nchannels;
}
int ShortTimeProcessImpl::getNumberOfDataChannels() const
{
return _nDataChannels;
}
ShortTimeProcessImpl::~ShortTimeProcessImpl()
{
}
void ShortTimeProcessImpl::initVariableMembers()
{
_firstCall = true;
}
void ShortTimeProcessImpl::initWindowBuffers()
{
// Create auxiliar buffers
_frame.reset(new BaseType[_windowSize]);
// Setting window vector
wipp::set(1.0,_window.get(),_windowSize+1);
wipp::window(_window.get(), _windowSize+1, wipp::wippHANN);
wipp::sqrt(&_window[1],_windowSize-1);
_window[0]=0;
// Setting inverse window vector
BaseType ones[_windowSize];
wipp::set(1.0, ones, _windowSize);
wipp::copyBuffer(_window.get(),_iwindow.get(),_windowSize);
wipp::div(&_window[1], ones, &_iwindow[1], _windowSize-1);
}
void ShortTimeProcessImpl::initBuffers()
{
wipp::setZeros(_frame.get(),_windowSize);
for (unsigned int i = 0; i<_nchannels; ++i)
{
_latencyBufferProcessed.push_back(SignalPtr(new BaseType[_windowSize]));
wipp::wipp_circular_buffer_t *cb;
wipp::init_cirular_buffer(&cb, _maximumLatencyBufferSize, _frame.get(), _windowSize);
_latencyBufferSignal.push_back(cb);
wipp::setZeros(_latencyBufferProcessed.back().get(), _windowSize);
_analysisFramesPtr.push_back(new BaseType[_analysisLength]);
_analysisFrames.push_back(SignalPtr(_analysisFramesPtr.back()));
wipp::setZeros(_analysisFrames.back().get(), _analysisLength);
}
allocateNDataChannels(_nDataChannels);
}
void ShortTimeProcessImpl::allocateNDataChannels(int nDataChannels)
{
for (unsigned int i = _dataFrames.size(); i < nDataChannels; ++i)
{
_dataFramesPtr.push_back(new BaseType[_windowSize]);
_dataFrames.push_back(SignalPtr(_dataFramesPtr.back()));
wipp::setZeros(_dataFrames.back().get(), _windowSize);
}
for (unsigned int i = _latencyBufferSignal.size(); i < nDataChannels + _nchannels; ++i)
{
BaseType zeros[_windowSize];
wipp::setZeros(zeros, _windowSize);
// _latencyBufferSignal.push_back(container::CircularBuffer<BaseType, _maximumLatencyBufferSize>());
_latencyBufferProcessed.push_back(SignalPtr(new BaseType[_windowSize]));
wipp::setZeros(_latencyBufferProcessed.back().get(), _windowSize);
wipp::wipp_circular_buffer_t *cb;
wipp::init_cirular_buffer(&cb, _maximumLatencyBufferSize, zeros, _windowSize);
_latencyBufferSignal.push_back(cb);
}
}
int ShortTimeProcessImpl::getAmountOfRemainingSamples()
{
if (_firstCall)
return 0;
else
return _windowShift;
}
void ShortTimeProcessImpl::clear()
{
_latencyBufferSignal.clear();
_analysisFrames.clear();
_analysisFramesPtr.clear();
for (size_t i = 0; i < _latencyBufferSignal.size(); ++i)
{
wipp::wipp_circular_buffer_t *f = _latencyBufferSignal.at(i);
wipp::delete_circular_buffer(&f);
}
_dataFrames.clear();
_dataFramesPtr.clear();
_latencyBufferProcessed.clear();
initBuffers();
}
void ShortTimeProcessImpl::ShortTimeProcessing(const SignalVector &signal, const SignalVector &output, int length)
{
std::string msg = "ShortTimeProcess process frame of ";
msg += std::to_string(_windowSize) + " samples";
int lastFrame = length - _windowSize;
int sample = 0;
SignalVector::const_iterator it;
for (it = output.begin(); it != output.end(); ++it)
wipp::setZeros(it->get(), length);
for (sample=0; sample <= lastFrame; sample = sample + _windowShift)
{
unsigned int channel;
for (channel = 0, it = signal.begin(); // Foreach signal channel
it != signal.end() && channel < _nchannels;
++it, ++channel)
{
BaseType *ptr = it->get();
wipp::copyBuffer(&ptr[sample],_frame.get(),_windowSize);
wipp::mult(_window.get(),_frame.get(),_windowSize);
frameAnalysis(_frame.get(), _analysisFrames[channel].get(), _windowSize, _analysisLength, channel);
}
for(channel = 0; // Foreach data channel
it != signal.end() && channel < _nDataChannels;
++it, ++channel)
{
BaseType *ptr = it->get();
wipp::copyBuffer(&ptr[sample], _dataFrames[channel].get(), _windowSize);
}
/// Set data channels point to the actual signal channels.
processParametrisation();
if (!_doSynthesis)
continue;
for (channel = 0, it = output.begin(); // Foreach signal channel
it != output.end() && channel < _nchannels;
++it, ++channel)
{
BaseType *ptr =it->get();
frameSynthesis(_frame.get(), _analysisFrames[channel].get(), _windowSize, _analysisLength, channel);
wipp::mult(_window.get(),_frame.get(),_windowSize);
wipp::add(_frame.get(),&ptr[sample],_windowSize);
}
for(channel = 0; // Foreach data channel
it != output.end() && channel < _nDataChannels;
++it, ++channel)
{
BaseType *ptr = it->get();
wipp::copyBuffer(_dataFrames[channel].get(), &ptr[sample], _windowSize);
}
}
}
int ShortTimeProcessImpl::calculateOrderFromSampleRate(int sampleRate, double frameRate)
{
int order = static_cast<int>(log(2*frameRate*sampleRate)/log(2.0F) + 0.5);
if (0 < order && order < 4)
{
ERROR_STREAM("Too low order for FFT: " << order << " this might cose undefined errors.");
}
else if(order <= 0)
{
std::stringstream oss;
oss << "Negative or zero FFT order value: " << order << ". "
<< "Order is optained from frame rate: " << frameRate
<< " and sample rate: " << sampleRate;
throw(DspException(oss.str()));
}
return order;
}
void ShortTimeProcessImpl::unwindowFrame(double *frame, size_t length) const
{
wipp::mult(_iwindow.get(), frame, ((length < _windowSize) ? length : _windowSize));
}
void ShortTimeProcessImpl::unwindowFrame(double *frame, double *unwindowed, size_t length) const
{
wipp::setZeros(unwindowed, length);
wipp::copyBuffer(frame, unwindowed, length);
wipp::mult(_iwindow.get(), frame, ((length < _windowSize) ? length : _windowSize));
}
int ShortTimeProcessImpl::getLatency() const
{
size_t occupancy;
// return _latencyBufferSignal[0].getCountUsed();
wipp::cf_occupancy(_latencyBufferSignal[0], &occupancy);
return occupancy;
}
int ShortTimeProcessImpl::getMaxLatency() const
{
return getWindowSize() + _windowShift;
}
int ShortTimeProcessImpl::getMinLatency() const
{
return _windowShift;
}
int ShortTimeProcessImpl::getAnalysisLength() const
{
return _analysisLength;
}
int ShortTimeProcessImpl::getWindowSize() const
{
return _windowSize;
}
int ShortTimeProcessImpl::getFrameSize() const
{
return getWindowSize();
}
int ShortTimeProcessImpl::getFrameRate() const
{
return _windowShift;
}
void ShortTimeProcessImpl::frameAnalysis(BaseType *inFrame,
BaseType *analysis,
int frameLength,
int analysisLength,
int channel)
{
_qtdebug.plot(inFrame, frameLength, QtDebug::IN_FRAME, channel);
_frameProcessor->frameAnalysis(inFrame, analysis, frameLength, analysisLength, channel);
}
void ShortTimeProcessImpl::processParametrisation()
{
_qtdebug.plot(_analysisFrames, _analysisLength, QtDebug::IN_ANALYSIS);
_frameProcessor->processParametrisation(_analysisFramesPtr, _analysisLength, _dataFramesPtr, _windowSize);
_qtdebug.plot(_analysisFrames, _analysisLength, QtDebug::OUT_ANALYSIS);
}
void ShortTimeProcessImpl::frameSynthesis(BaseType *outFrame,
BaseType *analysis,
int frameLength,
int analysisLength,
int channel)
{
_frameProcessor->frameSynthesis(outFrame, analysis, frameLength, analysisLength, channel);
_qtdebug.plot(outFrame, frameLength, QtDebug::OUT_FRAME, channel);
}
}
| jordi-adell/dspone | src/dspone/rt/ShortTimeProcessImpl.cpp | C++ | lgpl-3.0 | 9,276 |
/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/set.hpp>
#include <bh_ir.hpp>
#include <bh_util.hpp>
using namespace std;
using namespace boost;
namespace io = boost::iostreams;
BhIR::BhIR(const std::vector<char> &serialized_archive, std::map<const bh_base*, bh_base> &remote2local,
vector<bh_base*> &data_recv, set<bh_base*> &frees) {
// Wrap 'serialized_archive' in an input stream
iostreams::basic_array_source<char> source(&serialized_archive[0], serialized_archive.size());
iostreams::stream<iostreams::basic_array_source<char> > input_stream(source);
archive::binary_iarchive ia(input_stream);
// Load number of repeats and the repeat condition
ia >> _nrepeats;
{
size_t t;
ia >> t;
_repeat_condition = reinterpret_cast<bh_base*>(t);
}
// Load the instruction list
ia >> instr_list;
// Load the set of syncs
{
vector<size_t> base_as_int;
ia >> base_as_int;
for(size_t base: base_as_int) {
_syncs.insert(reinterpret_cast<bh_base*>(base));
}
}
// Load the new base arrays
std::vector<bh_base> news;
ia >> news;
// Find all freed base arrays (remote base pointers)
for (const bh_instruction &instr: instr_list) {
if (instr.opcode == BH_FREE) {
frees.insert(instr.operand[0].base);
}
}
// Add the new base array to 'remote2local' and to 'data_recv'
size_t new_base_count = 0;
for (const bh_instruction &instr: instr_list) {
for (const bh_view &v: instr.operand) {
if (bh_is_constant(&v))
continue;
if (not util::exist(remote2local, v.base)) {
assert(new_base_count < news.size());
remote2local[v.base] = news[new_base_count++];
if (remote2local[v.base].data != nullptr)
data_recv.push_back(&remote2local[v.base]);
}
}
}
assert(new_base_count == news.size());
// Update all base pointers to point to the local bases
for (bh_instruction &instr: instr_list) {
for (bh_view &v: instr.operand) {
if (not bh_is_constant(&v)) {
v.base = &remote2local.at(v.base);
}
}
}
// Update all base pointers in the bhir's `_syncs` set
{
set<bh_base*> syncs_as_local_ptr;
for (bh_base *base: _syncs) {
if (util::exist(remote2local, base)) {
syncs_as_local_ptr.insert(&remote2local.at(base));
}
}
_syncs = std::move(syncs_as_local_ptr);
}
// Update the `_repeat_condition` pointer
if (_repeat_condition != nullptr) {
_repeat_condition = &remote2local.at(_repeat_condition);
}
}
std::vector<char> BhIR::write_serialized_archive(set<bh_base *> &known_base_arrays, vector<bh_base *> &new_data) {
// Find new base arrays in 'bhir', which the de-serializing component should know about, and their data (if any)
vector<bh_base> new_bases; // New base arrays in the order they appear in the instruction list
for (bh_instruction &instr: instr_list) {
for (const bh_view &v: instr.operand) {
if (not bh_is_constant(&v) and not util::exist(known_base_arrays, v.base)) {
new_bases.push_back(*v.base);
known_base_arrays.insert(v.base);
if (v.base->data != nullptr) {
new_data.push_back(v.base);
}
}
}
}
// Wrap 'ret' in an output stream
std::vector<char> ret;
iostreams::stream<iostreams::back_insert_device<vector<char> > > output_stream(ret);
archive::binary_oarchive oa(output_stream);
// Write number of repeats and the repeat condition
oa << _nrepeats;
if (_repeat_condition != nullptr and util::exist(known_base_arrays, _repeat_condition)) {
size_t t = reinterpret_cast<size_t >(_repeat_condition);
oa << t;
} else {
size_t t = 0;
oa << t;
}
// Write the instruction list
oa << instr_list;
vector<size_t> base_as_int;
for(bh_base *base: _syncs) {
base_as_int.push_back(reinterpret_cast<size_t>(base));
}
oa << base_as_int;
oa << new_bases;
return ret;
}
| mfherbst/bohrium | core/bh_ir.cpp | C++ | lgpl-3.0 | 5,269 |
# -*- coding: utf-8 -*-
# Some utils
import hashlib
import uuid
def get_hash(data):
"""Returns hashed string"""
return hashlib.sha256(data).hexdigest()
def get_token():
return str(uuid.uuid4())
| aluminiumgeek/organic | utils.py | Python | lgpl-3.0 | 212 |
#!/usr/bin/python
# -*- coding: latin-1 -*-
# Copyright 2015 Oeyvind Brandtsegg
#
# This file is part of the Signal Interaction Toolkit
#
# The Signal Interaction Toolkit is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# The Signal Interaction Toolkit 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 The Signal Interaction Toolkit.
# If not, see <http://www.gnu.org/licenses/>.
import sys
if sys.argv[1] == 'template':
effectname = 'template'
parameters = [('Vol', (0.0, 1.0, 0.5, 0.25, 0.00001))]
# pName, (min, max, default, skew, increment)
# where skew is a dynamic adjustment of exp/lin/log translation if the GUI widget
# and increment is the smallest change allowed by the GUI widget
if sys.argv[1] == 'stereopan':
effectname = 'stereopan'
parameters = [('Pan', (0.0, 1.0, 0.5, 1, 0.001)),
('Mix', (0.0, 1.0, 0.5, 1, 0.001))]
if sys.argv[1] == 'tremolam':
effectname = 'tremolam'
parameters = [('Depth', (0.0, 1.0, 0.5, 0.25, 0.001)),
('RateLow', (0.0, 10.0, 0.5, 0.25, 0.001)),
('RateHigh', (0.0, 500.0, 0.5, 0.25, 0.001))]
if sys.argv[1] == 'vst_mediator':
effectname = 'vst_mediator'
parameters = [('parm1', (0.0, 1.0, 0.5, 1, 0.001)),
('parm2', (0.0, 1.0, 0.5, 1, 0.001)),
('parm3', (0.0, 1.0, 0.5, 1, 0.001)),
('parm4', (0.0, 1.0, 0.5, 1, 0.001)),
('parm5', (0.0, 1.0, 0.5, 1, 0.001)),
('parm6', (0.0, 1.0, 0.5, 1, 0.001)),
('parm7', (0.0, 1.0, 0.5, 1, 0.001)),
('parm8', (0.0, 1.0, 0.5, 1, 0.001))
]
if sys.argv[1] == 'vst_MIDIator':
effectname = 'vst_MIDIator'
parameters = [('parm1', (0.0, 1.0, 0.5, 1, 0.001)),
('parm2', (0.0, 1.0, 0.5, 1, 0.001)),
('parm3', (0.0, 1.0, 0.5, 1, 0.001)),
('parm4', (0.0, 1.0, 0.5, 1, 0.001)),
('parm5', (0.0, 1.0, 0.5, 1, 0.001)),
('parm6', (0.0, 1.0, 0.5, 1, 0.001)),
('parm7', (0.0, 1.0, 0.5, 1, 0.001)),
('parm8', (0.0, 1.0, 0.5, 1, 0.001))
]
if sys.argv[1] == 'stereodelay':
effectname = 'stereodelay'
parameters = [('delaytime', (0.0008, 2.0, 0.5, 0.25, 0.00001)),
('filt_fq', (100, 10000, 1000, 0.35, 1)),
('feedback', (0.0, 0.9999, 0.3, 1.9, 0.0001))
]
if sys.argv[1] == 'pluck':
effectname = 'pluck'
parameters = [('inlevel', (0, 1.0, 1, 0.3, 0.01)),
('freq', (1, 1450, 400, 0.3, 0.01)),
('filt_fq', (1000, 16000, 7000, 0.35, 1)),
('feedback', (0.8, 0.9999, 0.95, 1.9, 0.0001)),
('mix', (0, 1.0, 1, 0.3, 0.01))
]
if sys.argv[1] == 'lpf18dist':
effectname = 'lpf18dist'
parameters = [('Drive', (1, 12, 2, 1, 0.1)),
('Freq', (20, 10000, 3000, 0.35, 1)),
('Resonance', (0.001, 0.95, 0.3, 1, 0.001)),
('Dist', (0.001, 10, 0.2, 0.5, 0.001)),
('Mix', (0.0, 1.0, 1.0, 1, 0.01)),
]
if sys.argv[1] == 'screverb':
effectname = 'screverb'
parameters = [('InLevel', (0, 1.0, 0.2, 0.3, 0.01)),
('Feed', (0.0, 1.0, 0.85, 1.2, 0.01)),
('FiltFq', (100, 14000, 7000, 0.6, 1)),
('PitchMod', (0.0, 4.0, 0.9, 1, 0.01)),
('PreDly', (0.0, 500, 120, 1, 1)),
('LfRoll', (20, 500, 90, 1, 1)),
('Mix', (0.0, 1.0, 1.0, 1, 0.01))
]
if sys.argv[1] == 'freeverb':
effectname = 'freeverb'
parameters = [('inlevel', (0, 1.0, 1.0, 0.3, 0.01)),
('reverbtime', (0.0, 8.0, 1.5, 0.4, 0.01)),
('reverbdamp', (0.0, 1.0, 0.25, 0.6, 0.01)),
('reverbmix', (0.0, 1.0, 0.7, 1, 0.01))
]
if sys.argv[1] == 'mincertime':
effectname = 'mincertime'
parameters = [('inlevel', (0, 1.0, 1, 0.3, 0.01)),
('timpoint', (0, 0.99, 0.1, 0.4, 0.001)),
('pitch', (0.0, 2.0, 1.0, 1, 0.01)),
('feedback', (0.0, 1.0, 0.0, 1, 0.01)),
('mix', (0, 1.0, 1, 0.3, 0.01))
]
if sys.argv[1] == 'plucktremlpfverb':
effectname = 'plucktremlpfverb'
parameters = [('inlevel', (0, 1.0, 1, 0.3, 0.01)),
('pluckfreq', (1, 1450, 400, 0.3, 0.01)),
('pluckfilt', (1000, 16000, 7000, 0.35, 1)),
('pluckfeed', (0.8, 0.9999, 0.95, 1.9, 0.0001)),
('pluckmix', (0, 1.0, 1, 0.3, 0.01)),
('tremDepth', (0.0, 1.0, 0.5, 0.25, 0.001)),
('tRateLow', (0.0, 10.0, 0.5, 0.25, 0.001)),
('tRateHigh', (0.0, 500.0, 0.5, 0.25, 0.001)),
('lpfDrive', (1, 12, 2, 1, 0.1)),
('lpfFreq', (20, 10000, 3000, 0.35, 1)),
('lpfResonance', (0.001, 0.95, 0.3, 1, 0.001)),
('lpfDist', (0.001, 10, 0.2, 0.5, 0.001)),
('lpfMix', (0.0, 1.0, 1.0, 1, 0.01)),
('reverbtime', (0.0, 8.0, 1.5, 0.4, 0.01)),
('reverbdamp', (0.0, 1.0, 0.25, 0.6, 0.01)),
('reverbmix', (0.0, 1.0, 0.7, 1, 0.01))
]
if sys.argv[1] == 'mincerpanverb':
effectname = 'mincerpanverb'
parameters = [('inlevel', (0, 1.0, 1, 0.3, 0.01)),
('mincertime', (0, 0.99, 0.1, 0.4, 0.001)),
('mincerpitch', (0.0, 2.0, 1.0, 1, 0.01)),
('mincerfeed', (0.0, 1.0, 0.0, 1, 0.01)),
('mincermix', (0, 1.0, 1, 0.3, 0.01)),
('Pan', (0.0, 1.0, 0.5, 1, 0.001)),
('panMix', (0.0, 1.0, 0.5, 1, 0.001)),
('reverbtime', (0.0, 8.0, 1.5, 0.4, 0.01)),
('reverbdamp', (0.0, 1.0, 0.25, 0.6, 0.01)),
('reverbmix', (0.0, 1.0, 0.7, 1, 0.01))
]
#
scorefile = open(effectname+'_score_events.inc', 'w')
fractionalinstr = 0
for p in parameters:
fractionalinstr += 1
scorefile.write('i4.{fracinstr:02d} 3.1 $SCORELEN "{pname}"\n'.format(fracinstr=fractionalinstr, pname=p[0]))
#
chn_init_file = open(effectname+'_parameter_ranges.inc', 'w')
instr_template = '''
instr 1
; list of min and max for the mappable parameters
{}
endin
'''
parameter_ranges = ''
for i in range(len(parameters)):
parm = parameters[i]
parameter_ranges += ' chnset {}, "{}_min" \n'.format(parm[1][0], parm[0])
parameter_ranges += ' chnset {}, "{}_max" \n'.format(parm[1][1], parm[0])
chn_init_file.write(instr_template.format(parameter_ranges))
#
start_x_pos = 30
start_y_pos = 5
plant_height = 85
analysis_parms = '"rms", "rms_preEq", "cps", "pitch", "centroid", "spread", "skewness", "kurtosis", "flatness", "crest", "flux", "amp_trans", "amp_t_dens", "centr_trans", "centr_t_dens", "kurt_trans", "pitchup_trans", "pitchdown_trans", "cps_raw"'
plant = '''groupbox bounds({start_y}, {start_x}, 564, 81), plant("plant_{pname}"), linethickness("0"){{
combobox channel("source1_{pname}"), bounds(10, 12, 90, 20), items({analysis_p}), value(1), channeltype("string")
combobox channel("chan1_{pname}"), bounds(103, 12, 50, 20), items("1", "2", "3", "4"), value(1)
numberbox bounds(158, 14, 35, 15), channel("rise1_{pname}"), range(0.01, 10.0, 0.01)
numberbox bounds(196, 14, 35, 15), channel("fall1_{pname}"), range(0.01, 10.0, 0.5)
hslider bounds(233, 12, 86, 20), channel("scale1_{pname}"), range(-1.0, 1.0, 0, 1, 0.01)
button bounds(320, 12, 29, 19), channel("scale1_x_{pname}"), text("x 1","x 10"),
hslider bounds(349, 12, 86, 20), channel("curve1_{pname}"), range(-5.0, 5.0, 0)
combobox channel("source2_{pname}"), bounds(10, 34, 90, 20), items({analysis_p}), value(1), channeltype("string")
combobox channel("chan2_{pname}"), bounds(103, 34, 50, 20), items("1", "2", "3", "4"), value(1)
numberbox bounds(158, 36, 35, 15), channel("rise2_{pname}"), range(0.01, 10.0, 0.01)
numberbox bounds(196, 36, 35, 15), channel("fall2_{pname}"), range(0.01, 10.0, 0.5)
hslider bounds(233, 34, 86, 20), channel("scale2_{pname}"), range(-1.0, 1.0, 0, 1, 0.01)
button bounds(320, 34, 29, 19), channel("scale2_x_{pname}"), text("x 1","x 10"),
hslider bounds(349, 34, 86, 20), channel("curve2_{pname}"), range(-5.0, 5.0, 0)
label bounds(10, 58, 90, 12), text("source"), colour(20,20,20,255)
label bounds(103, 58, 50, 12), text("chan"), colour(20,20,20,255)
label bounds(156, 58, 76, 12), text("rise/fall"), colour(20,20,20,255)
label bounds(236, 58, 110, 12), text("scale"), colour(20,20,20,255)
label bounds(352, 58, 81, 12), text("curve"), colour(20,20,20,255)
rslider bounds(433, 12, 62, 62), text("offset"), channel("offset_{pname}"), range({p_min}, {p_max}, {p_default}, {p_skew}, {p_incr})
combobox bounds(433, 1, 55, 12), channel("offsetx_{pname}"), items("-1", "Nornm", "+1"), , value(2), channeltype("string")
rslider bounds(494, 8, 66, 66), text("{pname}"), channel("{pname}"), range({p_min}, {p_max}, {p_default}, {p_skew}, {p_incr})
}}
'''
plantMIDI = '''groupbox bounds({start_y}, {start_x}, 710, 81), plant("plant_{pname}"), linethickness("0"){{
combobox channel("source1_{pname}"), bounds(10, 12, 90, 20), items({analysis_p}), value(1), channeltype("string")
combobox channel("chan1_{pname}"), bounds(103, 12, 50, 20), items("1", "2", "3", "4"), value(1)
numberbox bounds(158, 14, 35, 15), channel("rise1_{pname}"), range(0.01, 10.0, 0.01)
numberbox bounds(196, 14, 35, 15), channel("fall1_{pname}"), range(0.01, 10.0, 0.5)
hslider bounds(233, 12, 86, 20), channel("scale1_{pname}"), range(-1.0, 1.0, 0, 1, 0.01)
button bounds(320, 12, 29, 19), channel("scale1_x_{pname}"), text("x 1","x 10"),
hslider bounds(349, 12, 86, 20), channel("curve1_{pname}"), range(-5.0, 5.0, 0)
combobox channel("source2_{pname}"), bounds(10, 34, 90, 20), items({analysis_p}), value(1), channeltype("string")
combobox channel("chan2_{pname}"), bounds(103, 34, 50, 20), items("1", "2", "3", "4"), value(1)
numberbox bounds(158, 36, 35, 15), channel("rise2_{pname}"), range(0.01, 10.0, 0.01)
numberbox bounds(196, 36, 35, 15), channel("fall2_{pname}"), range(0.01, 10.0, 0.5)
hslider bounds(233, 34, 86, 20), channel("scale2_{pname}"), range(-1.0, 1.0, 0, 1, 0.01)
button bounds(320, 34, 29, 19), channel("scale2_x_{pname}"), text("x 1","x 10"),
hslider bounds(349, 34, 86, 20), channel("curve2_{pname}"), range(-5.0, 5.0, 0)
label bounds(10, 58, 90, 12), text("source"), colour(20,20,20,255)
label bounds(103, 58, 50, 12), text("chan"), colour(20,20,20,255)
label bounds(156, 58, 76, 12), text("rise/fall"), colour(20,20,20,255)
label bounds(236, 58, 110, 12), text("scale"), colour(20,20,20,255)
label bounds(352, 58, 81, 12), text("curve"), colour(20,20,20,255)
rslider bounds(433, 12, 62, 62), text("offset"), channel("offset_{pname}"), range({p_min}, {p_max}, {p_default}, {p_skew}, {p_incr})
combobox bounds(433, 1, 55, 12), channel("offsetx_{pname}"), items("-1", "Nornm", "+1"), , value(2), channeltype("string")
rslider bounds(494, 8, 66, 66), text("{pname}"), channel("{pname}"), range({p_min}, {p_max}, {p_default}, {p_skew}, {p_incr})
label bounds(570, 8, 55, 12), text("midi"), colour(20,20,20,255)
checkbox bounds(632, 8, 12, 12), text("enable"), channel("enable_{pname}"), value(1)
numberbox bounds(570, 25, 55, 15), channel("midich_{pname}"), range(1, 16, 1)
numberbox bounds(570, 42, 55, 15), channel("ctrlnum_{pname}"), range(1, 127, 1)
label bounds(632, 25, 70, 12), text("channel"), colour(20,20,20,255)
label bounds(632, 42, 70, 12), text("ctrl"), colour(20,20,20,255)
}}
'''
if effectname == 'vst_MIDIator': plant = plantMIDI
guifile = open(effectname+'_gui_scratchpad.inc', 'w')
x_pos = start_x_pos
x_pos1 = start_x_pos
y_pos = start_y_pos
for i in range(len(parameters)):
parm = parameters[i]
if (effectname == 'plucktremlpfverb') and (parm[0] == 'lpfDrive'):
x_pos1 = x_pos
x_pos = start_x_pos
y_pos = 575
guifile.write(plant.format(start_x=x_pos, start_y=y_pos, pname=parm[0], analysis_p=analysis_parms,p_min=parm[1][0], p_max=parm[1][1], p_default=parm[1][2], p_skew=parm[1][3], p_incr=parm[1][4]))
x_pos+=plant_height
guifile.write(';next x position available below plants is {}'.format(max([x_pos,x_pos1]))) | Oeyvind/interprocessing | codeUtility.py | Python | lgpl-3.0 | 12,966 |
# frozen_string_literal: true
require 'rails_com/config'
require 'rails_com/engine'
require 'rails_com/action_controller'
require 'rails_com/action_view'
require 'rails_com/action_text'
require 'rails_com/action_mailbox'
require 'rails_com/active_storage'
# Rails extension
require 'generators/scaffold_generator'
require 'generators/jbuilder_generator' if defined?(Jbuilder)
# default_form, 需要位于 rails_com 的加载之后
require 'default_form/config'
require 'default_form/active_record/extend'
require 'default_form/override/action_view/helpers/tags/collection_check_boxes'
require 'default_form/override/action_view/helpers/tags/collection_radio_buttons'
require 'default_form/controller_helper'
require 'default_form/view_helper'
# Utils
require 'rails_com/utils/time_helper'
require 'rails_com/utils/num_helper'
require 'rails_com/utils/qrcode_helper'
require 'rails_com/utils/uid_helper'
require 'rails_com/utils/hex_helper'
require 'rails_com/utils/jobber'
# active storage
require 'active_storage/service/disc_service'
# outside
require 'jbuilder'
require 'default_where'
require 'rails_extend'
require 'kaminari'
require 'acts_as_list'
require 'turbo-rails'
| qinmingyuan/rails_com | lib/rails_com.rb | Ruby | lgpl-3.0 | 1,183 |
<?php
namespace timesplinter\tsfw\i18n\common;
/**
* @author Pascal Muenst <dev@timesplinter.ch>
* @copyright Copyright (c) 2014, TiMESPLiNTER Webdevelopment
*/
class Localizer
{
protected $localeCategories;
protected $categories;
public function __construct()
{
$this->initLocaleCategories();
}
/**
* @param string $acceptedLanguagesString
* @param array $fallBacks
* @param string $default
* @param array|null $categories
*
* @return Localizer
*/
public static function fromAcceptedLanguages($acceptedLanguagesString, array $fallBacks = array(), $default = 'C', array $categories = array(LC_ALL))
{
$acceptedLanguageArray = array($default => 0.0);
foreach(explode(',', $acceptedLanguagesString) as $lang) {
if(preg_match('/([a-z-]{2,})(?:;q=(.+))?/i', $lang, $matches) === 0)
continue;
$localeParts = explode('_', strtr($matches[1], array('-' => '_')));
$localeCode = strtolower($localeParts[0]) . (isset($localeParts[1]) ? '_' . strtoupper($localeParts[1]) : null);
$acceptedLanguageArray[$localeCode] = isset($matches[2]) ? (float)$matches[2] : 1.0;
}
uasort($acceptedLanguageArray, function($a, $b) {
if($a === $b) return 0;
elseif($a < $b) return 1;
else return 0;
});
sort($categories);
$localesToSet = array_keys($acceptedLanguageArray);
$localizer = new Localizer();
$localeArr = array_fill_keys($categories, $localesToSet);
if(isset($localeArr[LC_ALL]) === true) {
// special case wa?
foreach($fallBacks as $cat => $localeMap) {
$localeArr[$cat] = $localeArr[LC_ALL];
}
}
foreach($localeArr as $cat => $locales) {
for($i = 0; $i < count($locales); ++$i) {
if(isset($fallBacks[$cat][$locales[$i]]) === false)
continue;
$localeArr[$cat][$i] = $fallBacks[$cat][$locales[$i]];
}
$localeArr[$cat] = array_unique($localeArr[$cat]);
}
$localizer->setLocale($localeArr);
return $localizer;
}
protected function initLocaleCategories()
{
$this->localeCategories = array(
LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME
);
if(defined('LC_MESSAGES') === true)
$this->localeCategories[] = LC_MESSAGES;
}
/**
* @param array $locales A single locale value as string or an array with category and corresponding locale(s)
*
* @return array|bool Returns an array of the specific locale set for the provided categories or false
*
* @throws \UnexpectedValueException
*/
public function setLocale(array $locales)
{
$localesSet = array();
foreach($locales as $category => $catLocales) {
if(in_array($category, $this->localeCategories) === false)
throw new \UnexpectedValueException('Invalid category: ' . $category);
if(($setCatLocale = setlocale($category, $catLocales)) !== false && in_array($category, array(LC_ALL, LC_MESSAGES)) === true) {
putenv('LANG=' . $setCatLocale);
putenv('LANGUAGE=' . $setCatLocale);
}
$localesSet[$category] = $setCatLocale;
}
return $localesSet;
}
/**
* Get all categories with its corresponding locale set
*
* @return array List of set locales. Category as key and its corresponding locale as value.
*/
public function getLocales()
{
$currentLocales = array();
foreach($this->localeCategories as $category) {
if($category === LC_ALL)
continue;
$currentLocales[$category] = setlocale($category, 0);
}
return $currentLocales;
}
/**
* Get the current locale value set for a specific category
*
* @param int $category
*
* @return string The current locale for this category
*/
public function getLocale($category)
{
return setlocale($category, '0');
}
}
/* EOF */ | TiMESPLiNTER/tsfw-i18n | src/timesplinter/tsfw/i18n/common/Localizer.php | PHP | lgpl-3.0 | 3,706 |
#
# SonarQube, open source software quality management tool.
# Copyright (C) 2008-2013 SonarSource
# mailto:contact AT sonarsource DOT com
#
# SonarQube is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3 of the License, or (at your option) any later version.
#
# SonarQube is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
#
# Sonar 3.3
#
class RemoveProfilesProvidedColumn < ActiveRecord::Migration
def self.up
remove_column('rules_profiles', 'provided')
end
end
| xinghuangxu/xinghuangxu.sonarqube | sonar-server/src/main/webapp/WEB-INF/db/migrate/335_remove_profiles_provided_column.rb | Ruby | lgpl-3.0 | 1,016 |