repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
alanlong9278/ruby-china-message
app/helpers/nodes_helper.rb
135
# coding: utf-8 module NodesHelper def render_node_summary(node) content_tag(:p, node.summary, class: "summary") end end
gpl-2.0
Pzev/LazerTech
src/main/java/com/pzev/lazertech/item/ItemScrewdriver.java
220
package com.pzev.lazertech.item; public class ItemScrewdriver extends ItemLT { public ItemScrewdriver() { super(); this.setUnlocalizedName("screwdriver"); this.maxStackSize = 1; } }
gpl-2.0
FractalBobz/kmuddy
plugins/mapper/cmapdata.cpp
5263
/*************************************************************************** cmapdata.cpp ------------------- begin : Sat Mar 10 2001 copyright : (C) 2001 by Kmud Developer Team email : kmud-devel@kmud.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 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "cmapdata.h" #include <kapplication.h> #include "cmaplevel.h" CMapData::CMapData() { //zoneList.setAutoDelete(true); gridSize.setWidth(20); gridSize.setHeight(20); // FIXME_jp: This needs loading/saving defaultPathTwoWay = true; showUpperLevel = true; showLowerLevel = true; createModeActive = true; gridVisable = true; speedwalkAbortActive = false; speedwalkAbortLimit = 100; speedwalkDelay = 5; validRoomCheck = false; defaultTextColor = Qt::black; defaultTextFont = kapp->font(); defaultTextFont.setPointSize(8); failedMoveMsg.clear(); rootZone = NULL; //initDirections(); } CMapData::~CMapData() { } /** This is used to get the first zone in a list of zones */ CMapZone *CMapData::getFirstZone(void) { currentZone = rootZone; return currentZone; } /** This is used to get the next zone is a list of zones */ CMapZone *CMapData::getNextZone(void) { // Find next zone in current zone CMapZone *zone = findFirstSubZone(currentZone); if (zone) { currentZone = zone; return zone; } // Find next zone in at the same level // if no zones in the current zone m_foundCurrentZone = false; currentZone = getNextSameLevelZone(currentZone); return currentZone; } /** This is used to get the current zone in a list of zones */ CMapZone *CMapData::getCurrentZone(void) { return currentZone; } signed int CMapData::getZoneNumber(CMapZone *findZone) { int result = -1; int count = 0; for (CMapZone *zone = getFirstZone();zone!=0;zone = getNextZone()) { if (zone == findZone) { result = count; break; } count++; } return result; } void CMapData::initDirections(void) { directions[NORTH] = "north"; directions[SOUTH] = "south"; directions[WEST] = "west"; directions[EAST] = "east"; directions[NORTHWEST] = "northwest"; directions[NORTHEAST] = "northeast"; directions[SOUTHWEST] = "southwest"; directions[SOUTHEAST] = "southeast"; directions[UP] = "up"; directions[DOWN] = "down"; directions[NORTH+(NUM_DIRECTIONS/2)] = "n"; directions[SOUTH+(NUM_DIRECTIONS/2)] = "s"; directions[WEST+(NUM_DIRECTIONS/2)] = "w"; directions[EAST+(NUM_DIRECTIONS/2)] = "e"; directions[NORTHWEST+(NUM_DIRECTIONS/2)] = "nw"; directions[NORTHEAST+(NUM_DIRECTIONS/2)] = "ne"; directions[SOUTHWEST+(NUM_DIRECTIONS/2)] = "sw"; directions[SOUTHEAST+(NUM_DIRECTIONS/2)] = "se"; directions[UP+(NUM_DIRECTIONS/2)] = "u"; directions[DOWN+(NUM_DIRECTIONS/2)] = "d"; } /** This is used to get a zone and the given index as if they * were in a list. The current Zone is set to the one at the * index */ CMapZone *CMapData::getZoneAt(int index) { int i = 0; for (CMapZone *zone = getFirstZone(); zone !=0; zone=getNextZone()) { if (i == index) return zone; i++; } currentZone = NULL; return NULL; } /** This method is used to get the first sub zone of a parent zone * @param parent The parent zone, it is the fist sub zone of the parent that is returned * @return The first sub zone of the parent zone */ CMapZone *CMapData::findFirstSubZone(CMapZone *parent) { CMapZone *result = NULL; m_foundCurrentZone = false; // Check all the levels of the parent zone for a sub zone, make result equal // the first zone that is found. for (CMapLevel *level = parent->getLevels()->first();level!=0;level = parent->getLevels()->next()) { CMapZone *zone = level->getZoneList()->first(); if (zone) { result = zone; break; } } return result; } CMapZone *CMapData::getNextSameLevelZone(CMapZone *current) { CMapZone *parent = current->getZone(); CMapZone *result = NULL; if (parent) { for (CMapLevel *level = parent->getLevels()->first();level!=0; level = parent->getLevels()->next()) { for (CMapZone *zone = level->getZoneList()->first();zone!=0;zone = level->getZoneList()->next()) { if (zone==current) { m_foundCurrentZone = true; continue; } if (m_foundCurrentZone) { result = zone; return zone; break; } } } // Go up a zone and try again because a zone was not found at this level if (result==NULL) { m_foundCurrentZone = false; result = getNextSameLevelZone(parent); } } return result; }
gpl-2.0
lamsfoundation/lams
3rdParty_sources/spring/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.java
14828
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.annotation; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.annotation.Lookup; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.ResourceLoaderAware; import org.springframework.core.env.Environment; import org.springframework.core.env.EnvironmentCapable; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternUtils; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.classreading.CachingMetadataReaderFactory; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.core.type.filter.TypeFilter; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** * A component provider that scans the classpath from a base package. It then * applies exclude and include filters to the resulting classes to find candidates. * * <p>This implementation is based on Spring's * {@link org.springframework.core.type.classreading.MetadataReader MetadataReader} * facility, backed by an ASM {@link org.springframework.asm.ClassReader ClassReader}. * * @author Mark Fisher * @author Juergen Hoeller * @author Ramnivas Laddad * @author Chris Beams * @since 2.5 * @see org.springframework.core.type.classreading.MetadataReaderFactory * @see org.springframework.core.type.AnnotationMetadata * @see ScannedGenericBeanDefinition */ public class ClassPathScanningCandidateComponentProvider implements EnvironmentCapable, ResourceLoaderAware { static final String DEFAULT_RESOURCE_PATTERN = "**/*.class"; protected final Log logger = LogFactory.getLog(getClass()); private String resourcePattern = DEFAULT_RESOURCE_PATTERN; private final List<TypeFilter> includeFilters = new LinkedList<TypeFilter>(); private final List<TypeFilter> excludeFilters = new LinkedList<TypeFilter>(); private Environment environment; private ConditionEvaluator conditionEvaluator; private ResourcePatternResolver resourcePatternResolver; private MetadataReaderFactory metadataReaderFactory; /** * Protected constructor for flexible subclass initialization. * @since 4.3.6 */ protected ClassPathScanningCandidateComponentProvider() { } /** * Create a ClassPathScanningCandidateComponentProvider with a {@link StandardEnvironment}. * @param useDefaultFilters whether to register the default filters for the * {@link Component @Component}, {@link Repository @Repository}, * {@link Service @Service}, and {@link Controller @Controller} * stereotype annotations * @see #registerDefaultFilters() */ public ClassPathScanningCandidateComponentProvider(boolean useDefaultFilters) { this(useDefaultFilters, new StandardEnvironment()); } /** * Create a ClassPathScanningCandidateComponentProvider with the given {@link Environment}. * @param useDefaultFilters whether to register the default filters for the * {@link Component @Component}, {@link Repository @Repository}, * {@link Service @Service}, and {@link Controller @Controller} * stereotype annotations * @param environment the Environment to use * @see #registerDefaultFilters() */ public ClassPathScanningCandidateComponentProvider(boolean useDefaultFilters, Environment environment) { if (useDefaultFilters) { registerDefaultFilters(); } setEnvironment(environment); setResourceLoader(null); } /** * Set the resource pattern to use when scanning the classpath. * This value will be appended to each base package name. * @see #findCandidateComponents(String) * @see #DEFAULT_RESOURCE_PATTERN */ public void setResourcePattern(String resourcePattern) { Assert.notNull(resourcePattern, "'resourcePattern' must not be null"); this.resourcePattern = resourcePattern; } /** * Add an include type filter to the <i>end</i> of the inclusion list. */ public void addIncludeFilter(TypeFilter includeFilter) { this.includeFilters.add(includeFilter); } /** * Add an exclude type filter to the <i>front</i> of the exclusion list. */ public void addExcludeFilter(TypeFilter excludeFilter) { this.excludeFilters.add(0, excludeFilter); } /** * Reset the configured type filters. * @param useDefaultFilters whether to re-register the default filters for * the {@link Component @Component}, {@link Repository @Repository}, * {@link Service @Service}, and {@link Controller @Controller} * stereotype annotations * @see #registerDefaultFilters() */ public void resetFilters(boolean useDefaultFilters) { this.includeFilters.clear(); this.excludeFilters.clear(); if (useDefaultFilters) { registerDefaultFilters(); } } /** * Register the default filter for {@link Component @Component}. * <p>This will implicitly register all annotations that have the * {@link Component @Component} meta-annotation including the * {@link Repository @Repository}, {@link Service @Service}, and * {@link Controller @Controller} stereotype annotations. * <p>Also supports Java EE 6's {@link javax.annotation.ManagedBean} and * JSR-330's {@link javax.inject.Named} annotations, if available. * */ @SuppressWarnings("unchecked") protected void registerDefaultFilters() { this.includeFilters.add(new AnnotationTypeFilter(Component.class)); ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader(); try { this.includeFilters.add(new AnnotationTypeFilter( ((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false)); logger.debug("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning"); } catch (ClassNotFoundException ex) { // JSR-250 1.1 API (as included in Java EE 6) not available - simply skip. } try { this.includeFilters.add(new AnnotationTypeFilter( ((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false)); logger.debug("JSR-330 'javax.inject.Named' annotation found and supported for component scanning"); } catch (ClassNotFoundException ex) { // JSR-330 API not available - simply skip. } } /** * Set the Environment to use when resolving placeholders and evaluating * {@link Conditional @Conditional}-annotated component classes. * <p>The default is a {@link StandardEnvironment}. * @param environment the Environment to use */ public void setEnvironment(Environment environment) { Assert.notNull(environment, "Environment must not be null"); this.environment = environment; this.conditionEvaluator = null; } @Override public final Environment getEnvironment() { return this.environment; } /** * Return the {@link BeanDefinitionRegistry} used by this scanner, if any. */ protected BeanDefinitionRegistry getRegistry() { return null; } /** * Set the {@link ResourceLoader} to use for resource locations. * This will typically be a {@link ResourcePatternResolver} implementation. * <p>Default is a {@code PathMatchingResourcePatternResolver}, also capable of * resource pattern resolving through the {@code ResourcePatternResolver} interface. * @see org.springframework.core.io.support.ResourcePatternResolver * @see org.springframework.core.io.support.PathMatchingResourcePatternResolver */ @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader); this.metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader); } /** * Return the ResourceLoader that this component provider uses. */ public final ResourceLoader getResourceLoader() { return this.resourcePatternResolver; } /** * Set the {@link MetadataReaderFactory} to use. * <p>Default is a {@link CachingMetadataReaderFactory} for the specified * {@linkplain #setResourceLoader resource loader}. * <p>Call this setter method <i>after</i> {@link #setResourceLoader} in order * for the given MetadataReaderFactory to override the default factory. */ public void setMetadataReaderFactory(MetadataReaderFactory metadataReaderFactory) { this.metadataReaderFactory = metadataReaderFactory; } /** * Return the MetadataReaderFactory used by this component provider. */ public final MetadataReaderFactory getMetadataReaderFactory() { return this.metadataReaderFactory; } /** * Scan the class path for candidate components. * @param basePackage the package to check for annotated classes * @return a corresponding Set of autodetected bean definitions */ public Set<BeanDefinition> findCandidateComponents(String basePackage) { Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>(); try { String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resolveBasePackage(basePackage) + '/' + this.resourcePattern; Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath); boolean traceEnabled = logger.isTraceEnabled(); boolean debugEnabled = logger.isDebugEnabled(); for (Resource resource : resources) { if (traceEnabled) { logger.trace("Scanning " + resource); } if (resource.isReadable()) { try { MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource); if (isCandidateComponent(metadataReader)) { ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader); sbd.setResource(resource); sbd.setSource(resource); if (isCandidateComponent(sbd)) { if (debugEnabled) { logger.debug("Identified candidate component class: " + resource); } candidates.add(sbd); } else { if (debugEnabled) { logger.debug("Ignored because not a concrete top-level class: " + resource); } } } else { if (traceEnabled) { logger.trace("Ignored because not matching any filter: " + resource); } } } catch (Throwable ex) { throw new BeanDefinitionStoreException( "Failed to read candidate component class: " + resource, ex); } } else { if (traceEnabled) { logger.trace("Ignored because not readable: " + resource); } } } } catch (IOException ex) { throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex); } return candidates; } /** * Resolve the specified base package into a pattern specification for * the package search path. * <p>The default implementation resolves placeholders against system properties, * and converts a "."-based package path to a "/"-based resource path. * @param basePackage the base package as specified by the user * @return the pattern specification to be used for package searching */ protected String resolveBasePackage(String basePackage) { return ClassUtils.convertClassNameToResourcePath(this.environment.resolveRequiredPlaceholders(basePackage)); } /** * Determine whether the given class does not match any exclude filter * and does match at least one include filter. * @param metadataReader the ASM ClassReader for the class * @return whether the class qualifies as a candidate component */ protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException { for (TypeFilter tf : this.excludeFilters) { if (tf.match(metadataReader, this.metadataReaderFactory)) { return false; } } for (TypeFilter tf : this.includeFilters) { if (tf.match(metadataReader, this.metadataReaderFactory)) { return isConditionMatch(metadataReader); } } return false; } /** * Determine whether the given class is a candidate component based on any * {@code @Conditional} annotations. * @param metadataReader the ASM ClassReader for the class * @return whether the class qualifies as a candidate component */ private boolean isConditionMatch(MetadataReader metadataReader) { if (this.conditionEvaluator == null) { this.conditionEvaluator = new ConditionEvaluator(getRegistry(), getEnvironment(), getResourceLoader()); } return !this.conditionEvaluator.shouldSkip(metadataReader.getAnnotationMetadata()); } /** * Determine whether the given bean definition qualifies as candidate. * <p>The default implementation checks whether the class is not an interface * and not dependent on an enclosing class. * <p>Can be overridden in subclasses. * @param beanDefinition the bean definition to check * @return whether the bean definition qualifies as a candidate component */ protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) { AnnotationMetadata metadata = beanDefinition.getMetadata(); return (metadata.isIndependent() && (metadata.isConcrete() || (metadata.isAbstract() && metadata.hasAnnotatedMethods(Lookup.class.getName())))); } /** * Clear the underlying metadata cache, removing all cached class metadata. */ public void clearCache() { if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) { ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache(); } } }
gpl-2.0
lamsfoundation/lams
3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/MessageIDBuilder.java
1386
/* * Licensed to the University Corporation for Advanced Internet Development, * Inc. (UCAID) under one or more contributor license agreements. See the * NOTICE file distributed with this work for additional information regarding * copyright ownership. The UCAID licenses this file to You under the Apache * License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opensaml.ws.wsaddressing.impl; import org.opensaml.ws.wsaddressing.MessageID; /** * MessageIDBuilder. * */ public class MessageIDBuilder extends AbstractWSAddressingObjectBuilder<MessageID> { /** {@inheritDoc} */ public MessageID buildObject() { return buildObject(MessageID.ELEMENT_NAME); } /** {@inheritDoc} */ public MessageID buildObject(String namespaceURI, String localName, String namespacePrefix) { return new MessageIDImpl(namespaceURI, localName, namespacePrefix); } }
gpl-2.0
rafaeljusto/druns
core/payment/dao_log.go
1099
package payment import ( "fmt" "net" "strings" "github.com/rafaeljusto/druns/core/db" "github.com/rafaeljusto/druns/core/dblog" "github.com/rafaeljusto/druns/core/errors" ) type daoLog struct { sqler db.SQLer ip net.IP agent int tableName string tableFields []string } func newDAOLog(sqler db.SQLer, ip net.IP, agent int) daoLog { return daoLog{ sqler: sqler, ip: ip, agent: agent, tableName: "payment_log", tableFields: []string{ "id", "client_id", "status", "expires_at", "value", "log_id", }, } } func (dao *daoLog) save(p *Payment, operation dblog.Operation) error { dbLog, err := dblog.NewService(dao.sqler).Create(dao.agent, dao.ip, operation) if err != nil { return err } query := fmt.Sprintf( "INSERT INTO %s (%s) VALUES (%s)", dao.tableName, strings.Join(dao.tableFields, ", "), db.Placeholders(dao.tableFields), ) _, err = dao.sqler.Exec( query, p.Id, p.Client.Id, p.Status, p.ExpiresAt, p.Value, dbLog.Id, ) if err != nil { return errors.New(err) } return nil }
gpl-2.0
function2/projecteuler
src/problem_27.cpp
2126
// https://projecteuler.net/problem=27 // Michael Seyfert <michael@codesand.org> /* Problem Statement: Euler discovered the remarkable quadratic formula: n² + n + 41 It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 41² + 41 + 41 is clearly divisible by 41. The incredible formula n² − 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, −79 and 1601, is −126479. Considering quadratics of the form: n² + an + b, where |a| < 1000 and |b| < 1000 where |n| is the modulus/absolute value of n e.g. |11| = 11 and |−4| = 4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. */ /* We are given two good examples for this problem to check your code. */ #include<cmath> #include<vector> #include<iostream> using namespace std; int main() { // Do a prime seive. static const int N = 1000000; vector<bool> prime(N,true); prime[0] = prime[1] = false; int root = int(floor(sqrt(N))); for(int k = 2;k <= root;++k) for(int j = k*2;j < N; j += k) prime[j] = false; // First solution, brute force: int best_streak = 0; int best_a=-1000; int best_b=-1000; for(int a = -999; a < 1000; ++a) for(int b = -999; b < 1000; ++b) { // Check prime streak. int streak = 0; for(int n = 0;;++n){ int val = n * n + a * n + b; if(val < 0) break; if(val >= N){ cerr << "!!NEED LARGER N\n"; break; } if(prime[val]) ++streak; else break; } // // should be 40, 41. // if(a == 1 && b == 41) // cout << "*** " << streak << ' ' << a*b << '\n'; if(streak > best_streak){ best_a = a; best_b = b; best_streak = streak; // cout << best_a << ' ' << best_b << ' ' << best_streak << '\n'; } } cout << best_a << ' ' << best_b << ' ' << best_streak << '\n'; cout << best_a * best_b << '\n'; }
gpl-2.0
laurynasl/rubyrogue
spec/models/map_spec.rb
12115
# Copyright (C) 2008 Laurynas Liutkus # All rights reserved. See the file named LICENSE in the distribution # for more details. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. require File.dirname(__FILE__) + '/../spec_helper' describe Map, "name" do before(:each) do @map = Map.load(TESTMAP) @map.name = 'cave' end it "should return map name" do @map.name.should == 'cave' end it "should return map name with index" do @map.index = 3 @map.name.should == 'cave-3' end end describe Map, 'load' do it "should load map from file" do @map = Map.load(TESTMAP) @map.name.should == 'cave-1' @map.tiles.size.should == 21 @map.tiles[1].should == "#...........................############" @map.memory.size.should == 21 @map.memory[1].should == " " @map.width.should == 40 @map.height.should == 21 @map.squares.should_not be_nil @map.monsters.first.should be_instance_of(Monster) end end describe Map, 'find_square' do it "should find square" do @map = Map.load(TESTMAP) square = @map.find_square(1, 1) square.should be_instance_of(Square) square.x.should == 1 square.y.should == 1 square.inventory.items.first.name.should == 'short sword' end it "should return nil when square is empty and remove that square" do @map = Map.load(TESTMAP) square = @map.find_square(1, 1) square.inventory.items.clear square.should be_empty @map.find_square(1, 1).should be_nil @map.squares[@map.width + 1].should be_nil end it "should create square if forced" do @map = Map.load(TESTMAP) @map.find_square(2, 1).should be_nil #ensures changes to map don't silently break test square = @map.find_square(2, 1, :force => true) square.should be_instance_of(Square) square.x.should == 2 square.y.should == 1 square.inventory.items.should == [] end end describe Map, 'find_monster' do it "should find monster" do @map = Map.load(TESTMAP) monster = @map.find_monster(11, 1) monster.should be_instance_of(Monster) monster.x.should == 11 monster.y.should == 1 monster.monster_type.should == 'kobold' end end describe Map, "square_symbol_at" do before(:each) do @game = testgame @map = @game.map end it "should return background" do @map.lighting = [true] * (@map.width * @map.height) @map.square_symbol_at(3, 1).should be_char(:yellow, '.') @map.square_symbol_at(3, 2).should be_char(:yellow, '#') #@map.square_symbol_at(2, 1).should be_char('@') @map.square_symbol_at(2, 14).should be_char(:white, '(') @map.square_symbol_at(10, 1).should be_char(:white, '[') @map.find_square(10, 1).inventory.items = [] @map.square_symbol_at(10, 1).should be_char(:yellow, '.') @map.square_symbol_at(26, 2).should be_char(:white, '>') @map.find_square(26, 2).stair['down'] = false @map.square_symbol_at(26, 2).should be_char(:white, '<') end it "should return space when square is outside of map" do @map.lighting = [true] * (@map.width * @map.height) @map.square_symbol_at(100, 1).should be_char(:black, ' ') @map.square_symbol_at(1, 100).should be_char(:black, ' ') end it "should display monster" do @map.lighting = [true] * (@map.width * @map.height) @map.square_symbol_at(11, 1).should be_char(:white, 'k') MonsterClass.all['kobold'].symbol = 'K' @map.square_symbol_at(11, 1).should be_char(:white, 'K') end it "should recall from memory" do @map.lighting = [] @map.memory = ['', 'abcdefghijkl'] @map.square_symbol_at(11, 1).should be_char(:white, 'l') end end describe Map, "passable_at?" do it "should return true when square is passable" do @game = testgame @map = @game.map @map.passable_at?(0, 0).should be_false # # @map.passable_at?(1, 1).should be_true # . @map.passable_at?(11, 1).should be_false# k end end describe Map, "opaque_at?" do it "should return true when square opaque (light cannot pass through it)" do @game = testgame @map = @game.map @map.opaque_at?(0, 0).should be_true # # @map.opaque_at?(1, 1).should be_false # . end end describe Map, "try_to_generate_monster" do [nil, 0].each do |value| it "should generate monster and set counter to monsters count + 1, multiplied by 100" do kobold @game = testgame @map = @game.map @map.generate_monster_counter = value @map.should_receive(:find_random_passable_square).and_return([1, 6]) @kobold.x = nil @kobold.y = nil MonsterClass.should_receive(:generate).and_return(@kobold) @map.try_to_generate_monster @map.find_monster(1, 6).should == @kobold @map.generate_monster_counter.should == 200 end end it "should set count to 300 when there are 2 monsters" do kobold @game = testgame @map = @game.map @ui.stub!(:repaint_square) @map.monsters << @kobold @map.try_to_generate_monster @map.generate_monster_counter.should == 300 end it "should not generate monster when counter is more than" do @game = testgame @map = @game.map @map.generate_monster_counter = 11 @map.should_not_receive(:find_random_passable_square) @map.try_to_generate_monster @map.generate_monster_counter.should == 10 end end describe Map, "find_random_passable_square" do before(:each) do @game = testgame @map = @game.map end it "should find at first try" do @map.should_receive(:rand).with(40).and_return(1) @map.should_receive(:rand).with(21).and_return(6) @map.find_random_passable_square.should == [1, 6] end it "should find at third try" do @map.should_receive(:rand).and_return(34, 11, 22, 7, 23, 8) @map.find_random_passable_square.should == [23, 8] end end describe Map, "Field of view (fov)" do it "should not see monster which it cannot see" do @game = testgame @game.player.x = 3 @game.player.y = 14 @map = @game.map @map.calculate_fov @map.visible_at?(4, 14).should be_true @map.visible_at?(3, 18).should be_nil end end describe Map, "apply_lighting" do before(:each) do @game = testgame @map = @game.map @map.lighting = Hash.new(true) @map.spotted_monsters = [] end it "should memorize square" do @map.memory[3][2].should == ' '[0] @map.apply_lighting(2, 3) @map.memory[3][2].should == '#'[0] end it "should memorize spotted monster" do @kobold = @map.find_monster(11, 1) @map.apply_lighting(11, 1) @map.spotted_monsters.first.should == @kobold end end describe Map, "find_nearest_visible_monster" do it "should return when no monster is visible" do @game = testgame @game.map.find_nearest_visible_monster.should be_nil end it "should find monster using monsters spotted during calculate_fov" do @game = testgame @map = @game.map @kobold = @map.find_monster(11, 1) @game.player.x = 6 @map.calculate_fov @map.find_nearest_visible_monster.should == @kobold end it "should find nearest monster using square_range_to from spotted_monsters" do @game = testgame orc('x' => 3, 'y' => 1) kobold('x' => 4, 'y' => 1) @game.map.spotted_monsters << @kobold << @orc @game.map.find_nearest_visible_monster.should == @orc end end describe Map, "drop_items" do it "should put items at specified coordinates" do @game = testgame @game.map.drop_items(1, 2, [Item.new('knife'), Item.new('short bow')]) @game.map.find_square(1, 2).inventory.collect{|item| item.to_s}.should == ['15 darts', 'knife', 'short bow'] end end describe Map, "inspect" do it "should not be so verbose and display just map name" do @game = testgame @game.map.inspect.should == '<Map cave-1>' end end describe Map, "generate" do it "should generate map" do #Map.should_receive(:rand).with(7).and_return(3) # width will be 3 + 3 #Map.should_receive(:rand).with(7).and_return(5) # height will be 5 + 3 #Map.should_receive(:rand).with(34).and_return(11) # x #Map.should_receive(:rand).with(13).and_return(2) # y map = Map.generate :width => 120, :height => 45, :rooms => 50 map.width.should == 120 map.height.should == 45 map.tiles.size.should == 45 #puts #map.tiles.each do |line| #line.size.should == 120 #puts line #end #p map.rooms end end describe Map, "can_place_room?" do before(:each) do @map = Map.new @map.width = 40 @map.height = 20 @map.tiles = (0..19).collect{ '#' * 40 } @room = {:width => 5, :height => 4, :x => 12, :y => 9} @map.rooms = [@room] @map.place_room(@room) end [ {:width => 5, :height => 4, :x => 2, :y => 1}, {:width => 6, :height => 4, :x => 10, :y => 14}, {:width => 6, :height => 4, :x => 4, :y => 11}, {:width => 6, :height => 4, :x => 18, :y => 11} ].each do |room| it "should return true because there is enough space" do @map.place_room(room, ',') begin @map.can_place_room?(room).should be_true rescue puts puts @map.tiles p room raise end end end [ {:width => 6, :height => 4, :x => 10, :y => 5}, {:width => 6, :height => 4, :x => 10, :y => 13}, {:width => 6, :height => 4, :x => 5, :y => 11}, {:width => 6, :height => 4, :x => 17, :y => 11} ].each do |room| it "should return false because it touches existing room" do @map.place_room(room, ',') begin @map.can_place_room?(room).should be_false rescue puts puts @map.tiles p room raise end end end after(:each) do #instance_variables.each do |i| #value = instance_variable_get(i) #printf "%s = %s\n", i, value #end #puts #puts @_defined_description #puts @map.tiles end end describe Map, "connect_rooms" do before(:each) do @map = Map.new @map.width = 40 @map.height = 20 @map.tiles = (0..19).collect{ '#' * 40 } @room = {:width => 5, :height => 4, :x => 12, :y => 9} @map.rooms = [@room] @map.place_room(@room) @map.lighting = mock('Lighting', :'[]' => true) @map.monsters = [] @map.squares = [] end [ {:width => 5, :height => 4, :x => 2, :y => 1} ].each do |room| it "should connect two rooms" do @map.place_room(room, ',') begin @map.join_rooms(@room, room) @map.square_symbol_at(14, 2).should be_char(:yellow, '.') @map.square_symbol_at(13, 2).should be_char(:yellow, '.') @map.square_symbol_at(14, 3).should be_char(:yellow, '.') rescue puts puts @map.tiles p room raise end end end end describe Map, "dungeon" do it "should return dungeon" do game = infinite_game game.load_map('dungeons of doom-3') map = game.map map.dungeon.should == {'infinite' => true, 'danger_multiplier' => 5, 'danger_summand' => 2} end end describe Map, "danger" do it "should return danger level" do #(map index multiplied by dungeon danger multiplier and summed with dungeon danger summand) game = infinite_game game.load_map('dungeons of doom-3') map = game.map map.danger.should == 17 end it "should return 1 if dungeon is undefined" do map = Map.load(TESTMAP) map.danger.should == 1 end end
gpl-2.0
michellemorales/OpenMM
kaldi/src/nnet3/nnet-descriptor-test.cc
8189
// nnet3/nnet-descriptor-test.cc // Copyright 2015 Johns Hopkins University (author: Daniel Povey) // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "nnet3/nnet-descriptor.h" namespace kaldi { namespace nnet3 { ForwardingDescriptor *GenRandForwardingDescriptor(int32 num_nodes) { if (Rand() % 2 != 0) { return new SimpleForwardingDescriptor(Rand() % num_nodes); } else { int32 r = Rand() % 4; if (r == 0) { Index offset; offset.t = Rand() % 5; offset.x = Rand() % 2; return new OffsetForwardingDescriptor(GenRandForwardingDescriptor(num_nodes), offset); } else if (r == 1) { std::vector<ForwardingDescriptor*> vec; int32 n = 1 + Rand() % 3; for (int32 i = 0; i < n; i++) vec.push_back(GenRandForwardingDescriptor(num_nodes)); return new SwitchingForwardingDescriptor(vec); } else if (r == 2) { return new RoundingForwardingDescriptor( GenRandForwardingDescriptor(num_nodes), 1 + Rand() % 4); } else { return new ReplaceIndexForwardingDescriptor( GenRandForwardingDescriptor(num_nodes), (Rand() % 2 == 0 ? ReplaceIndexForwardingDescriptor::kT : ReplaceIndexForwardingDescriptor::kX), -2 + Rand() % 4); } } } // generates a random descriptor. SumDescriptor *GenRandSumDescriptor( int32 num_nodes) { if (Rand() % 3 != 0) { bool not_required = (Rand() % 5 == 0); if (not_required) return new OptionalSumDescriptor(GenRandSumDescriptor(num_nodes)); else return new SimpleSumDescriptor(GenRandForwardingDescriptor(num_nodes)); } else { return new BinarySumDescriptor((Rand() % 2 == 0 ? BinarySumDescriptor::kSum: BinarySumDescriptor::kFailover), GenRandSumDescriptor(num_nodes), GenRandSumDescriptor(num_nodes)); } } // generates a random descriptor. void GenRandDescriptor(int32 num_nodes, Descriptor *desc) { int32 num_parts = 1 + Rand() % 3; std::vector<SumDescriptor*> parts; for (int32 part = 0; part < num_parts; part++) parts.push_back(GenRandSumDescriptor(num_nodes)); *desc = Descriptor(parts); } // This function tests both the I/O for the descriptors, and the // Copy() function. void UnitTestDescriptorIo() { for (int32 i = 0; i < 100; i++) { int32 num_nodes = 1 + Rand() % 5; std::vector<std::string> node_names(num_nodes); for (int32 i = 0; i < node_names.size(); i++) { std::ostringstream ostr; ostr << "a" << (i+1); node_names[i] = ostr.str(); } Descriptor desc; std::ostringstream ostr; GenRandDescriptor(num_nodes, &desc); desc.WriteConfig(ostr, node_names); Descriptor desc2(desc), desc3, desc4; desc3 = desc; std::vector<std::string> tokens; DescriptorTokenize(ostr.str(), &tokens); tokens.push_back("end of input"); std::istringstream istr(ostr.str()); const std::string *next_token = &(tokens[0]); bool ans = desc4.Parse(node_names, &next_token); KALDI_ASSERT(ans); std::ostringstream ostr2; desc2.WriteConfig(ostr2, node_names); std::ostringstream ostr3; desc3.WriteConfig(ostr3, node_names); std::ostringstream ostr4; desc4.WriteConfig(ostr4, node_names); KALDI_ASSERT(ostr.str() == ostr2.str()); KALDI_ASSERT(ostr.str() == ostr3.str()); KALDI_LOG << "x = " << ostr.str(); KALDI_LOG << "y = " << ostr4.str(); if (ostr.str() != ostr4.str()) { KALDI_WARN << "x and y differ: checking that it's due to Offset normalization."; KALDI_ASSERT(ostr.str().find("Offset(Offset") != std::string::npos || (ostr.str().find("Offset(") != std::string::npos && ostr.str().find(", 0)") != std::string::npos)); } } } // This function tests GeneralDescriptor, but only for correctly-normalized input. void UnitTestGeneralDescriptor() { for (int32 i = 0; i < 100; i++) { int32 num_nodes = 1 + Rand() % 5; std::vector<std::string> node_names(num_nodes); for (int32 i = 0; i < node_names.size(); i++) { std::ostringstream ostr; ostr << "a" << (i+1); node_names[i] = ostr.str(); } Descriptor desc; std::ostringstream ostr; GenRandDescriptor(num_nodes, &desc); desc.WriteConfig(ostr, node_names); Descriptor desc2(desc), desc3; desc3 = desc; std::vector<std::string> tokens; DescriptorTokenize(ostr.str(), &tokens); tokens.push_back("end of input"); std::istringstream istr(ostr.str()); const std::string *next_token = &(tokens[0]); GeneralDescriptor *gen_desc = GeneralDescriptor::Parse(node_names, &next_token); if (*next_token != "end of input") KALDI_ERR << "Parsing Descriptor, expected end of input but got " << "'" << *next_token << "'"; Descriptor *desc4 = gen_desc->ConvertToDescriptor(); std::ostringstream ostr2; desc4->WriteConfig(ostr2, node_names); KALDI_LOG << "Original descriptor was: " << ostr.str(); KALDI_LOG << "Parsed descriptor was: " << ostr2.str(); if (ostr2.str() != ostr.str()) KALDI_WARN << "Strings differed. Check manually."; delete gen_desc; delete desc4; } } // normalizes the text form of a descriptor. std::string NormalizeTextDescriptor(const std::vector<std::string> &node_names, const std::string &desc_str) { std::vector<std::string> tokens; DescriptorTokenize(desc_str, &tokens); tokens.push_back("end of input"); const std::string *next_token = &(tokens[0]); GeneralDescriptor *gen_desc = GeneralDescriptor::Parse(node_names, &next_token); if (*next_token != "end of input") KALDI_ERR << "Parsing Descriptor, expected end of input but got " << "'" << *next_token << "'"; Descriptor *desc = gen_desc->ConvertToDescriptor(); std::ostringstream ostr; desc->WriteConfig(ostr, node_names); delete gen_desc; delete desc; KALDI_LOG << "Result of normalizing " << desc_str << " is: " << ostr.str(); return ostr.str(); } void UnitTestGeneralDescriptorSpecial() { std::vector<std::string> names; names.push_back("a"); names.push_back("b"); names.push_back("c"); names.push_back("d"); KALDI_ASSERT(NormalizeTextDescriptor(names, "a") == "a"); KALDI_ASSERT(NormalizeTextDescriptor(names, "Offset(Offset(a, 3, 5), 2, 1)") == "Offset(a, 5, 6)"); KALDI_ASSERT(NormalizeTextDescriptor(names, "Offset(Sum(a, b), 2, 1)") == "Sum(Offset(a, 2, 1), Offset(b, 2, 1))"); KALDI_ASSERT(NormalizeTextDescriptor(names, "Sum(Append(a, b), Append(c, d))") == "Append(Sum(a, c), Sum(b, d))"); KALDI_ASSERT(NormalizeTextDescriptor(names, "Append(Append(a, b), Append(c, d))") == "Append(a, b, c, d)"); KALDI_ASSERT(NormalizeTextDescriptor(names, "Sum(a, b, c, d)") == "Sum(a, Sum(b, Sum(c, d)))"); KALDI_ASSERT(NormalizeTextDescriptor(names, "Sum(a)") == "a"); KALDI_ASSERT(NormalizeTextDescriptor(names, "Offset(a, 0)") == "a"); } } // namespace nnet3 } // namespace kaldi int main() { using namespace kaldi; using namespace kaldi::nnet3; UnitTestGeneralDescriptorSpecial(); UnitTestGeneralDescriptor(); UnitTestDescriptorIo(); KALDI_LOG << "Nnet descriptor tests succeeded."; return 0; }
gpl-2.0
dziamid/velo
wp-content/themes/mindig/theme/shortcodes.php
59615
<?php /** * This file belongs to the YIT Plugin Framework. * * This source file is subject to the GNU GENERAL PUBLIC LICENSE (GPL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.gnu.org/licenses/gpl-3.0.txt */ /** * Return the list of shortcodes and their settings * * @package Yithemes * @author Francesco Licandro <francesco.licandro@yithemes.com> * @since 1.0.0 */ if ( ! defined( 'ABSPATH' ) ) { exit; } // Exit if accessed directly $config = YIT_Plugin_Common::load(); $awesome_icons = YIT_Plugin_Common::get_awesome_icons(); $animate = $config['animate']; $shop_shortcodes = array(); $theme_shortcodes = array( /* === Accordion === */ 'accordion' => array( 'title' => __('Accordion', 'yit' ), 'description' => __('Create a accordion content', 'yit' ), 'tab' => 'shortcodes', 'has_content' => true, 'in_visual_composer' => true, 'attributes' => array( 'title' => array( 'title' => __('Title', 'yit'), 'type' => 'text', 'std' => 'your_title' ), 'opened' => array( 'title' => __('Opened', 'yit'), 'type' => 'checkbox', 'std' => 'no' ), 'class_icon_closed' => array( 'title' => __('Class Icon Closed', 'yit'), 'type' => 'select-icon', 'options' => $awesome_icons, 'std' => 'plus' ), 'class_icon_opened' => array( 'title' => __('Class Icon Opened', 'yit'), 'type' => 'select-icon', 'options' => $awesome_icons, 'std' => 'minus' ), 'animate' => array( 'title' => __('Animation', 'yit'), 'type' => 'select', 'options' => $animate, 'std' => '' ), 'animation_delay' => array( 'title' => __('Animation Delay', 'yit'), 'type' => 'text', 'desc' => __('This value determines the delay to which the animation starts once it\'s visible on the screen.', 'yit'), 'std' => '0' ) ) ), /* ====== ONE PAGE ANCHOR ======== */ 'onepage_anchor' => array( 'title' => __( 'OnePage Anchor', 'yit' ), 'description' => __( 'Add the anchor for your OnePage', 'yit' ), 'tab' => 'shortcodes', 'has_content' => false, 'in_visual_composer' => true, 'attributes' => array( 'name' => array( 'title' => __('Name anchor (the name of anchor you define in the menu with #)', 'yit'), 'type' => 'text', 'std' => '' ) ) ), /* === MODAL === */ 'modal' => array( 'title' => __( 'Modal Window', 'yit' ), 'description' => __( 'Create a modal window', 'yit' ), 'tab' => 'shortcodes', 'in_visual_composer' => true, 'has_content' => true, 'attributes' => array( 'title' => array( 'title' => __( 'Modal Title', 'yit' ), 'type' => 'text', 'std' => __( 'Your title here', 'yit' ) ), 'opener' => array( 'title' => __( 'Type of modal opener', 'yit' ), 'type' => 'select', 'options' => array( 'button' => __( 'Button', 'yit' ), 'text' => __( 'Textual Link', 'yit' ), 'image' => __( 'Image', 'yit' ) ), 'std' => 'button' ), 'button_text_opener' => array( 'title' => __( 'Text of the button', 'yit' ), 'type' => 'text', 'std' => __( 'Open Modal', 'yit' ), 'deps' => array( 'ids' => 'opener', 'values' => 'button' ) ), 'button_style' => array( 'title' => __( 'Style of the button', 'yit' ), 'type' => 'select', 'options' => array( 'normal' => __( 'Normal', 'yit' ), 'alternative' => __( 'Alternative', 'yit' ) ), 'std' => 'normal', 'deps' => array( 'ids' => 'opener', 'values' => 'button' ) ), 'link_text_opener' => array( 'title' => __( 'Text of the link', 'yit' ), 'type' => 'text', 'std' => __( 'Open Modal', 'yit' ), 'deps' => array( 'ids' => 'opener', 'values' => 'text' ) ), 'link_icon_type' => array( 'title' => __( 'Icon type', 'yit' ), 'type' => 'select', 'options' => array( 'none' => __( 'None', 'yit' ), 'theme-icon' => __( 'Theme Icon', 'yit' ), 'custom' => __( 'Custom Icon', 'yit' ) ), 'std' => 'none', 'deps' => array( 'ids' => 'opener', 'values' => 'text' ) ), 'link_icon_theme' => array( 'title' => __( 'Icon', 'yit' ), 'type' => 'select-icon', // home|file|time|ecc 'options' => $awesome_icons, 'std' => '', 'deps' => array( 'ids' => 'link_icon_type', 'values' => 'theme-icon' ) ), 'link_icon_url' => array( 'title' => __( 'Icon URL', 'yit' ), 'type' => 'text', 'std' => '', 'deps' => array( 'ids' => 'link_icon_type', 'values' => 'custom' ) ), 'link_text_size' => array( 'title' => __( 'Font size of the link', 'yit' ), 'type' => 'number', 'std' => 17, 'min' => 1, 'max' => 99, 'deps' => array( 'ids' => 'opener', 'values' => 'text' ) ), 'image_opener' => array( 'title' => __( 'Url of the image', 'yit' ), 'type' => 'text', 'std' => '', 'deps' => array( 'ids' => 'opener', 'values' => 'image' ) ), ) ), /*================= FEATURED COLUMNS ================*/ 'featured_column' => array( 'title' => __( 'Featured Columns', 'yit' ), 'description' => __( 'Print a column with image, description and button', 'yit' ), 'tab' => 'shortcodes', 'has_content' => true, 'in_visual_composer' => true, 'create' => true, 'attributes' => array( 'title' => array( 'title' => __( 'Title', 'yit' ), 'type' => 'text', 'std' => '' ), 'subtitle' => array( 'title' => __( 'Subtitle', 'yit' ), 'type' => 'text', 'std' => '' ), 'show_button' => array( 'title' => __( 'Show Button', 'yit' ), 'type' => 'checkbox', 'std' => 'yes' ), 'label_button' => array( 'title' => __( 'Label Button', 'yit' ), 'type' => 'text', 'std' => '', 'deps' => array( 'ids' => 'show_button', 'values' => '1' ) ), 'url_button' => array( 'title' => __( 'Url Button', 'yit' ), 'type' => 'text', 'std' => '', 'deps' => array( 'ids' => 'show_button', 'values' => '1' ) ), 'background_image' => array( 'title' => __( 'Background image URL', 'yit' ), 'type' => 'text', 'std' => '' ), 'first' => array( 'title' => __( 'First column?', 'yit' ), 'type' => 'checkbox', 'std' => 'no' ), 'last' => array( 'title' => __( 'Last Columns?', 'yit' ), 'type' => 'checkbox', 'std' => 'no' ), 'animate' => array( 'title' => __('Animation', 'yit'), 'type' => 'select', 'options' => $animate, 'std' => '' ), 'animation_delay' => array( 'title' => __('Animation Delay', 'yit'), 'type' => 'text', 'desc' => __('This value determines the delay to which the animation starts once it\'s visible on the screen.', 'yit'), 'std' => '0' ) ) ), /*================= PARALLAX ================*/ 'parallax' => array( 'title' => __( 'Parallax effect', 'yit' ), 'description' => __( 'Create a fancy full-width parallax effect', 'yit' ), 'tab' => 'shortcodes', 'has_content' => true, 'in_visual_composer' => true, 'create' => true, 'attributes' => array( 'height' => array( 'title' => __( 'Container height', 'yit' ), 'type' => 'number', 'std' => 300 ), 'image' => array( 'title' => __( 'Background Image URL', 'yit' ), 'type' => 'text', 'std' => '' ), 'valign' => array( 'title' => __( 'Vertical Align', 'yit' ), 'type' => 'select', 'options' => array( 'top' => __( 'Top', 'yit' ), 'center' => __( 'Center', 'yit' ), 'bottom' => __( 'Bottom', 'yit' ), ), 'std' => 'center' ), 'halign' => array( 'title' => __( 'Horizontal Align', 'yit' ), 'type' => 'select', 'options' => array( 'left' => __( 'Left', 'yit' ), 'center' => __( 'Center', 'yit' ), 'right' => __( 'Right', 'yit' ), ), 'std' => 'center' ), 'font_p' => array( 'title' => __( 'Paragraph Font Size', 'yit' ), 'type' => 'number', 'std' => 24 ), 'color' => array( 'title' => __( 'Content Text Color', 'yit' ), 'type' => 'colorpicker', 'std' => '#ffffff' ), 'overlay_opacity' => array( 'title' => __( 'Overlay', 'yit' ), 'description' => __( 'Set an opacity of overlay (0-100)', 'yit' ), 'type' => 'number', 'std' => '0' ), 'border_bottom' => array( 'title' => __( 'Border Bottom', 'yit' ), 'description' => __( 'Set a size for border bottom (0-10)', 'yit' ), 'type' => 'number', 'min' => 0, 'max' => 10, 'std' => '0' ), 'effect' => array( 'title' => __( 'Effect', 'yit' ), 'type' => 'select', 'options' => array( 'fadeIn' => __( 'fadeIn', 'yit' ), 'fadeInUp' => __( 'fadeInUp', 'yit' ), 'fadeInDown' => __( 'fadeInDown', 'yit' ), 'fadeInLeft' => __( 'fadeInLeft', 'yit' ), 'fadeInRight' => __( 'fadeInRight', 'yit' ), 'fadeInUpBig' => __( 'fadeInUpBig', 'yit' ), 'fadeInDownBig' => __( 'fadeInDownBig', 'yit' ), 'fadeInLeftBig' => __( 'fadeInLeftBig', 'yit' ), 'fadeInRightBig' => __( 'fadeInRightBig', 'yit' ), 'bounceIn' => __( 'bounceIn', 'yit' ), 'bounceInDown' => __( 'bounceInDown', 'yit' ), 'bounceInUp' => __( 'bounceInUp', 'yit' ), 'bounceInLeft' => __( 'bounceInLeft', 'yit' ), 'bounceInRight' => __( 'bounceInRight', 'yit' ), 'rotateIn' => __( 'rotateIn', 'yit' ), 'rotateInDownLeft' => __( 'rotateInDownLeft', 'yit' ), 'rotateInDownRight' => __( 'rotateInDownRight', 'yit' ), 'rotateInUpLeft' => __( 'rotateInUpLeft', 'yit' ), 'rotateInUpRight' => __( 'rotateInUpRight', 'yit' ), 'lightSpeedIn' => __( 'lightSpeedIn', 'yit' ), 'hinge' => __( 'hinge', 'yit' ), 'rollIn' => __( 'rollIn', 'yit' ), ), 'std' => 'fadeIn' ), 'video_upload_mp4' => array( 'title' => __( 'Video Mp4', 'yit' ), 'type' => 'text', 'std' => '' ), 'video_upload_ogg' => array( 'title' => __( 'Video Ogg', 'yit' ), 'type' => 'text', 'std' => '' ), 'video_upload_webm' => array( 'title' => __( 'Video Webm', 'yit' ), 'type' => 'text', 'std' => '' ), 'video_button' => array( 'title' => __( 'Add a button', 'yit' ), 'description' => __( 'Add a button to see a video in a lightbox', 'yit' ), 'type' => 'checkbox', 'std' => 'no' ), 'video_button_style' => array( 'title' => __( 'Video button style', 'yit' ), 'description' => __( 'Choose a style for video button', 'yit' ), 'type' => 'select', 'options' => yit_button_style(), 'std' => 'ghost' ), 'video_url' => array( 'title' => __( 'Video URL', 'yit' ), 'description' => __( 'Paste the url of the video that will be opened in the lightbox', 'yit' ), 'type' => 'text', 'std' => '' ), 'label_button_video' => array( 'title' => __( 'Button Label', 'yit' ), 'description' => __( 'Add the label of the button', 'yit' ), 'type' => 'text', 'std' => '' ) ) ), /* === CONTACT INFO === */ 'contact_info' => array( 'title' => __('Contact info', 'yit' ), 'description' => __('Show a contact info', 'yit' ), 'tab' => 'shortcodes', 'in_visual_composer' => true, 'has_content' => false, 'attributes' => array( 'title' => array( 'title' => __('Title', 'yit'), 'type' => 'text', 'std' => '' ), 'subtitle' => array( 'title' => __('Subtitle', 'yit'), 'type' => 'text', 'std' => '' ), 'address_title' => array( 'title' => __('Address Title', 'yit'), 'type' => 'text', 'std' => '' ), 'address' => array( 'title' => __('Address', 'yit'), 'type' => 'text', 'std' => '' ), 'address_icon' => array( 'title' => __('Address icon', 'yit'), 'type' => 'text', 'std' => '' ), 'phone_title' => array( 'title' => __('Phone Title', 'yit'), 'type' => 'text', 'std' => '' ), 'phone' => array( 'title' => __('Phone', 'yit'), 'type' => 'text', 'std' => '' ), 'phone_icon' => array( 'title' => __('Phone icon', 'yit'), 'type' => 'text', 'std' => '' ), 'mobile_title' => array( 'title' => __('Mobile Title', 'yit'), 'type' => 'text', 'std' => '' ), 'mobile' => array( 'title' => __('Mobile', 'yit'), 'type' => 'text', 'std' => '' ), 'mobile_icon' => array( 'title' => __('Mobile icon', 'yit'), 'type' => 'text', 'std' => '' ), 'fax_title' => array( 'title' => __('Fax Title', 'yit'), 'type' => 'text', 'std' => '' ), 'fax' => array( 'title' => __('Fax', 'yit'), 'type' => 'text', 'std' => '' ), 'fax_icon' => array( 'title' => __('Fax icon', 'yit'), 'type' => 'text', 'std' => '' ), 'email_title' => array( 'title' => __('E-mail Title', 'yit'), 'type' => 'text', 'std' => '' ), 'email' => array( 'title' => __('E-mail text', 'yit'), 'type' => 'text', 'std' => '' ), 'email_icon' => array( 'title' => __('E-mail icon', 'yit'), 'type' => 'text', 'std' => '' ), 'email_link' => array( 'title' => __('E-mail link', 'yit'), 'type' => 'text', 'std' => '' ), 'animate' => array( 'title' => __('Animation', 'yit'), 'type' => 'select', 'options' => $animate, 'std' => '' ), 'animation_delay' => array( 'title' => __('Animation Delay', 'yit'), 'type' => 'text', 'desc' => __('This value determines the delay to which the animation starts once it\'s visible on the screen.', 'yit'), 'std' => '0' ) ) ), /* === GOOGLE MAPS === */ 'googlemap' => array( 'title' => __( 'Google Maps', 'yit' ), 'description' => __( 'Print the google map box', 'yit' ), 'tab' => 'shortcodes', 'in_visual_composer' => true, 'has_content' => false, 'attributes' => array( 'full_width' => array( 'title' => __( 'Full Width', 'yit' ), 'type' => "checkbox", 'std' => 'yes' ), 'width' => array( 'title' => __( 'Width', 'yit' ), 'type' => 'number', 'std' => '', 'deps' => array( 'ids' => 'full_width', 'values' => '0' ) ), 'height' => array( 'title' => __( 'Height', 'yit' ), 'type' => 'number', 'std' => '' ), 'src' => array( 'title' => __( 'URL', 'yit' ), 'type' => 'text', 'std' => '' ), 'logo' => array( 'title' => __( 'Logo', 'yit' ), 'type' => 'text', 'std' => '' ), 'address' => array( 'title' => __( 'Address', 'yit' ), 'type' => 'text', 'std' => '' ), 'info' => array( 'title' => __( 'Info', 'yit' ), 'type' => 'text', 'std' => '' ), 'animate' => array( 'title' => __( 'Animation', 'yit' ), 'type' => 'select', 'options' => $animate, 'std' => '' ), 'animation_delay' => array( 'title' => __( 'Animation Delay', 'yit' ), 'type' => 'text', 'desc' => __( 'This value determines the delay to which the animation starts once it\'s visible on the screen.', 'yit' ), 'std' => '0' ) ) ), /*================= BLOG SECTION =================*/ 'blog_section' => array( 'title' => __( 'Blog', 'yit' ), 'description' => __( 'Print a blog section', 'yit' ), 'tab' => 'section', 'has_content' => false, 'in_visual_composer' => true, 'create' => true, 'attributes' => array( 'nitems' => array( 'title' => __( 'Number of items', 'yit' ), 'description' => __( '-1 to show all elements', 'yit' ), 'type' => 'number', 'min' => - 1, 'max' => 99, 'std' => - 1 ), 'ncolumns' => array( 'title' => __( 'Number of columns', 'yit' ), 'description' => __( 'Select number of columns to show', 'yit' ), 'type' => 'select', 'options' => array( 1 => 'One Column', 2 => 'Two Columns', 3 => 'Three Columns' ), 'std' => 1 ), 'enable_thumbnails' => array( 'title' => __( 'Show Thumbnails', 'yit' ), 'type' => 'checkbox', 'std' => 'yes' ), 'enable_date' => array( 'title' => __( 'Show Date', 'yit' ), 'type' => 'checkbox', 'std' => 'yes' ), 'enable_title' => array( 'title' => __( 'Show Title', 'yit' ), 'type' => 'checkbox', 'std' => 'yes' ), 'enable_author' => array( 'title' => __( 'Show Author', 'yit' ), 'type' => 'checkbox', 'std' => 'yes' ), 'enable_comments' => array( 'title' => __( 'Show Comments', 'yit' ), 'type' => 'checkbox', 'std' => 'yes' ) ) ), /* === TEASER === */ 'teaser' => array( 'title' => __( 'Teaser', 'yit' ), 'description' => __( 'Create a banner with an image, a link and text.', 'yit' ), 'tab' => 'shortcode', 'has_content' => false, 'multiple' => false, 'unlimited' => false, 'in_visual_composer' => false, 'hide' => true, 'attributes' => array( 'title' => array( 'title' => __( 'Title', 'yit' ), 'type' => 'text', 'std' => '' ), 'subtitle' => array( 'title' => __( 'Subtitle', 'yit' ), 'type' => 'text', 'std' => '' ), 'image' => array( 'title' => __( 'Image URL', 'yit' ), 'type' => 'text', 'std' => '' ), 'link' => array( 'title' => __( 'Link', 'yit' ), 'type' => 'text', 'std' => '' ), 'button' => array( 'title' => __( 'Label button', 'yit' ), 'type' => 'text', 'std' => '' ), 'slogan_position' => array( 'title' => __( 'Slogan Position', 'yit' ), 'type' => 'select', 'options' => array( 'top' => __( 'Top', 'yit' ), 'center' => __( 'Center', 'yit' ), 'bottom' => __( 'Bottom', 'yit' ), ), 'std' => '' ), 'animate' => array( 'title' => __( 'Animation', 'yit' ), 'type' => 'select', 'options' => $animate, 'std' => '' ), 'animation_delay' => array( 'title' => __( 'Animation Delay', 'yit' ), 'type' => 'text', 'desc' => __( 'This value determines the delay to which the animation starts once it\'s visible on the screen.', 'yit' ), 'std' => '0' ) ) ), /* === RECENT POST === */ 'recentpost' => array( 'title' => __( 'Recent post box', 'yit' ), 'description' => __( 'Shows last post of a specific category', 'yit' ), 'tab' => 'shortcodes', 'has_content' => false, 'in_visual_composer' => true, 'attributes' => array( 'items' => array( 'title' => __( 'N. of items', 'yit' ), 'type' => 'number', 'std' => '3' ), 'cat_name' => array( 'title' => __( 'Category', 'yit' ), 'type' => 'select', // list of all categories 'multiple' => true, 'options' => $categories, 'std' => serialize( array() ) ), 'excerpt' => array( 'title' => __( 'Show Excerpt', 'yit' ), 'type' => 'checkbox', // yes|no 'std' => 'no' ), 'excerpt_length' => array( 'title' => __( 'Limit words', 'yit' ), 'type' => 'number', 'std' => '20', 'deps' => array( 'ids' => 'excerpt', 'values' => '1' ) ), 'readmore' => array( 'title' => __( 'More text', 'yit' ), 'type' => 'text', 'std' => '', 'deps' => array( 'ids' => 'excerpt', 'values' => '1' ) ), 'showthumb' => array( 'title' => __( 'Show Thumbnail', 'yit' ), 'type' => 'checkbox', // yes|no 'std' => 'no' ), 'date' => array( 'title' => __( 'Show Date', 'yit' ), 'type' => 'checkbox', // yes|no 'std' => 'true', 'deps' => array( 'ids' => 'showthumb', 'values' => '1' ) ), 'show_categories' => array( 'title' => __( 'Show Categories', 'yit' ), 'type' => 'checkbox', // yes|no 'std' => 'true' ), 'show_tags' => array( 'title' => __( 'Show Tags', 'yit' ), 'type' => 'checkbox', // yes|no 'std' => 'true' ), 'author' => array( 'title' => __( 'Show Author', 'yit' ), 'type' => 'checkbox', // yes|no 'std' => 'no' ), 'comments' => array( 'title' => __( 'Show Comments', 'yit' ), 'type' => 'checkbox', // yes|no 'std' => 'no' ), 'animate' => array( 'title' => __( 'Animation', 'yit' ), 'type' => 'select', 'options' => $animate, 'std' => '' ), 'animation_delay' => array( 'title' => __( 'Animation Delay', 'yit' ), 'type' => 'text', 'desc' => __( 'This value determines the delay to which the animation starts once it\'s visible on the screen.', 'yit' ), 'std' => '0' ), 'popular' => array( 'title' => '', 'type' => 'checkbox', 'std' => '0', 'hide' => true ) ) ), /* === POPULAR POST === */ 'popularpost' => array( 'title' => __('Popular post box', 'yit' ), 'description' => __('Shows popular posts', 'yit' ), 'tab' => 'shortcodes', 'has_content' => false, 'in_visual_composer' => true, 'attributes' => array( 'items' => array( 'title' => __('N. of items', 'yit'), 'type' => 'number', 'std' => '3' ), 'cat_name' => array( 'title' => __('Category', 'yit'), 'type' => 'select', // list of all categories 'multiple' => true, 'options' => $categories, 'std' => serialize( array() ) ), 'excerpt' => array( 'title' => __( 'Show Excerpt', 'yit' ), 'type' => 'checkbox', // yes|no 'std' => 'no' ), 'excerpt_length' => array( 'title' => __('Limit words', 'yit'), 'type' => 'number', 'std' => '20', 'deps' => array( 'ids' => 'excerpt', 'values' => '1' ) ), 'readmore' => array( 'title' => __('More text', 'yit'), 'type' => 'text', 'std' => 'Read more...', 'deps' => array( 'ids' => 'excerpt', 'values' => '1' ) ), 'showthumb' => array( 'title' => __('Thumbnail', 'yit'), 'type' => 'checkbox', // yes|no 'std' => 'no' ), 'date' => array( 'title' => __( 'Show Date', 'yit' ), 'type' => 'checkbox', // yes|no 'std' => 'no', 'deps' => array( 'ids' => 'showthumb', 'values' => '1' ) ), 'author' => array( 'title' => __( 'Show Author', 'yit' ), 'type' => 'checkbox', // yes|no 'std' => 'no' ), 'comments' => array( 'title' => __( 'Show Comments', 'yit' ), 'type' => 'checkbox', // yes|no 'std' => 'no' ), 'animate' => array( 'title' => __('Animation', 'yit'), 'type' => 'select', 'options' => $animate, 'std' => '' ), 'animation_delay' => array( 'title' => __('Animation Delay', 'yit'), 'type' => 'text', 'desc' => __('This value determines the delay to which the animation starts once it\'s visible on the screen.', 'yit'), 'std' => '0' ) ) ), /*================= SEPARATOR ================*/ 'separator' => array( 'title' => __( 'Separator', 'yit' ), 'description' => __( 'Print a separator line', 'yit' ), 'tab' => 'shortcodes', 'has_content' => false, 'create' => true, 'in_visual_composer' => true, 'attributes' => array( 'style' => array( 'title' => __( 'Separator style', 'yit' ), 'type' => 'select', 'options' => array( 'single' => __( 'Single line', 'yit' ), 'double' => __( 'Double line', 'yit' ), 'dotted' => __( 'Dotted line', 'yit' ), 'dashed' => __( 'Dashed line', 'yit' ) ), 'std' => 'single' ), 'color' => array( 'title' => __( 'Separator color', 'yit' ), 'type' => 'colorpicker', 'std' => '#cdcdcd' ), 'margin_top' => array( 'title' => __( 'Margin top', 'yit' ), 'type' => 'number', 'min' => 0, 'max' => 999, 'std' => 40 ), 'margin_bottom' => array( 'title' => __( 'Margin bottom', 'yit' ), 'type' => 'number', 'min' => 0, 'max' => 999, 'std' => 40 ) ) ), /* === SHARE === */ 'share' => array( 'title' => __( 'Share', 'yit' ), 'description' => __( 'Print share buttons', 'yit' ), 'has_content' => false, 'in_visual_composer' => true, 'tab' => 'shortcodes', 'attributes' => array( 'icon_source' => array( 'title' => __( 'Icon type', 'yit' ), 'type' => 'select', 'options' => array( 'theme-icon' => __( 'Theme Icon', 'yit' ), 'custom' => __( 'Custom Icon', 'yit' ) ), 'std' => 'theme-icon' ), 'icon_theme' => array( 'title' => __( 'Icon', 'yit' ), 'type' => 'select-icon', // home|file|time|ecc 'options' => $awesome_icons, 'std' => '', 'deps' => array( 'ids' => 'icon_source', 'values' => 'theme-icon' ) ), 'icon_url' => array( 'title' => __( 'Icon URL', 'yit' ), 'type' => 'text', 'std' => '', 'deps' => array( 'ids' => 'icon_source', 'values' => 'custom' ) ), 'title' => array( 'title' => __( 'Title', 'yit' ), 'type' => 'text', 'std' => '' ), 'socials' => array( 'title' => __( 'Socials', 'yit' ), 'type' => 'select', 'multiple' => true, 'options' => array( 'facebook' => __( 'Facebook', 'yit' ), 'twitter' => __( 'Twitter', 'yit' ), 'google' => __( 'Google+', 'yit' ), 'pinterest' => __( 'Pinterest', 'yit' ) ), 'std' => serialize( array() ) //'std' => 'facebook, twitter, google, pinterest, bookmark' ), 'class' => array( 'title' => __( 'CSS Class', 'yit' ), 'type' => 'text', 'std' => '' ), 'size' => array( 'title' => __( 'Size', 'yit' ), 'type' => 'select', // small| 'options' => array( 'small' => __( 'Small', 'yit' ), '' => __( 'Normal', 'yit' ) ), 'std' => '' ), 'icon_type' => array( 'title' => __( 'Icon Type', 'yit' ), 'type' => 'select', 'options' => array( 'icon' => __( 'Icon', 'yit' ), 'text' => __( 'Text', 'yit' ) ), 'std' => 'icon', ), 'show_in' => array( 'title' => __( 'Show socials in cloud', 'yit' ), 'type' => 'select', // yes|no 'options' => array( 'modal' => __( 'Modal box', 'yit' ), 'dropdown' => __( 'Dropdown List', 'yit' ), 'inline' => __( 'Inline List', 'yit' ), ), 'std' => 'inline' ) ) ), /* === BUTTON === */ 'button' => array( 'title' => __( 'Button', 'yit' ), 'description' => __( 'Show a simple custom button', 'yit' ), 'tab' => 'shortcodes', 'has_content' => true, 'in_visual_composer' => true, 'attributes' => array( 'href' => array( 'title' => __( 'URL', 'yit' ), 'type' => 'text', 'std' => '#' ), 'target' => array( 'title' => __( 'Target', 'yit' ), 'type' => 'select', 'options' => array( '' => __( 'Default', 'yit' ), '_blank' => __( 'Blank', 'yit' ), '_parent' => __( 'Parent', 'yit' ), '_top' => __( 'Top', 'yit' ) ), 'std' => '' ), 'color' => array( 'title' => __( 'Color', 'yit' ), 'description' => __( 'You can find the buttons list', 'yit' ), 'type' => 'select', // btn-view-over-the-town-1|btn-the-bizzniss-1|btn-french-1|ecc 'options' => apply_filters( 'yit_button_style', '' ), //apply_filters( 'yit_button_style' , $button_style ), 'std' => 'flat' ), 'dimension' => array( 'title' => __( 'Width', 'yit' ), 'type' => 'select', // extra large!large|medium|small 'options' => array( 'extra-large' => __( 'Extra Large', 'yit' ), 'large' => __( 'Large', 'yit' ), 'normal' => __( 'Medium', 'yit' ), 'small' => __( 'Small', 'yit' ) ), 'std' => 'normal', ), 'icon' => array( 'title' => __( 'Icon', 'yit' ), 'type' => 'select-icon', // home|file|time|ecc 'options' => $awesome_icons_with_null, 'std' => '' ), 'icon_size' => array( 'title' => __( 'Icon size', 'yit' ), 'type' => 'number', 'std' => '12' ), 'animation' => array( 'title' => __( 'Icon Animation', 'yit' ), 'type' => 'select', 'options' => array( '' => __( 'None', 'yit' ), 'RtL' => __( 'Right to Left', 'yit' ), 'LtR' => __( 'Left to Right', 'yit' ), 'CtL' => __( 'Center to Left', 'yit' ), 'CtR' => __( 'Center to Right', 'yit' ), 'UtC' => __( 'Up to Center', 'yit' ), 'LtC' => __( 'Left to Center', 'yit' ), 'RtC' => __( 'Right to Center', 'yit' ), ), 'std' => '' ), 'animate' => array( 'title' => __( 'Animation', 'yit' ), 'type' => 'select', 'options' => $animate, 'std' => '' ), 'animation_delay' => array( 'title' => __( 'Animation Delay', 'yit' ), 'type' => 'text', 'desc' => __( 'This value determines the delay to which the animation starts once it\'s visible on the screen.', 'yit' ), 'std' => '0' ), 'class' => array( 'title' => __( 'CSS class', 'yit' ), 'type' => 'text', 'std' => '' ) ), ) ); if ( function_exists( 'YIT_Team' ) ) { $theme_shortcodes['team_section'] = array( 'title' => __( 'Team', 'yit' ), 'description' => __( 'Adds team members', 'yit' ), 'tab' => 'section', 'create' => false, 'has_content' => false, 'in_visual_composer' => true, 'attributes' => array( 'team' => array( 'title' => __( 'Team', 'yit' ), 'type' => 'select', 'options' => YIT_Team()->get_teams(), 'std' => '' ), 'nitems' => array( 'title' => __( 'Number of member', 'yit' ), 'type' => 'number', 'min' => - 1, 'max' => 99, 'std' => - 1 ), 'items_per_row' => array( 'title' => __( 'Members per row', 'yit' ), 'type' => 'select', 'options' => array( '3' => __( '3 items', 'yit' ), '4' => __( '4 items', 'yit' ), ), 'std' => '4' ), 'show_role' => array( 'title' => __( 'Show role', 'yit' ), 'type' => 'checkbox', 'std' => 'yes' ), 'show_social' => array( 'title' => __( 'Show social', 'yit' ), 'type' => 'checkbox', 'std' => 'yes' ) ) ); } if ( function_exists( 'WC' ) ) { $shop_shortcodes = array( /* === PRODUCTS CATEGORY === */ 'products_categories' => array( 'title' => __( 'Product Categories', 'yit' ), 'description' => __( 'List all (or limited) product categories', 'yit' ), 'tab' => 'shop', 'has_content' => false, 'in_visual_composer' => true, 'attributes' => array( 'category' => array( 'title' => __( 'Category', 'yit' ), 'type' => 'checklist', 'options' => yit_get_shop_categories( true ), 'std' => '' ), 'hide_empty' => array( 'title' => __( 'Hide empty', 'yit' ), 'type' => 'checkbox', 'std' => 'yes' ), 'show_counter' => array( 'title' => __( 'Show Counter', 'yit' ), 'type' => 'checkbox', 'std' => 'yes' ), 'orderby' => array( 'title' => __( 'Order by', 'yit' ), 'type' => 'select', 'options' => apply_filters( 'woocommerce_catalog_orderby', array( 'menu_order' => __( 'Default sorting', 'yit' ), 'title' => __( 'Sort alphabetically', 'yit' ), 'date' => __( 'Sort by most recent', 'yit' ), 'price' => __( 'Sort by price', 'yit' ) ) ), 'std' => 'menu_order' ), 'order' => array( 'title' => __( 'Sorting', 'yit' ), 'type' => 'select', 'options' => array( 'desc' => __( 'Descending', 'yit' ), 'asc' => __( 'Crescent', 'yit' ) ), 'std' => 'desc' ), 'animate' => array( 'title' => __( 'Animation', 'yit' ), 'type' => 'select', 'options' => $animate, 'std' => '' ), 'animation_delay' => array( 'title' => __( 'Animation Delay', 'yit' ), 'type' => 'text', 'desc' => __( 'This value determines the delay to which the animation starts once it\'s visible on the screen.', 'yit' ), 'std' => '0' ) ) ), /* === PRODUCTS SLIDER === */ 'products_slider' => array( 'title' => __( 'Products slider', 'yit' ), 'description' => __( 'Add a products slider', 'yit' ), 'tab' => 'shop', 'has_content' => false, 'in_visual_composer' => true, 'attributes' => array( 'title' => array( 'title' => __( 'Title', 'yit' ), 'type' => 'text', 'std' => '' ), 'per_page' => array( 'title' => __( 'Items', 'yit' ), 'type' => 'number', 'std' => '12' ), 'category' => array( 'title' => __( 'Category', 'yit' ), 'type' => 'select', 'options' => yit_get_shop_categories( false ), 'std' => serialize( array() ), 'multiple' => true ), 'layout' => array( 'title' => __( 'Layout', 'yit' ), 'type' => 'select', 'options' => array( 'default' => __( 'Default Layout', 'yit' ), 'zoom' => __( 'Zoom Layout', 'yit' ), 'flip' => __( 'Flip Layout', 'yit' ) ), 'std' => 'default' ), 'product_type' => array( 'title' => __( 'Product Type', 'yit' ), 'type' => 'select', 'options' => array( 'all' => __( 'All products', 'yit' ), 'featured' => __( 'Featured Products', 'yit' ), 'on_sale' => __( 'On Sale Products', 'yit' ) ), 'std' => 'all' ), 'orderby' => array( 'title' => __( 'Order by', 'yit' ), 'type' => 'select', 'options' => apply_filters( 'woocommerce_catalog_orderby', array( 'rand' => __( 'Random', 'yit' ), 'title' => __( 'Sort alphabetically', 'yit' ), 'date' => __( 'Sort by most recent', 'yit' ), 'price' => __( 'Sort by price', 'yit' ), 'sales' => __( 'Sort by sales', 'yit' ) ) ), 'std' => 'rand' ), 'order' => array( 'title' => __( 'Sorting', 'yit' ), 'type' => 'select', 'options' => array( 'desc' => __( 'Descending', 'yit' ), 'asc' => __( 'Crescent', 'yit' ) ), 'std' => 'desc' ), 'hide_free' => array( 'title' => __( 'Hide free products', 'yit' ), 'type' => 'checkbox', 'std' => 'no' ), 'show_hidden' => array( 'title' => __( 'Show hidden products', 'yit' ), 'type' => 'checkbox', 'std' => 'no' ), 'autoplay' => array( 'title' => __( 'Autoplay', 'yit' ), 'type' => 'select', 'options' => array( 'true' => __( 'True', 'yit' ), 'false' => __( 'False', 'yit' ), ), 'std' => 'true' ), 'animate' => array( 'title' => __( 'Animation', 'yit' ), 'type' => 'select', 'options' => $animate, 'std' => '' ), 'animation_delay' => array( 'title' => __( 'Animation Delay', 'yit' ), 'type' => 'text', 'desc' => __( 'This value determines the delay to which the animation starts once it\'s visible on the screen.', 'yit' ), 'std' => '0' ) ) ), /* === SHOW PRODUCTS === */ 'show_products' => ( ! function_exists( 'WC' ) ) ? false : array( 'title' => __( 'Show the products', 'yit' ), 'description' => __( 'Show the products', 'yit' ), 'tab' => 'shop', 'has_content' => false, 'in_visual_composer' => true, 'attributes' => array( 'per_page' => array( 'title' => __( 'N. of items', 'yit' ), 'description' => __( 'Show all with -1', 'yit' ), 'type' => 'number', 'std' => '8' ), 'layout' => array( 'title' => __( 'Layout', 'yit' ), 'type' => 'select', 'options' => array( 'default' => __( 'Default Layout', 'yit' ), 'zoom' => __( 'Zoom Layout', 'yit' ), 'flip' => __( 'Flip Layout', 'yit' ) ), 'std' => 'default' ), 'masonry' => array( 'title' => __( 'Enable Masonry', 'yit' ), 'desc' => __( 'Enable masonry style.', 'yit' ), 'type' => 'checkbox', 'std' => 'no' ), 'category' => array( 'title' => __( 'Category', 'yit' ), 'type' => 'select', 'multiple' => true, 'options' => yit_get_shop_categories( false ), 'std' => serialize( array() ) ), 'show' => array( 'title' => __( 'Show', 'yit' ), 'type' => 'select', 'options' => array( 'all' => __( 'All Products', 'yit' ), 'featured' => __( 'Featured Products', 'yit' ), 'on_sale' => __( 'On Sale Products', 'yit' ), ), 'std' => 'all' ), 'orderby' => array( 'title' => __( 'Order by', 'yit' ), 'type' => 'select', 'options' => apply_filters( 'woocommerce_catalog_orderby', array( 'rand' => __( 'Random', 'yit' ), 'title' => __( 'Sort alphabetically', 'yit' ), 'date' => __( 'Sort by most recent', 'yit' ), 'price' => __( 'Sort by price', 'yit' ), 'sales' => __( 'Sort by sales', 'yit' ) ) ), 'std' => 'rand' ), 'order' => array( 'title' => __( 'Sorting', 'yit' ), 'type' => 'select', 'options' => array( 'desc' => __( 'Descending', 'yit' ), 'asc' => __( 'Crescent', 'yit' ) ), 'std' => 'desc' ), 'hide_free' => array( 'title' => __( 'Hide free products', 'yit' ), 'type' => 'checkbox', 'std' => 'no' ), 'show_hidden' => array( 'title' => __( 'Show hidden products', 'yit' ), 'type' => 'checkbox', 'std' => 'no' ), 'animate' => array( 'title' => __( 'Animation', 'yit' ), 'type' => 'select', 'options' => $animate, 'std' => '' ), 'animation_delay' => array( 'title' => __( 'Animation Delay', 'yit' ), 'type' => 'text', 'desc' => __( 'This value determines the delay to which the animation starts once it\'s visible on the screen.', 'yit' ), 'std' => '0' ) ) ), /* === PRODUCTS CATEGORY SLIDER === */ 'products_categories_slider' => array( 'title' => __('Categories slider', 'yit'), 'description' => __('List all (or limited) product categories', 'yit'), 'tab' => 'shop', 'has_content' => false, 'in_visual_composer' => true, 'attributes' => array( 'title' => array( 'title' => __( 'Title', 'yit' ), 'type' => 'text', 'std' => '' ), 'category' => array( 'title' => __('Category', 'yit'), 'type' => 'checklist', 'options' => $shop_categories_id, 'std' => '' ), 'show_counter' => array( 'title' => __('Show Counter', 'yit'), 'type' => 'checkbox', 'std' => 'yes' ), 'hide_empty' => array( 'title' => __('Hide empty', 'yit'), 'type' => 'checkbox', 'std' => 'yes' ), 'orderby' => array( 'title' => __( 'Order by', 'yit' ), 'type' => 'select', 'options' => apply_filters( 'woocommerce_catalog_orderby', array( 'menu_order' => __( 'Default sorting', 'yit' ), 'title' => __( 'Sort alphabetically', 'yit' ), 'count' => __( 'Sort by products count', 'yit' ) ) ), 'std' => 'menu_order' ), 'order' => array( 'title' => __('Sorting', 'yit'), 'type' => 'select', 'options' => array( 'desc' => __('Descending', 'yit'), 'asc' => __('Crescent', 'yit') ), 'std' => 'desc' ), 'animate' => array( 'title' => __('Animation', 'yit'), 'type' => 'select', 'options' => $animate, 'std' => '' ), 'animation_delay' => array( 'title' => __('Animation Delay', 'yit'), 'type' => 'text', 'desc' => __('This value determines the delay to which the animation starts once it\'s visible on the screen.', 'yit'), 'std' => '0' ), 'autoplay' => array( 'title' => __('Autoplay', 'yit'), 'type' => 'select', 'options' => array( 'true' => __('True', 'yit'), 'false' => __('False', 'yit'), ), 'std' => 'true' ) ) ), ); } return ! empty( $shop_shortcodes ) ? array_merge( $theme_shortcodes, $shop_shortcodes ) : $theme_shortcodes;
gpl-2.0
hardvain/mono-compiler
class/System/ReferenceSources/Win32Exception.cs
330
using System.Runtime.CompilerServices; namespace System.ComponentModel { partial class Win32Exception { [MethodImplAttribute (MethodImplOptions.InternalCall)] internal static extern string W32ErrorMessage (int error_code); private static string GetErrorMessage (int error) { return W32ErrorMessage (error); } } }
gpl-2.0
MPI-ExperimentGroup/ExperimentTemplate
registration/src/main/java/nl/mpi/tg/eg/frinex/rest/AudioDataRepository.java
3266
/* * Copyright (C) 2018 Max Planck Institute for Psycholinguistics, Nijmegen * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package nl.mpi.tg.eg.frinex.rest; import java.util.Date; import java.util.List; import java.util.UUID; import nl.mpi.tg.eg.frinex.model.AudioData; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.data.rest.core.annotation.RestResource; import org.springframework.transaction.annotation.Transactional; /** * @since Aug 13, 2018 4:34:41 PM (creation date) * @author Peter Withers <peter.withers@mpi.nl> */ @RepositoryRestResource(collectionResourceRel = "audiodata", path = "audiodata") public interface AudioDataRepository extends PagingAndSortingRepository<AudioData, Long> { @Override @RestResource(exported = false) public abstract <S extends AudioData> S save(S entity); @Override @RestResource(exported = false) public abstract void delete(AudioData entity); @Override @RestResource(exported = false) public void deleteAll(Iterable<? extends AudioData> arg0); @Override @RestResource(exported = false) public void deleteById(Long arg0); @Transactional @RestResource(exported = false) public void deleteByUserId(@Param("userId") String userId); public int countByUserId(@Param("userId") String userId); @Override @RestResource(exported = false) public <S extends AudioData> Iterable<S> saveAll(Iterable<S> arg0); @Override @RestResource(exported = false) public abstract void deleteAll(); @Override @RestResource(exported = false) public void deleteAllById(Iterable<? extends Long> ids); @Transactional @Query(value = "select distinct to_char(submitDate,'YYYY-MM-DD') as resultString from AudioData order by resultString asc") public List<String> findSubmitDateDistinctByOrderBySubmitDateAsc(); @Transactional List<AudioData> findAllBySubmitDateBetween(Date submitDateStart, Date submitDateEnd); @Transactional public List<AudioData> findByUserIdOrderBySubmitDateAsc(@Param("userId") String userId); @Transactional public List<AudioData> findBySubmitDateOrderBySubmitDateAsc(@Param("submitDate") String userId); @Transactional public List<AudioData> findByShortLivedTokenAndUserId(@Param("shortLivedToken") UUID shortLivedToken, @Param("userId") String userId); }
gpl-2.0
qoswork/opennmszh
opennms-webapp/src/main/java/org/opennms/web/controller/DownloadReportController.java
6331
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2009-2014 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.web.controller; import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.lf5.util.StreamUtils; import org.opennms.api.reporting.ReportFormat; import org.opennms.core.utils.BeanUtils; import org.opennms.core.utils.LogUtils; import org.opennms.core.utils.WebSecurityUtils; import org.opennms.netmgt.dao.ReportdConfigurationDao; import org.opennms.reporting.core.svclayer.ReportStoreService; import org.opennms.web.servlet.MissingParameterException; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; /** * <p>DownloadReportController class.</p> * * @author ranger * @version $Id: $ * @since 1.8.1 */ public class DownloadReportController extends AbstractController { private ReportStoreService m_reportStoreService; private ReportdConfigurationDao m_reportdConfigurationDao; /** {@inheritDoc} */ @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { String fileName = request.getParameter("fileName"); m_reportdConfigurationDao = BeanUtils.getBean("reportdContext", "reportdConfigDao", ReportdConfigurationDao.class); final File storageDirectory = new File(m_reportdConfigurationDao.getStorageDirectory()); if (fileName != null) { final File requestedFile = new File(fileName); if (!requestedFile.getParentFile().getCanonicalFile().equals(storageDirectory.getCanonicalFile())) { LogUtils.warnf(this, "User attempted to retrieve file %s but was restricted to %s", requestedFile, storageDirectory); throw new IllegalArgumentException("Cannot retrieve reports from outside Reportd storage directory"); } if (fileName.toLowerCase().endsWith(".pdf")) { response.setContentType("application/pdf;charset=UTF-8"); } if (fileName.toLowerCase().endsWith(".csv")) { response.setContentType("text/csv;charset=UTF-8"); } response.setHeader("Content-disposition", "inline; filename=" + fileName); response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "cache"); response.setHeader("Cache-Control", "must-revalidate"); StreamUtils.copy(new FileInputStream(new File(fileName)), response.getOutputStream()); return null; } String[] requiredParameters = new String[] { "locatorId", "format" }; for (String requiredParameter : requiredParameters) { if (request.getParameter(requiredParameter) == null) { throw new MissingParameterException(requiredParameter, requiredParameters); } } try { Integer reportCatalogEntryId = Integer.valueOf(WebSecurityUtils.safeParseInt(request.getParameter("locatorId"))); String requestFormat = new String(request.getParameter("format")); if ((ReportFormat.PDF == ReportFormat.valueOf(requestFormat)) || (ReportFormat.SVG == ReportFormat.valueOf(requestFormat)) ) { response.setContentType("application/pdf;charset=UTF-8"); response.setHeader("Content-disposition", "inline; filename=" + reportCatalogEntryId.toString() + ".pdf"); response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "cache"); response.setHeader("Cache-Control", "must-revalidate"); } if(ReportFormat.CSV == ReportFormat.valueOf(requestFormat)) { response.setContentType("text/csv;charset=UTF-8"); response.setHeader("Content-disposition", "inline; filename=" + reportCatalogEntryId.toString() + ".csv"); response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "cache"); response.setHeader("Cache-Control", "must-revalidate"); } m_reportStoreService.render( reportCatalogEntryId, ReportFormat.valueOf(requestFormat), (OutputStream) response.getOutputStream()); } catch (NumberFormatException e) { // TODO something useful here. } return null; } /** * <p>setReportStoreService</p> * * @param reportStoreService a {@link org.opennms.reporting.core.svclayer.ReportStoreService} object. */ public void setReportStoreService(ReportStoreService reportStoreService) { m_reportStoreService = reportStoreService; } }
gpl-2.0
iTTemple/html
wp-content/themes/invictus_2.6.2/doitmax_fw/includes/activation.inc.php
3632
<?php require_once('../../../../../wp-config.php'); @header('Content-Type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset')); ?> <style> body, td, textarea, input, select { line-height: 1.4em; color: #333; font-family: sans-serif; font-size: 13px; } a:link, a:visited { color: #21759B; text-decoration: none; } a:hover, a:active { color: #d54e21; } .max_style_alert { display: block; border-width: 1px; border-style: solid; padding: 1.25em; margin: 0; -moz-border-radius: 3px; -khtml-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; background-color: #FFFFE0; border: 1px solid #E6DB55; line-height: 1.35em; } .max_style_alert h4 { margin: 0 0 5px; padding: 0; } h1, h2, h3, h4, h5 { font-family: Georgia,"Times New Roman","Bitstream Charter",Times,serif; font-weight: normal; margin: 0; padding: 0; } h2 { font-size: 24px; padding: 10px 0 5px; } h3 { font-size: 19px; padding: 15px 0 0 } h4 { font-size: 16px; padding: 15px 0 10px; color: #555; } </style> <div style="padding: 10px 30px"> <img src="<?php echo get_template_directory_uri() . '/thumbnail.jpg'; ?>" align="left" alt="Invictus - A Premium Photographer Portfolio Theme by doitmax" width="80" height="80" style="margin: 10px 23px 0 0" /> <h2><?php _e('Theme successfully activated!', MAX_SHORTNAME) ?></h2> <p><?php _e('Thank you for purchasing and activating my theme. You are now ready to start working with this theme and setup some general things, upload photos and create an awesome website.', MAX_SHORTNAME) ?></p> <h3><?php _e('But stop, wait a second...', MAX_SHORTNAME) ?></h3> <p><?php _e('...before you start working, please take some time to follow us on <strong><a href="http://www.facebook.com/pages/doitmax/120695808006003" target="_blank">facebook</a></strong> or <strong><a href="http://twitter.com/#!/doitmax" target="_blank">Twitter</a></strong> to instantly receive notifications about updates, new items on themeforest.net or other important things.', MAX_SHORTNAME) ?></p> <h4><?php _e('Follow doitmax on facebook', MAX_SHORTNAME) ?></h4> <div id="fb-root"></div> <script> (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="fb-like-box" data-href="http://www.facebook.com/pages/doitmax/120695808006003" data-width="594" data-height="215" data-show-faces="true" data-stream="false" data-header="true"></div> <br />&nbsp; <h4>Follow doitmax on Twitter</h4> <p><a href="https://twitter.com/doitmax" class="twitter-follow-button">Follow @doitmax</a></p> <script src="//platform.twitter.com/widgets.js" type="text/javascript"></script> <br /> <div class="max_style_alert"><?php _e('If you need any help creating your website open the help file included in your downloaded ZIP package or check out our <a href="http://help.doitmax.de/invictus/" target="_blank">online documentation</a>. If you are expecting any problems setting up your theme, having trouble using any theme features, or have discovered a bug, head over to our <a href="http://support.doitmax.de/" target="_blank">Support Forum</a>. We will do our best to help and answer your request as soon as possible.', MAX_SHORTNAME) ?></div> <p style="text-align: right"><a href="#" onClick="window.parent.tb_remove();"><?php _e('Skip those social gimmicks &raquo;', MAX_SHORTNAME) ?></a></p> </div>
gpl-2.0
Kenishi/DroidNavi
android/AndroidTeleLog/src/com/aberdyne/droidnavi/PreferenceStore.java
2394
package com.aberdyne.droidnavi; import java.util.ArrayList; import java.util.Set; import java.util.TreeSet; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; public class PreferenceStore { private static PreferenceStore m_instance = null; private final String PREF_SERVER_LIST = "serverList"; private Activity m_parent = null; private PreferenceStore(Activity activity) { m_parent = activity; } static public PreferenceStore createPreferenceStore(Activity activity) { if(m_instance == null) { m_instance = new PreferenceStore(activity); } return m_instance; } /** * Add a new server IP to the stored preferences for later retrieval * @param serverIp A string to a valid IP address * @return True if everything went ok. False if something went wrong or if serverIp * was null. */ public synchronized boolean addServer(String serverIp) { if(serverIp == null) return false; // Get the current serverIps or create a new one if it doesn't exist SharedPreferences pref = m_parent.getPreferences(Context.MODE_PRIVATE); Set<String> set = pref.getStringSet(PREF_SERVER_LIST, null); set = (set == null) ? new TreeSet<String>() : set; try { set.add(serverIp); } catch (Exception e) { return false; } // Replace set SharedPreferences.Editor editor = pref.edit(); editor.putStringSet(PREF_SERVER_LIST, set); editor.commit(); return true; } /** * Remove the IP from the server list * @param serverIp A valid IP that should be on the list */ public synchronized void removeServer(String serverIp) { if(serverIp == null) return; SharedPreferences pref = m_parent.getPreferences(Context.MODE_PRIVATE); Set<String> set = pref.getStringSet(PREF_SERVER_LIST, null); if(set != null) { set.remove(serverIp); SharedPreferences.Editor editor = pref.edit(); editor.putStringSet(PREF_SERVER_LIST, set); editor.commit(); } } /** * Retrieve a copy of the currently stored server list * @return An array of string IPs */ public ArrayList<String> getServerList() { SharedPreferences pref = m_parent.getPreferences(Context.MODE_PRIVATE); Set<String> serverSet = pref.getStringSet(PREF_SERVER_LIST, null); if(serverSet == null) { return null; } ArrayList<String> list = new ArrayList<String>(serverSet); return list; } }
gpl-2.0
openjdk/jdk7u
jdk/src/share/classes/java/security/MessageDigest.java
22109
/* * Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.security; import java.util.*; import java.lang.*; import java.io.IOException; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.InputStream; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; import sun.security.util.Debug; /** * This MessageDigest class provides applications the functionality of a * message digest algorithm, such as SHA-1 or SHA-256. * Message digests are secure one-way hash functions that take arbitrary-sized * data and output a fixed-length hash value. * * <p>A MessageDigest object starts out initialized. The data is * processed through it using the {@link #update(byte) update} * methods. At any point {@link #reset() reset} can be called * to reset the digest. Once all the data to be updated has been * updated, one of the {@link #digest() digest} methods should * be called to complete the hash computation. * * <p>The {@code digest} method can be called once for a given number * of updates. After {@code digest} has been called, the MessageDigest * object is reset to its initialized state. * * <p>Implementations are free to implement the Cloneable interface. * Client applications can test cloneability by attempting cloning * and catching the CloneNotSupportedException: * * <pre>{@code * MessageDigest md = MessageDigest.getInstance("SHA-256"); * * try { * md.update(toChapter1); * MessageDigest tc1 = md.clone(); * byte[] toChapter1Digest = tc1.digest(); * md.update(toChapter2); * ...etc. * } catch (CloneNotSupportedException cnse) { * throw new DigestException("couldn't make digest of partial content"); * } * }</pre> * * <p>Note that if a given implementation is not cloneable, it is * still possible to compute intermediate digests by instantiating * several instances, if the number of digests is known in advance. * * <p>Note that this class is abstract and extends from * {@code MessageDigestSpi} for historical reasons. * Application developers should only take notice of the methods defined in * this {@code MessageDigest} class; all the methods in * the superclass are intended for cryptographic service providers who wish to * supply their own implementations of message digest algorithms. * * <p> Every implementation of the Java platform is required to support * the following standard {@code MessageDigest} algorithms: * <ul> * <li>{@code MD5}</li> * <li>{@code SHA-1}</li> * <li>{@code SHA-256}</li> * </ul> * These algorithms are described in the <a href= * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest"> * MessageDigest section</a> of the * Java Cryptography Architecture Standard Algorithm Name Documentation. * Consult the release documentation for your implementation to see if any * other algorithms are supported. * * @author Benjamin Renaud * * @see DigestInputStream * @see DigestOutputStream */ public abstract class MessageDigest extends MessageDigestSpi { private static final Debug pdebug = Debug.getInstance("provider", "Provider"); private static final boolean skipDebug = Debug.isOn("engine=") && !Debug.isOn("messagedigest"); private String algorithm; // The state of this digest private static final int INITIAL = 0; private static final int IN_PROGRESS = 1; private int state = INITIAL; // The provider private Provider provider; /** * Creates a message digest with the specified algorithm name. * * @param algorithm the standard name of the digest algorithm. * See the MessageDigest section in the <a href= * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest"> * Java Cryptography Architecture Standard Algorithm Name Documentation</a> * for information about standard algorithm names. */ protected MessageDigest(String algorithm) { this.algorithm = algorithm; } /** * Returns a MessageDigest object that implements the specified digest * algorithm. * * <p> This method traverses the list of registered security Providers, * starting with the most preferred Provider. * A new MessageDigest object encapsulating the * MessageDigestSpi implementation from the first * Provider that supports the specified algorithm is returned. * * <p> Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * * @param algorithm the name of the algorithm requested. * See the MessageDigest section in the <a href= * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest"> * Java Cryptography Architecture Standard Algorithm Name Documentation</a> * for information about standard algorithm names. * * @return a Message Digest object that implements the specified algorithm. * * @exception NoSuchAlgorithmException if no Provider supports a * MessageDigestSpi implementation for the * specified algorithm. * * @see Provider */ public static MessageDigest getInstance(String algorithm) throws NoSuchAlgorithmException { try { MessageDigest md; Object[] objs = Security.getImpl(algorithm, "MessageDigest", (String)null); if (objs[0] instanceof MessageDigest) { md = (MessageDigest)objs[0]; } else { md = new Delegate((MessageDigestSpi)objs[0], algorithm); } md.provider = (Provider)objs[1]; if (!skipDebug && pdebug != null) { pdebug.println("MessageDigest." + algorithm + " algorithm from: " + md.provider.getName()); } return md; } catch(NoSuchProviderException e) { throw new NoSuchAlgorithmException(algorithm + " not found"); } } /** * Returns a MessageDigest object that implements the specified digest * algorithm. * * <p> A new MessageDigest object encapsulating the * MessageDigestSpi implementation from the specified provider * is returned. The specified provider must be registered * in the security provider list. * * <p> Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * * @param algorithm the name of the algorithm requested. * See the MessageDigest section in the <a href= * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest"> * Java Cryptography Architecture Standard Algorithm Name Documentation</a> * for information about standard algorithm names. * * @param provider the name of the provider. * * @return a MessageDigest object that implements the specified algorithm. * * @exception NoSuchAlgorithmException if a MessageDigestSpi * implementation for the specified algorithm is not * available from the specified provider. * * @exception NoSuchProviderException if the specified provider is not * registered in the security provider list. * * @exception IllegalArgumentException if the provider name is null * or empty. * * @see Provider */ public static MessageDigest getInstance(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { if (provider == null || provider.length() == 0) throw new IllegalArgumentException("missing provider"); Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider); if (objs[0] instanceof MessageDigest) { MessageDigest md = (MessageDigest)objs[0]; md.provider = (Provider)objs[1]; return md; } else { MessageDigest delegate = new Delegate((MessageDigestSpi)objs[0], algorithm); delegate.provider = (Provider)objs[1]; return delegate; } } /** * Returns a MessageDigest object that implements the specified digest * algorithm. * * <p> A new MessageDigest object encapsulating the * MessageDigestSpi implementation from the specified Provider * object is returned. Note that the specified Provider object * does not have to be registered in the provider list. * * @param algorithm the name of the algorithm requested. * See the MessageDigest section in the <a href= * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest"> * Java Cryptography Architecture Standard Algorithm Name Documentation</a> * for information about standard algorithm names. * * @param provider the provider. * * @return a MessageDigest object that implements the specified algorithm. * * @exception NoSuchAlgorithmException if a MessageDigestSpi * implementation for the specified algorithm is not available * from the specified Provider object. * * @exception IllegalArgumentException if the specified provider is null. * * @see Provider * * @since 1.4 */ public static MessageDigest getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmException { if (provider == null) throw new IllegalArgumentException("missing provider"); Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider); if (objs[0] instanceof MessageDigest) { MessageDigest md = (MessageDigest)objs[0]; md.provider = (Provider)objs[1]; return md; } else { MessageDigest delegate = new Delegate((MessageDigestSpi)objs[0], algorithm); delegate.provider = (Provider)objs[1]; return delegate; } } /** * Returns the provider of this message digest object. * * @return the provider of this message digest object */ public final Provider getProvider() { return this.provider; } /** * Updates the digest using the specified byte. * * @param input the byte with which to update the digest. */ public void update(byte input) { engineUpdate(input); state = IN_PROGRESS; } /** * Updates the digest using the specified array of bytes, starting * at the specified offset. * * @param input the array of bytes. * * @param offset the offset to start from in the array of bytes. * * @param len the number of bytes to use, starting at * {@code offset}. */ public void update(byte[] input, int offset, int len) { if (input == null) { throw new IllegalArgumentException("No input buffer given"); } if (input.length - offset < len) { throw new IllegalArgumentException("Input buffer too short"); } engineUpdate(input, offset, len); state = IN_PROGRESS; } /** * Updates the digest using the specified array of bytes. * * @param input the array of bytes. */ public void update(byte[] input) { engineUpdate(input, 0, input.length); state = IN_PROGRESS; } /** * Update the digest using the specified ByteBuffer. The digest is * updated using the {@code input.remaining()} bytes starting * at {@code input.position()}. * Upon return, the buffer's position will be equal to its limit; * its limit will not have changed. * * @param input the ByteBuffer * @since 1.5 */ public final void update(ByteBuffer input) { if (input == null) { throw new NullPointerException(); } engineUpdate(input); state = IN_PROGRESS; } /** * Completes the hash computation by performing final operations * such as padding. The digest is reset after this call is made. * * @return the array of bytes for the resulting hash value. */ public byte[] digest() { /* Resetting is the responsibility of implementors. */ byte[] result = engineDigest(); state = INITIAL; return result; } /** * Completes the hash computation by performing final operations * such as padding. The digest is reset after this call is made. * * @param buf output buffer for the computed digest * * @param offset offset into the output buffer to begin storing the digest * * @param len number of bytes within buf allotted for the digest * * @return the number of bytes placed into {@code buf} * * @exception DigestException if an error occurs. */ public int digest(byte[] buf, int offset, int len) throws DigestException { if (buf == null) { throw new IllegalArgumentException("No output buffer given"); } if (buf.length - offset < len) { throw new IllegalArgumentException ("Output buffer too small for specified offset and length"); } int numBytes = engineDigest(buf, offset, len); state = INITIAL; return numBytes; } /** * Performs a final update on the digest using the specified array * of bytes, then completes the digest computation. That is, this * method first calls {@link #update(byte[]) update(input)}, * passing the <i>input</i> array to the {@code update} method, * then calls {@link #digest() digest()}. * * @param input the input to be updated before the digest is * completed. * * @return the array of bytes for the resulting hash value. */ public byte[] digest(byte[] input) { update(input); return digest(); } /** * Returns a string representation of this message digest object. */ public String toString() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream p = new PrintStream(baos); p.print(algorithm+" Message Digest from "+provider.getName()+", "); switch (state) { case INITIAL: p.print("<initialized>"); break; case IN_PROGRESS: p.print("<in progress>"); break; } p.println(); return (baos.toString()); } /** * Compares two digests for equality. Does a simple byte compare. * * @implNote * All bytes in {@code digesta} are examined to determine equality. * The calculation time depends only on the length of {@code digesta}. * It does not depend on the length of {@code digestb} or the contents * of {@code digesta} and {@code digestb}. * * @param digesta one of the digests to compare. * * @param digestb the other digest to compare. * * @return true if the digests are equal, false otherwise. */ public static boolean isEqual(byte[] digesta, byte[] digestb) { if (digesta == digestb) return true; if (digesta == null || digestb == null) { return false; } int lenA = digesta.length; int lenB = digestb.length; if (lenB == 0) { return lenA == 0; } int result = 0; result |= lenA - lenB; // time-constant comparison for (int i = 0; i < lenA; i++) { // If i >= lenB, indexB is 0; otherwise, i. int indexB = ((i - lenB) >>> 31) * i; result |= digesta[i] ^ digestb[indexB]; } return result == 0; } /** * Resets the digest for further use. */ public void reset() { engineReset(); state = INITIAL; } /** * Returns a string that identifies the algorithm, independent of * implementation details. The name should be a standard * Java Security name (such as "SHA-256"). * See the MessageDigest section in the <a href= * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest"> * Java Cryptography Architecture Standard Algorithm Name Documentation</a> * for information about standard algorithm names. * * @return the name of the algorithm */ public final String getAlgorithm() { return this.algorithm; } /** * Returns the length of the digest in bytes, or 0 if this operation is * not supported by the provider and the implementation is not cloneable. * * @return the digest length in bytes, or 0 if this operation is not * supported by the provider and the implementation is not cloneable. * * @since 1.2 */ public final int getDigestLength() { int digestLen = engineGetDigestLength(); if (digestLen == 0) { try { MessageDigest md = (MessageDigest)clone(); byte[] digest = md.digest(); return digest.length; } catch (CloneNotSupportedException e) { return digestLen; } } return digestLen; } /** * Returns a clone if the implementation is cloneable. * * @return a clone if the implementation is cloneable. * * @exception CloneNotSupportedException if this is called on an * implementation that does not support {@code Cloneable}. */ public Object clone() throws CloneNotSupportedException { if (this instanceof Cloneable) { return super.clone(); } else { throw new CloneNotSupportedException(); } } /* * The following class allows providers to extend from MessageDigestSpi * rather than from MessageDigest. It represents a MessageDigest with an * encapsulated, provider-supplied SPI object (of type MessageDigestSpi). * If the provider implementation is an instance of MessageDigestSpi, * the getInstance() methods above return an instance of this class, with * the SPI object encapsulated. * * Note: All SPI methods from the original MessageDigest class have been * moved up the hierarchy into a new class (MessageDigestSpi), which has * been interposed in the hierarchy between the API (MessageDigest) * and its original parent (Object). */ static class Delegate extends MessageDigest { // The provider implementation (delegate) private MessageDigestSpi digestSpi; // constructor public Delegate(MessageDigestSpi digestSpi, String algorithm) { super(algorithm); this.digestSpi = digestSpi; } /** * Returns a clone if the delegate is cloneable. * * @return a clone if the delegate is cloneable. * * @exception CloneNotSupportedException if this is called on a * delegate that does not support {@code Cloneable}. */ public Object clone() throws CloneNotSupportedException { if (digestSpi instanceof Cloneable) { MessageDigestSpi digestSpiClone = (MessageDigestSpi)digestSpi.clone(); // Because 'algorithm', 'provider', and 'state' are private // members of our supertype, we must perform a cast to // access them. MessageDigest that = new Delegate(digestSpiClone, ((MessageDigest)this).algorithm); that.provider = ((MessageDigest)this).provider; that.state = ((MessageDigest)this).state; return that; } else { throw new CloneNotSupportedException(); } } protected int engineGetDigestLength() { return digestSpi.engineGetDigestLength(); } protected void engineUpdate(byte input) { digestSpi.engineUpdate(input); } protected void engineUpdate(byte[] input, int offset, int len) { digestSpi.engineUpdate(input, offset, len); } protected void engineUpdate(ByteBuffer input) { digestSpi.engineUpdate(input); } protected byte[] engineDigest() { return digestSpi.engineDigest(); } protected int engineDigest(byte[] buf, int offset, int len) throws DigestException { return digestSpi.engineDigest(buf, offset, len); } protected void engineReset() { digestSpi.engineReset(); } } }
gpl-2.0
mivion/swisseph
src/callback.cc
385
#include "swisseph.h" using namespace v8; void HandleCallback (Nan::NAN_METHOD_ARGS_TYPE info, Local <Value> result) { if (info [info.Length () - 1]->IsFunction ()) { Local <Function> callback = Local <Function>::Cast (info [info.Length () - 1]); Local <Value> argv [1] = { result }; callback->Call(Nan::GetCurrentContext(),Nan::GetCurrentContext()->Global(), 1, argv); }; };
gpl-2.0
CarvingIT/science-problems
public_html/bulk_add_list.php
772
<?php include 'includes/php_header.php'; if($_POST['new_old'] == 'new'){ /* Create a new list And then add problems to the list */ $u->createList($_POST['new_list_name']); //Get the id of the list $list_id = $u->getUserListId($u->user_profile['username'], $_POST['new_list_name']); foreach($_POST['problem_id'] as $p_id){ $u->listAction($p_id, $list_id); } } else if($_POST['new_old'] == 'old'){ /* Get the list id Add problems to it */ foreach($_POST['problem_id'] as $p_id){ $u->listAction($p_id, $_POST['list']); } } // Finally, redirect user to the lists page header("location:/my_lists.php"); ?>
gpl-2.0
darkloveir/Skyfire-6.1.2-version
src/server/game/Achievements/AchievementMgr.cpp
139746
/* * Copyright (C) 2011-2014 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2014 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "AchievementMgr.h" #include "Battleground.h" #include "RatedMgr.h" #include "RatedInfo.h" #include "CellImpl.h" #include "Chat.h" #include "Common.h" #include "DatabaseEnv.h" #include "DBCEnums.h" #include "DBCStructure.h" #include "DisableMgr.h" #include "GameEventMgr.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "Guild.h" #include "GuildMgr.h" #include "InstanceScript.h" #include "Language.h" #include "Map.h" #include "MapManager.h" #include "ObjectMgr.h" #include "Player.h" #include "ReputationMgr.h" #include "ScriptMgr.h" #include "SpellMgr.h" #include "World.h" #include "WorldPacket.h" namespace Trinity { class AchievementChatBuilder { public: AchievementChatBuilder(Player const& player, ChatMsg msgtype, int32 textId, uint32 ach_id) : i_player(player), i_msgtype(msgtype), i_textId(textId), i_achievementId(ach_id) { } void operator()(WorldPacket& data, LocaleConstant loc_idx) { std::string text = sObjectMgr->GetTrinityString(i_textId, loc_idx); ChatHandler::BuildChatPacket(data, i_msgtype, LANG_UNIVERSAL, &i_player, &i_player, text, i_achievementId); } private: Player const& i_player; ChatMsg i_msgtype; int32 i_textId; uint32 i_achievementId; }; } // namespace Trinity bool AchievementCriteriaData::IsValid(CriteriaEntry const* criteria) { if (dataType >= MAX_ACHIEVEMENT_CRITERIA_DATA_TYPE) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` for criteria (Entry: %u) has wrong data type (%u), ignored.", criteria->ID, dataType); return false; } switch (criteria->type) { case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE: case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE: case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG: case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: // only hardcoded list case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL: case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA: case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE: case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL: case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL: case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE: case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2: case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET: case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2: case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT: case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT: case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE: case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST: // only Children's Week achievements case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM: // only Children's Week achievements case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS: case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL: break; default: if (dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` has data for non-supported criteria type (Entry: %u Type: %u), ignored.", criteria->ID, criteria->type); return false; } break; } switch (dataType) { case ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE: case ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT: return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_CREATURE: if (!creature.id || !sObjectMgr->GetCreatureTemplate(creature.id)) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_CREATURE (%u) has non-existing creature id in value1 (%u), ignored.", criteria->ID, criteria->type, dataType, creature.id); return false; } return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE: if (!classRace.class_id && !classRace.race_id) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) must not have 0 in either value field, ignored.", criteria->ID, criteria->type, dataType); return false; } if (classRace.class_id && ((1 << (classRace.class_id-1)) & CLASSMASK_ALL_PLAYABLE) == 0) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) has non-existing class in value1 (%u), ignored.", criteria->ID, criteria->type, dataType, classRace.class_id); return false; } if (classRace.race_id && ((1 << (classRace.race_id-1)) & RACEMASK_ALL_PLAYABLE) == 0) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) has non-existing race in value2 (%u), ignored.", criteria->ID, criteria->type, dataType, classRace.race_id); return false; } return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_LESS_HEALTH: if (health.percent < 1 || health.percent > 100) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_PLAYER_LESS_HEALTH (%u) has wrong percent value in value1 (%u), ignored.", criteria->ID, criteria->type, dataType, health.percent); return false; } return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA: case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA: { SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(aura.spell_id); if (!spellEntry) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell id in value1 (%u), ignored.", criteria->ID, criteria->type, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id); return false; } if (aura.effect_idx >= 3) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell effect index in value2 (%u), ignored.", criteria->ID, criteria->type, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.effect_idx); return false; } if (!spellEntry->Effects[aura.effect_idx].ApplyAuraName) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has non-aura spell effect (ID: %u Effect: %u), ignores.", criteria->ID, criteria->type, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id, aura.effect_idx); return false; } return true; } case ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE: if (value.compType >= COMP_TYPE_MAX) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE (%u) has wrong ComparisionType in value2 (%u), ignored.", criteria->ID, criteria->type, dataType, value.compType); return false; } return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL: if (level.minlevel > STRONG_MAX_LEVEL) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL (%u) has wrong minlevel in value1 (%u), ignored.", criteria->ID, criteria->type, dataType, level.minlevel); return false; } return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER: if (gender.gender > GENDER_NONE) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER (%u) has wrong gender in value1 (%u), ignored.", criteria->ID, criteria->type, dataType, gender.gender); return false; } return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT: if (!ScriptId) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT (%u) does not have ScriptName set, ignored.", criteria->ID, criteria->type, dataType); return false; } return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT: if (map_players.maxcount <= 0) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT (%u) has wrong max players count in value1 (%u), ignored.", criteria->ID, criteria->type, dataType, map_players.maxcount); return false; } return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM: if (team.team != ALLIANCE && team.team != HORDE) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM (%u) has unknown team in value1 (%u), ignored.", criteria->ID, criteria->type, dataType, team.team); return false; } return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK: if (drunk.state >= MAX_DRUNKEN) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK (%u) has unknown drunken state in value1 (%u), ignored.", criteria->ID, criteria->type, dataType, drunk.state); return false; } return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY: if (!sHolidaysStore.LookupEntry(holiday.id)) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY (%u) has unknown holiday in value1 (%u), ignored.", criteria->ID, criteria->type, dataType, holiday.id); return false; } return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_BG_LOSS_TEAM_SCORE: return true; // not check correctness node indexes case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_EQUIPED_ITEM: if (equipped_item.item_quality >= MAX_ITEM_QUALITY) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_requirement` (Entry: %u Type: %u) for requirement ACHIEVEMENT_CRITERIA_REQUIRE_S_EQUIPED_ITEM (%u) has unknown quality state in value1 (%u), ignored.", criteria->ID, criteria->type, dataType, equipped_item.item_quality); return false; } return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE: if (!classRace.class_id && !classRace.race_id) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) must not have 0 in either value field, ignored.", criteria->ID, criteria->type, dataType); return false; } if (classRace.class_id && ((1 << (classRace.class_id-1)) & CLASSMASK_ALL_PLAYABLE) == 0) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) has non-existing class in value1 (%u), ignored.", criteria->ID, criteria->type, dataType, classRace.class_id); return false; } if (classRace.race_id && ((1 << (classRace.race_id-1)) & RACEMASK_ALL_PLAYABLE) == 0) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) has non-existing race in value2 (%u), ignored.", criteria->ID, criteria->type, dataType, classRace.race_id); return false; } return true; default: TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) has data for non-supported data type (%u), ignored.", criteria->ID, criteria->type, dataType); return false; } } bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source, Unit const* target, uint32 miscValue1 /*= 0*/) const { switch (dataType) { case ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE: return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_CREATURE: if (!target || target->GetTypeId() != TYPEID_UNIT) return false; return target->GetEntry() == creature.id; case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE: if (!target || target->GetTypeId() != TYPEID_PLAYER) return false; if (classRace.class_id && classRace.class_id != target->ToPlayer()->getClass()) return false; if (classRace.race_id && classRace.race_id != target->ToPlayer()->getRace()) return false; return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE: if (!source || source->GetTypeId() != TYPEID_PLAYER) return false; if (classRace.class_id && classRace.class_id != source->ToPlayer()->getClass()) return false; if (classRace.race_id && classRace.race_id != source->ToPlayer()->getRace()) return false; return true; case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_LESS_HEALTH: if (!target || target->GetTypeId() != TYPEID_PLAYER) return false; return !target->HealthAbovePct(health.percent); case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA: return source->HasAuraEffect(aura.spell_id, aura.effect_idx); case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA: return target && target->HasAuraEffect(aura.spell_id, aura.effect_idx); case ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE: return CompareValues(ComparisionType(value.compType), miscValue1, value.value); case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL: if (!target) return false; return target->getLevel() >= level.minlevel; case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER: if (!target) return false; return target->getGender() == gender.gender; case ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT: return sScriptMgr->OnCriteriaCheck(ScriptId, const_cast<Player*>(source), const_cast<Unit*>(target)); case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT: return source->GetMap()->GetPlayersCountExceptGMs() <= map_players.maxcount; case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM: if (!target || target->GetTypeId() != TYPEID_PLAYER) return false; return target->ToPlayer()->GetTeam() == team.team; case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK: return Player::GetDrunkenstateByValue(source->GetDrunkValue()) >= DrunkenState(drunk.state); case ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY: return IsHolidayActive(HolidayIds(holiday.id)); case ACHIEVEMENT_CRITERIA_DATA_TYPE_BG_LOSS_TEAM_SCORE: { Battleground* bg = source->GetBattleground(); if (!bg) return false; uint32 score = bg->GetTeamScore(source->GetTeamId() == TEAM_ALLIANCE ? TEAM_HORDE : TEAM_ALLIANCE); return score >= bg_loss_team_score.min_score && score <= bg_loss_team_score.max_score; } case ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT: { if (!source->IsInWorld()) return false; Map* map = source->GetMap(); if (!map->IsDungeon()) { TC_LOG_ERROR("achievement", "Achievement system call ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT (%u) for achievement criteria %u for non-dungeon/non-raid map %u", ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT, criteria_id, map->GetId()); return false; } InstanceScript* instance = ((InstanceMap*)map)->GetInstanceScript(); if (!instance) { TC_LOG_ERROR("achievement", "Achievement system call ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT (%u) for achievement criteria %u for map %u but map does not have a instance script", ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT, criteria_id, map->GetId()); return false; } return instance->CheckAchievementCriteriaMeet(criteria_id, source, target, miscValue1); } case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_EQUIPED_ITEM: { ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(miscValue1); if (!pProto) return false; return pProto->ItemLevel >= equipped_item.item_level && pProto->Quality >= equipped_item.item_quality; } default: break; } return false; } bool AchievementCriteriaDataSet::Meets(Player const* source, Unit const* target, uint32 miscValue /*= 0*/) const { for (Storage::const_iterator itr = storage.begin(); itr != storage.end(); ++itr) if (!itr->Meets(criteria_id, source, target, miscValue)) return false; return true; } template<class T> AchievementMgr<T>::AchievementMgr(T* owner): _owner(owner), _achievementPoints(0) { } template<class T> AchievementMgr<T>::~AchievementMgr() { } template<class T> void AchievementMgr<T>::SendPacket(WorldPacket* data) const { } template<> void AchievementMgr<Guild>::SendPacket(WorldPacket* data) const { GetOwner()->BroadcastPacket(data); } template<> void AchievementMgr<Player>::SendPacket(WorldPacket* data) const { GetOwner()->GetSession()->SendPacket(data); } template<class T> void AchievementMgr<T>::RemoveCriteriaProgress(CriteriaEntry const* entry) { if (!entry) return; CriteriaProgressMap::iterator criteriaProgress = m_criteriaProgress.find(entry->ID); if (criteriaProgress == m_criteriaProgress.end()) return; WorldPacket data(SMSG_CRITERIA_DELETED, 4); data << uint32(entry->ID); SendPacket(&data); m_criteriaProgress.erase(criteriaProgress); } template<> void AchievementMgr<Guild>::RemoveCriteriaProgress(CriteriaEntry const* entry) { if (!entry) return; CriteriaProgressMap::iterator criteriaProgress = m_criteriaProgress.find(entry->ID); if (criteriaProgress == m_criteriaProgress.end()) return; ObjectGuid guid = GetOwner()->GetGUID(); WorldPacket data(SMSG_GUILD_CRITERIA_DELETED, 4 + 8); data << guid; data << uint32(entry->ID); SendPacket(&data); m_criteriaProgress.erase(criteriaProgress); } template<class T> void AchievementMgr<T>::ResetAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1, uint64 miscValue2, bool evenIfCriteriaComplete) { TC_LOG_DEBUG("achievement", "ResetAchievementCriteria(%u, " UI64FMTD ", " UI64FMTD ")", type, miscValue1, miscValue2); // disable for gamemasters with GM-mode enabled if (GetOwner()->IsGameMaster()) return; AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetAchievementCriteriaByType(type); for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i) { CriteriaEntry const* achievementCriteria = (*i); // don't update already completed criteria if not forced or achievement already complete if (!IsCompletedCriteria(achievementCriteria)) RemoveCriteriaProgress(achievementCriteria); } } template<> void AchievementMgr<Guild>::ResetAchievementCriteria(AchievementCriteriaTypes /*type*/, uint64 /*miscValue1*/, uint64 /*miscValue2*/, bool /*evenIfCriteriaComplete*/) { // Not needed } template<class T> void AchievementMgr<T>::DeleteFromDB(uint32 /*lowguid*/) { } template<> void AchievementMgr<Player>::DeleteFromDB(uint32 lowguid) { SQLTransaction trans = CharacterDatabase.BeginTransaction(); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT); stmt->setUInt32(0, lowguid); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT_PROGRESS); stmt->setUInt32(0, lowguid); trans->Append(stmt); CharacterDatabase.CommitTransaction(trans); } template<> void AchievementMgr<Guild>::DeleteFromDB(uint32 lowguid) { SQLTransaction trans = CharacterDatabase.BeginTransaction(); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_GUILD_ACHIEVEMENTS); stmt->setUInt32(0, lowguid); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_GUILD_ACHIEVEMENT_CRITERIA); stmt->setUInt32(0, lowguid); trans->Append(stmt); CharacterDatabase.CommitTransaction(trans); } template<class T> void AchievementMgr<T>::SaveToDB(SQLTransaction& /*trans*/) { } template<> void AchievementMgr<Player>::SaveToDB(SQLTransaction& trans) { if (!m_completedAchievements.empty()) { for (CompletedAchievementMap::iterator iter = m_completedAchievements.begin(); iter != m_completedAchievements.end(); ++iter) { if (!iter->second.changed) continue; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT_BY_ACHIEVEMENT); stmt->setUInt16(0, iter->first); stmt->setUInt32(1, GetOwner()->GetGUID()); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_ACHIEVEMENT); stmt->setUInt32(0, GetOwner()->GetGUID()); stmt->setUInt16(1, iter->first); stmt->setUInt32(2, uint32(iter->second.date)); trans->Append(stmt); iter->second.changed = false; } } if (!m_criteriaProgress.empty()) { for (CriteriaProgressMap::iterator iter = m_criteriaProgress.begin(); iter != m_criteriaProgress.end(); ++iter) { if (!iter->second.changed) continue; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT_PROGRESS_BY_CRITERIA); stmt->setUInt32(0, GetOwner()->GetGUID()); stmt->setUInt16(1, iter->first); trans->Append(stmt); if (iter->second.counter) { stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_ACHIEVEMENT_PROGRESS); stmt->setUInt32(0, GetOwner()->GetGUID()); stmt->setUInt16(1, iter->first); stmt->setUInt32(2, iter->second.counter); stmt->setUInt32(3, uint32(iter->second.date)); trans->Append(stmt); } iter->second.changed = false; } } } template<> void AchievementMgr<Guild>::SaveToDB(SQLTransaction& trans) { PreparedStatement* stmt; std::ostringstream guidstr; for (CompletedAchievementMap::const_iterator itr = m_completedAchievements.begin(); itr != m_completedAchievements.end(); ++itr) { if (!itr->second.changed) continue; stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_ACHIEVEMENT); stmt->setUInt32(0, GetOwner()->GetId()); stmt->setUInt16(1, itr->first); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_ACHIEVEMENT); stmt->setUInt32(0, GetOwner()->GetId()); stmt->setUInt16(1, itr->first); stmt->setUInt32(2, itr->second.date); for (std::set<uint64>::const_iterator gItr = itr->second.guids.begin(); gItr != itr->second.guids.end(); ++gItr) guidstr << GUID_LOPART(*gItr) << ','; stmt->setString(3, guidstr.str()); trans->Append(stmt); guidstr.str(""); } for (CriteriaProgressMap::const_iterator itr = m_criteriaProgress.begin(); itr != m_criteriaProgress.end(); ++itr) { if (!itr->second.changed) continue; stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_ACHIEVEMENT_CRITERIA); stmt->setUInt32(0, GetOwner()->GetId()); stmt->setUInt16(1, itr->first); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_ACHIEVEMENT_CRITERIA); stmt->setUInt32(0, GetOwner()->GetId()); stmt->setUInt16(1, itr->first); stmt->setUInt64(2, itr->second.counter); stmt->setUInt32(3, itr->second.date); stmt->setUInt32(4, GUID_LOPART(itr->second.CompletedGUID)); trans->Append(stmt); } } template<class T> void AchievementMgr<T>::LoadFromDB(PreparedQueryResult achievementResult, PreparedQueryResult criteriaResult) { } template<> void AchievementMgr<Player>::LoadFromDB(PreparedQueryResult achievementResult, PreparedQueryResult criteriaResult) { if (achievementResult) { do { Field* fields = achievementResult->Fetch(); uint32 achievementid = fields[0].GetUInt16(); // must not happen: cleanup at server startup in sAchievementMgr->LoadCompletedAchievements() AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementid); if (!achievement) continue; CompletedAchievementData& ca = m_completedAchievements[achievementid]; ca.date = time_t(fields[1].GetUInt32()); ca.changed = false; _achievementPoints += achievement->points; // title achievement rewards are retroactive if (AchievementReward const* reward = sAchievementMgr->GetAchievementReward(achievement)) if (uint32 titleId = reward->titleId[Player::TeamForRace(GetOwner()->getRace()) == ALLIANCE ? 0 : 1]) if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(titleId)) GetOwner()->SetTitle(titleEntry); } while (achievementResult->NextRow()); } if (criteriaResult) { time_t now = time(NULL); do { Field* fields = criteriaResult->Fetch(); uint32 id = fields[0].GetUInt16(); uint64 counter = fields[1].GetUInt64(); time_t date = time_t(fields[2].GetUInt32()); CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(id); if (!criteria) { // we will remove not existed criteria for all characters TC_LOG_ERROR("achievement", "Non-existing achievement criteria %u data removed from table `character_achievement_progress`.", id); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA); stmt->setUInt16(0, uint16(id)); CharacterDatabase.Execute(stmt); continue; } if (criteria->timeLimit && time_t(date + criteria->timeLimit) < now) continue; CriteriaProgress& progress = m_criteriaProgress[id]; progress.counter = counter; progress.date = date; progress.changed = false; } while (criteriaResult->NextRow()); } } template<> void AchievementMgr<Guild>::LoadFromDB(PreparedQueryResult achievementResult, PreparedQueryResult criteriaResult) { if (achievementResult) { do { Field* fields = achievementResult->Fetch(); uint32 achievementid = fields[0].GetUInt16(); // must not happen: cleanup at server startup in sAchievementMgr->LoadCompletedAchievements() AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementid); if (!achievement) continue; CompletedAchievementData& ca = m_completedAchievements[achievementid]; ca.date = time_t(fields[1].GetUInt32()); Tokenizer guids(fields[2].GetString(), ' '); for (uint32 i = 0; i < guids.size(); ++i) ca.guids.insert(MAKE_NEW_GUID(atol(guids[i]), 0, HIGHGUID_PLAYER)); ca.changed = false; _achievementPoints += achievement->points; } while (achievementResult->NextRow()); } if (criteriaResult) { time_t now = time(NULL); do { Field* fields = criteriaResult->Fetch(); uint32 id = fields[0].GetUInt16(); uint32 counter = fields[1].GetUInt32(); time_t date = time_t(fields[2].GetUInt32()); uint64 guid = fields[3].GetUInt32(); CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(id); if (!criteria) { // we will remove not existed criteria for all guilds TC_LOG_ERROR("achievement", "Non-existing achievement criteria %u data removed from table `guild_achievement_progress`.", id); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA_GUILD); stmt->setUInt16(0, uint16(id)); CharacterDatabase.Execute(stmt); continue; } if (criteria->timeLimit && time_t(date + criteria->timeLimit) < now) continue; CriteriaProgress& progress = m_criteriaProgress[id]; progress.counter = counter; progress.date = date; progress.CompletedGUID = MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER); progress.changed = false; } while (criteriaResult->NextRow()); } } template<class T> void AchievementMgr<T>::Reset() { } template<> void AchievementMgr<Player>::Reset() { for (auto completedAchievementsMap : m_completedAchievements) { WorldPacket data(SMSG_ACHIEVEMENT_DELETED, 4 + 4); data << uint32(completedAchievementsMap.first); data << uint32(0); // Immunities SendPacket(&data); } for (CriteriaProgressMap::const_iterator iter = m_criteriaProgress.begin(); iter != m_criteriaProgress.end(); ++iter) { WorldPacket data(SMSG_CRITERIA_DELETED, 4); data << uint32(iter->first); SendPacket(&data); } m_completedAchievements.clear(); _achievementPoints = 0; m_criteriaProgress.clear(); DeleteFromDB(GetOwner()->GetGUIDLow()); // re-fill data CheckAllAchievementCriteria(GetOwner()); } template<> void AchievementMgr<Guild>::Reset() { ObjectGuid guid = GetOwner()->GetGUID(); for (CompletedAchievementMap::const_iterator iter = m_completedAchievements.begin(); iter != m_completedAchievements.end(); ++iter) { WorldPacket data(SMSG_GUILD_ACHIEVEMENT_DELETED, 4); data << guid; data << uint32(iter->first); data.AppendPackedTime(iter->second.date); SendPacket(&data); } while (!m_criteriaProgress.empty()) if (CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(m_criteriaProgress.begin()->first)) RemoveCriteriaProgress(criteria); _achievementPoints = 0; m_completedAchievements.clear(); DeleteFromDB(GetOwner()->GetId()); } template<class T> void AchievementMgr<T>::SendAchievementEarned(AchievementEntry const* achievement) const { // Don't send for achievements with ACHIEVEMENT_FLAG_HIDDEN if (achievement->flags & ACHIEVEMENT_FLAG_HIDDEN) return; TC_LOG_DEBUG("achievement", "AchievementMgr::SendAchievementEarned(%u)", achievement->ID); if (Guild* guild = sGuildMgr->GetGuildById(GetOwner()->GetGuildId())) { Trinity::AchievementChatBuilder say_builder(*GetOwner(), CHAT_MSG_GUILD_ACHIEVEMENT, LANG_ACHIEVEMENT_EARNED, achievement->ID); Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> say_do(say_builder); guild->BroadcastWorker(say_do); } if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_KILL | ACHIEVEMENT_FLAG_REALM_FIRST_REACH)) { // broadcast realm first reached WorldPacket data(SMSG_SERVER_FIRST_ACHIEVEMENT, GetOwner()->GetName().size() + 1 + 8 + 4 + 4); data << GetOwner()->GetName(); data << uint64(GetOwner()->GetGUID()); data << uint32(achievement->ID); data << uint32(0); // 1=link supplied string as player name, 0=display plain string sWorld->SendGlobalMessage(&data); } // if player is in world he can tell his friends about new achievement else if (GetOwner()->IsInWorld()) { Trinity::AchievementChatBuilder say_builder(*GetOwner(), CHAT_MSG_ACHIEVEMENT, LANG_ACHIEVEMENT_EARNED, achievement->ID); CellCoord p = Trinity::ComputeCellCoord(GetOwner()->GetPositionX(), GetOwner()->GetPositionY()); Cell cell(p); cell.SetNoCreate(); Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> say_do(say_builder); Trinity::PlayerDistWorker<Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> > say_worker(GetOwner(), sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), say_do); TypeContainerVisitor<Trinity::PlayerDistWorker<Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> >, WorldTypeMapContainer > message(say_worker); cell.Visit(p, message, *GetOwner()->GetMap(), *GetOwner(), sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY)); } ObjectGuid guid = GetOwner()->GetGUID(); ObjectGuid guid2 = GetOwner()->GetGUID(); WorldPacket data(SMSG_ACHIEVEMENT_EARNED, 16 + 16 + 4 + 4 + 4 + 4 + 1); data << guid; // Earner data << guid2; // Sender data << uint32(achievement->ID); // AchievementID data.AppendPackedTime(time(NULL)); // Time data << uint32(realmID); // EarnerVirtualRealm data << uint32(realmID); // EarnerNativeRealm data.WriteBit(0); // Initial GetOwner()->SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), true); } template<> void AchievementMgr<Guild>::SendAchievementEarned(AchievementEntry const* achievement) const { ObjectGuid guid = GetOwner()->GetGUID(); WorldPacket data(SMSG_GUILD_ACHIEVEMENT_EARNED, 8+4+8); data << guid; data.AppendPackedTime(time(NULL)); data << uint32(achievement->ID); SendPacket(&data); } template<class T> void AchievementMgr<T>::SendCriteriaUpdate(CriteriaEntry const* /*entry*/, CriteriaProgress const* /*progress*/, uint32 /*timeElapsed*/, bool /*timedCompleted*/) const { } template<> void AchievementMgr<Player>::SendCriteriaUpdate(CriteriaEntry const* entry, CriteriaProgress const* progress, uint32 timeElapsed, bool timedCompleted) const { ObjectGuid guid = GetOwner()->GetGUID128(); WorldPacket data(SMSG_CRITERIA_UPDATE, 4 + 4 + 16 + 4 + 18); data << uint32(entry->ID); data << uint64(progress->counter); data << guid; data << uint32(timeElapsed); data.AppendPackedTime(progress->date); if (!entry->timeLimit) data.WriteBits(0, 4); else data.WriteBits(timedCompleted ? 0 : 1, 4); SendPacket(&data); } template<> void AchievementMgr<Guild>::SendCriteriaUpdate(CriteriaEntry const* entry, CriteriaProgress const* progress, uint32 /*timeElapsed*/, bool /*timedCompleted*/) const { //will send response to criteria progress request WorldPacket data(SMSG_GUILD_CRITERIA_DATA, 3 + 1 + 1 + 8 + 8 + 4 + 4 + 4 + 4 + 4); ObjectGuid counter = progress->counter; // for accessing every byte individually ObjectGuid guid = progress->CompletedGUID; // From CriteriaUpdate data << uint32(0); // Unk // EarnedAchievement data << counter; // Guid data << guid; // Guid data << uint32(progress->date); // DateCreated data << uint32(progress->date); // DateStarted data << uint32(progress->date); // DateUpdated data << uint32(entry->ID); // CriteriaID data << uint32(0); // Flags SendPacket(&data); } /** * called at player login. The player might have fulfilled some achievements when the achievement system wasn't working yet */ template<class T> void AchievementMgr<T>::CheckAllAchievementCriteria(Player* referencePlayer) { // suppress sending packets for (uint32 i=0; i<ACHIEVEMENT_CRITERIA_TYPE_TOTAL; ++i) UpdateAchievementCriteria(AchievementCriteriaTypes(i), 0, 0, 0, NULL, referencePlayer); } static const uint32 achievIdByArenaSlot[MAX_ARENA_SLOT] = {1057, 1107, 1108}; static const uint32 achievIdForDungeon[][4] = { // ach_cr_id, is_dungeon, is_raid, is_heroic_dungeon { 321, true, true, true }, { 916, false, true, false }, { 917, false, true, false }, { 918, true, false, false }, { 2219, false, false, true }, { 0, false, false, false } }; // Helper function to avoid having to specialize template for a 800 line long function template <typename T> static bool IsGuild() { return false; } template<> bool IsGuild<Guild>() { return true; } /** * this function will be called whenever the user might have done a criteria relevant action */ template<class T> void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1 /*= 0*/, uint64 miscValue2 /*= 0*/, uint64 miscValue3 /*= 0*/, Unit const* unit /*= NULL*/, Player* referencePlayer /*= NULL*/) { if (type >= ACHIEVEMENT_CRITERIA_TYPE_TOTAL) { TC_LOG_DEBUG("achievement", "UpdateAchievementCriteria: Wrong criteria type %u", type); return; } if (!referencePlayer) { TC_LOG_DEBUG("achievement", "UpdateAchievementCriteria: Player is NULL! Cant update criteria"); return; } // disable for gamemasters with GM-mode enabled if (referencePlayer->IsGameMaster()) { TC_LOG_DEBUG("achievement", "UpdateAchievementCriteria: [Player %s GM mode on] %s, %s (%u), " UI64FMTD ", " UI64FMTD ", " UI64FMTD , referencePlayer->GetName().c_str(), GetLogNameForGuid(GetOwner()->GetGUID()), AchievementGlobalMgr::GetCriteriaTypeString(type), type, miscValue1, miscValue2, miscValue3); return; } TC_LOG_DEBUG("achievement", "UpdateAchievementCriteria: %s, %s (%u), " UI64FMTD ", " UI64FMTD ", " UI64FMTD , GetLogNameForGuid(GetOwner()->GetGUID()), AchievementGlobalMgr::GetCriteriaTypeString(type), type, miscValue1, miscValue2, miscValue3); AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetAchievementCriteriaByType(type); for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i) { CriteriaEntry const* achievementCriteria = (*i); if (!CanUpdateCriteria(achievementCriteria, NULL, miscValue1, miscValue2, miscValue3, unit, referencePlayer)) continue; // requirements not found in the dbc if (AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria)) if (!data->Meets(referencePlayer, unit, miscValue1)) continue; switch (type) { // std. case: increment at 1 case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS: case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL: case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION: case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS: /* FIXME: for online player only currently */ case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED: case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED: case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED: case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN: case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS: case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_DEATH: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST: case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP: case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON: case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE: case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER: case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM: case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET: case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2: case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL: case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2: case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA: case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT: case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT: case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE: case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT: case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT: case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL: case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS: case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE: case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE: case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL: case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL: case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS: case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA: case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA: // This also behaves like ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); break; // std case: increment at miscValue1 case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS: case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS: case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD: case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING: case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER: case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL: case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY: case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS:/* FIXME: for online player only currently */ case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED: case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED: case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS: case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND: case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE: case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE: SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_ACCUMULATE); break; case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE: case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE: case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE: case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY: SetCriteriaProgress(achievementCriteria, miscValue2, referencePlayer, PROGRESS_ACCUMULATE); break; // std case: high value at miscValue1 case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD: /* FIXME: for online player only currently */ case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED: SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_HIGHEST); break; case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL: SetCriteriaProgress(achievementCriteria, referencePlayer->getLevel(), referencePlayer); break; case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL: if (uint32 skillvalue = referencePlayer->GetBaseSkillValue(achievementCriteria->reach_skill_level.skillID)) SetCriteriaProgress(achievementCriteria, skillvalue, referencePlayer); break; case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL: if (uint32 maxSkillvalue = referencePlayer->GetPureMaxSkillValue(achievementCriteria->learn_skill_level.skillID)) SetCriteriaProgress(achievementCriteria, maxSkillvalue, referencePlayer); break; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT: SetCriteriaProgress(achievementCriteria, referencePlayer->GetRewardedQuestCount(), referencePlayer); break; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY: { time_t nextDailyResetTime = sWorld->GetNextDailyQuestsResetTime(); CriteriaProgress *progress = GetCriteriaProgress(achievementCriteria); if (!miscValue1) // Login case. { // reset if player missed one day. if (progress && progress->date < (nextDailyResetTime - 2 * DAY)) SetCriteriaProgress(achievementCriteria, 0, referencePlayer, PROGRESS_SET); continue; } ProgressType progressType; if (!progress) // 1st time. Start count. progressType = PROGRESS_SET; else if (progress->date < (nextDailyResetTime - 2 * DAY)) // last progress is older than 2 days. Player missed 1 day => Restart count. progressType = PROGRESS_SET; else if (progress->date < (nextDailyResetTime - DAY)) // last progress is between 1 and 2 days. => 1st time of the day. progressType = PROGRESS_ACCUMULATE; else // last progress is within the day before the reset => Already counted today. continue; SetCriteriaProgress(achievementCriteria, 1, referencePlayer, progressType); break; } case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE: { uint32 counter = 0; const RewardedQuestSet &rewQuests = referencePlayer->getRewardedQuests(); for (RewardedQuestSet::const_iterator itr = rewQuests.begin(); itr != rewQuests.end(); ++itr) { Quest const* quest = sObjectMgr->GetQuestTemplate(*itr); if (quest && quest->GetZoneOrSort() >= 0 && uint32(quest->GetZoneOrSort()) == achievementCriteria->complete_quests_in_zone.zoneID) ++counter; } SetCriteriaProgress(achievementCriteria, counter, referencePlayer); break; } case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING: // miscValue1 is the ingame fallheight*100 as stored in dbc SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer); break; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL: case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA: case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP: case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT: SetCriteriaProgress(achievementCriteria, 1, referencePlayer); break; case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT: SetCriteriaProgress(achievementCriteria, referencePlayer->GetBankBagSlotCount(), referencePlayer); break; case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION: { int32 reputation = referencePlayer->GetReputationMgr().GetReputation(achievementCriteria->gain_reputation.factionID); if (reputation > 0) SetCriteriaProgress(achievementCriteria, reputation, referencePlayer); break; } case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION: SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetExaltedFactionCount(), referencePlayer); break; case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS: { uint32 spellCount = 0; for (PlayerSpellMap::const_iterator spellIter = referencePlayer->GetSpellMap().begin(); spellIter != referencePlayer->GetSpellMap().end(); ++spellIter) { SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellIter->first); for (SkillLineAbilityMap::const_iterator skillIter = bounds.first; skillIter != bounds.second; ++skillIter) { if (skillIter->second->SkillLine == achievementCriteria->learn_skillline_spell.skillLine) spellCount++; } } SetCriteriaProgress(achievementCriteria, spellCount, referencePlayer); break; } case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION: SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetReveredFactionCount(), referencePlayer); break; case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION: SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetHonoredFactionCount(), referencePlayer); break; case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS: SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetVisibleFactionCount(), referencePlayer); break; case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE: { uint32 spellCount = 0; for (PlayerSpellMap::const_iterator spellIter = referencePlayer->GetSpellMap().begin(); spellIter != referencePlayer->GetSpellMap().end(); ++spellIter) { SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellIter->first); for (SkillLineAbilityMap::const_iterator skillIter = bounds.first; skillIter != bounds.second; ++skillIter) if (skillIter->second->SkillLine == achievementCriteria->learn_skill_line.skillLine) spellCount++; } SetCriteriaProgress(achievementCriteria, spellCount, referencePlayer); break; } case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL: SetCriteriaProgress(achievementCriteria, referencePlayer->GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS), referencePlayer); break; case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED: SetCriteriaProgress(achievementCriteria, referencePlayer->GetMoney(), referencePlayer, PROGRESS_HIGHEST); break; case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS: if (!miscValue1) SetCriteriaProgress(achievementCriteria, _achievementPoints, referencePlayer, PROGRESS_SET); else SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_ACCUMULATE); break; case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING: { uint32 reqTeamType = achievementCriteria->highest_team_rating.teamtype; if (miscValue1) { if (miscValue2 != reqTeamType) continue; SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_HIGHEST); } else // login case { RatedInfo* rInfo = sRatedMgr->GetRatedInfo(referencePlayer->GetGUID()); for (uint8 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot) { RatedType ratedType = RatedInfo::GetRatedTypeBySlot(arena_slot); if (!ratedType != reqTeamType) continue; StatsBySlot const* stats = rInfo->GetStatsBySlot(ratedType); SetCriteriaProgress(achievementCriteria, stats->PersonalRating, referencePlayer, PROGRESS_HIGHEST); break; } } break; } case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING: { uint32 reqTeamType = achievementCriteria->highest_personal_rating.teamtype; if (miscValue1) { if (miscValue2 != reqTeamType) continue; SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_HIGHEST); } else // login case { RatedInfo* rInfo = sRatedMgr->GetRatedInfo(referencePlayer->GetGUID()); for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot) { RatedType ratedType = RatedInfo::GetRatedTypeBySlot(arena_slot); if (ratedType != reqTeamType) continue; StatsBySlot const *stats = rInfo->GetStatsBySlot(ratedType); SetCriteriaProgress(achievementCriteria, stats->PersonalRating, referencePlayer, PROGRESS_HIGHEST); break; } } break; } case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL: SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer); break; // FIXME: not triggered in code as result, need to implement case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_RAID: case ACHIEVEMENT_CRITERIA_TYPE_PLAY_ARENA: case ACHIEVEMENT_CRITERIA_TYPE_OWN_RANK: case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE: case ACHIEVEMENT_CRITERIA_TYPE_SPENT_GOLD_GUILD_REPAIRS: case ACHIEVEMENT_CRITERIA_TYPE_CRAFT_ITEMS_GUILD: case ACHIEVEMENT_CRITERIA_TYPE_CATCH_FROM_POOL: case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_BANK_SLOTS: case ACHIEVEMENT_CRITERIA_TYPE_EARN_GUILD_ACHIEVEMENT_POINTS: case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_BATTLEGROUND: case ACHIEVEMENT_CRITERIA_TYPE_REACH_BG_RATING: case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_TABARD: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_GUILD: case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILLS_GUILD: case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE_GUILD: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ARCHAEOLOGY_PROJECTS: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE_TYPE: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE: break; // Not implemented yet :( } AchievementCriteriaTreeList achievementCriteriaTreeList = sAchievementMgr->GetAchievementCriteriaTreeList(achievementCriteria); for (AchievementCriteriaTreeList::const_iterator iter = achievementCriteriaTreeList.begin(); iter != achievementCriteriaTreeList.end(); iter++) { AchievementEntry const* achievement = sAchievementMgr->GetAchievementEntryByCriteriaTree(*iter); if (!achievement) continue; if (IsCompletedCriteriaForAchievement(achievementCriteria, achievement)) CompletedCriteriaFor(achievement, referencePlayer); // check again the completeness for SUMM and REQ COUNT achievements, // as they don't depend on the completed criteria but on the sum of the progress of each individual criteria if (achievement->flags & ACHIEVEMENT_FLAG_SUMM) if (IsCompletedAchievement(achievement)) CompletedAchievement(achievement, referencePlayer); if (AchievementEntryList const* achRefList = sAchievementMgr->GetAchievementByReferencedId(achievement->ID)) for (AchievementEntryList::const_iterator itr = achRefList->begin(); itr != achRefList->end(); ++itr) if (IsCompletedAchievement(*itr)) CompletedAchievement(*itr, referencePlayer); } } } template<class T> bool AchievementMgr<T>::IsCompletedCriteria(CriteriaEntry const* criteria) { AchievementCriteriaTreeList const& criteriaTreeList = sAchievementMgr->GetAchievementCriteriaTreeList(criteria); for (AchievementCriteriaTreeList::const_iterator iter = criteriaTreeList.begin(); iter != criteriaTreeList.end(); iter++) { CriteriaTreeEntry const* criteriaTree = *iter; AchievementEntry const* achievement = sAchievementMgr->GetAchievementEntryByCriteriaTree(criteriaTree); if (!achievement) return false; if (CriteriaEntry const* criteria = sCriteriaStore.LookupEntry(criteriaTree->ID)) if (!IsCompletedCriteriaForAchievement(criteria, achievement)) return false; } return true; } template<class T> bool AchievementMgr<T>::IsCompletedCriteriaForAchievement(CriteriaEntry const* criteria, AchievementEntry const* achievement) { if (!criteria || !achievement) return false; CriteriaTreeEntry const* criteriaTree = NULL; AchievementCriteriaTreeList const* treeList = sAchievementMgr->GetSubCriteriaTreeById(achievement->criteriaTreeID); if (treeList) { for (AchievementCriteriaTreeList::const_iterator iter = treeList->begin(); iter != treeList->end(); iter++) { if ((*iter)->criteriaID == criteria->ID) { criteriaTree = *iter; break; } } } if (!criteriaTree) return false; // counter can never complete if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER) return false; if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL)) { // someone on this realm has already completed that achievement if (sAchievementMgr->IsRealmCompleted(achievement)) return false; } CriteriaProgress const* progress = GetCriteriaProgress(criteria); if (!progress) return false; switch (AchievementCriteriaTypes(criteria->type)) { case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG: case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE: case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL: case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL: case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE: case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE: case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST: case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING: case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET: case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2: case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL: case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2: case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE: case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA: case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL: case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL: case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING: case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT: case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION: case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION: case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP: case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT: case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT: case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS: case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE: case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE: case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD: case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY: case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT: case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL: case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT: case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS: case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL: case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE: case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE: case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS: case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS: case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY: return progress->counter >= criteriaTree->criteriaCount; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL: case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA: return progress->counter >= 1; case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL: return progress->counter >= (criteriaTree->criteriaCount * 75); case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS: return progress->counter >= 9000; case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA: return criteriaTree->criteriaCount && progress->counter >= criteriaTree->criteriaCount; // handle all statistic-only criteria here case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND: case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP: case ACHIEVEMENT_CRITERIA_TYPE_DEATH: case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON: case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE: case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER: case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING: case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS: case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS: case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS: case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER: case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL: case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL: case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE: case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS: case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED: case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS: case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION: case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION: case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS: case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED: case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED: case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED: case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN: case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS: default: return false; } return false; } template<class T> void AchievementMgr<T>::CompletedCriteriaFor(AchievementEntry const* achievement, Player* referencePlayer) { // counter can never complete if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER) return; // already completed and stored if (HasAchieved(achievement->ID)) return; if (IsCompletedAchievement(achievement)) CompletedAchievement(achievement, referencePlayer); } template<class T> bool AchievementMgr<T>::IsCompletedAchievement(AchievementEntry const* entry) { // counter can never complete if (entry->flags & ACHIEVEMENT_FLAG_COUNTER) return false; // for achievement with referenced achievement criterias get from referenced and counter from self uint32 achievementForTestId = entry->refAchievement ? entry->refAchievement : entry->ID; uint32 achievementForTestCount = entry->count; if (CriteriaTreeEntry const* criteriaTree = sCriteriaTreeStore.LookupEntry(entry->criteriaTreeID)) achievementForTestCount = criteriaTree->criteriaCount; AchievementCriteriaEntryList cList; AchievementCriteriaTreeList const* list = sAchievementMgr->GetSubCriteriaTreeById(entry->criteriaTreeID); for (AchievementCriteriaTreeList::const_iterator iter = list->begin(); iter != list->end(); iter++) { CriteriaTreeEntry const* criteriaTree = *iter; if (CriteriaEntry const* criteria = sCriteriaStore.LookupEntry(criteriaTree->criteriaID)) cList.push_back(criteria); } if (!cList.size()) return false; uint64 count = 0; // For SUMM achievements, we have to count the progress of each criteria of the achievement. // Oddly, the target count is NOT contained in the achievement, but in each individual criteria if (entry->flags & ACHIEVEMENT_FLAG_SUMM) { for (AchievementCriteriaEntryList::const_iterator itr = cList.begin(); itr != cList.end(); ++itr) { CriteriaEntry const* criteria = *itr; CriteriaProgress const* progress = GetCriteriaProgress(criteria); if (!progress) continue; count += progress->counter; // for counters, field4 contains the main count requirement if (count >= sCriteriaTreeStore.LookupEntry(entry->criteriaTreeID)->criteriaCount) return true; } return false; } // Default case - need complete all or bool completed_all = true; for (AchievementCriteriaEntryList::const_iterator itr = cList.begin(); itr != cList.end(); ++itr) { CriteriaEntry const* criteria = *itr; bool completed = IsCompletedCriteriaForAchievement(criteria, entry); // found an uncompleted criteria, but DONT return false yet - there might be a completed criteria with ACHIEVEMENT_CRITERIA_COMPLETE_FLAG_ALL if (completed) ++count; else completed_all = false; // completed as have req. count of completed criterias if (achievementForTestCount > 0 && achievementForTestCount <= count) return true; } // all criterias completed requirement if (completed_all && achievementForTestCount == 0) return true; return false; } template<class T> CriteriaProgress* AchievementMgr<T>::GetCriteriaProgress(uint32 criteriaID) { CriteriaProgressMap::iterator iter = m_criteriaProgress.find(criteriaID); if (iter == m_criteriaProgress.end()) return NULL; return &(iter->second); } template<class T> void AchievementMgr<T>::SetCriteriaProgress(CriteriaEntry const* entry, uint64 changeValue, Player* referencePlayer, ProgressType ptype) { // Don't allow to cheat - doing timed achievements without timer active TimedAchievementMap::iterator timedIter = m_timedAchievements.find(entry->ID); if (entry->timeLimit && timedIter == m_timedAchievements.end()) return; TC_LOG_DEBUG("achievement", "SetCriteriaProgress(%u, " UI64FMTD ") for (%s GUID: %u)", entry->ID, changeValue, GetLogNameForGuid(GetOwner()->GetGUID()), GUID_LOPART(GetOwner()->GetGUID())); CriteriaProgress* progress = GetCriteriaProgress(entry); if (!progress) { // not create record for 0 counter but allow it for timed achievements // we will need to send 0 progress to client to start the timer if (changeValue == 0 && !entry->timeLimit) return; progress = &m_criteriaProgress[entry->ID]; progress->counter = changeValue; } else { uint64 newValue = 0; switch (ptype) { case PROGRESS_SET: newValue = changeValue; break; case PROGRESS_ACCUMULATE: { // avoid overflow uint64 max_value = std::numeric_limits<uint64>::max(); newValue = max_value - progress->counter > changeValue ? progress->counter + changeValue : max_value; break; } case PROGRESS_HIGHEST: newValue = progress->counter < changeValue ? changeValue : progress->counter; break; } // not update (not mark as changed) if counter will have same value if (progress->counter == newValue && !entry->timeLimit) return; progress->counter = newValue; } progress->changed = true; progress->date = time(NULL); // set the date to the latest update. uint32 timeElapsed = 0; // @todo : Fix me AchievementCriteriaTreeList criteriaList = sAchievementMgr->GetAchievementCriteriaTreeList(entry); for (AchievementCriteriaTreeList::const_iterator iter = criteriaList.begin(); iter != criteriaList.end(); iter++) { AchievementEntry const* achievement = sAchievementMgr->GetAchievementEntryByCriteriaTree(*iter); if (!achievement) continue; bool criteriaComplete = IsCompletedCriteriaForAchievement(entry, achievement); if (entry->timeLimit) { // Client expects this in packet timeElapsed = entry->timeLimit - (timedIter->second/IN_MILLISECONDS); // Remove the timer, we wont need it anymore if (criteriaComplete) m_timedAchievements.erase(timedIter); } if (criteriaComplete && achievement->flags & ACHIEVEMENT_FLAG_SHOW_CRITERIA_MEMBERS && !progress->CompletedGUID) progress->CompletedGUID = referencePlayer->GetGUID128(); } SendCriteriaUpdate(entry, progress, timeElapsed, false); } template<class T> void AchievementMgr<T>::UpdateTimedAchievements(uint32 timeDiff) { if (!m_timedAchievements.empty()) { for (TimedAchievementMap::iterator itr = m_timedAchievements.begin(); itr != m_timedAchievements.end();) { // Time is up, remove timer and reset progress if (itr->second <= timeDiff) { CriteriaEntry const* entry = sAchievementMgr->GetAchievementCriteria(itr->first); RemoveCriteriaProgress(entry); m_timedAchievements.erase(itr++); } else { itr->second -= timeDiff; ++itr; } } } } template<class T> void AchievementMgr<T>::StartTimedAchievement(AchievementCriteriaTimedTypes /*type*/, uint32 /*entry*/, uint32 /*timeLost = 0*/) { } template<> void AchievementMgr<Player>::StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry, uint32 timeLost /* = 0 */) { AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetTimedAchievementCriteriaByType(type); for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i) { if ((*i)->timedCriteriaMiscId != entry) continue; AchievementEntry const* achievement = sAchievementMgr->GetAchievement(entry); if (m_timedAchievements.find((*i)->ID) == m_timedAchievements.end() && !IsCompletedCriteriaForAchievement(*i, achievement)) { // Start the timer if ((*i)->timeLimit * IN_MILLISECONDS > timeLost) { m_timedAchievements[(*i)->ID] = (*i)->timeLimit * IN_MILLISECONDS - timeLost; // and at client too SetCriteriaProgress(*i, 0, GetOwner(), PROGRESS_SET); } } } } template<class T> void AchievementMgr<T>::RemoveTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) { AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetTimedAchievementCriteriaByType(type); for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i) { if ((*i)->timedCriteriaMiscId != entry) continue; TimedAchievementMap::iterator timedIter = m_timedAchievements.find((*i)->ID); // We don't have timer for this achievement if (timedIter == m_timedAchievements.end()) continue; // remove progress RemoveCriteriaProgress(*i); // Remove the timer m_timedAchievements.erase(timedIter); } } template<> void AchievementMgr<Player>::CompletedAchievement(AchievementEntry const* achievement, Player* referencePlayer) { // disable for gamemasters with GM-mode enabled if (GetOwner()->IsGameMaster()) return; if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER || HasAchieved(achievement->ID)) return; if (achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_NEWS) if (Guild* guild = referencePlayer->GetGuild()) guild->AddGuildNews(GUILD_NEWS_PLAYER_ACHIEVEMENT, referencePlayer->GetGUID(), achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_HEADER, achievement->ID); if (!GetOwner()->GetSession()->PlayerLoading()) SendAchievementEarned(achievement); TC_LOG_INFO("achievement", "AchievementMgr::CompletedAchievement(%u). Player: %s (%u)", achievement->ID, GetOwner()->GetName().c_str(), GetOwner()->GetGUIDLow()); CompletedAchievementData& ca = m_completedAchievements[achievement->ID]; ca.date = time(NULL); ca.changed = true; // don't insert for ACHIEVEMENT_FLAG_REALM_FIRST_KILL since otherwise only the first group member would reach that achievement /// @todo where do set this instead? if (!(achievement->flags & ACHIEVEMENT_FLAG_REALM_FIRST_KILL)) sAchievementMgr->SetRealmCompleted(achievement); _achievementPoints += achievement->points; UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT, 0, 0, 0, NULL, referencePlayer); UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS, achievement->points, 0, 0, NULL, referencePlayer); // reward items and titles if any AchievementReward const* reward = sAchievementMgr->GetAchievementReward(achievement); // no rewards if (!reward) return; // titles //! Currently there's only one achievement that deals with gender-specific titles. //! Since no common attributes were found, (not even in titleRewardFlags field) //! we explicitly check by ID. Maybe in the future we could move the achievement_reward //! condition fields to the condition system. if (uint32 titleId = reward->titleId[achievement->ID == 1793 ? GetOwner()->getGender() : (GetOwner()->GetTeam() == ALLIANCE ? 0 : 1)]) if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(titleId)) GetOwner()->SetTitle(titleEntry); // mail if (reward->sender) { Item* item = reward->itemId ? Item::CreateItem(reward->itemId, 1, GetOwner()) : NULL; int loc_idx = GetOwner()->GetSession()->GetSessionDbLocaleIndex(); // subject and text std::string subject = reward->subject; std::string text = reward->text; if (loc_idx >= 0) { if (AchievementRewardLocale const* loc = sAchievementMgr->GetAchievementRewardLocale(achievement)) { ObjectMgr::GetLocaleString(loc->subject, loc_idx, subject); ObjectMgr::GetLocaleString(loc->text, loc_idx, text); } } MailDraft draft(subject, text); SQLTransaction trans = CharacterDatabase.BeginTransaction(); if (item) { // save new item before send item->SaveToDB(trans); // save for prevent lost at next mail load, if send fail then item will deleted // item draft.AddItem(item); } draft.SendMailTo(trans, GetOwner(), MailSender(MAIL_CREATURE, reward->sender)); CharacterDatabase.CommitTransaction(trans); } } template<> void AchievementMgr<Guild>::CompletedAchievement(AchievementEntry const* achievement, Player* referencePlayer) { TC_LOG_DEBUG("achievement", "AchievementMgr<Guild>::CompletedAchievement(%u)", achievement->ID); if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER || HasAchieved(achievement->ID)) return; if (achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_NEWS) if (Guild* guild = referencePlayer->GetGuild()) guild->AddGuildNews(GUILD_NEWS_GUILD_ACHIEVEMENT, 0, achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_HEADER, achievement->ID); SendAchievementEarned(achievement); CompletedAchievementData& ca = m_completedAchievements[achievement->ID]; ca.date = time(NULL); ca.changed = true; if (achievement->flags & ACHIEVEMENT_FLAG_SHOW_GUILD_MEMBERS) { if (referencePlayer->GetGuildId() == GetOwner()->GetId()) ca.guids.insert(referencePlayer->GetGUID()); if (Group const* group = referencePlayer->GetGroup()) for (GroupReference const* ref = group->GetFirstMember(); ref != NULL; ref = ref->next()) if (Player const* groupMember = ref->GetSource()) if (groupMember->GetGuildId() == GetOwner()->GetId()) ca.guids.insert(groupMember->GetGUID()); } sAchievementMgr->SetRealmCompleted(achievement); _achievementPoints += achievement->points; UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT, 0, 0, 0, NULL, referencePlayer); UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS, achievement->points, 0, 0, NULL, referencePlayer); } struct VisibleAchievementPred { bool operator()(CompletedAchievementMap::value_type const& val) { AchievementEntry const* achievement = sAchievementMgr->GetAchievement(val.first); return achievement && !(achievement->flags & ACHIEVEMENT_FLAG_HIDDEN); } }; template<class T> void AchievementMgr<T>::SendAllAchievementData(Player* /*receiver*/) const { /* * Temporary fix for displaying achievements! Still uses old system. * More core and database changes required for cross character achievements */ VisibleAchievementPred isVisible; size_t numCriteria = m_criteriaProgress.size(); size_t numAchievements = std::count_if(m_completedAchievements.begin(), m_completedAchievements.end(), isVisible); ByteBuffer criteriaData(numCriteria * (4 + 4 + 4 + 4 + 8 + 8)); ByteBuffer completedData(numAchievements * (4 + 4 + 4 + 4 + 8)); ObjectGuid guid = GetOwner()->GetGUID(); ObjectGuid counter; WorldPacket data(SMSG_ALL_ACHIEVEMENT_DATA, numAchievements + (numAchievements * 32) + numCriteria + (numCriteria * 44)); data << uint32(numAchievements); data << uint32(numCriteria); for (auto itr : m_completedAchievements) { if (!isVisible(itr)) continue; completedData << uint32(itr.first); // Id completedData.AppendPackedTime(itr.second.date); // Date completedData << guid; // Owner completedData << uint32(realmID); // VirtualRealmAddress completedData << uint32(realmID); // NativeRealmAddress } for (auto itr : m_criteriaProgress) { counter = itr.second.counter; criteriaData << uint32(itr.first); // Id criteriaData << uint64(0); // Quantity criteriaData << counter; // Player criteriaData.AppendPackedTime(itr.second.date); // Date criteriaData << uint32(0); // TimeFromStart criteriaData << uint32(0); // TimeFromCreate data.WriteBits(0, 4); } data.FlushBits(); data.append(completedData); data.append(criteriaData); SendPacket(&data); } template<> void AchievementMgr<Guild>::SendAllAchievementData(Player* receiver) const { VisibleAchievementPred isVisible; WorldPacket data(SMSG_GUILD_ACHIEVEMENT_DATA, m_completedAchievements.size() * (4 + 4) + 3); ObjectGuid guid; data << uint32(0); data.WriteBits(std::count_if(m_completedAchievements.begin(), m_completedAchievements.end(), isVisible), 19); for (CompletedAchievementMap::const_iterator itr = m_completedAchievements.begin(); itr != m_completedAchievements.end(); ++itr) { if (!isVisible(*itr)) continue; data << uint32(itr->first); data.AppendPackedTime(itr->second.date); data << guid; data << uint32(0); // RealmID data << uint32(0); // RealmID } receiver->GetSession()->SendPacket(&data); } template<> void AchievementMgr<Player>::SendAchievementInfo(Player* receiver, uint32 /*achievementId = 0 */) { ObjectGuid guid = GetOwner()->GetGUID(); ObjectGuid counter; VisibleAchievementPred isVisible; size_t numCriteria = m_criteriaProgress.size(); size_t numAchievements = std::count_if(m_completedAchievements.begin(), m_completedAchievements.end(), isVisible); ByteBuffer criteriaData(numCriteria * 16); WorldPacket data(SMSG_RESPOND_INSPECT_ACHIEVEMENTS, 1 + 8 + 3 + 3 + numAchievements * (4 + 4) + numCriteria * (0)); data << guid; data.WriteBits(numAchievements, 23); data.WriteBits(numCriteria, 21); for (CriteriaProgressMap::const_iterator itr = m_criteriaProgress.begin(); itr != m_criteriaProgress.end(); ++itr) { counter = itr->second.counter; data << counter; data << guid; data.WriteBits(0, 2); // criteria progress flags criteriaData << uint32(0); // timer 1 criteriaData.AppendPackedTime(itr->second.date); criteriaData << uint32(itr->first); criteriaData << uint32(0); // timer 2 } data.FlushBits(); data.append(criteriaData); for (CompletedAchievementMap::const_iterator itr = m_completedAchievements.begin(); itr != m_completedAchievements.end(); ++itr) { if (!isVisible(*itr)) continue; data << uint32(itr->first); data.AppendPackedTime(itr->second.date); } receiver->GetSession()->SendPacket(&data); } template<> void AchievementMgr<Guild>::SendAchievementInfo(Player* receiver, uint32 achievementId /*= 0*/) { AchievementEntry const* achievement = sAchievementStore.LookupEntry(achievementId); if (!achievement) { // send empty packet WorldPacket data(SMSG_GUILD_CRITERIA_DATA, 3); data.WriteBits(0, 19); data.FlushBits(); receiver->GetSession()->SendPacket(&data); return; } AchievementCriteriaEntryList criterias; AchievementCriteriaTreeList const* list = sAchievementMgr->GetSubCriteriaTreeById(achievement->criteriaTreeID); for (AchievementCriteriaTreeList::const_iterator iter = list->begin(); iter != list->end(); iter++) { if (CriteriaEntry const* cr = sCriteriaStore.LookupEntry((*iter)->criteriaID)) criterias.push_back(cr); } static CriteriaProgress defaultCriteria = { 0, 0, 0, false }; CriteriaProgress const* criteria; ObjectGuid counter; ObjectGuid counter2 = 0; ByteBuffer criteriaData(criterias.size() * (8 + 8 + 4 + 4 + 4 + 4 + 4)); uint32 completed; WorldPacket data(SMSG_GUILD_CRITERIA_DATA, 3 + criterias.size() * (8 + 8 + 4 + 4 + 4 + 4 + 4)); data.WriteBits(criterias.size(), 19); for (AchievementCriteriaEntryList::const_iterator itr = criterias.begin(); itr != criterias.end(); itr++) { criteria = GetCriteriaProgress((*itr)->ID); if (!criteria) { criteria = &defaultCriteria; completed = 0; } else completed = 1; counter = criteria->counter; data << counter2; data << counter; criteriaData << (uint32)(*itr)->ID; criteriaData << (uint32)criteria->date; criteriaData << (uint32)criteria->date; criteriaData << (uint32)completed; criteriaData << (uint32)criteria->date; } data.FlushBits(); data.append(criteriaData); receiver->GetSession()->SendPacket(&data); } template<class T> bool AchievementMgr<T>::HasAchieved(uint32 achievementId) const { return m_completedAchievements.find(achievementId) != m_completedAchievements.end(); } template<class T> bool AchievementMgr<T>::CanUpdateCriteria(CriteriaEntry const* criteria, AchievementEntry const* achievement, uint64 miscValue1, uint64 miscValue2, uint64 miscValue3, Unit const* unit, Player* referencePlayer) { if (DisableMgr::IsDisabledFor(DISABLE_TYPE_ACHIEVEMENT_CRITERIA, criteria->ID, NULL)) { TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Disabled", criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type)); return false; } if (achievement && achievement->mapID != -1 && referencePlayer->GetMapId() != uint32(achievement->mapID)) { TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Wrong map", criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type)); return false; } if (achievement && ((achievement->requiredFaction == ACHIEVEMENT_FACTION_HORDE && referencePlayer->GetTeam() != HORDE) || (achievement->requiredFaction == ACHIEVEMENT_FACTION_ALLIANCE && referencePlayer->GetTeam() != ALLIANCE))) { TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Wrong faction", criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type)); return false; } if (IsCompletedCriteria(criteria)) { TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Is Completed", criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type)); return false; } if (!RequirementsSatisfied(criteria, miscValue1, miscValue2, miscValue3, unit, referencePlayer)) { TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Requirements not satisfied", criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type)); return false; } if (!AdditionalRequirementsSatisfied(criteria, miscValue1, miscValue2, unit, referencePlayer)) { TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Additional requirements not satisfied", criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type)); return false; } if (!ConditionsSatisfied(criteria, referencePlayer)) { TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Conditions not satisfied", criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type)); return false; } return true; } template<class T> bool AchievementMgr<T>::ConditionsSatisfied(CriteriaEntry const* criteria, Player* referencePlayer) const { /* for (uint32 i = 0; i < MAX_CRITERIA_REQUIREMENTS; ++i) { if (!criteria->additionalRequirements[i].additionalRequirement_type) continue; switch (criteria->additionalRequirements[i].additionalRequirement_type) { case ACHIEVEMENT_CRITERIA_CONDITION_BG_MAP: if (referencePlayer->GetMapId() != criteria->additionalRequirements[i].additionalRequirement_value) return false; break; case ACHIEVEMENT_CRITERIA_CONDITION_NOT_IN_GROUP: if (referencePlayer->GetGroup()) return false; break; default: break; } } */ return true; } template<class T> bool AchievementMgr<T>::RequirementsSatisfied(CriteriaEntry const* achievementCriteria, uint64 miscValue1, uint64 miscValue2, uint64 miscValue3, Unit const* unit, Player* referencePlayer) const { switch (AchievementCriteriaTypes(achievementCriteria->type)) { case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST: case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION: case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING: case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN: case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS: case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS: case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER: case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL: case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS: case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED: case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL: case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY: case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL: case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD: case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS: case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS: case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED: case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL: case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED: case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED: case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL: case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED: case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED: case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS: case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP: case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL: case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA: case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS: if (!miscValue1) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY: case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT: case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE: case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS: case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION: case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION: case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING: case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS: case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL: break; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT: if (m_completedAchievements.find(achievementCriteria->complete_achievement.linkedAchievement) == m_completedAchievements.end()) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG: if (!miscValue1 || achievementCriteria->win_bg.bgMapID != referencePlayer->GetMapId()) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE: if (!miscValue1 || achievementCriteria->kill_creature.creatureID != miscValue1) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL: // update at loading or specific skill update if (miscValue1 && miscValue1 != achievementCriteria->reach_skill_level.skillID) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL: // update at loading or specific skill update if (miscValue1 && miscValue1 != achievementCriteria->learn_skill_level.skillID) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE: if (miscValue1 && miscValue1 != achievementCriteria->complete_quests_in_zone.zoneID) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND: if (!miscValue1 || referencePlayer->GetMapId() != achievementCriteria->complete_battleground.mapID) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP: if (!miscValue1 || referencePlayer->GetMapId() != achievementCriteria->death_at_map.mapID) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_DEATH: { if (!miscValue1) return false; // skip wrong arena achievements, if not achievIdByArenaSlot then normal total death counter /*bool notfit = false; for (int j = 0; j < MAX_ARENA_SLOT; ++j) { if (achievIdByArenaSlot[j] == achievementCriteria->achievement) { Battleground* bg = referencePlayer->GetBattleground(); if (!bg || !bg->IsArena() || RatedInfo::GetRatedSlotByType(bg->GetRatedType()) != j) notfit = true; break; } } if (notfit) return false;*/ break; } case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON: { if (!miscValue1) return false; /* Map const* map = referencePlayer->IsInWorld() ? referencePlayer->GetMap() : sMapMgr->FindMap(referencePlayer->GetMapId(), referencePlayer->GetInstanceId()); if (!map || !map->IsDungeon()) return false; // search case bool found = false; for (int j = 0; achievIdForDungeon[j][0]; ++j) { if (achievIdForDungeon[j][0] == achievementCriteria->achievement) { if (map->IsRaid()) { // if raid accepted (ignore difficulty) if (!achievIdForDungeon[j][2]) break; // for } else if (referencePlayer->GetDungeonDifficulty() == DUNGEON_DIFFICULTY_NORMAL) { // dungeon in normal mode accepted if (!achievIdForDungeon[j][1]) break; // for } else { // dungeon in heroic mode accepted if (!achievIdForDungeon[j][3]) break; // for } found = true; break; // for } } if (!found) return false; //FIXME: work only for instances where max == min for players if (((InstanceMap*)map)->GetMaxPlayers() != achievementCriteria->death_in_dungeon.manLimit) return false; */ return false; } case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE: if (!miscValue1 || miscValue1 != achievementCriteria->killed_by_creature.creatureEntry) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER: if (!miscValue1 || !unit || unit->GetTypeId() != TYPEID_PLAYER) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM: if (!miscValue1 || miscValue2 != achievementCriteria->death_from.type) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: { // if miscValues != 0, it contains the questID. if (miscValue1) { if (miscValue1 != achievementCriteria->complete_quest.questID) return false; } else { // login case. if (!referencePlayer->GetQuestRewardStatus(achievementCriteria->complete_quest.questID)) return false; } if (AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria)) if (!data->Meets(referencePlayer, unit)) return false; break; } case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET: case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2: if (!miscValue1 || miscValue1 != achievementCriteria->be_spell_target.spellID) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL: case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2: if (!miscValue1 || miscValue1 != achievementCriteria->cast_spell.spellID) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL: if (miscValue1 && miscValue1 != achievementCriteria->learn_spell.spellID) return false; if (!referencePlayer->HasSpell(achievementCriteria->learn_spell.spellID)) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE: // miscValue1 = itemId - miscValue2 = count of item loot // miscValue3 = loot_type (note: 0 = LOOT_CORPSE and then it ignored) if (!miscValue1 || !miscValue2 || !miscValue3 || miscValue3 != achievementCriteria->loot_type.lootType) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM: if (miscValue1 && achievementCriteria->own_item.itemID != miscValue1) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM: if (!miscValue1 || achievementCriteria->use_item.itemID != miscValue1) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM: if (!miscValue1 || miscValue1 != achievementCriteria->own_item.itemID) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA: { WorldMapOverlayEntry const* worldOverlayEntry = sWorldMapOverlayStore.LookupEntry(achievementCriteria->explore_area.areaReference); if (!worldOverlayEntry) break; bool matchFound = false; for (int j = 0; j < MAX_WORLD_MAP_OVERLAY_AREA_IDX; ++j) { uint32 area_id = worldOverlayEntry->areatableID[j]; if (!area_id) // array have 0 only in empty tail break; int32 exploreFlag = GetAreaFlagByAreaID(area_id); if (exploreFlag < 0) continue; uint32 playerIndexOffset = uint32(exploreFlag) / 32; uint32 mask = 1 << (uint32(exploreFlag) % 32); if (referencePlayer->GetUInt32Value(PLAYER_FIELD_EXPLORED_ZONES + playerIndexOffset) & mask) { matchFound = true; break; } } if (!matchFound) return false; break; } case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION: if (miscValue1 && miscValue1 != achievementCriteria->gain_reputation.factionID) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM: // miscValue1 = itemid miscValue2 = itemSlot if (!miscValue1 || miscValue2 != achievementCriteria->equip_epic_item.itemSlot) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT: case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT: { // miscValue1 = itemid miscValue2 = diced value if (!miscValue1 || miscValue2 != achievementCriteria->roll_greed_on_loot.rollValue) return false; ItemTemplate const* proto = sObjectMgr->GetItemTemplate(uint32(miscValue1)); if (!proto) return false; break; } case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE: if (!miscValue1 || miscValue1 != achievementCriteria->do_emote.emoteID) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE: case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE: if (!miscValue1) return false; // map specific case (BG in fact) expected player targeted damage/heal if (!unit || unit->GetTypeId() != TYPEID_PLAYER) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM: // miscValue1 = item_id if (!miscValue1 || miscValue1 != achievementCriteria->equip_item.itemID) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT: if (!miscValue1 || miscValue1 != achievementCriteria->use_gameobject.goEntry) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT: if (!miscValue1 || miscValue1 != achievementCriteria->fish_in_gameobject.goEntry) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS: if (miscValue1 && miscValue1 != achievementCriteria->learn_skillline_spell.skillLine) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM: case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM: { if (!miscValue1) return false; ItemTemplate const* proto = sObjectMgr->GetItemTemplate(uint32(miscValue1)); if (!proto || proto->Quality < ITEM_QUALITY_EPIC) return false; break; } case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE: if (miscValue1 && miscValue1 != achievementCriteria->learn_skill_line.skillLine) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS: if (!miscValue1 || miscValue1 != achievementCriteria->hk_class.classID) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE: if (!miscValue1 || miscValue1 != achievementCriteria->hk_race.raceID) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE: if (!miscValue1 || miscValue1 != achievementCriteria->bg_objective.objectiveId) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA: if (!miscValue1 || miscValue1 != achievementCriteria->honorable_kill_at_area.areaID) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY: if (!miscValue1 || !miscValue2 || int64(miscValue2) < 0 || miscValue1 != achievementCriteria->currencyGain.currency) return false; break; case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA: if (miscValue1 != achievementCriteria->win_arena.mapID) return false; break; default: break; } return true; } template<class T> bool AchievementMgr<T>::AdditionalRequirementsSatisfied(CriteriaEntry const* criteria, uint64 miscValue1, uint64 miscValue2, Unit const* unit, Player* referencePlayer) const { ModifierTreeEntry const* condition = sModifierTreeStore.LookupEntry(criteria->modifierTreeId); if (!condition) return true; ModifierTreeEntryList const* list = sAchievementMgr->GetModifierTreeByModifierId(condition->ID); if (!list) return true; for (ModifierTreeEntryList::const_iterator iter = list->begin(); iter != list->end(); iter++) { ModifierTreeEntry const* tree = (*iter); uint32 reqType = tree->conditionType; uint32 reqValue = tree->conditionValue[0]; switch (AchievementCriteriaAdditionalCondition(reqType)) { case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_ENTRY: // 4 if (!unit || unit->GetEntry() != reqValue) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_PLAYER: // 5 if (!unit || unit->GetTypeId() != TYPEID_PLAYER) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_DEAD: // 6 if (!unit || unit->IsAlive()) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_ENEMY: // 7 if (!unit || !referencePlayer->IsHostileTo(unit)) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_HAS_AURA: // 8 if (!referencePlayer->HasAura(reqValue)) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HAS_AURA: // 10 if (!unit || !unit->HasAura(reqValue)) return false; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HAS_AURA_TYPE: // 11 if (!unit || !unit->HasAuraType(AuraType(reqValue))) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_MIN: // 14 { // miscValue1 is itemid ItemTemplate const* const item = sObjectMgr->GetItemTemplate(uint32(miscValue1)); if (!item || item->Quality < reqValue) return false; break; } case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_EQUALS: // 15 { // miscValue1 is itemid ItemTemplate const* const item = sObjectMgr->GetItemTemplate(uint32(miscValue1)); if (!item || item->Quality != reqValue) return false; break; } case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_AREA_OR_ZONE: // 17 { uint32 zoneId, areaId; referencePlayer->GetZoneAndAreaId(zoneId, areaId); if (zoneId != reqValue && areaId != reqValue) return false; break; } case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_AREA_OR_ZONE: // 18 { if (!unit) return false; uint32 zoneId, areaId; unit->GetZoneAndAreaId(zoneId, areaId); if (zoneId != reqValue && areaId != reqValue) return false; break; } case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAP_DIFFICULTY: // 20 if (uint32(referencePlayer->GetMap()->GetDifficulty()) != reqValue) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_RACE: // 25 if (referencePlayer->getRace() != reqValue) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_CLASS: // 26 if (referencePlayer->getClass() != reqValue) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_RACE: // 27 if (!unit || unit->GetTypeId() != TYPEID_PLAYER || unit->getRace() != reqValue) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CLASS: // 28 if (!unit || unit->GetTypeId() != TYPEID_PLAYER || unit->getClass() != reqValue) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAX_GROUP_MEMBERS: // 29 if (referencePlayer->GetGroup() && referencePlayer->GetGroup()->GetMembersCount() >= reqValue) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_TYPE: // 30 { if (!unit) return false; Creature const* const creature = unit->ToCreature(); if (!creature || creature->GetCreatureType() != reqValue) return false; break; } case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_MAP: // 32 if (referencePlayer->GetMapId() != reqValue) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TITLE_BIT_INDEX: // 38 // miscValue1 is title's bit index if (miscValue1 != reqValue) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_LEVEL: // 39 if (referencePlayer->getLevel() != reqValue) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_LEVEL: // 40 if (!unit || unit->getLevel() != reqValue) return false; break; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_ZONE: // 41 if (!unit || unit->GetZoneId() != reqValue) return false; case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HEALTH_PERCENT_BELOW: // 46 if (!unit || unit->GetHealthPct() >= reqValue) return false; break; default: break; } } return true; } char const* AchievementGlobalMgr::GetCriteriaTypeString(uint32 type) { return GetCriteriaTypeString(AchievementCriteriaTypes(type)); } char const* AchievementGlobalMgr::GetCriteriaTypeString(AchievementCriteriaTypes type) { switch (type) { case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE: return "KILL_CREATURE"; case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG: return "TYPE_WIN_BG"; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ARCHAEOLOGY_PROJECTS: return "COMPLETE_RESEARCH"; case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL: return "REACH_LEVEL"; case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL: return "REACH_SKILL_LEVEL"; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT: return "COMPLETE_ACHIEVEMENT"; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT: return "COMPLETE_QUEST_COUNT"; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY: return "COMPLETE_DAILY_QUEST_DAILY"; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE: return "COMPLETE_QUESTS_IN_ZONE"; case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY: return "CURRENCY"; case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE: return "DAMAGE_DONE"; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST: return "COMPLETE_DAILY_QUEST"; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND: return "COMPLETE_BATTLEGROUND"; case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP: return "DEATH_AT_MAP"; case ACHIEVEMENT_CRITERIA_TYPE_DEATH: return "DEATH"; case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON: return "DEATH_IN_DUNGEON"; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_RAID: return "COMPLETE_RAID"; case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE: return "KILLED_BY_CREATURE"; case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER: return "KILLED_BY_PLAYER"; case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING: return "FALL_WITHOUT_DYING"; case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM: return "DEATHS_FROM"; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: return "COMPLETE_QUEST"; case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET: return "BE_SPELL_TARGET"; case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL: return "CAST_SPELL"; case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE: return "BG_OBJECTIVE_CAPTURE"; case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA: return "HONORABLE_KILL_AT_AREA"; case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA: return "WIN_ARENA"; case ACHIEVEMENT_CRITERIA_TYPE_PLAY_ARENA: return "PLAY_ARENA"; case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL: return "LEARN_SPELL"; case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL: return "HONORABLE_KILL"; case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM: return "OWN_ITEM"; case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA: return "WIN_RATED_ARENA"; case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING: return "HIGHEST_TEAM_RATING"; case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING: return "HIGHEST_PERSONAL_RATING"; case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL: return "LEARN_SKILL_LEVEL"; case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM: return "USE_ITEM"; case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM: return "LOOT_ITEM"; case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA: return "EXPLORE_AREA"; case ACHIEVEMENT_CRITERIA_TYPE_OWN_RANK: return "OWN_RANK"; case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT: return "BUY_BANK_SLOT"; case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION: return "GAIN_REPUTATION"; case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION: return "GAIN_EXALTED_REPUTATION"; case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP: return "VISIT_BARBER_SHOP"; case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM: return "EQUIP_EPIC_ITEM"; case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT: return "ROLL_NEED_ON_LOOT"; case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT: return "GREED_ON_LOOT"; case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS: return "HK_CLASS"; case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE: return "HK_RACE"; case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE: return "DO_EMOTE"; case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE: return "HEALING_DONE"; case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS: return "GET_KILLING_BLOWS"; case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM: return "EQUIP_ITEM"; case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS: return "MONEY_FROM_VENDORS"; case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS: return "GOLD_SPENT_FOR_TALENTS"; case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS: return "NUMBER_OF_TALENT_RESETS"; case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD: return "MONEY_FROM_QUEST_REWARD"; case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING: return "GOLD_SPENT_FOR_TRAVELLING"; case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER: return "GOLD_SPENT_AT_BARBER"; case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL: return "GOLD_SPENT_FOR_MAIL"; case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY: return "LOOT_MONEY"; case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT: return "USE_GAMEOBJECT"; case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2: return "BE_SPELL_TARGET2"; case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL: return "SPECIAL_PVP_KILL"; case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT: return "FISH_IN_GAMEOBJECT"; case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE: return "EARNED_PVP_TITLE"; case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS: return "LEARN_SKILLLINE_SPELLS"; case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL: return "WIN_DUEL"; case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL: return "LOSE_DUEL"; case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE: return "KILL_CREATURE_TYPE"; case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS: return "GOLD_EARNED_BY_AUCTIONS"; case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION: return "CREATE_AUCTION"; case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID: return "HIGHEST_AUCTION_BID"; case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS: return "WON_AUCTIONS"; case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD: return "HIGHEST_AUCTION_SOLD"; case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED: return "HIGHEST_GOLD_VALUE_OWNED"; case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION: return "GAIN_REVERED_REPUTATION"; case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION: return "GAIN_HONORED_REPUTATION"; case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS: return "KNOWN_FACTIONS"; case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM: return "LOOT_EPIC_ITEM"; case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM: return "RECEIVE_EPIC_ITEM"; case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED: return "ROLL_NEED"; case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED: return "ROLL_GREED"; case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT: return "HIT_DEALT"; case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED: return "HIT_RECEIVED"; case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED: return "TOTAL_DAMAGE_RECEIVED"; case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED: return "HIGHEST_HEAL_CASTED"; case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED: return "TOTAL_HEALING_RECEIVED"; case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED: return "HIGHEST_HEALING_RECEIVED"; case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED: return "QUEST_ABANDONED"; case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN: return "FLIGHT_PATHS_TAKEN"; case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE: return "LOOT_TYPE"; case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2: return "CAST_SPELL2"; case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE: return "LEARN_SKILL_LINE"; case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL: return "EARN_HONORABLE_KILL"; case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS: return "ACCEPTED_SUMMONINGS"; case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS: return "EARN_ACHIEVEMENT_POINTS"; case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS: return "USE_LFD_TO_GROUP_WITH_PLAYERS"; case ACHIEVEMENT_CRITERIA_TYPE_SPENT_GOLD_GUILD_REPAIRS: return "SPENT_GOLD_GUILD_REPAIRS"; case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL: return "REACH_GUILD_LEVEL"; case ACHIEVEMENT_CRITERIA_TYPE_CRAFT_ITEMS_GUILD: return "CRAFT_ITEMS_GUILD"; case ACHIEVEMENT_CRITERIA_TYPE_CATCH_FROM_POOL: return "CATCH_FROM_POOL"; case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_BANK_SLOTS: return "BUY_GUILD_BANK_SLOTS"; case ACHIEVEMENT_CRITERIA_TYPE_EARN_GUILD_ACHIEVEMENT_POINTS: return "EARN_GUILD_ACHIEVEMENT_POINTS"; case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_BATTLEGROUND: return "WIN_RATED_BATTLEGROUND"; case ACHIEVEMENT_CRITERIA_TYPE_REACH_BG_RATING: return "REACH_BG_RATING"; case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_TABARD: return "BUY_GUILD_TABARD"; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_GUILD: return "COMPLETE_QUESTS_GUILD"; case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILLS_GUILD: return "HONORABLE_KILLS_GUILD"; case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE_GUILD: return "KILL_CREATURE_TYPE_GUILD"; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE_TYPE: return "GUILD_CHALLENGE_TYPE"; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE: return "GUILD_CHALLENGE"; } return "MISSING_TYPE"; } template class AchievementMgr<Guild>; template class AchievementMgr<Player>; //========================================================== void AchievementGlobalMgr::LoadAchievementCriteriaList() { uint32 oldMSTime = getMSTime(); if (sCriteriaStore.GetNumRows() == 0) { TC_LOG_ERROR("server.loading", ">> Loaded 0 achievement criteria."); return; } for (uint32 entryId = 0; entryId < sCriteriaTreeStore.GetNumRows(); entryId++) { CriteriaTreeEntry const* criteriaTree = sCriteriaTreeStore.LookupEntry(entryId); if (!criteriaTree) continue; if (CriteriaTreeEntry const* parent = sCriteriaTreeStore.LookupEntry(criteriaTree->parentID)) m_SubCriteriaTreeListById[parent->ID].push_back(criteriaTree); ModifierTreeEntryByTreeId m_ModifierTreeEntryByTreeId; CriteriaEntry const* criteriaEntry = sCriteriaStore.LookupEntry(criteriaTree->criteriaID); if (!criteriaEntry) continue; m_AchievementCriteriaTreeByCriteriaId[criteriaEntry->ID].push_back(criteriaTree); } for (uint32 entryId = 0; entryId < sModifierTreeStore.GetNumRows(); entryId++) { ModifierTreeEntry const* modifier = sModifierTreeStore.LookupEntry(entryId); if (!modifier) continue; if (modifier->parent) m_ModifierTreeEntryByTreeId[modifier->parent].push_back(modifier); } uint32 criterias = 0; for (uint32 entryId = 0; entryId < sCriteriaStore.GetNumRows(); entryId++) { CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(entryId); if (!criteria) continue; m_AchievementCriteriasByType[criteria->type].push_back(criteria); if (criteria->timeLimit) m_AchievementCriteriasByTimedType[criteria->timedCriteriaStartType].push_back(criteria); } TC_LOG_INFO("server.loading", ">> Loaded %u achievement criteria in %u ms", ++criterias, GetMSTimeDiffToNow(oldMSTime)); } void AchievementGlobalMgr::LoadAchievementReferenceList() { uint32 oldMSTime = getMSTime(); if (sAchievementStore.GetNumRows() == 0) { TC_LOG_INFO("server.loading", ">> Loaded 0 achievement references."); return; } uint32 count = 0; for (uint32 entryId = 0; entryId < sAchievementStore.GetNumRows(); ++entryId) { AchievementEntry const* achievement = sAchievementMgr->GetAchievement(entryId); if (!achievement) continue; m_AchievementEntryByCriteriaTree[achievement->criteriaTreeID] = achievement; if (!achievement->refAchievement) continue; m_AchievementListByReferencedId[achievement->refAchievement].push_back(achievement); ++count; } // Once Bitten, Twice Shy (10 player) - Icecrown Citadel if (AchievementEntry const* achievement = sAchievementMgr->GetAchievement(4539)) const_cast<AchievementEntry*>(achievement)->mapID = 631; // Correct map requirement (currently has Ulduar) TC_LOG_INFO("server.loading", ">> Loaded %u achievement references in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } void AchievementGlobalMgr::LoadAchievementCriteriaData() { uint32 oldMSTime = getMSTime(); m_criteriaDataMap.clear(); // need for reload case QueryResult result = WorldDatabase.Query("SELECT criteria_id, type, value1, value2, ScriptName FROM achievement_criteria_data"); if (!result) { TC_LOG_INFO("server.loading", ">> Loaded 0 additional achievement criteria data. DB table `achievement_criteria_data` is empty."); return; } uint32 count = 0; do { Field* fields = result->Fetch(); uint32 criteria_id = fields[0].GetUInt32(); CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(criteria_id); if (!criteria) { TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` has data for non-existing criteria (Entry: %u), ignore.", criteria_id); continue; } uint32 dataType = fields[1].GetUInt8(); std::string scriptName = fields[4].GetString(); uint32 scriptId = 0; if (scriptName.length()) // not empty { if (dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT) TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` has ScriptName set for non-scripted data type (Entry: %u, type %u), useless data.", criteria_id, dataType); else scriptId = sObjectMgr->GetScriptId(scriptName.c_str()); } AchievementCriteriaData data(dataType, fields[2].GetUInt32(), fields[3].GetUInt32(), scriptId); if (!data.IsValid(criteria)) continue; // this will allocate empty data set storage AchievementCriteriaDataSet& dataSet = m_criteriaDataMap[criteria_id]; dataSet.SetCriteriaId(criteria_id); // add real data only for not NONE data types if (data.dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE) dataSet.Add(data); // counting data by and data types ++count; } while (result->NextRow()); TC_LOG_INFO("server.loading", ">> Loaded %u additional achievement criteria data in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } void AchievementGlobalMgr::LoadCompletedAchievements() { uint32 oldMSTime = getMSTime(); QueryResult result = CharacterDatabase.Query("SELECT achievement FROM character_achievement GROUP BY achievement"); if (!result) { TC_LOG_INFO("server.loading", ">> Loaded 0 realm first completed achievements. DB table `character_achievement` is empty."); return; } do { Field* fields = result->Fetch(); uint16 achievementId = fields[0].GetUInt16(); const AchievementEntry* achievement = sAchievementMgr->GetAchievement(achievementId); if (!achievement) { // Remove non existent achievements from all characters TC_LOG_ERROR("achievement", "Non-existing achievement %u data removed from table `character_achievement`.", achievementId); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEVMENT); stmt->setUInt16(0, uint16(achievementId)); CharacterDatabase.Execute(stmt); continue; } else if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL)) m_allCompletedAchievements.insert(achievementId); } while (result->NextRow()); TC_LOG_INFO("server.loading", ">> Loaded %lu realm first completed achievements in %u ms", (unsigned long)m_allCompletedAchievements.size(), GetMSTimeDiffToNow(oldMSTime)); } void AchievementGlobalMgr::LoadRewards() { uint32 oldMSTime = getMSTime(); m_achievementRewards.clear(); // need for reload case // 0 1 2 3 4 5 6 QueryResult result = WorldDatabase.Query("SELECT entry, title_A, title_H, item, sender, subject, text FROM achievement_reward"); if (!result) { TC_LOG_ERROR("server.loading", ">> Loaded 0 achievement rewards. DB table `achievement_reward` is empty."); return; } uint32 count = 0; do { Field* fields = result->Fetch(); uint32 entry = fields[0].GetUInt32(); const AchievementEntry* pAchievement = GetAchievement(entry); if (!pAchievement) { TC_LOG_ERROR("sql.sql", "Table `achievement_reward` has wrong achievement (Entry: %u), ignored.", entry); continue; } AchievementReward reward; reward.titleId[0] = fields[1].GetUInt32(); reward.titleId[1] = fields[2].GetUInt32(); reward.itemId = fields[3].GetUInt32(); reward.sender = fields[4].GetUInt32(); reward.subject = fields[5].GetString(); reward.text = fields[6].GetString(); // must be title or mail at least if (!reward.titleId[0] && !reward.titleId[1] && !reward.sender) { TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have title or item reward data, ignored.", entry); continue; } if (pAchievement->requiredFaction == ACHIEVEMENT_FACTION_ANY && ((reward.titleId[0] == 0) != (reward.titleId[1] == 0))) TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has title (A: %u H: %u) for only one team.", entry, reward.titleId[0], reward.titleId[1]); if (reward.titleId[0]) { CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(reward.titleId[0]); if (!titleEntry) { TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid title id (%u) in `title_A`, set to 0", entry, reward.titleId[0]); reward.titleId[0] = 0; } } if (reward.titleId[1]) { CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(reward.titleId[1]); if (!titleEntry) { TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid title id (%u) in `title_H`, set to 0", entry, reward.titleId[1]); reward.titleId[1] = 0; } } //check mail data before item for report including wrong item case if (reward.sender) { if (!sObjectMgr->GetCreatureTemplate(reward.sender)) { TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid creature entry %u as sender, mail reward skipped.", entry, reward.sender); reward.sender = 0; } } else { if (reward.itemId) TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data but has item reward, item will not be rewarded.", entry); if (!reward.subject.empty()) TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data but has mail subject.", entry); if (!reward.text.empty()) TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data but has mail text.", entry); } if (reward.itemId) { if (!sObjectMgr->GetItemTemplate(reward.itemId)) { TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid item id %u, reward mail will not contain item.", entry, reward.itemId); reward.itemId = 0; } } m_achievementRewards[entry] = reward; ++count; } while (result->NextRow()); TC_LOG_INFO("server.loading", ">> Loaded %u achievement rewards in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } void AchievementGlobalMgr::LoadRewardLocales() { uint32 oldMSTime = getMSTime(); m_achievementRewardLocales.clear(); // need for reload case QueryResult result = WorldDatabase.Query("SELECT entry, subject_loc1, text_loc1, subject_loc2, text_loc2, subject_loc3, text_loc3, subject_loc4, text_loc4, " "subject_loc5, text_loc5, subject_loc6, text_loc6, subject_loc7, text_loc7, subject_loc8, text_loc8, " "subject_loc9, text_loc9, subject_loc10, text_loc10, subject_loc11, text_loc11 " " FROM locales_achievement_reward"); if (!result) { TC_LOG_INFO("server.loading", ">> Loaded 0 achievement reward locale strings. DB table `locales_achievement_reward` is empty"); return; } do { Field* fields = result->Fetch(); uint32 entry = fields[0].GetUInt32(); if (m_achievementRewards.find(entry) == m_achievementRewards.end()) { TC_LOG_ERROR("sql.sql", "Table `locales_achievement_reward` (Entry: %u) has locale strings for non-existing achievement reward.", entry); continue; } AchievementRewardLocale& data = m_achievementRewardLocales[entry]; for (int i = 1; i < TOTAL_LOCALES; ++i) { LocaleConstant locale = (LocaleConstant) i; ObjectMgr::AddLocaleString(fields[1 + 2 * (i - 1)].GetString(), locale, data.subject); ObjectMgr::AddLocaleString(fields[1 + 2 * (i - 1) + 1].GetString(), locale, data.text); } } while (result->NextRow()); TC_LOG_INFO("server.loading", ">> Loaded %lu achievement reward locale strings in %u ms", (unsigned long)m_achievementRewardLocales.size(), GetMSTimeDiffToNow(oldMSTime)); } AchievementEntry const* AchievementGlobalMgr::GetAchievement(uint32 achievementId) const { return sAchievementStore.LookupEntry(achievementId); } CriteriaEntry const* AchievementGlobalMgr::GetAchievementCriteria(uint32 criteriaId) const { return sCriteriaStore.LookupEntry(criteriaId); }
gpl-2.0
intelie/esper
esper/src/test/java/com/espertech/esper/regression/client/MyFlushedSimpleView.java
2548
/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.regression.client; import com.espertech.esper.core.StatementContext; import com.espertech.esper.client.EventBean; import com.espertech.esper.client.EventType; import com.espertech.esper.view.StatementStopCallback; import com.espertech.esper.view.View; import com.espertech.esper.view.ViewSupport; import com.espertech.esper.view.Viewable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class MyFlushedSimpleView extends ViewSupport implements StatementStopCallback { private List<EventBean> events; private EventType eventType; public MyFlushedSimpleView(StatementContext statementContext) { statementContext.getStatementStopService().addSubscriber(this); events = new ArrayList<EventBean>(); } public void statementStopped() { this.updateChildren(events.toArray(new EventBean[0]), null); events = new ArrayList<EventBean>(); } public void setParent(Viewable parent) { super.setParent(parent); eventType = parent.getEventType(); } public View cloneView(StatementContext statementContext) { return new MyFlushedSimpleView(statementContext); } public final void update(EventBean[] newData, EventBean[] oldData) { if (newData != null) { for (int i = 0; i < newData.length; i++) { events.add(newData[0]); } } } public final EventType getEventType() { return eventType; } public final Iterator<EventBean> iterator() { return events.iterator(); } public final String toString() { return this.getClass().getName(); } }
gpl-2.0
CoordCulturaDigital-Minc/culturadigital.br
wp-content/plugins/db-cache/languages/uk_UA.php
2382
<?php /* Version 0.5 */ $dbc_labels['configuration'] = "Налаштування"; $dbc_labels['activate'] = "Увімкнути"; $dbc_labels['timeout'] = "Час життя кешу"; $dbc_labels['timeout_desc'] = "хвилин(и). <em>(Застарілі файли видаляються автоматично)</em>"; $dbc_labels['tablesfilter'] = "Таблиці для кешування"; $dbc_labels['saved'] = "Налаштування збережено."; $dbc_labels['cantsave'] = "Налаштування не може бути збережено. Будь-ласка <a href=\"http://codex.wordpress.org/Changing_File_Permissions\" target=\"blank\">встановіть права запису</a> для файла <u>config.ini</u>"; $dbc_labels['activated'] = "Кешування увімкнено."; $dbc_labels['notactivated'] = "Кешування не ввімкнено. Будь-ласка <a href=\"http://codex.wordpress.org/Changing_File_Permissions\" target=\"blank\">встановіть права запису</a> для папки <u>wp-content</u>"; $dbc_labels['deactivated'] = "Кешування вимкнено. Всі файли кешу видалені."; $dbc_labels['cleaned'] = "Файли кешу видалені."; $dbc_labels['expiredcleaned'] = "Застарілі файли кешу видалені."; $dbc_labels['additional'] = "Додаткові параметри"; $dbc_labels['loadstat'] = "Шаблон виводу статистики"; $dbc_labels['loadstattemplate'] = "<!-- Згенеровано за {timer} секунд. Виконано {queries} запитів до БД та {cached} кешованих запитів. Використано {memory} пам'яті -->"; $dbc_labels['loadstatdescription'] = "Налаштування показу статистики використання ресурсів в футері вашого шаблону. Щоб вимкнути - залиште це поле порожнім.<br/> {timer} - час генерації, {queries} - кількість запитів, {cached} - кешовані запити, {memory} - пам`ять"; $dbc_labels['save'] = "Зберегти"; $dbc_labels['clear'] = "Очистити кеш"; $dbc_labels['clearold'] = "Видалити застарілі файли кешу"; ?>
gpl-2.0
lucianobagattin/Sitio1
wp-content/themes/dt-armada/inc/shortcodes/includes/slideshow/slideshow.php
3345
<?php /** * Slideshow shortcode. * */ // File Security Check if ( ! defined( 'ABSPATH' ) ) { exit; } /** * Shortcode slideshow class. * */ class DT_Shortcode_Slideshow extends DT_Shortcode { static protected $instance; protected $shortcode_name = 'dt_slideshow'; protected $plugin_name = 'dt_mce_plugin_shortcode_slideshow'; public static function get_instance() { if ( !self::$instance ) { self::$instance = new DT_Shortcode_Slideshow(); } return self::$instance; } protected function __construct() { add_shortcode( $this->shortcode_name, array($this, 'shortcode') ); // add shortcode button $tinymce_button = new DT_ADD_MCE_BUTTON( $this->plugin_name, basename(dirname(__FILE__)), false, 4 ); } public function shortcode( $atts, $content = null ) { extract( shortcode_atts( array( 'posts' => '', 'width' => '800', 'height' => '450' ), $atts ) ); // sanitize attributes $width = absint( $width ); $height = absint( $height ); $posts = array_map( 'trim', explode(',', $posts) ); $attachments_id = array(); $selected_posts_titles = array(); if ( $posts ) { // get posts by slug foreach ( $posts as $post_slug ) { $args = array( 'no_found_rows' => 1, 'ignore_sticky_posts' => 1, 'posts_per_page' => 1, 'post_type' => 'dt_slideshow', 'post_status' => 'publish', 'name' => $post_slug ); $dt_query = new WP_Query( $args ); if ( $dt_query->have_posts() ) { $dt_post = $dt_query->posts[0]; $selected_posts_titles[] = get_the_title( $dt_post ); $slides_id = get_post_meta( $dt_post->ID, '_dt_slider_media_items', true ); if ( $slides_id ) { $attachments_id = array_merge( $attachments_id, $slides_id ); } } } // get fresh one } else { $args = array( 'no_found_rows' => 1, 'ignore_sticky_posts' => 1, 'posts_per_page' => 1, 'post_type' => 'dt_slideshow', 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC' ); $dt_query = new WP_Query( $args ); if ( $dt_query->have_posts() ) { $dt_post = $dt_query->posts[0]; $selected_posts_titles[] = get_the_title( $dt_post ); $slides_id = get_post_meta( $dt_post->ID, '_dt_slider_media_items', true ); if ( $slides_id ) { $attachments_id = array_merge( $attachments_id, $slides_id ); } } } if ( function_exists('vc_is_inline') && vc_is_inline() ) { if ( empty($selected_posts_titles) ) { $dummy_posts_titles = __( 'No posts selected', LANGUAGE_ZONE ); } else { $dummy_posts_titles = esc_html( join( ', ', $selected_posts_titles ) ); } $output = ' <div class="dt_vc-shortcode_dummy dt_vc-royal_slider" style="height: 250px;"> <h5>Royal slider</h4> <p class="text-small"><strong>Display slider(s):</strong> ' . $dummy_posts_titles . '</p> </div> '; } else { $attachments_data = presscore_get_attachment_post_data( $attachments_id ); $output = presscore_get_royal_slider( $attachments_data, array( 'width' => $width, 'height' => $height, 'class' => array( 'slider-simple' ), 'style' => ' style="width: 100%"' ) ); } return $output; } } // create shortcode DT_Shortcode_Slideshow::get_instance();
gpl-2.0
leotaillard/lesgrandestables2015
wp-content/themes/lgtds2015/footer.php
1671
<?php /** * The template for displaying the footer * * Contains the closing of the "off-canvas-wrap" div and all content after. * * @package WordPress * @subpackage FoundationPress * @since FoundationPress 1.0.0 */ ?> </section> <div id="footer-container"> <footer id="footer"> <div class="row"> <div class="small-12 large-12 columns"> <div class="logo-footer"> <a href="<?php echo home_url(); ?>"><img src="<?php echo get_template_directory_uri(); ?>/img/logo-lgtds-footer.svg" width="224" alt="Logo des grandes tables de suisse" /></a> </div> <p>© <?php echo date('Y'); ?> Les grandes tables de suisse - All rights reserved.</p> </div> </div> </footer> <!-- Display Partners --> <?php get_template_part( 'parts/loop', 'partners' ); ?> </div> <?php if ( ! get_theme_mod( 'wpt_mobile_menu_layout' ) || get_theme_mod( 'wpt_mobile_menu_layout' ) == 'offcanvas' ) : ?> <a class="exit-off-canvas"></a> <?php endif; ?> <?php do_action( 'foundationpress_layout_end' ); ?> <?php if ( ! get_theme_mod( 'wpt_mobile_menu_layout' ) || get_theme_mod( 'wpt_mobile_menu_layout' ) == 'offcanvas' ) : ?> </div> </div> <?php endif; ?> <?php wp_footer(); ?> <?php if (is_front_page()) { ?> <script type="text/javascript"> jQuery(document).ready(function() { jQuery('.covervid-video').coverVid(1280, 720); }); </script> <?php } ?> <?php if (is_singular( 'chef' ) || is_singular( 'hotel' )) { ?> <script type="text/javascript"> jQuery(document).ready(function() { // make the youtube fit jQuery('.video').fitVids(); }); </script> <?php } ?> <?php do_action( 'foundationpress_before_closing_body' ); ?> </body> </html>
gpl-2.0
abhishek1234321/Foundation-6-Shortcodes
shortcodes/tabs/class-fn-tabs.php
2757
<?php Class FN_Tabs { public function __construct() { add_shortcode( 'fn_tabs', array( $this, 'render_parent' ) ); add_shortcode( 'fn_tab', array( $this, 'render_child' ) ); } public function render_parent( $atts, $content = null ) { $atts = shortcode_atts( array( 'id' => null, 'class' => null, 'style' => null, 'vertical' => null, ), $atts, 'fn_tabs' ); // Remove whitespaces from starting and ending of shortcode attributes $atts = array_map( 'trim', $atts ); $default_class = ' tabs '; $class = ''; if ( ! empty( $atts['id'] ) ) { $atts['id'] = ' id="' . $atts['id'] . '" '; } else { $atts['id'] = ' '; } if ( ! empty( $atts['style'] ) ) { $atts['style'] = ' style="' . $atts['style'] . '"'; } if ( 'yes' === strtolower( $atts['vertical'] ) ) { $class .= ' vertical '; } if ( ! empty( $atts['class'] ) ) { $atts['class'] = $default_class . $class . $atts['class']; } else { $atts['class'] = $default_class . $class; } $atts = preg_replace( '/\s+/', ' ', $atts ); $atts['class'] = trim( $atts['class'] ); $html = sprintf( '<ul%sclass="%s" data-tabs%s>%s</ul>', $atts['id'], $atts['class'], $atts['style'], do_shortcode( $content ) ); return $html; } public function render_child( $atts, $content = null ) { $atts = shortcode_atts( array( 'id' => null, 'class' => null, 'style' => null, 'title' => null, 'is_active' => null, ), $atts, 'fn_tab' ); // Remove whitespaces from starting and ending of shortcode attributes $atts = array_map( 'trim', $atts ); $default_class = ' tabs-title '; $class = ''; if ( ! empty( $atts['id'] ) ) { $atts['id'] = ' id="' . $atts['id'] . '" '; } else { $atts['id'] = ' '; } if ( ! empty( $atts['style'] ) ) { $atts['style'] = ' style="' . $atts['style'] . '"'; } // Return if no title is specified if ( empty( $atts['title'] ) ) { return; } if ( 'yes' === strtolower( $atts['is_active'] ) ) { $class .= ' is-active '; } if ( ! empty( $atts['class'] ) ) { $atts['class'] = $default_class . $class . $atts['class']; } else { $atts['class'] = $default_class . $class; } $atts = preg_replace( '/\s+/', ' ', $atts ); $atts['class'] = trim( $atts['class'] ); $anchor_tag = sprintf( '<a href="#" aria-selected="true">%s</a>', $atts['title'] ); $accordion_content = sprintf( '<div class="accordion-s" data-tab-s>%s</div>', do_shortcode( $content ) ); $html = sprintf( '<li%sclass="%s" data-accordion-item%s>%s</li>', $atts['id'], $atts['class'], $atts['style'], $anchor_tag . $accordion_content ); return $html; } } // new FN_Tabs();
gpl-2.0
arataa/youroomm
wp-content/themes/youroom/page.php
700
<?php /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package WordPress * @subpackage Twenty_Eleven * @since Twenty Eleven 1.0 */ get_header(); ?> <div class="yourm_wrapper"> <div class="above"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php comments_template( '', true ); ?> <?php endwhile; // end of the loop. ?> </div><!-- #above --> </div><!-- #yourm_wrapper --> <?php get_footer(); ?>
gpl-2.0
TUD-OS/M3
src/libs/rustbase/src/arch/host/serial.rs
1615
/* * Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * M3 is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details. */ use errors::{Code, Error}; use libc; static mut LOG_FD: i32 = -1; pub fn read(buf: &mut [u8]) -> Result<usize, Error> { match unsafe { libc::read(0, buf.as_mut_ptr() as *mut libc::c_void, buf.len()) } { res if res < 0 => Err(Error::new(Code::ReadFailed)), res => Ok(res as usize), } } pub fn write(buf: &[u8]) -> Result<usize, Error> { match unsafe { libc::write(LOG_FD, buf.as_ptr() as *const libc::c_void, buf.len()) } { res if res < 0 => Err(Error::new(Code::WriteFailed)), res => Ok(res as usize), } } pub fn init() { unsafe { LOG_FD = libc::open( "run/log.txt\0".as_ptr() as *const libc::c_char, if cfg!(feature = "kernel") { libc::O_WRONLY | libc::O_APPEND | libc::O_CREAT | libc::O_TRUNC } else { libc::O_WRONLY | libc::O_APPEND } ); assert!(LOG_FD != -1); } }
gpl-2.0
barbaracollignon/Autodock4.lga.MPI
*cc and *h files/gs.cc
54285
/* $Id: gs.cc,v 1.33 2009/05/20 16:08:57 rhuey Exp $ $Id: gs.cc, autodock4.lga.mpi v0.0 2010/10/10 22:55:01 collignon Exp $ AutoDock Copyright (C) 2009 The Scripps Research Institute. All rights reserved. AutoDock is a Trade Mark of The Scripps Research Institute. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif /******************************************************************** These are the methods for Global_Search and its derivations. rsh 9/95 *********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> /*time_t time(time_t *tloc); */ #include <time.h> /*time_t time(time_t *tloc); */ #include <sys/times.h> #include <math.h> #include "gs.h" #include "ranlib.h" #include "eval.h" #include "rep.h" #include "rep_constants.h" #include "assert.h" #ifdef sgi #include <ieeefp.h> #endif #ifdef sun #include <ieeefp.h> #endif #include "constants.h" #include "autocomm.h" #include "timesyshms.h" #include "writePDBQT.h" #include "qmultiply.h" extern FILE *logFile; extern class Eval evaluate; extern int sel_prop_count;//debug extern int global_ntor;//debug extern int debug;//debug //#define DEBUG //#define DEBUG2 //#define DEBUG3 //#define DEBUG_MUTATION double worst_in_window(double *window, int size) { register int i; double worst; worst = window[0]; #ifdef DEBUG2 (void)fprintf(logFile, "gs.cc/double worst_in_window(double *window, int size)_________________________\n");//debug #endif for (i=1; i<size; i++) { #ifdef DEBUG2 (void)fprintf(logFile, "gs.cc/window[%d]= %.3f\tworst= %.3f\n", i, window[i], worst);//debug #endif if (window[i]>worst) { worst = window[i]; #ifdef DEBUG2 (void)fprintf(logFile, "gs.cc/i= %d\t(window[i]>worst)\tUpdating: worst= %.3f\n", i, worst);//debug #endif } }// for i #ifdef DEBUG2 (void)fprintf(logFile, "gs.cc/Returning: worst= %.3f\n\n", worst);//debug #endif return(worst); } double avg_in_window(double *window, int size) { register int i; double mysum = 0.0, myavg = 0.0; #ifdef DEBUG2 (void)fprintf(logFile, "gs.cc/avg_in_window(double *window, int size)_________________________\n");//debug #endif for (i=0; i<size; i++) { mysum += window[i]; #ifdef DEBUG2 (void)fprintf(logFile, "gs.cc/mysum= %.3f\twindow[%d]= %.3f\n",mysum, i, window[i]);//debug #endif } myavg = mysum / size; #ifdef DEBUG2 (void)fprintf(logFile, "gs.cc/Returning: myavg= %.3f\n\n",myavg);//debug #endif return(myavg); } // Also set avg double Genetic_Algorithm::worst_this_generation(Population &pop) { register unsigned int i; double worstval, avgval; #ifdef DEBUG2 (void)fprintf(logFile, "gs.cc/worst_this_generation(Population &pop)_________________________\n"); #endif #ifdef DEBUG (void)fprintf(logFile, "gs.cc/double Genetic_Algorithm::worst_this_generation(Population &pop)\n"); #endif /* DEBUG */ avgval = worstval = pop[0].value(Normal_Eval); #ifdef DEBUG2 (void)fprintf(logFile, "gs.cc/avgval= %.3f\tworstval= %.3f\n", avgval, worstval); #endif for (i=1; i<pop.num_individuals(); i++) { avgval += pop[i].value(Normal_Eval); #ifdef DEBUG2 (void)fprintf(logFile, "gs.cc/avgval= %.3f\tpop[%d].value(Normal_Eval)= %.3f\n", avgval, i, pop[i].value(Normal_Eval)); #endif if (pop[i].value(Normal_Eval)>worstval) { worstval = pop[i].value(Normal_Eval); #ifdef DEBUG2 (void)fprintf(logFile, "gs.cc/(pop[i].value(Normal_Eval)>worstval): Updating: worstval= %.3f\n", worstval); #endif } } avg = avgval/pop.num_individuals(); #ifdef DEBUG2 (void)fprintf(logFile, "gs.cc/Returning: avg= %.3f, worstval= %.3f\n\n", avg, worstval); #endif return(worstval); } // This could be made inline Genetic_Algorithm::Genetic_Algorithm( EvalMode init_e_mode, Selection_Mode init_s_mode, Xover_Mode init_c_mode, Worst_Mode init_w_mode, int init_elitism, Real init_c_rate, Real init_m_rate, int init_window_size, unsigned int init_max_generations, unsigned int outputEveryNgens) : e_mode(init_e_mode), s_mode(init_s_mode), c_mode(init_c_mode), w_mode(init_w_mode), elitism(init_elitism), c_rate(init_c_rate), m_rate(init_m_rate), window_size(init_window_size), alpha(1.0), beta(0.0), tranStep(2.0), // 2 Angstroms quatStep( DegreesToRadians( 30.0 ) ), // 30 degrees torsStep( DegreesToRadians( 30.0 ) ), // 30 degrees low(-100), high(100), generations(0), max_generations(init_max_generations), outputEveryNgens(100), converged(0), alloc(NULL), mutation_table(NULL), ordering(NULL), m_table_size(0), worst(0.0L), avg(0.0L) { #ifdef DEBUG (void)fprintf(logFile, "gs.cc/Genetic_Algorithm::Genetic_Algorithm(EvalMode init_e_mode,...\n"); #endif /* DEBUG */ worst_window = new double[window_size]; } void Genetic_Algorithm::set_worst(Population &currentPop) { double temp = 0.0; #ifdef DEBUG (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::set_worst(Population &currentPop)\n"); #endif /* DEBUG */ worst_window[generations%window_size] = worst_this_generation(currentPop); switch(w_mode) { // Assume for this case that there's a window_size of 1 case Ever: if (generations!=0) { if (temp>worst) worst = worst_window[0]; } else { worst = worst_window[0]; } break; case OfN: if (generations>=window_size) { worst = worst_in_window(worst_window, window_size); } else { worst = worst_in_window(worst_window, generations+1); } break; case AverageOfN: if (generations>=window_size) { worst = avg_in_window(worst_window, window_size); } else { worst = avg_in_window(worst_window, generations+1); } break; default: (void)fprintf(logFile,"gs.cc/Unable to set the individual with the worst fitness!\n"); } } M_mode Genetic_Algorithm::m_type(RepType type) { #ifdef DEBUG (void)fprintf(logFile, "gs.cc/M_mode Genetic_Algorithm::m_type(RepType type)\n"); #endif /* DEBUG */ switch(type) { case T_BitV: return(BitFlip); case T_RealV: case T_CRealV: return(CauchyDev); case T_IntV: return(IUniformSub); default: (void)fprintf(logFile,"gs.cc/Unrecognized Type (The allowed types are: T_BitV, T_RealV, T_CRealV and T_IntV)!\n"); return(ERR); } } void Genetic_Algorithm::make_table(int size, Real prob) { register int i, j; double L = 0.0L; #ifdef DEBUG (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::make_table(int size=%d, Real prob=%f)\n",size, prob); #endif /* DEBUG */ #ifdef DEBUG_MUTATION (void)fprintf(logFile, "\ngs.cc/void Genetic_Algorithm::make_table(int size=%d, Real prob=%f)\n",size, prob); #endif /* DEBUG */ m_table_size = size; mutation_table = new Real[size+1]; mutation_table[0] = pow(1-prob, size); mutation_table[size] = 1; #ifdef DEBUG_MUTATION fprintf(logFile,"mutation_table[0] = %.3f\n", mutation_table[0]); fprintf(logFile,"mutation_table[%d] = %.3f\n", size,mutation_table[size]); #endif i = 1; while (i<=(int)size*prob) { L = 0.0; for (j=1; j<=i; j++) { L += log(size+1-j) - log(j); #ifdef DEBUG_MUTATION fprintf(logFile,"j= %d (size+1-j)= %d log(_)= %.4f log(j)=%.4f L= %.4f\n", j, (size+1-j), log(size+1-j), log(j), L); #endif } L += i*log(prob) + (size-i)*log(1-prob); #ifdef DEBUG_MUTATION fprintf(logFile,"j= %d (size+1-j)= %d log(_)= %.4f log(j)=%.4f L= %.4f\n", j, (size+1-j), log(size+1-j), log(j), L); #endif mutation_table[i] = mutation_table[i-1]+exp(L); #ifdef DEBUG_MUTATION fprintf(logFile,"mutation_table[%d] = %.3f\n", i, mutation_table[i]); #endif i++; } // end while #ifdef DEBUG_MUTATION fprintf(logFile,"L= %.3f exp(L)= %.3f\n", L, exp(L) ); #endif L = exp(L); for (; i<size; i++) { #ifdef DEBUG_MUTATION fprintf(logFile,"i= %d L= %.3f prob= %.3f size= %d (size+1-i)= %d i*(1-prob)= %.3f\n", i, L, prob, size, (size+1-i), i*(1-prob) ); #endif L = (L*prob*(size+1-i))/(i*(1-prob)); #ifdef DEBUG_MUTATION fprintf(logFile,"L= %.3f\n", L ); #endif mutation_table[i] = mutation_table[i-1]+L; #ifdef DEBUG_MUTATION fprintf(logFile,"mutation_table[%d] = %.3f\n", i, mutation_table[i]); #endif } #ifdef DEBUG_MUTATION // fflush(logFile); #endif } int Genetic_Algorithm::check_table(Real prob) { int low, high; #ifdef DEBUG (void)fprintf(logFile, "gs.cc/int Genetic_Algorithm::check_table(Real prob=%f)\n",prob); #endif /* DEBUG */ #ifdef DEBUG_MUTATION (void)fprintf(logFile, "\ngs.cc/int Genetic_Algorithm::check_table(Real prob=%f)\n",prob); #endif /* DEBUG */ low = 0; high = m_table_size; #ifdef DEBUG_MUTATION fprintf(logFile,"prob= %.3f low= %d high= %d\n", prob, low, high ); #endif while (high-low>1) { #ifdef DEBUG_MUTATION fprintf(logFile,"high-low= %d\n", high-low ); fprintf(logFile,"(high+low)/2= %d mutation_table[(high+low)/2]= %.3f prob= %.3f\n", (high+low)/2, mutation_table[(high+low)/2], prob ); #endif if (mutation_table[(high+low)/2]<prob) { low = (high+low)/2; #ifdef DEBUG_MUTATION fprintf(logFile,"low= %d\n", low ); #endif } else if (mutation_table[(high+low)/2]>prob) { high = (high+low)/2; #ifdef DEBUG_MUTATION fprintf(logFile,"high= %d\n", high ); #endif } else { high = low = (high+low)/2; #ifdef DEBUG_MUTATION fprintf(logFile,"low= %d high= %d\n", low, high ); #endif } } return(low); } void Genetic_Algorithm::initialize(unsigned int pop_size, unsigned int num_poss_mutations) { register unsigned int i; #ifdef DEBUG (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::initialize(unsigned int pop_size=%d, ",pop_size); (void)fprintf(logFile, "unsigned int num_poss_mutations=%d)\n",num_poss_mutations); #endif /* DEBUG */ if (alloc!=NULL) { delete [] alloc; } if (ordering!=NULL) { delete [] ordering; } if (mutation_table!=NULL) { delete [] mutation_table; } alloc = new Real[pop_size]; ordering = new unsigned int[pop_size]; for (i=0; i<pop_size; i++) { ordering[i] = i; assert(ordering[i] < pop_size);//debug alloc[i] = 1.0; // changed by gmm, 12-sep-1997. } make_table(pop_size*num_poss_mutations, m_rate); } void Genetic_Algorithm::mutate(Genotype &mutant, int gene_number) { Element tempvar; #ifdef DEBUG (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::mutate(Genotype &mutant, int gene_number=%d)\n",gene_number); #endif /* DEBUG */ #ifdef DEBUG_MUTATION (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::mutate(Genotype &mutant, int gene_number=%d)\n",gene_number); #endif /* DEBUG */ switch(m_type(mutant.gtype(gene_number))) { case BitFlip: #ifdef DEBUG_MUTATION fprintf( logFile, "case BitFlip: gene_number=%d\n", gene_number ); #endif //((unsigned char *)gene)[point] = 1 - ((unsigned char *)gene)[point]; // Read the bit tempvar = mutant.gread(gene_number); // Flip it tempvar.bit = 1 - tempvar.bit; // write it mutant.write(tempvar, gene_number); break; case CauchyDev: #ifdef DEBUG_MUTATION fprintf( logFile, "case CauchyDev: gene_number=%d\n", gene_number ); #endif // gene_numbers 3, 4, 5 and 6 correspond to the // four components of the quaternion, (x,y,z,w) if ( is_rotation_index( gene_number ) ) { #ifdef DEBUG_MUTATION fprintf( logFile, "is_rotation_index( gene_number=%d )\n", gene_number ); #endif // Mutate all four comopnents of the quaternion, (x,y,z,w) simultaneously: // Generate a uniformly-distributed quaternion Quat q_change; q_change = uniformQuat(); #ifdef DEBUG_MUTATION fprintf( logFile, "q_change -- after uniformQuat\n" ); printQuat_q( logFile, q_change ); #endif Quat q_current = mutant.readQuat(); #ifdef DEBUG_MUTATION fprintf( logFile, "q_current -- after mutant.readQuat()\n" ); printQuat_q( logFile, q_current ); #endif Quat q_new; #ifdef DEBUG_MUTATION fprintf( logFile, "q_current -- about to call qmultiply\n" ); #endif #ifdef DEBUG_QUAT #ifdef DEBUG_QUAT_PRINT pr( logFile, "DEBUG_QUAT: mutate() -- q_current\n" ); // (void) fflush(logFile); #endif // DEBUG_QUAT_PRINT // Make sure the quaternion is suitable for 3D rotation assertQuatOK( q_current ); #ifdef DEBUG_QUAT_PRINT pr( logFile, "DEBUG_QUAT: mutate() -- q_change\n" ); // (void) fflush(logFile); #endif // DEBUG_QUAT_PRINT // Make sure the quaternion is suitable for 3D rotation assertQuatOK( q_change ); #endif // DEBUG_QUAT // Multiply the quaternions, applying the rotation to the current orientation qmultiply( &q_new, &q_current, &q_change ); #ifdef DEBUG_QUAT #ifdef DEBUG_QUAT_PRINT pr( logFile, "DEBUG_QUAT: mutate() -- q_current\n" ); // (void) fflush(logFile); #endif // Make sure the quaternion is suitable for 3D rotation assertQuatOK( q_new ); #endif // DEBUG_QUAT #ifdef DEBUG_MUTATION fprintf( logFile, "q_new - after qmultiply\n" ); printQuat_q( logFile, q_new ); #endif mutant.writeQuat( q_new ); } else { // Read the real tempvar = mutant.gread(gene_number); #ifdef DEBUG_MUTATION (void)fprintf(logFile, " ---CauchyDev---\n" ); (void)fprintf(logFile, " Before mutating: tempvar= %.3f\n", tempvar.real ); (void)fprintf(logFile, " gene_number= %d\n", gene_number ); (void)fprintf(logFile, " tempvar.real += scauchy2()\n" ); #endif // Add deviate // We never vary alpha and beta, so just use the faster "scauchy2()" function: tempvar.real += scauchy2(); #ifdef DEBUG_MUTATION (void)fprintf(logFile, " Add Cauchy deviate: tempvar= %.3f\n", tempvar.real ); // (void)fflush(logFile ); #endif // Write it mutant.write(tempvar, gene_number); } break; case IUniformSub: #ifdef DEBUG_MUTATION fprintf( logFile, "case IUniformSub: gene_number=%d\n", gene_number ); #endif //((int *)gene)[point] = ignuin(low, high); // Generate the new integer tempvar.integer = ignuin(low, high); // Write it //mutant.write((void *)(&tempvar.integer), gene_number); mutant.write(tempvar, gene_number); break; default: (void)fprintf(logFile,"gs.cc/Unrecognized mutation Mode!\n"); break; } } void Genetic_Algorithm::mutation(Population &pure) { int num_mutations, individual, gene_number; #ifdef DEBUG (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::mutation(Population &pure)\n"); #endif /* DEBUG */ #ifdef DEBUG_MUTATION (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::mutation(Population &pure)\n"); #endif /* DEBUG */ num_mutations = check_table(ranf()); #ifdef DEBUG_MUTATION (void)fprintf(logFile, "num_mutations= %d\n", num_mutations ); #endif /* DEBUG */ // Note we don't check to see if we mutate the same gene twice. // So, effectively we are lowering the mutation rate, etc... // Might want to check out Bentley's chapter on selection. for (; num_mutations>0; num_mutations--) { individual = ignlgi()%pure.num_individuals(); gene_number = ignlgi()%pure[individual].genotyp.num_genes(); #ifdef DEBUG_MUTATION (void)fprintf(logFile, " @__@ mutate(pure[individual=%d].genotyp, gene_number=%d);\n\n", individual, gene_number ); #endif /* DEBUG */ mutate(pure[individual].genotyp, gene_number); pure[individual].age = 0L; pure[individual].mapping();//map genotype to phenotype and evaluate } } void Genetic_Algorithm::crossover(Population &original_population) { register unsigned int i; int first_point, second_point, temp_index, temp_ordering; Real alpha = 0.5; #ifdef DEBUG (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::crossover(Population &original_population)\n"); #endif /* DEBUG */ // Shuffle the population // Permute the ordering of the population, "original_population" for (i=0; i<original_population.num_individuals(); i++) { temp_ordering = ordering[i]; // ignlgi is GeNerate LarGe Integer and is in com.cc temp_index = ignlgi()%original_population.num_individuals(); ordering[i] = ordering[temp_index]; assert(ordering[i] < original_population.num_individuals());//debug assert(ordering[i] >= 0);//debug ordering[temp_index] = temp_ordering; assert(ordering[temp_index] < original_population.num_individuals());//debug assert(ordering[temp_index] >= 0);//debug } // How does Goldberg implement crossover? // Loop over individuals in population for (i=0; i<original_population.num_individuals()-1; i=i+2) { // The two individuals undergoing crossover are original_population[ordering[i]] and original_population[ordering[i+1]] if (ranf() < c_rate) { // Perform crossover with a probability of c_rate // Assert the quaternions of the mother and father are okay: Genotype father = original_population[ordering[i]].genotyp; Genotype mother = original_population[ordering[i+1]].genotyp; Quat q_father, q_mother; #ifdef DEBUG_QUAT_PRINT pr( logFile, "DEBUG_QUAT: crossover() q_father (individual=%d)\n", ordering[i] ); #endif // endif DEBUG_QUAT_PRINT // Make sure the quaternion is suitable for 3D rotation q_father = father.readQuat(); #ifdef DEBUG_QUAT_PRINT printQuat( logFile, q_father ); // (void) fflush(logFile); #endif // endif DEBUG_QUAT_PRINT assertQuatOK( q_father ); #ifdef DEBUG_QUAT_PRINT pr( logFile, "DEBUG_QUAT: crossover() q_mother (individual=%d)\n", ordering[i+1] ); // (void) fflush(logFile); #endif // endif DEBUG_QUAT_PRINT // Make sure the quaternion is suitable for 3D rotation q_mother = mother.readQuat(); #ifdef DEBUG_QUAT_PRINT printQuat( logFile, q_mother ); // (void) fflush(logFile); #endif // endif DEBUG_QUAT_PRINT assertQuatOK( q_mother ); // Pos. Orient. Conf. // 0 1 2 3 4 5 6 7 8 9 // X Y Z x y z w t t t // num_genes() = 10 switch(c_mode) { case OnePt: // To guarantee 1-point always creates 2 non-empty partitions, // the crossover point must lie in range from 1 to num_genes-1. // Choose one random integer in this range // Make sure we do not crossover inside a quaternion... do { // first_point = ignlgi()%original_population[i].genotyp.num_genes(); first_point = ignuin(1, original_population[i].genotyp.num_genes()-1); } while ( is_within_rotation_index( first_point ) ) ; // We can accomplish one point crossover by using the 2pt crossover operator crossover_2pt( original_population[ordering[i]].genotyp, original_population[ordering[i+1]].genotyp, first_point, original_population[ordering[i]].genotyp.num_genes() ); original_population[ordering[i]].age = 0L; original_population[ordering[i+1]].age = 0L; break; case TwoPt: // To guarantee 2-point always creates 3 non-empty partitions, // each crossover point must lie in range from 1 to num_genes-1. // Choose two different random integers in this range // Make sure we do not crossover inside a quaternion... do { first_point = ignuin(1, original_population[i].genotyp.num_genes()-1); } while ( is_within_rotation_index( first_point ) ) ; do { second_point = ignuin(1, original_population[i].genotyp.num_genes()-1); } while ( is_within_rotation_index( second_point ) || second_point == first_point ); // Do two-point crossover, with the crossed-over offspring replacing the parents in situ: crossover_2pt( original_population[ordering[i]].genotyp, original_population[ordering[i+1]].genotyp, min( first_point, second_point ), max( first_point, second_point) ); original_population[ordering[i]].age = 0L; original_population[ordering[i+1]].age = 0L; break; case Branch: // New crossover mode, designed to exchange just one corresponding sub-trees (or "branch") // between two individuals. // If there are only position and orientation genes, there will be only // 7 genes; this mode would not change anything in such rigid-body dockings. if (original_population[i].genotyp.num_genes() <= 7) { // Rigid body docking, so no torsion genes to crossover. break; } else { // Pick a random torsion gene first_point = ignuin(7, original_population[i].genotyp.num_genes()-1); second_point = original_population.get_eob( first_point - 7 ); // Do two-point crossover, with the crossed-over offspring replacing the parents in situ: crossover_2pt( original_population[ordering[i]].genotyp, original_population[ordering[i+1]].genotyp, min( first_point, second_point ), max( first_point, second_point) ); original_population[ordering[i]].age = 0L; original_population[ordering[i+1]].age = 0L; break; } case Uniform: crossover_uniform( original_population[ordering[i]].genotyp, original_population[ordering[i+1]].genotyp, original_population[ordering[i]].genotyp.num_genes()); original_population[ordering[i]].age = 0L; original_population[ordering[i+1]].age = 0L; break; case Arithmetic: // select the parents A and B // create new offspring, a and b, where // a = x*A + (1-x)*B, and b = (1-x)*A + x*B -- note: x is alpha in the code alpha = (Real) ranf(); #ifdef DEBUG (void)fprintf(logFile, "gs.cc/ alpha = " FDFMT "\n", alpha); (void)fprintf(logFile, "gs.cc/ About to call crossover_arithmetic with original_population[%d] & [%d]\n", i, i+1); #endif /* DEBUG */ crossover_arithmetic( original_population[ i ].genotyp, original_population[i+1].genotyp, alpha ); original_population[ordering[i]].age = 0L; original_population[ordering[i+1]].age = 0L; break; default: (void)fprintf(logFile,"gs.cc/ Unrecognized crossover mode!\n"); } //map genotype to phenotype and evaluate energy original_population[ i ].mapping(); original_population[i+1].mapping(); } } } void Genetic_Algorithm::crossover_2pt(Genotype &father, Genotype &mother, unsigned int pt1, unsigned int pt2) { // Assumes that 0<=pt1<=pt2<=number_of_pts #ifdef DEBUG (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::crossover_2pt(Genotype"); (void)fprintf(logFile, "&father, Genotype &mother, unsigned int pt1, unsigned int pt2)\n"); (void)fprintf(logFile,"gs.cc/Performing crossover from %d to %d \n", pt1,pt2); #endif /* DEBUG */ // loop over genes to be crossed over for (unsigned int i=pt1; i<pt2; i++) { #ifdef DEBUG //(void)fprintf(logFile,"gs.cc/1::At pt %d father: %.3lf mother: %.3lf\n", //i, *((double *)father.gread(i)), *((double *)mother.gread(i)) ); #endif /* DEBUG */ Element temp = father.gread(i); father.write(mother.gread(i), i); mother.write(temp, i); #ifdef DEBUG //(void)fprintf(logFile,"gs.cc/1::At pt %d father: %.3lf mother: %.3lf\n", //i, *((double *)father.gread(i)), *((double *)mother.gread(i)) ); #endif /* DEBUG */ } #ifdef DEBUG_QUAT Quat q_father, q_mother; #ifdef DEBUG_QUAT_PRINT pr( logFile, "DEBUG_QUAT: crossover_2pt() q_father\n" ); pr( logFile, "DEBUG_QUAT: crossover_2pt() pt1=%d, pt2=%d\n", pt1, pt2 ); #endif // endif DEBUG_QUAT_PRINT // Make sure the quaternion is suitable for 3D rotation q_father = father.readQuat(); #ifdef DEBUG_QUAT_PRINT printQuat( logFile, q_father ); // (void) fflush(logFile); #endif // endif DEBUG_QUAT_PRINT assertQuatOK( q_father ); #ifdef DEBUG_QUAT_PRINT pr( logFile, "DEBUG_QUAT: crossover_2pt() q_mother\n" ); // (void) fflush(logFile); #endif // endif DEBUG_QUAT_PRINT // Make sure the quaternion is suitable for 3D rotation q_mother = mother.readQuat(); #ifdef DEBUG_QUAT_PRINT printQuat( logFile, q_mother ); // (void) fflush(logFile); #endif // endif DEBUG_QUAT_PRINT assertQuatOK( q_mother ); #endif // endif DEBUG_QUAT } void Genetic_Algorithm::crossover_uniform(Genotype &father, Genotype &mother, unsigned int num_genes) { #ifdef DEBUG (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::crossover_uniform(Genotype"); (void)fprintf(logFile, "&father, Genotype &mother, unsigned int num_genes)\n"); #endif /* DEBUG */ for (unsigned int i=0; i<num_genes; i++) { // Choose either father's or mother's gene/rotation gene set, with a 50/50 probability if (ranf() > 0.5 ) continue; // 50% probability of crossing a gene or gene-set; next i if ( ! is_rotation_index( i ) ) { // Exchange parent's genes Element temp = father.gread(i); father.write(mother.gread(i), i); mother.write(temp, i); } else if ( is_first_rotation_index(i) ) { // don't crossover within a quaternion, only at the start; next i #ifdef DEBUG_QUAT Quat q_father, q_mother; #ifdef DEBUG_QUAT_PRINT pr( logFile, "DEBUG_QUAT: pre-crossover_uniform() q_father\n" ); #endif // endif DEBUG_QUAT_PRINT // Make sure the quaternion is suitable for 3D rotation q_father = father.readQuat(); #ifdef DEBUG_QUAT_PRINT printQuat( logFile, q_father ); // (void) fflush(logFile); #endif // endif DEBUG_QUAT_PRINT assertQuatOK( q_father ); #ifdef DEBUG_QUAT_PRINT pr( logFile, "DEBUG_QUAT: pre-crossover_uniform() q_mother\n" ); // (void) fflush(logFile); #endif // endif DEBUG_QUAT_PRINT // Make sure the quaternion is suitable for 3D rotation q_mother = mother.readQuat(); #ifdef DEBUG_QUAT_PRINT printQuat( logFile, q_mother ); // (void) fflush(logFile); #endif // endif DEBUG_QUAT_PRINT assertQuatOK( q_mother ); #endif // endif DEBUG_QUAT // Exchange father's or mother's set of rotation genes for (unsigned int j=i; j<i+4; j++) { Element temp = father.gread(j); father.write(mother.gread(j), j); mother.write(temp, j); } // Increment gene counter, i, by 3, to skip the 3 remaining rotation genes i=i+3; #ifdef DEBUG_QUAT #ifdef DEBUG_QUAT_PRINT pr( logFile, "DEBUG_QUAT: post-crossover_uniform() q_father\n" ); #endif // endif DEBUG_QUAT_PRINT // Make sure the quaternion is suitable for 3D rotation q_father = father.readQuat(); #ifdef DEBUG_QUAT_PRINT printQuat( logFile, q_father ); // (void) fflush(logFile); #endif // endif DEBUG_QUAT_PRINT assertQuatOK( q_father ); #ifdef DEBUG_QUAT_PRINT pr( logFile, "DEBUG_QUAT: post-crossover_uniform() q_mother\n" ); // (void) fflush(logFile); #endif // endif DEBUG_QUAT_PRINT // Make sure the quaternion is suitable for 3D rotation q_mother = mother.readQuat(); #ifdef DEBUG_QUAT_PRINT printQuat( logFile, q_mother ); // (void) fflush(logFile); #endif // endif DEBUG_QUAT_PRINT assertQuatOK( q_mother ); #endif // endif DEBUG_QUAT } // is_rotation_index( i ) } // next i } void Genetic_Algorithm::crossover_arithmetic(Genotype &A, Genotype &B, Real alpha) { register unsigned int i; Element temp_A, temp_B; Real one_minus_alpha; one_minus_alpha = 1.0 - alpha; #ifdef DEBUG (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::crossover_arithmetic(Genotype"); (void)fprintf(logFile, "&A, Genotype &B, Real alpha)\n"); (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::crossover_arithmetic"); (void)fprintf(logFile, "/Trying to perform arithmetic crossover using alpha = " FDFMT "\n", alpha); // (void)fflush(logFile); #endif /* DEBUG */ // loop over genes to be crossed over // a = alpha*A + (1-alpha)*B // b = (1-alpha)*A + alpha*B for (i=0; i<A.num_genes(); i++) { if ( is_translation_index(i) ) { #ifdef DEBUG (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::crossover_arithmetic"); (void)fprintf(logFile, "/looping over genes to be crossed over, i = %d\n", i); // (void)fflush(logFile); #endif /* DEBUG */ temp_A = A.gread(i); temp_B = B.gread(i); #ifdef DEBUG (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::crossover_arithmetic"); (void)fprintf(logFile, "/temp_A = %.3f & temp_B = %.3f\n", temp_A.real, temp_B.real); // (void)fflush(logFile); #endif A.write( (one_minus_alpha * temp_A.real + alpha * temp_B.real), i); B.write( (alpha * temp_A.real + one_minus_alpha * temp_B.real), i); #ifdef DEBUG (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::crossover_arithmetic"); (void)fprintf(logFile, "/A = %.3f & B = %.3f\n", A.gread(i).real, B.gread(i).real); // (void)fflush(logFile); #endif } else if ( is_rotation_index(i) ) { // Interpolate the father's and mother's set of 4 quaternion genes Quat q_A; q_A = slerp( A.readQuat(), B.readQuat(), alpha ); B.writeQuat( slerp( A.readQuat(), B.readQuat(), one_minus_alpha ) ); A.writeQuat( q_A ); // Increment gene counter, i, by 3, to skip the 3 remaining quaternion genes i=i+3; } else if ( is_conformation_index(i) ) { // Use anglular interpolation, alerp(a,b,fract), to generate properly interpolated torsion angles temp_A = A.gread(i); temp_B = B.gread(i); A.write( alerp(temp_A.real, temp_B.real, alpha), i); B.write( alerp(temp_A.real, temp_B.real, one_minus_alpha), i); } else { // MP: BUG CHECK! (void)fprintf(logFile, "Invalid gene type at i=%d\n", i); // (void)fflush(logFile); exit(-1); } } } /* * */ /* * Proportional Selection * * * We want to perform minimization on a function. To do so, we * take fitness values in a given generation and normalize them s.t. * they are non-negative, and such that smaller f's are given a higher * weighting. * If f in [a,b], then f' in [A,B] s.t. f(a) => f'(B) and f(b) => f'(A) is * * f' = (B-A) * (1 - (f-a)/(b-a)) + A * * = (B-A) * (b-f)/(b-a) + A * * Note that it suffices to map f into [0,1], giving * * f' = (b-f)/(b-a) * * Now the expected number of samples generated from a given point is * * N * f'_i / \sum f'_i = N * ((b-f_i)/(b-a)) / \sum ((b-f_i)/(b-a)) * * = N * (b-f_i) / (N*b - \sum f_i) * * Within a given generation, let 'b' be the maximal (worst) individual and * let 'a' be the minimal individual. * * Note: * (1) This calculation is invariant to the value of B, but _not_ * invariant to the value of A. * (2) This selection strategy works fine for functions bounded above, * but it won't necessarily work for functions which are unbounded * above. * * The 'b' parameter is represented as 'Worst' and is selected by the * scale_fitness method. If a value is greater than Worst, it is given a * value of zero for it's expectation. */ void Genetic_Algorithm::selection_proportional(Population &original_population, Individual *new_pop) { register unsigned int i=0, start_index = 0; int temp_ordering, temp_index; #ifdef DEBUG2 int allzero = 1;//debug Molecule *individualMol;//debug #endif #undef CHECK_ISNAN #ifdef CHECK_ISNAN int allEnergiesEqual = 1; double diffwa = 0.0, invdiffwa = 0.0, firstEnergy = 0.0; #endif #ifdef DEBUG (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::"); (void)fprintf(logFile, "selection_proportional(Population &original_population, Individual *new_pop)\n"); #endif /* DEBUG */ #ifdef DEBUG2 (void)fprintf(logFile, "gs.cc/At the start of sel_prop: sel_prop_count= %d, start_index= %d\n\n",sel_prop_count, start_index); //debug original_population.printPopulationAsStates(logFile, original_population.num_individuals(), global_ntor);//debug #endif #ifdef CHECK_ISNAN /* * This is the new code to check for the NaN case that could * arise; this will preempt any fatal errors. */ // Calculate expected number of children for each individual assert(finite(worst)); assert(finite(avg)); assert(!ISNAN(worst)); assert(!ISNAN(avg)); diffwa = worst - avg; assert(finite(diffwa)); assert(!ISNAN(diffwa)); if (diffwa != 0.0) { // added by gmm, 4-JUN-1997 invdiffwa = 1.0 / diffwa; if (ISNAN(invdiffwa)) { (void)fprintf(logFile,"WARNING! While doing proportional selection, not-a-number was detected (NaN).\n"); (void)fprintf(logFile,"All members of the population will be arbitrarily allocated 1 child each.\n\n"); for (i=0; i < original_population.num_individuals(); i++) { alloc[i] = 1.0; // arbitrary } // Assume run has converged: converged = 1; (void)fprintf(stderr,"WARNING! The population appears to have converged, so this run will shortly terminate.\n"); } else { assert(finite(invdiffwa)); assert(finite(worst)); assert(finite(original_population.num_individuals())); assert(!ISNAN(invdiffwa)); assert(!ISNAN(worst)); assert(!ISNAN(original_population.num_individuals())); for (i=0; i < original_population.num_individuals(); i++) { alloc[i] = (worst - original_population[i].value(e_mode)) * invdiffwa; assert(finite(original_population[i].value(e_mode))); assert(finite(alloc[i])); assert(!ISNAN(original_population[i].value(e_mode))); assert(!ISNAN(alloc[i])); }// for i }// endif (ISNAN(invdiffwa)) } else if (original_population.num_individuals() > 1) { // diffwa = 0.0, so worst = avg // This implies the population may have converged. converged = 1; // Write warning message to both stderr and logFile... (void)fprintf(stderr,"WARNING! While doing proportional selection, worst (%6.2le) = avg (%6.2le).\n", worst, avg); (void)fprintf(stderr," This would cause a division-by-zero error.\n"); (void)fprintf(stderr," All members of the population will be arbitrarily allocated 1 child each.\n"); (void)fprintf(stderr,"WARNING! The population appears to have converged, so this run will shortly terminate.\n\n"); (void)fprintf(logFile,"WARNING! While doing proportional selection, worst (%6.2le) = avg (%6.2le).\n", worst, avg); (void)fprintf(logFile," This would cause a division-by-zero error.\n"); (void)fprintf(logFile," All members of the population will be arbitrarily allocated 1 child each.\n"); (void)fprintf(logFile,"WARNING! The population appears to have converged, so this run will shortly terminate.\n\n"); alloc[0] = 1.0; // Added by gmm, 2-APR-1997 firstEnergy = original_population[0].value(e_mode); allEnergiesEqual = 1; for (i=1; i < original_population.num_individuals(); i++) { alloc[i] = 1.0; // Added by gmm, 2-APR-1997 allEnergiesEqual = allEnergiesEqual && (firstEnergy == original_population[i].value(e_mode)); } if (allEnergiesEqual) { (void)fprintf(logFile," All individuals in the population have the same fitness (%6.2le)\n", firstEnergy); } else { (void)fprintf(logFile," Here are the fitness values of the population:\n\n"); for (i=0; i < original_population.num_individuals(); i++) { (void)fprintf(logFile,"%3d = %6.2le, ", i+1, original_population[i].value(e_mode) ); } } (void)fprintf(logFile,"\n"); } // diffwa = 0.0, so worst = avg /* * Commented out because this writes too many * errors out -- (worst-avg) is constant inside loop, * so can be brought outside for-loop. * for (i=0; i<original_population.num_individuals(); i++) { * if ((worst - avg) != 0.0) { // added by gmm, 4-JUN-1997 * // In function minimization, the max energy is the worst * alloc[i] = (worst - original_population[i].value(e_mode))/(worst - avg); * } else { * (void)fprintf(logFile,"gs.cc/WARNING! While doing proportional selection, * worst (%6.2le) and avg (%6.2le) were found equal, which would cause a * division-by-zero error; this was just prevented, for individual %d\n", * worst, avg, i); // Added by gmm, 4-JUN-1997 * alloc[i] = 1.0; // Added by gmm, 2-APR-1997 * } * } */ #else /* * This is how the code used to be, before the worst=avg problem * was observed. */ // Calculate expected number of children for each individual for (i=0; i < original_population.num_individuals(); i++) { // In our case of function minimization, the max individual is the worst if(avg==worst) alloc[i] = 1./(original_population.num_individuals()+1); // HACK TODO investigate 2008-11 else alloc[i] = (worst - original_population[i].value(e_mode))/(worst - avg); } #endif /* not CHECK_ISNAN */ #ifdef DEBUG2 allzero = 1; //debug unsigned int J;//debug (void)fprintf(logFile, "gs.cc: checking that all alloc[] variables are not all zero...\n"); //debug for (J=0; J < original_population.num_individuals(); J++) {//debug allzero = allzero & (alloc[J] == (Real)0.0);//debug }//debug if (allzero) {//debug (void)fprintf(logFile, "gs.cc: W A R N I N G ! all alloc variables are zero!\n"); //debug }//debug #endif // Permute the individuals #ifdef DEBUG2 (void)fprintf(logFile, "gs.cc: Permuting beginning: original_population.num_individuals()= %d\n", original_population.num_individuals()); //debug #endif for (i=0; i < original_population.num_individuals(); i++) { temp_ordering = ordering[i]; assert(ordering[i] < original_population.num_individuals());//debug temp_index = ignlgi()%(original_population.num_individuals()); assert(ordering[temp_index] < original_population.num_individuals());//debug ordering[i] = ordering[temp_index]; ordering[temp_index] = temp_ordering; #ifdef DEBUG2 //(void)fprintf(logFile, "gs.cc: permuting in sel_prop: ordering check: ordering[i=%d]= %d, ordering[temp_index=%d]= %d\n", ordering[i],i, ordering[temp_index], temp_index);//debug #endif }// endfor i // We might get some savings here if we sorted the individuals before calling // this routine for (i=0; (i < original_population.num_individuals()) && (start_index < original_population.num_individuals()); i++) { for (; (alloc[i] >= 1.0) && (start_index < original_population.num_individuals()); alloc[i]-= 1.0) { new_pop[start_index] = original_population[i]; //new_pop[start_index].incrementAge(); // DOTO 2008-11 why is this changing alloc[] ++start_index; } } #ifdef DEBUG2 (void)fprintf(stderr, "gs.cc/void Genetic_Algorithm::"); //debug (void)fprintf(stderr, "selection_proportional(Population &original_population, Individual *new_pop)\n"); //debug #endif i = 0; #ifdef DEBUG2 int count = 0;//debug (void)fprintf(stderr, "gs.cc/beginning \"while(start_index < original_population.num_individuals()) {\" loop\n"); //debug #endif // ??? start_index = 0; // gmm, 1998-07-13 ??? while (start_index < original_population.num_individuals()) { Real r; // local #ifdef DEBUG2 (void)fprintf(stderr, "gs.cc:596/inside \"while(start_index(=%d) < original_population.num_individuals()(=%d)) \" loop: count= %d\n", start_index, original_population.num_individuals(), ++count); //debug #endif assert(ordering[i] < original_population.num_individuals());//debug r = ranf(); #ifdef DEBUG2 (void)fprintf(stderr, "gs.cc:599/inside debug_ranf= %.3f, alloc[ordering[i]]= %.3e, ordering[i]= %d, i= %d\n", r, alloc[ordering[i]], ordering[i], i); // debug #endif // DEBUG2 if (r < alloc[ordering[i]]) { #ifdef DEBUG2 (void)fprintf(stderr, "gs.cc:603/inside (debug_ranf < alloc[ordering[i]]) is true!\n"); //debug (void)fprintf(stderr, "gs.cc:604/inside about to increment start_index in: \"new_pop[start_index++] = original_population[ordering[i]];\"; right now, start_index= %d\n", start_index); //debug #endif new_pop[start_index] = original_population[ordering[i]]; //new_pop[start_index].incrementAge(); start_index++; #ifdef DEBUG2 (void)fprintf(stderr, "gs.cc:605/inside just incremented start_index, now start_index= %d\n", start_index); //debug #endif }// endif (ranf() < alloc[ordering[i]]) #ifdef DEBUG2 (void)fprintf(stderr, "gs.cc:608/inside i= %d, original_population.num_individuals()= %d\n", i, original_population.num_individuals()); //debug (void)fprintf(stderr, "gs.cc:609/inside about to \"i = (i+1)%%original_population.num_individuals();\"\n"); //debug #endif i = (i+1)%original_population.num_individuals(); #ifdef DEBUG2 (void)fprintf(stderr, "gs.cc:611/inside just done \"i = (i+1)%%original_population.num_individuals();\"\n"); //debug (void)fprintf(stderr, "gs.cc:612/inside i= %d _____________________________________________________\n\n", i); //debug allzero = 1;//debug for (J=0; J < original_population.num_individuals(); J++) {//debug allzero = allzero & (alloc[J] == (Real)0.0);//debug }//debug if (allzero) {//debug (void)fprintf(logFile, "gs.cc: W A R N I N G ! all alloc variables are zero!\n"); //debug }//debug #endif }// endwhile (start_index < original_population.num_individuals()) #ifdef DEBUG2 (void)fprintf(stderr, "gs.cc/finished \"while(start_index < original_population.num_individuals()) \" loop\n"); //debug #endif } /* Probabilistic Binary Tournament Selection * * This type of tournament selection was described in Goldberg and Deb (1991), * and performs the same type of selection as is seen in linear rank * selection. Two individuals are chosen at random, and the better individual * is selected with probability P, 0.5 <= P <= 1. If we let 2P = C, then * we see that the expected number of samples generated by rank r_i is * * N * [2P - 2(2P-1) r_i] , 1 >= P >= 0.5 * * We can again parameterize this ranking with K, the relative probability * between the best and worst individual. Since 2P = C, * P = K/(1+K). */ void Genetic_Algorithm::selection_tournament(Population &original_population, Individual *new_pop) { register unsigned int i = 0, start_index = 0; int temp_ordering, temp_index; #ifdef DEBUG (void)fprintf(logFile, "gs.cc/void Genetic_Algorithm::"); (void)fprintf(logFile, "selection_tournament(Population &original_population, Individual *new_pop)\n"); #endif /* DEBUG */ original_population.msort(original_population.num_individuals()); for (i=0; i<original_population.num_individuals(); i++) { alloc[i] = original_population.num_individuals()*(2*tournament_prob - i*(4*tournament_prob - 2)); } for (i=0; (i < original_population.num_individuals()) && (start_index < original_population.num_individuals()); i++) { for (; (alloc[i] >= 1.0) && (start_index < original_population.num_individuals()); alloc[i] -= 1.0) { new_pop[start_index++] = original_population[i]; } } for (i=0; i < original_population.num_individuals(); i++) { temp_ordering = ordering[i]; temp_index = ignlgi()%original_population.num_individuals(); ordering[i] = ordering[temp_index]; ordering[temp_index] = temp_ordering; } i = 0; while (start_index < original_population.num_individuals()) { if (ranf() < alloc[ordering[i]]) { new_pop[start_index++] = original_population[ordering[i]]; } i = (i+1)%original_population.num_individuals(); } } Individual *Genetic_Algorithm::selection(Population &solutions) { Individual *next_generation; #ifdef DEBUG (void)fprintf(logFile, "gs.cc/Individual *Genetic_Algorithm::selection(Population &solutions)\n"); #endif /* DEBUG */ next_generation = new Individual[solutions.num_individuals()]; set_worst(solutions); switch(s_mode) { case Proportional: selection_proportional(solutions, next_generation); break; case Tournament: selection_tournament(solutions, next_generation); break; case Boltzmann: (void)fprintf(logFile,"gs.cc/Unimplemented Selection Method - using proportional\n"); selection_proportional(solutions, next_generation); break; default: (void)fprintf(logFile,"gs.cc/Unknown Selection Mode!\n"); } return(next_generation); } // For right now global search is taken to be a GA // // This is where the action is... SEARCH! // int Genetic_Algorithm::search(Population &solutions) { register unsigned int i; unsigned int oldest = 0, oldestIndividual = 0, fittestIndividual = 0; double fittest = BIG; struct tms tms_genStart; struct tms tms_genEnd; Clock genStart; Clock genEnd; #ifdef DEBUG /* DEBUG { */ (void)fprintf(logFile, "gs.cc/int Genetic_Algorithm::search(Population &solutions)\n"); #endif /* } DEBUG */ genStart = times( &tms_genStart ); #ifdef DEBUG3 /* DEBUG3 { */ for (i=0; i<solutions.num_individuals(); i++) { (void)fprintf(logFile,"%ld ", solutions[i].age); } (void)fprintf(logFile,"\n"); #endif /* } DEBUG3 */ // search no longer doing Mapping on the incoming population // assumed already mapped earlier, may 2009 mp+rh #ifdef DEBUG3 /* DEBUG3 { */ (void)fprintf(logFile,"About to perform Selection on the solutions.\n"); for (i=0; i<solutions.num_individuals(); i++) { (void)fprintf(logFile,"%ld ", solutions[i].age); } (void)fprintf(logFile,"\n"); #endif /* } DEBUG3 */ // // Perform selection // Population newPop(solutions.num_individuals(), selection(solutions)); #ifdef DEBUG3 /* DEBUG3 { */ (void)fprintf(logFile,"About to perform Crossover on the population, newPop.\n"); for (i=0; i<solutions.num_individuals(); i++) { (void)fprintf(logFile,"%ld ", newPop[i].age); } (void)fprintf(logFile,"\n"); #endif /* } DEBUG3 */ // // Perform crossover // crossover(newPop); #ifdef DEBUG3 /* DEBUG3 { */ (void)fprintf(logFile,"About to perform mutation on the population, newPop.\n"); for (i=0; i<solutions.num_individuals(); i++) { (void)fprintf(logFile,"%ld ", newPop[i].age); } (void)fprintf(logFile,"\n"); #endif /* } DEBUG3 */ // // Perform mutation // mutation(newPop); #ifdef DEBUG3 /* DEBUG3 { */ (void)fprintf(logFile,"About to perform elitism, newPop.\n"); for (i=0; i<solutions.num_individuals(); i++) { (void)fprintf(logFile,"%ld ", newPop[i].age); } (void)fprintf(logFile,"\n"); #endif /* } DEBUG3 */ // // Copy the n best individuals to the next population, if the elitist flag is set, where n is the value of elitism. // if (elitism > 0) { solutions.msort(elitism); for (i=0; i<elitism; i++) { newPop[solutions.num_individuals()-1-i] = solutions[i]; } } #ifdef DEBUG3 /* DEBUG3 { */ (void)fprintf(logFile,"About to Update the Current Generation, newPop.\n"); for (i=0; i<solutions.num_individuals(); i++) { (void)fprintf(logFile,"%ld ", newPop[i].age); } (void)fprintf(logFile,"\n"); #endif /* } DEBUG3 */ // // Update current generation // solutions = newPop; // // Increase the number of generations // generations++; // // Increment the age of surviving individuals... // for (i=0; i<solutions.num_individuals(); i++) { solutions[i].incrementAge(); } if (debug > 0) { (void)fprintf(logFile,"DEBUG: Generation: %3u, outputEveryNgens = %3u, generations%%outputEveryNgens = %u\n", generations, outputEveryNgens, generations%outputEveryNgens); } if (generations%outputEveryNgens == 0) { oldest = 0L; fittest = BIG; for (i=0; i<solutions.num_individuals(); i++) { if (solutions[i].age >= oldest) { oldest = solutions[i].age; oldestIndividual = i; } if (solutions[i].value(Normal_Eval) <= fittest) { fittest = solutions[i].value(Normal_Eval); fittestIndividual = i; } } /* Only output if the output level is not 0. */ if (outputEveryNgens != OUTLEV0_GENS) { // (void)fprintf(logFile, "___\noutputEveryNgens = %d, OUTLEV0_GENS=%d\n___\n", outputEveryNgens, OUTLEV0_GENS); if (outputEveryNgens > 1) { #ifndef DEBUG3 (void)fprintf(logFile,"Generation: %3u Oldest's energy: %.3f Lowest energy: %.3f Num.evals.: %ld Timing: ", generations, solutions[oldestIndividual].value(Normal_Eval), solutions[fittestIndividual].value(Normal_Eval), evaluate.evals() ); #else (void)fprintf(logFile,"Generation: %3u Oldest ind.: %u/%u, age: %lu, energy: %.3f Lowest energy individual: %u/%u, age: %lu, energy: %.3f Num.evals.: %ld Timing: ", generations, oldestIndividual+1, solutions.num_individuals(), solutions[oldestIndividual].age, solutions[oldestIndividual].value(Normal_Eval), fittestIndividual+1, solutions.num_individuals(), solutions[fittestIndividual].age, solutions[fittestIndividual].value(Normal_Eval), evaluate.evals() ); #endif /* DEBUG3 */ } else { #ifndef DEBUG3 (void)fprintf(logFile,"Generation: %3u Oldest's energy: %.3f Lowest energy: %.3f Num.evals.: %ld Timing: ", generations, solutions[oldestIndividual].value(Normal_Eval), solutions[fittestIndividual].value(Normal_Eval), evaluate.evals() ); #else (void)fprintf(logFile,"Generation: %3u Oldest: %u/%u, age: %lu, energy: %.3f Lowest energy individual: %u/%u, age: %lu, energy: %.3f Num.evals.: %ld Timing: ", generations, oldestIndividual+1, solutions.num_individuals(), solutions[oldestIndividual].age, solutions[oldestIndividual].value(Normal_Eval), fittestIndividual+1, solutions.num_individuals(), solutions[fittestIndividual].age, solutions[fittestIndividual].value(Normal_Eval), evaluate.evals() ); #endif /* DEBUG3 */ } } genEnd = times( &tms_genEnd ); timesyshms( genEnd - genStart, &tms_genStart, &tms_genEnd ); genStart = times( &tms_genStart ); } return(0); }
gpl-2.0
EdDev/vdsm
tests/network/dhcp.py
7328
# Copyright 2013-2017 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import from errno import ENOENT, ESRCH import logging import os from signal import SIGKILL, SIGTERM from subprocess import PIPE, Popen from time import sleep, time from vdsm.common.cmdutils import CommandPath from vdsm.network import cmd _DNSMASQ_BINARY = CommandPath('dnsmasq', '/usr/sbin/dnsmasq') _DHCLIENT_BINARY = CommandPath('dhclient', '/usr/sbin/dhclient', '/sbin/dhclient') _START_CHECK_TIMEOUT = 0.5 _DHCLIENT_TIMEOUT = 10 _WAIT_FOR_STOP_TIMEOUT = 2 _DHCLIENT_LEASE = '/var/lib/dhclient/dhclient{0}--{1}.lease' _DHCLIENT_LEASE_LEGACY = '/var/lib/dhclient/dhclient{0}-{1}.leases' class DhcpError(Exception): pass class Dnsmasq(): def __init__(self): self._popen = None def start(self, interface, dhcp_range_from=None, dhcp_range_to=None, dhcpv6_range_from=None, dhcpv6_range_to=None, router=None, ipv6_slaac_prefix=None): # --dhcp-authoritative The only DHCP server on network # -p 0 don't act as a DNS server # --dhcp-option=3,<router> advertise a specific gateway (or None) # --dhcp-option=6 don't reply with any DNS servers # -d don't daemonize and log to stderr # --bind-dynamic bind only the testing veth iface command = [ _DNSMASQ_BINARY.cmd, '--dhcp-authoritative', '-p', '0', '--dhcp-option=3' + (',{0}'.format(router) if router else ''), '--dhcp-option=6', '-i', interface, '-I', 'lo', '-d', '--bind-dynamic', ] if dhcp_range_from and dhcp_range_to: command += ['--dhcp-range={0},{1},2m'.format(dhcp_range_from, dhcp_range_to)] if dhcpv6_range_from and dhcpv6_range_to: command += ['--dhcp-range={0},{1},2m'.format(dhcpv6_range_from, dhcpv6_range_to)] if ipv6_slaac_prefix: command += ['--enable-ra'] command += ['--dhcp-range={0},slaac,2m'.format(ipv6_slaac_prefix)] self._popen = Popen(command, close_fds=True, stderr=PIPE) sleep(_START_CHECK_TIMEOUT) if self._popen.poll(): raise DhcpError('Failed to start dnsmasq DHCP server.\n%s\n%s' % (self._popen.stderr, ' '.join(command))) def stop(self): self._popen.kill() self._popen.wait() logging.debug(self._popen.stderr) class ProcessCannotBeKilled(Exception): pass class DhclientRunner(object): """On the interface, dhclient is run to obtain a DHCP lease. In the working directory (tmp_dir), which is managed by the caller. dhclient accepts the following date_formats: 'default' and 'local'. """ def __init__(self, interface, family, tmp_dir, date_format, default_route=False): self._interface = interface self._family = family self._date_format = date_format self._conf_file = os.path.join(tmp_dir, 'test.conf') self._pid_file = os.path.join(tmp_dir, 'test.pid') self.pid = None self.lease_file = os.path.join(tmp_dir, 'test.lease') cmds = [_DHCLIENT_BINARY.cmd, '-' + str(family), '-1', '-v', '-timeout', str(_DHCLIENT_TIMEOUT), '-cf', self._conf_file, '-pf', self._pid_file, '-lf', self.lease_file] if not default_route: # Instruct Fedora/EL's dhclient-script not to set gateway on iface cmds += ['-e', 'DEFROUTE=no'] self._cmd = cmds + [self._interface] def _create_conf(self): with open(self._conf_file, 'w') as f: if self._date_format: f.write('db-time-format {0};'.format(self._date_format)) def start(self): self._create_conf() rc, out, err = cmd.exec_sync(self._cmd) if rc: # == 2 logging.debug(err) raise DhcpError('dhclient failed to obtain a lease: %d', rc) with open(self._pid_file) as pid_file: self.pid = int(pid_file.readline()) def stop(self): if self._try_kill(SIGTERM): return if self._try_kill(SIGKILL): return raise ProcessCannotBeKilled('cmd=%s, pid=%s' % (' '.join(self._cmd), self.pid)) def _try_kill(self, signal, timeout=_WAIT_FOR_STOP_TIMEOUT): now = time() deadline = now + timeout while now < deadline: try: os.kill(self.pid, signal) except OSError as err: if err.errno != ESRCH: raise return True # no such process sleep(0.5) if not self._is_running(): return True now = time() return False def _is_running(self): executable_link = '/proc/{0}/exe'.format(self.pid) try: executable = os.readlink(executable_link) except OSError as err: if err.errno == ENOENT: return False # no such pid else: raise return executable == _DHCLIENT_BINARY.cmd def delete_dhclient_leases(iface, dhcpv4=False, dhcpv6=False): if dhcpv4: _delete_with_fallback(_DHCLIENT_LEASE.format('', iface), _DHCLIENT_LEASE_LEGACY.format('', iface)) if dhcpv6: _delete_with_fallback(_DHCLIENT_LEASE.format('6', iface), _DHCLIENT_LEASE_LEGACY.format('6', iface)) def _delete_with_fallback(*file_names): """ Delete the first file in file_names that exists. This is useful when removing dhclient lease files. dhclient stores leases either as e.g. 'dhclient6-test-network.leases' if it existed before, or as 'dhclient6--test-network.lease'. The latter is more likely to exist. We intentionally only delete one file, the one initscripts chose and wrote to. Since the legacy one is preferred, after the test it will be gone and on the next run ifup will use the more modern name. """ for name in file_names: try: os.unlink(name) return except OSError as ose: if ose.errno != ENOENT: logging.error('Failed to delete: %s', name, exc_info=True) raise
gpl-2.0
FollyLabs/SudoSolver
SudoSolver-Java/src/org/folly/sudosolver/logic/Approach.java
329
package org.folly.sudosolver.logic; import org.folly.sudosolver.base.SudokuGrid; abstract public class Approach { public boolean validateSudokuGrid(SudokuGrid grid) { return true; } public boolean logic(SudokuGrid grid) { return true; } public void displaySudokuGrid(SudokuGrid grid) { return; } }
gpl-2.0
aragorn55/ClassSampleCode
mobiledev/SaveData/SaveData.UI/AppDelegate.cs
1413
using System; using System.Linq; using System.Collections.Generic; using Foundation; using UIKit; namespace SaveData.UI { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; set; } // This method is invoked when the application is about to move from active to inactive state. // OpenGL applications should use this method to pause. public override void OnResignActivation (UIApplication application) { } // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { } } }
gpl-2.0
borisay/ychenik
sites/all/themes/ytheme/templates/views-view--search.tpl.php
768
<div class="<?php print $classes; ?>"> <?php if ($exposed): ?> <div class="view-filters"> <?php print $exposed; ?> </div> <?php endif; ?> <?php $view = views_get_current_view(); $res = $view->total_rows; if ($view -> total_rows !== NULL && $view->name == 'search') { ?> <div class="counter_rows"> <?php print '"'.$view->total_rows.'"'.' Businesses found in your search'; ?> </div> <?php } ?> <?php if ($rows): ?> <div class="view-content"> <?php print $rows; ?> </div> <?php elseif ($empty): ?> <div class="view-empty"> <?php print $empty; ?> </div> <?php endif; ?> <?php if ($pager): ?> <?php print $pager; ?> <?php endif; ?> </div><?php /* class view */ ?>
gpl-2.0
yad/easy-scriptdev2
scripts/outland/auchindoun/shadow_labyrinth/instance_shadow_labyrinth.cpp
5305
/* Copyright (C) 2006 - 2011 ScriptDev2 <http://www.scriptdev2.com/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Instance_Shadow_Labyrinth SD%Complete: 85 SDComment: Some cleanup left along with save SDCategory: Auchindoun, Shadow Labyrinth EndScriptData */ #include "precompiled.h" #include "shadow_labyrinth.h" /* Shadow Labyrinth encounters: 1 - Ambassador Hellmaw event 2 - Blackheart the Inciter event 3 - Grandmaster Vorpil event 4 - Murmur event */ instance_shadow_labyrinth::instance_shadow_labyrinth(Map* pMap) : ScriptedInstance(pMap), m_uiFelOverseerCount(0) { Initialize(); } void instance_shadow_labyrinth::Initialize() { memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); } void instance_shadow_labyrinth::OnObjectCreate(GameObject* pGo) { switch(pGo->GetEntry()) { case GO_REFECTORY_DOOR: if (m_auiEncounter[2] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_SCREAMING_HALL_DOOR: if (m_auiEncounter[3] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; default: return; } m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid(); } void instance_shadow_labyrinth::OnCreatureCreate(Creature* pCreature) { switch(pCreature->GetEntry()) { case NPC_VORPIL: m_mNpcEntryGuidStore[NPC_VORPIL] = pCreature->GetObjectGuid(); break; case NPC_FEL_OVERSEER: ++m_uiFelOverseerCount; // TODO should actually only count alive ones debug_log("SD2: Shadow Labyrinth: counting %u Fel Overseers.", m_uiFelOverseerCount); break; } } void instance_shadow_labyrinth::SetData(uint32 uiType, uint32 uiData) { switch(uiType) { case TYPE_HELLMAW: m_auiEncounter[0] = uiData; break; case TYPE_OVERSEER: if (uiData != DONE) { error_log("SD2: Shadow Labyrinth: TYPE_OVERSEER did not expect other data than DONE"); return; } if (m_uiFelOverseerCount) { --m_uiFelOverseerCount; if (m_uiFelOverseerCount) { debug_log("SD2: Shadow Labyrinth: %u Fel Overseers left to kill.", m_uiFelOverseerCount); // Skip save call return; } else { m_auiEncounter[1] = DONE; debug_log("SD2: Shadow Labyrinth: TYPE_OVERSEER == DONE"); } } break; case TYPE_INCITER: if (uiData == DONE) DoUseDoorOrButton(GO_REFECTORY_DOOR); m_auiEncounter[2] = uiData; break; case TYPE_VORPIL: if (uiData == DONE) DoUseDoorOrButton(GO_SCREAMING_HALL_DOOR); m_auiEncounter[3] = uiData; break; case TYPE_MURMUR: m_auiEncounter[4] = uiData; break; } if (uiData == DONE) { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << m_auiEncounter[0] << " " << m_auiEncounter[1] << " " << m_auiEncounter[2] << " " << m_auiEncounter[3] << " " << m_auiEncounter[4]; m_strInstData = saveStream.str(); SaveToDB(); OUT_SAVE_INST_DATA_COMPLETE; } } uint32 instance_shadow_labyrinth::GetData(uint32 uiType) { switch(uiType) { case TYPE_HELLMAW: return m_auiEncounter[0]; case TYPE_OVERSEER: return m_auiEncounter[1]; default: return 0; } } void instance_shadow_labyrinth::Load(const char* chrIn) { if (!chrIn) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(chrIn); std::istringstream loadStream(chrIn); loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2] >> m_auiEncounter[3] >> m_auiEncounter[4]; for(uint8 i = 0; i < MAX_ENCOUNTER; ++i) if (m_auiEncounter[i] == IN_PROGRESS) m_auiEncounter[i] = NOT_STARTED; OUT_LOAD_INST_DATA_COMPLETE; } InstanceData* GetInstanceData_instance_shadow_labyrinth(Map* pMap) { return new instance_shadow_labyrinth(pMap); } void AddSC_instance_shadow_labyrinth() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "instance_shadow_labyrinth"; pNewScript->GetInstanceData = &GetInstanceData_instance_shadow_labyrinth; pNewScript->RegisterSelf(); }
gpl-2.0
r-martins/PagSeguro-Magento-Transparente
app/code/community/RicardoMartins/PagSeguro/Model/Payment/Recurring.php
16353
<?php /** * PagSeguro Transparente Magento * Model CC Class - responsible for credit card payment processing * * @category RicardoMartins * @package RicardoMartins_PagSeguro * @author Ricardo Martins * @copyright Copyright (c) 2015 Ricardo Martins (http://r-martins.github.io/PagSeguro-Magento-Transparente/) * @license https://opensource.org/licenses/MIT MIT License */ class RicardoMartins_PagSeguro_Model_Payment_Recurring extends RicardoMartins_PagSeguro_Model_Recurring implements Mage_Payment_Model_Recurring_Profile_MethodInterface { protected $_code = 'rm_pagseguro_recurring'; protected $_formBlockType = 'ricardomartins_pagseguro/form_recurring'; protected $_infoBlockType = 'ricardomartins_pagseguro/form_info_recurring'; protected $_isGateway = true; protected $_canAuthorize = true; protected $_canCapture = true; protected $_canRefund = true; protected $_canRefundInvoicePartial = true; protected $_canVoid = true; protected $_canUseInternal = false; protected $_canUseCheckout = true; protected $_canUseForMultishipping = false; protected $_canSaveCc = false; protected $_canCreateBillingAgreement = true; /** * Check if module is available for current quote and customer group (if restriction is activated) * @param Mage_Sales_Model_Quote $quote * * @return bool */ public function isAvailable($quote = null) { $isAvailable = parent::isAvailable($quote); if (empty($quote)) { return $isAvailable; } $helper = Mage::helper('ricardomartins_pagseguro'); $useApp = $helper->getLicenseType() == 'app'; if (!$useApp || !$quote->isNominal()) { return false; } $helper = Mage::helper('ricardomartins_pagseguro/recurring'); $lastItem = $quote->getItemsCollection()->getLastItem(); if (!$lastItem->getId()) { return false; } $product = $lastItem->getProduct(); $profile = $product->getRecurringProfile(); $pagSeguroPeriod = $helper->getPagSeguroPeriod($profile); if (false == $pagSeguroPeriod || $profile['start_date_is_editable']) { return false; } if ($isAvailable) { return true; } return false; } /** * Assign data to info model instance * * @param mixed $data * @return Mage_Payment_Model_Info */ public function assignData($data) { if (!($data instanceof Varien_Object)) { $data = new Varien_Object($data); } $info = $this->getInfoInstance(); /** @var RicardoMartins_PagSeguro_Helper_Params $pHelper */ $pHelper = Mage::helper('ricardomartins_pagseguro/params'); $info->setAdditionalInformation('sender_hash', $pHelper->getPaymentHash('sender_hash')) ->setAdditionalInformation('credit_card_token', $pHelper->getPaymentHash('credit_card_token')) ->setAdditionalInformation('credit_card_owner', $data->getPsCcOwner()) ->setCcType($pHelper->getPaymentHash('cc_type')) ->setCcLast4(substr($data->getPsCcNumber(), -4)); //cpf if (Mage::helper('ricardomartins_pagseguro')->isCpfVisible()) { $info->setAdditionalInformation($this->getCode() . '_cpf', $data->getData($this->getCode() . '_cpf')); } //DOB $ownerDobAttribute = Mage::getStoreConfig('payment/rm_pagseguro_cc/owner_dob_attribute'); if (empty($ownerDobAttribute)) { $info->setAdditionalInformation( 'credit_card_owner_birthdate', date( 'd/m/Y', strtotime( $data->getPsCcOwnerBirthdayYear(). '/'. $data->getPsCcOwnerBirthdayMonth(). '/'.$data->getPsCcOwnerBirthdayDay() ) ) ); } return $this; } /** * Validate payment method information object * * @return Mage_Payment_Model_Abstract */ public function validate() { parent::validate(); /** @var RicardoMartins_PagSeguro_Helper_Data $helper */ $helper = Mage::helper('ricardomartins_pagseguro'); /** @var RicardoMartins_PagSeguro_Helper_Params $pHelper */ $pHelper = Mage::helper('ricardomartins_pagseguro/params'); $shippingMethod = Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getShippingMethod(); // verifica se não há método de envio selecionado antes de exibir o erro de falha no cartão de crédito - Weber if (empty($shippingMethod)) { return false; } $senderHash = $pHelper->getPaymentHash('sender_hash'); $creditCardToken = $pHelper->getPaymentHash('credit_card_token'); //mapeia a request URL atual $controller = Mage::app()->getRequest()->getControllerName(); $action = Mage::app()->getRequest()->getActionName(); $route = Mage::app()->getRequest()->getRouteName(); $pathRequest = $route.'/'.$controller.'/'.$action; //seta os paths para bloqueio de validação instantânea definidos no admin no array $configPaths = Mage::getStoreConfig('payment/rm_pagseguro/exception_request_validate'); $configPaths = preg_split('/\r\n|[\r\n]/', $configPaths); //Valida token e hash se a request atual se encontra na lista de //exceções do admin ou se a requisição vem de placeOrder if ((!$creditCardToken || !$senderHash) && !in_array($pathRequest, $configPaths)) { $missingInfo = sprintf('Token do cartão: %s', var_export($creditCardToken, true)); $missingInfo .= sprintf('/ Sender_hash: %s', var_export($senderHash, true)); $missingInfo .= '/ URL desta requisição: ' . $pathRequest; $helper->writeLog( "Falha ao obter o token do cartao ou sender_hash. Ative o modo debug e observe o console de erros do seu navegador. Se esta for uma atualização via Ajax, ignore esta mensagem até a finalização do pedido, ou configure a url de exceção. $missingInfo" ); } return $this; } /** * Validate data * * @param Mage_Payment_Model_Recurring_Profile $profile * * @throws Mage_Core_Exception */ public function validateRecurringProfile(Mage_Payment_Model_Recurring_Profile $profile) { //what was validatable was validated in order to display PagSeguro as a payment method (isAvailable) //nothing more to be validate here. :O return $this; } /** * Submit to the gateway * * @param Mage_Payment_Model_Recurring_Profile $profile * @param Mage_Payment_Model_Info $paymentInfo */ public function submitRecurringProfile( Mage_Payment_Model_Recurring_Profile $profile, Mage_Payment_Model_Info $paymentInfo ) { $pagseguroPlanCode = $this->createPagseguroPlan($profile); $profile->setToken($pagseguroPlanCode); $subResp = $this->subscribeToPlan($pagseguroPlanCode, $paymentInfo, $profile); if (!isset($subResp->code) || empty($subResp->code)) { Mage::throwException('Falha ao realizar subscrição. Por favor tente novamente.'); } $profile->setReferenceId((string)$subResp->code); $profile->setState(Mage_Sales_Model_Recurring_Profile::STATE_PENDING); $additionalInfo = $profile->getAdditionalInfo(); $profile->setAdditionalInfo( array_merge( $additionalInfo, array('isSandbox' => Mage::helper('ricardomartins_pagseguro')->isSandbox()) ) ); //método chamado em segundo lugar durante o processo de compra, depois do validate profile } /** * Fetch details * * @param string $referenceId * @param Varien_Object $result */ public function getRecurringProfileDetails($referenceId, Varien_Object $result) { $profile = Mage::registry('current_recurring_profile'); $subscriptionDetails = Mage::getModel('ricardomartins_pagseguro/recurring')->getPreApprovalDetails( $referenceId, $profile->getAdditionalInfo('isSandbox') ); if (!isset($subscriptionDetails->status)) { return false; } switch ((string)$subscriptionDetails->status) { case 'ACTIVE': $result->setIsProfileActive(true); break; case 'INITIATED': case 'PENDING': $result->setIsProfilePending(true); break; case 'CANCELLED': case 'CANCELLED_BY_RECEIVER': case 'CANCELLED_BY_SENDER': $result->setIsProfileCanceled(true); break; case 'EXPIRED': $result->setIsProfileExpired(true); break; case 'SUSPENDED': $result->setIsProfileSuspended(true); break; } if ($profile->getId()) { $currentInfo = $profile->getAdditionalInfo(); $currentInfo = is_array($currentInfo) ? $currentInfo : array(); $profile->setAdditionalInfo( array_merge( $currentInfo, array('tracker' => (string)$subscriptionDetails->tracker, 'reference' => (string)$subscriptionDetails->reference, 'status' => (string)$subscriptionDetails->status) ) ); $profile->save(); Mage::getModel('ricardomartins_pagseguro/recurring')->createOrders($profile); } $result->setAdditionalInformation(array('tracker' =>(string)$subscriptionDetails->tracker)); //este método é chamado quando forçamos a atualização de um perfil no admin e via cron } /** * Check whether can get recurring profile details * * @return bool */ public function canGetRecurringProfileDetails() { return true; //chamado quando entramos no perfil recorrente em Vendas > Perfil recorrente > clicamos em um perfil // TODO: Implement canGetRecurringProfileDetails() method. } /** * Update data * * @param Mage_Payment_Model_Recurring_Profile $profile */ public function updateRecurringProfile(Mage_Payment_Model_Recurring_Profile $profile) { //quando um perfil suspenso é reativado $a = 1; // TODO: Implement updateRecurringProfile() method. } /** * Manage status * * @param Mage_Payment_Model_Recurring_Profile $profile */ public function updateRecurringProfileStatus(Mage_Payment_Model_Recurring_Profile $profile) { switch ($profile->getNewState()) { case Mage_Sales_Model_Recurring_Profile::STATE_SUSPENDED: $this->changePagseguroStatus($profile, 'SUSPENDED'); break; case Mage_Sales_Model_Recurring_Profile::STATE_ACTIVE: $this->changePagseguroStatus($profile, 'ACTIVE'); break; case Mage_Sales_Model_Recurring_Profile::STATE_CANCELED: $this->cancelPagseguroProfile($profile); break; } $this->getRecurringProfileDetails($profile->getReferenceId(), new Varien_Object()); //método chamado quando clicamos em Suspender, Ativar ou Cancelar um perfil } /** * Create pagseguro plan and return plan code in Pagseguro * @param $profile * * @return string * @throws Mage_Core_Exception */ public function createPagseguroPlan($profile) { $helper = Mage::helper('ricardomartins_pagseguro/recurring'); $currentInfo = $profile->getAdditionalInfo(); $currentInfo = (!is_array($currentInfo)) ? array() : $currentInfo; $uniqIdRef = substr(strtoupper(uniqid()), 0, 7); //reference that will be used in product name and subscription $profile->setAdditionalInfo(array_merge($currentInfo, array('reference'=>$uniqIdRef))); $params = $helper->getCreatePlanParams($profile); $helper->writeLog('Criando plano de assinatura junto ao PagSeguro: ' . $params['preApprovalName']); $returnXml = $this->callApi($params, null, 'pre-approvals/request'); $this->validateCreatePlanResponse($returnXml); $profile->setReferenceId($params['reference']); $this->mergeAdditionalInfo( array('recurringReference' => $params['reference'], 'recurringPagseguroPlanCode' => (string)$returnXml->code, 'isSandbox' => Mage::helper('ricardomartins_pagseguro')->isSandbox(), ) ); $this->setPlanCode((string)$returnXml->code); return (string)$returnXml->code; } /** * @param string $pagseguroPlanCode * @param Mage_Payment_Model_Info $paymentInfo * @param Mage_Payment_Model_Recurring_Profile $profile */ public function subscribeToPlan($pagseguroPlanCode, $paymentInfo, $profile) { $reference = $profile->getAdditionalInfo('reference'); $profile->setReferenceId($reference); $profileInfo = $profile->getAdditionalInfo(); $profileInfo = !is_array($profileInfo) ? array() : $profileInfo; $profile->setAdditionalInfo(array_merge($profileInfo, array('pagSeguroPlanCode'=>$pagseguroPlanCode))); $jsonArray = array( 'plan' => $pagseguroPlanCode, 'reference' => $reference, 'sender' => Mage::helper('ricardomartins_pagseguro/params')->getSenderParamsJson($paymentInfo->getQuote()), 'paymentMethod' => Mage::helper('ricardomartins_pagseguro/params')->getPaymentParamsJson($paymentInfo), ); $body = Zend_Json::encode($jsonArray); $headers[] = 'Content-Type: application/json'; $headers[] = 'Accept: application/vnd.pagseguro.com.br.v1+json;charset=ISO-8859-1'; Mage::helper('ricardomartins_pagseguro/recurring')->writeLog('Aderindo cliente ao plano'); $response = $this->callJsonApi($body, $headers, 'pre-approvals', true); $this->validateJsonResponse($response); return $response; } /** * @param SimpleXMLElement $returnXml * @param array $errMsg * * @throws Mage_Core_Exception */ protected function validateCreatePlanResponse(SimpleXMLElement $returnXml) { $errMsg = array(); $rmHelper = Mage::helper('ricardomartins_pagseguro'); if (isset($returnXml->errors)) { foreach ($returnXml->errors as $error) { $errMsg[] = $rmHelper->__((string)$error->message) . ' (' . $error->code . ')'; } Mage::throwException( 'Um ou mais erros ocorreram ao criar seu plano de pagamento junto ao PagSeguro.' . PHP_EOL . implode( PHP_EOL, $errMsg ) ); } if (isset($returnXml->error)) { $error = $returnXml->error; $errMsg[] = $rmHelper->__((string)$error->message) . ' (' . $error->code . ')'; if (count($returnXml->error) > 1) { unset($errMsg); foreach ($returnXml->error as $error) { $errMsg[] = $rmHelper->__((string)$error->message) . ' (' . $error->code . ')'; } } Mage::throwException( 'Um erro ocorreu ao criar seu plano de pagamento junto ao PagSeguro.' . PHP_EOL . implode( PHP_EOL, $errMsg ) ); } if (!isset($returnXml->code)) { Mage::throwException( 'Um erro ocorreu ao tentar criar seu plano de pagamento junto ao Pagseugro. O código do plano' . ' não foi retornado.' ); } } }
gpl-2.0
autoplot/app
FitsDataSource/src/org/autoplot/fits/FitsDataSource.java
7967
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.autoplot.fits; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.das2.util.monitor.ProgressMonitor; import org.eso.fits.FitsData; import org.eso.fits.FitsFile; import org.eso.fits.FitsHDUnit; import org.eso.fits.FitsKeyword; import org.eso.fits.FitsMatrix; import org.eso.fits.FitsTable; import org.das2.qds.AbstractDataSet; import org.das2.qds.ArrayDataSet; import org.das2.qds.DataSetOps; import org.das2.qds.DataSetUtil; import org.das2.qds.FDataSet; import org.das2.qds.MutablePropertyDataSet; import org.das2.qds.QDataSet; import org.autoplot.datasource.AbstractDataSource; import org.autoplot.datasource.MetadataModel; import org.das2.qds.ops.Ops; /** * * @author jbf */ public class FitsDataSource extends AbstractDataSource { FitsDataSource(URI uri) { super(uri); } @Override public QDataSet getDataSet(ProgressMonitor mon) throws Exception { int ihdu = 0; Map<String, Integer> plottable = FitsDataSourceFactory.getPlottable(resourceURI, mon); String name = (String) getParams().get("arg_0"); if (name != null) { ihdu = plottable.get(name); } FitsFile file = new FitsFile(getFile(mon)); FitsHDUnit hdu = file.getHDUnit(ihdu); FitsData fd= hdu.getData(); ArrayDataSet result; if ( fd instanceof FitsMatrix ) { FitsMatrix dm = (FitsMatrix) hdu.getData(); int naxis[] = dm.getNaxis(); double crval[] = dm.getCrval(); double crpix[] = dm.getCrpix(); double cdelt[] = dm.getCdelt(); float[] fdata = new float[dm.getNoValues()]; dm.getFloatValues(0, dm.getNoValues(), fdata); if (naxis.length == 3) { naxis = new int[]{naxis[2], naxis[0], naxis[1]}; crval = new double[] { crval[2], crval[1], crval[0] }; crpix = new double[] { crpix[2], crpix[1], crpix[0] }; cdelt = new double[] { cdelt[2], cdelt[1], cdelt[0] }; } else if ( naxis.length==2 ) { naxis = new int[]{ naxis[1], naxis[0] }; crval = new double[] { crval[1], crval[0] }; crpix = new double[] { crpix[1], crpix[0] }; cdelt = new double[] { cdelt[1], cdelt[0] }; } else if ( naxis.length==0 ) { throw new IllegalArgumentException("Unable to use fits file"); } result = FDataSet.wrap(fdata, naxis); int rank = result.rank(); MutablePropertyDataSet xx; if ( rank==2 ) { xx= DataSetUtil.tagGenDataSet(naxis[0], crval[0] - cdelt[0] * crpix[0], cdelt[0]); xx.putProperty( QDataSet.NAME, "axis0" ); result.putProperty( "DEPEND_0", xx); xx= DataSetUtil.tagGenDataSet(naxis[1], crval[1] - cdelt[1] * crpix[1], cdelt[1]); xx.putProperty( QDataSet.NAME, "axis1" ); result.putProperty( "DEPEND_1", xx); return DataSetOps.transpose2(result); } else { xx= DataSetUtil.tagGenDataSet(naxis[2], crval[1] - cdelt[0] * crpix[0], cdelt[0]); xx.putProperty( QDataSet.NAME, "axis0" ); result.putProperty( "DEPEND_2", xx); xx= DataSetUtil.tagGenDataSet(naxis[1], crval[1] - cdelt[1] * crpix[1], cdelt[1]); xx.putProperty( QDataSet.NAME, "axis1" ); result.putProperty( "DEPEND_1", xx); xx = DataSetUtil.indexGenDataSet(naxis[0]); xx.putProperty( QDataSet.NAME, "bundle" ); result.putProperty("DEPEND_0",xx); return result; } } else if ( fd instanceof FitsTable ) { final FitsTable ft= (FitsTable)fd; MutablePropertyDataSet mpds= new AbstractDataSet() { @Override public int rank() { return 2; } @Override public double value( int i0, int i1 ) { return ft.getColumn(i1).getReal(i0); } @Override public int length() { return ft.getNoRows(); } @Override public int length(int i0) { return ft.getNoColumns(); } }; mpds.putProperty(QDataSet.QUBE,Boolean.TRUE); QDataSet bds= new AbstractDataSet() { @Override public int rank() { return 2; } @Override public double value( int i0, int i1 ) { return 1; } @Override public int length() { return ft.getNoColumns(); } @Override public int length(int i) { return 0; } @Override public Object property( String name, int i ) { if ( name.equals(QDataSet.LABEL) ) { return ft.getColumn(i).getLabel(); } else if ( name.equals(QDataSet.NAME) ) { return Ops.safeName(ft.getColumn(i).getLabel()); } else { return super.property(name); } } }; mpds.putProperty(QDataSet.BUNDLE_1,bds); if ( bds.length()==1 ) { return DataSetOps.unbundle(mpds,0); // scalar } else { return mpds; } } else { throw new IllegalArgumentException("fitsdata type not supported: "+fd.getClass() ); } } @Override public Map<String, Object> getMetadata(ProgressMonitor mon) throws Exception { int ihdu = 0; Map<String, Integer> plottable = FitsDataSourceFactory.getPlottable(uri, mon); String name = (String) getParams().get("arg_0"); if (name != null) { ihdu = plottable.get(name); } FitsFile file = new FitsFile(getFile(mon)); FitsHDUnit hdu = file.getHDUnit(ihdu); Map<String, Object> meta = new HashMap<String, Object>(); Enumeration e = hdu.getHeader().getKeywords(); while (e.hasMoreElements()) { FitsKeyword key = (FitsKeyword) e.nextElement(); Object val; switch (key.getType()) { case FitsKeyword.BOOLEAN: val = key.getBool(); break; case FitsKeyword.COMMENT: val = key.getComment(); break; case FitsKeyword.DATE: val = key.getDate(); break; case FitsKeyword.INTEGER: val = key.getInt(); break; case FitsKeyword.NONE: val = "NONE"; break; case FitsKeyword.REAL: val = key.getReal(); break; case FitsKeyword.STRING: val = key.getString(); break; default: val = "????"; } meta.put(key.getName(), val); } return meta; } @Override public MetadataModel getMetadataModel() { return new FitsMetadataModel(); } }
gpl-2.0
trungjc/ease
wp-content/plugins/motopress/mp/previewTooltip/previewTooltip.dev.js
385
steal('jquery/class', function($) { /** * @class MP.previewTooltip */ $.Class('MP.previewTooltip', /** @Static */ { previewTooltip: function() { $(".motopress-show-hide-btn").tooltip({ placement: "top", container: ".motopress-helper-container" }); } }, /** @Prototype */ {}) });
gpl-2.0
muromec/qtopia-ezx
src/3rdparty/libraries/helix/src/common/container/test/guid2ptr_tests.cpp
7282
/* ***** BEGIN LICENSE BLOCK ***** * Source last modified: $Id: guid2ptr_tests.cpp,v 1.3 2004/07/09 18:21:31 hubbe Exp $ * * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved. * * The contents of this file, and the files included with this file, * are subject to the current version of the RealNetworks Public * Source License (the "RPSL") available at * http://www.helixcommunity.org/content/rpsl unless you have licensed * the file under the current version of the RealNetworks Community * Source License (the "RCSL") available at * http://www.helixcommunity.org/content/rcsl, in which case the RCSL * will apply. You may also obtain the license terms directly from * RealNetworks. You may not use this file except in compliance with * the RPSL or, if you have a valid RCSL with RealNetworks applicable * to this file, the RCSL. Please see the applicable RPSL or RCSL for * the rights, obligations and limitations governing use of the * contents of the file. * * Alternatively, the contents of this file may be used under the * terms of the GNU General Public License Version 2 or later (the * "GPL") in which case the provisions of the GPL are applicable * instead of those above. If you wish to allow use of your version of * this file only under the terms of the GPL, and not to allow others * to use your version of this file under the terms of either the RPSL * or RCSL, indicate your decision by deleting the provisions above * and replace them with the notice and other provisions required by * the GPL. If you do not delete the provisions above, a recipient may * use your version of this file under the terms of any one of the * RPSL, the RCSL or the GPL. * * This file is part of the Helix DNA Technology. RealNetworks is the * developer of the Original Code and owns the copyrights in the * portions it created. * * This file, and the files included with this file, is distributed * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET * ENJOYMENT OR NON-INFRINGEMENT. * * Technology Compatibility Kit Test Suite(s) Location: * http://www.helixcommunity.org/content/tck * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ #include "./map_spec_tests.h" //#include "hxguidmap.h" #include "chxmapguidtoobj.h" #include "hx_ut_debug.h" #include "./hxlist.h" #include "./kv_store.h" #include "./find_match.h" template<> class MapSpecificTests<CHXMapGUIDToObj> { public: bool operator()(); private: bool TestIterator(); bool TestIterator2(); bool TestGetStartPosition(); bool TestGetNextAssoc(); }; bool MapSpecificTests<CHXMapGUIDToObj>::operator() () { bool ret = (TestIterator() && TestIterator2() && TestGetStartPosition() && TestGetNextAssoc()); DPRINTF (D_ERROR, ("MapSpecificTests<CHXMapGUIDToObj> : %d\n", ret)); return ret; } bool MapSpecificTests<CHXMapGUIDToObj>::TestIterator() { bool ret = true; CHXMapGUIDToObj map; KeyValueStore<GUID, void*> store; for (int i = 0; i < 10; i++) store.Create(i); for (int j = 0; j < store.GetCount(); j++) map.SetAt(store.GetKey(j), store.GetValue(j)); CHXMapGUIDToObj::Iterator itr = map.Begin(); HLXList<int> matchList; for (; ret && (itr != map.End()); ++itr) { int index = 0; if (!FindMatch<GUID, void*>()(store, *itr.get_key(), *itr, index)) { DPRINTF (D_ERROR, ("MapSpecificTests<CHXMapGUIDToObj>::TestIterator() : Failed to find key/value pair\n")); ret = false; } else if (matchList.Find(index)) { DPRINTF (D_ERROR, ("MapSpecificTests<CHXMapGUIDToObj>::TestIterator() : Index already in match list\n")); ret = false; } else { matchList.AddTail(index); } } if (ret && (matchList.GetCount() != map.GetCount())) { DPRINTF (D_ERROR, ("MapSpecificTests<CHXMapGUIDToObj>::TestIterator() : match list count does not match map count\n")); ret = false; } return ret; } bool MapSpecificTests<CHXMapGUIDToObj>::TestIterator2() { // This test is the same as TestIterator() except that // it uses the default constructor of the iterator. bool ret = true; CHXMapGUIDToObj map; KeyValueStore<GUID, void*> store; for (int i = 0; i < 10; i++) store.Create(i); for (int j = 0; j < store.GetCount(); j++) map.SetAt(store.GetKey(j), store.GetValue(j)); CHXMapGUIDToObj::Iterator itr; HLXList<int> matchList; for (itr = map.Begin(); ret && (itr != map.End()); ++itr) { int index = 0; if (!FindMatch<GUID, void*>()(store, *itr.get_key(), *itr, index)) { DPRINTF (D_ERROR, ("MapSpecificTests<CHXMapGUIDToObj>::TestIterator2() : Failed to find key/value pair\n")); ret = false; } else if (matchList.Find(index)) { DPRINTF (D_ERROR, ("MapSpecificTests<CHXMapGUIDToObj>::TestIterator2() : Index already in match list\n")); ret = false; } else { matchList.AddTail(index); } } if (ret && (matchList.GetCount() != map.GetCount())) { DPRINTF (D_ERROR, ("MapSpecificTests<CHXMapGUIDToObj>::TestIterator2() : match list count does not match map count\n")); ret = false; } return ret; } bool MapSpecificTests<CHXMapGUIDToObj>::TestGetStartPosition() { bool ret = false; CHXMapGUIDToObj map; POSITION pos = map.GetStartPosition(); if (!pos) { KeyValueStore<GUID, void*> store; store.Create(0); map.SetAt(store.GetKey(0), store.GetValue(0)); pos = map.GetStartPosition(); if (pos) ret = true; else { DPRINTF (D_ERROR, ("MapSpecificTests<CHXMapGUIDToObj>::TestGetStartPosition() : pos NULL for a non-empty map\n")); } } else { DPRINTF (D_ERROR, ("MapSpecificTests<CHXMapGUIDToObj>::TestGetStartPosition() : pos not NULL for an empty map\n")); } return ret; } bool MapSpecificTests<CHXMapGUIDToObj>::TestGetNextAssoc() { bool ret = true; CHXMapGUIDToObj map; KeyValueStore<GUID, void*> store; for (int i = 0; i < 10; i++) store.Create(i); for (int j = 0; j < store.GetCount(); j++) map.SetAt(store.GetKey(j), store.GetValue(j)); #ifdef DO_MAP_DUMP map.Dump(); #endif /* DO_MAP_DUMP */ POSITION pos = map.GetStartPosition(); HLXList<int> matchList; while (ret && pos) { GUID* pKey; void* value = 0; int index = 0; map.GetNextAssoc(pos, pKey, value); if (!FindMatch<GUID, void*>()(store, *pKey, value, index)) { DPRINTF (D_ERROR, ("MapSpecificTests<CHXMapGUIDToObj>::TestGetNextAssoc() : failed to find the key/value pair\n")); ret = false; } else if (matchList.Find(index)) { DPRINTF (D_ERROR, ("MapSpecificTests<CHXMapGUIDToObj>::TestGetNextAssoc() : Item %d already visited\n", index)); ret = false; } else matchList.AddTail(index); } if (ret && (matchList.GetCount() != map.GetCount())) { DPRINTF (D_ERROR, ("MapSpecificTests<CHXMapGUIDToObj>::TestGetNextAssoc() : items visited count doesn't match map item count\n")); ret = false; } return ret; }
gpl-2.0
lara-press/framework
src/LaraPress/Admin/Column.php
533
<?php namespace LaraPress\Admin; class Column { public $label; public $value; /** * Column constructor. * @param string $label * @param string|\Closure $value */ public function __construct(string $label, $value = null) { $this->label = $label; $this->value = $value; } public function getValue($postId) { if ($this->value instanceof \Closure) { return call_user_func($this->value, $postId); } return $this->value; } }
gpl-2.0
balp/mkgmap
src/uk/me/parabola/mkgmap/reader/osm/boundary/Osm5BoundaryDataSource.java
1647
/* * Copyright (C) 2006, 2011. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 or * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ package uk.me.parabola.mkgmap.reader.osm.boundary; import java.util.Set; import uk.me.parabola.mkgmap.reader.osm.MultiPolygonFinishHook; import uk.me.parabola.mkgmap.reader.osm.OsmReadingHooks; import uk.me.parabola.mkgmap.reader.osm.xml.Osm5MapDataSource; import uk.me.parabola.util.EnhancedProperties; public class Osm5BoundaryDataSource extends Osm5MapDataSource implements LoadableBoundaryDataSource { private BoundarySaver saver; protected void addBackground(boolean mapHasPolygon4B) { // do not add a background polygon } protected OsmReadingHooks[] getPossibleHooks() { return new OsmReadingHooks[] { new MultiPolygonFinishHook() }; } protected void createElementSaver() { elementSaver = new BoundaryElementSaver(getConfig(), saver); } public Set<String> getUsedTags() { // return null => all tags are used return null; } protected void createConverter() { converter = new BoundaryConverter(saver); } private final EnhancedProperties props = new EnhancedProperties(); protected EnhancedProperties getConfig() { return props; } public void setBoundarySaver(BoundarySaver saver) { this.saver = saver; } }
gpl-2.0
celsocelante/trab2prog3
CadastroRevisoes.cpp
4484
#include "CadastroRevisoes.h" CadastroRevisoes::CadastroRevisoes(const char* entrada, Revista* revista){ string cell, linha; string codigo; int codigo_int; string revisor; int revisor_int; string originalidade, apresentacao, conteudo; double originalidade_d, apresentacao_d,conteudo_d; ifstream inf(entrada); getline(inf, linha); while (getline(inf, linha)) { stringstream lineStream(linha); getline(lineStream,codigo,';'); // Converte o string lido para inteiro codigo_int = atoi(codigo.c_str()); getline(lineStream,revisor,';'); revisor_int = atoi(revisor.c_str()); // Lê as notas como string e as converte para um valor em double getline(lineStream,originalidade,';'); replace(originalidade.begin(),originalidade.end(), ',', '.'); originalidade_d = atof(originalidade.c_str()); getline(lineStream,conteudo,';'); replace(conteudo.begin(),conteudo.end(), ',', '.'); conteudo_d = atof(conteudo.c_str()); getline(lineStream,apresentacao,';'); replace(apresentacao.begin(),apresentacao.end(), ',', '.'); apresentacao_d = atof(apresentacao.c_str()); // Cria o stream para o texto da inconsistência e o transforma em string ostringstream texto_inconsistencia_stream; string texto_inconsistencia; Colaborador* c = revista->buscaColaborador(revisor_int); if(c == NULL || !(dynamic_cast<Revisor*>(c) != 0)){ // Trata inconsistencia #8: Revisor informado para revisao nao esta cadastrado texto_inconsistencia_stream << "O código " << revisor_int << " encontrado no cadastro de revisões não corresponde a um revisor cadastrado."; texto_inconsistencia = texto_inconsistencia_stream.str(); Inconsistencia* i = new Inconsistencia(texto_inconsistencia,8); revista->adicionaInconsistencia(i); } else{ Revisor* r = dynamic_cast<Revisor*>(c); Avaliacao* avaliacao = new Avaliacao(r); avaliacao->atribuirNota(originalidade_d,conteudo_d,apresentacao_d); Artigo* artigo = revista->getEdicao()->buscaArtigo(codigo_int); if(artigo == NULL){ texto_inconsistencia_stream.str(""); // Trata insconsistencia #9: código do artigo não está cadastrado em artigos submetidos à edição texto_inconsistencia_stream << "O código " << codigo_int << " encontrado no cadastro de revisões não corresponde a um artigo cadastrado."; texto_inconsistencia = texto_inconsistencia_stream.str(); Inconsistencia* i = new Inconsistencia(texto_inconsistencia,9); revista->adicionaInconsistencia(i); } else{ artigo->adicionaAvaliacao(avaliacao); r->vinculaRevisao(artigo); texto_inconsistencia_stream.str(""); // Trata inconsistencia #10: revisor não habilitado a revisar artigo sob tema da edição if(revista->getEdicao()->getTema() != NULL) if(!(revista->getEdicao()->getTema()->contemRevisor(r))){ texto_inconsistencia_stream << "O revisor " << r->getNome() << " avaliou o artigo " + artigo->getTitulo() << ", porém ele não consta como apto a avaliar o tema" << "\'" << revista->getEdicao()->getTema()->getTitulo() << "\'" << " desta edição."; texto_inconsistencia = texto_inconsistencia_stream.str(); Inconsistencia* i = new Inconsistencia(texto_inconsistencia,10); revista->adicionaInconsistencia(i); } } } } // Ordena os artigos submetidos a edição pelas médias das revisões cadastradas para cada artigo revista->getEdicao()->ordenaSubmetidos(); // Trata inconsistencia #11: revisor não habilitado a revisar artigo sob tema da edição ostringstream texto_inconsistencia_stream; string texto_inconsistencia; set<Artigo*>::iterator it; for(it = revista->getEdicao()->getArtigos()->begin(); it != revista->getEdicao()->getArtigos()->end(); ++it){ Artigo* a = *it; if (!a->quantidadeRevisoes()){ texto_inconsistencia_stream << "O artigo " << "\"" << a->getTitulo() << "\"" << " possui " << a->getQuantidadeRevisoes() << " revisões. Cada artigo deve conter exatamente 3 revisões."; texto_inconsistencia = texto_inconsistencia_stream.str(); Inconsistencia* i = new Inconsistencia(texto_inconsistencia,11); revista->adicionaInconsistencia(i); // Limpa o stream de mensagem de inconsistencia texto_inconsistencia_stream.str(""); } } }
gpl-2.0
iproduct/IPT-Course-Java-8
IPT-Course-Java-33ed/invoicing/src/invoicing/exception/NonExistingEntityException.java
499
package invoicing.exception; public class NonExistingEntityException extends Exception { public NonExistingEntityException() { } public NonExistingEntityException(String arg0) { super(arg0); } public NonExistingEntityException(Throwable arg0) { super(arg0); } public NonExistingEntityException(String arg0, Throwable arg1) { super(arg0, arg1); } public NonExistingEntityException(String arg0, Throwable arg1, boolean arg2, boolean arg3) { super(arg0, arg1, arg2, arg3); } }
gpl-2.0
CharlesZ-Chen/checker-framework
checker/jtreg/nullness/inheritDeclAnnoPersist/Extends.java
1343
/* * @test * @summary Test that inherited declaration annotations are stored in bytecode. * * @compile -source 7 -target 7 ../PersistUtil.java Driver.java ReferenceInfoUtil.java Extends.java Super.java * @run main Driver Extends */ public class Extends { @ADescriptions({ @ADescription(annotation = "org/checkerframework/checker/nullness/qual/EnsuresNonNull") }) public String m1() { StringBuilder sb = new StringBuilder(); return TestWrapper.wrap("@Override void setf() {f = new Object();}\n"); } @ADescriptions({}) public String m2() { return TestWrapper.wrap("@Override void setg() {}\n"); } // Issue 342 // We do not want that behavior with related annotations. @Pure should // override @SideEffectFree. @ADescriptions({ @ADescription(annotation = "org/checkerframework/dataflow/qual/Pure"), @ADescription(annotation = "org/checkerframework/dataflow/qual/SideEffectFree") }) public String m3() { return TestWrapper.wrap("@Pure @Override void seth() {}\n"); } } class TestWrapper { public static String wrap(String method) { StringBuilder sb = new StringBuilder(); sb.append("class Test extends Super {\n"); sb.append(method); sb.append("}"); return sb.toString(); } }
gpl-2.0
Argalep/ServUO
Scripts/Services/ChampionSystem/ChampionSpawn.cs
50038
using Server.Gumps; using Server.Items; using Server.Mobiles; using Server.Regions; using Server.Services.Virtues; using Server.Spells.Necromancy; using System; using System.Collections.Generic; using System.Linq; namespace Server.Engines.CannedEvil { public class ChampionSpawn : Item { public static readonly int MaxStrayDistance = 250; private bool m_Active; private bool m_RandomizeType; private ChampionSpawnType m_Type; private List<Mobile> m_Creatures; private List<Item> m_RedSkulls; private List<Item> m_WhiteSkulls; private ChampionPlatform m_Platform; private ChampionAltar m_Altar; private int m_Kills; private Mobile m_Champion; //private int m_SpawnRange; private Rectangle2D m_SpawnArea; private ChampionSpawnRegion m_Region; private TimeSpan m_ExpireDelay; private DateTime m_ExpireTime; private TimeSpan m_RestartDelay; private DateTime m_RestartTime; private Timer m_Timer, m_RestartTimer; private IdolOfTheChampion m_Idol; private bool m_HasBeenAdvanced; private bool m_ConfinedRoaming; private Dictionary<Mobile, int> m_DamageEntries; public List<Mobile> Creatures => m_Creatures; [CommandProperty(AccessLevel.GameMaster)] public string GroupName { get; set; } [CommandProperty(AccessLevel.GameMaster)] public double SpawnMod { get; set; } [CommandProperty(AccessLevel.GameMaster)] public int SpawnRadius { get; set; } [CommandProperty(AccessLevel.GameMaster)] public double KillsMod { get; set; } [CommandProperty(AccessLevel.GameMaster)] public bool AutoRestart { get; set; } [CommandProperty(AccessLevel.GameMaster)] public string SpawnName { get; set; } [CommandProperty(AccessLevel.GameMaster)] public bool ConfinedRoaming { get { return m_ConfinedRoaming; } set { m_ConfinedRoaming = value; } } [CommandProperty(AccessLevel.GameMaster)] public bool HasBeenAdvanced { get { return m_HasBeenAdvanced; } set { m_HasBeenAdvanced = value; } } [Constructable] public ChampionSpawn() : base(0xBD2) { Movable = false; Visible = false; m_Creatures = new List<Mobile>(); m_RedSkulls = new List<Item>(); m_WhiteSkulls = new List<Item>(); m_Platform = new ChampionPlatform(this); m_Altar = new ChampionAltar(this); m_Idol = new IdolOfTheChampion(this); m_ExpireDelay = TimeSpan.FromMinutes(10.0); m_RestartDelay = TimeSpan.FromMinutes(10.0); m_DamageEntries = new Dictionary<Mobile, int>(); m_RandomizeType = false; SpawnRadius = 35; SpawnMod = 1; Timer.DelayCall(TimeSpan.Zero, new TimerCallback(SetInitialSpawnArea)); } public void SetInitialSpawnArea() { //Previous default used to be 24; SpawnArea = new Rectangle2D(new Point2D(X - SpawnRadius, Y - SpawnRadius), new Point2D(X + SpawnRadius, Y + SpawnRadius)); } public void UpdateRegion() { if (m_Region != null) m_Region.Unregister(); if (!Deleted && Map != Map.Internal) { m_Region = new ChampionSpawnRegion(this); m_Region.Register(); } } [CommandProperty(AccessLevel.GameMaster)] public bool RandomizeType { get { return m_RandomizeType; } set { m_RandomizeType = value; } } [CommandProperty(AccessLevel.GameMaster)] public int Kills { get { return m_Kills; } set { m_Kills = value; InvalidateProperties(); } } [CommandProperty(AccessLevel.GameMaster)] public Rectangle2D SpawnArea { get { return m_SpawnArea; } set { m_SpawnArea = value; InvalidateProperties(); UpdateRegion(); } } [CommandProperty(AccessLevel.GameMaster)] public TimeSpan RestartDelay { get { return m_RestartDelay; } set { m_RestartDelay = value; } } [CommandProperty(AccessLevel.GameMaster)] public DateTime RestartTime => m_RestartTime; [CommandProperty(AccessLevel.GameMaster)] public TimeSpan ExpireDelay { get { return m_ExpireDelay; } set { m_ExpireDelay = value; } } [CommandProperty(AccessLevel.GameMaster)] public DateTime ExpireTime { get { return m_ExpireTime; } set { m_ExpireTime = value; } } [CommandProperty(AccessLevel.GameMaster)] public ChampionSpawnType Type { get { return m_Type; } set { m_Type = value; InvalidateProperties(); } } [CommandProperty(AccessLevel.GameMaster)] public bool Active { get { return m_Active; } set { if (value) Start(); else Stop(); PrimevalLichPuzzle.Update(this); InvalidateProperties(); } } [CommandProperty(AccessLevel.GameMaster)] public Mobile Champion { get { return m_Champion; } set { m_Champion = value; } } [CommandProperty(AccessLevel.GameMaster)] public int Level { get { return m_RedSkulls.Count; } set { for (int i = m_RedSkulls.Count - 1; i >= value; --i) { m_RedSkulls[i].Delete(); m_RedSkulls.RemoveAt(i); } for (int i = m_RedSkulls.Count; i < value; ++i) { Item skull = new Item(0x1854); skull.Hue = 0x26; skull.Movable = false; skull.Light = LightType.Circle150; skull.MoveToWorld(GetRedSkullLocation(i), Map); m_RedSkulls.Add(skull); } InvalidateProperties(); } } [CommandProperty(AccessLevel.GameMaster)] public int StartLevel { get; private set; } private void RemoveSkulls() { if (m_WhiteSkulls != null) { for (int i = 0; i < m_WhiteSkulls.Count; ++i) m_WhiteSkulls[i].Delete(); m_WhiteSkulls.Clear(); } if (m_RedSkulls != null) { for (int i = 0; i < m_RedSkulls.Count; i++) m_RedSkulls[i].Delete(); m_RedSkulls.Clear(); } } public int MaxKills { get { int l = Level; return ChampionSystem.MaxKillsForLevel(l); } } public bool IsChampionSpawn(Mobile m) { return m_Creatures.Contains(m); } public void SetWhiteSkullCount(int val) { for (int i = m_WhiteSkulls.Count - 1; i >= val; --i) { m_WhiteSkulls[i].Delete(); m_WhiteSkulls.RemoveAt(i); } for (int i = m_WhiteSkulls.Count; i < val; ++i) { Item skull = new Item(0x1854); skull.Movable = false; skull.Light = LightType.Circle150; skull.MoveToWorld(GetWhiteSkullLocation(i), Map); m_WhiteSkulls.Add(skull); Effects.PlaySound(skull.Location, skull.Map, 0x29); Effects.SendLocationEffect(new Point3D(skull.X + 1, skull.Y + 1, skull.Z), skull.Map, 0x3728, 10); } } public void Start(bool serverLoad = false) { if (m_Active || Deleted) return; m_Active = true; m_HasBeenAdvanced = false; if (m_Timer != null) m_Timer.Stop(); m_Timer = new SliceTimer(this); m_Timer.Start(); if (m_RestartTimer != null) m_RestartTimer.Stop(); m_RestartTimer = null; if (m_Altar != null) m_Altar.Hue = 0; PrimevalLichPuzzle.Update(this); if (!serverLoad) { double chance = Utility.RandomDouble(); if (chance < 0.1) Level = 4; else if (chance < 0.25) Level = 3; else if (chance < 0.5) Level = 2; else if (Utility.RandomBool()) Level = 1; StartLevel = Level; if (Level > 0 && m_Altar != null) { Effects.PlaySound(m_Altar.Location, m_Altar.Map, 0x29); Effects.SendLocationEffect(new Point3D(m_Altar.X + 1, m_Altar.Y + 1, m_Altar.Z), m_Altar.Map, 0x3728, 10); } } } public void Stop() { if (!m_Active || Deleted) return; m_Active = false; m_HasBeenAdvanced = false; // We must despawn all the creatures. if (m_Creatures != null) { for (int i = 0; i < m_Creatures.Count; ++i) m_Creatures[i].Delete(); m_Creatures.Clear(); } if (m_Timer != null) m_Timer.Stop(); m_Timer = null; if (m_RestartTimer != null) m_RestartTimer.Stop(); m_RestartTimer = null; if (m_Altar != null) m_Altar.Hue = 0x455; PrimevalLichPuzzle.Update(this); RemoveSkulls(); m_Kills = 0; } public void BeginRestart(TimeSpan ts) { if (m_RestartTimer != null) m_RestartTimer.Stop(); m_RestartTime = DateTime.UtcNow + ts; m_RestartTimer = new RestartTimer(this, ts); m_RestartTimer.Start(); } public void EndRestart() { if (RandomizeType) { switch (Utility.Random(5)) { case 0: Type = ChampionSpawnType.Abyss; break; case 1: Type = ChampionSpawnType.Arachnid; break; case 2: Type = ChampionSpawnType.ColdBlood; break; case 3: Type = ChampionSpawnType.VerminHorde; break; case 4: Type = ChampionSpawnType.UnholyTerror; break; } } m_HasBeenAdvanced = false; Start(); } #region Scroll of Transcendence private ScrollOfTranscendence CreateRandomSoT(bool felucca) { int level = Utility.RandomMinMax(1, 5); if (felucca) level += 5; return ScrollOfTranscendence.CreateRandom(level, level); } #endregion public static void GiveScrollTo(Mobile killer, SpecialScroll scroll) { if (scroll == null || killer == null) //sanity return; if (scroll is ScrollOfTranscendence) killer.SendLocalizedMessage(1094936); // You have received a Scroll of Transcendence! else killer.SendLocalizedMessage(1049524); // You have received a scroll of power! if (killer.Alive) killer.AddToBackpack(scroll); else { if (killer.Corpse != null && !killer.Corpse.Deleted) killer.Corpse.DropItem(scroll); else killer.AddToBackpack(scroll); } // Justice reward PlayerMobile pm = (PlayerMobile)killer; for (int j = 0; j < pm.JusticeProtectors.Count; ++j) { Mobile prot = pm.JusticeProtectors[j]; if (prot.Map != killer.Map || prot.Murderer || prot.Criminal || !JusticeVirtue.CheckMapRegion(killer, prot)) continue; int chance = 0; switch (VirtueHelper.GetLevel(prot, VirtueName.Justice)) { case VirtueLevel.Seeker: chance = 60; break; case VirtueLevel.Follower: chance = 80; break; case VirtueLevel.Knight: chance = 100; break; } if (chance > Utility.Random(100)) { try { prot.SendLocalizedMessage(1049368); // You have been rewarded for your dedication to Justice! SpecialScroll scrollDupe = Activator.CreateInstance(scroll.GetType()) as SpecialScroll; if (scrollDupe != null) { scrollDupe.Skill = scroll.Skill; scrollDupe.Value = scroll.Value; prot.AddToBackpack(scrollDupe); } } catch { } } } } private DateTime _NextGhostCheck; public void OnSlice() { if (!m_Active || Deleted) return; int currentRank = Rank; if (m_Champion != null) { if (m_Champion.Deleted) { RegisterDamageTo(m_Champion); if (m_Champion is BaseChampion) AwardArtifact(((BaseChampion)m_Champion).GetArtifact()); m_DamageEntries.Clear(); if (m_Altar != null) { m_Altar.Hue = 0x455; if (Map == Map.Felucca) { new StarRoomGate(true, m_Altar.Location, m_Altar.Map); } } m_Champion = null; Stop(); if (AutoRestart) BeginRestart(m_RestartDelay); } else if (m_Champion.Alive && m_Champion.GetDistanceToSqrt(this) > MaxStrayDistance) { m_Champion.MoveToWorld(new Point3D(X, Y, Z - 15), Map); } } else { int kills = m_Kills; for (int i = 0; i < m_Creatures.Count; ++i) { Mobile m = m_Creatures[i]; if (m.Deleted) { if (m.Corpse != null && !m.Corpse.Deleted) { ((Corpse)m.Corpse).BeginDecay(TimeSpan.FromMinutes(1)); } m_Creatures.RemoveAt(i); --i; int rankOfMob = GetRankFor(m); if (rankOfMob == currentRank) ++m_Kills; Mobile killer = m.FindMostRecentDamager(false); RegisterDamageTo(m); if (killer is BaseCreature) killer = ((BaseCreature)killer).GetMaster(); if (killer is PlayerMobile) { #region Scroll of Transcendence if (Map == Map.Felucca) { if (Utility.RandomDouble() < ChampionSystem.ScrollChance) { PlayerMobile pm = (PlayerMobile)killer; if (Utility.RandomDouble() < ChampionSystem.TranscendenceChance) { ScrollOfTranscendence SoTF = CreateRandomSoT(true); GiveScrollTo(pm, SoTF); } else { PowerScroll PS = PowerScroll.CreateRandomNoCraft(5, 5); GiveScrollTo(pm, PS); } } } if (Map == Map.Ilshenar || Map == Map.Tokuno || Map == Map.Malas) { if (Utility.RandomDouble() < 0.0015) { killer.SendLocalizedMessage(1094936); // You have received a Scroll of Transcendence! ScrollOfTranscendence SoTT = CreateRandomSoT(false); killer.AddToBackpack(SoTT); } } #endregion int mobSubLevel = rankOfMob + 1; if (mobSubLevel >= 0) { bool gainedPath = false; int pointsToGain = mobSubLevel * 40; if (VirtueHelper.Award(killer, VirtueName.Valor, pointsToGain, ref gainedPath)) { if (gainedPath) killer.SendLocalizedMessage(1054032); // You have gained a path in Valor! else killer.SendLocalizedMessage(1054030); // You have gained in Valor! //No delay on Valor gains } PlayerMobile.ChampionTitleInfo info = ((PlayerMobile)killer).ChampionTitles; info.Award(m_Type, mobSubLevel); Server.Engines.CityLoyalty.CityLoyaltySystem.OnSpawnCreatureKilled(m as BaseCreature, mobSubLevel); } } } } // Only really needed once. if (m_Kills > kills) InvalidateProperties(); double n = m_Kills / (double)MaxKills; int p = (int)(n * 100); if (p >= 90) AdvanceLevel(); else if (p > 0) SetWhiteSkullCount(p / 20); if (DateTime.UtcNow >= m_ExpireTime) Expire(); Respawn(); } if (m_Timer != null && m_Timer.Running && _NextGhostCheck < DateTime.UtcNow) { foreach (PlayerMobile ghost in m_Region.GetEnumeratedMobiles().OfType<PlayerMobile>().Where(pm => !pm.Alive && (pm.Corpse == null || pm.Corpse.Deleted))) { Map map = ghost.Map; Point3D loc = ExorcismSpell.GetNearestShrine(ghost, ref map); if (loc != Point3D.Zero) { ghost.MoveToWorld(loc, map); } else { ghost.MoveToWorld(new Point3D(989, 520, -50), Map.Malas); } } _NextGhostCheck = DateTime.UtcNow + TimeSpan.FromMinutes(Utility.RandomMinMax(5, 8)); } } public void AdvanceLevel() { m_ExpireTime = DateTime.UtcNow + m_ExpireDelay; if (Level < 16) { m_Kills = 0; ++Level; InvalidateProperties(); SetWhiteSkullCount(0); if (m_Altar != null) { Effects.PlaySound(m_Altar.Location, m_Altar.Map, 0x29); Effects.SendLocationEffect(new Point3D(m_Altar.X + 1, m_Altar.Y + 1, m_Altar.Z), m_Altar.Map, 0x3728, 10); } } else { SpawnChampion(); } } public void SpawnChampion() { m_Kills = 0; Level = 0; StartLevel = 0; InvalidateProperties(); SetWhiteSkullCount(0); try { m_Champion = Activator.CreateInstance(ChampionSpawnInfo.GetInfo(m_Type).Champion) as Mobile; } catch { } if (m_Champion != null) { Point3D p = new Point3D(X, Y, Z - 15); m_Champion.MoveToWorld(p, Map); ((BaseCreature)m_Champion).Home = p; if (m_Champion is BaseChampion) { ((BaseChampion)m_Champion).OnChampPopped(this); } } } public void Respawn() { if (!m_Active || Deleted || m_Champion != null) return; int currentLevel = Level; int currentRank = Rank; int maxSpawn = (int)(MaxKills * 0.5d * SpawnMod); if (currentLevel >= 16) maxSpawn = Math.Min(maxSpawn, MaxKills - m_Kills); if (maxSpawn < 3) maxSpawn = 3; int spawnRadius = (int)(SpawnRadius * ChampionSystem.SpawnRadiusModForLevel(Level)); Rectangle2D spawnBounds = new Rectangle2D(new Point2D(X - spawnRadius, Y - spawnRadius), new Point2D(X + spawnRadius, Y + spawnRadius)); int mobCount = 0; foreach (Mobile m in m_Creatures) { if (GetRankFor(m) == currentRank) ++mobCount; } while (mobCount <= maxSpawn) { Mobile m = Spawn(); if (m == null) return; Point3D loc = GetSpawnLocation(spawnBounds, spawnRadius); // Allow creatures to turn into Paragons at Ilshenar champions. m.OnBeforeSpawn(loc, Map); m_Creatures.Add(m); m.MoveToWorld(loc, Map); ++mobCount; if (m is BaseCreature) { BaseCreature bc = m as BaseCreature; bc.Tamable = false; bc.IsChampionSpawn = true; if (!m_ConfinedRoaming) { bc.Home = Location; bc.RangeHome = spawnRadius; } else { bc.Home = bc.Location; Point2D xWall1 = new Point2D(spawnBounds.X, bc.Y); Point2D xWall2 = new Point2D(spawnBounds.X + spawnBounds.Width, bc.Y); Point2D yWall1 = new Point2D(bc.X, spawnBounds.Y); Point2D yWall2 = new Point2D(bc.X, spawnBounds.Y + spawnBounds.Height); double minXDist = Math.Min(bc.GetDistanceToSqrt(xWall1), bc.GetDistanceToSqrt(xWall2)); double minYDist = Math.Min(bc.GetDistanceToSqrt(yWall1), bc.GetDistanceToSqrt(yWall2)); bc.RangeHome = (int)Math.Min(minXDist, minYDist); } } } } public Point3D GetSpawnLocation() { return GetSpawnLocation(m_SpawnArea, 24); } public Point3D GetSpawnLocation(Rectangle2D rect, int range) { Map map = Map; if (map == null) return Location; int cx = Location.X; int cy = Location.Y; // Try 20 times to find a spawnable location. for (int i = 0; i < 20; i++) { int dx = Utility.Random(range * 2); int dy = Utility.Random(range * 2); int x = rect.X + dx; int y = rect.Y + dy; // Make spawn area circular //if ((cx - x) * (cx - x) + (cy - y) * (cy - y) > range * range) // continue; int z = Map.GetAverageZ(x, y); if (Map.CanSpawnMobile(new Point2D(x, y), z)) return new Point3D(x, y, z); /* try @ platform Z if map z fails */ else if (Map.CanSpawnMobile(new Point2D(x, y), m_Platform.Location.Z)) return new Point3D(x, y, m_Platform.Location.Z); } return Location; } public int Rank => ChampionSystem.RankForLevel(Level); public int GetRankFor(Mobile m) { Type[][] types = ChampionSpawnInfo.GetInfo(m_Type).SpawnTypes; Type t = m.GetType(); for (int i = 0; i < types.GetLength(0); i++) { Type[] individualTypes = types[i]; for (int j = 0; j < individualTypes.Length; j++) { if (t == individualTypes[j]) return i; } } return -1; } public Mobile Spawn() { Type[][] types = ChampionSpawnInfo.GetInfo(m_Type).SpawnTypes; int v = Rank; if (v >= 0 && v < types.Length) return Spawn(types[v]); return null; } public Mobile Spawn(params Type[] types) { try { return Activator.CreateInstance(types[Utility.Random(types.Length)]) as Mobile; } catch { return null; } } public void Expire() { m_Kills = 0; if (m_WhiteSkulls.Count == 0) { // They didn't even get 20%, go back a level if (Level > StartLevel) --Level; InvalidateProperties(); } else { SetWhiteSkullCount(0); } m_ExpireTime = DateTime.UtcNow + m_ExpireDelay; } public Point3D GetRedSkullLocation(int index) { int x, y; if (index < 5) { x = index - 2; y = -2; } else if (index < 9) { x = 2; y = index - 6; } else if (index < 13) { x = 10 - index; y = 2; } else { x = -2; y = 14 - index; } return new Point3D(X + x, Y + y, Z - 15); } public Point3D GetWhiteSkullLocation(int index) { int x, y; switch (index) { default: case 0: x = -1; y = -1; break; case 1: x = 1; y = -1; break; case 2: x = 1; y = 1; break; case 3: x = -1; y = 1; break; } return new Point3D(X + x, Y + y, Z - 15); } public override void AddNameProperty(ObjectPropertyList list) { list.Add("champion spawn"); } public override void GetProperties(ObjectPropertyList list) { base.GetProperties(list); if (m_Active) { list.Add(1060742); // active list.Add(1060658, "Type\t{0}", m_Type); // ~1_val~: ~2_val~ list.Add(1060659, "Level\t{0}", Level); // ~1_val~: ~2_val~ list.Add(1060660, "Kills\t{0} of {1} ({2:F1}%)", m_Kills, MaxKills, 100.0 * ((double)m_Kills / MaxKills)); // ~1_val~: ~2_val~ //list.Add( 1060661, "Spawn Range\t{0}", m_SpawnRange ); // ~1_val~: ~2_val~ } else { list.Add(1060743); // inactive } } public override void OnDoubleClick(Mobile from) { from.SendGump(new PropertiesGump(from, this)); } public override void OnLocationChange(Point3D oldLoc) { if (Deleted) return; if (m_Platform != null) m_Platform.Location = new Point3D(X, Y, Z - 20); if (m_Altar != null) m_Altar.Location = new Point3D(X, Y, Z - 15); if (m_Idol != null) m_Idol.Location = new Point3D(X, Y, Z - 15); if (m_RedSkulls != null) { for (int i = 0; i < m_RedSkulls.Count; ++i) m_RedSkulls[i].Location = GetRedSkullLocation(i); } if (m_WhiteSkulls != null) { for (int i = 0; i < m_WhiteSkulls.Count; ++i) m_WhiteSkulls[i].Location = GetWhiteSkullLocation(i); } m_SpawnArea.X += Location.X - oldLoc.X; m_SpawnArea.Y += Location.Y - oldLoc.Y; UpdateRegion(); } public override void OnMapChange() { if (Deleted) return; if (m_Platform != null) m_Platform.Map = Map; if (m_Altar != null) m_Altar.Map = Map; if (m_Idol != null) m_Idol.Map = Map; if (m_RedSkulls != null) { for (int i = 0; i < m_RedSkulls.Count; ++i) m_RedSkulls[i].Map = Map; } if (m_WhiteSkulls != null) { for (int i = 0; i < m_WhiteSkulls.Count; ++i) m_WhiteSkulls[i].Map = Map; } UpdateRegion(); } public override void OnAfterDelete() { base.OnAfterDelete(); if (m_Platform != null) m_Platform.Delete(); if (m_Altar != null) m_Altar.Delete(); if (m_Idol != null) m_Idol.Delete(); RemoveSkulls(); if (m_Creatures != null) { for (int i = 0; i < m_Creatures.Count; ++i) { Mobile mob = m_Creatures[i]; if (!mob.Player) mob.Delete(); } m_Creatures.Clear(); } if (m_Champion != null && !m_Champion.Player) m_Champion.Delete(); Stop(); UpdateRegion(); } public ChampionSpawn(Serial serial) : base(serial) { } public virtual void RegisterDamageTo(Mobile m) { if (m == null) return; foreach (DamageEntry de in m.DamageEntries) { if (de.HasExpired) continue; Mobile damager = de.Damager; Mobile master = damager.GetDamageMaster(m); if (master != null) damager = master; RegisterDamage(damager, de.DamageGiven); } } public void RegisterDamage(Mobile from, int amount) { if (from == null || !from.Player) return; if (m_DamageEntries.ContainsKey(from)) m_DamageEntries[from] += amount; else m_DamageEntries.Add(from, amount); } public void AwardArtifact(Item artifact) { if (artifact == null) return; int totalDamage = 0; Dictionary<Mobile, int> validEntries = new Dictionary<Mobile, int>(); foreach (KeyValuePair<Mobile, int> kvp in m_DamageEntries) { if (IsEligible(kvp.Key, artifact)) { validEntries.Add(kvp.Key, kvp.Value); totalDamage += kvp.Value; } } int randomDamage = Utility.RandomMinMax(1, totalDamage); totalDamage = 0; foreach (KeyValuePair<Mobile, int> kvp in validEntries) { totalDamage += kvp.Value; if (totalDamage >= randomDamage) { GiveArtifact(kvp.Key, artifact); return; } } artifact.Delete(); } public void GiveArtifact(Mobile to, Item artifact) { if (to == null || artifact == null) return; to.PlaySound(0x5B4); Container pack = to.Backpack; if (pack == null || !pack.TryDropItem(to, artifact, false)) artifact.Delete(); else to.SendLocalizedMessage(1062317); // For your valor in combating the fallen beast, a special artifact has been bestowed on you. } public bool IsEligible(Mobile m, Item Artifact) { return m.Player && m.Alive && m.Region != null && m.Region == m_Region && m.Backpack != null && m.Backpack.CheckHold(m, Artifact, false); } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write(8); // version writer.Write(StartLevel); writer.Write(KillsMod); writer.Write(GroupName); writer.Write(SpawnName); writer.Write(AutoRestart); writer.Write(SpawnMod); writer.Write(SpawnRadius); writer.Write(m_DamageEntries.Count); foreach (KeyValuePair<Mobile, int> kvp in m_DamageEntries) { writer.Write(kvp.Key); writer.Write(kvp.Value); } writer.Write(m_ConfinedRoaming); writer.WriteItem<IdolOfTheChampion>(m_Idol); writer.Write(m_HasBeenAdvanced); writer.Write(m_SpawnArea); writer.Write(m_RandomizeType); // writer.Write( m_SpawnRange ); writer.Write(m_Kills); writer.Write(m_Active); writer.Write((int)m_Type); writer.Write(m_Creatures, true); writer.Write(m_RedSkulls, true); writer.Write(m_WhiteSkulls, true); writer.WriteItem<ChampionPlatform>(m_Platform); writer.WriteItem<ChampionAltar>(m_Altar); writer.Write(m_ExpireDelay); writer.WriteDeltaTime(m_ExpireTime); writer.Write(m_Champion); writer.Write(m_RestartDelay); writer.Write(m_RestartTimer != null); if (m_RestartTimer != null) writer.WriteDeltaTime(m_RestartTime); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); m_DamageEntries = new Dictionary<Mobile, int>(); int version = reader.ReadInt(); switch (version) { case 8: StartLevel = reader.ReadInt(); goto case 7; case 7: KillsMod = reader.ReadDouble(); GroupName = reader.ReadString(); goto case 6; case 6: SpawnName = reader.ReadString(); AutoRestart = reader.ReadBool(); SpawnMod = reader.ReadDouble(); SpawnRadius = reader.ReadInt(); goto case 5; case 5: { int entries = reader.ReadInt(); Mobile m; int damage; for (int i = 0; i < entries; ++i) { m = reader.ReadMobile(); damage = reader.ReadInt(); if (m == null) continue; m_DamageEntries.Add(m, damage); } goto case 4; } case 4: { m_ConfinedRoaming = reader.ReadBool(); m_Idol = reader.ReadItem<IdolOfTheChampion>(); m_HasBeenAdvanced = reader.ReadBool(); goto case 3; } case 3: { m_SpawnArea = reader.ReadRect2D(); goto case 2; } case 2: { m_RandomizeType = reader.ReadBool(); goto case 1; } case 1: { if (version < 3) { int oldRange = reader.ReadInt(); m_SpawnArea = new Rectangle2D(new Point2D(X - oldRange, Y - oldRange), new Point2D(X + oldRange, Y + oldRange)); } m_Kills = reader.ReadInt(); goto case 0; } case 0: { if (version < 1) m_SpawnArea = new Rectangle2D(new Point2D(X - 24, Y - 24), new Point2D(X + 24, Y + 24)); //Default was 24 bool active = reader.ReadBool(); m_Type = (ChampionSpawnType)reader.ReadInt(); m_Creatures = reader.ReadStrongMobileList(); m_RedSkulls = reader.ReadStrongItemList(); m_WhiteSkulls = reader.ReadStrongItemList(); m_Platform = reader.ReadItem<ChampionPlatform>(); m_Altar = reader.ReadItem<ChampionAltar>(); m_ExpireDelay = reader.ReadTimeSpan(); m_ExpireTime = reader.ReadDeltaTime(); m_Champion = reader.ReadMobile(); m_RestartDelay = reader.ReadTimeSpan(); if (reader.ReadBool()) { m_RestartTime = reader.ReadDeltaTime(); BeginRestart(m_RestartTime - DateTime.UtcNow); } if (version < 4) { m_Idol = new IdolOfTheChampion(this); m_Idol.MoveToWorld(new Point3D(X, Y, Z - 15), Map); } if (m_Platform == null || m_Altar == null || m_Idol == null) Delete(); else if (active) Start(true); break; } } foreach (BaseCreature bc in m_Creatures.OfType<BaseCreature>()) { bc.IsChampionSpawn = true; } Timer.DelayCall(TimeSpan.Zero, new TimerCallback(UpdateRegion)); } public void SendGump(Mobile mob) { mob.SendGump(new ChampionSpawnInfoGump(this)); } private class ChampionSpawnInfoGump : Gump { private class Damager { public Mobile Mobile; public int Damage; public Damager(Mobile mob, int dmg) { Mobile = mob; Damage = dmg; } } private const int gBoarder = 20; private const int gRowHeight = 25; private const int gFontHue = 0; private static readonly int[] gWidths = { 20, 160, 160, 20 }; private static readonly int[] gTab; private static readonly int gWidth; static ChampionSpawnInfoGump() { gWidth = gWidths.Sum(); int tab = 0; gTab = new int[gWidths.Length]; for (int i = 0; i < gWidths.Length; ++i) { gTab[i] = tab; tab += gWidths[i]; } } private readonly ChampionSpawn m_Spawn; public ChampionSpawnInfoGump(ChampionSpawn spawn) : base(40, 40) { m_Spawn = spawn; AddBackground(0, 0, gWidth, gBoarder * 2 + gRowHeight * (8 + spawn.m_DamageEntries.Count), 0x13BE); int top = gBoarder; AddLabel(gBoarder, top, gFontHue, "Champion Spawn Info Gump"); top += gRowHeight; AddLabel(gTab[1], top, gFontHue, "Kills"); AddLabel(gTab[2], top, gFontHue, spawn.Kills.ToString()); top += gRowHeight; AddLabel(gTab[1], top, gFontHue, "Max Kills"); AddLabel(gTab[2], top, gFontHue, spawn.MaxKills.ToString()); top += gRowHeight; AddLabel(gTab[1], top, gFontHue, "Level"); AddLabel(gTab[2], top, gFontHue, spawn.Level.ToString()); top += gRowHeight; AddLabel(gTab[1], top, gFontHue, "Rank"); AddLabel(gTab[2], top, gFontHue, spawn.Rank.ToString()); top += gRowHeight; AddLabel(gTab[1], top, gFontHue, "Active"); AddLabel(gTab[2], top, gFontHue, spawn.Active.ToString()); top += gRowHeight; AddLabel(gTab[1], top, gFontHue, "Auto Restart"); AddLabel(gTab[2], top, gFontHue, spawn.AutoRestart.ToString()); top += gRowHeight; List<Damager> damagers = new List<Damager>(); foreach (Mobile mob in spawn.m_DamageEntries.Keys) { damagers.Add(new Damager(mob, spawn.m_DamageEntries[mob])); } damagers = damagers.OrderByDescending(x => x.Damage).ToList<Damager>(); foreach (Damager damager in damagers) { AddLabelCropped(gTab[1], top, 100, gRowHeight, gFontHue, damager.Mobile.RawName); AddLabelCropped(gTab[2], top, 80, gRowHeight, gFontHue, damager.Damage.ToString()); top += gRowHeight; } AddButton(gWidth - (gBoarder + 30), top, 0xFA5, 0xFA7, 1, GumpButtonType.Reply, 0); AddLabel(gWidth - (gBoarder + 100), top, gFontHue, "Refresh"); } public override void OnResponse(Network.NetState sender, RelayInfo info) { switch (info.ButtonID) { case 1: m_Spawn.SendGump(sender.Mobile); break; } } } } public class ChampionSpawnRegion : BaseRegion { public static void Initialize() { EventSink.Logout += OnLogout; EventSink.Login += OnLogin; } public override bool YoungProtected => false; private readonly ChampionSpawn m_Spawn; public ChampionSpawn ChampionSpawn => m_Spawn; public ChampionSpawnRegion(ChampionSpawn spawn) : base(null, spawn.Map, Region.Find(spawn.Location, spawn.Map), spawn.SpawnArea) { m_Spawn = spawn; } public override bool AllowHousing(Mobile from, Point3D p) { return false; } public override void AlterLightLevel(Mobile m, ref int global, ref int personal) { base.AlterLightLevel(m, ref global, ref personal); global = Math.Max(global, 1 + m_Spawn.Level); //This is a guesstimate. TODO: Verify & get exact values // OSI testing: at 2 red skulls, light = 0x3 ; 1 red = 0x3.; 3 = 8; 9 = 0xD 8 = 0xD 12 = 0x12 10 = 0xD } public override bool OnMoveInto(Mobile m, Direction d, Point3D newLocation, Point3D oldLocation) { if (m is PlayerMobile && !m.Alive && (m.Corpse == null || m.Corpse.Deleted) && Map == Map.Felucca) { return false; } return base.OnMoveInto(m, d, newLocation, oldLocation); } public static void OnLogout(LogoutEventArgs e) { Mobile m = e.Mobile; if (m is PlayerMobile && m.Region.IsPartOf<ChampionSpawnRegion>() && m.AccessLevel == AccessLevel.Player && m.Map == Map.Felucca) { if (m.Alive && m.Backpack != null) { List<Item> list = new List<Item>(m.Backpack.Items.Where(i => i.LootType == LootType.Cursed)); foreach (Item item in list) { item.MoveToWorld(m.Location, m.Map); } ColUtility.Free(list); } Timer.DelayCall(TimeSpan.FromMilliseconds(250), () => { Map map = m.LogoutMap; Point3D loc = ExorcismSpell.GetNearestShrine(m, ref map); if (loc != Point3D.Zero) { m.LogoutLocation = loc; m.LogoutMap = map; } else { m.LogoutLocation = new Point3D(989, 520, -50); m.LogoutMap = Map.Malas; } }); } } public static void OnLogin(LoginEventArgs e) { Mobile m = e.Mobile; if (m is PlayerMobile && !m.Alive && (m.Corpse == null || m.Corpse.Deleted) && m.Region.IsPartOf<ChampionSpawnRegion>() && m.Map == Map.Felucca) { Map map = m.Map; Point3D loc = ExorcismSpell.GetNearestShrine(m, ref map); if (loc != Point3D.Zero) { m.MoveToWorld(loc, map); } else { m.MoveToWorld(new Point3D(989, 520, -50), Map.Malas); } } } } public class IdolOfTheChampion : Item { private ChampionSpawn m_Spawn; public ChampionSpawn Spawn => m_Spawn; public override string DefaultName => "Idol of the Champion"; public IdolOfTheChampion(ChampionSpawn spawn) : base(0x1F18) { m_Spawn = spawn; Movable = false; } public override void OnAfterDelete() { base.OnAfterDelete(); if (m_Spawn != null) m_Spawn.Delete(); } public IdolOfTheChampion(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write(0); // version writer.Write(m_Spawn); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); switch (version) { case 0: { m_Spawn = reader.ReadItem() as ChampionSpawn; if (m_Spawn == null) Delete(); break; } } } } }
gpl-2.0
mzmine/mzmine3
src/main/java/io/github/mzmine/gui/framework/ScrollablePanel.java
11639
/* * Copyright 2006-2021 The MZmine Development Team * * This file is part of MZmine. * * MZmine 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. * * MZmine 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 MZmine; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package io.github.mzmine.gui.framework; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.LayoutManager; import java.awt.Rectangle; import javax.swing.JPanel; import javax.swing.JViewport; import javax.swing.Scrollable; import javax.swing.SwingConstants; /** * A panel that implements the Scrollable interface. This class allows you to customize the * scrollable features by using newly provided setter methods so you don't have to extend this class * every time. * * Scrollable amounts can be specifed as a percentage of the viewport size or as an actual pixel * value. The amount can be changed for both unit and block scrolling for both horizontal and * vertical scrollbars. * * The Scrollable interface only provides a boolean value for determining whether or not the * viewport size (width or height) should be used by the scrollpane when determining if scrollbars * should be made visible. This class supports the concept of dynamically changing this value based * on the size of the viewport. In this case the viewport size will only be used when it is larger * than the panels size. This has the effect of ensuring the viewport is always full as components * added to the panel will be size to fill the area available, based on the rules of the applicable * layout manager of course. */ public class ScrollablePanel extends JPanel implements Scrollable, SwingConstants { public enum ScrollableSizeHint { NONE, FIT, STRETCH; } public enum IncrementType { PERCENT, PIXELS; } private ScrollableSizeHint scrollableHeight = ScrollableSizeHint.NONE; private ScrollableSizeHint scrollableWidth = ScrollableSizeHint.NONE; private IncrementInfo horizontalBlock; private IncrementInfo horizontalUnit; private IncrementInfo verticalBlock; private IncrementInfo verticalUnit; /** * Default constructor that uses a FlowLayout */ public ScrollablePanel() { this(new FlowLayout()); } /** * Constuctor for specifying the LayoutManager of the panel. * * @param layout the LayountManger for the panel */ public ScrollablePanel(LayoutManager layout) { super(layout); IncrementInfo block = new IncrementInfo(IncrementType.PERCENT, 100); IncrementInfo unit = new IncrementInfo(IncrementType.PERCENT, 10); setScrollableBlockIncrement(HORIZONTAL, block); setScrollableBlockIncrement(VERTICAL, block); setScrollableUnitIncrement(HORIZONTAL, unit); setScrollableUnitIncrement(VERTICAL, unit); } /** * Get the height ScrollableSizeHint enum * * @return the ScrollableSizeHint enum for the height */ public ScrollableSizeHint getScrollableHeight() { return scrollableHeight; } /** * Set the ScrollableSizeHint enum for the height. The enum is used to determine the boolean value * that is returned by the getScrollableTracksViewportHeight() method. The valid values are: * * ScrollableSizeHint.NONE - return "false", which causes the height of the panel to be used when * laying out the children ScrollableSizeHint.FIT - return "true", which causes the height of the * viewport to be used when laying out the children ScrollableSizeHint.STRETCH - return "true" * when the viewport height is greater than the height of the panel, "false" otherwise. * * @param scrollableHeight as represented by the ScrollableSizeHint enum. */ public void setScrollableHeight(ScrollableSizeHint scrollableHeight) { this.scrollableHeight = scrollableHeight; revalidate(); } /** * Get the width ScrollableSizeHint enum * * @return the ScrollableSizeHint enum for the width */ public ScrollableSizeHint getScrollableWidth() { return scrollableWidth; } /** * Set the ScrollableSizeHint enum for the width. The enum is used to determine the boolean value * that is returned by the getScrollableTracksViewportWidth() method. The valid values are: * * ScrollableSizeHint.NONE - return "false", which causes the width of the panel to be used when * laying out the children ScrollableSizeHint.FIT - return "true", which causes the width of the * viewport to be used when laying out the children ScrollableSizeHint.STRETCH - return "true" * when the viewport width is greater than the width of the panel, "false" otherwise. * * @param scrollableWidth as represented by the ScrollableSizeHint enum. */ public void setScrollableWidth(ScrollableSizeHint scrollableWidth) { this.scrollableWidth = scrollableWidth; revalidate(); } /** * Get the block IncrementInfo for the specified orientation * * @return the block IncrementInfo for the specified orientation */ public IncrementInfo getScrollableBlockIncrement(int orientation) { return orientation == SwingConstants.HORIZONTAL ? horizontalBlock : verticalBlock; } /** * Specify the information needed to do block scrolling. * * @param orientation specify the scrolling orientation. Must be either: SwingContants.HORIZONTAL * or SwingContants.VERTICAL. * @paran type specify how the amount parameter in the calculation of the scrollable amount. Valid * values are: IncrementType.PERCENT - treat the amount as a % of the viewport size * IncrementType.PIXEL - treat the amount as the scrollable amount * @param amount a value used with the IncrementType to determine the scrollable amount */ public void setScrollableBlockIncrement(int orientation, IncrementType type, int amount) { IncrementInfo info = new IncrementInfo(type, amount); setScrollableBlockIncrement(orientation, info); } /** * Specify the information needed to do block scrolling. * * @param orientation specify the scrolling orientation. Must be either: SwingContants.HORIZONTAL * or SwingContants.VERTICAL. * @param info An IncrementInfo object containing information of how to calculate the scrollable * amount. */ public void setScrollableBlockIncrement(int orientation, IncrementInfo info) { switch (orientation) { case SwingConstants.HORIZONTAL: horizontalBlock = info; break; case SwingConstants.VERTICAL: verticalBlock = info; break; default: throw new IllegalArgumentException("Invalid orientation: " + orientation); } } /** * Get the unit IncrementInfo for the specified orientation * * @return the unit IncrementInfo for the specified orientation */ public IncrementInfo getScrollableUnitIncrement(int orientation) { return orientation == SwingConstants.HORIZONTAL ? horizontalUnit : verticalUnit; } /** * Specify the information needed to do unit scrolling. * * @param orientation specify the scrolling orientation. Must be either: SwingContants.HORIZONTAL * or SwingContants.VERTICAL. * @paran type specify how the amount parameter in the calculation of the scrollable amount. Valid * values are: IncrementType.PERCENT - treat the amount as a % of the viewport size * IncrementType.PIXEL - treat the amount as the scrollable amount * @param amount a value used with the IncrementType to determine the scrollable amount */ public void setScrollableUnitIncrement(int orientation, IncrementType type, int amount) { IncrementInfo info = new IncrementInfo(type, amount); setScrollableUnitIncrement(orientation, info); } /** * Specify the information needed to do unit scrolling. * * @param orientation specify the scrolling orientation. Must be either: SwingContants.HORIZONTAL * or SwingContants.VERTICAL. * @param info An IncrementInfo object containing information of how to calculate the scrollable * amount. */ public void setScrollableUnitIncrement(int orientation, IncrementInfo info) { switch (orientation) { case SwingConstants.HORIZONTAL: horizontalUnit = info; break; case SwingConstants.VERTICAL: verticalUnit = info; break; default: throw new IllegalArgumentException("Invalid orientation: " + orientation); } } // Implement Scrollable interface @Override public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } @Override public int getScrollableUnitIncrement(Rectangle visible, int orientation, int direction) { switch (orientation) { case SwingConstants.HORIZONTAL: return getScrollableIncrement(horizontalUnit, visible.width); case SwingConstants.VERTICAL: return getScrollableIncrement(verticalUnit, visible.height); default: throw new IllegalArgumentException("Invalid orientation: " + orientation); } } @Override public int getScrollableBlockIncrement(Rectangle visible, int orientation, int direction) { switch (orientation) { case SwingConstants.HORIZONTAL: return getScrollableIncrement(horizontalBlock, visible.width); case SwingConstants.VERTICAL: return getScrollableIncrement(verticalBlock, visible.height); default: throw new IllegalArgumentException("Invalid orientation: " + orientation); } } protected int getScrollableIncrement(IncrementInfo info, int distance) { if (info.getIncrement() == IncrementType.PIXELS) return info.getAmount(); else return distance * info.getAmount() / 100; } @Override public boolean getScrollableTracksViewportWidth() { if (scrollableWidth == ScrollableSizeHint.NONE) return false; if (scrollableWidth == ScrollableSizeHint.FIT) return true; // STRETCH sizing, use the greater of the panel or viewport width if (getParent() instanceof JViewport) { return (((JViewport) getParent()).getWidth() > getPreferredSize().width); } return false; } @Override public boolean getScrollableTracksViewportHeight() { if (scrollableHeight == ScrollableSizeHint.NONE) return false; if (scrollableHeight == ScrollableSizeHint.FIT) return true; // STRETCH sizing, use the greater of the panel or viewport height if (getParent() instanceof JViewport) { return (((JViewport) getParent()).getHeight() > getPreferredSize().height); } return false; } /** * Helper class to hold the information required to calculate the scroll amount. */ static class IncrementInfo { private IncrementType type; private int amount; public IncrementInfo(IncrementType type, int amount) { this.type = type; this.amount = amount; } public IncrementType getIncrement() { return type; } public int getAmount() { return amount; } @Override public String toString() { return "ScrollablePanel[" + type + ", " + amount + "]"; } } }
gpl-2.0
dengxiayehu/fqrtmpplayer
player-android/jni/audio_encoder.cpp
10554
#include <memory> #include "audio_encoder.h" #include "rtmp_handler.h" #include "common.h" #define DUMP_AAC 0 using namespace xutil; static const char *aac_get_error(AACENC_ERROR err) { switch (err) { case AACENC_OK: return "No error"; case AACENC_INVALID_HANDLE: return "Invalid handle"; case AACENC_MEMORY_ERROR: return "Memory allocation error"; case AACENC_UNSUPPORTED_PARAMETER: return "Unsupported parameter"; case AACENC_INVALID_CONFIG: return "Invalid config"; case AACENC_INIT_ERROR: return "Initialization error"; case AACENC_INIT_AAC_ERROR: return "AAC library initialization error"; case AACENC_INIT_SBR_ERROR: return "SBR library initialization error"; case AACENC_INIT_TP_ERROR: return "Transport library initialization error"; case AACENC_INIT_META_ERROR: return "Metadata library initialization error"; case AACENC_ENCODE_ERROR: return "Encoding error"; case AACENC_ENCODE_EOF: return "End of file"; default: return "Unknown error"; } } AudioEncoder::AudioEncoder() : m_hdlr(NULL), m_aot(0), m_samplerate(0), m_channels(0), m_bits_per_sample(0), m_cond(m_mutex), m_thrd(NULL), m_quit(false), m_file(NULL) { m_iobuf = new IOBuffer; #if defined(DUMP_AAC) && (DUMP_AAC != 0) m_file = new xfile::File; m_file->open("/sdcard/fqrtmp.aac", "wb"); #endif } AudioEncoder::~AudioEncoder() { if (m_hdlr) { m_quit = true; m_cond.signal(); JOIN_DELETE_THREAD(m_thrd); SAFE_DELETE(m_iobuf); SAFE_DELETE(m_file); aacEncClose(&m_hdlr); } } int AudioEncoder::init(jobject audio_config) { jvalue jval; CHANNEL_MODE mode; int sce = 0, cpe = 0; int bitrate; AACENC_ERROR err; #define CALL_METHOD(obj, name, signature) do { \ jboolean has_exception = JNI_FALSE; \ jval = jnu_call_method_by_name(&has_exception, obj, name, signature); \ if (has_exception) { \ E("Exception with %s()", name); \ goto error; \ } \ } while (0) CALL_METHOD(audio_config, "getChannelCount", "()I"); if ((err = aacEncOpen(&m_hdlr, 0, jval.i)) != AACENC_OK) { E("Unable to open the encoder: %s", aac_get_error(err)); goto error; } m_channels = jval.i; CALL_METHOD(audio_config, "getAudioObjectType", "()I"); if ((err = aacEncoder_SetParam(m_hdlr, AACENC_AOT, jval.i)) != AACENC_OK) { E("Unable to set the AOT %d: %s", jval.i, aac_get_error(err)); goto error; } m_aot = jval.i; CALL_METHOD(audio_config, "getSamplerate", "()I"); if ((err = aacEncoder_SetParam(m_hdlr, AACENC_SAMPLERATE, jval.i)) != AACENC_OK) { E("Unable to set the sample rate %d: %s\n", jval.i, aac_get_error(err)); goto error; } m_samplerate = jval.i; switch (m_channels) { case 1: mode = MODE_1; sce = 1; cpe = 0; break; case 2: mode = MODE_2; sce = 0; cpe = 1; break; case 3: mode = MODE_1_2; sce = 1; cpe = 1; break; case 4: mode = MODE_1_2_1; sce = 2; cpe = 1; break; case 5: mode = MODE_1_2_2; sce = 1; cpe = 2; break; case 6: mode = MODE_1_2_2_1; sce = 2; cpe = 2; break; default: E("Unsupported number of channels %d", m_channels); goto error; } if ((err = aacEncoder_SetParam(m_hdlr, AACENC_CHANNELMODE, mode)) != AACENC_OK) { E("Unable to set channel mode %d: %s\n", mode, aac_get_error(err)); goto error; } if ((err = aacEncoder_SetParam(m_hdlr, AACENC_CHANNELORDER, 1)) != AACENC_OK) { E("Unable to set wav channel order %d: %s\n", mode, aac_get_error(err)); goto error; } CALL_METHOD(audio_config, "getBitsPerSample", "()I"); m_bits_per_sample = jval.i; #define SET_FIELD(obj, name, signature, val) do { \ jboolean has_exception = JNI_FALSE; \ jnu_set_field_by_name(&has_exception, obj, name, signature, val); \ if (has_exception) { \ E("Exception occurred when set field \"%s\"", name); \ goto error; \ } \ } while (0) CALL_METHOD(audio_config, "getBitrate", "()I"); if (jval.i <= 0) { if (m_aot == AOT_PS) { sce = 1; cpe = 0; } bitrate = (96*sce + 128*cpe) * m_samplerate / 44; if (m_aot == AOT_SBR || m_aot == AOT_PS) { bitrate /= 2; } } else { bitrate = jval.i; } if ((err = aacEncoder_SetParam(m_hdlr, AACENC_BITRATE, bitrate)) != AACENC_OK) { E("Unable to set the bitrate %d: %s", bitrate, aac_get_error(err)); goto error; } SET_FIELD(audio_config, "mBitrate", "I", bitrate); if ((err = aacEncoder_SetParam(m_hdlr, AACENC_TRANSMUX, 2 /* ADTS bitstream format */)) != AACENC_OK) { E("Unable to set the transmux format: %s", aac_get_error(err)); goto error; } if ((err = aacEncoder_SetParam(m_hdlr, AACENC_SIGNALING_MODE, 0)) != AACENC_OK) { E("Unable to set signaling mode: %s", aac_get_error(err)); goto error; } if ((err = aacEncoder_SetParam(m_hdlr, AACENC_AFTERBURNER, 1)) != AACENC_OK) { E("Unable to set afterburner: %s", aac_get_error(err)); goto error; } if ((err = aacEncEncode(m_hdlr, NULL, NULL, NULL, NULL)) != AACENC_OK) { E("Unable to initialize the encoder: %s\n", aac_get_error(err)); goto error; } if ((err = aacEncInfo(m_hdlr, &m_info)) != AACENC_OK) { E("Unable to get encoder info: %s", aac_get_error(err)); goto error; } SET_FIELD(audio_config, "mFrameLength", "I", m_info.frameLength); SET_FIELD(audio_config, "mEncoderDelay", "I", m_info.encoderDelay); frac_init(&m_pts, 0, 0, m_samplerate); D("AudioEncoder: m_aot=%d, m_samplerate=%d, m_channels=%d, m_bits_per_sample=%d, frameLength=%d, encoderDelay=%d", m_aot, m_samplerate, m_channels, m_bits_per_sample, m_info.frameLength, m_info.encoderDelay); m_thrd = CREATE_THREAD_ROUTINE(encode_routine, NULL, false); return 0; error: E("Init audio encoder failed"); return -1; #undef CALL_METHOD #undef SET_FIELD } int AudioEncoder::feed(uint8_t *buffer, int len) { AutoLock l(m_mutex); m_iobuf->read_from_buffer(buffer, len); m_cond.signal(); return 0; } volatile bool AudioEncoder::quit() const { return m_quit; } unsigned int AudioEncoder::encode_routine(void *arg) { int input_size = m_channels * 2 * m_info.frameLength; uint8_t *input_buf = (uint8_t *) malloc(input_size); int16_t *convert_buf = (int16_t *) malloc(input_size); uint8_t outbuf[20480]; if (!input_buf || !convert_buf) { E("malloc failed: %s", ERRNOMSG); goto done; } D("aac encode_routine started .."); while (!m_quit) { AACENC_BufDesc in_buf = { 0 }, out_buf = { 0 }; AACENC_InArgs in_args = { 0 }; AACENC_OutArgs out_args = { 0 }; int in_identifier = IN_AUDIO_DATA; int in_size, in_elem_size; int out_identifier = OUT_BITSTREAM_DATA; int out_size, out_elem_size; int i; void *in_ptr, *out_ptr; AACENC_ERROR err; BEGIN AutoLock l(m_mutex); while (!m_quit && GETAVAILABLEBYTESCOUNT(*m_iobuf) < (uint32_t) input_size) { m_cond.wait(); } if (m_quit) break; memcpy(input_buf, GETIBPOINTER(*m_iobuf), input_size); m_iobuf->ignore(input_size); END for (i = 0; i < input_size/2; ++i) { const uint8_t *in = &input_buf[2*i]; convert_buf[i] = in[0] | (in[1] << 8); } in_ptr = convert_buf; in_size = input_size; in_elem_size = 2; in_args.numInSamples = input_size/2; in_buf.numBufs = 1; in_buf.bufs = &in_ptr; in_buf.bufferIdentifiers = &in_identifier; in_buf.bufSizes = &in_size; in_buf.bufElSizes = &in_elem_size; out_ptr = outbuf; out_size = sizeof(outbuf); out_elem_size = 1; out_buf.numBufs = 1; out_buf.bufs = &out_ptr; out_buf.bufferIdentifiers = &out_identifier; out_buf.bufSizes = &out_size; out_buf.bufElSizes = &out_elem_size; if ((err = aacEncEncode(m_hdlr, &in_buf, &out_buf, &in_args, &out_args)) != AACENC_OK) { if (err == AACENC_ENCODE_EOF) { W("libfdk-aac eof?"); goto done; } E("Unable to encode audio frame: %s", aac_get_error(err)); goto done; } if (out_args.numOutBytes != 0) { std::auto_ptr<Packet> pkt_out( new Packet(outbuf, out_args.numOutBytes, m_pts.val, m_pts.val)); if (m_file) { m_file->write_buffer(outbuf, out_args.numOutBytes); } if (gfq.rtmp_hdlr) { gfq.rtmp_hdlr->send_audio(pkt_out->pts, pkt_out->data, pkt_out->size); } frac_add(&m_pts, m_info.frameLength * 1000); } } done: SAFE_FREE(input_buf); SAFE_FREE(convert_buf); D("aac encode_routine ended"); return 0; } jint openAudioEncoder(JNIEnv *env, jobject thiz, jobject audio_config) { gfq.audio_enc = new AudioEncoder; if (gfq.audio_enc->init(audio_config) < 0) { closeAudioEncoder(env, thiz); return -1; } return 0; } jint closeAudioEncoder(JNIEnv *env, jobject thiz) { SAFE_DELETE(gfq.audio_enc); return 0; } jint sendRawAudio(JNIEnv *env, jobject thiz, jbyteArray byte_arr, jint len) { int ret = 0; if (gfq.audio_enc && !gfq.audio_enc->quit()) { uint8_t *buffer; jboolean is_copy; buffer = (uint8_t *) env->GetByteArrayElements(byte_arr, &is_copy); if (!buffer) { E("Get audio buffer failed"); return -1; } ret = gfq.audio_enc->feed(buffer, len); env->ReleaseByteArrayElements(byte_arr, (jbyte *) buffer, 0); } return ret; }
gpl-2.0
oat-sa/extension-tao-outcomerdf
actions/class.Results.php
6599
<?php /** * 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; under version 2 * of the License (non-upgradable). * * 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. * * Copyright (c) 2002-2008 (original work) Public Research Centre Henri Tudor & University of Luxembourg (under the project TAO & TAO2); * 2008-2010 (update and modification) Deutsche Institut für Internationale Pädagogische Forschung (under the project TAO-TRANSFER); * 2009-2012 (update and modification) Public Research Centre Henri Tudor (under the project TAO-SUSTAIN & TAO-DEV); * */ /** * Results Controller provide actions performed from url resolution * * * @author Patrick Plichart <patrick@taotesting.com> * @author Bertrand Chevrier, <taosupport@tudor.lu> * @package taoResults * @license GPLv2 http://www.opensource.org/licenses/gpl-2.0.php */ class taoResults_actions_Results extends tao_actions_SaSModule { /** * constructor: initialize the service and the default data * @return Results */ public function __construct() { parent::__construct(); //the service is initialized by default $this->service = taoResults_models_classes_ResultsService::singleton(); $this->defaultData(); } protected function getClassService() { return taoResults_models_classes_ResultsService::singleton(); } /* * controller actions */ /** * Edit a result class * @return void */ public function editResultClass() { $clazz = $this->getCurrentClass(); if($this->hasRequestParameter('property_mode')){ $this->setSessionAttribute('property_mode', $this->getRequestParameter('property_mode')); } $myForm = $this->editClass($clazz, $this->service->getRootClass()); if($myForm->isSubmited()){ if($myForm->isValid()){ if($clazz instanceof core_kernel_classes_Resource){ $this->setSessionAttribute("showNodeUri", tao_helpers_Uri::encode($clazz->getUri())); } $this->setData('message', __('Class saved')); $this->setData('reload', true); } } $this->setData('formTitle', __('Edit result class')); $this->setData('myForm', $myForm->render()); $this->setView('form.tpl', 'tao'); } /** * Delete a result or a result class * @return void */ public function delete() { if(!tao_helpers_Request::isAjax()){ throw new Exception("wrong request mode"); } $deleted = false; if($this->getRequestParameter('uri')){ $deleted = $this->service->deleteResult($this->getCurrentInstance()); } else{ $deleted = $this->service->deleteResultClass($this->getCurrentClass()); } echo json_encode(array('deleted' => $deleted)); } /** * * @author Patrick Plichart <patrick@taotesting.com> */ public function viewResult() { $result = $this->getCurrentInstance(); $testTaker = $this->service->getTestTakerData($result); if ( (is_object($testTaker) and (get_class($testTaker)=='core_kernel_classes_Literal')) or (is_null($testTaker)) ) { //the test taker is unknown $this->setData('userLogin', $testTaker); $this->setData('userLabel', $testTaker); $this->setData('userFirstName', $testTaker); $this->setData('userLastName', $testTaker); $this->setData('userEmail', $testTaker); } else { $login = (count($testTaker[PROPERTY_USER_LOGIN])>0) ? current($testTaker[PROPERTY_USER_LOGIN])->literal :""; $label = (count($testTaker[RDFS_LABEL])>0) ? current($testTaker[RDFS_LABEL])->literal:""; $firstName = (count($testTaker[PROPERTY_USER_FIRSTNAME])>0) ? current($testTaker[PROPERTY_USER_FIRSTNAME])->literal:""; $userLastName = (count($testTaker[PROPERTY_USER_LASTNAME])>0) ? current($testTaker[PROPERTY_USER_LASTNAME])->literal:""; $userEmail = (count($testTaker[PROPERTY_USER_MAIL])>0) ? current($testTaker[PROPERTY_USER_MAIL])->literal:""; $this->setData('userLogin', $login); $this->setData('userLabel', $label); $this->setData('userFirstName', $firstName); $this->setData('userLastName', $userLastName); $this->setData('userEmail', $userEmail); } $filter = ($this->hasRequestParameter("filter")) ? $this->getRequestParameter("filter") : "lastSubmitted"; $stats = $this->service->getItemVariableDataStatsFromDeliveryResult($result, $filter); $this->setData('nbResponses', $stats["nbResponses"]); $this->setData('nbCorrectResponses', $stats["nbCorrectResponses"]); $this->setData('nbIncorrectResponses', $stats["nbIncorrectResponses"]); $this->setData('nbUnscoredResponses', $stats["nbUnscoredResponses"]); $this->setData('deliveryResultLabel', $result->getLabel()); $this->setData('variables', $stats["data"]); //retireve variables not related to item executions $deliveryVariables = $this->service->getVariableDataFromDeliveryResult($result); $this->setData('deliveryVariables', $deliveryVariables); $this->setData('uri',$this->getRequestParameter("uri")); $this->setData('classUri',$this->getRequestParameter("classUri")); $this->setData('filter',$filter); $this->setView('viewResult.tpl'); } public function getFile(){ $variableUri = $this->getRequestParameter("variableUri"); $file = $this->service->getVariableFile($variableUri); $trace = $file["data"]; header('Set-Cookie: fileDownload=true'); //used by jquery file download to find out the download has been triggered ... setcookie("fileDownload","true", 0, "/"); header("Content-type: ".$file["mimetype"]); if (!isset($file["filename"]) || $file["filename"]==""){ header('Content-Disposition: attachment; filename=download'); } else { header('Content-Disposition: attachment; filename='.$file["filename"]); } echo $file["data"]; } } ?>
gpl-2.0
svyatoslavteterin/belton.by
core/lexicon/th/package_builder.inc.php
7643
<?php /** * Package Builder English lexicon topic * * @language en * @package modx * @subpackage lexicon */ $_lang['as_system_settings'] = 'ตั้งค่าระบบ'; $_lang['as_context_settings'] = 'ตั้งค่าบริบท'; $_lang['as_lexicon_entries'] = 'Lexicon เอนทรี'; $_lang['as_lexicon_topics'] = 'หัวข้อ Lexicon'; $_lang['build'] = 'สร้าง'; $_lang['class_key'] = 'คลาสคีย์'; $_lang['class_key_desc'] = 'ประเภทของอ็อบเจกต์ที่คุณต้องการเชื่อมโยงกับแผนที่ไปยังสื่อนำ'; $_lang['class_key_custom'] = 'หรือคลาสกำหนดเอง'; $_lang['class_key_custom_desc'] = 'คุณสามารถระบุชื่อคลาส custom xPDOObject ที่ไม่อยู่ในรายการข้างล่างนี้'; $_lang['file'] = 'ไฟล์'; $_lang['index'] = 'ดัชนี'; $_lang['object'] = 'อ็อบเจกต์'; $_lang['object_id'] = 'อ็อบเจกต์ไอดี'; $_lang['object_id_desc'] = 'อ็อบเจกต์ที่คุณต้องการแม็ป จำเป็น'; $_lang['package_autoselects'] = 'Package Auto-Includes'; $_lang['package_autoselects_desc'] = 'กรุณาเลือกรีซอร์สที่คุณต้องการให้รวมในตัวสร้างแพ็กเกจโดยอัตโนมัติ หมายเหตุ: ถ้า building จาก core แนะนำว่าไม่ควรเลือกตัวเลือกใดๆ ในนี้'; $_lang['package_build'] = 'สร้างแพ็กเกจ'; $_lang['package_build_desc'] = 'ตอนนี้คุณพร้อมที่จะสร้างแพ็กเกจ มันจะถูกเก็บไว้ที่โฟลเดอร์ core/packages'; $_lang['package_build_err'] = 'เกิดข้อผิดพลาดขณะที่พยายามสร้างแพ็กเกจ'; $_lang['package_build_xml'] = 'สร้างแพ็กเกจจาก XML'; $_lang['package_build_xml_desc'] = 'กรุณาเลือกไฟล์ XML ที่ถูกต้อง สำหรับส่วนประกอบของคุณ'; $_lang['package_builder'] = 'ตัวสร้างแพ็กเกจ'; $_lang['package_built'] = 'แพ็กเกจถูกสร้างแล้ว'; $_lang['package_info'] = 'ข้อมูลแพคเกจ'; $_lang['package_info_desc'] = 'ขั้นแรกระบุข้อมูลแพคเกจ เช่น เวอร์ชันและการปล่อย'; $_lang['package_method'] = 'เลือกวิธีการแพ็กกิ้ง'; $_lang['package_method_desc'] = 'กรุณาเลือกวิธีการสร้างแพ็กเกจที่คุณต้องการเลือกใช้'; $_lang['php_script'] = 'สคริปต์ PHP'; $_lang['preserve_keys'] = 'คีย์สงวน'; $_lang['preserve_keys_desc'] = 'นี่จะเก็บ primary keys เป็นค่าที่พวกเขาเป็นอยู่ในฐานข้อมูลในขณะนี้'; $_lang['release'] = 'ปล่อย'; $_lang['resolve_files'] = 'แก้ไขไฟล์'; $_lang['resolve_files_desc'] = 'เมื่อเช็คเคริ่องหมายถูก จะแก้ไฟล์ที่ระบุใน resolvers'; $_lang['resolve_php'] = 'Resolve PHP Scripts'; $_lang['resolve_php_desc'] = 'เมื่อเช็คถูก จะแก้ PHP scripts ที่ระบุใน resolvers'; $_lang['resolver_add'] = 'เพิ่ม Resolver'; $_lang['resolver_create'] = 'สร้าง Resolver'; $_lang['resolver_name_desc'] = 'ชื่อของ resolver ใช้สำหรับจุดประสงค์ในการจัดเก็บ'; $_lang['resolver_remove'] = 'ลบ Resolver'; $_lang['resolver_remove_confirm'] = 'คุณแน่ใจว่าต้องการลบ resolver นี้?'; $_lang['resolver_source_desc'] = 'เส้นทางที่แน่นอนของแหล่งข้อมูลของ resolver ถ้าเป็น file resolver เลือกโฟลเดอร์ของไฟล์ที่คุณต้องการคัดลอก ถ้าเป็น PHP Script ให้ระบุสคริปต์ ตัวอย่าง: <br /><br />/public_html/modx/_build/components/demo/'; $_lang['resolver_target_desc'] = 'เส้นทางเป้าหมายที่แน่นอนสำหรับสถานที่ที่ resolver จะเก็บไฟล์หรือแอ็กชันไว้ ตามปกติแล้วคุณไม่ควรเปลี่ยนมัน ตัวอย่าง: <br /><br />return MODX_ASSETS_PATH . "snippets/";'; $_lang['resolver_type_desc'] = 'File resolvers จะตรวจะสอบให้แน่ใจว่าได้คัดลอกไฟล์ทั้งหมดในไดเรกทอรีของซอร์สไปที่เป้าหมาย ส่วน PHP Script resolvers execute ไฟล์ซอร์สเป็นแบบ PHP'; $_lang['resolvers'] = 'ตัวแก้ปัญหา'; $_lang['source'] = 'ซอร์ส'; $_lang['target'] = 'เป้าหมาย'; $_lang['type'] = 'ประเภท'; $_lang['unique_key'] = 'Unique Key'; $_lang['unique_key_desc'] = 'A unique key เป็นการระบุวิธิการค้นหาของอ็อบเจกต์ สามารถเป็นสตริงหรือรายการที่คั่นด้วยจุลภาค ตัวอย่าง: <br />"name" สำหรับ modPlugin<br />"templatename" สำหรับ modTemplate<br />หรือซับซ้อนมากขึ้น "pluginid,evtid" สำหรับ modPluginEvent'; $_lang['update_object'] = 'ปรับปรุงอ็อบเจกต์'; $_lang['update_object_desc'] = 'ถ้าเช็คเครื่องหมายถูก จะอัปเดตอ็อบเจกต์ถ้ามันถูกพบ หรือถ้าไม่เช็คจะไม่บันทึกอ็อบเจกต์ ถ้ามันเจอแล้ว'; $_lang['use_wizard'] = 'ใช้ตัวช่วยสร้าง'; $_lang['use_xml'] = 'สร้างจากไฟล์ XML'; $_lang['vehicle'] = 'ตัวนำ'; $_lang['vehicle_add'] = 'เพิ่มตัวนำ'; $_lang['vehicle_create'] = 'สร้างตัวนำ'; $_lang['vehicle_remove'] = 'ลบตัวนำ'; $_lang['vehicle_remove_confirm'] = 'คุณแน่ใจว่าต้องการลบตัวนำนี้?'; $_lang['vehicles'] = 'ตัวนำ'; $_lang['vehicles_add'] = 'เพิ่มตัวนำ'; $_lang['vehicles_desc'] = 'ตัวนำเป็นอ็อบเจกต์ที่ถูกบรรจุในแพ็กเกจ คุณอาจเพิ่มมันได้ที่นี่'; $_lang['version'] = 'เวอร์ชัน'; $_lang['xml_file_err_upload'] = 'มีข้อผิดพลาดขณะที่พยายามอัปโหลดไฟล์ XML';
gpl-2.0
klas/SEBLOD-bugfixed
administrator/components/com_cck/models/template.php
4755
<?php /** * @version SEBLOD 3.x Core ~ $Id: template.php sebastienheraud $ * @package SEBLOD (App Builder & CCK) // SEBLOD nano (Form Builder) * @url http://www.seblod.com * @editor Octopoos - www.octopoos.com * @copyright Copyright (C) 2009 - 2016 SEBLOD. All Rights Reserved. * @license GNU General Public License version 2 or later; see _LICENSE.php **/ defined( '_JEXEC' ) or die; // Model class CCKModelTemplate extends JCckBaseLegacyModelAdmin { protected $text_prefix = 'COM_CCK'; protected $vName = 'template'; // canDelete protected function canDelete( $record ) { $user = JFactory::getUser(); if ( ! empty( $record->folder ) ) { // Folder Permissions return $user->authorise( 'core.delete', CCK_COM.'.folder.'.(int)$record->folder ); } else { // Component Permissions return parent::canDelete( $record ); } } // canEditState protected function canEditState( $record ) { $user = JFactory::getUser(); if ( ! empty( $record->folder ) ) { // Folder Permissions return $user->authorise( 'core.edit.state', CCK_COM.'.folder.'.(int)$record->folder ); } else { // Component Permissions return parent::canEditState( $record ); } } // populateState protected function populateState() { $app = JFactory::getApplication( 'administrator' ); $pk = $app->input->getInt( 'id', 0 ); if ( ( $mode = $app->getUserState( CCK_COM.'.edit.template.mode' ) ) != '' ) { $this->setState( 'mode', $mode ); } $this->setState( 'template.id', $pk ); } // getForm public function getForm( $data = array(), $loadData = true ) { $form = $this->loadForm( CCK_COM.'.'.$this->vName, $this->vName, array( 'control' => 'jform', 'load_data' => $loadData ) ); if ( empty( $form ) ) { return false; } return $form; } // getItem public function getItem( $pk = null ) { if ( $item = parent::getItem( $pk ) ) { // } return $item; } // getTable public function getTable( $type = 'Template', $prefix = CCK_TABLE, $config = array() ) { return JTable::getInstance( $type, $prefix, $config ); } // loadFormData protected function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState( CCK_COM.'.edit.'.$this->vName.'.data', array() ); if ( empty( $data ) ) { $data = $this->getItem(); } return $data; } // -------- -------- -------- -------- -------- -------- -------- -------- // Store // prepareData protected function prepareData() { $data = JRequest::get( 'post' ); $data['description'] = JRequest::getVar( 'description', '', '', 'string', JREQUEST_ALLOWRAW ); if ( $data['mode'] ) { $data['featured'] = 0; } else { if ( $data['featured'] ) { JCckDatabase::execute( 'UPDATE #__cck_core_templates SET featured = 0 WHERE id' ); } else { if ( !JCckDatabase::loadResult( 'SELECT COUNT(id) FROM #__cck_core_templates WHERE featured = 1 AND id != '.(int)$data['id'] ) ) { $data['featured'] = 1; } } } // JSON if ( isset( $data['json'] ) && is_array( $data['json'] ) ) { foreach ( $data['json'] as $k=>$v ) { if ( is_array( $v ) ) { $data[$k] = JCckDev::toJSON( $v ); } } } return $data; } // prepareExport_Variation public function prepareExport_Variation( $name, $folder ) { $config = JFactory::getConfig(); $tmp_path = $config->get( 'tmp_path' ); $tmp_dir = uniqid( 'cck_' ); $path = $tmp_path.'/'.$tmp_dir; $filename = 'var_cck_'.$name; $path_zip = $tmp_path.'/'.$filename.'.zip'; $src = JPATH_SITE.$folder.$name; // Variation jimport( 'cck.base.install.export' ); if ( JFolder::exists( $src ) ) { JFolder::copy( $src, $path.'/'.$name ); } // Manifest $manifest = JPATH_ADMINISTRATOR.'/manifests/files/'.$filename.'.xml'; jimport( 'joomla.filesystem.file' ); if ( JFile::exists( $manifest ) ) { JFile::copy( $manifest, $path.'/'.$filename.'.xml' ); } else { $xml = CCK_Export::prepareFile( (object)array( 'title'=>$filename ) ); $fileset = $xml->addChild( 'fileset' ); $files = $fileset->addChild( 'files' ); $files->addAttribute( 'target', 'libraries/cck/rendering/variations' ); $file = $files->addChild( 'folder', $name ); CCK_Export::createFile( $path.'/'.$filename.'.xml', '<?xml version="1.0" encoding="utf-8"?>'.$xml->asIndentedXML() ); } CCK_Export::clean( $path ); CCK_Export::exportLanguage( $path.'/'.$filename.'.xml', JPATH_SITE, $path ); return CCK_Export::zip( $path, $path_zip ); } } ?>
gpl-2.0
MathiasGruber/MembraneFoam
src/solvers/simplePorousSaltTransport/UEqn.H
1530
// Update the viscosity field mu = mu0 + mu_mACoeff*m_A; // Construct the Momentum equation tmp<fvVectorMatrix> UEqn ( fvm::div(phi, U) - fvm::laplacian(mu, U) - fvc::div(mu*dev2(fvc::grad(U)().T())) ); UEqn().relax(); // Update the mu_laplacian field // http://www.cfd-online.com/Forums/openfoam-solving/58214-calculating-divdevreff.html // mu_laplacianU = fvc::laplacian( mu, U ); mu_laplacianU = fvc::laplacian( mu, U ) + fvc::div(mu*dev2(fvc::grad(U)().T())); // Include the porous media resistance and solve the momentum equation // either implicit in the tensorial resistance or transport using by // including the spherical part of the resistance in the momentum diagonal tmp<volScalarField> trAU; tmp<volTensorField> trTU; if (pressureImplicitPorosity) { tmp<volTensorField> tTU = tensor(I)*UEqn().A(); pZones.addResistance(UEqn(), tTU()); trTU = inv(tTU()); trTU().rename("rAU"); fvOptions.constrain(UEqn()); volVectorField gradp(fvc::grad(p)); for (int UCorr=0; UCorr<nUCorr; UCorr++) { U = trTU() & (UEqn().H() - gradp); } U.correctBoundaryConditions(); fvOptions.correct(U); } else { pZones.addResistance(UEqn()); fvOptions.constrain(UEqn()); solve(UEqn() == -fvc::grad(p)); fvOptions.correct(U); trAU = 1.0/UEqn().A(); trAU().rename("rAU"); }
gpl-2.0
czechmate777/BridgeBuilder
src/java/com/czechmate777/ropebridge/client/render/ItemRenderRegister.java
775
package com.czechmate777.ropebridge.client.render; import com.czechmate777.ropebridge.Main; import com.czechmate777.ropebridge.items.ModItems; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.item.Item; public class ItemRenderRegister { public static String modid = Main.MODID; public static void registerItemRenderer() { reg(ModItems.bridgeBuilder); reg(ModItems.bridgeBuilderHook); reg(ModItems.bridgeBuilderBarrel); reg(ModItems.bridgeBuilderHandle); } public static void reg(Item item) { Minecraft.getMinecraft().getRenderItem().getItemModelMesher() .register(item, 0, new ModelResourceLocation(modid + ":" + item.getUnlocalizedName().substring(5), "inventory")); } }
gpl-2.0
veteran29/Clipboard-Share
src/com/veteran29/clipboardshare/Main.java
1961
/** ** @author veteran29 **/ package com.veteran29.clipboardshare; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.os.Build; import android.os.Bundle; import android.util.Log; public class Main extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Context ctx = this.getApplicationContext(); Intent notificationIntent = new Intent(ctx, Share.class); PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationManager nm = (NotificationManager) ctx .getSystemService(Context.NOTIFICATION_SERVICE); Resources res = ctx.getResources(); Notification.Builder builder = new Notification.Builder(ctx); builder.setContentIntent(contentIntent) .setSmallIcon(android.R.drawable.ic_menu_share) .setOngoing(true) .setContentTitle( res.getText(R.string.notif_title) ) .setContentText( res.getText(R.string.notif_text) ); if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { builder.setPriority(Notification.PRIORITY_MIN); if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { Log.d("Clip Board Share", "API is equal or above 17"); builder.setShowWhen(false); } else { builder.setWhen(0); } } Notification n = builder.build(); nm.notify(01, n); this.finish(); } }
gpl-2.0
virtual-network/vn-sdm
sdm/common/message/SDMReqxTEDS.cpp
2441
#include <string.h> #include <stdio.h> #include "SDMReqxTEDS.h" SDMReqxTEDS::SDMReqxTEDS():select(-1),destination(),source() { MsgName = SDM_ReqxTEDS; device_name[0] = '\0'; total_length = 12; } long SDMReqxTEDS::Send() { return SendDM(); } long SDMReqxTEDS::Recv(long port) { int result; result = RecvFrom(port); if (result <= 0) return SDM_MESSAGE_RECV_ERROR; return result; } long SDMReqxTEDS::Marshal(char* buf) { int cur; cur = HEADER_SIZE; cur += destination.Marshal(buf,cur); PUT_CHAR(&buf[cur],select); cur += sizeof(select); switch(select) { case 0: case 2: //use sensor_id cur += source.Marshal(buf,cur); break; case 1: //use device_name case 3: msg_length = (short)strlen(device_name); memcpy(buf+cur,device_name,msg_length); cur += msg_length; buf[cur] = '\0'; cur++; break; default: return SDM_INVALID_SELECT; } msg_length = cur - HEADER_SIZE; MarshalHeader(buf); //re-marshal header with correct length return msg_length + HEADER_SIZE; } long SDMReqxTEDS::Unmarshal(const char* buf) { int cur; long device_name_msg_length; cur = UnmarshalHeader(buf); if(cur==SDM_INVALID_MESSAGE) { return SDM_INVALID_MESSAGE; } if(total_length>msg_length) { return SDM_INVALID_MESSAGE; } cur += destination.Unmarshal(buf,cur); select = GET_CHAR (&buf[cur]); cur += sizeof(select); switch(select) { case 0: case 2: cur += source.Unmarshal(buf,cur); return cur; case 1: case 3: device_name_msg_length = (long)strlen(buf+cur); memset(device_name,0,sizeof(device_name)); memcpy(&device_name,buf+cur,device_name_msg_length); cur += device_name_msg_length + 1; return cur; default: break; }; #ifdef BUILD_WITH_MESSAGE_LOGGING Logger.MessageReceived(*this); #endif return SDM_INVALID_SELECT; } int SDMReqxTEDS::MsgToString(char *str_buf, int length) const { char source_id[40]; char dest_id[40]; if (length < 8096) return 0; source.IDToString(source_id, 40); destination.IDToString(dest_id, 40); #ifdef WIN32 sprintf(str_buf, #else snprintf(str_buf,length, #endif "SDMReqxTEDS %ld:%ld %ld bytes, Select: %d", sec, subsec, msg_length, select); switch(select) { case 0: case 2: //use sensor_id strcat(str_buf," Source: "); strcat(str_buf, source_id); break; case 1: //use device_name case 3: strcat(str_buf," DeviceName: "); strcat(str_buf, device_name); break; default: break; } return (int)strlen(str_buf); }
gpl-2.0
timofeysie/indoct
WEB-INF/src/com/businessglue/struts/remote/GetHouseDecksAction.java
6022
package com.businessglue.struts.remote; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.Map.Entry; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.catechis.FileStorage; import org.catechis.I18NWebUtility; import org.catechis.Storage; import org.catechis.constants.Constants; import org.catechis.dto.SavedTest; import org.catechis.dto.SimpleWord; import org.catechis.dto.UserInfo; import org.catechis.dto.WordCategory; import org.catechis.file.FileSaveTests; import org.catechis.file.FileTestRecords; import org.catechis.file.FileWordCategoriesManager; import org.catechis.wherewithal.DeckCard; import org.catechis.wherewithal.HouseDeck; import com.businessglue.util.Workaround; /** <p>This class accepts a teacher_id and a device_id and loads the device_id.xml file in the house_decks folder of the teacher's folder, and send the file to the android app. * @author Timothy Curchod */ public class GetHouseDecksAction extends Action { private static String DEBUG_TAG = "GetHouseDecksAction"; /** *<p>Load an xml file and set it as a hashtable and a vector in the session. */ public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); String method = "perform"; ServletContext context = getServlet().getServletContext(); String context_path = context.getRealPath("/WEB-INF/"); Map pairs = request.getParameterMap(); context.log(DEBUG_TAG+"."+method+" pairs "+pairs.size()); printParameters(request); FileSaveTests f_save_tests = new FileSaveTests(); String teacher_id = request.getParameter("teacher_id"); String device_id = request.getParameter("device_id"); context.log(DEBUG_TAG+"."+method+" teacher_id "+teacher_id); context.log(DEBUG_TAG+"."+method+" device_id "+device_id); Storage store = new FileStorage(context_path, context); Vector house_decks = f_save_tests.loadHouseDecks(teacher_id, context_path, device_id); printHouseDecks(house_decks); printLog(f_save_tests.getLog(), context); xmlResponse(response, house_decks); f_save_tests.saveHouseDecks(teacher_id, context_path, device_id, house_decks); return (mapping.findForward("not_used")); } private void xmlResponse(HttpServletResponse response, Vector house_decks) { ServletContext context = getServlet().getServletContext(); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); sb.append("<house_decks>"); for (int i = 1; i < house_decks.size(); i++) { HouseDeck house_deck = (HouseDeck)house_decks.get(i); sb.append("<house_deck>"); sb.append("<deck_id>"+house_deck.getDeckId()+"</deck_id>"); sb.append("<player_id>"+house_deck.getPlayerId()+"</player_id>"); sb.append("<game_id>"+house_deck.getGameId()+"</game_id>"); sb.append("<deck_name>"+house_deck.getDeckName()+"</deck_name>"); Hashtable <String,DeckCard> deck_cards = house_deck.getCards(); context.log("deck "+house_deck.getDeckName()+" has "+deck_cards.size()); for (Enumeration keys = deck_cards.keys(); keys.hasMoreElements() ;) { String deck_id = (String)keys.nextElement(); DeckCard deck_card = (DeckCard)deck_cards.get(deck_id); sb.append("<deck_card>"); sb.append("<card_id>"+deck_card.getCardId()+"</card_id>"); sb.append("<card_name>"+deck_card.getCardName()+"</card_name>"); sb.append("<status>"+deck_card.getStatus()+"</status>"); sb.append("<index>"+deck_card.getIndex()+"</index>"); sb.append("<type>"+deck_card.getType()+"</type>"); sb.append("</deck_card>"); } sb.append("</house_deck>"); } sb.append("</house_decks>"); response.setContentType("text/xml"); response.setContentLength(sb.length()); PrintWriter out; try { out = response.getWriter(); out.println(sb.toString()); out.close(); out.flush(); } catch (IOException e) { context.log("Could not steal output stream"); } } private void printHouseDecks(Vector house_decks) { String method = "printHouseDecks"; ServletContext context = getServlet().getServletContext(); for (int i = 1; i < house_decks.size(); i++) { HouseDeck house_deck = (HouseDeck)house_decks.get(i); Hashtable <String,DeckCard> deck_cards = house_deck.getCards(); context.log(DEBUG_TAG+"."+method+": deck_name "+house_deck.getDeckName()+" cards "+deck_cards.size()); for (Enumeration keys = deck_cards.keys(); keys.hasMoreElements() ;) { String deck_id = (String)keys.nextElement(); DeckCard deck_card = (DeckCard)deck_cards.get(deck_id); context.log(DEBUG_TAG+"."+method+": name "+deck_card.getCardName()+" id "+deck_card.getCardId()); } } } private void printParameters(HttpServletRequest request) { String method = "printParameters"; ServletContext context = getServlet().getServletContext(); Enumeration <String> names = request.getParameterNames(); while (names.hasMoreElements()) { String parameter = names.nextElement(); String value = request.getParameter(parameter); context.log(DEBUG_TAG+"."+method+" "+parameter+" - "+value); } } private void printLog(Vector log, ServletContext context) { int total = log.size(); int i = 0; while (i<total) { context.log(DEBUG_TAG+".log "+(String)log.get(i)); i++; } } }
gpl-2.0
neg90/CE
modelo/clases/infcorreo.php
1689
<?php class infcorreo { //Atributos private $id; private $cantContactos; private $cantEmpresas; private $arrayEmpresas; private $asunto; private $adjunto; private $mensaje; private $fecha; public function __construct($id,$cantContactos,$cantEmpresas,$arrayEmpresas,$fecha,$asunto,$adjunto,$mensaje) { $this->id = $id; $this->cantContactos = $cantContactos; $this->cantEmpresas = $cantEmpresas; $this->arrayEmpresas = $arrayEmpresas; $this->fecha = $fecha; $this->asunto = $asunto; $this->adjunto = $adjunto; $this->mensaje = $mensaje; } public function getMensaje(){ return $this->mensaje; } public function setMensaje($mensaje){ $this->mensaje = $mensaje; } public function getAsunto(){ return $this->asunto; } public function setAsunto($asunto){ $this->asunto = $asunto; } public function getAdjunto(){ return $this->adjunto; } public function setAdjunto($adjunto){ $this->adjunto = $adjunto; } public function getId(){ return $this->id; } public function setId($id){ $this->id = $id; } public function getCantContactos(){ return $this->cantContactos; } public function setCantContactos($cantContactos){ $this->cantContactos = $cantContactos; } public function getCantEmpresas(){ return $this->cantEmpresas; } public function setCantEmpresas($cantEmpresas){ $this->cantEmpresas = $cantEmpresas; } public function getArrayEmpresas(){ return $this->arrayEmpresas; } public function setArrayEmpresas($arrayEmpresas){ $this->arrayEmpresas = $arrayEmpresas; } public function getFecha(){ return $this->fecha; } public function setFecha($fecha){ $this->fecha = $fecha; } } ?>
gpl-2.0
de-mklinger/jshint-maven-plugin
src/main/java/de/mklinger/maven/jshint/jshint/JSHint.java
3257
package de.mklinger.maven.jshint.jshint; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.IOUtils; import org.mozilla.javascript.EcmaError; import org.mozilla.javascript.NativeArray; import org.mozilla.javascript.NativeObject; import org.mozilla.javascript.ScriptableObject; import de.mklinger.maven.jshint.util.Rhino; public class JSHint { private static final String PREQUEL = "print=function(){};" + "quit=function(){};" + "readFile=function(){};" + "arguments=[];"; private final Rhino rhino; private final String srcFileEncoding; public JSHint(final String jshintResourceName, final String srcFileEncoding) throws IOException { this.srcFileEncoding = srcFileEncoding; rhino = new Rhino(); try { rhino.eval(PREQUEL); rhino.eval(commentOutTheShebang(resourceAsString(jshintResourceName, "UTF-8"))); } catch (final EcmaError e) { throw new RuntimeException("Javascript eval error:" + e.getScriptStackTrace(), e); } } private String commentOutTheShebang(final String code) { if (code.startsWith("#!")) { return "//" + code; } else { return code; } } public List<Hint> run(final InputStream source, final String options, final String globals) throws IOException { final List<Hint> results = new ArrayList<Hint>(); final String sourceAsText = toString(source, srcFileEncoding); final NativeObject nativeOptions = toJsObject(options); final NativeObject nativeGlobals = toJsObject(globals); final Boolean codePassesMuster = rhino.call("JSHINT", sourceAsText, nativeOptions, nativeGlobals); if (!codePassesMuster) { final NativeArray errors = rhino.eval("JSHINT.errors"); for (final Object next : errors) { if (next != null) { // sometimes it seems that the last error in the list is null final JSObject jso = new JSObject((NativeObject)next); results.add(new Hint(jso)); } } } return results; } private NativeObject toJsObject(final String options) { final NativeObject nativeOptions = new NativeObject(); for (final String nextOption : options.split(",")) { final String option = nextOption.trim(); if (!option.isEmpty()) { final String name; final Object value; final int valueDelimiter = option.indexOf(':'); if (valueDelimiter == -1) { name = option; value = Boolean.TRUE; } else { name = option.substring(0, valueDelimiter); final String rest = option.substring(valueDelimiter + 1).trim(); if (rest.matches("[0-9]+")) { value = Integer.parseInt(rest); } else if ("true".equals(rest)) { value = Boolean.TRUE; } else if ("false".equals(rest)) { value = Boolean.FALSE; } else { value = rest; } } nativeOptions.defineProperty(name, value, ScriptableObject.READONLY); } } return nativeOptions; } private static String toString(final InputStream in, final String encoding) throws IOException { return IOUtils.toString(in, encoding); } private String resourceAsString(final String name, final String encoding) throws IOException { try (final InputStream in = getClass().getResourceAsStream(name)) { return toString(in, encoding); } } }
gpl-2.0
maxhutch/nek-tests
corner/test_corner.py
1475
import json from nekpy.dask.subgraph import series from nekpy.dask import run_all from nekpy.dask.tasks import configure from os.path import join, dirname from os import getcwd from nekpy.tools.log import grep_log import numpy as np import pytest base_dir = join(getcwd(), "scratch") with open(join(dirname(__file__), "corner_f90.tusr"), "r") as f: tusr = f.read() def ndiff(test, ref): tests = grep_log(test, "Maximum scalar") refs = grep_log(ref, "Maximum scalar") assert tests.shape[0] == refs.shape[0] max_scalar_diff = np.max(np.abs(tests-refs)) assert max_scalar_diff < 1.e-9 tests = grep_log(test, "Maximum velocity") refs = grep_log(ref, "Maximum velocity") assert tests.shape[0] == refs.shape[0] max_velocity_diff = np.max(np.abs(tests-refs)) assert max_velocity_diff < 1.e-9 return def old_test(name): with open(join(dirname(__file__), "{}.json".format(name))) as f: base = json.load(f) base["prefix"] = "test_{}".format(name) workdir = join(base_dir, base["prefix"]) config = configure(base, {'name': base["prefix"]}, workdir) res = series(config, tusr) run_all([res,], base)[0] with open(join(workdir, "{}-0.stdout".format(base["prefix"]))) as f: test = f.readlines() with open(join(dirname(__file__), "{}_ref.out".format(name))) as f: ref = f.readlines() ndiff(test, ref) return def test_simple(): old_test("corner") return
gpl-2.0
NatLibFi/NDL-VuFind2
module/Finna/src/Finna/View/Helper/Root/Callnumber.php
3663
<?php /** * Holdings callnumber view helper * * PHP version 7 * * Copyright (C) The National Library of Finland 2016. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category VuFind * @package View_Helpers * @author Samuli Sillanpää <samuli.sillanpaa@helsinki.fi> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org Main Site */ namespace Finna\View\Helper\Root; use Finna\LocationService\LocationService; /** * Holdings callnumber view helper * * @category VuFind * @package View_Helpers * @author Samuli Sillanpää <samuli.sillanpaa@helsinki.fi> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org Main Site */ class Callnumber extends \Laminas\View\Helper\AbstractHelper { /** * Location Service. * * @var LocationService */ protected $locationService = null; /** * Constructor * * @param LocationService $locationService Location Service * of Finland Location Service */ public function __construct(LocationService $locationService) { $this->locationService = $locationService; } /** * Returns HTML for a holding callnumber. * * @param string $source Record source * @param string $title Record title * @param string $callnumber Callnumber * @param string $collection Collection * @param string $location Location * @param string $language Language * @param string $page Page (record|results) * * @return string */ public function callnumber( $source, $title, $callnumber, $collection, $location, $language, $page = 'record' ) { $params = [ 'callnumber' => $callnumber, 'location' => $location, 'title' => $title, 'page' => $page, 'source' => $source ]; // Set results-online to just results for qrCode config below if ('results-online' === $page) { $page = 'results'; } $config = $this->locationService->getConfig( $source, $title, $callnumber, $collection, $location, $language ); if ($config) { $params['collection'] = $collection; $params['location'] = $location; $params['title'] = $title; $params['locationServiceUrl'] = $config['url']; $params['locationServiceModal'] = $config['modal']; $params['qrCode'] = $config[$page == 'results' ? 'qrCodeResults' : 'qrCodeRecord']; } return $this->getView()->render( 'Helpers/holding-callnumber.phtml', $params ); } /** * Check if QR-code option is enabled. * * @return boolean */ public function useQrCode() { return $this->locationService->useQrCode(); } }
gpl-2.0
ducsatthu/com_fee
site/controllers/department.php
4640
<?php /** * @version 1.0.0 * @package com_fee * @copyright Bản quyền (C) 2015. Các quyền đều được bảo vệ. * @license bản quyền mã nguồn mở GNU phiên bản 2 * @author Linh <mr.lynk92@gmail.com> - http:// */ // No direct access defined('_JEXEC') or die; require_once JPATH_COMPONENT . '/controller.php'; /** * Department controller class. */ class FeeControllerDepartment extends FeeController { /** * Method to check out an item for editing and redirect to the edit form. * * @since 1.6 */ public function edit() { $app = JFactory::getApplication(); // Get the previous edit id (if any) and the current edit id. $previousId = (int) $app->getUserState('com_fee.edit.department.id'); $editId = $app->input->getInt('id', null, 'array'); // Set the user id for the user to edit in the session. $app->setUserState('com_fee.edit.department.id', $editId); // Get the model. $model = $this->getModel('Department', 'FeeModel'); // Check out the item if ($editId) { $model->checkout($editId); } // Check in the previous user. if ($previousId && $previousId !== $editId) { $model->checkin($previousId); } // Redirect to the edit screen. $this->setRedirect(JRoute::_('index.php?option=com_fee&view=departmentform&layout=edit', false)); } /** * Method to save a user's profile data. * * @return void * @since 1.6 */ public function publish() { // Initialise variables. $app = JFactory::getApplication(); //Checking if the user can remove object $user = JFactory::getUser(); if ($user->authorise('core.edit', 'com_fee') || $user->authorise('core.edit.state', 'com_fee')) { $model = $this->getModel('Department', 'FeeModel'); // Get the user data. $id = $app->input->getInt('id'); $state = $app->input->getInt('state'); // Attempt to save the data. $return = $model->publish($id, $state); // Check for errors. if ($return === false) { $this->setMessage(JText::sprintf('Save failed: %s', $model->getError()), 'warning'); } // Clear the profile id from the session. $app->setUserState('com_fee.edit.department.id', null); // Flush the data from the session. $app->setUserState('com_fee.edit.department.data', null); // Redirect to the list screen. $this->setMessage(JText::_('COM_FEE_ITEM_SAVED_SUCCESSFULLY')); $menu = & JSite::getMenu(); $item = $menu->getActive(); if (!$item) { // If there isn't any menu item active, redirect to list view $this->setRedirect(JRoute::_('index.php?option=com_fee&view=departments', false)); } else { $this->setRedirect(JRoute::_($item->link . $menuitemid, false)); } } else { throw new Exception(500); } } public function remove() { // Initialise variables. $app = JFactory::getApplication(); //Checking if the user can remove object $user = JFactory::getUser(); if ($user->authorise($user->authorise('core.delete', 'com_fee'))) { $model = $this->getModel('Department', 'FeeModel'); // Get the user data. $id = $app->input->getInt('id', 0); // Attempt to save the data. $return = $model->delete($id); // Check for errors. if ($return === false) { $this->setMessage(JText::sprintf('Delete failed', $model->getError()), 'warning'); } else { // Check in the profile. if ($return) { $model->checkin($return); } // Clear the profile id from the session. $app->setUserState('com_fee.edit.department.id', null); // Flush the data from the session. $app->setUserState('com_fee.edit.department.data', null); $this->setMessage(JText::_('COM_FEE_ITEM_DELETED_SUCCESSFULLY')); } // Redirect to the list screen. $menu = & JSite::getMenu(); $item = $menu->getActive(); $this->setRedirect(JRoute::_($item->link, false)); } else { throw new Exception(500); } } }
gpl-2.0
1anc3r/Horse_Riding_Board
Board.java
3557
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Board extends JPanel { private JLabel l[][]; final int D = 8; final int M = 12; final int b[][] = new int[M][M]; private int px[] = new int[64]; private int py[] = new int[64]; final int nx[] = {-2, -1, 1, 2, 2, 1, -1, -2}; final int ny[] = {1, 2, 2, 1, -1, -2, -2, -1}; int ox,oy; public void initBoard(){ int i, j; for (i = 0; i < 2; i++ ){ for (j = 0; j < M; j++){ b[i][j]=1; b[M-i-1][j]=1; b[j][i]=1; b[j][M-i-1]=1; } } } public void Path(int x, int y){ px[0] = x; py[0] = y; x = x + 1; y = y + 1; int i; int pedometer = 1; int direction[] = new int[D]; int nsd=8,nsx=0,nsy=0; b[x][y] = pedometer; for (pedometer = 2; pedometer < 65; pedometer++) { nsd = 8; for (i = 0; i < D; i++) { if (b[x+nx[i]][y+ny[i]] == 0) { direction[i] = Step(x+nx[i],y+ny[i]); if (direction[i] < nsd) { nsd = direction[i]; nsx = x+nx[i]; nsy = y+ny[i]; } } } x = nsx; y = nsy; b[x][y] = pedometer; px[pedometer-1] = x-1; py[pedometer-1] = y-1; } } public int Step(int x, int y){ int count = 0; for (int i = 0; i < D; i++) { if (b[x+nx[i]][y+ny[i]] == 0) { count++; } } return count; } public void initGUI(int grids,int gridsize) { l = new JLabel[grids][grids]; for(int i=0; i<grids; i++) { for(int j=0; j<grids; j++) { l[i][j] = new JLabel(); l[i][j].setSize(gridsize,gridsize); l[i][j].setLocation(i*gridsize,j*gridsize); l[i][j].setFont(new java.awt.Font("Dialog", 1, 25)); l[i][j].setForeground(Color.gray); l[i][j].setHorizontalTextPosition(JLabel.CENTER); l[i][j].setHorizontalAlignment(SwingConstants.CENTER); l[i][j].addMouseListener(new MouseAdapter(i,j)); ; l[i][j].setBorder(BorderFactory.createLineBorder(Color.black)); if((i+j)%2==0) { l[i][j].setBackground(Color.black); l[i][j].setOpaque(true); } add(l[i][j]); } } } public class MouseAdapter implements MouseListener{ int x,y; public MouseAdapter(int i,int j){ x = j; y = i; } public void mouseClicked(MouseEvent e) { Path(x+1,y+1); new Jump(l,px,py).start(); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } } public Board(){ super(null); initGUI(8,80); initBoard(); } public static void main(String[] args) { JFrame f = new JFrame(); f.setSize(658,677); f.setLocationRelativeTo(null); f.add(new Board()); f.setVisible(true); } }
gpl-2.0
iagolucchese/projectRooms
Assets/_makeYOURlevel_LITE/PREFAB_makeYOURlevel_LITE/6_scripts/uScriptRuntime/Nodes/Actions/Variables/Lists/uScriptAct_ModifyListByIndexGameObject.cs
3307
// uScript Action Node // (C) 2011 Detox Studios LLC using UnityEngine; using System.Collections; using System.Collections.Generic; [NodePath("Actions/Variables/Lists/GameObject")] [NodeCopyright("Copyright 2012 by Detox Studios LLC")] [NodeToolTip("Modify a list by specifying a specific slot number (index) in the list.")] [NodeAuthor("Detox Studios LLC", "http://www.detoxstudios.com")] [NodeHelp("http://www.uscript.net/docs/index.php?title=Node_Reference_Guide")] [FriendlyName("Modify List By Index (GameObject)", "Modify a list by specifying a specific slot number (index) in the list.")] public class uScriptAct_ModifyListByIndexGameObject : uScriptLogic { // ================================================================================ // Output Sockets // ================================================================================ // public bool Out { get { return true; } } // ================================================================================ // Input Sockets and Node Parameters // ================================================================================ [FriendlyName("Insert Into List", "Inserts an item into the list at the specified index.")] public void InsertIntoList (ref GameObject[] GameObjectList, int Index, GameObject[] Target, out int ListCount) { List<GameObject> list = new List<GameObject> (GameObjectList); if (Index < 0) { Index = 0; } if (list.Count == 0) { foreach (GameObject go in Target) { list.Add (go); } } else { if (Index + 1 >= list.Count) { foreach (GameObject go in Target) { list.Add (go); } } else { foreach (GameObject go in Target) { list.Insert (Index, go); } } } GameObjectList = list.ToArray (); ListCount = GameObjectList.Length; } // Parameter Attributes are applied below in EmptyList() [FriendlyName("Remove From List", "Removes an item from the list at the specified index.")] public void RemoveFromList ( [FriendlyName("List", "The list to modify.")] ref GameObject[] GameObjectList, [FriendlyName("Index", "The index number where you wish to perform the modification. If the number is larger than the elements contained in the list, the action will be performed on the largest valid index number of the list. Negative values are automatically converted to 0.")] int Index, [FriendlyName("Insert Target", "The Target variable(s) to add or remove from the list. This socket is ignored when using the Remove From List input socket.")] GameObject[] Target, [FriendlyName("List Size", "The remaining number of items in the list after the modification has taken place.")] out int ListCount ) { List<GameObject> list = new List<GameObject> (GameObjectList); if (Index < 0) { Index = 0; } if (list.Count > 0) { if (Index >= list.Count) { list.RemoveAt (list.Count - 1); } else { list.RemoveAt (Index); } } GameObjectList = list.ToArray (); ListCount = GameObjectList.Length; } // ================================================================================ // Miscellaneous Node Functionality // ================================================================================ // }
gpl-2.0
tectronics/xenogeddon
src/com/jmex/font3d/math/TriangulationEdge.java
2519
/* * Copyright (c) 2003-2009 jMonkeyEngine * 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 'jMonkeyEngine' 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 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. */ package com.jmex.font3d.math; public class TriangulationEdge extends PlanarEdge { /** Used when making the monotone polygons. */ TriangulationVertex helper = null; public boolean marked = false; TriangulationEdge(PlanarVertex orig, boolean real) { super(orig, real); } public TriangulationVertex getOtherEnd(TriangulationVertex currentvertex) { return (TriangulationVertex) (getOrigin() == currentvertex ? getTwin().getOrigin() : getOrigin()); } public boolean isHelperMergeVertex() { return (helper != null && helper.getType() == TriangulationVertex.VertexType.MERGE); } @Override public String toString() { return "{("+(isRealEdge() ? "real " : "unreal")+")"+ getOrigin().getIndex()+"("+getOrigin().point.x+","+getOrigin().point.y+")->"+ getTwin().getOrigin().getIndex()+":("+getTwin().getOrigin().point.x+","+getTwin().getOrigin().point.y+")"+ ",Helper:"+helper+ ",angle:"+getAngle()+"}"; } }
gpl-2.0
quazgar/bioread
src/bioread/headers.py
19345
# coding: utf8 # Part of the bioread package for reading BIOPAC data. # # Copyright (c) 2010 Board of Regents of the University of Wisconsin System # # Written by John Ollinger <ollinger@wisc.edu> and Nate Vack <njvack@wisc.edu> # at the Waisman Laboratory for Brain Imaging and Behavior, University of # Wisconsin-Madison # Project home: http://github.com/njvack/bioread from bioread.struct_dict import StructDict from bioread.file_revisions import * class Header(object): """ Represents a binary header and its unpacking """ def __init__(self, struct_dict): self.struct_dict = struct_dict self.offset = None self.unpacked = {} def unpack_from_str(self, str_data): self.raw_data = str_data self.__unpack_data() def unpack_from_file(self, data_file, offset): self.offset = offset data_file.seek(offset) self.raw_data = data_file.read(self.struct_dict.len_bytes) self.__unpack_data() @property def effective_len_bytes(self): """ This will be overridden frequently -- it's used in navigating files. """ return self.struct_dict.len_bytes @property def format_string(self): return self.struct_dict.format_string def __unpack_data(self): self.data = self.struct_dict.unpack(self.raw_data) def __getitem__(self, key): return self.data[key] def __str__(self): return str(self.data) class VersionedHeaderStructure(object): def __init__(self, *structure_elements): self.structure_elements = structure_elements def elements_for(self, version): return [se for se in self.structure_elements if se[2] <= version] class BiopacHeader(Header): """ A simple superclass for GraphHeader, ChannelHeader, and friends. """ def __init__(self, header_structure, file_revision, byte_order_flag): self.file_revision = file_revision self.byte_order_flag = byte_order_flag self.header_structure = header_structure sd = StructDict( byte_order_flag, header_structure.elements_for(file_revision)) super(BiopacHeader, self).__init__(sd) class GraphHeader(BiopacHeader): """ The main Graph Header for an AcqKnowledge file. The documentation is much more complete for older files (revision 45 and below); I've looked to find the reliable (and essential) structure information in later files. The fields we really need to decode the data: Length Number of channels Sample time Data compressed? """ def __init__(self, file_revision, byte_order_flag): self.file_revision = file_revision super(GraphHeader, self).__init__( self.__h_elts, file_revision, byte_order_flag) @property def effective_len_bytes(self): return self.data['lExtItemHeaderLen'] @property def channel_count(self): return self.data['nChannels'] @property def sample_time(self): return self.data['dSampleTime'] @property def compressed(self): return self.data.get('bCompressed') == 1 @property def data_format(self): fmt = 'uncompressed' if self.compressed: fmt = 'compressed' return fmt @property def __version_bin(self): bin = 'Unknown' if self.file_revision < V_400B: bin = 'PRE_4' else: bin = 'POST_4' return bin @property def __h_elt_versions(self): return { 'PRE_4' : VersionedHeaderStructure( ('nItemHeaderLen' ,'h' ,V_ALL), ('lVersion' ,'l' ,V_ALL), ('lExtItemHeaderLen' ,'l' ,V_20a), ('nChannels' ,'h' ,V_20a), ('nHorizAxisType' ,'h' ,V_20a), ('nCurChannel' ,'h' ,V_20a), ('dSampleTime' ,'d' ,V_20a), ('dTimeOffset' ,'d' ,V_20a), ('dTimeScale' ,'d' ,V_20a), ('dTimeCursor1' ,'d' ,V_20a), ('dTimeCursor2' ,'d' ,V_20a), ('rcWindow' ,'4h' ,V_20a), ('nMeasurement' ,'6h' ,V_20a), ('fHilite' ,'h' ,V_20a), ('dFirstTimeOffset' ,'d' ,V_20a), ('nRescale' ,'h' ,V_20a), ('szHorizUnits1' ,'40s' ,V_20a), ('szHorizUnits2' ,'10s' ,V_20a), ('nInMemory' ,'h' ,V_20a), ('fGrid' ,'h' ,V_20a), ('fMarkers' ,'h' ,V_20a), ('nPlotDraft' ,'h' ,V_20a), ('nDispMode' ,'h' ,V_20a), ('rRReserved' ,'h' ,V_20a), ('BShowToolBar' ,'h' ,V_30r), ('BShowChannelButtons' ,'h' ,V_30r), ('BShowMeasurements' ,'h' ,V_30r), ('BShowMarkers' ,'h' ,V_30r), ('BShowJournal' ,'h' ,V_30r), ('CurXChannel' ,'h' ,V_30r), ('MmtPrecision' ,'h' ,V_30r), ('NMeasurementRows' ,'h' ,V_303), ('mmt40' ,'40h' ,V_303), ('mmtChan40' ,'40h' ,V_303), ('MmtCalcOpnd1' ,'40h' ,V_35x), ('MmtCalcOpnd2' ,'40h' ,V_35x), ('MmtCalcOp' ,'40h' ,V_35x), ('MmtCalcConstant' ,'40d' ,V_35x), ('bNewGridWithMinor' ,'l' ,V_370), ('colorMajorGrid' ,'4B' ,V_370), ('colorMinorGrid' ,'4B' ,V_370), ('wMajorGridStyle' ,'h' ,V_370), ('wMinorGridStyle' ,'h' ,V_370), ('wMajorGridWidth' ,'h' ,V_370), ('wMinorGridWidth' ,'h' ,V_370), ('bFixedUnitsDiv' ,'l' ,V_370), ('bMid_Range_Show' ,'l' ,V_370), ('dStart_Middle_Point' ,'d' ,V_370), ('dOffset_Point' ,'60d' ,V_370), ('hGrid' ,'d' ,V_370), ('vGrid' ,'60d' ,V_370), ('bEnableWaveTools' ,'l' ,V_370), ('hozizPrecision' ,'h' ,V_373), ('Reserved' ,'20b' ,V_381), ('bOverlapMode' ,'l' ,V_381), ('bShowHardware' ,'l' ,V_381), ('bXAutoPlot' ,'l' ,V_381), ('bXAutoScroll' ,'l' ,V_381), ('bStartButtonVisible' ,'l' ,V_381), ('bCompressed' ,'l' ,V_381), ('bAlwaysStartButtonVisible','l' ,V_381), ('pathVideo' ,'260s' ,V_382), ('optSyncDelay' ,'l' ,V_382), ('syncDelay' ,'d' ,V_382), ('bHRP_PasteMeasurements' ,'l' ,V_382), ('graphType' ,'l' ,V_390), ('mmtCalcExpr' ,'10240s',V_390), ('mmtMomentOrder' ,'40l' ,V_390), ('mmtTimeDelay' ,'40l' ,V_390), ('mmtEmbedDim' ,'40l' ,V_390), ('mmtMIDelay' ,'40l' ,V_390), ), 'POST_4' : VersionedHeaderStructure( ('nItemHeaderLen' ,'h' ,V_ALL), ('lVersion' ,'l' ,V_ALL), ('lExtItemHeaderLen' ,'l' ,V_20a), ('nChannels' ,'h' ,V_20a), ('nHorizAxisType' ,'h' ,V_20a), ('nCurChannel' ,'h' ,V_20a), ('dSampleTime' ,'d' ,V_20a), ('dTimeOffset' ,'d' ,V_20a), ('dTimeScale' ,'d' ,V_20a), ('dTimeCursor1' ,'d' ,V_20a), ('dTimeCursor2' ,'d' ,V_20a), ('rcWindow' ,'4h' ,V_20a), ('nMeasurement' ,'6h' ,V_20a), ('fHilite' ,'h' ,V_20a), ('dFirstTimeOffset' ,'d' ,V_20a), ('nRescale' ,'h' ,V_20a), ('szHorizUnits1' ,'40s' ,V_20a), ('szHorizUnits2' ,'10s' ,V_20a), ('nInMemory' ,'h' ,V_20a), ('fGrid' ,'h' ,V_20a), ('fMarkers' ,'h' ,V_20a), ('nPlotDraft' ,'h' ,V_20a), ('nDispMode' ,'h' ,V_20a), ('rRReserved' ,'h' ,V_20a), ('Unknown' ,'822B' ,V_400B), ('bCompressed' ,'l' ,V_400B), )} @property def __h_elts(self): return self.__h_elt_versions[self.__version_bin] class ChannelHeader(BiopacHeader): """ The main Channel Header for an AcqKnowledge file. Note that this is known to be wrong for more modern files -- but for the purposes of this reader, we don't care. Enough fields are right that we can still find our way around. """ def __init__(self, file_revision, byte_order_flag): self.file_revision = file_revision super(ChannelHeader, self).__init__( self.__h_elts, file_revision, byte_order_flag) @property def __version_bin(self): bin = 'Unknown' if self.file_revision < V_400B: bin = 'PRE_4' else: bin = 'POST_4' return bin @property def effective_len_bytes(self): return self.data['lChanHeaderLen'] @property def frequency_divider(self): """ The number you divide the graph's samples_per_second by to get this channel's samples_per_second. If not defined (as in old file versions), this should be 1. """ return self.data.get('nVarSampleDivider') or 1 @property def raw_scale(self): return self.data['dAmplScale'] @property def raw_offset(self): return self.data['dAmplOffset'] @property def units(self): return self.data['szUnitsText'] @property def name(self): return self.data['szCommentText'] @property def point_count(self): return self.data['lBufLength'] @property def __h_elts(self): return self.__h_elt_versions[self.__version_bin] @property def __h_elt_versions(self): return { 'PRE_4' : VersionedHeaderStructure( ('lChanHeaderLen' ,'l' ,V_20a), ('nNum' ,'h' ,V_20a), ('szCommentText' ,'40s' ,V_20a), ('rgbColor' ,'4B' ,V_20a), ('nDispChan' ,'h' ,V_20a), ('dVoltOffset' ,'d' ,V_20a), ('dVoltScale' ,'d' ,V_20a), ('szUnitsText' ,'20s' ,V_20a), ('lBufLength' ,'l' ,V_20a), ('dAmplScale' ,'d' ,V_20a), ('dAmplOffset' ,'d' ,V_20a), ('nChanOrder' ,'h' ,V_20a), ('nDispSize' ,'h' ,V_20a), ('plotMode' ,'h' ,V_30r), ('vMid' ,'d' ,V_30r), ('szDescription' ,'128s' ,V_370), ('nVarSampleDivider' ,'h' ,V_370), ('vertPrecision' ,'h' ,V_373), ('activeSegmentColor' ,'4b' ,V_382), ('activeSegmentStyle' ,'l' ,V_382), ), 'POST_4' : VersionedHeaderStructure( ('lChanHeaderLen' ,'l' ,V_20a), ('nNum' ,'h' ,V_20a), ('szCommentText' ,'40s' ,V_20a), ('notColor' ,'4B' ,V_20a), ('nDispChan' ,'h' ,V_20a), ('dVoltOffset' ,'d' ,V_20a), ('dVoltScale' ,'d' ,V_20a), ('szUnitsText' ,'20s' ,V_20a), ('lBufLength' ,'l' ,V_20a), ('dAmplScale' ,'d' ,V_20a), ('dAmplOffset' ,'d' ,V_20a), ('nChanOrder' ,'h' ,V_20a), ('nDispSize' ,'h' ,V_20a), ('unknown' ,'40s' ,V_400B), ('nVarSampleDivider' ,'h' ,V_400B), )} class ForeignHeader(BiopacHeader): """ The Foreign Data header for AcqKnowledge files. This does some tricky stuff based on file versions, ultimately to correctly determine the effective length. """ def __init__(self, file_revision, byte_order_flag): self.file_revision = file_revision super(ForeignHeader, self).__init__( self.__h_elts, file_revision, byte_order_flag) @property def __version_bin(self): bin = 'Unknown' if self.file_revision <= V_390: bin = "PRE_4" elif self.file_revision < V_41a: bin = "EARLY_4" else: bin = "LATE_4" return bin @property def effective_len_bytes(self): return self.__effective_len_byte_versions[self.__version_bin]() @property def __h_elts(self): return self.__h_elt_versions[self.__version_bin] @property def __effective_len_byte_versions(self): # Make a hash of functions so we don't evaluate all code paths return { "PRE_4" : lambda: self.data['nLength'], "EARLY_4" : lambda: self.data['lLengthExtended'] + 8, "LATE_4" : lambda: self.data['nLength'] + 8 # always correct? } @property def __h_elt_versions(self): return { "PRE_4" : VersionedHeaderStructure( ('nLength' ,'h' ,V_20a), ('nType' ,'h' ,V_20a), ), "EARLY_4" : VersionedHeaderStructure( ('nLength' ,'h' ,V_400B), ('nType' ,'h' ,V_400B), ('lReserved' ,'l' ,V_400B), ('lLengthExtended' ,'l' ,V_400B), ), "LATE_4" : VersionedHeaderStructure( ('nLength' ,'h' ,V_400B), ('nType' ,'h' ,V_400B), ('lReserved' ,'l' ,V_400B), )} class ChannelDTypeHeader(BiopacHeader): def __init__(self, file_revision, byte_order_flag): super(ChannelDTypeHeader, self).__init__( self.__h_elts, file_revision, byte_order_flag) @property def type_code(self): return self.data['nType'] @property def __h_elts(self): # This lets the standard effective_len_bytes work fine, I think. return VersionedHeaderStructure( ('nSize' ,'h' ,V_20a), ('nType' ,'h' ,V_20a), ) class MainCompressionHeader(BiopacHeader): # In old (r41) compressed files, the header's 232 bytes long and I have # no idea what's in it. # In new compressed files, at data_start_offset there's a long, # containing the length of some header H1. # At data_start_offset + len(H1), there's something we don't care about. # From there, it's 94 bytes to the start of the first channel header. def __init__(self, file_revision, byte_order_flag): super(MainCompressionHeader, self).__init__( self.__h_elts, file_revision, byte_order_flag) @property def effective_len_bytes(self): return self.__effective_len_byte_versions[self.__version_bin]() @property def __effective_len_byte_versions(self): # Determined through experimentation, may not be correct for some # revisions. return { 'PRE_4': lambda: 232, 'POST_4': lambda: self.data['lSize'] + 94 } @property def __version_bin(self): bin = "Unknown" if self.file_revision < V_400B: bin = "PRE_4" else: bin = "POST_4" return bin @property def __h_elts(self): return VersionedHeaderStructure( ('lSize' ,'l' ,V_381), ) class ChannelCompressionHeader(BiopacHeader): def __init__(self, file_revision, byte_order_flag): super(ChannelCompressionHeader, self).__init__( self.__h_elts, file_revision, byte_order_flag) @property def effective_len_bytes(self): """ Return the length of the header UP TO THE NEXT HEADER, skipping the compressed data. Use header_only_len_bytes for only the header length. """ return self.header_only_len_bytes + self.data['lCompressedLen'] @property def header_only_len_bytes(self): """ A truly variable-length header. Oddly, the channel description and units are included in the header. This class doesn't have a way to get those out, but we'll just use them from the earlier channel header. Immediately after this header, the compressed data starts -- it will be after the units text, and starts with 'x'. """ return (self.struct_dict.len_bytes + self.data['lChannelLabelLen'] + self.data['lUnitLabelLen']) @property def compressed_data_offset(self): """ The offset to the compressed data. Note that this won't be valid until self#unpack_from_file() is run. """ return self.offset + self.header_only_len_bytes @property def compressed_data_len(self): return self.data['lCompressedLen'] @property def __h_elts(self): return VersionedHeaderStructure( ('Unknown' ,'44B' ,V_381), ('lChannelLabelLen' ,'l' ,V_381), ('lUnitLabelLen' ,'l' ,V_381), ('lUncompressedLen' ,'l' ,V_381), ('lCompressedLen' ,'l' ,V_381), )
gpl-2.0
Ryudo302/chartifacts
chartifacts-parent/chartifacts-core/src/test/java/br/com/colbert/chartifacts/negocio/chartrun/MaiorSubidaChartRunStrategyTest.java
1792
package br.com.colbert.chartifacts.negocio.chartrun; import static br.com.colbert.chartifacts.dominio.chart.PosicaoChart.NUMERO_POSICAO_AUSENCIA; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.Optional; import javax.inject.Inject; import org.junit.Test; import br.com.colbert.chartifacts.dominio.chart.ChartRun; import br.com.colbert.chartifacts.tests.support.AbstractTestCase; /** * Testes unitários da {@link MaiorSubidaChartRunStrategy}. * * @author Thiago Colbert * @since 15/03/2015 */ public class MaiorSubidaChartRunStrategyTest extends AbstractTestCase { @Inject private MaiorSubidaChartRunStrategy strategy; @Test public void testIdentificarComSubidas() { ChartRun chartRun = ChartRun.novo(10, 7, 1); Optional<VariacaoPosicao> maiorSubida = strategy.identificar(chartRun); assertThat(maiorSubida.isPresent(), is(true)); VariacaoPosicao variacao = maiorSubida.get(); assertThat(variacao.getNumeroPosicaoA(), is(equalTo(7))); assertThat(variacao.getNumeroPosicaoB(), is(equalTo(1))); } @Test public void testIdentificarComSubidasESaidas() { ChartRun chartRun = ChartRun.novo(10, 7, 1, NUMERO_POSICAO_AUSENCIA, 5, 10); Optional<VariacaoPosicao> maiorQueda = strategy.identificar(chartRun); assertThat(maiorQueda.isPresent(), is(true)); VariacaoPosicao variacao = maiorQueda.get(); assertThat(variacao.getNumeroPosicaoA(), is(equalTo(7))); assertThat(variacao.getNumeroPosicaoB(), is(equalTo(1))); } @Test public void testIdentificarSemSubidas() { ChartRun chartRun = ChartRun.novo(10, 12, 14); Optional<VariacaoPosicao> maiorSubida = strategy.identificar(chartRun); assertThat(maiorSubida.isPresent(), is(false)); } }
gpl-2.0
iMitaka/HackBulgaria
Week 10/01 - Books/BookManager/BookManager.Models/Properties/AssemblyInfo.cs
1412
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BookManager.Models")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BookManager.Models")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("166ffb85-be47-40eb-bc89-71282c4a4f66")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
gpl-2.0
EcosistemaUrbano/local_in
localin/registro.php
1455
<?php ob_start(); /* Template Name: Registro de usuario */ get_header(); if ( array_key_exists('nombre', $_POST) ) { $nombre = sanitize_text_field($_POST['nombre']); } if ( array_key_exists('mail', $_POST) ) { $mail = sanitize_text_field($_POST['mail']); } if ( array_key_exists('pass', $_POST) ) { $pass = sanitize_text_field($_POST['pass']); } if ( array_key_exists('pass2', $_POST) ) { $pass2 = sanitize_text_field($_POST['pass2']); } if ( array_key_exists('ref', $_POST) ) { $ref = sanitize_text_field($_POST['ref']); } else { $ref = WHATIF_BLOGURL; } $user_id = username_exists( $nombre ); // nos aseguramos que el user no existe if ( $user_id ) { $redirect = WHATIF_BLOGURL. "/user-sesion?fail=name&ref=" .$ref; wp_redirect($redirect); exit; } elseif ( email_exists($mail) ) { $redirect = WHATIF_BLOGURL. "/user-sesion?fail=mail&ref=" .$ref; wp_redirect($redirect); exit; } elseif ( $pass != $pass2 ) { $redirect = WHATIF_BLOGURL. "/user-sesion?fail=pass&ref=" .$ref; wp_redirect($redirect); exit; } else { $random_pass = wp_generate_password( 12, false ); // esto se puede usar para que no sea necesario incluir passw if ( $pass == '' ) { $pass = $random_pass; } $user_id = wp_create_user( $nombre, $pass, $mail ); $redirect = WHATIF_BLOGURL. "/user-sesion?signup=success&ref=" .$ref; wp_redirect($redirect); exit; $reg_out = __('Your username has been added.','whatif'); } echo $reg_out; get_footer(); ob_end_flush(); ?>
gpl-2.0
teamfx/openjfx-8u-dev-rt
modules/web/src/main/native/Source/JavaScriptCore/bytecode/ExecutionCounter.cpp
6974
/* * Copyright (C) 2012, 2014, 2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h" #include "ExecutionCounter.h" #include "CodeBlock.h" #include "ExecutableAllocator.h" #include "JSCInlines.h" #include "VMInlines.h" namespace JSC { template<CountingVariant countingVariant> ExecutionCounter<countingVariant>::ExecutionCounter() { reset(); } template<CountingVariant countingVariant> void ExecutionCounter<countingVariant>::forceSlowPathConcurrently() { m_counter = 0; } template<CountingVariant countingVariant> bool ExecutionCounter<countingVariant>::checkIfThresholdCrossedAndSet(CodeBlock* codeBlock) { if (hasCrossedThreshold(codeBlock)) return true; if (setThreshold(codeBlock)) return true; return false; } template<CountingVariant countingVariant> void ExecutionCounter<countingVariant>::setNewThreshold(int32_t threshold, CodeBlock* codeBlock) { reset(); m_activeThreshold = threshold; setThreshold(codeBlock); } template<CountingVariant countingVariant> void ExecutionCounter<countingVariant>::deferIndefinitely() { m_totalCount = 0; m_activeThreshold = std::numeric_limits<int32_t>::max(); m_counter = std::numeric_limits<int32_t>::min(); } double applyMemoryUsageHeuristics(int32_t value, CodeBlock* codeBlock) { #if ENABLE(JIT) double multiplier = ExecutableAllocator::memoryPressureMultiplier( codeBlock->baselineAlternative()->predictedMachineCodeSize()); #else // This code path will probably not be taken, but if it is, we fake it. double multiplier = 1.0; UNUSED_PARAM(codeBlock); #endif ASSERT(multiplier >= 1.0); return multiplier * value; } int32_t applyMemoryUsageHeuristicsAndConvertToInt(int32_t value, CodeBlock* codeBlock) { double doubleResult = applyMemoryUsageHeuristics(value, codeBlock); ASSERT(doubleResult >= 0); if (doubleResult > std::numeric_limits<int32_t>::max()) return std::numeric_limits<int32_t>::max(); return static_cast<int32_t>(doubleResult); } template<CountingVariant countingVariant> bool ExecutionCounter<countingVariant>::hasCrossedThreshold(CodeBlock* codeBlock) const { // This checks if the current count rounded up to the threshold we were targeting. // For example, if we are using half of available executable memory and have // m_activeThreshold = 1000, applyMemoryUsageHeuristics(m_activeThreshold) will be // 2000, but we will pretend as if the threshold was crossed if we reach 2000 - // 1000 / 2, or 1500. The reasoning here is that we want to avoid thrashing. If // this method returns false, then the JIT's threshold for when it will again call // into the slow path (which will call this method a second time) will be set // according to the difference between the current count and the target count // according to *current* memory usage. But by the time we call into this again, we // may have JIT'ed more code, and so the target count will increase slightly. This // may lead to a repeating pattern where the target count is slightly incremented, // the JIT immediately matches that increase, calls into the slow path again, and // again the target count is slightly incremented. Instead of having this vicious // cycle, we declare victory a bit early if the difference between the current // total and our target according to memory heuristics is small. Our definition of // small is arbitrarily picked to be half of the original threshold (i.e. // m_activeThreshold). double modifiedThreshold = applyMemoryUsageHeuristics(m_activeThreshold, codeBlock); double actualCount = static_cast<double>(m_totalCount) + m_counter; double desiredCount = modifiedThreshold - static_cast<double>( std::min(m_activeThreshold, maximumExecutionCountsBetweenCheckpoints())) / 2; bool result = actualCount >= desiredCount; CODEBLOCK_LOG_EVENT(codeBlock, "thresholdCheck", ("activeThreshold = ", m_activeThreshold, ", modifiedThreshold = ", modifiedThreshold, ", actualCount = ", actualCount, ", desiredCount = ", desiredCount)); return result; } template<CountingVariant countingVariant> bool ExecutionCounter<countingVariant>::setThreshold(CodeBlock* codeBlock) { if (m_activeThreshold == std::numeric_limits<int32_t>::max()) { deferIndefinitely(); return false; } // Compute the true total count. double trueTotalCount = count(); // Correct the threshold for current memory usage. double threshold = applyMemoryUsageHeuristics(m_activeThreshold, codeBlock); // Threshold must be non-negative and not NaN. ASSERT(threshold >= 0); // Adjust the threshold according to the number of executions we have already // seen. This shouldn't go negative, but it might, because of round-off errors. threshold -= trueTotalCount; if (threshold <= 0) { m_counter = 0; m_totalCount = trueTotalCount; return true; } threshold = clippedThreshold(codeBlock->globalObject(), threshold); m_counter = static_cast<int32_t>(-threshold); m_totalCount = trueTotalCount + threshold; return false; } template<CountingVariant countingVariant> void ExecutionCounter<countingVariant>::reset() { m_counter = 0; m_totalCount = 0; m_activeThreshold = 0; } template<CountingVariant countingVariant> void ExecutionCounter<countingVariant>::dump(PrintStream& out) const { out.printf("%lf/%lf, %d", count(), static_cast<double>(m_activeThreshold), m_counter); } template class ExecutionCounter<CountingForBaseline>; template class ExecutionCounter<CountingForUpperTiers>; } // namespace JSC
gpl-2.0
openjdk/jdk8u
jdk/test/jdk/jfr/tool/TestPrintXML.java
9546
/* * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.tool; import java.io.File; import java.io.StringReader; import java.nio.file.Path; import java.time.OffsetDateTime; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import javax.xml.XMLConstants; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import jdk.jfr.Timespan; import jdk.jfr.Timestamp; import jdk.jfr.ValueDescriptor; import jdk.jfr.consumer.RecordedEvent; import jdk.jfr.consumer.RecordedObject; import jdk.jfr.consumer.RecordingFile; import jdk.test.lib.process.OutputAnalyzer; /** * @test * @key jfr * @summary Tests print --xml * * @library /lib / * @modules java.scripting java.xml jdk.jfr * * @run main/othervm jdk.jfr.tool.TestPrintXML */ public class TestPrintXML { public static void main(String... args) throws Throwable { Path recordingFile = ExecuteHelper.createProfilingRecording().toAbsolutePath(); OutputAnalyzer output = ExecuteHelper.jfr("print", "--xml", "--stack-depth", "9999", recordingFile.toString()); System.out.println(recordingFile); String xml = output.getStdout(); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new File(System.getProperty("test.src"), "jfr.xsd")); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setSchema(schema); factory.setNamespaceAware(true); SAXParser sp = factory.newSAXParser(); XMLReader xr = sp.getXMLReader(); RecordingHandler handler = new RecordingHandler(); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.parse(new InputSource(new StringReader(xml))); // Verify that all data was written correctly List<RecordedEvent> events = RecordingFile.readAllEvents(recordingFile); Collections.sort(events, (e1, e2) -> e1.getEndTime().compareTo(e2.getEndTime())); Iterator<RecordedEvent> it = events.iterator(); for (XMLEvent xmlEvent : handler.events) { RecordedEvent re = it.next(); if (!compare(re, xmlEvent.values)) { System.out.println("Expected:"); System.out.println("----------------------"); System.out.println(re); System.out.println(); System.out.println("Was (XML)"); System.out.println("----------------------"); System.out.println(xmlEvent); System.out.println(); throw new Exception("Event doesn't match"); } } } @SuppressWarnings("unchecked") static boolean compare(Object eventObject, Object xmlObject) { if (eventObject == null) { return xmlObject == null; } if (eventObject instanceof RecordedObject) { RecordedObject re = (RecordedObject) eventObject; Map<String, Object> xmlMap = (Map<String, Object>) xmlObject; List<ValueDescriptor> fields = re.getFields(); if (fields.size() != xmlMap.size()) { return false; } for (ValueDescriptor v : fields) { String name = v.getName(); Object xmlValue = xmlMap.get(name); Object expectedValue = re.getValue(name); if (v.getAnnotation(Timestamp.class) != null) { // Make instant of OffsetDateTime xmlValue = OffsetDateTime.parse("" + xmlValue).toInstant().toString(); expectedValue = re.getInstant(name); } if (v.getAnnotation(Timespan.class) != null) { expectedValue = re.getDuration(name); } if (!compare(expectedValue, xmlValue)) { return false; } } return true; } if (eventObject.getClass().isArray()) { Object[] array = (Object[]) eventObject; Object[] xmlArray = (Object[]) xmlObject; if (array.length != xmlArray.length) { return false; } for (int i = 0; i < array.length; i++) { if (!compare(array[i], xmlArray[i])) { return false; } } return true; } String s1 = String.valueOf(eventObject); String s2 = (String) xmlObject; return s1.equals(s2); } static class XMLEvent { String name; private Map<String, Object> values = new HashMap<>(); XMLEvent(String name) { this.name = name; } } public static final class RecordingHandler extends DefaultHandler { private Stack<Object> objects = new Stack<>(); private Stack<SimpleEntry<String, String>> elements = new Stack<>(); private List<XMLEvent> events = new ArrayList<>(); @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { elements.push(new SimpleEntry<>(attrs.getValue("name"), attrs.getValue("index"))); String nil = attrs.getValue("xsi:nil"); if ("true".equals(nil)) { objects.push(null); return; } switch (qName) { case "event": objects.push(new XMLEvent(attrs.getValue("type"))); break; case "struct": objects.push(new HashMap<String, Object>()); break; case "array": objects.push(new Object[Integer.parseInt(attrs.getValue("size"))]); break; case "value": objects.push(new StringBuilder()); break; } } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (!objects.isEmpty()) { Object o = objects.peek(); if (o instanceof StringBuilder) { ((StringBuilder) o).append(ch, start, length); } } } @SuppressWarnings("unchecked") @Override public void endElement(String uri, String localName, String qName) { SimpleEntry<String, String> element = elements.pop(); switch (qName) { case "event": case "struct": case "array": case "value": String name = element.getKey(); Object value = objects.pop(); if (objects.isEmpty()) { events.add((XMLEvent) value); return; } if (value instanceof StringBuilder) { value = ((StringBuilder) value).toString(); } Object parent = objects.peek(); if (parent instanceof XMLEvent) { ((XMLEvent) parent).values.put(name, value); } if (parent instanceof Map) { ((Map<String, Object>) parent).put(name, value); } if (parent != null && parent.getClass().isArray()) { int index = Integer.parseInt(element.getValue()); ((Object[]) parent)[index] = value; } } } public void warning(SAXParseException spe) throws SAXException { throw new SAXException(spe); } public void error(SAXParseException spe) throws SAXException { throw new SAXException(spe); } public void fatalError(SAXParseException spe) throws SAXException { throw new SAXException(spe); } } }
gpl-2.0
vikto9494/Lobo_Browser
XAMJ_Project/HTML_Renderer/org/lobobrowser/html/domimpl/HTMLHtmlElementImpl.java
1373
/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Oct 8, 2005 */ package org.lobobrowser.html.domimpl; import org.w3c.dom.html2.HTMLHtmlElement; public class HTMLHtmlElementImpl extends HTMLElementImpl implements HTMLHtmlElement { public HTMLHtmlElementImpl() { super("HTML", true); } public HTMLHtmlElementImpl(String name) { super(name, true); } public String getVersion() { return this.getAttribute("version"); } public void setVersion(String version) { this.setAttribute("version", version); } }
gpl-2.0
zsomko/visualcortex
python/plotting/covariance_ellipse.py
3091
#import matplotlib as plt #from numpy import * ## Force matplotlib to not use any Xwindows backend. #matplotlib.use('Agg') #import matplotlib.pyplot as plt #def plot_cov_contour(S, m): ## plots equidensity contor of a gaussian ## S: covariance matrix # phi=arange(0,2*pi+.01,.01) # points=zeros((size(phi), 2) # # [l, v] = linalg.eig(S) # A = diag(l) # # for i in range(0,size(phi)): # x[i] = dot(d, ) # (diag(d)'.*[cos(tRange(i)) sin(tRange(i))])*v'; # # # plot x # import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Arc def plot_point_cov(points, nstd=2, ax=None, **kwargs): """ Plots an `nstd` sigma ellipse based on the mean and covariance of a point "cloud" (points, an Nx2 array). Parameters ---------- points : An Nx2 array of the data points. nstd : The radius of the ellipse in numbers of standard deviations. Defaults to 2 standard deviations. ax : The axis that the ellipse will be plotted on. Defaults to the current axis. Additional keyword arguments are pass on to the ellipse patch. Returns ------- A matplotlib ellipse artist """ pos = points.mean(axis=0) cov = np.cov(points, rowvar=False) return plot_cov_ellipse(cov, pos, nstd, ax, **kwargs) def plot_cov_ellipse(cov, pos, nstd=2, ax=None, **kwargs): """ Plots an `nstd` sigma error ellipse based on the specified covariance matrix (`cov`). Additional keyword arguments are passed on to the ellipse patch artist. Parameters ---------- cov : The 2x2 covariance matrix to base the ellipse on pos : The location of the center of the ellipse. Expects a 2-element sequence of [x0, y0]. nstd : The radius of the ellipse in numbers of standard deviations. Defaults to 2 standard deviations. ax : The axis that the ellipse will be plotted on. Defaults to the current axis. Additional keyword arguments are pass on to the ellipse patch. Returns ------- A matplotlib ellipse artist """ def eigsorted(cov): vals, vecs = np.linalg.eigh(cov) order = vals.argsort()[::-1] return vals[order], vecs[:,order] if ax is None: ax = plt.gca() vals, vecs = eigsorted(cov) theta = np.degrees(np.arctan2(*vecs[:,0][::-1])) # Width and height are "full" widths, not radius width, height = 2 * nstd * np.sqrt(vals) ellip = Arc(xy=pos, width=width, height=height, angle=theta, **kwargs) ax.add_artist(ellip) return ellip if __name__ == '__main__': #-- Example usage ----------------------- # Generate some random, correlated data points = np.random.multivariate_normal( mean=(1,1), cov=[[0.4, 9],[9, 10]], size=1000 ) # Plot the raw points... x, y = points.T plt.plot(x, y, 'ro') # Plot a transparent 3 standard deviation covariance ellipse plot_point_cov(points, nstd=3, alpha=0.5, color='green') plt.show()
gpl-2.0
CoordCulturaDigital-Minc/culturadigital.br
wp-content/plugins/si-captcha-for-wordpress/captcha-secureimage/captcha-temp/8AZAPo22mTAdCxQb.php
32
<?php $captcha_word = 'DREM'; ?>
gpl-2.0
6finger/ci
components/com_phocagallery/views/user/view.html.php
27293
<?php /* * @package Joomla 1.5 * @copyright Copyright (C) 2005 Open Source Matters. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * * @component Phoca Component * @copyright Copyright (C) Jan Pavelka www.phoca.cz * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL */ defined( '_JEXEC' ) or die(); jimport( 'joomla.client.helper' ); jimport( 'joomla.application.component.view' ); jimport( 'joomla.html.pane' ); phocagalleryimport('phocagallery.file.fileupload'); phocagalleryimport( 'phocagallery.file.fileuploadmultiple' ); phocagalleryimport( 'phocagallery.file.fileuploadsingle' ); phocagalleryimport( 'phocagallery.file.fileuploadjava' ); phocagalleryimport('phocagallery.avatar.avatar'); phocagalleryimport('phocagallery.render.renderadmin'); phocagalleryimport('phocagallery.html.category'); //phocagalleryimport('phocagallery.pagination.paginationuser'); class PhocaGalleryViewUser extends JViewLegacy { protected $_context_subcat = 'com_phocagallery.phocagalleryusersubcat'; protected $_context_image = 'com_phocagallery.phocagalleryuserimage'; protected $tmpl; function display($tpl = null) { $app = JFactory::getApplication(); $document = JFactory::getDocument(); $uri = JFactory::getURI(); $menus = $app->getMenu(); $menu = $menus->getActive(); $this->params = $app->getParams(); $user = JFactory::getUser(); $path = PhocaGalleryPath::getPath(); $this->itemId = $app->input->get('Itemid', 0, 'int'); $neededAccessLevels = PhocaGalleryAccess::getNeededAccessLevels(); $access = PhocaGalleryAccess::isAccess($user->getAuthorisedViewLevels(), $neededAccessLevels); $this->tmpl['pi'] = 'media/com_phocagallery/images/'; $this->tmpl['pp'] = 'index.php?option=com_phocagallery&view=user&controller=user'; $this->tmpl['pl'] = 'index.php?option=com_users&view=login&return='.base64_encode($this->tmpl['pp'].'&Itemid='. $this->itemId); // LIBRARY $library = PhocaGalleryLibrary::getLibrary(); //$libraries['pg-css-ie'] = $library->getLibrary('pg-css-ie'); // Only registered users if (!$access) { $app->redirect(JRoute::_($this->tmpl['pl'], false), JText::_('COM_PHOCAGALLERY_NOT_AUTHORISED_ACTION')); exit; } $this->tmpl['gallerymetakey'] = $this->params->get( 'gallery_metakey', '' ); $this->tmpl['gallerymetadesc'] = $this->params->get( 'gallery_metadesc', '' ); if ($this->tmpl['gallerymetakey'] != '') { $document->setMetaData('keywords', $this->tmpl['gallerymetakey']); } if ($this->tmpl['gallerymetadesc'] != '') { $document->setMetaData('description', $this->tmpl['gallerymetadesc']); } PhocaGalleryRenderFront::renderAllCSS(); // = = = = = = = = = = = // PANE // = = = = = = = = = = = // - - - - - - - - - - // ALL TABS // - - - - - - - - - - // UCP is disabled (security reasons) if ((int)$this->params->get( 'enable_user_cp', 0 ) == 0) { $app->redirect(JURI::base(true), JText::_('COM_PHOCAGALLERY_UCP_DISABLED')); exit; } $this->tmpl['tab'] = $app->input->get('tab', 0, 'string'); $this->tmpl['maxuploadchar'] = $this->params->get( 'max_upload_char', 1000 ); $this->tmpl['maxcreatecatchar'] = $this->params->get( 'max_create_cat_char', 1000 ); $this->tmpl['dp'] = PhocaGalleryRenderInfo::getPhocaIc((int)$this->params->get( 'display_phoca_info', 1 )); $this->tmpl['showpageheading'] = $this->params->get( 'show_page_heading', 1 ); $this->tmpl['javaboxwidth'] = $this->params->get( 'java_box_width', 480 ); $this->tmpl['javaboxheight'] = $this->params->get( 'java_box_height', 480 ); $this->tmpl['enableuploadavatar'] = $this->params->get( 'enable_upload_avatar', 1 ); $this->tmpl['uploadmaxsize'] = $this->params->get( 'upload_maxsize', 3145728 ); $this->tmpl['uploadmaxsizeread'] = PhocaGalleryFile::getFileSizeReadable($this->tmpl['uploadmaxsize']); $this->tmpl['uploadmaxreswidth'] = $this->params->get( 'upload_maxres_width', 3072 ); $this->tmpl['uploadmaxresheight'] = $this->params->get( 'upload_maxres_height', 2304 ); $this->tmpl['multipleuploadchunk'] = $this->params->get( 'multiple_upload_chunk', 0 ); $this->tmpl['displaytitleupload'] = $this->params->get( 'display_title_upload', 0 ); $this->tmpl['displaydescupload'] = $this->params->get( 'display_description_upload', 0 ); $this->tmpl['enablejava'] = $this->params->get( 'enable_java', -1); $this->tmpl['enablemultiple'] = $this->params->get( 'enable_multiple', 0 ); $this->tmpl['ytbupload'] = $this->params->get( 'youtube_upload', 0 ); $this->tmpl['multipleuploadmethod'] = $this->params->get( 'multiple_upload_method', 1 ); $this->tmpl['multipleresizewidth'] = $this->params->get( 'multiple_resize_width', -1 ); $this->tmpl['multipleresizeheight'] = $this->params->get( 'multiple_resize_height', -1 ); $this->tmpl['usersubcatcount'] = $this->params->get( 'user_subcat_count', 5 ); $this->tmpl['userimagesmaxspace'] = $this->params->get( 'user_images_max_size', 20971520 ); $this->tmpl['iepx'] = '<div style="font-size:1px;height:1px;margin:0px;padding:0px;">&nbsp;</div>'; //Subcateogry $this->tmpl['parentid'] = $app->input->get('parentcategoryid', 0, 'int'); $document->addScript(JURI::base(true).'/media/com_phocagallery/js/comments.js'); $document->addCustomTag(PhocaGalleryRenderFront::renderOnUploadJS()); $document->addCustomTag(PhocaGalleryRenderFront::renderDescriptionCreateCatJS((int)$this->tmpl['maxcreatecatchar'])); $document->addCustomTag(PhocaGalleryRenderFront::userTabOrdering());// SubCategory + Image $document->addCustomTag(PhocaGalleryRenderFront::renderDescriptionCreateSubCatJS((int)$this->tmpl['maxcreatecatchar'])); $document->addCustomTag(PhocaGalleryRenderFront::saveOrderUserJS()); $model = $this->getModel('user'); $ownerMainCategory = $model->getOwnerMainCategory($user->id); $this->tmpl['usertab'] = 1; $this->tmpl['createcategory'] = 1; $this->tmpl['createsubcategory'] = 1; $this->tmpl['images'] = 1; $this->tmpl['displayupload'] = 1; // Tabs $displayTabs = 0; if ((int)$this->tmpl['usertab'] == 0) { $currentTab['user'] = -1; } else { $currentTab['user'] = $displayTabs; $displayTabs++; } if ((int)$this->tmpl['createcategory'] == 0) { $currentTab['createcategory'] = -1; } else { $currentTab['createcategory'] = $displayTabs; $displayTabs++; } if ((int)$this->tmpl['createsubcategory'] == 0) { $currentTab['createsubcategory'] = -1; } else { $currentTab['createsubcategory'] = $displayTabs; $displayTabs++; } if ((int)$this->tmpl['displayupload'] == 0) { $currentTab['images'] = -1; }else { $currentTab['images'] = $displayTabs; $displayTabs++; } $this->tmpl['displaytabs'] = $displayTabs; $this->tmpl['currenttab'] = $currentTab; // ACTION $this->tmpl['action'] = $uri->toString(); $this->tmpl['ftp'] = !JClientHelper::hasCredentials('ftp'); $sess = JFactory::getSession(); $this->assignRef('session', $sess); // SEF problem $isThereQM = false; $isThereQM = preg_match("/\?/i", $this->tmpl['action']); if ($isThereQM) { $amp = '&';// will be translated to htmlspecialchars } else { $amp = '?'; } $this->tmpl['actionamp'] = $this->tmpl['action'] . $amp; $this->tmpl['istheretab'] = false; $this->tmpl['istheretab'] = preg_match("/tab=/i", $this->tmpl['action']); // EDIT - subcategory, image $this->tmpl['task'] = $app->input->get( 'task', '', 'string'); $id = $app->input->get( 'id', '', 'string'); $idAlias = $id; // - - - - - - - - - - - // USER (AVATAR) // - - - - - - - - - - - $this->tmpl['user'] = $user->name; $this->tmpl['username'] = $user->username; $this->tmpl['useravatarimg'] = JHtml::_('image', $this->tmpl['pi'].'phoca_thumb_m_no_image.png', ''); $this->tmpl['useravatarapproved'] = 0; $userAvatar = $model->getUserAvatar($user->id); if ($userAvatar) { $pathAvatarAbs = $path->avatar_abs .'thumbs'.DS.'phoca_thumb_m_'. $userAvatar->avatar; $pathAvatarRel = $path->avatar_rel . 'thumbs/phoca_thumb_m_'. $userAvatar->avatar; if (JFile::exists($pathAvatarAbs)){ $this->tmpl['useravatarimg'] = '<img src="'.JURI::base(true) . '/' . $pathAvatarRel.'?imagesid='.md5(uniqid(time())).'" alt="" />'; $this->tmpl['useravatarapproved'] = $userAvatar->approved; } } if ($ownerMainCategory) { $this->tmpl['usermaincategory'] = $ownerMainCategory->title; } else { $this->tmpl['usermaincategory'] = JHtml::_('image',$this->tmpl['pi'].'icon-unpublish.png', JText::_('COM_PHOCAGALLERY_NOT_CREATED')) .' ('.JText::_('COM_PHOCAGALLERY_NOT_CREATED').')'; } $this->tmpl['usersubcategory'] = $model->getCountUserSubCat($user->id); $this->tmpl['usersubcategoryleft'] = (int)$this->tmpl['usersubcatcount'] - (int)$this->tmpl['usersubcategory']; if ((int)$this->tmpl['usersubcategoryleft'] < 0) {$this->tmpl['usersubcategoryleft'] = 0;} $this->tmpl['userimages'] = $model->getCountUserImage($user->id); $this->tmpl['userimagesspace'] = $model->getSumUserImage($user->id); $this->tmpl['userimagesspaceleft'] = (int)$this->tmpl['userimagesmaxspace'] - (int)$this->tmpl['userimagesspace']; if ((int)$this->tmpl['userimagesspaceleft'] < 0) {$this->tmpl['userimagesspaceleft'] = 0;} $this->tmpl['userimagesspace'] = PhocaGalleryFile::getFileSizeReadable($this->tmpl['userimagesspace']); $this->tmpl['userimagesspaceleft'] = PhocaGalleryFile::getFileSizeReadable($this->tmpl['userimagesspaceleft']); $this->tmpl['userimagesmaxspace'] = PhocaGalleryFile::getFileSizeReadable($this->tmpl['userimagesmaxspace']); // - - - - - - - - - - - // MAIN CATEGORY // - - - - - - - - - - - $ownerMainCategory = $model->getOwnerMainCategory($user->id); if (!empty($ownerMainCategory->id)) { if ((int)$ownerMainCategory->published == 1) { $this->tmpl['categorycreateoredithead'] = JText::_('COM_PHOCAGALLERY_MAIN_CATEGORY'); $this->tmpl['categorycreateoredit'] = JText::_('COM_PHOCAGALLERY_EDIT'); $this->tmpl['categorytitle'] = $ownerMainCategory->title; $this->tmpl['categoryapproved'] = $ownerMainCategory->approved; $this->tmpl['categorydescription'] = $ownerMainCategory->description; $this->tmpl['categorypublished'] = 1; } else { $this->tmpl['categorypublished'] = 0; } } else { $this->tmpl['categorycreateoredithead'] = JText::_('COM_PHOCAGALLERY_MAIN_CATEGORY'); $this->tmpl['categorycreateoredit'] = JText::_('COM_PHOCAGALLERY_CREATE'); $this->tmpl['categorytitle'] = ''; $this->tmpl['categorydescription'] = ''; $this->tmpl['categoryapproved'] = ''; $this->tmpl['categorypublished'] = -1; } // - - - - - - - - - - - // SUBCATEGORY // - - - - - - - - - - - if (!empty($ownerMainCategory->id)) { // EDIT $this->tmpl['categorysubcatedit'] = $model->getCategory((int)$id, $user->id); $this->tmpl['displaysubcategory'] = 1; // Get All Data - Subcategories $this->tmpl['subcategoryitems'] = $model->getDataSubcat($user->id); $this->tmpl['subcategorytotal'] = count($this->tmpl['subcategoryitems']); $model->setTotalSubCat($this->tmpl['subcategorytotal']); $this->tmpl['subcategorypagination'] = $model->getPaginationSubCat($user->id); $this->tmpl['subcategoryitems'] = array_slice($this->tmpl['subcategoryitems'],(int)$this->tmpl['subcategorypagination']->limitstart, (int)$this->tmpl['subcategorypagination']->limit); $filter_state_subcat = $app->getUserStateFromRequest( $this->_context_subcat.'.filter_state', 'filter_state_subcat', '', 'word' ); $filter_catid_subcat = $app->getUserStateFromRequest( $this->_context_subcat.'.filter_catid', 'filter_catid_subcat', 0, 'int' ); $filter_order_subcat = $app->getUserStateFromRequest( $this->_context_subcat.'.filter_order', 'filter_order_subcat', 'a.ordering', 'cmd' ); $filter_order_Dir_subcat= $app->getUserStateFromRequest( $this->_context_subcat.'.filter_order_Dir', 'filter_order_Dir_subcat', '', 'word' ); $search_subcat = $app->getUserStateFromRequest( $this->_context_subcat.'.search', 'phocagallerysubcatsearch', '', 'string' ); if (strpos($search_subcat, '"') !== false) { $search_subcat = str_replace(array('=', '<'), '', $search_subcat); } $search_subcat = JString::strtolower( $search_subcat ); $categories = $model->getCategoryList($user->id); if (!empty($categories)) { $javascript = 'class="inputbox" onchange="document.phocagallerysubcatform.submit();"'; $tree = array(); $text = ''; $tree = PhocaGalleryCategory::CategoryTreeOption($categories, $tree,0, $text, -1); array_unshift($tree, JHtml::_('select.option', '0', '- '.JText::_('COM_PHOCAGALLERY_SELECT_CATEGORY').' -', 'value', 'text')); $lists_subcat['catid'] = JHtml::_( 'select.genericlist', $tree, 'filter_catid_subcat', $javascript , 'value', 'text', $filter_catid_subcat ); } $this->tmpl['parentcategoryid'] = $filter_catid_subcat; // state filter //$lists['state'] = JHtml::_('grid.state', $filter_state ); $state_subcat[] = JHtml::_('select.option', '', '- '. JText::_( 'COM_PHOCAGALLERY_SELECT_STATE' ) .' -' ); $state_subcat[] = JHtml::_('select.option', 'P', JText::_( 'COM_PHOCAGALLERY_PUBLISHED' ) ); $state_subcat[] = JHtml::_('select.option', 'U', JText::_( 'COM_PHOCAGALLERY_UNPUBLISHED') ); $lists_subcat['state'] = JHtml::_('select.genericlist', $state_subcat, 'filter_state_subcat', 'class="inputbox" size="1" onchange="document.phocagallerysubcatform.submit();"', 'value', 'text', $filter_state_subcat ); // table ordering $lists_subcat['order_Dir'] = $filter_order_Dir_subcat; $lists_subcat['order'] = $filter_order_subcat; $this->tmpl['subcategoryordering'] = ($lists_subcat['order'] == 'a.ordering');//Ordering allowed ? // search filter $lists_subcat['search'] = $search_subcat; } else { $this->tmpl['displaysubcategory'] = 0; } // - - - - - - - - - - - // IMAGES // - - - - - - - - - - - if (!empty($ownerMainCategory->id)) { $catAccess = PhocaGalleryAccess::getCategoryAccess((int)$ownerMainCategory->id); // EDIT $this->tmpl['imageedit'] = $model->getImage((int)$id, $user->id); $this->tmpl['imageitems'] = $model->getDataImage($user->id); $this->tmpl['imagetotal'] = $model->getTotalImage($user->id); $this->tmpl['imagepagination'] = $model->getPaginationImage($user->id); $filter_state_image = $app->getUserStateFromRequest( $this->_context_image.'.filter_state', 'filter_state_image', '', 'word' ); $filter_catid_image = $app->getUserStateFromRequest( $this->_context_image.'.filter_catid', 'filter_catid_image', 0, 'int' ); $filter_order_image = $app->getUserStateFromRequest( $this->_context_image.'.filter_order', 'filter_order_image', 'a.ordering', 'cmd' ); $filter_order_Dir_image= $app->getUserStateFromRequest( $this->_context_image.'.filter_order_Dir', 'filter_order_Dir_image', '', 'word' ); $search_image = $app->getUserStateFromRequest( $this->_context_image.'.search', 'phocagalleryimagesearch', '', 'string' ); if (strpos($search_image, '"') !== false) { $search_image = str_replace(array('=', '<'), '', $search_image); } $search_image = JString::strtolower( $search_image ); $categoriesImage = $model->getCategoryList($user->id); if (!empty($categoriesImage)) { $javascript = 'class="inputbox" size="1" onchange="document.phocagalleryimageform.submit();"'; $tree = array(); $text = ''; $tree = PhocaGalleryCategory::CategoryTreeOption($categoriesImage, $tree,0, $text, -1); array_unshift($tree, JHtml::_('select.option', '0', '- '.JText::_('COM_PHOCAGALLERY_SELECT_CATEGORY').' -', 'value', 'text')); $lists_image['catid'] = JHtml::_( 'select.genericlist', $tree, 'filter_catid_image', $javascript , 'value', 'text', $filter_catid_image ); } // state filter $state_image[] = JHtml::_('select.option', '', '- '. JText::_( 'COM_PHOCAGALLERY_SELECT_STATE' ) .' -' ); $state_image[] = JHtml::_('select.option', 'P', JText::_( 'COM_PHOCAGALLERY_FIELD_PUBLISHED_LABEL' ) ); $state_image[] = JHtml::_('select.option', 'U', JText::_( 'COM_PHOCAGALLERY_FIELD_UNPUBLISHED_LABEL') ); $lists_image['state'] = JHtml::_('select.genericlist', $state_image, 'filter_state_image', 'class="inputbox" size="1" onchange="document.phocagalleryimageform.submit();"', 'value', 'text', $filter_state_image ); // table ordering $lists_image['order_Dir'] = $filter_order_Dir_image; $lists_image['order'] = $filter_order_image; $this->tmpl['imageordering'] = ($lists_image['order'] == 'a.ordering');//Ordering allowed ? // search filter $lists_image['search'] = $search_image; $this->tmpl['catidimage'] = $filter_catid_image; // Upload $this->tmpl['displayupload'] = 0; // USER RIGHT - UPLOAD - - - - - - - - - - - // 2, 2 means that user access will be ignored in function getUserRight for display Delete button $rightDisplayUpload = 0;// default is to null (all users cannot upload) if (!empty($catAccess)) { $rightDisplayUpload = PhocaGalleryAccess::getUserRight('uploaduserid', $catAccess->uploaduserid, 2, $user->getAuthorisedViewLevels(), $user->get('id', 0), 0); } if ($rightDisplayUpload == 1) { $this->tmpl['displayupload'] = 1; $document->addCustomTag(PhocaGalleryRenderFront::renderDescriptionUploadJS((int)$this->tmpl['maxuploadchar'])); } // - - - - - - - - - - - - - - - - - - - - - // USER RIGHT - ACCESS - - - - - - - - - - - $rightDisplay = 1;//default is set to 1 (all users can see the category) if (!empty($catAccess)) { $rightDisplay = PhocaGalleryAccess::getUserRight ('accessuserid', $catAccess->accessuserid, 0, $user->getAuthorisedViewLevels(), $user->get('id', 0), 1); } if ($rightDisplay == 0) { $app->redirect(JRoute::_($this->tmpl['pl'], false), JText::_('COM_PHOCAGALLERY_NOT_AUTHORISED_ACTION')); exit; } // - - - - - - - - - - - - - - - - - - - - - // = = = = = = = = = = // U P L O A D // = = = = = = = = = = // - - - - - - - - - - - // Upload // - - - - - - - - - - - if ((int)$this->tmpl['displayupload'] == 1) { $sU = new PhocaGalleryFileUploadSingle(); $sU->returnUrl = htmlspecialchars($this->tmpl['action'] . $amp .'task=upload&'. $this->session->getName().'='.$this->session->getId() .'&'. JSession::getFormToken().'=1&viewback=category&tab='.$this->tmpl['currenttab']['images']); $sU->tab = $this->tmpl['currenttab']['images']; $this->tmpl['su_output'] = $sU->getSingleUploadHTML(1); $this->tmpl['su_url'] = htmlspecialchars($this->tmpl['action'] . $amp .'task=upload&'. $this->session->getName().'='.$this->session->getId() .'&'. JSession::getFormToken().'=1&viewback=category&tab='.$this->tmpl['currenttab']['images']); } // - - - - - - - - - - - // Youtube Upload (single upload form can be used) // - - - - - - - - - - - if ((int)$this->tmpl['ytbupload'] > 0) { $sYU = new PhocaGalleryFileUploadSingle(); $sYU->returnUrl = htmlspecialchars($this->tmpl['action'] . $amp .'task=ytbupload&'. $this->session->getName().'='.$this->session->getId() .'&'. JSession::getFormToken().'=1&viewback=category&tab='.$this->tmpl['currenttab']['images']); $sYU->tab = $this->tmpl['currenttab']['images']; $this->tmpl['syu_output'] = $sYU->getSingleUploadHTML(1); $this->tmpl['syu_url'] = htmlspecialchars($this->tmpl['action'] . $amp .'task=ytbupload&'. $this->session->getName().'='.$this->session->getId() .'&'. JSession::getFormToken().'=1&viewback=category&tab='.$this->tmpl['currenttab']['images']); } // - - - - - - - - - - - // Multiple Upload // - - - - - - - - - - - // Get infos from multiple upload $muFailed = $app->input->get( 'mufailed', '0', 'int' ); $muUploaded = $app->input->get( 'muuploaded', '0', 'int' ); $this->tmpl['mu_response_msg'] = $muUploadedMsg = ''; if ($muUploaded > 0) { $muUploadedMsg = JText::_('COM_PHOCAGALLERY_COUNT_UPLOADED_IMG'). ': ' . $muUploaded; } if ($muFailed > 0) { $muFailedMsg = JText::_('COM_PHOCAGALLERY_COUNT_NOT_UPLOADED_IMG'). ': ' . $muFailed; } if ($muFailed > 0 && $muUploaded > 0) { $this->tmpl['mu_response_msg'] = '<div class="alert alert-info">' .JText::_('COM_PHOCAGALLERY_COUNT_UPLOADED_IMG'). ': ' . $muUploaded .'<br />' .JText::_('COM_PHOCAGALLERY_COUNT_NOT_UPLOADED_IMG'). ': ' . $muFailed.'</div>'; } else if ($muFailed > 0 && $muUploaded == 0) { $this->tmpl['mu_response_msg'] = '<div class="alert alert-error">' .JText::_('COM_PHOCAGALLERY_COUNT_NOT_UPLOADED_IMG'). ': ' . $muFailed.'</div>'; } else if ($muFailed == 0 && $muUploaded > 0){ $this->tmpl['mu_response_msg'] = '<div class="alert alert-success">' .JText::_('COM_PHOCAGALLERY_COUNT_UPLOADED_IMG'). ': ' . $muUploaded.'</div>'; } else { $this->tmpl['mu_response_msg'] = ''; } if((int)$this->tmpl['enablemultiple'] == 1 && (int)$this->tmpl['displayupload'] == 1) { PhocaGalleryFileUploadMultiple::renderMultipleUploadLibraries(); $mU = new PhocaGalleryFileUploadMultiple(); $mU->frontEnd = 2; $mU->method = $this->tmpl['multipleuploadmethod']; $mU->url = htmlspecialchars($this->tmpl['action'] . $amp .'controller=user&task=multipleupload&' . $this->session->getName().'='.$this->session->getId().'&' . JSession::getFormToken().'=1&tab='.$this->tmpl['currenttab']['images'] . '&catid='.$this->tmpl['catidimage']); $mU->reload = htmlspecialchars($this->tmpl['action'] . $amp . $this->session->getName().'='.$this->session->getId().'&' . JSession::getFormToken().'=1&tab='.$this->tmpl['currenttab']['images']); $mU->maxFileSize = PhocaGalleryFileUploadMultiple::getMultipleUploadSizeFormat($this->tmpl['uploadmaxsize']); $mU->chunkSize = '1mb'; $mU->imageHeight = $this->tmpl['multipleresizeheight']; $mU->imageWidth = $this->tmpl['multipleresizewidth']; $mU->imageQuality = 100; $mU->renderMultipleUploadJS(0, $this->tmpl['multipleuploadchunk']); $this->tmpl['mu_output']= $mU->getMultipleUploadHTML(); } // - - - - - - - - - - - // Java Upload // - - - - - - - - - - - if((int)$this->tmpl['enablejava'] == 1 && (int)$this->tmpl['displayupload'] == 1) { $jU = new PhocaGalleryFileUploadJava(); $jU->width = $this->tmpl['javaboxwidth']; $jU->height = $this->tmpl['javaboxheight']; $jU->resizewidth = $this->tmpl['multipleresizewidth']; $jU->resizeheight = $this->tmpl['multipleresizeheight']; $jU->uploadmaxsize = $this->tmpl['uploadmaxsize']; $jU->returnUrl = htmlspecialchars($this->tmpl['action'] . $amp . $this->session->getName().'='.$this->session->getId().'&' . JSession::getFormToken().'=1&tab='.$this->tmpl['currenttab']['images']); $jU->url = htmlspecialchars($this->tmpl['action'] . $amp .'controller=user&task=javaupload&' . $this->session->getName().'='.$this->session->getId().'&' . JSession::getFormToken().'=1&tab='.$this->tmpl['currenttab']['images'] . '&catid='.$this->tmpl['catidimage']); $jU->source = JURI::root(true).'/components/com_phocagallery/assets/jupload/wjhk.jupload.jar'; $this->tmpl['ju_output'] = $jU->getJavaUploadHTML(); } } else { $this->tmpl['displayupload'] = 0; } if (!empty($ownerMainCategory->id)) { $this->tmpl['ps'] = '&tab='. $this->tmpl['currenttab']['createsubcategory'] . '&limitstartsubcat='.$this->tmpl['subcategorypagination']->limitstart . '&limitstartimage='.$this->tmpl['imagepagination']->limitstart; } else { $this->tmpl['ps'] = '&tab='. $this->tmpl['currenttab']['createsubcategory']; } if (!empty($ownerMainCategory->id)) { $this->tmpl['psi'] = '&tab='. $this->tmpl['currenttab']['images'] . '&limitstartsubcat='.$this->tmpl['subcategorypagination']->limitstart . '&limitstartimage='.$this->tmpl['imagepagination']->limitstart; } else { $this->tmpl['psi'] = '&tab='. $this->tmpl['currenttab']['images']; } // ASIGN $this->assignRef( 'listssubcat', $lists_subcat); $this->assignRef( 'listsimage', $lists_image); //$this->assignRef( 'tmpl', $this->tmpl); //$this->assignRef( 'params', $this->params); $sess = JFactory::getSession(); $this->assignRef( 'session', $sess); $this->_prepareDocument(); parent::display($tpl); } protected function _prepareDocument() { $app = JFactory::getApplication(); $menus = $app->getMenu(); $pathway = $app->getPathway(); $this->params = $app->getParams(); $title = null; $this->tmpl['gallerymetakey'] = $this->params->get( 'gallery_metakey', '' ); $this->tmpl['gallerymetadesc'] = $this->params->get( 'gallery_metadesc', '' ); $menu = $menus->getActive(); if ($menu) { $this->params->def('page_heading', $this->params->get('page_title', $menu->title)); } else { $this->params->def('page_heading', JText::_('JGLOBAL_ARTICLES')); } $title = $this->params->get('page_title', ''); if (empty($title)) { $title = htmlspecialchars_decode($app->getCfg('sitename')); } else if ($app->getCfg('sitename_pagetitles', 0)) { $title = JText::sprintf('JPAGETITLE', htmlspecialchars_decode($app->getCfg('sitename')), $title); } $this->document->setTitle($title); if ($this->tmpl['gallerymetadesc'] != '') { $this->document->setDescription($this->tmpl['gallerymetadesc']); } else if ($this->params->get('menu-meta_description', '')) { $this->document->setDescription($this->params->get('menu-meta_description', '')); } if ($this->tmpl['gallerymetakey'] != '') { $this->document->setMetadata('keywords', $this->tmpl['gallerymetakey']); } else if ($this->params->get('menu-meta_keywords', '')) { $this->document->setMetadata('keywords', $this->params->get('menu-meta_keywords', '')); } if ($app->getCfg('MetaTitle') == '1' && $this->params->get('menupage_title', '')) { $this->document->setMetaData('title', $this->params->get('page_title', '')); } /*if ($app->getCfg('MetaAuthor') == '1') { $this->document->setMetaData('author', $this->item->author); } /*$mdata = $this->item->metadata->toArray(); foreach ($mdata as $k => $v) { if ($v) { $this->document->setMetadata($k, $v); } }*/ // Breadcrumbs TODO (Add the whole tree) /*if (isset($this->category[0]->parentid)) { if ($this->category[0]->parentid == 1) { } else if ($this->category[0]->parentid > 0) { $pathway->addItem($this->category[0]->parenttitle, JRoute::_(PhocaDocumentationHelperRoute::getCategoryRoute($this->category[0]->parentid, $this->category[0]->parentalias))); } } if (!empty($this->category[0]->title)) { $pathway->addItem($this->category[0]->title); }*/ } } ?>
gpl-2.0
emundus/v5
administrator/components/com_fabrik/controllers/connections.php
2620
<?php /** * Connections controller class * * @package Joomla.Administrator * @subpackage Fabrik * @copyright Copyright (C) 2005 Fabrik. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * @since 1.6 */ // No direct access. defined('_JEXEC') or die; require_once 'fabcontrolleradmin.php'; /** * Connections list controller class. * * @package Joomla.Administrator * @subpackage Fabrik * @since 1.6 */ class FabrikControllerConnections extends FabControllerAdmin { /** * The prefix to use with controller messages. * * @var string */ protected $text_prefix = 'COM_FABRIK_CONNECTIONS'; /** * View item name * * @var string */ protected $view_item = 'connections'; /** * Constructor. * * @param array $config An optional associative array of configuration settings. * * @see JController * * @since 1.6 */ public function __construct($config = array()) { parent::__construct($config); $this->registerTask('unsetDefault', 'setDefault'); } /** * Proxy for getModel. * * @param string $name model name * @param string $prefix model prefix * * @since 1.6 * * @return J model */ public function &getModel($name = 'Connection', $prefix = 'FabrikModel') { $model = parent::getModel($name, $prefix, array('ignore_request' => true)); return $model; } /** * Method to set the home property for a list of items * * @since 1.6 * * @return null */ public function setDefault() { // Check for request forgeries JSession::checkToken() or die(JText::_('JINVALID_TOKEN')); $app = JFactory::getApplication(); $input = $app->input; // Get items to publish from the request. $cid = $input->get('cid', array(), 'array'); $data = array('setDefault' => 1, 'unsetDefault' => 0); $task = $this->getTask(); $value = JArrayHelper::getValue($data, $task, 0, 'int'); if ($value == 0) { $this->setMessage(JText::_('COM_FABRIK_CONNECTION_CANT_UNSET_DEFAULT')); } if (empty($cid)) { JError::raiseWarning(500, JText::_($this->text_prefix . '_NO_ITEM_SELECTED')); } else { if ($value != 0) { $cid = $cid[0]; // Get the model. $model = $this->getModel(); // Publish the items. if (!$model->setDefault($cid, $value)) { JError::raiseWarning(500, $model->getError()); } else { $this->setMessage(JText::_('COM_FABRIK_CONNECTION_SET_DEFAULT')); } } } $this->setRedirect(JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list, false)); } }
gpl-2.0
mpranivong/golf-phpnuke
modules/Submit_News/language/lang-thai.php
3373
<?php /**************************************************************************/ /* PHP-NUKE: Advanced Content Management System */ /* ============================================ */ /* */ /* This is the language module with all the system messages */ /* */ /* If you made a translation, please sent to me (fbc@mandrakesoft.com) */ /* the translated file. Please keep the original text order by modules, */ /* and just one message per line, also double check your translation! */ /* */ /* You need to change the second quoted phrase, not the capital one! */ /* */ /* If you need to use double quotes (") remember to add a backslash (\), */ /* so your entry will look like: This is \"double quoted\" text. */ /* And, if you use HTML code, please double check it. */ /**************************************************************************/ define("_PRINTER","˹éÒàÍ¡ÊÒÃÊÓËÃѺà¤Ã×èͧ¾ÔÁ¾ì"); define("_FRIEND","Êè§àÃ×èͧ¹ÕéµèÍãËéà¾×è͹ÍèÒ¹"); define("_YOURNAME","ª×èͤس"); define("_OK","µ¡Å§!"); define("_ALLOWEDHTML"," HTML ·ÕèÊÒÁÒöãªéä´é:"); define("_EXTRANS","Extrans (à»ÅÕè¹ html tags à»ç¹ÍÑ¡ÉøÃÃÁ´Ò)"); define("_HTMLFORMATED","ºÑ¹·Ö¡à»ç¹ HTML"); define("_PLAINTEXT","¢éÍÁÙÅ»¡µÔ"); define("_ARTICLES","º·¤ÇÒÁ"); define("_SUBMITNEWS","à¼Âá¾ÃèàÃ×èͧËÃ×ͺ·¤ÇÒÁ"); define("_SUBMITADVICE","â»Ã´à¢Õ¹àÃ×èͧËÃ×ͺ·¤ÇÒÁ·Õèµéͧ¡ÒÃŧã¹áºº¿ÍÃìÁ¢éÒ§ÅèÒ§ áÅéǤÅÔ¡Êè§ <br> ¡ÃسҵÃǨÊͺäÇÂÒ¡Ã³ì µÑÇÊС´ ãËé¶Ù¡µéͧ<br> ·Ò§·ÕÁ§Ò¹¢ÍʧǹÊÔ·¸Ô¾Ô¨ÒóÒá¡éä¢ ËÃ×ÍÃЧѺ¡ÒÃà¼Âá¾ÃèµÒÁ¤ÇÒÁàËÁÒÐÊÁ"); define("_SUBTITLE","àÃ×èͧ"); define("_BEDESCRIPTIVE","â»Ã´ÃкØÊÑ鹿 ªÑ´à¨¹ áÅÐ ¡ÃЪѺ"); define("_BADTITLES","¢éͤÇÒÁ·Õè¤ÇÃÅÐàÇé¹äÁèµéͧ¾ÔÁ¾ìàªè¹ ='â»Ã´ÍèÒ¹.....' ËÃ×Í 'àÃ×èͧ.....'"); define("_HTMLISFINE","·èÒ¹ÊÒÁÒöá·Ã¡ HTML ËÃ×Í URLs link ä´é ¡ÃسҵÃǨÊͺ¤ÓÊÑè§ãËé¶Ù¡µéͧ¡è͹Êè§"); define("_AREYOUSURE","¡ÃسҵÃǨÊͺ link URL .ãËé¶Ù¡µéͧ"); define("_SUBPREVIEW","¡ÃسҵÃǨ´Ù¼Åº¹¨Í¡è͹¡è͹Êè§"); define("_SELECTTOPIC","â»Ã´àÅ×Í¡ËÑÇ¢éÍ"); define("_NEWSUBPREVIEW","áÊ´§¢éÍÁÙÅ¡è͹Êè§"); define("_STORYLOOK","àÃ×èͧ¢Í§¤Ø³¨ÐáÊ´§º¹¨ÍÀÒ¾´Ñ§¹Õé:"); define("_CHECKSTORY","â»Ã´µÃǨÊͺ¢éͤÇÒÁ link URL áÅÐ HTML ¡è͹Êè§àÃ×èͧ¢Í§·èÒ¹ !"); define("_THANKSSUB","¢Íº¤Ø³ÊÓËÃѺ¡ÒÃÊè§àÃ×èͧ!"); define("_SUBSENT","àÃ×èͧ¢Í§¤Ø³ä´éÃѺàÃÕºÃéÍÂáÅéÇ..."); define("_SUBTEXT","·Ò§àÃҨзӡÒõÃǨÊͺàÃ×èͧ áÅÐ Êè§ä»¢Öé¹à¼Âá¾Ãèã¹ËÑÇ¢éÍ·Õèà¡ÕèÂÇ¢éͧ."); define("_WEHAVESUB","¢³Ð¹ÕéàÃÒÁÕàÃ×èͧ·ÕèÊè§à¢éÒÁҨӹǹ"); define("_WAITING","àÃ×èͧ ÃÍ¡ÒÃà¼Âá¾Ãè"); define("_PREVIEW","·´ÅͧáÊ´§¼Åº¹¨ÍÀÒ¾"); define("_NEWUSER","ÊÁÒªÔ¡ãËÁè"); define("_USCORE","¤Ðá¹¹"); define("_DATE","Çѹ·Õè"); define("_STORYTEXT","à¹×éÍËÒ"); define("_EXTENDEDTEXT","à¾ÔèÁàµÔÁ"); define("_LANGUAGE","ÀÒÉÒ"); define("_SELECTMONTH2VIEW","¡ÃسÒàÅ×Í¡à´×͹·Õè¨Ð´Ù:"); define("_SHOWALLSTORIES","´ÙàÃ×èͧ·Ñé§ËÁ´"); define("_STORIESARCHIVE","àÃ×èͧ·Ñé§ËÁ´"); define("_ACTIONS","¡Ô¨¡ÃÃÁ"); define("_ARCHIVESINDEX","ÊÒúѭàÃ×èͧ·Ñé§ËÁ´"); define("_ALLSTORIESARCH","àÃ×èͧ·Ñé§ËÁ´"); define("_NEXTPAGE","˹éÒµèÍä»"); define("_PREVIOUSPAGE","˹éÒ¡è͹¹Õé"); ?>
gpl-2.0
stevebutton/www.maps.ponabana.dev
wp-content/plugins/content-views-query-and-display-post-page/admin/content-views-admin.php
11387
<?php /** * Content Views Admin * * @package PT_Content_Views_Admin * @author PT Guy <palaceofthemes@gmail.com> * @license GPL-2.0+ * @link http://www.contentviewspro.com/ * @copyright 2014 PT Guy */ class PT_Content_Views_Admin { /** * Instance of this class. * * @since 1.0.0 * * @var object */ protected static $instance = null; /** * Slug of the plugin screen. * * @since 1.0.0 * * @var string */ protected $plugin_screen_hook_suffix = null; // Slugs for sub menu pages protected $plugin_sub_screen_hook_suffix = null; /** * Initialize the plugin by loading admin scripts & styles and adding a * settings page and menu. * * @since 1.0.0 */ private function __construct() { /* * @TODO : * * - Uncomment following lines if the admin class should only be available for super admins */ /* if( ! is_super_admin() ) { return; } */ /* * Call $plugin_slug from public plugin class. */ $plugin = PT_Content_Views::get_instance(); $this->plugin_slug = $plugin->get_plugin_slug(); // Fix redirect error add_action( 'init', array( $this, 'do_output_buffer' ) ); // Redirect to "Add View" page when click "Add new" link in "All Views" page add_action( 'admin_init', array( $this, 'redirect_add_new' ) ); // Load admin style sheet and JavaScript. add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) ); add_action( 'admin_print_footer_scripts', array( $this, 'print_footer_scripts' ) ); // Add the options page and menu item. add_action( 'admin_menu', array( $this, 'add_plugin_admin_menu' ) ); // Ajax action $action = 'preview_request'; add_action( 'wp_ajax_' . $action, array( 'PT_CV_Functions', 'ajax_callback_' . $action ) ); // Output assets content at footer of page add_action( PT_CV_PREFIX_ . 'preview_footer', array( 'PT_CV_Html', 'assets_of_view_types' ) ); // Add an action link pointing to the options page. $plugin_basename = plugin_basename( plugin_dir_path( dirname(__FILE__) ) . $this->plugin_slug . '.php' ); add_filter( 'plugin_action_links_' . $plugin_basename, array( $this, 'filter_add_action_links' ) ); // Filter link of actions in All Views page add_filter( 'post_row_actions', array( $this, 'filter_view_row_actions' ), 10, 2 ); // Filter link of Title in All Views page add_filter( 'get_edit_post_link', array( $this, 'filter_get_edit_post_link' ), 10, 3 ); // Filter Title of Edit View page add_filter( 'admin_title', array( $this, 'filter_admin_title' ), 10, 2 ); // Custom hooks for both preview & frontend PT_CV_Hooks::init(); // Custom settings page PT_CV_Plugin::init(); } /** * Return an instance of this class. * * @since 1.0.0 * * @return object A single instance of this class. */ public static function get_instance() { /* * @TODO : * * - Uncomment following lines if the admin class should only be available for super admins */ /* if( ! is_super_admin() ) { return; } */ // If the single instance hasn't been set, set it now. if ( null == self::$instance ) { self::$instance = new self; } return self::$instance; } /** * Output buffering */ public function do_output_buffer() { ob_start(); } /** * Redirect to "Add View" page when click "Add new" link in "All Views" page */ public function redirect_add_new() { global $pagenow; if ( $pagenow === 'post-new.php' ) { $post_type = isset( $_GET['post_type'] ) ? $_GET['post_type'] : ''; if ( $post_type === PT_CV_POST_TYPE ) { wp_redirect( admin_url( 'admin.php?page=' . $this->plugin_slug . '-add' ), 301 ); exit; } } } /** * Register and enqueue admin-specific style sheet. * * @since 1.0.0 * * @return null Return early if no settings page is registered. */ public function enqueue_admin_styles() { if ( ! isset( $this->plugin_screen_hook_suffix ) ) { return; } // Load every Admin pages PT_CV_Asset::enqueue( 'admin-menu', 'style', array( 'src' => plugins_url( 'assets/css/menu.css', __FILE__ ), ) ); $screen = get_current_screen(); if ( $this->plugin_screen_hook_suffix == $screen->id || in_array( $screen->id, $this->plugin_sub_screen_hook_suffix ) ) { // WP assets wp_enqueue_style( 'thickbox' ); wp_enqueue_style( 'media-upload' ); wp_enqueue_style( 'wp-color-picker' ); // Main admin style PT_CV_Asset::enqueue( 'admin', 'style', array( 'src' => plugins_url( 'assets/css/admin.css', __FILE__ ), ) ); // Fix style of WP global $wp_version; if ( version_compare( $wp_version, '3.8.0' ) >= 0 ) { PT_CV_Asset::enqueue( 'admin-fix', 'style', array( 'src' => plugins_url( 'assets/css/wp38.css', __FILE__ ), 'ver' => $wp_version, ) ); } else { PT_CV_Asset::enqueue( 'admin-fix', 'style', array( 'src' => plugins_url( 'assets/css/wp.css', __FILE__ ), 'ver' => $wp_version, ) ); } // Bootstrap for Admin PT_CV_Asset::enqueue( 'bootstrap-admin', 'style', array( 'src' => plugins_url( 'assets/bootstrap/css/bootstrap.full.min.css', PT_CV_FILE ), ) ); // For Preview PT_CV_Html::frontend_styles(); // Main scripts PT_CV_Asset::enqueue( 'select2', 'style' ); PT_CV_Asset::enqueue( 'select2-bootstrap', 'style' ); } } /** * Register and enqueue admin-specific JavaScript. * * @since 1.0.0 * * @return null Return early if no settings page is registered. */ public function enqueue_admin_scripts() { if ( ! isset( $this->plugin_screen_hook_suffix ) ) { return; } $screen = get_current_screen(); if ( $this->plugin_screen_hook_suffix == $screen->id || in_array( $screen->id, $this->plugin_sub_screen_hook_suffix ) ) { // WP assets wp_enqueue_script( 'wp-color-picker' ); wp_enqueue_script( 'jquery-ui-sortable' ); // Main admin script PT_CV_Asset::enqueue( 'admin', 'script', array( 'src' => plugins_url( 'assets/js/admin.js', __FILE__ ), 'deps' => array( 'jquery' ), ) ); // Localize strings PT_CV_Asset::localize_script( 'admin', PT_CV_PREFIX_UPPER . 'ADMIN', array( 'text' => array( 'no_taxonomy' => __( 'There is no taxonomy for selected content type', PT_CV_DOMAIN ), 'pagination_disable' => __( 'Pagination is disabled when Limit = -1', PT_CV_DOMAIN ), 'prevent_click' => __( 'Opening a link is prevented in preview box', PT_CV_DOMAIN ), ), 'btn' => array( 'preview' => array( 'show' => __( 'Show Preview', PT_CV_DOMAIN ), 'hide' => __( 'Hide Preview', PT_CV_DOMAIN ), 'update' => __( 'Update Preview', PT_CV_DOMAIN ), ), ), 'data' => array( 'post_types_vs_taxonomies' => PT_CV_Values::post_types_vs_taxonomies(), ), ) ); // For Preview PT_CV_Html::frontend_scripts( true ); PT_CV_Asset::enqueue( 'select2' ); } } /** * Print script at footer of WP admin */ public function print_footer_scripts() { if ( ! isset( $this->plugin_screen_hook_suffix ) ) { return; } $screen = get_current_screen(); if ( $this->plugin_screen_hook_suffix == $screen->id || in_array( $screen->id, $this->plugin_sub_screen_hook_suffix ) ) { PT_Options_Framework::print_js(); } } /** * Register the administration menu for this plugin into the WordPress Dashboard menu. * * @since 1.0.0 */ public function add_plugin_admin_menu() { /* * Add a settings page for this plugin to the Settings menu. */ $this->plugin_screen_hook_suffix = add_menu_page( __( 'Content View Settings', $this->plugin_slug ), __( 'Content View Settings', $this->plugin_slug ), 'edit_posts', $this->plugin_slug, array( $this, 'display_plugin_admin_page' ), '', '45.6' ); $this->plugin_sub_screen_hook_suffix[] = PT_CV_Functions::menu_add_sub( $this->plugin_slug, __( 'All Content Views', $this->plugin_slug ), __( 'All Views', $this->plugin_slug ), 'list', __CLASS__ ); $this->plugin_sub_screen_hook_suffix[] = PT_CV_Functions::menu_add_sub( $this->plugin_slug, __( 'Add New View', $this->plugin_slug ), __( 'Add New', $this->plugin_slug ), 'add', __CLASS__ ); } /** * Render the settings page for this plugin. * * @since 1.0.0 */ public function display_plugin_admin_page() { include_once( 'views/admin.php' ); } /** * List all Views page */ public function display_sub_page_list() { include_once( 'views/list.php' ); } /** * Add/Edit View page */ public function display_sub_page_add() { include_once( 'views/view.php' ); } /** * Add settings action link to the plugins page, doesn't work in Multiple site * * @since 1.0.0 */ public function filter_add_action_links( $links ) { return array_merge( array( 'settings' => '<a href="' . admin_url( 'admin.php?page=' . $this->plugin_slug ) . '">' . __( 'Settings', $this->plugin_slug ) . '</a>', 'add' => '<a href="' . admin_url( 'admin.php?page=' . $this->plugin_slug . '-add' ) . '">' . __( 'Add View', $this->plugin_slug ) . '</a>', ), $links ); } /** * Filter link of actions in All Views page * * @param array $actions Array of actions link * @param object $post The post * * @return array */ public function filter_view_row_actions( $actions, $post ) { // Get current post type $post_type = PT_CV_Functions::admin_current_post_type(); if ( $post_type != PT_CV_POST_TYPE ) { return $actions; } // Remove Quick edit link unset( $actions['inline hide-if-no-js'] ); // Remove View link unset( $actions['view'] ); // Update Edit link // Get View id $view_id = get_post_meta( $post->ID, PT_CV_META_ID, true ); if ( ! empty( $view_id ) ) { $edit_link = PT_CV_Functions::view_link( $view_id ); $actions['edit'] = '<a href="' . esc_url( $edit_link ) . '" title="' . esc_attr( __( 'Edit this item' ) ) . '">' . __( 'Edit' ) . '</a>'; } // Filter actions $actions = apply_filters( PT_CV_PREFIX_ . 'view_row_actions', $actions, $view_id ); return $actions; } /** * Filter link of Title in All Views page */ public function filter_get_edit_post_link( $edit_link, $post_id, $context ) { // Get current post type $post_type = PT_CV_Functions::admin_current_post_type(); if ( $post_type != PT_CV_POST_TYPE ) { return $edit_link; } // Get View id $view_id = get_post_meta( $post_id, PT_CV_META_ID, true ); $edit_link = PT_CV_Functions::view_link( $view_id ); return $edit_link; } /** * Filter Title for View page * * @param string $admin_title * @param string $title */ public function filter_admin_title( $admin_title, $title ) { $screen = get_current_screen(); if ( ! $this || ! isset ( $this->plugin_sub_screen_hook_suffix ) ) return $admin_title; // If is View page if ( $this->plugin_screen_hook_suffix == $screen->id || in_array( $screen->id, $this->plugin_sub_screen_hook_suffix ) ) { // If View id is passed in url if ( ! empty ( $_GET['id'] ) ) { $admin_title = str_replace( 'Add New', 'Edit', $admin_title ); } } return $admin_title; } }
gpl-2.0
izapolsk/integration_tests
cfme/tests/test_db_migrate_manual.py
16765
import pytest from cfme import test_requirements @pytest.mark.manual @test_requirements.update @test_requirements.db_migration @pytest.mark.meta(coverage=[1478986, 1561075, 1590846, 1578957]) @pytest.mark.tier(2) def test_upgrade_dedicated_db_migration_local(): """ Test that you can locally migrate a dedicated database after upgrade. Previously it was missing the database.yml during setup with would case the rake task to fail. Polarion: assignee: jhenner casecomponent: Configuration caseimportance: medium initialEstimate: 1/3h startsin: 5.9 testSteps: 1. Upgrade appliances 2. Check failover expectedResults: 1. Confirm upgrade completes successfully 2. Confirm failover continues to work """ pass @pytest.mark.manual @test_requirements.update @test_requirements.db_migration @pytest.mark.tier(2) def test_upgrade_single_inplace_ipv6(): """ Upgrading a single appliance on ipv6 only env Polarion: assignee: jhenner casecomponent: Appliance caseimportance: medium initialEstimate: 1/3h setup: provision appliance add provider add repo file to /etc/yum.repos.d/ run "yum update" run "rake db:migrate" run "rake evm:automate:reset" run "systemctl start evmserverd" check webui is available add additional provider/provision vms startsin: 5.9 """ pass @pytest.mark.manual @test_requirements.restore @test_requirements.db_migration @pytest.mark.tier(2) def test_upgrade_single_negative_v2_key_fix_auth(): """ test migration without fetching v2_key also requires fix_auth Polarion: assignee: jhenner casecomponent: Configuration caseimportance: medium caseposneg: negative initialEstimate: 1/3h setup: restore a backup without using its v2_key run "fix_auth --invalid <password>" this will allow evm to start without credential errors testtype: functional """ pass @pytest.mark.manual @test_requirements.update @test_requirements.db_migration @pytest.mark.tier(2) @pytest.mark.meta(coverage=[1553841]) def test_upgrade_custom_css(): """Test css customization"s function correctly after upgrades. Polarion: assignee: jhenner casecomponent: Appliance caseimportance: medium initialEstimate: 1/6h setup: provision appliance add custom css file add repo file to /etc/yum.repos.d/ run "yum update" run "rake db:migrate" run "rake evm:automate:reset" run "systemctl start evmserverd" check webui is available check customization"s still work startsin: 5.10 """ pass @pytest.mark.manual @test_requirements.update @test_requirements.db_migration @pytest.mark.tier(2) @pytest.mark.meta(coverage=[1375313]) def test_upgrade_custom_widgets(): """ Upgrade appliance with custom widgets added Polarion: assignee: jhenner casecomponent: Appliance caseimportance: medium initialEstimate: 1/3h setup: provision appliance add custom widgets add repo file to /etc/yum.repos.d/ run "yum update" run "rake db:migrate" run "rake evm:automate:reset" run "systemctl start evmserverd" check webui is available check widgets still work correctly startsin: 5.9 """ pass @pytest.mark.manual @test_requirements.update @pytest.mark.tier(2) @pytest.mark.meta(coverage=[1463389]) def test_rh_rhsm_sat6_cred_save_crud(): """ Switch between rhsm and sat6 setup Polarion: assignee: jhenner casecomponent: Configuration caseimportance: medium caseposneg: negative initialEstimate: 1/12h setup: Provision appliance navigate to Configuration-settings-region-redhat updates Click edit subscription Setup rhsm subscription Save (validate and save if fails) edit subscription setup sat6 click save """ pass @pytest.mark.manual @test_requirements.update @test_requirements.db_migration @pytest.mark.tier(2) def test_upgrade_multi_ext_inplace(): """ test_upgrade_multi_ext_inplace Polarion: assignee: jhenner casecomponent: Configuration caseimportance: medium initialEstimate: 1h setup: 2 appliances: - Appliance A: internal DB, region 0 - Appliance B: external DB, pointed at A, region 0 - Setup LDAP on one of the appliances - Login as LDAP user A - Setup a provider - Provision a VM testtype: functional testSteps: 1. Run upgrade according to the migration guide (version-dependent) 2. Start the appliances back up 3. Login as LDAP user B 4. Add another provider 5. Provision another VM using the new provider 6. Visit provider/host/vm summary pages expectedResults: 1. Upgrade is successful, so is migration and related tasks (fix_auth) 2. Appliances are running 3. Login is successful 4. Provider added 5. VM provisioned 6. Summary pages can be loaded and show correct information """ pass @pytest.mark.manual @test_requirements.update @pytest.mark.tier(2) @pytest.mark.meta(coverage=[1375313]) def test_update_custom_widgets(): """ Upgrade appliance with custom widgets added Polarion: assignee: jhenner casecomponent: Appliance caseimportance: medium initialEstimate: 1/3h setup: provision appliance add custom widgets add repo file to /etc/yum.repos.d/ add RHSM details check for updates update using webui check webui is available check widgets still work correctly startsin: 5.9 """ pass @pytest.mark.manual @test_requirements.update @pytest.mark.tier(2) def test_rh_registration_rhsm_proxy_on_ipv6(): """ Test RHSM registration with IPV6 proxy settings Polarion: assignee: jhenner casecomponent: Appliance caseimportance: medium initialEstimate: 1/12h setup: Provision appliace Connect to webui Nav to Configuration-Settings-Region-Red Hat Updates Edit Registration The following settings that work for internal testing can be found here https://mojo.redhat.com/docs/DOC-1123648 Save settings Select appliance and click register startsin: 5.9 """ pass @pytest.mark.manual @test_requirements.update @pytest.mark.tier(2) def test_rh_registration_ui_proxy(): """ Check proxy settings are show in the list of info after saving subscription using proxy settings (RFE) Polarion: assignee: jhenner casecomponent: Configuration caseimportance: medium initialEstimate: 1/12h setup: Provision appliance navigate to Configuration-settings-region-redhat updates Click edit subscription Setup subscription with proxy validate and save check proxy settings areshown in ui """ pass @pytest.mark.manual @test_requirements.update @pytest.mark.tier(2) @pytest.mark.meta(coverage=[1553841]) def test_update_webui_custom_css(): """ Test css customization"s function correctly after webui update. Old bugzilla, css customisation is not possible to be done in production, but custom.css file can be changed Polarion: assignee: jhenner casecomponent: Appliance caseimportance: medium initialEstimate: 1/6h setup: provision appliance testSteps: 1. ssh to the appliance 2. change custom CSS file - you can run command: echo 'body {background-color: #FF00EF;}' >> /var/www/miq/vmdb/public/custom.css 3. add repo file to /etc/yum.repos.d/ 4. add RHSM settings 5. update through webui expectedResults: 1. 2. 3. 4. 5. webui is available and customizations still work startsin: 5.9 """ pass @pytest.mark.manual @test_requirements.update @pytest.mark.tier(2) @pytest.mark.meta(coverage=[1463289]) def test_rh_registration_proxy_crud(): """ Check proxy settings get added and removed from /etc/rhsm/rhsm.conf Polarion: assignee: jhenner casecomponent: Configuration caseimportance: medium initialEstimate: 1/12h setup: Provision appliance navigate to Configuration-settings-region-redhat updates Click edit subscription Setup subscription with proxy validate and save check proxy settings are added to rhsm.conf edit subscription again remove proxy settings validate and save check proxy settings are removed from rhsm.conf """ pass @pytest.mark.manual @pytest.mark.tier(2) @pytest.mark.meta(coverage=[1722540]) def test_upgrade_multi_replication_inplace(): """ test_upgrade_multi_replication_inplace Polarion: assignee: jhenner casecomponent: Configuration caseimportance: medium initialEstimate: 1h setup: 2 appliances: - Appliance A: Replication Global, region 0 - Appliance B: Replication Local, region 1 - Setup LDAP on one of the appliances - Login as LDAP user A - Setup a provider - Provision a VM testtype: functional testSteps: 1. Run upgrade according to the migration guide (version-dependent) 2. Start the appliances back up 3. Login as LDAP user B 4. Add another provider 5. Provision another VM using the new provider 6. Visit provider/host/vm summary pages expectedResults: 1. Upgrade is successful, so is migration and related tasks (fix_auth) 2. Appliances are running 3. Login is successful 4. Provider added 5. VM provisioned 6. Summary pages can be loaded and show correct information """ pass @pytest.mark.manual @test_requirements.update @pytest.mark.tier(2) def test_update_webui_ipv6(): """ Test updating the appliance to release version from prior version. (i.e 5.5.x to 5.5.x+) IPV6 only env Polarion: assignee: jhenner casecomponent: Appliance caseimportance: medium initialEstimate: 1/3h setup: -Provision configured appliance -Register it with RHSM using web UI -Create /etc/yum.repos.d/update.repo -populate file with repos from https://mojo.redhat.com/docs/DOC-1058772 -check for update in web UI -apply update -appliance should shutdown update and start back up -confirm you can login afterwards startsin: 5.8 """ pass @pytest.mark.manual @test_requirements.update @pytest.mark.tier(2) @pytest.mark.meta(coverage=[1411890]) def test_upgrade_check_repo_names(): """ Checks default rpm repos on a upgraded appliance Polarion: assignee: jhenner casecomponent: Configuration caseimportance: medium initialEstimate: 1/12h setup: Provision appliance navigate to Configuration-settings-region-redhat updates Click edit subscription Check repo name """ pass @pytest.mark.manual @pytest.mark.tier(2) @test_requirements.update @test_requirements.db_migration def test_upgrade_appliance_console_scap(): """ "ap" launches appliance_console, "" clears info screen, "14/17" Hardens appliance using SCAP configuration, "" complete. apply scap rules upgrade appliance and re-apply scap rules Test Source Polarion: assignee: jhenner casecomponent: Configuration caseimportance: medium initialEstimate: 1/3h startsin: 5.8 """ pass @pytest.mark.manual @test_requirements.update @test_requirements.db_migration @pytest.mark.tier(2) def test_upgrade_multi_ha_inplace(): """ Test upgrading HA setup to latest build and confirm it continues to work as expected. Polarion: assignee: jhenner casecomponent: Configuration caseimportance: medium initialEstimate: 1h startsin: 5.8 testSteps: 1. Upgrade appliances 2. Check failover expectedResults: 1. Confirm upgrade completes successfully 2. Confirm failover continues to work """ pass @pytest.mark.manual @test_requirements.update @test_requirements.db_migration @pytest.mark.tier(2) @pytest.mark.ignore_stream('5.10') def test_upgrade_multi_replication_inplace_55(): """ test upgrading replicated appliances to latest version Polarion: assignee: jhenner casecomponent: Configuration caseimportance: medium endsin: 5.9 initialEstimate: 1h startsin: 5.8 """ pass @pytest.mark.manual @test_requirements.update @test_requirements.db_migration @pytest.mark.tier(2) @pytest.mark.ignore_stream('5.11') def test_upgrade_multi_replication_inplace_56(): """ test upgrading replicated appliances to latest version Polarion: assignee: jhenner casecomponent: Configuration caseimportance: medium endsin: 5.10 initialEstimate: 1h startsin: 5.9 """ pass @pytest.mark.manual @test_requirements.update @pytest.mark.tier(2) def test_update_webui_ha(): """ Test webui update from minor versions with HA active Polarion: assignee: jhenner casecomponent: Configuration caseimportance: medium initialEstimate: 1/2h setup: provision 3 appliances setup HA following https://mojo.redhat.com/docs/DOC-1097888 check setup is working by accessing webui add repos for new build login to RHSM check for updates update appliances confirm HA continues to work as expected after update startsin: 5.7 """ pass @pytest.mark.manual @test_requirements.update @pytest.mark.tier(2) @pytest.mark.meta(coverage=[1461716]) def test_rh_rhsm_reregistering(): """ Switch between rhsm and sat6 registration Polarion: assignee: jhenner casecomponent: Configuration caseimportance: medium caseposneg: negative initialEstimate: 1/12h setup: Provision appliance navigate to Configuration-settings-region-redhat updates Click edit subscription Setup sat6 subscription validate and save register unregister (requires ssh commands) edit subscription setup rhsm validate and save register """ pass @pytest.mark.manual @test_requirements.update @pytest.mark.tier(2) def test_update_webui_replication(): """ Test webui update with replicated env Polarion: assignee: jhenner casecomponent: Appliance caseimportance: medium initialEstimate: 1h setup: Provision two appliances of the previous minor build setup replication between the two add update.repo file to /etc/yum.repos.d/ populate file with correct repos from https://mojo.redhat.com/docs/DOC-1058772 register with RHSM in webui check for updates apply update check replication/providers/vms testtype: functional """ pass
gpl-2.0
alexchentao/AL.Web
AL.Utils/Document/Excel/NPOI/SS/UserModel/IndexedColors.cs
5255
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace AL.Utils.NPOI.SS.UserModel { /** * A deprecated indexing scheme for colours that is still required for some records, and for backwards * compatibility with OLE2 formats. * * <p> * Each element corresponds to a color index (zero-based). When using the default indexed color palette, * the values are not written out, but instead are implied. When the color palette has been modified from default, * then the entire color palette is used. * </p> * * @author Yegor Kozlov */ public class IndexedColors { public static IndexedColors BLACK = new IndexedColors(8); public static IndexedColors WHITE = new IndexedColors(9); public static IndexedColors RED = new IndexedColors(10); public static IndexedColors BRIGHT_GREEN = new IndexedColors(11); public static IndexedColors BLUE = new IndexedColors(12); public static IndexedColors YELLOW = new IndexedColors(13); public static IndexedColors PINK = new IndexedColors(14); public static IndexedColors TURQUOISE = new IndexedColors(15); public static IndexedColors DARK_RED = new IndexedColors(16); public static IndexedColors GREEN = new IndexedColors(17); public static IndexedColors DARK_BLUE = new IndexedColors(18); public static IndexedColors DARK_YELLOW = new IndexedColors(19); public static IndexedColors VIOLET = new IndexedColors(20); public static IndexedColors TEAL = new IndexedColors(21); public static IndexedColors GREY_25_PERCENT = new IndexedColors(22); public static IndexedColors GREY_50_PERCENT = new IndexedColors(23); public static IndexedColors CORNFLOWER_BLUE = new IndexedColors(24); public static IndexedColors MAROON = new IndexedColors(25); public static IndexedColors LEMON_CHIFFON = new IndexedColors(26); public static IndexedColors ORCHID = new IndexedColors(28); public static IndexedColors CORAL = new IndexedColors(29); public static IndexedColors ROYAL_BLUE = new IndexedColors(30); public static IndexedColors LIGHT_CORNFLOWER_BLUE = new IndexedColors(31); public static IndexedColors SKY_BLUE = new IndexedColors(40); public static IndexedColors LIGHT_TURQUOISE = new IndexedColors(41); public static IndexedColors LIGHT_GREEN = new IndexedColors(42); public static IndexedColors LIGHT_YELLOW = new IndexedColors(43); public static IndexedColors PALE_BLUE = new IndexedColors(44); public static IndexedColors ROSE = new IndexedColors(45); public static IndexedColors LAVENDER = new IndexedColors(46); public static IndexedColors TAN = new IndexedColors(47); public static IndexedColors LIGHT_BLUE = new IndexedColors(48); public static IndexedColors AQUA = new IndexedColors(49); public static IndexedColors LIME = new IndexedColors(50); public static IndexedColors GOLD = new IndexedColors(51); public static IndexedColors LIGHT_ORANGE = new IndexedColors(52); public static IndexedColors ORANGE = new IndexedColors(53); public static IndexedColors BLUE_GREY = new IndexedColors(54); public static IndexedColors GREY_40_PERCENT = new IndexedColors(55); public static IndexedColors DARK_TEAL = new IndexedColors(56); public static IndexedColors SEA_GREEN = new IndexedColors(57); public static IndexedColors DARK_GREEN = new IndexedColors(58); public static IndexedColors OLIVE_GREEN = new IndexedColors(59); public static IndexedColors BROWN = new IndexedColors(60); public static IndexedColors PLUM = new IndexedColors(61); public static IndexedColors INDIGO = new IndexedColors(62); public static IndexedColors GREY_80_PERCENT = new IndexedColors(63); public static IndexedColors AUTOMATIC = new IndexedColors(64); private int index; IndexedColors(int idx) { index = idx; } /** * Returns index of this color * * @return index of this color */ public short Index { get { return (short)index; } } } }
gpl-2.0
marcomnc/AzzurraWS
test.php
545
<?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ define("MAGE_BASE_DIR", "..".DIRECTORY_SEPARATOR."..".DIRECTORY_SEPARATOR); define("BASE_STORE", 1); require_once(MAGE_BASE_DIR.'app/Mage.php'); //Path to Magento umask(0); Mage::app(); echo "<pre>"; error_reporting(E_ALL); ini_set("display_errors",1 ); $imp = 12345.345; $importo = Zend_Locale_Format::toNumber($imp, array('number_format' => '#0.00')); //$importo = preg_replace("/./", ",", $importo); echo $importo; die(); ?>
gpl-2.0
maxywb/vsipl
sourceryvsipl++-x86-3.1/src/vsipl++/tests/view.cpp
27189
/* Copyright (c) 2005, 2006, 2008 by CodeSourcery. All rights reserved. This file is available for license from CodeSourcery, Inc. under the terms of a commercial license and under the GPL. It is not part of the VSIPL++ reference implementation and is not available under the BSD license. */ /** @file tests/view.cpp @author Jules Bergmann @date 2005-03-22 @brief VSIPL++ Library: Unit tests for views: Vectors, Matrices, and Tesnors. */ #ifndef ILLEGALCASE # define ILLEGALCASE 0 #endif /*********************************************************************** Included Files ***********************************************************************/ #include <iostream> #include <cassert> #include <vsip/initfin.hpp> #include <vsip/support.hpp> #include <vsip/vector.hpp> #include <vsip/matrix.hpp> #include <vsip/domain.hpp> #include <vsip/core/length.hpp> #include <vsip/core/domain_utils.hpp> #include <vsip_csl/test.hpp> #include <vsip_csl/test-storage.hpp> using namespace std; using namespace vsip; using namespace vsip_csl; using vsip::impl::Length; /*********************************************************************** Definitions - Utility Functions ***********************************************************************/ /// Write a vector to a stream. template <typename T, typename Block> inline std::ostream& operator<<( std::ostream& out, vsip::const_Vector<T, Block> vec) VSIP_NOTHROW { for (vsip::index_type i=0; i<vec.size(); ++i) out << " " << i << ": " << vec.get(i) << "\n"; return out; } /// Write a matrix to a stream. template <typename T, typename Block> inline std::ostream& operator<<( std::ostream& out, vsip::const_Matrix<T, Block> v) VSIP_NOTHROW { for (vsip::index_type r=0; r<v.size(0); ++r) { out << " " << r << ":"; for (vsip::index_type c=0; c<v.size(1); ++c) out << " " << v.get(r, c); out << std::endl; } return out; } // Check the reported size of a vector against expected values. template <typename T, typename Block> void check_size( const_Vector<T, Block> view, Domain<1> const& dom) { test_assert(view.length() == dom.length()); test_assert(view.size() == dom.length()); test_assert(view.size(0) == dom.length()); } // Check the reported size of a matrix against expected values. template <typename T, typename Block> void check_size( const_Matrix<T, Block> view, Domain<2> const& dom) { test_assert(view.size() == dom[0].length() * dom[1].length()); test_assert(view.size(0) == dom[0].length()); test_assert(view.size(1) == dom[1].length()); } // Fill vector with sequence of values. template <typename T, typename Block> void fill_view( Vector<T, Block> view, int k, Index<1> offset, Domain<1> /* dom */) { for (index_type i=0; i<view.size(0); ++i) view.put(i, T(k*(i + offset[0])+1)); } // Fill matrix with a sequence of values. // Values are generated with a slope of K. template <typename T, typename Block> void fill_view( Matrix<T, Block> view, int k, Index<2> offset, Domain<2> dom) { for (index_type r=0; r<view.size(0); ++r) for (index_type c=0; c<view.size(1); ++c) { index_type i = (r+offset[0])*dom[1].length() + (c+offset[1]); view.put(r, c, T(k*i+1)); } } template <typename T, typename Block> void fill_view( Vector<T, Block> view, int k) { fill_view(view, k, Index<1>(0), Domain<1>(view.size(0))); } template <typename T, typename Block> void fill_view( Matrix<T, Block> view, int k) { fill_view(view, k, Index<2>(0, 0), Domain<2>(view.size(0), view.size(1))); } // Class to fill block with values based on K. // Partial specializations are provided for dimension equal 1 and 2. template <dimension_type Dim, typename Block> struct Fill_block; template <typename Block> struct Fill_block<1, Block> { static void fill( Block& blk, int k, Index<1> const& offset, Domain<1> const& /*dom*/) { typedef typename Block::value_type T; for (index_type i=0; i<blk.size(1, 0); ++i) { blk.put(i, T(k*(i+offset[0])+1)); } } static Index<1> origin() { return Index<1>(0); } static Domain<1> size(Block& blk) { return Domain<1>(blk.size(1, 0)); } }; template <typename Block> struct Fill_block<2, Block> { static void fill( Block& blk, int k, Index<2> const& offset, Domain<2> const& dom) { typedef typename Block::value_type T; for (index_type r=0; r<blk.size(2, 0); ++r) for (index_type c=0; c<blk.size(2, 1); ++c) { index_type i = (r+offset[0])*dom[1].length() + (c+offset[1]); blk.put(r, c, T(k*i+1)); } } static Index<2> origin() { return Index<2>(0, 0); } static Domain<2> size(Block& blk) { return Domain<2>(blk.size(2, 0), blk.size(2, 1)); } }; // fill_block -- fill a block with sequence of values. // // Values are generated with a slope of K. template <dimension_type Dim, typename Block> void fill_block(Block& blk, int k) { Fill_block<Dim, Block>::fill(blk, k, Fill_block<Dim, Block>::origin(), Fill_block<Dim, Block>::size(blk)); } // Test values in view against sequence. template <typename T, typename Block> void test_view(const_Vector<T, Block> vec, int k) { for (index_type i=0; i<vec.size(0); ++i) test_assert(equal(vec.get(i), T(k*i+1))); } // test_view -- test values in view against sequence. // // Asserts that view values match those generated by a call to // fill_view or fill_block with the same k value. template <typename T, typename Block> void test_view(const_Matrix<T, Block> v, int k) { for (index_type r=0; r<v.size(0); ++r) for (index_type c=0; c<v.size(1); ++c) { index_type i = r*v.size(1) + c; test_assert(equal(v.get(r, c), T(k*i+1))); } } // check_vector -- check values in vector against sequence. // // Checks that vector values match those generated by a call to // fill_vector or fill_block with the same k value. Rather than // triggering test_assertion failure, check_vector returns a boolean // pass/fail that can be used to cause an test_assertion failure in // the caller. template <typename T, typename Block> bool check_view(const_Vector<T, Block> vec, int k) { for (index_type i=0; i<vec.size(0); ++i) if (!equal(vec.get(i), T(k*i+1))) return false; return true; } // check_view -- check values in view against sequence. // // Checks that view values match those generated by a call to // fill_view or fill_block with the same k value. Rather than // triggering test_assertion failure, check_view returns a boolean // pass/fail that can be used to cause an test_assertion failure in // the caller. template <typename T, typename Block> bool check_view( const_Matrix<T, Block> view, int k, Index<2> offset, Domain<2> dom) { for (index_type r=0; r<view.size(0); ++r) for (index_type c=0; c<view.size(1); ++c) { index_type i = (r+offset[0])*dom[1].length() + (c+offset[1]); if (!equal(view.get(r, c), T(k*i+1))) return false; } return true; } template <typename T, typename Block> bool check_view( const_Matrix<T, Block> view, int k) { return check_view(view, k, Index<2>(0, 0), Domain<2>(view.size(0), view.size(1))); } // Check that all elements of a view have the same const values template <typename View> bool check_view_const( View view, typename View::value_type scalar) { dimension_type const dim = View::dim; Length<dim> ext = extent(view); for (Index<dim> idx; valid(ext,idx); next(ext, idx)) { if (!equal(get(view, idx), scalar)) return false; } return true; } // check_not_alias -- check that two views are not aliased. // // Changes made to one should not effect the other. template <template <typename, typename> class View1, template <typename, typename> class View2, typename T1, typename T2, typename Block1, typename Block2> void check_not_alias( View1<T1, Block1>& view1, View2<T2, Block2>& view2) { test_assert((View1<T1, Block1>::dim == View2<T2, Block2>::dim)); dimension_type const dim = View1<T1, Block1>::dim; fill_block<dim>(view1.block(), 2); fill_block<dim>(view2.block(), 3); // Make sure that updates to view2 do not affect view1. test_assert(check_view(view1, 2)); // And visa-versa. fill_block<dim>(view1.block(), 4); test_assert(check_view(view2, 3)); } // check_alias -- check that two views are aliased. // // Changes made to one should effect the other. template <template <typename, typename> class View1, template <typename, typename> class View2, typename T1, typename T2, typename Block1, typename Block2> void check_alias( View1<T1, Block1>& view1, View2<T2, Block2>& view2) { test_assert((View1<T1, Block1>::dim == View2<T2, Block2>::dim)); dimension_type const dim = View1<T1, Block1>::dim; fill_block<dim>(view1.block(), 2); test_assert(check_view(view1, 2)); test_assert(check_view(view2, 2)); fill_block<dim>(view2.block(), 3); test_assert(check_view(view1, 3)); test_assert(check_view(view2, 3)); } /*********************************************************************** Definitions - View Test Cases. ***********************************************************************/ // -------------------------------------------------------------------- // // Test cases for view get/put. // // The following functions are defined: // tc_get() // Test case for view get(). // test_get_type() / test_get() // Wrappers for different views and types. // -------------------------------------------------------------------- // template <typename Storage, dimension_type Dim> void tc_get(Domain<Dim> const& dom) { Storage stor(dom); check_size(stor.view, dom); fill_block<Dim>(stor.block(), 2); test_view(stor.view, 2); } template <typename T, dimension_type Dim> void test_get_type(Domain<Dim> const& dom) { tc_get< Storage<Dim, T> >(dom); tc_get<Const_storage<Dim, T> >(dom); } template <dimension_type Dim> void test_get(Domain<Dim> const& dom) { test_get_type<scalar_f> (dom); test_get_type<cscalar_f>(dom); test_get_type<int> (dom); test_get_type<short> (dom); } // -------------------------------------------------------------------- // // Test case for get/put. // // The following functions are defined: // tc_getput // Test a view's get() and put() member functions. // test_getput_type() / test_getput() // Wrappers for different views and types. // -------------------------------------------------------------------- // template <typename Storage, dimension_type Dim> void tc_getput(Domain<Dim> const& dom) { Storage stor(dom); check_size(stor.view, dom); fill_view(stor.view, 2); test_view(stor.view, 2); } template <typename T, dimension_type Dim> void test_getput_type(Domain<Dim> const& dom) { tc_getput<Storage<Dim, T> >(dom); #if (ILLEGALCASE == 1) // const_Views should not provide put(). tc_getput<Const_storage<Dim, T> >(dom); #endif } template <dimension_type Dim> void test_getput(Domain<Dim> const& dom) { test_getput_type<scalar_f> (dom); test_getput_type<cscalar_f>(dom); test_getput_type<int> (dom); test_getput_type<short> (dom); } // -------------------------------------------------------------------- // // Test case for view copy constructor. // // The following functions are defined: // tc_copy_cons() // Test copy construction of one view from another. // test_copy_cons_type(), test_copy_cons() // Wrappers for different views and types. // -------------------------------------------------------------------- // template <typename Storage1, typename Storage2, dimension_type Dim> void tc_copy_cons(Domain<Dim> const& dom, int k) { Storage1 stor1(dom); fill_block<Dim>(stor1.block(), k); typename Storage2::view_type view2(stor1.view); test_view(view2, k); check_alias(stor1.view, view2); } template <typename T1, typename T2, dimension_type Dim> void test_copy_cons_type(Domain<Dim> const& dom, int k) { tc_copy_cons< Storage<Dim, T1>, Storage<Dim, T2> >(dom, k); tc_copy_cons< Storage<Dim, T1>, Const_storage<Dim, T2> >(dom, k); tc_copy_cons<Const_storage<Dim, T1>, Const_storage<Dim, T2> >(dom, k); #if (ILLEGALCASE == 2) // It should be illegal to construct a View from a const_View. tc_copy_cons<Const_storage<Dim, T1>, Storage<Dim, T2>>(dom, k); #endif } template <dimension_type Dim> void test_copy_cons(Domain<Dim> const& dom, int k) { test_copy_cons_type< scalar_f, scalar_f>(dom, k); test_copy_cons_type<cscalar_f, cscalar_f>(dom, k); test_copy_cons_type< int, int>(dom, k); test_copy_cons_type< short, short>(dom, k); } // -------------------------------------------------------------------- // // Test case for view assignment // // The following functions are defined: // tc_assign() // Test assignment of one view to another. // test_assign_type(), test_assign() // Wrappers for different views and types. // -------------------------------------------------------------------- // template <typename Storage1, typename Storage2, dimension_type Dim> void tc_assign(Domain<Dim> const& dom, int k) { Storage1 stor1(dom); Storage2 stor2(dom); Storage2 stor2b(dom); fill_block<Dim>(stor1.block(), k); stor2.view = stor1.view; if (!check_view(stor2.view, k)) std::cout << "xxx " << k << ' ' << stor2.view << std::endl; test_assert(check_view(stor2.view, k)); check_not_alias(stor1.view, stor2.view); fill_block<Dim>(stor1.block(), k+1); stor2b.view = stor2.view = stor1.view; test_assert(check_view(stor2.view, k+1)); test_assert(check_view(stor2b.view, k+1)); } template <typename T1, typename T2, dimension_type Dim> void test_assign_type(Domain<Dim> const& dom, int k) { typedef typename vsip::impl::Row_major<Dim>::type row_t; typedef typename vsip::impl::Col_major<Dim>::type col_t; tc_assign< Storage<Dim, T1, row_t>, Storage<Dim, T2, row_t> >(dom, k); tc_assign< Storage<Dim, T1, row_t>, Storage<Dim, T2, col_t> >(dom, k); tc_assign< Storage<Dim, T1, col_t>, Storage<Dim, T2, row_t> >(dom, k); tc_assign< Storage<Dim, T1, col_t>, Storage<Dim, T2, col_t> >(dom, k); tc_assign< Storage<Dim, T1>, Storage<Dim, T2> >(dom, k); tc_assign<Const_storage<Dim, T1>, Storage<Dim, T2> >(dom, k); #if (ILLEGALCASE == 3) tc_assign< Storage<Dim, T1>, Const_storage<Dim, T2> >(dom, k); #endif #if (ILLEGALCASE == 4) tc_assign<Const_storage<Dim, T1>, Const_storage<Dim, T2> >(dom, k); #endif } template <dimension_type Dim> void test_assign(Domain<Dim> const& dom, int k) { test_assign_type<float, float>(dom, k); test_assign_type<int, float>(dom, k); } // -------------------------------------------------------------------- // // Test case for view assignment from scalar // // The following functions are defined: // tc_assign() // Test assignment of one view to another. // test_assign_type(), test_assign() // Wrappers for different views and types. // -------------------------------------------------------------------- // template <typename Storage, typename T, dimension_type Dim> void tc_assign_scalar( Domain<Dim> const& dom, int k) { Storage stor1(dom); Storage stor2(dom); stor1.view = T(k); test_assert(check_view_const(stor1.view, T(k))); stor1.view = stor2.view = T(k+1); test_assert(check_view_const(stor1.view, T(k+1))); test_assert(check_view_const(stor2.view, T(k+1))); } template <typename T1, typename T2, dimension_type Dim> void test_assign_scalar_type(Domain<Dim> const& dom, int k) { typedef typename vsip::impl::Row_major<Dim>::type row_t; typedef typename vsip::impl::Col_major<Dim>::type col_t; tc_assign_scalar<Storage<Dim, T1, row_t>, T2>(dom, k); } template <dimension_type Dim> void test_assign_scalar(Domain<Dim> const& dom, int k) { test_assign_scalar_type<float, float>(dom, k); // test_assign_scalar_type<int, float>(dom, k); } // -------------------------------------------------------------------- // // Test cases for passing views as parameters to functions // // The following functions are defined: // tc_sum_const() // Function taking a const_View parameter (returns the // sum of the view's elements). // tc_sum() // Function taking a View parameter (returns the sum of // the view's elements). // tc_call_sum_const() // Tests passing a view as a parameter when a const View // is expected. // tc_call_sum() // Tests passing a view as a parameter when a non-const // View is expected. // test_call_type(), test_call() // Wrappers for different views and types. // -------------------------------------------------------------------- // template <typename T, typename Block> T tc_sum_const(const_Vector<T, Block> vec) { T sumval = T(); for (index_type i=0; i<vec.size(0); ++i) sumval += vec.get(i); return sumval; } template <typename T, typename Block> T tc_sum(Vector<T, Block> vec) { T sumval = T(); for (index_type i=0; i<vec.size(0); ++i) sumval += vec.get(i); return sumval; } template <typename T, typename Block> T tc_sum_const(const_Matrix<T, Block> v) { T sumval = T(); for (index_type r=0; r<v.size(0); ++r) for (index_type c=0; c<v.size(1); ++c) sumval += v.get(r, c); return sumval; } template <typename T, typename Block> T tc_sum(Matrix<T, Block> v) { T sumval = T(); for (index_type r=0; r<v.size(0); ++r) for (index_type c=0; c<v.size(1); ++c) sumval += v.get(r, c); return sumval; } template <typename Storage, dimension_type Dim> void tc_call_sum_const(Domain<Dim> const& dom, int k) { Storage stor1(dom); typedef typename Storage::value_type T; fill_block<Dim>(stor1.block(), k); T sum = tc_sum_const(stor1.view); length_type len = stor1.view.size(); // dom[0].length() * dom[1].length(); if (!equal(sum, T(k*len*(len-1)/2+len))) { cout << "tc_call_sum_const -- fail\n" << " expected: " << T(k*len*(len-1)/2+len) << endl << " got : " << sum << endl; } test_assert(equal(sum, T(k*len*(len-1)/2+len))); } template <typename Storage, dimension_type Dim> void tc_call_sum(Domain<Dim> const& dom, int k) { Storage stor1(dom); typedef typename Storage::value_type T; fill_block<Dim>(stor1.block(), k); T sum = tc_sum(stor1.view); length_type len = stor1.view.size(); // dom[0].length() * dom[1].length(); test_assert(equal(sum, T(k*len*(len-1)/2+len))); } template <typename T, dimension_type Dim> void test_call_type(Domain<Dim> const& dom, int k) { tc_call_sum_const<Const_storage<Dim, T> >(dom, k); tc_call_sum_const< Storage<Dim, T> >(dom, k); #if (ILLEGALCASE == 5) // should not be able to pass a const_Matrix to a routine // expecting a Matrix. tc_call_sum<Const_storage<Dim, T> >(dom, k); #endif tc_call_sum< Storage<Dim, T> >(dom, k); } template <dimension_type Dim> void test_call(Domain<Dim> const& dom, int k) { test_call_type<scalar_f> (dom, k); test_call_type<cscalar_f>(dom, k); test_call_type<int> (dom, k); test_call_type<short> (dom, k); } // -------------------------------------------------------------------- // // Test cases for returning a view from a function. // // The following functions are defined: // return_view() // Returns a view, populated with a fill_block // tc_assign_return() // Test case: assign returned view to existing view. // tc_cons_return() // Test case: construct new view from returned view. // test_return_type() // Calls tc_assign_return() and tc_cons_return() test // cases for a given type. // test_return() // Test for view return. Calls test_return_type() for // several types. // -------------------------------------------------------------------- // // Returen view with domain DOM, filled with fill_block(k). template <typename Storage, dimension_type Dim> typename Storage::view_type return_view(Domain<Dim> const& dom, int k) { Storage stor(dom); // put_nth(stor.block(), 0, val) fill_block<Dim>(stor.block(), k); return stor.view; } // Assign a view from the value of a function returning a view. template <typename Storage1, typename Storage2, dimension_type Dim> void tc_assign_return(Domain<Dim> const& dom, int k) { Storage1 stor1(dom, typename Storage1::value_type()); // test_assert(view1.get(0, 0) != val || val == T()); stor1.view = return_view<Storage2>(dom, k); test_assert(check_view(stor1.view, k)); } // Construct a view from the value of a function returning a view. template <typename Storage1, typename Storage2, dimension_type Dim> void tc_cons_return(Domain<Dim> const& dom, int k) { typename Storage1::view_type view1(return_view<Storage2>(dom, k)); test_assert(check_view(view1, k)); } // Test tc_cons_assign() and tc_cons_return for a given type. template <typename T, dimension_type Dim> void test_return_type(Domain<Dim> const& dom, int k) { tc_assign_return<Storage<Dim, T>, Storage<Dim, T> >(dom, k); tc_assign_return<Storage<Dim, T>, Const_storage<Dim, T> >(dom, k); #if ILLEGALCASE == 6 // Illegal: you cannot assign to a const_Matrix tc_assign_return<float, const_Matrix, const_Matrix>(dom, k); #endif #if ILLEGALCASE == 7 // Illegal: you cannot assign to a const_Matrix tc_assign_return<float, const_Matrix, Matrix>(dom, k); #endif tc_cons_return< Storage<Dim, T>, Storage<Dim, T> >(dom, k); tc_cons_return< Storage<Dim, T>, Const_storage<Dim, T> >(dom, k); tc_cons_return<Const_storage<Dim, T>, Storage<Dim, T> >(dom, k); tc_cons_return<Const_storage<Dim, T>, Const_storage<Dim, T> >(dom, k); } // Test view return. template <dimension_type Dim> void test_return(Domain<Dim> const& dom, int k) { test_return_type<scalar_f> (dom, k); test_return_type<cscalar_f>(dom, k); test_return_type<int> (dom, k); test_return_type<short> (dom, k); } // -------------------------------------------------------------------- // // Test case for same-dimensional subviews (call-operator, get()). // // The following functions are defined: // tc_subview() // Test a 1-dim or 2-dim subview for consistency. // test_subview_type(), test_subview_domsub(), test_subview() // Wrappers for different views, types, and sizes. // -------------------------------------------------------------------- // template <typename Storage> void tc_subview( Domain<1> const& dom, Domain<1> const& sub, int k) { typedef typename Storage::value_type T; dimension_type const dim = 1; for (dimension_type d=0; d<dim; ++d) { test_assert(sub[d].first() >= dom[d].first()); test_assert(sub[d].impl_last() <= dom[d].impl_last()); } Storage stor(dom); fill_block<dim>(stor.block(), k); typename Storage::view_type::subview_type subv = stor.view(sub); typename Storage::view_type::const_subview_type csubv = stor.view.get(sub); for (index_type i=0; i<subv.size(); ++i) { index_type parent_i = sub.impl_nth(i); test_assert(stor.view.get(parent_i) == subv.get(i)); test_assert(stor.view.get(parent_i) == csubv.get(i)); T val = stor.view.get(parent_i) + T(1); stor.block().put(parent_i, val); test_assert(stor.view.get(parent_i) == val); test_assert(stor.view.get(parent_i) == subv.get(i)); test_assert(stor.view.get(parent_i) == csubv.get(i)); } } template <typename Storage> void tc_subview( Domain<2> const& dom, Domain<2> const& sub, int k) { typedef typename Storage::value_type T; dimension_type const dim = 2; for (dimension_type d=0; d<dim; ++d) { test_assert(sub[d].first() >= dom[d].first()); test_assert(sub[d].impl_last() <= dom[d].impl_last()); } Storage stor(dom); fill_block<dim>(stor.block(), k); typename Storage::view_type::subview_type subv = stor.view(sub); typename Storage::view_type::const_subview_type csubv = stor.view.get(sub); for (index_type r=0; r<subv.size(0); ++r) { for (index_type c=0; c<subv.size(1); ++c) { index_type par_r = sub[0].impl_nth(r); index_type par_c = sub[1].impl_nth(c); test_assert(stor.view.get(par_r, par_c) == subv.get(r, c)); test_assert(stor.view.get(par_r, par_c) == csubv.get(r, c)); T val = stor.view.get(par_r, par_c) + T(1); stor.block().put(par_r, par_c, val); test_assert(stor.view.get(par_r, par_c) == val); test_assert(stor.view.get(par_r, par_c) == subv.get(r, c)); test_assert(stor.view.get(par_r, par_c) == csubv.get(r, c)); } } } template <typename T, dimension_type Dim> void test_subview_type(Domain<Dim> const& dom, Domain<Dim> const& sub, int k) { tc_subview< Storage<Dim, T> >(dom, sub, k); tc_subview<Const_storage<Dim, T> >(dom, sub, k); } template <dimension_type Dim> void test_subview_domsub(Domain<Dim> const& dom, Domain<Dim> const& sub, int k) { test_subview_type<scalar_f> (dom, sub, k); test_subview_type<cscalar_f>(dom, sub, k); test_subview_type<int> (dom, sub, k); test_subview_type<short> (dom, sub, k); } void test_subview() { test_subview_domsub(Domain<1>(10), Domain<1>(0, 1, 3), 3); test_subview_domsub(Domain<1>(10), Domain<1>(5, 1, 3), 3); test_subview_domsub(Domain<1>(10), Domain<1>(0, 2, 3), 3); test_subview_domsub(Domain<1>(10), Domain<1>(5, 2, 3), 3); test_subview_domsub(Domain<1>(256), Domain<1>(5, 5, 40), 3); test_subview_domsub(Domain<2>(10, 10), Domain<2>(3, 3), 3); test_subview_domsub(Domain<2>(10, 10), Domain<2>(Domain<1>(5, 1, 3), Domain<1>(5, 1, 3)), 3); test_subview_domsub(Domain<2>(10, 10), Domain<2>(Domain<1>(0, 2, 3), Domain<1>(5, 1, 3)), 3); } // Wrap non-subview test cases. template <dimension_type Dim> void test_all(Domain<Dim> const& dom, int k) { test_get(dom); test_getput(dom); test_copy_cons(dom, k); test_assign(dom, k); test_assign_scalar(dom, k); test_call(dom, k); test_return(dom, k); } int main(int argc, char** argv) { vsip::vsipl init(argc, argv); test_all(Domain<1>(1), 3); test_all(Domain<1>(10), 3); test_all(Domain<1>(257), 3); test_all(Domain<1>(328), 3); test_all(Domain<2>(1, 10), 3); test_all(Domain<2>(10, 1), 3); // 9 test_all(Domain<2>(32, 32), 3); // 9 // These fail the function call test because the element sum exceeds // the dynamic range of float: // test_all(Domain<2>(17, 257), 3); // 37 // test_all(Domain<2>(1023, 10), 3); // 13 test_subview(); }
gpl-2.0
bjaraujo/ENigMA
trunk/src/integration/IntTetrahedron_Imp.hpp
765
// ***************************************************************************** // <ProjectName> ENigMA </ProjectName> // <Description> Extended Numerical Multiphysics Analysis </Description> // <HeadURL> $HeadURL$ </HeadURL> // <LastChangedDate> $LastChangedDate$ </LastChangedDate> // <LastChangedRevision> $LastChangedRevision$ </LastChangedRevision> // <Author> Billy Araujo </Author> // ***************************************************************************** namespace ENigMA { namespace integration { template <typename Real> CIntTetrahedron<Real>::CIntTetrahedron() { } template <typename Real> CIntTetrahedron<Real>::~CIntTetrahedron() { } } }
gpl-2.0
dajohnso/cfme_tests
cfme/containers/service.py
3143
# -*- coding: utf-8 -*- import random import itertools from cfme.common import SummaryMixin, Taggable from cfme.fixtures import pytest_selenium as sel from cfme.web_ui import toolbar as tb, match_location,\ PagedTable, CheckboxTable from cfme.containers.provider import details_page, Labelable,\ ContainerObjectAllBaseView from utils.appliance import Navigatable from utils.appliance.implementations.ui import navigator, CFMENavigateStep,\ navigate_to from navmazing import NavigateToAttribute, NavigateToSibling from functools import partial list_tbl = CheckboxTable(table_locator="//div[@id='list_grid']//table") paged_tbl = PagedTable(table_locator="//div[@id='list_grid']//table") match_page = partial(match_location, controller='container_service', title='Services') class Service(Taggable, Labelable, SummaryMixin, Navigatable): PLURAL = 'Container Services' def __init__(self, name, project_name, provider, appliance=None): self.name = name self.provider = provider self.project_name = project_name Navigatable.__init__(self, appliance=appliance) def load_details(self, refresh=False): navigate_to(self, 'Details') if refresh: tb.refresh() def click_element(self, *ident): self.load_details(refresh=True) return sel.click(details_page.infoblock.element(*ident)) def get_detail(self, *ident): """ Gets details from the details infoblock Args: *ident: An InfoBlock title, followed by the Key name, e.g. "Relationships", "Images" Returns: A string representing the contents of the InfoBlock's value. """ self.load_details(refresh=True) return details_page.infoblock.text(*ident) @classmethod def get_random_instances(cls, provider, count=1, appliance=None): """Generating random instances.""" service_list = provider.mgmt.list_service() random.shuffle(service_list) return [cls(obj.name, obj.project_name, provider, appliance=appliance) for obj in itertools.islice(service_list, count)] class ServiceAllView(ContainerObjectAllBaseView): TITLE_TEXT = 'Container Services' @navigator.register(Service, 'All') class All(CFMENavigateStep): prerequisite = NavigateToAttribute('appliance.server', 'LoggedIn') VIEW = ServiceAllView def step(self): self.prerequisite_view.navigation.select('Compute', 'Containers', 'Container Services') def resetter(self): # Reset view and selection tb.select("List View") from cfme.web_ui import paginator paginator.check_all() paginator.uncheck_all() @navigator.register(Service, 'Details') class Details(CFMENavigateStep): prerequisite = NavigateToSibling('All') def am_i_here(self): return match_page(summary='{} (Summary)'.format(self.obj.name)) def step(self): tb.select('List View') sel.click(paged_tbl.find_row_by_cell_on_all_pages({'Name': self.obj.name, 'Project Name': self.obj.project_name}))
gpl-2.0
Daomaster/Crazyflie-DDrone
DDTest/Dance_Test.py
8885
#!/usr/bin/python import time import sys import tty import termios import argparse sys.path.append("../lib") import cflib from cflib.crazyflie import Crazyflie from cfclient.utils.logconfigreader import LogConfig from cfclient.utils.logconfigreader import LogVariable from threading import Thread, Event from datetime import datetime import Gnuplot # Global values for accelometer accelvaluesX = [] accelvaluesY = [] accelvaluesZ = [] # Global key for threads key = "" # Global value for current and target altitude current_alt = 0 alt_init = 1.0 alt_inc = 0.2 target_alt = 0 user_mode = False class _GetchUnix: """ Class to get keys from the keyboard without pressing Enter. """ def __init__(self): pass def __call__(self): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class KeyReaderThread(Thread): """ This class is a basic thread for reading the keyboard """ def __init__(self): """ Initialize the thread """ Thread.__init__(self) def run(self): """ Read the keyboard and store the value in variable key """ global key getch = _GetchUnix() key = getch() while key != "e": key = getch() time.sleep(0.1) class TestFlight: def __init__(self): """ Initialize the quad copter """ # Log file for Accelerometer self.f1 = open('Accelerometer_log.txt', 'w') # Log file for Pitch Roll Yaw self.f2 = open('Stabalizer_log.txt', 'w') # Log file for altitude self.f3 = open('Barometer_log.txt', 'w') # write data into the log files self.f1.write('Accelerometer log\n {date} {acc.x} {acc.y} {acc.z}\n') self.f2.write('Stabilizer log\n{date} {Roll} {Pitch} {Yaw} {Thrust}\n') self.f3.write('Barometer log\n {data} {ASL}\n') # get the Unix time self.starttime = time.time() * 1000.0 self.date = time.time() * 1000.0 - self.starttime # Initialize the crazyflie and get the drivers ready self.crazyflie = cflib.crazyflie.Crazyflie() print 'Initializing drivers' cflib.crtp.init_drivers() # Start scanning available devices print 'Searching for available devices' available = cflib.crtp.scan_interfaces() radio = False for i in available: # Connect to the first device of the type 'radio' if 'radio' in i[0]: radio = True dev = i[0] print 'Connecting to interface with URI [{0}] and name {1}'.format(i[0], i[1]) self.crazyflie.open_link("radio://0/80/250K") ## radio://0/80/250K is most well connected radio frequency # Heungseok Park, 4.9.2015 #self.crazyflie.open_link(dev) break if not radio: print 'No quadcopter detected. Try to connect again.' exit(-1) # Set up the callback when connected self.crazyflie.connected.add_callback(self.connectSetupFinished) def connectSetupFinished(self, linkURI): """ Set the loggers """ # Log barometer # we use only barometer value(ASL Value) to control altitude self.logBaro = LogConfig("Baro", 200) self.logBaro.add_variable("baro.aslLong", "float") self.crazyflie.log.add_config(self.logBaro) if self.logBaro.valid: self.logBaro.data_received_cb.add_callback(self.print_baro_data) self.logBaro.start() else: print 'Could not setup log configuration for barometer after connection!' # Start another thread and doing control function call print "log for debugging: before start increasing_step" # Thread(target=self.increasing_step).start() # Thread(target=self.recursive_step).start() Thread(target=self.init_alt).start() def print_baro_data(self, ident, data, logconfig): # Output the Barometer data #logging.info("Id={0}, Barometer: asl={1:.4f}".format(ident, data["baro.aslLong"])) # Get the Current altitude and put it in the global var global current_alt current_alt = data["baro.aslLong"] # The Target Altitude = Current + init global target_alt global alt_init # Use a temp var to hold the value of target target = round(current_alt) + alt_init # if the target did not initialized then initialize it if target_alt == 0: target_alt = target # system output the time and the altitude, each id represents a time slice in Unix date = time.time() * 1000.0 - self.starttime sys.stdout.write('Id={0}, Baro: baro.aslLong{1:.4f}\r\n'.format(ident, data["baro.aslLong"])) self.f3.write('{} {}\n'.format(date, data["baro.aslLong"])) pass def print_stab_data(self, ident, data, logconfig): # Output the stablizer data (roll pith yaw) sys.stdout.write('Id={0}, Stabilizer: Roll={1:.2f}, Pitch={2:.2f}, Yaw={3:.2f}, Thrust={4:.2f}\r'.format(ident, data["stabilizer.roll"], data["stabilizer.pitch"], data["stabilizer.yaw"], data["stabilizer.thrust"])) # print('Id={0}, Stabilizer: Roll={1:.2f}, Pitch={2:.2f}, Yaw={3:.2f}, Thrust={4:.2f}\r'.format(ident, data["stabilizer.roll"], data["stabilizer.pitch"], data["stabilizer.yaw"], data["stabilizer.thrust"])) self.f2.write('{} {} {} {} {}\n'.format(self.date, data["stabilizer.roll"], data["stabilizer.pitch"], data["stabilizer.roll"], data["stabilizer.pitch"], data["stabilizer.yaw"], data["stabilizer.thrust"])) def print_accel_data(self, ident, data, logconfig): # Output the accelerometer data # global variables that holds x,y,z value global accelvaluesX global accelvaluesY global accelvaluesZ sys.stdout.write('Id={0}, Accelerometer: x={1:.2f}, y={2:.2f}, z={3:.2f}\r".format(ident, data["acc.x"], data["acc.y"], data["acc.z"]))') #print("Id={0}, Accelerometer: x={1:.2f}, y={2:.2f}, z={3:.2f}\n".format(ident, data["acc.x"], data["acc.y"], data["acc.z"])) #self.f1.write('{} {} {} {}\n'.format(self.date, data["acc.x"], data["acc.y"], data["acc.z"])) #sys.stdout.write("Id={0}, Accelerometer: x={1:.2f}, y={2:.2f}, z={3:.2f}\r".format(ident, data["acc.x"], data["acc.y"], data["acc.z"])) #date = time.time()*1000.0 - self.starttime #small_array = [] #small_array.append(date) #small_array.append(data["acc.x"]) #small_array.append(data["acc.y"]) #small_array.append(data["acc.z"]) #accelvaluesX.append(small_array_x) #print(accelvaluesX) #print(accelvaluesY) #print(accelvaluesZ) def init_alt(self): #global current_alt global target_alt global current_alt current_temp = current_alt target_temp = target_alt if current_temp != 0: print "- current_temp" + str(current_temp) print "- target_temp" + str(target_temp) # If the current = target then hold the altitude by using the build-in function althold if round(current_temp, 1) == target_temp: if current_temp != 0: sys.stdout.write("Now, current and target altitude is same, Let's hover!\r\n") self.crazyflie.param.set_value("flightmode.althold", "True") #the althold will last 4 second and then we set the thrust to 32767 which is the value that will hover self.crazyflie.commander.send_setpoint(0, 0, 0, 32767) return self.init_alt() # If the current < target the thrust up gain altitude # round function change float value to int elif round(current_temp, 3) < target_temp: sys.stdout.write("Current alt is lower than target value, Let's go up!\r\n") self.crazyflie.commander.send_setpoint(0, 0, 0, 40000) #for bandwidth reason, the command need to be delayed time.sleep(0.2) return self.init_alt() # If the current > target the thrust down lose altitude elif round(current_temp, 3) > target_temp: sys.stdout.write("Current alt is higher than target value, Let's go down!\r\n") self.crazyflie.commander.send_setpoint(0, 0, 0, 32000) #for bandwidth reason, the command need to be delayed time.sleep(0.2) return self.init_alt() # Start the program TestFlight()
gpl-2.0
i-make-robots/Arm5
src/main/java/com/marginallyclever/util/MarginallyCleverPreferences.java
9232
package com.marginallyclever.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.prefs.AbstractPreferences; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import org.jetbrains.annotations.NotNull; import com.marginallyclever.robotOverlord.log.Log; /** * Created on 6/7/15. * * @author Peter Colapietro * See <a href="http://www.davidc.net/programming/java/java-preferences-using-file-backing-store">Java Preferences using a file as the backing store</a> * See <a href="http://stackoverflow.com/a/25548386">SO answer to: How to synchronize file access in a Java servlet?</a> * @since v7.1.4 */ public class MarginallyCleverPreferences extends AbstractPreferences implements Ancestryable { /** * */ private final Map<String, String> root; /** * */ private final Map<String, Preferences> children; /** * */ private boolean thisIsRemoved; /** * */ private final Object mutex = new Object(); /** * Creates a preference node with the specified parent and the specified * name relative to its parent. * * @param parent the parent of this preference node, or null if this * is the root. * @param name the name of this preference node, relative to its parent, * or <tt>""</tt> if this is the root. * @throws IllegalArgumentException if <tt>name</tt> contains a slash * (<tt>'/'</tt>), or <tt>parent</tt> is <tt>null</tt> and * name isn't <tt>""</tt>. */ public MarginallyCleverPreferences(AbstractPreferences parent, String name) { super(parent, name); Log.message("Instantiating node "+ name); root = new TreeMap<>(); children = new TreeMap<>(); try { sync(); } catch (BackingStoreException e) { Log.error("Unable to sync on creation of node "+name+". "+e); } } @Override protected void putSpi(@NotNull String key, String value) { root.put(key, value); try { flush(); } catch (BackingStoreException e) { Log.error("Unable to flush after putting "+key+". "+e); } } @Override protected String getSpi(@NotNull String key) { return root.get(key); } @Override protected void removeSpi(@NotNull String key) { root.remove(key); try { flush(); } catch (BackingStoreException e) { Log.error("Unable to flush after removing "+key+". "+e); } } @Override protected void removeNodeSpi() throws BackingStoreException { flush(); thisIsRemoved = true; } @NotNull @Override protected String[] keysSpi() throws BackingStoreException { final Set<String> keySet = root.keySet(); return keySet.toArray(new String[keySet.size()]); } @NotNull @Override protected String[] childrenNamesSpi() throws BackingStoreException { final Set<String> childrenNames = children.keySet(); return childrenNames.toArray(new String[childrenNames.size()]); } /** * http://stackoverflow.com/a/24249709 */ @NotNull @Override protected AbstractPreferences childSpi(@NotNull String name) { AbstractPreferences childPreferenceNode = (AbstractPreferences) children.get(name); boolean isChildRemoved = false; if (childPreferenceNode != null) { try { isChildRemoved = getIsRemoved(childPreferenceNode); } catch (ReflectiveOperationException e) { Log.error( e.getMessage() ); } } if (childPreferenceNode == null || isChildRemoved) { final AbstractPreferences castedPreferences = new MarginallyCleverPreferences(this, name); childPreferenceNode = castedPreferences; children.put(name, childPreferenceNode); } return childPreferenceNode; } /** * FIXME - Pure hack to get around erasure. * * @return true if removed * @throws ReflectiveOperationException */ private boolean getIsRemoved(AbstractPreferences abstractPreference) throws ReflectiveOperationException { Log.message( abstractPreference.toString() ); final Method declaredMethod = AbstractPreferences.class.getDeclaredMethod("isRemoved"); declaredMethod.setAccessible(true); Object isRemoved = declaredMethod.invoke(abstractPreference, new Object[]{null}); return (boolean) isRemoved; } @Override protected void syncSpi() throws BackingStoreException { if (isRemoved()) { return; } final File propertiesPreferencesFile = MarginallyCleverPreferencesFileFactory.getPropertiesPreferencesFile(); if (!propertiesPreferencesFile.exists()) { return; } synchronized (mutex) { final Properties p = new Properties(); try { try (final InputStream inStream = new FileInputStream(propertiesPreferencesFile)) { p.load(inStream); } final StringBuilder sb = new StringBuilder(); getPath(sb); final String path = sb.toString(); final Enumeration<?> propertyNames = p.propertyNames(); while (propertyNames.hasMoreElements()) { final String propKey = (String) propertyNames.nextElement(); if (propKey.startsWith(path)) { final String subKey = propKey.substring(path.length()); // Only load immediate descendants if (subKey.indexOf('.') == -1) { root.put(subKey, p.getProperty(propKey)); } } } } catch (IOException e) { throw new BackingStoreException(e); } } } @Override protected void flushSpi() throws BackingStoreException { final File xmlPreferencesFile = MarginallyCleverPreferencesFileFactory.getXmlPreferencesFile(); final File file = MarginallyCleverPreferencesFileFactory.getPropertiesPreferencesFile(); synchronized (mutex) { try { final Properties p = new Properties(); final StringBuilder sb = new StringBuilder(); getPath(sb); final String path = sb.toString(); if (file.exists()) { try (final InputStream fileInputStream = new FileInputStream(file)) { p.load(fileInputStream); } final List<String> toRemove = new ArrayList<>(); // Make a list of all direct children of this node to be removed final Enumeration<?> pnen = p.propertyNames(); while (pnen.hasMoreElements()) { final String propKey = (String) pnen.nextElement(); if (propKey.startsWith(path)) { final String subKey = propKey.substring(path.length()); // Only do immediate descendants if (subKey.indexOf('.') == -1) { toRemove.add(propKey); } } } // Remove them now that the enumeration is done with for (String propKey : toRemove) { p.remove(propKey); } } // If this node hasn't been removed, add back in any values if (!thisIsRemoved) { for (String s : root.keySet()) { p.setProperty(path + s, root.get(s)); } storePreferencesInFile(file, p); storeNodeInFile(xmlPreferencesFile); } } catch (IOException e) { throw new BackingStoreException(e); } } } private void storeNodeInFile(File file) throws IOException, BackingStoreException { final Preferences parent = recursiveGetParent(this.parent() != null ? this.parent() : this); try (final OutputStream fileOutputStream = new FileOutputStream(file)) { parent.exportNode(fileOutputStream); } } private Preferences recursiveGetParent(Preferences node) { Preferences parent = node.parent(); if (parent == null) { node = parent; } else { recursiveGetParent(parent); } return node; } /** * @param file where to store preferences * @param p property to store * @throws IOException */ private void storePreferencesInFile(File file, Properties p) throws IOException, BackingStoreException { final String marginallyCleverPreferencesFileComments = "MarginallyCleverPreferences"; try (final OutputStream fileOutputStream = new FileOutputStream(file)) { p.store(fileOutputStream, marginallyCleverPreferencesFileComments); } } /** * @param sb String builder */ private void getPath(StringBuilder sb) { MarginallyCleverPreferences parent = null; try { parent = (MarginallyCleverPreferences) parent(); } catch (ClassCastException e) { //logger.info("NOOP"); } if (parent == null) { return; } parent.getPath(sb); sb.append(name()).append('.'); } @Override public Map<String, Preferences> getChildren() { return new TreeMap<>(children); } @Override public Map<String, String> getRoot() { return new TreeMap<>(root); } }
gpl-2.0
ddavison/greenshot-web
wp-content/plugins/wordpress-amazon-associate/AmazonWidget/Carousel.php
6086
<?php /* * copyright (c) 2010 MDBitz - Matthew John Denton - mdbitz.com * * This file is part of WordPress Amazon Associate Plugin. * * WordPress Amazon Associate 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. * * WordPress Amazon Associate 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 WordPress Amazon Associate. * If not, see <http://www.gnu.org/licenses/>. */ /** * Carousel * * This file contains the class AmazonWidget_Carousel * * @author Matthew John Denton <matt@mdbitz.com> * @package com.mdbitz.wordpress.amazon_associate.AmazonWidget */ /** * AmazonWidget_Carousel is plugin implementation of the Amazon Carousel Widget * * @package com.mdbitz.wordpress.amazon_associate.AmazonWidget */ class AmazonWidget_Carousel extends AmazonWidget_Abstract { /** * Constructor * * @param string $xml XML Representation of Object */ public function __construct($args = null) { if( is_null( $args ) ){ $args = self::getDefaultOptions(); } parent::__construct($args); $this->_values["widget"] = "Carousel"; } /** * Converts Properties from ShortCode to valid Format * * @param string $property * @return string */ protected function convert( $property ) { switch( $property ) { case "widget_type": return "widgetType"; break; case "search_index": return "searchIndex"; break; case "browse_node": return "browseNode"; break; case "asin": return "ASIN"; break; case "shuffle_products": return "shuffleProducts"; break; case "show_border": return "showBorder"; break; default: return parent::convert( $property ); break; } } /** * is property valid for this object * * @param String $property * @return boolean */ public function isValid($property) { switch ($property) { case "height": case "widgetType": case "searchIndex": case "browseNode": case "ASIN": case "keywords": case "shuffleProducts": case "showBorder": return true; break; default: return parent::isValid( $property ); break; } } /** * get Array of available Widget Types * * @return array */ public static function getAvailableTypes() { return array( "ASINList" => "ASIN List", "SearchAndAdd" => "Search and Add", "Bestsellers" => "Best Sellers", "NewReleases" => "New Releases", "MostWishedFor" => "Most Wished For", "MostGifted" => "Most Gifted" ); } /** * get Type Parameters that can be modified * * @param String $type Widget Type * @return array */ public static function getTypeParameters( $type ) { switch( $type ) { case "ASINList": return array( "ASIN" => "ASIN" ); break; case "SearchAndAdd": return array( "keywords" => "Keywords", "searchIndex" => "Search Index", "browseNode" => "Browse Node" ); break; case "Bestsellers": case "NewReleases": case "MostWishedFor": case "MostGifted": return array( "searchIndex" => "Search Index", "browseNode" => "Browse Node" ); break; } } /** * return Associative Array of Default Amazon Widget Options * * @return array */ public static function getDefaultOptions() { return array( "widgetType" => "Bestsellers", "searchIndex" => "Books", "title" => "Bestselling Books", "width" => "600", "height" => "200", "marketPlace" => self::getDefaultMarket() ); } /** * return Associative Array of Default Amazon Widget Short Code Options * * @return array */ public static function getDefaultShortCodeOptions() { return array( "widget_type" => "Bestsellers", "search_index" => "Books", "title" => "Bestselling Books", "width" => "600", "height" => "200", "browse_node" => null, "asin" => null, "keywords" => null, "shuffle_products" => null, "show_border" => null, "market_place" => self::getDefaultMarket() ); } /** * return Amazon Widget HTML * @return String */ public function toHTML() { switch( $this->_values['widgetType'] ) { case "ASINList": unset( $this->_values['keywords'] ); unset( $this->_values['searchIndex'] ); unset( $this->_values['browseNode'] ); break; case "SearchAndAdd": unset( $this->_values['ASIN'] ); break; default: unset( $this->_values['ASIN'] ); unset( $this->_values['keywords'] ); break; } return parent::toHTML(); } }
gpl-2.0
Paty-A/New
promocsv/export.php
887
<?php //require($_SERVER['DOCUMENT_ROOT'].'/wp-blog-header.php'); $promoconn = mysql_connect("localhost","salad_commandc","NDS7hic2JHJBCG"); mysql_select_db('salad_commandc'); function CSVExport($query) { $sql_csv = mysql_query($query) or die("Error: " . mysql_error()); //Replace this line with what is appropriate for your DB abstraction layer header("Content-type:text/octect-stream"); header("Content-Disposition:attachment;filename=data.csv"); while($row = mysql_fetch_row($sql_csv)) { $titleq = mysql_query("SELECT post_title FROM wp_posts WHERE ID=".$row[1].""); $title = mysql_fetch_array($titleq); $row[1]=$title['post_title']; print '"' . stripslashes(implode('","',$row)) . "\"\n"; } exit; } CSVExport("SELECT * FROM wp_promotions WHERE post_id='".mysql_real_escape_string($_GET['expo'])."' ORDER BY last_name, first_name, id"); ?>
gpl-2.0
linpingchuan/misc
java/framework/src/main/java/com/moon/helper/ClassHelper.java
2273
package com.moon.helper; import com.moon.ClassUtil; import com.moon.annotation.Controller; import com.moon.annotation.Service; import java.lang.annotation.Annotation; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; /** * Created by Paul on 2017/2/3. */ public final class ClassHelper { // 定义类集合(用于存放所加载的类) private static final Set<Class<?>> CLASS_SET; static { String basePackage = ""; CLASS_SET = ClassUtil.getClassSet(basePackage); } /** * 获取应用包名下的所有类 * * @return */ public static Set<Class<?>> getClassSet() { return CLASS_SET; } /** * 获取应用包名下的所有Service类 * * @return */ public static Set<Class<?>> getServiceClassSet() { return CLASS_SET.stream().filter(x -> x.isAnnotationPresent(Service.class)).collect(Collectors.toSet()); } /** * 获取应用包名下的所有Controller类 * * @return */ public static Set<Class<?>> getControllerClassSet() { return CLASS_SET.stream().filter(x -> x.isAnnotationPresent(Controller.class)).collect(Collectors.toSet()); } public static Set<Class<?>> getBeanClassSet() { Set<Class<?>> beanClassSet = new HashSet<>(); beanClassSet.addAll(getServiceClassSet()); beanClassSet.addAll(getControllerClassSet()); return beanClassSet; } /** * 获取应用包名下某父类(或接口)的所有子类(或实现类) * @param superClass * @return */ public static Set<Class<?>> getClassSetBySuper(Class<?> superClass) { Set<Class<?>> classSet = CLASS_SET.stream().filter(x -> superClass.isAssignableFrom(x) && !superClass.equals(x)).collect(Collectors.toSet()); return classSet; } /** * 获取应用包名下带有注解的所有类 * @param annotationClass * @return */ public static Set<Class<?>> getClassSetByAnnotation(Class<? extends Annotation> annotationClass){ Set<Class<?>> classSet=CLASS_SET.stream().filter(x->x.isAnnotationPresent(annotationClass)).collect(Collectors.toSet()); return classSet; } }
gpl-2.0
philjord/esmj3dfo4
esmj3dfo4/src/esmj3dfo4/data/shared/subrecords/KeyWords.java
665
package esmj3dfo4.data.shared.subrecords; import java.util.ArrayList; import esmj3d.data.shared.subrecords.FormID; import tools.io.ESMByteConvert; public class KeyWords { public ArrayList<FormID> keywords = new ArrayList<FormID>(); public int size = 0; public KeyWords() { } public void setKSIZ(byte[] bytes) { size = ESMByteConvert.extractInt(bytes, 0); } public void setKWDA(byte[] bytes) { //- KSIZ count unit32 Number of formids in the following KWDA subrecord //- KWDA keywords formid Formid array of keywords //so this is a bunch of formIds not just 1 //keywords.add(new FormID(bytes)); } }
gpl-2.0
popovici-gabriel/projects
ResourceScheduler/src/main/java/com/jpmorgan/model/MessageSequence.java
2081
package com.jpmorgan.model; import com.jpmorgan.endpoint.Message; import java.io.Serializable; import java.util.Date; /** * Message sequence model which will be sent to the Gateway. * * @param <ID> ID of the Message * @param <P> Payload of the Message. */ public abstract class MessageSequence<ID, P> implements Message, Serializable { private final ID id; private final Date created; private final Group<ID> group; private final P payload; protected boolean endOfMessage; protected MessageSequence(ID id, P payload, Date created, Group group) { this.id = id; this.payload = payload; this.created = created; this.group = group; this.endOfMessage = false; } public ID getGroupId() { return group.getId(); } public P getPayload() { return payload; } /** * If message is End Of Message this function should return false, true otherwise. * * @return tests whether next occurring message sequence is available */ public boolean hasNext() { return !this.endOfMessage; } /** * Test whether or not the message has been already processed. * * @return processed status */ public abstract boolean isCompleted(); @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MessageSequence that = (MessageSequence) o; if (!id.equals(that.id)) return false; return true; } @Override public int hashCode() { return id.hashCode(); } /** * Checks whether or not this is the end of message. * * @return status of message */ public boolean isEndOfMessage() { return endOfMessage; } /** * Get sequence ID * * @return ID */ public ID getId() { return id; } /** * Get group * * @return Group */ public Group<ID> getGroup() { return group; } }
gpl-2.0
Sensatus/mediawiki-core
languages/messages/MessagesVi.php
23286
<?php /** Vietnamese (Tiếng Việt) * * To improve a translation please visit https://translatewiki.net * * @ingroup Language * @file * * @author Apple * @author Arisa * @author Baonguyen21022003 * @author Cheers! * @author DHN * @author Kaganer * @author Minh Nguyen * @author Mxn * @author Neoneurone * @author Nguyễn Thanh Quang * @author Prenn * @author Skye Darcy * @author Thaisk * @author Thanhtai2009 * @author Tmct * @author Trần Nguyễn Minh Huy * @author Trần Thế Trung * @author Tttrung * @author Vietbio * @author Vinhtantran * @author Vương Ngân Hà * @author Withoutaname * @author לערי ריינהארט */ $namespaceNames = [ NS_MEDIA => 'Phương_tiện', NS_SPECIAL => 'Đặc_biệt', NS_TALK => 'Thảo_luận', NS_USER => 'Thành_viên', NS_USER_TALK => 'Thảo_luận_Thành_viên', NS_PROJECT_TALK => 'Thảo_luận_$1', NS_FILE => 'Tập_tin', NS_FILE_TALK => 'Thảo_luận_Tập_tin', NS_MEDIAWIKI => 'MediaWiki', NS_MEDIAWIKI_TALK => 'Thảo_luận_MediaWiki', NS_TEMPLATE => 'Bản_mẫu', NS_TEMPLATE_TALK => 'Thảo_luận_Bản_mẫu', NS_HELP => 'Trợ_giúp', NS_HELP_TALK => 'Thảo_luận_Trợ_giúp', NS_CATEGORY => 'Thể_loại', NS_CATEGORY_TALK => 'Thảo_luận_Thể_loại', ]; $namespaceAliases = [ 'Hình' => NS_FILE, 'Thảo_luận_Hình' => NS_FILE_TALK, 'Tiêu_bản' => NS_TEMPLATE, 'Thảo_luận_Tiêu_bản' => NS_TEMPLATE_TALK, ]; $specialPageAliases = [ 'Activeusers' => [ 'Người_dùng_tích_cực' ], 'Allmessages' => [ 'Mọi_thông_điệp', 'Mọi_thông_báo' ], 'AllMyUploads' => [ 'Mọi_tập_tin_của_tôi', 'Mọi_tập_tin_tôi_tải_lên' ], 'Allpages' => [ 'Mọi_bài' ], 'ApiHelp' => [ 'Trợ_giúp_API' ], 'Ancientpages' => [ 'Trang_cũ' ], 'Badtitle' => [ 'Tựa_đề_hỏng' ], 'Blankpage' => [ 'Trang_trắng' ], 'Block' => [ 'Cấm', 'Cấm_IP', 'Cấm_thành_viên', 'Cấm_người_dùng' ], 'Booksources' => [ 'Nguồn_sách' ], 'BrokenRedirects' => [ 'Đổi_hướng_sai' ], 'Categories' => [ 'Thể_loại' ], 'ChangeEmail' => [ 'Đổi_thư_điện_tử' ], 'ChangePassword' => [ 'Đổi_mật_khẩu' ], 'ComparePages' => [ 'So_sánh_trang' ], 'Confirmemail' => [ 'Xác_nhận_thư' ], 'Contributions' => [ 'Đóng_góp' ], 'CreateAccount' => [ 'Mở_tài_khoản', 'Đăng_ký', 'Đăng_kí' ], 'Deadendpages' => [ 'Trang_đường_cùng' ], 'DeletedContributions' => [ 'Đóng_góp_bị_xóa', 'Đóng_góp_bị_xoá' ], 'Diff' => [ 'Khác', 'Khác_biệt' ], 'DoubleRedirects' => [ 'Đổi_hướng_kép' ], 'EditWatchlist' => [ 'Sửa_danh_sách_theo_dõi' ], 'Emailuser' => [ 'Gửi_thư', 'Gửi_thư_điện_tử' ], 'ExpandTemplates' => [ 'Bung_bản_mẫu', 'Bung_tiêu_bản' ], 'Export' => [ 'Xuất' ], 'Fewestrevisions' => [ 'Ít_phiên_bản_nhất' ], 'FileDuplicateSearch' => [ 'Tìm_tập_tin_trùng' ], 'Filepath' => [ 'Đường_dẫn_tập_tin', 'Đường_dẫn_file' ], 'Import' => [ 'Nhập' ], 'Invalidateemail' => [ 'Hủy_thư', 'Hủy_thư_điện_tử', 'Huỷ_thư', 'Huỷ_thư_điện_tử', 'Tắt_thư' ], 'JavaScriptTest' => [ 'Thử_JavaScript' ], 'BlockList' => [ 'Danh_sách_cấm' ], 'LinkSearch' => [ 'Tìm_liên_kết' ], 'Listadmins' => [ 'Danh_sách_bảo_quản_viên', 'Danh_sách_admin' ], 'Listbots' => [ 'Danh_sách_bot', 'Danh_sách_robot' ], 'Listfiles' => [ 'Danh_sách_tập_tin', 'Danh_sách_hình' ], 'Listgrouprights' => [ 'Quyền_nhóm_người_dùng' ], 'Listredirects' => [ 'Trang_đổi_hướng' ], 'ListDuplicatedFiles' => [ 'Tập_tin_trùng_lắp' ], 'Listusers' => [ 'Danh_sách_thành_viên' ], 'Lockdb' => [ 'Khóa_CSDL', 'Khóa_cơ_sở_dữ_liệu', 'Khoá_CSDL', 'Khoá_cơ_sở_dữ_liệu' ], 'Log' => [ 'Nhật_trình' ], 'Lonelypages' => [ 'Trang_mồ_côi' ], 'Longpages' => [ 'Trang_dài' ], 'MediaStatistics' => [ 'Thống_kê_phương_tiện' ], 'MergeHistory' => [ 'Trộn_lịch_sử' ], 'MIMEsearch' => [ 'Tìm_MIME' ], 'Mostcategories' => [ 'Thể_loại_lớn_nhất' ], 'Mostimages' => [ 'Tập_tin_liên_kết_nhiều_nhất' ], 'Mostinterwikis' => [ 'Nhiều_liên_wiki_nhất', 'Nhiều_interwiki_nhất' ], 'Mostlinked' => [ 'Liên_kết_nhiều_nhất' ], 'Mostlinkedcategories' => [ 'Thể_loại_liên_kết_nhiều_nhất' ], 'Mostlinkedtemplates' => [ 'Bản_mẫu_liên_kết_nhiều_nhất', 'Tiêu_bản_liên_kết_nhiều_nhất' ], 'Mostrevisions' => [ 'Nhiều_phiên_bản_nhất' ], 'Movepage' => [ 'Di_chuyển', 'Đổi_tên_trang' ], 'Mycontributions' => [ 'Đóng_góp_của_tôi', 'Tôi_đóng_góp' ], 'MyLanguage' => [ 'Ngôn_ngữ_tôi' ], 'Mypage' => [ 'Trang_tôi', 'Trang_cá_nhân' ], 'Mytalk' => [ 'Thảo_luận_tôi', 'Trang_thảo_luận_của_tôi' ], 'Myuploads' => [ 'Tập_tin_tôi' ], 'Newimages' => [ 'Tập_tin_mới', 'Hình_mới' ], 'Newpages' => [ 'Trang_mới' ], 'PagesWithProp' => [ 'Trang_theo_thuộc_tính' ], 'PageLanguage' => [ 'Ngôn_ngữ_trang' ], 'PasswordReset' => [ 'Tái_tạo_mật_khẩu', 'Đặt_lại_mật_khẩu' ], 'PermanentLink' => [ 'Liên_kết_thường_trực' ], 'Preferences' => [ 'Tùy_chọn', 'Tuỳ_chọn' ], 'Prefixindex' => [ 'Tiền_tố' ], 'Protectedpages' => [ 'Trang_khóa', 'Trang_khoá' ], 'Protectedtitles' => [ 'Tựa_đề_bị_khóa', 'Tựa_đề_bị_khoá' ], 'Randompage' => [ 'Ngẫu_nhiên' ], 'RandomInCategory' => [ 'Ngẫu_nhiên_trong_thể_loại' ], 'Randomredirect' => [ 'Đổi_hướng_ngẫu_nhiên' ], 'Randomrootpage' => [ 'Trang_gốc_ngẫu_nhiên' ], 'Recentchanges' => [ 'Thay_đổi_gần_đây' ], 'Recentchangeslinked' => [ 'Thay_đổi_liên_quan' ], 'Redirect' => [ 'Đổi_hướng' ], 'ResetTokens' => [ 'Đặt_lại_dấu_hiệu' ], 'Revisiondelete' => [ 'Xóa_phiên_bản', 'Xoá_phiên_bản' ], 'RunJobs' => [ 'Chạy_việc' ], 'Search' => [ 'Tìm_kiếm' ], 'Shortpages' => [ 'Trang_ngắn' ], 'Specialpages' => [ 'Trang_đặc_biệt' ], 'Statistics' => [ 'Thống_kê' ], 'Tags' => [ 'Thẻ' ], 'TrackingCategories' => [ 'Thể_loại_theo_dõi' ], 'Unblock' => [ 'Bỏ_cấm' ], 'Uncategorizedcategories' => [ 'Thể_loại_chưa_phân_loại' ], 'Uncategorizedimages' => [ 'Tập_tin_chưa_phân_loại', 'Hình_chưa_phân_loại' ], 'Uncategorizedpages' => [ 'Trang_chưa_phân_loại' ], 'Uncategorizedtemplates' => [ 'Bản_mẫu_chưa_phân_loại', 'Tiêu_bản_chưa_phân_loại' ], 'Undelete' => [ 'Phục_hồi' ], 'Unlockdb' => [ 'Mở_khóa_CSDL', 'Mở_khóa_cơ_sở_dữ_liệu', 'Mở_khoá_CSDL', 'Mở_khoá_cơ_sở_dữ_liệu' ], 'Unusedcategories' => [ 'Thể_loại_chưa_dùng' ], 'Unusedimages' => [ 'Tập_tin_chưa_dùng', 'Hình_chưa_dùng' ], 'Unusedtemplates' => [ 'Bản_mẫu_chưa_dùng', 'Tiêu_bản_chưa_dùng' ], 'Unwatchedpages' => [ 'Trang_chưa_theo_dõi' ], 'Upload' => [ 'Tải_lên' ], 'UploadStash' => [ 'Hàng_đợi_tải_lên' ], 'Userlogin' => [ 'Đăng_nhập' ], 'Userlogout' => [ 'Đăng_xuất' ], 'Userrights' => [ 'Quyền_thành_viên', 'Quyền_người_dùng' ], 'Version' => [ 'Phiên_bản' ], 'Wantedcategories' => [ 'Thể_loại_cần_thiết' ], 'Wantedfiles' => [ 'Tập_tin_cần_thiết' ], 'Wantedpages' => [ 'Trang_cần_thiết' ], 'Wantedtemplates' => [ 'Bản_mẫu_cần_thiết', 'Tiêu_bản_cần_thiết' ], 'Watchlist' => [ 'Danh_sách_theo_dõi' ], 'Whatlinkshere' => [ 'Liên_kết_đến_đây' ], 'Withoutinterwiki' => [ 'Không_liên_wiki', 'Không_interwiki' ], ]; $magicWords = [ 'redirect' => [ '0', '#đổi', '#REDIRECT' ], 'notoc' => [ '0', '__KHÔNG_MỤC_LỤC__', '__KHÔNGMỤCLỤC__', '__NOTOC__' ], 'nogallery' => [ '0', '__KHÔNG_ALBUM__', '__KHÔNGALBUM__', '__NOGALLERY__' ], 'forcetoc' => [ '0', '__LUÔN_MỤC_LỤC__', '__LUÔNMỤCLỤC__', '__FORCETOC__' ], 'toc' => [ '0', '__MỤC_LỤC__', '__MỤCLỤC__', '__TOC__' ], 'noeditsection' => [ '0', '__KHÔNG_NÚT_SỬA_MỤC__', '__KHÔNGNÚTSỬAMỤC__', '__NOEDITSECTION__' ], 'currentmonth' => [ '1', 'THÁNG_NÀY', 'THÁNGNÀY', 'THÁNG_NÀY_2', 'THÁNGNÀY2', 'CURRENTMONTH', 'CURRENTMONTH2' ], 'currentmonth1' => [ '1', 'THÁNG_NÀY_1', 'THÁNGNÀY1', 'CURRENTMONTH1' ], 'currentmonthname' => [ '1', 'TÊN_THÁNG_NÀY', 'TÊNTHÁNGNÀY', 'CURRENTMONTHNAME' ], 'currentmonthnamegen' => [ '1', 'TÊN_DÀI_THÁNG_NÀY', 'TÊNDÀITHÁNGNÀY', 'CURRENTMONTHNAMEGEN' ], 'currentmonthabbrev' => [ '1', 'TÊN_NGẮN_THÁNG_NÀY', 'TÊNNGẮNTHÁNGNÀY', 'CURRENTMONTHABBREV' ], 'currentday' => [ '1', 'NGÀY_NÀY', 'NGÀYNÀY', 'CURRENTDAY' ], 'currentday2' => [ '1', 'NGÀY_NÀY_2', 'NGÀYNÀY2', 'CURRENTDAY2' ], 'currentdayname' => [ '1', 'TÊN_NGÀY_NÀY', 'TÊNNGÀYNÀY', 'CURRENTDAYNAME' ], 'currentyear' => [ '1', 'NĂM_NÀY', 'NĂMNÀY', 'CURRENTYEAR' ], 'currenttime' => [ '1', 'GIỜ_NÀY', 'GIỜNÀY', 'CURRENTTIME' ], 'currenthour' => [ '1', 'GIỜ_HIỆN_TẠI', 'GIỜHIỆNTẠI', 'CURRENTHOUR' ], 'localmonth' => [ '1', 'THÁNG_ĐỊA_PHƯƠNG', 'THÁNGĐỊAPHƯƠNG', 'LOCALMONTH', 'LOCALMONTH2' ], 'localmonth1' => [ '1', 'THÁNG_ĐỊA_PHƯƠNG_1', 'THÁNGĐỊAPHƯƠNG1', 'LOCALMONTH1' ], 'localmonthname' => [ '1', 'TÊN_THÁNG_ĐỊA_PHƯƠNG', 'TÊNTHÁNGĐỊAPHƯƠNG', 'LOCALMONTHNAME' ], 'localmonthabbrev' => [ '1', 'THÁNG_ĐỊA_PHƯƠNG_TẮT', 'THÁNGĐỊAPHƯƠNGTẮT', 'LOCALMONTHABBREV' ], 'localday' => [ '1', 'NGÀY_ĐỊA_PHƯƠNG', 'NGÀYĐỊAPHƯƠNG', 'LOCALDAY' ], 'localday2' => [ '1', 'NGÀY_ĐỊA_PHƯƠNG_2', 'NGÀYĐỊAPHƯƠNG2', 'LOCALDAY2' ], 'localdayname' => [ '1', 'TÊN_NGÀY_ĐỊA_PHƯƠNG', 'TÊNNGÀYĐỊAPHƯƠNG', 'LOCALDAYNAME' ], 'localyear' => [ '1', 'NĂM_ĐỊA_PHƯƠNG', 'NĂMĐỊAPHƯƠNG', 'LOCALYEAR' ], 'localtime' => [ '1', 'THỜI_GIAN_ĐỊA_PHƯƠNG', 'THỜIGIANĐỊAPHƯƠNG', 'LOCALTIME' ], 'localhour' => [ '1', 'GIỜ_ĐỊA_PHƯƠNG', 'GIỜĐỊAPHƯƠNG', 'LOCALHOUR' ], 'numberofpages' => [ '1', 'SỐ_TRANG', 'SỐTRANG', 'NUMBEROFPAGES' ], 'numberofarticles' => [ '1', 'SỐ_BÀI', 'SỐBÀI', 'NUMBEROFARTICLES' ], 'numberoffiles' => [ '1', 'SỐ_TẬP_TIN', 'SỐTẬPTIN', 'NUMBEROFFILES' ], 'numberofusers' => [ '1', 'SỐ_THÀNH_VIÊN', 'SỐTHÀNHVIÊN', 'NUMBEROFUSERS' ], 'numberofactiveusers' => [ '1', 'SỐ_THÀNH_VIÊN_TÍCH_CỰC', 'SỐTHÀNHVIÊNTÍCHCỰC', 'NUMBEROFACTIVEUSERS' ], 'numberofedits' => [ '1', 'SỐ_SỬA_ĐỔI', 'SỐSỬAĐỔI', 'NUMBEROFEDITS' ], 'pagename' => [ '1', 'TÊN_TRANG', 'TÊNTRANG', 'PAGENAME' ], 'pagenamee' => [ '1', 'TÊN_TRANG_2', 'TÊNTRANG2', 'PAGENAMEE' ], 'namespace' => [ '1', 'KHÔNG_GIAN_TÊN', 'KHÔNGGIANTÊN', 'NAMESPACE' ], 'namespacenumber' => [ '1', 'SỐ_KHÔNG_GIAN_TÊN', 'SỐKHÔNGGIANTÊN', 'NAMESPACENUMBER' ], 'talkspace' => [ '1', 'KGT_THẢO_LUẬN', 'KGTTHẢOLUẬN', 'TALKSPACE' ], 'subjectspace' => [ '1', 'KGT_NỘI_DUNG', 'KGTNỘIDUNG', 'SUBJECTSPACE', 'ARTICLESPACE' ], 'fullpagename' => [ '1', 'TÊN_TRANG_ĐỦ', 'TÊNTRANGĐỦ', 'FULLPAGENAME' ], 'subpagename' => [ '1', 'TÊN_TRANG_PHỤ', 'TÊNTRANGPHỤ', 'SUBPAGENAME' ], 'basepagename' => [ '1', 'TÊN_TRANG_GỐC', 'TÊNTRANGGỐC', 'BASEPAGENAME' ], 'talkpagename' => [ '1', 'TÊN_TRANG_THẢO_LUẬN', 'TÊNTRANGTHẢOLUẬN', 'TALKPAGENAME' ], 'subjectpagename' => [ '1', 'TÊN_TRANG_NỘI_DUNG', 'TÊNTRANGNỘIDUNG', 'SUBJECTPAGENAME', 'ARTICLEPAGENAME' ], 'msg' => [ '0', 'NHẮN:', 'MSG:' ], 'subst' => [ '0', 'THẾ:', 'SUBST:' ], 'safesubst' => [ '0', 'THẾ_AN_TOÀN:', 'SAFESUBST:' ], 'msgnw' => [ '0', 'NHẮN_MỚI:', 'NHẮNMỚI:', 'MSGNW:' ], 'img_thumbnail' => [ '1', 'nhỏ', 'thumbnail', 'thumb' ], 'img_manualthumb' => [ '1', 'nhỏ=$1', 'thumbnail=$1', 'thumb=$1' ], 'img_right' => [ '1', 'phải', 'right' ], 'img_left' => [ '1', 'trái', 'left' ], 'img_none' => [ '1', 'không', 'none' ], 'img_center' => [ '1', 'giữa', 'center', 'centre' ], 'img_framed' => [ '1', 'khung', 'framed', 'enframed', 'frame' ], 'img_frameless' => [ '1', 'không_khung', 'frameless' ], 'img_lang' => [ '1', 'tiếng=$1', 'ngôn_ngữ=$1', 'lang=$1' ], 'img_page' => [ '1', 'trang=$1', 'trang_$1', 'page=$1', 'page $1' ], 'img_upright' => [ '1', 'đứng', 'đứng=$1', 'đứng_$1', 'upright', 'upright=$1', 'upright $1' ], 'img_border' => [ '1', 'viền', 'border' ], 'img_baseline' => [ '1', 'chân-chữ', 'baseline' ], 'img_sub' => [ '1', 'chỉ-số-dưới', 'sub' ], 'img_super' => [ '1', 'chỉ-số-trên', 'super', 'sup' ], 'img_top' => [ '1', 'trên', 'top' ], 'img_text_top' => [ '1', 'trên-chữ', 'text-top' ], 'img_middle' => [ '1', 'nửa-chiều-cao', 'middle' ], 'img_bottom' => [ '1', 'dưới', 'bottom' ], 'img_text_bottom' => [ '1', 'dưới-chữ', 'text-bottom' ], 'img_link' => [ '1', 'liên_kết=$1', 'link=$1' ], 'img_alt' => [ '1', 'thế=$1', 'thay_thế=$1', 'alt=$1' ], 'img_class' => [ '1', 'lớp=$1', 'class=$1' ], 'int' => [ '0', 'NỘI:', 'INT:' ], 'sitename' => [ '1', 'TÊN_MẠNG', 'TÊNMẠNG', 'SITENAME' ], 'ns' => [ '0', 'KGT:', 'NS:' ], 'localurl' => [ '0', 'URL_ĐỊA_PHƯƠNG:', 'URLĐỊAPHƯƠNG:', 'LOCALURL:' ], 'articlepath' => [ '0', 'ĐƯỜNG_DẪN_BÀI', 'ĐƯỜNGDẪNBÀI', 'LỐI_BÀI', 'LỐIBÀI', 'ARTICLEPATH' ], 'pageid' => [ '0', 'ID_TRANG', 'IDTRANG', 'PAGEID' ], 'server' => [ '0', 'MÁY_CHỦ', 'MÁYCHỦ', 'SERVER' ], 'servername' => [ '0', 'TÊN_MÁY_CHỦ', 'TÊNMÁYCHỦ', 'SERVERNAME' ], 'scriptpath' => [ '0', 'ĐƯỜNG_DẪN_KỊCH_BẢN', 'ĐƯỜNGDẪNKỊCHBẢN', 'ĐƯỜNG_DẪN_SCRIPT', 'ĐƯỜNGDẪNSCRIPT', 'SCRIPTPATH' ], 'stylepath' => [ '0', 'ĐƯỜNG_DẪN_KIỂU', 'ĐƯỜNGDẪNKIỂU', 'STYLEPATH' ], 'grammar' => [ '0', 'NGỮ_PHÁP:', 'NGỮPHÁP:', 'GRAMMAR:' ], 'gender' => [ '0', 'GIỐNG:', 'GENDER:' ], 'notitleconvert' => [ '0', '__KHÔNG_CHUYỂN_TÊN__', '__KHÔNGCHUYỂNTÊN__', '__NOTITLECONVERT__', '__NOTC__' ], 'nocontentconvert' => [ '0', '__KHÔNG_CHUYỂN_NỘI_DUNG__', '__KHÔNGCHUYỂNNỘIDUNG__', '__NOCONTENTCONVERT__', '__NOCC__' ], 'currentweek' => [ '1', 'TUẦN_NÀY', 'TUẦNNÀY', 'CURRENTWEEK' ], 'localweek' => [ '1', 'TUẦN_ĐỊA_PHƯƠNG', 'TUẦNĐỊAPHƯƠNG', 'LOCALWEEK' ], 'revisionid' => [ '1', 'SỐ_BẢN', 'SỐBẢN', 'REVISIONID' ], 'revisionday' => [ '1', 'NGÀY_BẢN', 'NGÀYBẢN', 'REVISIONDAY' ], 'revisionday2' => [ '1', 'NGÀY_BẢN_2', 'NGÀYBẢN2', 'REVISIONDAY2' ], 'revisionmonth' => [ '1', 'THÁNG_BẢN', 'THÁNGBẢN', 'REVISIONMONTH' ], 'revisionmonth1' => [ '1', 'THÁNG_BẢN_1', 'THÁNGBẢN1', 'REVISIONMONTH1' ], 'revisionyear' => [ '1', 'NĂM_BẢN', 'NĂMBẢN', 'REVISIONYEAR' ], 'revisiontimestamp' => [ '1', 'MỐC_THỜI_GIAN_BẢN', 'MỐCTHỜIGIANBẢN', 'DẤU_THỜI_GIAN_BẢN', 'DẤUTHỜIGIANBẢN', 'REVISIONTIMESTAMP' ], 'revisionuser' => [ '1', 'NGƯỜI_DÙNG_BẢN', 'NGƯỜIDÙNGBẢN', 'REVISIONUSER' ], 'revisionsize' => [ '1', 'CỠ_PHIÊN_BẢN', 'CỠPHIÊNBẢN', 'REVISIONSIZE' ], 'plural' => [ '0', 'SỐ_NHIỀU:', 'SỐNHIỀU:', 'PLURAL:' ], 'fullurl' => [ '0', 'URL_ĐỦ:', 'URLĐỦ:', 'FULLURL:' ], 'canonicalurl' => [ '0', 'URL_CHUẨN:', 'URLCHUẨN:', 'CANONICALURL:' ], 'lcfirst' => [ '0', 'CHỮ_ĐẦU_HOA:', 'CHỮĐẦUHOA:', 'LCFIRST:' ], 'ucfirst' => [ '0', 'CHỮ_ĐẦU_THƯỜNG:', 'CHỮĐẦUTHƯỜNG:', 'UCFIRST:' ], 'lc' => [ '0', 'CHỮ_HOA:', 'CHỮHOA:', 'LC:' ], 'uc' => [ '0', 'CHỮ_THƯỜNG:', 'CHỮTHƯỜNG:', 'UC:' ], 'displaytitle' => [ '1', 'TÊN_HIỂN_THỊ', 'TÊNHIỂNTHỊ', 'DISPLAYTITLE' ], 'newsectionlink' => [ '1', '__LIÊN_KẾT_MỤC_MỚI__', '__LIÊNKẾTMỤCMỚI__', '__NEWSECTIONLINK__' ], 'nonewsectionlink' => [ '1', '__KHÔNG_LIÊN_KẾT_MỤC_MỚI__', '__KHÔNGLIÊNKẾTMỤCMỚI__', '__NONEWSECTIONLINK__' ], 'currentversion' => [ '1', 'BẢN_NÀY', 'BẢNNÀY', 'CURRENTVERSION' ], 'urlencode' => [ '0', 'MÃ_HÓA_URL:', 'MÃHÓAURL:', 'MÃ_HOÁ_URL:', 'MÃHOÁURL:', 'URLENCODE:' ], 'anchorencode' => [ '0', 'MÃ_HÓA_NEO', 'MÃHÓANEO', 'MÃ_HOÁ_NEO', 'MÃHOÁNEO', 'ANCHORENCODE' ], 'currenttimestamp' => [ '1', 'MỐC_THỜI_GIAN_NÀY', 'MỐCTHỜIGIANNÀY', 'DẤU_THỜI_GIAN_NÀY', 'DẤUTHỜIGIANNÀY', 'CURRENTTIMESTAMP' ], 'localtimestamp' => [ '1', 'MỐC_THỜI_GIAN_ĐỊA_PHƯƠNG', 'MỐCTHỜIGIANĐỊAPHƯƠNG', 'DẤU_THỜI_GIAN_ĐỊA_PHƯƠNG', 'DẤUTHỜIGIANĐỊAPHƯƠNG', 'LOCALTIMESTAMP' ], 'directionmark' => [ '1', 'DẤU_HƯỚNG_VIẾT', 'DẤUHƯỚNGVIẾT', 'DIRECTIONMARK', 'DIRMARK' ], 'language' => [ '0', '#NGÔN_NGỮ:', '#NGÔNNGỮ:', '#LANGUAGE:' ], 'contentlanguage' => [ '1', 'NGÔN_NGỮ_NỘI_DUNG', 'NGÔNNGỮNỘIDUNG', 'CONTENTLANGUAGE', 'CONTENTLANG' ], 'pagesinnamespace' => [ '1', 'CỠ_KHÔNG_GIAN_TÊN:', 'CỠKHÔNGGIANTÊN:', 'CỠ_KGT:', 'CỠKGT:', 'PAGESINNAMESPACE:', 'PAGESINNS:' ], 'numberofadmins' => [ '1', 'SỐ_BẢO_QUẢN_VIÊN', 'SỐBẢOQUẢNVIÊN', 'SỐ_QUẢN_LÝ', 'SỐQUẢNLÝ', 'SỐ_QUẢN_LÍ', 'SỐQUẢNLÍ', 'NUMBEROFADMINS' ], 'formatnum' => [ '0', 'PHÂN_CHIA_SỐ', 'PHÂNCHIASỐ', 'FORMATNUM' ], 'special' => [ '0', 'đặc_biệt', 'special' ], 'defaultsort' => [ '1', 'XẾP_MẶC_ĐỊNH:', 'XẾPMẶCĐỊNH:', 'DEFAULTSORT:', 'DEFAULTSORTKEY:', 'DEFAULTCATEGORYSORT:' ], 'filepath' => [ '0', 'ĐƯỜNG_DẪN_TẬP_TIN', 'ĐƯỜNGDẪNTẬPTIN', 'FILEPATH:' ], 'tag' => [ '0', 'thẻ', 'tag' ], 'hiddencat' => [ '1', '__THỂ_LOẠI_ẨN__', '__THỂLOẠIẨN__', '__HIDDENCAT__' ], 'pagesincategory' => [ '1', 'CỠ_THỂ_LOẠI', 'CỠTHỂLOẠI', 'PAGESINCATEGORY', 'PAGESINCAT' ], 'pagesize' => [ '1', 'CỠ_TRANG', 'CỠTRANG', 'PAGESIZE' ], 'index' => [ '1', '__CHỈ_MỤC__', '__CHỈMỤC__', '__INDEX__' ], 'noindex' => [ '1', '__KHÔNG_CHỈ_MỤC__', '__KHÔNGCHỈMỤC__', '__NOINDEX__' ], 'numberingroup' => [ '1', 'CỠ_NHÓM', 'CỠNHÓM', 'NUMBERINGROUP', 'NUMINGROUP' ], 'staticredirect' => [ '1', '__ĐỔI_HƯỚNG_NHẤT_ĐỊNH__', '__ĐỔIHƯỚNGNHẤTĐỊNH__', '__STATICREDIRECT__' ], 'protectionlevel' => [ '1', 'MỨC_KHÓA', 'MỨCKHÓA', 'MỨC_KHOÁ', 'MỨCKHOÁ', 'PROTECTIONLEVEL' ], 'cascadingsources' => [ '1', 'NGUỒN_THEO_TẦNG', 'NGUỒNTHEOTẦNG', 'CASCADINGSOURCES' ], 'formatdate' => [ '0', 'định_dạng_ngày', 'địnhdạngngày', 'formatdate', 'dateformat' ], 'url_path' => [ '0', 'ĐƯỜNG_DẪN', 'ĐƯỜNGDẪN', 'PATH' ], 'url_query' => [ '0', 'TRUY_VẤN', 'TRUYVẤN', 'QUERY' ], 'defaultsort_noerror' => [ '0', 'không_lỗi', 'noerror' ], 'defaultsort_noreplace' => [ '0', 'không_thay_thế', 'noreplace' ], 'pagesincategory_all' => [ '0', 'tất_cả', 'all' ], 'pagesincategory_pages' => [ '0', 'trang', 'pages' ], 'pagesincategory_subcats' => [ '0', 'thể_loại_con', 'subcats' ], 'pagesincategory_files' => [ '0', 'tập_tin', 'files' ], ]; $datePreferences = [ 'default', 'vi normal', 'vi spelloutmonth', 'vi shortcolon', 'vi shorth', 'ISO 8601', ]; $defaultDateFormat = 'vi normal'; $dateFormats = [ 'vi normal time' => 'H:i', 'vi normal date' => '"ngày" j "tháng" n "năm" Y', 'vi normal both' => 'H:i, "ngày" j "tháng" n "năm" Y', 'vi spelloutmonth time' => 'H:i', 'vi spelloutmonth date' => '"ngày" j xg "năm" Y', 'vi spelloutmonth both' => 'H:i, "ngày" j xg "năm" Y', 'vi shortcolon time' => 'H:i', 'vi shortcolon date' => 'j/n/Y', 'vi shortcolon both' => 'H:i, j/n/Y', 'vi shorth time' => 'H"h"i', 'vi shorth date' => 'j/n/Y', 'vi shorth both' => 'H"h"i, j/n/Y', ]; $datePreferenceMigrationMap = [ 'default', 'vi normal', 'vi normal', 'vi normal', ]; $linkTrail = "/^([a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]+)(.*)$/sDu"; $separatorTransformTable = [ ',' => '.', '.' => ',' ];
gpl-2.0
ThomasXBMC/XCSoar
src/Profile/DeviceConfig.cpp
8736
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2015 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #include "DeviceConfig.hpp" #include "Map.hpp" #include "Util/Macros.hpp" #include "Interface.hpp" #include "Device/Config.hpp" #ifdef ANDROID #include "Android/BluetoothHelper.hpp" #include "Java/Global.hxx" #endif #include <stdio.h> static const char *const port_type_strings[] = { "disabled", "serial", "rfcomm", "rfcomm_server", "ioio_uart", "droidsoar_v2", "nunchuck", "i2c_baro", "ioio_voltage", "auto", "internal", "tcp_client", "tcp_listener", "udp_listener", "pty", NULL }; static const char * MakeDeviceSettingName(char *buffer, const char *prefix, unsigned n, const char *suffix) { strcpy(buffer, prefix); if (n > 0) sprintf(buffer + strlen(buffer), "%u", n + 1); strcat(buffer, suffix); return buffer; } static bool StringToPortType(const char *value, DeviceConfig::PortType &type) { for (auto i = port_type_strings; *i != NULL; ++i) { if (StringIsEqual(value, *i)) { type = (DeviceConfig::PortType)std::distance(port_type_strings, i); return true; } } return false; } static bool ReadPortType(const ProfileMap &map, unsigned n, DeviceConfig::PortType &type) { char name[64]; MakeDeviceSettingName(name, "Port", n, "Type"); const char *value = map.Get(name); return value != NULL && StringToPortType(value, type); } static bool LoadPath(const ProfileMap &map, DeviceConfig &config, unsigned n) { char buffer[64]; MakeDeviceSettingName(buffer, "Port", n, "Path"); return map.Get(buffer, config.path); } static bool LoadPortIndex(const ProfileMap &map, DeviceConfig &config, unsigned n) { char buffer[64]; MakeDeviceSettingName(buffer, "Port", n, "Index"); unsigned index; if (!map.Get(buffer, index)) return false; /* adjust the number, compatibility quirk for XCSoar 5 */ if (index < 10) ++index; else if (index == 10) index = 0; TCHAR path[64]; _stprintf(path, _T("COM%u:"), index); config.path = path; return true; } void Profile::GetDeviceConfig(const ProfileMap &map, unsigned n, DeviceConfig &config) { char buffer[64]; bool have_port_type = ReadPortType(map, n, config.port_type); MakeDeviceSettingName(buffer, "Port", n, "BluetoothMAC"); map.Get(buffer, config.bluetooth_mac); MakeDeviceSettingName(buffer, "Port", n, "IOIOUartID"); map.Get(buffer, config.ioio_uart_id); MakeDeviceSettingName(buffer, "Port", n, "IPAddress"); if (!map.Get(buffer, config.ip_address)) config.ip_address.clear(); MakeDeviceSettingName(buffer, "Port", n, "TCPPort"); if (!map.Get(buffer, config.tcp_port)) config.tcp_port = 4353; config.path.clear(); if ((!have_port_type || config.port_type == DeviceConfig::PortType::SERIAL) && !LoadPath(map, config, n) && LoadPortIndex(map, config, n)) config.port_type = DeviceConfig::PortType::SERIAL; MakeDeviceSettingName(buffer, "Port", n, "BaudRate"); if (!map.Get(buffer, config.baud_rate)) { /* XCSoar before 6.2 used to store a "speed index", not the real baud rate - try to import the old settings */ static constexpr unsigned speed_index_table[] = { 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200 }; MakeDeviceSettingName(buffer, "Speed", n, "Index"); unsigned speed_index; if (map.Get(buffer, speed_index) && speed_index < ARRAY_SIZE(speed_index_table)) config.baud_rate = speed_index_table[speed_index]; } MakeDeviceSettingName(buffer, "Port", n, "BulkBaudRate"); if (!map.Get(buffer, config.bulk_baud_rate)) config.bulk_baud_rate = 0; strcpy(buffer, "DeviceA"); buffer[strlen(buffer) - 1] += n; map.Get(buffer, config.driver_name); MakeDeviceSettingName(buffer, "Port", n, "Enabled"); map.Get(buffer, config.enabled); MakeDeviceSettingName(buffer, "Port", n, "SyncFromDevice"); map.Get(buffer, config.sync_from_device); MakeDeviceSettingName(buffer, "Port", n, "SyncToDevice"); map.Get(buffer, config.sync_to_device); MakeDeviceSettingName(buffer, "Port", n, "K6Bt"); map.Get(buffer, config.k6bt); MakeDeviceSettingName(buffer, "Port", n, "I2C_Bus"); map.Get(buffer, config.i2c_bus); MakeDeviceSettingName(buffer, "Port", n, "I2C_Addr"); map.Get(buffer, config.i2c_addr); MakeDeviceSettingName(buffer, "Port", n, "PressureUse"); map.GetEnum(buffer, config.press_use); MakeDeviceSettingName(buffer, "Port", n, "SensorOffset"); map.Get(buffer, config.sensor_offset); MakeDeviceSettingName(buffer, "Port", n, "SensorFactor"); map.Get(buffer, config.sensor_factor); MakeDeviceSettingName(buffer, "Port", n, "UseSecondDevice"); map.Get(buffer, config.use_second_device); MakeDeviceSettingName(buffer, "Port", n, "SecondDevice"); map.Get(buffer, config.driver2_name); } static const char * PortTypeToString(DeviceConfig::PortType type) { const unsigned i = (unsigned)type; return i < ARRAY_SIZE(port_type_strings) ? port_type_strings[i] : NULL; } static void WritePortType(ProfileMap &map, unsigned n, DeviceConfig::PortType type) { const char *value = PortTypeToString(type); if (value == NULL) return; char name[64]; MakeDeviceSettingName(name, "Port", n, "Type"); map.Set(name, value); } void Profile::SetDeviceConfig(ProfileMap &map, unsigned n, const DeviceConfig &config) { char buffer[64]; WritePortType(map, n, config.port_type); MakeDeviceSettingName(buffer, "Port", n, "BluetoothMAC"); map.Set(buffer, config.bluetooth_mac); MakeDeviceSettingName(buffer, "Port", n, "IOIOUartID"); map.Set(buffer, config.ioio_uart_id); MakeDeviceSettingName(buffer, "Port", n, "Path"); map.Set(buffer, config.path); MakeDeviceSettingName(buffer, "Port", n, "BaudRate"); map.Set(buffer, config.baud_rate); MakeDeviceSettingName(buffer, "Port", n, "BulkBaudRate"); map.Set(buffer, config.bulk_baud_rate); MakeDeviceSettingName(buffer, "Port", n, "IPAddress"); map.Set(buffer, config.ip_address); MakeDeviceSettingName(buffer, "Port", n, "TCPPort"); map.Set(buffer, config.tcp_port); strcpy(buffer, "DeviceA"); buffer[strlen(buffer) - 1] += n; map.Set(buffer, config.driver_name); MakeDeviceSettingName(buffer, "Port", n, "Enabled"); map.Set(buffer, config.enabled); MakeDeviceSettingName(buffer, "Port", n, "SyncFromDevice"); map.Set(buffer, config.sync_from_device); MakeDeviceSettingName(buffer, "Port", n, "SyncToDevice"); map.Set(buffer, config.sync_to_device); MakeDeviceSettingName(buffer, "Port", n, "K6Bt"); map.Set(buffer, config.k6bt); MakeDeviceSettingName(buffer, "Port", n, "I2C_Bus"); map.Set(buffer, config.i2c_bus); MakeDeviceSettingName(buffer, "Port", n, "I2C_Addr"); map.Set(buffer, config.i2c_addr); MakeDeviceSettingName(buffer, "Port", n, "PressureUse"); map.SetEnum(buffer, config.press_use); MakeDeviceSettingName(buffer, "Port", n, "SensorOffset"); auto offset = DeviceConfig::UsesCalibration(config.port_type) ? config.sensor_offset : fixed(0); // Has new calibration data been delivered ? if (CommonInterface::Basic().sensor_calibration_available) offset = CommonInterface::Basic().sensor_calibration_offset; map.Set(buffer, offset); MakeDeviceSettingName(buffer, "Port", n, "SensorFactor"); auto factor = DeviceConfig::UsesCalibration(config.port_type) ? config.sensor_factor : fixed(0); // Has new calibration data been delivered ? if (CommonInterface::Basic().sensor_calibration_available) factor = CommonInterface::Basic().sensor_calibration_factor; map.Set(buffer, factor); MakeDeviceSettingName(buffer, "Port", n, "UseSecondDevice"); map.Set(buffer, config.use_second_device); MakeDeviceSettingName(buffer, "Port", n, "SecondDevice"); map.Set(buffer, config.driver2_name); }
gpl-2.0
rozion/telemedicine
interface/billing/billing_report.php
45690
<?php // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // WHEN CONVERT THIS TO NEW SECURITY MODEL, NEED TO REMOVE FOLLOWING // AT APPROXIMATELY LINE 377: // $_REQUEST = stripslashes_deep($_REQUEST); // http://open-emr.org/wiki/index.php/Active_Projects#PLAN require_once("../globals.php"); require_once("../../library/acl.inc"); require_once("../../custom/code_types.inc.php"); require_once("$srcdir/patient.inc"); include_once("$srcdir/../interface/reports/report.inc.php");//Criteria Section common php page require_once("$srcdir/billrep.inc"); require_once(dirname(__FILE__) . "/../../library/classes/OFX.class.php"); require_once(dirname(__FILE__) . "/../../library/classes/X12Partner.class.php"); require_once("$srcdir/formatting.inc.php"); require_once("$srcdir/options.inc.php"); require_once("adjustment_reason_codes.php"); $EXPORT_INC = "$webserver_root/custom/BillingExport.php"; $alertmsg = ''; if ($_POST['mode'] == 'export') { $sql = ReturnOFXSql(); $db = get_db(); $results = $db->Execute($sql); $billings = array(); if ($results->RecordCount() == 0) { echo xl("No Bills Found to Include in OFX Export<br>"); } else { while(!$results->EOF) { $billings[] = $results->fields; $results->MoveNext(); } $ofx = new OFX($billings); header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Disposition: attachment; filename=openemr_ofx.ofx"); header("Content-Type: text/xml"); echo $ofx->get_OFX(); exit; } } // This is obsolete. if ($_POST['mode'] == 'process') { if (exec("ps x | grep 'process_bills[.]php'")) { $alertmsg = xl('Request ignored - claims processing is already running!'); } else { exec("cd $webserver_root/library/freeb;" . "php -q process_bills.php bill > process_bills.log 2>&1 &"); $alertmsg = xl('Batch processing initiated; this may take a while.'); } } //global variables: if (!isset($_POST["mode"])) { $from_date = isset($_POST['from_date']) ? $_POST['from_date'] : date('Y-m-d'); $to_date = isset($_POST['to_date' ]) ? $_POST['to_date' ] : ''; $code_type = isset($_POST['code_type']) ? $_POST['code_type'] : 'all'; $unbilled = isset($_POST['unbilled' ]) ? $_POST['unbilled' ] : 'on'; $my_authorized = $_POST["authorized"]; } else { $from_date = $_POST["from_date"]; $to_date = $_POST["to_date"]; $code_type = $_POST["code_type"]; $unbilled = $_POST["unbilled"]; $my_authorized = $_POST["authorized"]; } // This tells us if only encounters that appear to be missing a "25" modifier // are to be reported. $missing_mods_only = !empty($_POST['missing_mods_only']); /* $from_date = isset($_POST['from_date']) ? $_POST['from_date'] : date('Y-m-d'); $to_date = empty($_POST['to_date' ]) ? $from_date : $_POST['to_date']; $code_type = isset($_POST['code_type']) ? $_POST['code_type'] : 'all'; $unbilled = isset($_POST['unbilled' ]) ? $_POST['unbilled' ] : 'on'; $my_authorized = $_POST["authorized"]; */ $left_margin = isset($_POST["left_margin"]) ? $_POST["left_margin"] : 24; $top_margin = isset($_POST["top_margin"] ) ? $_POST["top_margin" ] : 20; $ofrom_date = $from_date; $oto_date = $to_date; $ocode_type = $code_type; $ounbilled = $unbilled; $oauthorized = $my_authorized; ?> <html> <head> <?php if (function_exists(html_header_show)) html_header_show(); ?> <link rel="stylesheet" href="<?php echo $css_header; ?>" type="text/css"> <style> .subbtn { margin-top:3px; margin-bottom:3px; margin-left:2px; margin-right:2px } </style> <script> function select_all() { for($i=0;$i < document.update_form.length;$i++) { $name = document.update_form[$i].name; if ($name.substring(0,7) == "claims[" && $name.substring($name.length -6) == "[bill]") { document.update_form[$i].checked = true; } } set_button_states(); } function set_button_states() { var f = document.update_form; var count0 = 0; // selected and not billed or queued var count1 = 0; // selected and queued var count2 = 0; // selected and billed for($i = 0; $i < f.length; ++$i) { $name = f[$i].name; if ($name.substring(0, 7) == "claims[" && $name.substring($name.length -6) == "[bill]" && f[$i].checked == true) { if (f[$i].value == '0') ++count0; else if (f[$i].value == '1' || f[$i].value == '5') ++count1; else ++count2; } } var can_generate = (count0 > 0 || count1 > 0 || count2 > 0); var can_mark = (count1 > 0 || count0 > 0 || count2 > 0); var can_bill = (count0 == 0 && count1 == 0 && count2 > 0); <?php if (file_exists($EXPORT_INC)) { ?> f.bn_external.disabled = !can_generate; <?php } else { ?> // f.bn_hcfa_print.disabled = !can_generate; // f.bn_hcfa.disabled = !can_generate; // f.bn_ub92_print.disabled = !can_generate; // f.bn_ub92.disabled = !can_generate; f.bn_x12.disabled = !can_generate; <?php if ($GLOBALS['support_encounter_claims']) { ?> f.bn_x12_encounter.disabled = !can_generate; <?php } ?> f.bn_process_hcfa.disabled = !can_generate; f.bn_hcfa_txt_file.disabled = !can_generate; // f.bn_electronic_file.disabled = !can_bill; f.bn_reopen.disabled = !can_bill; <?php } ?> f.bn_mark.disabled = !can_mark; } // Process a click to go to an encounter. function toencounter(pid, pubpid, pname, enc, datestr, dobstr) { top.restoreSession(); <?php if ($GLOBALS['concurrent_layout']) { ?> var othername = (window.name == 'RTop') ? 'RBot' : 'RTop'; parent.left_nav.setPatient(pname,pid,pubpid,'',dobstr); parent.left_nav.setEncounter(datestr, enc, othername); parent.left_nav.setRadio(othername, 'enc'); parent.frames[othername].location.href = '../patient_file/encounter/encounter_top.php?set_encounter=' + enc + '&pid=' + pid; <?php } else { ?> location.href = '../patient_file/encounter/patient_encounter.php?set_encounter=' + enc + '&pid=' + pid; <?php } ?> } // Process a click to go to an patient. function topatient(pid, pubpid, pname, enc, datestr, dobstr) { top.restoreSession(); <?php if ($GLOBALS['concurrent_layout']) { ?> var othername = (window.name == 'RTop') ? 'RBot' : 'RTop'; parent.left_nav.setPatient(pname,pid,pubpid,'',dobstr); parent.frames[othername].location.href = '../patient_file/summary/demographics_full.php?pid=' + pid; <?php } else { ?> location.href = '../patient_file/summary/demographics_full.php?pid=' + pid; <?php } ?> } </script> <script language="javascript" type="text/javascript"> EncounterDateArray=new Array; CalendarCategoryArray=new Array; EncounterIdArray=new Array; function SubmitTheScreen() {//Action on Update List link if(!ProcessBeforeSubmitting()) return false; top.restoreSession(); document.the_form.mode.value='change'; document.the_form.target='_self'; document.the_form.action='billing_report.php'; document.the_form.submit(); return true; } function SubmitTheScreenPrint() {//Action on View Printable Report link if(!ProcessBeforeSubmitting()) return false; top.restoreSession(); document.the_form.target='new'; document.the_form.action='print_billing_report.php'; document.the_form.submit(); return true; } function SubmitTheScreenExportOFX() {//Action on Export OFX link if(!ProcessBeforeSubmitting()) return false; top.restoreSession(); document.the_form.mode.value='export'; document.the_form.target='_self'; document.the_form.action='billing_report.php'; document.the_form.submit(); return true; } function TestExpandCollapse() {//Checks whether the Expand All, Collapse All labels need to be placed.If any result set is there these will be placed. var set=-1; for(i=1;i<=document.getElementById("divnos").value;i++) { var ele = document.getElementById("divid_"+i); if(ele) { set=1; break; } } if(set==-1) { if(document.getElementById("ExpandAll")) { document.getElementById("ExpandAll").innerHTML=''; document.getElementById("CollapseAll").innerHTML=''; } } } function expandcollapse(atr){ if(atr == "expand") {//Called in the Expand All, Collapse All links(All items will be expanded or collapsed) for(i=1;i<=document.getElementById("divnos").value;i++){ var mydivid="divid_"+i;var myspanid="spanid_"+i; var ele = document.getElementById(mydivid); var text = document.getElementById(myspanid); if(ele) { ele.style.display = "inline";text.innerHTML = "<?php echo htmlspecialchars(xl('Collapse'), ENT_QUOTES); ?>"; } } } else { for(i=1;i<=document.getElementById("divnos").value;i++){ var mydivid="divid_"+i;var myspanid="spanid_"+i; var ele = document.getElementById(mydivid); var text = document.getElementById(myspanid); if(ele) { ele.style.display = "none"; text.innerHTML = "<?php echo htmlspecialchars(xl('Expand'), ENT_QUOTES); ?>"; } } } } function divtoggle(spanid, divid) {//Called in the Expand, Collapse links(This is for a single item) var ele = document.getElementById(divid); if(ele) { var text = document.getElementById(spanid); if(ele.style.display == "inline") { ele.style.display = "none"; text.innerHTML = "<?php echo htmlspecialchars(xl('Expand'), ENT_QUOTES); ?>"; } else { ele.style.display = "inline"; text.innerHTML = "<?php echo htmlspecialchars(xl('Collapse'), ENT_QUOTES); ?>"; } } } function MarkAsCleared(Type) { CheckBoxBillingCount=0; for (var CheckBoxBillingIndex =0; ; CheckBoxBillingIndex++) { CheckBoxBillingObject=document.getElementById('CheckBoxBilling'+CheckBoxBillingIndex); if(!CheckBoxBillingObject) break; if(CheckBoxBillingObject.checked) { ++CheckBoxBillingCount; } } if(Type==1) { Message='<?php echo htmlspecialchars( xl('After saving your batch, click [View Log] to check for errors.'), ENT_QUOTES); ?>'; } if(Type==2) { Message='<?php echo htmlspecialchars( xl('After saving the PDF, click [View Log] to check for errors.'), ENT_QUOTES); ?>'; } if(Type==3) { Message='<?php echo htmlspecialchars( xl('After saving the TEXT file(s), click [View Log] to check for errors.'), ENT_QUOTES); ?>'; } if(confirm(Message + "\n\n\n<?php echo htmlspecialchars( xl('Total'), ENT_QUOTES); ?>" + ' ' + CheckBoxBillingCount + ' ' + "<?php echo htmlspecialchars( xl('Selected'), ENT_QUOTES); ?>\n" + "<?php echo htmlspecialchars( xl('Would You Like them to be Marked as Cleared.'), ENT_QUOTES); ?>")) { document.getElementById('HiddenMarkAsCleared').value='yes'; } else { document.getElementById('HiddenMarkAsCleared').value=''; } } </script> <?php include_once("$srcdir/../interface/reports/report.script.php"); ?><!-- Criteria Section common javascript page--> <!-- ================================================== --> <!-- =============Included for Insurance ajax criteria==== --> <!-- ================================================== --> <script type="text/javascript" src="../../library/js/jquery.1.3.2.js"></script> <?php include_once("{$GLOBALS['srcdir']}/ajax/payment_ajax_jav.inc.php"); ?> <script type="text/javascript" src="../../library/js/common.js"></script> <style> #ajax_div_insurance { position: absolute; z-index:10; background-color: #FBFDD0; border: 1px solid #ccc; padding: 10px; } </style> <script language="javascript" type="text/javascript"> document.onclick=TakeActionOnHide; </script> <!-- ================================================== --> <!-- =============Included for Insurance ajax criteria==== --> <!-- ================================================== --> </head> <body class="body_top" onLoad="TestExpandCollapse()"> <p style='margin-top:5px;margin-bottom:5px;margin-left:5px'> <?php if ($GLOBALS['concurrent_layout']) { ?> <font class='title'><?php xl('Billing Manager','e') ?></font> <?php } else if ($userauthorized) { ?> <a href="../main/main.php" target='Main' onclick='top.restoreSession()'><font class=title><?php xl('Billing Manager','e') ?></font><font class=more> <?php echo $tback; ?></font></a> <?php } else { ?> <a href="../main/onotes/office_comments.php" target='Main' onclick='top.restoreSession()'><font class=title><?php xl('Billing Manager','e') ?></font><font class=more><?php echo $tback; ?></font></a> <?php } ?> </p> <form name='the_form' method='post' action='billing_report.php' onsubmit='return top.restoreSession()' style="display:inline"> <style type="text/css">@import url(../../library/dynarch_calendar.css);</style> <script type="text/javascript" src="../../library/dialog.js"></script> <script type="text/javascript" src="../../library/textformat.js"></script> <script type="text/javascript" src="../../library/dynarch_calendar.js"></script> <?php include_once("{$GLOBALS['srcdir']}/dynarch_calendar_en.inc.php"); ?> <script type="text/javascript" src="../../library/dynarch_calendar_setup.js"></script> <script language='JavaScript'> var mypcc = '1'; </script> <input type='hidden' name='mode' value='change'> <!-- ============================================================================================================================================= --> <!-- Criteria section Starts --> <!-- ============================================================================================================================================= --> <?php //The following are the search criteria per page.All the following variable which ends with 'Master' need to be filled properly. //Each item is seperated by a comma(,). //$ThisPageSearchCriteriaDisplayMaster ==>It is the display on screen for the set of criteria. //$ThisPageSearchCriteriaKeyMaster ==>Corresponding database fields in the same order. //$ThisPageSearchCriteriaDataTypeMaster ==>Corresponding data type in the same order. $_REQUEST = stripslashes_deep($_REQUEST);//To deal with magic quotes on. $ThisPageSearchCriteriaDisplayRadioMaster=array(); $ThisPageSearchCriteriaRadioKeyMaster=array(); $ThisPageSearchCriteriaQueryDropDownMaster=array(); $ThisPageSearchCriteriaQueryDropDownMasterDefault=array(); $ThisPageSearchCriteriaQueryDropDownMasterDefaultKey=array(); $ThisPageSearchCriteriaIncludeMaster=array(); $ThisPageSearchCriteriaDisplayMaster="Date of Service,Date of Entry,Date of Billing,Claim Type,Patient Name,". "Patient Id,Insurance Company,Encounter,Whether Insured,Charge Coded,Billing Status,". "Authorization Status,Last Level Billed,X12 Partner"; $ThisPageSearchCriteriaKeyMaster="form_encounter.date,billing.date,claims.process_time,claims.target,patient_data.fname,". "form_encounter.pid,claims.payer_id,form_encounter.encounter,insurance_data.provider,billing.id,billing.billed,". "billing.authorized,form_encounter.last_level_billed,billing.x12_partner_id"; $ThisPageSearchCriteriaDataTypeMaster="datetime,datetime,datetime,radio,text_like,". "text,include,text,radio,radio,radio,". "radio_like,radio,query_drop_down"; //The below section is needed if there is any 'radio' or 'radio_like' type in the $ThisPageSearchCriteriaDataTypeMaster //$ThisPageSearchCriteriaDisplayRadioMaster,$ThisPageSearchCriteriaRadioKeyMaster ==>For each radio data type this pair comes. //The key value 'all' indicates that no action need to be taken based on this.For that the key must be 'all'.Display value can be any thing. $ThisPageSearchCriteriaDisplayRadioMaster[1]="All,eClaims,Paper";//Display Value $ThisPageSearchCriteriaRadioKeyMaster[1]="all,standard,hcfa";//Key $ThisPageSearchCriteriaDisplayRadioMaster[2]="All,Insured,Non-Insured";//Display Value $ThisPageSearchCriteriaRadioKeyMaster[2]="all,1,0";//Key $ThisPageSearchCriteriaDisplayRadioMaster[3]="All,Coded,Not Coded";//Display Value $ThisPageSearchCriteriaRadioKeyMaster[3]="all,not null,null";//Key $ThisPageSearchCriteriaDisplayRadioMaster[4]="All,Unbilled,Billed,Denied";//Display Value $ThisPageSearchCriteriaRadioKeyMaster[4]="all,0,1,7";//Key $ThisPageSearchCriteriaDisplayRadioMaster[5]="All,Authorized,Unauthorized"; $ThisPageSearchCriteriaRadioKeyMaster[5]="%,1,0"; $ThisPageSearchCriteriaDisplayRadioMaster[6]="All,None,Ins 1,Ins 2 or Ins 3"; $ThisPageSearchCriteriaRadioKeyMaster[6]="all,0,1,2"; //The below section is needed if there is any 'query_drop_down' type in the $ThisPageSearchCriteriaDataTypeMaster $ThisPageSearchCriteriaQueryDropDownMaster[1]="SELECT name,id FROM x12_partners;"; $ThisPageSearchCriteriaQueryDropDownMasterDefault[1]="All";//Only one item will be here $ThisPageSearchCriteriaQueryDropDownMasterDefaultKey[1]="all";//Only one item will be here //The below section is needed if there is any 'include' type in the $ThisPageSearchCriteriaDataTypeMaster //Function name is added here.Corresponding include files need to be included in the respective pages as done in this page. //It is labled(Included for Insurance ajax criteria)(Line:-279-299). $ThisPageSearchCriteriaIncludeMaster[1]="InsuranceCompanyDisplay";//This is php function defined in the file 'report.inc.php' if(!isset($_REQUEST['mode']))//default case { $_REQUEST['final_this_page_criteria'][0]="(form_encounter.date between '".date("Y-m-d 00:00:00")."' and '".date("Y-m-d 23:59:59")."')"; $_REQUEST['final_this_page_criteria'][1]="billing.billed = '0'"; $_REQUEST['final_this_page_criteria_text'][0]=htmlspecialchars(xl("Date of Service = Today"), ENT_QUOTES); $_REQUEST['final_this_page_criteria_text'][1]=htmlspecialchars(xl("Billing Status = Unbilled"), ENT_QUOTES); $_REQUEST['date_master_criteria_form_encounter_date']="today"; $_REQUEST['master_from_date_form_encounter_date']=date("Y-m-d"); $_REQUEST['master_to_date_form_encounter_date']=date("Y-m-d"); $_REQUEST['radio_billing_billed']=0; } ?> <table width='100%' border="0" cellspacing="0" cellpadding="0"> <tr> <td width="25%">&nbsp;</td> <td width="50%"> <?php include_once("$srcdir/../interface/reports/criteria.tab.php"); ?> </td> <td width="25%"> <?php // ============================================================================================================================================= --> // Criteria section Ends --> // ============================================================================================================================================= --> ?> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="15%">&nbsp;</td> <td width="85%"><span class='text'><a onClick="javascript:return SubmitTheScreen();" href="#" class=link_submit>[<?php echo htmlspecialchars(xl('Update List'), ENT_QUOTES) ?>]</a> or <a onClick="javascript:return SubmitTheScreenExportOFX();" href="#" class='link_submit'><?php echo htmlspecialchars(xl('[Export OFX]'), ENT_QUOTES) ?></a></span> </td> </tr> <tr> <td>&nbsp;</td> <td><a onClick="javascript:return SubmitTheScreenPrint();" href="#" class='link_submit' ><?php echo htmlspecialchars(xl('[View Printable Report]'), ENT_QUOTES) ?></a></td> </tr> <tr> <td>&nbsp;</td> <td> <?php $acct_config = $GLOBALS['oer_config']['ws_accounting']; if($acct_config['enabled']) { if($acct_config['enabled'] !== 2) { print '<span class=text><a href="javascript:void window.open(\'' . $acct_config['url_path'] . '\')">' . htmlspecialchars(xl("[SQL-Ledger]"), ENT_QUOTES) . '</a> &nbsp; </span>'; } if (acl_check('acct', 'rep')) { print '<span class=text><a href="javascript:void window.open(\'sl_receipts_report.php\')" onclick="top.restoreSession()">' . htmlspecialchars(xl('[Reports]'), ENT_QUOTES) . '</a> &nbsp; </span>'; } if (acl_check('acct', 'eob')) { print '<span class=text><a href="javascript:void window.open(\'sl_eob_search.php\')" onclick="top.restoreSession()">' . htmlspecialchars(xl('[EOBs]'), ENT_QUOTES) . '</a></span>'; } } ?> </td> </tr> <tr> <td>&nbsp;</td> <td> <?php if (! file_exists($EXPORT_INC)) { ?> <!-- <a href="javascript:top.restoreSession();document.the_form.mode.value='process';document.the_form.submit()" class="link_submit" title="Process all queued bills to create electronic data (and print if requested)"><?php echo htmlspecialchars(xl('[Start Batch Processing]'), ENT_QUOTES) ?></a> &nbsp; --> <a href='../../library/freeb/process_bills.php' target='_blank' class='link_submit' title='<?php htmlspecialchars(xl('See messages from the last set of generated claims'), ENT_QUOTES); ?>'><?php echo htmlspecialchars(xl('[View Log]'), ENT_QUOTES) ?></a> <?php } ?> </td> </tr> <tr> <td>&nbsp;</td> <td><a href="javascript:select_all()" class="link_submit"><?php echo htmlspecialchars(xl('[Select All]','e'), ENT_QUOTES) ?></a></td> </tr> </table> </td> </tr> </table> <table width='100%' border="0" cellspacing="0" cellpadding="0" > <tr> <td> <hr color="#000000"> </td> </tr> </table> </form> <form name='update_form' method='post' action='billing_process.php' onsubmit='return top.restoreSession()' style="display:inline"> <center> <span class='text' style="display:inline"> <?php if (file_exists($EXPORT_INC)) { ?> <input type="submit" class="subbtn" name="bn_external" value="Export Billing" title="<?php xl('Export to external billing system','e') ?>"> <input type="submit" class="subbtn" name="bn_mark" value="Mark as Cleared" title="<?php xl('Mark as billed but skip billing','e') ?>"> <?php } else { ?> <!-- <input type="submit" class="subbtn" name="bn_hcfa_print" value="Queue HCFA &amp; Print" title="<?php xl('Queue for HCFA batch processing and printing','e') ?>"> <input type="submit" class="subbtn" name="bn_hcfa" value="Queue HCFA" title="<?php xl('Queue for HCFA batch processing','e')?>"> <input type="submit" class="subbtn" name="bn_ub92_print" value="Queue UB92 &amp; Print" title="<?php xl('Queue for UB-92 batch processing and printing','e')?>"> <input type="submit" class="subbtn" name="bn_ub92" value="Queue UB92" title="<?php xl('Queue for UB-92 batch processing','e')?>"> --> <input type="submit" class="subbtn" name="bn_x12" value="<?php xl('Generate X12','e')?>" title="<?php xl('Generate and download X12 batch','e')?>" onclick="MarkAsCleared(1)"> <?php if ($GLOBALS['support_encounter_claims']) { ?> <input type="submit" class="subbtn" name="bn_x12_encounter" value="<?php xl('Generate X12 Encounter','e')?>" title="<?php xl('Generate and download X12 encounter claim batch','e')?>" onclick="MarkAsCleared(1)"> <?php } ?> <input type="submit" class="subbtn" style="width:175px;" name="bn_process_hcfa" value="<?php xl('Generate CMS 1500 PDF','e')?>" title="<?php xl('Generate and download CMS 1500 paper claims','e')?>" onclick="MarkAsCleared(2)"> <input type="submit" class="subbtn" style="width:175px;" name="bn_hcfa_txt_file" value="<?php xl('Generate CMS 1500 TEXT','e')?>" title="<?php xl('Making batch text files for uploading to Clearing House and will mark as billed', 'e')?>" onclick="MarkAsCleared(3)"> <input type="submit" class="subbtn" name="bn_mark" value="<?php xl('Mark as Cleared','e')?>" title="<?php xl('Post to accounting and mark as billed','e')?>"> <input type="submit" class="subbtn" name="bn_reopen" value="<?php xl('Re-Open','e')?>" title="<?php xl('Mark as not billed','e')?>"> <!-- <input type="submit" class="subbtn" name="bn_electronic_file" value="Make Electronic Batch &amp; Clear" title="<?php xl('Download billing file, post to accounting and mark as billed','e')?>"> --> &nbsp;&nbsp;&nbsp; <?php xl('CMS 1500 Margins','e'); ?>: &nbsp;<?php xl('Left','e'); ?>: <input type='text' size='2' name='left_margin' value='<?php echo $left_margin; ?>' title=<?php xl('HCFA left margin in points','e','\'','\''); ?> /> &nbsp;<?php xl('Top','e'); ?>: <input type='text' size='2' name='top_margin' value='<?php echo $top_margin; ?>' title=<?php xl('HCFA top margin in points','e','\'','\''); ?> /> </span> <?php } ?> </center> <input type='hidden' name='HiddenMarkAsCleared' id='HiddenMarkAsCleared' value="" /> <input type='hidden' name='mode' value="bill" /> <input type='hidden' name='authorized' value="<?php echo $my_authorized; ?>" /> <input type='hidden' name='unbilled' value="<?php echo $unbilled; ?>" /> <input type='hidden' name='code_type' value="%" /> <input type='hidden' name='to_date' value="<?php echo $to_date; ?>" /> <input type='hidden' name='from_date' value="<?php echo $from_date; ?>" /> <?php if ($my_authorized == "on" ) { $my_authorized = "1"; } else { $my_authorized = "%"; } if ($unbilled == "on") { $unbilled = "0"; } else { $unbilled = "%"; } $list = getBillsListBetween("%"); ?> <input type='hidden' name='bill_list' value="<?php echo $list; ?>" /> <!-- new form for uploading --> <?php if (!isset($_POST["mode"])) { if (!isset($_POST["from_date"])) { $from_date = date("Y-m-d"); } else { $from_date = $_POST["from_date"]; } if (empty($_POST["to_date"])) { $to_date = ''; } else { $to_date = $_POST["to_date"]; } if (!isset($_POST["code_type"])) { $code_type="all"; } else { $code_type = $_POST["code_type"]; } if (!isset($_POST["unbilled"])) { $unbilled = "on"; } else { $unbilled = $_POST["unbilled"]; } if (!isset($_POST["authorized"])) { $my_authorized = "on"; } else { $my_authorized = $_POST["authorized"]; } } else { $from_date = $_POST["from_date"]; $to_date = $_POST["to_date"]; $code_type = $_POST["code_type"]; $unbilled = $_POST["unbilled"]; $my_authorized = $_POST["authorized"]; } if ($my_authorized == "on" ) { $my_authorized = "1"; } else { $my_authorized = "%"; } if ($unbilled == "on") { $unbilled = "0"; } else { $unbilled = "%"; } if (isset($_POST["mode"]) && $_POST["mode"] == "bill") { billCodesList($list); } ?> <table border="0" cellspacing="0" cellpadding="0" width="100%"> <?php if ($ret = getBillsBetween("%")) { if(is_array($ret)) { ?> <tr ><td colspan='8' align="right" ><table width="250" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="100" id='ExpandAll'><a onclick="expandcollapse('expand');" class='small' href="JavaScript:void(0);"><?php echo '('.htmlspecialchars( xl('Expand All'), ENT_QUOTES).')' ?></a></td> <td width="100" id='CollapseAll'><a onclick="expandcollapse('collapse');" class='small' href="JavaScript:void(0);"><?php echo '('.htmlspecialchars( xl('Collapse All'), ENT_QUOTES).')' ?></a></td> <td width="50">&nbsp;</td> </tr> </table> </td></tr> <?php } $loop = 0; $oldcode = ""; $last_encounter_id = ""; $lhtml = ""; $rhtml = ""; $lcount = 0; $rcount = 0; $bgcolor = ""; $skipping = FALSE; $mmo_empty_mod = false; $mmo_num_charges = 0; $divnos=0; foreach ($ret as $iter) { // We include encounters here that have never been billed. However // if it had no selected billing items but does have non-selected // billing items, then it is not of interest. if (!$iter['id']) { $res = sqlQuery("SELECT count(*) AS count FROM billing WHERE " . "encounter = '" . $iter['enc_encounter'] . "' AND " . "pid='" . $iter['enc_pid'] . "' AND " . "activity = 1"); if ($res['count'] > 0) continue; } $this_encounter_id = $iter['enc_pid'] . "-" . $iter['enc_encounter']; if ($last_encounter_id != $this_encounter_id) { // This dumps all HTML for the previous encounter. // if ($lhtml) { while ($rcount < $lcount) { $rhtml .= "<tr bgcolor='$bgcolor'><td colspan='7'></td></tr>"; ++$rcount; } // This test handles the case where we are only listing encounters // that appear to have a missing "25" modifier. if (!$missing_mods_only || ($mmo_empty_mod && $mmo_num_charges > 1)) { if($DivPut=='yes') { $lhtml.='</div>'; $DivPut='no'; } echo "<tr bgcolor='$bgcolor'>\n<td rowspan='$rcount' valign='top'>\n$lhtml</td>$rhtml\n"; echo "<tr bgcolor='$bgcolor'><td colspan='8' height='5'></td></tr>\n\n"; ++$encount; } } $lhtml = ""; $rhtml = ""; $mmo_empty_mod = false; $mmo_num_charges = 0; // If there are ANY unauthorized items in this encounter and this is // the normal case of viewing only authorized billing, then skip the // entire encounter. // $skipping = FALSE; if ($my_authorized == '1') { $res = sqlQuery("select count(*) as count from billing where " . "encounter = '" . $iter['enc_encounter'] . "' and " . "pid='" . $iter['enc_pid'] . "' and " . "activity = 1 and authorized = 0"); if ($res['count'] > 0) { $skipping = TRUE; $last_encounter_id = $this_encounter_id; continue; } } $name = getPatientData($iter['enc_pid'], "fname, mname, lname, pubpid, DATE_FORMAT(DOB,'%Y-%m-%d') as DOB_YMD"); # Check if patient has primary insurance and a subscriber exists for it. # If not we will highlight their name in red. # TBD: more checking here. # $res = sqlQuery("select count(*) as count from insurance_data where " . "pid = " . $iter['enc_pid'] . " and " . "type='primary' and " . "subscriber_lname is not null and " . "subscriber_lname != '' limit 1"); $namecolor = ($res['count'] > 0) ? "black" : "#ff7777"; $bgcolor = "#" . (($encount & 1) ? "ddddff" : "ffdddd"); echo "<tr bgcolor='$bgcolor'><td colspan='8' height='5'></td></tr>\n"; $lcount = 1; $rcount = 0; $oldcode = ""; $ptname = $name['fname'] . " " . $name['lname']; $raw_encounter_date = date("Y-m-d", strtotime($iter['enc_date'])); // Add Encounter Date to display with "To Encounter" button 2/17/09 JCH $lhtml .= "&nbsp;<span class=bold><font color='$namecolor'>$ptname" . "</font></span><span class=small>&nbsp;(" . $iter['enc_pid'] . "-" . $iter['enc_encounter'] . ")</span>"; //Encounter details are stored to javacript as array. $result4 = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe ". " left join openemr_postcalendar_categories on fe.pc_catid=openemr_postcalendar_categories.pc_catid WHERE fe.pid = '".$iter['enc_pid']."' order by fe.date desc"); if(sqlNumRows($result4)>0) ?> <script language='JavaScript'> Count=0; EncounterDateArray[<?php echo $iter['enc_pid']; ?>]=new Array; CalendarCategoryArray[<?php echo $iter['enc_pid']; ?>]=new Array; EncounterIdArray[<?php echo $iter['enc_pid']; ?>]=new Array; <?php while($rowresult4 = sqlFetchArray($result4)) { ?> EncounterIdArray[<?php echo $iter['enc_pid']; ?>][Count]='<?php echo htmlspecialchars($rowresult4['encounter'], ENT_QUOTES); ?>'; EncounterDateArray[<?php echo $iter['enc_pid']; ?>][Count]='<?php echo htmlspecialchars(oeFormatShortDate(date("Y-m-d", strtotime($rowresult4['date']))), ENT_QUOTES); ?>'; CalendarCategoryArray[<?php echo $iter['enc_pid']; ?>][Count]='<?php echo htmlspecialchars( xl_appt_category($rowresult4['pc_catname']), ENT_QUOTES); ?>'; Count++; <?php } ?> </script> <?php // Not sure why the next section seems to do nothing except post "To Encounter" button 2/17/09 JCH $lhtml .= "&nbsp;&nbsp;&nbsp;<a class=\"link_submit\" " . "href=\"javascript:window.toencounter(" . $iter['enc_pid'] . ",'" . addslashes($name['pubpid']) . "','" . addslashes($ptname) . "'," . $iter['enc_encounter'] . ",'" . oeFormatShortDate($raw_encounter_date) . "',' " . xl('DOB') . ": " . oeFormatShortDate($name['DOB_YMD']) . " " . xl('Age') . ": " . getPatientAge($name['DOB_YMD']) . "'); top.window.parent.left_nav.setPatientEncounter(EncounterIdArray[" . $iter['enc_pid'] . "],EncounterDateArray[" . $iter['enc_pid'] . "], CalendarCategoryArray[" . $iter['enc_pid'] . "])\">[" . xl('To Enctr') . " " . oeFormatShortDate($raw_encounter_date) . "]</a>"; // Changed "To xxx" buttons to allow room for encounter date display 2/17/09 JCH $lhtml .= "&nbsp;&nbsp;&nbsp;<a class=\"link_submit\" " . "href=\"javascript:window.topatient(" . $iter['enc_pid'] . ",'" . addslashes($name['pubpid']) . "','" . addslashes($ptname) . "'," . $iter['enc_encounter'] . ",'" . oeFormatShortDate($raw_encounter_date) . "',' " . xl('DOB') . ": " . oeFormatShortDate($name['DOB_YMD']) . " " . xl('Age') . ": " . getPatientAge($name['DOB_YMD']) . "'); top.window.parent.left_nav.setPatientEncounter(EncounterIdArray[" . $iter['enc_pid'] . "],EncounterDateArray[" . $iter['enc_pid'] . "], CalendarCategoryArray[" . $iter['enc_pid'] . "])\">[" . xl('To Dems') . "]</a>"; $divnos=$divnos+1; $lhtml .= "&nbsp;&nbsp;&nbsp;<a onclick='divtoggle(\"spanid_$divnos\",\"divid_$divnos\");' class='small' id='aid_$divnos' href=\"JavaScript:void(0);". "\">(<span id=spanid_$divnos class=\"indicator\">" . htmlspecialchars( xl('Expand'), ENT_QUOTES) . "</span>)</a>"; if ($iter['id']) { $lcount += 2; $lhtml .= "<br />\n"; $lhtml .= "&nbsp;<span class=text>Bill: "; $lhtml .= "<select name='claims[" . $this_encounter_id . "][payer]' style='background-color:$bgcolor'>"; $query = "SELECT id.provider AS id, id.type, id.date, " . "ic.x12_default_partner_id AS ic_x12id, ic.name AS provider " . "FROM insurance_data AS id, insurance_companies AS ic WHERE " . "ic.id = id.provider AND " . "id.pid = '" . mysql_escape_string($iter['enc_pid']) . "' AND " . "id.date <= '$raw_encounter_date' " . "ORDER BY id.type ASC, id.date DESC"; $result = sqlStatement($query); $count = 0; $default_x12_partner = $iter['ic_x12id']; $prevtype = ''; while ($row = mysql_fetch_array($result)) { if (strcmp($row['type'], $prevtype) == 0) continue; $prevtype = $row['type']; if (strlen($row['provider']) > 0) { // This preserves any existing insurance company selection, which is // important when EOB posting has re-queued for secondary billing. $lhtml .= "<option value=\"" . strtoupper(substr($row['type'],0,1)) . $row['id'] . "\""; if (($count == 0 && !$iter['payer_id']) || $row['id'] == $iter['payer_id']) { $lhtml .= " selected"; if (!is_numeric($default_x12_partner)) $default_x12_partner = $row['ic_x12id']; } $lhtml .= ">" . $row['type'] . ": " . $row['provider'] . "</option>"; } $count++; } $lhtml .= "<option value='-1'>Unassigned</option>\n"; $lhtml .= "</select>&nbsp;&nbsp;\n"; $lhtml .= "<select name='claims[" . $this_encounter_id . "][partner]' style='background-color:$bgcolor'>"; $x = new X12Partner(); $partners = $x->_utility_array($x->x12_partner_factory()); foreach ($partners as $xid => $xname) { $lhtml .= '<option label="' . $xname . '" value="' . $xid .'"'; if ($xid == $default_x12_partner) { $lhtml .= "selected"; } $lhtml .= '>' . $xname . '</option>'; } $lhtml .= "</select>"; $DivPut='yes'; $lhtml .= "<br>\n&nbsp;<div id='divid_$divnos' style='display:none'>" . oeFormatShortDate(substr($iter['date'], 0, 10)) . substr($iter['date'], 10, 6) . " " . xl("Encounter was coded"); $query = "SELECT * FROM claims WHERE " . "patient_id = '" . $iter['enc_pid'] . "' AND " . "encounter_id = '" . $iter['enc_encounter'] . "' " . "ORDER BY version"; $cres = sqlStatement($query); $lastcrow = false; while ($crow = sqlFetchArray($cres)) { $query = "SELECT id.type, ic.name " . "FROM insurance_data AS id, insurance_companies AS ic WHERE " . "id.pid = '" . $iter['enc_pid'] . "' AND " . "id.provider = '" . $crow['payer_id'] . "' AND " . "id.date <= '$raw_encounter_date' AND " . "ic.id = id.provider " . "ORDER BY id.type ASC, id.date DESC"; $irow= sqlQuery($query); if ($crow['bill_process']) { $lhtml .= "<br>\n&nbsp;" . oeFormatShortDate(substr($crow['bill_time'], 0, 10)) . substr($crow['bill_time'], 10, 6) . " " . xl("Queued for") . " {$irow['type']} {$crow['target']} " . xl("billing to ") . $irow['name']; ++$lcount; } else if ($crow['status'] < 6) { if ($crow['status'] > 1) { $lhtml .= "<br>\n&nbsp;" . oeFormatShortDate(substr($crow['bill_time'], 0, 10)) . substr($crow['bill_time'], 10, 6) . " " . htmlspecialchars( xl("Marked as cleared"), ENT_QUOTES); ++$lcount; } else { $lhtml .= "<br>\n&nbsp;" . oeFormatShortDate(substr($crow['bill_time'], 0, 10)) . substr($crow['bill_time'], 10, 6) . " " . htmlspecialchars( xl("Re-opened"), ENT_QUOTES); ++$lcount; } } else if ($crow['status'] == 6) { $lhtml .= "<br>\n&nbsp;" . oeFormatShortDate(substr($crow['bill_time'], 0, 10)) . substr($crow['bill_time'], 10, 6) . " " . htmlspecialchars( xl("This claim has been forwarded to next level."), ENT_QUOTES); ++$lcount; } else if ($crow['status'] == 7) { $lhtml .= "<br>\n&nbsp;" . oeFormatShortDate(substr($crow['bill_time'], 0, 10)) . substr($crow['bill_time'], 10, 6) . " " . htmlspecialchars( xl("This claim has been denied.Reason:-"), ENT_QUOTES); if($crow['process_file']) { $code_array=split(',',$crow['process_file']); foreach($code_array as $code_key => $code_value) { $lhtml .= "<br>\n&nbsp;&nbsp;&nbsp;"; $reason_array=split('_',$code_value); if(!isset($adjustment_reasons[$reason_array[3]])) { $lhtml .=htmlspecialchars( xl("For code"), ENT_QUOTES).' ['.$reason_array[0].'] '.htmlspecialchars( xl("and modifier"), ENT_QUOTES).' ['.$reason_array[1].'] '.htmlspecialchars( xl("the Denial code is"), ENT_QUOTES).' ['.$reason_array[2].' '.$reason_array[3].']'; } else { $lhtml .=htmlspecialchars( xl("For code"), ENT_QUOTES).' ['.$reason_array[0].'] '.htmlspecialchars( xl("and modifier"), ENT_QUOTES).' ['.$reason_array[1].'] '.htmlspecialchars( xl("the Denial Group code is"), ENT_QUOTES).' ['.$reason_array[2].'] '.htmlspecialchars( xl("and the Reason is"), ENT_QUOTES).':- '.$adjustment_reasons[$reason_array[3]]; } } } else { $lhtml .=htmlspecialchars( xl("Not Specified."), ENT_QUOTES); } ++$lcount; } if ($crow['process_time']) { $lhtml .= "<br>\n&nbsp;" . oeFormatShortDate(substr($crow['process_time'], 0, 10)) . substr($crow['process_time'], 10, 6) . " " . xl("Claim was generated to file ") . "<a href='get_claim_file.php?key=" . $crow['process_file'] . "' onclick='top.restoreSession()'>" . $crow['process_file'] . "</a>"; ++$lcount; } $lastcrow = $crow; } // end while ($crow = sqlFetchArray($cres)) if ($lastcrow && $lastcrow['status'] == 4) { $lhtml .= "<br>\n&nbsp;This claim has been closed."; ++$lcount; } if ($lastcrow && $lastcrow['status'] == 5) { $lhtml .= "<br>\n&nbsp;This claim has been canceled."; ++$lcount; } } // end if ($iter['id']) } // end if ($last_encounter_id != $this_encounter_id) if ($skipping) continue; // Collect info related to the missing modifiers test. if ($iter['fee'] > 0) { ++$mmo_num_charges; $tmp = substr($iter['code'], 0, 3); if (($tmp == '992' || $tmp == '993') && empty($iter['modifier'])) $mmo_empty_mod = true; } ++$rcount; if ($rhtml) { $rhtml .= "<tr bgcolor='$bgcolor'>\n"; } $rhtml .= "<td width='50'>"; if ($iter['id'] && $oldcode != $iter['code_type']) { $rhtml .= "<span class=text>" . $iter['code_type'] . ": </span>"; } $oldcode = $iter['code_type']; $rhtml .= "</td>\n"; $justify = ""; if ($iter['id'] && $code_types[$iter['code_type']]['just']) { $js = split(":",$iter['justify']); $counter = 0; foreach ($js as $j) { if(!empty($j)) { if ($counter == 0) { $justify .= " (<b>$j</b>)"; } else { $justify .= " ($j)"; } $counter++; } } } $rhtml .= "<td><span class='text'>" . ($iter['code_type'] == 'COPAY' ? oeFormatMoney($iter['code']) : $iter['code']); if ($iter['modifier']) $rhtml .= ":" . $iter['modifier']; $rhtml .= "</span><span style='font-size:8pt;'>$justify</span></td>\n"; $rhtml .= '<td align="right"><span style="font-size:8pt;">&nbsp;&nbsp;&nbsp;'; if ($iter['id'] && $iter['fee'] > 0) { $rhtml .= oeFormatMoney($iter['fee']); } $rhtml .= "</span></td>\n"; $rhtml .= '<td><span style="font-size:8pt;">&nbsp;&nbsp;&nbsp;'; if ($iter['id']) $rhtml .= getProviderName(empty($iter['provider_id']) ? $iter['enc_provider_id'] : $iter['provider_id']); $rhtml .= "</span></td>\n"; $rhtml .= '<td width=100>&nbsp;&nbsp;&nbsp;<span style="font-size:8pt;">'; if ($iter['id']) $rhtml .= oeFormatSDFT(strtotime($iter{"date"})); $rhtml .= "</span></td>\n"; if ($iter['id'] && $iter['authorized'] != 1) { $rhtml .= "<td><span class=alert>".xl("Note: This code was not entered by an authorized user. Only authorized codes may be uploaded to the Open Medical Billing Network for processing. If you wish to upload these codes, please select an authorized user here.")."</span></td>\n"; } else { $rhtml .= "<td></td>\n"; } if ($iter['id'] && $last_encounter_id != $this_encounter_id) { $tmpbpr = $iter['bill_process']; if ($tmpbpr == '0' && $iter['billed']) $tmpbpr = '2'; $rhtml .= "<td><input type='checkbox' value='$tmpbpr' name='claims[" . $this_encounter_id . "][bill]' onclick='set_button_states()' id='CheckBoxBilling" . $CheckBoxBilling*1 . "'>&nbsp;</td>\n"; $CheckBoxBilling++; } else { $rhtml .= "<td></td>\n"; } $rhtml .= "</tr>\n"; $last_encounter_id = $this_encounter_id; } // end foreach if ($lhtml) { while ($rcount < $lcount) { $rhtml .= "<tr bgcolor='$bgcolor'><td colspan='7'></td></tr>"; ++$rcount; } if (!$missing_mods_only || ($mmo_empty_mod && $mmo_num_charges > 1)) { if($DivPut=='yes') { $lhtml.='</div>'; $DivPut='no'; } echo "<tr bgcolor='$bgcolor'>\n<td rowspan='$rcount' valign='top'>\n$lhtml</td>$rhtml\n"; echo "<tr bgcolor='$bgcolor'><td colspan='8' height='5'></td></tr>\n"; } } } ?> </table> </form> <script> set_button_states(); <?php if ($alertmsg) { echo "alert('$alertmsg');\n"; } ?> </script> <input type="hidden" name="divnos" id="divnos" value="<?php echo $divnos ?>"/> <input type='hidden' name='ajax_mode' id='ajax_mode' value='' /> </body> </html>
gpl-2.0
neilbrown/susman
dnotify.py
3660
#!/usr/bin/env python # class to allow watching multiple files and # calling a callback when any change (size or mtime) # # We take exclusive use of SIGIO and maintain a global list of # watched files. # As we cannot get siginfo in python, we check every file # every time we get a signal. # we report change is size, mtime, or ino of the file (given by name) # Copyright (C) 2011 Neil Brown <neilb@suse.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 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import os, fcntl, signal dirlist = [] def notified(sig, stack): for d in dirlist: fcntl.fcntl(d.fd, fcntl.F_NOTIFY, (fcntl.DN_MODIFY|fcntl.DN_RENAME| fcntl.DN_CREATE|fcntl.DN_DELETE)) d.check() class dir(): def __init__(self, dname): self.dname = dname self.fd = os.open(dname, 0) self.files = [] self.callbacks = [] fcntl.fcntl(self.fd, fcntl.F_NOTIFY, (fcntl.DN_MODIFY|fcntl.DN_RENAME| fcntl.DN_CREATE|fcntl.DN_DELETE)) if not dirlist: signal.signal(signal.SIGIO, notified) dirlist.append(self) def watch(self, fname, callback): f = file(os.path.join(self.dname, fname), callback) self.files.append(f) return f def watchall(self, callback): self.callbacks.append(callback) def check(self): newlist = [] for c in self.callbacks: if c(): newlist.append(c) self.callbacks = newlist for f in self.files: f.check() def cancel(self, victim): if victim in self.files: self.files.remove(victim) class file(): def __init__(self, fname, callback): self.name = fname try: stat = os.stat(self.name) except OSError: self.ino = 0 self.size = 0 self.mtime = 0 else: self.ino = stat.st_ino self.size = stat.st_size self.mtime = stat.st_mtime self.callback = callback def check(self): try: stat = os.stat(self.name) except OSError: if self.ino == 0: return False self.size = 0 self.mtime = 0 self.ino = 0 else: if stat.st_size == self.size and stat.st_mtime == self.mtime \ and stat.st_ino == self.ino: return False self.size = stat.st_size self.mtime = stat.st_mtime self.ino = stat.st_ino self.callback(self) return True def cancel(self): global dirlist for d in dirlist: d.cancel(self) if __name__ == "__main__" : import signal ## def ping(f): print "got ", f.name d = dir("/tmp/n") a = d.watch("a", ping) b = d.watch("b", ping) c = d.watch("c", ping) while True: signal.pause()
gpl-2.0
ProjectOverlord/AndroidMusicProject
AudioPlayer/app/src/main/java/com/progettofondamenti/audioplayer/listeners/RewindListener.java
551
package com.progettofondamenti.audioplayer.listeners; import android.view.View; import com.progettofondamenti.audioplayer.IPlayer; /** * Listener for the RewindButton. * * @author team * @see android.view.View.OnClickListener */ public class RewindListener implements View.OnClickListener{ private IPlayer player; /** * RewindListener() * @param player */ public RewindListener(IPlayer player){ super(); this.player = player; } @Override public void onClick(View v) { player.rewind(); } }
gpl-2.0
anhtuan8591/shop
administrator/components/com_acymailing/helpers/acymailer.php
20786
<?php /** * @copyright Copyright (C) 2009-2012 ACYBA SARL - All rights reserved. * @license http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL */ defined('_JEXEC') or die('Restricted access'); ?> <?php require_once(ACYMAILING_FRONT.'inc'.DS.'phpmailer'.DS.'class.phpmailer.php'); class acymailerHelper extends acymailingPHPMailer { var $report = true; var $loadedToSend = true; var $checkConfirmField = true; var $checkEnabled = true; var $checkAccept = true; var $parameters = array(); var $dispatcher; var $errorNumber = 0; var $reportMessage = ''; var $autoAddUser = false; var $errorNewTry = array(1,6); var $app; var $forceTemplate = 0; var $alreadyCheckedAddresses = false; var $checkPublished = true; var $introtext; function acymailerHelper() { JPluginHelper::importPlugin('acymailing'); $this->dispatcher = JDispatcher::getInstance(); $this->app = JFactory::getApplication(); $this->subscriberClass = acymailing_get('class.subscriber'); $this->encodingHelper = acymailing_get('helper.encoding'); $this->userHelper = acymailing_get('helper.user'); $this->config =& acymailing_config(); $this->setFrom($this->config->get('from_email'),$this->config->get('from_name')); $this->Sender = $this->cleanText($this->config->get('bounce_email')); if(empty($this->Sender)) $this->Sender = ''; switch ( $this->config->get('mailer_method','phpmail') ) { case 'smtp' : $this->IsSMTP(); $this->Host = trim($this->config->get('smtp_host')); $port = $this->config->get('smtp_port'); if(empty($port) && $this->config->get('smtp_secured') == 'ssl') $port = 465; if(!empty($port)) $this->Host.= ':'.$port; $this->SMTPAuth = (bool) $this->config->get('smtp_auth',true); $this->Username = trim($this->config->get('smtp_username')); $this->Password = trim($this->config->get('smtp_password')); $this->SMTPSecure = trim((string)$this->config->get('smtp_secured')); if(empty($this->Sender)) $this->Sender = strpos($this->Username,'@') ? $this->Username : $this->config->get('from_email'); break; case 'sendmail' : $this->IsSendmail(); $this->SendMail = trim($this->config->get('sendmail_path')); if(empty($this->SendMail)) $this->SendMail = '/usr/sbin/sendmail'; break; case 'qmail' : $this->IsQmail(); break; case 'elasticemail' : $port = $this->config->get('elasticemail_port','2525'); if(is_numeric($port)){ $this->IsSMTP(); if($port == '25'){ $this->Host = 'smtp25.elasticemail.com:25'; }else{ $this->Host = 'smtp.elasticemail.com:2525'; } $this->Username = trim($this->config->get('elasticemail_username')); $this->Password = trim($this->config->get('elasticemail_password')); $this->SMTPAuth = true; }else{ include_once (ACYMAILING_FRONT . 'inc' . DS . 'phpmailer' . DS . 'class.elasticemail.php'); $this->Mailer = 'elasticemail'; $this->elasticEmail = new acymailingElasticemail(); $this->elasticEmail->Username = trim($this->config->get('elasticemail_username')); $this->elasticEmail->Password = trim($this->config->get('elasticemail_password')); } break; case 'smtp_com' : $this->IsSMTP(); $this->Host = 'smtp.com:2525'; $this->Username = trim($this->config->get('smtp_com_username')); $this->Password = trim($this->config->get('smtp_com_password')); $this->SMTPAuth = true; break; default : $this->IsMail(); break; }//endswitch $this->PluginDir = dirname(__FILE__).DS; $this->CharSet = strtolower($this->config->get('charset')); if(empty($this->CharSet)) $this->CharSet = 'utf-8'; $this->clearAll(); $this->Encoding = $this->config->get('encoding_format'); if(empty($this->Encoding)) $this->Encoding = '8bit'; $this->Hostname = trim($this->config->get('hostname','')); $this->WordWrap = intval($this->config->get('word_wrapping',0)); @ini_set('pcre.backtrack_limit', 1000000); }//endfct function send(){ if(empty($this->ReplyTo)){ $this->_addReplyTo($this->config->get('reply_email'),$this->config->get('reply_name')); } if((bool)$this->config->get('embed_images',0) && $this->Mailer != 'elasticemail'){ $this->embedImages(); } if(empty($this->Subject) OR empty($this->Body)){ $this->reportMessage = JText::_( 'SEND_EMPTY'); $this->errorNumber = 8; if($this->report){ $this->app->enqueueMessage($this->reportMessage, 'error'); } return false; } if(!$this->alreadyCheckedAddresses){ $this->alreadyCheckedAddresses = true; if(empty($this->ReplyTo[0][0]) || !$this->userHelper->validEmail($this->ReplyTo[0][0])){ $this->reportMessage = JText::_( 'VALID_EMAIL').' ( '.JText::_('REPLYTO_ADDRESS').' : '.$this->ReplyTo[0][0].' ) '; $this->errorNumber = 9; if($this->report){ $this->app->enqueueMessage($this->reportMessage, 'error'); } return false; } if(empty($this->From) || !$this->userHelper->validEmail($this->From)){ $this->reportMessage = JText::_( 'VALID_EMAIL').' ( '.JText::_('FROM_ADDRESS').' : '.$this->From.' ) '; $this->errorNumber = 9; if($this->report){ $this->app->enqueueMessage($this->reportMessage, 'error'); } return false; } if(!empty($this->Sender) && !$this->userHelper->validEmail($this->Sender)){ $this->reportMessage = JText::_( 'VALID_EMAIL').' ( '.JText::_('BOUNCE_ADDRESS').' : '.$this->Sender.' ) '; $this->errorNumber = 9; if($this->report){ $this->app->enqueueMessage($this->reportMessage, 'error'); } return false; } } if(function_exists('mb_convert_encoding') && !empty($this->sendHTML)){ $this->Body = mb_convert_encoding($this->Body,'HTML-ENTITIES','UTF-8'); $this->Body = str_replace(array('&amp;','&sigmaf;'),array('&','ς'),$this->Body); } if($this->CharSet != 'utf-8'){ $this->Body = $this->encodingHelper->change($this->Body,'UTF-8',$this->CharSet); $this->Subject = $this->encodingHelper->change($this->Subject,'UTF-8',$this->CharSet); if(!empty($this->AltBody)) $this->AltBody = $this->encodingHelper->change($this->AltBody,'UTF-8',$this->CharSet); } if(strpos($this->Host,'elasticemail')){ $this->addCustomHeader('referral:2f0447bb-173a-459d-ab1a-ab8cbebb9aab'); } $this->Subject = str_replace(array('’','“','”','–'),array("'",'"','"','-'),$this->Subject); $this->Body = str_replace(" ",' ',$this->Body); ob_start(); $result = parent::Send(); $warnings = ob_get_clean(); if(!empty($warnings) && strpos($warnings,'bloque')){ $result = false; } $receivers = array(); foreach($this->to as $oneReceiver){ $receivers[] = $oneReceiver[0]; } if(!$result){ $this->reportMessage = JText::sprintf( 'SEND_ERROR','<b><i>'.$this->Subject.'</i></b>','<b><i>'.implode(' , ',$receivers).'</i></b>'); if(!empty($this->ErrorInfo)) $this->reportMessage .= ' | '.$this->ErrorInfo; if(!empty($warnings)) $this->reportMessage .= ' | '.$warnings; $this->errorNumber = 1; if($this->report){ $this->app->enqueueMessage($this->reportMessage, 'error'); } }else{ $this->reportMessage = JText::sprintf( 'SEND_SUCCESS','<b><i>'.$this->Subject.'</i></b>','<b><i>'.implode(' , ',$receivers).'</i></b>'); if(!empty($warnings)) $this->reportMessage .= ' | '.$warnings; if($this->report){ $this->app->enqueueMessage($this->reportMessage, 'message'); } } return $result; } function load($mailid){ $mailClass = acymailing_get('class.mail'); $this->defaultMail[$mailid] = $mailClass->get($mailid); if(empty($this->defaultMail[$mailid]->mailid)) return false; if(empty($this->defaultMail[$mailid]->altbody)) $this->defaultMail[$mailid]->altbody = $this->textVersion($this->defaultMail[$mailid]->body); if(!empty($this->defaultMail[$mailid]->attach)){ $this->defaultMail[$mailid]->attachments = array(); $uploadFolder = str_replace(array('/','\\'),DS,html_entity_decode($this->config->get('uploadfolder'))); $uploadFolder = trim($uploadFolder,DS.' ').DS; $uploadPath = str_replace(array('/','\\'),DS,ACYMAILING_ROOT.$uploadFolder); $uploadURL = ACYMAILING_LIVE.str_replace(DS,'/',$uploadFolder); foreach($this->defaultMail[$mailid]->attach as $oneAttach){ $attach = new stdClass(); $attach->name = $oneAttach->filename; $attach->filename = $uploadPath.$oneAttach->filename; $attach->url = $uploadURL.$oneAttach->filename; $this->defaultMail[$mailid]->attachments[] = $attach; } } $this->dispatcher->trigger('acymailing_replacetags',array(&$this->defaultMail[$mailid],$this->loadedToSend)); $this->defaultMail[$mailid]->body = acymailing_absoluteURL($this->defaultMail[$mailid]->body); return $this->defaultMail[$mailid]; } function clearAll(){ $this->Subject = ''; $this->Body = ''; $this->AltBody = ''; $this->ClearAllRecipients(); $this->ClearAttachments(); $this->ClearCustomHeaders(); $this->ClearReplyTos(); $this->errorNumber = 0; $this->MessageID = ''; $this->setFrom($this->config->get('from_email'),$this->config->get('from_name')); } function sendOne($mailid,$receiverid){ $this->clearAll(); if(!isset($this->defaultMail[$mailid])){ $this->loadedToSend = true; if(!$this->load($mailid)){ $this->reportMessage = 'Can not load the e-mail : '.$mailid; if($this->report){ $this->app->enqueueMessage($this->reportMessage, 'error'); } $this->errorNumber = 2; return false; } } if(!empty($this->forceTemplate) AND empty($this->defaultMail[$mailid]->tempid)){ $this->defaultMail[$mailid]->tempid = $this->forceTemplate; } if(!isset($this->forceVersion) AND $this->checkPublished AND empty($this->defaultMail[$mailid]->published)){ $this->reportMessage = JText::sprintf('SEND_ERROR_PUBLISHED',$mailid); $this->errorNumber = 3; if($this->report){ $this->app->enqueueMessage($this->reportMessage, 'error'); } return false; } if(!is_object($receiverid)){ $receiver = $this->subscriberClass->get($receiverid); if(empty($receiver->subid) AND is_string($receiverid) AND $this->autoAddUser){ if($this->userHelper->validEmail($receiverid)){ $newUser = new stdClass(); $newUser->email = $receiverid; $this->subscriberClass->checkVisitor = false; $this->subscriberClass->sendConf = false; $subid = $this->subscriberClass->save($newUser); $receiver = $this->subscriberClass->get($subid); } } }else{ $receiver = $receiverid; } if(empty($receiver->email)){ $this->reportMessage = JText::sprintf( 'SEND_ERROR_USER','<b><i>'.(isset($receiver->subid) ? $receiver->subid : $receiverid).'</i></b>'); if($this->report){ $this->app->enqueueMessage($this->reportMessage, 'error'); } $this->errorNumber = 4; return false; } $this->MessageID = "<".preg_replace("|[^a-z0-9+_]|i",'',base64_encode(rand(0,9999999))."AC".$receiver->subid."Y".$this->defaultMail[$mailid]->mailid."BA".base64_encode(time().rand(0,99999)))."@".$this->ServerHostname().">"; if(!isset($this->forceVersion)){ if($this->checkConfirmField AND empty($receiver->confirmed) AND $this->config->get('require_confirmation',0) AND $this->defaultMail[$mailid]->alias != 'confirmation'){ $this->reportMessage = JText::sprintf( 'SEND_ERROR_CONFIRMED','<b><i>'.$receiver->email.'</i></b>'); if($this->report){ $this->app->enqueueMessage($this->reportMessage, 'error'); } $this->errorNumber = 5; return false; } if($this->checkEnabled AND empty($receiver->enabled)){ $this->reportMessage = JText::sprintf( 'SEND_ERROR_APPROVED','<b><i>'.$receiver->email.'</i></b>'); if($this->report){ $this->app->enqueueMessage($this->reportMessage, 'error'); } $this->errorNumber = 6; return false; } } if($this->checkAccept AND empty($receiver->accept)){ $this->reportMessage = JText::sprintf( 'SEND_ERROR_ACCEPT','<b><i>'.$receiver->email.'</i></b>'); if($this->report){ $this->app->enqueueMessage($this->reportMessage, 'error'); } $this->errorNumber = 7; return false; } $addedName = $this->config->get('add_names',true) ? $this->cleanText($receiver->name) : ''; $this->AddAddress($this->cleanText($receiver->email),$addedName); if(!isset($this->forceVersion)){ $this->sendHTML = $receiver->html && $this->defaultMail[$mailid]->html; $this->IsHTML($this->sendHTML); }else{ $this->sendHTML = (bool) $this->forceVersion; $this->IsHTML($this->sendHTML); } $this->Subject = $this->defaultMail[$mailid]->subject; if($this->sendHTML){ $this->Body = $this->defaultMail[$mailid]->body; if($this->config->get('multiple_part',false)){ $this->AltBody = $this->defaultMail[$mailid]->altbody; } }else{ $this->Body = $this->defaultMail[$mailid]->altbody; } $this->setFrom($this->defaultMail[$mailid]->fromemail,$this->defaultMail[$mailid]->fromname); $this->_addReplyTo($this->defaultMail[$mailid]->replyemail,$this->defaultMail[$mailid]->replyname); if(!empty($this->defaultMail[$mailid]->attachments)){ if($this->config->get('embed_files')){ foreach($this->defaultMail[$mailid]->attachments as $attachment){ $this->AddAttachment($attachment->filename); } }else{ $attachStringHTML = '<br/><fieldset><legend>'.JText::_( 'ATTACHMENTS' ).'</legend><table>'; $attachStringText = "\n"."\n".'------- '.JText::_( 'ATTACHMENTS' ).' -------'; foreach($this->defaultMail[$mailid]->attachments as $attachment){ $attachStringHTML .= '<tr><td><a href="'.$attachment->url.'" target="_blank">'.$attachment->name.'</a></td></tr>'; $attachStringText .= "\n".'-- '.$attachment->name.' ( '.$attachment->url.' )'; } $attachStringHTML .= '</table></fieldset>'; if($this->sendHTML){ $this->Body .= $attachStringHTML; if(!empty($this->AltBody)) $this->AltBody .= "\n".$attachStringText; }else{ $this->Body .= $attachStringText; } } } if(!empty($this->parameters)){ $keysparams = array_keys($this->parameters); $this->Subject = str_replace($keysparams,$this->parameters,$this->Subject); $this->Body = str_replace($keysparams,$this->parameters,$this->Body); if(!empty($this->AltBody)) $this->AltBody = str_replace($keysparams,$this->parameters,$this->AltBody); } if(!empty($this->introtext)){ $this->Body = $this->introtext.$this->Body; $this->AltBody = $this->textVersion($this->introtext).$this->AltBody; } $this->body = &$this->Body; $this->altbody = &$this->AltBody; $this->subject = &$this->Subject; $this->from = &$this->From; $this->fromName = &$this->FromName; $this->replyto = &$this->ReplyTo; $this->replyname = $this->defaultMail[$mailid]->replyname; $this->replyemail = $this->defaultMail[$mailid]->replyemail; $this->mailid = $this->defaultMail[$mailid]->mailid; $this->key = $this->defaultMail[$mailid]->key; $this->alias = $this->defaultMail[$mailid]->alias; $this->type = $this->defaultMail[$mailid]->type; $this->tempid = $this->defaultMail[$mailid]->tempid; $this->sentby = $this->defaultMail[$mailid]->sentby; $this->userid = $this->defaultMail[$mailid]->userid; $this->filter = $this->defaultMail[$mailid]->filter; if(empty($receiver->key) && !empty($receiver->subid)){ $receiver->key = md5(substr($receiver->email,0,strpos($receiver->email,'@')).time()); $db = JFactory::getDBO(); $db->setQuery('UPDATE '.acymailing_table('subscriber').' SET `key`= '.$db->Quote($receiver->key).' WHERE subid = '.(int) $receiver->subid.' LIMIT 1'); $db->query(); } $this->dispatcher->trigger('acymailing_replaceusertags',array(&$this,&$receiver,true)); if($this->sendHTML){ if(!empty($this->AltBody)) $this->AltBody = $this->textVersion($this->AltBody,false); }else{ $this->Body = $this->textVersion($this->Body,false); } return $this->send(); } function embedImages(){ preg_match_all('/(src|background)="([^"]*)"/Ui', $this->Body, $images); $result = true; if(!empty($images[2])) { $mimetypes = array('bmp' => 'image/bmp', 'gif' => 'image/gif', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'png' => 'image/png', 'tiff' => 'image/tiff', 'tif' => 'image/tiff'); $allimages = array(); foreach($images[2] as $i => $url) { if(isset($allimages[$url])) continue; $allimages[$url] = 1; $path = $url; $otheracymailinglive = str_replace('http://www.','http://',ACYMAILING_LIVE); if($otheracymailinglive == ACYMAILING_LIVE) $otheracymailinglive = str_replace('http://','http://www.',ACYMAILING_LIVE); if(strpos($url,ACYMAILING_LIVE) !== false || strpos($url,$otheracymailinglive) !== false){ $path = str_replace(array(ACYMAILING_LIVE,$otheracymailinglive,'/'),array(ACYMAILING_ROOT,ACYMAILING_ROOT,DS),urldecode($url)); } $filename = basename($url); $md5 = md5($filename); $cid = 'cid:' . $md5; $fileParts = explode(".", $filename); $ext = strtolower($fileParts[1]); if(!isset($mimetypes[$ext])) continue; $mimeType = $mimetypes[$ext]; if($this->AddEmbeddedImage($path, $md5, $filename, 'base64', $mimeType)){ $this->Body = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $this->Body); }else{ $result = false; } } } return $result; } function textVersion($html,$fullConvert = true){ $html = acymailing_absoluteURL($html); if($fullConvert){ $html = preg_replace('# +#',' ',$html); $html = str_replace(array("\n","\r","\t"),'',$html); } $removepictureslinks = "#< *a[^>]*> *< *img[^>]*> *< *\/ *a *>#isU"; $removeScript = "#< *script(?:(?!< */ *script *>).)*< */ *script *>#isU"; $removeStyle = "#< *style(?:(?!< */ *style *>).)*< */ *style *>#isU"; $removeStrikeTags = '#< *strike(?:(?!< */ *strike *>).)*< */ *strike *>#iU'; $replaceByTwoReturnChar = '#< *(h1|h2)[^>]*>#Ui'; $replaceByStars = '#< *li[^>]*>#Ui'; $replaceByReturnChar1 = '#< */ *(li|td|dt|tr|div|p)[^>]*> *< *(li|td|dt|tr|div|p)[^>]*>#Ui'; $replaceByReturnChar = '#< */? *(br|p|h1|h2|legend|h3|li|ul|dd|dt|h4|h5|h6|tr|td|div)[^>]*>#Ui'; $replaceLinks = '/< *a[^>]*href *= *"([^#][^"]*)"[^>]*>(.+)< *\/ *a *>/Uis'; $text = preg_replace(array($removepictureslinks,$removeScript,$removeStyle,$removeStrikeTags,$replaceByTwoReturnChar,$replaceByStars,$replaceByReturnChar1,$replaceByReturnChar,$replaceLinks),array('','','','',"\n\n","\n* ","\n","\n",'${2} ( ${1} )'),$html); $text = preg_replace('#(&lt;|&\#60;)([^ \n\r\t])#i','&lt; ${2}',$text); $text = str_replace(array(" ","&nbsp;"),' ',strip_tags($text)); $text = trim(@html_entity_decode($text,ENT_QUOTES,'UTF-8')); if($fullConvert){ $text = preg_replace('# +#',' ',$text); $text = preg_replace('#\n *\n\s+#',"\n\n",$text); } return $text; } function cleanText($text){ return trim( preg_replace( '/(%0A|%0D|\n+|\r+)/i', '', (string) $text ) ); } function setFrom($email,$name=''){ if(!empty($email)){ $this->From = $this->cleanText($email); } if(!empty($name) AND $this->config->get('add_names',true)){ $this->FromName = $this->cleanText($name); } } function addParamInfo(){ if(!empty($_SERVER)){ $serverinfo = array(); foreach($_SERVER as $oneKey => $oneInfo){ $serverinfo[] = $oneKey.' => '.strip_tags(print_r($oneInfo,true)); } $this->addParam('serverinfo',implode('<br />',$serverinfo)); } if(!empty($_REQUEST)){ $postinfo = array(); foreach($_REQUEST as $oneKey => $oneInfo){ $postinfo[] = $oneKey.' => '.strip_tags(print_r($oneInfo,true)); } $this->addParam('postinfo',implode('<br />',$postinfo)); } } function addParam($name,$value){ $tagName = '{'.$name.'}'; $this->parameters[$tagName] = $value; } function _addReplyTo($email,$name){ if(empty($email)) return; $replyToName = $this->config->get('add_names',true) ? $this->cleanText(trim($name)) : ''; $replyToEmail = trim($email); if(substr_count($replyToEmail,'@')>1){ $replyToEmailArray = explode(';',str_replace(array(';',','),';',$replyToEmail)); $replyToNameArray = explode(';',str_replace(array(';',','),';',$replyToName)); foreach($replyToEmailArray as $i => $oneReplyTo){ $this->AddReplyTo($this->cleanText($oneReplyTo),@$replyToNameArray[$i]); } }else{ $this->AddReplyTo($this->cleanText($replyToEmail),$replyToName); } } }
gpl-2.0
adini121/WebDriver
src/main/java/org/sayem/webdriver/selenium/cookies/LoadCookieInfo.java
1640
package org.sayem.webdriver.selenium.cookies; import org.openqa.selenium.Cookie; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Date; import java.util.StringTokenizer; public class LoadCookieInfo { public static void main(String... args) { WebDriver driver = new FirefoxDriver(); driver.get("http://www.facebook.com"); try { File f2 = new File("browser.data"); FileReader fr = new FileReader(f2); BufferedReader br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { StringTokenizer str = new StringTokenizer(line, ";"); while (str.hasMoreTokens()) { String name = str.nextToken(); String value = str.nextToken(); String domain = str.nextToken(); String path = str.nextToken(); Date expiry = null; String dt; if (!(dt = str.nextToken()).equals("null")) { expiry = new Date(dt); } boolean isSecure = new Boolean(str.nextToken()).booleanValue(); Cookie ck = new Cookie(name, value, domain, path, expiry, isSecure); driver.manage().addCookie(ck); } } } catch (Exception ex) { ex.printStackTrace(); } driver.get("http://www.facebook.com"); } }
gpl-2.0
masamorro999/AutosRA
AutosRa.API/Models/AccountViewModels.cs
968
using System; using System.Collections.Generic; namespace AutosRa.API.Models { // Models returned by AccountController actions. public class ExternalLoginViewModel { public string Name { get; set; } public string Url { get; set; } public string State { get; set; } } public class ManageInfoViewModel { public string LocalLoginProvider { get; set; } public string Email { get; set; } public IEnumerable<UserLoginInfoViewModel> Logins { get; set; } public IEnumerable<ExternalLoginViewModel> ExternalLoginProviders { get; set; } } public class UserInfoViewModel { public string Email { get; set; } public bool HasRegistered { get; set; } public string LoginProvider { get; set; } } public class UserLoginInfoViewModel { public string LoginProvider { get; set; } public string ProviderKey { get; set; } } }
gpl-2.0
FengISU/DEM_project
src/variable.cpp
138300
/* ---------------------------------------------------------------------- This is the ██╗ ██╗ ██████╗ ██████╗ ██████╗ ██╗ ██╗████████╗███████╗ ██║ ██║██╔════╝ ██╔════╝ ██╔════╝ ██║ ██║╚══██╔══╝██╔════╝ ██║ ██║██║ ███╗██║ ███╗██║ ███╗███████║ ██║ ███████╗ ██║ ██║██║ ██║██║ ██║██║ ██║██╔══██║ ██║ ╚════██║ ███████╗██║╚██████╔╝╚██████╔╝╚██████╔╝██║ ██║ ██║ ███████║ ╚══════╝╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝® DEM simulation engine, released by DCS Computing Gmbh, Linz, Austria http://www.dcs-computing.com, office@dcs-computing.com LIGGGHTS® is part of CFDEM®project: http://www.liggghts.com | http://www.cfdem.com Core developer and main author: Christoph Kloss, christoph.kloss@dcs-computing.com LIGGGHTS® is open-source, distributed under the terms of the GNU Public License, version 2 or later. It 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. You should have received a copy of the GNU General Public License along with LIGGGHTS®. If not, see http://www.gnu.org/licenses . See also top-level README and LICENSE files. LIGGGHTS® and CFDEM® are registered trade marks of DCS Computing GmbH, the producer of the LIGGGHTS® software and the CFDEM®coupling software See http://www.cfdem.com/terms-trademark-policy for details. ------------------------------------------------------------------------- Contributing author and copyright for this file: This file is from LAMMPS LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. ------------------------------------------------------------------------- */ #include "math.h" #include "stdlib.h" #include "string.h" #include "ctype.h" #include "unistd.h" #include "variable.h" #include "universe.h" #include "atom.h" #include "update.h" #include "group.h" #include "domain.h" #include "comm.h" #include "region.h" #include "modify.h" #include "compute.h" #include "fix.h" #include "fix_store.h" #include "output.h" #include "thermo.h" #include "random_mars.h" #include "fix_multisphere.h" #include "math_const.h" #include "atom_masks.h" #include "memory.h" #include "error.h" #include "force.h" #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #define sleep Sleep #define ATOM AATOM #endif using namespace LAMMPS_NS; using namespace MathConst; #define VARDELTA 4 #define MAXLEVEL 4 #define MAXLINE 256 #define CHUNK 1024 #define MYROUND(a) (( a-floor(a) ) >= .5) ? ceil(a) : floor(a) enum{INDEX,LOOP,WORLD,UNIVERSE,ULOOP,STRING,GETENV, SCALARFILE,ATOMFILE,EQUAL,ATOM}; enum{ARG,OP}; // customize by adding a function // if add before OR, // also set precedence level in constructor and precedence length in *.h enum{DONE,ADD,SUBTRACT,MULTIPLY,DIVIDE,CARAT,MODULO,UNARY, NOT,EQ,NE,LT,LE,GT,GE,AND,OR, SQRT,EXP,LN,LOG,ABS,SIN,COS,TAN,ASIN,ACOS,ATAN,ATAN2, RANDOM,NORMAL,CEIL,FLOOR,ROUND,RAMP,STAGGER,LOGFREQ,STRIDE, VDISPLACE,SWIGGLE,CWIGGLE,GMASK,RMASK,GRMASK, VALUE,ATOMARRAY,TYPEARRAY,INTARRAY}; // customize by adding a special function enum{SUM,XMIN,XMAX,AVE,TRAP,NEXT}; #define INVOKED_SCALAR 1 #define INVOKED_VECTOR 2 #define INVOKED_ARRAY 4 #define INVOKED_PERATOM 8 #define BIG 1.0e20 /* ---------------------------------------------------------------------- */ Variable::Variable(LAMMPS *lmp) : Pointers(lmp) { MPI_Comm_rank(world,&me); nvar = maxvar = 0; names = NULL; style = NULL; num = NULL; which = NULL; pad = NULL; reader = NULL; data = NULL; eval_in_progress = NULL; randomequal = NULL; randomatom = NULL; // customize by assigning a precedence level precedence[DONE] = 0; precedence[OR] = 1; precedence[AND] = 2; precedence[EQ] = precedence[NE] = 3; precedence[LT] = precedence[LE] = precedence[GT] = precedence[GE] = 4; precedence[ADD] = precedence[SUBTRACT] = 5; precedence[MULTIPLY] = precedence[DIVIDE] = precedence[MODULO] = 6; precedence[CARAT] = 7; precedence[UNARY] = precedence[NOT] = 8; } /* ---------------------------------------------------------------------- */ Variable::~Variable() { for (int i = 0; i < nvar; i++) { delete [] names[i]; delete reader[i]; if (style[i] == LOOP || style[i] == ULOOP) delete [] data[i][0]; else for (int j = 0; j < num[i]; j++) delete [] data[i][j]; delete [] data[i]; } memory->sfree(names); memory->destroy(style); memory->destroy(num); memory->destroy(which); memory->destroy(pad); memory->sfree(reader); memory->sfree(data); memory->destroy(eval_in_progress); delete randomequal; delete randomatom; } /* ---------------------------------------------------------------------- called by variable command in input script ------------------------------------------------------------------------- */ void Variable::set(int narg, char **arg) { if (narg < 2) error->all(FLERR,"Illegal variable command"); // DELETE // doesn't matter if variable no longer exists if (strcmp(arg[1],"delete") == 0) { if (narg != 2) error->all(FLERR,"Illegal variable command"); if (find(arg[0]) >= 0) remove(find(arg[0])); return; // INDEX // num = listed args, which = 1st value, data = copied args } else if (strcmp(arg[1],"index") == 0) { if (narg < 3) error->all(FLERR,"Illegal variable command"); if (find(arg[0]) >= 0) return; if (nvar == maxvar) grow(); style[nvar] = INDEX; num[nvar] = narg - 2; which[nvar] = 0; pad[nvar] = 0; data[nvar] = new char*[num[nvar]]; copy(num[nvar],&arg[2],data[nvar]); // LOOP // 1 arg + pad: num = N, which = 1st value, data = single string // 2 args + pad: num = N2, which = N1, data = single string } else if (strcmp(arg[1],"loop") == 0) { if (find(arg[0]) >= 0) return; if (nvar == maxvar) grow(); style[nvar] = LOOP; int nfirst=0,nlast=0; if (narg == 3 || (narg == 4 && strcmp(arg[3],"pad") == 0)) { nfirst = 1; nlast = force->inumeric(FLERR,arg[2]); if (nlast <= 0) error->all(FLERR,"Illegal variable command"); if (narg == 4 && strcmp(arg[3],"pad") == 0) { char digits[12]; sprintf(digits,"%d",nlast); pad[nvar] = strlen(digits); } else pad[nvar] = 0; } else if (narg == 4 || (narg == 5 && strcmp(arg[4],"pad") == 0)) { nfirst = force->inumeric(FLERR,arg[2]); nlast = force->inumeric(FLERR,arg[3]); if (nfirst > nlast || nlast < 0) error->all(FLERR,"Illegal variable command"); if (narg == 5 && strcmp(arg[4],"pad") == 0) { char digits[12]; sprintf(digits,"%d",nlast); pad[nvar] = strlen(digits); } else pad[nvar] = 0; } else error->all(FLERR,"Illegal variable command"); num[nvar] = nlast; which[nvar] = nfirst-1; data[nvar] = new char*[1]; data[nvar][0] = NULL; // WORLD // num = listed args, which = partition this proc is in, data = copied args // error check that num = # of worlds in universe } else if (strcmp(arg[1],"world") == 0) { if (narg < 3) error->all(FLERR,"Illegal variable command"); if (find(arg[0]) >= 0) return; if (nvar == maxvar) grow(); style[nvar] = WORLD; num[nvar] = narg - 2; if (num[nvar] != universe->nworlds) error->all(FLERR,"World variable count doesn't match # of partitions"); which[nvar] = universe->iworld; pad[nvar] = 0; data[nvar] = new char*[num[nvar]]; copy(num[nvar],&arg[2],data[nvar]); // UNIVERSE and ULOOP // for UNIVERSE: num = listed args, data = copied args // for ULOOP: num = N, data = single string // which = partition this proc is in // universe proc 0 creates lock file // error check that all other universe/uloop variables are same length } else if (strcmp(arg[1],"universe") == 0 || strcmp(arg[1],"uloop") == 0) { if (strcmp(arg[1],"universe") == 0) { if (narg < 3) error->all(FLERR,"Illegal variable command"); if (find(arg[0]) >= 0) return; if (nvar == maxvar) grow(); style[nvar] = UNIVERSE; num[nvar] = narg - 2; pad[nvar] = 0; data[nvar] = new char*[num[nvar]]; copy(num[nvar],&arg[2],data[nvar]); } else if (strcmp(arg[1],"uloop") == 0) { if (narg < 3 || narg > 4 || (narg == 4 && strcmp(arg[3],"pad") != 0)) error->all(FLERR,"Illegal variable command"); if (find(arg[0]) >= 0) return; if (nvar == maxvar) grow(); style[nvar] = ULOOP; num[nvar] = force->inumeric(FLERR,arg[2]); data[nvar] = new char*[1]; data[nvar][0] = NULL; if (narg == 4) { char digits[12]; sprintf(digits,"%d",num[nvar]); pad[nvar] = strlen(digits); } else pad[nvar] = 0; } if (num[nvar] < universe->nworlds) error->all(FLERR,"Universe/uloop variable count < # of partitions"); which[nvar] = universe->iworld; if (universe->me == 0) { char filename[200] ; sprintf(filename,"tmp.lammps.variable%s",universe->universe_id?universe->universe_id:""); FILE *fp = fopen(filename,"w"); fprintf(fp,"%d\n",universe->nworlds); fclose(fp); } for (int jvar = 0; jvar < nvar; jvar++) if (num[jvar] && (style[jvar] == UNIVERSE || style[jvar] == ULOOP) && num[nvar] != num[jvar]) error->all(FLERR, "All universe/uloop variables must have same # of values"); // STRING // remove pre-existing var if also style STRING (allows it to be reset) // num = 1, which = 1st value // data = 1 value, string to eval } else if (strcmp(arg[1],"string") == 0) { if (narg != 3) error->all(FLERR,"Illegal variable command"); if (find(arg[0]) >= 0) { if (style[find(arg[0])] != STRING) error->all(FLERR,"Cannot redefine variable as a different style"); remove(find(arg[0])); } if (nvar == maxvar) grow(); style[nvar] = STRING; num[nvar] = 1; which[nvar] = 0; pad[nvar] = 0; data[nvar] = new char*[num[nvar]]; copy(1,&arg[2],data[nvar]); // GETENV // remove pre-existing var if also style GETENV (allows it to be reset) // num = 1, which = 1st value // data = 1 value, string to eval } else if (strcmp(arg[1],"getenv") == 0) { if (narg != 3) error->all(FLERR,"Illegal variable command"); if (find(arg[0]) >= 0) { if (style[find(arg[0])] != GETENV) error->all(FLERR,"Cannot redefine variable as a different style"); remove(find(arg[0])); } if (nvar == maxvar) grow(); style[nvar] = GETENV; num[nvar] = 1; which[nvar] = 0; pad[nvar] = 0; data[nvar] = new char*[num[nvar]]; copy(1,&arg[2],data[nvar]); data[nvar][1] = NULL; // SCALARFILE for strings or numbers // which = 1st value // data = 1 value, string to eval } else if (strcmp(arg[1],"file") == 0) { if (narg != 3) error->all(FLERR,"Illegal variable command"); if (find(arg[0]) >= 0) return; if (nvar == maxvar) grow(); style[nvar] = SCALARFILE; num[nvar] = 1; which[nvar] = 0; pad[nvar] = 0; data[nvar] = new char*[num[nvar]]; data[nvar][0] = new char[MAXLINE]; reader[nvar] = new VarReader(lmp,arg[0],arg[2],SCALARFILE); int flag = reader[nvar]->read_scalar(data[nvar][0]); if (flag) error->all(FLERR,"File variable could not read value"); // ATOMFILE for numbers // which = 1st value // data = NULL } else if (strcmp(arg[1],"atomfile") == 0) { if (narg != 3) error->all(FLERR,"Illegal variable command"); if (find(arg[0]) >= 0) return; if (nvar == maxvar) grow(); style[nvar] = ATOMFILE; num[nvar] = 1; which[nvar] = 0; pad[nvar] = 0; data[nvar] = new char*[num[nvar]]; data[nvar][0] = NULL; reader[nvar] = new VarReader(lmp,arg[0],arg[2],ATOMFILE); int flag = reader[nvar]->read_peratom(); if (flag) error->all(FLERR,"Atomfile variable could not read values"); // EQUAL // remove pre-existing var if also style EQUAL (allows it to be reset) // num = 2, which = 1st value // data = 2 values, 1st is string to eval, 2nd is filled on retrieval } else if (strcmp(arg[1],"equal") == 0) { if (narg != 3) error->all(FLERR,"Illegal variable command"); if (find(arg[0]) >= 0) { if (style[find(arg[0])] != EQUAL) error->all(FLERR,"Cannot redefine variable as a different style"); remove(find(arg[0])); } if (nvar == maxvar) grow(); style[nvar] = EQUAL; num[nvar] = 2; which[nvar] = 0; pad[nvar] = 0; data[nvar] = new char*[num[nvar]]; copy(1,&arg[2],data[nvar]); data[nvar][1] = NULL; // ATOM // remove pre-existing var if also style ATOM (allows it to be reset) // num = 1, which = 1st value // data = 1 value, string to eval } else if (strcmp(arg[1],"atom") == 0) { if (narg != 3) error->all(FLERR,"Illegal variable command"); if (find(arg[0]) >= 0) { if (style[find(arg[0])] != ATOM) error->all(FLERR,"Cannot redefine variable as a different style"); remove(find(arg[0])); } if (nvar == maxvar) grow(); style[nvar] = ATOM; num[nvar] = 1; which[nvar] = 0; pad[nvar] = 0; data[nvar] = new char*[num[nvar]]; copy(1,&arg[2],data[nvar]); } else error->all(FLERR,"Illegal variable command"); // set name of variable // must come at end, since STRING/EQUAL/ATOM reset may have removed name // name must be all alphanumeric chars or underscores int n = strlen(arg[0]) + 1; names[nvar] = new char[n]; strcpy(names[nvar],arg[0]); for (int i = 0; i < n-1; i++) if (!isalnum(names[nvar][i]) && names[nvar][i] != '_') error->all(FLERR,"Variable name must be alphanumeric or " "underscore characters"); nvar++; } /* ---------------------------------------------------------------------- INDEX variable created by command-line argument make it INDEX rather than STRING so cannot be re-defined in input script ------------------------------------------------------------------------- */ void Variable::set(char *name, int narg, char **arg) { char **newarg = new char*[2+narg]; newarg[0] = name; newarg[1] = (char *) "index"; for (int i = 0; i < narg; i++) newarg[2+i] = arg[i]; set(2+narg,newarg); delete [] newarg; } /* ---------------------------------------------------------------------- increment variable(s) return 0 if OK if successfully incremented return 1 if any variable is exhausted, free the variable to allow re-use ------------------------------------------------------------------------- */ int Variable::next(int narg, char **arg) { int ivar; if (narg == 0) error->all(FLERR,"Illegal next command"); // check that variables exist and are all the same style // exception: UNIVERSE and ULOOP variables can be mixed in same next command for (int iarg = 0; iarg < narg; iarg++) { ivar = find(arg[iarg]); if (ivar == -1) error->all(FLERR,"Invalid variable in next command"); if (style[ivar] == ULOOP && style[find(arg[0])] == UNIVERSE) continue; else if (style[ivar] == UNIVERSE && style[find(arg[0])] == ULOOP) continue; else if (style[ivar] != style[find(arg[0])]) error->all(FLERR,"All variables in next command must be same style"); } // invalid styles STRING or EQUAL or WORLD or ATOM or GETENV int istyle = style[find(arg[0])]; if (istyle == STRING || istyle == EQUAL || istyle == WORLD || istyle == GETENV || istyle == ATOM) error->all(FLERR,"Invalid variable style with next command"); // increment all variables in list // if any variable is exhausted, set flag = 1 and remove var to allow re-use int flag = 0; if (istyle == INDEX || istyle == LOOP) { for (int iarg = 0; iarg < narg; iarg++) { ivar = find(arg[iarg]); which[ivar]++; if (which[ivar] >= num[ivar]) { flag = 1; remove(ivar); } } } else if (istyle == SCALARFILE) { for (int iarg = 0; iarg < narg; iarg++) { ivar = find(arg[iarg]); int done = reader[ivar]->read_scalar(data[ivar][0]); if (done) { flag = 1; remove(ivar); } } } else if (istyle == ATOMFILE) { for (int iarg = 0; iarg < narg; iarg++) { ivar = find(arg[iarg]); int done = reader[ivar]->read_peratom(); if (done) { flag = 1; remove(ivar); } } } else if (istyle == UNIVERSE || istyle == ULOOP) { // wait until lock file can be created and owned by proc 0 of this world // read next available index and Bcast it within my world // set all variables in list to nextindex int nextindex; if (me == 0) { char filename_1[200],filename_2[200]; sprintf(filename_1,"tmp.lammps.variable%s",universe->universe_id?universe->universe_id:""); sprintf(filename_2,"tmp.lammps.variable.lock%s",universe->universe_id?universe->universe_id:""); while (1) { if (!rename(filename_1,filename_2)) break; sleep(100); } FILE *fp = fopen(filename_2,"r"); fscanf(fp,"%d",&nextindex); fclose(fp); fp = fopen(filename_2,"w"); fprintf(fp,"%d\n",nextindex+1); fclose(fp); rename(filename_2,filename_1); if (universe->uscreen) fprintf(universe->uscreen, "Increment via next: value %d on partition %d\n", nextindex+1,universe->iworld); if (universe->ulogfile) fprintf(universe->ulogfile, "Increment via next: value %d on partition %d\n", nextindex+1,universe->iworld); } MPI_Bcast(&nextindex,1,MPI_INT,0,world); for (int iarg = 0; iarg < narg; iarg++) { ivar = find(arg[iarg]); which[ivar] = nextindex; if (which[ivar] >= num[ivar]) { flag = 1; remove(ivar); } } } return flag; } /* ---------------------------------------------------------------------- return ptr to the data text associated with a variable if INDEX or WORLD or UNIVERSE or STRING or SCALARFILE var, return ptr to stored string if LOOP or ULOOP var, write int to data[0] and return ptr to string if EQUAL var, evaluate variable and put result in str if GETENV var, query environment and put result in str if ATOM or ATOMFILE var, return NULL return NULL if no variable with name or which value is bad, caller must respond ------------------------------------------------------------------------- */ char *Variable::retrieve(char *name) { int ivar = find(name); if (ivar == -1) return NULL; if (which[ivar] >= num[ivar]) return NULL; char *str = NULL; if (style[ivar] == INDEX || style[ivar] == WORLD || style[ivar] == UNIVERSE || style[ivar] == STRING || style[ivar] == SCALARFILE) { str = data[ivar][which[ivar]]; } else if (style[ivar] == LOOP || style[ivar] == ULOOP) { char result[16]; if (pad[ivar] == 0) sprintf(result,"%d",which[ivar]+1); else { char padstr[16]; sprintf(padstr,"%%0%dd",pad[ivar]); sprintf(result,padstr,which[ivar]+1); } int n = strlen(result) + 1; delete [] data[ivar][0]; data[ivar][0] = new char[n]; strcpy(data[ivar][0],result); str = data[ivar][0]; } else if (style[ivar] == EQUAL) { char result[64]; double answer = evaluate(data[ivar][0],NULL); sprintf(result,"%.15g",answer); int n = strlen(result) + 1; if (data[ivar][1]) delete [] data[ivar][1]; data[ivar][1] = new char[n]; strcpy(data[ivar][1],result); str = data[ivar][1]; } else if (style[ivar] == GETENV) { const char *result = getenv(data[ivar][0]); if (data[ivar][1]) delete [] data[ivar][1]; if (result == NULL) result = (const char *)""; int n = strlen(result) + 1; data[ivar][1] = new char[n]; strcpy(data[ivar][1],result); str = data[ivar][1]; } else if (style[ivar] == ATOM || style[ivar] == ATOMFILE) return NULL; return str; } /* ---------------------------------------------------------------------- return result of equal-style variable evaluation ------------------------------------------------------------------------- */ double Variable::compute_equal(int ivar) { // eval_in_progress used to detect circle dependencies // could extend this later to check v_a = c_b + v_a constructs? eval_in_progress[ivar] = 1; double value = evaluate(data[ivar][0],NULL); eval_in_progress[ivar] = 0; return value; } /* ---------------------------------------------------------------------- return result of immediate equal-style variable evaluation called from Input::substitute() ------------------------------------------------------------------------- */ double Variable::compute_equal(char *str) { return evaluate(str,NULL); } /* ---------------------------------------------------------------------- compute result of atom-style and atomfile-style variable evaluation only computed for atoms in igroup, else result is 0.0 answers are placed every stride locations into result if sumflag, add variable values to existing result ------------------------------------------------------------------------- */ void Variable::compute_atom(int ivar, int igroup, double *result, int stride, int sumflag) { Tree *tree; double *vstore = NULL; if (style[ivar] == ATOM) { evaluate(data[ivar][0],&tree); collapse_tree(tree); } else vstore = reader[ivar]->fix->vstore; int groupbit = group->bitmask[igroup]; int *mask = atom->mask; int nlocal = atom->nlocal; if (style[ivar] == ATOM) { if (sumflag == 0) { int m = 0; for (int i = 0; i < nlocal; i++) { if (mask[i] & groupbit) result[m] = eval_tree(tree,i); else result[m] = 0.0; m += stride; } } else { int m = 0; for (int i = 0; i < nlocal; i++) { if (mask[i] & groupbit) result[m] += eval_tree(tree,i); m += stride; } } } else { if (sumflag == 0) { int m = 0; for (int i = 0; i < nlocal; i++) { if (mask[i] & groupbit) result[m] = vstore[i]; else result[m] = 0.0; m += stride; } } else { int m = 0; for (int i = 0; i < nlocal; i++) { if (mask[i] & groupbit) result[m] += vstore[i]; m += stride; } } } if (style[ivar] == ATOM) free_tree(tree); } /* ---------------------------------------------------------------------- search for name in list of variables names return index or -1 if not found ------------------------------------------------------------------------- */ int Variable::find(char *name) { for (int i = 0; i < nvar; i++) if (strcmp(name,names[i]) == 0) return i; return -1; } /* ---------------------------------------------------------------------- return 1 if variable is EQUAL style, 0 if not ------------------------------------------------------------------------- */ int Variable::equalstyle(int ivar) { if (style[ivar] == EQUAL) return 1; return 0; } /* ---------------------------------------------------------------------- return 1 if variable is ATOM or ATOMFILE style, 0 if not ------------------------------------------------------------------------- */ int Variable::atomstyle(int ivar) { if (style[ivar] == ATOM || style[ivar] == ATOMFILE) return 1; return 0; } /* ---------------------------------------------------------------------- remove Nth variable from list and compact list delete reader explicitly if it exists ------------------------------------------------------------------------- */ void Variable::remove(int n) { delete [] names[n]; if (style[n] == LOOP || style[n] == ULOOP) delete [] data[n][0]; else for (int i = 0; i < num[n]; i++) delete [] data[n][i]; delete [] data[n]; delete reader[n]; for (int i = n+1; i < nvar; i++) { names[i-1] = names[i]; style[i-1] = style[i]; num[i-1] = num[i]; which[i-1] = which[i]; pad[i-1] = pad[i]; reader[i-1] = reader[i]; data[i-1] = data[i]; } nvar--; } /* ---------------------------------------------------------------------- make space in arrays for new variable ------------------------------------------------------------------------- */ void Variable::grow() { int old = maxvar; maxvar += VARDELTA; names = (char **) memory->srealloc(names,maxvar*sizeof(char *),"var:names"); memory->grow(style,maxvar,"var:style"); memory->grow(num,maxvar,"var:num"); memory->grow(which,maxvar,"var:which"); memory->grow(pad,maxvar,"var:pad"); reader = (VarReader **) memory->srealloc(reader,maxvar*sizeof(VarReader *),"var:reader"); for (int i = old; i < maxvar; i++) reader[i] = NULL; data = (char ***) memory->srealloc(data,maxvar*sizeof(char **),"var:data"); memory->grow(eval_in_progress,maxvar,"var:eval_in_progress"); for (int i = 0; i < maxvar; i++) eval_in_progress[i] = 0; } /* ---------------------------------------------------------------------- copy narg strings from **from to **to, and allocate space for them ------------------------------------------------------------------------- */ void Variable::copy(int narg, char **from, char **to) { int n; for (int i = 0; i < narg; i++) { n = strlen(from[i]) + 1; to[i] = new char[n]; strcpy(to[i],from[i]); } } /* ---------------------------------------------------------------------- recursive evaluation of a string str str is an equal-style or atom-style formula containing one or more items: number = 0.0, -5.45, 2.8e-4, ... constant = PI thermo keyword = ke, vol, atoms, ... math operation = (),-x,x+y,x-y,x*y,x/y,x^y, x==y,x!=y,x<y,x<=y,x>y,x>=y,x&&y,x||y, sqrt(x),exp(x),ln(x),log(x),abs(x), sin(x),cos(x),tan(x),asin(x),atan2(y,x),... group function = count(group), mass(group), xcm(group,x), ... special function = sum(x),min(x), ... atom value = x[i], y[i], vx[i], ... atom vector = x, y, vx, ... compute = c_ID, c_ID[i], c_ID[i][j] fix = f_ID, f_ID[i], f_ID[i][j] variable = v_name, v_name[i] equal-style variables passes in tree = NULL: evaluate the formula, return result as a double atom-style variable passes in tree = non-NULL: parse the formula but do not evaluate it create a parse tree and return it ------------------------------------------------------------------------- */ double Variable::evaluate(char *str, Tree **tree) { int op,opprevious; double value1,value2; char onechar; char *ptr; double argstack[MAXLEVEL]; Tree *treestack[MAXLEVEL]; int opstack[MAXLEVEL]; int nargstack = 0; int ntreestack = 0; int nopstack = 0; int i = 0; int expect = ARG; while (1) { onechar = str[i]; // whitespace: just skip if (isspace(onechar)) i++; // ---------------- // parentheses: recursively evaluate contents of parens // ---------------- else if (onechar == '(') { if (expect == OP) error->all(FLERR,"Invalid syntax in variable formula"); expect = OP; char *contents; i = find_matching_paren(str,i,contents); i++; // evaluate contents and push on stack if (tree) { Tree *newtree; evaluate(contents,&newtree); treestack[ntreestack++] = newtree; } else argstack[nargstack++] = evaluate(contents,NULL); delete [] contents; // ---------------- // number: push value onto stack // ---------------- } else if (isdigit(onechar) || onechar == '.') { if (expect == OP) error->all(FLERR,"Invalid syntax in variable formula"); expect = OP; // istop = end of number, including scientific notation int istart = i; while (isdigit(str[i]) || str[i] == '.') i++; if (str[i] == 'e' || str[i] == 'E') { i++; if (str[i] == '+' || str[i] == '-') i++; while (isdigit(str[i])) i++; } int istop = i - 1; int n = istop - istart + 1; char *number = new char[n+1]; strncpy(number,&str[istart],n); number[n] = '\0'; if (tree) { Tree *newtree = new Tree(); newtree->type = VALUE; newtree->value = atof(number); newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else argstack[nargstack++] = atof(number); delete [] number; // ---------------- // letter: c_ID, c_ID[], c_ID[][], f_ID, f_ID[], f_ID[][], // v_name, v_name[], exp(), xcm(,), x, x[], PI, vol // ---------------- } else if (isalpha(onechar)) { if (expect == OP) error->all(FLERR,"Invalid syntax in variable formula"); expect = OP; // istop = end of word // word = all alphanumeric or underscore int istart = i; while (isalnum(str[i]) || str[i] == '_') i++; int istop = i-1; int n = istop - istart + 1; char *word = new char[n+1]; strncpy(word,&str[istart],n); word[n] = '\0'; // ---------------- // compute // ---------------- if (strncmp(word,"c_",2) == 0) { if (domain->box_exist == 0) error->all(FLERR, "Variable evaluation before simulation box is defined"); n = strlen(word) - 2 + 1; char *id = new char[n]; strcpy(id,&word[2]); int icompute = modify->find_compute(id); if (icompute < 0) error->all(FLERR,"Invalid compute ID in variable formula"); Compute *compute = modify->compute[icompute]; delete [] id; // parse zero or one or two trailing brackets // point i beyond last bracket // nbracket = # of bracket pairs // index1,index2 = int inside each bracket pair int nbracket,index1,index2; if (str[i] != '[') nbracket = 0; else { nbracket = 1; ptr = &str[i]; index1 = int_between_brackets(ptr); i = ptr-str+1; if (str[i] == '[') { nbracket = 2; ptr = &str[i]; index2 = int_between_brackets(ptr); i = ptr-str+1; } } // c_ID = scalar from global scalar if (nbracket == 0 && compute->scalar_flag) { if (update->whichflag == 0) { if (compute->invoked_scalar != update->ntimestep) error->all(FLERR,"Compute used in variable between runs " "is not current"); } else if (!(compute->invoked_flag & INVOKED_SCALAR)) { compute->compute_scalar(); compute->invoked_flag |= INVOKED_SCALAR; } value1 = compute->scalar; if (tree) { Tree *newtree = new Tree(); newtree->type = VALUE; newtree->value = value1; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else argstack[nargstack++] = value1; // c_ID[i] = scalar from global vector } else if (nbracket == 1 && compute->vector_flag) { if (index1 > compute->size_vector) error->all(FLERR,"Variable formula compute vector " "is accessed out-of-range"); if (update->whichflag == 0) { if (compute->invoked_vector != update->ntimestep) error->all(FLERR,"Compute used in variable between runs " "is not current"); } else if (!(compute->invoked_flag & INVOKED_VECTOR)) { compute->compute_vector(); compute->invoked_flag |= INVOKED_VECTOR; } value1 = compute->vector[index1-1]; if (tree) { Tree *newtree = new Tree(); newtree->type = VALUE; newtree->value = value1; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else argstack[nargstack++] = value1; // c_ID[i][j] = scalar from global array } else if (nbracket == 2 && compute->array_flag) { if (index1 > compute->size_array_rows) error->all(FLERR,"Variable formula compute array " "is accessed out-of-range"); if (index2 > compute->size_array_cols) error->all(FLERR,"Variable formula compute array " "is accessed out-of-range"); if (update->whichflag == 0) { if (compute->invoked_array != update->ntimestep) error->all(FLERR,"Compute used in variable between runs " "is not current"); } else if (!(compute->invoked_flag & INVOKED_ARRAY)) { compute->compute_array(); compute->invoked_flag |= INVOKED_ARRAY; } value1 = compute->array[index1-1][index2-1]; if (tree) { Tree *newtree = new Tree(); newtree->type = VALUE; newtree->value = value1; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else argstack[nargstack++] = value1; // c_ID[i] = scalar from per-atom vector } else if (nbracket == 1 && compute->peratom_flag && compute->size_peratom_cols == 0) { if (update->whichflag == 0) { if (compute->invoked_peratom != update->ntimestep) error->all(FLERR,"Compute used in variable between runs " "is not current"); } else if (!(compute->invoked_flag & INVOKED_PERATOM)) { compute->compute_peratom(); compute->invoked_flag |= INVOKED_PERATOM; } peratom2global(1,NULL,compute->vector_atom,1,index1, tree,treestack,ntreestack,argstack,nargstack); // c_ID[i][j] = scalar from per-atom array } else if (nbracket == 2 && compute->peratom_flag && compute->size_peratom_cols > 0) { if (index2 > compute->size_peratom_cols) error->all(FLERR,"Variable formula compute array " "is accessed out-of-range"); if (update->whichflag == 0) { if (compute->invoked_peratom != update->ntimestep) error->all(FLERR,"Compute used in variable between runs " "is not current"); } else if (!(compute->invoked_flag & INVOKED_PERATOM)) { compute->compute_peratom(); compute->invoked_flag |= INVOKED_PERATOM; } if (compute->array_atom) peratom2global(1,NULL,&compute->array_atom[0][index2-1], compute->size_peratom_cols,index1, tree,treestack,ntreestack,argstack,nargstack); else peratom2global(1,NULL,NULL, compute->size_peratom_cols,index1, tree,treestack,ntreestack,argstack,nargstack); // c_ID = vector from per-atom vector } else if (nbracket == 0 && compute->peratom_flag && compute->size_peratom_cols == 0) { if (tree == NULL) error->all(FLERR, "Per-atom compute in equal-style variable formula"); if (update->whichflag == 0) { if (compute->invoked_peratom != update->ntimestep) error->all(FLERR,"Compute used in variable between runs " "is not current"); } else if (!(compute->invoked_flag & INVOKED_PERATOM)) { compute->compute_peratom(); compute->invoked_flag |= INVOKED_PERATOM; } Tree *newtree = new Tree(); newtree->type = ATOMARRAY; newtree->array = compute->vector_atom; newtree->nstride = 1; newtree->selfalloc = 0; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; // c_ID[i] = vector from per-atom array } else if (nbracket == 1 && compute->peratom_flag && compute->size_peratom_cols > 0) { if (tree == NULL) error->all(FLERR, "Per-atom compute in equal-style variable formula"); if (index1 > compute->size_peratom_cols) error->all(FLERR,"Variable formula compute array " "is accessed out-of-range"); if (update->whichflag == 0) { if (compute->invoked_peratom != update->ntimestep) error->all(FLERR,"Compute used in variable between runs " "is not current"); } else if (!(compute->invoked_flag & INVOKED_PERATOM)) { compute->compute_peratom(); compute->invoked_flag |= INVOKED_PERATOM; } Tree *newtree = new Tree(); newtree->type = ATOMARRAY; if (compute->array_atom) newtree->array = &compute->array_atom[0][index1-1]; else newtree->array = NULL; newtree->nstride = compute->size_peratom_cols; newtree->selfalloc = 0; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else error->all(FLERR,"Mismatched compute in variable formula"); // ---------------- // fix // ---------------- } else if (strncmp(word,"f_",2) == 0) { if (domain->box_exist == 0) error->all(FLERR, "Variable evaluation before simulation box is defined"); n = strlen(word) - 2 + 1; char *id = new char[n]; strcpy(id,&word[2]); int ifix = modify->find_fix(id); if (ifix < 0) error->all(FLERR,"Invalid fix ID in variable formula"); Fix *fix = modify->fix[ifix]; delete [] id; // parse zero or one or two trailing brackets // point i beyond last bracket // nbracket = # of bracket pairs // index1,index2 = int inside each bracket pair int nbracket,index1,index2; if (str[i] != '[') nbracket = 0; else { nbracket = 1; ptr = &str[i]; index1 = int_between_brackets(ptr); i = ptr-str+1; if (str[i] == '[') { nbracket = 2; ptr = &str[i]; index2 = int_between_brackets(ptr); i = ptr-str+1; } } // f_ID = scalar from global scalar if (nbracket == 0 && fix->scalar_flag) { if (update->whichflag > 0 && update->ntimestep % fix->global_freq) error->all(FLERR,"Fix in variable not computed at compatible time"); value1 = fix->compute_scalar(); if (tree) { Tree *newtree = new Tree(); newtree->type = VALUE; newtree->value = value1; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else argstack[nargstack++] = value1; // f_ID[i] = scalar from global vector } else if (nbracket == 1 && fix->vector_flag) { if (index1 > fix->size_vector) error->all(FLERR, "Variable formula fix vector is accessed out-of-range"); if (update->whichflag > 0 && update->ntimestep % fix->global_freq) error->all(FLERR,"Fix in variable not computed at compatible time"); value1 = fix->compute_vector(index1-1); if (tree) { Tree *newtree = new Tree(); newtree->type = VALUE; newtree->value = value1; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else argstack[nargstack++] = value1; // f_ID[i][j] = scalar from global array } else if (nbracket == 2 && fix->array_flag) { if (index1 > fix->size_array_rows) error->all(FLERR, "Variable formula fix array is accessed out-of-range"); if (index2 > fix->size_array_cols) error->all(FLERR, "Variable formula fix array is accessed out-of-range"); if (update->whichflag > 0 && update->ntimestep % fix->global_freq) error->all(FLERR,"Fix in variable not computed at compatible time"); value1 = fix->compute_array(index1-1,index2-1); if (tree) { Tree *newtree = new Tree(); newtree->type = VALUE; newtree->value = value1; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else argstack[nargstack++] = value1; // f_ID[i] = scalar from per-atom vector } else if (nbracket == 1 && fix->peratom_flag && fix->size_peratom_cols == 0) { if (update->whichflag > 0 && update->ntimestep % fix->peratom_freq) error->all(FLERR, "Fix in variable not computed at compatible time"); peratom2global(1,NULL,fix->vector_atom,1,index1, tree,treestack,ntreestack,argstack,nargstack); // f_ID[i][j] = scalar from per-atom array } else if (nbracket == 2 && fix->peratom_flag && fix->size_peratom_cols > 0) { if (index2 > fix->size_peratom_cols) error->all(FLERR, "Variable formula fix array is accessed out-of-range"); if (update->whichflag > 0 && update->ntimestep % fix->peratom_freq) error->all(FLERR,"Fix in variable not computed at compatible time"); if (fix->array_atom) peratom2global(1,NULL,&fix->array_atom[0][index2-1], fix->size_peratom_cols,index1, tree,treestack,ntreestack,argstack,nargstack); else peratom2global(1,NULL,NULL, fix->size_peratom_cols,index1, tree,treestack,ntreestack,argstack,nargstack); // f_ID = vector from per-atom vector } else if (nbracket == 0 && fix->peratom_flag && fix->size_peratom_cols == 0) { if (tree == NULL) error->all(FLERR,"Per-atom fix in equal-style variable formula"); if (update->whichflag > 0 && update->ntimestep % fix->peratom_freq) error->all(FLERR,"Fix in variable not computed at compatible time"); Tree *newtree = new Tree(); newtree->type = ATOMARRAY; newtree->array = fix->vector_atom; newtree->nstride = 1; newtree->selfalloc = 0; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; // f_ID[i] = vector from per-atom array } else if (nbracket == 1 && fix->peratom_flag && fix->size_peratom_cols > 0) { if (tree == NULL) error->all(FLERR,"Per-atom fix in equal-style variable formula"); if (index1 > fix->size_peratom_cols) error->all(FLERR, "Variable formula fix array is accessed out-of-range"); if (update->whichflag > 0 && update->ntimestep % fix->peratom_freq) error->all(FLERR,"Fix in variable not computed at compatible time"); Tree *newtree = new Tree(); newtree->type = ATOMARRAY; if (fix->array_atom) newtree->array = &fix->array_atom[0][index1-1]; else newtree->array = NULL; newtree->nstride = fix->size_peratom_cols; newtree->selfalloc = 0; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else error->all(FLERR,"Mismatched fix in variable formula"); // ---------------- // variable // ---------------- } else if (strncmp(word,"v_",2) == 0) { n = strlen(word) - 2 + 1; char *id = new char[n]; strcpy(id,&word[2]); int ivar = find(id); if (ivar < 0) error->all(FLERR,"Invalid variable name in variable formula"); if (eval_in_progress[ivar]) error->all(FLERR,"Variable has circular dependency"); // parse zero or one trailing brackets // point i beyond last bracket // nbracket = # of bracket pairs // index = int inside bracket int nbracket,index; if (str[i] != '[') nbracket = 0; else { nbracket = 1; ptr = &str[i]; index = int_between_brackets(ptr); i = ptr-str+1; } // v_name = scalar from non atom/atomfile variable if (nbracket == 0 && style[ivar] != ATOM && style[ivar] != ATOMFILE) { char *var = retrieve(id); if (var == NULL) error->all(FLERR,"Invalid variable evaluation in variable formula"); if (tree) { Tree *newtree = new Tree(); newtree->type = VALUE; newtree->value = atof(var); newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else argstack[nargstack++] = atof(var); // v_name = per-atom vector from atom-style variable // evaluate the atom-style variable as newtree } else if (nbracket == 0 && style[ivar] == ATOM) { if (tree == NULL) error->all(FLERR, "Atom-style variable in equal-style variable formula"); Tree *newtree; evaluate(data[ivar][0],&newtree); treestack[ntreestack++] = newtree; // v_name = per-atom vector from atomfile-style variable } else if (nbracket == 0 && style[ivar] == ATOMFILE) { if (tree == NULL) error->all(FLERR,"Atomfile-style variable in " "equal-style variable formula"); Tree *newtree = new Tree(); newtree->type = ATOMARRAY; newtree->array = reader[ivar]->fix->vstore; newtree->nstride = 1; newtree->selfalloc = 0; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; // v_name[N] = scalar from atom-style variable // compute the per-atom variable in result // use peratom2global to extract single value from result } else if (nbracket && style[ivar] == ATOM) { double *result; memory->create(result,atom->nlocal,"variable:result"); compute_atom(ivar,0,result,1,0); peratom2global(1,NULL,result,1,index, tree,treestack,ntreestack,argstack,nargstack); memory->destroy(result); // v_name[N] = scalar from atomfile-style variable } else if (nbracket && style[ivar] == ATOMFILE) { peratom2global(1,NULL,reader[ivar]->fix->vstore,1,index, tree,treestack,ntreestack,argstack,nargstack); } else error->all(FLERR,"Mismatched variable in variable formula"); delete [] id; // ---------------- // math/group/special function or atom value/vector or // constant or thermo keyword // ---------------- } else { // ---------------- // math or group or special function // ---------------- if (str[i] == '(') { char *contents; i = find_matching_paren(str,i,contents); i++; if (math_function(word,contents,tree, treestack,ntreestack,argstack,nargstack)); else if (group_function(word,contents,tree, treestack,ntreestack,argstack,nargstack)); else if (special_function(word,contents,tree, treestack,ntreestack,argstack,nargstack)); else error->all(FLERR,"Invalid math/group/special function " "in variable formula"); delete [] contents; // ---------------- // atom value // ---------------- } else if (str[i] == '[') { if (domain->box_exist == 0) error->all(FLERR, "Variable evaluation before simulation box is defined"); ptr = &str[i]; int id = int_between_brackets(ptr); i = ptr-str+1; peratom2global(0,word,NULL,0,id, tree,treestack,ntreestack,argstack,nargstack); // ---------------- // atom vector // ---------------- } else if (is_atom_vector(word)) { if (domain->box_exist == 0) error->all(FLERR, "Variable evaluation before simulation box is defined"); atom_vector(word,tree,treestack,ntreestack); // ---------------- // constant // ---------------- } else if (is_constant(word)) { value1 = constant(word); if (tree) { Tree *newtree = new Tree(); newtree->type = VALUE; newtree->value = value1; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else argstack[nargstack++] = value1; // ---------------- // thermo keyword // ---------------- } else { if (domain->box_exist == 0) error->all(FLERR, "Variable evaluation before simulation box is defined"); int flag = output->thermo->evaluate_keyword(word,&value1); if (flag) error->all(FLERR,"Invalid thermo keyword in variable formula"); if (tree) { Tree *newtree = new Tree(); newtree->type = VALUE; newtree->value = value1; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else argstack[nargstack++] = value1; } } delete [] word; // ---------------- // math operator, including end-of-string // ---------------- } else if (strchr("+-*/^<>=!&|%\0",onechar)) { if (onechar == '+') op = ADD; else if (onechar == '-') op = SUBTRACT; else if (onechar == '*') op = MULTIPLY; else if (onechar == '/') op = DIVIDE; else if (onechar == '%') op = MODULO; else if (onechar == '^') op = CARAT; else if (onechar == '=') { if (str[i+1] != '=') error->all(FLERR,"Invalid syntax in variable formula"); op = EQ; i++; } else if (onechar == '!') { if (str[i+1] == '=') { op = NE; i++; } else op = NOT; } else if (onechar == '<') { if (str[i+1] != '=') op = LT; else { op = LE; i++; } } else if (onechar == '>') { if (str[i+1] != '=') op = GT; else { op = GE; i++; } } else if (onechar == '&') { if (str[i+1] != '&') error->all(FLERR,"Invalid syntax in variable formula"); op = AND; i++; } else if (onechar == '|') { if (str[i+1] != '|') error->all(FLERR,"Invalid syntax in variable formula"); op = OR; i++; } else op = DONE; i++; if (op == SUBTRACT && expect == ARG) { opstack[nopstack++] = UNARY; continue; } if (op == NOT && expect == ARG) { opstack[nopstack++] = op; continue; } if (expect == ARG) error->all(FLERR,"Invalid syntax in variable formula"); expect = ARG; // evaluate stack as deep as possible while respecting precedence // before pushing current op onto stack while (nopstack && precedence[opstack[nopstack-1]] >= precedence[op]) { opprevious = opstack[--nopstack]; if (tree) { Tree *newtree = new Tree(); newtree->type = opprevious; if (opprevious == UNARY) { newtree->left = treestack[--ntreestack]; newtree->middle = newtree->right = NULL; } else { newtree->right = treestack[--ntreestack]; newtree->middle = NULL; newtree->left = treestack[--ntreestack]; } treestack[ntreestack++] = newtree; } else { value2 = argstack[--nargstack]; if (opprevious != UNARY && opprevious != NOT) value1 = argstack[--nargstack]; if (opprevious == ADD) argstack[nargstack++] = value1 + value2; else if (opprevious == SUBTRACT) argstack[nargstack++] = value1 - value2; else if (opprevious == MULTIPLY) argstack[nargstack++] = value1 * value2; else if (opprevious == DIVIDE) { if (value2 == 0.0) error->all(FLERR,"Divide by 0 in variable formula"); argstack[nargstack++] = value1 / value2; } else if (opprevious == MODULO) { if (value2 == 0.0) error->all(FLERR,"Modulo 0 in variable formula"); argstack[nargstack++] = fmod(value1,value2); } else if (opprevious == CARAT) { if (value2 == 0.0) error->all(FLERR,"Power by 0 in variable formula"); argstack[nargstack++] = pow(value1,value2); } else if (opprevious == UNARY) { argstack[nargstack++] = -value2; } else if (opprevious == NOT) { if (value2 == 0.0) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == EQ) { if (value1 == value2) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == NE) { if (value1 != value2) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == LT) { if (value1 < value2) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == LE) { if (value1 <= value2) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == GT) { if (value1 > value2) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == GE) { if (value1 >= value2) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == AND) { if (value1 != 0.0 && value2 != 0.0) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == OR) { if (value1 != 0.0 || value2 != 0.0) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } } } // if end-of-string, break out of entire formula evaluation loop if (op == DONE) break; // push current operation onto stack opstack[nopstack++] = op; } else error->all(FLERR,"Invalid syntax in variable formula"); } if (nopstack) error->all(FLERR,"Invalid syntax in variable formula"); // for atom-style variable, return remaining tree // for equal-style variable, return remaining arg if (tree) { if (ntreestack != 1) error->all(FLERR,"Invalid syntax in variable formula"); *tree = treestack[0]; return 0.0; } else { if (nargstack != 1) error->all(FLERR,"Invalid syntax in variable formula"); return argstack[0]; } } /* ---------------------------------------------------------------------- one-time collapse of an atom-style variable parse tree tree was created by one-time parsing of formula string via evaulate() only keep tree nodes that depend on ATOMARRAY, TYPEARRAY, INTARRAY remainder is converted to single VALUE this enables optimal eval_tree loop over atoms customize by adding a function: sqrt(),exp(),ln(),log(),abs(),sin(),cos(),tan(),asin(),acos(),atan(), atan2(y,x),random(x,y,z),normal(x,y,z),ceil(),floor(),round(), ramp(x,y),stagger(x,y),logfreq(x,y,z),stride(x,y,z), vdisplace(x,y),swiggle(x,y,z),cwiggle(x,y,z), gmask(x),rmask(x),grmask(x,y) ---------------------------------------------------------------------- */ double Variable::collapse_tree(Tree *tree) { double arg1,arg2; if (tree->type == VALUE) return tree->value; if (tree->type == ATOMARRAY) return 0.0; if (tree->type == TYPEARRAY) return 0.0; if (tree->type == INTARRAY) return 0.0; if (tree->type == ADD) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; tree->value = arg1 + arg2; return tree->value; } if (tree->type == SUBTRACT) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; tree->value = arg1 - arg2; return tree->value; } if (tree->type == MULTIPLY) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; tree->value = arg1 * arg2; return tree->value; } if (tree->type == DIVIDE) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (arg2 == 0.0) error->one(FLERR,"Divide by 0 in variable formula"); tree->value = arg1 / arg2; return tree->value; } if (tree->type == MODULO) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (arg2 == 0.0) error->one(FLERR,"Modulo 0 in variable formula"); tree->value = fmod(arg1,arg2); return tree->value; } if (tree->type == CARAT) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (arg2 == 0.0) error->one(FLERR,"Power by 0 in variable formula"); tree->value = pow(arg1,arg2); return tree->value; } if (tree->type == UNARY) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; tree->value = -arg1; return tree->value; } if (tree->type == NOT) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; if (arg1 == 0.0) tree->value = 1.0; else tree->value = 0.0; return tree->value; } if (tree->type == EQ) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (arg1 == arg2) tree->value = 1.0; else tree->value = 0.0; return tree->value; } if (tree->type == NE) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (arg1 != arg2) tree->value = 1.0; else tree->value = 0.0; return tree->value; } if (tree->type == LT) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (arg1 < arg2) tree->value = 1.0; else tree->value = 0.0; return tree->value; } if (tree->type == LE) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (arg1 <= arg2) tree->value = 1.0; else tree->value = 0.0; return tree->value; } if (tree->type == GT) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (arg1 > arg2) tree->value = 1.0; else tree->value = 0.0; return tree->value; } if (tree->type == GE) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (arg1 >= arg2) tree->value = 1.0; else tree->value = 0.0; return tree->value; } if (tree->type == AND) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (arg1 != 0.0 && arg2 != 0.0) tree->value = 1.0; else tree->value = 0.0; return tree->value; } if (tree->type == OR) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (arg1 != 0.0 || arg2 != 0.0) tree->value = 1.0; else tree->value = 0.0; return tree->value; } if (tree->type == SQRT) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; if (arg1 < 0.0) error->one(FLERR,"Sqrt of negative value in variable formula"); tree->value = sqrt(arg1); return tree->value; } if (tree->type == EXP) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; tree->value = exp(arg1); return tree->value; } if (tree->type == LN) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; if (arg1 <= 0.0) error->one(FLERR,"Log of zero/negative value in variable formula"); tree->value = log(arg1); return tree->value; } if (tree->type == LOG) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; if (arg1 <= 0.0) error->one(FLERR,"Log of zero/negative value in variable formula"); tree->value = log10(arg1); return tree->value; } if (tree->type == ABS) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; tree->value = fabs(arg1); return tree->value; } if (tree->type == SIN) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; tree->value = sin(arg1); return tree->value; } if (tree->type == COS) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; tree->value = cos(arg1); return tree->value; } if (tree->type == TAN) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; tree->value = tan(arg1); return tree->value; } if (tree->type == ASIN) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; if (arg1 < -1.0 || arg1 > 1.0) error->one(FLERR,"Arcsin of invalid value in variable formula"); tree->value = asin(arg1); return tree->value; } if (tree->type == ACOS) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; if (arg1 < -1.0 || arg1 > 1.0) error->one(FLERR,"Arccos of invalid value in variable formula"); tree->value = acos(arg1); return tree->value; } if (tree->type == ATAN) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; tree->value = atan(arg1); return tree->value; } if (tree->type == ATAN2) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; tree->value = atan2(arg1,arg2); return tree->value; } // random() or normal() do not become a single collapsed value if (tree->type == RANDOM) { collapse_tree(tree->left); collapse_tree(tree->middle); if (randomatom == NULL) { int seed = static_cast<int> (collapse_tree(tree->right)); if (seed <= 0) error->one(FLERR,"Invalid math function in variable formula"); randomatom = new RanMars(lmp,seed+me); } return 0.0; } if (tree->type == NORMAL) { collapse_tree(tree->left); double sigma = collapse_tree(tree->middle); if (sigma < 0.0) error->one(FLERR,"Invalid math function in variable formula"); if (randomatom == NULL) { int seed = static_cast<int> (collapse_tree(tree->right)); if (seed <= 0) error->one(FLERR,"Invalid math function in variable formula"); randomatom = new RanMars(lmp,seed+me); } return 0.0; } if (tree->type == CEIL) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; tree->value = ceil(arg1); return tree->value; } if (tree->type == FLOOR) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; tree->value = floor(arg1); return tree->value; } if (tree->type == ROUND) { arg1 = collapse_tree(tree->left); if (tree->left->type != VALUE) return 0.0; tree->type = VALUE; tree->value = MYROUND(arg1); return tree->value; } if (tree->type == RAMP) { arg1 = collapse_tree(tree->left); arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; double delta = update->ntimestep - update->beginstep; if (delta != 0.0) delta /= update->endstep - update->beginstep; tree->value = arg1 + delta*(arg2-arg1); return tree->value; } if (tree->type == STAGGER) { int ivalue1 = static_cast<int> (collapse_tree(tree->left)); int ivalue2 = static_cast<int> (collapse_tree(tree->right)); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (ivalue1 <= 0 || ivalue2 <= 0 || ivalue1 <= ivalue2) error->one(FLERR,"Invalid math function in variable formula"); int lower = update->ntimestep/ivalue1 * ivalue1; int delta = update->ntimestep - lower; if (delta < ivalue2) tree->value = lower+ivalue2; else tree->value = lower+ivalue1; return tree->value; } if (tree->type == LOGFREQ) { int ivalue1 = static_cast<int> (collapse_tree(tree->left)); int ivalue2 = static_cast<int> (collapse_tree(tree->middle)); int ivalue3 = static_cast<int> (collapse_tree(tree->right)); if (tree->left->type != VALUE || tree->middle->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (ivalue1 <= 0 || ivalue2 <= 0 || ivalue3 <= 0 || ivalue2 >= ivalue3) error->one(FLERR,"Invalid math function in variable formula"); if (update->ntimestep < ivalue1) tree->value = ivalue1; else { int lower = ivalue1; while (update->ntimestep >= ivalue3*lower) lower *= ivalue3; int multiple = update->ntimestep/lower; if (multiple < ivalue2) tree->value = (multiple+1)*lower; else tree->value = lower*ivalue3; } return tree->value; } if (tree->type == STRIDE) { int ivalue1 = static_cast<int> (collapse_tree(tree->left)); int ivalue2 = static_cast<int> (collapse_tree(tree->middle)); int ivalue3 = static_cast<int> (collapse_tree(tree->right)); if (tree->left->type != VALUE || tree->middle->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (ivalue1 < 0 || ivalue2 < 0 || ivalue3 <= 0 || ivalue1 > ivalue2) error->one(FLERR,"Invalid math function in variable formula"); if (update->ntimestep < ivalue1) tree->value = ivalue1; else if (update->ntimestep < ivalue2) { int offset = update->ntimestep - ivalue1; tree->value = ivalue1 + (offset/ivalue3)*ivalue3 + ivalue3; if (tree->value > ivalue2) tree->value = 9.0e18; } else tree->value = 9.0e18; return tree->value; } if (tree->type == VDISPLACE) { double arg1 = collapse_tree(tree->left); double arg2 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; double delta = update->ntimestep - update->beginstep; tree->value = arg1 + arg2*delta*update->dt; return tree->value; } if (tree->type == SWIGGLE) { double arg1 = collapse_tree(tree->left); double arg2 = collapse_tree(tree->middle); double arg3 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->middle->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (arg3 == 0.0) error->one(FLERR,"Invalid math function in variable formula"); double delta = update->ntimestep - update->beginstep; double omega = 2.0*MY_PI/arg3; tree->value = arg1 + arg2*sin(omega*delta*update->dt); return tree->value; } if (tree->type == CWIGGLE) { double arg1 = collapse_tree(tree->left); double arg2 = collapse_tree(tree->middle); double arg3 = collapse_tree(tree->right); if (tree->left->type != VALUE || tree->middle->type != VALUE || tree->right->type != VALUE) return 0.0; tree->type = VALUE; if (arg3 == 0.0) error->one(FLERR,"Invalid math function in variable formula"); double delta = update->ntimestep - update->beginstep; double omega = 2.0*MY_PI/arg3; tree->value = arg1 + arg2*(1.0-cos(omega*delta*update->dt)); return tree->value; } // mask functions do not become a single collapsed value if (tree->type == GMASK) return 0.0; if (tree->type == RMASK) return 0.0; if (tree->type == GRMASK) return 0.0; return 0.0; } /* ---------------------------------------------------------------------- evaluate an atom-style variable parse tree for atom I tree was created by one-time parsing of formula string via evaulate() customize by adding a function: sqrt(),exp(),ln(),log(),sin(),cos(),tan(),asin(),acos(),atan(), atan2(y,x),random(x,y,z),normal(x,y,z),ceil(),floor(),round(), ramp(x,y),stagger(x,y),logfreq(x,y,z),stride(x,y,z), vdisplace(x,y),swiggle(x,y,z),cwiggle(x,y,z), gmask(x),rmask(x),grmask(x,y) ---------------------------------------------------------------------- */ double Variable::eval_tree(Tree *tree, int i) { double arg,arg1,arg2,arg3; if (tree->type == VALUE) return tree->value; if (tree->type == ATOMARRAY) return tree->array[i*tree->nstride]; if (tree->type == TYPEARRAY) return tree->array[atom->type[i]]; if (tree->type == INTARRAY) return (double) tree->iarray[i*tree->nstride]; if (tree->type == ADD) return eval_tree(tree->left,i) + eval_tree(tree->right,i); if (tree->type == SUBTRACT) return eval_tree(tree->left,i) - eval_tree(tree->right,i); if (tree->type == MULTIPLY) return eval_tree(tree->left,i) * eval_tree(tree->right,i); if (tree->type == DIVIDE) { double denom = eval_tree(tree->right,i); if (denom == 0.0) error->one(FLERR,"Divide by 0 in variable formula"); return eval_tree(tree->left,i) / denom; } if (tree->type == MODULO) { double denom = eval_tree(tree->right,i); if (denom == 0.0) error->one(FLERR,"Modulo 0 in variable formula"); return fmod(eval_tree(tree->left,i),denom); } if (tree->type == CARAT) { double exponent = eval_tree(tree->right,i); if (exponent == 0.0) error->one(FLERR,"Power by 0 in variable formula"); return pow(eval_tree(tree->left,i),exponent); } if (tree->type == UNARY) return -eval_tree(tree->left,i); if (tree->type == NOT) { if (eval_tree(tree->left,i) == 0.0) return 1.0; else return 0.0; } if (tree->type == EQ) { if (eval_tree(tree->left,i) == eval_tree(tree->right,i)) return 1.0; else return 0.0; } if (tree->type == NE) { if (eval_tree(tree->left,i) != eval_tree(tree->right,i)) return 1.0; else return 0.0; } if (tree->type == LT) { if (eval_tree(tree->left,i) < eval_tree(tree->right,i)) return 1.0; else return 0.0; } if (tree->type == LE) { if (eval_tree(tree->left,i) <= eval_tree(tree->right,i)) return 1.0; else return 0.0; } if (tree->type == GT) { if (eval_tree(tree->left,i) > eval_tree(tree->right,i)) return 1.0; else return 0.0; } if (tree->type == GE) { if (eval_tree(tree->left,i) >= eval_tree(tree->right,i)) return 1.0; else return 0.0; } if (tree->type == AND) { if (eval_tree(tree->left,i) != 0.0 && eval_tree(tree->right,i) != 0.0) return 1.0; else return 0.0; } if (tree->type == OR) { if (eval_tree(tree->left,i) != 0.0 || eval_tree(tree->right,i) != 0.0) return 1.0; else return 0.0; } if (tree->type == SQRT) { arg1 = eval_tree(tree->left,i); if (arg1 < 0.0) error->one(FLERR,"Sqrt of negative value in variable formula"); return sqrt(arg1); } if (tree->type == EXP) return exp(eval_tree(tree->left,i)); if (tree->type == LN) { arg1 = eval_tree(tree->left,i); if (arg1 <= 0.0) error->one(FLERR,"Log of zero/negative value in variable formula"); return log(arg1); } if (tree->type == LOG) { arg1 = eval_tree(tree->left,i); if (arg1 <= 0.0) error->one(FLERR,"Log of zero/negative value in variable formula"); return log10(arg1); } if (tree->type == ABS) return fabs(eval_tree(tree->left,i)); if (tree->type == SIN) return sin(eval_tree(tree->left,i)); if (tree->type == COS) return cos(eval_tree(tree->left,i)); if (tree->type == TAN) return tan(eval_tree(tree->left,i)); if (tree->type == ASIN) { arg1 = eval_tree(tree->left,i); if (arg1 < -1.0 || arg1 > 1.0) error->one(FLERR,"Arcsin of invalid value in variable formula"); return asin(arg1); } if (tree->type == ACOS) { arg1 = eval_tree(tree->left,i); if (arg1 < -1.0 || arg1 > 1.0) error->one(FLERR,"Arccos of invalid value in variable formula"); return acos(arg1); } if (tree->type == ATAN) return atan(eval_tree(tree->left,i)); if (tree->type == ATAN2) return atan2(eval_tree(tree->left,i),eval_tree(tree->right,i)); if (tree->type == RANDOM) { double lower = eval_tree(tree->left,i); double upper = eval_tree(tree->middle,i); if (randomatom == NULL) { int seed = static_cast<int> (eval_tree(tree->right,i)); if (seed <= 0) error->one(FLERR,"Invalid math function in variable formula"); randomatom = new RanMars(lmp,seed+me); } return randomatom->uniform()*(upper-lower)+lower; } if (tree->type == NORMAL) { double mu = eval_tree(tree->left,i); double sigma = eval_tree(tree->middle,i); if (sigma < 0.0) error->one(FLERR,"Invalid math function in variable formula"); if (randomatom == NULL) { int seed = static_cast<int> (eval_tree(tree->right,i)); if (seed <= 0) error->one(FLERR,"Invalid math function in variable formula"); randomatom = new RanMars(lmp,seed+me); } return mu + sigma*randomatom->gaussian(); } if (tree->type == CEIL) return ceil(eval_tree(tree->left,i)); if (tree->type == FLOOR) return floor(eval_tree(tree->left,i)); if (tree->type == ROUND) return MYROUND(eval_tree(tree->left,i)); if (tree->type == RAMP) { arg1 = eval_tree(tree->left,i); arg2 = eval_tree(tree->right,i); double delta = update->ntimestep - update->beginstep; if (delta != 0.0) delta /= update->endstep - update->beginstep; arg = arg1 + delta*(arg2-arg1); return arg; } if (tree->type == STAGGER) { int ivalue1 = static_cast<int> (eval_tree(tree->left,i)); int ivalue2 = static_cast<int> (eval_tree(tree->right,i)); if (ivalue1 <= 0 || ivalue2 <= 0 || ivalue1 <= ivalue2) error->one(FLERR,"Invalid math function in variable formula"); int lower = update->ntimestep/ivalue1 * ivalue1; int delta = update->ntimestep - lower; if (delta < ivalue2) arg = lower+ivalue2; else arg = lower+ivalue1; return arg; } if (tree->type == LOGFREQ) { int ivalue1 = static_cast<int> (eval_tree(tree->left,i)); int ivalue2 = static_cast<int> (eval_tree(tree->middle,i)); int ivalue3 = static_cast<int> (eval_tree(tree->right,i)); if (ivalue1 <= 0 || ivalue2 <= 0 || ivalue3 <= 0 || ivalue2 >= ivalue3) error->one(FLERR,"Invalid math function in variable formula"); if (update->ntimestep < ivalue1) arg = ivalue1; else { int lower = ivalue1; while (update->ntimestep >= ivalue3*lower) lower *= ivalue3; int multiple = update->ntimestep/lower; if (multiple < ivalue2) arg = (multiple+1)*lower; else arg = lower*ivalue3; } return arg; } if (tree->type == STRIDE) { int ivalue1 = static_cast<int> (eval_tree(tree->left,i)); int ivalue2 = static_cast<int> (eval_tree(tree->middle,i)); int ivalue3 = static_cast<int> (eval_tree(tree->right,i)); if (ivalue1 < 0 || ivalue2 < 0 || ivalue3 <= 0 || ivalue1 > ivalue2) error->one(FLERR,"Invalid math function in variable formula"); if (update->ntimestep < ivalue1) arg = ivalue1; else if (update->ntimestep < ivalue2) { int offset = update->ntimestep - ivalue1; arg = ivalue1 + (offset/ivalue3)*ivalue3 + ivalue3; if (arg > ivalue2) arg = 9.0e18; } else arg = 9.0e18; return arg; } if (tree->type == VDISPLACE) { arg1 = eval_tree(tree->left,i); arg2 = eval_tree(tree->right,i); double delta = update->ntimestep - update->beginstep; arg = arg1 + arg2*delta*update->dt; return arg; } if (tree->type == SWIGGLE) { arg1 = eval_tree(tree->left,i); arg2 = eval_tree(tree->middle,i); arg3 = eval_tree(tree->right,i); if (arg3 == 0.0) error->one(FLERR,"Invalid math function in variable formula"); double delta = update->ntimestep - update->beginstep; double omega = 2.0*MY_PI/arg3; arg = arg1 + arg2*sin(omega*delta*update->dt); return arg; } if (tree->type == CWIGGLE) { arg1 = eval_tree(tree->left,i); arg2 = eval_tree(tree->middle,i); arg3 = eval_tree(tree->right,i); if (arg3 == 0.0) error->one(FLERR,"Invalid math function in variable formula"); double delta = update->ntimestep - update->beginstep; double omega = 2.0*MY_PI/arg3; arg = arg1 + arg2*(1.0-cos(omega*delta*update->dt)); return arg; } if (tree->type == GMASK) { if (atom->mask[i] & tree->ivalue1) return 1.0; else return 0.0; } if (tree->type == RMASK) { if (domain->regions[tree->ivalue1]->match(atom->x[i][0], atom->x[i][1], atom->x[i][2])) return 1.0; else return 0.0; } if (tree->type == GRMASK) { if ((atom->mask[i] & tree->ivalue1) && (domain->regions[tree->ivalue2]->match(atom->x[i][0], atom->x[i][1], atom->x[i][2]))) return 1.0; else return 0.0; } return 0.0; } /* ---------------------------------------------------------------------- */ void Variable::free_tree(Tree *tree) { if (tree->left) free_tree(tree->left); if (tree->middle) free_tree(tree->middle); if (tree->right) free_tree(tree->right); if (tree->type == ATOMARRAY && tree->selfalloc) memory->destroy(tree->array); delete tree; } /* ---------------------------------------------------------------------- find matching parenthesis in str, allocate contents = str between parens i = left paren return loc or right paren ------------------------------------------------------------------------- */ int Variable::find_matching_paren(char *str, int i,char *&contents) { // istop = matching ')' at same level, allowing for nested parens int istart = i; int ilevel = 0; while (1) { i++; if (!str[i]) break; if (str[i] == '(') ilevel++; else if (str[i] == ')' && ilevel) ilevel--; else if (str[i] == ')') break; } if (!str[i]) error->all(FLERR,"Invalid syntax in variable formula"); int istop = i; int n = istop - istart - 1; contents = new char[n+1]; strncpy(contents,&str[istart+1],n); contents[n] = '\0'; return istop; } /* ---------------------------------------------------------------------- find int between brackets and return it ptr initially points to left bracket return it pointing to right bracket error if no right bracket or brackets are empty error if any between-bracket chars are non-digits or value == 0 ------------------------------------------------------------------------- */ int Variable::int_between_brackets(char *&ptr) { char *start = ++ptr; while (*ptr && *ptr != ']') { if (!isdigit(*ptr)) error->all(FLERR,"Non digit character between brackets in variable"); ptr++; } if (*ptr != ']') error->all(FLERR,"Mismatched brackets in variable"); if (ptr == start) error->all(FLERR,"Empty brackets in variable"); *ptr = '\0'; int index = atoi(start); *ptr = ']'; if (index == 0) error->all(FLERR,"Index between variable brackets must be positive"); return index; } /* ---------------------------------------------------------------------- process a math function in formula push result onto tree or arg stack word = math function contents = str between parentheses with one,two,three args return 0 if not a match, 1 if successfully processed customize by adding a math function: sqrt(),exp(),ln(),log(),abs(),sin(),cos(),tan(),asin(),acos(),atan(), atan2(y,x),random(x,y,z),normal(x,y,z),ceil(),floor(),round(), ramp(x,y),stagger(x,y),logfreq(x,y,z),stride(x,y,z), vdisplace(x,y),swiggle(x,y,z),cwiggle(x,y,z) ------------------------------------------------------------------------- */ int Variable::math_function(char *word, char *contents, Tree **tree, Tree **treestack, int &ntreestack, double *argstack, int &nargstack) { // word not a match to any math function if (strcmp(word,"sqrt") && strcmp(word,"exp") && strcmp(word,"ln") && strcmp(word,"log") && strcmp(word,"abs") && strcmp(word,"sin") && strcmp(word,"cos") && strcmp(word,"tan") && strcmp(word,"asin") && strcmp(word,"acos") && strcmp(word,"atan") && strcmp(word,"atan2") && strcmp(word,"random") && strcmp(word,"normal") && strcmp(word,"ceil") && strcmp(word,"floor") && strcmp(word,"round") && strcmp(word,"ramp") && strcmp(word,"stagger") && strcmp(word,"logfreq") && strcmp(word,"stride") && strcmp(word,"vdisplace") && strcmp(word,"swiggle") && strcmp(word,"cwiggle")) return 0; // parse contents for arg1,arg2,arg3 separated by commas // ptr1,ptr2 = location of 1st and 2nd comma, NULL if none char *arg1,*arg2,*arg3; char *ptr1,*ptr2; ptr1 = find_next_comma(contents); if (ptr1) { *ptr1 = '\0'; ptr2 = find_next_comma(ptr1+1); if (ptr2) *ptr2 = '\0'; } else ptr2 = NULL; int n = strlen(contents) + 1; arg1 = new char[n]; strcpy(arg1,contents); int narg = 1; if (ptr1) { n = strlen(ptr1+1) + 1; arg2 = new char[n]; strcpy(arg2,ptr1+1); narg = 2; } else arg2 = NULL; if (ptr2) { n = strlen(ptr2+1) + 1; arg3 = new char[n]; strcpy(arg3,ptr2+1); narg = 3; } else arg3 = NULL; // evaluate args Tree *newtree = NULL; double value1=0.0,value2=0.0,value3=0.0; if (tree) { newtree = new Tree(); Tree *argtree; if (narg == 1) { evaluate(arg1,&argtree); newtree->left = argtree; newtree->middle = newtree->right = NULL; } else if (narg == 2) { evaluate(arg1,&argtree); newtree->left = argtree; newtree->middle = NULL; evaluate(arg2,&argtree); newtree->right = argtree; } else if (narg == 3) { evaluate(arg1,&argtree); newtree->left = argtree; evaluate(arg2,&argtree); newtree->middle = argtree; evaluate(arg3,&argtree); newtree->right = argtree; } treestack[ntreestack++] = newtree; } else { if (narg == 1) { value1 = evaluate(arg1,NULL); } else if (narg == 2) { value1 = evaluate(arg1,NULL); value2 = evaluate(arg2,NULL); } else if (narg == 3) { value1 = evaluate(arg1,NULL); value2 = evaluate(arg2,NULL); value3 = evaluate(arg3,NULL); } } if (strcmp(word,"sqrt") == 0) { if (narg != 1) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = SQRT; else { if (value1 < 0.0) error->all(FLERR,"Sqrt of negative value in variable formula"); argstack[nargstack++] = sqrt(value1); } } else if (strcmp(word,"exp") == 0) { if (narg != 1) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = EXP; else argstack[nargstack++] = exp(value1); } else if (strcmp(word,"ln") == 0) { if (narg != 1) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = LN; else { if (value1 <= 0.0) error->all(FLERR,"Log of zero/negative value in variable formula"); argstack[nargstack++] = log(value1); } } else if (strcmp(word,"log") == 0) { if (narg != 1) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = LOG; else { if (value1 <= 0.0) error->all(FLERR,"Log of zero/negative value in variable formula"); argstack[nargstack++] = log10(value1); } } else if (strcmp(word,"abs") == 0) { if (narg != 1) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = ABS; else argstack[nargstack++] = fabs(value1); } else if (strcmp(word,"sin") == 0) { if (narg != 1) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = SIN; else argstack[nargstack++] = sin(value1); } else if (strcmp(word,"cos") == 0) { if (narg != 1) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = COS; else argstack[nargstack++] = cos(value1); } else if (strcmp(word,"tan") == 0) { if (narg != 1) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = TAN; else argstack[nargstack++] = tan(value1); } else if (strcmp(word,"asin") == 0) { if (narg != 1) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = ASIN; else { if (value1 < -1.0 || value1 > 1.0) error->all(FLERR,"Arcsin of invalid value in variable formula"); argstack[nargstack++] = asin(value1); } } else if (strcmp(word,"acos") == 0) { if (narg != 1) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = ACOS; else { if (value1 < -1.0 || value1 > 1.0) error->all(FLERR,"Arccos of invalid value in variable formula"); argstack[nargstack++] = acos(value1); } } else if (strcmp(word,"atan") == 0) { if (narg != 1) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = ATAN; else argstack[nargstack++] = atan(value1); } else if (strcmp(word,"atan2") == 0) { if (narg != 2) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = ATAN2; else argstack[nargstack++] = atan2(value1,value2); } else if (strcmp(word,"random") == 0) { if (narg != 3) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = RANDOM; else { if (randomequal == NULL) { int seed = static_cast<int> (value3); if (seed <= 0) error->all(FLERR,"Invalid math function in variable formula"); randomequal = new RanMars(lmp,seed); } argstack[nargstack++] = randomequal->uniform()*(value2-value1) + value1; } } else if (strcmp(word,"normal") == 0) { if (narg != 3) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = NORMAL; else { if (value2 < 0.0) error->all(FLERR,"Invalid math function in variable formula"); if (randomequal == NULL) { int seed = static_cast<int> (value3); if (seed <= 0) error->all(FLERR,"Invalid math function in variable formula"); randomequal = new RanMars(lmp,seed); } argstack[nargstack++] = value1 + value2*randomequal->gaussian(); } } else if (strcmp(word,"ceil") == 0) { if (narg != 1) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = CEIL; else argstack[nargstack++] = ceil(value1); } else if (strcmp(word,"floor") == 0) { if (narg != 1) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = FLOOR; else argstack[nargstack++] = floor(value1); } else if (strcmp(word,"round") == 0) { if (narg != 1) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = ROUND; else argstack[nargstack++] = MYROUND(value1); } else if (strcmp(word,"ramp") == 0) { if (narg != 2) error->all(FLERR,"Invalid math function in variable formula"); if (update->whichflag == 0) error->all(FLERR,"Cannot use ramp in variable formula between runs"); if (tree) newtree->type = RAMP; else { double delta = update->ntimestep - update->beginstep; if (delta != 0.0) delta /= update->endstep - update->beginstep; double value = value1 + delta*(value2-value1); argstack[nargstack++] = value; } } else if (strcmp(word,"stagger") == 0) { if (narg != 2) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = STAGGER; else { int ivalue1 = static_cast<int> (value1); int ivalue2 = static_cast<int> (value2); if (ivalue1 <= 0 || ivalue2 <= 0 || ivalue1 <= ivalue2) error->all(FLERR,"Invalid math function in variable formula"); int lower = update->ntimestep/ivalue1 * ivalue1; int delta = update->ntimestep - lower; double value; if (delta < ivalue2) value = lower+ivalue2; else value = lower+ivalue1; argstack[nargstack++] = value; } } else if (strcmp(word,"logfreq") == 0) { if (narg != 3) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = LOGFREQ; else { int ivalue1 = static_cast<int> (value1); int ivalue2 = static_cast<int> (value2); int ivalue3 = static_cast<int> (value3); if (ivalue1 <= 0 || ivalue2 <= 0 || ivalue3 <= 0 || ivalue2 >= ivalue3) error->all(FLERR,"Invalid math function in variable formula"); double value; if (update->ntimestep < ivalue1) value = ivalue1; else { int lower = ivalue1; while (update->ntimestep >= ivalue3*lower) lower *= ivalue3; int multiple = update->ntimestep/lower; if (multiple < ivalue2) value = (multiple+1)*lower; else value = lower*ivalue3; } argstack[nargstack++] = value; } } else if (strcmp(word,"stride") == 0) { if (narg != 3) error->all(FLERR,"Invalid math function in variable formula"); if (tree) newtree->type = STRIDE; else { int ivalue1 = static_cast<int> (value1); int ivalue2 = static_cast<int> (value2); int ivalue3 = static_cast<int> (value3); if (ivalue1 < 0 || ivalue2 < 0 || ivalue3 <= 0 || ivalue1 > ivalue2) error->one(FLERR,"Invalid math function in variable formula"); double value; if (update->ntimestep < ivalue1) value = ivalue1; else if (update->ntimestep < ivalue2) { int offset = update->ntimestep - ivalue1; value = ivalue1 + (offset/ivalue3)*ivalue3 + ivalue3; if (value > ivalue2) value = 9.0e18; } else value = 9.0e18; argstack[nargstack++] = value; } } else if (strcmp(word,"vdisplace") == 0) { if (narg != 2) error->all(FLERR,"Invalid math function in variable formula"); if (update->whichflag == 0) error->all(FLERR,"Cannot use vdisplace in variable formula between runs"); if (tree) newtree->type = VDISPLACE; else { double delta = update->ntimestep - update->beginstep; double value = value1 + value2*delta*update->dt; argstack[nargstack++] = value; } } else if (strcmp(word,"swiggle") == 0) { if (narg != 3) error->all(FLERR,"Invalid math function in variable formula"); if (update->whichflag == 0) error->all(FLERR,"Cannot use swiggle in variable formula between runs"); if (tree) newtree->type = CWIGGLE; else { if (value3 == 0.0) error->all(FLERR,"Invalid math function in variable formula"); double delta = update->ntimestep - update->beginstep; double omega = 2.0*MY_PI/value3; double value = value1 + value2*sin(omega*delta*update->dt); argstack[nargstack++] = value; } } else if (strcmp(word,"cwiggle") == 0) { if (narg != 3) error->all(FLERR,"Invalid math function in variable formula"); if (update->whichflag == 0) error->all(FLERR,"Cannot use cwiggle in variable formula between runs"); if (tree) newtree->type = CWIGGLE; else { if (value3 == 0.0) error->all(FLERR,"Invalid math function in variable formula"); double delta = update->ntimestep - update->beginstep; double omega = 2.0*MY_PI/value3; double value = value1 + value2*(1.0-cos(omega*delta*update->dt)); argstack[nargstack++] = value; } } delete [] arg1; delete [] arg2; delete [] arg3; return 1; } /* ---------------------------------------------------------------------- process a group function in formula with optional region arg push result onto tree or arg stack word = group function contents = str between parentheses with one,two,three args return 0 if not a match, 1 if successfully processed customize by adding a group function with optional region arg: count(group),mass(group),charge(group), xcm(group,dim),vcm(group,dim),fcm(group,dim), bound(group,xmin),gyration(group),ke(group),angmom(group,dim), torque(group,dim),inertia(group,dim),omega(group,dim) ------------------------------------------------------------------------- */ int Variable::group_function(char *word, char *contents, Tree **tree, Tree **treestack, int &ntreestack, double *argstack, int &nargstack) { int n_ms = modify->n_fixes_style("multisphere"); if(n_ms > 0 && !static_cast<FixMultisphere*>(modify->find_fix_style("multisphere",0))->allow_group_and_set()) error->all(FLERR,"Variable command 'group' may not be used together with fix multisphere"); // word not a match to any group function if (strcmp(word,"count") && strcmp(word,"mass") && strcmp(word,"charge") && strcmp(word,"xcm") && strcmp(word,"vcm") && strcmp(word,"fcm") && strcmp(word,"bound") && strcmp(word,"gyration") && strcmp(word,"ke") && strcmp(word,"angmom") && strcmp(word,"torque") && strcmp(word,"inertia") && strcmp(word,"omega")) return 0; // parse contents for arg1,arg2,arg3 separated by commas // ptr1,ptr2 = location of 1st and 2nd comma, NULL if none char *arg1,*arg2,*arg3; char *ptr1,*ptr2; ptr1 = find_next_comma(contents); if (ptr1) { *ptr1 = '\0'; ptr2 = find_next_comma(ptr1+1); if (ptr2) *ptr2 = '\0'; } else ptr2 = NULL; int n = strlen(contents) + 1; arg1 = new char[n]; strcpy(arg1,contents); int narg = 1; if (ptr1) { n = strlen(ptr1+1) + 1; arg2 = new char[n]; strcpy(arg2,ptr1+1); narg = 2; } else arg2 = NULL; if (ptr2) { n = strlen(ptr2+1) + 1; arg3 = new char[n]; strcpy(arg3,ptr2+1); narg = 3; } else arg3 = NULL; // group to operate on int igroup = group->find(arg1); if (igroup == -1) error->all(FLERR,"Group ID in variable formula does not exist"); // match word to group function double value = 0.0; if (strcmp(word,"count") == 0) { if (narg == 1) value = group->count(igroup); else if (narg == 2) value = group->count(igroup,region_function(arg2)); else error->all(FLERR,"Invalid group function in variable formula"); } else if (strcmp(word,"mass") == 0) { if (narg == 1) value = group->mass(igroup); else if (narg == 2) value = group->mass(igroup,region_function(arg2)); else error->all(FLERR,"Invalid group function in variable formula"); } else if (strcmp(word,"charge") == 0) { if (narg == 1) value = group->charge(igroup); else if (narg == 2) value = group->charge(igroup,region_function(arg2)); else error->all(FLERR,"Invalid group function in variable formula"); } else if (strcmp(word,"xcm") == 0) { atom->check_mass(); double xcm[3]; if (narg == 2) { double masstotal = group->mass(igroup); group->xcm(igroup,masstotal,xcm); } else if (narg == 3) { int iregion = region_function(arg3); double masstotal = group->mass(igroup,iregion); group->xcm(igroup,masstotal,xcm,iregion); } else error->all(FLERR,"Invalid group function in variable formula"); if (strcmp(arg2,"x") == 0) value = xcm[0]; else if (strcmp(arg2,"y") == 0) value = xcm[1]; else if (strcmp(arg2,"z") == 0) value = xcm[2]; else error->all(FLERR,"Invalid group function in variable formula"); } else if (strcmp(word,"vcm") == 0) { atom->check_mass(); double vcm[3]; if (narg == 2) { double masstotal = group->mass(igroup); group->vcm(igroup,masstotal,vcm); } else if (narg == 3) { int iregion = region_function(arg3); double masstotal = group->mass(igroup,iregion); group->vcm(igroup,masstotal,vcm,iregion); } else error->all(FLERR,"Invalid group function in variable formula"); if (strcmp(arg2,"x") == 0) value = vcm[0]; else if (strcmp(arg2,"y") == 0) value = vcm[1]; else if (strcmp(arg2,"z") == 0) value = vcm[2]; else error->all(FLERR,"Invalid group function in variable formula"); } else if (strcmp(word,"fcm") == 0) { double fcm[3]; if (narg == 2) group->fcm(igroup,fcm); else if (narg == 3) group->fcm(igroup,fcm,region_function(arg3)); else error->all(FLERR,"Invalid group function in variable formula"); if (strcmp(arg2,"x") == 0) value = fcm[0]; else if (strcmp(arg2,"y") == 0) value = fcm[1]; else if (strcmp(arg2,"z") == 0) value = fcm[2]; else error->all(FLERR,"Invalid group function in variable formula"); } else if (strcmp(word,"bound") == 0) { double minmax[6]; if (narg == 2) group->bounds(igroup,minmax); else if (narg == 3) group->bounds(igroup,minmax,region_function(arg3)); else error->all(FLERR,"Invalid group function in variable formula"); if (strcmp(arg2,"xmin") == 0) value = minmax[0]; else if (strcmp(arg2,"xmax") == 0) value = minmax[1]; else if (strcmp(arg2,"ymin") == 0) value = minmax[2]; else if (strcmp(arg2,"ymax") == 0) value = minmax[3]; else if (strcmp(arg2,"zmin") == 0) value = minmax[4]; else if (strcmp(arg2,"zmax") == 0) value = minmax[5]; else error->all(FLERR,"Invalid group function in variable formula"); } else if (strcmp(word,"gyration") == 0) { atom->check_mass(); double xcm[3]; if (narg == 1) { double masstotal = group->mass(igroup); group->xcm(igroup,masstotal,xcm); value = group->gyration(igroup,masstotal,xcm); } else if (narg == 2) { int iregion = region_function(arg2); double masstotal = group->mass(igroup,iregion); group->xcm(igroup,masstotal,xcm,iregion); value = group->gyration(igroup,masstotal,xcm,iregion); } else error->all(FLERR,"Invalid group function in variable formula"); } else if (strcmp(word,"ke") == 0) { if (narg == 1) value = group->ke(igroup); else if (narg == 2) value = group->ke(igroup,region_function(arg2)); else error->all(FLERR,"Invalid group function in variable formula"); } else if (strcmp(word,"angmom") == 0) { atom->check_mass(); double xcm[3],lmom[3]; if (narg == 2) { double masstotal = group->mass(igroup); group->xcm(igroup,masstotal,xcm); group->angmom(igroup,xcm,lmom); } else if (narg == 3) { int iregion = region_function(arg3); double masstotal = group->mass(igroup,iregion); group->xcm(igroup,masstotal,xcm,iregion); group->angmom(igroup,xcm,lmom,iregion); } else error->all(FLERR,"Invalid group function in variable formula"); if (strcmp(arg2,"x") == 0) value = lmom[0]; else if (strcmp(arg2,"y") == 0) value = lmom[1]; else if (strcmp(arg2,"z") == 0) value = lmom[2]; else error->all(FLERR,"Invalid group function in variable formula"); } else if (strcmp(word,"torque") == 0) { atom->check_mass(); double xcm[3],tq[3]; if (narg == 2) { double masstotal = group->mass(igroup); group->xcm(igroup,masstotal,xcm); group->torque(igroup,xcm,tq); } else if (narg == 3) { int iregion = region_function(arg3); double masstotal = group->mass(igroup,iregion); group->xcm(igroup,masstotal,xcm,iregion); group->torque(igroup,xcm,tq,iregion); } else error->all(FLERR,"Invalid group function in variable formula"); if (strcmp(arg2,"x") == 0) value = tq[0]; else if (strcmp(arg2,"y") == 0) value = tq[1]; else if (strcmp(arg2,"z") == 0) value = tq[2]; else error->all(FLERR,"Invalid group function in variable formula"); } else if (strcmp(word,"inertia") == 0) { atom->check_mass(); double xcm[3],inertia[3][3]; if (narg == 2) { double masstotal = group->mass(igroup); group->xcm(igroup,masstotal,xcm); group->inertia(igroup,xcm,inertia); } else if (narg == 3) { int iregion = region_function(arg3); double masstotal = group->mass(igroup,iregion); group->xcm(igroup,masstotal,xcm,iregion); group->inertia(igroup,xcm,inertia,iregion); } else error->all(FLERR,"Invalid group function in variable formula"); if (strcmp(arg2,"xx") == 0) value = inertia[0][0]; else if (strcmp(arg2,"yy") == 0) value = inertia[1][1]; else if (strcmp(arg2,"zz") == 0) value = inertia[2][2]; else if (strcmp(arg2,"xy") == 0) value = inertia[0][1]; else if (strcmp(arg2,"yz") == 0) value = inertia[1][2]; else if (strcmp(arg2,"xz") == 0) value = inertia[0][2]; else error->all(FLERR,"Invalid group function in variable formula"); } else if (strcmp(word,"omega") == 0) { atom->check_mass(); double xcm[3],angmom[3],inertia[3][3],omega[3]; if (narg == 2) { double masstotal = group->mass(igroup); group->xcm(igroup,masstotal,xcm); group->angmom(igroup,xcm,angmom); group->inertia(igroup,xcm,inertia); group->omega(angmom,inertia,omega); } else if (narg == 3) { int iregion = region_function(arg3); double masstotal = group->mass(igroup,iregion); group->xcm(igroup,masstotal,xcm,iregion); group->angmom(igroup,xcm,angmom,iregion); group->inertia(igroup,xcm,inertia,iregion); group->omega(angmom,inertia,omega); } else error->all(FLERR,"Invalid group function in variable formula"); if (strcmp(arg2,"x") == 0) value = omega[0]; else if (strcmp(arg2,"y") == 0) value = omega[1]; else if (strcmp(arg2,"z") == 0) value = omega[2]; else error->all(FLERR,"Invalid group function in variable formula"); } delete [] arg1; delete [] arg2; delete [] arg3; // save value in tree or on argstack if (tree) { Tree *newtree = new Tree(); newtree->type = VALUE; newtree->value = value; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else argstack[nargstack++] = value; return 1; } /* ---------------------------------------------------------------------- */ int Variable::region_function(char *id) { int iregion = domain->find_region(id); if (iregion == -1) error->all(FLERR,"Region ID in variable formula does not exist"); int n_ms = modify->n_fixes_style("multisphere"); if(n_ms > 0 && !static_cast<FixMultisphere*>(modify->find_fix_style("multisphere",0))->allow_group_and_set()) error->all(FLERR,"Variable command 'region' may not be used together with fix multisphere"); // init region in case sub-regions have been deleted domain->regions[iregion]->init(); return iregion; } /* ---------------------------------------------------------------------- process a special function in formula push result onto tree or arg stack word = special function contents = str between parentheses with one,two,three args return 0 if not a match, 1 if successfully processed customize by adding a special function: sum(x),min(x),max(x),ave(x),trap(x),gmask(x),rmask(x),grmask(x,y),next(x) ------------------------------------------------------------------------- */ int Variable::special_function(char *word, char *contents, Tree **tree, Tree **treestack, int &ntreestack, double *argstack, int &nargstack) { // word not a match to any special function if (strcmp(word,"sum") && strcmp(word,"min") && strcmp(word,"max") && strcmp(word,"ave") && strcmp(word,"trap") && strcmp(word,"gmask") && strcmp(word,"rmask") && strcmp(word,"grmask") && strcmp(word,"next")) return 0; // parse contents for arg1,arg2,arg3 separated by commas // ptr1,ptr2 = location of 1st and 2nd comma, NULL if none char *arg1,*arg2,*arg3; char *ptr1,*ptr2; ptr1 = find_next_comma(contents); if (ptr1) { *ptr1 = '\0'; ptr2 = find_next_comma(ptr1+1); if (ptr2) *ptr2 = '\0'; } else ptr2 = NULL; int n = strlen(contents) + 1; arg1 = new char[n]; strcpy(arg1,contents); int narg = 1; if (ptr1) { n = strlen(ptr1+1) + 1; arg2 = new char[n]; strcpy(arg2,ptr1+1); narg = 2; } else arg2 = NULL; if (ptr2) { n = strlen(ptr2+1) + 1; arg3 = new char[n]; strcpy(arg3,ptr2+1); narg = 3; } else arg3 = NULL; // special functions that operate on global vectors if (strcmp(word,"sum") == 0 || strcmp(word,"min") == 0 || strcmp(word,"max") == 0 || strcmp(word,"ave") == 0 || strcmp(word,"trap") == 0) { int method = 0; if (strcmp(word,"sum") == 0) method = SUM; else if (strcmp(word,"min") == 0) method = XMIN; else if (strcmp(word,"max") == 0) method = XMAX; else if (strcmp(word,"ave") == 0) method = AVE; else if (strcmp(word,"trap") == 0) method = TRAP; if (narg != 1) error->all(FLERR,"Invalid special function in variable formula"); Compute *compute = NULL; Fix *fix = NULL; int index=0,nvec=0,nstride=0; if (strstr(arg1,"c_") == arg1) { ptr1 = strchr(arg1,'['); if (ptr1) { ptr2 = ptr1; index = int_between_brackets(ptr2); *ptr1 = '\0'; } else index = 0; int icompute = modify->find_compute(&arg1[2]); if (icompute < 0) error->all(FLERR,"Invalid compute ID in variable formula"); compute = modify->compute[icompute]; if (index == 0 && compute->vector_flag) { if (update->whichflag == 0) { if (compute->invoked_vector != update->ntimestep) error->all(FLERR, "Compute used in variable between runs is not current"); } else if (!(compute->invoked_flag & INVOKED_VECTOR)) { compute->compute_vector(); compute->invoked_flag |= INVOKED_VECTOR; } nvec = compute->size_vector; nstride = 1; } else if (index && compute->array_flag) { if (index > compute->size_array_cols) error->all(FLERR,"Variable formula compute array " "is accessed out-of-range"); if (update->whichflag == 0) { if (compute->invoked_array != update->ntimestep) error->all(FLERR, "Compute used in variable between runs is not current"); } else if (!(compute->invoked_flag & INVOKED_ARRAY)) { compute->compute_array(); compute->invoked_flag |= INVOKED_ARRAY; } nvec = compute->size_array_rows; nstride = compute->size_array_cols; } else error->all(FLERR,"Mismatched compute in variable formula"); } else if (strstr(arg1,"f_") == arg1) { ptr1 = strchr(arg1,'['); if (ptr1) { ptr2 = ptr1; index = int_between_brackets(ptr2); *ptr1 = '\0'; } else index = 0; int ifix = modify->find_fix(&arg1[2]); if (ifix < 0) error->all(FLERR,"Invalid fix ID in variable formula"); fix = modify->fix[ifix]; if (index == 0 && fix->vector_flag) { if (update->whichflag > 0 && update->ntimestep % fix->global_freq) error->all(FLERR,"Fix in variable not computed at compatible time"); nvec = fix->size_vector; nstride = 1; } else if (index && fix->array_flag) { if (index > fix->size_array_cols) error->all(FLERR, "Variable formula fix array is accessed out-of-range"); if (update->whichflag > 0 && update->ntimestep % fix->global_freq) error->all(FLERR,"Fix in variable not computed at compatible time"); nvec = fix->size_array_rows; nstride = fix->size_array_cols; } else error->all(FLERR,"Mismatched fix in variable formula"); } else error->all(FLERR,"Invalid special function in variable formula"); double value = 0.0; if (method == XMIN) value = BIG; if (method == XMAX) value = -BIG; if (compute) { double *vec; if (index) { if (compute->array) vec = &compute->array[0][index-1]; else vec = NULL; } else vec = compute->vector; int j = 0; for (int i = 0; i < nvec; i++) { if (method == SUM) value += vec[j]; else if (method == XMIN) value = MIN(value,vec[j]); else if (method == XMAX) value = MAX(value,vec[j]); else if (method == AVE) value += vec[j]; else if (method == TRAP) { if (i > 0 && i < nvec-1) value += vec[j]; else value += 0.5*vec[j]; } j += nstride; } } if (fix) { double one; for (int i = 0; i < nvec; i++) { if (index) one = fix->compute_array(i,index-1); else one = fix->compute_vector(i); if (method == SUM) value += one; else if (method == XMIN) value = MIN(value,one); else if (method == XMAX) value = MAX(value,one); else if (method == AVE) value += one; else if (method == TRAP) { if (i > 0 && i < nvec-1) value += one; else value += 0.5*one; } } } if (method == AVE) value /= nvec; // save value in tree or on argstack if (tree) { Tree *newtree = new Tree(); newtree->type = VALUE; newtree->value = value; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else argstack[nargstack++] = value; // mask special functions } else if (strcmp(word,"gmask") == 0) { if (tree == NULL) error->all(FLERR,"Gmask function in equal-style variable formula"); if (narg != 1) error->all(FLERR,"Invalid special function in variable formula"); int igroup = group->find(arg1); if (igroup == -1) error->all(FLERR,"Group ID in variable formula does not exist"); Tree *newtree = new Tree(); newtree->type = GMASK; newtree->ivalue1 = group->bitmask[igroup]; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else if (strcmp(word,"rmask") == 0) { if (tree == NULL) error->all(FLERR,"Rmask function in equal-style variable formula"); if (narg != 1) error->all(FLERR,"Invalid special function in variable formula"); int iregion = region_function(arg1); Tree *newtree = new Tree(); newtree->type = RMASK; newtree->ivalue1 = iregion; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else if (strcmp(word,"grmask") == 0) { if (tree == NULL) error->all(FLERR,"Grmask function in equal-style variable formula"); if (narg != 2) error->all(FLERR,"Invalid special function in variable formula"); int igroup = group->find(arg1); if (igroup == -1) error->all(FLERR,"Group ID in variable formula does not exist"); int iregion = region_function(arg2); Tree *newtree = new Tree(); newtree->type = GRMASK; newtree->ivalue1 = group->bitmask[igroup]; newtree->ivalue2 = iregion; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; // special function for file-style or atomfile-style variables } else if (strcmp(word,"next") == 0) { if (narg != 1) error->all(FLERR,"Invalid special function in variable formula"); int ivar = find(arg1); if (ivar == -1) error->all(FLERR,"Variable ID in variable formula does not exist"); // SCALARFILE has single current value, read next one // save value in tree or on argstack if (style[ivar] == SCALARFILE) { double value = atof(data[ivar][0]); int done = reader[ivar]->read_scalar(data[ivar][0]); if (done) remove(ivar); if (tree) { Tree *newtree = new Tree(); newtree->type = VALUE; newtree->value = value; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else argstack[nargstack++] = value; // ATOMFILE has per-atom values, save values in tree // copy current per-atom values into result so can read next ones // set selfalloc = 1 so result will be deleted by free_tree() after eval } else if (style[ivar] == ATOMFILE) { if (tree == NULL) error->all(FLERR,"Atomfile variable in equal-style variable formula"); double *result; memory->create(result,atom->nlocal,"variable:result"); memcpy(result,reader[ivar]->fix->vstore,atom->nlocal*sizeof(double)); int done = reader[ivar]->read_peratom(); if (done) remove(ivar); Tree *newtree = new Tree(); newtree->type = ATOMARRAY; newtree->array = result; newtree->nstride = 1; newtree->selfalloc = 1; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else error->all(FLERR,"Invalid variable style in special function next"); } delete [] arg1; delete [] arg2; delete [] arg3; return 1; } /* ---------------------------------------------------------------------- extract a global value from a per-atom quantity in a formula flag = 0 -> word is an atom vector flag = 1 -> vector is a per-atom compute or fix quantity with nstride id = positive global ID of atom, converted to local index push result onto tree or arg stack customize by adding an atom vector: id,mass,type,x,y,z,vx,vy,vz,fx,fy,fz ------------------------------------------------------------------------- */ void Variable::peratom2global(int flag, char *word, double *vector, int nstride, int id, Tree **tree, Tree **treestack, int &ntreestack, double *argstack, int &nargstack) { if (atom->map_style == 0) error->all(FLERR, "Indexed per-atom vector in variable formula without atom map"); int index = atom->map(id); double mine; if (index >= 0 && index < atom->nlocal) { if (flag == 0) { if (strcmp(word,"id") == 0) mine = atom->tag[index]; else if (strcmp(word,"mass") == 0) { if (atom->rmass) mine = atom->rmass[index]; else mine = atom->mass[atom->type[index]]; } else if (strcmp(word,"type") == 0) mine = atom->type[index]; else if (strcmp(word,"x") == 0) mine = atom->x[index][0]; else if (strcmp(word,"y") == 0) mine = atom->x[index][1]; else if (strcmp(word,"z") == 0) mine = atom->x[index][2]; else if (strcmp(word,"vx") == 0) mine = atom->v[index][0]; else if (strcmp(word,"vy") == 0) mine = atom->v[index][1]; else if (strcmp(word,"vz") == 0) mine = atom->v[index][2]; else if (strcmp(word,"fx") == 0) mine = atom->f[index][0]; else if (strcmp(word,"fy") == 0) mine = atom->f[index][1]; else if (strcmp(word,"fz") == 0) mine = atom->f[index][2]; else if ((strcmp(word,"omegax") == 0) && atom->omega_flag) mine = atom->omega[index][0]; else if ((strcmp(word,"omegay") == 0) && atom->omega_flag) mine = atom->omega[index][1]; else if ((strcmp(word,"omegaz") == 0) && atom->omega_flag) mine = atom->omega[index][2]; else if ((strcmp(word,"tqx") == 0) && atom->torque_flag) mine = atom->torque[index][0]; else if ((strcmp(word,"tqy") == 0) && atom->torque_flag) mine = atom->torque[index][1]; else if ((strcmp(word,"tqz") == 0) && atom->torque_flag) mine = atom->torque[index][2]; else if ((strcmp(word,"r") == 0) && atom->radius_flag) mine = atom->radius[index]; else error->one(FLERR,"Invalid atom vector in variable formula"); } else mine = vector[index*nstride]; } else mine = 0.0; double value; MPI_Allreduce(&mine,&value,1,MPI_DOUBLE,MPI_SUM,world); if (tree) { Tree *newtree = new Tree(); newtree->type = VALUE; newtree->value = value; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; } else argstack[nargstack++] = value; } /* ---------------------------------------------------------------------- check if word matches an atom vector return 1 if yes, else 0 customize by adding an atom vector: id,mass,type,x,y,z,vx,vy,vz,fx,fy,fz ------------------------------------------------------------------------- */ int Variable::is_atom_vector(char *word) { if (strcmp(word,"id") == 0) return 1; if (strcmp(word,"mass") == 0) return 1; if (strcmp(word,"type") == 0) return 1; if (strcmp(word,"x") == 0) return 1; if (strcmp(word,"y") == 0) return 1; if (strcmp(word,"z") == 0) return 1; if (strcmp(word,"vx") == 0) return 1; if (strcmp(word,"vy") == 0) return 1; if (strcmp(word,"vz") == 0) return 1; if (strcmp(word,"fx") == 0) return 1; if (strcmp(word,"fy") == 0) return 1; if (strcmp(word,"fz") == 0) return 1; if ((strcmp(word,"omegax") == 0) && atom->omega_flag) return 1; if ((strcmp(word,"omegay") == 0) && atom->omega_flag) return 1; if ((strcmp(word,"omegaz") == 0) && atom->omega_flag) return 1; if ((strcmp(word,"tqx") == 0) && atom->torque_flag) return 1; if ((strcmp(word,"tqy") == 0) && atom->torque_flag) return 1; if ((strcmp(word,"tqz") == 0) && atom->torque_flag) return 1; if ((strcmp(word,"r") == 0) && atom->radius_flag) return 1; return 0; } /* ---------------------------------------------------------------------- process an atom vector in formula push result onto tree word = atom vector customize by adding an atom vector: id,mass,type,x,y,z,vx,vy,vz,fx,fy,fz ------------------------------------------------------------------------- */ void Variable::atom_vector(char *word, Tree **tree, Tree **treestack, int &ntreestack) { if (tree == NULL) error->all(FLERR,"Atom vector in equal-style variable formula"); Tree *newtree = new Tree(); newtree->type = ATOMARRAY; newtree->nstride = 3; newtree->selfalloc = 0; newtree->left = newtree->middle = newtree->right = NULL; treestack[ntreestack++] = newtree; if (strcmp(word,"id") == 0) { newtree->type = INTARRAY; newtree->nstride = 1; newtree->iarray = atom->tag; } else if (strcmp(word,"mass") == 0) { if (atom->rmass) { newtree->nstride = 1; newtree->array = atom->rmass; } else { newtree->type = TYPEARRAY; newtree->array = atom->mass; } } else if (strcmp(word,"type") == 0) { newtree->type = INTARRAY; newtree->nstride = 1; newtree->iarray = atom->type; } else if (strcmp(word,"x") == 0) newtree->array = &atom->x[0][0]; else if (strcmp(word,"y") == 0) newtree->array = &atom->x[0][1]; else if (strcmp(word,"z") == 0) newtree->array = &atom->x[0][2]; else if (strcmp(word,"vx") == 0) newtree->array = &atom->v[0][0]; else if (strcmp(word,"vy") == 0) newtree->array = &atom->v[0][1]; else if (strcmp(word,"vz") == 0) newtree->array = &atom->v[0][2]; else if (strcmp(word,"fx") == 0) newtree->array = &atom->f[0][0]; else if (strcmp(word,"fy") == 0) newtree->array = &atom->f[0][1]; else if (strcmp(word,"fz") == 0) newtree->array = &atom->f[0][2]; else if ((strcmp(word,"omegax") == 0) && atom->omega_flag) newtree->array = &atom->omega[0][0]; else if ((strcmp(word,"omegay") == 0) && atom->omega_flag) newtree->array = &atom->omega[0][1]; else if ((strcmp(word,"omegaz") == 0) && atom->omega_flag) newtree->array = &atom->omega[0][2]; else if ((strcmp(word,"tqx") == 0) && atom->torque_flag) newtree->array = &atom->torque[0][0]; else if ((strcmp(word,"tqy") == 0) && atom->torque_flag) newtree->array = &atom->torque[0][1]; else if ((strcmp(word,"tqz") == 0) && atom->torque_flag) newtree->array = &atom->torque[0][2]; else if ((strcmp(word,"r") == 0) && atom->radius_flag) { newtree->nstride = 1; newtree->array = atom->radius; } } /* ---------------------------------------------------------------------- check if word matches a constant return 1 if yes, else 0 customize by adding a constant: PI ------------------------------------------------------------------------- */ int Variable::is_constant(char *word) { if (strcmp(word,"PI") == 0) return 1; return 0; } /* ---------------------------------------------------------------------- process a constant in formula customize by adding a constant: PI ------------------------------------------------------------------------- */ double Variable::constant(char *word) { if (strcmp(word,"PI") == 0) return MY_PI; return 0.0; } /* ---------------------------------------------------------------------- read a floating point value from a string generate an error if not a legitimate floating point value ------------------------------------------------------------------------- */ double Variable::numeric(char *str) { int n = strlen(str); for (int i = 0; i < n; i++) { if (isdigit(str[i])) continue; if (str[i] == '-' || str[i] == '+' || str[i] == '.') continue; if (str[i] == 'e' || str[i] == 'E') continue; error->all(FLERR, "Expected floating point parameter in variable definition"); } return atof(str); } /* ---------------------------------------------------------------------- read an integer value from a string generate an error if not a legitimate integer value ------------------------------------------------------------------------- */ int Variable::inumeric(char *str) { int n = strlen(str); for (int i = 0; i < n; i++) { if (isdigit(str[i]) || str[i] == '-' || str[i] == '+') continue; error->all(FLERR,"Expected integer parameter in variable definition"); } return atoi(str); } /* ---------------------------------------------------------------------- find next comma in str skip commas inside one or more nested parenthesis only return ptr to comma at level 0, else NULL if not found ------------------------------------------------------------------------- */ char *Variable::find_next_comma(char *str) { int level = 0; for (char *p = str; *p; ++p) { if ('(' == *p) level++; else if (')' == *p) level--; else if (',' == *p && !level) return p; } return NULL; } /* ---------------------------------------------------------------------- debug routine for printing formula tree recursively ------------------------------------------------------------------------- */ void Variable::print_tree(Tree *tree, int level) { printf("TREE %d: %d %g\n",level,tree->type,tree->value); if (tree->left) print_tree(tree->left,level+1); if (tree->middle) print_tree(tree->middle,level+1); if (tree->right) print_tree(tree->right,level+1); return; } /* ---------------------------------------------------------------------- recursive evaluation of string str called from "if" command in input script str is a boolean expression containing one or more items: number = 0.0, -5.45, 2.8e-4, ... math operation = (),x==y,x!=y,x<y,x<=y,x>y,x>=y,x&&y,x||y ------------------------------------------------------------------------- */ double Variable::evaluate_boolean(char *str) { int op,opprevious; double value1,value2; char onechar; double argstack[MAXLEVEL]; int opstack[MAXLEVEL]; int nargstack = 0; int nopstack = 0; int i = 0; int expect = ARG; while (1) { onechar = str[i]; // whitespace: just skip if (isspace(onechar)) i++; // ---------------- // parentheses: recursively evaluate contents of parens // ---------------- else if (onechar == '(') { if (expect == OP) error->all(FLERR,"Invalid Boolean syntax in if command"); expect = OP; char *contents; i = find_matching_paren(str,i,contents); i++; // evaluate contents and push on stack argstack[nargstack++] = evaluate_boolean(contents); delete [] contents; // ---------------- // number: push value onto stack // ---------------- } else if (isdigit(onechar) || onechar == '.' || onechar == '-') { if (expect == OP) error->all(FLERR,"Invalid Boolean syntax in if command"); expect = OP; // istop = end of number, including scientific notation int istart = i++; while (isdigit(str[i]) || str[i] == '.') i++; if (str[i] == 'e' || str[i] == 'E') { i++; if (str[i] == '+' || str[i] == '-') i++; while (isdigit(str[i])) i++; } int istop = i - 1; int n = istop - istart + 1; char *number = new char[n+1]; strncpy(number,&str[istart],n); number[n] = '\0'; argstack[nargstack++] = atof(number); delete [] number; // ---------------- // Boolean operator, including end-of-string // ---------------- } else if (strchr("<>=!&|\0",onechar)) { if (onechar == '=') { if (str[i+1] != '=') error->all(FLERR,"Invalid Boolean syntax in if command"); op = EQ; i++; } else if (onechar == '!') { if (str[i+1] == '=') { op = NE; i++; } else op = NOT; } else if (onechar == '<') { if (str[i+1] != '=') op = LT; else { op = LE; i++; } } else if (onechar == '>') { if (str[i+1] != '=') op = GT; else { op = GE; i++; } } else if (onechar == '&') { if (str[i+1] != '&') error->all(FLERR,"Invalid Boolean syntax in if command"); op = AND; i++; } else if (onechar == '|') { if (str[i+1] != '|') error->all(FLERR,"Invalid Boolean syntax in if command"); op = OR; i++; } else op = DONE; i++; if (op == NOT && expect == ARG) { opstack[nopstack++] = op; continue; } if (expect == ARG) error->all(FLERR,"Invalid Boolean syntax in if command"); expect = ARG; // evaluate stack as deep as possible while respecting precedence // before pushing current op onto stack while (nopstack && precedence[opstack[nopstack-1]] >= precedence[op]) { opprevious = opstack[--nopstack]; value2 = argstack[--nargstack]; if (opprevious != NOT) value1 = argstack[--nargstack]; if (opprevious == NOT) { if (value2 == 0.0) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == EQ) { if (value1 == value2) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == NE) { if (value1 != value2) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == LT) { if (value1 < value2) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == LE) { if (value1 <= value2) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == GT) { if (value1 > value2) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == GE) { if (value1 >= value2) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == AND) { if (value1 != 0.0 && value2 != 0.0) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } else if (opprevious == OR) { if (value1 != 0.0 || value2 != 0.0) argstack[nargstack++] = 1.0; else argstack[nargstack++] = 0.0; } } // if end-of-string, break out of entire formula evaluation loop if (op == DONE) break; // push current operation onto stack opstack[nopstack++] = op; } else error->all(FLERR,"Invalid Boolean syntax in if command"); } if (nopstack) error->all(FLERR,"Invalid Boolean syntax in if command"); if (nargstack != 1) error->all(FLERR,"Invalid Boolean syntax in if command"); return argstack[0]; } /* ---------------------------------------------------------------------- */ unsigned int Variable::data_mask(int ivar) { if (eval_in_progress[ivar]) return EMPTY_MASK; eval_in_progress[ivar] = 1; unsigned int datamask = data_mask(data[ivar][0]); eval_in_progress[ivar] = 0; return datamask; } /* ---------------------------------------------------------------------- */ unsigned int Variable::data_mask(char *str) { unsigned int datamask = EMPTY_MASK; for (unsigned int i=0; i < strlen(str)-2; i++) { int istart = i; while (isalnum(str[i]) || str[i] == '_') i++; int istop = i-1; int n = istop - istart + 1; char *word = new char[n+1]; strncpy(word,&str[istart],n); word[n] = '\0'; // ---------------- // compute // ---------------- if ((strncmp(word,"c_",2) == 0) && (i>0) && (!isalnum(str[i-1]))) { if (domain->box_exist == 0) error->all(FLERR, "Variable evaluation before simulation box is defined"); n = strlen(word) - 2 + 1; char *id = new char[n]; strcpy(id,&word[2]); int icompute = modify->find_compute(id); if (icompute < 0) error->all(FLERR,"Invalid compute ID in variable formula"); datamask &= modify->compute[icompute]->data_mask(); delete [] id; } if ((strncmp(word,"f_",2) == 0) && (i>0) && (!isalnum(str[i-1]))) { if (domain->box_exist == 0) error->all(FLERR, "Variable evaluation before simulation box is defined"); n = strlen(word) - 2 + 1; char *id = new char[n]; strcpy(id,&word[2]); int ifix = modify->find_fix(id); if (ifix < 0) error->all(FLERR,"Invalid fix ID in variable formula"); datamask &= modify->fix[ifix]->data_mask(); delete [] id; } if ((strncmp(word,"v_",2) == 0) && (i>0) && (!isalnum(str[i-1]))) { int ivar = find(word); datamask &= data_mask(ivar); } delete [] word; } return datamask; } /* ---------------------------------------------------------------------- class to read variable values from a file for flag = SCALARFILE, reads one value per line for flag = ATOMFILE, reads set of one value per atom ------------------------------------------------------------------------- */ VarReader::VarReader(LAMMPS *lmp, char *name, char *file, int flag) : Pointers(lmp) { me = comm->me; style = flag; if (me == 0) { fp = fopen(file,"r"); if (fp == NULL) { char str[128]; sprintf(str,"Cannot open file variable file %s",file); error->one(FLERR,str); } } else fp = NULL; // if atomfile-style variable, must store per-atom values read from file // allocate a new fix STORE, so they persist // id = variable-ID + VARIABLE_STORE, fix group = all fix = NULL; id_fix = NULL; buffer = NULL; if (style == ATOMFILE) { if (atom->map_style == 0) error->all(FLERR, "Cannot use atomfile-style variable unless atom map exists"); int n = strlen(name) + strlen("_VARIABLE_STORE") + 1; id_fix = new char[n]; strcpy(id_fix,name); strcat(id_fix,"_VARIABLE_STORE"); char **newarg = new char*[5]; newarg[0] = id_fix; newarg[1] = (char *) "all"; newarg[2] = (char *) "STORE"; newarg[3] = (char *) "0"; newarg[4] = (char *) "1"; modify->add_fix(5,newarg); fix = (FixStore *) modify->fix[modify->nfix-1]; delete [] newarg; buffer = new char[CHUNK*MAXLINE]; } } /* ---------------------------------------------------------------------- */ VarReader::~VarReader() { if (me == 0) fclose(fp); // check modify in case all fixes have already been deleted if (fix) { if (modify) modify->delete_fix(id_fix); delete [] id_fix; delete [] buffer; } } /* ---------------------------------------------------------------------- read for SCALARFILE style read next value from file into str for file-style variable strip comments, skip blank lines return 0 if successful, 1 if end-of-file ------------------------------------------------------------------------- */ int VarReader::read_scalar(char *str) { int n; char *ptr; // read one string from file if (me == 0) { while (1) { if (fgets(str,MAXLINE,fp) == NULL) n = 0; else n = strlen(str); if (n == 0) break; // end of file str[n-1] = '\0'; // strip newline if ((ptr = strchr(str,'#'))) *ptr = '\0'; // strip comment if (strtok(str," \t\n\r\f") == NULL) continue; // skip if blank n = strlen(str) + 1; break; } } MPI_Bcast(&n,1,MPI_INT,0,world); if (n == 0) return 1; MPI_Bcast(str,n,MPI_CHAR,0,world); return 0; } /* ---------------------------------------------------------------------- read snapshot of per-atom values from file into str for atomfile-style variable return 0 if successful, 1 if end-of-file ------------------------------------------------------------------------- */ int VarReader::read_peratom() { int i,m,n,tagdata,nchunk,eof; char *ptr,*next; double value; // set all per-atom values to 0.0 // values that appear in file will overwrite this double *vstore = fix->vstore; int nlocal = atom->nlocal; for (i = 0; i < nlocal; i++) vstore[i] = 0.0; // read one string from file, convert to Nlines char str[MAXLINE]; if (me == 0) { while (1) { if (fgets(str,MAXLINE,fp) == NULL) n = 0; else n = strlen(str); if (n == 0) break; // end of file str[n-1] = '\0'; // strip newline if ((ptr = strchr(str,'#'))) *ptr = '\0'; // strip comment if (strtok(str," \t\n\r\f") == NULL) continue; // skip if blank n = strlen(str) + 1; break; } } MPI_Bcast(&n,1,MPI_INT,0,world); if (n == 0) return 1; MPI_Bcast(str,n,MPI_CHAR,0,world); bigint nlines = ATOBIGINT(str); int map_tag_max = atom->map_tag_max; bigint nread = 0; while (nread < nlines) { nchunk = MIN(nlines-nread,CHUNK); eof = comm->read_lines_from_file(fp,nchunk,MAXLINE,buffer); if (eof) return 1; char *buf = buffer; for (i = 0; i < nchunk; i++) { next = strchr(buf,'\n'); *next = '\0'; sscanf(buf,"%d %lg",&tagdata,&value); if (tagdata <= 0 || tagdata > map_tag_max) error->one(FLERR,"Invalid atom ID in variable file"); if ((m = atom->map(tagdata)) >= 0) vstore[m] = value; buf = next + 1; } nread += nchunk; } return 0; }
gpl-2.0
anshumang/lammps-analytics
src/GPU/pair_lj_cut_coul_long_gpu.cpp
10975
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Mike Brown (SNL) ------------------------------------------------------------------------- */ #include "math.h" #include "stdio.h" #include "stdlib.h" #include "pair_lj_cut_coul_long_gpu.h" #include "atom.h" #include "atom_vec.h" #include "comm.h" #include "force.h" #include "neighbor.h" #include "neigh_list.h" #include "integrate.h" #include "memory.h" #include "error.h" #include "neigh_request.h" #include "universe.h" #include "update.h" #include "domain.h" #include "string.h" #include "kspace.h" #include "gpu_extra.h" #define EWALD_F 1.12837917 #define EWALD_P 0.3275911 #define A1 0.254829592 #define A2 -0.284496736 #define A3 1.421413741 #define A4 -1.453152027 #define A5 1.061405429 using namespace LAMMPS_NS; // External functions from cuda library for atom decomposition int ljcl_gpu_init(const int ntypes, double **cutsq, double **host_lj1, double **host_lj2, double **host_lj3, double **host_lj4, double **offset, double *special_lj, const int nlocal, const int nall, const int max_nbors, const int maxspecial, const double cell_size, int &gpu_mode, FILE *screen, double **host_cut_ljsq, double host_cut_coulsq, double *host_special_coul, const double qqrd2e, const double g_ewald); void ljcl_gpu_clear(); int ** ljcl_gpu_compute_n(const int ago, const int inum, const int nall, double **host_x, int *host_type, double *sublo, double *subhi, tagint *tag, int **nspecial, tagint **special, const bool eflag, const bool vflag, const bool eatom, const bool vatom, int &host_start, int **ilist, int **jnum, const double cpu_time, bool &success, double *host_q, double *boxlo, double *prd); void ljcl_gpu_compute(const int ago, const int inum, const int nall, double **host_x, int *host_type, int *ilist, int *numj, int **firstneigh, const bool eflag, const bool vflag, const bool eatom, const bool vatom, int &host_start, const double cpu_time, bool &success, double *host_q, const int nlocal, double *boxlo, double *prd); double ljcl_gpu_bytes(); /* ---------------------------------------------------------------------- */ PairLJCutCoulLongGPU::PairLJCutCoulLongGPU(LAMMPS *lmp) : PairLJCutCoulLong(lmp), gpu_mode(GPU_FORCE) { respa_enable = 0; cpu_time = 0.0; GPU_EXTRA::gpu_ready(lmp->modify, lmp->error); } /* ---------------------------------------------------------------------- free all arrays ------------------------------------------------------------------------- */ PairLJCutCoulLongGPU::~PairLJCutCoulLongGPU() { ljcl_gpu_clear(); } /* ---------------------------------------------------------------------- */ void PairLJCutCoulLongGPU::compute(int eflag, int vflag) { if (eflag || vflag) ev_setup(eflag,vflag); else evflag = vflag_fdotr = 0; int nall = atom->nlocal + atom->nghost; int inum, host_start; bool success = true; int *ilist, *numneigh, **firstneigh; if (gpu_mode != GPU_FORCE) { inum = atom->nlocal; firstneigh = ljcl_gpu_compute_n(neighbor->ago, inum, nall, atom->x, atom->type, domain->sublo, domain->subhi, atom->tag, atom->nspecial, atom->special, eflag, vflag, eflag_atom, vflag_atom, host_start, &ilist, &numneigh, cpu_time, success, atom->q, domain->boxlo, domain->prd); } else { inum = list->inum; ilist = list->ilist; numneigh = list->numneigh; firstneigh = list->firstneigh; ljcl_gpu_compute(neighbor->ago, inum, nall, atom->x, atom->type, ilist, numneigh, firstneigh, eflag, vflag, eflag_atom, vflag_atom, host_start, cpu_time, success, atom->q, atom->nlocal, domain->boxlo, domain->prd); } if (!success) error->one(FLERR,"Insufficient memory on accelerator"); if (host_start<inum) { cpu_time = MPI_Wtime(); cpu_compute(host_start, inum, eflag, vflag, ilist, numneigh, firstneigh); cpu_time = MPI_Wtime() - cpu_time; } } /* ---------------------------------------------------------------------- init specific to this pair style ------------------------------------------------------------------------- */ void PairLJCutCoulLongGPU::init_style() { cut_respa = NULL; if (!atom->q_flag) error->all(FLERR,"Pair style lj/cut/coul/long/gpu requires atom attribute q"); if (force->newton_pair) error->all(FLERR,"Cannot use newton pair with lj/cut/coul/long/gpu pair style"); // Repeat cutsq calculation because done after call to init_style double maxcut = -1.0; double cut; for (int i = 1; i <= atom->ntypes; i++) { for (int j = i; j <= atom->ntypes; j++) { if (setflag[i][j] != 0 || (setflag[i][i] != 0 && setflag[j][j] != 0)) { cut = init_one(i,j); cut *= cut; if (cut > maxcut) maxcut = cut; cutsq[i][j] = cutsq[j][i] = cut; } else cutsq[i][j] = cutsq[j][i] = 0.0; } } double cell_size = sqrt(maxcut) + neighbor->skin; cut_coulsq = cut_coul * cut_coul; // insure use of KSpace long-range solver, set g_ewald if (force->kspace == NULL) error->all(FLERR,"Pair style is incompatible with KSpace style"); g_ewald = force->kspace->g_ewald; // setup force tables if (ncoultablebits) init_tables(cut_coul,cut_respa); int maxspecial=0; if (atom->molecular) maxspecial=atom->maxspecial; int success = ljcl_gpu_init(atom->ntypes+1, cutsq, lj1, lj2, lj3, lj4, offset, force->special_lj, atom->nlocal, atom->nlocal+atom->nghost, 300, maxspecial, cell_size, gpu_mode, screen, cut_ljsq, cut_coulsq, force->special_coul, force->qqrd2e, g_ewald); GPU_EXTRA::check_flag(success,error,world); if (gpu_mode == GPU_FORCE) { int irequest = neighbor->request(this); neighbor->requests[irequest]->half = 0; neighbor->requests[irequest]->full = 1; } } /* ---------------------------------------------------------------------- */ double PairLJCutCoulLongGPU::memory_usage() { double bytes = Pair::memory_usage(); return bytes + ljcl_gpu_bytes(); } /* ---------------------------------------------------------------------- */ void PairLJCutCoulLongGPU::cpu_compute(int start, int inum, int eflag, int vflag, int *ilist, int *numneigh, int **firstneigh) { int i,j,ii,jj,jnum,itype,jtype,itable; double qtmp,xtmp,ytmp,ztmp,delx,dely,delz,evdwl,ecoul,fpair; double fraction,table; double r,r2inv,r6inv,forcecoul,forcelj,factor_coul,factor_lj; double grij,expm2,prefactor,t,erfc; int *jlist; double rsq; evdwl = ecoul = 0.0; double **x = atom->x; double **f = atom->f; double *q = atom->q; int *type = atom->type; double *special_coul = force->special_coul; double *special_lj = force->special_lj; double qqrd2e = force->qqrd2e; // loop over neighbors of my atoms for (ii = start; ii < inum; ii++) { i = ilist[ii]; qtmp = q[i]; xtmp = x[i][0]; ytmp = x[i][1]; ztmp = x[i][2]; itype = type[i]; jlist = firstneigh[i]; jnum = numneigh[i]; for (jj = 0; jj < jnum; jj++) { j = jlist[jj]; factor_lj = special_lj[sbmask(j)]; factor_coul = special_coul[sbmask(j)]; j &= NEIGHMASK; delx = xtmp - x[j][0]; dely = ytmp - x[j][1]; delz = ztmp - x[j][2]; rsq = delx*delx + dely*dely + delz*delz; jtype = type[j]; if (rsq < cutsq[itype][jtype]) { r2inv = 1.0/rsq; if (rsq < cut_coulsq) { if (!ncoultablebits || rsq <= tabinnersq) { r = sqrt(rsq); grij = g_ewald * r; expm2 = exp(-grij*grij); t = 1.0 / (1.0 + EWALD_P*grij); erfc = t * (A1+t*(A2+t*(A3+t*(A4+t*A5)))) * expm2; prefactor = qqrd2e * qtmp*q[j]/r; forcecoul = prefactor * (erfc + EWALD_F*grij*expm2); if (factor_coul < 1.0) forcecoul -= (1.0-factor_coul)*prefactor; } else { union_int_float_t rsq_lookup; rsq_lookup.f = rsq; itable = rsq_lookup.i & ncoulmask; itable >>= ncoulshiftbits; fraction = (rsq_lookup.f - rtable[itable]) * drtable[itable]; table = ftable[itable] + fraction*dftable[itable]; forcecoul = qtmp*q[j] * table; if (factor_coul < 1.0) { table = ctable[itable] + fraction*dctable[itable]; prefactor = qtmp*q[j] * table; forcecoul -= (1.0-factor_coul)*prefactor; } } } else forcecoul = 0.0; if (rsq < cut_ljsq[itype][jtype]) { r6inv = r2inv*r2inv*r2inv; forcelj = r6inv * (lj1[itype][jtype]*r6inv - lj2[itype][jtype]); } else forcelj = 0.0; fpair = (forcecoul + factor_lj*forcelj) * r2inv; f[i][0] += delx*fpair; f[i][1] += dely*fpair; f[i][2] += delz*fpair; if (eflag) { if (rsq < cut_coulsq) { if (!ncoultablebits || rsq <= tabinnersq) ecoul = prefactor*erfc; else { table = etable[itable] + fraction*detable[itable]; ecoul = qtmp*q[j] * table; } if (factor_coul < 1.0) ecoul -= (1.0-factor_coul)*prefactor; } else ecoul = 0.0; if (rsq < cut_ljsq[itype][jtype]) { evdwl = r6inv*(lj3[itype][jtype]*r6inv-lj4[itype][jtype]) - offset[itype][jtype]; evdwl *= factor_lj; } else evdwl = 0.0; } if (evflag) ev_tally_full(i,evdwl,ecoul,fpair,delx,dely,delz); } } } }
gpl-2.0
PatrizioG/WpTheme-W3Css-Underscores
functions.php
4452
<?php /** * underscores functions and definitions * * @link https://developer.wordpress.org/themes/basics/theme-functions/ * * @package underscores */ if ( ! function_exists( 'underscores_setup' ) ) : /** * Sets up theme defaults and registers support for various WordPress features. * * Note that this function is hooked into the after_setup_theme hook, which * runs before the init hook. The init hook is too late for some features, such * as indicating support for post thumbnails. */ function underscores_setup() { /* * Make theme available for translation. * Translations can be filed in the /languages/ directory. * If you're building a theme based on underscores, use a find and replace * to change 'underscores' to the name of your theme in all the template files. */ load_theme_textdomain( 'underscores', get_template_directory() . '/languages' ); // Add default posts and comments RSS feed links to head. add_theme_support( 'automatic-feed-links' ); /* * Let WordPress manage the document title. * By adding theme support, we declare that this theme does not use a * hard-coded <title> tag in the document head, and expect WordPress to * provide it for us. */ add_theme_support( 'title-tag' ); /* * Enable support for Post Thumbnails on posts and pages. * * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/ */ add_theme_support( 'post-thumbnails' ); // This theme uses wp_nav_menu() in one location. register_nav_menus( array( 'menu-1' => esc_html__( 'Primary', 'underscores' ), ) ); /* * Switch default core markup for search form, comment form, and comments * to output valid HTML5. */ add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption', ) ); // Set up the WordPress core custom background feature. add_theme_support( 'custom-background', apply_filters( 'underscores_custom_background_args', array( 'default-color' => 'ffffff', 'default-image' => '', ) ) ); // Add theme support for selective refresh for widgets. add_theme_support( 'customize-selective-refresh-widgets' ); } endif; add_action( 'after_setup_theme', 'underscores_setup' ); /** * Set the content width in pixels, based on the theme's design and stylesheet. * * Priority 0 to make it available to lower priority callbacks. * * @global int $content_width */ function underscores_content_width() { $GLOBALS['content_width'] = apply_filters( 'underscores_content_width', 640 ); } add_action( 'after_setup_theme', 'underscores_content_width', 0 ); /** * Register widget area. * * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar */ function underscores_widgets_init() { register_sidebar( array( 'name' => esc_html__( 'Sidebar', 'underscores' ), 'id' => 'sidebar-1', 'description' => esc_html__( 'Add widgets here.', 'underscores' ), 'before_widget' => '<section id="%1$s" class="widget %2$s">', 'after_widget' => '</section>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', ) ); } add_action( 'widgets_init', 'underscores_widgets_init' ); /** * Enqueue scripts and styles. */ function underscores_scripts() { wp_enqueue_style( 'underscores-style', get_stylesheet_uri() ); wp_enqueue_style( 'w3', get_template_directory_uri() . '/assets/css/w3.css',false,'4.0','all' ); wp_enqueue_script( 'underscores-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20151215', true ); wp_enqueue_script( 'underscores-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true ); if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } add_action( 'wp_enqueue_scripts', 'underscores_scripts' ); /** * Implement the Custom Header feature. */ require get_template_directory() . '/inc/custom-header.php'; /** * Custom template tags for this theme. */ require get_template_directory() . '/inc/template-tags.php'; /** * Custom functions that act independently of the theme templates. */ require get_template_directory() . '/inc/extras.php'; /** * Customizer additions. */ require get_template_directory() . '/inc/customizer.php'; /** * Load Jetpack compatibility file. */ require get_template_directory() . '/inc/jetpack.php';
gpl-2.0
panbasten/imeta
imeta3.x/imeta-src/imeta-core/src/main/java/com/plywet/imeta/repository/ObjectRevision.java
536
package com.plywet.imeta.repository; import java.util.Date; /** * A revision is simply a name, a commit comment and a date * * @author matt * */ public interface ObjectRevision { /** * @return The internal name or number of the revision */ public String getName(); /** * @return The creation date of the revision */ public Date getCreationDate(); /** * @return The revision comment */ public String getComment(); /** * @return The user that caused the revision */ public String getLogin(); }
gpl-2.0
ThiagoScar/mixerp
src/Libraries/Web API/Core/ZipCodeTypeController.cs
10304
using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web.Http; using MixERP.Net.ApplicationState.Cache; using MixERP.Net.Common.Extensions; using MixERP.Net.EntityParser; using Newtonsoft.Json; using PetaPoco; namespace MixERP.Net.Api.Core { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Zip Code Types. /// </summary> [RoutePrefix("api/v1.5/core/zip-code-type")] public class ZipCodeTypeController : ApiController { /// <summary> /// The ZipCodeType data context. /// </summary> private readonly MixERP.Net.Schemas.Core.Data.ZipCodeType ZipCodeTypeContext; public ZipCodeTypeController() { this.LoginId = AppUsers.GetCurrent().View.LoginId.ToLong(); this.UserId = AppUsers.GetCurrent().View.UserId.ToInt(); this.OfficeId = AppUsers.GetCurrent().View.OfficeId.ToInt(); this.Catalog = AppUsers.GetCurrentUserDB(); this.ZipCodeTypeContext = new MixERP.Net.Schemas.Core.Data.ZipCodeType { Catalog = this.Catalog, LoginId = this.LoginId }; } public long LoginId { get; } public int UserId { get; private set; } public int OfficeId { get; private set; } public string Catalog { get; } /// <summary> /// Counts the number of zip code types. /// </summary> /// <returns>Returns the count of the zip code types.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/core/zip-code-type/count")] public long Count() { try { return this.ZipCodeTypeContext.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Returns an instance of zip code type. /// </summary> /// <param name="zipCodeTypeId">Enter ZipCodeTypeId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("{zipCodeTypeId}")] [Route("~/api/core/zip-code-type/{zipCodeTypeId}")] public MixERP.Net.Entities.Core.ZipCodeType Get(int zipCodeTypeId) { try { return this.ZipCodeTypeContext.Get(zipCodeTypeId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Creates a paginated collection containing 25 zip code types on each page, sorted by the property ZipCodeTypeId. /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/core/zip-code-type")] public IEnumerable<MixERP.Net.Entities.Core.ZipCodeType> GetPagedResult() { try { return this.ZipCodeTypeContext.GetPagedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Creates a paginated collection containing 25 zip code types on each page, sorted by the property ZipCodeTypeId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/core/zip-code-type/page/{pageNumber}")] public IEnumerable<MixERP.Net.Entities.Core.ZipCodeType> GetPagedResult(long pageNumber) { try { return this.ZipCodeTypeContext.GetPagedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Creates a filtered and paginated collection containing 25 zip code types on each page, sorted by the property ZipCodeTypeId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/core/zip-code-type/get-where/{pageNumber}")] public IEnumerable<MixERP.Net.Entities.Core.ZipCodeType> GetWhere(long pageNumber, [FromBody]dynamic filters) { try { List<EntityParser.Filter> f = JsonConvert.DeserializeObject<List<EntityParser.Filter>>(filters); return this.ZipCodeTypeContext.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Displayfields is a lightweight key/value collection of zip code types. /// </summary> /// <returns>Returns an enumerable key/value collection of zip code types.</returns> [AcceptVerbs("GET", "HEAD")] [Route("display-fields")] [Route("~/api/core/zip-code-type/display-fields")] public IEnumerable<DisplayField> GetDisplayFields() { try { return this.ZipCodeTypeContext.GetDisplayFields(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Adds your instance of Account class. /// </summary> /// <param name="zipCodeType">Your instance of zip code types class to add.</param> [AcceptVerbs("POST")] [Route("add/{zipCodeType}")] [Route("~/api/core/zip-code-type/add/{zipCodeType}")] public void Add(MixERP.Net.Entities.Core.ZipCodeType zipCodeType) { if (zipCodeType == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.ZipCodeTypeContext.Add(zipCodeType); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Edits existing record with your instance of Account class. /// </summary> /// <param name="zipCodeType">Your instance of Account class to edit.</param> /// <param name="zipCodeTypeId">Enter the value for ZipCodeTypeId in order to find and edit the existing record.</param> [AcceptVerbs("PUT")] [Route("edit/{zipCodeTypeId}/{zipCodeType}")] [Route("~/api/core/zip-code-type/edit/{zipCodeTypeId}/{zipCodeType}")] public void Edit(int zipCodeTypeId, MixERP.Net.Entities.Core.ZipCodeType zipCodeType) { if (zipCodeType == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.ZipCodeTypeContext.Update(zipCodeType, zipCodeTypeId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Deletes an existing instance of Account class via ZipCodeTypeId. /// </summary> /// <param name="zipCodeTypeId">Enter the value for ZipCodeTypeId in order to find and delete the existing record.</param> [AcceptVerbs("DELETE")] [Route("delete/{zipCodeTypeId}")] [Route("~/api/core/zip-code-type/delete/{zipCodeTypeId}")] public void Delete(int zipCodeTypeId) { try { this.ZipCodeTypeContext.Delete(zipCodeTypeId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } } }
gpl-2.0
isel-leic-ave/ave-2015-16-sem1-i41n
aula24-observer/Observer02-delegates-lambdas.cs
1024
using System; using System.Windows.Forms; using System.Collections.Generic; class Program { static void Main() { Counter c = new Counter(); c.AddObserver(value => Console.WriteLine("ConsoleHandler = " + value)); c.AddObserver(value => MessageBox.Show("Item = " + value) ); c.DoIt(5, 7); } } /* * O Counter representa o papel de um Publisher - Lança notificações/eventos. */ class Counter { private List<Observer> obs = new List<Observer>(); public void AddObserver(Observer o) { obs.Add(o); } public void RemoveObserver(Observer o) { obs.Remove(o); } public void NotifyObservers(int n) { foreach (Observer o in obs) o.Invoke(n); } // Notifica o método de callback Feedback do objecto o, // por cada iteração de from a to. public void DoIt(int from, int to) { for (int i = from; i <= to; i++) { NotifyObservers(i); } } } /* * Definição do contracto Observer. */ delegate void Observer(int value);
gpl-2.0