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
/* * #%L * GC4S components * %% * Copyright (C) 2014 - 2018 Hugo López-Fernández, Daniel Glez-Peña, Miguel Reboiro-Jato, * Florentino Fdez-Riverola, Rosalía Laza-Fidalgo, Reyes Pavón-Rial * %% * 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ /** * Provides interfaces and classes frelated to different types of events fired * by file chooser components. * * @author hlfernandez */ package org.sing_group.gc4s.input.filechooser.event;
hlfernandez/GC4S
gc4s/src/main/java/org/sing_group/gc4s/input/filechooser/event/package-info.java
Java
gpl-3.0
1,101
<?php App::uses('AppModel', 'Model'); /** * People Model * */ class People extends AppModel { /** * Use table * * @var mixed False or table name */ public $useTable = 'peoples'; /** * Display field * * @var string */ public $displayField = 'name'; /** * Validation rules * * @var array */ public $validate = array( 'name' => array( 'notEmpty' => array( 'rule' => array('notEmpty'), //'message' => 'Your custom message here', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), 'last_name' => array( 'notEmpty' => array( 'rule' => array('notEmpty'), //'message' => 'Your custom message here', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), ); }
tomasturi33/persona
app/Model/People.php
PHP
gpl-3.0
1,001
//This file is part of the gNumerator MathML DOM library, a complete //implementation of the w3c mathml dom specification //Copyright (C) 2003, Andy Somogyi // //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 // //For details, see http://numerator.sourceforge.net, or send mail to //andy@epsilon3.net using System; using System.Xml; namespace MathML { /// <summary> /// This interface represents the semantics element in MathML. /// </summary> public class MathMLSemanticsElement : MathMLElement { /// <summary> /// creates a new MathMLOperatorElement. /// </summary> /// <param name="prefix">The prefix of the new element (if any).</param> /// <param name="localName">The local name of the new element.</param> /// <param name="namespaceURI">The namespace URI of the new element (if any).</param> /// <param name="doc">The owner document</param> public MathMLSemanticsElement(string prefix, string localName, string namespaceURI, MathMLDocument doc) : base(prefix, localName, namespaceURI, doc) { } /// <summary> /// accept a visitor. /// return the return value of the visitor's visit method /// </summary> public override object Accept(MathMLVisitor v, object args) { return v.Visit(this, args); } /// <summary> /// Implement rule 2 of the definition of an embelished operator /// <see cref="MathMLElement"/> /// </summary> public override MathMLOperatorElement EmbelishedOperator { get { MathMLElement firstChild = FirstChild as MathMLElement; return firstChild is not null ? firstChild.EmbelishedOperator : null; } } } }
Altaxo/Altaxo
Libraries/Numerator/MathML/MathMLSemanticsElement.cs
C#
gpl-3.0
2,353
--TEST-- free statement after close --SKIPIF-- <?php require_once('skipif.inc'); ?> --FILE-- <?php include "connect.inc"; /************************ * free statement after close ************************/ $link = mysqli_connect($host, $user, $passwd); $stmt1 = mysqli_prepare($link, "SELECT CURRENT_USER()"); mysqli_execute($stmt1); mysqli_close($link); @mysqli_stmt_close($stmt1); printf("Ok\n"); ?> --EXPECT-- Ok
tukusejssirs/eSpievatko
spievatko/espievatko/prtbl/srv/new/php-5.2.5/ext/mysqli/tests/051.phpt
PHP
gpl-3.0
431
package ipl.frj.launcher; public enum ExecutionMode { PLAIN, TESTSET, VERBOSE; }
ferram/jtabwb_provers
ipl_frj/src/ipl/frj/launcher/ExecutionMode.java
Java
gpl-3.0
84
ig.module( 'game.weapons.beam' ) .requires( 'impact.entity' ) .defines(function() { WeaponBeam = ig.Class.extend({ name: 'WeaponBeam', displayName: 'Lasers', playerAnimOffset: 0, hudImage: new ig.Image( 'media/hud-bullet.png' ), shootSFX: new ig.Sound('media/sounds/eyebeams.*'), fire: function() { var player = ig.game.player; var pos = player.getProjectileStartPosition(); ig.game.spawnEntity( EntityBeamParticle, pos.x, pos.y, { flip: player.flip }); this.shootSFX.play(); } }); EntityBeamParticle = WeaponBase.extend({ size: { x: 20, y: 4 }, offset: { x: 0, y: 0 }, animSheet: new ig.AnimationSheet( 'media/laser-beam.png', 20, 4 ), type: ig.Entity.TYPE.NONE, checkAgainst: ig.Entity.TYPE.B, collides: ig.Entity.COLLIDES.PASSIVE, maxVel: { x: 500, y: 0 }, friction: {x: 0, y: 0}, damage: 15, init: function( x, y, settings ) { this.parent( x + (settings.flip ? -20 : 0), y, settings); this.vel.x = (settings.flip ? -this.maxVel.x : this.maxVel.x); this.addAnim( 'idle', 0.2, [0], true); this.addAnim( 'hit', 0.03, [1,2,3,4], true); }, update: function() { this.parent(); if( this.currentAnim === this.anims.hit && this.currentAnim.loopCount > 0 ) { this.kill(); } }, handleMovementTrace: function( res ) { this.parent(res); if( res.collision.x || res.collision.y || res.collision.slope ) { this.vel.x = 0; this.currentAnim = this.anims.hit.rewind(); } }, check: function(other) { if( this.currentAnim !== this.anims.hit ) { other.receiveDamage(this.damage, this); this.kill(); } }, collideWith: function( other, axis ) { if( this.currentAnim !== this.anims.hit && other ) { this.kill(); } } }); });
gamebytes/rock-kickass
lib/game/weapons/beam.js
JavaScript
gpl-3.0
1,887
/* Copyright (C) 2012,2013 Max Planck Institute for Polymer Research Copyright (C) 2008,2009,2010,2011 Max-Planck-Institute for Polymer Research & Fraunhofer SCAI This file is part of ESPResSo++. ESPResSo++ is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ESPResSo++ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ // ESPP_CLASS #ifndef __ESPRESSOPP_PARTICLEGROUP_H #define __ESPRESSOPP_PARTICLEGROUP_H #include "Particle.hpp" #include "log4espp.hpp" #include "types.hpp" //#include <list> #include <boost/signals2.hpp> namespace espresso { /** * \brief group of particles * * This part contains a list of particles to e.g. organize the system into * molecules. The particles are stored as ids, in addition a list of active * particles on the processor (or will it be cell) is generated by connecting * to the communicator signals. * * This is a first try. Further extensions might be to put groups into groups. * */ class ParticleGroup { public: ParticleGroup(shared_ptr <storage::Storage> _storage); ~ParticleGroup(); /** * \brief add particle to group * * @param pid particle id */ void add(longint pid); // for debugging purpose void print(); bool has(longint pid); longint size() {return particles.size();} static void registerPython(); /** * iterator for active particles * */ struct iterator: std::map<longint, Particle*>::iterator { iterator(const std::map<longint, Particle*>::iterator &i) : std::map<longint, Particle*>::iterator(i) { } Particle* operator*() const { return (std::map<longint, Particle*>::iterator::operator*()).second; } Particle* operator->() const { return (operator*()); } }; /** * \brief begin iterator for active particles * * @return begin iterator */ iterator begin() { return active.begin(); } /** * \brief end iterator for active particles * * @return end iterator */ iterator end() { return active.end(); } protected: // list of active particles // key: particle id, value: reference to local particle std::map<longint, Particle*> active; // list of all particles in group, /// \todo find better solution here // key: particle id, value: NONE, just used for lookup //std::map<longint, longint> particles; std::set<longint> particles; // pointer to storage object shared_ptr<storage::Storage> storage; // some signalling stuff to keep track of the particles in cell boost::signals2::connection con_send, con_recv, con_changed; void beforeSendParticles(ParticleList& pl, class OutBuffer& buf); void afterRecvParticles(ParticleList& pl, class InBuffer& buf); void onParticlesChanged(); static LOG4ESPP_DECL_LOGGER(theLogger); }; } #endif /* PARTICLEGROUP_H */
BackupTheBerlios/espressopp
src/ParticleGroup.hpp
C++
gpl-3.0
4,065
/* * This file is part of NLua. * * Copyright (c) 2013 Vinicius Jarina (viniciusjarina@gmail.com) * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; namespace NLua.Config { public static class Consts { public const string NLuaDescription = "Bridge between the Lua runtime and the CLR"; #if DEBUG public const string NLuaConfiguration = "Debug"; #else public const string NLuaConfiguration = "Release"; #endif public const string NLuaCompany = "NLua.org"; public const string NLuaProduct = "NLua"; public const string NLuaCopyright = "Copyright 2003-2013 Vinicius Jarina , Fabio Mascarenhas, Kevin Hesterm and Megax"; public const string NLuaTrademark = "MIT license"; public const string NLuaVersion = "1.3.0"; public const string NLuaFileVersion = "1.3.0"; } }
thexa4/FactorioCalculator
References/NLua/Core/NLua/Config/NLuaConfig.cs
C#
gpl-3.0
1,890
package rtg.world.biome.realistic.biomesyougo; import net.minecraft.block.Block; import net.minecraft.block.BlockPlanks; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.ChunkPrimer; import rtg.api.config.BiomeConfig; import rtg.api.util.BlockUtil; import rtg.api.util.noise.SimplexNoise; import rtg.api.world.RTGWorld; import rtg.api.world.surface.SurfaceBase; import rtg.api.world.terrain.TerrainBase; import rtg.api.world.terrain.heighteffect.GroundEffect; import java.util.Random; public class RealisticBiomeBYGWeepingWitchForest extends RealisticBiomeBYGBase { public RealisticBiomeBYGWeepingWitchForest(Biome biome) { super(biome, RiverType.NORMAL, BeachType.NORMAL); } @Override public void initConfig() { this.getConfig().addProperty(this.getConfig().ALLOW_LOGS).set(true); this.getConfig().addProperty(this.getConfig().FALLEN_LOG_DENSITY_MULTIPLIER); this.getConfig().addProperty(this.getConfig().SURFACE_MIX_BLOCK).set(""); } @Override public void initDecos() { fallenTrees(new IBlockState[]{ BlockUtil.getBlockStateFromCfgString("byg:witchhazellog", BlockUtil.getStateLog(BlockPlanks.EnumType.ACACIA)), BlockUtil.getBlockStateFromCfgString("byg:witchhazellog", BlockUtil.getStateLog(BlockPlanks.EnumType.ACACIA)) }, new int[]{4, 4} ); } @Override public TerrainBase initTerrain() { return new TerrainVanillaRoofedForest(); } @Override public SurfaceBase initSurface() { return new SurfaceVanillaRoofedForest(getConfig(), baseBiome().topBlock, baseBiome().fillerBlock, 0f, 1.5f, 60f, 65f, 1.5f, baseBiome().topBlock, 0.15f); } public static class TerrainVanillaRoofedForest extends TerrainBase { private GroundEffect groundEffect = new GroundEffect(4f); public TerrainVanillaRoofedForest() { } @Override public float generateNoise(RTGWorld rtgWorld, int x, int y, float border, float river) { //return terrainPlains(x, y, simplex, river, 160f, 10f, 60f, 80f, 65f) return riverized(65f + groundEffect.added(rtgWorld, x, y), river); } } public static class SurfaceVanillaRoofedForest extends SurfaceBase { private float min; private float sCliff = 1.5f; private float sHeight = 60f; private float sStrength = 65f; private float cCliff = 1.5f; private IBlockState mixBlock; private float mixHeight; public SurfaceVanillaRoofedForest(BiomeConfig config, IBlockState top, IBlockState fill, float minCliff, float stoneCliff, float stoneHeight, float stoneStrength, float clayCliff, IBlockState mix, float mixSize) { super(config, top, fill); min = minCliff; sCliff = stoneCliff; sHeight = stoneHeight; sStrength = stoneStrength; cCliff = clayCliff; mixBlock = this.getConfigBlock(config.SURFACE_MIX_BLOCK.get(), mix); mixHeight = mixSize; } @Override public void paintTerrain(ChunkPrimer primer, int i, int j, int x, int z, int depth, RTGWorld rtgWorld, float[] noise, float river, Biome[] base) { Random rand = rtgWorld.rand(); SimplexNoise simplex = rtgWorld.simplexInstance(0); float c = TerrainBase.calcCliff(x, z, noise); int cliff = 0; boolean m = false; Block b; for (int k = 255; k > -1; k--) { b = primer.getBlockState(x, k, z).getBlock(); if (b == Blocks.AIR) { depth = -1; } else if (b == Blocks.STONE) { depth++; if (depth == 0) { float p = simplex.noise3f(i / 8f, j / 8f, k / 8f) * 0.5f; if (c > min && c > sCliff - ((k - sHeight) / sStrength) + p) { cliff = 1; } if (c > cCliff) { cliff = 2; } if (cliff == 1) { if (rand.nextInt(3) == 0) { primer.setBlockState(x, k, z, hcCobble()); } else { primer.setBlockState(x, k, z, hcStone()); } } else if (cliff == 2) { primer.setBlockState(x, k, z, getShadowStoneBlock()); } else if (k < 63) { if (k < 62) { primer.setBlockState(x, k, z, fillerBlock); } else { primer.setBlockState(x, k, z, topBlock); } } else if (simplex.noise2f(i / 12f, j / 12f) > mixHeight) { primer.setBlockState(x, k, z, mixBlock); m = true; } else { primer.setBlockState(x, k, z, topBlock); } } else if (depth < 6) { if (cliff == 1) { primer.setBlockState(x, k, z, hcStone()); } else if (cliff == 2) { primer.setBlockState(x, k, z, getShadowStoneBlock()); } else { primer.setBlockState(x, k, z, fillerBlock); } } } } } } }
Team-RTG/Realistic-Terrain-Generation
src/main/java/rtg/world/biome/realistic/biomesyougo/RealisticBiomeBYGWeepingWitchForest.java
Java
gpl-3.0
6,120
/* Zevra, a UCI chess playing engine Copyright (C) 2016-2017 Oleg Smirnov (author) Zevra is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. Zevra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "goback.hpp" GoBack::GoBack() {}
sovaz1997/ChessProblemGenerator
Zevra/goback.cpp
C++
gpl-3.0
751
/* * Copyright © 2008 Daniel W. Goldberg * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System.Collections.Generic; namespace TAMU.GeoInnovation.Applications.Census.ReferenceDataImporter.Workers { public interface ICensusTractLevelImporterWorker : IStateLevelImporterWorker { #region Properties bool ShouldDoCensusTracts2000 { get; set; } bool ShouldDoCensusBlocks2000 { get; set; } bool ShouldDoCensusBlocks2008 { get; set; } bool ShouldDoCensusBlocks2010 { get; set; } bool ShouldDoCensusTracts2010 { get; set; } bool ShouldDoCensusBlockGroups2000 { get; set; } List<string> Zips { get; set; } List<string> States { get; set; } #endregion } }
TamuGeoInnovation/TAMU.GeoInnovation.PointIntersectors.Census.ReferenceDataImporters
src/Main/Workers/Interfaces/ICensusTractLevelImporterWorker.cs
C#
gpl-3.0
1,360
/* * Straight - A system to manage financial demands for small and decentralized * organizations. * Copyright (C) 2011 Octahedron * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package br.octahedron.figgo.modules.admin.util; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Scanner; import java.util.TimeZone; import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import com.google.appengine.api.urlfetch.HTTPHeader; import com.google.appengine.api.urlfetch.HTTPMethod; import com.google.appengine.api.urlfetch.HTTPRequest; import com.google.appengine.api.urlfetch.HTTPResponse; import com.google.appengine.api.urlfetch.URLFetchService; import com.google.appengine.api.urlfetch.URLFetchServiceFactory; /** * @author Danilo Penna Queiroz */ public class Route53Util { private static final Logger logger = Logger.getLogger(Route53Util.class.getName()); private static final URLFetchService urlFetchService = URLFetchServiceFactory.getURLFetchService(); private static final SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.US); private static final String ROUTE53_SERVER = "https://route53.amazonaws.com"; private static final String EXISTS_DOMAIN_MESSAGE = "type CNAME but it already exists"; private static final String DATE_COMMAND = "/date"; private static final String VERSION_SPEC = "/2011-05-05"; private static final String HOSTED_ZONE_COMMAND = "/hostedzone/"; private static final String RRSET = "/rrset"; private static final String ACCESS_ID_TOKEN = "{accessid}"; private static final String SIGNATURE_TOKEN = "{sign}"; private static final String DOMAIN_TOKEN = "{domain}"; private static final String CREATE_DOMAIN_TEMPLATE = "create_domain.xml"; private static final String KEY_ALGORITHM = "PBKDF2WithHmacSHA1"; private static final String MAC_ALGORITHM = "HmacSHA1"; private static final String AUTH_TOKEN = "AWS3-HTTPS AWSAccessKeyId={accessid},Algorithm=" + MAC_ALGORITHM + ",Signature={sign}"; private static final String FETCH_DATE_HEADER = "Date"; private static final String SUBMIT_DATE_HEADER = "x-amz-date"; private static final String AUTHORIZATION_HEADER = "X-Amzn-Authorization"; static { formatter.setTimeZone(TimeZone.getTimeZone("GMT")); } public static void createDomain(String domain, String accessId, String accessKey, String hostedZoneId) throws Route53Exception { try { HTTPRequest request = new HTTPRequest(new URL(ROUTE53_SERVER + VERSION_SPEC + HOSTED_ZONE_COMMAND + hostedZoneId + RRSET), HTTPMethod.POST); String requestBody = generateRequestBody(domain); logger.fine(requestBody); request.setPayload(requestBody.getBytes()); signRequest(request, accessId, accessKey); HTTPResponse response = urlFetchService.fetch(request); if (response.getResponseCode() != 200) { logger.fine("Unable to create domain: " + domain); String out = new String(response.getContent()); if (out.contains(EXISTS_DOMAIN_MESSAGE)) { throw new DomainAlreadyExistsException(domain); } else { throw new Route53Exception(out); } } // TODO change it when we migrate to Java 7 } catch (MalformedURLException e) { logger.log(Level.WARNING, "Unexpected error: " + e.getMessage(), e); } catch (InvalidKeyException e) { logger.log(Level.WARNING, "Unexpected error: " + e.getMessage(), e); } catch (InvalidKeySpecException e) { logger.log(Level.WARNING, "Unexpected error: " + e.getMessage(), e); } catch (NoSuchAlgorithmException e) { logger.log(Level.WARNING, "Unexpected error: " + e.getMessage(), e); } catch (IOException e) { logger.log(Level.WARNING, "Unexpected error: " + e.getMessage(), e); } } protected static void signRequest(HTTPRequest request, String accessID, String key) throws IOException, InvalidKeyException, InvalidKeySpecException, NoSuchAlgorithmException { String date = fetchDate(); String sign = sign(date, key); String signature = AUTH_TOKEN.replace(ACCESS_ID_TOKEN, accessID); signature = signature.replace(SIGNATURE_TOKEN, sign); request.addHeader(new HTTPHeader(SUBMIT_DATE_HEADER, date)); request.addHeader(new HTTPHeader(AUTHORIZATION_HEADER, signature)); request.addHeader(new HTTPHeader("Content-Type", "text/xml; charset=UTF-8")); } protected static String sign(String content, String key) throws InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, IllegalStateException { Mac mac = Mac.getInstance(MAC_ALGORITHM); SecretKey skey = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM); mac.init(skey); mac.update(content.getBytes()); return new String(Base64.encodeBase64((mac.doFinal()))); } protected static String fetchDate() throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(ROUTE53_SERVER + DATE_COMMAND).openConnection(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { return formatter.format(new Date(connection.getHeaderFieldDate(FETCH_DATE_HEADER, 0))); } else { return null; } } protected static String generateRequestBody(String domain) { Scanner sc = new Scanner(Route53Util.class.getClassLoader().getResourceAsStream(CREATE_DOMAIN_TEMPLATE)); try { StringBuilder buf = new StringBuilder(); while (sc.hasNext()) { String token = sc.next(); if (token.contains(DOMAIN_TOKEN)) { buf.append(token.replace(DOMAIN_TOKEN, domain)); } else { buf.append(token); } buf.append(' '); } return buf.toString(); } finally { sc.close(); } } }
fesl/figgo
src/main/java/br/octahedron/figgo/modules/admin/util/Route53Util.java
Java
gpl-3.0
6,610
/* * LaaNo Android application * * @author Aleksandr Borisenko <developer@laano.net> * Copyright (C) 2017 Aleksandr Borisenko * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.bytesforge.linkasanote.laano; import static com.google.common.base.Preconditions.checkNotNull; import android.accounts.Account; import android.content.res.Resources; import android.util.SparseArray; import android.util.SparseIntArray; import android.view.Menu; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.StringRes; import androidx.appcompat.app.ActionBar; import com.bytesforge.linkasanote.R; import com.bytesforge.linkasanote.data.Favorite; import com.bytesforge.linkasanote.data.Link; import com.bytesforge.linkasanote.data.Note; import com.bytesforge.linkasanote.laano.favorites.FavoritesViewModel; import com.bytesforge.linkasanote.laano.links.LinksViewModel; import com.bytesforge.linkasanote.laano.notes.NotesViewModel; import com.bytesforge.linkasanote.manageaccounts.AccountItem; import com.bytesforge.linkasanote.settings.Settings; import com.bytesforge.linkasanote.sync.SyncAdapter; import com.bytesforge.linkasanote.utils.CloudUtils; import com.bytesforge.linkasanote.utils.CommonUtils; import com.google.android.material.snackbar.Snackbar; import com.google.android.material.tabs.TabLayout; public class LaanoUiManager { private static final String TAG = LaanoUiManager.class.getSimpleName(); private final LaanoActivity laanoActivity; private final Settings settings; private final Resources resources; private final ActionBar actionBar; private final TabLayout tabLayout; private final Menu drawerMenu; private final LaanoDrawerHeaderViewModel headerViewModel; private final LaanoFragmentPagerAdapter pagerAdapter; private SparseArray<String> syncTitles = new SparseArray<>(); private SparseArray<String> normalTitles = new SparseArray<>(); private SparseIntArray syncUploaded = new SparseIntArray(); private SparseIntArray syncDownloaded = new SparseIntArray(); private boolean syncState = false; public LaanoUiManager( @NonNull LaanoActivity laanoActivity, @NonNull Settings settings, @NonNull TabLayout tabLayout, @NonNull Menu drawerMenu, @NonNull LaanoDrawerHeaderViewModel headerViewModel, @NonNull LaanoFragmentPagerAdapter pagerAdapter) { this.laanoActivity = checkNotNull(laanoActivity); this.settings = settings; this.tabLayout = checkNotNull(tabLayout); this.drawerMenu = checkNotNull(drawerMenu); this.headerViewModel = checkNotNull(headerViewModel); this.pagerAdapter = checkNotNull(pagerAdapter); resources = checkNotNull(laanoActivity).getResources(); this.actionBar = checkNotNull(laanoActivity.getSupportActionBar()); } public void setTabSyncState(int position) { if (pagerAdapter.getState(position) != LaanoFragmentPagerAdapter.STATE_SYNC) { setTab(position, LaanoFragmentPagerAdapter.STATE_SYNC); setSyncTitle(position); } } public void setTabNormalState(int position, boolean isConflicted) { setTab(position, isConflicted ? LaanoFragmentPagerAdapter.STATE_PROBLEM : LaanoFragmentPagerAdapter.STATE_DEFAULT); } private void setTab(int position, int state) { TabLayout.Tab tab = tabLayout.getTabAt(position); if (tab == null) return; pagerAdapter.updateTab(tab, position, state); } private void setSyncTitle(int position) { String title = String.format(resources.getString( R.string.laano_actionbar_manager_sync_title), syncUploaded.get(position), syncDownloaded.get(position)); syncTitles.put(position, title); } public void setFilterType(int position, @NonNull FilterType filterType) { checkNotNull(filterType); String normalTitle; switch (filterType) { case ALL: normalTitle = resources.getString(R.string.filter_all); break; case CONFLICTED: normalTitle = resources.getString(R.string.filter_conflicted); break; case LINK: Link linkFilter = settings.getLinkFilter(); if (linkFilter == null) { throw new IllegalStateException("setFilterType(): Link filter must not be null"); } String linkTitle = linkFilter.getName() == null ? linkFilter.getLink() : linkFilter.getName(); normalTitle = LinksViewModel.FILTER_PREFIX + " " + linkTitle; break; case FAVORITE: Favorite favoriteFilter = settings.getFavoriteFilter(); if (favoriteFilter == null) { throw new IllegalStateException("setFilterType(): Favorite filter must not be null"); } String filterPrefix = favoriteFilter.isAndGate() ? FavoritesViewModel.FILTER_AND_GATE_PREFIX : FavoritesViewModel.FILTER_OR_GATE_PREFIX; normalTitle = filterPrefix + " " + favoriteFilter.getName(); break; case NOTE: Note noteFilter = settings.getNoteFilter(); if (noteFilter == null) { throw new IllegalStateException("setFilterType(): Note filter must not be null"); } normalTitle = NotesViewModel.FILTER_PREFIX + " " + noteFilter.getNote(); break; case NO_TAGS: normalTitle = resources.getString(R.string.filter_no_tags); break; case UNBOUND: normalTitle = resources.getString(R.string.filter_unbound); break; default: throw new IllegalArgumentException("Unexpected filtering type [" + filterType.name() + "]"); } setNormalTitle(position, normalTitle); } private void setNormalTitle(int position, String normalTitle) { String title = CommonUtils.strFirstLine(normalTitle); normalTitles.put(position, title); } public void updateTitle(int position) { if (position != laanoActivity.getActiveTab()) return; String title; if (pagerAdapter.getState(position) == LaanoFragmentPagerAdapter.STATE_SYNC) { title = syncTitles.get(position); } else { title = normalTitles.get(position); } if (title == null) { // Fallback title = pagerAdapter.getPageTitle(position).toString(); } actionBar.setTitle(title); } public void resetCounters(int position) { syncUploaded.put(position, 0); syncDownloaded.put(position, 0); } public void setUploaded(int position, int count) { syncUploaded.put(position, count); setSyncTitle(position); } public void incUploaded(int position) { syncUploaded.put(position, syncUploaded.get(position) + 1); setSyncTitle(position); } public void setDownloaded(int position, int count) { syncDownloaded.put(position, count); setSyncTitle(position); } public void incDownloaded(int position) { syncDownloaded.put(position, syncDownloaded.get(position) + 1); setSyncTitle(position); } public void updateDefaultAccount(Account account) { settings.setSyncable(account != null); if (settings.isSyncable()) { assert account != null; AccountItem accountItem = CloudUtils.getAccountItem(account, laanoActivity); headerViewModel.showAccount(accountItem); } else { headerViewModel.showAppName(); } updateNormalDrawerMenu(); } /** * Update Navigation Drawer Header */ public void updateSyncStatus() { long lastSyncTime = settings.getLastSyncTime(); int syncStatus = settings.getSyncStatus(); headerViewModel.showSyncStatus(lastSyncTime, syncStatus); } public void notifySyncStatus() { int syncStatus = settings.getSyncStatus(); switch (syncStatus) { case SyncAdapter.SYNC_STATUS_SYNCED: showShortToast(R.string.toast_sync_success); break; case SyncAdapter.SYNC_STATUS_ERROR: showLongToast(R.string.toast_sync_error); break; case SyncAdapter.SYNC_STATUS_CONFLICT: showLongToast(R.string.toast_sync_conflict); break; } } public void showShortToast(@StringRes int toastId) { Toast.makeText(laanoActivity, toastId, Toast.LENGTH_SHORT).show(); } public void showLongToast(@StringRes int toastId) { Toast.makeText(laanoActivity, toastId, Toast.LENGTH_LONG).show(); } private void updateNormalDrawerMenu() { if (Settings.GLOBAL_MULTIACCOUNT_SUPPORT) { drawerMenu.findItem(R.id.add_account_menu_item).setVisible(true); drawerMenu.findItem(R.id.manage_accounts_menu_item).setVisible(true); } else if (settings.isSyncable()) { drawerMenu.findItem(R.id.add_account_menu_item).setVisible(false); drawerMenu.findItem(R.id.manage_accounts_menu_item).setVisible(true); } else { drawerMenu.findItem(R.id.add_account_menu_item).setVisible(true); drawerMenu.findItem(R.id.manage_accounts_menu_item).setVisible(false); } setNormalDrawerMenu(); } public void setSyncDrawerMenu() { if (!syncState) { syncState = true; drawerMenu.findItem(R.id.sync_menu_item).setTitle(R.string.drawer_actions_sync_in_progress); drawerMenu.findItem(R.id.sync_menu_item).setEnabled(false); } } /** * Set Navigation Drawer Menu to Normal state */ public void setNormalDrawerMenu() { syncState = false; drawerMenu.findItem(R.id.sync_menu_item).setTitle(R.string.drawer_actions_sync_start); if (settings.isSyncable()) { drawerMenu.findItem(R.id.sync_menu_item).setEnabled(true); } else { drawerMenu.findItem(R.id.sync_menu_item).setEnabled(false); } } public void setCurrentTab(int tab) { laanoActivity.setCurrentTab(tab); } public void showApplicationOfflineSnackbar() { Snackbar.make(tabLayout, R.string.laano_offline, Snackbar.LENGTH_LONG).show(); } public void showApplicationNotSyncableSnackbar() { Snackbar.make(tabLayout, R.string.laano_not_syncable, Snackbar.LENGTH_LONG).show(); } }
alexcustos/linkasanote
app/src/main/java/com/bytesforge/linkasanote/laano/LaanoUiManager.java
Java
gpl-3.0
11,505
package info.peilwebsystems.opensource.marketlist.productmanagement.repository; import java.util.Set; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import info.peilwebsystems.opensource.marketlist.productmanagement.domain.Category; @Repository public interface CategoryRepository extends CrudRepository<Category, Long> { Set<Category> findAllByOrderByName(); }
lgpoliveira/MarketList
src/main/java/info/peilwebsystems/opensource/marketlist/productmanagement/repository/CategoryRepository.java
Java
gpl-3.0
431
package crypto import ( "bytes" "encoding/hex" "fmt" "testing" "time" "github.com/eris-ltd/mint-client/Godeps/_workspace/src/github.com/eris-ltd/eris-keys/crypto/secp256k1" ) func Test0Key(t *testing.T) { t.Skip() key, _ := hex.DecodeString("1111111111111111111111111111111111111111111111111111111111111111") p, err := secp256k1.GeneratePubKey(key) addr := Sha3(p[1:])[12:] fmt.Printf("%x\n", p) fmt.Printf("%v %x\n", err, addr) } // These tests are sanity checks. // They should ensure that we don't e.g. use Sha3-224 instead of Sha3-256 // and that the sha3 library uses keccak-f permutation. func TestSha3(t *testing.T) { msg := []byte("abc") exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45") checkhash(t, "Sha3-256", func(in []byte) []byte { return Sha3(in) }, msg, exp) } /* func TestSha256(t *testing.T) { msg := []byte("abc") exp, _ := hex.DecodeString("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad") checkhash(t, "Sha256", Sha256, msg, exp) } func TestRipemd160(t *testing.T) { msg := []byte("abc") exp, _ := hex.DecodeString("8eb208f7e05d987a9b044a8e98c6b087f15a0bfc") checkhash(t, "Ripemd160", Ripemd160, msg, exp) } */ func checkhash(t *testing.T, name string, f func([]byte) []byte, msg, exp []byte) { sum := f(msg) if bytes.Compare(exp, sum) != 0 { t.Errorf("hash %s returned wrong result.\ngot: %x\nwant: %x", name, sum, exp) } } func BenchmarkSha3(b *testing.B) { a := []byte("hello world") amount := 1000000 start := time.Now() for i := 0; i < amount; i++ { Sha3(a) } fmt.Println(amount, ":", time.Since(start)) } // TODO: we should add sig tests too
alist/mint-client
Godeps/_workspace/src/github.com/eris-ltd/eris-keys/crypto/crypto_test.go
GO
gpl-3.0
1,679
package ru.fgv.test8; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalDouble; import java.util.TreeMap; import java.util.stream.LongStream; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.joda.time.DateTime; import org.joda.time.Duration; import static java.util.stream.Collectors.counting; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; /** * * @author prusakovan */ public class LambdaMain { static final Logger LOG = LogManager.getLogger(LambdaMain.class.getName()); /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here String test = "hello, world"; LOG.info("Тест {}", test); // Тест обхода коллекций Stream<Integer> st = Stream.iterate(1, i -> ++i); List<Integer> l = st.limit(300000).collect(toList()); DateTime start = DateTime.now(); Integer sum1 = 0; for (Integer i : l) { sum1 += i; } DateTime end = DateTime.now(); Duration dur1 = new Duration(start, end); start = DateTime.now(); Optional<Integer> summ = l.stream().reduce((i, j) -> i + j); Integer sum2 = summ.orElse(0); end = DateTime.now(); Duration dur2 = new Duration(start, end); start = DateTime.now(); Optional<Integer> summ2 = l.parallelStream().reduce(Integer::sum); Integer sum3 = summ2.orElse(0); end = DateTime.now(); Duration dur3 = new Duration(start, end); LOG.info("Результат работы через цикл: время - {}, сумма = {}]", dur1.getMillis(), sum1); LOG.info("Результат работы через Stream: время - {}, сумма = {}]", dur2.getMillis(), sum2); LOG.info("Результат работы через Parallel: время - {}, сумма = {}]", dur3.getMillis(), sum3); // тест поиска среднего значения случайных чисел Stream<Long> avg = Stream.generate(LambdaMain::intRandom); List<Long> g = avg.limit(1000000).collect(toList()); LongStream avgLong = LongStream.generate(LambdaMain::intRandom); start = DateTime.now(); long m1 = 0; for (Long i : g) { m1 += i; } double max1 = (double) m1 / g.size(); Duration durAvg1 = new Duration(start, DateTime.now()); start = DateTime.now(); OptionalDouble a = g.stream().mapToLong(Long::longValue).average(); Duration durAvg2 = new Duration(start, DateTime.now()); start = DateTime.now(); OptionalDouble a2 = g.parallelStream().mapToLong(Long::longValue).average(); Duration durAvg3 = new Duration(start, DateTime.now()); start = DateTime.now(); OptionalDouble an = avgLong.limit(1000000).average(); Duration durAvgN2 = new Duration(start, DateTime.now()); LOG.info("Поиск среднего арифмитического: "); LOG.info("Результат работы через цикл: время - {}, среднее = {}]", durAvg1.getMillis(), max1); LOG.info("Результат работы через Stream: время - {}, среднее = {}]", durAvg2.getMillis(), a.orElse(0)); LOG.info("Результат работы через Parallel: время - {}, среднее = {}]", durAvg3.getMillis(), a2.orElse(0)); LOG.info("Результат работы через Stream: время - {}, среднее = {}]", durAvgN2.getMillis(), an.orElse(0)); //LOG.info("Результат работы через Parallel: время - {}, среднее = {}]", durAvgN3.getMillis(), an2.orElse(0)); // считываем файл и определяем число слов и пр. start = DateTime.now(); try (InputStream resource = LambdaMain.class.getClassLoader().getResourceAsStream("Losev.txt"); InputStreamReader isr = new InputStreamReader(resource, "UTF-8"); BufferedReader br = new BufferedReader(isr);) { String find = "античность"; Stream<String> splitAsStream = br.lines(); Map<Integer, Map<String, Long>> collect = splitAsStream .flatMap(s -> Stream.of(s.split("[\\P{L}]+"))) .map(s -> s.toLowerCase()) .filter(s -> s.length() > 2) .collect( groupingBy(s -> s.length(), groupingBy(s -> s, counting()))); TreeMap<Integer, Map<String, Long>> sorted = new TreeMap<>(collect); LOG.info(collect.toString()); Map<String, Long> findRaw = sorted.get(find.length()); LOG.info("Слово {} встречается {} раз. В нем {} букв", find, findRaw.getOrDefault(find, 0L), find.length()); Map<String, Long> value = sorted.lastEntry().getValue(); Optional<String> findFirst = value.keySet().stream().findFirst(); LOG.info("Cамое длинное встречающее слово {} встречается в тексте {} раз", findFirst.orElse("-"), value.get(findFirst.get())); Map<Integer, Integer> countingInText = sorted.entrySet().stream() //.map(entr -> entr.getValue().size()) .collect(toMap(entr -> entr.getKey(), entr -> entr.getValue().size())); LOG.info("Количество вхождений слов определенной длины:"); countingInText.forEach( (key, v) -> LOG.info("Слова длиной {} символов встречаются в тексте {}", key, v) ); } catch (IOException ex) { LOG.warn("Ошибка {}", ex.toString()); } Duration durText = new Duration(start, DateTime.now()); LOG.info("Вся работа с текстом, включая закрытие потоков заняла: {} мс.", durText.getMillis()); } private static Long intRandom() { return (long) (10000000 * Math.abs(Math.random())); } }
iok1979/test
test8/src/main/java/ru/fgv/test8/LambdaMain.java
Java
gpl-3.0
6,686
// XTPChartPointSeriesStyle.cpp // // This file is a part of the XTREME TOOLKIT PRO MFC class library. // (c)1998-2012 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Common/XTPPropExchange.h" #include "../../Types/XTPChartTypes.h" #include "../../XTPChartDefines.h" #include "../../XTPChartElement.h" #include <Chart/XTPChartLegendItem.h> #include "../../XTPChartElementView.h" #include "../../XTPChartSeries.h" #include "../../XTPChartSeriesPoint.h" #include <Chart/XTPChartSeriesPointView.h> #include "../../XTPChartSeriesView.h" #include "../../XTPChartSeriesLabel.h" #include "../../XTPChartSeriesStyle.h" #include <Common/XTPMathUtils.h> #include "../../Drawing/XTPChartDeviceCommand.h" #include "../../Diagram/Diagram2D/XTPChartDiagram2DSeriesStyle.h" #include "../../Diagram/Diagram2D/XTPChartDiagram2DSeriesLabel.h" #include "../../Diagram/Diagram2D/XTPChartDiagram2DSeriesView.h" #include "XTPChartPointSeriesStyle.h" #include "XTPChartPointSeriesLabel.h" #include "XTPChartPointSeriesView.h" #include "XTPChartMarker.h" IMPLEMENT_SERIAL(CXTPChartPointSeriesStyle, CXTPChartDiagram2DSeriesStyle, VERSIONABLE_SCHEMA | _XTP_SCHEMA_CURRENT) ////////////////////////////////////////////////////////////////////////// // CXTPChartPointSeriesStyle CXTPChartPointSeriesStyle::CXTPChartPointSeriesStyle() { m_pMarker = new CXTPChartMarker(this); SetLabel(new CXTPChartPointSeriesLabel()); } CXTPChartPointSeriesStyle::~CXTPChartPointSeriesStyle() { SAFE_RELEASE(m_pMarker); } void CXTPChartPointSeriesStyle::DoPropExchange(CXTPPropExchange* pPX) { CXTPChartDiagram2DSeriesStyle::DoPropExchange(pPX); CXTPPropExchangeSection secMarker(pPX->GetSection(_T("Marker"))); m_pMarker->DoPropExchange(&secMarker); } CXTPChartSeriesView* CXTPChartPointSeriesStyle::CreateView(CXTPChartSeries* pSeries, CXTPChartDiagramView* pDiagramView) { return new CXTPChartPointSeriesView(pSeries, pDiagramView); } ////////////////////////////////////////////////////////////////////////// // CXTPChartPointSeriesView CXTPChartPointSeriesView::CXTPChartPointSeriesView(CXTPChartSeries* pSeries, CXTPChartDiagramView* pDiagramView) : CXTPChartDiagram2DSeriesView(pSeries,pDiagramView) { } CXTPChartSeriesPointView* CXTPChartPointSeriesView::CreateSeriesPointView(CXTPChartDeviceContext* pDC, CXTPChartSeriesPoint* pPoint, CXTPChartElementView* pParentView) { UNREFERENCED_PARAMETER(pDC); return new CXTPChartPointSeriesPointView(pPoint, pParentView); } CXTPChartDeviceCommand* CXTPChartPointSeriesView::CreateLegendDeviceCommand(CXTPChartDeviceContext* pDC, CRect rcBounds) { UNREFERENCED_PARAMETER(pDC); rcBounds.DeflateRect(1, 1, 2, 2); CXTPChartDeviceCommand* pCommand = new CXTPChartDeviceCommand(); CXTPChartPointSeriesStyle* pStyle = STATIC_DOWNCAST(CXTPChartPointSeriesStyle, m_pSeries->GetStyle()); CXTPChartPointF ptCenter(rcBounds.CenterPoint().x, rcBounds.CenterPoint().y) ; int nSize = min(rcBounds.Width(), rcBounds.Height()); pCommand->AddChildCommand(pStyle->GetMarker()->CreateDeviceCommand(pDC, ptCenter, nSize, m_pSeries->GetColor(), m_pSeries->GetColor2(), m_pSeries->GetColor().GetDarkColor())); return pCommand; } ////////////////////////////////////////////////////////////////////////// // CXTPChartPointSeriesPointView CXTPChartPointSeriesPointView::CXTPChartPointSeriesPointView(CXTPChartSeriesPoint* pPoint, CXTPChartElementView* pParentView) : CXTPChartSeriesPointView(pPoint, pParentView) { } CXTPChartPointF CXTPChartPointSeriesPointView::GetScreenPoint() const { CXTPChartPointSeriesView* pView = (CXTPChartPointSeriesView*)GetSeriesView(); return pView->GetScreenPoint(m_pPoint->GetInternalArgumentValue(), m_dInternalValue); } CXTPChartDeviceCommand* CXTPChartPointSeriesPointView::CreateDeviceCommand(CXTPChartDeviceContext* pDC) { CXTPChartColor color = GetColor(); CXTPChartColor color2 = GetColor2(); CXTPChartColor colorBorder = GetColor().GetDarkColor(); if (CXTPMathUtils::IsNan(m_dInternalValue)) return NULL; CXTPChartDeviceCommand* pCommand = new CXTPChartHitTestElementCommand(m_pPoint); CXTPChartPointF point = GetScreenPoint(); pCommand->AddChildCommand(((CXTPChartPointSeriesStyle*)GetSeriesView()->GetStyle())->GetMarker()->CreateDeviceCommand(pDC, point, color, color2, colorBorder)); return pCommand; } CXTPChartDeviceCommand* CXTPChartPointSeriesPointView::CreateLegendDeviceCommand(CXTPChartDeviceContext* pDC, CRect rcBounds) { UNREFERENCED_PARAMETER(pDC); rcBounds.DeflateRect(1, 1, 2, 2); CXTPChartDeviceCommand* pCommand = new CXTPChartDeviceCommand(); CXTPChartPointSeriesStyle* pStyle = STATIC_DOWNCAST(CXTPChartPointSeriesStyle, GetSeriesView()->GetSeries()->GetStyle()); CXTPChartPointF ptCenter(rcBounds.CenterPoint().x, rcBounds.CenterPoint().y) ; int nSize = min(rcBounds.Width(), rcBounds.Height()); pCommand->AddChildCommand(pStyle->GetMarker()->CreateDeviceCommand(pDC, ptCenter, nSize, GetColor(), GetColor2(), GetColor().GetDarkColor())); return pCommand; } #ifdef _XTP_ACTIVEX BEGIN_DISPATCH_MAP(CXTPChartPointSeriesStyle, CXTPChartDiagram2DSeriesStyle) DISP_PROPERTY_EX_ID(CXTPChartPointSeriesStyle, "Marker", 4, OleGetMarker, SetNotSupported, VT_DISPATCH) END_DISPATCH_MAP() // {D32BCC77-27BF-4cb1-9ABF-4558D9835223} static const GUID IID_IChartPointSeriesStyle = { 0xd32bcc77, 0x27bf, 0x4cb1, { 0x9a, 0xbf, 0x45, 0x58, 0xd9, 0x83, 0x52, 0x23 } }; BEGIN_INTERFACE_MAP(CXTPChartPointSeriesStyle, CXTPChartDiagram2DSeriesStyle) INTERFACE_PART(CXTPChartPointSeriesStyle, IID_IChartPointSeriesStyle, Dispatch) END_INTERFACE_MAP() IMPLEMENT_OLETYPELIB_EX(CXTPChartPointSeriesStyle, IID_IChartPointSeriesStyle) // {24490E6F-92B6-4671-9613-6B2A0FBF80A8} IMPLEMENT_OLECREATE_EX2(CXTPChartPointSeriesStyle, "Codejock.ChartPointSeriesStyle." _XTP_AXLIB_VERSION, 0x24490e6f, 0x92b6, 0x4671, 0x96, 0x13, 0x6b, 0x2a, 0xf, 0xbf, 0x80, 0xa8); LPDISPATCH CXTPChartPointSeriesStyle::OleGetMarker() { return XTPGetDispatch(m_pMarker); } #endif
atlaser/Tools
PMEditor/libs/Xtreme_ToolkitPro_v15.3.1/Source/Chart/Styles/Point/XTPChartPointSeriesStyle.cpp
C++
gpl-3.0
6,589
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Renderers to align Moodle's HTML with that expected by Bootstrap * * @package theme_bootstrapbase * @copyright 2012 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class theme_bootstrapbase_core_renderer extends core_renderer { /* * This renders a notification message. * Uses bootstrap compatible html. */ public function notification($message, $classes = 'notifyproblem') { $message = clean_text($message); $type = ''; if ($classes == 'notifyproblem') { $type = 'alert alert-error'; } if ($classes == 'notifysuccess') { $type = 'alert alert-success'; } if ($classes == 'notifymessage') { $type = 'alert alert-info'; } if ($classes == 'redirectmessage') { $type = 'alert alert-block alert-info'; } return "<div class=\"$type\">$message</div>"; } /* * This renders the navbar. * Uses bootstrap compatible html. */ public function navbar() { $items = $this->page->navbar->get_items(); foreach ($items as $item) { $item->hideicon = true; $breadcrumbs[] = $this->render($item); } $divider = '<span class="divider">/</span>'; $list_items = '<li>'.join(" $divider</li><li>", $breadcrumbs).'</li>'; $title = '<span class="accesshide">'.get_string('pagepath').'</span>'; return $title . "<ul class=\"breadcrumb\">$list_items</ul>"; } /* * Overriding the custom_menu function ensures the custom menu is * always shown, even if no menu items are configured in the global * theme settings page. * We use the sitename as the first menu item. */ public function custom_menu($custommenuitems = '') { global $CFG; if (!empty($CFG->custommenuitems)) { $custommenuitems .= $CFG->custommenuitems; } $custommenu = new custom_menu($custommenuitems, current_language()); return $this->render_custom_menu($custommenu); } /* * This renders the bootstrap top menu. * * This renderer is needed to enable the Bootstrap style navigation. */ protected function render_custom_menu(custom_menu $menu) { // If the menu has no children return an empty string. if (!$menu->has_children()) { return ''; } $addlangmenu = true; $langs = get_string_manager()->get_list_of_translations(); if ($this->page->course != SITEID and !empty($this->page->course->lang)) { // Do not show lang menu if language forced. $addlangmenu = false; } if (count($langs) < 2) { $addlangmenu = false; } if ($addlangmenu) { $language = $menu->add(get_string('language'), new moodle_url('#'), get_string('language'), 10000); foreach ($langs as $langtype => $langname) { $language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname); } } $content = '<ul class="nav">'; foreach ($menu->get_children() as $item) { $content .= $this->render_custom_menu_item($item, 1); } return $content.'</ul>'; } /* * This code renders the custom menu items for the * bootstrap dropdown menu. */ protected function render_custom_menu_item(custom_menu_item $menunode, $level = 0 ) { static $submenucount = 0; if ($menunode->has_children()) { if ($level == 1) { $dropdowntype = 'dropdown'; } else { $dropdowntype = 'dropdown-submenu'; } $content = html_writer::start_tag('li', array('class'=>$dropdowntype)); // If the child has menus render it as a sub menu. $submenucount++; if ($menunode->get_url() !== null) { $url = $menunode->get_url(); } else { $url = '#cm_submenu_'.$submenucount; } $content .= html_writer::start_tag('a', array('href'=>$url, 'class'=>'dropdown-toggle', 'data-toggle'=>'dropdown')); $content .= $menunode->get_title(); if ($level == 1) { $content .= '<b class="caret"></b>'; } $content .= '</a>'; $content .= '<ul class="dropdown-menu">'; foreach ($menunode->get_children() as $menunode) { $content .= $this->render_custom_menu_item($menunode, 0); } $content .= '</ul>'; } else { $content = '<li>'; // The node doesn't have children so produce a final menuitem. if ($menunode->get_url() !== null) { $url = $menunode->get_url(); } else { $url = '#'; } $content .= html_writer::link($url, $menunode->get_text(), array('title'=>$menunode->get_title())); } return $content; } }
avasys/moodle
theme/bootstrapbase/renderers/core.php
PHP
gpl-3.0
5,831
package org.schabi.newpipe.player.helper; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.content.Context; import android.content.Intent; import android.media.AudioFocusRequest; import android.media.AudioManager; import android.media.audiofx.AudioEffect; import android.os.Build; import android.util.Log; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.analytics.AnalyticsListener; public class AudioReactor implements AudioManager.OnAudioFocusChangeListener, AnalyticsListener { private static final String TAG = "AudioFocusReactor"; private static final boolean SHOULD_BUILD_FOCUS_REQUEST = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O; private static final int DUCK_DURATION = 1500; private static final float DUCK_AUDIO_TO = .2f; private static final int FOCUS_GAIN_TYPE = AudioManager.AUDIOFOCUS_GAIN; private static final int STREAM_TYPE = AudioManager.STREAM_MUSIC; private final SimpleExoPlayer player; private final Context context; private final AudioManager audioManager; private final AudioFocusRequest request; public AudioReactor(@NonNull final Context context, @NonNull final SimpleExoPlayer player) { this.player = player; this.context = context; this.audioManager = ContextCompat.getSystemService(context, AudioManager.class); player.addAnalyticsListener(this); if (SHOULD_BUILD_FOCUS_REQUEST) { request = new AudioFocusRequest.Builder(FOCUS_GAIN_TYPE) .setAcceptsDelayedFocusGain(true) .setWillPauseWhenDucked(true) .setOnAudioFocusChangeListener(this) .build(); } else { request = null; } } public void dispose() { abandonAudioFocus(); player.removeAnalyticsListener(this); } /*////////////////////////////////////////////////////////////////////////// // Audio Manager //////////////////////////////////////////////////////////////////////////*/ public void requestAudioFocus() { if (SHOULD_BUILD_FOCUS_REQUEST) { audioManager.requestAudioFocus(request); } else { audioManager.requestAudioFocus(this, STREAM_TYPE, FOCUS_GAIN_TYPE); } } public void abandonAudioFocus() { if (SHOULD_BUILD_FOCUS_REQUEST) { audioManager.abandonAudioFocusRequest(request); } else { audioManager.abandonAudioFocus(this); } } public int getVolume() { return audioManager.getStreamVolume(STREAM_TYPE); } public void setVolume(final int volume) { audioManager.setStreamVolume(STREAM_TYPE, volume, 0); } public int getMaxVolume() { return audioManager.getStreamMaxVolume(STREAM_TYPE); } /*////////////////////////////////////////////////////////////////////////// // AudioFocus //////////////////////////////////////////////////////////////////////////*/ @Override public void onAudioFocusChange(final int focusChange) { Log.d(TAG, "onAudioFocusChange() called with: focusChange = [" + focusChange + "]"); switch (focusChange) { case AudioManager.AUDIOFOCUS_GAIN: onAudioFocusGain(); break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: onAudioFocusLossCanDuck(); break; case AudioManager.AUDIOFOCUS_LOSS: case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: onAudioFocusLoss(); break; } } private void onAudioFocusGain() { Log.d(TAG, "onAudioFocusGain() called"); player.setVolume(DUCK_AUDIO_TO); animateAudio(DUCK_AUDIO_TO, 1.0f); if (PlayerHelper.isResumeAfterAudioFocusGain(context)) { player.setPlayWhenReady(true); } } private void onAudioFocusLoss() { Log.d(TAG, "onAudioFocusLoss() called"); player.setPlayWhenReady(false); } private void onAudioFocusLossCanDuck() { Log.d(TAG, "onAudioFocusLossCanDuck() called"); // Set the volume to 1/10 on ducking player.setVolume(DUCK_AUDIO_TO); } private void animateAudio(final float from, final float to) { final ValueAnimator valueAnimator = new ValueAnimator(); valueAnimator.setFloatValues(from, to); valueAnimator.setDuration(AudioReactor.DUCK_DURATION); valueAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(final Animator animation) { player.setVolume(from); } @Override public void onAnimationCancel(final Animator animation) { player.setVolume(to); } @Override public void onAnimationEnd(final Animator animation) { player.setVolume(to); } }); valueAnimator.addUpdateListener(animation -> player.setVolume(((float) animation.getAnimatedValue()))); valueAnimator.start(); } /*////////////////////////////////////////////////////////////////////////// // Audio Processing //////////////////////////////////////////////////////////////////////////*/ @Override public void onAudioSessionId(final EventTime eventTime, final int audioSessionId) { if (!PlayerHelper.isUsingDSP()) { return; } final Intent intent = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION); intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId); intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.getPackageName()); context.sendBroadcast(intent); } }
theScrabi/NewPipe
app/src/main/java/org/schabi/newpipe/player/helper/AudioReactor.java
Java
gpl-3.0
6,060
/* src/c-interface-ncs.cc * * Copyright 2004, 2005 The University of York * Copyright 2007, 2008 The University of Oxford * Author: Paul Emsley * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA */ #ifdef USE_PYTHON #include "Python.h" // before system includes to stop "POSIX_C_SOURCE" redefined problems #endif #include "compat/coot-sysdep.h" #include <stdlib.h> #include <iostream> #if defined _MSC_VER #include <windows.h> #endif #include "globjects.h" //includes gtk/gtk.h #include "callbacks.h" #include "interface.h" // now that we are moving callback // functionality to the file, we need this // header since some of the callbacks call // functions are built by glade. #include <vector> #include <string> #include <algorithm> #include <mmdb2/mmdb_manager.h> #include "coords/mmdb-extras.h" #include "coords/mmdb.h" #include "coords/mmdb-crystal.h" #include "graphics-info.h" #include "c-interface.h" #include "c-interface-gtk-widgets.h" #include "cc-interface.hh" #include "guile-fixups.h" // Including python needs to come after graphics-info.h, because // something in Python.h (2.4 - chihiro) is redefining FF1 (in // ssm_superpose.h) to be 0x00004000 (Grrr). // // 20100813: Python.h needs to come before to stop"_POSIX_C_SOURCE" redefined problems // // #ifdef USE_PYTHON // #include "Python.h" // #endif // USE_PYTHON int add_strict_ncs_matrix(int imol, const char *this_chain_id, const char *target_chain_id, float m11, float m12, float m13, float m21, float m22, float m23, float m31, float m32, float m33, float t1, float t2, float t3) { int istat = 0; if (is_valid_model_molecule(imol)) { clipper::Mat33<double> m(m11, m12, m13, m21, m22, m23, m31, m32, m33); clipper::Coord_orth c(t1, t2, t3); clipper::RTop_orth rtop(m, c); coot::coot_mat44 cm44; // The orientation is a guess: FIXME or testme. cm44.m[0].v4[0] = m11; cm44.m[0].v4[1] = m12; cm44.m[0].v4[2] = m13; cm44.m[1].v4[0] = m21; cm44.m[1].v4[1] = m22; cm44.m[1].v4[2] = m23; cm44.m[2].v4[0] = m31; cm44.m[2].v4[1] = m32; cm44.m[2].v4[2] = m33; // translation cm44.m[0].v4[3] = t1; cm44.m[1].v4[3] = t2; cm44.m[2].v4[3] = t3; // sensibles cm44.m[3].v4[0] = 0.0; cm44.m[3].v4[1] = 0.0; cm44.m[3].v4[2] = 0.0; cm44.m[3].v4[3] = 1.0; istat = 1; std::string tch = target_chain_id; std::string chain_id = this_chain_id; graphics_info_t::molecules[imol].add_strict_ncs_matrix(chain_id, tch, cm44); graphics_draw(); } return istat; } int add_strict_ncs_from_mtrix_from_self_file(int imol) { int istat = 0; if (is_valid_model_molecule(imol)) { graphics_info_t g; g.molecules[imol].add_strict_ncs_from_mtrix_from_self_file(); } return istat; } GtkWidget *wrapped_create_ncs_maps_dialog() { GtkWidget *dialog = create_ncs_maps_dialog(); short int diff_maps_only_flag = 0; int ifound; // Maps: ifound = fill_ligands_dialog_map_bits_by_dialog_name(dialog, "ncs_maps_maps", diff_maps_only_flag); if (ifound == 0) { std::cout << "Error: you must have a difference map to analyse!" << std::endl; GtkWidget *none_frame = lookup_widget(dialog, "no_maps_frame"); gtk_widget_show(none_frame); } // Models: short int have_ncs_flag = 1; ifound = fill_vbox_with_coords_options_by_dialog_name(dialog, "ncs_maps_models", have_ncs_flag); if (ifound == 0) { std::cout << "You must have molecules with NCS to use this function\n"; GtkWidget *none_frame = lookup_widget(dialog, "no_models_frame"); gtk_widget_show(none_frame); } return dialog; } void add_ncs_matrix(int imol, const char *chain_id, const char *target_chain_id, float m11, float m12, float m13, float m21, float m22, float m23, float m31, float m32, float m33, float t1, float t2, float t3) { if (is_valid_model_molecule(imol)) { clipper::Mat33<double> m(m11, m12, m13, m21, m22, m23, m31, m32, m33); clipper::Coord_orth c(t1, t2, t3); clipper::RTop_orth rtop(m, c); // std::cout << "DEBUG:: add_ncs_matrix for imol " << imol << " chain_id " << chain_id // << " target_chain_id " << target_chain_id << std::endl; graphics_info_t::molecules[imol].add_ncs_ghost(chain_id, target_chain_id, rtop); graphics_draw(); } } void clear_ncs_ghost_matrices(int imol) { if (is_valid_model_molecule(imol)) { graphics_info_t::molecules[imol].clear_ncs_ghost_matrices(); } } int show_strict_ncs_state(int imol) { if (is_valid_model_molecule(imol)) { return graphics_info_t::molecules[imol].show_strict_ncs_flag; } return 0; } void set_show_strict_ncs(int imol, int state) { short int istate = 0; if (is_valid_model_molecule(imol)) { graphics_info_t::molecules[imol].show_strict_ncs_flag = state; istate = 1; graphics_draw(); } } /* At what level of homology should we say that we can't see homology for NCS calculation? (default 0.8) */ void set_ncs_homology_level(float flev) { graphics_info_t::ncs_homology_level = flev; } /* ----------------------------------------------------------------------- */ /* NCS */ /* ----------------------------------------------------------------------- */ /* section NCS */ void set_draw_ncs_ghosts(int imol, int istate) { if (is_valid_model_molecule(imol)) { graphics_info_t::molecules[imol].set_show_ghosts(istate); graphics_draw(); } } /*! \brief return the drawing state of NCS ghosts for molecule number imol */ int draw_ncs_ghosts_state(int imol) { int r = -1; if (is_valid_model_molecule(imol)) { r = graphics_info_t::molecules[imol].draw_ncs_ghosts_p(); } return r; } void set_ncs_ghost_bond_thickness(int imol, float f) { if (is_valid_model_molecule(imol)) { graphics_info_t::molecules[imol].set_ghost_bond_thickness(f); graphics_draw(); } } void ncs_update_ghosts(int imol) { if (is_valid_model_molecule(imol)) { int incs = graphics_info_t::molecules[imol].update_ncs_ghosts(); if (incs) graphics_draw(); } } GtkWidget *wrapped_create_ncs_control_dialog() { GtkWidget *w = create_ncs_control_dialog(); for (int imol=0; imol<graphics_info_t::n_molecules(); imol++) if (is_valid_model_molecule(imol)) graphics_info_t::molecules[imol].fill_ncs_control_frame(w); return w; } void ncs_control_change_ncs_master_to_chain(int imol, int ichain) { std::cout << "DEBUG:: ncs_control_change_ncs_master_to_chain imol: " << imol << " and ichain: " << ichain << std::endl; if (is_valid_model_molecule(imol)) { std::vector<std::string> chain_ids = coot::util::chains_in_molecule(graphics_info_t::molecules[imol].atom_sel.mol); if (ichain < int(chain_ids.size())) graphics_info_t::molecules[imol].set_ncs_master_chain(chain_ids[ichain], graphics_info_t::ncs_homology_level); graphics_draw(); } } void ncs_control_change_ncs_master_to_chain_id(int imol, const char *chain_id) { std::cout << "DEBUG ncs_control_change_ncs_master_to_chain_id imol: " << imol << " and chain_id: " << chain_id << std::endl; if (is_valid_model_molecule(imol)) { std::vector<std::string> chain_ids = coot::util::chains_in_molecule(graphics_info_t::molecules[imol].atom_sel.mol); std::vector<std::string>::iterator match = find(chain_ids.begin(), chain_ids.end(), chain_id); if (match != chain_ids.end()) graphics_info_t::molecules[imol].set_ncs_master_chain(chain_id, graphics_info_t::ncs_homology_level); graphics_draw(); } } void ncs_control_change_ncs_master_to_chain_update_widget(GtkWidget *w, int imol, int ichain) { std::cout << "DEBUG ncs_control_change_ncs_master_to_chain_update_widget imol: " << imol << " and ichain: " << ichain << std::endl; if (is_valid_model_molecule(imol)) { ncs_control_change_ncs_master_to_chain(imol, ichain); // Now we want to update the widget. We need to change the sensitivity of // all the Chain check boxes in the dispaly ncs chain vbox. // // We need to change to desensitve the chain that matches ichain. // // This is a -widget-work function graphics_info_t::molecules[imol].ncs_control_change_ncs_master_to_chain_update_widget(w, ichain); } } void ncs_control_display_chain(int imol, int ichain, int state) { std::cout << "%%%% ncs_control_display_chain " << std::endl; if (is_valid_model_molecule(imol)) { graphics_info_t::molecules[imol].set_display_ncs_ghost_chain(ichain, state); graphics_draw(); } } // The NCS "Yes" was pressed, do we need to make the rtops for this // molecule? We do if there ncs_ghosts.size() > 0. // // If ncs_ghosts.size() == 0, then this widget should not be active. // // void make_ncs_ghosts_maybe(int imol) { // c.f. fill_bond_parameters_internals() // int imol = graphics_info_t::bond_parameters_molecule; old way. broken. if (is_valid_model_molecule(imol)) { // it should be! if (graphics_info_t::molecules[imol].has_ncs_p()) { if (graphics_info_t::molecules[imol].ncs_ghosts_have_rtops_p() == 0) { std::cout << "%%%%%%%%% calling fill_ghost_info() from c-interface.cc make_ncs_ghosts_maybe()" << std::endl; graphics_info_t::molecules[imol].fill_ghost_info(1, graphics_info_t::ncs_homology_level); } } } } // int make_dynamically_transformed_ncs_maps(int imol_model, int imol_map, int overwrite_maps_of_same_name_flag) { int nmaps=0; if (is_valid_model_molecule(imol_model)) { if (is_valid_map_molecule(imol_map)) { float homology_lev = graphics_info_t::ncs_homology_level; graphics_info_t g; if (g.molecules[imol_model].has_ncs_p() > 0) { if (g.molecules[imol_model].ncs_ghosts_have_rtops_p() == 0) { // fill the rtops and set the flag g.molecules[imol_model].fill_ghost_info(1, homology_lev); } } std::vector<coot::ghost_molecule_display_t> local_ncs_ghosts = g.molecules[imol_model].NCS_ghosts(); for (unsigned int ighost=0; ighost<local_ncs_ghosts.size(); ighost++) { int imol = -1;// gets reset std::string ncs_map_name = "Map "; ncs_map_name += coot::util::int_to_string(imol_map); ncs_map_name += " "; ncs_map_name += local_ncs_ghosts[ighost].name; if (overwrite_maps_of_same_name_flag) { int imap_ghost_existing = g.lookup_molecule_name(ncs_map_name); if (is_valid_map_molecule(imap_ghost_existing)) { imol = imap_ghost_existing; } else { imol = graphics_info_t::create_molecule(); } } else { imol = graphics_info_t::create_molecule(); } g.molecules[imol].install_ghost_map(g.molecules[imol_map].xmap, ncs_map_name, // was local_ncs_ghosts[ighost].name? local_ncs_ghosts[ighost], g.molecules[imol_map].is_difference_map_p(), g.swap_difference_map_colours, g.molecules[imol_map].map_sigma()); nmaps++; } if (graphics_info_t::ncs_maps_do_average_flag) { std:: string imol_map_name = coot::util::int_to_string(imol_map); std::vector<std::pair<clipper::Xmap<float>, std::string> > xmaps = g.molecules[imol_model].ncs_averaged_maps(g.molecules[imol_map].xmap, homology_lev, imol_map_name); std::cout << "INFO:: made " << xmaps.size() << " averaged map(s)" << std::endl; for (unsigned int i=0; i<xmaps.size(); i++) { std::string name; name += xmaps[i].second; int imol = -1;// gets reset int imap_ghost_existing = g.lookup_molecule_name(name); if (overwrite_maps_of_same_name_flag) { if (is_valid_map_molecule(imap_ghost_existing)) { imol = imap_ghost_existing; } else { imol = graphics_info_t::create_molecule(); } } else { imol = graphics_info_t::create_molecule(); } g.molecules[imol].new_map(xmaps[i].first, name); if (g.molecules[imol_map].is_difference_map_p()) g.molecules[imol].set_map_is_difference_map(); nmaps++; } } } else { std::cout << "WARNING:: molecule number " << imol_map << " is not a valid map molecule\n"; } } else { std::cout << "WARNING:: molecule number " << imol_model << " is not a valid model molecule\n"; } if (nmaps > 0) graphics_draw(); return nmaps; } // Also this should go elsewhere // int make_dynamically_transformed_ncs_maps_by_widget(GtkWidget *dialog) { // Decode the options and call the above function: int imol_map = -1; int imol_coords = -1; GtkWidget *map_button; short int found_active_button_for_map = 0; for (int imol=0; imol<graphics_info_t::n_molecules(); imol++) { if (graphics_info_t::molecules[imol].has_xmap()) { std::string map_str = "ncs_maps_maps_radiobutton_"; map_str += graphics_info_t::int_to_string(imol); map_button = lookup_widget(dialog, map_str.c_str()); if (map_button) { if (GTK_TOGGLE_BUTTON(map_button)->active) { imol_map = imol; found_active_button_for_map = 1; break; } } else { std::cout << "WARNING:: (error) " << map_str << " map button not found in " << "make_dynamically_transformed_ncs_maps_by_widget" << std::endl; } } } GtkWidget *coords_button; short int found_active_button_for_coords = 0; for (int imol=0; imol<graphics_info_t::n_molecules(); imol++) { if (graphics_info_t::molecules[imol].has_model()) { if (graphics_info_t::molecules[imol].has_ncs_p()) { std::string coords_str = "ncs_maps_models_radiobutton_"; coords_str += graphics_info_t::int_to_string(imol); coords_button = lookup_widget(dialog, coords_str.c_str()); if (coords_button) { if (GTK_TOGGLE_BUTTON(coords_button)->active) { imol_coords = imol; found_active_button_for_coords = 1; } } else { std::cout << "WARNING:: (error) " << coords_str << " coords button not found in " << "make_dynamically_transformed_ncs_maps_by_widget" << std::endl; } } } } // Use a button to get this value at some stage. int overwrite_maps_of_same_name_flag = 0; if (!found_active_button_for_coords) { std::cout << "You need to define a set of coordinates for NCS maping\n"; } else { if (!found_active_button_for_map) { std::cout << "You need to define a map for NCS maping\n"; } else { make_dynamically_transformed_ncs_maps(imol_coords, imol_map, overwrite_maps_of_same_name_flag); } } return 0; } // Should be in c-interface-em.cc, perhaps? int scale_cell(int imol_map, float fac_u, float fac_v, float fac_w) { int retval = 0; if (is_valid_map_molecule(imol_map)) { retval = graphics_info_t::molecules[imol_map].scale_cell(fac_u, fac_v, fac_w); graphics_draw(); } return retval; } #ifdef USE_GUILE SCM ncs_chain_differences_scm(int imol, const char *master_chain_id) { float mc_weight = 1.0; SCM r = SCM_BOOL_F; if (is_valid_model_molecule(imol)) { coot::ncs_differences_t diffs = graphics_info_t::molecules[imol].ncs_chain_differences(master_chain_id, mc_weight); if (diffs.size() == 0) { std::cout << "no diffs" << std::endl; } else { r = SCM_EOL; for (int idiff=int(diffs.size()-1); idiff>=0; idiff--) { SCM l_residue_data = SCM_EOL; coot::ncs_chain_difference_t cd = diffs.diffs[idiff]; if (cd.residue_info.size() > 0) { std::cout << "NCS target chain has " << cd.residue_info.size() << " peers." << std::endl; // for (int iresinf=0; iresinf<cd.residue_info.size(); iresinf++) { for (int iresinf=(int(cd.residue_info.size())-1); iresinf>=0; iresinf--) { if (0) std::cout << "resinfo: " << cd.residue_info[iresinf].resno << " " << cd.residue_info[iresinf].inscode << " " << cd.residue_info[iresinf].serial_number << " to " << cd.residue_info[iresinf].target_resno << " " << cd.residue_info[iresinf].target_inscode << " " << cd.residue_info[iresinf].target_serial_number << " diff: " << cd.residue_info[iresinf].mean_diff << std::endl; coot::residue_spec_t this_res(cd.peer_chain_id, cd.residue_info[iresinf].resno, cd.residue_info[iresinf].inscode); coot::residue_spec_t target_res(diffs.target_chain_id, cd.residue_info[iresinf].target_resno, cd.residue_info[iresinf].target_inscode); SCM res_l = SCM_EOL; res_l = scm_cons(scm_double2num(cd.residue_info[iresinf].mean_diff), res_l); // res_l = scm_cons(scm_cdr(scm_residue(target_res)), res_l); // res_l = scm_cons(scm_cdr(scm_residue(this_res)), res_l); l_residue_data = scm_cons(res_l, l_residue_data); } r = scm_cons(l_residue_data, SCM_EOL); r = scm_cons(scm_makfrom0str(diffs.target_chain_id.c_str()), r); r = scm_cons(scm_makfrom0str(cd.peer_chain_id.c_str()), r); } } } } return r; } #endif /* USE_GUILE */ #ifdef USE_PYTHON PyObject *ncs_chain_differences_py(int imol, const char *master_chain_id) { PyObject *r = Py_False; if (is_valid_model_molecule(imol)) { coot::ncs_differences_t diffs = graphics_info_t::molecules[imol].ncs_chain_differences(master_chain_id, 1.0); if (diffs.size() == 0) { std::cout << "no diffs" << std::endl; } else { r = PyList_New(0); for (unsigned int idiff=0; idiff<diffs.size(); idiff++) { PyObject *l_residue_data = PyList_New(0); coot::ncs_chain_difference_t cd = diffs.diffs[idiff]; if (cd.residue_info.size() > 0) { std::cout << "NCS target chain has " << cd.residue_info.size() << " peers." << std::endl; // for (int iresinf=0; iresinf<cd.residue_info.size(); iresinf++) { for (unsigned int iresinf=0; iresinf<cd.residue_info.size(); iresinf++) { if (0) std::cout << "resinfo: " << cd.residue_info[iresinf].resno << " " << cd.residue_info[iresinf].inscode << " " << cd.residue_info[iresinf].serial_number << " to " << cd.residue_info[iresinf].target_resno << " " << cd.residue_info[iresinf].target_inscode << " " << cd.residue_info[iresinf].target_serial_number << " diff: " << cd.residue_info[iresinf].mean_diff << std::endl; coot::residue_spec_t this_res(cd.peer_chain_id, cd.residue_info[iresinf].resno, cd.residue_info[iresinf].inscode); coot::residue_spec_t target_res(diffs.target_chain_id, cd.residue_info[iresinf].target_resno, cd.residue_info[iresinf].target_inscode); // according to Paul's documentation we should have resno and inscode // for both residues here too PyObject *thisr = PyList_GetSlice(py_residue(this_res), 2, 4); PyObject *masta = PyList_GetSlice(py_residue(target_res), 2, 4); // res_l list seems only to have one element in Paul's scm code // currently?! Correct?! PyObject *res_l = PyList_New(3); PyList_SetItem(res_l, 0, thisr); PyList_SetItem(res_l, 1, masta); PyList_SetItem(res_l, 2, PyFloat_FromDouble(cd.residue_info[iresinf].mean_diff)); PyList_Append(l_residue_data, res_l); Py_XDECREF(res_l); } PyList_Append(r, PyString_FromString(cd.peer_chain_id.c_str())); PyList_Append(r, PyString_FromString(diffs.target_chain_id.c_str())); PyList_Append(r, l_residue_data); Py_XDECREF(l_residue_data); } } } } if (PyBool_Check(r)) { Py_INCREF(r); } return r; } #endif /* USE_PYTHON */ #ifdef USE_GUILE SCM ncs_chain_ids_scm(int imol) { SCM r = SCM_BOOL_F; if (is_valid_model_molecule(imol)) { if (graphics_info_t::molecules[imol].has_ncs_p()) { std::vector<std::vector<std::string> > ncs_ghost_chains = graphics_info_t::molecules[imol].ncs_ghost_chains(); // std::cout << "There are " << ncs_ghost_chains.size() << " ncs ghost chains" // << std::endl; if (ncs_ghost_chains.size() > 0) { r = SCM_EOL; for (int i=(int(ncs_ghost_chains.size())-1); i>=0; i--) { SCM string_list_scm = generic_string_vector_to_list_internal(ncs_ghost_chains[i]); r = scm_cons(string_list_scm, r); } } } } return r; } #endif /* USE_GUILE */ #ifdef USE_PYTHON PyObject *ncs_chain_ids_py(int imol) { PyObject *r = Py_False; if (is_valid_model_molecule(imol)) { if (graphics_info_t::molecules[imol].has_ncs_p()) { std::vector<std::vector<std::string> > ncs_ghost_chains = graphics_info_t::molecules[imol].ncs_ghost_chains(); // std::cout << "There are " << ncs_ghost_chains.size() << " ncs ghost chains" // << std::endl; if (ncs_ghost_chains.size() > 0) { r = PyList_New(ncs_ghost_chains.size()); for (unsigned int i=0; i<ncs_ghost_chains.size(); i++) { PyObject *string_list_py = generic_string_vector_to_list_internal_py(ncs_ghost_chains[i]); PyList_SetItem(r, i, string_list_py); } } } } if (PyBool_Check(r)) { Py_INCREF(r); } return r; } #endif /* USE_PYTHON */ #ifdef USE_GUILE /* return #f on bad imol or a list of ghosts on good imol. Can include NCS rtops if they are available, else the rtops are #f */ SCM ncs_ghosts_scm(int imol) { SCM r = SCM_BOOL_F; if (!is_valid_model_molecule(imol)) { std::cout << "WARNING:: molecule number " << imol << " is not valid" << std::endl; } else { r = SCM_EOL; std::vector<coot::ghost_molecule_display_t> ncs_ghosts = graphics_info_t::molecules[imol].NCS_ghosts(); for (unsigned int ighost=0; ighost<ncs_ghosts.size(); ighost++) { SCM ghost_scm = SCM_EOL; SCM display_it_flag_scm = SCM_BOOL_F; if (ncs_ghosts[ighost].display_it_flag) display_it_flag_scm = SCM_BOOL_T; SCM rtop_scm = SCM_BOOL_F; if (graphics_info_t::molecules[imol].ncs_ghosts_have_rtops_p()) rtop_scm = rtop_to_scm(ncs_ghosts[ighost].rtop); SCM target_chain_id_scm = scm_makfrom0str(ncs_ghosts[ighost].target_chain_id.c_str()); SCM chain_id_scm = scm_makfrom0str(ncs_ghosts[ighost].chain_id.c_str()); SCM name_scm = scm_makfrom0str(ncs_ghosts[ighost].name.c_str()); ghost_scm = scm_cons(display_it_flag_scm, ghost_scm); ghost_scm = scm_cons(rtop_scm, ghost_scm); ghost_scm = scm_cons(target_chain_id_scm, ghost_scm); ghost_scm = scm_cons(chain_id_scm, ghost_scm); ghost_scm = scm_cons(name_scm, ghost_scm); r = scm_cons(ghost_scm, r); } r = scm_reverse(r); } return r; } #endif /* USE_GUILE */ #ifdef USE_PYTHON /* return False on bad imol or a list of ghosts on good imol. Can include NCS rtops if they are available, else the rtops are False */ PyObject *ncs_ghosts_py(int imol) { PyObject *r = Py_False; if (!is_valid_model_molecule(imol)) { std::cout << "WARNING:: molecule number " << imol << " is not valid" << std::endl; } else { r = PyList_New(0); std::vector<coot::ghost_molecule_display_t> ncs_ghosts = graphics_info_t::molecules[imol].NCS_ghosts(); for (unsigned int ighost=0; ighost<ncs_ghosts.size(); ighost++) { PyObject *ghost_py = PyList_New(5); PyObject *display_it_flag_py = Py_False; if (ncs_ghosts[ighost].display_it_flag) display_it_flag_py = Py_True; PyObject *rtop_py = Py_False; if (graphics_info_t::molecules[imol].ncs_ghosts_have_rtops_p()) { rtop_py = rtop_to_python(ncs_ghosts[ighost].rtop); } PyObject *target_chain_id_py = PyString_FromString(ncs_ghosts[ighost].target_chain_id.c_str()); PyObject *chain_id_py = PyString_FromString(ncs_ghosts[ighost].chain_id.c_str()); PyObject *name_py = PyString_FromString(ncs_ghosts[ighost].name.c_str()); PyList_SetItem(ghost_py, 0, name_py); PyList_SetItem(ghost_py, 1, chain_id_py); PyList_SetItem(ghost_py, 2, target_chain_id_py); PyList_SetItem(ghost_py, 3, rtop_py); PyList_SetItem(ghost_py, 4, display_it_flag_py); PyList_Append(r, ghost_py); Py_XDECREF(ghost_py); } } if (PyBool_Check(r)) { Py_INCREF(r); } return r; } #endif /* USE_PYTHON */ // This should be in c-interface-ncs-gui.cc void validation_graph_ncs_diffs_mol_selector_activate (GtkMenuItem *menuitem, gpointer user_data) { int imol = GPOINTER_TO_INT(user_data); #if defined(HAVE_GTK_CANVAS) || defined(HAVE_GNOME_CANVAS) #ifdef HAVE_GSL graphics_info_t g; g.ncs_diffs_from_mol(imol); #else printf("not compiled with GSL - remake\n"); #endif /* HAVE_GSL */ #else printf("not compiled with HAVE_GTK_CANVAS/GNOME_CANVAS - remake\n"); #endif /* HAVE_GTK_CANVAS */ } void set_ncs_matrix_type(int flag) { graphics_info_t g; if (flag == coot::NCS_SSM) { #ifdef HAVE_SSMLIB g.ncs_matrix_flag = coot::NCS_SSM; #else std::cout<< "WARNING:: not compiled with SSM, so will use LSQ for NCS matrix determination" <<std::endl; g.ncs_matrix_flag = coot::NCS_LSQ; #endif // HAVE_SSMLIB } else { if (flag == coot::NCS_LSQ2) { g.ncs_matrix_flag = coot::NCS_LSQ2; } else { g.ncs_matrix_flag = coot::NCS_LSQ; } } } int get_ncs_matrix_state() { graphics_info_t g; return g.ncs_matrix_flag; } /*! \brief Given that we are in chain current_chain, apply the NCS operator that maps current_chain on to next_ncs_chain, so that the relative view is preserved. For NCS skipping. */ void apply_ncs_to_view_orientation(int imol, const char *current_chain, const char *next_ncs_chain) { if (is_valid_model_molecule(imol)) { short int forward_flag = 1; // emulate previous behaviour. Not // sure that this is what is needed. coot::util::quaternion q(graphics_info_t::quat[0], graphics_info_t::quat[1], graphics_info_t::quat[2], graphics_info_t::quat[3]); clipper::Mat33<double> current_view_mat = q.matrix(); clipper::Coord_orth current_centre(graphics_info_t::RotationCentre_x(), graphics_info_t::RotationCentre_y(), graphics_info_t::RotationCentre_z()); std::pair<bool, clipper::RTop_orth> new_ori = graphics_info_t::molecules[imol].apply_ncs_to_view_orientation(current_view_mat, current_centre, current_chain, next_ncs_chain, forward_flag); std::cout << "DEBUG:: NCS view in: \n" << current_view_mat.format() << std::endl; std::cout << "DEBUG:: NCS view out: " << new_ori.first << std::endl; std::cout << "DEBUG:: NCS view out: \n" << new_ori.second.format() << "\n"; if (new_ori.first) { coot::util::quaternion vq(new_ori.second.rot()); graphics_info_t::quat[0] = vq.q0; graphics_info_t::quat[1] = vq.q1; graphics_info_t::quat[2] = vq.q2; graphics_info_t::quat[3] = vq.q3; } graphics_draw(); } } /*! \brief Given that we are in chain current_chain, apply the NCS operator that maps current_chain on to next_ncs_chain, so that the relative view is preserved. For NCS skipping. */ void apply_ncs_to_view_orientation_and_screen_centre(int imol, const char *current_chain, const char *next_ncs_chain, short int forward_flag) { if (is_valid_model_molecule(imol)) { coot::util::quaternion q(graphics_info_t::quat[0], graphics_info_t::quat[1], graphics_info_t::quat[2], graphics_info_t::quat[3]); clipper::Coord_orth current_centre(graphics_info_t::RotationCentre_x(), graphics_info_t::RotationCentre_y(), graphics_info_t::RotationCentre_z()); clipper::Mat33<double> current_view_mat = q.matrix(); std::pair<bool, clipper::RTop_orth> new_ori = graphics_info_t::molecules[imol].apply_ncs_to_view_orientation(current_view_mat, current_centre, current_chain, next_ncs_chain, forward_flag); // std::cout << " NCS view in: \n" << current_view_mat.format() << std::endl; // std::cout << " NCS view out: " << new_ori.first << std::endl; // std::cout << " NCS view out: \n" << new_ori.second.format() << "\n"; if (new_ori.first) { coot::util::quaternion vq(new_ori.second.rot()); graphics_info_t::quat[0] = vq.q0; graphics_info_t::quat[1] = vq.q1; graphics_info_t::quat[2] = vq.q2; graphics_info_t::quat[3] = vq.q3; clipper::Coord_orth new_centre(new_ori.second.trn()); graphics_info_t g; g.setRotationCentre(coot::Cartesian(new_centre.x(), new_centre.y(), new_centre.z())); g.update_things_on_move(); if (graphics_info_t::environment_show_distances) { std::pair<int, int> r = g.get_closest_atom(); // std::cout << "got closest atom " << r.first << " " << r.second << std::endl; if (r.first >= 0) { g.mol_no_for_environment_distances = r.second; g.update_environment_distances_maybe(r.first, r.second); } } } graphics_draw(); } } #include "cc-interface-ncs.hh" std::vector<int> make_ncs_maps(int imol_model, int imol_map) { double border = 2.5; // A: the additional distance between the centre of the atom // and the most-extented atom (so that we capture the // density of the most-extented atom. std::vector<int> new_map_molecule_numbers; int status = -1; if (is_valid_model_molecule(imol_model)) { if (is_valid_map_molecule(imol_map)) { // get_model_ncs_info(): returns ghost info. if (graphics_info_t::molecules[imol_model].ncs_ghosts_have_rtops_p() == 0) { graphics_info_t::molecules[imol_model].fill_ghost_info(1, graphics_info_t::ncs_homology_level); } std::vector<coot::ghost_molecule_display_t> ncs_ghosts = graphics_info_t::molecules[imol_model].NCS_ghosts(); if (! ncs_ghosts.empty()) { // get the middle of and target chain_id for (unsigned int ighst=0; ighst<ncs_ghosts.size(); ighst++) { std::pair<clipper::Coord_orth, double> ccr = graphics_info_t::molecules[imol_model].chain_centre_and_radius(ncs_ghosts[ighst].target_chain_id); const clipper::Coord_orth chain_centre = ccr.first; double ncs_chain_radius = ccr.second + border; // if we are are the // centre of a given // chain_id, how big a // radius do we need // to encompass all // atoms of that chain? clipper::RTop_orth rt = ncs_ghosts[ighst].rtop; std::cout << "rtop for ghost is \n" << rt.format() << std::endl; const clipper::Cell &map_cell = graphics_info_t::molecules[imol_map].xmap.cell(); const clipper::Spacegroup &space_group = graphics_info_t::molecules[imol_map].xmap.spacegroup(); std::string space_group_name = space_group.symbol_xhm(); int imol_new = transform_map_raw(imol_map, rt.rot()(0,0), rt.rot()(0,1), rt.rot()(0,2), rt.rot()(1,0), rt.rot()(1,1), rt.rot()(1,2), rt.rot()(2,0), rt.rot()(2,1), rt.rot()(2,2), rt.trn()[0], rt.trn()[1], rt.trn()[2], chain_centre.x(), chain_centre.y(), chain_centre.z(), ncs_chain_radius, space_group_name.c_str(), map_cell.descr().a(), map_cell.descr().b(), map_cell.descr().c(), clipper::Util::rad2d(map_cell.descr().alpha()), clipper::Util::rad2d(map_cell.descr().beta()), clipper::Util::rad2d(map_cell.descr().gamma())); new_map_molecule_numbers.push_back(imol_new); } } } } return new_map_molecule_numbers; }
jlec/coot
src/c-interface-ncs.cc
C++
gpl-3.0
32,681
package nl.juraji.biliomi.config.core.biliomi; /** * Created by Juraji on 9-10-2017. * Biliomi */ public class USCore { private String updateMode; private boolean checkForUpdates; private String countryCode; public String getUpdateMode() { return updateMode; } public void setUpdateMode(String updateMode) { this.updateMode = updateMode; } public boolean isCheckForUpdates() { return checkForUpdates; } public void setCheckForUpdates(boolean checkForUpdates) { this.checkForUpdates = checkForUpdates; } public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } }
Juraji/Biliomi
core/src/main/java/nl/juraji/biliomi/config/core/biliomi/USCore.java
Java
gpl-3.0
761
using System; using System.Collections.Generic; using System.Text; using WorldWind.Renderable; using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using System.Drawing; namespace AppScene { /// <summary> /// 此示例主要演示如何构造一个mesh网格,以及实现碰撞检测 /// </summary> public class Sphere : RenderableObject { #region 私有变量 private Vector3 m_center;//球体球心(模型坐标) private float m_radius;//球体半径 private short m_slices;//球体在水平方向的分块数目 private short m_stacks;//球体在竖直方向的分块数目 private CustomVertex.PositionColored[] vertices;//定义球体网格顶点 private short[] indices;//定义球体网格中三角形索引 private Mesh mesh;//球体mesh网格 #endregion /// <summary> /// 构造啊函数 /// </summary> /// <param name="name">名称</param> /// <param name="param">模型参数</param> /// <param name="radius">球体半径</param> /// <param name="slices">球体在水平方向的分块数目</param> /// <param name="stacks">球体在竖直方向的分块数目</param> public Sphere(string name, float radius, short slices, short stacks) : base(name) { this.m_radius = radius; this.m_slices = slices; this.m_stacks = stacks; } #region 构造球体 /// <summary> /// 计算顶点 /// </summary> /// <remarks> /// 球体上任意一点坐标可以通过球形坐标来表示(r半径,theta垂直角,alpha水平角) /// X=r*sin(theta)*cos(alpha); /// Y=r*cos(theta); /// Z=r*sin(theta)*sin(alpha); /// </remarks> private void ComputeVertexs() { vertices = new CustomVertex.PositionColored[(m_stacks + 1) * (m_slices + 1)]; float theta = (float)Math.PI / m_stacks; float alpha = 2 * (float)Math.PI / m_slices; for (int i = 0; i < m_slices + 1; i++) { for (int j = 0; j < m_stacks + 1; j++) { Vector3 pt = new Vector3(); pt.X = m_center.X + m_radius * (float)Math.Sin(i * theta) * (float)Math.Cos(j * alpha); pt.Y = m_center.Y + m_radius * (float)Math.Cos(i * theta); pt.Z = m_center.Z + m_radius * (float)Math.Sin(i * theta) * (float)Math.Sin(j * alpha); vertices[j + i * (m_stacks + 1)].Position = pt; vertices[j + i * (m_stacks + 1)].Color = Color.FromArgb(200, Color.Blue).ToArgb(); } } } /// <summary> /// 计算索引 /// </summary> private void ComputeIndices() { indices = new short[6 * m_stacks * m_slices]; for (short i = 0; i < m_slices; i++) { for (short j = 0; j < m_stacks; j++) { indices[6 * (j + i * m_stacks)] = (short)(j + i * (m_stacks + 1)); indices[6 * (j + i * m_stacks) + 1] = (short)(j + i * (m_stacks + 1) + 1); indices[6 * (j + i * m_stacks) + 2] = (short)(j + (i + 1) * (m_stacks + 1)); indices[6 * (j + i * m_stacks) + 3] = (short)(j + i * (m_stacks + 1) + 1); indices[6 * (j + i * m_stacks) + 4] = (short)(j + (i + 1) * (m_stacks + 1) + 1); indices[6 * (j + i * m_stacks) + 5] = (short)(j + (i + 1) * (m_stacks + 1)); } } } #endregion #region Renderable /// <summary> /// 初始化对象 /// </summary> /// <param name="drawArgs">渲染参数</param> public override void Initialize(DrawArgs drawArgs) { //计算模型位置 //this.ComputePosition(drawArgs, this.m_modelParam); ////计算转换矩阵 //this.ComputeWorldTransform(this.m_modelParam); //球体球心 this.m_center = new Vector3(); m_center.X = 0; m_center.Y = 0; m_center.Z = 0; ComputeVertexs();//计算顶点 ComputeIndices();//计算索引 //构造mesh mesh = new Mesh(indices.Length / 3, vertices.Length, MeshFlags.Managed, CustomVertex.PositionColored.Format, drawArgs.Device); //顶点缓冲 GraphicsStream vs = mesh.LockVertexBuffer(LockFlags.None); vs.Write(vertices); mesh.UnlockVertexBuffer(); vs.Dispose(); //索引缓冲 GraphicsStream ids = mesh.LockIndexBuffer(LockFlags.None); ids.Write(indices); mesh.UnlockIndexBuffer(); ids.Dispose(); this.isInitialized = true; } /// <summary> /// 渲染对象 /// </summary> /// <param name="drawArgs">渲染参数</param> public override void Render(DrawArgs drawArgs) { if (!this.IsOn || !this.isInitialized) return; //获取当前世界变换 Matrix world = drawArgs.Device.GetTransform(TransformType.World); //获取当前顶点格式 VertexFormats format = drawArgs.Device.VertexFormat; //获取当前的Z缓冲方式 int zEnable = drawArgs.Device.GetRenderStateInt32(RenderStates.ZEnable); //获取纹理状态 int colorOper = drawArgs.Device.GetTextureStageStateInt32(0, TextureStageStates.ColorOperation); try { //计算模型的转换矩阵 Matrix m = this.WorldTransform; m = drawArgs.Device.GetTransform(TransformType.World); // m *= Matrix.Translation(this.m_position - drawArgs.WorldCamera.ReferenceCenter); m *= Matrix.Translation(this.m_position); //设置世界矩阵 drawArgs.Device.SetTransform(TransformType.World, m); //获取当前转换矩阵,主要用于选择操作时,顶点的转换 //设置顶点格式 drawArgs.Device.VertexFormat = CustomVertex.PositionColored.Format; //设置Z缓冲 drawArgs.Device.SetRenderState(RenderStates.ZEnable, true); //设置纹理状态,此处未使用纹理 drawArgs.Device.SetTextureStageState(0, TextureStageStates.ColorOperation, (int)TextureOperation.Disable); //绘制mesh网格 mesh.DrawSubset(0); } catch (Exception e) { Utility.Log.Write(e); } finally { drawArgs.Device.SetTransform(TransformType.World, world); drawArgs.Device.VertexFormat = format; drawArgs.Device.SetRenderState(RenderStates.ZEnable, zEnable); drawArgs.Device.SetTextureStageState(0, TextureStageStates.ColorOperation, colorOper); } } /// <summary> /// 更新对象 /// </summary> /// <param name="drawArgs">渲染参数</param> public override void Update(DrawArgs drawArgs) { if (!this.isInitialized) { this.Initialize(drawArgs); } // base.Update(drawArgs); } /// <summary> /// 执行选择操作 /// </summary> /// <param name="X">点选X坐标</param> /// <param name="Y">点选Y坐标</param> /// <param name="drawArgs">渲染参数</param> /// <returns>选择返回True,否则返回False</returns> public bool PerformSelectionAction(int X, int Y, DrawArgs drawArgs) { if (!this.isInitialized) return false; Vector3 v1 = new Vector3(); v1.X = X; v1.Y = Y; v1.Z = 0; Vector3 v2 = new Vector3(); v2.X = X; v2.Y = Y; v2.Z = 1; //将屏幕坐标装换为世界坐标,构造一个射线 Vector3 rayPos = drawArgs.WorldCamera.UnProject(v1); Vector3 rayDir = drawArgs.WorldCamera.UnProject(v2) - rayPos; //判断模型是否与射线相交 bool result = this.IntersectWithRay(rayPos, rayDir, drawArgs); //if (result) // drawArgs.Selection.Add(this); return result; } /// <summary> /// 判断模型是否与射线相交 /// </summary> /// <param name="rayPos">射线原点</param> /// <param name="rayDir">射线方向</param> /// <param name="drawArgs">绘制参数</param> /// <returns>如果相交返回True,否则返回False</returns> public bool IntersectWithRay(Vector3 rayPos, Vector3 rayDir, DrawArgs drawArgs) { //if (!this.IsOn || !this.isInitialized || !this.IsSelectable) return false; bool isSelected = false; //try //{ // //选中距离 // float dis; // //构造一条基于模型本体坐标系的射线,用于判断射线是否与模型相交 // Matrix invert = Matrix.Invert(this.WorldTransform.Matrix3d); // Vector3 rayPos1 = Vector3.TransformCoordinate(rayPos, invert); // Vector3 rayPos2 = rayPos + rayDir; // rayPos2 = Vector3.TransformCoordinate(rayPos2, invert); // Vector3 rayDir1 = rayPos2 - rayPos1; // Ray ray1 = new Ray(rayPos1, rayDir1); // isSelected = mesh.Intersects(ray1, out dis); // this.m_selectedMinDistance = dis; //} //catch (Exception caught) //{ // Utility.Log.Write(caught); //} return isSelected; } /// <summary> /// 释放对象 /// </summary> public override void Dispose() { if (this.mesh != null) this.mesh.Dispose(); this.isInitialized = false; //base.Dispose(); } #endregion public Vector3 m_position { get; set; } public Matrix WorldTransform { get; set; } public override bool PerformSelectionAction(DrawArgs drawArgs) { throw new NotImplementedException(); } } }
yhexie/AppScene
AppScene/Renderable/Sphere.cs
C#
gpl-3.0
10,686
package java基础.数值表示; import org.junit.Test; /** * java 语言中只有单目运算符、赋值运算符和三目运算符是从右向左运算的, * 其它运算符都是从左向右运算的。 * @author lv * */ public class 运算符 { public static void main(String[] args) { 移位运算符(); } /** * <<: 左移 * >>: 右移 * >>>: 无符号右移 */ @Test private static void 移位运算符() { int i = 4; System.out.println(i>>1); System.out.println(i>>>1); int j = -4; System.out.println(j>>1); System.out.println(j>>>1); } }
xvusrmqj/algorithms
JavaInterview/src/java基础/数值表示/运算符.java
Java
gpl-3.0
617
<?php /************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014-2022 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko * Website: https://www.espocrm.com * * EspoCRM 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. * * EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "EspoCRM" word. ************************************************************************/ namespace tests\integration\Espo\Export; use Espo\ORM\EntityManager; use Espo\Core\{ FileStorage\Manager as FileStorageManager, Select\SearchParams, Select\Where\Item as WhereItem, }; use Espo\Tools\Export\{ Factory, Params, }; class ExportTest extends \tests\integration\Core\BaseTestCase { /** * @var EntityManager */ private $entityManager; /** * @var Factory */ private $factory; /** * @var FileStorageManager */ private $fileStorageManager; protected function setUp(): void { parent::setUp(); $this->entityManager = $this->getContainer()->get('entityManager'); $this->factory = $this->getContainer() ->get('injectableFactory') ->create(Factory::class); $this->fileStorageManager = $this->getContainer()->get('fileStorageManager'); } public function testCsvWithFieldList(): void { $user =$this->entityManager->createEntity('User', [ 'id' => 'user-id', 'userName' => 'user', 'lastName' => 'User', ]); $this->entityManager->createEntity('Task', [ 'id' => '1', 'name' => 'test-1', 'assignedUserId' => $user->getId(), ]); $this->entityManager->createEntity('Task', [ 'id' => '2', 'name' => 'test-2', 'assignedUserId' => $user->getId(), ]); $this->entityManager->createEntity('Task', [ 'id' => '3', 'name' => 'test-3', ]); $searchParams = SearchParams ::create() ->withWhere(WhereItem::fromRaw([ 'type' => 'equals', 'attribute' => 'assignedUserId', 'value' => $user->getId(), ])); $params = Params ::create('Task') ->withFieldList([ 'name', 'assignedUser', ]) ->withSearchParams($searchParams) ->withFormat('csv'); $export = $this->factory->create(); $attachmentId = $export ->setParams($params) ->run() ->getAttachmentId(); $attachment = $this->entityManager->getEntity('Attachment', $attachmentId); $contents = $this->fileStorageManager->getContents($attachment); $exepectedContents = "name,assignedUserId,assignedUserName\n" . "test-2,user-id,User\n" . "test-1,user-id,User\n"; $this->assertEquals($exepectedContents, $contents); } public function testCsvWithAttributeList(): void { $user = $this->entityManager->createEntity('User', [ 'id' => 'user-id', 'userName' => 'user', 'lastName' => 'User', ]); $this->entityManager->createEntity('Task', [ 'id' => '1', 'name' => 'test-1', 'assignedUserId' => $user->getId(), ]); $this->entityManager->createEntity('Task', [ 'id' => '2', 'name' => 'test-2', 'assignedUserId' => $user->getId(), ]); $params = Params ::create('Task') ->withAttributeList([ 'id', 'name', 'assignedUserId', ]) ->withAccessControl(false) ->withFormat('csv'); $export = $this->factory->create(); $attachmentId = $export ->setParams($params) ->run() ->getAttachmentId(); $attachment = $this->entityManager->getEntity('Attachment', $attachmentId); $contents = $this->fileStorageManager->getContents($attachment); $exepectedContents = "id,name,assignedUserId\n" . "2,test-2,user-id\n" . "1,test-1,user-id\n"; $this->assertEquals($exepectedContents, $contents); } public function testCsvCollection(): void { $user = $this->entityManager->createEntity('User', [ 'id' => 'user-id', 'userName' => 'user', 'lastName' => 'User', ]); $this->entityManager->createEntity('Task', [ 'id' => '1', 'name' => 'test-1', 'assignedUserId' => $user->getId(), ]); $this->entityManager->createEntity('Task', [ 'id' => '2', 'name' => 'test-2', 'assignedUserId' => $user->getId(), ]); $this->entityManager->createEntity('Task', [ 'id' => '3', 'name' => 'test-3', ]); $collection = $this->entityManager ->getRDBRepository('Task') ->where([ 'assignedUserId' => $user->getId(), ]) ->order('id', 'ASC') ->find(); $params = Params ::create('Task') ->withAttributeList([ 'name', 'assignedUserId', ]) ->withFieldList([ 'name', 'assignedUser', ]) ->withFormat('csv'); $export = $this->factory->create(); $attachmentId = $export ->setParams($params) ->setCollection($collection) ->run() ->getAttachmentId(); $attachment = $this->entityManager->getEntity('Attachment', $attachmentId); $contents = $this->fileStorageManager->getContents($attachment); $exepectedContents = "name,assignedUserId\n" . "test-1,user-id\n" . "test-2,user-id\n"; $this->assertEquals($exepectedContents, $contents); } }
espocrm/espocrm
tests/integration/Espo/Export/ExportTest.php
PHP
gpl-3.0
7,120
from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from form_utils.forms import BetterForm import form_utils.fields as bf_fields from tao.widgets import ChoiceFieldWithOtherAttrs, SelectWithOtherAttrs, TwoSidedSelectWidget, SpinnerWidget from tao import datasets from tao.models import DataSetProperty from tao.xml_util import module_xpath, module_xpath_iterate def from_xml_2(cls, ui_holder, xml_root, prefix=None): query = module_xpath(xml_root, '//sql/query') simulation_name = module_xpath(xml_root, '//sql/simulation') galaxy_model_name = module_xpath(xml_root, '//sql/galaxy-model') simulation = datasets.simulation_from_xml(simulation_name) galaxy_model = datasets.galaxy_model_from_xml(galaxy_model_name) data_set = datasets.dataset_find_from_xml(simulation, galaxy_model) output_properties = [dsp for dsp in SQLJobForm._map_elems(xml_root)] if data_set is not None: query = query.replace('-table-', data_set.database) simulation_id = None if simulation is not None: simulation_id = simulation.id galaxy_model_id = None if galaxy_model is not None: galaxy_model_id = galaxy_model.id params = { prefix+'-galaxy_model': galaxy_model_id, prefix+'-dark_matter_simulation': simulation_id, prefix+'-query': query, prefix+'-output_properties': output_properties, } return cls(ui_holder, params, prefix=prefix) class SQLJobForm(BetterForm): SUMMARY_TEMPLATE = 'mock_galaxy_factory/sql_job_summary.html' simple_fields = ['dark_matter_simulation', 'galaxy_model'] fieldsets = [ ('primary', { 'legend': 'Data Selection', 'fields': simple_fields, 'query': '', }),] def __init__(self, *args, **kwargs): self.ui_holder = args[0] super(SQLJobForm, self).__init__(*args[1:], **kwargs) is_int = False #self.fields['query'].widget.attrs['data-bind'] = '' self.fields['query'] = forms.CharField() self.fields['dark_matter_simulation'] = ChoiceFieldWithOtherAttrs(choices=[]) self.fields['galaxy_model'] = ChoiceFieldWithOtherAttrs(choices=[]) self.fields['output_properties'] = bf_fields.forms.MultipleChoiceField(required=False, choices=[], widget=TwoSidedSelectWidget) self.fields['query'].widget.attrs['data-bind'] = 'value: query' self.fields['dark_matter_simulation'].widget.attrs['data-bind'] = 'options: dark_matter_simulations, value: dark_matter_simulation, optionsText: function(i) { return i.fields.name}, event: {change: function() { box_size(dark_matter_simulation().fields.box_size); }}' self.fields['galaxy_model'].widget.attrs['data-bind'] = 'options: galaxy_models, value: galaxy_model, optionsText: function(i) { return i.fields.name }' self.fields['output_properties'].widget.attrs['ko_data'] = {'widget':'output_properties_widget','value':'output_properties'} def clean(self): super(SQLJobForm, self).clean() return self.cleaned_data def to_json_dict(self): """Answer the json dictionary representation of the receiver. i.e. something that can easily be passed to json.dumps()""" json_dict = {} for fn in self.fields.keys(): ffn = self.prefix + '-' + fn val = self.data.get(ffn) if val is not None: json_dict[ffn] = val return json_dict def to_xml(self, parent_xml_element): version = 2.0 to_xml_2(self, parent_xml_element) @classmethod def from_xml(cls, ui_holder, xml_root, prefix=None): version = module_xpath(xml_root, '//workflow/schema-version') if version == '2.0': return from_xml_2(cls, ui_holder, xml_root, prefix=prefix) else: return cls(ui_holder, {}, prefix=prefix) @classmethod def _map_elems(cls, xml_root): for elem in module_xpath_iterate(xml_root, '//votable/fields/item', text=False): label = elem.get('label') units = elem.get('units') name = elem.text yield {'label': label, 'units': units, 'name': name}
IntersectAustralia/asvo-tao
web/tao/sql_job_form.py
Python
gpl-3.0
4,293
/* * Copyright (C) Alibaba Cloud Computing * All rights reserved. * * 版权所有 (C)阿里云计算有限公司 */ using System; using System.Runtime.Serialization; namespace Aliyun.OSS.Transform { [Serializable] internal class ResponseDeserializationException : InvalidOperationException, ISerializable { public ResponseDeserializationException() { } public ResponseDeserializationException(string message) : base(message) { } public ResponseDeserializationException(string message, Exception innerException) : base(message, innerException) { } protected ResponseDeserializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
bojuelu/unity-toolbox
Assets/AliyunSDK/sdk/Transform/ResponseDeserializationException.cs
C#
gpl-3.0
823
/* * WAG.java * * BEAST: Bayesian Evolutionary Analysis by Sampling Trees * Copyright (C) 2014 BEAST Developers * * BEAST 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. * * BEAST 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 BEAST. If not, see <http://www.gnu.org/licenses/>. */ package beast.evomodel.substmodel; import beast.evolution.datatype.AminoAcids; import beast.util.Citation; import beast.util.Citation.Author; import beast.util.Citation.Status; import java.util.Arrays; import java.util.List; /** * WAG model of amino acid evolution (S. Whelan and N. Goldman 2000) * Whelan, S. and N. Goldman. 2000. Bioinformatics ?. * * @version $Id: WAG.java,v 1.3 2005/05/24 20:25:58 rambaut Exp $ * * @author Andrew Rambaut * @author Alexei Drummond */ @Citation(authors = {@Author(initials = "S", surname = "Whelan"), @Author(initials = "N", surname = "Goldman")}, title = "A General Empirical Model of Protein Evolution Derived from Multiple Protein Families Using a Maximum-Likelihood Approach", year = 2001, journal = "Mol Biol Evol", volume = 18, startpage = 691, endpage = 699, status = Status.PUBLISHED) public class WAG extends EmpiricalRateMatrix.AbstractAminoAcid { public static final WAG INSTANCE = new WAG(); // The rates below are specified assuming that the amino acids are in this order: // ARNDCQEGHILKMFPSTWYV // but the AminoAcids dataType wants them in this order: // ACDEFGHIKLMNPQRSTVWY // This is solved by calling the setEmpiricalRates and setEmpiricalFrequencies methods private WAG() { super("WAG"); int n = AminoAcids.INSTANCE.getStateCount(); double[][] rate = new double[n][n]; // Q matrix rate[0][1] = 0.610810; rate[0][2] = 0.569079; rate[0][3] = 0.821500; rate[0][4] = 1.141050; rate[0][5] = 1.011980; rate[0][6] = 1.756410; rate[0][7] = 1.572160; rate[0][8] = 0.354813; rate[0][9] = 0.219023; rate[0][10] = 0.443935; rate[0][11] = 1.005440; rate[0][12] = 0.989475; rate[0][13] = 0.233492; rate[0][14] = 1.594890; rate[0][15] = 3.733380; rate[0][16] = 2.349220; rate[0][17] = 0.125227; rate[0][18] = 0.268987; rate[0][19] = 2.221870; rate[1][2] = 0.711690; rate[1][3] = 0.165074; rate[1][4] = 0.585809; rate[1][5] = 3.360330; rate[1][6] = 0.488649; rate[1][7] = 0.650469; rate[1][8] = 2.362040; rate[1][9] = 0.206722; rate[1][10] = 0.551450; rate[1][11] = 5.925170; rate[1][12] = 0.758446; rate[1][13] = 0.116821; rate[1][14] = 0.753467; rate[1][15] = 1.357640; rate[1][16] = 0.613776; rate[1][17] = 1.294610; rate[1][18] = 0.423612; rate[1][19] = 0.280336; rate[2][3] = 6.013660; rate[2][4] = 0.296524; rate[2][5] = 1.716740; rate[2][6] = 1.056790; rate[2][7] = 1.253910; rate[2][8] = 4.378930; rate[2][9] = 0.615636; rate[2][10] = 0.147156; rate[2][11] = 3.334390; rate[2][12] = 0.224747; rate[2][13] = 0.110793; rate[2][14] = 0.217538; rate[2][15] = 4.394450; rate[2][16] = 2.257930; rate[2][17] = 0.078463; rate[2][18] = 1.208560; rate[2][19] = 0.221176; rate[3][4] = 0.033379; rate[3][5] = 0.691268; rate[3][6] = 6.833400; rate[3][7] = 0.961142; rate[3][8] = 1.032910; rate[3][9] = 0.043523; rate[3][10] = 0.093930; rate[3][11] = 0.533362; rate[3][12] = 0.116813; rate[3][13] = 0.052004; rate[3][14] = 0.472601; rate[3][15] = 1.192810; rate[3][16] = 0.417372; rate[3][17] = 0.146348; rate[3][18] = 0.363243; rate[3][19] = 0.169417; rate[4][5] = 0.109261; rate[4][6] = 0.023920; rate[4][7] = 0.341086; rate[4][8] = 0.275403; rate[4][9] = 0.189890; rate[4][10] = 0.428414; rate[4][11] = 0.083649; rate[4][12] = 0.437393; rate[4][13] = 0.441300; rate[4][14] = 0.122303; rate[4][15] = 1.560590; rate[4][16] = 0.570186; rate[4][17] = 0.795736; rate[4][18] = 0.604634; rate[4][19] = 1.114570; rate[5][6] = 6.048790; rate[5][7] = 0.366510; rate[5][8] = 4.749460; rate[5][9] = 0.131046; rate[5][10] = 0.964886; rate[5][11] = 4.308310; rate[5][12] = 1.705070; rate[5][13] = 0.110744; rate[5][14] = 1.036370; rate[5][15] = 1.141210; rate[5][16] = 0.954144; rate[5][17] = 0.243615; rate[5][18] = 0.252457; rate[5][19] = 0.333890; rate[6][7] = 0.630832; rate[6][8] = 0.635025; rate[6][9] = 0.141320; rate[6][10] = 0.172579; rate[6][11] = 2.867580; rate[6][12] = 0.353912; rate[6][13] = 0.092310; rate[6][14] = 0.755791; rate[6][15] = 0.782467; rate[6][16] = 0.914814; rate[6][17] = 0.172682; rate[6][18] = 0.217549; rate[6][19] = 0.655045; rate[7][8] = 0.276379; rate[7][9] = 0.034151; rate[7][10] = 0.068651; rate[7][11] = 0.415992; rate[7][12] = 0.194220; rate[7][13] = 0.055288; rate[7][14] = 0.273149; rate[7][15] = 1.486700; rate[7][16] = 0.251477; rate[7][17] = 0.374321; rate[7][18] = 0.114187; rate[7][19] = 0.209108; rate[8][9] = 0.152215; rate[8][10] = 0.555096; rate[8][11] = 0.992083; rate[8][12] = 0.450867; rate[8][13] = 0.756080; rate[8][14] = 0.771387; rate[8][15] = 0.822459; rate[8][16] = 0.525511; rate[8][17] = 0.289998; rate[8][18] = 4.290350; rate[8][19] = 0.131869; rate[9][10] = 3.517820; rate[9][11] = 0.360574; rate[9][12] = 4.714220; rate[9][13] = 1.177640; rate[9][14] = 0.111502; rate[9][15] = 0.353443; rate[9][16] = 1.615050; rate[9][17] = 0.234326; rate[9][18] = 0.468951; rate[9][19] = 8.659740; rate[10][11] = 0.287583; rate[10][12] = 5.375250; rate[10][13] = 2.348200; rate[10][14] = 0.462018; rate[10][15] = 0.382421; rate[10][16] = 0.364222; rate[10][17] = 0.740259; rate[10][18] = 0.443205; rate[10][19] = 1.997370; rate[11][12] = 1.032220; rate[11][13] = 0.098843; rate[11][14] = 0.619503; rate[11][15] = 1.073780; rate[11][16] = 1.537920; rate[11][17] = 0.152232; rate[11][18] = 0.147411; rate[11][19] = 0.342012; rate[12][13] = 1.320870; rate[12][14] = 0.194864; rate[12][15] = 0.556353; rate[12][16] = 1.681970; rate[12][17] = 0.570369; rate[12][18] = 0.473810; rate[12][19] = 2.282020; rate[13][14] = 0.179896; rate[13][15] = 0.606814; rate[13][16] = 0.191467; rate[13][17] = 1.699780; rate[13][18] = 7.154480; rate[13][19] = 0.725096; rate[14][15] = 1.786490; rate[14][16] = 0.885349; rate[14][17] = 0.156619; rate[14][18] = 0.239607; rate[14][19] = 0.351250; rate[15][16] = 4.847130; rate[15][17] = 0.578784; rate[15][18] = 0.872519; rate[15][19] = 0.258861; rate[16][17] = 0.126678; rate[16][18] = 0.325490; rate[16][19] = 1.547670; rate[17][18] = 2.763540; rate[17][19] = 0.409817; rate[18][19] = 0.347826; setEmpiricalRates(rate, "ARNDCQEGHILKMFPSTWYV"); double[] f = new double[n]; f[0] = 0.0866; f[1] = 0.0440; f[2] = 0.0391; f[3] = 0.0570; f[4] = 0.0193; f[5] = 0.0367; f[6] = 0.0581; f[7] = 0.0833; f[8] = 0.0244; f[9] = 0.0485; f[10] = 0.0862; f[11] = 0.0620; f[12] = 0.0195; f[13] = 0.0384; f[14] = 0.0458; f[15] = 0.0695; f[16] = 0.0610; f[17] = 0.0144; f[18] = 0.0353; f[19] = 0.0709; setEmpiricalFrequencies(f, "ARNDCQEGHILKMFPSTWYV"); } }
armanbilge/B3
src/beast/evomodel/substmodel/WAG.java
Java
gpl-3.0
7,525
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | Version: 3.2 \\ / A nd | Web: http://www.foam-extend.org \\/ M anipulation | For copyright notice see file Copyright ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend 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. foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>. Class Foam::genericFvPatch Description FV variant of the genericPolyPatch. SourceFiles genericFvPatch.C \*---------------------------------------------------------------------------*/ #ifndef genericFvPatch_H #define genericFvPatch_H #include "fvPatch.H" #include "genericPolyPatch.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class genericFvPatch Declaration \*---------------------------------------------------------------------------*/ class genericFvPatch : public fvPatch { public: //- Runtime type information TypeName(genericPolyPatch::typeName_()); // Constructors //- Construct from components genericFvPatch(const polyPatch& patch, const fvBoundaryMesh& bm) : fvPatch(patch, bm) {} }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
src/finiteVolume/fvMesh/fvPatches/basic/generic/genericFvPatch.H
C++
gpl-3.0
2,354
/* * * Copyright 2014-2016 Ignacio San Roman Lana * * This file is part of OpenCV_ML_Tool * * OpenCV_ML_Tool 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. * * OpenCV_ML_Tool 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 OpenCV_ML_Tool. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * isanromanlana@gmail.com */ #include "basic_transformations.h" MLT::Basic_Transformations::Basic_Transformations (int inputType, int outputType) { input = inputType; output = outputType; } MLT::Basic_Transformations::~Basic_Transformations (){} int MLT::Basic_Transformations::Extract (vector<Mat> imagenes, vector<Mat> &descriptores) { for (uint i = 0; i < imagenes.size (); i++){ Mat img_out; Mat gray; Mat aux; Mat img8u; Mat imgOutHsv; Mat imgOutA; Mat imgOutB; int level = 0; vector<Mat> channels; switch (input) { case RGB: { switch (output) { case RGB: imagenes[i].copyTo(img_out); break; case GRAY: cvtColor(imagenes[i], img_out, COLOR_BGR2GRAY); break; case THRESHOLD: imagenes[i].convertTo(img8u,CV_8U); cvtColor(img8u, gray, COLOR_BGR2GRAY); cv::threshold(gray, img_out, 0, 1, THRESH_BINARY | THRESH_OTSU); break; case CANNY: cvtColor(imagenes[i], gray, COLOR_BGR2GRAY); gray.convertTo(img8u,CV_8U); level = cv::threshold (img8u, aux, 0, 255, THRESH_BINARY | THRESH_OTSU); cv::Canny(img8u, img_out, 0.5 * level, level); break; case SOBEL: cvtColor(imagenes[i], gray, COLOR_BGR2GRAY); cv::Sobel(gray, imgOutA, CV_32F, 1, 0); cv::Sobel(gray, imgOutB, CV_32F, 0, 1); convertScaleAbs(imgOutA + imgOutB, img_out); break; case HSV: cvtColor(imagenes[i], img_out, COLOR_BGR2HSV); break; case H_CHANNEL: cvtColor(imagenes[i], imgOutHsv, COLOR_BGR2HSV); split(imgOutHsv, channels); channels[0].copyTo(img_out); break; case S_CHANNEL: cvtColor(imagenes[i], imgOutHsv, COLOR_BGR2HSV); split(imgOutHsv, channels); channels[1].copyTo(img_out); break; case V_CHANNEL: cvtColor(imagenes[i], imgOutHsv, COLOR_BGR2HSV); split(imgOutHsv, channels); channels[2].copyTo(img_out); break; case COLOR_PREDOMINANTE: cvtColor (imagenes[i], imgOutHsv, COLOR_BGR2HSV); img_out = Mat::zeros(imgOutHsv.rows, imgOutHsv.cols, CV_32FC1); for (int y = 0;y < imgOutHsv.rows; y++) { for (int x = 0; x < imgOutHsv.cols; x++) { Vec3b pixel = imgOutHsv.at<Vec3b>(y, x); if (pixel[0] >= 0. && pixel[0]<30.) img_out.at<float>(y,x) = 1; else if (pixel[0] >= 30. && pixel[0] < 60.) img_out.at<float>(y,x) = 2; else if (pixel[0] >= 60. && pixel[0] < 90.) img_out.at<float>(y,x) = 3; else if (pixel[0] >= 90. && pixel[0] < 120.) img_out.at<float>(y,x) = 4; else if (pixel[0] >= 120. && pixel[0] < 150.) img_out.at<float>(y,x) = 5; else if (pixel[0] >= 150. && pixel[0] < 180.) img_out.at<float>(y,x) = 6; } } break; default: cout << "ERROR en Extract: El tipo de transformacion indicado no esta contemplado" << endl; this->error=1; return this->error; } break; } case HSV: { switch (output) { case RGB: cvtColor(imagenes[i], img_out, COLOR_HSV2BGR); break; case GRAY: split(imagenes[i], channels); channels[2].copyTo(img_out); break; case THRESHOLD: split(imagenes[i], channels); channels[2].copyTo(gray); gray.convertTo(img8u,CV_8U); cv::threshold(img8u, img_out, 0, 1, THRESH_BINARY | THRESH_OTSU); break; case CANNY: split(imagenes[i], channels); channels[2].copyTo(gray); imagenes[i].convertTo(img8u, CV_8U); level = cv::threshold(img8u, aux, 0, 255, THRESH_BINARY | THRESH_OTSU); cv::Canny(img8u, img_out, 0.5 * level, level); break; case SOBEL: split(imagenes[i], channels); channels[2].copyTo(gray); cv::Sobel(gray, imgOutA, CV_32F,1,0); cv::Sobel(gray, imgOutB, CV_32F,0,1); convertScaleAbs(imgOutA + imgOutB, img_out); break; case HSV: imagenes[i].copyTo(img_out); break; case H_CHANNEL: split(imagenes[i],channels); channels[0].copyTo(img_out); break; case S_CHANNEL: split(imagenes[i],channels); channels[1].copyTo(img_out); break; case V_CHANNEL: split(imagenes[i],channels); channels[2].copyTo(img_out); break; case COLOR_PREDOMINANTE: img_out = Mat::zeros(imagenes[i].rows, imagenes[i].cols, CV_32FC1); for (int y = 0; y < imagenes[i].rows; y++) { for (int x = 0; x < imagenes[i].cols; x++) { Vec3b pixel = imagenes[i].at<Vec3b>(y, x); if (pixel[0] >= 0. && pixel[0] < 30.) img_out.at<float>(y,x) = 1; else if (pixel[0] >= 30. && pixel[0] < 60.) img_out.at<float>(y,x) = 2; else if (pixel[0] >= 60. && pixel[0] < 90.) img_out.at<float>(y,x) = 3; else if (pixel[0] >= 90. && pixel[0] < 120.) img_out.at<float>(y,x) = 4; else if (pixel[0] >= 120. && pixel[0] < 150.) img_out.at<float>(y,x) = 5; else if (pixel[0] >= 150. && pixel[0] < 180.) img_out.at<float>(y,x) = 6; } } break; default: cout << "ERROR en Extract: El tipo de transformacion indicado no esta contemplado" << endl; this->error=1; return this->error; } break; } case GRAY: { switch (output) { case RGB: break; case GRAY: imagenes[i].copyTo(img_out); break; case THRESHOLD: imagenes[i].convertTo(img8u,CV_8U); cv::threshold(img8u, img_out, 0, 1, THRESH_BINARY | THRESH_OTSU); break; case CANNY: imagenes[i].convertTo(img8u,CV_8U); level = cv::threshold(img8u, aux, 0, 255, THRESH_BINARY | THRESH_OTSU); cv::Canny(img8u, img_out, 0.5 * level, level); break; case SOBEL: cv::Sobel(imagenes[i], imgOutA, CV_32F,1,0); cv::Sobel(imagenes[i], imgOutB, CV_32F,0,1); convertScaleAbs(imgOutA + imgOutB, img_out); break; //case HSV: // break; //case H_CHANNEL: // break; //case S_CHANNEL: // break; case V_CHANNEL: imagenes[i].copyTo(img_out); break; //case COLOR_PREDOMINANTE: // break; default: cout << "ERROR en Extract: El tipo de transformacion indicado no esta contemplado" << endl; this->error=1; return this->error; } break; } case H_CHANNEL: { switch (output) { case COLOR_PREDOMINANTE: img_out = Mat::zeros(imagenes[i].rows,imagenes[i].cols,CV_32FC1); for (int y = 0;y<imagenes[i].rows;y++) { for (int x = 0; x < imagenes[i].cols;x++) { Vec3b pixel = imagenes[i].at<Vec3b>(y, x); if (pixel[0] >= 0. && pixel[0]<30.) img_out.at<float>(y,x) = 1; else if (pixel[0] >= 30. && pixel[0] < 60.) img_out.at<float>(y,x) = 2; else if (pixel[0] >= 60. && pixel[0] < 90.) img_out.at<float>(y,x) = 3; else if (pixel[0] >= 90. && pixel[0] < 120.) img_out.at<float>(y,x) = 4; else if (pixel[0] >= 120. && pixel[0] < 150.) img_out.at<float>(y,x) = 5; else if (pixel[0] >= 150. && pixel[0] < 180.) img_out.at<float>(y,x) = 6; } } break; default: cout << "ERROR en Extract: El tipo de transformacion indicado no esta contemplado" << endl; this->error=1; return this->error; } break; } default: cout << "ERROR en Extract: El tipo de transformacion indicado no esta contemplado" << endl; this->error=1; return this->error; } img_out.convertTo (img_out,CV_32F); descriptores.push_back (img_out); } this->error=0; return this->error; }
IgnacioSRL/OpenCV_ML_Tool
src/Extraccion_Caracteristicas/basic_transformations.cpp
C++
gpl-3.0
12,064
/* * Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.sufficientlysecure.keychain.ui; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import android.app.Activity; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.widget.Toast; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.intents.OpenKeychainIntents; import org.sufficientlysecure.keychain.provider.TemporaryStorageProvider; import org.sufficientlysecure.keychain.ui.base.BaseActivity; public class DecryptActivity extends BaseActivity { /* Intents */ public static final String ACTION_DECRYPT_FROM_CLIPBOARD = "DECRYPT_DATA_CLIPBOARD"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setFullScreenDialogClose(new View.OnClickListener() { @Override public void onClick(View v) { setResult(Activity.RESULT_CANCELED); finish(); } }, false); // Handle intent actions handleActions(savedInstanceState, getIntent()); } @Override protected void initLayout() { setContentView(R.layout.decrypt_files_activity); } /** * Handles all actions with this intent */ private void handleActions(Bundle savedInstanceState, Intent intent) { // No need to initialize fragments if we are just being restored if (savedInstanceState != null) { return; } ArrayList<Uri> uris = new ArrayList<>(); String action = intent.getAction(); if (action == null) { Toast.makeText(this, "Error: No action specified!", Toast.LENGTH_LONG).show(); setResult(Activity.RESULT_CANCELED); finish(); return; } try { switch (action) { case Intent.ACTION_SEND: { // When sending to Keychain Decrypt via share menu // Binary via content provider (could also be files) // override uri to get stream from send if (intent.hasExtra(Intent.EXTRA_STREAM)) { uris.add(intent.<Uri>getParcelableExtra(Intent.EXTRA_STREAM)); } else if (intent.hasExtra(Intent.EXTRA_TEXT)) { String text = intent.getStringExtra(Intent.EXTRA_TEXT); Uri uri = readToTempFile(text); uris.add(uri); } break; } case Intent.ACTION_SEND_MULTIPLE: { if (intent.hasExtra(Intent.EXTRA_STREAM)) { uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); } else if (intent.hasExtra(Intent.EXTRA_TEXT)) { for (String text : intent.getStringArrayListExtra(Intent.EXTRA_TEXT)) { Uri uri = readToTempFile(text); uris.add(uri); } } break; } case ACTION_DECRYPT_FROM_CLIPBOARD: { ClipboardManager clipMan = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); if (clipMan == null) { break; } ClipData clip = clipMan.getPrimaryClip(); if (clip == null) { break; } // check if data is available as uri Uri uri = null; for (int i = 0; i < clip.getItemCount(); i++) { ClipData.Item item = clip.getItemAt(i); Uri itemUri = item.getUri(); if (itemUri != null) { uri = itemUri; break; } } // otherwise, coerce to text (almost always possible) and work from there if (uri == null) { String text = clip.getItemAt(0).coerceToText(this).toString(); uri = readToTempFile(text); } uris.add(uri); break; } // for everything else, just work on the intent data case OpenKeychainIntents.DECRYPT_DATA: case Intent.ACTION_VIEW: default: uris.add(intent.getData()); } } catch (IOException e) { Toast.makeText(this, R.string.error_reading_text, Toast.LENGTH_LONG).show(); finish(); return; } // Definitely need a data uri with the decrypt_data intent if (uris.isEmpty()) { Toast.makeText(this, "No data to decrypt!", Toast.LENGTH_LONG).show(); setResult(Activity.RESULT_CANCELED); finish(); return; } displayListFragment(uris); } public Uri readToTempFile(String text) throws IOException { Uri tempFile = TemporaryStorageProvider.createFile(this); OutputStream outStream = getContentResolver().openOutputStream(tempFile); outStream.write(text.getBytes()); outStream.close(); return tempFile; } public void displayListFragment(ArrayList<Uri> inputUris) { DecryptListFragment frag = DecryptListFragment.newInstance(inputUris); FragmentManager fragMan = getSupportFragmentManager(); FragmentTransaction trans = fragMan.beginTransaction(); trans.replace(R.id.decrypt_files_fragment_container, frag); // if there already is a fragment, allow going back to that. otherwise, we're top level! if (fragMan.getFragments() != null && !fragMan.getFragments().isEmpty()) { trans.addToBackStack("list"); } trans.commit(); } }
xSooDx/open-keychain
OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptActivity.java
Java
gpl-3.0
7,046
#include "fiber.h" namespace focss { Fiber Fiber::linear() const { Fiber new_fiber = *this; new_fiber.gamma = 0; return new_fiber; } Fiber Fiber::nonlinear() const { Fiber new_fiber = *this; new_fiber.alpha = 0; new_fiber.beta2 = 0; return new_fiber; } Fiber Fiber::dispersive() const { Fiber new_fiber = *this; new_fiber.alpha = 0; new_fiber.gamma = 0; return new_fiber; } Fiber Fiber::operator-() const { Fiber new_fiber = *this; new_fiber.alpha = -alpha; new_fiber.beta2 = -beta2; new_fiber.gamma = -gamma; return new_fiber; } Fiber Fiber::operator*(const double& length_factor) const { Fiber new_fiber = *this; if (length_factor >= 0) { new_fiber.length *= length_factor; } else { new_fiber.alpha = -alpha; new_fiber.beta2 = -beta2; new_fiber.gamma = -gamma; new_fiber.length *= -length_factor; } return new_fiber; } } // namespace focss
euav/ssfm
src/focss/module/fiber.cpp
C++
gpl-3.0
974
<?php /* You may not change or alter any portion of this comment or credits of supporting developers from this source code or any supporting source code which is considered copyrighted (c) material of the original comment or credit authors. 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. */ /** * @copyright The XUUPS Project http://sourceforge.net/projects/xuups/ * @license http://www.fsf.org/copyleft/gpl.html GNU public license * @package Publisher * @subpackage Action * @since 1.0 * @author trabis <lusopoemas@gmail.com> * @author Taiwen Jiang <phppp@users.sourceforge.net> * @version $Id: search.php 10374 2012-12-12 23:39:48Z trabis $ */ include_once dirname(__FILE__) . '/header.php'; xoops_loadLanguage('search'); //Checking general permissions $config_handler = xoops_gethandler("config"); $xoopsConfigSearch = $config_handler->getConfigsByCat(XOOPS_CONF_SEARCH); if (empty($xoopsConfigSearch["enable_search"])) { redirect_header(PUBLISHER_URL . "/index.php", 2, _NOPERM); exit(); } $groups = $xoopsUser ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS; $gperm_handler = xoops_getmodulehandler('groupperm', PUBLISHER_DIRNAME); $module_id = $publisher->getModule()->mid(); //Checking permissions if (!$publisher->getConfig('perm_search') || !$gperm_handler->checkRight('global', _PUBLISHER_SEARCH, $groups, $module_id)) { redirect_header(PUBLISHER_URL, 2, _NOPERM); exit(); } $xoopsConfig["module_cache"][$module_id] = 0; $xoopsOption["template_main"] = 'publisher_search.html'; include XOOPS_ROOT_PATH . '/header.php'; $module_info_search = $publisher->getModule()->getInfo("search"); include_once PUBLISHER_ROOT_PATH . "/" . $module_info_search["file"]; $limit = 10; //$publisher->getConfig('idxcat_perpage'); $uid = 0; $queries = array(); $andor = PublisherRequest::getString('andor'); $start = PublisherRequest::getInt('start'); $category = PublisherRequest::getArray('category'); $username = PublisherRequest::getString('uname'); $searchin = PublisherRequest::getArray('searchin'); $sortby = PublisherRequest::getString('sortby'); $term = PublisherRequest::getString('term'); if (empty($category) || (is_array($category) && in_array("all", $category))) { $category = array(); } else { $category = !is_array($category) ? explode(",", $category) : $category; $category = array_map("intval", $category); } $andor = (in_array(strtoupper($andor), array("OR", "AND", "EXACT"))) ? strtoupper($andor) : "OR"; $sortby = (in_array(strtolower($sortby), array("itemid", "datesub", "title", "categoryid"))) ? strtolower($sortby) : "itemid"; if (!(empty($_POST["submit"]) && empty($term))) { $next_search["category"] = implode(",", $category); $next_search["andor"] = $andor; $next_search["term"] = $term; $query = trim($term); if ($andor != "EXACT") { $ignored_queries = array(); // holds kewords that are shorter than allowed minmum length $temp_queries = preg_split("/[\s,]+/", $query); foreach ($temp_queries as $q) { $q = trim($q); if (strlen($q) >= $xoopsConfigSearch["keyword_min"]) { $queries[] = $myts->addSlashes($q); } else { $ignored_queries[] = $myts->addSlashes($q); } } if (count($queries) == 0) { redirect_header(PUBLISHER_URL . "/search.php", 2, sprintf(_SR_KEYTOOSHORT, $xoopsConfigSearch["keyword_min"])); exit(); } } else { if (strlen($query) < $xoopsConfigSearch["keyword_min"]) { redirect_header(PUBLISHER_URL . "/search.php", 2, sprintf(_SR_KEYTOOSHORT, $xoopsConfigSearch["keyword_min"])); exit(); } $queries = array($myts->addSlashes($query)); } $uname_required = false; $search_username = trim($username); $next_search["uname"] = $search_username; if (!empty($search_username)) { $uname_required = true; $search_username = $myts->addSlashes($search_username); if (!$result = $xoopsDB->query("SELECT uid FROM " . $xoopsDB->prefix("users") . " WHERE uname LIKE " . $xoopsDB->quoteString("%$search_username%"))) { redirect_header(PUBLISHER_URL . "/search.php", 1, _CO_PUBLISHER_ERROR); exit(); } $uid = array(); while ($row = $xoopsDB->fetchArray($result)) { $uid[] = $row["uid"]; } } else { $uid = 0; } $next_search["sortby"] = $sortby; $next_search["searchin"] = implode("|", $searchin); if (!empty($time)) { $extra = ""; } else { $extra = ""; } if ($uname_required && (!$uid || count($uid) < 1)) { $results = array(); } else { $results = $module_info_search["func"]($queries, $andor, $limit, $start, $uid, $category, $sortby, $searchin, $extra); } if (count($results) < 1) { $results[] = array("text" => _SR_NOMATCH); } $xoopsTpl->assign("results", $results); if (count($next_search) > 0) { $items = array(); foreach ($next_search as $para => $val) { if (!empty($val)) $items[] = "{$para}={$val}"; } if (count($items) > 0) $paras = implode("&", $items); unset($next_search); unset($items); } $search_url = PUBLISHER_URL . "/search.php?" . $paras; if (count($results)) { $next = $start + $limit; $queries = implode(",", $queries); $search_url_next = $search_url . "&start={$next}"; $search_next = "<a href=\"" . htmlspecialchars($search_url_next) . "\">" . _SR_NEXT . "</a>"; $xoopsTpl->assign("search_next", $search_next); } if ($start > 0) { $prev = $start - $limit; $search_url_prev = $search_url . "&start={$prev}"; $search_prev = "<a href=\"" . htmlspecialchars($search_url_prev) . "\">" . _SR_PREVIOUS . "</a>"; $xoopsTpl->assign("search_prev", $search_prev); } unset($results); $search_info = _SR_KEYWORDS . ": " . $myts->htmlSpecialChars($term); if ($uname_required) { if ($search_info) $search_info .= "<br />"; $search_info .= _CO_PUBLISHER_UID . ": " . $myts->htmlSpecialChars($search_username); } $xoopsTpl->assign("search_info", $search_info); } /* type */ $type_select = "<select name=\"andor\" class=\"form-control\">"; $type_select .= "<option value=\"OR\""; if ("OR" == $andor) $type_select .= " selected=\"selected\""; $type_select .= ">" . _SR_ANY . "</option>"; $type_select .= "<option value=\"AND\""; if ("AND" == $andor) $type_select .= " selected=\"selected\""; $type_select .= ">" . _SR_ALL . "</option>"; $type_select .= "<option value=\"EXACT\""; if ("EXACT" == $andor) $type_select .= " selected=\"selected\""; $type_select .= ">" . _SR_EXACT . "</option>"; $type_select .= "</select>"; /* category */ $categories = $publisher->getHandler('category')->getCategoriesForSearch(); $select_category = "<select name=\"category[]\" size=\"5\" multiple=\"multiple\" class=\"form-control\">"; $select_category .= "<option value=\"all\""; if (empty($category) || count($category) == 0) $select_category .= "selected=\"selected\""; $select_category .= ">" . _ALL . "</option>"; foreach ($categories as $id => $cat) { $select_category .= "<option value=\"" . $id . "\""; if (in_array($id, $category)) $select_category .= "selected=\"selected\""; $select_category .= ">" . $cat . "</option>"; } $select_category .= "</select>"; /* scope */ $searchin_select = ""; $searchin_select .= "<label class=\"checkbox-inline\"> <input type=\"checkbox\" name=\"searchin[]\" value=\"title\""; if (in_array("title", $searchin)) $searchin_select .= " checked"; $searchin_select .= " />" . _CO_PUBLISHER_TITLE . "</label>"; $searchin_select .= "<label class=\"checkbox-inline\"> <input type=\"checkbox\" name=\"searchin[]\" value=\"subtitle\""; if (in_array("subtitle", $searchin)) $searchin_select .= " checked"; $searchin_select .= " />" . _CO_PUBLISHER_SUBTITLE . "</label>"; $searchin_select .= "<label class=\"checkbox-inline\"> <input type=\"checkbox\" name=\"searchin[]\" value=\"summary\""; if (in_array("summary", $searchin)) $searchin_select .= " checked"; $searchin_select .= " />" . _CO_PUBLISHER_SUMMARY . "</label>"; $searchin_select .= "<label class=\"checkbox-inline\"> <input type=\"checkbox\" name=\"searchin[]\" value=\"text\""; if (in_array("body", $searchin)) $searchin_select .= " checked"; $searchin_select .= " />" . _CO_PUBLISHER_BODY . "</label>"; $searchin_select .= "<label class=\"checkbox-inline\"> <input type=\"checkbox\" name=\"searchin[]\" value=\"keywords\""; if (in_array("meta_keywords", $searchin)) $searchin_select .= " checked"; $searchin_select .= " />" . _CO_PUBLISHER_ITEM_META_KEYWORDS . "</label>"; $searchin_select .= "<label class=\"checkbox-inline\"> <input type=\"checkbox\" name=\"searchin[]\" value=\"all\""; if (in_array("all", $searchin) || empty($searchin)) $searchin_select .= " checked"; $searchin_select .= " />" . _ALL . "</label>"; /* sortby */ $sortby_select = "<select name=\"sortby\" class=\"form-control\">"; $sortby_select .= "<option value=\"itemid\""; if ("itemid" == $sortby || empty($sortby)) $sortby_select .= " selected=\"selected\""; $sortby_select .= ">" . _NONE . "</option>"; $sortby_select .= "<option value=\"datesub\""; if ("datesub" == $sortby) $sortby_select .= " selected=\"selected\""; $sortby_select .= ">" . _CO_PUBLISHER_DATESUB . "</option>"; $sortby_select .= "<option value=\"title\""; if ("title" == $sortby) $sortby_select .= " selected=\"selected\""; $sortby_select .= ">" . _CO_PUBLISHER_TITLE . "</option>"; $sortby_select .= "<option value=\"categoryid\""; if ("categoryid" == $sortby) $sortby_select .= " selected=\"selected\""; $sortby_select .= ">" . _CO_PUBLISHER_CATEGORY . "</option>"; $sortby_select .= "</select>"; $xoopsTpl->assign("type_select", $type_select); $xoopsTpl->assign("searchin_select", $searchin_select); $xoopsTpl->assign("category_select", $select_category); $xoopsTpl->assign("sortby_select", $sortby_select); $xoopsTpl->assign("search_term", $term); $xoopsTpl->assign("search_user", $username); $xoopsTpl->assign("modulename", $publisher->getModule()->name()); if ($xoopsConfigSearch["keyword_min"] > 0) { $xoopsTpl->assign("search_rule", sprintf(_SR_KEYIGNORE, $xoopsConfigSearch["keyword_min"])); } include XOOPS_ROOT_PATH . "/footer.php"; ?>
kevjoe/xoops-newoni
modules/publisher/xoops_and_module_changes/modules/publisher/search.php
PHP
gpl-3.0
10,611
package epmc.param.value.cancellator; import epmc.param.value.polynomial.TypePolynomial; import epmc.param.value.polynomial.ValuePolynomial; public interface Cancellator { interface Builder { Builder setType(TypePolynomial type); Cancellator build(); } void cancel(ValuePolynomial operand1, ValuePolynomial operand2); }
liyi-david/ePMC
plugins/param/src/main/java/epmc/param/value/cancellator/Cancellator.java
Java
gpl-3.0
361
/* SpiroNet.Avalonia Copyright (C) 2019 Wiesław Šoltés This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using Avalonia; using Avalonia.Controls; using Avalonia.Media; using System; using System.Collections.Generic; namespace SpiroNet.Editor.Avalonia.Renderer { public class CanvasRenderer : Canvas { private static Geometry LeftKnot = StreamGeometry.Parse("M0,-4 A 4,4 0 0 0 0,4"); private static Geometry RightKnot = StreamGeometry.Parse("M0,-4 A 4,4 0 0 1 0,4"); private static Geometry EndKnot = StreamGeometry.Parse("M-3.5,-3.5 L3.5,3.5 M-3.5,3.5 L3.5,-3.5"); private static Geometry EndOpenContourKnot = StreamGeometry.Parse("M-3.5,-3.5 L0,0 -3.5,3.5"); private static Geometry OpenContourKnot = StreamGeometry.Parse("M3.5,-3.5 L0,0 3.5,3.5"); private IDictionary<BasicStyle, BasicStyleCache> _cache; private BasicStyle _geometryStyle; private BasicStyle _hitGeometryStyle; private BasicStyle _pointStyle; private BasicStyle _hitPointStyle; private BasicStyle _guideStyle; private BasicStyle _snapGuideStyle; private BasicStyle _snapPointStyle; private BasicStyle _newLineStyle; private BasicStyle _lineStyle; public SpiroEditor SpiroEditor { get { return GetValue(SpiroEditorProperty); } set { SetValue(SpiroEditorProperty, value); } } public static readonly StyledProperty<SpiroEditor> SpiroEditorProperty = AvaloniaProperty.Register<CanvasRenderer, SpiroEditor>(nameof(SpiroEditor)); public CanvasRenderer() { InitializeStyles(); } private void InitializeStyles() { _cache = new Dictionary<BasicStyle, BasicStyleCache>(); // Spiro styles. _geometryStyle = new BasicStyle( new Argb(255, 0, 0, 0), new Argb(128, 128, 128, 128), 2.0); _hitGeometryStyle = new BasicStyle( new Argb(255, 255, 0, 0), new Argb(128, 128, 0, 0), 2.0); _pointStyle = new BasicStyle( new Argb(192, 0, 0, 255), new Argb(192, 0, 0, 255), 2.0); _hitPointStyle = new BasicStyle( new Argb(192, 255, 0, 0), new Argb(192, 255, 0, 0), 2.0); // Guide styles. _guideStyle = new BasicStyle( new Argb(255, 0, 255, 255), new Argb(255, 0, 255, 255), 1.0); _snapGuideStyle = new BasicStyle( new Argb(255, 255, 255, 0), new Argb(255, 255, 255, 0), 1.0); _snapPointStyle = new BasicStyle( new Argb(255, 255, 255, 0), new Argb(255, 255, 255, 0), 1.0); _newLineStyle = new BasicStyle( new Argb(255, 255, 255, 0), new Argb(255, 255, 255, 0), 1.0); _lineStyle = new BasicStyle( new Argb(255, 0, 255, 255), new Argb(255, 0, 255, 255), 1.0); } private BasicStyleCache FromCache(BasicStyle style) { BasicStyleCache value; if (_cache.TryGetValue(style, out value)) { return value; } value = new BasicStyleCache(style); _cache.Add(style, value); return value; } public override void Render(DrawingContext context) { base.Render(context); if (SpiroEditor != null && SpiroEditor.Drawing != null) { if (SpiroEditor.Drawing.Guides != null && SpiroEditor.State.DisplayGuides) { DrawGuides(context); } var state = SpiroEditor.State; if (SpiroEditor.State.DisplayGuides && (state.Tool == EditorTool.Guide || state.Tool == EditorTool.Spiro)) { if ((state.Tool == EditorTool.Spiro && state.EnableSnap) || (state.Tool == EditorTool.Guide && state.IsCaptured) || (state.Tool == EditorTool.Guide && state.HaveSnapPoint)) { DrawHorizontalGuide(context, FromCache(state.HaveSnapPoint ? _snapGuideStyle : _guideStyle), state.GuidePosition, SpiroEditor.Drawing.Width); DrawVerticalGuide(context, FromCache(state.HaveSnapPoint ? _snapGuideStyle : _guideStyle), state.GuidePosition, SpiroEditor.Drawing.Height); } if (state.Tool == EditorTool.Guide && state.HaveSnapPoint) { DrawGuidePoint( context, FromCache(_snapPointStyle), SpiroEditor.State.SnapPoint, SpiroEditor.State.SnapPointRadius); } if (state.Tool == EditorTool.Guide && state.IsCaptured) { DrawGuideLine( context, FromCache(_newLineStyle), SpiroEditor.Measure.Point0, SpiroEditor.Measure.Point1); } } if (SpiroEditor.Drawing.Shapes != null) { DrawSpiroShapes(context); } } } private void DrawSpiroShapes(DrawingContext dc) { var state = SpiroEditor.State; foreach (var shape in SpiroEditor.Drawing.Shapes) { if (!state.HitSetShapes.Contains(shape)) { DrawSpiroShape(dc, shape, false); if (SpiroEditor.State.DisplayKnots) { DrawSpiroKnots(dc, shape, false, -1); } } } for (int i = 0; i < state.HitListShapes.Count; i++) { var shape = state.HitListShapes[i]; var index = state.HitListPoints[i]; bool isSelected = index == -1; DrawSpiroShape(dc, shape, isSelected); if (SpiroEditor.State.DisplayKnots) { DrawSpiroKnots(dc, shape, true, index); } } } private void DrawSpiroShape(DrawingContext dc, SpiroShape shape, bool isSelected) { string data; var result = SpiroEditor.Data.TryGetValue(shape, out data); if (result && !string.IsNullOrEmpty(data)) { var geometry = StreamGeometry.Parse(data); if (isSelected) { var cache = FromCache(_hitGeometryStyle); dc.DrawGeometry( shape.IsFilled ? cache.FillBrush : null, shape.IsStroked ? cache.StrokePen : null, geometry); } else { var cache = FromCache(_geometryStyle); dc.DrawGeometry( shape.IsFilled ? cache.FillBrush : null, shape.IsStroked ? cache.StrokePen : null, geometry); } } } private void DrawSpiroKnots(DrawingContext dc, SpiroShape shape, bool shapeIsSelected, int index) { var pointCache = FromCache(_pointStyle); var hitPointCache = FromCache(_hitPointStyle); IList<SpiroKnot> knots; SpiroEditor.Knots.TryGetValue(shape, out knots); if (knots != null) { for (int i = 0; i < knots.Count; i++) { var knot = knots[i]; var brush = shapeIsSelected && i == index ? hitPointCache.FillBrush : pointCache.FillBrush; var pen = shapeIsSelected && i == index ? hitPointCache.StrokePen : pointCache.StrokePen; DrawSpiroKnot(dc, brush, pen, knot); } } else { for (int i = 0; i < shape.Points.Count; i++) { var point = shape.Points[i]; var brush = shapeIsSelected && i == index ? hitPointCache.FillBrush : pointCache.FillBrush; var pen = shapeIsSelected && i == index ? hitPointCache.StrokePen : pointCache.StrokePen; DrawSpiroPoint(dc, brush, pen, point); } } } private void DrawSpiroKnot(DrawingContext dc, IBrush brush, Pen pen, SpiroKnot knot) { switch (knot.Type) { case SpiroPointType.Corner: dc.FillRectangle(brush, new Rect(knot.X - 3.5, knot.Y - 3.5, 7, 7)); break; case SpiroPointType.G4: FillEllipse(dc, brush, new GuidePoint(knot.X, knot.Y), 3.5, 3.5); break; case SpiroPointType.G2: { var rm = Rotation(ToRadians(knot.Theta), new Vector(knot.X, knot.Y)); var rt = dc.PushPreTransform(rm); dc.FillRectangle(brush, new Rect(knot.X - 1.5, knot.Y - 3.5, 3, 7)); rt.Dispose(); } break; case SpiroPointType.Left: { var rm = Rotation(ToRadians(knot.Theta), new Vector(knot.X, knot.Y)); var tm = Translate(knot.X, knot.Y); var rt = dc.PushPreTransform(rm); var tt = dc.PushPreTransform(tm); dc.DrawGeometry(brush, null, LeftKnot); tt.Dispose(); rt.Dispose(); } break; case SpiroPointType.Right: { var rm = Rotation(ToRadians(knot.Theta), new Vector(knot.X, knot.Y)); var tm = Translate(knot.X, knot.Y); var rt = dc.PushPreTransform(rm); var tt = dc.PushPreTransform(tm); dc.DrawGeometry(brush, null, RightKnot); tt.Dispose(); rt.Dispose(); } break; case SpiroPointType.End: { var rm = Rotation(ToRadians(knot.Theta), new Vector(knot.X, knot.Y)); var tm = Translate(knot.X, knot.Y); var rt = dc.PushPreTransform(rm); var tt = dc.PushPreTransform(tm); dc.DrawGeometry(null, pen, EndKnot); tt.Dispose(); rt.Dispose(); } break; case SpiroPointType.OpenContour: { var rm = Rotation(ToRadians(knot.Theta), new Vector(knot.X, knot.Y)); var tm = Translate(knot.X, knot.Y); var rt = dc.PushPreTransform(rm); var tt = dc.PushPreTransform(tm); dc.DrawGeometry(null, pen, OpenContourKnot); tt.Dispose(); rt.Dispose(); } break; case SpiroPointType.EndOpenContour: { var rm = Rotation(ToRadians(knot.Theta), new Vector(knot.X, knot.Y)); var tm = Translate(knot.X, knot.Y); var rt = dc.PushPreTransform(rm); var tt = dc.PushPreTransform(tm); dc.DrawGeometry(null, pen, EndOpenContourKnot); tt.Dispose(); rt.Dispose(); } break; } } private void DrawSpiroPoint(DrawingContext dc, IBrush brush, Pen pen, SpiroControlPoint point) { switch (point.Type) { case SpiroPointType.Corner: dc.FillRectangle(brush, new Rect(point.X - 3.5, point.Y - 3.5, 7, 7)); break; case SpiroPointType.G4: case SpiroPointType.G2: case SpiroPointType.Left: case SpiroPointType.Right: case SpiroPointType.End: case SpiroPointType.OpenContour: case SpiroPointType.EndOpenContour: var tm = Translate(point.X, point.Y); var tt = dc.PushPreTransform(tm); dc.DrawGeometry(null, pen, EndKnot); tt.Dispose(); break; } } private void DrawGuides(DrawingContext dc) { foreach (var guide in SpiroEditor.Drawing.Guides) { DrawGuideLine(dc, FromCache(_lineStyle), guide.Point0, guide.Point1); } } private void DrawGuidePoint(DrawingContext dc, BasicStyleCache cache, GuidePoint point, double radius) { FillEllipse(dc, cache.FillBrush, point, radius, radius); } private void DrawGuideLine(DrawingContext dc, BasicStyleCache cache, GuidePoint point0, GuidePoint point1) { dc.DrawLine(cache.StrokePen, new Point(point0.X, point0.Y), new Point(point1.X, point1.Y)); } private void DrawHorizontalGuide(DrawingContext dc, BasicStyleCache cache, GuidePoint point, double width) { var point0 = new GuidePoint(0, point.Y); var point1 = new GuidePoint(width, point.Y); DrawGuideLine(dc, cache, point0, point1); } private void DrawVerticalGuide(DrawingContext dc, BasicStyleCache cache, GuidePoint point, double height) { var point0 = new GuidePoint(point.X, 0); var point1 = new GuidePoint(point.X, height); DrawGuideLine(dc, cache, point0, point1); } private static void FillEllipse(DrawingContext dc, IBrush brush, GuidePoint point, double radiusX, double radiusY) { var g = new EllipseGeometry(new Rect(point.X - radiusX, point.Y - radiusY, 2.0 * radiusX, 2.0 * radiusY)); dc.DrawGeometry(brush, null, g); } private static double ToRadians(double degrees) { return degrees * Math.PI / 180.0; } private static Matrix Translate(double offsetX, double offsetY) { return new Matrix(1.0, 0.0, 0.0, 1.0, offsetX, offsetY); } private static Matrix Rotation(double radians) { double cos = Math.Cos(radians); double sin = Math.Sin(radians); return new Matrix(cos, sin, -sin, cos, 0, 0); } private static Matrix Rotation(double angle, Vector center) { return Translate(-center.X, -center.Y) * Rotation(angle) * Translate(center.X, center.Y); } } }
wieslawsoltes/SpiroNet
src/SpiroNet.Editor.Avalonia/Renderer/CanvasRenderer.cs
C#
gpl-3.0
16,438
import szurubooru.model.util from szurubooru.model.base import Base from szurubooru.model.comment import Comment, CommentScore from szurubooru.model.pool import Pool, PoolName, PoolPost from szurubooru.model.pool_category import PoolCategory from szurubooru.model.post import ( Post, PostFavorite, PostFeature, PostNote, PostRelation, PostScore, PostSignature, PostTag, ) from szurubooru.model.snapshot import Snapshot from szurubooru.model.tag import Tag, TagImplication, TagName, TagSuggestion from szurubooru.model.tag_category import TagCategory from szurubooru.model.user import User, UserToken
rr-/szurubooru
server/szurubooru/model/__init__.py
Python
gpl-3.0
632
<?php return [ 'user-1' => 'Nom de l\'utilisateur', 'logout-1' => 'D&eacute;connexion', 'logout-2' => 'Voulez-vous vous d&eacute;connecter ?', 'logout-3' => 'Cliquez sur Non si vous d&eacute;sirez continuer votre travail. Cliquez sur Oui pour vous d&eacute;connecter.', 'logout-4' => 'Oui', 'logout-5' => 'Non', ];
ntja/smartschool
v1/view/resources/lang/fr/user.php
PHP
gpl-3.0
341
# -*- coding:binary -*- require 'spec_helper' require 'rex/proto/kerberos' require 'msf/kerberos/client' describe Msf::Kerberos::Client::Base do subject do mod = ::Msf::Exploit.new mod.extend ::Msf::Kerberos::Client mod.send(:initialize) mod end let(:client_opts) do { :name_type => Rex::Proto::Kerberos::Model::NT_PRINCIPAL, :client_name => 'test' } end let(:server_opts) do { :name_type => Rex::Proto::Kerberos::Model::NT_PRINCIPAL, :server_name => 'krbtgt/DOMAIN' } end describe "#build_client_name" do context "when no opts" do it "create a Rex::Proto::Kerberos::Model::PrincipalName" do expect(subject.build_client_name).to be_a(Rex::Proto::Kerberos::Model::PrincipalName) end it "creates a PrincipalName with empty name_String" do client_name = subject.build_client_name expect(client_name.name_string).to eq([]) end it "creates a NT_PRINCIPAL type PrincipalName" do client_name = subject.build_client_name expect(client_name.name_type).to eq(Rex::Proto::Kerberos::Model::NT_PRINCIPAL) end end context "when opts" do it "create a Rex::Proto::Kerberos::Model::PrincipalName" do expect(subject.build_server_name(client_opts)).to be_a(Rex::Proto::Kerberos::Model::PrincipalName) end it "builds name_string from opts" do client_name = subject.build_client_name(client_opts) expect(client_name.name_string).to eq(['test']) end it "builds name_type from opts" do client_name = subject.build_client_name(client_opts) expect(client_name.name_type).to eq(Rex::Proto::Kerberos::Model::NT_PRINCIPAL) end end end describe "#build_server_name" do context "when no opts" do it "create a Rex::Proto::Kerberos::Model::PrincipalName" do expect(subject.build_server_name).to be_a(Rex::Proto::Kerberos::Model::PrincipalName) end it "creates a PrincipalName with empty name_string" do client_name = subject.build_server_name expect(client_name.name_string).to eq([]) end it "creates a NT_PRINCIPAL type PrincipalName" do client_name = subject.build_server_name expect(client_name.name_type).to eq(Rex::Proto::Kerberos::Model::NT_PRINCIPAL) end end context "when opts" do it "create a Rex::Proto::Kerberos::Model::PrincipalName" do expect(subject.build_server_name(server_opts)).to be_a(Rex::Proto::Kerberos::Model::PrincipalName) end it "builds the name_string opts" do client_name = subject.build_server_name(server_opts) expect(client_name.name_string).to eq(['krbtgt', 'DOMAIN']) end it "builds the name_type from opts" do client_name = subject.build_server_name(server_opts) expect(client_name.name_type).to eq(Rex::Proto::Kerberos::Model::NT_PRINCIPAL) end end end end
cSploit/android.MSF
spec/lib/msf/kerberos/client/base_spec.rb
Ruby
gpl-3.0
2,990
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | Version: 3.2 \\ / A nd | Web: http://www.foam-extend.org \\/ M anipulation | For copyright notice see file Copyright ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend 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. foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "channelIndex.H" #include "boolList.H" #include "syncTools.H" #include "OFstream.H" #include "meshTools.H" #include "foamTime.H" #include "SortableList.H" // * * * * * * * * * * * * * Static Member Data * * * * * * * * * * * * * * // template<> const char* Foam::NamedEnum<Foam::vector::components, 3>::names[] = { "x", "y", "z" }; const Foam::NamedEnum<Foam::vector::components, 3> Foam::channelIndex::vectorComponentsNames_; // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // // Determines face blocking void Foam::channelIndex::walkOppositeFaces ( const polyMesh& mesh, const labelList& startFaces, boolList& blockedFace ) { const cellList& cells = mesh.cells(); const faceList& faces = mesh.faces(); label nBnd = mesh.nFaces() - mesh.nInternalFaces(); DynamicList<label> frontFaces(startFaces); forAll(frontFaces, i) { label faceI = frontFaces[i]; blockedFace[faceI] = true; } while (returnReduce(frontFaces.size(), sumOp<label>()) > 0) { // Transfer across. boolList isFrontBndFace(nBnd, false); forAll(frontFaces, i) { label faceI = frontFaces[i]; if (!mesh.isInternalFace(faceI)) { isFrontBndFace[faceI-mesh.nInternalFaces()] = true; } } syncTools::swapBoundaryFaceList(mesh, isFrontBndFace, false); // Add forAll(isFrontBndFace, i) { label faceI = mesh.nInternalFaces()+i; if (isFrontBndFace[i] && !blockedFace[faceI]) { blockedFace[faceI] = true; frontFaces.append(faceI); } } // Transfer across cells DynamicList<label> newFrontFaces(frontFaces.size()); forAll(frontFaces, i) { label faceI = frontFaces[i]; { const cell& ownCell = cells[mesh.faceOwner()[faceI]]; label oppositeFaceI = ownCell.opposingFaceLabel(faceI, faces); if (oppositeFaceI == -1) { FatalErrorIn("channelIndex::walkOppositeFaces(..)") << "Face:" << faceI << " owner cell:" << ownCell << " is not a hex?" << abort(FatalError); } else { if (!blockedFace[oppositeFaceI]) { blockedFace[oppositeFaceI] = true; newFrontFaces.append(oppositeFaceI); } } } if (mesh.isInternalFace(faceI)) { const cell& neiCell = mesh.cells()[mesh.faceNeighbour()[faceI]]; label oppositeFaceI = neiCell.opposingFaceLabel(faceI, faces); if (oppositeFaceI == -1) { FatalErrorIn("channelIndex::walkOppositeFaces(..)") << "Face:" << faceI << " neighbour cell:" << neiCell << " is not a hex?" << abort(FatalError); } else { if (!blockedFace[oppositeFaceI]) { blockedFace[oppositeFaceI] = true; newFrontFaces.append(oppositeFaceI); } } } } frontFaces.transfer(newFrontFaces); } } // Calculate regions. void Foam::channelIndex::calcLayeredRegions ( const polyMesh& mesh, const labelList& startFaces ) { boolList blockedFace(mesh.nFaces(), false); walkOppositeFaces ( mesh, startFaces, blockedFace ); if (false) { OFstream str(mesh.time().path()/"blockedFaces.obj"); label vertI = 0; forAll(blockedFace, faceI) { if (blockedFace[faceI]) { const face& f = mesh.faces()[faceI]; forAll(f, fp) { meshTools::writeOBJ(str, mesh.points()[f[fp]]); } str<< 'f'; forAll(f, fp) { str << ' ' << vertI+fp+1; } str << nl; vertI += f.size(); } } } // Do analysis for connected regions cellRegion_.reset(new regionSplit(mesh, blockedFace)); Info<< "Detected " << cellRegion_().nRegions() << " layers." << nl << endl; // Sum number of entries per region regionCount_ = regionSum(scalarField(mesh.nCells(), 1.0)); // Average cell centres to determine ordering. pointField regionCc ( regionSum(mesh.cellCentres()) / regionCount_ ); SortableList<scalar> sortComponent(regionCc.component(dir_)); sortMap_ = sortComponent.indices(); y_ = sortComponent; if (symmetric_) { y_.setSize(cellRegion_().nRegions()/2); } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // Foam::channelIndex::channelIndex ( const polyMesh& mesh, const dictionary& dict ) : symmetric_(readBool(dict.lookup("symmetric"))), dir_(vectorComponentsNames_.read(dict.lookup("component"))) { const polyBoundaryMesh& patches = mesh.boundaryMesh(); const wordList patchNames(dict.lookup("patches")); label nFaces = 0; forAll(patchNames, i) { label patchI = patches.findPatchID(patchNames[i]); if (patchI == -1) { FatalErrorIn("channelIndex::channelIndex(const polyMesh&)") << "Illegal patch " << patchNames[i] << ". Valid patches are " << patches.name() << exit(FatalError); } nFaces += patches[patchI].size(); } labelList startFaces(nFaces); nFaces = 0; forAll(patchNames, i) { const polyPatch& pp = patches[patches.findPatchID(patchNames[i])]; forAll(pp, j) { startFaces[nFaces++] = pp.start()+j; } } // Calculate regions. calcLayeredRegions(mesh, startFaces); } Foam::channelIndex::channelIndex ( const polyMesh& mesh, const labelList& startFaces, const bool symmetric, const direction dir ) : symmetric_(symmetric), dir_(dir) { // Calculate regions. calcLayeredRegions(mesh, startFaces); } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * // // ************************************************************************* //
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
applications/utilities/postProcessing/miscellaneous/postChannel/channelIndex.C
C++
gpl-3.0
7,956
package de.helfenkannjeder.istatus.server.business; import static de.helfenkannjeder.istatus.server.business.Constants.LOADGRAPH; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import javax.persistence.EntityGraph; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.validation.constraints.NotNull; import de.helfenkannjeder.istatus.server.domain.Squad; public class SquadService implements Serializable { private static final long serialVersionUID = 7630421539856219706L; public enum FetchType { SQUAD_ONLY, WITH_MEMBERS } public enum OrderByType { UNORDERED, NAME } @PersistenceContext private transient EntityManager em; @NotNull(message = "{squad.notFound.id}") public Squad findSquadById(Long id, FetchType fetch) { if (id == null) { return null; } Squad squad = null; EntityGraph<?> entityGraph; Map<String, Object> props; switch (fetch) { case SQUAD_ONLY: squad = em.find(Squad.class, id); break; case WITH_MEMBERS: entityGraph = em.getEntityGraph(Squad.GRAPH_MEMBERS); props = Collections.singletonMap(LOADGRAPH, entityGraph); squad = em.find(Squad.class, id, props); break; default: break; } return squad; } @NotNull(message = "{squad.notFound.id}") public List<Squad> findSquadByOrganisationId(Long organisationId, FetchType fetch) { if (organisationId == null) { return null; } TypedQuery<Squad> query = null; EntityGraph<?> entityGraph; query = em.createNamedQuery(Squad.FIND_SQUADS_BY_ORGANISATION, Squad.class) .setParameter(Squad.PARAM_ORGANISATION_ID, organisationId); switch (fetch) { case WITH_MEMBERS: entityGraph = em.getEntityGraph(Squad.GRAPH_MEMBERS); query.setHint(LOADGRAPH, entityGraph); break; case SQUAD_ONLY: default: break; } return query.getResultList(); } public <T extends Squad> T createSquad(T squad) { if (squad == null) { return squad; } em.persist(squad); return squad; } public <T extends Squad> T updateSquad(T squad) { if (squad == null) { return null; } em.detach(squad); // Was the object deleted competitive? Squad tmp = findSquadById(squad.getId(), FetchType.SQUAD_ONLY); if (tmp == null) { throw new ConcurrentDeletedException(squad.getId()); } em.detach(tmp); squad = em.merge(squad); return squad; } public void deleteSquad(Squad squad) { if (squad == null) { return; } deleteSquadById(squad.getId()); } public void deleteSquadById(Long id) { final Squad squad = findSquadById(id, FetchType.SQUAD_ONLY); if (squad == null) { // Squad does not exist or is already deleted return; } em.remove(squad); } }
KrugT/iStatus.report-Server
src/main/java/de/helfenkannjeder/istatus/server/business/SquadService.java
Java
gpl-3.0
2,929
package vivadaylight3.myrmecology.common.item.ant; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import vivadaylight3.myrmecology.api.item.ItemAnt; import vivadaylight3.myrmecology.common.Reference; import vivadaylight3.myrmecology.common.lib.Time; public class AntPlains extends ItemAnt { public AntPlains() { super(); } @Override public String getSpeciesName() { // TODO Auto-generated method stub return "Field Ant"; } @Override public String getSpeciesSubName() { return Reference.ANT_PLAINS_NAME; } @Override public boolean isHillAnt() { // TODO Auto-generated method stub return true; } @Override public int getFertility() { // TODO Auto-generated method stub return 3; } @Override public int getLifetime() { // TODO Auto-generated method stub return Time.getTicksFromMinutes(20); } @Override public boolean eatsSweet() { return true; } @Override public boolean eatsSavoury() { // TODO Auto-generated method stub return true; } @Override public boolean eatsMeat() { // TODO Auto-generated method stub return true; } @Override public boolean eatsLarvae() { // TODO Auto-generated method stub return true; } @Override public void performBehaviour(World world, int x, int y, int z) { } @Override public String getSpeciesBinomialName() { // TODO Auto-generated method stub return "Antus Fieldia"; } @Override public BiomeGenBase[] getAntBiomes() { BiomeGenBase[] biomes = new BiomeGenBase[] { BiomeGenBase.extremeHills, BiomeGenBase.extremeHillsEdge, BiomeGenBase.plains }; return biomes; } @Override public boolean getWinged() { return false; } @Override public boolean getNocturnal() { return true; } @Override public int[] getColours() { return new int[] { 0x162308, 0x406618 }; } }
SamTebbs33/myrmecology
src/minecraft/vivadaylight3/myrmecology/common/item/ant/AntPlains.java
Java
gpl-3.0
1,965
/*===========================================================================*\ * * * OpenFlipper * * Copyright (C) 2001-2014 by Computer Graphics Group, RWTH Aachen * * www.openflipper.org * * * *--------------------------------------------------------------------------- * * This file is part of OpenFlipper. * * * * OpenFlipper 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 with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenFlipper 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 LesserGeneral Public * * License along with OpenFlipper. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision$ * * $LastChangedBy$ * * $Date$ * * * \*===========================================================================*/ #include "TreeItem.hh" //-------------------------------------------------------------------------------- TreeItem::TreeItem(int _id, QString _name, DataType _type, TreeItem* _parent) : id_(_id), dataType_(_type), visible_(true), name_(_name), parentItem_(_parent) { } // =============================================================================== // Static Members // =============================================================================== int TreeItem::id() { return id_; } //-------------------------------------------------------------------------------- bool TreeItem::dataType(DataType _type) { if ( _type == DATA_ALL ) { return true; } return ( (dataType_ & _type) ); } //-------------------------------------------------------------------------------- DataType TreeItem::dataType() { return dataType_; } //-------------------------------------------------------------------------------- int TreeItem::group() { // Skip root node if ( parent() == 0 ) return -1; // Dont count root node as a group if ( parent()->parent() == 0 ) return -1; // Only consider groups if ( !parent()->dataType(DATA_GROUP) ) return -1; // Get the group id return ( parent()->id() ); } //-------------------------------------------------------------------------------- bool TreeItem::isGroup() { return ( dataType(DATA_GROUP) ); } // =============================================================================== // Dynamic Members // =============================================================================== bool TreeItem::visible() { return visible_; } //-------------------------------------------------------------------------------- void TreeItem::visible(bool _visible) { visible_ = _visible; } //-------------------------------------------------------------------------------- QString TreeItem::name() { return name_; } //-------------------------------------------------------------------------------- void TreeItem::name(QString _name ) { name_ = _name; } // =============================================================================== // Tree Structure // =============================================================================== TreeItem* TreeItem::next() { // Visit child item of this node if ( childItems_.size() > 0 ) { return childItems_[0]; } // No Child Item so visit the next child of the parentItem_ if ( parentItem_ ) { TreeItem* parentPointer = parentItem_; TreeItem* thisPointer = this; // while we are not at the root node while ( parentPointer ) { // If there is an unvisited child of the parent, return this one if ( parentPointer->childCount() > ( thisPointer->row() + 1) ) { return parentPointer->childItems_[ thisPointer->row() + 1 ]; } // Go to the next level thisPointer = parentPointer; parentPointer = parentPointer->parentItem_; } return thisPointer; } return this; } //-------------------------------------------------------------------------------- int TreeItem::level() { int level = 0; TreeItem* current = this; // Go up and count the levels to the root node while ( current->parent() != 0 ) { level++; current = current->parent(); } return level; } //-------------------------------------------------------------------------------- int TreeItem::row() const { if (parentItem_) return parentItem_->childItems_.indexOf(const_cast<TreeItem*>(this)); return 0; } //-------------------------------------------------------------------------------- TreeItem* TreeItem::parent() { return parentItem_; } //-------------------------------------------------------------------------------- void TreeItem::setParent(TreeItem* _parent) { parentItem_ = _parent; } //-------------------------------------------------------------------------------- void TreeItem::appendChild(TreeItem *item) { childItems_.append(item); } //-------------------------------------------------------------------------------- TreeItem *TreeItem::child(int row) { return childItems_.value(row); } //-------------------------------------------------------------------------------- int TreeItem::childCount() const { return childItems_.count(); } //-------------------------------------------------------------------------------- TreeItem* TreeItem::childExists(int _objectId) { // Check if this object has the requested id if ( id_ == _objectId ) return this; // search in children for ( int i = 0 ; i < childItems_.size(); ++i ) { TreeItem* tmp = childItems_[i]->childExists(_objectId); if ( tmp != 0) return tmp; } return 0; } //-------------------------------------------------------------------------------- TreeItem* TreeItem::childExists(QString _name) { // Check if this object has the requested id if ( name() == _name ) return this; // search in children for ( int i = 0 ; i < childItems_.size(); ++i ) { TreeItem* tmp = childItems_[i]->childExists(_name); if ( tmp != 0) return tmp; } return 0; } //-------------------------------------------------------------------------------- void TreeItem::removeChild( TreeItem* _item ) { bool found = false; QList<TreeItem*>::iterator i; for (i = childItems_.begin(); i != childItems_.end(); ++i) { if ( *i == _item ) { found = true; break; } } if ( !found ) { std::cerr << "TreeItem: Illegal remove request" << std::endl; return; } childItems_.erase(i); } //-------------------------------------------------------------------------------- QList< TreeItem* > TreeItem::getLeafs() { QList< TreeItem* > items; for ( int i = 0 ; i < childItems_.size(); ++i ) { items = items + childItems_[i]->getLeafs(); } // If we are a leave... if ( childCount() == 0 ) items.push_back(this); return items; } //-------------------------------------------------------------------------------- void TreeItem::deleteSubtree() { // call function for all children of this node for ( int i = 0 ; i < childItems_.size(); ++i) { // remove the subtree recursively childItems_[i]->deleteSubtree(); // delete child delete childItems_[i]; } // clear the array childItems_.clear(); } //=============================================================================
heartvalve/OpenFlipper
Plugin-VSI/types/objectId/TreeItem.cc
C++
gpl-3.0
9,535
/* * Controllable.cpp * * This file is part of the IHMC DisService Library/Component * Copyright (c) 2006-2016 IHMC. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 (GPLv3) as published by the Free Software Foundation. * * U.S. Government agencies and organizations may redistribute * and/or modify this program under terms equivalent to * "Government Purpose Rights" as defined by DFARS * 252.227-7014(a)(12) (February 2014). * * Alternative licenses that allow for use within commercial products may be * available. Contact Niranjan Suri at IHMC (nsuri@ihmc.us) for details. */ #include "Controllable.h" using namespace IHMC_ACI; using namespace NOMADSUtil; Controllable::Controllable() : _m (6) { _bLockReleased = true; } Controllable::~Controllable() { } void Controllable::lock() { _m.lock (12); } void Controllable::unlock() { _m.unlock (12); }
ihmc/nomads
aci/cpp/DisService/Controllable.cpp
C++
gpl-3.0
983
using System; using System.Globalization; using System.Text; using NReco.PdfGenerator; using SmartStore.Core.Logging; using SmartStore.Utilities; namespace SmartStore.Services.Pdf { public class WkHtmlToPdfConverter : IPdfConverter { public WkHtmlToPdfConverter() { Logger = NullLogger.Instance; } public ILogger Logger { get; set; } public byte[] Convert(PdfConvertSettings settings) { Guard.NotNull(settings, nameof(settings)); if (settings.Page == null) { throw Error.InvalidOperation("The 'Page' property of the 'settings' argument cannot be null."); } try { var converter = CreateWkConverter(settings); var input = settings.Page.Process("page"); if (settings.Page.Kind == PdfContentKind.Url) { return converter.GeneratePdfFromFile(input, null); } else { return converter.GeneratePdf(input, null); } } catch (Exception ex) { Logger.Error(ex, "Html to Pdf conversion error"); throw; } finally { TeardownContent(settings.Cover); TeardownContent(settings.Footer); TeardownContent(settings.Header); TeardownContent(settings.Page); } } private void TeardownContent(IPdfContent content) { if (content != null) content.Teardown(); } internal HtmlToPdfConverter CreateWkConverter(PdfConvertSettings settings) { // Global options var converter = new HtmlToPdfConverter { Grayscale = settings.Grayscale, LowQuality = settings.LowQuality, Orientation = (PageOrientation)(int)settings.Orientation, PageHeight = settings.PageHeight, PageWidth = settings.PageWidth, Size = (PageSize)(int)settings.Size, PdfToolPath = FileSystemHelper.TempDir("wkhtmltopdf") }; if (settings.Margins != null) { converter.Margins.Bottom = settings.Margins.Bottom; converter.Margins.Left = settings.Margins.Left; converter.Margins.Right = settings.Margins.Right; converter.Margins.Top = settings.Margins.Top; } var sb = new StringBuilder(settings.CustomFlags); // doc title if (settings.Title.HasValue()) { sb.AppendFormat(CultureInfo.CurrentCulture, " --title \"{0}\"", settings.Title); } // Cover content & options if (settings.Cover != null) { var path = settings.Cover.Process("cover"); if (path.HasValue()) { sb.AppendFormat(" cover \"{0}\" ", path); settings.Cover.WriteArguments("cover", sb); if (settings.CoverOptions != null) { settings.CoverOptions.Process("cover", sb); } } } // Toc options if (settings.TocOptions != null && settings.TocOptions.Enabled) { settings.TocOptions.Process("toc", sb); } // apply cover & toc converter.CustomWkHtmlArgs = sb.ToString().Trim().NullEmpty(); sb.Clear(); // Page options if (settings.PageOptions != null) { settings.PageOptions.Process("page", sb); } // Header content & options if (settings.Header != null) { var path = settings.Header.Process("header"); if (path.HasValue()) { sb.AppendFormat(" --header-html \"{0}\"", path); settings.Header.WriteArguments("header", sb); } } if (settings.HeaderOptions != null && (settings.Header != null || settings.HeaderOptions.HasText)) { settings.HeaderOptions.Process("header", sb); } // Footer content & options if (settings.Footer != null) { var path = settings.Footer.Process("footer"); if (path.HasValue()) { sb.AppendFormat(" --footer-html \"{0}\"", path); settings.Footer.WriteArguments("footer", sb); } } if (settings.FooterOptions != null && (settings.Footer != null || settings.FooterOptions.HasText)) { settings.FooterOptions.Process("footer", sb); } // apply settings converter.CustomWkHtmlPageArgs = sb.ToString().Trim().NullEmpty(); return converter; } } }
mfalkao/SmartStoreNET
src/Libraries/SmartStore.Services/Pdf/WkHtmlToPdfConverter.cs
C#
gpl-3.0
3,899
turingApp.controller('TurConverseTrainingListCtrl', [ "$scope", "$filter", "turConverseTrainingResource", function ($scope, $filter, turConverseTrainingResource) { $scope.conversations = turConverseTrainingResource.query( function() { $scope.conversations = $filter('orderBy')($scope.conversations, '-date'); }); }]);
openviglet/turing
src/main/resources/public/js/build/extract/feature/converse/training/TurConverseTrainingListCtrl.js
JavaScript
gpl-3.0
373
import curses import datetime import itertools import sys import time from tabulate import tabulate from Brick.sockserver import SockClient def build_info(client): headers = ["SID", "CONF", "BOOT", "TERM", "TIME", "STATE", "CPU%", "MEM%", "TASK", "NQ", "QUEUE"] table = [] res = [] for status in client.get_status(): sid, conf, st, ft, status, current_task, queue, cpu, memory = status nq = len(queue) if nq > 5: queue = str(queue[:5])[:-1] + "...]" st = datetime.datetime.fromtimestamp(st) if ft: ft = datetime.datetime.fromtimestamp(ft) rt = ft - st else: rt = datetime.datetime.now() - st rt -= datetime.timedelta(microseconds=rt.microseconds) st = st.strftime("%Y-%m-%d %H:%M:%S") ft = ft.strftime("%Y-%m-%d %H:%M:%S") if ft else "Running" res.append([sid, conf, st, ft, rt, status, cpu, memory, current_task, nq, queue]) work = sorted([x for x in res if x[3] == "Running"], key=lambda x: x[0]) idle = sorted([y for y in res if y[3] != "Running"], key=lambda x: x[0]) for item in itertools.chain(work, idle): table.append(item) return tabulate(table, headers=headers, tablefmt="psql") def list_status(): port = int(sys.argv[1]) client = SockClient(("localhost", port)) print build_info(client) def brick_top(): port = int(sys.argv[1]) client = SockClient(("localhost", port)) def output(window): curses.use_default_colors() while True: window.clear() window.addstr(build_info(client)) window.refresh() time.sleep(1) curses.wrapper(output)
Tefx/Brick
Brick/tools.py
Python
gpl-3.0
1,716
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2020 Canonical Ltd * * This program 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package daemon import ( "net/http" "time" . "gopkg.in/check.v1" "github.com/snapcore/snapd/overlord/state" ) var _ = Suite(&seedingDebugSuite{}) type seedingDebugSuite struct { apiBaseSuite } func (s *seedingDebugSuite) SetUpTest(c *C) { s.apiBaseSuite.SetUpTest(c) s.daemonWithOverlordMock(c) } func (s *seedingDebugSuite) getSeedingDebug(c *C) interface{} { req, err := http.NewRequest("GET", "/v2/debug?aspect=seeding", nil) c.Assert(err, IsNil) rsp := getDebug(debugCmd, req, nil).(*resp) c.Assert(rsp.Type, Equals, ResponseTypeSync) return rsp.Result } func (s *seedingDebugSuite) TestNoData(c *C) { data := s.getSeedingDebug(c) c.Check(data, NotNil) c.Check(data, DeepEquals, &seedingInfo{}) } func (s *seedingDebugSuite) TestSeedingDebug(c *C) { seeded := true preseeded := true key1 := "foo" key2 := "bar" preseedStartTime, err := time.Parse(time.RFC3339, "2020-01-01T10:00:00Z") c.Assert(err, IsNil) preseedTime, err := time.Parse(time.RFC3339, "2020-01-01T10:00:01Z") c.Assert(err, IsNil) seedRestartTime, err := time.Parse(time.RFC3339, "2020-01-01T10:00:03Z") c.Assert(err, IsNil) seedTime, err := time.Parse(time.RFC3339, "2020-01-01T10:00:07Z") c.Assert(err, IsNil) st := s.d.overlord.State() st.Lock() st.Set("preseeded", preseeded) st.Set("seeded", seeded) st.Set("preseed-system-key", key1) st.Set("seed-restart-system-key", key2) st.Set("preseed-start-time", preseedStartTime) st.Set("seed-restart-time", seedRestartTime) st.Set("preseed-time", preseedTime) st.Set("seed-time", seedTime) st.Unlock() data := s.getSeedingDebug(c) c.Check(data, DeepEquals, &seedingInfo{ Seeded: true, Preseeded: true, PreseedSystemKey: "foo", SeedRestartSystemKey: "bar", PreseedStartTime: &preseedStartTime, PreseedTime: &preseedTime, SeedRestartTime: &seedRestartTime, SeedTime: &seedTime, }) } func (s *seedingDebugSuite) TestSeedingDebugSeededNoTimes(c *C) { seedTime, err := time.Parse(time.RFC3339, "2020-01-01T10:00:07Z") c.Assert(err, IsNil) st := s.d.overlord.State() st.Lock() // only set seed-time and seeded st.Set("seed-time", seedTime) st.Set("seeded", true) st.Unlock() data := s.getSeedingDebug(c) c.Check(data, DeepEquals, &seedingInfo{ Seeded: true, SeedTime: &seedTime, }) } func (s *seedingDebugSuite) TestSeedingDebugPreseededStillSeeding(c *C) { preseedStartTime, err := time.Parse(time.RFC3339, "2020-01-01T10:00:00Z") c.Assert(err, IsNil) preseedTime, err := time.Parse(time.RFC3339, "2020-01-01T10:00:01Z") c.Assert(err, IsNil) seedRestartTime, err := time.Parse(time.RFC3339, "2020-01-01T10:00:03Z") c.Assert(err, IsNil) st := s.d.overlord.State() st.Lock() st.Set("preseeded", true) st.Set("seeded", false) st.Set("preseed-system-key", "foo") st.Set("seed-restart-system-key", "bar") st.Set("preseed-start-time", preseedStartTime) st.Set("seed-restart-time", seedRestartTime) st.Set("preseed-time", preseedTime) st.Unlock() data := s.getSeedingDebug(c) c.Check(data, DeepEquals, &seedingInfo{ Seeded: false, Preseeded: true, PreseedSystemKey: "foo", SeedRestartSystemKey: "bar", PreseedStartTime: &preseedStartTime, PreseedTime: &preseedTime, SeedRestartTime: &seedRestartTime, }) } func (s *seedingDebugSuite) TestSeedingDebugPreseededSeedError(c *C) { preseedStartTime, err := time.Parse(time.RFC3339, "2020-01-01T10:00:00Z") c.Assert(err, IsNil) preseedTime, err := time.Parse(time.RFC3339, "2020-01-01T10:00:01Z") c.Assert(err, IsNil) seedRestartTime, err := time.Parse(time.RFC3339, "2020-01-01T10:00:03Z") c.Assert(err, IsNil) st := s.d.overlord.State() st.Lock() st.Set("preseeded", true) st.Set("seeded", false) st.Set("preseed-system-key", "foo") st.Set("seed-restart-system-key", "bar") st.Set("preseed-start-time", preseedStartTime) st.Set("seed-restart-time", seedRestartTime) st.Set("preseed-time", preseedTime) chg1 := st.NewChange("seed", "tentative 1") t11 := st.NewTask("seed task", "t11") t12 := st.NewTask("seed task", "t12") chg1.AddTask(t11) chg1.AddTask(t12) t11.SetStatus(state.UndoneStatus) t11.Errorf("t11: undone") t12.SetStatus(state.ErrorStatus) t12.Errorf("t12: fail") // ensure different spawn time time.Sleep(50 * time.Millisecond) chg2 := st.NewChange("seed", "tentative 2") t21 := st.NewTask("seed task", "t21") chg2.AddTask(t21) t21.SetStatus(state.ErrorStatus) t21.Errorf("t21: error") chg3 := st.NewChange("seed", "tentative 3") t31 := st.NewTask("seed task", "t31") chg3.AddTask(t31) t31.SetStatus(state.DoingStatus) st.Unlock() data := s.getSeedingDebug(c) c.Check(data, DeepEquals, &seedingInfo{ Seeded: false, Preseeded: true, PreseedSystemKey: "foo", SeedRestartSystemKey: "bar", PreseedStartTime: &preseedStartTime, PreseedTime: &preseedTime, SeedRestartTime: &seedRestartTime, SeedError: `cannot perform the following tasks: - t12 (t12: fail)`, }) }
jdstrand/snapd
daemon/api_debug_seeding_test.go
GO
gpl-3.0
5,750
from .conftest import decode_response YARA_TEST_RULE = 'rule rulename {strings: $a = "foobar" condition: $a}' def test_no_data(test_app): result = decode_response(test_app.post('/rest/binary_search')) assert 'Input payload validation failed' in result['message'] assert 'errors' in result assert 'is a required property' in result['errors']['rule_file'] def test_no_rule_file(test_app): result = decode_response(test_app.post('/rest/binary_search', json=dict())) assert 'Input payload validation failed' in result['message'] assert 'errors' in result assert '\'rule_file\' is a required property' in result['errors']['rule_file'] def test_wrong_rule_file_format(test_app): result = decode_response(test_app.post('/rest/binary_search', json={'rule_file': 'not an actual rule file'})) assert 'Error in YARA rule file' in result['error_message'] def test_firmware_uid_not_found(test_app): data = {'rule_file': YARA_TEST_RULE, 'uid': 'not found'} result = decode_response(test_app.post('/rest/binary_search', json=data)) assert 'not found in database' in result['error_message'] def test_start_binary_search(test_app): result = decode_response(test_app.post('/rest/binary_search', json={'rule_file': YARA_TEST_RULE})) assert 'Started binary search' in result['message'] def test_start_binary_search_with_uid(test_app): data = {'rule_file': YARA_TEST_RULE, 'uid': 'uid_in_db'} result = decode_response(test_app.post('/rest/binary_search', json=data)) assert 'Started binary search' in result['message'] def test_get_result_without_search_id(test_app): result = decode_response(test_app.get('/rest/binary_search')) assert 'The method is not allowed for the requested URL' in result['message'] def test_get_result_non_existent_id(test_app): result = decode_response(test_app.get('/rest/binary_search/foobar')) assert 'result is not ready yet' in result['error_message']
fkie-cad/FACT_core
src/test/unit/web_interface/rest/test_rest_binary_search.py
Python
gpl-3.0
1,968
package com.library.app.order.services; import com.library.app.DateUtils; import static com.library.app.author.AuthorForTestsRepository.allAuthors; import static com.library.app.book.BookForTestsRepository.allBooks; import static com.library.app.book.BookForTestsRepository.normalizeDependencies; import static com.library.app.category.CategoryForTestsRepository.allCategories; import com.library.app.commontests.utils.ArquillianTestUtils; import com.library.app.commontests.utils.TestRepositoryEJB; import com.library.app.order.OrderForTestsRepository; import static com.library.app.order.OrderForTestsRepository.orderReserved; import com.library.app.order.model.Order; import com.library.app.order.model.Order.OrderStatus; import com.library.app.order.model.OrderFilter; import com.library.app.order.services.impl.OrderExpiratorJob; import com.library.app.pagination.PaginatedData; import static com.library.app.user.UserForTestsRepository.allUsers; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; import org.jboss.shrinkwrap.api.spec.WebArchive; import static org.junit.Assert.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) public class OrderExpirationJobIntTest { @Inject private OrderExpiratorJob orderExpiratorJob; @Inject private OrderServices orderServices; @Inject private TestRepositoryEJB testRepositoryEJB; @PersistenceContext private EntityManager em; @Deployment public static WebArchive createDeployment(){ return ArquillianTestUtils.createDeploymentArchive(); } @Test @InSequence(1) public void prepareOrderForTest() { testRepositoryEJB.deleteAll(); allCategories().forEach(testRepositoryEJB::add); allAuthors().forEach(testRepositoryEJB::add); allBooks().forEach((book) -> testRepositoryEJB.add(normalizeDependencies(book, em))); allUsers().forEach(testRepositoryEJB::add); final Order orderReservedToBeExpired = orderReserved(); orderReservedToBeExpired.setCreatedAt(DateUtils.currentDatePlusDays(-8)); final Order orderReserved = orderReserved(); testRepositoryEJB.add(OrderForTestsRepository.normalizeDependencies(orderReservedToBeExpired, em)); testRepositoryEJB.add(OrderForTestsRepository.normalizeDependencies(orderReserved, em)); } @Test @InSequence(2) public void runJob(){ assertNumberOfOrdersWithStatus(2, OrderStatus.RESERVED); assertNumberOfOrdersWithStatus(0, OrderStatus.RESERVATION_EXPIRED); orderExpiratorJob.run(); assertNumberOfOrdersWithStatus(1, OrderStatus.RESERVED); assertNumberOfOrdersWithStatus(1, OrderStatus.RESERVATION_EXPIRED); } private void assertNumberOfOrdersWithStatus(final int expectedTotalRecords, final OrderStatus status) { final OrderFilter orderFilter = new OrderFilter(); orderFilter.setStatus(status); final PaginatedData<Order> orders = orderServices.findByFilter(orderFilter); assertThat(orders.getNumberOfRows(), is(equalTo(expectedTotalRecords))); } }
DarkoDoko/library-javaee-example
library-app/library-integration-tests/src/test/java/com/library/app/order/services/OrderExpirationJobIntTest.java
Java
gpl-3.0
3,372
/*! * @copyright &copy; Kartik Visweswaran, Krajee.com, 2013 - 2016 * @version 4.0.1 * * A simple yet powerful JQuery star rating plugin that allows rendering fractional star ratings and supports * Right to Left (RTL) input. * * For more JQuery plugins visit http://plugins.krajee.com * For more Yii related demos visit http://demos.krajee.com */ (function (factory) { "use strict"; if (typeof define === 'function' && define.amd) { // jshint ignore:line // AMD. Register as an anonymous module. define(['jquery'], factory); // jshint ignore:line } else { // noinspection JSUnresolvedVariable if (typeof module === 'object' && module.exports) { // jshint ignore:line // Node/CommonJS // noinspection JSUnresolvedVariable module.exports = factory(require('jquery')); // jshint ignore:line } else { // Browser globals factory(window.jQuery); } } }(function ($) { "use strict"; $.fn.ratingLocales = {}; var NAMESPACE, DEFAULT_MIN, DEFAULT_MAX, DEFAULT_STEP, isEmpty, getCss, addCss, getDecimalPlaces, applyPrecision, handler, Rating; NAMESPACE = '.rating'; DEFAULT_MIN = 0; DEFAULT_MAX = 5; DEFAULT_STEP = 0.5; isEmpty = function (value, trim) { return value === null || value === undefined || value.length === 0 || (trim && $.trim(value) === ''); }; getCss = function (condition, css) { return condition ? ' ' + css : ''; }; addCss = function ($el, css) { $el.removeClass(css).addClass(css); }; getDecimalPlaces = function (num) { var match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); return !match ? 0 : Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0)); }; applyPrecision = function (val, precision) { return parseFloat(val.toFixed(precision)); }; handler = function ($el, event, callback, skipNS) { var ev = skipNS ? event : event.split(' ').join(NAMESPACE + ' ') + NAMESPACE; $el.off(ev).on(ev, callback); }; Rating = function (element, options) { var self = this; self.$element = $(element); self._init(options); }; Rating.prototype = { constructor: Rating, _parseAttr: function (vattr, options) { var self = this, $el = self.$element, elType = $el.attr('type'), finalVal, val, chk, out; if (elType === 'range' || elType === 'number') { val = options[vattr] || $el.data(vattr) || $el.attr(vattr); switch (vattr) { case 'min': chk = DEFAULT_MIN; break; case 'max': chk = DEFAULT_MAX; break; default: chk = DEFAULT_STEP; } finalVal = isEmpty(val) ? chk : val; out = parseFloat(finalVal); } else { out = parseFloat(options[vattr]); } return isNaN(out) ? chk : out; }, _setDefault: function (key, val) { var self = this; if (isEmpty(self[key])) { self[key] = val; } }, _listenClick: function (e, callback) { e.stopPropagation(); e.preventDefault(); if (e.handled !== true) { callback(e); e.handled = true; } else { return false; } }, _starClick: function (e) { var self = this, pos; self._listenClick(e, function (ev) { if (self.inactive) { return false; } pos = self._getTouchPosition(ev); self._setStars(pos); self.$element.trigger('change').trigger('rating.change', [self.$element.val(), self._getCaption()]); self.starClicked = true; }); }, _starMouseMove: function (e) { var self = this, pos, out; if (!self.hoverEnabled || self.inactive || (e && e.isDefaultPrevented())) { return; } self.starClicked = false; pos = self._getTouchPosition(e); out = self.calculate(pos); self._toggleHover(out); self.$element.trigger('rating.hover', [out.val, out.caption, 'stars']); }, _starMouseLeave: function (e) { var self = this, out; if (!self.hoverEnabled || self.inactive || self.starClicked || (e && e.isDefaultPrevented())) { return; } out = self.cache; self._toggleHover(out); self.$element.trigger('rating.hoverleave', ['stars']); }, _clearClick: function (e) { var self = this; self._listenClick(e, function () { if (!self.inactive) { self.clear(); self.clearClicked = true; } }); }, _clearMouseMove: function (e) { var self = this, caption, val, width, out; if (!self.hoverEnabled || self.inactive || !self.hoverOnClear || (e && e.isDefaultPrevented())) { return; } self.clearClicked = false; caption = '<span class="' + self.clearCaptionClass + '">' + self.clearCaption + '</span>'; val = self.clearValue; width = self.getWidthFromValue(val) || 0; out = {caption: caption, width: width, val: val}; self._toggleHover(out); self.$element.trigger('rating.hover', [val, caption, 'clear']); }, _clearMouseLeave: function (e) { var self = this, out; if (!self.hoverEnabled || self.inactive || self.clearClicked || !self.hoverOnClear || (e && e.isDefaultPrevented())) { return; } out = self.cache; self._toggleHover(out); self.$element.trigger('rating.hoverleave', ['clear']); }, _resetForm: function (e) { var self = this; if (e && e.isDefaultPrevented()) { return; } if (!self.inactive) { self.reset(); } }, _setTouch: function (e, flag) { //noinspection JSUnresolvedVariable var self = this, ev, touches, pos, out, caption, w, width, isTouchCapable = 'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch); if (!isTouchCapable || self.inactive) { return; } ev = e.originalEvent; //noinspection JSUnresolvedVariable touches = !isEmpty(ev.touches) ? ev.touches : ev.changedTouches; pos = self._getTouchPosition(touches[0]); if (flag) { self._setStars(pos); self.$element.trigger('change').trigger('rating.change', [self.$element.val(), self._getCaption()]); self.starClicked = true; } else { out = self.calculate(pos); caption = out.val <= self.clearValue ? self.fetchCaption(self.clearValue) : out.caption; w = self.getWidthFromValue(self.clearValue); width = out.val <= self.clearValue ? w + '%' : out.width; self._setCaption(caption); self.$filledStars.css('width', width); } }, _initTouch: function (e) { var self = this, flag = (e.type === "touchend"); self._setTouch(e, flag); }, _initSlider: function (options) { var self = this; if (isEmpty(self.$element.val())) { self.$element.val(0); } self.initialValue = self.$element.val(); self._setDefault('min', self._parseAttr('min', options)); self._setDefault('max', self._parseAttr('max', options)); self._setDefault('step', self._parseAttr('step', options)); if (isNaN(self.min) || isEmpty(self.min)) { self.min = DEFAULT_MIN; } if (isNaN(self.max) || isEmpty(self.max)) { self.max = DEFAULT_MAX; } if (isNaN(self.step) || isEmpty(self.step) || self.step === 0) { self.step = DEFAULT_STEP; } self.diff = self.max - self.min; }, _initHighlight: function (v) { var self = this, w, cap = self._getCaption(); if (!v) { v = self.$element.val(); } w = self.getWidthFromValue(v) + '%'; self.$filledStars.width(w); self.cache = {caption: cap, width: w, val: v}; }, _getContainerCss: function () { var self = this; return 'rating-container' + getCss(self.theme, 'theme-' + self.theme) + getCss(self.rtl, 'rating-rtl') + getCss(self.size, 'rating-' + self.size) + getCss(self.animate, 'rating-animate') + getCss(self.disabled || self.readonly, 'rating-disabled') + getCss(self.containerClass, self.containerClass); }, _checkDisabled: function () { var self = this, $el = self.$element, opts = self.options; self.disabled = opts.disabled === undefined ? $el.attr('disabled') || false : opts.disabled; self.readonly = opts.readonly === undefined ? $el.attr('readonly') || false : opts.readonly; self.inactive = (self.disabled || self.readonly); $el.attr({disabled: self.disabled, readonly: self.readonly}); }, _addContent: function (type, content) { var self = this, $container = self.$container, isClear = type === 'clear'; if (self.rtl) { return isClear ? $container.append(content) : $container.prepend(content); } else { return isClear ? $container.prepend(content) : $container.append(content); } }, _generateRating: function () { var self = this, $el = self.$element, $rating, $container, w; $container = self.$container = $(document.createElement("div")).insertBefore($el); addCss($container, self._getContainerCss()); self.$rating = $rating = $(document.createElement("div")).attr('class', 'rating').appendTo($container) .append(self._getStars('empty')).append(self._getStars('filled')); self.$emptyStars = $rating.find('.empty-stars'); self.$filledStars = $rating.find('.filled-stars'); self._renderCaption(); self._renderClear(); self._initHighlight(); $container.append($el); if (self.rtl) { w = Math.max(self.$emptyStars.outerWidth(), self.$filledStars.outerWidth()); self.$emptyStars.width(w); } }, _getCaption: function () { var self = this; return self.$caption && self.$caption.length ? self.$caption.html() : self.defaultCaption; }, _setCaption: function (content) { var self = this; if (self.$caption && self.$caption.length) { self.$caption.html(content); } }, _renderCaption: function () { var self = this, val = self.$element.val(), html, $cap = self.captionElement ? $(self.captionElement) : ''; if (!self.showCaption) { return; } html = self.fetchCaption(val); if ($cap && $cap.length) { addCss($cap, 'caption'); $cap.html(html); self.$caption = $cap; return; } self._addContent('caption', '<div class="caption">' + html + '</div>'); self.$caption = self.$container.find(".caption"); }, _renderClear: function () { var self = this, css, $clr = self.clearElement ? $(self.clearElement) : ''; if (!self.showClear) { return; } css = self._getClearClass(); if ($clr.length) { addCss($clr, css); $clr.attr({"title": self.clearButtonTitle}).html(self.clearButton); self.$clear = $clr; return; } self._addContent('clear', '<div class="' + css + '" title="' + self.clearButtonTitle + '">' + self.clearButton + '</div>'); self.$clear = self.$container.find('.' + self.clearButtonBaseClass); }, _getClearClass: function () { return this.clearButtonBaseClass + ' ' + ((this.inactive) ? '' : this.clearButtonActiveClass); }, _getTouchPosition: function (e) { var pageX = isEmpty(e.pageX) ? e.originalEvent.touches[0].pageX : e.pageX; return pageX - this.$rating.offset().left; }, _toggleHover: function (out) { var self = this, w, width, caption; if (!out) { return; } if (self.hoverChangeStars) { w = self.getWidthFromValue(self.clearValue); width = out.val <= self.clearValue ? w + '%' : out.width; self.$filledStars.css('width', width); } if (self.hoverChangeCaption) { caption = out.val <= self.clearValue ? self.fetchCaption(self.clearValue) : out.caption; if (caption) { self._setCaption(caption + ''); } } }, _init: function (options) { var self = this, $el = self.$element.addClass('hide'); self.options = options; $.each(options, function (key, value) { self[key] = value; }); if (self.rtl || $el.attr('dir') === 'rtl') { self.rtl = true; $el.attr('dir', 'rtl'); } self.starClicked = false; self.clearClicked = false; self._initSlider(options); self._checkDisabled(); if (self.displayOnly) { self.inactive = true; self.showClear = false; self.showCaption = false; } self._generateRating(); self._listen(); return $el.removeClass('rating-loading'); }, _listen: function () { var self = this, $el = self.$element, $form = $el.closest('form'), $rating = self.$rating, $clear = self.$clear; handler($rating, 'touchstart touchmove touchend', $.proxy(self._initTouch, self)); handler($rating, 'click touchstart', $.proxy(self._starClick, self)); handler($rating, 'mousemove', $.proxy(self._starMouseMove, self)); handler($rating, 'mouseleave', $.proxy(self._starMouseLeave, self)); if (self.showClear && $clear.length) { handler($clear, 'click touchstart', $.proxy(self._clearClick, self)); handler($clear, 'mousemove', $.proxy(self._clearMouseMove, self)); handler($clear, 'mouseleave', $.proxy(self._clearMouseLeave, self)); } if ($form.length) { handler($form, 'reset', $.proxy(self._resetForm, self)); } return $el; }, _getStars: function (type) { var self = this, stars = '<span class="' + type + '-stars">', i; for (i = 1; i <= self.stars; i++) { stars += '<span class="star">' + self[type + 'Star'] + '</span>'; } return stars + '</span>'; }, _setStars: function (pos) { var self = this, out = arguments.length ? self.calculate(pos) : self.calculate(), $el = self.$element; $el.val(out.val); self.$filledStars.css('width', out.width); self._setCaption(out.caption); self.cache = out; return $el; }, showStars: function (val) { var self = this, v = parseFloat(val); self.$element.val(isNaN(v) ? self.clearValue : v); return self._setStars(); }, calculate: function (pos) { var self = this, defaultVal = isEmpty(self.$element.val()) ? 0 : self.$element.val(), val = arguments.length ? self.getValueFromPosition(pos) : defaultVal, caption = self.fetchCaption(val), width = self.getWidthFromValue(val); width += '%'; return {caption: caption, width: width, val: val}; }, getValueFromPosition: function (pos) { var self = this, precision = getDecimalPlaces(self.step), val, factor, maxWidth = self.$rating.width(); factor = (self.diff * pos) / (maxWidth * self.step); factor = self.rtl ? Math.floor(factor) : Math.ceil(factor); val = applyPrecision(parseFloat(self.min + factor * self.step), precision); val = Math.max(Math.min(val, self.max), self.min); return self.rtl ? (self.max - val) : val; }, getWidthFromValue: function (val) { var self = this, min = self.min, max = self.max, factor, $r = self.$emptyStars, w; if (!val || val <= min || min === max) { return 0; } w = $r.outerWidth(); factor = w ? $r.width() / w : 1; if (val >= max) { return 100; } return (val - min) * factor * 100 / (max - min); }, fetchCaption: function (rating) { var self = this, val = parseFloat(rating) || self.clearValue, css, cap, capVal, cssVal, caption, vCap = self.starCaptions, vCss = self.starCaptionClasses; if (val && val !== self.clearValue) { val = applyPrecision(val, getDecimalPlaces(self.step)); } cssVal = typeof vCss === "function" ? vCss(val) : vCss[val]; capVal = typeof vCap === "function" ? vCap(val) : vCap[val]; cap = isEmpty(capVal) ? self.defaultCaption.replace(/\{rating}/g, val) : capVal; css = isEmpty(cssVal) ? self.clearCaptionClass : cssVal; caption = (val === self.clearValue) ? self.clearCaption : cap; return '<span class="' + css + '">' + caption + '</span>'; }, destroy: function () { var self = this, $el = self.$element; if (!isEmpty(self.$container)) { self.$container.before($el).remove(); } $.removeData($el.get(0)); return $el.off('rating').removeClass('hide'); }, create: function (options) { var self = this, opts = options || self.options || {}; return self.destroy().rating(opts); }, clear: function () { var self = this, title = '<span class="' + self.clearCaptionClass + '">' + self.clearCaption + '</span>'; if (!self.inactive) { self._setCaption(title); } return self.showStars(self.clearValue).trigger('change').trigger('rating.clear'); }, reset: function () { var self = this; return self.showStars(self.initialValue).trigger('rating.reset'); }, update: function (val) { var self = this; return arguments.length ? self.showStars(val) : self.$element; }, refresh: function (options) { var self = this, $el = self.$element; if (!options) { return $el; } return self.destroy().rating($.extend(true, self.options, options)).trigger('rating.refresh'); } }; $.fn.rating = function (option) { var args = Array.apply(null, arguments), retvals = []; args.shift(); this.each(function () { var self = $(this), data = self.data('rating'), options = typeof option === 'object' && option, lang = options.language || self.data('language') || 'en', loc = {}, opts; if (!data) { if (lang !== 'en' && !isEmpty($.fn.ratingLocales[lang])) { loc = $.fn.ratingLocales[lang]; } opts = $.extend(true, {}, $.fn.rating.defaults, $.fn.ratingLocales.en, loc, options, self.data()); data = new Rating(this, opts); self.data('rating', data); } if (typeof option === 'string') { retvals.push(data[option].apply(data, args)); } }); switch (retvals.length) { case 0: return this; case 1: return retvals[0] === undefined ? this : retvals[0]; default: return retvals; } }; $.fn.rating.defaults = { theme: '', language: 'en', stars: 5, filledStar: '<i class="glyphicon glyphicon-star"></i>', emptyStar: '<i class="glyphicon glyphicon-star-empty"></i>', containerClass: '', size: 'md', animate: true, displayOnly: false, rtl: false, showClear: false, showCaption: false, starCaptionClasses: { 0.5: 'label label-danger', 1: 'label label-danger', 1.5: 'label label-warning', 2: 'label label-warning', 2.5: 'label label-info', 3: 'label label-info', 3.5: 'label label-primary', 4: 'label label-primary', 4.5: 'label label-success', 5: 'label label-success' }, clearButton: '<i class="glyphicon glyphicon-minus-sign"></i>', clearButtonBaseClass: 'clear-rating', clearButtonActiveClass: 'clear-rating-active', clearCaptionClass: 'label label-default', clearValue: null, captionElement: null, clearElement: null, hoverEnabled: true, hoverChangeCaption: true, hoverChangeStars: true, hoverOnClear: true }; $.fn.ratingLocales.en = { defaultCaption: '{rating} Stars', starCaptions: { 0.5: 'Half Star', 1: 'One Star', 1.5: 'One & Half Star', 2: 'Two Stars', 2.5: 'Two & Half Stars', 3: 'Three Stars', 3.5: 'Three & Half Stars', 4: 'Four Stars', 4.5: 'Four & Half Stars', 5: 'Five Stars' }, clearButtonTitle: 'Clear', clearCaption: 'Not Rated' }; $.fn.rating.Constructor = Rating; /** * Convert automatically inputs with class 'rating' into Krajee's star rating control. */ $(document).ready(function () { var $input = $('input.rating'); if ($input.length) { $input.removeClass('rating-loading').addClass('rating-loading').rating(); } }); }));
uc-web/CHAMBING
resources/plugins/ratingbar/star-rating.js
JavaScript
gpl-3.0
23,526
# Author: medariox <dariox@gmx.com>, # based on Antoine Bertin's <diaoulael@gmail.com> work # and originally written by Nyaran <nyayukko@gmail.com> # URL: https://github.com/SickRage/SickRage/ # # This file is part of SickRage. # # SickRage 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. # # SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>. import os import re import datetime import traceback import subliminal import subprocess import pkg_resources import sickbeard from subliminal.api import provider_manager from babelfish import Language, language_converters from sickbeard import logger from sickbeard import history from sickbeard import db from sickbeard import processTV from sickrage.helper.common import media_extensions, dateTimeFormat from sickrage.helper.encoding import ek from sickrage.helper.exceptions import ex from sickrage.show.Show import Show DISTRIBUTION = pkg_resources.Distribution(location=os.path.dirname(os.path.dirname(__file__)), project_name='fake_entry_points', version='1.0.0') ENTRY_POINTS = { 'subliminal.providers': [ 'addic7ed = subliminal.providers.addic7ed:Addic7edProvider', 'legendastv = subliminal.providers.legendastv:LegendasTvProvider', 'napiprojekt = subliminal.providers.napiprojekt:NapiProjektProvider', 'opensubtitles = subliminal.providers.opensubtitles:OpenSubtitlesProvider', 'podnapisi = subliminal.providers.podnapisi:PodnapisiProvider', 'thesubdb = subliminal.providers.thesubdb:TheSubDBProvider', 'tvsubtitles = subliminal.providers.tvsubtitles:TVsubtitlesProvider' ], 'babelfish.language_converters': [ 'addic7ed = subliminal.converters.addic7ed:Addic7edConverter', 'legendastv = subliminal.converters.legendastv:LegendasTvConverter', 'thesubdb = subliminal.converters.thesubdb:TheSubDBConverter', 'tvsubtitles = subliminal.converters.tvsubtitles:TVsubtitlesConverter' ] } # pylint: disable=protected-access # Access to a protected member of a client class DISTRIBUTION._ep_map = pkg_resources.EntryPoint.parse_map(ENTRY_POINTS, DISTRIBUTION) pkg_resources.working_set.add(DISTRIBUTION) provider_manager.ENTRY_POINT_CACHE.pop('subliminal.providers') subliminal.region.configure('dogpile.cache.memory') PROVIDER_URLS = { 'addic7ed': 'http://www.addic7ed.com', 'legendastv': 'http://www.legendas.tv', 'napiprojekt': 'http://www.napiprojekt.pl', 'opensubtitles': 'http://www.opensubtitles.org', 'podnapisi': 'http://www.podnapisi.net', 'thesubdb': 'http://www.thesubdb.com', 'tvsubtitles': 'http://www.tvsubtitles.net' } def sorted_service_list(): new_list = [] lmgtfy = 'http://lmgtfy.com/?q=%s' current_index = 0 for current_service in sickbeard.SUBTITLES_SERVICES_LIST: if current_service in subliminal.provider_manager.names(): new_list.append({'name': current_service, 'url': PROVIDER_URLS[current_service] if current_service in PROVIDER_URLS else lmgtfy % current_service, 'image': current_service + '.png', 'enabled': sickbeard.SUBTITLES_SERVICES_ENABLED[current_index] == 1 }) current_index += 1 for current_service in subliminal.provider_manager.names(): if current_service not in [service['name'] for service in new_list]: new_list.append({'name': current_service, 'url': PROVIDER_URLS[current_service] if current_service in PROVIDER_URLS else lmgtfy % current_service, 'image': current_service + '.png', 'enabled': False, }) return new_list def enabled_service_list(): return [service['name'] for service in sorted_service_list() if service['enabled']] def wanted_languages(sql_like=None): wanted = frozenset(sickbeard.SUBTITLES_LANGUAGES).intersection(subtitle_code_filter()) return (wanted, '%' + ','.join(wanted) + '%')[bool(sql_like)] def get_needed_languages(subtitles): return {from_code(language) for language in wanted_languages().difference(subtitles)} def subtitle_code_filter(): return {code for code in language_converters['opensubtitles'].codes if len(code) == 3} def needs_subtitles(subtitles): if isinstance(subtitles, basestring): subtitles = {subtitle.strip() for subtitle in subtitles.split(',')} if sickbeard.SUBTITLES_MULTI: return len(wanted_languages().difference(subtitles)) > 0 else: return len(subtitles) == 0 # Hack around this for now. def from_code(language): language = language.strip() if language not in language_converters['opensubtitles'].codes: return Language('und') return Language.fromopensubtitles(language) # pylint: disable=no-member def name_from_code(code): return from_code(code).name def code_from_code(code): return from_code(code).opensubtitles def download_subtitles(subtitles_info): existing_subtitles = subtitles_info['subtitles'] if not needs_subtitles(existing_subtitles): logger.log(u'Episode already has all needed subtitles, skipping episode %dx%d of show %s' % (subtitles_info['season'], subtitles_info['episode'], subtitles_info['show_name']), logger.DEBUG) return (existing_subtitles, None) # Check if we really need subtitles languages = get_needed_languages(existing_subtitles) if not languages: logger.log(u'No subtitles needed for %s S%02dE%02d' % (subtitles_info['show_name'], subtitles_info['season'], subtitles_info['episode']), logger.DEBUG) return (existing_subtitles, None) subtitles_path = get_subtitles_path(subtitles_info['location']).encode(sickbeard.SYS_ENCODING) video_path = subtitles_info['location'].encode(sickbeard.SYS_ENCODING) video = get_video(video_path, subtitles_path=subtitles_path) if not video: logger.log(u'Exception caught in subliminal.scan_video for %s S%02dE%02d' % (subtitles_info['show_name'], subtitles_info['season'], subtitles_info['episode']), logger.DEBUG) return (existing_subtitles, None) providers = enabled_service_list() provider_configs = {'addic7ed': {'username': sickbeard.ADDIC7ED_USER, 'password': sickbeard.ADDIC7ED_PASS}, 'legendastv': {'username': sickbeard.LEGENDASTV_USER, 'password': sickbeard.LEGENDASTV_PASS}, 'opensubtitles': {'username': sickbeard.OPENSUBTITLES_USER, 'password': sickbeard.OPENSUBTITLES_PASS}} pool = subliminal.api.ProviderPool(providers=providers, provider_configs=provider_configs) try: subtitles_list = pool.list_subtitles(video, languages) if not subtitles_list: logger.log(u'No subtitles found for %s S%02dE%02d on any provider' % (subtitles_info['show_name'], subtitles_info['season'], subtitles_info['episode']), logger.DEBUG) return (existing_subtitles, None) for sub in subtitles_list: matches = sub.get_matches(video, hearing_impaired=False) score = subliminal.subtitle.compute_score(matches, video) logger.log(u"[%s] Subtitle score for %s is: %s (min=132)" % (sub.provider_name, sub.id, score), logger.DEBUG) found_subtitles = pool.download_best_subtitles(subtitles_list, video, languages=languages, min_score=132, hearing_impaired=sickbeard.SUBTITLES_HEARING_IMPAIRED, only_one=not sickbeard.SUBTITLES_MULTI) subliminal.save_subtitles(video, found_subtitles, directory=subtitles_path, single=not sickbeard.SUBTITLES_MULTI) except Exception: logger.log(u"Error occurred when downloading subtitles for: %s" % video_path) logger.log(traceback.format_exc(), logger.ERROR) return (existing_subtitles, None) for subtitle in found_subtitles: subtitle_path = subliminal.subtitle.get_subtitle_path(video.name, None if not sickbeard.SUBTITLES_MULTI else subtitle.language) if subtitles_path is not None: subtitle_path = ek(os.path.join, subtitles_path, ek(os.path.split, subtitle_path)[1]) sickbeard.helpers.chmodAsParent(subtitle_path) sickbeard.helpers.fixSetGroupID(subtitle_path) if (not sickbeard.EMBEDDED_SUBTITLES_ALL and sickbeard.SUBTITLES_EXTRA_SCRIPTS and video_path.rsplit(".", 1)[1] in media_extensions): run_subs_extra_scripts(subtitles_info, found_subtitles, video, single=not sickbeard.SUBTITLES_MULTI) current_subtitles = [subtitle.language.opensubtitles for subtitle in found_subtitles] new_subtitles = frozenset(current_subtitles).difference(existing_subtitles) current_subtitles += existing_subtitles if sickbeard.SUBTITLES_HISTORY: for subtitle in found_subtitles: logger.log(u'history.logSubtitle %s, %s' % (subtitle.provider_name, subtitle.language.opensubtitles), logger.DEBUG) history.logSubtitle(subtitles_info['show_indexerid'], subtitles_info['season'], subtitles_info['episode'], subtitles_info['status'], subtitle) return (current_subtitles, new_subtitles) def refresh_subtitles(episode_info, existing_subtitles): video = get_video(episode_info['location'].encode(sickbeard.SYS_ENCODING)) if not video: logger.log(u"Exception caught in subliminal.scan_video, subtitles couldn't be refreshed", logger.DEBUG) return (existing_subtitles, None) current_subtitles = get_subtitles(video) if existing_subtitles == current_subtitles: logger.log(u'No changed subtitles for %s S%02dE%02d' % (episode_info['show_name'], episode_info['season'], episode_info['episode']), logger.DEBUG) return (existing_subtitles, None) else: return (current_subtitles, True) def get_video(video_path, subtitles_path=None): if not subtitles_path: subtitles_path = get_subtitles_path(video_path).encode(sickbeard.SYS_ENCODING) try: if not sickbeard.EMBEDDED_SUBTITLES_ALL and video_path.endswith('.mkv'): video = subliminal.scan_video(video_path, subtitles=True, embedded_subtitles=True, subtitles_dir=subtitles_path) else: video = subliminal.scan_video(video_path, subtitles=True, embedded_subtitles=False, subtitles_dir=subtitles_path) except Exception: return None return video def get_subtitles_path(video_path): if ek(os.path.isabs, sickbeard.SUBTITLES_DIR): new_subtitles_path = sickbeard.SUBTITLES_DIR elif sickbeard.SUBTITLES_DIR: new_subtitles_path = ek(os.path.join, ek(os.path.dirname, video_path), sickbeard.SUBTITLES_DIR) dir_exists = sickbeard.helpers.makeDir(new_subtitles_path) if not dir_exists: logger.log(u'Unable to create subtitles folder ' + new_subtitles_path, logger.ERROR) else: sickbeard.helpers.chmodAsParent(new_subtitles_path) else: new_subtitles_path = ek(os.path.join, ek(os.path.dirname, video_path)) return new_subtitles_path def get_subtitles(video): """Return a sorted list of detected subtitles for the given video file""" result_list = [] if not video.subtitle_languages: return result_list for language in video.subtitle_languages: if hasattr(language, 'opensubtitles') and language.opensubtitles: result_list.append(language.opensubtitles) return sorted(result_list) class SubtitlesFinder(object): """ The SubtitlesFinder will be executed every hour but will not necessarly search and download subtitles. Only if the defined rule is true """ def __init__(self): self.amActive = False @staticmethod def subtitles_download_in_pp(): # pylint: disable=too-many-locals logger.log(u'Checking for needed subtitles in Post-Process folder', logger.INFO) providers = enabled_service_list() provider_configs = {'addic7ed': {'username': sickbeard.ADDIC7ED_USER, 'password': sickbeard.ADDIC7ED_PASS}, 'legendastv': {'username': sickbeard.LEGENDASTV_USER, 'password': sickbeard.LEGENDASTV_PASS}, 'opensubtitles': {'username': sickbeard.OPENSUBTITLES_USER, 'password': sickbeard.OPENSUBTITLES_PASS}} pool = subliminal.api.ProviderPool(providers=providers, provider_configs=provider_configs) # Search for all wanted languages languages = {from_code(language) for language in wanted_languages()} if not languages: return run_post_process = False # Check if PP folder is set if sickbeard.TV_DOWNLOAD_DIR and ek(os.path.isdir, sickbeard.TV_DOWNLOAD_DIR): for root, _, files in ek(os.walk, sickbeard.TV_DOWNLOAD_DIR, topdown=False): for video_filename in sorted(files): if video_filename.rsplit(".", 1)[1] in media_extensions: try: video = subliminal.scan_video(os.path.join(root, video_filename), subtitles=False, embedded_subtitles=False) subtitles_list = pool.list_subtitles(video, languages) if not subtitles_list: logger.log(u'No subtitles found for %s' % ek(os.path.join, root, video_filename), logger.DEBUG) continue hearing_impaired = sickbeard.SUBTITLES_HEARING_IMPAIRED found_subtitles = pool.download_best_subtitles(subtitles_list, video, languages=languages, hearing_impaired=hearing_impaired, min_score=132, only_one=not sickbeard.SUBTITLES_MULTI) for sub in subtitles_list: matches = sub.get_matches(video, hearing_impaired=False) score = subliminal.subtitle.compute_score(matches, video) logger.log(u"[%s] Subtitle score for %s is: %s (min=132)" % (sub.provider_name, sub.id, score), logger.DEBUG) downloaded_languages = set() for subtitle in found_subtitles: logger.log(u"Found subtitle for %s in %s provider with language %s" % (os.path.join(root, video_filename), subtitle.provider_name, subtitle.language.opensubtitles), logger.DEBUG) subliminal.save_subtitles(video, found_subtitles, directory=root, single=not sickbeard.SUBTITLES_MULTI) subtitles_multi = not sickbeard.SUBTITLES_MULTI subtitle_path = subliminal.subtitle.get_subtitle_path(video.name, None if subtitles_multi else subtitle.language) if root is not None: subtitle_path = ek(os.path.join, root, ek(os.path.split, subtitle_path)[1]) sickbeard.helpers.chmodAsParent(subtitle_path) sickbeard.helpers.fixSetGroupID(subtitle_path) downloaded_languages.add(subtitle.language.opensubtitles) # Don't run post processor unless at least one file has all of the needed subtitles if not needs_subtitles(downloaded_languages): run_post_process = True except Exception as error: logger.log(u"Error occurred when downloading subtitles for: %s. Error: %r" % (os.path.join(root, video_filename), ex(error))) if run_post_process: logger.log(u"Starting post-process with default settings now that we found subtitles") processTV.processDir(sickbeard.TV_DOWNLOAD_DIR) def run(self, force=False): # pylint: disable=unused-argument if not sickbeard.USE_SUBTITLES: return if len(sickbeard.subtitles.enabled_service_list()) < 1: logger.log(u'Not enough services selected. At least 1 service is required to ' 'search subtitles in the background', logger.WARNING) return self.amActive = True if sickbeard.SUBTITLES_DOWNLOAD_IN_PP: self.subtitles_download_in_pp() logger.log(u'Checking for subtitles', logger.INFO) # get episodes on which we want subtitles # criteria is: # - show subtitles = 1 # - episode subtitles != config wanted languages or 'und' (depends on config multi) # - search count < 2 and diff(airdate, now) > 1 week : now -> 1d # - search count < 7 and diff(airdate, now) <= 1 week : now -> 4h -> 8h -> 16h -> 1d -> 1d -> 1d today = datetime.date.today().toordinal() database = db.DBConnection() sql_results = database.select( 'SELECT s.show_name, e.showid, e.season, e.episode, e.status, e.subtitles, ' + 'e.subtitles_searchcount AS searchcount, e.subtitles_lastsearch AS lastsearch, e.location, ' '(? - e.airdate) AS airdate_daydiff ' + 'FROM tv_episodes AS e INNER JOIN tv_shows AS s ON (e.showid = s.indexer_id) ' + 'WHERE s.subtitles = 1 AND e.subtitles NOT LIKE (?) ' + 'AND (e.subtitles_searchcount <= 2 OR (e.subtitles_searchcount <= 7 AND airdate_daydiff <= 7)) ' + 'AND e.location != ""', [today, wanted_languages(True)]) if len(sql_results) == 0: logger.log(u'No subtitles to download', logger.INFO) self.amActive = False return rules = self._get_rules() now = datetime.datetime.now() for ep_to_sub in sql_results: if not ek(os.path.isfile, ep_to_sub['location']): logger.log(u'Episode file does not exist, cannot download subtitles for episode %dx%d of show %s' % (ep_to_sub['season'], ep_to_sub['episode'], ep_to_sub['show_name']), logger.DEBUG) continue if not needs_subtitles(ep_to_sub['subtitles']): logger.log(u'Episode already has all needed subtitles, skipping episode %dx%d of show %s' % (ep_to_sub['season'], ep_to_sub['episode'], ep_to_sub['show_name']), logger.DEBUG) continue # http://bugs.python.org/issue7980#msg221094 # I dont think this needs done here, but keeping to be safe (Recent shows rule) datetime.datetime.strptime('20110101', '%Y%m%d') if ((ep_to_sub['airdate_daydiff'] > 7 and ep_to_sub['searchcount'] < 2 and now - datetime.datetime.strptime(ep_to_sub['lastsearch'], dateTimeFormat) > datetime.timedelta(hours=rules['old'][ep_to_sub['searchcount']])) or (ep_to_sub['airdate_daydiff'] <= 7 and ep_to_sub['searchcount'] < 7 and now - datetime.datetime.strptime(ep_to_sub['lastsearch'], dateTimeFormat) > datetime.timedelta(hours=rules['new'][ep_to_sub['searchcount']]))): logger.log(u'Downloading subtitles for episode %dx%d of show %s' % (ep_to_sub['season'], ep_to_sub['episode'], ep_to_sub['show_name']), logger.DEBUG) show_object = Show.find(sickbeard.showList, int(ep_to_sub['showid'])) if not show_object: logger.log(u'Show not found', logger.DEBUG) self.amActive = False return episode_object = show_object.getEpisode(int(ep_to_sub["season"]), int(ep_to_sub["episode"])) if isinstance(episode_object, str): logger.log(u'Episode not found', logger.DEBUG) self.amActive = False return existing_subtitles = episode_object.subtitles try: episode_object.download_subtitles() except Exception as error: logger.log(u'Unable to find subtitles', logger.DEBUG) logger.log(str(error), logger.DEBUG) self.amActive = False return new_subtitles = frozenset(episode_object.subtitles).difference(existing_subtitles) if new_subtitles: logger.log(u'Downloaded subtitles for S%02dE%02d in %s' % (ep_to_sub["season"], ep_to_sub["episode"], ', '.join(new_subtitles))) self.amActive = False @staticmethod def _get_rules(): """ Define the hours to wait between 2 subtitles search depending on: - the episode: new or old - the number of searches done so far (searchcount), represented by the index of the list """ return {'old': [0, 24], 'new': [0, 4, 8, 4, 16, 24, 24]} def run_subs_extra_scripts(episode_object, found_subtitles, video, single=False): for script_name in sickbeard.SUBTITLES_EXTRA_SCRIPTS: script_cmd = [piece for piece in re.split("( |\\\".*?\\\"|'.*?')", script_name) if piece.strip()] script_cmd[0] = ek(os.path.abspath, script_cmd[0]) logger.log(u"Absolute path to script: " + script_cmd[0], logger.DEBUG) for subtitle in found_subtitles: subtitle_path = subliminal.subtitle.get_subtitle_path(video.name, None if single else subtitle.language) inner_cmd = script_cmd + [video.name, subtitle_path, subtitle.language.opensubtitles, episode_object['show_name'], str(episode_object['season']), str(episode_object['episode']), episode_object['name'], str(episode_object['show_indexerid'])] # use subprocess to run the command and capture output logger.log(u"Executing command: %s" % inner_cmd) try: process = subprocess.Popen(inner_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=sickbeard.PROG_DIR) out, _ = process.communicate() # @UnusedVariable logger.log(u"Script result: %s" % out, logger.DEBUG) except Exception as error: logger.log(u"Unable to run subs_extra_script: " + ex(error))
hernandito/SickRage
sickbeard/subtitles.py
Python
gpl-3.0
24,581
// Copyright (c) 2005 - 2017 Settlers Freaks (sf-team at siedler25.org) // // This file is part of Return To The Roots. // // Return To The Roots is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // Return To The Roots 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 Return To The Roots. If not, see <http://www.gnu.org/licenses/>. #include "defines.h" // IWYU pragma: keep #include "dskMainMenu.h" #include "GlobalVars.h" #include "Loader.h" #include "WindowManager.h" #include "Settings.h" #include "CollisionDetection.h" #include "controls/ctrlText.h" #include "controls/ctrlTimer.h" #include "desktops/dskCredits.h" #include "desktops/dskIntro.h" #include "desktops/dskMultiPlayer.h" #include "desktops/dskOptions.h" #include "desktops/dskSinglePlayer.h" #include "desktops/dskTest.h" #include "ingameWindows/iwMsgbox.h" #include "ingameWindows/iwTextfile.h" enum { ID_btSingleplayer = dskMenuBase::ID_FIRST_FREE, ID_btMultiplayer, ID_btOptions, ID_btIntro, ID_btReadme, ID_btCredits, ID_btQuit, ID_logo, ID_tmrDebugData }; dskMainMenu::dskMainMenu() { RTTR_Assert(dskMenuBase::ID_FIRST_FREE <= 3); // "Einzelspieler" AddTextButton(ID_btSingleplayer, DrawPoint(115, 180), Extent(220, 22), TC_GREEN2, _("Singleplayer"), NormalFont); // "Mehrspieler" AddTextButton(ID_btMultiplayer, DrawPoint(115, 210), Extent(220, 22), TC_GREEN2, _("Multiplayer"), NormalFont); // "Optionen" AddTextButton(ID_btOptions, DrawPoint(115, 250), Extent(220, 22), TC_GREEN2, _("Options"), NormalFont); // "Intro" AddTextButton(ID_btIntro, DrawPoint(115, 280), Extent(220, 22), TC_GREEN2, _("Intro"), NormalFont); // "ReadMe" AddTextButton(ID_btReadme, DrawPoint(115, 310), Extent(220, 22), TC_GREEN2, _("Readme"), NormalFont); // "Credits" AddTextButton(ID_btCredits, DrawPoint(115, 340), Extent(220, 22), TC_GREEN2, _("Credits"), NormalFont); // "Programm verlassen" AddTextButton(ID_btQuit, DrawPoint(115, 390), Extent(220, 22), TC_RED1, _("Quit program"), NormalFont); AddImage(ID_logo, DrawPoint(20, 20), LOADER.GetImageN("logo", 0)); if(SETTINGS.global.submit_debug_data == 0) AddTimer(ID_tmrDebugData, 250); /*AddText(20, DrawPoint(50, 450), _("Font Test"), COLOR_YELLOW, glArchivItem_Font::DF_LEFT, SmallFont); AddText(21, DrawPoint(50, 470), _("Font Test"), COLOR_YELLOW, glArchivItem_Font::DF_LEFT, NormalFont); AddText(22, DrawPoint(50, 490), _("Font Test"), COLOR_YELLOW, glArchivItem_Font::DF_LEFT, LargeFont);*/ // !\"#$%&'()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz\\_ABCDEFGHIJKLMNOPQRSTUVWXYZÇüéâäàåçêëèïîì©ÄÅôöòûùÖÜáíóúñ } void dskMainMenu::Msg_Timer(const unsigned ctrl_id) { GetCtrl<ctrlTimer>(ctrl_id)->Stop(); WINDOWMANAGER.Show( new iwMsgbox(_("Submit debug data?"), _("RttR now supports sending debug data. Would you like to help us improving this game by sending debug data?"), this, MSB_YESNO, MSB_QUESTIONRED, 100)); } void dskMainMenu::Msg_MsgBoxResult(const unsigned msgbox_id, const MsgboxResult mbr) { if(msgbox_id == 100) { if(mbr == MSR_YES) SETTINGS.global.submit_debug_data = 1; else SETTINGS.global.submit_debug_data = 2; SETTINGS.Save(); } } bool dskMainMenu::Msg_LeftUp(const MouseCoords& mc) { Window* txtVersion = GetCtrl<Window>(dskMenuBase::ID_txtVersion); if(mc.dbl_click && IsPointInRect(mc.GetPos(), txtVersion->GetBoundaryRect())) { WINDOWMANAGER.Switch(new dskTest); return true; } return false; } void dskMainMenu::Msg_ButtonClick(const unsigned ctrl_id) { switch(ctrl_id) { case ID_btSingleplayer: // "Single Player" WINDOWMANAGER.Switch(new dskSinglePlayer); break; case ID_btMultiplayer: // "Multiplayer" WINDOWMANAGER.Switch(new dskMultiPlayer); break; case ID_btOptions: // "Options" WINDOWMANAGER.Switch(new dskOptions); break; case ID_btIntro: // "Intro" WINDOWMANAGER.Switch(new dskIntro); break; case ID_btCredits: // "Credits" WINDOWMANAGER.Switch(new dskCredits); break; case ID_btQuit: // "Quit" GLOBALVARS.notdone = false; break; case ID_btReadme: // "Readme" WINDOWMANAGER.Show(new iwTextfile("readme.txt", _("Readme!"))); break; } }
frin/s25client
src/desktops/dskMainMenu.cpp
C++
gpl-3.0
4,997
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.08.11 at 01:51:42 PM MSK // package org.smpte_ra.reg._395._2014._13._1.aaf; 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.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import org.smpte_ra.reg._2003._2012.Boolean; import org.smpte_ra.reg._2003._2012.DeltaEntryArray; import org.smpte_ra.reg._2003._2012.IndexEntryArray; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;all> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}EssenceStreamID" minOccurs="0"/> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}EditUnitByteCount" minOccurs="0"/> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}IndexEntryArray" minOccurs="0"/> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}ExtStartOffset" minOccurs="0"/> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}SingleIndexLocation" minOccurs="0"/> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}SingleEssenceLocation" minOccurs="0"/> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}IndexStartPosition"/> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}InstanceID" minOccurs="0"/> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}PositionTableCount" minOccurs="0"/> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}IndexDuration"/> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}IndexStreamID" minOccurs="0"/> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}IndexEditRate"/> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}ForwardIndexDirection" minOccurs="0"/> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}VBEByteCount" minOccurs="0"/> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}DeltaEntryArray" minOccurs="0"/> * &lt;element ref="{http://www.smpte-ra.org/reg/335/2012}SliceCount" minOccurs="0"/> * &lt;/all> * &lt;attribute ref="{http://sandflow.com/ns/SMPTEST2001-1/baseline}path"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { }) @XmlRootElement(name = "IndexTableSegment") public class IndexTableSegment { @XmlElement(name = "EssenceStreamID", namespace = "http://www.smpte-ra.org/reg/335/2012") @XmlSchemaType(name = "anySimpleType") protected String essenceStreamID; @XmlElement(name = "EditUnitByteCount", namespace = "http://www.smpte-ra.org/reg/335/2012") @XmlSchemaType(name = "anySimpleType") protected String editUnitByteCount; @XmlElement(name = "IndexEntryArray", namespace = "http://www.smpte-ra.org/reg/335/2012") protected IndexEntryArray indexEntryArray; @XmlElement(name = "ExtStartOffset", namespace = "http://www.smpte-ra.org/reg/335/2012") @XmlSchemaType(name = "anySimpleType") protected String extStartOffset; @XmlElement(name = "SingleIndexLocation", namespace = "http://www.smpte-ra.org/reg/335/2012") @XmlSchemaType(name = "token") protected Boolean singleIndexLocation; @XmlElement(name = "SingleEssenceLocation", namespace = "http://www.smpte-ra.org/reg/335/2012") @XmlSchemaType(name = "token") protected Boolean singleEssenceLocation; @XmlElement(name = "IndexStartPosition", namespace = "http://www.smpte-ra.org/reg/335/2012", required = true) @XmlSchemaType(name = "anySimpleType") protected String indexStartPosition; @XmlElement(name = "InstanceID", namespace = "http://www.smpte-ra.org/reg/335/2012") @XmlSchemaType(name = "anyURI") protected String instanceID; @XmlElement(name = "PositionTableCount", namespace = "http://www.smpte-ra.org/reg/335/2012") @XmlSchemaType(name = "anySimpleType") protected String positionTableCount; @XmlElement(name = "IndexDuration", namespace = "http://www.smpte-ra.org/reg/335/2012", required = true) @XmlSchemaType(name = "anySimpleType") protected String indexDuration; @XmlElement(name = "IndexStreamID", namespace = "http://www.smpte-ra.org/reg/335/2012") @XmlSchemaType(name = "anySimpleType") protected String indexStreamID; @XmlElement(name = "IndexEditRate", namespace = "http://www.smpte-ra.org/reg/335/2012", required = true) protected String indexEditRate; @XmlElement(name = "ForwardIndexDirection", namespace = "http://www.smpte-ra.org/reg/335/2012") @XmlSchemaType(name = "token") protected Boolean forwardIndexDirection; @XmlElement(name = "VBEByteCount", namespace = "http://www.smpte-ra.org/reg/335/2012") @XmlSchemaType(name = "anySimpleType") protected String vbeByteCount; @XmlElement(name = "DeltaEntryArray", namespace = "http://www.smpte-ra.org/reg/335/2012") protected DeltaEntryArray deltaEntryArray; @XmlElement(name = "SliceCount", namespace = "http://www.smpte-ra.org/reg/335/2012") @XmlSchemaType(name = "anySimpleType") protected String sliceCount; @XmlAttribute(name = "path", namespace = "http://sandflow.com/ns/SMPTEST2001-1/baseline") protected String path; /** * Gets the value of the essenceStreamID property. * * @return * possible object is * {@link String } * */ public String getEssenceStreamID() { return essenceStreamID; } /** * Sets the value of the essenceStreamID property. * * @param value * allowed object is * {@link String } * */ public void setEssenceStreamID(String value) { this.essenceStreamID = value; } /** * Gets the value of the editUnitByteCount property. * * @return * possible object is * {@link String } * */ public String getEditUnitByteCount() { return editUnitByteCount; } /** * Sets the value of the editUnitByteCount property. * * @param value * allowed object is * {@link String } * */ public void setEditUnitByteCount(String value) { this.editUnitByteCount = value; } /** * Gets the value of the indexEntryArray property. * * @return * possible object is * {@link IndexEntryArray } * */ public IndexEntryArray getIndexEntryArray() { return indexEntryArray; } /** * Sets the value of the indexEntryArray property. * * @param value * allowed object is * {@link IndexEntryArray } * */ public void setIndexEntryArray(IndexEntryArray value) { this.indexEntryArray = value; } /** * Gets the value of the extStartOffset property. * * @return * possible object is * {@link String } * */ public String getExtStartOffset() { return extStartOffset; } /** * Sets the value of the extStartOffset property. * * @param value * allowed object is * {@link String } * */ public void setExtStartOffset(String value) { this.extStartOffset = value; } /** * Gets the value of the singleIndexLocation property. * * @return * possible object is * {@link Boolean } * */ public Boolean getSingleIndexLocation() { return singleIndexLocation; } /** * Sets the value of the singleIndexLocation property. * * @param value * allowed object is * {@link Boolean } * */ public void setSingleIndexLocation(Boolean value) { this.singleIndexLocation = value; } /** * Gets the value of the singleEssenceLocation property. * * @return * possible object is * {@link Boolean } * */ public Boolean getSingleEssenceLocation() { return singleEssenceLocation; } /** * Sets the value of the singleEssenceLocation property. * * @param value * allowed object is * {@link Boolean } * */ public void setSingleEssenceLocation(Boolean value) { this.singleEssenceLocation = value; } /** * Gets the value of the indexStartPosition property. * * @return * possible object is * {@link String } * */ public String getIndexStartPosition() { return indexStartPosition; } /** * Sets the value of the indexStartPosition property. * * @param value * allowed object is * {@link String } * */ public void setIndexStartPosition(String value) { this.indexStartPosition = value; } /** * Gets the value of the instanceID property. * * @return * possible object is * {@link String } * */ public String getInstanceID() { return instanceID; } /** * Sets the value of the instanceID property. * * @param value * allowed object is * {@link String } * */ public void setInstanceID(String value) { this.instanceID = value; } /** * Gets the value of the positionTableCount property. * * @return * possible object is * {@link String } * */ public String getPositionTableCount() { return positionTableCount; } /** * Sets the value of the positionTableCount property. * * @param value * allowed object is * {@link String } * */ public void setPositionTableCount(String value) { this.positionTableCount = value; } /** * Gets the value of the indexDuration property. * * @return * possible object is * {@link String } * */ public String getIndexDuration() { return indexDuration; } /** * Sets the value of the indexDuration property. * * @param value * allowed object is * {@link String } * */ public void setIndexDuration(String value) { this.indexDuration = value; } /** * Gets the value of the indexStreamID property. * * @return * possible object is * {@link String } * */ public String getIndexStreamID() { return indexStreamID; } /** * Sets the value of the indexStreamID property. * * @param value * allowed object is * {@link String } * */ public void setIndexStreamID(String value) { this.indexStreamID = value; } /** * Gets the value of the indexEditRate property. * * @return * possible object is * {@link String } * */ public String getIndexEditRate() { return indexEditRate; } /** * Sets the value of the indexEditRate property. * * @param value * allowed object is * {@link String } * */ public void setIndexEditRate(String value) { this.indexEditRate = value; } /** * Gets the value of the forwardIndexDirection property. * * @return * possible object is * {@link Boolean } * */ public Boolean getForwardIndexDirection() { return forwardIndexDirection; } /** * Sets the value of the forwardIndexDirection property. * * @param value * allowed object is * {@link Boolean } * */ public void setForwardIndexDirection(Boolean value) { this.forwardIndexDirection = value; } /** * Gets the value of the vbeByteCount property. * * @return * possible object is * {@link String } * */ public String getVBEByteCount() { return vbeByteCount; } /** * Sets the value of the vbeByteCount property. * * @param value * allowed object is * {@link String } * */ public void setVBEByteCount(String value) { this.vbeByteCount = value; } /** * Gets the value of the deltaEntryArray property. * * @return * possible object is * {@link DeltaEntryArray } * */ public DeltaEntryArray getDeltaEntryArray() { return deltaEntryArray; } /** * Sets the value of the deltaEntryArray property. * * @param value * allowed object is * {@link DeltaEntryArray } * */ public void setDeltaEntryArray(DeltaEntryArray value) { this.deltaEntryArray = value; } /** * Gets the value of the sliceCount property. * * @return * possible object is * {@link String } * */ public String getSliceCount() { return sliceCount; } /** * Sets the value of the sliceCount property. * * @param value * allowed object is * {@link String } * */ public void setSliceCount(String value) { this.sliceCount = value; } /** * Gets the value of the path property. * * @return * possible object is * {@link String } * */ public String getPath() { return path; } /** * Sets the value of the path property. * * @param value * allowed object is * {@link String } * */ public void setPath(String value) { this.path = value; } }
DSRCorporation/imf-conversion
imf-essence-descriptors/src/main/java/org/smpte_ra/reg/_395/_2014/_13/_1/aaf/IndexTableSegment.java
Java
gpl-3.0
14,561
/* * eGov suite of products aim to improve the internal efficiency,transparency, * accountability and the service delivery of the government organizations. * * Copyright (C) <2015> eGovernments Foundation * * The updated version of eGov suite of products as by eGovernments Foundation * is available at http://www.egovernments.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * 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/ or * http://www.gnu.org/licenses/gpl.html . * * In addition to the terms of the GPL license to be adhered to in using this * program, the following additional terms are to be complied with: * * 1) All versions of this program, verbatim or modified must carry this * Legal Notice. * * 2) Any misrepresentation of the origin of the material is prohibited. It * is required that all modified versions of this material be marked in * reasonable ways as different from the original version. * * 3) This license does not grant any rights to any user of the program * with regards to rights under trademark law for use of the trade names * or trademarks of eGovernments Foundation. * * In case of any queries, you can reach eGovernments Foundation at contact@egovernments.org. */ package org.egov.lib.security; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface ParameterCheck { /** * the position of the parameter to be checked. */ int position() default 1; boolean isCollection() default false; }
egovernments/egov-playground
eGov/egov/egov-commons/src/main/java/org/egov/lib/security/ParameterCheck.java
Java
gpl-3.0
2,224
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Strings for component 'gradeexport_txt', language 'es', branch 'MOODLE_26_STABLE' * * @package gradeexport_txt * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['pluginname'] = 'Archivo en texto plano'; $string['txt:publish'] = 'Publicar exportación de calificaciones TXT'; $string['txt:view'] = 'Usar exportación de calificaciones en texto';
dixidix/simulacion
extras/moodledata/lang/es/gradeexport_txt.php
PHP
gpl-3.0
1,190
package org.arig.robot.system.blockermanager; import lombok.extern.slf4j.Slf4j; import org.arig.robot.model.CommandeRobot; import org.arig.robot.model.enums.TypeConsigne; import org.arig.robot.model.monitor.MonitorTimeSerie; import org.arig.robot.monitoring.IMonitoringWrapper; import org.arig.robot.services.TrajectoryManager; import org.arig.robot.system.encoders.Abstract2WheelsEncoders; import org.springframework.beans.factory.annotation.Autowired; @Slf4j public class SystemBlockerManager implements ISystemBlockerManager { private static final byte MAX_ERROR_DISTANCE = 5; private static final byte MAX_ERROR_ORIENTATION = 5; @Autowired private CommandeRobot cmdRobot; @Autowired private TrajectoryManager trajectoryManager; @Autowired private Abstract2WheelsEncoders encoders; @Autowired protected IMonitoringWrapper monitoringWrapper; private final double seuilDistancePulse; private final double seuilOrientationPulse; private byte countErrorDistance = 0; private byte countErrorOrientation = 0; public SystemBlockerManager(double seuilDistancePulse, double seuilOrientationPulse) { this.seuilDistancePulse = seuilDistancePulse; this.seuilOrientationPulse = seuilOrientationPulse; } @Override public void reset() { countErrorDistance = 0; countErrorOrientation = 0; } @Override public void process() { if (cmdRobot.isType(TypeConsigne.DIST, TypeConsigne.XY) && !trajectoryManager.isTrajetAtteint() && Math.abs(encoders.getDistance()) < seuilDistancePulse) { countErrorDistance++; } else { countErrorDistance = 0; } if (cmdRobot.isType(TypeConsigne.ANGLE, TypeConsigne.XY) && !trajectoryManager.isTrajetAtteint() && Math.abs(encoders.getOrientation()) < seuilOrientationPulse) { countErrorOrientation++; } else { countErrorOrientation = 0; } // Construction du monitoring final MonitorTimeSerie serie = new MonitorTimeSerie() .measurementName("blocker") .addField("maxErrorDistance", MAX_ERROR_DISTANCE) .addField("maxErrorOrientation", MAX_ERROR_ORIENTATION) .addField("seuilDistance", seuilDistancePulse) .addField("seuilOrientation", seuilOrientationPulse) .addField("countErrorDistance", countErrorDistance) .addField("countErrorOrientation", countErrorOrientation); monitoringWrapper.addTimeSeriePoint(serie); // x itérations de 500 ms (cf Scheduler) if (countErrorDistance >= MAX_ERROR_DISTANCE && countErrorOrientation >= MAX_ERROR_ORIENTATION) { log.warn("Détection de blocage trop importante : distance {} ; orientation {}", countErrorDistance, countErrorOrientation); trajectoryManager.cancelMouvement(); reset(); } } }
ARIG-Robotique/robots
robot-system-lib-parent/robot-system-lib-core/src/main/java/org/arig/robot/system/blockermanager/SystemBlockerManager.java
Java
gpl-3.0
3,005
import numpy as np import matplotlib.pyplot as plt from asteroseismology_model import * keep = np.loadtxt('keep.txt') # Trace plot of the number of peaks plt.plot(keep[:,0].astype('int')) plt.xlabel('Iteration', fontsize=18) plt.ylabel('Number of Peaks', fontsize=18) plt.show() # Histogram of the number of peaks plt.hist(keep[:,0].astype('int'), 100) plt.xlabel('Number of peaks', fontsize=18) plt.ylabel('Number of Posterior Samples', fontsize=18) plt.show() def signal(params): """ Calculate the expected curve from the parameters (mostly copied from log_likelihood) """ # Rename the parameters num_peaks = int(params[0]) B = np.exp(params[1]) # Calculate the expected/model signal mu = B + np.zeros(N) # Add the peaks k = 2 for i in range(0, num_peaks): # Get the parameters A = -20.*np.log(1. - params[k]) xc = x_min + x_range*params[k+1] width = np.exp(np.log(1E-2*x_range) + np.log(1E2)*params[k+2]) # Add the Lorentzian peak mu += A/(1. + ((data[:,0] - xc)/width)**2) k += 3 # Exponential distribution return mu # Plot a movie of the fits # Only use the second half of the run. # Also, accumulate all x-values (frequencies) and amplitudes # in these arrays: all_x = np.array([]) all_A = np.array([]) plt.ion() for i in range(keep.shape[0]//2, keep.shape[0]): # Plotting plt.hold(False) plt.plot(data[:,0], data[:,1], 'b.') mu = signal(keep[i, :]) plt.hold(True) plt.plot(data[:,0], mu, 'r-', linewidth=2) plt.title('Model {i}/{n}'.format(i=(i+1), n=keep.shape[0])) plt.xlabel('Frequency') plt.ylabel('Power') plt.draw() # Accumulate num_peaks = keep[i, 0].astype('int') A = -10*np.log(1. - keep[i, 2::3][0:num_peaks]) x = 10.*keep[i, 3::3][0:num_peaks] all_x = np.hstack([all_x, x]) all_A = np.hstack([all_A, A]) plt.ioff() plt.show() plt.hist(all_x, 200) plt.xlabel('Frequency') plt.ylabel('Number of Posterior Samples') plt.show() plt.plot(all_x, all_A, 'b.', markersize=1) plt.xlabel('$x$', fontsize=18) plt.ylabel('$A$', fontsize=18) plt.show()
eggplantbren/WinterSchool
Code/asteroseismology_results.py
Python
gpl-3.0
2,064
/** * (C) 2013-2014 Stephan Rauh http://www.beyondjava.net * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.beyondjava.jsfComponents.inputText; import java.io.IOException; import java.util.List; import javax.faces.component.*; import javax.faces.context.FacesContext; import javax.faces.event.*; import org.primefaces.component.column.Column; import org.primefaces.component.outputlabel.OutputLabel; import de.beyondjava.jsfComponents.common.*; import de.beyondjava.jsfComponents.message.NGMessage; /** * Add AngularJS behaviour to a standard Primefaces InputText. * * @author Stephan Rauh http://www.beyondjava.net * */ @FacesComponent("de.beyondjava.InputText") public class NGInputText extends org.primefaces.component.inputtext.InputText implements SystemEventListener, NGUIComponent { public static final String COMPONENT_FAMILY = "javax.faces.Input"; /** * if the ID has not been set by the application, we define our own default * id (which equals the ngModel attribute) */ private boolean isDefaultId = true; /** * Prevents endless loop during calls from NGUIComponentTools. Such a * variable should never be needed, no doubt about it. Guess I didn\"t find * the best algorithm yet. :) */ private boolean preventRecursion = false; /** * This constructor subscribes to the PreRenderViewEvent. Catching the * PreRenderViewEvent allows AngularFaces to modify the JSF tree by adding a * label and a message. */ public NGInputText() { FacesContext context = FacesContext.getCurrentInstance(); UIViewRoot root = context.getViewRoot(); root.subscribeToViewEvent(PreRenderViewEvent.class, this); } @Override public void encodeBegin(FacesContext context) throws IOException { if ("text".equals(getType())) { Class<?> type = ELTools.getType(this); if ((int.class == type) || (Integer.class == type) || (long.class == type) || (Long.class == type) || (double.class == type) || (Double.class == type) || (byte.class == type) || (Byte.class == type) || (short.class == type) || (Short.class == type) || (float.class == type) || (Float.class == type)) { setType("number"); } } super.encodeBegin(context); } @Override public String getClientId(FacesContext context) { if (preventRecursion) { return super.getClientId(context); } return NGUIComponentTools.getClientId(context, this); } @Override public String getFamily() { return COMPONENT_FAMILY; } @Override public String getId() { if (isDefaultId) { setId(ELTools.getNGModel(this)); } return super.getId(); } /** * if no label is provided by the XHTML file, try to guess it from the * ng-model attribute. */ @Override public String getLabel() { String label = super.getLabel(); if (null == label) { String ngModel; ngModel = ELTools.getNGModel(this); return NGWordUtiltites.labelFromCamelCase(ngModel); } return label; } @Override public int getMaxlength() { int maxlength = super.getMaxlength(); if (maxlength <= 0) { NGBeanAttributeInfo info = ELTools.getBeanAttributeInfos(this); maxlength = (int) info.getMaxSize(); } return maxlength; } @Override public int getSize() { int size = super.getSize(); if (size <= 0) { NGBeanAttributeInfo info = ELTools.getBeanAttributeInfos(this); size = (int) info.getMaxSize(); } return super.getSize(); } private void insertLabelBeforeThisInputField() { OutputLabel l = new OutputLabel(); l.setFor(getId()); l.setValue(getLabel()); List<UIComponent> tree = getParent().getChildren(); for (int i = 0; i < tree.size(); i++) { if (tree.get(i) == this) { tree.add(i, l); break; } } } private void insertMessageBehindThisInputField() { NGMessage l = new NGMessage(); l.setFor(getId()); l.setDisplay("text"); l.setTarget(this); List<UIComponent> tree = getParent().getChildren(); for (int i = 0; i < tree.size(); i++) { if (tree.get(i) == this) { tree.add(i + 1, l); break; } } } @Override public boolean isListenerForSource(Object source) { return (source instanceof UIViewRoot); } @Override public boolean isRequired() { NGBeanAttributeInfo info = ELTools.getBeanAttributeInfos(this); if (info.isRequired()) { return true; } return super.isRequired(); } /** * Prevents endless loop during calls from NGUIComponentTools. Such a * variable should never be needed, no doubt about it. Guess I didn\"t find * the best algorithm yet. :) */ @Override public boolean preventRecursion() { return preventRecursion = true; } /** * Prevents endless loop during calls from NGUIComponentTools. Such a * variable should never be needed, no doubt about it. Guess I didn\"t find * the best algorithm yet. :) */ @Override public boolean preventRecursion(boolean reset) { return preventRecursion = false; } /** * Catching the PreRenderViewEvent allows AngularFaces to modify the JSF tree * by adding a label and a message. */ @Override public void processEvent(SystemEvent event) throws AbortProcessingException { if (!FacesContext.getCurrentInstance().isPostback()) { if (!(getParent() instanceof Column)) { insertLabelBeforeThisInputField(); insertMessageBehindThisInputField(); } } } @Override public void setId(String id) { if (!id.startsWith("j_idt")) { isDefaultId = false; } super.setId(id); } @Override public void setValue(Object value) { super.setValue(value); } }
stephanrauh/BackUp
AngularFaces/AngularFaces_1.0/AngularFaces-core/src/main/java/de/beyondjava/jsfComponents/inputText/NGInputText.java
Java
gpl-3.0
6,667
import config from './config'; import webpackConfig from './webpack.config'; import path from 'path'; import _ from 'lodash'; import gulp from 'gulp'; import webpack from 'webpack'; import rimraf from 'rimraf-promise'; import sequence from 'run-sequence'; import $plumber from 'gulp-plumber'; import $sass from 'gulp-sass'; import $sourcemaps from 'gulp-sourcemaps'; import $pug from 'gulp-pug'; import $util from 'gulp-util'; import $rev from 'gulp-rev'; import $replace from 'gulp-replace'; import $prefixer from 'gulp-autoprefixer'; import $size from 'gulp-size'; import $imagemin from 'gulp-imagemin'; import $changed from 'gulp-changed'; // Set environment variable. process.env.NODE_ENV = config.env.debug ? 'development' : 'production'; // Create browserSync. const browserSync = require('browser-sync').create(); // Rewrite gulp.src for better error handling. let gulpSrc = gulp.src; gulp.src = function () { return gulpSrc(...arguments) .pipe($plumber((error) => { const { plugin, message } = error; $util.log($util.colors.red(`Error (${plugin}): ${message}`)); this.emit('end'); })); }; // Create server. gulp.task('server', () => { browserSync.init({ notify: false, server: { baseDir: config.buildDir } }); }); // Compiles and deploys images. gulp.task('images', () => { return gulp.src(config.images.entry) .pipe($changed(config.images.output)) .pipe($imagemin()) .pipe($size({ title: '[images]', gzip: true })) .pipe(gulp.dest(config.images.output)); }); gulp.task('files', () => { return gulp.src(config.files.entry) .pipe($changed(config.files.output)) .pipe($size({ title: '[files]', gzip: true })) .pipe(gulp.dest(config.files.output)); }); // Compiles and deploys stylesheets. gulp.task('stylesheets', () => { if (config.env.debug) { return gulp.src(config.stylesheets.entry) .pipe($sourcemaps.init()) .pipe($sass(config.stylesheets.sass).on('error', $sass.logError)) .pipe($prefixer(config.stylesheets.autoprefixer)) .pipe($sourcemaps.write('/')) .pipe(gulp.dest(config.stylesheets.output)) .pipe($size({ title: '[stylesheets]', gzip: true })) .pipe(browserSync.stream({ match: '**/*.css' })); } else { return gulp.src(config.stylesheets.entry) .pipe($sass(config.stylesheets.sass).on('error', $sass.logError)) .pipe($prefixer(config.stylesheets.autoprefixer)) .pipe(gulp.dest(config.stylesheets.output)) .pipe($size({ title: '[stylesheets]', gzip: true })); } }); // Compiles and deploys javascript files. gulp.task('javascripts', (callback) => { let guard = false; if (config.env.debug) { webpack(webpackConfig).watch(100, build(callback)); } else { webpack(webpackConfig).run(build(callback)); } function build (done) { return (err, stats) => { if (err) { throw new $util.PluginError('webpack', err); } else { $util.log($util.colors.green('[webpack]'), stats.toString()); } if (!guard && done) { guard = true; done(); } }; } }); // Compiles and deploys HTML files. gulp.task('html', () => { return gulp.src(config.html.entry) .pipe($pug()) .pipe(gulp.dest(config.html.output)); }); // Files revision. gulp.task('rev', (callback) => { gulp.src(config.rev.entry) .pipe($rev()) .pipe(gulp.dest(config.rev.output)) .pipe($rev.manifest(config.rev.manifestFile)) .pipe(gulp.dest(config.rev.output)) .on('end', () => { const manifestFile = path.join(config.rev.output, config.rev.manifestFile); const manifest = require(manifestFile); let removables = []; let pattern = (_.keys(manifest)).join('|'); for (let v in manifest) { if (v !== manifest[v]) { removables.push(path.join(config.rev.output, v)); } } removables.push(manifestFile); rimraf(`{${removables.join(',')}}`) .then(() => { if (!_.isEmpty(config.cdn)) { gulp.src(config.rev.replace) .pipe($replace(new RegExp(`((?:\\.?\\.\\/?)+)?([\\/\\da-z\\.-]+)(${pattern})`, 'gi'), (m) => { let k = m.match(new RegExp(pattern, 'i'))[0]; let v = manifest[k]; return m.replace(k, v).replace(/^((?:\.?\.?\/?)+)?/, _.endsWith(config.cdn, '/') ? config.cdn : `${config.cdn}/`); })) .pipe(gulp.dest(config.rev.output)) .on('end', callback) .on('error', callback); } else { gulp.src(config.rev.replace) .pipe($replace(new RegExp(`${pattern}`, 'gi'), (m) => (manifest[m]))) .pipe(gulp.dest(config.rev.output)) .on('end', callback) .on('error', callback); } }); }) .on('error', callback); }); // Watch for file changes. gulp.task('watch', () => { config.watch.entries.map((entry) => { gulp.watch(entry.files, { cwd: config.sourceDir }, entry.tasks); }); gulp.watch([ 'public/**/*.html', 'public/**/*.js' ]).on('change', () => { browserSync.reload(); }); }); gulp.task('default', () => { let seq = [ 'images', 'files', 'javascripts', 'stylesheets', 'html' ]; if (config.env.debug) { seq.push('server'); seq.push('watch'); } rimraf(config.buildDir) .then(() => { sequence(...seq); }) .catch((error) => { throw error; }); });
Genert/bsp-viewer
gulpfile.babel.js
JavaScript
gpl-3.0
5,487
/* This file is part of am.string~. am.string~ 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. am.string~ 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 am.string~. If not, see <http://www.gnu.org/licenses/>. */ // // main.cpp // amstr // // Created by Aengus Martin on 17/09/13. // // #include <sys/time.h> #include <iostream> #include "ext.h" #include "ext_obex.h" #include "z_dsp.h" #include "math.h" #include "am.string.h" #include "am.string.dsp.h" int main(int argc, const char * argv[]) { std::cout << "Running commandline am.string dsp" << std::endl; long vectorSize = 256; #ifdef _DEBUG_ std::cout << "_DEBUG_ is defined" << std::endl; #endif /* * Allocate and initialise */ t_sample **sigin = new t_sample*[3]; t_sample **sigout = new t_sample*[1]; for (int i = 0; i < 3; i++ ) sigin[i] = new t_sample[vectorSize]; sigout[0] = new t_sample[vectorSize]; t_amstring* x = new t_amstring; x->maxDelay = 8192.0; x->delayLineLength = (long)x->maxDelay + (long)ceil(VD_FILTER_ORDER/2.0); x->delayLine = new t_sample[x->delayLineLength]; x->dlWrite = 0; // [ constant parts of lagrange coefficients ] int n,k; for(n=0; n<=VD_FILTER_ORDER; n++) { x->cc[n] = 1.0; for(k=0; k<=VD_FILTER_ORDER; k++) { if(k!=n) {x->cc[n] = x->cc[n] * 1.0/((t_sample)(n-k));} } } // [ coefficients for D.C. Blocking HPF ] t_sample sr = 44100.0; t_sample hpfcutoff = TWOPI * 20.0 / sr; // High-pass cutoff in radians/sample. x->dcb_a0 = 1.0 / (1.0 + (hpfcutoff/2.0) ); x->dcb_a1 = -x->dcb_a0; x->dcb_b1 = x->dcb_a0 * (1.0 - (hpfcutoff/2.0)); x->previousHpfOutput = 0.0; x->previousHpfInput = 0.0; x->lpf_xnminus1 = 0.0; x->lpf_xnminus2 = 0.0; x->highFreqGain=0.9; /* * Do the DSP */ double timeTaken; timeval t1, t2; gettimeofday(&t1, NULL); for (int i = 0; i < 1000; i++ ) { amstring_dodsp3_64(x, NULL, sigin, 3, sigout, 1, vectorSize, 0, NULL); } gettimeofday(&t2, NULL); timeTaken = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms timeTaken += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms std::cout << "Time taken: " << timeTaken << " milliseconds" << std::endl; /* * Deallocate stuff at the end */ delete [] sigin; delete [] sigout; delete [] x; return 0; }
aengusm/am.string
Code/main.cpp
C++
gpl-3.0
2,878
#include <iomanip> #include <iostream> #include <stdexcept> #include <string> #include <fstream> using namespace std; #include "Fecha.h" #include "Consultorio.h" typedef string medico; typedef string paciente; #ifndef DOMJUDGE ifstream in("cola.txt"); auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt #endif bool resuelve() { while(true){ int N; cin >> N; if (!cin) return false; string inst; medico med; paciente pac; int d, h, m; Consultorio con; for (int i = 0; i < N; ++i) { try { cin >> inst; if (inst == "nuevoMedico") { cin >> med; con.nuevoMedico(med); } else if (inst == "pideConsulta") { cin >> pac >> med >> d >> h >> m; con.pideConsulta(pac, med, Fecha(d,h,m)); } else if (inst == "siguientePaciente") { cin >> med; pac = con.siguientePaciente(med); cout << "Siguiente paciente doctor " << med << '\n'; cout << pac << '\n'; cout << "---\n"; } else if (inst == "atiendeConsulta") { cin >> med; con.atiendeConsulta(med); } else if (inst == "listaPacientes") { cin >> med >> d; auto vec = con.listaPacientes(med, Fecha(d,0,0)); cout << "Doctor " << med << " dia " << d << '\n'; for (auto p : vec) { cout << p.second << ' '; cout << setfill('0') << setw(2) << p.first.getHour() << ':'; cout << setfill('0') << setw(2) << p.first.getMinute() << '\n'; } cout << "---\n"; } }catch(invalid_argument e) { cout << e.what() << '\n' << "---\n"; } } cout << "------\n"; } } int main() { resuelve(); //while (){} return 0; }
Alexis01/EDA
16-17/2cuatri/practicas/week10/main.cpp
C++
gpl-3.0
2,169
/** * Copyright (c) 2002-2012 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.kernel.impl.batchinsert; import org.neo4j.graphdb.RelationshipType; import org.neo4j.unsafe.batchinsert.BatchRelationship; /** * Simple relationship wrapping start node id, end node id and relationship * type. * * @deprecated this class has been moved to {@link BatchRelationship} */ public class SimpleRelationship { private final long id; private final long startNodeId; private final long endNodeId; private final RelationshipType type; /** * This constructor is for internal use only, but made public while phasing * it out. * * @deprecated don't add any use of this constructor. */ public SimpleRelationship( long id, long startNodeId, long endNodeId, RelationshipType type ) { this.id = id; this.startNodeId = startNodeId; this.endNodeId = endNodeId; this.type = type; } public long getId() { return id; // & 0xFFFFFFFFL; } public long getStartNode() { return startNodeId; // & 0xFFFFFFFFL; } public long getEndNode() { return endNodeId; // & 0xFFFFFFFFL; } public RelationshipType getType() { return type; } }
dksaputra/community
kernel/src/main/java/org/neo4j/kernel/impl/batchinsert/SimpleRelationship.java
Java
gpl-3.0
2,023
<?php namespace MediaCloud\Vendor\Illuminate\Contracts\Support; interface Htmlable { /** * Get content as a string of HTML. * * @return string */ public function toHtml(); }
Interfacelab/ilab-media-tools
lib/mcloud-illuminate/contracts/Support/Htmlable.php
PHP
gpl-3.0
204
#include <wx/wxFlatNotebook/popup_dlg.h> #include <wx/listctrl.h> #include <wx/wxFlatNotebook/wxFlatNotebook.h> #include <wx/wxFlatNotebook/renderer.h> #include <wx/listbox.h> #include <wx/image.h> //#include <wx/mstream.h> #include <wx/wxFlatNotebook/fnb_resources.h> wxBitmap wxTabNavigatorWindow::m_bmp; wxTabNavigatorWindow::wxTabNavigatorWindow(wxWindow* parent) : m_listBox(NULL) , m_selectedItem(-1) , m_panel(NULL) { Create(parent); GetSizer()->Fit(this); GetSizer()->SetSizeHints(this); GetSizer()->Layout(); Centre(); } wxTabNavigatorWindow::wxTabNavigatorWindow() : wxDialog() , m_listBox(NULL) , m_selectedItem(-1) , m_panel(NULL) { } wxTabNavigatorWindow::~wxTabNavigatorWindow() { } void wxTabNavigatorWindow::Create(wxWindow* parent) { long style = 0; if( !wxDialog::Create(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, style) ) return; wxBoxSizer *sz = new wxBoxSizer( wxVERTICAL ); SetSizer( sz ); long flags = wxLB_SINGLE | wxNO_BORDER ; m_listBox = new wxListBox(this, wxID_ANY, wxDefaultPosition, wxSize(200, 150), 0, NULL, flags); static int panelHeight = 0; if( panelHeight == 0 ) { wxMemoryDC mem_dc; // bitmap must be set before it can be used for anything wxBitmap bmp(10, 10); mem_dc.SelectObject(bmp); wxFont font(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT)); font.SetWeight( wxBOLD ); mem_dc.SetFont(font); int w; mem_dc.GetTextExtent(wxT("Tp"), &w, &panelHeight); panelHeight += 4; // Place a spacer of 2 pixels // Out signpost bitmap is 24 pixels if( panelHeight < 24 ) panelHeight = 24; } m_panel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxSize(200, panelHeight)); sz->Add( m_panel ); sz->Add( m_listBox, 1, wxEXPAND ); SetSizer( sz ); // Connect events to the list box m_listBox->Connect(wxID_ANY, wxEVT_KEY_UP, wxKeyEventHandler(wxTabNavigatorWindow::OnKeyUp), NULL, this); m_listBox->Connect(wxID_ANY, wxEVT_NAVIGATION_KEY, wxNavigationKeyEventHandler(wxTabNavigatorWindow::OnNavigationKey), NULL, this); m_listBox->Connect(wxID_ANY, wxEVT_COMMAND_LISTBOX_DOUBLECLICKED, wxCommandEventHandler(wxTabNavigatorWindow::OnItemSelected), NULL, this); // Connect paint event to the panel m_panel->Connect(wxID_ANY, wxEVT_PAINT, wxPaintEventHandler(wxTabNavigatorWindow::OnPanelPaint), NULL, this); m_panel->Connect(wxID_ANY, wxEVT_ERASE_BACKGROUND, wxEraseEventHandler(wxTabNavigatorWindow::OnPanelEraseBg), NULL, this); SetBackgroundColour( wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE) ); m_listBox->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE)); PopulateListControl( static_cast<wxFlatNotebook*>( parent ) ); // Create the bitmap, only once if( !m_bmp.Ok() ) { wxImage img(signpost_xpm); img.SetAlpha(signpost_alpha, true); m_bmp = wxBitmap(img); } } void wxTabNavigatorWindow::OnKeyUp(wxKeyEvent &event) { if( event.GetKeyCode() == WXK_CONTROL ) { CloseDialog(); } } void wxTabNavigatorWindow::OnNavigationKey(wxNavigationKeyEvent &event) { long selected = m_listBox->GetSelection(); wxFlatNotebook* bk = static_cast<wxFlatNotebook*>(GetParent()); long maxItems = bk->GetPageCount(); long itemToSelect; if( event.GetDirection() ) { // Select next page if (selected == maxItems - 1) itemToSelect = 0; else itemToSelect = selected + 1; } else { // Previous page if( selected == 0 ) itemToSelect = maxItems - 1; else itemToSelect = selected - 1; } m_listBox->SetSelection( itemToSelect ); } void wxTabNavigatorWindow::PopulateListControl(wxFlatNotebook *book) { int selection = book->GetSelection(); int count = book->GetPageCount(); m_listBox->Append( book->GetPageText(static_cast<int>(selection)) ); m_indexMap[0] = selection; int itemIdx(1); int prevSel = book->GetPreviousSelection(); if( prevSel != wxNOT_FOUND ) { // Insert the previous selection as second entry m_listBox->Append( book->GetPageText(static_cast<int>(prevSel)) ); m_indexMap[1] = prevSel; itemIdx++; } for(int c=0; c<count; c++) { // Skip selected page if( c == selection ) continue; // Skip previous selected page as well if( c == prevSel ) continue; m_listBox->Append( book->GetPageText(static_cast<int>(c)) ); m_indexMap[itemIdx] = c; itemIdx++; } // Select the next entry after the current selection m_listBox->SetSelection( 0 ); wxNavigationKeyEvent dummy; dummy.SetDirection(true); OnNavigationKey(dummy); } void wxTabNavigatorWindow::OnItemSelected(wxCommandEvent & event ) { wxUnusedVar( event ); CloseDialog(); } void wxTabNavigatorWindow::CloseDialog() { wxFlatNotebook* bk = static_cast<wxFlatNotebook*>(GetParent()); m_selectedItem = m_listBox->GetSelection(); std::map<int, int>::iterator iter = m_indexMap.find(m_selectedItem); bk->SetSelection( iter->second ); EndModal( wxID_OK ); } void wxTabNavigatorWindow::OnPanelPaint(wxPaintEvent &event) { wxUnusedVar(event); wxPaintDC dc(m_panel); wxRect rect = m_panel->GetClientRect(); static bool first = true; static wxBitmap bmp( rect.width, rect.height ); if( first ) { first = false; wxMemoryDC mem_dc; mem_dc.SelectObject( bmp ); wxColour endColour( wxSystemSettings::GetColour(wxSYS_COLOUR_BTNSHADOW) ); wxColour startColour( wxFNBRenderer::LightColour(endColour, 50) ); wxFNBRenderer::PaintStraightGradientBox(mem_dc, rect, startColour, endColour); // Draw the caption title and place the bitmap wxPoint bmpPt; wxPoint txtPt; // get the bitmap optimal position, and draw it bmpPt.y = (rect.height - m_bmp.GetHeight()) / 2; bmpPt.x = 3; mem_dc.DrawBitmap( m_bmp, bmpPt, true ); // get the text position, and draw it int fontHeight(0), w(0); wxFont font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); font.SetWeight( wxBOLD ); mem_dc.SetFont( font ); mem_dc.GetTextExtent( wxT("Tp"), &w, &fontHeight ); txtPt.x = bmpPt.x + m_bmp.GetWidth() + 4; txtPt.y = (rect.height - fontHeight)/2; mem_dc.SetTextForeground( *wxWHITE ); mem_dc.DrawText( wxT("Opened tabs:"), txtPt ); mem_dc.SelectObject( wxNullBitmap ); } dc.DrawBitmap( bmp, 0, 0 ); } void wxTabNavigatorWindow::OnPanelEraseBg(wxEraseEvent &event) { wxUnusedVar(event); }
TricksterGuy/complx
lc3edit/wxFlatNotebook/popup_dlg.cpp
C++
gpl-3.0
6,478
using Newtonsoft.Json; using WebMerge.Client.Converters; namespace WebMerge.Client.ResponseModels { public class DataRouteFile { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("file_contents")] [JsonConverter(typeof (Base64ByteConverter))] public byte[] FileContents { get; set; } } }
csharpsi/webmerge.net
src/WebMerge.Client/ResponseModels/DataRouteFile.cs
C#
gpl-3.0
364
namespace CaveVins { partial class Combien { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit(); this.SuspendLayout(); // // numericUpDown1 // this.numericUpDown1.Location = new System.Drawing.Point(31, 74); this.numericUpDown1.Name = "numericUpDown1"; this.numericUpDown1.Size = new System.Drawing.Size(120, 20); this.numericUpDown1.TabIndex = 0; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(28, 26); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(35, 13); this.label1.TabIndex = 1; this.label1.Text = "label1"; // // button1 // this.button1.DialogResult = System.Windows.Forms.DialogResult.OK; this.button1.Location = new System.Drawing.Point(193, 74); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 2; this.button1.Text = "Valider"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // Combien // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(298, 122); this.Controls.Add(this.button1); this.Controls.Add(this.label1); this.Controls.Add(this.numericUpDown1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Name = "Combien"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Form2"; this.TopMost = true; ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.NumericUpDown numericUpDown1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; } }
jtraulle/WineTeK
src/CaveVins/CaveVins/15-Outils/Combien.designer.cs
C#
gpl-3.0
3,574
/* Copyright (c) 2001-2008, The HSQL Development Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the HSQL Development Group nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hsqldb.jdbc; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.sql.CallableStatement; import java.sql.Date; //#ifdef JAVA6 /* import java.sql.NClob; import java.sql.RowId; import java.sql.SQLXML; */ //#endif JAVA6 import java.sql.Time; import java.sql.Timestamp; import java.sql.SQLException; import java.util.Calendar; //#ifdef JAVA2 import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.NClob; import java.sql.Ref; import java.sql.RowId; import java.sql.SQLXML; import java.util.Map; //#endif JAVA2 import org.hsqldb.HsqlException; import org.hsqldb.Trace; import org.hsqldb.lib.IntValueHashMap; // boucherb@users patch 1.7.2 - CallableStatement impl removed // from jdbcPreparedStatement and moved here; sundry changes elsewhere to // comply // TODO: 1.7.2 Alpha N :: DONE // maybe implement set-by-parameter-name. We have an informal spec, // being "@p1" => 1, "@p2" => 2, etc. Problems: return value is "@p0" // and there is no support for registering the return value as an out // parameter. // TODO: 1.8.x // engine and client-side mechanisms for adding, retrieving, // navigating (and perhaps controlling holdability of) multiple // results generated from a single execution. // boucherb@users 2004-03/04-xx - patch 1.7.2 - some minor code cleanup // - parameter map NPE correction // - embedded SQL/SQLCLI client usability // (parameter naming changed from @n to @pn) // boucherb@users 2004-04-xx - doc 1.7.2 - javadocs added/updated /** * <!-- start generic documentation --> * * The interface used to execute SQL stored procedures. The JDBC API * provides a stored procedure SQL escape syntax that allows stored * procedures to be called in a standard way for all RDBMSs. This escape * syntax has one form that includes a result parameter and one that does * not. If used, the result parameter must be registered as an OUT parameter. * The other parameters can be used for input, output or both. Parameters * are referred to sequentially, by number, with the first parameter being 1. * <PRE> * {?= call &lt;procedure-name&gt;[&lt;arg1&gt;,&lt;arg2&gt;, ...]} * {call &lt;procedure-name&gt;[&lt;arg1&gt;,&lt;arg2&gt;, ...]} * </PRE> * <P> * IN parameter values are set using the <code>set</code> methods inherited from * {@link PreparedStatement}. The type of all OUT parameters must be * registered prior to executing the stored procedure; their values * are retrieved after execution via the <code>get</code> methods provided here. * <P> * A <code>CallableStatement</code> can return one {@link ResultSet} object or * multiple <code>ResultSet</code> objects. Multiple * <code>ResultSet</code> objects are handled using operations * inherited from {@link Statement}. * <P> * For maximum portability, a call's <code>ResultSet</code> objects and * update counts should be processed prior to getting the values of output * parameters. * <P> * <!-- end generic documentation --> * <!-- start Release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Since 1.7.2, the JDBC CallableStatement interface implementation has been * broken out of the jdbcPreparedStatement class into this one. <p> * * With 1.7.2, some of the previously unsupported features of this interface * are now supported, such as the parameterName-based setter methods. <p> * * More importantly, jdbcCallableStatement objects are now backed by a true * compiled parameteric representation. Hence, there are now significant * performance gains to be had by using a CallableStatement object instead of * a Statement object, if a short-running CALL statement is to be executed more * than a small number of times. Moreover, the recent work lays the foundation * for work in a subsequenct release to support CallableStatement OUT and * IN OUT style parameters, as well as the generation and retrieval of multiple * results in response to the execution of a CallableStatement object. <p> * * For a more in-depth discussion of performance issues regarding 1.7.2 * prepared and callable statement objects, please see overview section of * {@link jdbcPreparedStatement jdbcPreparedStatment}. * * <hr> * * As with many DBMS, HSQLDB support for stored procedures is not provided in * a completely standard fashion. <p> * * Beyond the XOpen/ODBC extended scalar functions, stored procedures are * typically supported in ways that vary greatly from one DBMS implementation * to the next. So, it is almost guaranteed that the code for a stored * procedure written under a specific DBMS product will not work without * at least some modification in the context of another vendor's product * or even across a single vendor's product lines. Moving stored procedures * from one DBMS product line to another almost invariably involves complex * porting issues and often may not be possible at all. <em>Be warned</em>. <p> * * At present, HSQLDB stored procedures map directly onto the methods of * compiled Java classes found on the classpath of the engine at runtime. This * is done in a non-standard but fairly efficient way by issuing a class * grant (and possibly method aliases) of the form: <p> * * <PRE class="SqlCodeExample"> * GRANT ALL ON CLASS &quot;package.class&quot; TO [&lt;user-name&gt; | PUBLIC] * CREATE ALIAS &ltcall-alias&gt; FOR &quot;package.class.method&quot; -- optional * </PRE> * * This has the effect of allowing the specified user(s) to access the * set of uniquely named public static methods of the specified class, * in either the role of SQL functions or stored procedures. * For example: <p> * * <PRE class="SqlCodeExample"> * CONNECT &lt;admin-user&gt; PASSWORD &lt;admin-user-password&gt;; * GRANT ALL ON CLASS &quot;org.myorg.MyClass&quot; TO PUBLIC; * CREATE ALIAS sp_my_method FOR &quot;org.myorg.MyClass.myMethod&quot; * CONNECT &lt;any-user&gt; PASSWORD &lt;any-user-password&gt;; * SELECT &quot;org.myorg.MyClass.myMethod&quot;(column_1) FROM table_1; * SELECT sp_my_method(column_1) FROM table_1; * CALL 2 + &quot;org.myorg.MyClass.myMethod&quot;(-5); * CALL 2 + sp_my_method(-5); * </PRE> * * Please note the use of the term &quot;uniquely named&quot; above. Including * 1.7.2, no support is provided to deterministically resolve overloaded * method names, and there can be issues with inherited methods as well; * currently, it is strongly recommended that developers creating stored * procedure library classes for HSQLDB simply avoid designs such that SQL * stored procedure calls attempt to resolve to: <p> * * <ol> * <li>inherited public static methods * <li>overloaded public static methods * </ol> * * Also, please note that <code>OUT</code> and <code>IN OUT</code> parameters * are not yet supported due to some unresolved low level support issues. <p> * * Including 1.7.2, the HSQLDB stored procedure call mechanism is essentially a * thin wrap of the HSQLDB SQL function call mechanism, extended to include the * more general HSQLDB SQL expression evaluation mechanism. In addition to * stored procedure calls that resolve directly to Java method invocations, the * extention provides the ability to evaluate simple SQL expressions, possibly * containing Java method invocations, outside any <code>INSERT</code>, * <code>UPDATE</code>, <code>DELETE</code> or <code>SELECT</code> statement * context. <p> * * With HSQLDB, executing a <code>CALL</code> statement that produces an opaque * (OTHER) or known scalar object reference has virtually the same effect as: * * <PRE class="SqlCodeExample"> * CREATE TABLE DUAL (dummy VARCHAR); * INSERT INTO DUAL VALUES(NULL); * SELECT &lt;simple-expression&gt; FROM DUAL; * </PRE> * * As a transitional measure, HSQLDB provides the ability to materialize a * general result set in response to stored procedure execution. In this case, * the stored procedure's Java method descriptor must specify a return type of * java.lang.Object for external use (although at any point in the devlopment * cycle, other, proprietary return types may accepted internally for engine * development purposes). * When HSQLDB detects that the runtime class of the resulting Object is * elligible, an automatic internal unwrapping is performed to correctly * expose the underlying result set to the client, whether local or remote. <p> * * Additionally, HSQLDB automatically detects if java.sql.Connection is * the class of the first argument of any underlying Java method(s). If so, * then the engine transparently supplies the internal Connection object * corresponding to the Session executing the call, adjusting the positions * of other arguments to suite the SQL context. <p> * * The features above are not intended to be permanent. Rather, the intention * is to offer more general and powerful mechanisms in a future release; * it is recommend to use them only as a temporary convenience. <p> * * For instance, one might be well advised to future-proof by writing * HSQLDB-specific adapter methods that in turn call the real logic of an * underlying generalized JDBC stored procedure library. <p> * * Here is a very simple example of an HSQLDB stored procedure generating a * user-defined result set: * * <pre class="JavaCodeExample"> * <span class="JavaKeyWord">package</span> mypackage; * * <span class="JavaKeyWord">class</span> MyClass { * * <span class="JavaKeyWord">public static</span> Object <b>mySp</b>(Connection conn) <span class="JavaKeyWord">throws</span> SQLException { * <span class="JavaKeyWord">return</span> conn.<b>createStatement</b>().<b>executeQuery</b>(<span class="JavaStringLiteral">"select * from my_table"</span>); * } * } * </pre> * * Here is a refinement demonstrating no more than the bare essence of the idea * behind a more portable style: * * <pre class="JavaCodeExample"> * <span class="JavaKeyWord">package</span> mypackage; * * <span class="JavaKeyWord">import</span> java.sql.ResultSet; * <span class="JavaKeyWord">import</span> java.sql.SQLException; * * <span class="JavaKeyWord">class</span> MyLibraryClass { * * <span class="JavaKeyWord">public static</span> ResultSet <b>mySp()</b> <span class="JavaKeyWord">throws</span> SQLException { * <span class="JavaKeyWord">return</span> ctx.<b>getConnection</b>().<b>createStatement</b>().<b>executeQuery</b>(<span class="JavaStringLiteral">"select * from my_table"</span>); * } * } * * //-- * * <span class="JavaKeyWord">package</span> myadaptorpackage; * * <span class="JavaKeyWord">import</span> java.sql.Connection; * <span class="JavaKeyWord">import</span> java.sql.SQLException; * * <span class="JavaKeyWord">class</span> MyAdaptorClass { * * <span class="JavaKeyWord">public static</span> Object <b>mySp</b>(Connection conn) <span class="JavaKeyWord">throws</span> SQLException { * MyLibraryClass.<b>getCtx()</b>.<b>setConnection</b>(conn); * <span class="JavaKeyWord">return</span> MyLibraryClass.<b>mySp</b>(); * } * } * </pre> * * In a future release, it is intended to provided some new features * that will support writing fairly portable JDBC-based stored procedure * code: <P> * * <ul> * <li> Support for the <span class="JavaStringLiteral">"jdbc:default:connection"</span> * standard database connection url. <p> * * <li> A well-defined specification of the behaviour of the HSQLDB execution * stack under stored procedure calls. <p> * * <li> A well-defined, pure JDBC specification for generating multiple * results from HSQLDB stored procedures for client retrieval. * </ul> * * (boucherb@users) * </div> * <!-- end Release-specific documentation --> * * @author boucherb@users * @version 1.7.2 * @since 1.7.2 * @see jdbcConnection#prepareCall * @see jdbcResultSet */ public class jdbcCallableStatement extends jdbcPreparedStatement implements CallableStatement { /** parameter name => parameter index */ private IntValueHashMap parameterNameMap; /** parameter index => registered OUT type */ // private IntKeyIntValueHashMap outRegistrationMap; /** * Constructs a new jdbcCallableStatement with the specified connection and * result type. * * @param c the connection on which this statement will execute * @param sql the SQL statement this object represents * @param type the type of result this statement will produce * @throws HsqlException if the statement is not accepted by the database * @throws SQLException if preprocessing by driver fails */ public jdbcCallableStatement(jdbcConnection c, String sql, int type) throws HsqlException, SQLException { super(c, sql, type); String[] names; String name; // outRegistrationMap = new IntKeyIntValueHashMap(); parameterNameMap = new IntValueHashMap(); if (pmdDescriptor != null && pmdDescriptor.metaData != null) { names = pmdDescriptor.metaData.colNames; for (int i = 0; i < names.length; i++) { name = names[i]; // PRE: should never happen in practice if (name == null || name.length() == 0) { continue; // throw? } parameterNameMap.put(name, i); } } } /** * Retrieves the parameter index corresponding to the given * parameter name. <p> * * @param parameterName to look up * @throws SQLException if not found * @return index for name */ int findParameterIndex(String parameterName) throws SQLException { checkClosed(); int index = parameterNameMap.get(parameterName, -1); if (index >= 0) { return index + 1; } throw Util.sqlException(Trace.COLUMN_NOT_FOUND, parameterName); } /** * Does the specialized work required to free this object's resources and * that of it's parent classes. <p> * * @throws SQLException if a database access error occurs */ public void close() throws SQLException { if (isClosed()) { return; } // outRegistrationMap = null; parameterNameMap = null; super.close(); } /** * Performs an internal check for OUT or IN OUT column index validity. <p> * * @param i the one-based column index to check * @throws SQLException if there is no such OUT or IN OUT column */ private void checkGetParameterIndex(int i) throws SQLException { checkClosed(); if (i < 1 || i > parameterModes.length) { String msg = "Parameter index out of bounds: " + i; throw Util.sqlException(Trace.INVALID_JDBC_ARGUMENT, msg); } /* int mode = parameterModes[i - 1]; switch (mode) { default : String msg = "Not OUT or IN OUT mode: " + mode + " for parameter: " + i; throw Util.sqlException(Trace.INVALID_JDBC_ARGUMENT, msg); case Expression.PARAM_IN_OUT : case Expression.PARAM_OUT : break; // this is OK } */ } /** * Checks if the parameter of the given index has been successfully * registered as an OUT parameter. <p> * * @param parameterIndex to check * @throws SQLException if not registered */ /* private void checkIsRegisteredParameterIndex(int parameterIndex) throws SQLException { int type; String msg; checkClosed(); type = outRegistrationMap.get(parameterIndex, Integer.MIN_VALUE); if (type == Integer.MIN_VALUE) { msg = "Parameter not registered: " + parameterIndex; throw Util.sqlException(Trace.INVALID_JDBC_ARGUMENT, msg); } } */ // ----------------------------------- JDBC 1 ---------------------------------- /** * <!-- start generic documentation --> * Registers the OUT parameter in ordinal position * <code>parameterIndex</code> to the JDBC type * <code>sqlType</code>. All OUT parameters must be registered * before a stored procedure is executed. * <p> * The JDBC type specified by <code>sqlType</code> for an OUT * parameter determines the Java type that must be used * in the <code>get</code> method to read the value of that parameter. * <p> * If the JDBC type expected to be returned to this output parameter * is specific to this particular database, <code>sqlType</code> * should be <code>java.sql.Types.OTHER</code>. The method * {@link #getObject} retrieves the value. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @param sqlType the JDBC type code defined by <code>java.sql.Types</code>. * If the parameter is of JDBC type <code>NUMERIC</code> * or <code>DECIMAL</code>, the version of * <code>registerOutParameter</code> that accepts a scale value * should be used. * @exception SQLException if a database access error occurs * @see java.sql.Types */ public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { throw Util.notSupported(); } /** * <!-- start generic documentation --> * Registers the parameter in ordinal position * <code>parameterIndex</code> to be of JDBC type * <code>sqlType</code>. This method must be called * before a stored procedure is executed. * <p> * The JDBC type specified by <code>sqlType</code> for an OUT * parameter determines the Java type that must be used * in the <code>get</code> method to read the value of that parameter. * <p> * This version of <code>registerOutParameter</code> should be * used when the parameter is of JDBC type <code>NUMERIC</code> * or <code>DECIMAL</code>. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @param sqlType the SQL type code defined by <code>java.sql.Types</code>. * @param scale the desired number of digits to the right of the * decimal point. It must be greater than or equal to zero. * @exception SQLException if a database access error occurs * @see java.sql.Types */ public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { registerOutParameter(parameterIndex, sqlType); } /** * <!-- start generic documentation --> * Retrieves whether the last OUT parameter read had the value of * SQL <code>NULL</code>. Note that this method should be called only * after calling a getter method; otherwise, there is no value to use in * determining whether it is <code>null</code> or not. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @return <code>true</code> if the last parameter read was SQL * <code>NULL</code>; <code>false</code> otherwise * @exception SQLException if a database access error occurs */ public boolean wasNull() throws SQLException { throw Util.notSupported(); } /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>CHAR</code>, * <code>VARCHAR</code>, or <code>LONGVARCHAR</code> parameter as a * <code>String</code> in the Java programming language. * <p> * For the fixed-length type JDBC <code>CHAR</code>, * the <code>String</code> object * returned has exactly the same value the (JDBC4 clarification:) SQL * <code>CHAR</code> value had in the * database, including any padding added by the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return the parameter value. If the value is SQL <code>NULL</code>, * the result * is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setString */ public String getString(int parameterIndex) throws SQLException { throw Util.notSupported(); } /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>BIT</code> parameter * as a <code>boolean</code> in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>false</code>. * @exception SQLException if a database access error occurs * @see #setBoolean */ public boolean getBoolean(int parameterIndex) throws SQLException { throw Util.notSupported(); } /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>TINYINT</code> * parameter as a <code>byte</code> in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>0</code>. * @exception SQLException if a database access error occurs * @see #setByte */ public byte getByte(int parameterIndex) throws SQLException { throw Util.notSupported(); } /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>SMALLINT</code> * parameter as a <code>short</code> in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>0</code>. * @exception SQLException if a database access error occurs * @see #setShort */ public short getShort(int parameterIndex) throws SQLException { throw Util.notSupported(); } /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>INTEGER</code> * parameter as an <code>int</code> in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>0</code>. * @exception SQLException if a database access error occurs * @see #setInt */ public int getInt(int parameterIndex) throws SQLException { throw Util.notSupported(); } /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>BIGINT</code> * parameter as a <code>long</code> in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>0</code>. * @exception SQLException if a database access error occurs * @see #setLong */ public long getLong(int parameterIndex) throws SQLException { throw Util.notSupported(); } /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>FLOAT</code> * parameter as a <code>float</code> in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return the parameter value. If the value is SQL <code>NULL</code>, the * result is <code>0</code>. * @exception SQLException if a database access error occurs * @see #setFloat */ public float getFloat(int parameterIndex) throws SQLException { throw Util.notSupported(); } /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>DOUBLE</code> * parameter as a <code>double</code> in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>0</code>. * @exception SQLException if a database access error occurs * @see #setDouble */ public double getDouble(int parameterIndex) throws SQLException { throw Util.notSupported(); } /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>NUMERIC</code> * parameter as a <code>java.math.BigDecimal</code> object with * <i>scale</i> digits to the right of the decimal point. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @param scale the number of digits to the right of the decimal point * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>null</code>. * @exception SQLException if a database access error occurs * @deprecated use <code>getBigDecimal(int parameterIndex)</code> * or <code>getBigDecimal(String parameterName)</code> * @see #setBigDecimal */ //#ifdef DEPRECATEDJDBC public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { throw Util.notSupported(); } //#endif /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>BINARY</code> or * <code>VARBINARY</code> parameter as an array of <code>byte</code> * values in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setBytes */ public byte[] getBytes(int parameterIndex) throws SQLException { throw Util.notSupported(); } /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>DATE</code> parameter * as a <code>java.sql.Date</code> object. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return the parameter value. If the value is SQL <code>NULL</code>, the * result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setDate */ public Date getDate(int parameterIndex) throws SQLException { throw Util.notSupported(); } /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>TIME</code> parameter * as a <code>java.sql.Time</code> object. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setTime */ public Time getTime(int parameterIndex) throws SQLException { throw Util.notSupported(); } /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>TIMESTAMP</code> * parameter as a <code>java.sql.Timestamp</code> object. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setTimestamp */ public Timestamp getTimestamp(int parameterIndex) throws SQLException { throw Util.notSupported(); } /** * <!-- start generic documentation --> * Retrieves the value of the designated parameter as an <code>Object</code> * in the Java programming language. If the value is an SQL <code>NULL</code>, * the driver returns a Java <code>null</code>. * <p> * This method returns a Java object whose type corresponds to the JDBC * type that was registered for this parameter using the method * <code>registerOutParameter</code>. By registering the target JDBC * type as <code>java.sql.Types.OTHER</code>, this method can be used * to read database-specific abstract data types. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return A <code>java.lang.Object</code> holding the OUT parameter value * @exception SQLException if a database access error occurs * @see java.sql.Types * @see #setObject */ public Object getObject(int parameterIndex) throws SQLException { throw Util.notSupported(); } // ----------------------------------- JDBC 2 ---------------------------------- /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>NUMERIC</code> * parameter as a <code>java.math.BigDecimal</code> object with as many * digits to the right of the decimal point as the value contains. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return the parameter value in full precision. If the value is * SQL <code>NULL</code>, the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setBigDecimal * @since JDK 1.2 (JDK 1.1.x developers: read the new overview for * jdbcPreparedStatement) */ public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { throw Util.notSupported(); } /** * <!-- start generic documentation --> * Returns an object representing the value of OUT parameter * <code>parameterIndex</code> and uses <code>map</code> for the custom * mapping of the parameter value. * <p> * This method returns a Java object whose type corresponds to the * JDBC type that was registered for this parameter using the method * <code>registerOutParameter</code>. By registering the target * JDBC type as <code>java.sql.Types.OTHER</code>, this method can * be used to read database-specific abstract data types. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, and so on * @param map the mapping from SQL type names to Java classes * @return a <code>java.lang.Object</code> holding the OUT parameter value * @exception SQLException if a database access error occurs * @see #setObject * @since JDK 1.2 (JDK 1.1.x developers: read the new overview for * jdbcPreparedStatement) */ //#ifdef JAVA2 public Object getObject(int parameterIndex, Map map) throws SQLException { throw Util.notSupported(); } //#endif JAVA2 /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC * <code>REF(&lt;structured-type&gt;)</code> parameter as a * {@link java.sql.Ref} object in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return the parameter value as a <code>Ref</code> object in the * Java programming language. If the value was SQL <code>NULL</code>, * the value <code>null</code> is returned. * @exception SQLException if a database access error occurs * @since JDK 1.2 (JDK 1.1.x developers: read the new overview for * jdbcPreparedStatement) */ //#ifdef JAVA2 public Ref getRef(int parameterIndex) throws SQLException { throw Util.notSupported(); } //#endif JAVA2 /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>BLOB</code> * parameter as a {@link java.sql.Blob} object in the Java * programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @return the parameter value as a <code>Blob</code> object in the * Java programming language. If the value was SQL <code>NULL</code>, * the value <code>null</code> is returned. * @exception SQLException if a database access error occurs * @since JDK 1.2 (JDK 1.1.x developers: read the new overview for * jdbcPreparedStatement) */ //#ifdef JAVA2 public Blob getBlob(int parameterIndex) throws SQLException { throw Util.notSupported(); } //#endif JAVA2 /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>CLOB</code> * parameter as a {@link java.sql.Clob} object in the Java programming * language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, and * so on * @return the parameter value as a <code>Clob</code> object in the * Java programming language. If the value was SQL <code>NULL</code>, the * value <code>null</code> is returned. * @exception SQLException if a database access error occurs * @since JDK 1.2 (JDK 1.1.x developers: read the new overview for * jdbcPreparedStatement) */ //#ifdef JAVA2 public Clob getClob(int parameterIndex) throws SQLException { throw Util.notSupported(); } //#endif JAVA2 /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>ARRAY</code> * parameter as an {@link java.sql.Array} object in the Java programming * language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, and * so on * @return the parameter value as an <code>Array</code> object in * the Java programming language. If the value was SQL <code>NULL</code>, * the value <code>null</code> is returned. * @exception SQLException if a database access error occurs * @since JDK 1.2 (JDK 1.1.x developers: read the new overview for * jdbcPreparedStatement) */ //#ifdef JAVA2 public Array getArray(int parameterIndex) throws SQLException { throw Util.notSupported(); } //#endif JAVA2 /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>DATE</code> * parameter as a <code>java.sql.Date</code> object, using * the given <code>Calendar</code> object * to construct the date. * With a <code>Calendar</code> object, the driver * can calculate the date taking into account a custom timezone and * locale. If no <code>Calendar</code> object is specified, the driver * uses the default timezone and locale. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @param cal the <code>Calendar</code> object the driver will use * to construct the date * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setDate * @since JDK 1.2 (JDK 1.1.x developers: read the new overview for * jdbcPreparedStatement) */ public Date getDate(int parameterIndex, Calendar cal) throws SQLException { throw Util.notSupported(); // try { // return HsqlDateTime.getDate(getString(parameterIndex), cal); // } catch (Exception e) { // throw Util.sqlException(Trace.INVALID_ESCAPE, // e.getMessage()); // } } /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>TIME</code> * parameter as a <code>java.sql.Time</code> object, using * the given <code>Calendar</code> object * to construct the time. * With a <code>Calendar</code> object, the driver * can calculate the time taking into account a custom timezone and locale. * If no <code>Calendar</code> object is specified, the driver uses the * default timezone and locale. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @param cal the <code>Calendar</code> object the driver will use * to construct the time * @return the parameter value; if the value is SQL <code>NULL</code>, * the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setTime * @since JDK 1.2 (JDK 1.1.x developers: read the new overview for * jdbcPreparedStatement) */ public Time getTime(int parameterIndex, Calendar cal) throws SQLException { throw Util.notSupported(); // try { // return HsqlDateTime.getTime(getString(parameterIndex), cal); // } catch (Exception e) { // throw Util.sqlException(Trace.INVALID_ESCAPE, // e.getMessage()); // } } /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>TIMESTAMP</code> * parameter as a <code>java.sql.Timestamp</code> object, using * the given <code>Calendar</code> object to construct * the <code>Timestamp</code> object. * With a <code>Calendar</code> object, the driver * can calculate the timestamp taking into account a custom timezone and * locale. If no <code>Calendar</code> object is specified, the driver * uses the default timezone and locale. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2, * and so on * @param cal the <code>Calendar</code> object the driver will use * to construct the timestamp * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setTimestamp * @since JDK 1.2 (JDK 1.1.x developers: read the new overview for * jdbcPreparedStatement) */ public Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { throw Util.notSupported(); // try { // return HsqlDateTime.getTimestamp(getString(parameterIndex), cal); // } catch (Exception e) { // throw Util.sqlException(Trace.INVALID_ESCAPE, // e.getMessage()); // } } /** * <!-- start generic documentation --> * Registers the designated output parameter. This version of * the method <code>registerOutParameter</code> * should be used for a user-defined or <code>REF</code> output parameter. * Examples of user-defined types include: <code>STRUCT</code>, * <code>DISTINCT</code>, <code>JAVA_OBJECT</code>, and named array types. * <p> * (JDBC4 claraification:) All OUT parameters must be registered * before a stored procedure is executed. * <p> For a user-defined parameter, the fully-qualified SQL * type name of the parameter should also be given, while a * <code>REF</code> parameter requires that the fully-qualified type name * of the referenced type be given. A JDBC driver that does not need the * type code and type name information may ignore it. To be portable, * however, applications should always provide these values for * user-defined and <code>REF</code> parameters. * * Although it is intended for user-defined and <code>REF</code> parameters, * this method may be used to register a parameter of any JDBC type. * If the parameter does not have a user-defined or <code>REF</code> type, * the <i>typeName</i> parameter is ignored. * * <P><B>Note:</B> When reading the value of an out parameter, you * must use the getter method whose Java type corresponds to the * parameter's registered SQL type. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2,... * @param sqlType a value from {@link java.sql.Types} * @param typeName the fully-qualified name of an SQL structured type * @exception SQLException if a database access error occurs * @see java.sql.Types * @since JDK 1.2 (JDK 1.1.x developers: read the new overview for * jdbcPreparedStatement) * */ public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { registerOutParameter(parameterIndex, sqlType); } // ----------------------------------- JDBC 3 ---------------------------------- /** * <!-- start generic documentation --> * Registers the OUT parameter named * <code>parameterName</code> to the JDBC type * <code>sqlType</code>. All OUT parameters must be registered * before a stored procedure is executed. * <p> * The JDBC type specified by <code>sqlType</code> for an OUT * parameter determines the Java type that must be used * in the <code>get</code> method to read the value of that parameter. * <p> * If the JDBC type expected to be returned to this output parameter * is specific to this particular database, <code>sqlType</code> * should be <code>java.sql.Types.OTHER</code>. The method * {@link #getObject} retrieves the value. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param sqlType the JDBC type code defined by <code>java.sql.Types</code>. * If the parameter is of JDBC type <code>NUMERIC</code> * or <code>DECIMAL</code>, the version of * <code>registerOutParameter</code> that accepts a scale value * should be used. * @exception SQLException if a database access error occurs * @since JDK 1.4, HSQL 1.7.0 * @see java.sql.Types */ //#ifdef JAVA4 public void registerOutParameter(String parameterName, int sqlType) throws SQLException { registerOutParameter(findParameterIndex(parameterName), sqlType); } //#endif JAVA4 /** * <!-- start generic documentation --> * Registers the parameter named * <code>parameterName</code> to be of JDBC type * <code>sqlType</code>. (JDBC4 clarification:) All OUT parameters must be registered * before a stored procedure is executed. * <p> * The JDBC type specified by <code>sqlType</code> for an OUT * parameter determines the Java type that must be used * in the <code>get</code> method to read the value of that parameter. * <p> * This version of <code>registerOutParameter</code> should be * used when the parameter is of JDBC type <code>NUMERIC</code> * or <code>DECIMAL</code>. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param sqlType SQL type code defined by <code>java.sql.Types</code>. * @param scale the desired number of digits to the right of the * decimal point. It must be greater than or equal to zero. * @exception SQLException if a database access error occurs * @since JDK 1.4, HSQLDB 1.7.0 * @see java.sql.Types */ //#ifdef JAVA4 public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { registerOutParameter(findParameterIndex(parameterName), sqlType); } //#endif JAVA4 /** * <!-- start generic documentation --> * Registers the designated output parameter. This version of * the method <code>registerOutParameter</code> * should be used for a user-named or REF output parameter. Examples * of user-named types include: STRUCT, DISTINCT, JAVA_OBJECT, and * named array types. <p> * * (JDBC4 clarification:) All OUT parameters must be registered * before a stored procedure is executed. * <p> * For a user-named parameter the fully-qualified SQL * type name of the parameter should also be given, while a REF * parameter requires that the fully-qualified type name of the * referenced type be given. A JDBC driver that does not need the * type code and type name information may ignore it. To be portable, * however, applications should always provide these values for * user-named and REF parameters. * * Although it is intended for user-named and REF parameters, * this method may be used to register a parameter of any JDBC type. * If the parameter does not have a user-named or REF type, the * typeName parameter is ignored. * * <P><B>Note:</B> When reading the value of an out parameter, you * must use the <code>getXXX</code> method whose Java type XXX corresponds * to the parameter's registered SQL type. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param sqlType a value from {@link java.sql.Types} * @param typeName the fully-qualified name of an SQL structured type * @exception SQLException if a database access error occurs * @see java.sql.Types * @since JDK 1.4, HSQL 1.7.0 */ //#ifdef JAVA4 public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { registerOutParameter(findParameterIndex(parameterName), sqlType); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of the designated JDBC <code>DATALINK</code> * parameter as a <code>java.net.URL</code> object. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterIndex the first parameter is 1, the second is 2,... * @return a <code>java.net.URL</code> object that represents the * JDBC <code>DATALINK</code> value used as the designated * parameter * @exception SQLException if a database access error occurs, * or if the URL being returned is * not a valid URL on the Java platform * @see #setURL * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public java.net.URL getURL(int parameterIndex) throws SQLException { throw Util.notSupported(); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given <code>java.net.URL</code> * object. The driver converts this to an SQL <code>DATALINK</code> * value when it sends it to the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param val the parameter value * @exception SQLException if a database access error occurs, * or if a URL is malformed * @see #getURL * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setURL(String parameterName, java.net.URL val) throws SQLException { setURL(findParameterIndex(parameterName), val); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to SQL <code>NULL</code>. * * <P><B>Note:</B> You must specify the parameter's SQL type. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param sqlType the SQL type code defined in <code>java.sql.Types</code> * @exception SQLException if a database access error occurs * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setNull(String parameterName, int sqlType) throws SQLException { setNull(findParameterIndex(parameterName), sqlType); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given Java <code>boolean</code> value. * (JDBC4 clarification:) The driver converts this * to an SQL <code>BIT</code> or <code>BOOLEAN</code> value when it sends * it to the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @exception SQLException if a database access error occurs * @see #getBoolean * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setBoolean(String parameterName, boolean x) throws SQLException { setBoolean(findParameterIndex(parameterName), x); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given Java <code>byte</code> value. * The driver converts this to an SQL <code>TINYINT</code> value when it * sends it to the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @exception SQLException if a database access error occurs * @see #getByte * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setByte(String parameterName, byte x) throws SQLException { setByte(findParameterIndex(parameterName), x); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given Java <code>short</code> value. * The driver converts this to an SQL <code>SMALLINT</code> value when * it sends it to the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @exception SQLException if a database access error occurs * @see #getShort * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setShort(String parameterName, short x) throws SQLException { setShort(findParameterIndex(parameterName), x); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given Java <code>int</code> value. * The driver converts this to an SQL <code>INTEGER</code> value when it * sends it to the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @exception SQLException if a database access error occurs * @see #getInt * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setInt(String parameterName, int x) throws SQLException { setInt(findParameterIndex(parameterName), x); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given Java <code>long</code> value. * The driver converts this to an SQL <code>BIGINT</code> value when it * sends it to the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @exception SQLException if a database access error occurs * @see #getLong * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setLong(String parameterName, long x) throws SQLException { setLong(findParameterIndex(parameterName), x); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given Java <code>float</code> value. * The driver converts this to an SQL <code>FLOAT</code> value when it * sends it to the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @exception SQLException if a database access error occurs * @see #getFloat * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setFloat(String parameterName, float x) throws SQLException { setFloat(findParameterIndex(parameterName), x); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given Java <code>double</code> value. * The driver converts this to an SQL <code>DOUBLE</code> value when it * sends it to the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @exception SQLException if a database access error occurs * @see #getDouble * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setDouble(String parameterName, double x) throws SQLException { setDouble(findParameterIndex(parameterName), x); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given * <code>java.math.BigDecimal</code> value. * The driver converts this to an SQL <code>NUMERIC</code> value when * it sends it to the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @exception SQLException if a database access error occurs * @see #getBigDecimal * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException { setBigDecimal(findParameterIndex(parameterName), x); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given Java <code>String</code> * value. The driver converts this to an SQL <code>VARCHAR</code> * or <code>LONGVARCHAR</code> value (depending on the argument's * size relative to the driver's limits on <code>VARCHAR</code> values) * when it sends it to the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @exception SQLException if a database access error occurs * @see #getString * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setString(String parameterName, String x) throws SQLException { setString(findParameterIndex(parameterName), x); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given Java array of bytes. * The driver converts this to an SQL <code>VARBINARY</code> or * <code>LONGVARBINARY</code> (depending on the argument's size relative * to the driver's limits on <code>VARBINARY</code> values) when it sends * it to the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @exception SQLException if a database access error occurs * @see #getBytes * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setBytes(String parameterName, byte[] x) throws SQLException { setBytes(findParameterIndex(parameterName), x); } //#endif JAVA4 /** * <!-- start generic documentation --> * (JDBC4 clarification:) Sets the designated parameter to the given <code>java.sql.Date</code> value * using the default time zone of the virtual machine that is running * the application. The driver converts this to an SQL <code>DATE</code> value * when it sends it to the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @exception SQLException if a database access error occurs * @see #getDate * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setDate(String parameterName, Date x) throws SQLException { setDate(findParameterIndex(parameterName), x); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given <code>java.sql.Time</code> * value. The driver converts this to an SQL <code>TIME</code> value * when it sends it to the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @exception SQLException if a database access error occurs * @see #getTime * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setTime(String parameterName, Time x) throws SQLException { setTime(findParameterIndex(parameterName), x); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given * <code>java.sql.Timestamp</code> value. The driver * converts this to an SQL <code>TIMESTAMP</code> value when it * sends it to the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @exception SQLException if a database access error occurs * @see #getTimestamp * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setTimestamp(String parameterName, Timestamp x) throws SQLException { setTimestamp(findParameterIndex(parameterName), x); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given input stream, which will * have the specified number of bytes. * When a very large ASCII value is input to a <code>LONGVARCHAR</code> * parameter, it may be more practical to send it via a * <code>java.io.InputStream</code>. Data will be read from the stream * as needed until end-of-file is reached. The JDBC driver will * do any necessary conversion from ASCII to the database char format. * * <P><B>Note:</B> This stream object can either be a standard * Java stream object or your own subclass that implements the * standard interface. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the Java input stream that contains the ASCII parameter value * @param length the number of bytes in the stream * @exception SQLException if a database access error occurs * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setAsciiStream(String parameterName, java.io.InputStream x, int length) throws SQLException { setAsciiStream(findParameterIndex(parameterName), x, length); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given input stream, which will * have the specified number of bytes. * When a very large binary value is input to a <code>LONGVARBINARY</code> * parameter, it may be more practical to send it via a * <code>java.io.InputStream</code> object. The data will be read from * the stream as needed until end-of-file is reached. * * <P><B>Note:</B> This stream object can either be a standard * Java stream object or your own subclass that implements the * standard interface. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the java input stream which contains the binary parameter value * @param length the number of bytes in the stream * @exception SQLException if a database access error occurs * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setBinaryStream(String parameterName, java.io.InputStream x, int length) throws SQLException { setBinaryStream(findParameterIndex(parameterName), x, length); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the value of the designated parameter with the given object. * The second argument must be an object type; for integral values, the * <code>java.lang</code> equivalent objects should be used. * * <p>The given Java object will be converted to the given targetSqlType * before being sent to the database. * * If the object has a custom mapping (is of a class implementing the * interface <code>SQLData</code>), * the JDBC driver should call the method <code>SQLData.writeSQL</code> * to write it to the SQL data stream. * If, on the other hand, the object is of a class implementing * <code>Ref</code>, <code>Blob</code>, <code>Clob</code>, * <code>Struct</code>, or <code>Array</code>, the driver should pass it * to the database as a value of the corresponding SQL type. * <P> * Note that this method may be used to pass datatabase- * specific abstract data types. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the object containing the input parameter value * @param targetSqlType the SQL type (as defined in java.sql.Types) to be * sent to the database. The scale argument may further qualify this type. * @param scale for java.sql.Types.DECIMAL or java.sql.Types.NUMERIC types, * this is the number of digits after the decimal point. For all * other types, this value will be ignored. * @exception SQLException if a database access error occurs * @see java.sql.Types * @see #getObject * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException { setObject(findParameterIndex(parameterName), x, targetSqlType, scale); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the value of the designated parameter with the given object. * This method is like the method <code>setObject</code> * above, except that it assumes a scale of zero. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the object containing the input parameter value * @param targetSqlType the SQL type (as defined in java.sql.Types) to be * sent to the database * @exception SQLException if a database access error occurs * @see #getObject * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { setObject(findParameterIndex(parameterName), x, targetSqlType); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the value of the designated parameter with the given object. * The second parameter must be of type <code>Object</code>; therefore, * the <code>java.lang</code> equivalent objects should be used for * built-in types. * * <p>The JDBC specification specifies a standard mapping from * Java <code>Object</code> types to SQL types. The given argument * will be converted to the corresponding SQL type before being * sent to the database. * * <p>Note that this method may be used to pass datatabase- * specific abstract data types, by using a driver-specific Java * type. * * If the object is of a class implementing the interface * <code>SQLData</code>, the JDBC driver should call the method * <code>SQLData.writeSQL</code> to write it to the SQL data stream. * If, on the other hand, the object is of a class implementing * <code>Ref</code>, <code>Blob</code>, <code>Clob</code>, * <code>Struct</code>, or <code>Array</code>, the driver should pass it * to the database as a value of the corresponding SQL type. * <P> * This method throws an exception if there is an ambiguity, for example, * if the object is of a class implementing more than one of the * interfaces named above. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the object containing the input parameter value * @exception SQLException if a database access error occurs or if the given * <code>Object</code> parameter is ambiguous * @see #getObject * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setObject(String parameterName, Object x) throws SQLException { setObject(findParameterIndex(parameterName), x); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given <code>Reader</code> * object, which is the given number of characters long. * When a very large UNICODE value is input to a <code>LONGVARCHAR</code> * parameter, it may be more practical to send it via a * <code>java.io.Reader</code> object. The data will be read from the * stream as needed until end-of-file is reached. The JDBC driver will * do any necessary conversion from UNICODE to the database char format. * * <P><B>Note:</B> This stream object can either be a standard * Java stream object or your own subclass that implements the * standard interface. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param reader the <code>java.io.Reader</code> object that * contains the UNICODE data used as the designated parameter * @param length the number of characters in the stream * @exception SQLException if a database access error occurs * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setCharacterStream(String parameterName, java.io.Reader reader, int length) throws SQLException { setCharacterStream(findParameterIndex(parameterName), reader, length); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given <code>java.sql.Date</code> * value, using the given <code>Calendar</code> object. The driver uses * the <code>Calendar</code> object to construct an SQL <code>DATE</code> * value, which the driver then sends to the database. With a * a <code>Calendar</code> object, the driver can calculate the date * taking into account a custom timezone. If no * <code>Calendar</code> object is specified, the driver uses the default * timezone, which is that of the virtual machine running the * application. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @param cal the <code>Calendar</code> object the driver will use * to construct the date * @exception SQLException if a database access error occurs * @see #getDate * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setDate(String parameterName, Date x, Calendar cal) throws SQLException { setDate(findParameterIndex(parameterName), x, cal); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given <code>java.sql.Time</code> * value, using the given <code>Calendar</code> object. The driver uses * the <code>Calendar</code> object to construct an SQL <code>TIME</code> * value, which the driver then sends to the database. With a * a <code>Calendar</code> object, the driver can calculate the time * taking into account a custom timezone. If no * <code>Calendar</code> object is specified, the driver uses the default * timezone, which is that of the virtual machine running the * application. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @param cal the <code>Calendar</code> object the driver will use * to construct the time * @exception SQLException if a database access error occurs * @see #getTime * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setTime(String parameterName, Time x, Calendar cal) throws SQLException { setTime(findParameterIndex(parameterName), x, cal); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to the given * <code>java.sql.Timestamp</code> value, using the given * <code>Calendar</code> object. The driver uses the * <code>Calendar</code> object to construct an SQL * <code>TIMESTAMP</code> value, which the driver then sends to the * database. With a <code>Calendar</code> object, the driver can * calculate the timestamp taking into account a custom timezone. If no * <code>Calendar</code> object is specified, the driver uses the default * timezone, which is that of the virtual machine running the * application. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param x the parameter value * @param cal the <code>Calendar</code> object the driver will use * to construct the timestamp * @exception SQLException if a database access error occurs * @see #getTimestamp * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setTimestamp(String parameterName, Timestamp x, Calendar cal) throws SQLException { setTimestamp(findParameterIndex(parameterName), x, cal); } //#endif JAVA4 /** * <!-- start generic documentation --> * Sets the designated parameter to SQL <code>NULL</code>. * This version of the method <code>setNull</code> should * be used for user-defined types and <code>REF</code> type parameters. * Examples of user-defined types include: <code>STRUCT</code>, * <code>DISTINCT</code>, <code>JAVA_OBJECT</code>, and * named array types. * * <P><B>Note:</B> To be portable, applications must give the * SQL type code and the fully-qualified SQL type name when specifying * a <code>NULL</code> user-defined or <code>REF</code> parameter. * In the case of a user-defined type the name is the type name of the * parameter itself. For a <code>REF</code> parameter, the name is the * type name of the referenced type. If a JDBC driver does not need * the type code or type name information, it may ignore it. * * Although it is intended for user-defined and <code>Ref</code> * parameters, this method may be used to set a null parameter of * any JDBC type. If the parameter does not have a user-defined or * <code>REF</code> type, the given <code>typeName</code> is ignored. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * Starting with 1.7.2, HSLQDB supports this. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param sqlType a value from <code>java.sql.Types</code> * @param typeName the fully-qualified name of an SQL user-defined type; * ignored if the parameter is not a user-defined type or * SQL <code>REF</code> value * @exception SQLException if a database access error occurs * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { setNull(findParameterIndex(parameterName), sqlType, typeName); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>CHAR</code>, <code>VARCHAR</code>, * or <code>LONGVARCHAR</code> parameter as a <code>String</code> in * the Java programming language. * <p> * For the fixed-length type JDBC <code>CHAR</code>, * the <code>String</code> object * returned has exactly the same value the (JDBC4 clarification:) SQL * <code>CHAR</code> value had in the * database, including any padding added by the database. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setString * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public String getString(String parameterName) throws SQLException { return getString(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * (JDBC4 modified:) Retrieves the value of a JDBC <code>BIT</code> or <code>BOOLEAN</code> * parameter as a * <code>boolean</code> in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>false</code>. * @exception SQLException if a database access error occurs * @see #setBoolean * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public boolean getBoolean(String parameterName) throws SQLException { return getBoolean(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>TINYINT</code> parameter as a * <code>byte</code> in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>0</code>. * @exception SQLException if a database access error occurs * @see #setByte * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public byte getByte(String parameterName) throws SQLException { return getByte(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>SMALLINT</code> parameter as * a <code>short</code> in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>0</code>. * @exception SQLException if a database access error occurs * @see #setShort * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public short getShort(String parameterName) throws SQLException { return getShort(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>INTEGER</code> parameter as * an <code>int</code> in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>0</code>. * @exception SQLException if a database access error occurs * @see #setInt * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public int getInt(String parameterName) throws SQLException { return getInt(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>BIGINT</code> parameter as * a <code>long</code> in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>0</code>. * @exception SQLException if a database access error occurs * @see #setLong * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public long getLong(String parameterName) throws SQLException { return getLong(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>FLOAT</code> parameter as * a <code>float</code> in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>0</code>. * @exception SQLException if a database access error occurs * @see #setFloat * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public float getFloat(String parameterName) throws SQLException { return getFloat(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>DOUBLE</code> parameter as * a <code>double</code> in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>0</code>. * @exception SQLException if a database access error occurs * @see #setDouble * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public double getDouble(String parameterName) throws SQLException { return getDouble(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>BINARY</code> or * <code>VARBINARY</code> parameter as an array of <code>byte</code> * values in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setBytes * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public byte[] getBytes(String parameterName) throws SQLException { return getBytes(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>DATE</code> parameter as a * <code>java.sql.Date</code> object. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setDate * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public Date getDate(String parameterName) throws SQLException { return getDate(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>TIME</code> parameter as a * <code>java.sql.Time</code> object. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setTime * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public Time getTime(String parameterName) throws SQLException { return getTime(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>TIMESTAMP</code> parameter as a * <code>java.sql.Timestamp</code> object. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setTimestamp * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public Timestamp getTimestamp(String parameterName) throws SQLException { return getTimestamp(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a parameter as an <code>Object</code> in the Java * programming language. If the value is an SQL <code>NULL</code>, the * driver returns a Java <code>null</code>. * <p> * This method returns a Java object whose type corresponds to the JDBC * type that was registered for this parameter using the method * <code>registerOutParameter</code>. By registering the target JDBC * type as <code>java.sql.Types.OTHER</code>, this method can be used * to read database-specific abstract data types. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return A <code>java.lang.Object</code> holding the OUT parameter value. * @exception SQLException if a database access error occurs * @see java.sql.Types * @see #setObject * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public Object getObject(String parameterName) throws SQLException { return getObject(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>NUMERIC</code> parameter as a * <code>java.math.BigDecimal</code> object with as many digits to the * right of the decimal point as the value contains. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value in full precision. If the value is * SQL <code>NULL</code>, the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setBigDecimal * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public BigDecimal getBigDecimal(String parameterName) throws SQLException { return getBigDecimal(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Returns an object representing the value of OUT parameter * <code>parameterName</code> and uses <code>map</code> for the custom * mapping of the parameter value. * <p> * This method returns a Java object whose type corresponds to the * JDBC type that was registered for this parameter using the method * <code>registerOutParameter</code>. By registering the target * JDBC type as <code>java.sql.Types.OTHER</code>, this method can * be used to read database-specific abstract data types. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param map the mapping from SQL type names to Java classes * @return a <code>java.lang.Object</code> holding the OUT parameter value * @exception SQLException if a database access error occurs * @see #setObject * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public Object getObject(String parameterName, Map map) throws SQLException { return getObject(findParameterIndex(parameterName), map); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>REF(&lt;structured-type&gt;)</code> * parameter as a {@link Ref} object in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value as a <code>Ref</code> object in the * Java programming language. If the value was SQL <code>NULL</code>, * the value <code>null</code> is returned. * @exception SQLException if a database access error occurs * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public Ref getRef(String parameterName) throws SQLException { return getRef(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>BLOB</code> parameter as a * {@link java.sql.Blob} object in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value as a <code>Blob</code> object in the * Java programming language. If the value was SQL <code>NULL</code>, * the value <code>null</code> is returned. * @exception SQLException if a database access error occurs * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public Blob getBlob(String parameterName) throws SQLException { return getBlob(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>CLOB</code> parameter as a * {@link java.sql.Clob} object in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value as a <code>Clob</code> object in the * Java programming language. If the value was SQL <code>NULL</code>, * the value <code>null</code> is returned. * @exception SQLException if a database access error occurs * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public Clob getClob(String parameterName) throws SQLException { return getClob(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>ARRAY</code> parameter as an * {@link Array} object in the Java programming language. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value as an <code>Array</code> object in * Java programming language. If the value was SQL <code>NULL</code>, * the value <code>null</code> is returned. * @exception SQLException if a database access error occurs * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public Array getArray(String parameterName) throws SQLException { return getArray(findParameterIndex(parameterName)); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>DATE</code> parameter as a * <code>java.sql.Date</code> object, using * the given <code>Calendar</code> object * to construct the date. * With a <code>Calendar</code> object, the driver * can calculate the date taking into account a custom timezone and * locale. If no <code>Calendar</code> object is specified, the d * river uses the default timezone and locale. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param cal the <code>Calendar</code> object the driver will use * to construct the date * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setDate * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public Date getDate(String parameterName, Calendar cal) throws SQLException { return getDate(findParameterIndex(parameterName), cal); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>TIME</code> parameter as a * <code>java.sql.Time</code> object, using * the given <code>Calendar</code> object * to construct the time. * With a <code>Calendar</code> object, the driver * can calculate the time taking into account a custom timezone and * locale. If no <code>Calendar</code> object is specified, the driver * uses the default timezone and locale. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @param cal the <code>Calendar</code> object the driver will use * to construct the time * @return the parameter value; if the value is SQL <code>NULL</code>, * the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setTime * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public Time getTime(String parameterName, Calendar cal) throws SQLException { return getTime(findParameterIndex(parameterName), cal); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>TIMESTAMP</code> parameter as a * <code>java.sql.Timestamp</code> object, using * the given <code>Calendar</code> object to construct * the <code>Timestamp</code> object. * With a <code>Calendar</code> object, the driver * can calculate the timestamp taking into account a custom timezone * and locale. If no <code>Calendar</code> object is specified, the * driver uses the default timezone and locale. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * * @param parameterName the name of the parameter * @param cal the <code>Calendar</code> object the driver will use * to construct the timestamp * @return the parameter value. If the value is SQL <code>NULL</code>, * the result is <code>null</code>. * @exception SQLException if a database access error occurs * @see #setTimestamp * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { return getTimestamp(findParameterIndex(parameterName), cal); } //#endif JAVA4 /** * <!-- start generic documentation --> * Retrieves the value of a JDBC <code>DATALINK</code> parameter as a * <code>java.net.URL</code> object. <p> * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 1.7.2 does not support this feature. <p> * * Calling this method always throws an <code>SQLException</code>. * </div> * <!-- end release-specific documentation --> * * @param parameterName the name of the parameter * @return the parameter value as a <code>java.net.URL</code> object in the * Java programming language. If the value was SQL * <code>NULL</code>, the value <code>null</code> is returned. * @exception SQLException if a database access error occurs, * or if there is a problem with the URL * @see #setURL * @since JDK 1.4, HSQLDB 1.7.0 */ //#ifdef JAVA4 public java.net.URL getURL(String parameterName) throws SQLException { return getURL(findParameterIndex(parameterName)); } @Override public Reader getCharacterStream(int arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Reader getCharacterStream(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Reader getNCharacterStream(int arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Reader getNCharacterStream(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public NClob getNClob(int arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public NClob getNClob(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public String getNString(int arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public String getNString(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public RowId getRowId(int arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public RowId getRowId(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public SQLXML getSQLXML(int arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public SQLXML getSQLXML(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public void setAsciiStream(String arg0, InputStream arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setAsciiStream(String arg0, InputStream arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void setBinaryStream(String arg0, InputStream arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setBinaryStream(String arg0, InputStream arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void setBlob(String arg0, Blob arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setBlob(String arg0, InputStream arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setBlob(String arg0, InputStream arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void setCharacterStream(String arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setCharacterStream(String arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void setClob(String arg0, Clob arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setClob(String arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setClob(String arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void setNCharacterStream(String arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setNCharacterStream(String arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void setNClob(String arg0, NClob arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setNClob(String arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setNClob(String arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void setNString(String arg0, String arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setRowId(String arg0, RowId arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setSQLXML(String arg0, SQLXML arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setAsciiStream(int arg0, InputStream arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setAsciiStream(int arg0, InputStream arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void setBinaryStream(int arg0, InputStream arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setBinaryStream(int arg0, InputStream arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void setBlob(int arg0, InputStream arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setBlob(int arg0, InputStream arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void setCharacterStream(int arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setCharacterStream(int arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void setClob(int arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setClob(int arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void setNCharacterStream(int arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setNCharacterStream(int arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void setNClob(int arg0, NClob arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setNClob(int arg0, Reader arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setNClob(int arg0, Reader arg1, long arg2) throws SQLException { // TODO Auto-generated method stub } @Override public void setNString(int arg0, String arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setRowId(int arg0, RowId arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setSQLXML(int arg0, SQLXML arg1) throws SQLException { // TODO Auto-generated method stub } @Override public boolean isPoolable() throws SQLException { // TODO Auto-generated method stub return false; } @Override public void setPoolable(boolean arg0) throws SQLException { // TODO Auto-generated method stub } @Override public boolean isWrapperFor(Class<?> arg0) throws SQLException { // TODO Auto-generated method stub return false; } @Override public <T> T unwrap(Class<T> arg0) throws SQLException { // TODO Auto-generated method stub return null; } //#endif JAVA4 //#ifdef JAVA6 /* public void setPoolable(boolean poolable) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public boolean isPoolable() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public <T> T unwrap(Class<T> iface) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public boolean isWrapperFor(Class<?> iface) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setRowId(int parameterIndex, RowId x) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setNString(int parameterIndex, String value) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setNClob(int parameterIndex, NClob value) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setClob(int parameterIndex, Reader reader) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setNClob(int parameterIndex, Reader reader) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public RowId getRowId(int parameterIndex) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public RowId getRowId(String parameterName) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setRowId(String parameterName, RowId x) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setNString(String parameterName, String value) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setNClob(String parameterName, NClob value) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setClob(String parameterName, Reader reader, long length) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setNClob(String parameterName, Reader reader, long length) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public NClob getNClob(int parameterIndex) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public NClob getNClob(String parameterName) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public SQLXML getSQLXML(int parameterIndex) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public SQLXML getSQLXML(String parameterName) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public String getNString(int parameterIndex) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public String getNString(String parameterName) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public Reader getNCharacterStream(int parameterIndex) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public Reader getNCharacterStream(String parameterName) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public Reader getCharacterStream(int parameterIndex) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public Reader getCharacterStream(String parameterName) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setBlob(String parameterName, Blob x) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setClob(String parameterName, Clob x) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setAsciiStream(String parameterName, InputStream x, long length) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setBinaryStream(String parameterName, InputStream x, long length) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setCharacterStream(String parameterName, Reader reader, long length) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setAsciiStream(String parameterName, InputStream x) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setBinaryStream(String parameterName, InputStream x) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setCharacterStream(String parameterName, Reader reader) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setNCharacterStream(String parameterName, Reader value) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setClob(String parameterName, Reader reader) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setBlob(String parameterName, InputStream inputStream) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } public void setNClob(String parameterName, Reader reader) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } */ //#endif JAVA6 }
ckaestne/LEADT
workspace/hsqldb/src/org/hsqldb/jdbc/jdbcCallableStatement.java
Java
gpl-3.0
141,388
<?php /** * WPMovieLibrary Legacy functions. * * Deal with old WordPress/WPMovieLibrary versions. * * @since 1.3 * * @package WPMovieLibrary * @author Charlie MERLAND <charlie.merland@gmail.com> * @license GPL-3.0 * @link http://www.caercam.org/ * @copyright 2014 CaerCam.org */ if ( ! defined( 'ABSPATH' ) ) exit; /** * Simple function to check WordPress version. This is mainly * used for styling as WP3.8 introduced a brand new dashboard * look n feel. * * @since 1.0 * * @return boolean Older/newer than WordPress 3.8? */ function wpmoly_modern_wp() { return version_compare( get_bloginfo( 'version' ), '3.8', '>=' ); } /** * Simple function to check for deprecated movie metadata. Prior to version 1.3 * metadata are stored in a unique meta field and must be converted to be used * in latest versions. * * @since 2.0 * * @return boolean Deprecated meta? */ function wpmoly_has_deprecated_meta( $post_id = null ) { if ( ! is_null( $post_id ) && class_exists( 'WPMOLY_Legacy' ) ) return WPMOLY_Legacy::has_deprecated_meta( $post_id ); // Option not set, simultate deprecated to update counter $deprecated = get_option( 'wpmoly_has_deprecated_meta' ); if ( false === $deprecated ) return true; // transient set but count to 0 means we don't do anything $deprecated = ( '0' == $deprecated ? false : true ); return $deprecated; }
wp-plugins/wpmovielibrary
includes/functions/wpmoly-legacy-functions.php
PHP
gpl-3.0
1,413
/*****************************************************************************/ /* _QnA: Event Handlers and Helpers .js*/ /*****************************************************************************/ Template._QnA.events({ "submit #newQuestion": function (e, tmpl) { e.preventDefault(); var question = Utils.forms.sArrayToObject($(e.currentTarget).serializeArray()) , chatter = tmpl.data && tmpl.data.chatter; if (!chatter) { Growl.error("Could not find chatter."); return; } if (question.message) { question.chatterId = chatter._id; Meteor.call("/app/chatters/add/question", question, function (err, result) { if (err) { Growl.error(err); } else { $(e.currentTarget)[0].reset(); } }); } else { Growl.error("Please add some text and try again.", { title: "Doh?!" }); } return false; } , "click a[href=#voteUp]": function (e) { e.preventDefault(); Meteor.call("/app/questions/vote", { "count": 1, "questionId": this._id }, function (err, result) { if (err) { Growl.error(err); } }); } , "click a[href=#voteDown]": function (e) { e.preventDefault(); Meteor.call("/app/questions/vote", { "count": -1, "questionId": this._id }, function (err, result) { if (err) { Growl.error(err); } }); } }); Template._QnA.helpers({ replyCount: function () { var _count = parseInt(this.replyCount) || 0; return { "num": _count, "label": (_count === 1) ? "reply" : "replies" }; } , questionActions: function () { var loggedInUser = Meteor.user() , actions = [] , editPath = Router.routes["questions.edit"].path({ "chatterId": this.chatterId, "_id": this._id }) , deletePath = Router.routes["questions.delete"].path({ "chatterId": this.chatterId, "_id": this._id }); if (this.created.by === loggedInUser._id || Roles.userIsInRole(loggedInUser, ["admin-role"])) { actions.push({ "actionPath": editPath, "actionLabel": "Edit" }); actions.push({ "actionPath": deletePath, "actionLabel": "Delete" }); } return actions; } }); /*****************************************************************************/ /* _QnA: Lifecycle Hooks */ /*****************************************************************************/ Template._QnA.created = function () { }; Template._QnA.rendered = function () { }; Template._QnA.destroyed = function () { };
fletchtj/BackRowChatter
client/views/chatters/chatters_qna/chatters_qna.js
JavaScript
gpl-3.0
2,484
package name.herve.jtlm; public class JTLMException extends Exception { private static final long serialVersionUID = 8617680724685561829L; public JTLMException() { super(); } public JTLMException(String message) { super(message); } public JTLMException(String message, Throwable cause) { super(message, cause); } public JTLMException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public JTLMException(Throwable cause) { super(cause); } }
nrv/jTLM
src/main/java/name/herve/jtlm/JTLMException.java
Java
gpl-3.0
598
(function($){ /* * VGA, SVGA, QVGA */ libDraw.ns('risc.hw.vga'); // Text mode... // /* CGA 16 colors pallete: */ var _CGA_PALLETE = [ '#000000', '#0000AA', '#00AA00', '#00AAAA', '#AA0000', '#AA00AA', '#AA5500', '#AAAAAA', '#555555', '#5555FF', '#55FF55', '#55FFFF', '#FF5555', '#FF55FF', '#FFFF55', '#FFFFFF' ]; var _RESOLUTION_MODES = { 'CGA_80_25': { width: 640, height: 200, cols: 80, rows: 25, charWidth: 8, charHeight: 8, font: '8px monospace', fontHeight: 8 }, 'VGA_80_25': { width: 720, height: 400, cols:80, rows: 25, charWidth: 9, charHeight: 16, font: '12px monospace', fontHeight: 12 } }; var VGA = function(config){ libDraw.ext(this, config); this.mode = _RESOLUTION_MODES[config.mode || 'VGA_80_25']; if(!this.mode){ throw new Error('Mode [' + config.mode + '] is not valid VGA mode.'); } if(!this.memory){ throw new Error('Not attached to memory!'); } this.origin = this.origin || 0xB8000; if(this.memory.length < this.origin+(this.mode.rows*this.mode.cols*2)){ throw new Error("Not enough memory. Unable to map physical memory at 0x" + risc.utils.wToHex(this.origin)); } this.cache = new Int32Array(this.mode.cols*this.mode.rows/2); if(!this.runtime){ var canvas = $('<canvas class="vga-canvas"></canvas>')[0]; this.runtime = new libDraw.pkg.runtime.Runtime({ spec: { width: this.mode.width, height: this.mode.height, canvas: canvas }, clock:{ interval: 100, // 10 FPS mode: 'interval' } }); $(this.appendTo || document.body).append(canvas); } var self = this; this.runtime.register(function(g, frame, rt){ self.draw(g, rt); }); }; libDraw.ext(VGA,{ turnOn: function(){ this.runtime.clock.start(); // for now }, turnOff: function(){ this.runtime.clock.stop(); // for now }, draw: function(g,rt){ var total = this.mode.rows*this.mode.cols/2; if(!this.bgset){ this.bgset = true; g.background('#000'); } g.setFont(this.mode.font); var l = 0; var row = 0; var col = 0; var originW = this.origin>>2; // div by 4 for(var i = 0; i < total; i++){ if(this.cache[i] != this.memory[originW+i]){ this.cache[i] = this.memory[originW+i]; l = i*2; row = Math.floor(l/this.mode.cols); col = l%this.mode.cols; this.__printCharacter(row,col, this.cache[i], g); col++; if(col >= this.mode.cols){ col = 0; row++; } this.__printCharacter(row,col, this.cache[i]>>16, g); } } }, __printCharacter: function(row, col, char, graphics){ graphics.fill('#000'); graphics.rect(col*this.mode.charWidth, row*this.mode.charHeight, this.mode.charWidth, this.mode.charHeight); graphics.fill(_CGA_PALLETE[(char>>12)&0xF]); graphics.rect(col*this.mode.charWidth, row*this.mode.charHeight, this.mode.charWidth, this.mode.charHeight); graphics.fill(_CGA_PALLETE[(char>>8)&0xF]); graphics.stroke(_CGA_PALLETE[(char>>8)&0xF]); graphics.text(String.fromCharCode(char&0xFF), col*this.mode.charWidth, row*this.mode.charHeight+this.mode.fontHeight); }, writeText: function(row, col, text, fgColor, bgColor){ for(var i = 0; i < text.length; i++){ col++; if(col>=this.mode.cols){ col=0; row++; } if(row>=this.mode.rows) break; this.__writeChar(row,col,text[i],fgColor,bgColor); } }, __writeChar: function(row, col, char, fgColor, bgColor){ var origin = this.origin>>2; var halfWord = row*this.mode.cols+col; var word = Math.floor(halfWord/2) + origin; var sh = (halfWord%2)*16; var int32 = char.charCodeAt(0) | ((fgColor&0xF)<<12) | ((bgColor&0xF)<<8); this.memory[word] = this.memory[word]&(~(0xFFFF<<sh)) | int32<<sh; //console.log('PRINTED CHAR IN WORD: ', word, ' -> ', risc.utils.wToHex(this.memory[word])); } }); risc.hw.vga.VGA = VGA; })(jQuery);
natemago/primer
src/hw/vga.js
JavaScript
gpl-3.0
5,034
<?php /** * @name Required * Ensure that the length of the given value is lower than . * * @package Catapult.Data.Constraints * * @author Cyril Nicodème * @version 1.0 * * @since 04/2015 * * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace Catapult\Data\Constraints; class MaxLength implements IConstraints { private $message; private $number = 0; public function __construct($number, $message = '%d chars maximum.') { $this->number = $number; $this->message = $message; } public function validate($name, $value) { if (empty($value)) return null; if (strlen($value) >= $this->number) { return sprintf($this->message, $name, $this->number); } } }
cnicodeme/Catapult
data/constraints/maxlength.php
PHP
gpl-3.0
770
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?). Doom 3 Source Code 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. Doom 3 Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "../idlib/precompiled.h" #pragma hdrstop #include "Game_local.h" /*********************************************************************** idAnimState ***********************************************************************/ /* ===================== idAnimState::idAnimState ===================== */ idAnimState::idAnimState() { self = NULL; animator = NULL; thread = NULL; idleAnim = true; disabled = true; channel = ANIMCHANNEL_ALL; animBlendFrames = 0; lastAnimBlendFrames = 0; } /* ===================== idAnimState::~idAnimState ===================== */ idAnimState::~idAnimState() { delete thread; } /* ===================== idAnimState::Save ===================== */ void idAnimState::Save( idSaveGame* savefile ) const { savefile->WriteObject( self ); // Save the entity owner of the animator savefile->WriteObject( animator->GetEntity() ); savefile->WriteObject( thread ); savefile->WriteString( state ); savefile->WriteInt( animBlendFrames ); savefile->WriteInt( lastAnimBlendFrames ); savefile->WriteInt( channel ); savefile->WriteBool( idleAnim ); savefile->WriteBool( disabled ); } /* ===================== idAnimState::Restore ===================== */ void idAnimState::Restore( idRestoreGame* savefile ) { savefile->ReadObject( reinterpret_cast<idClass*&>( self ) ); idEntity* animowner; savefile->ReadObject( reinterpret_cast<idClass*&>( animowner ) ); if( animowner ) { animator = animowner->GetAnimator(); } savefile->ReadObject( reinterpret_cast<idClass*&>( thread ) ); savefile->ReadString( state ); savefile->ReadInt( animBlendFrames ); savefile->ReadInt( lastAnimBlendFrames ); savefile->ReadInt( channel ); savefile->ReadBool( idleAnim ); savefile->ReadBool( disabled ); } /* ===================== idAnimState::Init ===================== */ void idAnimState::Init( idActor* owner, idAnimator* _animator, int animchannel ) { assert( owner ); assert( _animator ); self = owner; animator = _animator; channel = animchannel; if( !thread ) { thread = new idThread(); thread->ManualDelete(); } thread->EndThread(); thread->ManualControl(); } /* ===================== idAnimState::Shutdown ===================== */ void idAnimState::Shutdown() { delete thread; thread = NULL; } /* ===================== idAnimState::SetState ===================== */ void idAnimState::SetState( const char* statename, int blendFrames ) { const function_t* func; func = self->scriptObject.GetFunction( statename ); if( !func ) { assert( 0 ); gameLocal.Error( "Can't find function '%s' in object '%s'", statename, self->scriptObject.GetTypeName() ); } state = statename; disabled = false; animBlendFrames = blendFrames; lastAnimBlendFrames = blendFrames; thread->CallFunction( self, func, true ); animBlendFrames = blendFrames; lastAnimBlendFrames = blendFrames; disabled = false; idleAnim = false; if( ai_debugScript.GetInteger() == self->entityNumber ) { gameLocal.Printf( "%d: %s: Animstate: %s\n", gameLocal.time, self->name.c_str(), state.c_str() ); } } /* ===================== idAnimState::StopAnim ===================== */ void idAnimState::StopAnim( int frames ) { animBlendFrames = 0; animator->Clear( channel, gameLocal.time, FRAME2MS( frames ) ); } /* ===================== idAnimState::PlayAnim ===================== */ void idAnimState::PlayAnim( int anim ) { if( anim ) { animator->PlayAnim( channel, anim, gameLocal.time, FRAME2MS( animBlendFrames ) ); } animBlendFrames = 0; } /* ===================== idAnimState::CycleAnim ===================== */ void idAnimState::CycleAnim( int anim ) { if( anim ) { animator->CycleAnim( channel, anim, gameLocal.time, FRAME2MS( animBlendFrames ) ); } animBlendFrames = 0; } /* ===================== idAnimState::BecomeIdle ===================== */ void idAnimState::BecomeIdle() { idleAnim = true; } /* ===================== idAnimState::Disabled ===================== */ bool idAnimState::Disabled() const { return disabled; } /* ===================== idAnimState::AnimDone ===================== */ bool idAnimState::AnimDone( int blendFrames ) const { int animDoneTime; animDoneTime = animator->CurrentAnim( channel )->GetEndTime(); if( animDoneTime < 0 ) { // playing a cycle return false; } else if( animDoneTime - FRAME2MS( blendFrames ) <= gameLocal.time ) { return true; } else { return false; } } /* ===================== idAnimState::IsIdle ===================== */ bool idAnimState::IsIdle() const { return disabled || idleAnim; } /* ===================== idAnimState::GetAnimFlags ===================== */ animFlags_t idAnimState::GetAnimFlags() const { animFlags_t flags; memset( &flags, 0, sizeof( flags ) ); if( !disabled && !AnimDone( 0 ) ) { flags = animator->GetAnimFlags( animator->CurrentAnim( channel )->AnimNum() ); } return flags; } /* ===================== idAnimState::Enable ===================== */ void idAnimState::Enable( int blendFrames ) { if( disabled ) { disabled = false; animBlendFrames = blendFrames; lastAnimBlendFrames = blendFrames; if( state.Length() ) { SetState( state.c_str(), blendFrames ); } } } /* ===================== idAnimState::Disable ===================== */ void idAnimState::Disable() { disabled = true; idleAnim = false; } /* ===================== idAnimState::UpdateState ===================== */ bool idAnimState::UpdateState() { if( disabled ) { return false; } if( ai_debugScript.GetInteger() == self->entityNumber ) { thread->EnableDebugInfo(); } else { thread->DisableDebugInfo(); } thread->Execute(); return true; } /*********************************************************************** idActor ***********************************************************************/ const idEventDef AI_EnableEyeFocus( "enableEyeFocus" ); const idEventDef AI_DisableEyeFocus( "disableEyeFocus" ); const idEventDef EV_Footstep( "footstep" ); const idEventDef EV_FootstepLeft( "leftFoot" ); const idEventDef EV_FootstepRight( "rightFoot" ); const idEventDef EV_EnableWalkIK( "EnableWalkIK" ); const idEventDef EV_DisableWalkIK( "DisableWalkIK" ); const idEventDef EV_EnableLegIK( "EnableLegIK", "d" ); const idEventDef EV_DisableLegIK( "DisableLegIK", "d" ); const idEventDef AI_StopAnim( "stopAnim", "dd" ); const idEventDef AI_PlayAnim( "playAnim", "ds", 'd' ); const idEventDef AI_PlayCycle( "playCycle", "ds", 'd' ); const idEventDef AI_IdleAnim( "idleAnim", "ds", 'd' ); const idEventDef AI_SetSyncedAnimWeight( "setSyncedAnimWeight", "ddf" ); const idEventDef AI_SetBlendFrames( "setBlendFrames", "dd" ); const idEventDef AI_GetBlendFrames( "getBlendFrames", "d", 'd' ); const idEventDef AI_AnimState( "animState", "dsd" ); const idEventDef AI_GetAnimState( "getAnimState", "d", 's' ); const idEventDef AI_InAnimState( "inAnimState", "ds", 'd' ); const idEventDef AI_FinishAction( "finishAction", "s" ); const idEventDef AI_AnimDone( "animDone", "dd", 'd' ); const idEventDef AI_OverrideAnim( "overrideAnim", "d" ); const idEventDef AI_EnableAnim( "enableAnim", "dd" ); const idEventDef AI_PreventPain( "preventPain", "f" ); const idEventDef AI_DisablePain( "disablePain" ); const idEventDef AI_EnablePain( "enablePain" ); const idEventDef AI_GetPainAnim( "getPainAnim", NULL, 's' ); const idEventDef AI_SetAnimPrefix( "setAnimPrefix", "s" ); const idEventDef AI_HasAnim( "hasAnim", "ds", 'f' ); const idEventDef AI_CheckAnim( "checkAnim", "ds" ); const idEventDef AI_ChooseAnim( "chooseAnim", "ds", 's' ); const idEventDef AI_AnimLength( "animLength", "ds", 'f' ); const idEventDef AI_AnimDistance( "animDistance", "ds", 'f' ); const idEventDef AI_HasEnemies( "hasEnemies", NULL, 'd' ); const idEventDef AI_NextEnemy( "nextEnemy", "E", 'e' ); const idEventDef AI_ClosestEnemyToPoint( "closestEnemyToPoint", "v", 'e' ); const idEventDef AI_SetNextState( "setNextState", "s" ); const idEventDef AI_SetState( "setState", "s" ); const idEventDef AI_GetState( "getState", NULL, 's' ); const idEventDef AI_GetHead( "getHead", NULL, 'e' ); CLASS_DECLARATION( idAFEntity_Gibbable, idActor ) EVENT( AI_EnableEyeFocus, idActor::Event_EnableEyeFocus ) EVENT( AI_DisableEyeFocus, idActor::Event_DisableEyeFocus ) EVENT( EV_Footstep, idActor::Event_Footstep ) EVENT( EV_FootstepLeft, idActor::Event_Footstep ) EVENT( EV_FootstepRight, idActor::Event_Footstep ) EVENT( EV_EnableWalkIK, idActor::Event_EnableWalkIK ) EVENT( EV_DisableWalkIK, idActor::Event_DisableWalkIK ) EVENT( EV_EnableLegIK, idActor::Event_EnableLegIK ) EVENT( EV_DisableLegIK, idActor::Event_DisableLegIK ) EVENT( AI_PreventPain, idActor::Event_PreventPain ) EVENT( AI_DisablePain, idActor::Event_DisablePain ) EVENT( AI_EnablePain, idActor::Event_EnablePain ) EVENT( AI_GetPainAnim, idActor::Event_GetPainAnim ) EVENT( AI_SetAnimPrefix, idActor::Event_SetAnimPrefix ) EVENT( AI_StopAnim, idActor::Event_StopAnim ) EVENT( AI_PlayAnim, idActor::Event_PlayAnim ) EVENT( AI_PlayCycle, idActor::Event_PlayCycle ) EVENT( AI_IdleAnim, idActor::Event_IdleAnim ) EVENT( AI_SetSyncedAnimWeight, idActor::Event_SetSyncedAnimWeight ) EVENT( AI_SetBlendFrames, idActor::Event_SetBlendFrames ) EVENT( AI_GetBlendFrames, idActor::Event_GetBlendFrames ) EVENT( AI_AnimState, idActor::Event_AnimState ) EVENT( AI_GetAnimState, idActor::Event_GetAnimState ) EVENT( AI_InAnimState, idActor::Event_InAnimState ) EVENT( AI_FinishAction, idActor::Event_FinishAction ) EVENT( AI_AnimDone, idActor::Event_AnimDone ) EVENT( AI_OverrideAnim, idActor::Event_OverrideAnim ) EVENT( AI_EnableAnim, idActor::Event_EnableAnim ) EVENT( AI_HasAnim, idActor::Event_HasAnim ) EVENT( AI_CheckAnim, idActor::Event_CheckAnim ) EVENT( AI_ChooseAnim, idActor::Event_ChooseAnim ) EVENT( AI_AnimLength, idActor::Event_AnimLength ) EVENT( AI_AnimDistance, idActor::Event_AnimDistance ) EVENT( AI_HasEnemies, idActor::Event_HasEnemies ) EVENT( AI_NextEnemy, idActor::Event_NextEnemy ) EVENT( AI_ClosestEnemyToPoint, idActor::Event_ClosestEnemyToPoint ) EVENT( EV_StopSound, idActor::Event_StopSound ) EVENT( AI_SetNextState, idActor::Event_SetNextState ) EVENT( AI_SetState, idActor::Event_SetState ) EVENT( AI_GetState, idActor::Event_GetState ) EVENT( AI_GetHead, idActor::Event_GetHead ) END_CLASS /* ===================== idActor::idActor ===================== */ idActor::idActor() { viewAxis.Identity(); scriptThread = NULL; // initialized by ConstructScriptObject, which is called by idEntity::Spawn use_combat_bbox = false; head = NULL; team = 0; rank = 0; fovDot = 0.0f; eyeOffset.Zero(); pain_debounce_time = 0; pain_delay = 0; pain_threshold = 0; state = NULL; idealState = NULL; leftEyeJoint = INVALID_JOINT; rightEyeJoint = INVALID_JOINT; soundJoint = INVALID_JOINT; modelOffset.Zero(); deltaViewAngles.Zero(); painTime = 0; allowPain = false; allowEyeFocus = false; waitState = ""; blink_anim = NULL; blink_time = 0; blink_min = 0; blink_max = 0; finalBoss = false; attachments.SetGranularity( 1 ); enemyNode.SetOwner( this ); enemyList.SetOwner( this ); } /* ===================== idActor::~idActor ===================== */ idActor::~idActor() { int i; idEntity* ent; DeconstructScriptObject(); scriptObject.Free(); StopSound( SND_CHANNEL_ANY, false ); delete combatModel; combatModel = NULL; if( head.GetEntity() ) { head.GetEntity()->ClearBody(); head.GetEntity()->PostEventMS( &EV_Remove, 0 ); } // remove any attached entities for( i = 0; i < attachments.Num(); i++ ) { ent = attachments[ i ].ent.GetEntity(); if( ent ) { ent->PostEventMS( &EV_Remove, 0 ); } } ShutdownThreads(); } /* ===================== idActor::Spawn ===================== */ void idActor::Spawn() { idEntity* ent; idStr jointName; float fovDegrees; copyJoints_t copyJoint; animPrefix = ""; state = NULL; idealState = NULL; spawnArgs.GetInt( "rank", "0", rank ); spawnArgs.GetInt( "team", "0", team ); spawnArgs.GetVector( "offsetModel", "0 0 0", modelOffset ); spawnArgs.GetBool( "use_combat_bbox", "0", use_combat_bbox ); viewAxis = GetPhysics()->GetAxis(); spawnArgs.GetFloat( "fov", "90", fovDegrees ); SetFOV( fovDegrees ); pain_debounce_time = 0; pain_delay = SEC2MS( spawnArgs.GetFloat( "pain_delay" ) ); pain_threshold = spawnArgs.GetInt( "pain_threshold" ); LoadAF(); walkIK.Init( this, IK_ANIM, modelOffset ); // the animation used to be set to the IK_ANIM at this point, but that was fixed, resulting in // attachments not binding correctly, so we're stuck setting the IK_ANIM before attaching things. animator.ClearAllAnims( gameLocal.time, 0 ); animator.SetFrame( ANIMCHANNEL_ALL, animator.GetAnim( IK_ANIM ), 0, 0, 0 ); // spawn any attachments we might have const idKeyValue* kv = spawnArgs.MatchPrefix( "def_attach", NULL ); while( kv ) { idDict args; args.Set( "classname", kv->GetValue().c_str() ); // make items non-touchable so the player can't take them out of the character's hands args.Set( "no_touch", "1" ); // don't let them drop to the floor args.Set( "dropToFloor", "0" ); gameLocal.SpawnEntityDef( args, &ent ); if( !ent ) { gameLocal.Error( "Couldn't spawn '%s' to attach to entity '%s'", kv->GetValue().c_str(), name.c_str() ); } else { Attach( ent ); } kv = spawnArgs.MatchPrefix( "def_attach", kv ); } SetupDamageGroups(); SetupHead(); // clear the bind anim animator.ClearAllAnims( gameLocal.time, 0 ); idEntity* headEnt = head.GetEntity(); idAnimator* headAnimator; if( headEnt ) { headAnimator = headEnt->GetAnimator(); } else { headAnimator = &animator; } if( headEnt ) { // set up the list of joints to copy to the head for( kv = spawnArgs.MatchPrefix( "copy_joint", NULL ); kv != NULL; kv = spawnArgs.MatchPrefix( "copy_joint", kv ) ) { if( kv->GetValue() == "" ) { // probably clearing out inherited key, so skip it continue; } jointName = kv->GetKey(); if( jointName.StripLeadingOnce( "copy_joint_world " ) ) { copyJoint.mod = JOINTMOD_WORLD_OVERRIDE; } else { jointName.StripLeadingOnce( "copy_joint " ); copyJoint.mod = JOINTMOD_LOCAL_OVERRIDE; } copyJoint.from = animator.GetJointHandle( jointName ); if( copyJoint.from == INVALID_JOINT ) { gameLocal.Warning( "Unknown copy_joint '%s' on entity %s", jointName.c_str(), name.c_str() ); continue; } jointName = kv->GetValue(); copyJoint.to = headAnimator->GetJointHandle( jointName ); if( copyJoint.to == INVALID_JOINT ) { gameLocal.Warning( "Unknown copy_joint '%s' on head of entity %s", jointName.c_str(), name.c_str() ); continue; } copyJoints.Append( copyJoint ); } } // set up blinking blink_anim = headAnimator->GetAnim( "blink" ); blink_time = 0; // it's ok to blink right away blink_min = SEC2MS( spawnArgs.GetFloat( "blink_min", "0.5" ) ); blink_max = SEC2MS( spawnArgs.GetFloat( "blink_max", "8" ) ); // set up the head anim if necessary int headAnim = headAnimator->GetAnim( "def_head" ); if( headAnim ) { if( headEnt ) { headAnimator->CycleAnim( ANIMCHANNEL_ALL, headAnim, gameLocal.time, 0 ); } else { headAnimator->CycleAnim( ANIMCHANNEL_HEAD, headAnim, gameLocal.time, 0 ); } } if( spawnArgs.GetString( "sound_bone", "", jointName ) ) { soundJoint = animator.GetJointHandle( jointName ); if( soundJoint == INVALID_JOINT ) { gameLocal.Warning( "idAnimated '%s' at (%s): cannot find joint '%s' for sound playback", name.c_str(), GetPhysics()->GetOrigin().ToString( 0 ), jointName.c_str() ); } } finalBoss = spawnArgs.GetBool( "finalBoss" ); FinishSetup(); } /* ================ idActor::FinishSetup ================ */ void idActor::FinishSetup() { const char* scriptObjectName; // setup script object if( spawnArgs.GetString( "scriptobject", NULL, &scriptObjectName ) ) { if( !scriptObject.SetType( scriptObjectName ) ) { gameLocal.Error( "Script object '%s' not found on entity '%s'.", scriptObjectName, name.c_str() ); } ConstructScriptObject(); } SetupBody(); } /* ================ idActor::SetupHead ================ */ void idActor::SetupHead() { idAFAttachment* headEnt; idStr jointName; const char* headModel; jointHandle_t joint; jointHandle_t damageJoint; int i; const idKeyValue* sndKV; // sikk - removed multiplayer //if ( gameLocal.isClient ) { // return; //} headModel = spawnArgs.GetString( "def_head", "" ); if( headModel[ 0 ] ) { jointName = spawnArgs.GetString( "head_joint" ); joint = animator.GetJointHandle( jointName ); if( joint == INVALID_JOINT ) { gameLocal.Error( "Joint '%s' not found for 'head_joint' on '%s'", jointName.c_str(), name.c_str() ); } // set the damage joint to be part of the head damage group damageJoint = joint; for( i = 0; i < damageGroups.Num(); i++ ) { if( damageGroups[ i ] == "head" ) { damageJoint = static_cast<jointHandle_t>( i ); break; } } // copy any sounds in case we have frame commands on the head idDict args; sndKV = spawnArgs.MatchPrefix( "snd_", NULL ); while( sndKV ) { args.Set( sndKV->GetKey(), sndKV->GetValue() ); sndKV = spawnArgs.MatchPrefix( "snd_", sndKV ); } headEnt = static_cast<idAFAttachment*>( gameLocal.SpawnEntityType( idAFAttachment::Type, &args ) ); headEnt->SetName( va( "%s_head", name.c_str() ) ); headEnt->SetBody( this, headModel, damageJoint ); head = headEnt; idVec3 origin; idMat3 axis; idAttachInfo& attach = attachments.Alloc(); attach.channel = animator.GetChannelForJoint( joint ); animator.GetJointTransform( joint, gameLocal.time, origin, axis ); origin = renderEntity.origin + ( origin + modelOffset ) * renderEntity.axis; attach.ent = headEnt; headEnt->SetOrigin( origin ); headEnt->SetAxis( renderEntity.axis ); headEnt->BindToJoint( this, joint, true ); } } /* ================ idActor::CopyJointsFromBodyToHead ================ */ void idActor::CopyJointsFromBodyToHead() { idEntity* headEnt = head.GetEntity(); idAnimator* headAnimator; int i; idMat3 mat; idMat3 axis; idVec3 pos; if( !headEnt ) { return; } headAnimator = headEnt->GetAnimator(); // copy the animation from the body to the head for( i = 0; i < copyJoints.Num(); i++ ) { if( copyJoints[ i ].mod == JOINTMOD_WORLD_OVERRIDE ) { mat = headEnt->GetPhysics()->GetAxis().Transpose(); GetJointWorldTransform( copyJoints[ i ].from, gameLocal.time, pos, axis ); pos -= headEnt->GetPhysics()->GetOrigin(); headAnimator->SetJointPos( copyJoints[ i ].to, copyJoints[ i ].mod, pos * mat ); headAnimator->SetJointAxis( copyJoints[ i ].to, copyJoints[ i ].mod, axis * mat ); } else { animator.GetJointLocalTransform( copyJoints[ i ].from, gameLocal.time, pos, axis ); headAnimator->SetJointPos( copyJoints[ i ].to, copyJoints[ i ].mod, pos ); headAnimator->SetJointAxis( copyJoints[ i ].to, copyJoints[ i ].mod, axis ); } } } /* ================ idActor::Restart ================ */ void idActor::Restart() { assert( !head.GetEntity() ); SetupHead(); FinishSetup(); } /* ================ idActor::Save archive object for savegame file ================ */ void idActor::Save( idSaveGame* savefile ) const { idActor* ent; int i; savefile->WriteInt( team ); savefile->WriteInt( rank ); savefile->WriteMat3( viewAxis ); savefile->WriteInt( enemyList.Num() ); for( ent = enemyList.Next(); ent != NULL; ent = ent->enemyNode.Next() ) { savefile->WriteObject( ent ); } savefile->WriteFloat( fovDot ); savefile->WriteVec3( eyeOffset ); savefile->WriteVec3( modelOffset ); savefile->WriteAngles( deltaViewAngles ); savefile->WriteInt( pain_debounce_time ); savefile->WriteInt( pain_delay ); savefile->WriteInt( pain_threshold ); savefile->WriteInt( damageGroups.Num() ); for( i = 0; i < damageGroups.Num(); i++ ) { savefile->WriteString( damageGroups[ i ] ); } savefile->WriteInt( damageScale.Num() ); for( i = 0; i < damageScale.Num(); i++ ) { savefile->WriteFloat( damageScale[ i ] ); } savefile->WriteBool( use_combat_bbox ); head.Save( savefile ); savefile->WriteInt( copyJoints.Num() ); for( i = 0; i < copyJoints.Num(); i++ ) { savefile->WriteInt( copyJoints[i].mod ); savefile->WriteJoint( copyJoints[i].from ); savefile->WriteJoint( copyJoints[i].to ); } savefile->WriteJoint( leftEyeJoint ); savefile->WriteJoint( rightEyeJoint ); savefile->WriteJoint( soundJoint ); walkIK.Save( savefile ); savefile->WriteString( animPrefix ); savefile->WriteString( painAnim ); savefile->WriteInt( blink_anim ); savefile->WriteInt( blink_time ); savefile->WriteInt( blink_min ); savefile->WriteInt( blink_max ); // script variables savefile->WriteObject( scriptThread ); savefile->WriteString( waitState ); headAnim.Save( savefile ); torsoAnim.Save( savefile ); legsAnim.Save( savefile ); savefile->WriteBool( allowPain ); savefile->WriteBool( allowEyeFocus ); savefile->WriteInt( painTime ); savefile->WriteInt( attachments.Num() ); for( i = 0; i < attachments.Num(); i++ ) { attachments[i].ent.Save( savefile ); savefile->WriteInt( attachments[i].channel ); } savefile->WriteBool( finalBoss ); idToken token; //FIXME: this is unneccesary if( state ) { idLexer src( state->Name(), idStr::Length( state->Name() ), "idAI::Save" ); src.ReadTokenOnLine( &token ); src.ExpectTokenString( "::" ); src.ReadTokenOnLine( &token ); savefile->WriteString( token ); } else { savefile->WriteString( "" ); } if( idealState ) { idLexer src( idealState->Name(), idStr::Length( idealState->Name() ), "idAI::Save" ); src.ReadTokenOnLine( &token ); src.ExpectTokenString( "::" ); src.ReadTokenOnLine( &token ); savefile->WriteString( token ); } else { savefile->WriteString( "" ); } } /* ================ idActor::Restore unarchives object from save game file ================ */ void idActor::Restore( idRestoreGame* savefile ) { int i, num; idActor* ent; savefile->ReadInt( team ); savefile->ReadInt( rank ); savefile->ReadMat3( viewAxis ); savefile->ReadInt( num ); for( i = 0; i < num; i++ ) { savefile->ReadObject( reinterpret_cast<idClass*&>( ent ) ); assert( ent ); if( ent ) { ent->enemyNode.AddToEnd( enemyList ); } } savefile->ReadFloat( fovDot ); savefile->ReadVec3( eyeOffset ); savefile->ReadVec3( modelOffset ); savefile->ReadAngles( deltaViewAngles ); savefile->ReadInt( pain_debounce_time ); savefile->ReadInt( pain_delay ); savefile->ReadInt( pain_threshold ); savefile->ReadInt( num ); damageGroups.SetGranularity( 1 ); damageGroups.SetNum( num ); for( i = 0; i < num; i++ ) { savefile->ReadString( damageGroups[ i ] ); } savefile->ReadInt( num ); damageScale.SetNum( num ); for( i = 0; i < num; i++ ) { savefile->ReadFloat( damageScale[ i ] ); } savefile->ReadBool( use_combat_bbox ); head.Restore( savefile ); savefile->ReadInt( num ); copyJoints.SetNum( num ); for( i = 0; i < num; i++ ) { int val; savefile->ReadInt( val ); copyJoints[i].mod = static_cast<jointModTransform_t>( val ); savefile->ReadJoint( copyJoints[i].from ); savefile->ReadJoint( copyJoints[i].to ); } savefile->ReadJoint( leftEyeJoint ); savefile->ReadJoint( rightEyeJoint ); savefile->ReadJoint( soundJoint ); walkIK.Restore( savefile ); savefile->ReadString( animPrefix ); savefile->ReadString( painAnim ); savefile->ReadInt( blink_anim ); savefile->ReadInt( blink_time ); savefile->ReadInt( blink_min ); savefile->ReadInt( blink_max ); savefile->ReadObject( reinterpret_cast<idClass*&>( scriptThread ) ); savefile->ReadString( waitState ); headAnim.Restore( savefile ); torsoAnim.Restore( savefile ); legsAnim.Restore( savefile ); savefile->ReadBool( allowPain ); savefile->ReadBool( allowEyeFocus ); savefile->ReadInt( painTime ); savefile->ReadInt( num ); for( i = 0; i < num; i++ ) { idAttachInfo& attach = attachments.Alloc(); attach.ent.Restore( savefile ); savefile->ReadInt( attach.channel ); } savefile->ReadBool( finalBoss ); idStr statename; savefile->ReadString( statename ); if( statename.Length() > 0 ) { state = GetScriptFunction( statename ); } savefile->ReadString( statename ); if( statename.Length() > 0 ) { idealState = GetScriptFunction( statename ); } } /* ================ idActor::Hide ================ */ void idActor::Hide() { idEntity* ent; idEntity* next; idAFEntity_Base::Hide(); if( head.GetEntity() ) { head.GetEntity()->Hide(); } for( ent = GetNextTeamEntity(); ent != NULL; ent = next ) { next = ent->GetNextTeamEntity(); if( ent->GetBindMaster() == this ) { ent->Hide(); if( ent->IsType( idLight::Type ) ) { static_cast<idLight*>( ent )->Off(); } } } UnlinkCombat(); } /* ================ idActor::Show ================ */ void idActor::Show() { idEntity* ent; idEntity* next; idAFEntity_Base::Show(); if( head.GetEntity() ) { head.GetEntity()->Show(); } for( ent = GetNextTeamEntity(); ent != NULL; ent = next ) { next = ent->GetNextTeamEntity(); if( ent->GetBindMaster() == this ) { ent->Show(); if( ent->IsType( idLight::Type ) ) { static_cast<idLight*>( ent )->On(); } } } LinkCombat(); } /* ============== idActor::GetDefaultSurfaceType ============== */ int idActor::GetDefaultSurfaceType() const { return SURFTYPE_FLESH; } /* ================ idActor::ProjectOverlay ================ */ void idActor::ProjectOverlay( const idVec3& origin, const idVec3& dir, float size, const char* material ) { idEntity* ent; idEntity* next; idEntity::ProjectOverlay( origin, dir, size, material ); for( ent = GetNextTeamEntity(); ent != NULL; ent = next ) { next = ent->GetNextTeamEntity(); if( ent->GetBindMaster() == this ) { if( ent->fl.takedamage && ent->spawnArgs.GetBool( "bleed" ) ) { ent->ProjectOverlay( origin, dir, size, material ); } } } } /* ================ idActor::LoadAF ================ */ bool idActor::LoadAF() { idStr fileName; if( !spawnArgs.GetString( "ragdoll", "*unknown*", fileName ) || !fileName.Length() ) { return false; } af.SetAnimator( GetAnimator() ); return af.Load( this, fileName ); } /* ===================== idActor::SetupBody ===================== */ void idActor::SetupBody() { const char* jointname; animator.ClearAllAnims( gameLocal.time, 0 ); animator.ClearAllJoints(); idEntity* headEnt = head.GetEntity(); if( headEnt ) { jointname = spawnArgs.GetString( "bone_leftEye" ); leftEyeJoint = headEnt->GetAnimator()->GetJointHandle( jointname ); jointname = spawnArgs.GetString( "bone_rightEye" ); rightEyeJoint = headEnt->GetAnimator()->GetJointHandle( jointname ); // set up the eye height. check if it's specified in the def. if( !spawnArgs.GetFloat( "eye_height", "0", eyeOffset.z ) ) { // if not in the def, then try to base it off the idle animation int anim = headEnt->GetAnimator()->GetAnim( "idle" ); if( anim && ( leftEyeJoint != INVALID_JOINT ) ) { idVec3 pos; idMat3 axis; headEnt->GetAnimator()->PlayAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, 0 ); headEnt->GetAnimator()->GetJointTransform( leftEyeJoint, gameLocal.time, pos, axis ); headEnt->GetAnimator()->ClearAllAnims( gameLocal.time, 0 ); headEnt->GetAnimator()->ForceUpdate(); pos += headEnt->GetPhysics()->GetOrigin() - GetPhysics()->GetOrigin(); eyeOffset = pos + modelOffset; } else { // just base it off the bounding box size eyeOffset.z = GetPhysics()->GetBounds()[ 1 ].z - 6; } } headAnim.Init( this, headEnt->GetAnimator(), ANIMCHANNEL_ALL ); } else { jointname = spawnArgs.GetString( "bone_leftEye" ); leftEyeJoint = animator.GetJointHandle( jointname ); jointname = spawnArgs.GetString( "bone_rightEye" ); rightEyeJoint = animator.GetJointHandle( jointname ); // set up the eye height. check if it's specified in the def. if( !spawnArgs.GetFloat( "eye_height", "0", eyeOffset.z ) ) { // if not in the def, then try to base it off the idle animation int anim = animator.GetAnim( "idle" ); if( anim && ( leftEyeJoint != INVALID_JOINT ) ) { idVec3 pos; idMat3 axis; animator.PlayAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, 0 ); animator.GetJointTransform( leftEyeJoint, gameLocal.time, pos, axis ); animator.ClearAllAnims( gameLocal.time, 0 ); animator.ForceUpdate(); eyeOffset = pos + modelOffset; } else { // just base it off the bounding box size eyeOffset.z = GetPhysics()->GetBounds()[ 1 ].z - 6; } } headAnim.Init( this, &animator, ANIMCHANNEL_HEAD ); } waitState = ""; torsoAnim.Init( this, &animator, ANIMCHANNEL_TORSO ); legsAnim.Init( this, &animator, ANIMCHANNEL_LEGS ); } /* ===================== idActor::CheckBlink ===================== */ void idActor::CheckBlink() { // check if it's time to blink if( !blink_anim || ( health <= 0 ) || !allowEyeFocus || ( blink_time > gameLocal.time ) ) { return; } idEntity* headEnt = head.GetEntity(); if( headEnt ) { headEnt->GetAnimator()->PlayAnim( ANIMCHANNEL_EYELIDS, blink_anim, gameLocal.time, 1 ); } else { animator.PlayAnim( ANIMCHANNEL_EYELIDS, blink_anim, gameLocal.time, 1 ); } // set the next blink time blink_time = gameLocal.time + blink_min + gameLocal.random.RandomFloat() * ( blink_max - blink_min ); } /* ================ idActor::GetPhysicsToVisualTransform ================ */ bool idActor::GetPhysicsToVisualTransform( idVec3& origin, idMat3& axis ) { if( af.IsActive() ) { af.GetPhysicsToVisualTransform( origin, axis ); return true; } origin = modelOffset; axis = viewAxis; return true; } /* ================ idActor::GetPhysicsToSoundTransform ================ */ bool idActor::GetPhysicsToSoundTransform( idVec3& origin, idMat3& axis ) { if( soundJoint != INVALID_JOINT ) { animator.GetJointTransform( soundJoint, gameLocal.time, origin, axis ); origin += modelOffset; axis = viewAxis; } else { origin = GetPhysics()->GetGravityNormal() * -eyeOffset.z; axis.Identity(); } return true; } /*********************************************************************** script state management ***********************************************************************/ /* ================ idActor::ShutdownThreads ================ */ void idActor::ShutdownThreads() { headAnim.Shutdown(); torsoAnim.Shutdown(); legsAnim.Shutdown(); if( scriptThread ) { scriptThread->EndThread(); scriptThread->PostEventMS( &EV_Remove, 0 ); delete scriptThread; scriptThread = NULL; } } /* ================ idActor::ShouldConstructScriptObjectAtSpawn Called during idEntity::Spawn to see if it should construct the script object or not. Overridden by subclasses that need to spawn the script object themselves. ================ */ bool idActor::ShouldConstructScriptObjectAtSpawn() const { return false; } /* ================ idActor::ConstructScriptObject Called during idEntity::Spawn. Calls the constructor on the script object. Can be overridden by subclasses when a thread doesn't need to be allocated. ================ */ idThread* idActor::ConstructScriptObject() { const function_t* constructor; // make sure we have a scriptObject if( !scriptObject.HasObject() ) { gameLocal.Error( "No scriptobject set on '%s'. Check the '%s' entityDef.", name.c_str(), GetEntityDefName() ); } if( !scriptThread ) { // create script thread scriptThread = new idThread(); scriptThread->ManualDelete(); scriptThread->ManualControl(); scriptThread->SetThreadName( name.c_str() ); } else { scriptThread->EndThread(); } // call script object's constructor constructor = scriptObject.GetConstructor(); if( !constructor ) { gameLocal.Error( "Missing constructor on '%s' for entity '%s'", scriptObject.GetTypeName(), name.c_str() ); } // init the script object's data scriptObject.ClearObject(); // just set the current function on the script. we'll execute in the subclasses. scriptThread->CallFunction( this, constructor, true ); return scriptThread; } /* ===================== idActor::GetScriptFunction ===================== */ const function_t* idActor::GetScriptFunction( const char* funcname ) { const function_t* func; func = scriptObject.GetFunction( funcname ); if( !func ) { scriptThread->Error( "Unknown function '%s' in '%s'", funcname, scriptObject.GetTypeName() ); } return func; } /* ===================== idActor::SetState ===================== */ void idActor::SetState( const function_t* newState ) { if( !newState ) { gameLocal.Error( "idActor::SetState: Null state" ); } if( ai_debugScript.GetInteger() == entityNumber ) { gameLocal.Printf( "%d: %s: State: %s\n", gameLocal.time, name.c_str(), newState->Name() ); } state = newState; idealState = state; scriptThread->CallFunction( this, state, true ); } /* ===================== idActor::SetState ===================== */ void idActor::SetState( const char* statename ) { const function_t* newState; newState = GetScriptFunction( statename ); SetState( newState ); } /* ===================== idActor::UpdateScript ===================== */ void idActor::UpdateScript() { int i; if( ai_debugScript.GetInteger() == entityNumber ) { scriptThread->EnableDebugInfo(); } else { scriptThread->DisableDebugInfo(); } // a series of state changes can happen in a single frame. // this loop limits them in case we've entered an infinite loop. for( i = 0; i < 20; i++ ) { if( idealState != state ) { SetState( idealState ); } // don't call script until it's done waiting if( scriptThread->IsWaiting() ) { break; } scriptThread->Execute(); if( idealState == state ) { break; } } if( i == 20 ) { scriptThread->Warning( "idActor::UpdateScript: exited loop to prevent lockup" ); } } /*********************************************************************** vision ***********************************************************************/ /* ===================== idActor::setFov ===================== */ void idActor::SetFOV( float fov ) { fovDot = ( float )cos( DEG2RAD( fov * 0.5f ) ); } /* ===================== idActor::SetEyeHeight ===================== */ void idActor::SetEyeHeight( float height ) { eyeOffset.z = height; } /* ===================== idActor::EyeHeight ===================== */ float idActor::EyeHeight() const { return eyeOffset.z; } /* ===================== idActor::EyeOffset ===================== */ idVec3 idActor::EyeOffset() const { return GetPhysics()->GetGravityNormal() * -eyeOffset.z; } /* ===================== idActor::GetEyePosition ===================== */ idVec3 idActor::GetEyePosition() const { return GetPhysics()->GetOrigin() + ( GetPhysics()->GetGravityNormal() * -eyeOffset.z ); } /* ===================== idActor::GetViewPos ===================== */ void idActor::GetViewPos( idVec3& origin, idMat3& axis ) const { origin = GetEyePosition(); axis = viewAxis; } /* ===================== idActor::CheckFOV ===================== */ bool idActor::CheckFOV( const idVec3& pos ) const { if( fovDot == 1.0f ) { return true; } float dot; idVec3 delta; delta = pos - GetEyePosition(); // get our gravity normal const idVec3& gravityDir = GetPhysics()->GetGravityNormal(); // infinite vertical vision, so project it onto our orientation plane delta -= gravityDir * ( gravityDir * delta ); delta.Normalize(); dot = viewAxis[ 0 ] * delta; return ( dot >= fovDot ); } /* ===================== idActor::CanSee ===================== */ bool idActor::CanSee( idEntity* ent, bool useFov ) const { trace_t tr; idVec3 eye; idVec3 toPos; if( ent->IsHidden() ) { return false; } if( ent->IsType( idActor::Type ) ) { toPos = ( ( idActor* )ent )->GetEyePosition(); } else { toPos = ent->GetPhysics()->GetOrigin(); } if( useFov && !CheckFOV( toPos ) ) { return false; } eye = GetEyePosition(); gameLocal.clip.TracePoint( tr, eye, toPos, MASK_OPAQUE, this ); if( tr.fraction >= 1.0f || ( gameLocal.GetTraceEntity( tr ) == ent ) ) { return true; } return false; } /* ===================== idActor::PointVisible ===================== */ bool idActor::PointVisible( const idVec3& point ) const { trace_t results; idVec3 start, end; start = GetEyePosition(); end = point; end[2] += 1.0f; gameLocal.clip.TracePoint( results, start, end, MASK_OPAQUE, this ); return ( results.fraction >= 1.0f ); } /* ===================== idActor::GetAIAimTargets Returns positions for the AI to aim at. ===================== */ void idActor::GetAIAimTargets( const idVec3& lastSightPos, idVec3& headPos, idVec3& chestPos ) { headPos = lastSightPos + EyeOffset(); chestPos = ( headPos + lastSightPos + GetPhysics()->GetBounds().GetCenter() ) * 0.5f; } /* ===================== idActor::GetRenderView ===================== */ renderView_t* idActor::GetRenderView() { renderView_t* rv = idEntity::GetRenderView(); rv->viewaxis = viewAxis; rv->vieworg = GetEyePosition(); return rv; } /*********************************************************************** Model/Ragdoll ***********************************************************************/ /* ================ idActor::SetCombatModel ================ */ void idActor::SetCombatModel() { idAFAttachment* headEnt; if( !use_combat_bbox ) { if( combatModel ) { combatModel->Unlink(); combatModel->LoadModel( modelDefHandle ); } else { combatModel = new idClipModel( modelDefHandle ); } headEnt = head.GetEntity(); if( headEnt ) { headEnt->SetCombatModel(); } } } /* ================ idActor::GetCombatModel ================ */ idClipModel* idActor::GetCombatModel() const { return combatModel; } /* ================ idActor::LinkCombat ================ */ void idActor::LinkCombat() { idAFAttachment* headEnt; if( fl.hidden || use_combat_bbox ) { return; } if( combatModel ) { combatModel->Link( gameLocal.clip, this, 0, renderEntity.origin, renderEntity.axis, modelDefHandle ); } headEnt = head.GetEntity(); if( headEnt ) { headEnt->LinkCombat(); } } /* ================ idActor::UnlinkCombat ================ */ void idActor::UnlinkCombat() { idAFAttachment* headEnt; if( combatModel ) { combatModel->Unlink(); } headEnt = head.GetEntity(); if( headEnt ) { headEnt->UnlinkCombat(); } } /* ================ idActor::StartRagdoll ================ */ bool idActor::StartRagdoll() { float slomoStart, slomoEnd; float jointFrictionDent, jointFrictionDentStart, jointFrictionDentEnd; float contactFrictionDent, contactFrictionDentStart, contactFrictionDentEnd; // if no AF loaded if( !af.IsLoaded() ) { return false; } // if the AF is already active if( af.IsActive() ) { return true; } // disable the monster bounding box GetPhysics()->DisableClip(); // start using the AF af.StartFromCurrentPose( spawnArgs.GetInt( "velocityTime", "0" ) ); slomoStart = MS2SEC( gameLocal.time ) + spawnArgs.GetFloat( "ragdoll_slomoStart", "-1.6" ); slomoEnd = MS2SEC( gameLocal.time ) + spawnArgs.GetFloat( "ragdoll_slomoEnd", "0.8" ); // do the first part of the death in slow motion af.GetPhysics()->SetTimeScaleRamp( slomoStart, slomoEnd ); jointFrictionDent = spawnArgs.GetFloat( "ragdoll_jointFrictionDent", "0.1" ); jointFrictionDentStart = MS2SEC( gameLocal.time ) + spawnArgs.GetFloat( "ragdoll_jointFrictionStart", "0.2" ); jointFrictionDentEnd = MS2SEC( gameLocal.time ) + spawnArgs.GetFloat( "ragdoll_jointFrictionEnd", "1.2" ); // set joint friction dent af.GetPhysics()->SetJointFrictionDent( jointFrictionDent, jointFrictionDentStart, jointFrictionDentEnd ); contactFrictionDent = spawnArgs.GetFloat( "ragdoll_contactFrictionDent", "0.1" ); contactFrictionDentStart = MS2SEC( gameLocal.time ) + spawnArgs.GetFloat( "ragdoll_contactFrictionStart", "1.0" ); contactFrictionDentEnd = MS2SEC( gameLocal.time ) + spawnArgs.GetFloat( "ragdoll_contactFrictionEnd", "2.0" ); // set contact friction dent af.GetPhysics()->SetContactFrictionDent( contactFrictionDent, contactFrictionDentStart, contactFrictionDentEnd ); // drop any items the actor is holding idMoveableItem::DropItems( this, "death", NULL ); // drop any articulated figures the actor is holding idAFEntity_Base::DropAFs( this, "death", NULL ); RemoveAttachments(); return true; } /* ================ idActor::StopRagdoll ================ */ void idActor::StopRagdoll() { if( af.IsActive() ) { af.Stop(); } } /* ================ idActor::UpdateAnimationControllers ================ */ bool idActor::UpdateAnimationControllers() { if( af.IsActive() ) { return idAFEntity_Base::UpdateAnimationControllers(); } else { animator.ClearAFPose(); } if( walkIK.IsInitialized() ) { walkIK.Evaluate(); return true; } return false; } /* ================ idActor::RemoveAttachments ================ */ void idActor::RemoveAttachments() { int i; idEntity* ent; // remove any attached entities for( i = 0; i < attachments.Num(); i++ ) { ent = attachments[ i ].ent.GetEntity(); if( ent && ent->spawnArgs.GetBool( "remove" ) ) { ent->PostEventMS( &EV_Remove, 0 ); } } } /* ================ idActor::Attach ================ */ void idActor::Attach( idEntity* ent ) { idVec3 origin; idMat3 axis; jointHandle_t joint; idStr jointName; idAttachInfo& attach = attachments.Alloc(); idAngles angleOffset; idVec3 originOffset; jointName = ent->spawnArgs.GetString( "joint" ); joint = animator.GetJointHandle( jointName ); if( joint == INVALID_JOINT ) { gameLocal.Error( "Joint '%s' not found for attaching '%s' on '%s'", jointName.c_str(), ent->GetClassname(), name.c_str() ); } angleOffset = ent->spawnArgs.GetAngles( "angles" ); originOffset = ent->spawnArgs.GetVector( "origin" ); attach.channel = animator.GetChannelForJoint( joint ); GetJointWorldTransform( joint, gameLocal.time, origin, axis ); attach.ent = ent; ent->SetOrigin( origin + originOffset * renderEntity.axis ); idMat3 rotate = angleOffset.ToMat3(); idMat3 newAxis = rotate * axis; ent->SetAxis( newAxis ); ent->BindToJoint( this, joint, true ); ent->cinematic = cinematic; } /* ================ idActor::Teleport ================ */ void idActor::Teleport( const idVec3& origin, const idAngles& angles, idEntity* destination ) { GetPhysics()->SetOrigin( origin + idVec3( 0, 0, CM_CLIP_EPSILON ) ); GetPhysics()->SetLinearVelocity( vec3_origin ); viewAxis = angles.ToMat3(); UpdateVisuals(); if( !IsHidden() ) { // kill anything at the new position gameLocal.KillBox( this ); } } /* ================ idActor::GetDeltaViewAngles ================ */ const idAngles& idActor::GetDeltaViewAngles() const { return deltaViewAngles; } /* ================ idActor::SetDeltaViewAngles ================ */ void idActor::SetDeltaViewAngles( const idAngles& delta ) { deltaViewAngles = delta; } /* ================ idActor::HasEnemies ================ */ bool idActor::HasEnemies() const { idActor* ent; for( ent = enemyList.Next(); ent != NULL; ent = ent->enemyNode.Next() ) { if( !ent->fl.hidden ) { return true; } } return false; } /* ================ idActor::ClosestEnemyToPoint ================ */ idActor* idActor::ClosestEnemyToPoint( const idVec3& pos ) { idActor* ent; idActor* bestEnt; float bestDistSquared; float distSquared; idVec3 delta; bestDistSquared = idMath::INFINITY; bestEnt = NULL; for( ent = enemyList.Next(); ent != NULL; ent = ent->enemyNode.Next() ) { if( ent->fl.hidden ) { continue; } delta = ent->GetPhysics()->GetOrigin() - pos; distSquared = delta.LengthSqr(); if( distSquared < bestDistSquared ) { bestEnt = ent; bestDistSquared = distSquared; } } return bestEnt; } /* ================ idActor::EnemyWithMostHealth ================ */ idActor* idActor::EnemyWithMostHealth() { idActor* ent; idActor* bestEnt; int most = -9999; bestEnt = NULL; for( ent = enemyList.Next(); ent != NULL; ent = ent->enemyNode.Next() ) { if( !ent->fl.hidden && ( ent->health > most ) ) { bestEnt = ent; most = ent->health; } } return bestEnt; } /* ================ idActor::OnLadder ================ */ bool idActor::OnLadder() const { return false; } /* ============== idActor::GetAASLocation ============== */ void idActor::GetAASLocation( idAAS* aas, idVec3& pos, int& areaNum ) const { idVec3 size; idBounds bounds; GetFloorPos( 64.0f, pos ); if( !aas ) { areaNum = 0; return; } size = aas->GetSettings()->boundingBoxes[0][1]; bounds[0] = -size; size.z = 32.0f; bounds[1] = size; areaNum = aas->PointReachableAreaNum( pos, bounds, AREA_REACHABLE_WALK ); if( areaNum ) { aas->PushPointIntoAreaNum( areaNum, pos ); } } /*********************************************************************** animation state ***********************************************************************/ /* ===================== idActor::SetAnimState ===================== */ void idActor::SetAnimState( int channel, const char* statename, int blendFrames ) { const function_t* func; func = scriptObject.GetFunction( statename ); if( !func ) { assert( 0 ); gameLocal.Error( "Can't find function '%s' in object '%s'", statename, scriptObject.GetTypeName() ); } switch( channel ) { case ANIMCHANNEL_HEAD : headAnim.SetState( statename, blendFrames ); allowEyeFocus = true; break; case ANIMCHANNEL_TORSO : torsoAnim.SetState( statename, blendFrames ); legsAnim.Enable( blendFrames ); allowPain = true; allowEyeFocus = true; break; case ANIMCHANNEL_LEGS : legsAnim.SetState( statename, blendFrames ); torsoAnim.Enable( blendFrames ); allowPain = true; allowEyeFocus = true; break; default: gameLocal.Error( "idActor::SetAnimState: Unknown anim group" ); break; } } /* ===================== idActor::GetAnimState ===================== */ const char* idActor::GetAnimState( int channel ) const { switch( channel ) { case ANIMCHANNEL_HEAD : return headAnim.state; break; case ANIMCHANNEL_TORSO : return torsoAnim.state; break; case ANIMCHANNEL_LEGS : return legsAnim.state; break; default: gameLocal.Error( "idActor::GetAnimState: Unknown anim group" ); return NULL; break; } } /* ===================== idActor::InAnimState ===================== */ bool idActor::InAnimState( int channel, const char* statename ) const { switch( channel ) { case ANIMCHANNEL_HEAD : if( headAnim.state == statename ) { return true; } break; case ANIMCHANNEL_TORSO : if( torsoAnim.state == statename ) { return true; } break; case ANIMCHANNEL_LEGS : if( legsAnim.state == statename ) { return true; } break; default: gameLocal.Error( "idActor::InAnimState: Unknown anim group" ); break; } return false; } /* ===================== idActor::WaitState ===================== */ const char* idActor::WaitState() const { if( waitState.Length() ) { return waitState; } else { return NULL; } } /* ===================== idActor::SetWaitState ===================== */ void idActor::SetWaitState( const char* _waitstate ) { waitState = _waitstate; } /* ===================== idActor::UpdateAnimState ===================== */ void idActor::UpdateAnimState() { headAnim.UpdateState(); torsoAnim.UpdateState(); legsAnim.UpdateState(); } /* ===================== idActor::GetAnim ===================== */ int idActor::GetAnim( int channel, const char* animname ) { int anim; const char* temp; idAnimator* animatorPtr; if( channel == ANIMCHANNEL_HEAD ) { if( !head.GetEntity() ) { return 0; } animatorPtr = head.GetEntity()->GetAnimator(); } else { animatorPtr = &animator; } if( animPrefix.Length() ) { temp = va( "%s_%s", animPrefix.c_str(), animname ); anim = animatorPtr->GetAnim( temp ); if( anim ) { return anim; } } anim = animatorPtr->GetAnim( animname ); return anim; } /* =============== idActor::SyncAnimChannels =============== */ void idActor::SyncAnimChannels( int channel, int syncToChannel, int blendFrames ) { idAnimator* headAnimator; idAFAttachment* headEnt; int anim; idAnimBlend* syncAnim; int starttime; int blendTime; int cycle; blendTime = FRAME2MS( blendFrames ); if( channel == ANIMCHANNEL_HEAD ) { headEnt = head.GetEntity(); if( headEnt ) { headAnimator = headEnt->GetAnimator(); syncAnim = animator.CurrentAnim( syncToChannel ); if( syncAnim ) { anim = headAnimator->GetAnim( syncAnim->AnimFullName() ); if( !anim ) { anim = headAnimator->GetAnim( syncAnim->AnimName() ); } if( anim ) { cycle = animator.CurrentAnim( syncToChannel )->GetCycleCount(); starttime = animator.CurrentAnim( syncToChannel )->GetStartTime(); headAnimator->PlayAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, blendTime ); headAnimator->CurrentAnim( ANIMCHANNEL_ALL )->SetCycleCount( cycle ); headAnimator->CurrentAnim( ANIMCHANNEL_ALL )->SetStartTime( starttime ); } else { headEnt->PlayIdleAnim( blendTime ); } } } } else if( syncToChannel == ANIMCHANNEL_HEAD ) { headEnt = head.GetEntity(); if( headEnt ) { headAnimator = headEnt->GetAnimator(); syncAnim = headAnimator->CurrentAnim( ANIMCHANNEL_ALL ); if( syncAnim ) { anim = GetAnim( channel, syncAnim->AnimFullName() ); if( !anim ) { anim = GetAnim( channel, syncAnim->AnimName() ); } if( anim ) { cycle = headAnimator->CurrentAnim( ANIMCHANNEL_ALL )->GetCycleCount(); starttime = headAnimator->CurrentAnim( ANIMCHANNEL_ALL )->GetStartTime(); animator.PlayAnim( channel, anim, gameLocal.time, blendTime ); animator.CurrentAnim( channel )->SetCycleCount( cycle ); animator.CurrentAnim( channel )->SetStartTime( starttime ); } } } } else { animator.SyncAnimChannels( channel, syncToChannel, gameLocal.time, blendTime ); } } /*********************************************************************** Damage ***********************************************************************/ /* ============ idActor::Gib ============ */ void idActor::Gib( const idVec3& dir, const char* damageDefName ) { // no gibbing in multiplayer - by self damage or by moving objects // sikk - removed multiplayer //if ( gameLocal.isMultiplayer ) { // return; //} // only gib once if( gibbed ) { return; } idAFEntity_Gibbable::Gib( dir, damageDefName ); if( head.GetEntity() ) { head.GetEntity()->Hide(); } StopSound( SND_CHANNEL_VOICE, false ); } /* ============ idActor::Damage this entity that is being damaged inflictor entity that is causing the damage attacker entity that caused the inflictor to damage targ example: this=monster, inflictor=rocket, attacker=player dir direction of the attack for knockback in global space point point at which the damage is being inflicted, used for headshots damage amount of damage being inflicted inflictor, attacker, dir, and point can be NULL for environmental effects Bleeding wounds and surface overlays are applied in the collision code that calls Damage() ============ */ void idActor::Damage( idEntity* inflictor, idEntity* attacker, const idVec3& dir, const char* damageDefName, const float damageScale, const int location ) { if( !fl.takedamage ) { return; } if( !inflictor ) { inflictor = gameLocal.world; } if( !attacker ) { attacker = gameLocal.world; } // sikk - removed so "finalBoss" can be used for other things //if ( finalBoss && !inflictor->IsType( idSoulCubeMissile::Type ) ) { // return; //} // ---> sikk - Monsters of the same class do not damage each other if( IsType( idAI::Type ) && attacker->IsType( idAI::Type ) ) { const char* classname; const char* attackerclassname; spawnArgs.GetString( "classname", NULL, &classname ); attacker->spawnArgs.GetString( "classname", NULL, &attackerclassname ); if( !idStr::Icmp( classname, attackerclassname ) ) { return; } } // <--- sikk - Monsters of the same class do not damage each other const idDict* damageDef = gameLocal.FindEntityDefDict( damageDefName ); if( !damageDef ) { gameLocal.Error( "Unknown damageDef '%s'", damageDefName ); } int damage = damageDef->GetInt( "damage" ) * damageScale; damage = GetDamageForLocation( damage, location ); // inform the attacker that they hit someone attacker->DamageFeedback( this, inflictor, damage ); if( damage > 0 ) { // ---> sikk - Level Stats System: Add damage to level stat if( attacker && attacker->IsType( idPlayer::Type ) && inflictor ) { static_cast< idPlayer* >( attacker )->AddToLevelStat( DAMAGEDEALT, damage ); } // <--- sikk - Level Stats System // sikk - Added damage debug for idActor's if( g_debugDamage.GetInteger() ) { gameLocal.Printf( "entity:%i health:%i damage:%i damageScale:%f\n", entityNumber, health, damage, damageScale ); } health -= damage; if( health <= 0 ) { if( health < -999 ) { health = -999; } renderEntity.shaderParms[ 9 ] = damageDef->GetInt( "killType", "0" ); // sikk - Custom Kill Types bool forceGib = damageDef->GetBool( "forceGib" ); if( attacker->IsType( idPlayer::Type ) && static_cast<idPlayer*>( attacker )->comboFull ) { forceGib = true; } Killed( inflictor, attacker, damage, dir, location ); if( ( health < spawnArgs.GetInt( "gibHealth", "-20" ) && spawnArgs.GetBool( "gib" ) && damageDef->GetBool( "gib" ) ) || forceGib ) // sikk - Always gib { renderEntity.shaderParms[ 9 ] = -1; // if it's gibbed, we don't do a burn away, just remove it immediately in the script Gib( dir, damageDefName ); } } else { Pain( inflictor, attacker, damage, dir, location ); } } else { // don't accumulate knockback if( af.IsLoaded() ) { // clear impacts af.Rest(); // physics is turned off by calling af.Rest() BecomeActive( TH_PHYSICS ); } } } /* ===================== idActor::ClearPain ===================== */ void idActor::ClearPain() { pain_debounce_time = 0; } /* ===================== idActor::Pain ===================== */ bool idActor::Pain( idEntity* inflictor, idEntity* attacker, int damage, const idVec3& dir, int location ) { if( af.IsLoaded() ) { // clear impacts af.Rest(); // physics is turned off by calling af.Rest() BecomeActive( TH_PHYSICS ); } if( gameLocal.time < pain_debounce_time ) { return false; } // don't play pain sounds more than necessary pain_debounce_time = gameLocal.time + pain_delay; if( health > 75 ) { StartSound( "snd_pain_small", SND_CHANNEL_VOICE, 0, false, NULL ); } else if( health > 50 ) { StartSound( "snd_pain_medium", SND_CHANNEL_VOICE, 0, false, NULL ); } else if( health > 25 ) { StartSound( "snd_pain_large", SND_CHANNEL_VOICE, 0, false, NULL ); } else { StartSound( "snd_pain_huge", SND_CHANNEL_VOICE, 0, false, NULL ); } if( !allowPain || ( gameLocal.time < painTime ) ) { // don't play a pain anim return false; } if( pain_threshold && ( damage < pain_threshold ) ) { return false; } // set the pain anim idStr damageGroup = GetDamageGroup( location ); painAnim = ""; if( animPrefix.Length() ) { if( damageGroup.Length() && ( damageGroup != "legs" ) ) { sprintf( painAnim, "%s_pain_%s", animPrefix.c_str(), damageGroup.c_str() ); if( !animator.HasAnim( painAnim ) ) { sprintf( painAnim, "pain_%s", damageGroup.c_str() ); if( !animator.HasAnim( painAnim ) ) { painAnim = ""; } } } if( !painAnim.Length() ) { sprintf( painAnim, "%s_pain", animPrefix.c_str() ); if( !animator.HasAnim( painAnim ) ) { painAnim = ""; } } } else if( damageGroup.Length() && ( damageGroup != "legs" ) ) { sprintf( painAnim, "pain_%s", damageGroup.c_str() ); if( !animator.HasAnim( painAnim ) ) { sprintf( painAnim, "pain_%s", damageGroup.c_str() ); if( !animator.HasAnim( painAnim ) ) { painAnim = ""; } } } if( !painAnim.Length() ) { painAnim = "pain"; } if( g_debugDamage.GetBool() ) { gameLocal.Printf( "Damage: joint: '%s', zone '%s', anim '%s'\n", animator.GetJointName( ( jointHandle_t )location ), damageGroup.c_str(), painAnim.c_str() ); } return true; } /* ===================== idActor::SpawnGibs ===================== */ void idActor::SpawnGibs( const idVec3& dir, const char* damageDefName ) { idAFEntity_Gibbable::SpawnGibs( dir, damageDefName ); RemoveAttachments(); } /* ===================== idActor::SetupDamageGroups FIXME: only store group names once and store an index for each joint ===================== */ void idActor::SetupDamageGroups() { int i; const idKeyValue* arg; idStr groupname; idList<jointHandle_t> jointList; int jointnum; float scale; // create damage zones damageGroups.SetNum( animator.NumJoints() ); arg = spawnArgs.MatchPrefix( "damage_zone ", NULL ); while( arg ) { groupname = arg->GetKey(); groupname.Strip( "damage_zone " ); animator.GetJointList( arg->GetValue(), jointList ); for( i = 0; i < jointList.Num(); i++ ) { jointnum = jointList[ i ]; damageGroups[ jointnum ] = groupname; } jointList.Clear(); arg = spawnArgs.MatchPrefix( "damage_zone ", arg ); } // initilize the damage zones to normal damage damageScale.SetNum( animator.NumJoints() ); for( i = 0; i < damageScale.Num(); i++ ) { damageScale[ i ] = 1.0f; } // set the percentage on damage zones arg = spawnArgs.MatchPrefix( "damage_scale ", NULL ); while( arg ) { scale = atof( arg->GetValue() ); groupname = arg->GetKey(); groupname.Strip( "damage_scale " ); for( i = 0; i < damageScale.Num(); i++ ) { if( damageGroups[ i ] == groupname ) { damageScale[ i ] = scale; } } arg = spawnArgs.MatchPrefix( "damage_scale ", arg ); } } /* ===================== idActor::GetDamageForLocation ===================== */ int idActor::GetDamageForLocation( int damage, int location ) { if( ( location < 0 ) || ( location >= damageScale.Num() ) ) { return damage; } return ( int )ceil( damage * damageScale[ location ] ); } /* ===================== idActor::GetDamageGroup ===================== */ const char* idActor::GetDamageGroup( int location ) { if( ( location < 0 ) || ( location >= damageGroups.Num() ) ) { return ""; } return damageGroups[ location ]; } /*********************************************************************** Events ***********************************************************************/ /* ===================== idActor::PlayFootStepSound ===================== */ void idActor::PlayFootStepSound() { const char* sound = NULL; const idMaterial* material; if( !GetPhysics()->HasGroundContacts() ) { return; } // start footstep sound based on material type material = GetPhysics()->GetContact( 0 ).material; if( material != NULL ) { sound = spawnArgs.GetString( va( "snd_footstep_%s", gameLocal.sufaceTypeNames[ material->GetSurfaceType() ] ) ); } if( *sound == '\0' ) { sound = spawnArgs.GetString( "snd_footstep" ); } if( *sound != '\0' ) { StartSoundShader( declManager->FindSound( sound ), SND_CHANNEL_BODY, 0, false, NULL ); } } /* ===================== idActor::Event_EnableEyeFocus ===================== */ void idActor::Event_EnableEyeFocus() { allowEyeFocus = true; blink_time = gameLocal.time + blink_min + gameLocal.random.RandomFloat() * ( blink_max - blink_min ); } /* ===================== idActor::Event_DisableEyeFocus ===================== */ void idActor::Event_DisableEyeFocus() { allowEyeFocus = false; idEntity* headEnt = head.GetEntity(); if( headEnt ) { headEnt->GetAnimator()->Clear( ANIMCHANNEL_EYELIDS, gameLocal.time, FRAME2MS( 2 ) ); } else { animator.Clear( ANIMCHANNEL_EYELIDS, gameLocal.time, FRAME2MS( 2 ) ); } } /* =============== idActor::Event_Footstep =============== */ void idActor::Event_Footstep() { PlayFootStepSound(); } /* ===================== idActor::Event_EnableWalkIK ===================== */ void idActor::Event_EnableWalkIK() { walkIK.EnableAll(); } /* ===================== idActor::Event_DisableWalkIK ===================== */ void idActor::Event_DisableWalkIK() { walkIK.DisableAll(); } /* ===================== idActor::Event_EnableLegIK ===================== */ void idActor::Event_EnableLegIK( int num ) { walkIK.EnableLeg( num ); } /* ===================== idActor::Event_DisableLegIK ===================== */ void idActor::Event_DisableLegIK( int num ) { walkIK.DisableLeg( num ); } /* ===================== idActor::Event_PreventPain ===================== */ void idActor::Event_PreventPain( float duration ) { painTime = gameLocal.time + SEC2MS( duration ); } /* =============== idActor::Event_DisablePain =============== */ void idActor::Event_DisablePain() { allowPain = false; } /* =============== idActor::Event_EnablePain =============== */ void idActor::Event_EnablePain() { allowPain = true; } /* ===================== idActor::Event_GetPainAnim ===================== */ void idActor::Event_GetPainAnim() { if( !painAnim.Length() ) { idThread::ReturnString( "pain" ); } else { idThread::ReturnString( painAnim ); } } /* ===================== idActor::Event_SetAnimPrefix ===================== */ void idActor::Event_SetAnimPrefix( const char* prefix ) { animPrefix = prefix; } /* =============== idActor::Event_StopAnim =============== */ void idActor::Event_StopAnim( int channel, int frames ) { switch( channel ) { case ANIMCHANNEL_HEAD : headAnim.StopAnim( frames ); break; case ANIMCHANNEL_TORSO : torsoAnim.StopAnim( frames ); break; case ANIMCHANNEL_LEGS : legsAnim.StopAnim( frames ); break; default: gameLocal.Error( "Unknown anim group" ); break; } } /* =============== idActor::Event_PlayAnim =============== */ void idActor::Event_PlayAnim( int channel, const char* animname ) { animFlags_t flags; idEntity* headEnt; int anim; anim = GetAnim( channel, animname ); if( !anim ) { if( ( channel == ANIMCHANNEL_HEAD ) && head.GetEntity() ) { gameLocal.DPrintf( "missing '%s' animation on '%s' (%s)\n", animname, name.c_str(), spawnArgs.GetString( "def_head", "" ) ); } else { gameLocal.DPrintf( "missing '%s' animation on '%s' (%s)\n", animname, name.c_str(), GetEntityDefName() ); } idThread::ReturnInt( 0 ); return; } switch( channel ) { case ANIMCHANNEL_HEAD : headEnt = head.GetEntity(); if( headEnt ) { headAnim.idleAnim = false; headAnim.PlayAnim( anim ); flags = headAnim.GetAnimFlags(); if( !flags.prevent_idle_override ) { if( torsoAnim.IsIdle() ) { torsoAnim.animBlendFrames = headAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_HEAD, headAnim.lastAnimBlendFrames ); if( legsAnim.IsIdle() ) { legsAnim.animBlendFrames = headAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_HEAD, headAnim.lastAnimBlendFrames ); } } } } break; case ANIMCHANNEL_TORSO : torsoAnim.idleAnim = false; torsoAnim.PlayAnim( anim ); flags = torsoAnim.GetAnimFlags(); if( !flags.prevent_idle_override ) { if( headAnim.IsIdle() ) { headAnim.animBlendFrames = torsoAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } if( legsAnim.IsIdle() ) { legsAnim.animBlendFrames = torsoAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } } break; case ANIMCHANNEL_LEGS : legsAnim.idleAnim = false; legsAnim.PlayAnim( anim ); flags = legsAnim.GetAnimFlags(); if( !flags.prevent_idle_override ) { if( torsoAnim.IsIdle() ) { torsoAnim.animBlendFrames = legsAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); if( headAnim.IsIdle() ) { headAnim.animBlendFrames = legsAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); } } } break; default : gameLocal.Error( "Unknown anim group" ); break; } idThread::ReturnInt( 1 ); } /* =============== idActor::Event_PlayCycle =============== */ void idActor::Event_PlayCycle( int channel, const char* animname ) { animFlags_t flags; int anim; anim = GetAnim( channel, animname ); if( !anim ) { if( ( channel == ANIMCHANNEL_HEAD ) && head.GetEntity() ) { gameLocal.DPrintf( "missing '%s' animation on '%s' (%s)\n", animname, name.c_str(), spawnArgs.GetString( "def_head", "" ) ); } else { gameLocal.DPrintf( "missing '%s' animation on '%s' (%s)\n", animname, name.c_str(), GetEntityDefName() ); } idThread::ReturnInt( false ); return; } switch( channel ) { case ANIMCHANNEL_HEAD : headAnim.idleAnim = false; headAnim.CycleAnim( anim ); flags = headAnim.GetAnimFlags(); if( !flags.prevent_idle_override ) { if( torsoAnim.IsIdle() && legsAnim.IsIdle() ) { torsoAnim.animBlendFrames = headAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_HEAD, headAnim.lastAnimBlendFrames ); legsAnim.animBlendFrames = headAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_HEAD, headAnim.lastAnimBlendFrames ); } } break; case ANIMCHANNEL_TORSO : torsoAnim.idleAnim = false; torsoAnim.CycleAnim( anim ); flags = torsoAnim.GetAnimFlags(); if( !flags.prevent_idle_override ) { if( headAnim.IsIdle() ) { headAnim.animBlendFrames = torsoAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } if( legsAnim.IsIdle() ) { legsAnim.animBlendFrames = torsoAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } } break; case ANIMCHANNEL_LEGS : legsAnim.idleAnim = false; legsAnim.CycleAnim( anim ); flags = legsAnim.GetAnimFlags(); if( !flags.prevent_idle_override ) { if( torsoAnim.IsIdle() ) { torsoAnim.animBlendFrames = legsAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); if( headAnim.IsIdle() ) { headAnim.animBlendFrames = legsAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); } } } break; default: gameLocal.Error( "Unknown anim group" ); } idThread::ReturnInt( true ); } /* =============== idActor::Event_IdleAnim =============== */ void idActor::Event_IdleAnim( int channel, const char* animname ) { int anim; anim = GetAnim( channel, animname ); if( !anim ) { if( ( channel == ANIMCHANNEL_HEAD ) && head.GetEntity() ) { gameLocal.DPrintf( "missing '%s' animation on '%s' (%s)\n", animname, name.c_str(), spawnArgs.GetString( "def_head", "" ) ); } else { gameLocal.DPrintf( "missing '%s' animation on '%s' (%s)\n", animname, name.c_str(), GetEntityDefName() ); } switch( channel ) { case ANIMCHANNEL_HEAD : headAnim.BecomeIdle(); break; case ANIMCHANNEL_TORSO : torsoAnim.BecomeIdle(); break; case ANIMCHANNEL_LEGS : legsAnim.BecomeIdle(); break; default: gameLocal.Error( "Unknown anim group" ); } idThread::ReturnInt( false ); return; } switch( channel ) { case ANIMCHANNEL_HEAD : headAnim.BecomeIdle(); if( torsoAnim.GetAnimFlags().prevent_idle_override ) { // don't sync to torso body if it doesn't override idle anims headAnim.CycleAnim( anim ); } else if( torsoAnim.IsIdle() && legsAnim.IsIdle() ) { // everything is idle, so play the anim on the head and copy it to the torso and legs headAnim.CycleAnim( anim ); torsoAnim.animBlendFrames = headAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_HEAD, headAnim.lastAnimBlendFrames ); legsAnim.animBlendFrames = headAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_HEAD, headAnim.lastAnimBlendFrames ); } else if( torsoAnim.IsIdle() ) { // sync the head and torso to the legs SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_LEGS, headAnim.animBlendFrames ); torsoAnim.animBlendFrames = headAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_LEGS, torsoAnim.animBlendFrames ); } else { // sync the head to the torso SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_TORSO, headAnim.animBlendFrames ); } break; case ANIMCHANNEL_TORSO : torsoAnim.BecomeIdle(); if( legsAnim.GetAnimFlags().prevent_idle_override ) { // don't sync to legs if legs anim doesn't override idle anims torsoAnim.CycleAnim( anim ); } else if( legsAnim.IsIdle() ) { // play the anim in both legs and torso torsoAnim.CycleAnim( anim ); legsAnim.animBlendFrames = torsoAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } else { // sync the anim to the legs SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_LEGS, torsoAnim.animBlendFrames ); } if( headAnim.IsIdle() ) { SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } break; case ANIMCHANNEL_LEGS : legsAnim.BecomeIdle(); if( torsoAnim.GetAnimFlags().prevent_idle_override ) { // don't sync to torso if torso anim doesn't override idle anims legsAnim.CycleAnim( anim ); } else if( torsoAnim.IsIdle() ) { // play the anim in both legs and torso legsAnim.CycleAnim( anim ); torsoAnim.animBlendFrames = legsAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); if( headAnim.IsIdle() ) { SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); } } else { // sync the anim to the torso SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_TORSO, legsAnim.animBlendFrames ); } break; default: gameLocal.Error( "Unknown anim group" ); } idThread::ReturnInt( true ); } /* ================ idActor::Event_SetSyncedAnimWeight ================ */ void idActor::Event_SetSyncedAnimWeight( int channel, int anim, float weight ) { idEntity* headEnt; headEnt = head.GetEntity(); switch( channel ) { case ANIMCHANNEL_HEAD : if( headEnt ) { animator.CurrentAnim( ANIMCHANNEL_ALL )->SetSyncedAnimWeight( anim, weight ); } else { animator.CurrentAnim( ANIMCHANNEL_HEAD )->SetSyncedAnimWeight( anim, weight ); } if( torsoAnim.IsIdle() ) { animator.CurrentAnim( ANIMCHANNEL_TORSO )->SetSyncedAnimWeight( anim, weight ); if( legsAnim.IsIdle() ) { animator.CurrentAnim( ANIMCHANNEL_LEGS )->SetSyncedAnimWeight( anim, weight ); } } break; case ANIMCHANNEL_TORSO : animator.CurrentAnim( ANIMCHANNEL_TORSO )->SetSyncedAnimWeight( anim, weight ); if( legsAnim.IsIdle() ) { animator.CurrentAnim( ANIMCHANNEL_LEGS )->SetSyncedAnimWeight( anim, weight ); } if( headEnt && headAnim.IsIdle() ) { animator.CurrentAnim( ANIMCHANNEL_ALL )->SetSyncedAnimWeight( anim, weight ); } break; case ANIMCHANNEL_LEGS : animator.CurrentAnim( ANIMCHANNEL_LEGS )->SetSyncedAnimWeight( anim, weight ); if( torsoAnim.IsIdle() ) { animator.CurrentAnim( ANIMCHANNEL_TORSO )->SetSyncedAnimWeight( anim, weight ); if( headEnt && headAnim.IsIdle() ) { animator.CurrentAnim( ANIMCHANNEL_ALL )->SetSyncedAnimWeight( anim, weight ); } } break; default: gameLocal.Error( "Unknown anim group" ); } } /* =============== idActor::Event_OverrideAnim =============== */ void idActor::Event_OverrideAnim( int channel ) { switch( channel ) { case ANIMCHANNEL_HEAD : headAnim.Disable(); if( !torsoAnim.IsIdle() ) { SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } else { SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); } break; case ANIMCHANNEL_TORSO : torsoAnim.Disable(); SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); if( headAnim.IsIdle() ) { SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } break; case ANIMCHANNEL_LEGS : legsAnim.Disable(); SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); break; default: gameLocal.Error( "Unknown anim group" ); break; } } /* =============== idActor::Event_EnableAnim =============== */ void idActor::Event_EnableAnim( int channel, int blendFrames ) { switch( channel ) { case ANIMCHANNEL_HEAD : headAnim.Enable( blendFrames ); break; case ANIMCHANNEL_TORSO : torsoAnim.Enable( blendFrames ); break; case ANIMCHANNEL_LEGS : legsAnim.Enable( blendFrames ); break; default: gameLocal.Error( "Unknown anim group" ); break; } } /* =============== idActor::Event_SetBlendFrames =============== */ void idActor::Event_SetBlendFrames( int channel, int blendFrames ) { switch( channel ) { case ANIMCHANNEL_HEAD : headAnim.animBlendFrames = blendFrames; headAnim.lastAnimBlendFrames = blendFrames; break; case ANIMCHANNEL_TORSO : torsoAnim.animBlendFrames = blendFrames; torsoAnim.lastAnimBlendFrames = blendFrames; break; case ANIMCHANNEL_LEGS : legsAnim.animBlendFrames = blendFrames; legsAnim.lastAnimBlendFrames = blendFrames; break; default: gameLocal.Error( "Unknown anim group" ); break; } } /* =============== idActor::Event_GetBlendFrames =============== */ void idActor::Event_GetBlendFrames( int channel ) { switch( channel ) { case ANIMCHANNEL_HEAD : idThread::ReturnInt( headAnim.animBlendFrames ); break; case ANIMCHANNEL_TORSO : idThread::ReturnInt( torsoAnim.animBlendFrames ); break; case ANIMCHANNEL_LEGS : idThread::ReturnInt( legsAnim.animBlendFrames ); break; default: gameLocal.Error( "Unknown anim group" ); break; } } /* =============== idActor::Event_AnimState =============== */ void idActor::Event_AnimState( int channel, const char* statename, int blendFrames ) { SetAnimState( channel, statename, blendFrames ); } /* =============== idActor::Event_GetAnimState =============== */ void idActor::Event_GetAnimState( int channel ) { const char* state; state = GetAnimState( channel ); idThread::ReturnString( state ); } /* =============== idActor::Event_InAnimState =============== */ void idActor::Event_InAnimState( int channel, const char* statename ) { bool instate; instate = InAnimState( channel, statename ); idThread::ReturnInt( instate ); } /* =============== idActor::Event_FinishAction =============== */ void idActor::Event_FinishAction( const char* actionname ) { if( waitState == actionname ) { SetWaitState( "" ); } } /* =============== idActor::Event_AnimDone =============== */ void idActor::Event_AnimDone( int channel, int blendFrames ) { bool result; switch( channel ) { case ANIMCHANNEL_HEAD : result = headAnim.AnimDone( blendFrames ); idThread::ReturnInt( result ); break; case ANIMCHANNEL_TORSO : result = torsoAnim.AnimDone( blendFrames ); idThread::ReturnInt( result ); break; case ANIMCHANNEL_LEGS : result = legsAnim.AnimDone( blendFrames ); idThread::ReturnInt( result ); break; default: gameLocal.Error( "Unknown anim group" ); } } /* ================ idActor::Event_HasAnim ================ */ void idActor::Event_HasAnim( int channel, const char* animname ) { if( GetAnim( channel, animname ) != NULL ) { idThread::ReturnFloat( 1.0f ); } else { idThread::ReturnFloat( 0.0f ); } } /* ================ idActor::Event_CheckAnim ================ */ void idActor::Event_CheckAnim( int channel, const char* animname ) { if( !GetAnim( channel, animname ) ) { if( animPrefix.Length() ) { gameLocal.Error( "Can't find anim '%s_%s' for '%s'", animPrefix.c_str(), animname, name.c_str() ); } else { gameLocal.Error( "Can't find anim '%s' for '%s'", animname, name.c_str() ); } } } /* ================ idActor::Event_ChooseAnim ================ */ void idActor::Event_ChooseAnim( int channel, const char* animname ) { int anim; anim = GetAnim( channel, animname ); if( anim ) { if( channel == ANIMCHANNEL_HEAD ) { if( head.GetEntity() ) { idThread::ReturnString( head.GetEntity()->GetAnimator()->AnimFullName( anim ) ); return; } } else { idThread::ReturnString( animator.AnimFullName( anim ) ); return; } } idThread::ReturnString( "" ); } /* ================ idActor::Event_AnimLength ================ */ void idActor::Event_AnimLength( int channel, const char* animname ) { int anim; anim = GetAnim( channel, animname ); if( anim ) { if( channel == ANIMCHANNEL_HEAD ) { if( head.GetEntity() ) { idThread::ReturnFloat( MS2SEC( head.GetEntity()->GetAnimator()->AnimLength( anim ) ) ); return; } } else { idThread::ReturnFloat( MS2SEC( animator.AnimLength( anim ) ) ); return; } } idThread::ReturnFloat( 0.0f ); } /* ================ idActor::Event_AnimDistance ================ */ void idActor::Event_AnimDistance( int channel, const char* animname ) { int anim; anim = GetAnim( channel, animname ); if( anim ) { if( channel == ANIMCHANNEL_HEAD ) { if( head.GetEntity() ) { idThread::ReturnFloat( head.GetEntity()->GetAnimator()->TotalMovementDelta( anim ).Length() ); return; } } else { idThread::ReturnFloat( animator.TotalMovementDelta( anim ).Length() ); return; } } idThread::ReturnFloat( 0.0f ); } /* ================ idActor::Event_HasEnemies ================ */ void idActor::Event_HasEnemies() { bool hasEnemy; hasEnemy = HasEnemies(); idThread::ReturnInt( hasEnemy ); } /* ================ idActor::Event_NextEnemy ================ */ void idActor::Event_NextEnemy( idEntity* ent ) { idActor* actor; if( !ent || ( ent == this ) ) { actor = enemyList.Next(); } else { if( !ent->IsType( idActor::Type ) ) { gameLocal.Error( "'%s' cannot be an enemy", ent->name.c_str() ); } actor = static_cast<idActor*>( ent ); if( actor->enemyNode.ListHead() != &enemyList ) { gameLocal.Error( "'%s' is not in '%s' enemy list", actor->name.c_str(), name.c_str() ); } } for( ; actor != NULL; actor = actor->enemyNode.Next() ) { if( !actor->fl.hidden ) { idThread::ReturnEntity( actor ); return; } } idThread::ReturnEntity( NULL ); } /* ================ idActor::Event_ClosestEnemyToPoint ================ */ void idActor::Event_ClosestEnemyToPoint( const idVec3& pos ) { idActor* bestEnt = ClosestEnemyToPoint( pos ); idThread::ReturnEntity( bestEnt ); } /* ================ idActor::Event_StopSound ================ */ void idActor::Event_StopSound( int channel, int netSync ) { if( channel == SND_CHANNEL_VOICE ) { idEntity* headEnt = head.GetEntity(); if( headEnt ) { headEnt->StopSound( channel, ( netSync != 0 ) ); } } StopSound( channel, ( netSync != 0 ) ); } /* ===================== idActor::Event_SetNextState ===================== */ void idActor::Event_SetNextState( const char* name ) { idealState = GetScriptFunction( name ); if( idealState == state ) { state = NULL; } } /* ===================== idActor::Event_SetState ===================== */ void idActor::Event_SetState( const char* name ) { idealState = GetScriptFunction( name ); if( idealState == state ) { state = NULL; } scriptThread->DoneProcessing(); } /* ===================== idActor::Event_GetState ===================== */ void idActor::Event_GetState() { if( state ) { idThread::ReturnString( state->Name() ); } else { idThread::ReturnString( "" ); } } /* ===================== idActor::Event_GetHead ===================== */ void idActor::Event_GetHead() { idThread::ReturnEntity( head.GetEntity() ); }
RobertBeckebans/Sikkpin-Feedback
neo/game/Actor.cpp
C++
gpl-3.0
82,129
// Copyright 2007, 2008 Joe White // // This file is part of DGrok <http://www.excastle.com/dgrok/>. // // DGrok 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. // // DGrok 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 DGrok. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Text; using DGrok.Framework; using DGrok.Visitors; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; namespace DGrok.Tests.Visitors { [TestFixture] public class FindGlobalVariablesTests : CodeBaseActionTestCase { protected override void AddPrefix(List<string> unit) { unit.Add("unit Foo;"); unit.Add("interface"); unit.Add("implementation"); } protected override void AddSuffix(List<string> unit) { unit.Add("end."); } protected override ICodeBaseAction CreateAction() { return new FindGlobalVariables(); } [Test] public void SectionWithOneVariable() { IList<Hit> hits = HitsFor( "var", " Foo: Integer;"); Assert.That(hits.Count, Is.EqualTo(1)); Assert.That(hits[0].Description, Is.EqualTo("Foo")); } [Test] public void SectionWithTwoVariableGroups() { IList<Hit> hits = HitsFor( "var", " Foo, Bar: Integer;", " Baz, Quux: Boolean;"); Assert.That(hits.Count, Is.EqualTo(4)); Assert.That(hits[0].Description, Is.EqualTo("Foo")); Assert.That(hits[1].Description, Is.EqualTo("Bar")); Assert.That(hits[2].Description, Is.EqualTo("Baz")); Assert.That(hits[3].Description, Is.EqualTo("Quux")); } [Test] public void TypedConstantsDoNotHit() { IList<Hit> hits = HitsFor( "const", " Foo: Integer = 42;"); Assert.That(hits.Count, Is.EqualTo(0)); } [Test] public void LocalVariablesDoNotHit() { IList<Hit> hits = HitsFor( "procedure Foo;", "var", " Foo: Integer;", "begin", "end;"); Assert.That(hits.Count, Is.EqualTo(0)); } [Test] public void ClassVariablesDoNotHit() { IList<Hit> hits = HitsFor( "type", " TFoo = class", " var", " Foo: Integer;", " end;"); Assert.That(hits.Count, Is.EqualTo(0)); } [Test] public void RecordVariablesDoNotHit() { IList<Hit> hits = HitsFor( "type", " TFoo = record", " var", " Foo: Integer;", " end;"); Assert.That(hits.Count, Is.EqualTo(0)); } [Test] public void VarParametersDoNotHit() { IList<Hit> hits = HitsFor( "procedure Foo(var X: Integer);", "begin", "end;"); Assert.That(hits.Count, Is.EqualTo(0)); } } }
Turbo87/DGrok
DGrok.Tests/Visitors/FindGlobalVariablesTests.cs
C#
gpl-3.0
3,875
isc.defineClass("BrewClubs", "myWindow").addProperties({ initWidget: function(initData){ this.Super("initWidget", arguments); this.BrewClubsDS = isc.myDataSource.create({ cacheAllData: false, dataURL: serverPath + "BrewClubs.php", showFilterEditor: true, fields:[ {name: "clubID", primaryKey: true, type: "sequence", detail: true, canEdit: false}, {name: "LastYear", width: 75, prompt: "The last year this club as invited.", canEdit: false}, {name: "clubName", width: "*"}, {name: "clubAbbr", width: 75}, {name: "distance", type: "integer", width: 65}, {name: "city", width: 150}, {name: "state", width: 50}, {name: "active", type: "text", width: 50, editorType: "selectItem", defaultValue: "Y", optionDataSource: isc.Clients.yesNoDS, displayField: "displayLOV", valueField: "valueLOV"}, {name: "lastChangeDate", type: "date", detail: true, canEdit: false} ] }); this.BrewClubsLG = isc.myListGrid.create({ dataSource: this.BrewClubsDS, name: "Brew Clubs", parent: this, showFilterEditor: true, sortField: "clubName" }); this.localContextMenu = isc.myClubMenu.create({ callingListGrid: this.BrewClubsLG, parent: this }); this.addItem(isc.myVLayout.create({members: [this.BrewClubsLG]})); this.BrewClubsLG.canEdit = checkPerms(this.getClassName() + ".js"); this.BrewClubsLG.filterData({active: "Y"}); } });
braddoro/cabrew
bluehost/smart/client/BrewClubs.js
JavaScript
gpl-3.0
1,399
class CreateTopics < ActiveRecord::Migration[5.0] def change create_table :topics do |t| t.belongs_to :forum, index: true t.belongs_to :author, :polymorphic => true, index: true t.string :name t.text :about t.integer :hits, :default => 0 t.integer :posts_count, :default => 0 t.integer :ups, :default => 0 t.integer :downs, :default => 0 t.integer :points_per_post, :default => 0 t.integer :points_per_reply, :default => 0 t.boolean :active, :default => true t.boolean :sticky, :default => false t.boolean :locked, :default => false t.boolean :anonymous, :default => false t.timestamps null: false end add_foreign_key :topics, :forums end end
curriculr/curriculr
db/migrate/20130127014729_create_topics.rb
Ruby
gpl-3.0
752
#!/usr/bin/env python from Media import Media class Movie(Media): """Inherits Media. Attributes: section_type: The type of library this is (i.e. "TV Shows") title: The title of the media item natural_start_time: The scheduled start time before any shifting happens. natural_end_time: The end time of the scheduled content. duration: The duration of the media item. day_of_week: When the content is scheduled to play is_strict_time: If strict time, then anchor to "natural_start_time" """ def __init__( self, section_type, title, natural_start_time, natural_end_time, duration, day_of_week, is_strict_time, time_shift, overlap_max, plex_media_id, custom_section_name ): super(Movie, self).__init__( section_type, title, natural_start_time, natural_end_time, duration, day_of_week, is_strict_time, time_shift, overlap_max, plex_media_id, custom_section_name )
justinemter/pseudo-channel
src/Movie.py
Python
gpl-3.0
1,306
/* eslint-disable react/prop-types */ /* eslint-disable react/destructuring-assignment */ /* eslint-disable react/prefer-stateless-function */ import React, { Component } from 'react'; import IconButton from '@material-ui/core/IconButton'; import CloseIcon from '@material-ui/icons/Close'; import { withStyles } from '@material-ui/core/styles'; const styles = { btnIco: { float: 'right', }, }; class CloseModal extends Component { render() { return ( <IconButton style={styles.btnIco} edge="start" color="inherit" onClick={() => { this.props.callbackParent(); }} aria-label="close" > <CloseIcon /> </IconButton> ); } } export default withStyles(styles)(CloseModal);
linea-it/dri
frontend/landing_page/src/pages/Home/partials/ModalInterfaces/CloseModal.js
JavaScript
gpl-3.0
772
#include "./graphics/texture.h" #include "./image/image.h" #include "./utils/log.h" #include "./utils/timer.h" #include <string> using namespace std; namespace Splash { /*************/ Texture::Texture(RootObject* root) : GraphObject(root) { init(); } /*************/ Texture::~Texture() { #ifdef DEBUG Log::get() << Log::DEBUGGING << "Texture::~Texture - Destructor" << Log::endl; #endif } /*************/ void Texture::init() { _type = "texture"; registerAttributes(); // This is used for getting documentation "offline" if (!_root) return; _timestamp = Timer::getTime(); } /*************/ bool Texture::linkTo(const shared_ptr<GraphObject>& obj) { // Mandatory before trying to link return GraphObject::linkTo(obj); } /*************/ void Texture::registerAttributes() { GraphObject::registerAttributes(); } } // namespace Splash
sat-metalab/splash
src/graphics/texture.cpp
C++
gpl-3.0
897
/* * Copyright (c) 2005, Stephan Reiter <stephan.reiter@students.jku.at>, * Christian Wressnegger <christian.wressnegger@students.jku.at> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * The names of its contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ParticleType.h" #include "ParticleEmitter.h" #include <OpenSG/OSGImage.h> #include <OpenSG/OSGBlendChunk.h> OSG_USING_NAMESPACE CParticleType::CParticleType() : m_bTextureChanged( false ) { m_pMaterial = SimpleTexturedMaterial::create(); addRefCP( m_pMaterial ); // keep internal copy // set timeline defaults m_sizeChange.SetDefaultValue( 1.0f ); m_velocityChange.SetDefaultValue( 1.0f ); m_colorChange.SetDefaultValue( Vec3f( 1.0f, 1.0f, 1.0f ) ); } CParticleType::~CParticleType() { subRefCP( m_pMaterial ); } void CParticleType::RecreateTexture() { beginEditCP( m_pMaterial ); { BlendChunkPtr bc = BlendChunk::create(); beginEditCP( bc ); { if( m_bAdditive ) { bc->setSrcFactor( GL_SRC_ALPHA ); bc->setDestFactor( GL_ONE ); } else { // TODO: nicht richtiges alpha-blending, aber gute ergebnisse bei partikel. // für alpha-blending COLOR mit ALPHA ersetzen. // bc->setSrcFactor( GL_SRC_COLOR ); // bc->setDestFactor( GL_ONE_MINUS_SRC_COLOR ); bc->setSrcFactor( GL_SRC_ALPHA ); bc->setDestFactor( GL_ONE_MINUS_SRC_COLOR ); } } endEditCP( bc ); m_pMaterial->addChunk( bc ); m_pMaterial->setLit( false ); ImagePtr pTexture = Image::create(); pTexture->read( m_sTexture.c_str() ); m_pMaterial->setImage( pTexture ); m_pMaterial->setEnvMode( GL_MODULATE ); } endEditCP( m_pMaterial ); } bool CParticleType::bUpdateParticle( particle &io_particle, Real32 i_rDeltaTime, GeoPositionsPtr i_pPos, GeoColorsPtr i_pCols, MFVec3f *i_pSizes ) const { if( io_particle.bIsDead() ) return false; Real32 rLivedFraction = io_particle.rTimeLived / io_particle.rLifeTime; io_particle.rTimeLived += i_rDeltaTime; if( i_pSizes != 0 ) { Real32 rSize = io_particle.rSize0 * m_sizeChange.GetValue( rLivedFraction ); i_pSizes->push_back( Vec3f( rSize, rSize, rSize ) ); } Vec3f velocity = io_particle.velocity0 * m_velocityChange.GetValue( rLivedFraction ); io_particle.position += velocity * i_rDeltaTime; if( i_pPos != NullFC ) i_pPos->push_back( io_particle.position ); if( i_pCols != NullFC ) { Vec3f colorChange = m_colorChange.GetValue( rLivedFraction ); i_pCols->push_back( Color3f( io_particle.color0[0] * colorChange[0], io_particle.color0[1] * colorChange[1], io_particle.color0[2] * colorChange[2] ) ); } return true; }
jzarl/inVRs
tools/libraries/Particles/ParticleType.cpp
C++
gpl-3.0
4,196
<?php /** * TextSanitizer extension * * You may not change or alter any portion of this comment or credits * of supporting developers from this source code or any supporting source code * which is considered copyrighted (c) material of the original comment or credit authors. * 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. * * @copyright The XOOPS Project http://sourceforge.net/projects/xoops/ * @license GNU GPL 2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html) * @package class * @subpackage textsanitizer * @since 2.3.0 * @author Taiwen Jiang <phppp@users.sourceforge.net> * @version $Id: config.php 8066 2011-11-06 05:09:33Z beckmi $ */ defined('XOOPS_ROOT_PATH') or die('Restricted access'); return $config = array( 'detect_dimension' => 1); ?>
labscoop/xortify
azure/class/textsanitizer/flash/config.php
PHP
gpl-3.0
974
package mx.gob.jovenes.guanajuato.activities; import android.app.ProgressDialog; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import mx.gob.jovenes.guanajuato.R; import mx.gob.jovenes.guanajuato.adapters.VPEstadisticasAdapter; import mx.gob.jovenes.guanajuato.api.EventoAPI; import mx.gob.jovenes.guanajuato.api.Response; import mx.gob.jovenes.guanajuato.application.MyApplication; import mx.gob.jovenes.guanajuato.sesion.Sesion; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Retrofit; /** * Created by codigus on 11/08/2017. */ public class EstadisticasActivity extends AppCompatActivity implements SearchView.OnQueryTextListener { private TabLayout tabs; private ViewPager viewPager; private VPEstadisticasAdapter adapter; private int idEvento; private Retrofit retrofit; private EventoAPI eventoAPI; private static final String ENVIANDO_CORREO = "Enviando correo..."; private static final String POR_FAVOR_ESPERE = "Por favor espere..."; private static final String CORREO_ENVIADO = "Correo enviado"; private static final String ERROR_AL_ENVIAR = "Error al enviar"; private static final String ERROR_NO_HAY_REGISTROS = "Evento sin registros"; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); retrofit = ((MyApplication) getApplication()).getRetrofitInstance(); eventoAPI = retrofit.create(EventoAPI.class); setContentView(R.layout.activity_estadisticas); idEvento = getIntent().getIntExtra("idEvento", 0); tabs = (TabLayout) findViewById(R.id.tabs_estadísticas); viewPager = (ViewPager) findViewById(R.id.vp_estadisticas); adapter = new VPEstadisticasAdapter(getSupportFragmentManager()); viewPager.setAdapter(adapter); tabs.setupWithViewPager(viewPager); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); tabs.getTabAt(0).setText("Registrados"); tabs.getTabAt(1).setText("Interesados"); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.item_generar_excel: ProgressDialog progressDialog = ProgressDialog.show(this, ENVIANDO_CORREO, POR_FAVOR_ESPERE, true, false); Call<Response<Boolean>> call = eventoAPI.generarExcel(idEvento, Sesion.getUsuario().getEmail()); call.enqueue(new Callback<Response<Boolean>>() { @Override public void onResponse(Call<Response<Boolean>> call, retrofit2.Response<Response<Boolean>> response) { if (response.body().errors.length == 0) { progressDialog.dismiss(); Snackbar.make(findViewById(R.id.container_estadisticas), CORREO_ENVIADO, Snackbar.LENGTH_LONG).show(); } else if (response.body().errors[0].equals(ERROR_NO_HAY_REGISTROS)){ progressDialog.dismiss(); Snackbar.make(findViewById(R.id.container_estadisticas), ERROR_NO_HAY_REGISTROS, Snackbar.LENGTH_LONG).show(); } } @Override public void onFailure(Call<Response<Boolean>> call, Throwable t) { progressDialog.dismiss(); Snackbar.make(findViewById(R.id.container_estadisticas), ERROR_AL_ENVIAR, Snackbar.LENGTH_LONG).show(); } }); break; case android.R.id.home: this.onBackPressed(); break; } return true; } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { return false; } }
leonardolb95/RegistroAEventos
app/src/main/java/mx/gob/jovenes/guanajuato/activities/EstadisticasActivity.java
Java
gpl-3.0
4,568
import { includes } from 'lodash'; import { NPC } from '../../../../../shared/models/npc'; import { Currency } from '../../../../../shared/interfaces/holiday'; import { SantasPresents } from '../../../../quests'; export const setup = async (npc: NPC) => { npc.hostility = 'Never'; npc.affiliation = 'Frosty Friends'; npc.rightHand = await npc.$$room.npcLoader.loadItem('Christmas Gift - Rainbow'); npc.gear.Armor = await npc.$$room.npcLoader.loadItem('Risan Tunic'); npc.recalculateStats(); }; export const responses = (npc: NPC) => { const updatePlayerPresentCount = (player, num: number) => { SantasPresents.updateProgress(player, { giftBoost: num }); const { gifts } = player.getQuestData(SantasPresents); // 5: carrot if(gifts >= 5 && gifts - num < 5) { npc.$$room.npcLoader.putItemInPlayerHand(player, 'Christmas Carrot'); } // 50: gem if(gifts >= 50 && gifts - num < 50) { npc.$$room.npcLoader.putItemInPlayerHand(player, 'Christmas Gem'); } // 150: coal if(gifts >= 150 && gifts - num < 150) { npc.$$room.npcLoader.putItemInPlayerHand(player, 'Christmas Coal'); } // 250: wil pot if(gifts >= 250 && gifts - num < 250) { npc.$$room.npcLoader.putItemInPlayerHand(player, 'Antanian Willpower Potion'); } // 500: snowglobe if(gifts >= 500 && gifts - num < 500) { npc.$$room.npcLoader.putItemInPlayerHand(player, 'Christmas Snowglobe'); } if(SantasPresents.isComplete(player)) { SantasPresents.completeFor(player); } }; npc.parser.addCommand('hello') .set('syntax', ['hello']) .set('logic', (args, { player }) => { if(npc.distFrom(player) > 0) return 'Please move closer.'; if(!player.hasQuest(SantasPresents)) player.startQuest(SantasPresents); if(!player.rightHand) return `Ho ho ho! Can you bring me some presents, and help me save Christmas? Maybe from your SACK to mine? Bring me a lot of gifts and I can reward you!`; if(includes(player.rightHand.name, 'Christmas Gift -')) { player.setRightHand(null); player.earnCurrency(Currency.Christmas, 15); updatePlayerPresentCount(player, 1); return 'Thanks for the gift! Here\'s 15 tokens in return!'; } return `Ho ho ho! Can you bring me some presents, and help me save Christmas? Maybe from your SACK to mine? Bring me a lot of gifts and I can reward you!`; }); npc.parser.addCommand('sack') .set('syntax', ['sack']) .set('logic', (args, { player }) => { if(npc.distFrom(player) > 0) return 'Please move closer.'; if(player.rightHand) return 'Please empty your right hand, I might have something for you!'; if(!player.hasQuest(SantasPresents)) player.startQuest(SantasPresents); const giftIndexes = npc.$$room.npcLoader.getItemsFromPlayerSackByName(player, 'Christmas Gift -', true); npc.$$room.npcLoader.takeItemsFromPlayerSack(player, giftIndexes); const tokensGained = giftIndexes.length * 15; player.earnCurrency(Currency.Christmas, tokensGained); updatePlayerPresentCount(player, giftIndexes.length); return `Woah, thanks! Here's ${tokensGained} tokens for your presents.`; }); };
seiyria/landoftherair
src/server/scripts/npc/holiday/christmas/santa.ts
TypeScript
gpl-3.0
3,257
package org.hage.util.io; import org.junit.Test; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.URISyntaxException; import static org.junit.Assert.assertNotNull; public class ClasspathResourceTest { private static final String RESOURCE_EXISTING = "classpath:org/hage/util/io/testResource.res"; private static final String RESOURCE_NOT_EXISTING = "classpath:org/hage/util/io/noResource.res"; private static final String RESOURCE_INCORRECT_URI = "claspath:org/hage/util/io/testResource.res"; @Test public void testGetInputStream() throws UnknownSchemeException, FileNotFoundException { ClasspathResource classpathResource = new ClasspathResource(RESOURCE_EXISTING); InputStream inputStream = classpathResource.getInputStream(); assertNotNull(inputStream); } @Test public void testGetUri() throws URISyntaxException, UnknownSchemeException { ClasspathResource classpathResource = new ClasspathResource(RESOURCE_EXISTING); assertNotNull(classpathResource.getUri()); } @Test(expected = FileNotFoundException.class) public void testNotExisitngResource() throws FileNotFoundException, UnknownSchemeException, URISyntaxException { ClasspathResource classpathResource = new ClasspathResource(RESOURCE_NOT_EXISTING); assertNotNull(classpathResource.getUri()); classpathResource.getInputStream(); // Should throw } @SuppressWarnings("unused") @Test(expected = UnknownSchemeException.class) public void testIncorrectUriResource() throws UnknownSchemeException { ClasspathResource classpathResource = new ClasspathResource(RESOURCE_INCORRECT_URI); // Should throw } }
ymachkivskiy/hage
platform/common-utils/src/test/java/org/hage/util/io/ClasspathResourceTest.java
Java
gpl-3.0
1,745
#---LICENSE---------------------- ''' Copyright 2014 Travel Modelling Group, Department of Civil Engineering, University of Toronto This file is part of the TMG Toolbox. The TMG Toolbox 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. The TMG Toolbox 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 TMG Toolbox. If not, see <http://www.gnu.org/licenses/>. ''' #---METADATA--------------------- ''' Returb Boardings Authors: pkucirek Latest revision by: pkucirek Returns a 'serialized' (e.g. string repr) of transit line boardings to XTMF. See XTMF for documentation. ''' #---VERSION HISTORY ''' 0.0.1 Created on 2014-02-05 by pkucirek 0.1.0 Upgraded to work with get_attribute_values (partial read) ''' import inro.modeller as _m import traceback as _traceback from contextlib import contextmanager from contextlib import nested from json import loads _MODELLER = _m.Modeller() #Instantiate Modeller once. _util = _MODELLER.module('tmg.common.utilities') _tmgTPB = _MODELLER.module('tmg.common.TMG_tool_page_builder') ########################################################################################################## class ReturnBoardings(_m.Tool()): version = '0.1.0' tool_run_msg = "" number_of_tasks = 1 # For progress reporting, enter the integer number of tasks here # Tool Input Parameters # Only those parameters necessary for Modeller and/or XTMF to dock with # need to be placed here. Internal parameters (such as lists and dicts) # get initialized during construction (__init__) xtmf_ScenarioNumber = _m.Attribute(int) # parameter used by XTMF only xtmf_LineAggregationFile = _m.Attribute(str) xtmf_CheckAggregationFlag = _m.Attribute(bool) def __init__(self): #---Init internal variables self.TRACKER = _util.ProgressTracker(self.number_of_tasks) #init the ProgressTracker def page(self): pb = _m.ToolPageBuilder(self, title="Return Boardings", description="Cannot be called from Modeller.", runnable=False, branding_text="XTMF") return pb.render() ########################################################################################################## def __call__(self, xtmf_ScenarioNumber, xtmf_LineAggregationFile, xtmf_CheckAggregationFlag): _m.logbook_write("Extracting boarding results") #---1 Set up scenario scenario = _m.Modeller().emmebank.scenario(xtmf_ScenarioNumber) if (scenario is None): raise Exception("Scenario %s was not found!" %xtmf_ScenarioNumber) if not scenario.has_transit_results: raise Exception("Scenario %s does not have transit assignment results" %xtmf_ScenarioNumber) self.xtmf_LineAggregationFile = xtmf_LineAggregationFile self.xtmf_CheckAggregationFlag = xtmf_CheckAggregationFlag try: return self._Execute(scenario) except Exception as e: msg = str(e) + "\n" + _traceback.format_exc() raise Exception(msg) ########################################################################################################## def _Execute(self, scenario): lineAggregation = self._LoadLineAggregationFile() lineBoardings = self._GetLineResults(scenario) netSet = set([key for key in lineBoardings.iterkeys()]) if self.xtmf_CheckAggregationFlag: self._CheckAggregationFile(netSet, lineAggregation) self.TRACKER.completeTask() results = {} self.TRACKER.startProcess(len(lineBoardings)) for lineId, lineCount in lineBoardings.iteritems(): if not lineId in lineAggregation: self.TRACKER.completeSubtask() continue #Skip unmapped lines lineGroupId = lineAggregation[lineId] if lineGroupId in results: results[lineGroupId] += lineCount else: results[lineGroupId] = lineCount self.TRACKER.completeSubtask() print "Extracted results from Emme" return str(results) def _LoadLineAggregationFile(self): mapping = {} with open(self.xtmf_LineAggregationFile) as reader: reader.readline() for line in reader: cells = line.strip().split(',') key = cells[0].strip() val = cells[1].strip() mapping[key] = val return mapping def _GetLineResults(self, scenario): results = _util.fastLoadSummedSegmentAttributes(scenario, ['transit_boardings']) retVal = {} for lineId, attributes in results.iteritems(): id = str(lineId) retVal[id] = attributes['transit_boardings'] return retVal def _CheckAggregationFile(self, netSet, lineAggregation): aggSet = set([key for key in lineAggregation.iterkeys()]) linesInNetworkButNotMapped = [id for id in (netSet - aggSet)] linesMappedButNotInNetwork = [id for id in (aggSet - netSet)] if len(linesMappedButNotInNetwork) > 0: msg = "%s lines have been found in the network without a line grouping: " %len(linesInNetworkButNotMapped) msg += ",".join(linesInNetworkButNotMapped[:10]) if len(linesInNetworkButNotMapped) > 10: msg += "...(%s more)" %(len(linesInNetworkButNotMapped) - 10) print msg if len(linesMappedButNotInNetwork) > 0: msg = "%s lines have been found in the aggregation file but do not exist in the network: " %len(linesMappedButNotInNetwork) msg += ",".join(linesMappedButNotInNetwork[:10]) if len(linesMappedButNotInNetwork) > 10: msg += "...(%s more)" %(len(linesMappedButNotInNetwork) - 10) print msg ########################################################################################################## @_m.method(return_type=_m.TupleType) def percent_completed(self): return self.TRACKER.getProgress() @_m.method(return_type=unicode) def tool_run_msg_status(self): return self.tool_run_msg
TravelModellingGroup/TMGToolbox
TMGToolbox/src/XTMF_internal/return_boardings.py
Python
gpl-3.0
6,999
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ManageBean; import com.hp.hpl.jena.ontology.DatatypeProperty; import com.hp.hpl.jena.ontology.Individual; import com.hp.hpl.jena.ontology.ObjectProperty; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import facadePojo.DepartamentoFacade; import facadePojo.LineainvestigacionFacade; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import pojo.Lineainvestigacion; /** * * @author mateo */ @ManagedBean(name = "lineaInvestigacionBean") @SessionScoped public class LineaInvestigacionBean { private List<Lineainvestigacion> listaLineaInvestigacion; private List<Lineainvestigacion> listaLineaInvestigacionSelecionada; private Lineainvestigacion lineaInvestigacionSelecionada; @EJB LineainvestigacionFacade lineaInvestigacionFacade; @EJB DepartamentoFacade departamentoFacade; private String codigoLinea; private String nombre; private String descripcion; private String codDep; private String clase = "Linea_investigacion"; public String getCodigoLinea() { return codigoLinea; } public void setCodigoLinea(String codigoLinea) { this.codigoLinea = codigoLinea; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getCodDep() { return codDep; } public void setCodDep(String codDep) { this.codDep = codDep; } public List<Lineainvestigacion> getListaLineaInvestigacion() { return listaLineaInvestigacion; } public void setListaLineaInvestigacion(List<Lineainvestigacion> listaLineaInvestigacion) { this.listaLineaInvestigacion = listaLineaInvestigacion; } public List<Lineainvestigacion> getListaLineaInvestigacionSelecionada() { return listaLineaInvestigacionSelecionada; } public void setListaLineaInvestigacionSelecionada(List<Lineainvestigacion> listaLineaInvestigacionSelecionada) { this.listaLineaInvestigacionSelecionada = listaLineaInvestigacionSelecionada; } public Lineainvestigacion getLineaInvestigacionSelecionada() { return lineaInvestigacionSelecionada; } public void setLineaInvestigacionSelecionada(Lineainvestigacion lineaInvestigacionSelecionada) { this.lineaInvestigacionSelecionada = lineaInvestigacionSelecionada; } public LineainvestigacionFacade getLineaInvestigacionFacade() { return lineaInvestigacionFacade; } public void setLineaInvestigacionFacade(LineainvestigacionFacade lineaInvestigacionFacade) { this.lineaInvestigacionFacade = lineaInvestigacionFacade; } /** * Creates a new instance of LineaInvestigacionBean */ public LineaInvestigacionBean() { } @PostConstruct public void reset() { listaLineaInvestigacion = this.lineaInvestigacionFacade.findAll(); lineaInvestigacionSelecionada = null; listaLineaInvestigacionSelecionada = null; codDep = ""; nombre = ""; codigoLinea = ""; descripcion = ""; } public void nueva() { Lineainvestigacion lineaInvestigacion = new Lineainvestigacion(); lineaInvestigacion.setCodigoLinea(codigoLinea); lineaInvestigacion.setDescripcion(descripcion.toUpperCase()); lineaInvestigacion.setNombre(nombre.toUpperCase()); lineaInvestigacion.setCodDep(this.departamentoFacade.findByCodep(codDep).get(0)); try { this.lineaInvestigacionFacade.create(lineaInvestigacion); ModeloBean ont = (ModeloBean) FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get("modeloBean"); String nS = ont.getPrefijo(); OntModel modelo = ont.getModelOnt(); OntClass claseLin = modelo.getOntClass(nS + clase); Individual linea = modelo.createIndividual(nS + clase + codigoLinea, claseLin); Individual departamento = modelo.getIndividual(nS + "Departamento" + codDep); DatatypeProperty codigo_lin = modelo.getDatatypeProperty(nS + "codigo_linea"); DatatypeProperty nombre_lin = modelo.getDatatypeProperty(nS + "nombre_linea"); DatatypeProperty desc = modelo.getDatatypeProperty(nS + "descripcion"); ObjectProperty pertenece = modelo.getObjectProperty(nS + "Pertenece_a"); linea.setPropertyValue(codigo_lin, modelo.createTypedLiteral(lineaInvestigacion.getCodigoLinea())); linea.setPropertyValue(nombre_lin, modelo.createTypedLiteral(lineaInvestigacion.getNombre())); linea.setPropertyValue(desc, modelo.createTypedLiteral(lineaInvestigacion.getDescripcion())); linea.setPropertyValue(pertenece, departamento); departamento.addProperty(pertenece.getInverse(), linea); ont.guardarModelo(modelo); reset(); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Registro Exitoso", "")); } catch (Exception e) { System.out.println(e.toString()); FacesContext.getCurrentInstance(). addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error al registrar la linea ", "")); } } public void modificar() { String codigoDepartamento = ""; boolean cambio = false; try { lineaInvestigacionSelecionada.setDescripcion(lineaInvestigacionSelecionada.getDescripcion().toUpperCase()); lineaInvestigacionSelecionada.setNombre(lineaInvestigacionSelecionada.getNombre().toUpperCase()); if (!lineaInvestigacionSelecionada.getCodDep().getCodDep().equals(codDep)) { codigoDepartamento = lineaInvestigacionSelecionada.getCodDep().getCodDep(); lineaInvestigacionSelecionada.setCodDep(this.departamentoFacade.findByCodep(codDep).get(0)); cambio = true; } this.lineaInvestigacionFacade.edit(lineaInvestigacionSelecionada); ModeloBean ont = (ModeloBean) FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get("modeloBean"); String nS = ont.getPrefijo(); OntModel modelo = ont.getModelOnt(); Individual linea = modelo.getIndividual(nS + clase + lineaInvestigacionSelecionada.getCodigoLinea()); DatatypeProperty codigo_lin = modelo.getDatatypeProperty(nS + "codigo_linea"); DatatypeProperty nombre_lin = modelo.getDatatypeProperty(nS + "nombre_linea"); DatatypeProperty desc = modelo.getDatatypeProperty(nS + "descripcion"); if (cambio) { ObjectProperty pertenece = modelo.getObjectProperty(nS + "Pertenece_a"); Individual departamento = modelo.getIndividual(nS + "Departamento" + codigoDepartamento); linea.removeProperty(pertenece, departamento); departamento.removeProperty(pertenece.getInverse(), linea); departamento = modelo.getIndividual(nS + "Departamento" + codDep); linea.setPropertyValue(pertenece, departamento); departamento.addProperty(pertenece.getInverse(), linea); } linea.setPropertyValue(codigo_lin, modelo.createTypedLiteral(lineaInvestigacionSelecionada.getCodigoLinea())); linea.setPropertyValue(nombre_lin, modelo.createTypedLiteral(lineaInvestigacionSelecionada.getNombre())); linea.setPropertyValue(desc, modelo.createTypedLiteral(lineaInvestigacionSelecionada.getDescripcion())); ont.guardarModelo(modelo); reset(); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Linea de investigación Modificada", "")); } catch (Exception e) { System.out.println(e.toString()); FacesContext.getCurrentInstance(). addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error al modificar la linea ", "")); } } public void eliminar() { try { this.lineaInvestigacionFacade.remove(lineaInvestigacionSelecionada); ModeloBean ont = (ModeloBean) FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get("modeloBean"); String nS = ont.getPrefijo(); OntModel modelo = ont.getModelOnt(); OntClass claseLin = modelo.getOntClass(nS + clase); ObjectProperty pertenece = modelo.getObjectProperty(nS + "Pertenece_a"); Individual departamento = modelo.getIndividual(nS + "Departamento" + lineaInvestigacionSelecionada.getCodDep().getCodDep()); departamento.removeProperty(pertenece.getInverse(), modelo.getIndividual(nS + clase + lineaInvestigacionSelecionada.getCodigoLinea())); modelo.getIndividual(nS + clase + lineaInvestigacionSelecionada.getCodigoLinea()).remove(); ont.guardarModelo(modelo); reset(); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Linea de investigación Eliminada", "")); } catch (Exception e) { System.out.println(e.toString()); FacesContext.getCurrentInstance(). addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error al Eliminar la linea", "")); } } }
jimaguere/Maskana-Gestor-de-Conocimiento
src/java/ManageBean/LineaInvestigacionBean.java
Java
gpl-3.0
9,867
package tmp.generated_xhtml; import cide.gast.*; import cide.gparser.*; import cide.greferences.*; import java.util.*; public class Content_sub_Choice124 extends Content_sub_Choice1 { public Content_sub_Choice124(Element_acronym element_acronym, Token firstToken, Token lastToken) { super(new Property[] { new PropertyOne<Element_acronym>("element_acronym", element_acronym) }, firstToken, lastToken); } public Content_sub_Choice124(Property[] properties, IToken firstToken, IToken lastToken) { super(properties,firstToken,lastToken); } public ASTNode deepCopy() { return new Content_sub_Choice124(cloneProperties(),firstToken,lastToken); } public Element_acronym getElement_acronym() { return ((PropertyOne<Element_acronym>)getProperty("element_acronym")).getValue(); } }
ckaestne/CIDE
CIDE_Language_XML_concrete/src/tmp/generated_xhtml/Content_sub_Choice124.java
Java
gpl-3.0
837
<?php echo do_shortcode( '[ai1ec view="stream"]' ); ?>
briancompton/knightsplaza
enceinte/wp-content/themes/knightsplaza/inc/home-kp-events.php
PHP
gpl-3.0
55
namespace ConsoleApplication1.Entidades { public class Perfil { public string Tipo { get; set; } public Entrega Entrega { get; set; } } }
xxneeco83xx/Mapper
ConsoleApplication1/ConsoleApplication1/Entidades/Perfil.cs
C#
gpl-3.0
181
class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ result = [] for i in nums1: if i in nums2 and i not in result: result.append(i) return result
CharlotteLock/LeetCode
349. Intersection of Two Arrays.py
Python
gpl-3.0
324
/***************************************************************************** * VATA Tree Automata Library * * Copyright (c) 2011 Ondra Lengal <ilengal@fit.vutbr.cz> * * Description: * Operations for the command-line interface to the VATA library. * *****************************************************************************/ #ifndef _OPERATIONS_HH_ #define _OPERATIONS_HH_ // standard library headers #include <chrono> // VATA headers #include <vata/vata.hh> // local headers #include "parse_args.hh" using VATA::Util::Convert; using VATA::AutBase; using VATA::InclParam; using VATA::SimParam; using std::chrono::high_resolution_clock; using TimePoint = std::chrono::time_point<high_resolution_clock>; TimePoint startTime; template <class Automaton> bool CheckInclusion(Automaton smaller, Automaton bigger, const Arguments& args) { // insert default values Options options = args.options; options.insert(std::make_pair("sim", "no")); options.insert(std::make_pair("dir", "up")); options.insert(std::make_pair("optC", "no")); options.insert(std::make_pair("timeS", "yes")); options.insert(std::make_pair("rec", "no")); options.insert(std::make_pair("alg", "antichains")); options.insert(std::make_pair("order", "depth")); std::runtime_error optErrorEx("Invalid options for inclusion: " + Convert::ToString(options)); AutBase::StateType states = AutBase::SanitizeAutsForInclusion(smaller, bigger); /**************************************************************************** * Parsing of input parameters ****************************************************************************/ // parameters for inclusion InclParam ip; // the algorithm used if (options["alg"] == "antichains") { ip.SetAlgorithm(InclParam::e_algorithm::antichains); } else if (options["alg"] == "congr") { ip.SetAlgorithm(InclParam::e_algorithm::congruences); } else { throw optErrorEx; } // direction of the algorithm if (options["dir"] == "up") { ip.SetDirection(InclParam::e_direction::upward); } else if (options["dir"] == "down") { ip.SetDirection(InclParam::e_direction::downward); } else { throw optErrorEx; } // recursive/nonrecursive version if (options["rec"] == "yes") { ip.SetUseRecursion(true); } else if (options["rec"] == "no") { ip.SetUseRecursion(false); } else { throw optErrorEx; } // caching of implications if (options["optC"] == "no") { ip.SetUseDownwardCacheImpl(false); } else if (options["optC"] == "yes") { ip.SetUseDownwardCacheImpl(true); } else { throw optErrorEx; } // use simulation? if (options["sim"] == "no") { ip.SetUseSimulation(false); } else if (options["sim"] == "yes") { ip.SetUseSimulation(true); } else { throw optErrorEx; } if (options["order"] == "depth") { ip.SetSearchOrder(InclParam::e_search_order::depth); } else if (options["order"] == "breadth") { ip.SetSearchOrder(InclParam::e_search_order::breadth); } else {throw optErrorEx; } bool incl_sim_time = false; if (options["timeS"] == "no") { incl_sim_time = false; } else if (options["timeS"] == "yes") { incl_sim_time = true; } else { throw optErrorEx; } /**************************************************************************** * Additional handling ****************************************************************************/ // set the timer startTime = high_resolution_clock::now(); AutBase::StateDiscontBinaryRelation sim; if (ip.GetUseSimulation()) { // if simulation is desired, then compute it here! //Automaton unionAut = Automaton::UnionDisjointStates(smaller, bigger); Automaton unionAut; if (ip.GetAlgorithm() == InclParam::e_algorithm::congruences) { smaller = Automaton::UnionDisjointStates(smaller, bigger); } else { unionAut = Automaton::UnionDisjointStates(smaller, bigger); } // TODO: why so much code duplicity? if (InclParam::e_direction::upward == ip.GetDirection()) { // for upward algorithm compute the upward simulation SimParam sp; sp.SetRelation(VATA::SimParam::e_sim_relation::TA_UPWARD); sp.SetNumStates(states); sim = unionAut.ComputeSimulation(sp); ip.SetSimulation(&sim); } else if (InclParam::e_direction::downward == ip.GetDirection()) { // for downward algorithm, compute the downward simulation SimParam sp; sp.SetRelation(VATA::SimParam::e_sim_relation::TA_DOWNWARD); sp.SetNumStates(states); sim = unionAut.ComputeSimulation(sp); ip.SetSimulation(&sim); } else { assert(false); // fail gracefully } } if (!incl_sim_time) { // if the simulation time is not to be included in the total time // reset the timer startTime = high_resolution_clock::now(); } return Automaton::CheckInclusion(smaller, bigger, ip); } template < class Automaton, class StringToStateMap, class StateToStateMap> VATA::AutBase::StateDiscontBinaryRelation ComputeSimulation( Automaton aut, const Arguments& args, const StringToStateMap /* index */, // TODO: why is this here? StateToStateMap& translMap) { // TODO: Why was this here? // if (!args.pruneUseless) // { // throw std::runtime_error("Simulation can only be computed for " // "automata with pruned useless states!"); // } using StateType = AutBase::StateType; using StateToStateTranslator = AutBase::StateToStateTranslWeak; // insert default values Options options = args.options; options.insert(std::make_pair("dir", "down")); StateType stateCnt = 0; StateToStateTranslator stateTransl(translMap, [&stateCnt](const StateType&){return stateCnt++;}); aut = aut.ReindexStates(stateTransl); // AutBase::StateType states = AutBase::SanitizeAutForSimulation(aut, // stateCnt, stateTransl); SimParam sp; sp.SetNumStates(stateCnt); if (options["dir"] == "up") { sp.SetRelation(VATA::SimParam::e_sim_relation::TA_UPWARD); } else if (options["dir"] == "down") { sp.SetRelation(VATA::SimParam::e_sim_relation::TA_DOWNWARD); } else if (options["dir"] == "fwd") { sp.SetRelation(VATA::SimParam::e_sim_relation::FA_FORWARD); } else if (options["dir"] == "bwd") { sp.SetRelation(VATA::SimParam::e_sim_relation::FA_BACKWARD); } else { throw std::runtime_error("Invalid options for simulation: " + Convert::ToString(options)); } return aut.ComputeSimulation(sp); } template <class Automaton> Automaton ComputeReduction( Automaton aut, const Arguments& args) { // insert default values Options options = args.options; options.insert(std::make_pair("dir", "down")); if (options["dir"] == "up") { throw std::runtime_error("Unimplemented."); } else if (options["dir"] == "down") { return aut.Reduce(); } else { throw std::runtime_error("Invalid options for simulation: " + Convert::ToString(options)); } } template <class Automaton> bool CheckEquiv(Automaton smaller, Automaton bigger, const Arguments& args) { // insert default values Options options = args.options; options.insert(std::make_pair("order", "depth")); // parameters for inclusion InclParam ip; std::runtime_error optErrorEx("Invalid options for equivalence: " + Convert::ToString(options)); startTime = high_resolution_clock::now(); ip.SetEquivalence(true); ip.SetAlgorithm(InclParam::e_algorithm::congruences); if (options["order"] == "depth") { ip.SetSearchOrder(InclParam::e_search_order::depth); } else if (options["order"] == "breadth") { ip.SetSearchOrder(InclParam::e_search_order::breadth); } else { throw optErrorEx; } // TODO: change throw std::runtime_error("Equivalence not implemented"); // assert(false); // return Automaton::CheckInclusion(smaller, bigger, ip); } #endif
ondrik/libvata
cli/operations.hh
C++
gpl-3.0
7,750
#!/usr/bin/python # BSD Licensed, Copyright (c) 2006-2008 MetaCarta, Inc. import sys, os, traceback import cgi as cgimod from web_request.response import Response import urllib import StringIO class ApplicationException(Exception): """Any application exception should be subclassed from here. """ status_code = 500 status_message = "Error" def get_error(self): """Returns an HTTP Header line: a la '500 Error'""" return "%s %s" % (self.status_code, self.status_message) def binary_print(binary_data): """This function is designed to work around the fact that Python in Windows does not handle binary output correctly. This function will set the output to binary, and then write to stdout directly rather than using print.""" try: import msvcrt msvcrt.setmode(sys.__stdout__.fileno(), os.O_BINARY) except: # No need to do anything if we can't import msvcrt. pass sys.stdout.write(binary_data) def mod_python (dispatch_function, apache_request): """mod_python handler.""" from mod_python import apache, util try: if apache_request.headers_in.has_key("X-Forwarded-Host"): base_path = "http://" + apache_request.headers_in["X-Forwarded-Host"] else: base_path = "http://" + apache_request.headers_in["Host"] base_path += apache_request.uri[:-len(apache_request.path_info)] accepts = "" if apache_request.headers_in.has_key("Accept"): accepts = apache_request.headers_in["Accept"] elif apache_request.headers_in.has_key("Content-Type"): accepts = apache_request.headers_in["Content-Type"] post_data = apache_request.read() request_method = apache_request.method params = {} if request_method != "POST": fields = util.FieldStorage(apache_request) for key in fields.keys(): params[key.lower()] = fields[key] #if post_data: # for key, value in cgimod.parse_qsl(post_data, keep_blank_values=True): # params[key.lower()] = value returned_data = dispatch_function( base_path = base_path, path_info = apache_request.path_info, params = params, request_method = request_method, post_data = post_data, accepts = accepts ) if isinstance(returned_data, list) or isinstance(returned_data, tuple): format, data = returned_data[0:2] if len(returned_data) == 3: for key, value in returned_data[2].items(): apache_request.headers_out[key] = value apache_request.content_type = format apache_request.send_http_header() apache_request.write(data) else: obj = returned_data if obj.extra_headers: for key, value in obj.extra_headers.items(): apache_request.headers_out[key] = value (status, message) = obj.status_code.split(" ") apache_request.status = int(status) apache_request.content_type = obj.content_type apache_request.send_http_header() apache_request.write(obj.getData()) except ApplicationException, error: apache_request.content_type = "text/html" apache_request.status = error.status_code apache_request.send_http_header() apache_request.write("<h4>An error occurred</h4><p>%s<p>" % (str(error))) except Exception, error: apache_request.content_type = "text/html" apache_request.status = apache.HTTP_INTERNAL_SERVER_ERROR apache_request.send_http_header() apache_request.write("<h4>An error occurred</h4><p>%s\n</p><p>Trace back: <pre>%s</pre></p>\n" % ( str(error), "".join(traceback.format_tb(sys.exc_traceback)))) return apache.OK def wsgi (dispatch_function, environ, start_response): """handler for wsgiref simple_server""" try: path_info = base_path = "" if "PATH_INFO" in environ: path_info = environ["PATH_INFO"] if "HTTP_X_FORWARDED_HOST" in environ: base_path = "http://" + environ["HTTP_X_FORWARDED_HOST"] elif "HTTP_HOST" in environ: base_path = "http://" + environ["HTTP_HOST"] base_path += environ["SCRIPT_NAME"] accepts = None if environ.has_key("CONTENT_TYPE"): accepts = environ['CONTENT_TYPE'] else: accepts = environ.get('HTTP_ACCEPT', '') request_method = environ["REQUEST_METHOD"] params = {} post_data = None if environ.has_key('CONTENT_LENGTH') and environ['CONTENT_LENGTH']: post_data = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH'])) #if post_data: # for key, value in cgimod.parse_qsl(post_data, keep_blank_values=True): # params[key.lower()] = value if environ.has_key('QUERY_STRING'): for key, value in cgimod.parse_qsl(environ['QUERY_STRING'], keep_blank_values=True): params[key.lower()] = value returned_data = dispatch_function( base_path = base_path, path_info = path_info, params = params, request_method = request_method, post_data = post_data, accepts = accepts ) if isinstance(returned_data, list) or isinstance(returned_data, tuple): format, data = returned_data[0:2] headers = {'Content-Type': format} if len(returned_data) == 3: headers.update(returned_data[2]) start_response("200 OK", headers.items()) return [str(data)] else: # This is a a web_request.Response.Response object headers = {'Content-Type': returned_data.content_type} if returned_data.extra_headers: headers.update(returned_data.extra_headers) start_response("%s Message" % returned_data.status_code, headers.items()) return [returned_data.getData()] except ApplicationException, error: start_response(error.get_error(), [('Content-Type','text/plain')]) return ["An error occurred: %s" % (str(error))] except Exception, error: start_response("500 Internal Server Error", [('Content-Type','text/plain')]) return ["An error occurred: %s\n%s\n" % ( str(error), "".join(traceback.format_tb(sys.exc_traceback)))] def cgi (dispatch_function): """cgi handler""" try: accepts = "" if "CONTENT_TYPE" in os.environ: accepts = os.environ['CONTENT_TYPE'] elif "HTTP_ACCEPT" in os.environ: accepts = os.environ['HTTP_ACCEPT'] request_method = os.environ["REQUEST_METHOD"] post_data = None params = {} if request_method != "GET" and request_method != "DELETE": post_data = sys.stdin.read() #if post_data: # for key, value in cgimod.parse_qsl(post_data, keep_blank_values=True): # params[key.lower()] = value fields = cgimod.FieldStorage() if fields <> None: for key, value in cgimod.parse_qsl(fields.qs_on_post, keep_blank_values=True): params[key.lower()] = value else: fields = cgimod.FieldStorage() try: for key in fields.keys(): params[key.lower()] = urllib.unquote(fields[key].value) except TypeError: pass path_info = base_path = "" if "PATH_INFO" in os.environ: path_info = os.environ["PATH_INFO"] if "HTTP_X_FORWARDED_HOST" in os.environ: base_path = "http://" + os.environ["HTTP_X_FORWARDED_HOST"] elif "HTTP_HOST" in os.environ: base_path = "http://" + os.environ["HTTP_HOST"] base_path += os.environ["SCRIPT_NAME"] returned_data = dispatch_function( base_path = base_path, path_info = path_info, params = params, request_method = request_method, post_data = post_data, accepts = accepts ) if isinstance(returned_data, list) or isinstance(returned_data, tuple): format, data = returned_data[0:2] if len(returned_data) == 3: for (key, value) in returned_data[2].items(): print "%s: %s" % (key, value) print "Content-type: %s\n" % format if sys.platform == "win32": binary_print(data) else: print data else: # Returned object is a 'response' obj = returned_data if obj.extra_headers: for (key, value) in obj.extra_headers.items(): print "%s: %s" % (key, value) print "Content-type: %s\n" % obj.content_type if sys.platform == "win32": binary_print(obj.getData()) else: print obj.getData() except ApplicationException, error: print "Cache-Control: max-age=10, must-revalidate" # make the client reload print "Content-type: text/plain\n" print "An error occurred: %s\n" % (str(error)) except Exception, error: print "Cache-Control: max-age=10, must-revalidate" # make the client reload print "Content-type: text/plain\n" print "An error occurred: %s\n%s\n" % ( str(error), "".join(traceback.format_tb(sys.exc_traceback))) print params
guolivar/totus-niwa
service/thirdparty/featureserver/web_request/handlers.py
Python
gpl-3.0
10,134
""" Mopaq archive format found in Blizzard titles Diablo 1.0 and later Implemented according to info from http://www.zezula.net """ import struct, hashlib, sys from collections import namedtuple USERDATA_MAGIC = b'MPQ\x1A' FILEHEADER_MAGIC = b'MPQ\x1B' HET_MAGIC = b'HET\x1A' BET_MAGIC = b'BET\x1A' BITMAP_MAGIC = b'ptv3' PATCH_MAGIC = b'BSDIFF40' # offset 0x0000 MD5_MAGIC = b'MD5_' XFRM_MAGIC = b'XFRM' V1LEN = 0x20 V2LEN = 0x2C V3LEN = 0x44 # or greater V4LEN = 0xD0 L_N = 0 # neutral/American English L_CNTW = 0x404 # Chinese (Taiwan) L_CZ = 0x405 # Czech L_DE = 0x407 # German L_EN = 0x409 # English L_ES = 0x40A # Spanish L_FR = 0x40C # French L_IT = 0x410 # Italian L_JP = 0x411 # Japanese L_KR = 0x412 # Korean L_PL = 0x415 # Polish L_PT = 0x416 # Portuguese L_RU = 0x419 # Russian L_ENUK = 0x809 # UK English BF_IMPL = 0x00000100 # File is compressed using PKWARE Data compression library BF_COMP = 0x00000200 # File is compressed using combination of compression methods BF_ENCR = 0x00010000 # File is encrypted BF_FKEY = 0x00020000 # The decryption key for the file is altered according to the position of the file in the archive BF_PTCH = 0x00100000 # The file contains incremental patch for an existing file in base MPQ BF_SNGL = 0x01000000 # Instead of being divided to 0x1000-bytes blocks, the file is stored as single unit BF_DMRK = 0x02000000 # File is a deletion marker, indicating that the file no longer exists. This is used to allow patch archives to delete files present in lower-priority archives in the search chain. The file usually has length of 0 or 1 byte and its name is a hash BF_SCRC = 0x04000000 # File has checksums for each sector (explained in the File Data section). Ignored if file is not compressed or imploded. BF_EXST = 0x80000000 # Set if file exists, reset when the file was deleted AF_READ = 0x00000001 # MPQ opened read only AF_CHNG = 0x00000002 # tables were changed AF_PROT = 0x00000004 # protected MPQs like W3M maps AF_CHKS = 0x00000008 # checking sector CRC when reading files AF_FIXS = 0x00000010 # need fix size, used during archive open AF_IVLF = 0x00000020 # (listfile) invalidated AF_IVAT = 0x00000040 # (attributes) invalidated ATR_CRC32 = 0x00000001 # contains CRC32 for each file ATR_FTIME = 0x00000002 # file time for each file ATR_MD5 = 0x00000004 # MD5 for each file ATR_PATCHBIT = 0x00000008 # patch bit for each file ATR_ALL = 0x0000000F CF_HUFF = 0x01 # Huffman compression, WAVE files only CF_ZLIB = 0x02 CF_PKWR = 0x08 # PKWARE CF_BZP2 = 0x10 # BZip2, added in Warcraft 3 CF_SPRS = 0x20 # Sparse, added in Starcraft 2 CF_MONO = 0x40 # IMA ADPCM (mono) CF_STER = 0x80 # IMA ADPCM (stereo) CF_LZMA = 0x12 # added in Starcraft 2, not a combination CF_SAME = 0xFFFFFFFF # Same K_HASH = 0xC3AF3770 K_BLCK = 0xEC83B3A3 PTYPE1 = b'BSD0' # Blizzard modified version of BSDIFF40 incremental patch PTYPE2 = b'BSDP' PTYPE3 = b'COPY' # plain replace PTYPE4 = b'COUP' PTYPE5 = b'CPOG' UserDataHeader = namedtuple('UserDataHeader', [ 'magic', 'data_size', 'header_offset', 'header_size']) UserDataHeader.format = '<4s3L' Header = namedtuple('Header', [ 'magic', 'header_size', 'archive_size', # archive size, deprecated in ver. 2, calced as length from beg. of archive to end of hash table/block table/ext. block table (whichever is largest) 'version', # 0 = up to WoW:BC, 1 = WoW:BC-WoW:CT beta, 2/3 = WoW:CT beta and later 'block_size', 'hash_table_pos', 'block_table_pos', 'hash_table_size', 'block_table_size']) Header.format = '<4s2L2H4L' Header2 = namedtuple('Header2', [ 'hi_block_table_pos', 'hash_table_pos_hi', 'block_table_pos_hi']) Header2.format = '<Q2H' Header3 = namedtuple('Header3', [ 'archive_size64', 'bet_table_pos', 'het_table_pos']) Header3.format = '<Q3' Header4 = namedtuple('Header4', [ 'hash_table_size64', 'block_table_size64', 'hi_block_table_size', 'het_table_size', 'bet_table_size', 'raw_chunk_size']) Header4.format = '<Q5L' if sys.byteorder == 'little': Hash = namedtuple('Hash', [ 'name1', 'name2', 'locale', 'platform', 'block_index']) else: Hash = namedtuple('Hash', [ 'name1', 'name2', 'platform', 'locale', 'block_index']) Hash.format = '<2L2HL' Block = namedtuple('Block', [ 'file_pos', 'comp_size', 'uncomp_size', 'flags']) Block.format = '<4L' PatchInfo = namedtuple('PatchInfo', [ 'length', 'flags', 'uncomp_size', 'md5']) PatchInfo.format = '<3L16s' PatchHeader = namedtuple('PatchHeader', [ 'header_magic', 'size', 'size_before_patch', 'size_after_patch', 'md5', 'md5_block_size', 'md5_before_patch', 'md5_after_patch', 'xfrm_magic', 'xfrm_block_size', 'type']) PatchHeader.format = '<4s3L4sL16s16s4sL4s' FileEntry = namedtuple('FileEntry', [ 'byte_offset', 'file_time', 'bet_hash', 'hash_index', 'het_index', 'file_size', 'comp_size', 'flags', 'locale', 'platform', 'crc32', 'md5']) FileEntry.format = '<3Q5L2HL16s' ExtTable = namedtuple('ExtTable', [ 'magic', 'version', 'size']) ExtTable.format = '<4s2L' Bitmap = namedtuple('Bitmap', [ 'magic', 'unknown', 'game_build_num', 'map_offset_lo', 'map_offset_hi', 'block_size']) Bitmap.format = '<4s5L' HashEntryTable = namedtuple('HashEntryTable', [ 'and_mask', 'or_mask', 'index_size_total', 'index_size_extra', 'index_size', 'file_num', 'hash_table_size', 'hash_bit_size']) HashEntryTable.format = '<2Q6L' BlockEntryTable = namedtuple('BlockEntryTable', [ 'table_entry_size', 'bit_index_file_pos', 'bit_index_file_size', 'bit_index_comp_size', 'bit_index_flag_index', 'bit_index_unknown', 'bit_count_file_pos', 'bit_count_file_size', 'bit_count_comp_size', 'bit_count_flag_index', 'bit_count_unknown', 'bet_hash_size_total', 'bet_hash_size_extra', 'bet_hash_size', 'file_num', 'flag_num']) BlockEntryTable.format = '<16L'
Schala/format-scripts
mpq.py
Python
gpl-3.0
5,804
using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; namespace GitExtUtils.GitUI.Theming { public abstract class BmpTransformation { private readonly Bitmap _bmp; protected const int B = 0; protected const int G = 1; protected const int R = 2; protected const int A = 3; private const int BytesPerPixel = 4; private const PixelFormat PixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppArgb; protected Rectangle Rect { get; private set; } protected byte[]? BgraValues { get; private set; } protected bool ImageChanged { get; set; } protected BmpTransformation(Bitmap bmp) { _bmp = bmp; Rect = new Rectangle(location: default, size: bmp.Size); } public void Execute() { var bmpData = _bmp.LockBits(Rect, ImageLockMode.ReadWrite, PixelFormat); try { int numBytes = bmpData.Stride * bmpData.Height; BgraValues = new byte[numBytes]; Marshal.Copy(bmpData.Scan0, BgraValues, 0, numBytes); ExecuteRaw(); if (ImageChanged) { Marshal.Copy(BgraValues, 0, bmpData.Scan0, numBytes); } } finally { _bmp.UnlockBits(bmpData); } } protected abstract void ExecuteRaw(); protected int GetLocation(int x, int y) => BytesPerPixel * ((Rect.Width * y) + x); } }
EbenZhang/gitextensions
GitExtUtils/GitUI/Theming/BmpTransformation.cs
C#
gpl-3.0
1,622
#include "common.h" #include "SoundMngr.h" #include <FOnlineFileManager/FileManager.hpp> //#include <SimpleLeakDetector/SimpleLeakDetector.hpp> int SoundManager::Init() { if(active==true) return 1; FONLINE_LOG("SoundManager Init\n"); if (!fm.Init(opt_masterpath.c_str(), opt_critterpath.c_str(), opt_fopath.c_str())) return 0;; if(DirectSoundCreate8(0,&lpDS,0)!=DS_OK) { FONLINE_LOG("Неудалось создать устройство!\n"); return 0; } if(lpDS->SetCooperativeLevel(GetForegroundWindow(),DSSCL_NORMAL)!=DS_OK) { FONLINE_LOG("Неудалось установить уровень кооперации!\n"); return 0; } cur_snd=1; active=true; FONLINE_LOG("SoundManager Init OK\n"); return 1; } void SoundManager::Clear() { if(active==false) return; FONLINE_LOG("SoundManager Clear...\n"); fm.Clear(); lpDS->Release(); lpDS=NULL; for(sound_map::iterator it=sounds.begin(); it!=sounds.end(); it++) { // (*it).second->buf->Release(); delete (*it).second; } sounds.clear(); active=false; FONLINE_LOG("OK\n"); } void SoundManager::LPESound(char* fname, int TypePath) { uint16_t lpe=0; if(!(lpe=LoadSound(fname,TypePath))) return; PlaySound(lpe); } int SoundManager::LoadSound(char* fname, int TypePath) { if (!fm.LoadFile(fname,TypePath)) { FONLINE_LOG("Ошибка - Загрузка звука - Звук |%s| не найден\n",fname); return 0; } char* ext=strstr(fname,"."); if(!ext) { fm.UnloadFile(); FONLINE_LOG("Ошибка - Загрузка звука - Нет расширения у файла:|%s|\n",fname); return 0; } WAVEFORMATEX fmt; ZeroMemory(&fmt,sizeof(WAVEFORMATEX)); unsigned char* smplData=NULL; uint32_t sizeData=0; if(!stricmp(ext,".wav")) { if (!LoadWAV(&fmt, &smplData, &sizeData)) { if (smplData != NULL) { delete [] smplData; smplData = NULL; } fm.UnloadFile(); return 0; } } else if(!stricmp(ext,".acm")) { if(!LoadACM(&fmt,&smplData,&sizeData)) { if (smplData != NULL) { delete [] smplData; smplData = NULL; } fm.UnloadFile(); return 0; } } else if (!stricmp(ext, ".ogg")) { char full_path[256]; if (!fm.GetFullPath(fname,TypePath,&full_path[0])) { if (smplData != NULL) { delete [] smplData; smplData = NULL; } fm.UnloadFile(); return 0; } if (!LoadOGG(&fmt,&smplData,&sizeData,&full_path[0])) { if (smplData != NULL) { delete [] smplData; smplData = NULL; } fm.UnloadFile(); return 0; } } else { fm.UnloadFile(); FONLINE_LOG("Ошибка - Загрузка звука - Неизвестный формат файла звука |%s|\n",fname); return 0; } fm.UnloadFile(); DSBUFFERDESC dsbd; ZeroMemory(&dsbd,sizeof(DSBUFFERDESC)); dsbd.dwBufferBytes=sizeData; dsbd.dwFlags=DSBCAPS_STATIC;// | DSBCAPS_LOCSOFTWARE |DSSCL_PRIORITY ; dsbd.dwSize=sizeof(DSBUFFERDESC); dsbd.lpwfxFormat=&fmt; dsbd.dwReserved=0; Sound* nsnd=new Sound; if (lpDS->CreateSoundBuffer(&dsbd,&nsnd->buf,0) != DS_OK) { if (smplData != NULL) { delete [] smplData; smplData = NULL; } FONLINE_LOG("Ошибка - Загрузка звука - Неудалось создать буфер для звука\n"); return 0; } void *pDst=0; DWORD wSize=0; if (nsnd->buf->Lock(0, 0, &pDst, &wSize, 0, 0, DSBLOCK_ENTIREBUFFER) != DS_OK) { if (smplData != NULL) { delete [] smplData; smplData = NULL; } FONLINE_LOG("Ошибка - Загрузка звука - Невозможно заблокировать память\n"); return 0; } memcpy(pDst, smplData, wSize); if (smplData != NULL) { delete [] smplData; smplData = NULL; } nsnd->buf->Unlock(pDst,wSize,0,0); cur_snd++; sounds.insert(sound_map::value_type(cur_snd,nsnd)); return cur_snd; } int SoundManager::LoadWAV(WAVEFORMATEX* fformat, unsigned char** sample_data, size_t* size_data) { uint32_t dw_buf = fm.GetRDWord(); if(dw_buf!=MAKEFOURCC('R','I','F','F')) { FONLINE_LOG("|RIFF| not found |%d|\n"); return 0; } fm.GoForward(4); dw_buf=fm.GetRDWord(); if(dw_buf!=MAKEFOURCC('W','A','V','E')) { FONLINE_LOG("|WAVE| not found\n"); return 0; } dw_buf=fm.GetRDWord(); if(dw_buf!=MAKEFOURCC('f','m','t',' ')) { FONLINE_LOG("|fmt | not found\n"); return 0; } dw_buf=fm.GetRDWord(); if(!dw_buf) { FONLINE_LOG("Ошибка - Загрузка звука - .Неизвестный формат аудио файла\n"); return 0; } fm.Read(fformat,16); fformat->cbSize=0; if(fformat->wFormatTag!=1) { FONLINE_LOG("Ошибка - Загрузка звука - Сжатые файлы не поддерживаются\n"); return 0; } fm.GoForward(dw_buf-16); dw_buf=fm.GetRDWord(); if(dw_buf==MAKEFOURCC('f','a','c','t')) { dw_buf=fm.GetRDWord(); fm.GoForward(dw_buf); dw_buf=fm.GetRDWord(); } if(dw_buf!=MAKEFOURCC('d','a','t','a')) { FONLINE_LOG("Ошибка - Загрузка звука - ..Неизвестный формат аудио файла\n"); return 0; } dw_buf=fm.GetRDWord(); *size_data=dw_buf; *sample_data=new unsigned char[dw_buf]; if(!fm.Read(*sample_data,dw_buf)) { FONLINE_LOG("Ошибка - Загрузка звука - Звуковой файл битый\n"); return 0; } return 1; } int SoundManager::LoadACM(WAVEFORMATEX* fformat, unsigned char** sample_data, size_t* size_data) { int channel; int freq; int data_size; // int step_data_size; ACMDecompressor::Context acm; bool acmInitialized = ACMDecompressor::Init(&acm, fm.GetBufferPtr(),fm.GetFileSize(),channel,freq,data_size); data_size*=2; if (!acmInitialized) { FONLINE_LOG("Ошибка - Загрузка звука - Неинициализировался распаковщик ACM\n"); return 0; } freq/=2; //??? fformat->wFormatTag=WAVE_FORMAT_PCM; fformat->nChannels=2; //??? channel ??? fformat->nSamplesPerSec=freq; fformat->nBlockAlign=4; fformat->nAvgBytesPerSec=freq*4; fformat->wBitsPerSample=16; fformat->cbSize=0; *size_data=data_size; *sample_data=new unsigned char[data_size]; // unsigned char *step_buff = new unsigned char[0x10000]; /* int cur_buf=0; while(data_size) { step_data_size=acm->readAndDecompress((unsigned short*)step_buff,data_size>0x10000?0x10000:data_size); memcpy(*sample_data+cur_buf,step_buff,step_data_size); cur_buf+=step_data_size; data_size-=step_data_size; } */ int dec_data = ACMDecompressor::ReadAndDecompress(&acm, (unsigned short*)*sample_data,data_size); if (dec_data != data_size) { FONLINE_LOG("Ошибка - Загрузка звука - Ошибка в декодировании ACM\n"); if (*sample_data != NULL) { delete sample_data; sample_data = NULL; } return 0; } // SAFEDEL(step_buff); return 1; } int SoundManager::LoadOGG(WAVEFORMATEX* fformat, unsigned char** sample_data, size_t* size_data, char* ogg_path) { FILE *fs; if(!(fs=fopen(ogg_path,"rb"))) return 0; OggVorbis_File vf; if(ov_open(fs,&vf,NULL,0)) return 0; vorbis_info* vi=ov_info(&vf,-1); int data_len=(int)ov_pcm_total(&vf,-1); int start_pos=(int)ov_pcm_tell(&vf); int BPS=vi->channels==1?2:4; *size_data=(data_len-start_pos)*BPS; *sample_data=new unsigned char[*size_data]; size_t decoded=0; while (decoded < *size_data) { int curr; decoded += ov_read(&vf,(char*)(*sample_data)+decoded,(*size_data)-decoded,0,2,1,&curr); } fformat->wFormatTag=WAVE_FORMAT_PCM; fformat->nChannels=vi->channels; fformat->nSamplesPerSec=vi->rate; fformat->wBitsPerSample=16; fformat->nBlockAlign=vi->channels*fformat->wBitsPerSample/8; fformat->nAvgBytesPerSec=fformat->nBlockAlign*vi->rate; fformat->cbSize=0; return 1; } void SoundManager::PlaySound(uint16_t id) { if(!id) { FONLINE_LOG("Ошибка - Проигрывание звука - Звук не загружен!\n"); return; } sound_map::iterator it=sounds.find(id); if(it==sounds.end()) { FONLINE_LOG("Ошибка - Прогигрывание звука - Звук №%d не найден!",id); return; } (*it).second->buf->Play(0,0,0); } void SoundManager::StopSound(uint16_t id) { if(!id) { FONLINE_LOG("Ошибка - Приостоновление звука - Звук не загружен!\n"); return; } sound_map::iterator it=sounds.find(id); if(it==sounds.end()) { FONLINE_LOG("Ошибка - Приостоновление звука - Звук №%d не найден!",id); return; } (*it).second->buf->Stop(); (*it).second->buf->SetCurrentPosition(0); } void SoundManager::PauseSound(uint16_t id) { if(!id) { FONLINE_LOG("Ошибка - Приостоновление звука - Звук не загружен!\n"); return; } sound_map::iterator it=sounds.find(id); if(it==sounds.end()) { FONLINE_LOG("Ошибка - Приостоновление звука - Звук №%d не найден!",id); return; } (*it).second->buf->Stop(); } void SoundManager::EraseSound(uint16_t id) { if(!id) { FONLINE_LOG("Ошибка - Удаление звука - Звук не загружен!\n"); return; } sound_map::iterator it=sounds.find(id); if(it==sounds.end()) { FONLINE_LOG("Ошибка - Удаление звука - Звук №%d не найден!",id); return; } // (*it).second->buf->Release(); delete (*it).second; sounds.erase(it); }
alexknvl/fonline
src/FOnlineClient/SoundMngr.cpp
C++
gpl-3.0
10,196
// <copyright file="RegistryAction.cs" project="SevenUpdate.Base">Robert Baker</copyright> // <license href="http://www.gnu.org/licenses/gpl-3.0.txt" name="GNU General Public License 3" /> namespace SevenUpdate { using System.ComponentModel; using System.Runtime.Serialization; using ProtoBuf; /// <summary>Contains the Actions you can perform to the registry.</summary> [ProtoContract] [DataContract] [DefaultValue(Add)] public enum RegistryAction { /// <summary>Adds a registry entry to the machine.</summary> [ProtoEnum] [EnumMember] Add = 0, /// <summary>Deletes a registry key on the machine.</summary> [ProtoEnum] [EnumMember] DeleteKey = 1, /// <summary>Deletes a value of a registry key on the machine.</summary> [ProtoEnum] [EnumMember] DeleteValue = 2 } }
robertbaker/SevenUpdate
Source/SevenUpdate.Base/RegistryAction.cs
C#
gpl-3.0
908
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "./etc/")) sys.path.append(os.path.join(os.path.dirname(__file__), "./lib/")) from sheepsense.webapp import app as application if __name__ == "__main__": application.run()
basbloemsaat/sheepsense_v2
wsgi.py
Python
gpl-3.0
255
using System; using System.Collections.Generic; using Server; using Server.Network; using Server.Mobiles; namespace Server.Items { public class VialOfArmorEssence : Item, IPetBooster { public override int LabelNumber { get { return 1113018; } } // Vial of Armor Essence public TimeSpan Duration { get { return TimeSpan.FromMinutes( 10.0 ); } } public TimeSpan Cooldown { get { return TimeSpan.FromHours( 1.0 ); } } [Constructable] public VialOfArmorEssence() : base( 0xE24 ) { Weight = 1.0; Hue = 2405; } public VialOfArmorEssence( Serial serial ) : base( serial ) { } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); list.Add( 1113213 ); // * For Pets Only * list.Add( 1113219 ); // Damage Absorption 10% list.Add( 1113212, Duration.TotalMinutes.ToString() ); // Duration: ~1_val~ minutes list.Add( 1113218, Cooldown.TotalMinutes.ToString() ); // Cooldown: ~1_val~ minutes } public bool OnUsed( Mobile from, BaseCreature pet ) { if ( m_UnderEffect.Contains( pet ) ) { from.SendLocalizedMessage( 1113075 ); // Your pet is still under the effect of armor essence. return false; } else if ( DateTime.Now < pet.NextArmorEssence ) { from.SendLocalizedMessage( 1113076 ); // Your pet is still recovering from the last armor essence it consumed. return false; } else { pet.SayTo( from, 1113050 ); // Your pet looks much happier. pet.FixedEffect( 0x375A, 10, 15 ); pet.PlaySound( 0x1E7 ); List<ResistanceMod> mods = new List<ResistanceMod>(); mods.Add( new ResistanceMod( ResistanceType.Physical, 15 ) ); mods.Add( new ResistanceMod( ResistanceType.Fire, 10 ) ); mods.Add( new ResistanceMod( ResistanceType.Cold, 10 ) ); mods.Add( new ResistanceMod( ResistanceType.Poison, 10 ) ); mods.Add( new ResistanceMod( ResistanceType.Energy, 10 ) ); for ( int i = 0; i < mods.Count; i++ ) pet.AddResistanceMod( mods[i] ); m_UnderEffect.Add( pet ); Timer.DelayCall( Duration, new TimerCallback( delegate { for ( int i = 0; i < mods.Count; i++ ) pet.RemoveResistanceMod( mods[i] ); m_UnderEffect.Remove( pet ); } ) ); pet.NextArmorEssence = DateTime.Now + Duration + Cooldown; Delete(); return true; } } private static ISet<Mobile> m_UnderEffect = new HashSet<Mobile>(); public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); /*int version = */ reader.ReadInt(); } } }
greeduomacro/xrunuo
Scripts/Distro/Items/Skill Items/Animal Taming/VialOfArmorEssence.cs
C#
gpl-3.0
2,810
# vim: ts=4:sw=4:expandtab # BleachBit # Copyright (C) 2008-2021 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test case for module Worker """ from tests import TestCleaner, common from bleachbit import CLI, Command from bleachbit.Action import ActionProvider from bleachbit.Worker import * import os import tempfile import unittest class AccessDeniedActionAction(ActionProvider): action_key = 'access.denied' def __init__(self, action_element): self.pathname = action_element.getAttribute('path') def get_commands(self): # access denied, should fail and continue def accessdenied(): import errno raise OSError(errno.EACCES, 'Permission denied: /foo/bar') yield Command.Function(None, accessdenied, 'Test access denied') # real file, should succeed yield Command.Delete(self.pathname) class DoesNotExistAction(ActionProvider): action_key = 'does.not.exist' def __init__(self, action_element): self.pathname = action_element.getAttribute('path') def get_commands(self): # non-existent file, should fail and continue yield Command.Delete("doesnotexist") # real file, should succeed yield Command.Delete(self.pathname) class FunctionGeneratorAction(ActionProvider): action_key = 'function.generator' def __init__(self, action_element): self.pathname = action_element.getAttribute('path') def get_commands(self): # function generator without path, should succeed def funcgenerator(): yield 10 yield Command.Function(None, funcgenerator, 'funcgenerator') # real file, should succeed yield Command.Delete(self.pathname) class FunctionPathAction(ActionProvider): action_key = 'function.path' def __init__(self, action_element): self.pathname = action_element.getAttribute('path') def get_commands(self): # function with path, should succeed def pathfunc(path): pass # self.pathname must exist because it checks the file size yield Command.Function(self.pathname, pathfunc, 'pathfunc') # real file, should succeed yield Command.Delete(self.pathname) class InvalidEncodingAction(ActionProvider): action_key = 'invalid.encoding' def __init__(self, action_element): self.pathname = action_element.getAttribute('path') def get_commands(self): # file with invalid encoding (fd, filename) = tempfile.mkstemp('invalid-encoding-\xe4\xf6\xfc~') os.close(fd) yield Command.Delete(filename) # real file, should succeed yield Command.Delete(self.pathname) class FunctionPlainAction(ActionProvider): action_key = 'function.plain' def __init__(self, action_element): self.pathname = action_element.getAttribute('path') def get_commands(self): # plain function without path, should succeed def intfunc(): return int(5) yield Command.Function(None, intfunc, 'intfunc') # real file, should succeed yield Command.Delete(self.pathname) class LockedAction(ActionProvider): action_key = 'locked' def __init__(self, action_element): self.pathname = action_element.getAttribute('path') def get_commands(self): # Open the file with a non-exclusive lock, so the file should # be truncated and marked for deletion. This is checked just on # on Windows. fd = os.open(self.pathname, os.O_RDWR) from bleachbit.FileUtilities import getsize # Without admin privileges, this delete fails. yield Command.Delete(self.pathname) assert(os.path.exists(self.pathname)) fsize = getsize(self.pathname) if not fsize == 3: # Contents is "123" raise RuntimeError('Locked file has size %dB (not 3B)' % fsize) os.close(fd) # Now that the file is not locked, admin privileges # are not required to delete it. yield Command.Delete(self.pathname) class RuntimeErrorAction(ActionProvider): action_key = 'runtime' def __init__(self, action_element): self.pathname = action_element.getAttribute('path') def get_commands(self): # runtime exception, should fail and continue def runtime(): raise RuntimeError('This is a test exception') yield Command.Function(None, runtime, 'Test runtime exception') # real file, should succeed yield Command.Delete(self.pathname) class TruncateTestAction(ActionProvider): action_key = 'truncate.test' def __init__(self, action_element): self.pathname = action_element.getAttribute('path') def get_commands(self): # truncate real file yield Command.Truncate(self.pathname) # real file, should succeed yield Command.Delete(self.pathname) class WorkerTestCase(common.BleachbitTestCase): """Test case for module Worker""" def action_test_helper(self, command, special_expected, errors_expected, bytes_expected_posix, count_deleted_posix, bytes_expected_nt, count_deleted_nt): ui = CLI.CliCallback() (fd, filename) = tempfile.mkstemp( prefix='bleachbit-test-worker', dir=self.tempdir) os.write(fd, b'123') os.close(fd) self.assertExists(filename) astr = '<action command="%s" path="%s"/>' % (command, filename) cleaner = TestCleaner.action_to_cleaner(astr) backends['test'] = cleaner operations = {'test': ['option1']} worker = Worker(ui, True, operations) run = worker.run() while next(run): pass del backends['test'] self.assertNotExists(filename, "Path still exists '%s'" % filename) self.assertEqual(worker.total_special, special_expected, 'For command %s expecting %s special operations but observed %d' % (command, special_expected, worker.total_special)) self.assertEqual(worker.total_errors, errors_expected, 'For command %s expecting %d errors but observed %d' % (command, errors_expected, worker.total_errors)) if 'posix' == os.name: self.assertEqual(worker.total_bytes, bytes_expected_posix) self.assertEqual(worker.total_deleted, count_deleted_posix) elif 'nt' == os.name: self.assertEqual(worker.total_bytes, bytes_expected_nt) self.assertEqual(worker.total_deleted, count_deleted_nt) def test_AccessDenied(self): """Test Worker using Action.AccessDeniedAction""" self.action_test_helper('access.denied', 0, 1, 4096, 1, 3, 1) def test_DoesNotExist(self): """Test Worker using Action.DoesNotExistAction""" self.action_test_helper('does.not.exist', 0, 1, 4096, 1, 3, 1) def test_FunctionGenerator(self): """Test Worker using Action.FunctionGenerator""" self.action_test_helper('function.generator', 1, 0, 4096 + 10, 1, 3 + 10, 1) def test_FunctionPath(self): """Test Worker using Action.FunctionPathAction""" self.action_test_helper('function.path', 1, 0, 4096, 1, 3, 1) def test_FunctionPlain(self): """Test Worker using Action.FunctionPlainAction""" self.action_test_helper('function.plain', 1, 0, 4096 + 5, 1, 3 + 5, 1) def test_InvalidEncoding(self): """Test Worker using Action.InvalidEncodingAction""" self.action_test_helper('invalid.encoding', 0, 0, 4096, 2, 3, 2) @common.skipUnlessWindows def test_Locked(self): """Test Worker using Action.LockedAction""" from win32com.shell import shell if shell.IsUserAnAdmin(): # If an admin, the first attempt will mark for delete (3 bytes), # and the second attempt will actually delete it (3 bytes). errors_expected = 0 bytes_expected = 3 + 3 total_deleted = 2 else: # If not an admin, the first attempt will fail, and the second wil succeed. errors_expected = 1 bytes_expected = 3 total_deleted = 1 self.action_test_helper( 'locked', 0, errors_expected, None, None, bytes_expected, total_deleted) def test_RuntimeError(self): """Test Worker using Action.RuntimeErrorAction The Worker module handles these differently than access denied exceptions """ self.action_test_helper('runtime', 0, 1, 4096, 1, 3, 1) def test_Truncate(self): """Test Worker using Action.TruncateTestAction """ self.action_test_helper('truncate.test', 0, 0, 4096, 2, 3, 2) def test_deep_scan(self): """Test for deep scan""" # load cleaners from XML import bleachbit.CleanerML list(bleachbit.CleanerML.load_cleaners()) # DeepScan itself is tested elsewhere, so replace it here import bleachbit.DeepScan SaveDeepScan = bleachbit.DeepScan.DeepScan self.scanned = 0 parent = self class MyDeepScan: def __init__(self, searches): for (path, searches) in searches.items(): parent.assertEqual(path, os.path.expanduser('~')) for s in searches: parent.assertIn( s.regex, ['^Thumbs\\.db$', '^Thumbs\\.db:encryptable$']) def scan(self): parent.scanned += 1 yield True bleachbit.DeepScan.DeepScan = MyDeepScan # test operations = {'deepscan': ['thumbs_db']} ui = CLI.CliCallback() worker = Worker(ui, False, operations).run() while next(worker): pass self.assertEqual(1, self.scanned) # clean up bleachbit.DeepScan.DeepScan = SaveDeepScan def test_multiple_options(self): """Test one cleaner with two options""" ui = CLI.CliCallback() filename1 = self.mkstemp(prefix='bleachbit-test-worker') filename2 = self.mkstemp(prefix='bleachbit-test-worker') astr1 = '<action command="delete" search="file" path="%s"/>' % filename1 astr2 = '<action command="delete" search="file" path="%s"/>' % filename2 cleaner = TestCleaner.actions_to_cleaner([astr1, astr2]) backends['test'] = cleaner operations = {'test': ['option1', 'option2']} worker = Worker(ui, True, operations) run = worker.run() while next(run): pass del backends['test'] self.assertNotExists(filename1) self.assertNotExists(filename2) self.assertEqual(worker.total_special, 0) self.assertEqual(worker.total_errors, 0) self.assertEqual(worker.total_deleted, 2)
bleachbit/bleachbit
tests/TestWorker.py
Python
gpl-3.0
11,675
from setuptools import setup, find_packages version = {} with open('swk_casp/version.py') as f: exec(f.read(), version) url = 'https://github.com/trueneu/swiss-knife' setup(name='swk_casp', version=version['__version__'], packages=find_packages(), install_requires=[ 'swk>=0.0.4a4', 'requests>=2.9.1' ], description='Plugin for swk, enabling casp api', long_description='This is not a standalone program nor a library.' ' You should use it in conjunction with base program, swk.' ' For more information, please refer to documentation that can be found at {0}'.format(url), author="Pavel Gurkov", author_email="true.neu@gmail.com", url=url, license='GPLv3', platforms='Posix; MacOS X', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Intended Audience :: End Users/Desktop', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Topic :: System :: Systems Administration', 'Topic :: System :: Shells', 'Topic :: Utilities' ], keywords='cli swiss-knife sysadmin casp', entry_points={ 'swk_plugin': [ 'swk_casp = swk_casp.swk_casp:main' ], }, )
trueneu/swiss-knife
swk_plugins/swk_casp/setup.py
Python
gpl-3.0
1,746
using UnityEngine; using System.Collections; public class projectileAI : MonoBehaviour { public float speed = 25; void Start() { Vector3 newVelocity = Vector3.zero; newVelocity.y = speed; GetComponent<Rigidbody>().velocity = newVelocity; } // Update is called once per frame void Update() { } }
elmarjuz/gdp
Assets/SCRIPTS/projectileAI.cs
C#
gpl-3.0
359