code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
package games.strategy.triplea.attatchments;
import games.strategy.engine.data.Attachable;
import games.strategy.engine.data.GameData;
import games.strategy.engine.data.GameMap;
import games.strategy.engine.data.GameParseException;
import games.strategy.engine.data.PlayerID;
import games.strategy.engine.data.PlayerList;
import games.strategy.engine.data.Territory;
import games.strategy.engine.data.annotations.GameProperty;
import games.strategy.engine.data.annotations.InternalDoNotExport;
import games.strategy.triplea.delegate.Matches;
import games.strategy.triplea.delegate.OriginalOwnerTracker;
import games.strategy.util.Match;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
* The Purpose of this class is to hold shared and simple methods used by RulesAttachment
*
* @author veqryn [Mark Christopher Duncan]
*
*/
public abstract class AbstractRulesAttachment extends AbstractConditionsAttachment implements ICondition
{
private static final long serialVersionUID = -6977650137928964759L;
@InternalDoNotExport
protected boolean m_countEach = false; // Do Not Export (do not include in IAttachment). Determines if we will be counting each for the purposes of m_objectiveValue
@InternalDoNotExport
protected int m_eachMultiple = 1; // Do Not Export (do not include in IAttachment). The multiple that will be applied to m_objectiveValue if m_countEach is true
@InternalDoNotExport
protected int m_territoryCount = -1; // Do Not Export (do not include in IAttachment). Used with the next Territory conditions to determine the number of territories needed to be valid (ex: m_alliedOwnershipTerritories)
protected ArrayList<PlayerID> m_players = new ArrayList<PlayerID>(); // A list of players that can be used with directOwnershipTerritories, directExclusionTerritories, directPresenceTerritories, or any of the other territory lists
protected int m_objectiveValue = 0; // only used if the attachment begins with "objectiveAttachment"
protected int m_uses = -1; // only matters for objectiveValue, does not affect the condition
protected HashMap<Integer, Integer> m_turns = null; // condition for what turn it is
protected boolean m_switch = true; // for on/off conditions
protected String m_gameProperty = null; // allows custom GameProperties
public AbstractRulesAttachment(final String name, final Attachable attachable, final GameData gameData)
{
super(name, attachable, gameData);
}
/**
* Adds to, not sets. Anything that adds to instead of setting needs a clear function as well.
*
* @param names
* @throws GameParseException
*/
@GameProperty(xmlProperty = true, gameProperty = true, adds = true)
public void setPlayers(final String names) throws GameParseException
{
final PlayerList pl = getData().getPlayerList();
for (final String p : names.split(":"))
{
final PlayerID player = pl.getPlayerID(p);
if (player == null)
throw new GameParseException("Could not find player. name:" + p + thisErrorMsg());
m_players.add(player);
}
}
@GameProperty(xmlProperty = true, gameProperty = true, adds = false)
public void setPlayers(final ArrayList<PlayerID> value)
{
m_players = value;
}
public ArrayList<PlayerID> getPlayers()
{
if (m_players.isEmpty())
return new ArrayList<PlayerID>(Collections.singletonList((PlayerID) getAttachedTo()));
else
return m_players;
}
public void clearPlayers()
{
m_players.clear();
}
public void resetPlayers()
{
m_players = new ArrayList<PlayerID>();
}
@Override
@GameProperty(xmlProperty = true, gameProperty = true, adds = false)
public void setChance(final String chance) throws GameParseException
{
throw new GameParseException("chance not allowed for use with RulesAttachments, instead use it with Triggers or PoliticalActions" + thisErrorMsg());
}
@GameProperty(xmlProperty = true, gameProperty = true, adds = false)
public void setObjectiveValue(final String value)
{
m_objectiveValue = getInt(value);
}
@GameProperty(xmlProperty = true, gameProperty = true, adds = false)
public void setObjectiveValue(final Integer value)
{
m_objectiveValue = value;
}
public int getObjectiveValue()
{
return m_objectiveValue;
}
public void resetObjectiveValue()
{
m_objectiveValue = 0;
}
/**
* Internal use only, is not set by xml or property utils.
* Is used to determine the number of territories we need to satisfy a specific territory based condition check.
* It is set multiple times during each check [isSatisfied], as there might be multiple types of territory checks being done. So it is just a temporary value.
*
* @param value
*/
@InternalDoNotExport
protected void setTerritoryCount(final String value)
{
if (value.equals("each"))
{
m_territoryCount = 1;
m_countEach = true;
}
else
m_territoryCount = getInt(value);
}
public int getTerritoryCount()
{
return m_territoryCount;
}
/**
* Used to determine if there is a multiple on this national objective (if the user specified 'each' in the count.
* For example, you may want to have the player receive 3 PUs for controlling each territory, in a list of territories.
*
* @return
*/
public int getEachMultiple()
{
if (!getCountEach())
return 1;
return m_eachMultiple;
}
protected boolean getCountEach()
{
return m_countEach;
}
@GameProperty(xmlProperty = true, gameProperty = true, adds = false)
public void setUses(final String s)
{
m_uses = getInt(s);
}
@GameProperty(xmlProperty = true, gameProperty = true, adds = false)
public void setUses(final Integer u)
{
m_uses = u;
}
/**
* "uses" on RulesAttachments apply ONLY to giving money (PUs) to the player, they do NOT apply to the condition, and therefore should not be tested for in isSatisfied.
*
* @return
*/
public int getUses()
{
return m_uses;
}
public void resetUses()
{
m_uses = -1;
}
@GameProperty(xmlProperty = true, gameProperty = true, adds = false)
public void setSwitch(final String value)
{
m_switch = getBool(value);
}
@GameProperty(xmlProperty = true, gameProperty = true, adds = false)
public void setSwitch(final Boolean value)
{
m_switch = value;
}
public boolean getSwitch()
{
return m_switch;
}
public void resetSwitch()
{
m_switch = true;
}
@GameProperty(xmlProperty = true, gameProperty = true, adds = false)
public void setGameProperty(final String value)
{
m_gameProperty = value;
}
public String getGameProperty()
{
return m_gameProperty;
}
public boolean getGamePropertyState(final GameData data)
{
if (m_gameProperty == null)
return false;
return data.getProperties().get(m_gameProperty, false);
}
public void resetGameProperty()
{
m_gameProperty = null;
}
@GameProperty(xmlProperty = true, gameProperty = true, adds = false)
public void setTurns(final String turns) throws GameParseException
{
if (turns == null)
{
m_turns = null;
return;
}
m_turns = new HashMap<Integer, Integer>();
final String[] s = turns.split(":");
if (s.length < 1)
throw new GameParseException("Empty turn list" + thisErrorMsg());
for (final String subString : s)
{
int start, end;
try
{
start = getInt(subString);
end = start;
} catch (final Exception e)
{
final String[] s2 = subString.split("-");
if (s2.length != 2)
throw new GameParseException("Invalid syntax for turn range, must be 'int-int'" + thisErrorMsg());
start = getInt(s2[0]);
if (s2[1].equals("+"))
{
end = Integer.MAX_VALUE;
}
else
end = getInt(s2[1]);
}
final Integer t = Integer.valueOf(start);
final Integer u = Integer.valueOf(end);
m_turns.put(t, u);
}
}
@GameProperty(xmlProperty = true, gameProperty = true, adds = false)
public void setTurns(final HashMap<Integer, Integer> value)
{
m_turns = value;
}
public HashMap<Integer, Integer> getTurns()
{
return m_turns;
}
public void resetTurns()
{
m_turns = null;
}
protected boolean checkTurns(final GameData data)
{
final int turn = data.getSequence().getRound();
for (final Integer t : m_turns.keySet())
{
if (turn >= t && turn <= m_turns.get(t))
return true;
}
return false;
}
/**
* Takes a string like "original", "originalNoWater", "enemy", "controlled", "controlledNoWater", "all", "map", and turns it into an actual list of territories.
* Also sets territoryCount.
*
* @author veqryn
*/
protected Set<Territory> getTerritoriesBasedOnStringName(final String name, final Collection<PlayerID> players, final GameData data)
{
final GameMap gameMap = data.getMap();
if (name.equals("original") || name.equals("enemy")) // get all originally owned territories
{
final Set<Territory> originalTerrs = new HashSet<Territory>();
for (final PlayerID player : players)
{
originalTerrs.addAll(OriginalOwnerTracker.getOriginallyOwned(data, player));
}
setTerritoryCount(String.valueOf(originalTerrs.size()));
return originalTerrs;
}
else if (name.equals("originalNoWater")) // get all originally owned territories, but no water or impassibles
{
final Set<Territory> originalTerrs = new HashSet<Territory>();
for (final PlayerID player : players)
{
originalTerrs.addAll(Match.getMatches(OriginalOwnerTracker.getOriginallyOwned(data, player), Matches.TerritoryIsNotImpassableToLandUnits(player, data))); // TODO: does this account for occupiedTerrOf???
}
setTerritoryCount(String.valueOf(originalTerrs.size()));
return originalTerrs;
}
else if (name.equals("controlled"))
{
final Set<Territory> ownedTerrs = new HashSet<Territory>();
for (final PlayerID player : players)
{
ownedTerrs.addAll(gameMap.getTerritoriesOwnedBy(player));
}
setTerritoryCount(String.valueOf(ownedTerrs.size()));
return ownedTerrs;
}
else if (name.equals("controlledNoWater"))
{
final Set<Territory> ownedTerrsNoWater = new HashSet<Territory>();
for (final PlayerID player : players)
{
ownedTerrsNoWater.addAll(Match.getMatches(gameMap.getTerritoriesOwnedBy(player), Matches.TerritoryIsNotImpassableToLandUnits(player, data)));
}
setTerritoryCount(String.valueOf(ownedTerrsNoWater.size()));
return ownedTerrsNoWater;
}
else if (name.equals("all"))
{
final Set<Territory> allTerrs = new HashSet<Territory>();
for (final PlayerID player : players)
{
allTerrs.addAll(gameMap.getTerritoriesOwnedBy(player));
allTerrs.addAll(OriginalOwnerTracker.getOriginallyOwned(data, player));
}
setTerritoryCount(String.valueOf(allTerrs.size()));
return allTerrs;
}
else if (name.equals("map"))
{
final Set<Territory> allTerrs = new HashSet<Territory>(gameMap.getTerritories());
setTerritoryCount(String.valueOf(allTerrs.size()));
return allTerrs;
}
else
{ // The list just contained 1 territory
final Set<Territory> terr = new HashSet<Territory>();
final Territory t = data.getMap().getTerritory(name);
if (t == null)
throw new IllegalStateException("No territory called:" + name + thisErrorMsg());
terr.add(t);
setTerritoryCount(String.valueOf(1));
return terr;
}
}
/**
* Takes the raw data from the xml, and turns it into an actual territory list.
* Will also set territoryCount.
*
* @author veqryn
* @throws GameParseException
*/
protected Set<Territory> getTerritoryListBasedOnInputFromXML(final String[] terrs, final Collection<PlayerID> players, final GameData data)
{
// If there's only 1, it might be a 'group' (original, controlled, controlledNoWater, all)
if (terrs.length == 1)
{
return getTerritoriesBasedOnStringName(terrs[0], players, data);
}
else if (terrs.length == 2)
{
if (!terrs[1].equals("controlled") && !terrs[1].equals("controlledNoWater") && !terrs[1].equals("original") && !terrs[1].equals("originalNoWater") && !terrs[1].equals("all")
&& !terrs[1].equals("map") && !terrs[1].equals("enemy"))
{
return getListedTerritories(terrs, true, true); // Get the list of territories
}
else
{
final Set<Territory> rVal = getTerritoriesBasedOnStringName(terrs[1], players, data);
setTerritoryCount(String.valueOf(terrs[0])); // set it a second time, since getTerritoriesBasedOnStringName also sets it (so do it after the method call).
return rVal;
}
}
else
{
return getListedTerritories(terrs, true, true); // Get the list of territories
}
}
protected void validateNames(final String[] terrList) throws GameParseException
{
/*if (terrList != null && (!terrList.equals("controlled") && !terrList.equals("controlledNoWater") && !terrList.equals("original") && !terrList.equals("originalNoWater") && !terrList.equals("all") && !terrList.equals("map") && !terrList.equals("enemy")))
{
if (terrList.length != 2)
getListedTerritories(terrList);
else if (terrList.length == 2 && (!terrList[1].equals("controlled") && !terrList[1].equals("controlledNoWater") && !terrList[1].equals("original") && !terrList.equals("originalNoWater") && !terrList[1].equals("all") && !terrList[1].equals("map") && !terrList[1].equals("enemy")))
getListedTerritories(terrList);
}*/
if (terrList != null && terrList.length > 0)
getListedTerritories(terrList, true, true);
// removed checks for length & group commands because it breaks the setTerritoryCount feature.
}
/**
* Validate that all listed territories actually exist. Will return an empty list of territories if sent a list that is empty or contains only a "" string.
*
* @param list
* @return
* @throws GameParseException
*/
public Set<Territory> getListedTerritories(final String[] list, final boolean testFirstItemForCount, final boolean mustSetTerritoryCount)
{
final Set<Territory> rVal = new HashSet<Territory>();
// this list is null, empty, or contains "", so return a blank list of territories
if (list == null || list.length == 0 || (list.length == 1 && (list[0] == null || list[0].length() == 0)))
return rVal;
boolean haveSetCount = false;
for (int i = 0; i < list.length; i++)
{
final String name = list[i];
if (testFirstItemForCount && i == 0)
{
// See if the first entry contains the number of territories needed to meet the criteria
try
{
// check if this is an integer, and if so set territory count
getInt(name);
if (mustSetTerritoryCount)
{
haveSetCount = true;
setTerritoryCount(name);
}
continue;
} catch (final Exception e)
{
}
}
if (name.equals("each"))
{
m_countEach = true;
if (mustSetTerritoryCount)
{
haveSetCount = true;
setTerritoryCount(String.valueOf(1));
}
continue;
}
// Skip looking for the territory if the original list contains one of the 'group' commands
if (name.equals("controlled") || name.equals("controlledNoWater") || name.equals("original") || name.equals("originalNoWater") || name.equals("all")
|| name.equals("map") || name.equals("enemy"))
break;
// Validate all territories exist
final Territory territory = getData().getMap().getTerritory(name);
if (territory == null)
throw new IllegalStateException("No territory called:" + name + thisErrorMsg());
rVal.add(territory);
}
if (mustSetTerritoryCount && !haveSetCount)
{
setTerritoryCount(String.valueOf(rVal.size())); // if we have not set it, then set it to be the size of this list
}
return rVal;
}
@Override
public void validate(final GameData data) throws GameParseException
{
super.validate(data);
// TODO Auto-generated method stub
}
}
| tea-dragon/triplea | src/main/java/games/strategy/triplea/attatchments/AbstractRulesAttachment.java | Java | gpl-2.0 | 15,736 |
import styles from './index.css'
import React from 'react'
export default React.createClass({
propTypes: {
isLoading: React.PropTypes.bool.isRequired
},
render() {
return (
<div className={
this.props.isLoading === true ? styles.show : styles.hide
}></div>
)
}
})
| ndxm/nd-react-scaffold | src/components/common/loading/index.js | JavaScript | gpl-2.0 | 306 |
$.ajax({
async: false,
url: "http://api.visalus.com/ITReporting/SalesAnalytics/GetDataBySP/?SPName=usp_PROMO_ViCrunch3FF_JSON&?",
type: 'GET',
dataType: 'jsonp',
success: function (data) {
var result = JSON.stringify(data);
//alert(result);
var obj = jQuery.parseJSON(result);
var output="<table class='standings-table' width='100%'><tr class='head'><td align='center'>Rank</td><td>Name</td><td>Location</td><td align='center'>VIP Tier</td></tr>";
for (var i in obj) {
output+="<tr><td align='center'>" + obj[i].Rank + "</td><td>" + obj[i].Name + "</td><td>" + obj[i].Location + "</td><td align='center'>" + obj[i].VIPtier + "</td></tr>";
}
output+="</table>";
document.getElementById("crunchtime").innerHTML = output;
},
error: function (e) {
alert('fail');
}
});
| tsmulugeta/vi.com | js/crunchtime.js | JavaScript | gpl-2.0 | 1,074 |
Index imovel | wdantas/ImobControl | admin/application/views/imovel/index.php | PHP | gpl-2.0 | 12 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* 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.
*
* $URL$
* $Id$
*
*/
#ifdef ENABLE_LOL
#include "kyra/lol.h"
#include "kyra/screen_lol.h"
#include "kyra/timer.h"
#include "kyra/resource.h"
#include "common/endian.h"
namespace Kyra {
void LoLEngine::runInitScript(const char *filename, int optionalFunc) {
_suspendScript = true;
EMCData scriptData;
EMCState scriptState;
memset(&scriptData, 0, sizeof(EMCData));
_emc->unload(&_scriptData);
_emc->load(filename, &scriptData, &_opcodes);
_emc->init(&scriptState, &scriptData);
_emc->start(&scriptState, 0);
while (_emc->isValid(&scriptState))
_emc->run(&scriptState);
if (optionalFunc) {
_emc->init(&scriptState, &scriptData);
_emc->start(&scriptState, optionalFunc);
while (_emc->isValid(&scriptState))
_emc->run(&scriptState);
}
_emc->unload(&scriptData);
_suspendScript = false;
}
void LoLEngine::runInfScript(const char *filename) {
_emc->unload(&_scriptData);
_emc->load(filename, &_scriptData, &_opcodes);
runLevelScript(0x400, -1);
}
void LoLEngine::runLevelScript(int block, int flags) {
runLevelScriptCustom(block, flags, -1, 0, 0, 0);
}
void LoLEngine::runLevelScriptCustom(int block, int flags, int charNum, int item, int reg3, int reg4) {
EMCState scriptState;
memset(&scriptState, 0, sizeof(EMCState));
if (!_suspendScript) {
_emc->init(&scriptState, &_scriptData);
_emc->start(&scriptState, block);
scriptState.regs[0] = flags;
scriptState.regs[1] = charNum;
scriptState.regs[2] = item;
scriptState.regs[3] = reg3;
scriptState.regs[4] = reg4;
scriptState.regs[5] = block;
scriptState.regs[6] = _scriptDirection;
if (_emc->isValid(&scriptState)) {
if (*(scriptState.ip - 1) & flags) {
while (_emc->isValid(&scriptState))
_emc->run(&scriptState);
}
}
}
checkSceneUpdateNeed(block);
}
bool LoLEngine::checkSceneUpdateNeed(int func) {
if (_sceneUpdateRequired)
return true;
for (int i = 0; i < 15; i++) {
if (_visibleBlockIndex[i] == func) {
_sceneUpdateRequired = true;
return true;
}
}
if (_currentBlock == func){
_sceneUpdateRequired = true;
return true;
}
return false;
}
int LoLEngine::olol_setWallType(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setWallType(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
if (stackPos(2) != -1) {
if (_wllWallFlags[stackPos(2)] & 4)
deleteMonstersFromBlock(stackPos(0));
}
setWallType(stackPos(0), stackPos(1), stackPos(2));
return 1;
}
int LoLEngine::olol_getWallType(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getWallType(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
return _levelBlockProperties[stackPos(0)].walls[stackPos(1) & 3];
}
int LoLEngine::olol_drawScene(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_drawScene(%p) (%d)", (const void *)script, stackPos(0));
drawScene(stackPos(0));
return 1;
}
int LoLEngine::olol_rollDice(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_rollDice(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
return rollDice(stackPos(0), stackPos(1));
}
int LoLEngine::olol_moveParty(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_moveParty(%p) (%d)", (const void *)script, stackPos(0));
int mode = stackPos(0);
if (mode > 5 && mode < 10)
mode = (mode - 6 - _currentDirection) & 3;
Button b;
b.data0Val2 = b.data1Val2 = b.data2Val2 = 0xfe;
b.data0Val3 = b.data1Val3 = b.data2Val3 = 0x01;
switch (mode) {
case 0:
clickedUpArrow(&b);
break;
case 1:
clickedRightArrow(&b);
break;
case 2:
clickedDownArrow(&b);
break;
case 3:
clickedLeftArrow(&b);
break;
case 4:
clickedTurnLeftArrow(&b);
break;
case 5:
clickedTurnRightArrow(&b);
break;
case 10:
case 11:
case 12:
case 13:
mode = ABS(mode - 10 - _currentDirection);
if (mode > 2)
mode = (mode ^ 2) * -1;
while (mode) {
if (mode > 0) {
clickedTurnRightArrow(&b);
mode--;
} else {
clickedTurnLeftArrow(&b);
mode++;
}
}
break;
default:
break;
}
return 1;
}
int LoLEngine::olol_delay(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_delay(%p) (%d)", (const void *)script, stackPos(0));
delay(stackPos(0) * _tickLength, true);
return 1;
}
int LoLEngine::olol_setGameFlag(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setGameFlag(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
if (stackPos(1))
setGameFlag(stackPos(0));
else
resetGameFlag(stackPos(0));
return 1;
}
int LoLEngine::olol_testGameFlag(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_testGameFlag(%p) (%d)", (const void *)script, stackPos(0));
if (stackPos(0) < 0)
return 0;
return queryGameFlag(stackPos(0));
}
int LoLEngine::olol_loadLevelGraphics(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_loadLevelGraphics(%p) (%s, %d, %d, %d, %d, %d)", (const void *)script, stackPosString(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5));
loadLevelGraphics(stackPosString(0), stackPos(1), stackPos(2), stackPos(3) == -1 ? -1 : (uint16)stackPos(3), stackPos(4) == -1 ? -1 : (uint16)stackPos(4), (stackPos(5) == -1) ? 0 : stackPosString(5));
return 1;
}
int LoLEngine::olol_loadBlockProperties(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_loadBlockProperties(%p) (%s)", (const void *)script, stackPosString(0));
loadBlockProperties(stackPosString(0));
return 1;
}
int LoLEngine::olol_loadMonsterShapes(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_loadMonsterShapes(%p) (%s, %d, %d)", (const void *)script, stackPosString(0), stackPos(1), stackPos(2));
loadMonsterShapes(stackPosString(0), stackPos(1), stackPos(2));
return 1;
}
int LoLEngine::olol_deleteHandItem(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_deleteHandItem(%p) ()", (const void *)script);
int r = _itemInHand;
deleteItem(_itemInHand);
setHandItem(0);
return r;
}
int LoLEngine::olol_allocItemPropertiesBuffer(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_allocItemPropertiesBuffer(%p) (%d)", (const void *)script, stackPos(0));
delete[] _itemProperties;
_itemProperties = new ItemProperty[stackPos(0)];
return 1;
}
int LoLEngine::olol_setItemProperty(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setItemProperty(%p) (%d, %d, %d, %d, %d, %d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5), stackPos(6), stackPos(7), stackPos(8), stackPos(9));
ItemProperty *tmp = &_itemProperties[stackPos(0)];
tmp->nameStringId = stackPos(1);
tmp->shpIndex = stackPos(2);
tmp->type = stackPos(3);
// WORKAROUND for unpatched early floppy versions.
// The Vaelan's cube should not be able to be equipped in a weapon slot.
if (stackPos(0) == 264 && tmp->type == 5)
tmp->type = 0;
tmp->itemScriptFunc = stackPos(4);
tmp->might = stackPos(5);
tmp->skill = stackPos(6);
tmp->protection = stackPos(7);
tmp->flags = stackPos(8);
tmp->unkB = stackPos(9);
return 1;
}
int LoLEngine::olol_makeItem(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_makeItem(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
return makeItem(stackPos(0), stackPos(1), stackPos(2));
}
int LoLEngine::olol_placeMoveLevelItem(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setItemProperty(%p) (%d, %d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5));
placeMoveLevelItem(stackPos(0), stackPos(1), stackPos(2), stackPos(3) & 0xff, stackPos(4) & 0xff, stackPos(5));
return 1;
}
int LoLEngine::olol_createLevelItem(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setItemProperty(%p) (%d, %d, %d, %d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5), stackPos(6), stackPos(7));
int item = makeItem(stackPos(0), stackPos(1), stackPos(2));
if (item == -1)
return item;
placeMoveLevelItem(item, stackPos(3), stackPos(4), stackPos(5), stackPos(6), stackPos(7));
return item;
}
int LoLEngine::olol_getItemPara(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getItemPara(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
if (!stackPos(0))
return 0;
ItemInPlay *i = &_itemsInPlay[stackPos(0)];
ItemProperty *p = &_itemProperties[i->itemPropertyIndex];
switch (stackPos(1)) {
case 0:
return i->block;
case 1:
return i->x;
case 2:
return i->y;
case 3:
return i->level;
case 4:
return i->itemPropertyIndex;
case 5:
return i->shpCurFrame_flg;
case 6:
return p->nameStringId;
case 7:
break;
case 8:
return p->shpIndex;
case 9:
return p->type;
case 10:
return p->itemScriptFunc;
case 11:
return p->might;
case 12:
return p->skill;
case 13:
return p->protection;
case 14:
return p->unkB;
case 15:
return i->shpCurFrame_flg & 0x1fff;
case 16:
return p->flags;
case 17:
return (p->skill << 8) | ((uint8)p->might);
default:
break;
}
return -1;
}
int LoLEngine::olol_getCharacterStat(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getCharacterStat(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
LoLCharacter *c = &_characters[stackPos(0)];
int d = stackPos(2);
switch (stackPos(1)) {
case 0:
return c->flags;
case 1:
return c->raceClassSex;
case 5:
return c->hitPointsCur;
case 6:
return c->hitPointsMax;
case 7:
return c->magicPointsCur;
case 8:
return c->magicPointsMax;
case 9:
return c->itemProtection;
case 10:
return c->items[d];
case 11:
return c->skillLevels[d] + c->skillModifiers[d];
case 12:
return c->protectionAgainstItems[d];
case 13:
return (d & 0x80) ? c->itemsMight[7] : c->itemsMight[d];
case 14:
return c->skillModifiers[d];
case 15:
return c->id;
default:
break;
}
return 0;
}
int LoLEngine::olol_setCharacterStat(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setCharacterStat(%p) (%d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3));
LoLCharacter *c = &_characters[stackPos(0)];
int d = stackPos(2);
int e = stackPos(3);
switch (stackPos(1)) {
case 0:
c->flags = e;
break;
case 1:
c->raceClassSex = e & 0x0f;
break;
case 5:
setCharacterMagicOrHitPoints(stackPos(0), 0, e, 0);
break;
case 6:
c->hitPointsMax = e;
break;
case 7:
setCharacterMagicOrHitPoints(stackPos(0), 1, e, 0);
break;
case 8:
c->magicPointsMax = e;
break;
case 9:
c->itemProtection = e;
break;
case 10:
c->items[d] = 0;
break;
case 11:
c->skillLevels[d] = e;
break;
case 12:
c->protectionAgainstItems[d] = e;
break;
case 13:
if (d & 0x80)
c->itemsMight[7] = e;
else
c->itemsMight[d] = e;
break;
case 14:
c->skillModifiers[d] = e;
break;
default:
break;
}
return 0;
}
int LoLEngine::olol_loadLevelShapes(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_loadLevelShapes(%p) (%s, %s)", (const void *)script, stackPosString(0), stackPosString(1));
loadLevelShpDat(stackPosString(0), stackPosString(1), true);
return 1;
}
int LoLEngine::olol_closeLevelShapeFile(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_closeLevelShapeFile(%p) ()", (const void *)script);
delete _lvlShpFileHandle;
_lvlShpFileHandle = 0;
return 1;
}
int LoLEngine::olol_loadDoorShapes(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_loadDoorShapes(%p) (%s, %d, %d)", (const void *)script, stackPosString(0), stackPos(1), stackPos(2));
_screen->loadBitmap(stackPosString(0), 3, 3, 0);
const uint8 *p = _screen->getCPagePtr(2);
if (_doorShapes[0])
delete[] _doorShapes[0];
_doorShapes[0] = _screen->makeShapeCopy(p, stackPos(1));
if (_doorShapes[1])
delete[] _doorShapes[1];
_doorShapes[1] = _screen->makeShapeCopy(p, stackPos(2));
for (int i = 0; i < 20; i++) {
_wllWallFlags[i + 3] |= 7;
int t = i % 5;
if (t == 4)
_wllWallFlags[i + 3] &= 0xf8;
if (t == 3)
_wllWallFlags[i + 3] &= 0xfd;
}
if (stackPos(3)) {
for (int i = 3; i < 13; i++)
_wllWallFlags[i] &= 0xfd;
}
if (stackPos(4)) {
for (int i = 13; i < 23; i++)
_wllWallFlags[i] &= 0xfd;
}
return 1;
}
int LoLEngine::olol_initAnimStruct(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_initAnimStruct(%p) (%s, %d, %d, %d, %d, %d)", (const void *)script, stackPosString(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5));
if (_tim->initAnimStruct(stackPos(1), stackPosString(0), stackPos(2), stackPos(3), stackPos(4), 0, stackPos(5)))
return 1;
return 0;
}
int LoLEngine::olol_playAnimationPart(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_playAnimationPart(%p) (%d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3));
_animator->playPart(stackPos(0), stackPos(1), stackPos(2), stackPos(3));
return 1;
}
int LoLEngine::olol_freeAnimStruct(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_freeAnimStruct(%p) (%d)", (const void *)script, stackPos(0));
if (_tim->freeAnimStruct(stackPos(0)))
return 1;
return 0;
}
int LoLEngine::olol_getDirection(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getDirection(%p)", (const void *)script);
return _currentDirection;
}
int LoLEngine::olol_characterSurpriseFeedback(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_characterSurpriseFeedback(%p)", (const void *)script);
for (int i = 0; i < 4; i++) {
if (!(_characters[i].flags & 1) || _characters[i].id >= 0)
continue;
int s = -_characters[i].id;
int sfx = (s == 1) ? 136 : ((s == 5) ? 50 : ((s == 8) ? 49 : ((s == 9) ? 48 : 0)));
if (sfx)
snd_playSoundEffect(sfx, -1);
return 1;
}
return 1;
}
int LoLEngine::olol_setMusicTrack(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setMusicTrack(%p) (%d)", (const void *)script, stackPos(0));
_curMusicTheme = stackPos(0);
return 1;
}
int LoLEngine::olol_setSequenceButtons(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setSequenceButtons(%p) (%d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4));
setSequenceButtons(stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4));
return 1;
}
int LoLEngine::olol_setDefaultButtonState(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setDefaultButtonState(%p)", (const void *)script);
setDefaultButtonState();
return 1;
}
int LoLEngine::olol_checkRectForMousePointer(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_checkRectForMousePointer(%p) (%d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3));
return posWithinRect(_mouseX, _mouseY, stackPos(0), stackPos(1), stackPos(2), stackPos(3)) ? 1 : 0;
}
int LoLEngine::olol_clearDialogueField(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_clearDialogueField(%p) (%d)", (const void *)script, stackPos(0));
if (_currentControlMode && (!textEnabled()))
return 1;
_screen->setScreenDim(5);
const ScreenDim *d = _screen->getScreenDim(5);
_screen->fillRect(d->sx, d->sy, d->sx + d->w - (_flags.use16ColorMode ? 3 : 2), d->sy + d->h - 2, d->unkA);
_txt->clearDim(4);
_txt->resetDimTextPositions(4);
return 1;
}
int LoLEngine::olol_setupBackgroundAnimationPart(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setupBackgroundAnimationPart(%p) (%d, %d, %d, %d, %d, %d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5), stackPos(6), stackPos(7), stackPos(8), stackPos(9));
_animator->setupPart(stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5), stackPos(6), stackPos(7), stackPos(8), stackPos(9));
return 0;
}
int LoLEngine::olol_startBackgroundAnimation(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_startBackgroundAnimation(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
_animator->start(stackPos(0), stackPos(1));
return 1;
}
int LoLEngine::olol_fadeToBlack(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_fadeToBlack(%p) (%d)", (const void *)script, stackPos(0));
_screen->fadeToBlack(10);
return 1;
}
int LoLEngine::olol_fadePalette(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_fadePalette(%p)", (const void *)script);
if (_flags.use16ColorMode)
setPaletteBrightness(_screen->getPalette(0), _brightness, _lampEffect);
else
_screen->fadePalette(_screen->getPalette(3), 10);
_screen->_fadeFlag = 0;
return 1;
}
int LoLEngine::olol_loadBitmap(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_loadBitmap(%p) (%s, %d)", (const void *)script, stackPosString(0), stackPos(1));
_screen->loadBitmap(stackPosString(0), 3, 3, &_screen->getPalette(3));
if (stackPos(1) != 2)
_screen->copyPage(3, stackPos(1));
return 1;
}
int LoLEngine::olol_stopBackgroundAnimation(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_stopBackgroundAnimation(%p) (%d)", (const void *)script, stackPos(0));
_animator->stop(stackPos(0));
return 1;
}
int LoLEngine::olol_getGlobalScriptVar(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getGlobalScriptVar(%p) (%d)", (const void *)script, stackPos(0));
assert(stackPos(0) < 24);
return _globalScriptVars[stackPos(0)];
}
int LoLEngine::olol_setGlobalScriptVar(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setGlobalScriptVar(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
assert(stackPos(0) < 24);
_globalScriptVars[stackPos(0)] = stackPos(1);
return 1;
}
int LoLEngine::olol_getGlobalVar(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getGlobalVar(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
switch (stackPos(0)) {
case 0:
return _currentBlock;
case 1:
return _currentDirection;
case 2:
return _currentLevel;
case 3:
return _itemInHand;
case 4:
return _brightness;
case 5:
return _credits;
case 6:
return _globalScriptVars2[stackPos(1)];
case 8:
return _updateFlags;
case 9:
return _lampOilStatus;
case 10:
return _sceneDefaultUpdate;
case 11:
return _compassBroken;
case 12:
return _drainMagic;
case 13:
return getVolume(kVolumeSpeech) - 2;
default:
break;
}
return 0;
}
int LoLEngine::olol_setGlobalVar(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setGlobalVar(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
uint16 a = stackPos(1);
uint16 b = stackPos(2);
switch (stackPos(0)) {
case 0:
_currentBlock = b;
calcCoordinates(_partyPosX, _partyPosY, _currentBlock, 0x80, 0x80);
updateAutoMap(_currentBlock);
break;
case 1:
_currentDirection = b;
break;
case 2:
_currentLevel = b & 0xff;
break;
case 3:
setHandItem(b);
break;
case 4:
_brightness = b & 0xff;
break;
case 5:
_credits = b;
break;
case 6:
_globalScriptVars2[a] = b;
break;
case 7:
break;
case 8:
_updateFlags = b;
if (b == 1) {
if (!textEnabled() || (!(_currentControlMode & 2)))
timerUpdatePortraitAnimations(1);
disableSysTimer(2);
} else {
enableSysTimer(2);
}
break;
case 9:
_lampOilStatus = b & 0xff;
break;
case 10:
_sceneDefaultUpdate = b & 0xff;
gui_toggleButtonDisplayMode(0, 0);
break;
case 11:
_compassBroken = a & 0xff;
break;
case 12:
_drainMagic = a & 0xff;
break;
default:
break;
}
return 1;
}
int LoLEngine::olol_triggerDoorSwitch(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_triggerDoorSwitch(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
processDoorSwitch(stackPos(0)/*, (_wllWallFlags[_levelBlockProperties[stackPos(0)].walls[0]] & 8) ? 0 : 1*/, stackPos(1));
return 1;
}
int LoLEngine::olol_checkEquippedItemScriptFlags(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_checkEquippedItemScriptFlags(%p)", (const void *)script);
for (int i = 0; i < 4; i++) {
if (!(_characters[i].flags & 1))
continue;
for (int ii = 0; ii < 4; ii++) {
uint8 f = _itemProperties[_itemsInPlay[_characters[i].items[ii]].itemPropertyIndex].itemScriptFunc;
if (f == 0 || f == 2)
return 1;
}
}
return 0;
}
int LoLEngine::olol_setDoorState(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setDoorState(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
if (stackPos(1))
_levelBlockProperties[stackPos(0)].flags = (_levelBlockProperties[stackPos(0)].flags & 0xef) | 0x20;
else
_levelBlockProperties[stackPos(0)].flags &= 0xdf;
return 1;
}
int LoLEngine::olol_updateBlockAnimations(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_updateBlockAnimations(%p) (%d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3));
int block = stackPos(0);
int wall = stackPos(1);
setWallType(block, wall, _levelBlockProperties[block].walls[(wall == -1) ? 0 : wall] == stackPos(2) ? stackPos(3) : stackPos(2));
return 0;
}
int LoLEngine::olol_mapShapeToBlock(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_mapShapeToBlock(%p) (%d)", (const void *)script, stackPos(0));
return assignLevelShapes(stackPos(0));
}
int LoLEngine::olol_resetBlockShapeAssignment(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_resetBlockShapeAssignment(%p) (%d)", (const void *)script, stackPos(0));
uint8 v = stackPos(0) & 0xff;
memset(_wllShapeMap + 3, v, 5);
memset(_wllShapeMap + 13, v, 5);
return 1;
}
int LoLEngine::olol_copyRegion(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_copyRegion(%p) (%d, %d, %d, %d, %d, %d, %d, %d)",
(const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5), stackPos(6), stackPos(7));
_screen->copyRegion(stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5), stackPos(6), stackPos(7), Screen::CR_NO_P_CHECK);
if (!stackPos(7))
_screen->updateScreen();
return 1;
}
int LoLEngine::olol_initMonster(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_initMonster(%p) (%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)", (const void *)script,
stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5), stackPos(6), stackPos(7), stackPos(8), stackPos(9), stackPos(10));
uint16 x = 0;
uint16 y = 0;
calcCoordinates(x, y, stackPos(0), stackPos(1), stackPos(2));
uint16 w = _monsterProperties[stackPos(4)].maxWidth;
if (checkBlockBeforeObjectPlacement(x, y, w, 7, 7))
return -1;
for (uint8 i = 0; i < 30; i++) {
MonsterInPlay *l = &_monsters[i];
if (l->hitPoints || l->mode == 13)
continue;
memset(l, 0, sizeof(MonsterInPlay));
l->id = i;
l->x = x;
l->y = y;
l->facing = stackPos(3);
l->type = stackPos(4);
l->properties = &_monsterProperties[l->type];
l->direction = l->facing << 1;
l->hitPoints = (l->properties->hitPoints * _monsterModifiers[_monsterDifficulty]) >> 8;
if (_currentLevel == 12 && l->type == 2)
l->hitPoints = (l->hitPoints * (rollDice(1, 128) + 192)) >> 8;
l->numDistAttacks = l->properties->numDistAttacks;
l->distAttackTick = rollDice(1, calcMonsterSkillLevel(l->id | 0x8000, 8)) - 1;
l->flyingHeight = 2;
l->flags = stackPos(5);
l->assignedItems = 0;
setMonsterMode(l, stackPos(6));
placeMonster(l, l->x, l->y);
l->destX = l->x;
l->destY = l->y;
l->destDirection = l->direction;
for (int ii = 0; ii < 4; ii++)
l->equipmentShapes[ii] = stackPos(7 + ii);
checkSceneUpdateNeed(l->block);
return i;
}
return -1;
}
int LoLEngine::olol_fadeClearSceneWindow(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_fadeClearSceneWindow(%p)", (const void *)script);
_screen->fadeClearSceneWindow(10);
return 1;
}
int LoLEngine::olol_fadeSequencePalette(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_fadeSequencePalette(%p)", (const void *)script);
if (_flags.use16ColorMode) {
setPaletteBrightness(_screen->getPalette(0), _brightness, _lampEffect);
} else {
_screen->getPalette(3).copy(_screen->getPalette(0), 128);
_screen->loadSpecialColors(_screen->getPalette(3));
_screen->fadePalette(_screen->getPalette(3), 10);
}
_screen->_fadeFlag = 0;
return 1;
}
int LoLEngine::olol_redrawPlayfield(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_redrawPlayfield(%p)", (const void *)script);
if (_screen->_fadeFlag != 2)
_screen->fadeClearSceneWindow(10);
gui_drawPlayField();
setPaletteBrightness(_screen->getPalette(0), _brightness, _lampEffect);
_screen->_fadeFlag = 0;
return 1;
}
int LoLEngine::olol_loadNewLevel(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_loadNewLevel(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
_screen->fadeClearSceneWindow(10);
_screen->fillRect(112, 0, 288, 120, 0);
disableSysTimer(2);
for (int i = 0; i < 8; i++) {
if (!_flyingObjects[i].enable || _flyingObjects[i].objectType)
continue;
endObjectFlight(&_flyingObjects[i], _flyingObjects[i].x, _flyingObjects[i].y, 1);
}
completeDoorOperations();
generateTempData();
_currentBlock = stackPos(1);
_currentDirection = stackPos(2);
calcCoordinates(_partyPosX, _partyPosY, _currentBlock, 0x80, 0x80);
loadLevel(stackPos(0));
enableSysTimer(2);
script->ip = 0;
return 1;
}
int LoLEngine::olol_getNearestMonsterFromCharacter(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getNearestMonsterFromCharacter(%p) (%d)", (const void *)script, stackPos(0));
return getNearestMonsterFromCharacter(stackPos(0));
}
int LoLEngine::olol_dummy0(EMCState *script) {
return 0;
}
int LoLEngine::olol_loadMonsterProperties(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_loadMonsterProperties(%p) (%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)",
(const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5),
stackPos(6), stackPos(7), stackPos(8), stackPos(9), stackPos(10), stackPos(11), stackPos(12), stackPos(13),
stackPos(14), stackPos(15), stackPos(16), stackPos(17), stackPos(18), stackPos(19), stackPos(20),
stackPos(21), stackPos(22), stackPos(23), stackPos(24), stackPos(25), stackPos(26), stackPos(27),
stackPos(28), stackPos(29), stackPos(30), stackPos(31), stackPos(32), stackPos(33), stackPos(34),
stackPos(35), stackPos(36), stackPos(37), stackPos(38), stackPos(39), stackPos(40), stackPos(41));
MonsterProperty *l = &_monsterProperties[stackPos(0)];
l->shapeIndex = stackPos(1) & 0xff;
int shpWidthMax = 0;
for (int i = 0; i < 16; i++) {
uint8 m = _monsterShapes[(l->shapeIndex << 4) + i][3];
if (m > shpWidthMax)
shpWidthMax = m;
}
l->maxWidth = shpWidthMax;
l->fightingStats[0] = (stackPos(2) << 8) / 100; // hit chance
l->fightingStats[1] = 256; //
l->fightingStats[2] = (stackPos(3) << 8) / 100; // protection
l->fightingStats[3] = stackPos(4); // evade chance
l->fightingStats[4] = (stackPos(5) << 8) / 100; // speed
l->fightingStats[5] = (stackPos(6) << 8) / 100; //
l->fightingStats[6] = (stackPos(7) << 8) / 100; //
l->fightingStats[7] = (stackPos(8) << 8) / 100; //
l->fightingStats[8] = 0;
for (int i = 0; i < 8; i++) {
l->itemsMight[i] = stackPos(9 + i);
l->protectionAgainstItems[i] = (stackPos(17 + i) << 8) / 100;
}
l->itemProtection = stackPos(25);
l->hitPoints = stackPos(26);
l->speedTotalWaitTicks = 1;
l->flags = stackPos(27);
l->unk5 = stackPos(28);
// FIXME???
l->unk5 = stackPos(29);
//
l->numDistAttacks = stackPos(30);
l->numDistWeapons = stackPos(31);
for (int i = 0; i < 3; i++)
l->distWeapons[i] = stackPos(32 + i);
l->attackSkillChance = stackPos(35);
l->attackSkillType = stackPos(36);
l->defenseSkillChance = stackPos(37);
l->defenseSkillType = stackPos(38);
for (int i = 0; i < 3; i++)
l->sounds[i] = stackPos(39 + i);
return 1;
}
int LoLEngine::olol_battleHitSkillTest(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_battleHitSkillTest(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
return battleHitSkillTest(stackPos(0), stackPos(1), stackPos(2));
}
int LoLEngine::olol_inflictDamage(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_inflictDamage(%p) (%d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4));
if (stackPos(0) == -1) {
for (int i = 0; i < 4; i++)
inflictDamage(i, stackPos(1), stackPos(2), stackPos(3), stackPos(4));
} else {
inflictDamage(stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4));
}
return 1;
}
int LoLEngine::olol_moveMonster(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_moveMonster(%p) (%d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4));
MonsterInPlay *m = &_monsters[stackPos(0)];
if (m->mode == 1 || m->mode == 2) {
calcCoordinates(m->destX, m->destY, stackPos(1), stackPos(2), stackPos(3));
m->destDirection = stackPos(4) << 1;
if (m->x != m->destX || m->y != m->destY)
setMonsterDirection(m, calcMonsterDirection(m->x, m->y, m->destX, m->destY));
}
return 1;
}
int LoLEngine::olol_dialogueBox(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_dialogueBox(%p) (%d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3));
_tim->drawDialogueBox(stackPos(0), getLangString(stackPos(1)), getLangString(stackPos(2)), getLangString(stackPos(3)));
return 1;
}
int LoLEngine::olol_giveTakeMoney(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_giveTakeMoney(%p) (%d)", (const void *)script, stackPos(0));
int c = stackPos(0);
if (c >= 0)
giveCredits(c, 1);
else
takeCredits(-c, 1);
return 1;
}
int LoLEngine::olol_checkMoney(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_checkMoney(%p) (%d)", (const void *)script, stackPos(0));
return (stackPos(0) > _credits) ? 0 : 1;
}
int LoLEngine::olol_setScriptTimer(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setScriptTimer(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
uint8 id = 0x50 + stackPos(0);
if (stackPos(1)) {
_timer->enable(id);
_timer->setCountdown(id, stackPos(1));
} else {
_timer->disable(id);
}
return 1;
}
int LoLEngine::olol_createHandItem(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_createHandItem(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
if (_itemInHand)
return 0;
setHandItem(makeItem(stackPos(0), stackPos(1), stackPos(2)));
return 1;
}
int LoLEngine::olol_playAttackSound(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_playAttackSound(%p) (%d)", (const void *)script, stackPos(0));
static const uint8 sounds[] = { 12, 62, 63 };
int d = stackPos(0);
if ((d < 70 || d > 74) && (d < 81 || d > 89) && (d < 93 || d > 97) && (d < 102 || d > 106))
snd_playSoundEffect(sounds[_itemProperties[d].skill & 3], -1);
else
snd_playSoundEffect(12, -1);
return 1;
}
int LoLEngine::olol_characterJoinsParty(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_characterJoinsParty(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
int16 id = stackPos(0);
if (id < 0)
id = -id;
for (int i = 0; i < 4; i++) {
if (!(_characters[i].flags & 1) || _characters[i].id != id)
continue;
_characters[i].flags &= 0xfffe;
calcCharPortraitXpos();
if (!_updateFlags) {
gui_enableDefaultPlayfieldButtons();
gui_drawPlayField();
}
if (_selectedCharacter == i)
_selectedCharacter = 0;
return 1;
}
addCharacter(id);
if (!_updateFlags) {
gui_enableDefaultPlayfieldButtons();
gui_drawPlayField();
}
return 1;
}
int LoLEngine::olol_giveItem(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_giveItem(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
int item = makeItem(stackPos(0), stackPos(1), stackPos(2));
if (addItemToInventory(item))
return 1;
deleteItem(item);
return 0;
}
int LoLEngine::olol_loadTimScript(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_loadTimScript(%p) (%d, %s)", (const void *)script, stackPos(0), stackPosString(1));
if (_activeTim[stackPos(0)])
return 1;
char file[13];
snprintf(file, sizeof(file), "%s.TIM", stackPosString(1));
_activeTim[stackPos(0)] = _tim->load(file, &_timIngameOpcodes);
return 1;
}
int LoLEngine::olol_runTimScript(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_runTimScript(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
return _tim->exec(_activeTim[stackPos(0)], stackPos(1));
}
int LoLEngine::olol_releaseTimScript(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_releaseTimScript(%p) (%d)", (const void *)script, stackPos(0));
_tim->unload(_activeTim[stackPos(0)]);
return 1;
}
int LoLEngine::olol_initSceneWindowDialogue(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_initSceneWindowDialogue(%p) (%d)", (const void *)script, stackPos(0));
initSceneWindowDialogue(stackPos(0));
return 1;
}
int LoLEngine::olol_restoreAfterSceneWindowDialogue(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_restoreAfterSceneWindowDialogue(%p) (%d)", (const void *)script, stackPos(0));
restoreAfterSceneWindowDialogue(stackPos(0));
return 1;
}
int LoLEngine::olol_getItemInHand(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getItemInHand(%p))", (const void *)script);
return _itemInHand;
}
int LoLEngine::olol_checkMagic(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_checkMagic(%p )(%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
return checkMagic(stackPos(0), stackPos(1), stackPos(2));
}
int LoLEngine::olol_giveItemToMonster(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_giveItemToMonster(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
if (stackPos(0) == -1)
return 0;
giveItemToMonster(&_monsters[stackPos(0)], stackPos(1));
return 1;
}
int LoLEngine::olol_loadLangFile(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_loadLangFile(%p) (%s)", (const void *)script, stackPosString(0));
char filename[13];
snprintf(filename, sizeof(filename), "%s.%s", stackPosString(0), _languageExt[_lang]);
delete[] _levelLangFile;
_levelLangFile = _res->fileData(filename, 0);
return 1;
}
int LoLEngine::olol_playSoundEffect(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_playSoundEffect(%p) (%d)", (const void *)script, stackPos(0));
snd_playSoundEffect(stackPos(0), -1);
return 1;
}
int LoLEngine::olol_processDialogue(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_processDialogue(%p)", (const void *)script);
return _tim->processDialogue();
}
int LoLEngine::olol_stopTimScript(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_stopTimScript(%p) (%d)", (const void *)script, stackPos(0));
_tim->stopAllFuncs(_activeTim[stackPos(0)]);
return 1;
}
int LoLEngine::olol_getWallFlags(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getWallFlags(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
return _wllWallFlags[_levelBlockProperties[stackPos(0)].walls[stackPos(1) & 3]];
}
int LoLEngine::olol_changeMonsterStat(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_changeMonsterStat(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
if (stackPos(0) == -1)
return 1;
MonsterInPlay *m = &_monsters[stackPos(0) & 0x7fff];
int16 d = stackPos(2);
uint16 x = 0;
uint16 y = 0;
switch (stackPos(1)) {
case 0:
setMonsterMode(m, d);
break;
case 1:
m->hitPoints = d;
break;
case 2:
calcCoordinates(x, y, d, m->x & 0xff, m->y & 0xff);
if (!walkMonsterCheckDest(x, y, m, 7))
placeMonster(m, x, y);
break;
case 3:
setMonsterDirection(m, d << 1);
break;
case 6:
m->flags |= d;
break;
default:
break;
}
return 1;
}
int LoLEngine::olol_getMonsterStat(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getMonsterStat(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
if (stackPos(0) == -1)
return 0;
MonsterInPlay *m = &_monsters[stackPos(0) & 0x7fff];
int d = stackPos(1);
switch (d) {
case 0:
return m->mode;
case 1:
return m->hitPoints;
case 2:
return m->block;
case 3:
return m->facing;
case 4:
return m->type;
case 5:
return m->properties->hitPoints;
case 6:
return m->flags;
case 7:
return m->properties->flags;
case 8:
return _monsterAnimType[m->properties->shapeIndex];
default:
break;
}
return 0;
}
int LoLEngine::olol_releaseMonsterShapes(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_releaseMonsterShapes(%p)", (const void *)script);
for (int i = 0; i < 3; i++)
releaseMonsterShapes(i);
return 0;
}
int LoLEngine::olol_playCharacterScriptChat(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_playCharacterScriptChat(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
if (_flags.isTalkie) {
snd_stopSpeech(1);
stopPortraitSpeechAnim();
}
return playCharacterScriptChat(stackPos(0), stackPos(1), 1, getLangString(stackPos(2)), script, 0, 3);
}
int LoLEngine::olol_playEnvironmentalSfx(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_playEnvironmentalSfx(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
uint16 block = (stackPos(1) == -1) ? _currentBlock : stackPos(1);
snd_processEnvironmentalSoundEffect(stackPos(0), block);
return 1;
}
int LoLEngine::olol_update(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_update(%p)", (const void *)script);
update();
return 1;
}
int LoLEngine::olol_healCharacter(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_healCharacter(%p) (%d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3));
if (stackPos(3)) {
processMagicHeal(stackPos(0), stackPos(1));
} else {
increaseCharacterHitpoints(stackPos(0), stackPos(1), true);
if (stackPos(2))
gui_drawCharPortraitWithStats(stackPos(0));
}
return 1;
}
int LoLEngine::olol_drawExitButton(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_drawExitButton(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
static const uint8 printPara[] = { 0x90, 0x78, 0x0C, 0x9F, 0x80, 0x1E };
int cp = _screen->setCurPage(0);
Screen::FontId cf = _screen->setFont(Screen::FID_6_FNT);
int x = printPara[3 * stackPos(0)] << 1;
int y = printPara[3 * stackPos(0) + 1];
int offs = printPara[3 * stackPos(0) + 2];
char *str = getLangString(0x4033);
int w = _screen->getTextWidth(str);
if (_flags.use16ColorMode) {
gui_drawBox(x - offs - w, y - 9, w + offs, 9, 0xee, 0xcc, 0x11);
_screen->printText(str, x - (offs >> 1) - w, y - 7, 0xbb, 0);
} else {
gui_drawBox(x - offs - w, y - 9, w + offs, 9, 136, 251, 252);
_screen->printText(str, x - (offs >> 1) - w, y - 7, 144, 0);
}
if (stackPos(1))
_screen->drawGridBox(x - offs - w + 1, y - 8, w + offs - 2, 7, 1);
_screen->setFont(cf);
_screen->setCurPage(cp);
return 1;
}
int LoLEngine::olol_loadSoundFile(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_loadSoundFile(%p) (%d)", (const void *)script, stackPos(0));
snd_loadSoundFile(stackPos(0));
return 1;
}
int LoLEngine::olol_playMusicTrack(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_playMusicTrack(%p) (%d)", (const void *)script, stackPos(0));
return snd_playTrack(stackPos(0));
}
int LoLEngine::olol_deleteMonstersFromBlock(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_deleteMonstersFromBlock(%p) (%d)", (const void *)script, stackPos(0));
deleteMonstersFromBlock(stackPos(0));
return 1;
}
int LoLEngine::olol_countBlockItems(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_countBlockItems(%p) (%d)", (const void *)script, stackPos(0));
uint16 o = _levelBlockProperties[stackPos(0)].assignedObjects;
int res = 0;
while (o) {
if (!(o & 0x8000))
res++;
o = findObject(o)->nextAssignedObject;
}
return res;
}
int LoLEngine::olol_characterSkillTest(EMCState *script){
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_characterSkillTest(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
int skill = stackPos(0);
int n = countActiveCharacters();
int m = 0;
int c = 0;
for (int i = 0; i < n ; i++) {
int v = _characters[i].skillModifiers[skill] + _characters[i].skillLevels[skill] + 25;
if (v > m) {
m = v;
c = i;
}
}
return (rollDice(1, 100) > m) ? -1 : c;
}
int LoLEngine::olol_countAllMonsters(EMCState *script){
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_countAllMonsters(%p)", (const void *)script);
int res = 0;
for (int i = 0; i < 30; i++) {
if (_monsters[i].hitPoints > 0 && _monsters[i].mode != 13)
res++;
}
return res;
}
int LoLEngine::olol_playEndSequence(EMCState *script){
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_playEndSequence(%p)", (const void *)script);
int c = 0;
if (_characters[0].id == -9)
c = 1;
else if (_characters[0].id == -5)
c = 3;
else if (_characters[0].id == -1)
c = 2;
while (snd_updateCharacterSpeech())
delay(_tickLength);
_eventList.clear();
_screen->hideMouse();
_screen->getPalette(1).clear();
showOutro(c, (_monsterDifficulty == 2));
quitGame();
return 0;
}
int LoLEngine::olol_stopPortraitSpeechAnim(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_stopPortraitSpeechAnim(%p)", (const void *)script);
if (_flags.isTalkie)
snd_stopSpeech(1);
stopPortraitSpeechAnim();
return 1;
}
int LoLEngine::olol_setPaletteBrightness(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setPaletteBrightness(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
uint16 old = _brightness;
_brightness = stackPos(0);
if (stackPos(1) == 1)
setPaletteBrightness(_screen->getPalette(0), stackPos(0), _lampEffect);
return old;
}
int LoLEngine::olol_calcInflictableDamage(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_calcInflictableDamage(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
return calcInflictableDamage(stackPos(0), stackPos(1), stackPos(2));
}
int LoLEngine::olol_getInflictedDamage(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getInflictedDamage(%p) (%d)", (const void *)script, stackPos(0));
int mx = stackPos(0);
return rollDice(2, mx);
}
int LoLEngine::olol_checkForCertainPartyMember(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_checkForCertainPartyMember(%p) (%d)", (const void *)script, stackPos(0));
for (int i = 0; i < 4; i++) {
if (_characters[i].flags & 9 && _characters[i].id == stackPos(0))
return 1;
}
return 0;
}
int LoLEngine::olol_printMessage(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_printMessage(%p) (%d, %d, %d, %d, %d, %d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5), stackPos(6), stackPos(7), stackPos(8), stackPos(9));
int snd = stackPos(2);
_txt->printMessage(stackPos(0), getLangString(stackPos(1)), stackPos(3), stackPos(4), stackPos(5), stackPos(6), stackPos(7), stackPos(8), stackPos(9));
if (snd >= 0)
snd_playSoundEffect(snd, -1);
return 1;
}
int LoLEngine::olol_deleteLevelItem(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_deleteLevelItem(%p) (%d)", (const void *)script, stackPos(0));
if (_itemsInPlay[stackPos(0)].block)
removeLevelItem(stackPos(0), _itemsInPlay[stackPos(0)].block);
deleteItem(stackPos(0));
return 1;
}
int LoLEngine::olol_calcInflictableDamagePerItem(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_calcInflictableDamagePerItem(%p) (%d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4));
return calcInflictableDamagePerItem(stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4));
}
int LoLEngine::olol_distanceAttack(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_distanceAttack(%p) (%d, %d, %d, %d, %d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5), stackPos(6), stackPos(7), stackPos(8));
uint16 fX = stackPos(3);
uint16 fY = stackPos(4);
if (!(stackPos(8) & 0x8000))
fX = fY = 0x80;
uint16 x = 0;
uint16 y = 0;
calcCoordinates(x, y, stackPos(2), fX, fY);
if (launchObject(stackPos(0), stackPos(1), x, y, stackPos(5), stackPos(6) << 1, stackPos(7), stackPos(8), 0x3f))
return 1;
deleteItem(stackPos(1));
return 0;
}
int LoLEngine::olol_removeCharacterEffects(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_removeCharacterEffects(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
removeCharacterEffects(&_characters[stackPos(0)], stackPos(1), stackPos(2));
return 1;
}
int LoLEngine::olol_checkInventoryFull(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_checkInventoryFull(%p)", (const void *)script);
for (int i = 0; i < 48; i++) {
if (_inventory[i])
return 0;
}
return 1;
}
int LoLEngine::olol_objectLeavesLevel(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_objectLeavesLevel(%p) (%d, %d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5));
int o = _levelBlockProperties[stackPos(0)].assignedObjects;
int res = 0;
int level = stackPos(2);
int block = stackPos(1);
int runScript = stackPos(4);
int includeMonsters = stackPos(3);
int includeItems = stackPos(5);
// WORKAROUND for script bug
// Items would vanish when thrown towards the stairs
// in white tower level 3.
if (_currentLevel == 21 && level == 21 && block == 0x3e0) {
level = 20;
block = 0x0247;
}
while (o) {
int l = o;
o = findObject(o)->nextAssignedObject;
if (l & 0x8000) {
if (!includeMonsters)
continue;
l &= 0x7fff;
MonsterInPlay *m = &_monsters[l];
setMonsterMode(m, 14);
checkSceneUpdateNeed(m->block);
placeMonster(m, 0, 0);
res = 1;
} else {
if (!(_itemsInPlay[l].shpCurFrame_flg & 0x4000) || !includeItems)
continue;
placeMoveLevelItem(l, level, block, _itemsInPlay[l].x & 0xff, _itemsInPlay[l].y & 0xff, _itemsInPlay[l].flyingHeight);
if (!runScript || level != _currentLevel) {
res = 1;
continue;
}
runLevelScriptCustom(block, 0x80, -1, l, 0, 0);
res = 1;
}
}
return res;
}
int LoLEngine::olol_addSpellToScroll(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_addSpellToScroll(%p) (%d)", (const void *)script, stackPos(0));
addSpellToScroll(stackPos(0), stackPos(1));
return 1;
}
int LoLEngine::olol_playDialogueText(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_playDialogueText(%p) (%d)", (const void *)script, stackPos(0));
_txt->printDialogueText(3, getLangString(stackPos(0)), script, 0, 1);
return 1;
}
int LoLEngine::olol_playDialogueTalkText(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_playDialogueTalkText(%p) (%d)", (const void *)script, stackPos(0));
int track = stackPos(0);
if (!snd_playCharacterSpeech(track, 0, 0) || textEnabled()) {
char *s = getLangString(track);
_txt->printDialogueText(4, s, script, 0, 1);
}
return 1;
}
int LoLEngine::olol_checkMonsterTypeHostility(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_checkMonsterTypeHostility(%p) (%d)", (const void *)script, stackPos(0));
for (int i = 0; i < 30; i++) {
if (stackPos(0) != _monsters[i].type && stackPos(0) != -1)
continue;
return (_monsters[i].mode == 1) ? 0 : 1;
}
return 1;
}
int LoLEngine::olol_setNextFunc(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setNextFunc(%p) (%d)", (const void *)script, stackPos(0));
_nextScriptFunc = stackPos(0);
return 1;
}
int LoLEngine::olol_dummy1(EMCState *script) {
return 1;
}
int LoLEngine::olol_suspendMonster(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_suspendMonster(%p) (%d)", (const void *)script, stackPos(0));
MonsterInPlay *m = &_monsters[stackPos(0) & 0x7fff];
setMonsterMode(m, 14);
checkSceneUpdateNeed(m->block);
placeMonster(m, 0, 0);
return 1;
}
int LoLEngine::olol_setScriptTextParameter(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setScriptTextParameter(%p) (%d)", (const void *)script, stackPos(0));
_txt->_scriptTextParameter = stackPos(0);
return 1;
}
int LoLEngine::olol_triggerEventOnMouseButtonClick(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_triggerEventOnMouseButtonClick(%p) (%d)", (const void *)script, stackPos(0));
gui_notifyButtonListChanged();
snd_updateCharacterSpeech();
int f = checkInput(0);
removeInputTop();
if (f == 0 || (f & 0x800))
return 0;
int evt = stackPos(0);
if (evt) {
gui_triggerEvent(evt);
_seqTrigger = 1;
} else {
removeInputTop();
}
return 1;
}
int LoLEngine::olol_printWindowText(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_printWindowText(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
int dim = stackPos(0);
int flg = stackPos(1);
_screen->setScreenDim(dim);
if (flg & 1)
_txt->clearCurDim();
if (flg & 3)
_txt->resetDimTextPositions(dim);
_txt->printDialogueText(dim, getLangString(stackPos(2)), script, 0, 3);
return 1;
}
int LoLEngine::olol_countSpecificMonsters(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_countSpecificMonsters(%p) (%d, ...)", (const void *)script, stackPos(0));
uint16 types = 0;
int res = 0;
int cnt = 0;
while (stackPos(cnt) != -1)
types |= (1 << stackPos(cnt++));
for (int i = 0; i < 30; i++) {
if (((1 << _monsters[i].type) & types) && _monsters[i].mode < 14)
res++;
}
return res;
}
int LoLEngine::olol_updateBlockAnimations2(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_updateBlockAnimations2(%p) (%d, %d, %d, %d, ...)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3));
int numFrames = stackPos(3);
assert (numFrames <= 97);
int curFrame = stackPos(2) % numFrames;
setWallType(stackPos(0), stackPos(1), stackPos(4 + curFrame));
return 0;
}
int LoLEngine::olol_checkPartyForItemType(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_checkPartyForItemType(%p) (%d, %d, %d))", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
int p = stackPos(1);
if (!stackPos(2)) {
for (int i = 0; i < 48; i++) {
if (!_inventory[i] || _itemsInPlay[_inventory[i]].itemPropertyIndex != p)
continue;
return 1;
}
if (_itemsInPlay[_itemInHand].itemPropertyIndex == p)
return 1;
}
int last = (stackPos(0) == -1) ? 3 : stackPos(0);
int first = (stackPos(0) == -1) ? 0 : stackPos(0);
for (int i = first; i <= last; i++) {
if (itemEquipped(i, p))
return 1;
}
return 0;
}
int LoLEngine::olol_blockDoor(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_blockDoor(%p) (%d)", (const void *)script, stackPos(0));
_blockDoor = stackPos(0);
return _blockDoor;
}
int LoLEngine::olol_resetTimDialogueState(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_resetTimDialogueState(%p) (%d)", (const void *)script, stackPos(0));
_tim->resetDialogueState(_activeTim[stackPos(0)]);
return 1;
}
int LoLEngine::olol_getItemOnPos(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getItemOnPos(%p) (%d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3));
int pX = stackPos(1);
if (pX != -1)
pX &= 0xff;
int pY = stackPos(2);
if (pY != -1)
pY &= 0xff;
int o = (stackPos(3) || _emcLastItem == -1) ? stackPos(0) : _emcLastItem;
_emcLastItem = _levelBlockProperties[o].assignedObjects;
while (_emcLastItem) {
if (_emcLastItem & 0x8000) {
o = _emcLastItem & 0x7fff;
_emcLastItem = _levelBlockProperties[o].assignedObjects;
continue;
}
if (pX != -1 && (_itemsInPlay[_emcLastItem].x & 0xff) != pX) {
o = _emcLastItem & 0x7fff;
_emcLastItem = _levelBlockProperties[o].assignedObjects;
continue;
}
if (pY != -1 && (_itemsInPlay[_emcLastItem].y & 0xff) != pY) {
o = _emcLastItem & 0x7fff;
_emcLastItem = _levelBlockProperties[o].assignedObjects;
continue;
}
return _emcLastItem;
}
return 0;
}
int LoLEngine::olol_removeLevelItem(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_removeLevelItem(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
removeLevelItem(stackPos(0), stackPos(1));
return 1;
}
int LoLEngine::olol_savePage5(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_savePage5(%p)", (const void *)script);
// Not implemented: The original code uses this to back up and restore page 5 which is used
// to load WSA files. Since our WSA player provides its own memory buffers we don't
// need to use page 5.
return 1;
}
int LoLEngine::olol_restorePage5(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_restorePage5(%p)", (const void *)script);
// Not implemented: The original code uses this to back up and restore page 5 which is used
// to load WSA files. Since our WSA player provides its own memory buffers we don't
// need to use page 5.
for (int i = 0; i < 6; i++)
_tim->freeAnimStruct(i);
return 1;
}
int LoLEngine::olol_initDialogueSequence(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_initDialogueSequence(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
initDialogueSequence(stackPos(0), stackPos(1));
return 1;
}
int LoLEngine::olol_restoreAfterDialogueSequence(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_restoreAfterDialogueSequence(%p) (%d)", (const void *)script, stackPos(0));
restoreAfterDialogueSequence(stackPos(0));
return 1;
}
int LoLEngine::olol_setSpecialSceneButtons(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setSpecialSceneButtons(%p) (%d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4));
setSpecialSceneButtons(stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4));
return 1;
}
int LoLEngine::olol_restoreButtonsAfterSpecialScene(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_restoreButtonsAfterSpecialScene(%p)", (const void *)script);
gui_specialSceneRestoreButtons();
return 1;
}
int LoLEngine::olol_prepareSpecialScene(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_prepareSpecialScene(%p) (%d, %d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5));
prepareSpecialScene(stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5));
return 1;
}
int LoLEngine::olol_restoreAfterSpecialScene(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_restoreAfterSpecialScene(%p) (%d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3));
return restoreAfterSpecialScene(stackPos(0), stackPos(1), stackPos(2), stackPos(3));
}
int LoLEngine::olol_assignCustomSfx(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_assignCustomSfx(%p) (%s, %d)", (const void *)script, stackPosString(0), stackPos(1));
const char *c = stackPosString(0);
int i = stackPos(1);
if (!c || i > 250)
return 0;
uint16 t = READ_LE_UINT16(&_ingameSoundIndex[i << 1]);
if (t == 0xffff)
return 0;
strcpy(_ingameSoundList[t], c);
return 0;
}
int LoLEngine::olol_findAssignedMonster(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_findAssignedMonster(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
uint16 o = stackPos(1) == -1 ? _levelBlockProperties[stackPos(0)].assignedObjects : findObject(stackPos(1))->nextAssignedObject;
while (o) {
if (o & 0x8000)
return o & 0x7fff;
o = findObject(o)->nextAssignedObject;
}
return -1;
}
int LoLEngine::olol_checkBlockForMonster(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_checkBlockForMonster(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
uint16 block = stackPos(0);
uint16 id = stackPos(1) | 0x8000;
uint16 o = _levelBlockProperties[block].assignedObjects;
while (o & 0x8000) {
if (id == 0xffff || id == o)
return o & 0x7fff;
o = findObject(o)->nextAssignedObject;
}
return -1;
}
int LoLEngine::olol_transformRegion(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_transformRegion(%p) (%d, %d, %d, %d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5), stackPos(6), stackPos(7));
transformRegion(stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4), stackPos(5), stackPos(6), stackPos(7));
return 1;
}
int LoLEngine::olol_calcCoordinatesAddDirectionOffset(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_calcCoordinatesAddDirectionOffset(%p) (%d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3));
uint16 x = stackPos(0);
uint16 y = stackPos(1);
calcCoordinatesAddDirectionOffset(x, y, stackPos(2));
return stackPos(3) ? x : y;
}
int LoLEngine::olol_resetPortraitsAndDisableSysTimer(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_resetPortraitsAndDisableSysTimer(%p)", (const void *)script);
resetPortraitsAndDisableSysTimer();
return 1;
}
int LoLEngine::olol_enableSysTimer(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_enableSysTimer(%p)", (const void *)script);
_needSceneRestore = 0;
enableSysTimer(2);
return 1;
}
int LoLEngine::olol_checkNeedSceneRestore(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_checkNeedSceneRestore(%p)", (const void *)script);
return _needSceneRestore;
}
int LoLEngine::olol_getNextActiveCharacter(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getNextActiveCharacter(%p) (%d)", (const void *)script, stackPos(0));
if (stackPos(0))
_scriptCharacterCycle = 0;
else
_scriptCharacterCycle++;
while (_scriptCharacterCycle < 4) {
if (_characters[_scriptCharacterCycle].flags & 1)
return _scriptCharacterCycle;
_scriptCharacterCycle++;
}
return -1;
}
int LoLEngine::olol_paralyzePoisonCharacter(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_paralyzePoisonCharacter(%p) (%d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4));
return paralyzePoisonCharacter(stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4));
}
int LoLEngine::olol_drawCharPortrait(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_drawCharPortrait(%p) (%d)", (const void *)script, stackPos(0));
int charNum = stackPos(0);
if (charNum == -1)
gui_drawAllCharPortraitsWithStats();
else
gui_drawCharPortraitWithStats(charNum);
return 1;
}
int LoLEngine::olol_removeInventoryItem(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_removeInventoryItem(%p) (%d)", (const void *)script, stackPos(0));
int itemType = stackPos(0);
for (int i = 0; i < 48; i++) {
if (!_inventory[i] || _itemsInPlay[_inventory[i]].itemPropertyIndex != itemType)
continue;
_inventory[i] = 0;
gui_drawInventory();
return 1;
}
for (int i = 0; i < 4; i++) {
if (!(_characters[i].flags & 1))
continue;
for (int ii = 0; ii < 11; ii++) {
if (!_characters[i].items[ii] || _itemsInPlay[_characters[i].items[ii]].itemPropertyIndex != itemType)
continue;
_characters[i].items[ii] = 0;
return 1;
}
}
return 0;
}
int LoLEngine::olol_getAnimationLastPart(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getAnimationLastPart(%p) (%d)", (const void *)script, stackPos(0));
return _animator->resetLastPart(stackPos(0));
}
int LoLEngine::olol_assignSpecialGuiShape(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_assignSpecialGuiShape(%p) (%d, %d, %d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2), stackPos(3), stackPos(4));
if (stackPos(0)) {
_specialGuiShape = _levelShapes[_levelShapeProperties[_wllShapeMap[stackPos(0)]].shapeIndex[stackPos(1)]];
_specialGuiShapeX = stackPos(2);
_specialGuiShapeY = stackPos(3);
_specialGuiShapeMirrorFlag = stackPos(4);
} else {
_specialGuiShape = 0;
_specialGuiShapeX = _specialGuiShapeY = _specialGuiShapeMirrorFlag = 0;
}
return 1;
}
int LoLEngine::olol_findInventoryItem(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_findInventoryItem(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
if (stackPos(0) == 0) {
for (int i = 0; i < 48; i++) {
if (!_inventory[i])
continue;
if (_itemsInPlay[_inventory[i]].itemPropertyIndex == stackPos(2))
return 0;
}
}
int cur = stackPos(1);
int last = cur;
if (stackPos(1) == -1) {
cur = 0;
last = 4;
}
for (;cur < last; cur++) {
if (!(_characters[cur].flags & 1))
continue;
for (int i = 0; i < 11; i++) {
if (!_characters[cur].items[i])
continue;
if (_itemsInPlay[_characters[cur].items[i]].itemPropertyIndex == stackPos(2))
return cur;
}
}
return -1;
}
int LoLEngine::olol_restoreFadePalette(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_restoreFadePalette(%p)", (const void *)script);
_screen->getPalette(0).copy(_screen->getPalette(1), 0, _flags.use16ColorMode ? 16 : 128);
_screen->fadePalette(_screen->getPalette(0), 10);
_screen->_fadeFlag = 0;
return 1;
}
int LoLEngine::olol_getSelectedCharacter(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getSelectedCharacter(%p)", (const void *)script);
return _selectedCharacter;
}
int LoLEngine::olol_setHandItem(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setHandItem(%p) (%d)", (const void *)script, stackPos(0));
setHandItem(stackPos(0));
return 1;
}
int LoLEngine::olol_drinkBezelCup(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_drinkBezelCup(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
drinkBezelCup(3 - stackPos(0), stackPos(1));
return 1;
}
int LoLEngine::olol_changeItemTypeOrFlag(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_changeItemTypeOrFlag(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
if (stackPos(0) < 1)
return 0;
ItemInPlay *i = &_itemsInPlay[stackPos(0)];
int r = stackPos(2) & 0x1fff;
if (stackPos(1) == 4) {
i->itemPropertyIndex = r;
return r;
} else if (stackPos(1) == 15) {
i->shpCurFrame_flg = (i->shpCurFrame_flg & 0xe000) | r;
return r;
}
return -1;
}
int LoLEngine::olol_placeInventoryItemInHand(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_placeInventoryItemInHand(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
int itemType = stackPos(0);
int i = 0;
for (; i < 48; i++) {
if (!_inventory[i])
continue;
if (_itemsInPlay[_inventory[i]].itemPropertyIndex == itemType)
break;
}
if (i == 48)
return -1;
_inventoryCurItem = i;
int r = _itemInHand;
setHandItem(_inventory[i]);
_inventory[i] = r;
if (stackPos(1))
gui_drawInventory();
return r;
}
int LoLEngine::olol_castSpell(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_castSpell(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
return castSpell(stackPos(0), stackPos(1), stackPos(2));
}
int LoLEngine::olol_pitDrop(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_pitDrop(%p) (%d)", (const void *)script, stackPos(0));
int m = stackPos(0);
_screen->updateScreen();
if (m) {
gui_drawScene(2);
pitDropScroll(9);
snd_playSoundEffect(-1, -1);
shakeScene(30, 4, 0, 1);
} else {
int t = -1;
for (int i = 0; i < 4; i++) {
if (!(_characters[i].flags & 1) || (_characters[i].id >= 0))
continue;
if (_characters[i].id == -1)
t = 54;
else if (_characters[i].id == -5)
t = 53;
else if (_characters[i].id == -8)
t = 52;
else if (_characters[i].id == -9)
t = 51;
}
_screen->fillRect(112, 0, 288, 120, 0, 2);
snd_playSoundEffect(t, -1);
pitDropScroll(12);
}
return 1;
}
int LoLEngine::olol_increaseSkill(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_increaseSkill(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
LoLCharacter *c = &_characters[stackPos(0)];
int s = stackPos(1);
int l = c->skillLevels[s];
increaseExperience(stackPos(0), s, _expRequirements[l] - c->experiencePts[s]);
return c->skillLevels[s] - l;
}
int LoLEngine::olol_paletteFlash(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_paletteFlash(%p) (%d)", (const void *)script, stackPos(0));
Palette &p1 = _screen->getPalette(1);
if (_flags.use16ColorMode) {
Palette p2(16);
p2.copy(p1);
uint8 *d = p2.getData();
for (int i = 0; i < 16; i++)
d[i * 3] = 0x3f;
_screen->setScreenPalette(p2);
_screen->updateScreen();
delay(4 * _tickLength);
_screen->setScreenPalette(p1);
if (_smoothScrollModeNormal)
_screen->copyRegion(112, 0, 112, 0, 176, 120, 2, 0);
_screen->updateScreen();
} else {
Palette &p2 = _screen->getPalette(3);
uint8 ovl[256];
generateFlashPalette(p1, p2, stackPos(0));
_screen->loadSpecialColors(p1);
_screen->loadSpecialColors(p2);
if (_smoothScrollModeNormal) {
for (int i = 0; i < 256; i++)
ovl[i] = i;
ovl[1] = 6;
_screen->copyRegion(112, 0, 112, 0, 176, 120, 0, 2);
_screen->applyOverlay(112, 0, 176, 120, 0, ovl);
}
_screen->setScreenPalette(p2);
_screen->updateScreen();
delay(2 * _tickLength);
_screen->setScreenPalette(p1);
if (_smoothScrollModeNormal)
_screen->copyRegion(112, 0, 112, 0, 176, 120, 2, 0);
_screen->updateScreen();
}
return 0;
}
int LoLEngine::olol_restoreMagicShroud(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_restoreMagicShroud(%p)", (const void *)script);
WSAMovie_v2 *mov = new WSAMovie_v2(this);
mov->open("DARKLITE.WSA", 2, 0);
if (!mov->opened()) {
delete mov;
warning("LoLEngine::olol_restoreMagicShroud: Could not open file: \"DARKLITE.WSA\"");
return 1;
}
_screen->hideMouse();
Palette *fadeTab[28];
for (int i = 0; i < 28; i++)
fadeTab[i] = new Palette(_flags.use16ColorMode ? 16 : 256);
Palette **tpal1 = &fadeTab[0];
Palette **tpal2 = &fadeTab[1];
Palette **tpal3 = &fadeTab[2];
Palette **tpal4 = 0;
int len = _flags.use16ColorMode ? 48 : 768;
_res->loadFileToBuf("LITEPAL1.COL", (*tpal1)->getData(), len);
tpal2 = _screen->generateFadeTable(tpal3, 0, *tpal1, 21);
_res->loadFileToBuf("LITEPAL2.COL", (*tpal2)->getData(), len);
tpal4 = tpal2++;
_res->loadFileToBuf("LITEPAL3.COL", (*tpal1)->getData(), len);
_screen->generateFadeTable(tpal2, *tpal4, *tpal1, 4);
for (int i = 0; i < 21; i++) {
uint32 etime = _system->getMillis() + 20 * _tickLength;
mov->displayFrame(i, 0, 0, 0, 0, 0, 0);
_screen->setScreenPalette(**tpal3++);
_screen->updateScreen();
if (i == 2 || i == 5 || i == 8 || i == 11 || i == 13 || i == 15 || i == 17 || i == 19)
snd_playSoundEffect(95, -1);
delayUntil(etime);
}
snd_playSoundEffect(91, -1);
_screen->fadePalette(**tpal3++, 300);
for (int i = 22; i < 38; i++) {
uint32 etime = _system->getMillis() + 12 * _tickLength;
mov->displayFrame(i, 0, 0, 0, 0, 0, 0);
if (i == 22 || i == 24 || i == 28 || i == 32) {
snd_playSoundEffect(131, -1);
_screen->setScreenPalette(**tpal3++);
}
_screen->updateScreen();
delayUntil(etime);
}
mov->close();
delete mov;
for (int i = 0; i < 28; i++)
delete fadeTab[i];
_screen->showMouse();
return 1;
}
int LoLEngine::olol_disableControls(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_disableControls(%p) (%d)", (const void *)script, stackPos(0));
return gui_disableControls(stackPos(0));
}
int LoLEngine::olol_enableControls(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_enableControls(%p)", (const void *)script);
return gui_enableControls();
}
int LoLEngine::olol_shakeScene(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_shakeScene(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
shakeScene(stackPos(0), stackPos(1), stackPos(2), 1);
return 1;
}
int LoLEngine::olol_gasExplosion(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_gasExplosion(%p) (%d)", (const void *)script, stackPos(0));
processGasExplosion(stackPos(0));
return 1;
}
int LoLEngine::olol_calcNewBlockPosition(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_calcNewBlockPosition(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
return calcNewBlockPosition(stackPos(0), stackPos(1));
}
int LoLEngine::olol_fadeScene(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_fadeScene(%p)", (const void *)script);
gui_drawScene(2);
transformRegion(112, 0, 112, 0, 176, 120, 2, 0);
updateDrawPage2();
return 1;
}
int LoLEngine::olol_updateDrawPage2(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_updateDrawPage2(%p)", (const void *)script);
updateDrawPage2();
return 1;
}
int LoLEngine::olol_setMouseCursor(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_setMouseCursor(%p) (%d)", (const void *)script, stackPos(0));
if (stackPos(0) == 1)
setMouseCursorToIcon(133);
else
setMouseCursorToItemInHand();
return 1;
}
int LoLEngine::olol_characterSays(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_characterSays(%p) (%d, %d, %d)", (const void *)script, stackPos(0), stackPos(1), stackPos(2));
if (!_flags.isTalkie)
return 0;
if (stackPos(0) == -1) {
snd_stopSpeech(true);
return 1;
}
if (stackPos(0) != -2)
return characterSays(stackPos(0), stackPos(1), stackPos(2));
else
return snd_updateCharacterSpeech();
}
int LoLEngine::olol_queueSpeech(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_queueSpeech(%p) (%d, %d)", (const void *)script, stackPos(0), stackPos(1));
if (stackPos(0) && stackPos(1)) {
_nextSpeechId = stackPos(0) + 1000;
_nextSpeaker = stackPos(1);
}
return 1;
}
int LoLEngine::olol_getItemPrice(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getItemPrice(%p) (%d)", (const void *)script, stackPos(0));
int c = stackPos(0);
if (c < 0) {
c = -c;
if (c < 50)
return 50;
c = (c + 99) / 100;
return c * 100;
} else {
for (int i = 0; i < 46; i++) {
if (_itemCost[i] >= c)
return _itemCost[i];
}
}
return 0;
}
int LoLEngine::olol_getLanguage(EMCState *script) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::olol_getLanguage(%p)", (const void *)script);
return _lang;
}
#pragma mark -
int LoLEngine::tlol_setupPaletteFade(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_setupPaletteFade(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
_screen->getFadeParams(_screen->getPalette(0), param[0], _tim->_palDelayInc, _tim->_palDiff);
_tim->_palDelayAcc = 0;
return 1;
}
int LoLEngine::tlol_loadPalette(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_loadPalette(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
const char *palFile = (const char *)(tim->text + READ_LE_UINT16(tim->text + (param[0]<<1)));
_screen->loadPalette(palFile, _screen->getPalette(0));
return 1;
}
int LoLEngine::tlol_setupPaletteFadeEx(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_setupPaletteFadeEx(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
_screen->copyPalette(0, 1);
_screen->getFadeParams(_screen->getPalette(0), param[0], _tim->_palDelayInc, _tim->_palDiff);
_tim->_palDelayAcc = 0;
return 1;
}
int LoLEngine::tlol_processWsaFrame(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_processWsaFrame(%p, %p) (%d, %d, %d, %d, %d)",
(const void *)tim, (const void *)param, param[0], param[1], param[2], param[3], param[4]);
const int animIndex = tim->wsa[param[0]].anim - 1;
const int frame = param[1];
const int x2 = param[2];
const int y2 = param[3];
const int factor = MAX<int>(0, (int16)param[4]);
const int x1 = _animator->getAnimX(animIndex);
const int y1 = _animator->getAnimY(animIndex);
const Movie *wsa = _animator->getWsaCPtr(animIndex);
int w1 = wsa->width();
int h1 = wsa->height();
int w2 = (w1 * factor) / 100;
int h2 = (h1 * factor) / 100;
_animator->displayFrame(animIndex, 2, frame);
_screen->wsaFrameAnimationStep(x1, y1, x2, y2, w1, h1, w2, h2, 2, _flags.isDemo && _flags.platform != Common::kPlatformPC98 ? 0 : 8, 0);
if (!_flags.isDemo && _flags.platform != Common::kPlatformPC98)
_screen->checkedPageUpdate(8, 4);
_screen->updateScreen();
return 1;
}
int LoLEngine::tlol_displayText(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_displayText(%p, %p) (%d, %d)", (const void *)tim, (const void *)param, param[0], (int16)param[1]);
if (tim->isLoLOutro)
_tim->displayText(param[0], param[1], param[2]);
else
_tim->displayText(param[0], param[1]);
return 1;
}
int LoLEngine::tlol_initSceneWindowDialogue(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_initSceneWindowDialogue(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
initSceneWindowDialogue(param[0]);
return 1;
}
int LoLEngine::tlol_restoreAfterSceneWindowDialogue(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_restoreAfterSceneWindowDialogue(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
restoreAfterSceneWindowDialogue(param[0]);
return 1;
}
int LoLEngine::tlol_giveItem(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_giveItem(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
int item = makeItem(param[0], param[1], param[2]);
if (addItemToInventory(item))
return 1;
deleteItem(item);
return 0;
}
int LoLEngine::tlol_setPartyPosition(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_setPartyPosition(%p, %p) (%d, %d)", (const void *)tim, (const void *)param, param[0], param[1]);
if (param[0] == 1) {
_currentDirection = param[1];
} else if (param[0] == 0) {
_currentBlock = param[1];
calcCoordinates(_partyPosX, _partyPosY, _currentBlock, 0x80, 0x80);
}
return 1;
}
int LoLEngine::tlol_fadeClearWindow(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_fadeClearWindow(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
switch (param[0]) {
case 0:
_screen->fadeClearSceneWindow(10);
break;
case 1:
if (_flags.use16ColorMode) {
_screen->fadePalette(_screen->getPalette(1), 10);
} else {
_screen->getPalette(3).copy(_screen->getPalette(0), 128);
_screen->loadSpecialColors(_screen->getPalette(3));
_screen->fadePalette(_screen->getPalette(3), 10);
}
_screen->_fadeFlag = 0;
break;
case 2:
_screen->fadeToBlack(10);
break;
case 3:
_screen->loadSpecialColors(_screen->getPalette(3));
_screen->fadePalette(_screen->getPalette(_flags.use16ColorMode ? 1 : 3), 10);
_screen->_fadeFlag = 0;
break;
case 4:
if (_screen->_fadeFlag != 2)
_screen->fadeClearSceneWindow(10);
gui_drawPlayField();
setPaletteBrightness(_screen->getPalette(0), _brightness, _lampEffect);
_screen->_fadeFlag = 0;
break;
case 5:
_screen->loadSpecialColors(_screen->getPalette(3));
_screen->fadePalette(_screen->getPalette(1), 10);
_screen->_fadeFlag = 0;
break;
default:
break;
}
return 1;
}
int LoLEngine::tlol_copyRegion(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_copyRegion(%p, %p) (%d, %d, %d, %d, %d, %d, %d, %d)", (const void *)tim, (const void *)param, param[0], param[1], param[2], param[3], param[4], param[5], param[6], param[7]);
_screen->copyRegion(param[0], param[1], param[2], param[3], param[4], param[5], param[6], param[7], Screen::CR_NO_P_CHECK);
if (!param[7])
_screen->updateScreen();
return 1;
}
int LoLEngine::tlol_characterChat(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_characterChat(%p, %p) (%d, %d, %d)", (const void *)tim, (const void *)param, param[0], param[1], param[2]);
playCharacterScriptChat(param[0], param[1], 1, getLangString(param[2]), 0, param, 3);
return 1;
}
int LoLEngine::tlol_drawScene(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_drawScene(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
gui_drawScene(param[0]);
//if (_sceneDrawPage2 != 2 && param[0] == 2)
// _screen->copyRegion(112 << 3, 0, 112 << 3, 0, 176 << 3, 120, _sceneDrawPage2, 2, Screen::CR_NO_P_CHECK);
return 1;
}
int LoLEngine::tlol_update(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_update(%p, %p)", (const void *)tim, (const void *)param);
update();
return 1;
}
int LoLEngine::tlol_clearTextField(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_clearTextField(%p, %p)", (const void *)tim, (const void *)param);
if (_currentControlMode && !textEnabled())
return 1;
_screen->setScreenDim(5);
const ScreenDim *d = _screen->_curDim;
_screen->fillRect(d->sx, d->sy, d->sx + d->w - (_flags.use16ColorMode ? 3 : 2), d->sy + d->h - 2, d->unkA);
_txt->clearDim(4);
_txt->resetDimTextPositions(4);
return 1;
}
int LoLEngine::tlol_loadSoundFile(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_loadSoundFile(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
snd_loadSoundFile(param[0]);
return 1;
}
int LoLEngine::tlol_playMusicTrack(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_playMusicTrack(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
snd_playTrack(param[0]);
return 1;
}
int LoLEngine::tlol_playDialogueTalkText(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_playDialogueTalkText(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
if (!snd_playCharacterSpeech(param[0], 0, 0) || textEnabled())
_txt->printDialogueText(4, getLangString(param[0]), 0, param, 1);
return 1;
}
int LoLEngine::tlol_playSoundEffect(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_playSoundEffect(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
snd_playSoundEffect(param[0], -1);
return 1;
}
int LoLEngine::tlol_startBackgroundAnimation(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_startBackgroundAnimation(%p, %p) (%d, %d)", (const void *)tim, (const void *)param, param[0], param[1]);
_animator->start(param[0], param[1]);
return 1;
}
int LoLEngine::tlol_stopBackgroundAnimation(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_stopBackgroundAnimation(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
_animator->stop(param[0]);
return 1;
}
int LoLEngine::tlol_fadeInScene(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_fadeInScene(%p, %p) (%d, %d)", (const void *)tim, (const void *)param, param[0], param[1]);
const char *sceneFile = (const char *)(tim->text + READ_LE_UINT16(tim->text + (param[0]<<1)));
const char *overlayFile = (const char *)(tim->text + READ_LE_UINT16(tim->text + (param[1]<<1)));
_screen->copyRegion(0, 0, 0, 0, 320, 200, 0, 2, Screen::CR_NO_P_CHECK);
char filename[32];
strcpy(filename, sceneFile);
strcat(filename, ".CPS");
_screen->loadBitmap(filename, 7, 5, &_screen->getPalette(0));
uint8 *overlay = 0;
if (!_flags.use16ColorMode) {
filename[0] = 0;
if (_flags.isTalkie) {
strcpy(filename, _languageExt[_lang]);
strcat(filename, "/");
}
strcat(filename, overlayFile);
overlay = _res->fileData(filename, 0);
for (int i = 0; i < 3; ++i) {
uint32 endTime = _system->getMillis() + 10 * _tickLength;
_screen->copyBlockAndApplyOverlayOutro(4, 2, overlay);
_screen->copyRegion(0, 0, 0, 0, 320, 200, 2, 0, Screen::CR_NO_P_CHECK);
_screen->updateScreen();
delayUntil(endTime);
}
}
_screen->copyRegion(0, 0, 0, 0, 320, 200, 4, 0, Screen::CR_NO_P_CHECK);
if (_flags.use16ColorMode) {
_screen->fadePalette(_screen->getPalette(0), 5);
} else {
_screen->updateScreen();
delete[] overlay;
}
return 1;
}
int LoLEngine::tlol_unusedResourceFunc(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_unusedResourceFunc(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
// The original used 0x6 / 0x7 for some resource caching, we don't need this.
return 1;
}
int LoLEngine::tlol_fadeInPalette(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_fadeInPalette(%p, %p) (%d, %d)", (const void *)tim, (const void *)param, param[0], param[1]);
const char *bitmap = (const char *)(tim->text + READ_LE_UINT16(tim->text + (param[0]<<1)));
Palette pal(_screen->getPalette(0).getNumColors());
_screen->loadBitmap(bitmap, 3, 3, &pal);
if (_flags.use16ColorMode) {
_screen->getPalette(0).clear();
_screen->setScreenPalette(_screen->getPalette(0));
_screen->copyPage(2, 0);
}
_screen->fadePalette(pal, param[1]);
return 1;
}
int LoLEngine::tlol_fadeOutSound(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_fadeOutSound(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
_sound->beginFadeOut();
return 1;
}
int LoLEngine::tlol_displayAnimFrame(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_displayAnimFrame(%p, %p) (%d, %d)", (const void *)tim, (const void *)param, param[0], param[1]);
const int animIndex = tim->wsa[param[0]].anim - 1;
const Movie *wsa = _animator->getWsaCPtr(animIndex);
if (param[1] == 0xFFFF) {
_screen->copyRegion(0, 0, 0, 0, 320, 200, 0, 2, Screen::CR_NO_P_CHECK);
} else {
_animator->displayFrame(animIndex, 2, param[1], 0);
_screen->copyRegion(wsa->xAdd(), wsa->yAdd(), wsa->xAdd(), wsa->yAdd(), wsa->width(), wsa->height(), 2, 0);
}
return 1;
}
int LoLEngine::tlol_delayForChat(const TIM *tim, const uint16 *param) {
debugC(3, kDebugLevelScriptFuncs, "LoLEngine::tlol_delayForChat(%p, %p) (%d)", (const void *)tim, (const void *)param, param[0]);
if (!speechEnabled())
delay(param[0]);
return 1;
}
#pragma mark -
typedef Common::Functor1Mem<EMCState *, int, LoLEngine> OpcodeV2;
#define SetOpcodeTable(x) table = &x;
#define Opcode(x) table->push_back(new OpcodeV2(this, &LoLEngine::x))
#define OpcodeUnImpl() table->push_back(new OpcodeV2(this, 0))
typedef Common::Functor2Mem<const TIM *, const uint16 *, int, LoLEngine> TIMOpcodeLoL;
#define SetTimOpcodeTable(x) timTable = &x;
#define OpcodeTim(x) timTable->push_back(new TIMOpcodeLoL(this, &LoLEngine::x))
#define OpcodeTimUnImpl() timTable->push_back(new TIMOpcodeLoL(this, 0))
void LoLEngine::setupOpcodeTable() {
Common::Array<const Opcode *> *table = 0;
_opcodes.reserve(192);
SetOpcodeTable(_opcodes);
// 0x00
Opcode(olol_setWallType);
Opcode(olol_getWallType);
Opcode(olol_drawScene);
Opcode(olol_rollDice);
// 0x04
Opcode(olol_moveParty);
OpcodeUnImpl();
Opcode(olol_delay);
Opcode(olol_setGameFlag);
// 0x08
Opcode(olol_testGameFlag);
Opcode(olol_loadLevelGraphics);
Opcode(olol_loadBlockProperties);
Opcode(olol_loadMonsterShapes);
// 0x0C
Opcode(olol_deleteHandItem);
Opcode(olol_allocItemPropertiesBuffer);
Opcode(olol_setItemProperty);
Opcode(olol_makeItem);
// 0x10
Opcode(olol_placeMoveLevelItem);
Opcode(olol_createLevelItem);
Opcode(olol_getItemPara);
Opcode(olol_getCharacterStat);
// 0x14
Opcode(olol_setCharacterStat);
Opcode(olol_loadLevelShapes);
Opcode(olol_closeLevelShapeFile);
OpcodeUnImpl();
// 0x18
Opcode(olol_loadDoorShapes);
Opcode(olol_initAnimStruct);
Opcode(olol_playAnimationPart);
Opcode(olol_freeAnimStruct);
// 0x1C
Opcode(olol_getDirection);
Opcode(olol_characterSurpriseFeedback);
Opcode(olol_setMusicTrack);
Opcode(olol_setSequenceButtons);
// 0x20
Opcode(olol_setDefaultButtonState);
Opcode(olol_checkRectForMousePointer);
Opcode(olol_clearDialogueField);
Opcode(olol_setupBackgroundAnimationPart);
// 0x24
Opcode(olol_startBackgroundAnimation);
Opcode(o1_hideMouse);
Opcode(o1_showMouse);
Opcode(olol_fadeToBlack);
// 0x28
Opcode(olol_fadePalette);
Opcode(olol_loadBitmap);
Opcode(olol_stopBackgroundAnimation);
OpcodeUnImpl();
// 0x2C
OpcodeUnImpl();
Opcode(olol_getGlobalScriptVar);
Opcode(olol_setGlobalScriptVar);
Opcode(olol_getGlobalVar);
// 0x30
Opcode(olol_setGlobalVar);
Opcode(olol_triggerDoorSwitch);
Opcode(olol_checkEquippedItemScriptFlags);
Opcode(olol_setDoorState);
// 0x34
Opcode(olol_updateBlockAnimations);
Opcode(olol_mapShapeToBlock);
Opcode(olol_resetBlockShapeAssignment);
Opcode(olol_copyRegion);
// 0x38
Opcode(olol_initMonster);
Opcode(olol_fadeClearSceneWindow);
Opcode(olol_fadeSequencePalette);
Opcode(olol_redrawPlayfield);
// 0x3C
Opcode(olol_loadNewLevel);
Opcode(olol_getNearestMonsterFromCharacter);
Opcode(olol_dummy0);
Opcode(olol_loadMonsterProperties);
// 0x40
Opcode(olol_battleHitSkillTest);
Opcode(olol_inflictDamage);
OpcodeUnImpl();
OpcodeUnImpl();
// 0x44
Opcode(olol_moveMonster);
Opcode(olol_dialogueBox);
Opcode(olol_giveTakeMoney);
Opcode(olol_checkMoney);
// 0x48
Opcode(olol_setScriptTimer);
Opcode(olol_createHandItem);
Opcode(olol_playAttackSound);
Opcode(olol_characterJoinsParty);
// 0x4C
Opcode(olol_giveItem);
OpcodeUnImpl();
Opcode(olol_loadTimScript);
Opcode(olol_runTimScript);
// 0x50
Opcode(olol_releaseTimScript);
Opcode(olol_initSceneWindowDialogue);
Opcode(olol_restoreAfterSceneWindowDialogue);
Opcode(olol_getItemInHand);
// 0x54
Opcode(olol_checkMagic);
Opcode(olol_giveItemToMonster);
Opcode(olol_loadLangFile);
Opcode(olol_playSoundEffect);
// 0x58
Opcode(olol_processDialogue);
Opcode(olol_stopTimScript);
Opcode(olol_getWallFlags);
Opcode(olol_changeMonsterStat);
// 0x5C
Opcode(olol_getMonsterStat);
Opcode(olol_releaseMonsterShapes);
Opcode(olol_playCharacterScriptChat);
Opcode(olol_update);
// 0x60
Opcode(olol_playEnvironmentalSfx);
Opcode(olol_healCharacter);
Opcode(olol_drawExitButton);
Opcode(olol_loadSoundFile);
// 0x64
Opcode(olol_playMusicTrack);
Opcode(olol_deleteMonstersFromBlock);
Opcode(olol_countBlockItems);
Opcode(olol_characterSkillTest);
// 0x68
Opcode(olol_countAllMonsters);
Opcode(olol_playEndSequence);
Opcode(olol_stopPortraitSpeechAnim);
Opcode(olol_setPaletteBrightness);
// 0x6C
Opcode(olol_calcInflictableDamage);
Opcode(olol_getInflictedDamage);
Opcode(olol_checkForCertainPartyMember);
Opcode(olol_printMessage);
// 0x70
Opcode(olol_deleteLevelItem);
Opcode(olol_calcInflictableDamagePerItem);
Opcode(olol_distanceAttack);
Opcode(olol_removeCharacterEffects);
// 0x74
Opcode(olol_checkInventoryFull);
Opcode(olol_objectLeavesLevel);
OpcodeUnImpl();
OpcodeUnImpl();
// 0x78
Opcode(olol_addSpellToScroll);
Opcode(olol_playDialogueText);
Opcode(olol_playDialogueTalkText);
Opcode(olol_checkMonsterTypeHostility);
// 0x7C
Opcode(olol_setNextFunc);
Opcode(olol_dummy1);
OpcodeUnImpl();
Opcode(olol_suspendMonster);
// 0x80
Opcode(olol_setScriptTextParameter);
Opcode(olol_triggerEventOnMouseButtonClick);
Opcode(olol_printWindowText);
Opcode(olol_countSpecificMonsters);
// 0x84
Opcode(olol_updateBlockAnimations2);
Opcode(olol_checkPartyForItemType);
Opcode(olol_blockDoor);
Opcode(olol_resetTimDialogueState);
// 0x88
Opcode(olol_getItemOnPos);
Opcode(olol_removeLevelItem);
Opcode(olol_savePage5);
Opcode(olol_restorePage5);
// 0x8C
Opcode(olol_initDialogueSequence);
Opcode(olol_restoreAfterDialogueSequence);
Opcode(olol_setSpecialSceneButtons);
Opcode(olol_restoreButtonsAfterSpecialScene);
// 0x90
OpcodeUnImpl();
OpcodeUnImpl();
Opcode(olol_prepareSpecialScene);
Opcode(olol_restoreAfterSpecialScene);
// 0x94
Opcode(olol_assignCustomSfx);
OpcodeUnImpl();
Opcode(olol_findAssignedMonster);
Opcode(olol_checkBlockForMonster);
// 0x98
Opcode(olol_transformRegion);
Opcode(olol_calcCoordinatesAddDirectionOffset);
Opcode(olol_resetPortraitsAndDisableSysTimer);
Opcode(olol_enableSysTimer);
// 0x9C
Opcode(olol_checkNeedSceneRestore);
Opcode(olol_getNextActiveCharacter);
Opcode(olol_paralyzePoisonCharacter);
Opcode(olol_drawCharPortrait);
// 0xA0
Opcode(olol_removeInventoryItem);
OpcodeUnImpl();
OpcodeUnImpl();
Opcode(olol_getAnimationLastPart);
// 0xA4
Opcode(olol_assignSpecialGuiShape);
Opcode(olol_findInventoryItem);
Opcode(olol_restoreFadePalette);
Opcode(olol_calcNewBlockPosition);
// 0xA8
Opcode(olol_getSelectedCharacter);
Opcode(olol_setHandItem);
Opcode(olol_drinkBezelCup);
Opcode(olol_changeItemTypeOrFlag);
// 0xAC
Opcode(olol_placeInventoryItemInHand);
Opcode(olol_castSpell);
Opcode(olol_pitDrop);
Opcode(olol_increaseSkill);
// 0xB0
Opcode(olol_paletteFlash);
Opcode(olol_restoreMagicShroud);
Opcode(olol_dummy1); // anim buffer select?
Opcode(olol_disableControls);
// 0xB4
Opcode(olol_enableControls);
Opcode(olol_shakeScene);
Opcode(olol_gasExplosion);
Opcode(olol_calcNewBlockPosition);
// 0xB8
Opcode(olol_fadeScene);
Opcode(olol_updateDrawPage2);
Opcode(olol_setMouseCursor);
Opcode(olol_characterSays);
// 0xBC
Opcode(olol_queueSpeech);
Opcode(olol_getItemPrice);
Opcode(olol_getLanguage);
Opcode(olol_dummy0);
Common::Array<const TIMOpcode *> *timTable = 0;
_timIntroOpcodes.reserve(8);
SetTimOpcodeTable(_timIntroOpcodes);
// 0x00
OpcodeTim(tlol_setupPaletteFade);
OpcodeTimUnImpl();
OpcodeTim(tlol_loadPalette);
OpcodeTim(tlol_setupPaletteFadeEx);
// 0x04
OpcodeTim(tlol_processWsaFrame);
OpcodeTim(tlol_displayText);
OpcodeTimUnImpl();
OpcodeTimUnImpl();
_timOutroOpcodes.reserve(16);
SetTimOpcodeTable(_timOutroOpcodes);
// 0x00
OpcodeTim(tlol_setupPaletteFade);
OpcodeTimUnImpl();
OpcodeTim(tlol_loadPalette);
OpcodeTim(tlol_setupPaletteFadeEx);
// 0x04
OpcodeTimUnImpl();
OpcodeTim(tlol_fadeInScene);
OpcodeTim(tlol_unusedResourceFunc);
OpcodeTim(tlol_unusedResourceFunc);
// 0x08
OpcodeTim(tlol_fadeInPalette);
OpcodeTimUnImpl();
OpcodeTimUnImpl();
OpcodeTim(tlol_fadeOutSound);
// 0x0C
OpcodeTim(tlol_displayAnimFrame);
OpcodeTim(tlol_delayForChat);
OpcodeTim(tlol_displayText);
OpcodeTimUnImpl();
_timIngameOpcodes.reserve(17);
SetTimOpcodeTable(_timIngameOpcodes);
// 0x00
OpcodeTim(tlol_initSceneWindowDialogue);
OpcodeTim(tlol_restoreAfterSceneWindowDialogue);
OpcodeTimUnImpl();
OpcodeTim(tlol_giveItem);
// 0x04
OpcodeTim(tlol_setPartyPosition);
OpcodeTim(tlol_fadeClearWindow);
OpcodeTim(tlol_copyRegion);
OpcodeTim(tlol_characterChat);
// 0x08
OpcodeTim(tlol_drawScene);
OpcodeTim(tlol_update);
OpcodeTim(tlol_clearTextField);
OpcodeTim(tlol_loadSoundFile);
// 0x0C
OpcodeTim(tlol_playMusicTrack);
OpcodeTim(tlol_playDialogueTalkText);
OpcodeTim(tlol_playSoundEffect);
OpcodeTim(tlol_startBackgroundAnimation);
// 0x10
OpcodeTim(tlol_stopBackgroundAnimation);
}
} // End of namespace Kyra
#endif // ENABLE_LOL
| tramboi/scummvm-test | engines/kyra/script_lol.cpp | C++ | gpl-2.0 | 94,493 |
/*
This file is part of the Android application TarotDroid.
TarotDroid 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.
TarotDroid 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 TarotDroid. If not, see <http://www.gnu.org/licenses/>.
*/
package org.nla.tarotdroid.lib.ui.controls;
import org.nla.tarotdroid.lib.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.facebook.widget.ProfilePictureView;
/**
* A view aimed to display an facebook picture, a title and a content.
* @author Nicolas LAURENT daffycricket<a>yahoo.fr
*/
public class FacebookThumbnailItem extends LinearLayout {
/**
* The title string.
*/
private CharSequence title;
/**
* The content string.
*/
private CharSequence content;
/**
* The facebook id.
*/
private String facebookId;
/**
* Constructs a FacebookThumbnailItem.
* @param context
* @param facebookId
* @param title
* @param content
*/
public FacebookThumbnailItem(final Context context, String facebookId, CharSequence title, CharSequence content) {
super(context);
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.thumbnail_item_facebook, this);
this.facebookId = facebookId;
this.title = title;
this.content = content;
this.initializeViews();
}
/**
* Initializes the views.
*/
private void initializeViews() {
TextView txtTitle = (TextView) this.findViewById(R.id.txtTitle);
TextView txtContent = (TextView) this.findViewById(R.id.txtContent);
txtTitle.setText(this.title);
txtContent.setText(this.content);
if (this.facebookId != null) {
ProfilePictureView pictureView = (ProfilePictureView) this.findViewById(R.id.imgThumbnail);
pictureView.setProfileId(this.facebookId);
}
}
}
| daffycricket/tarotdroid | tarotDroidUiLib/src/main/java/org/nla/tarotdroid/lib/ui/controls/FacebookThumbnailItem.java | Java | gpl-2.0 | 2,372 |
<?php
namespace MediaWiki\Rest;
/**
* This is the base exception class for non-fatal exceptions thrown from REST
* handlers. The exception is not logged, it is merely converted to an
* error response.
*/
class HttpException extends \Exception {
/** @var array|null */
private $errorData = null;
public function __construct( $message, $code = 500, $errorData = null ) {
parent::__construct( $message, $code );
$this->errorData = $errorData;
}
/**
* @return array|null
*/
public function getErrorData() {
return $this->errorData;
}
}
| pierres/archlinux-mediawiki | includes/Rest/HttpException.php | PHP | gpl-2.0 | 558 |
module MusikHelper
end
| tiy-hou-q3-2015-rails/Musik | app/helpers/musik_helper.rb | Ruby | gpl-2.0 | 23 |
// Created by plusminus on 21:46:22 - 25.09.2008
package com.mapbox.mapboxsdk.tileprovider;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import com.mapbox.mapboxsdk.geometry.BoundingBox;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.tileprovider.constants.TileLayerConstants;
import com.mapbox.mapboxsdk.tileprovider.tilesource.ITileLayer;
import com.mapbox.mapboxsdk.util.BitmapUtils;
import uk.co.senab.bitmapcache.CacheableBitmapDrawable;
/**
* This is an abstract class. The tile provider is responsible for:
* <ul>
* <li>determining if a map tile is available,</li>
* <li>notifying the client, via a callback handler</li>
* </ul>
* see {@link MapTile} for an overview of how tiles are served by this provider.
*
* @author Marc Kurtz
* @author Nicolas Gramlich
*/
public abstract class MapTileLayerBase implements IMapTileProviderCallback, TileLayerConstants {
protected Context context;
protected final MapTileCache mTileCache;
private Handler mTileRequestCompleteHandler;
private boolean mUseDataConnection = true;
private ITileLayer mTileSource;
protected String mCacheKey = "";
/**
* Attempts to get a Drawable that represents a {@link MapTile}. If the tile is not immediately
* available this will return null and attempt to get the tile from known tile sources for
* subsequent future requests. Note that this may return a {@link CacheableBitmapDrawable} in
* which case you should follow proper handling procedures for using that Drawable or it may
* reused while you are working with it.
*
* @see CacheableBitmapDrawable
*/
public abstract Drawable getMapTile(MapTile pTile, boolean allowRemote);
public abstract void detach();
/**
* Gets the minimum zoom level this tile provider can provide
*
* @return the minimum zoom level
*/
public float getMinimumZoomLevel() {
return mTileSource.getMinimumZoomLevel();
}
/**
* Get the maximum zoom level this tile provider can provide.
*
* @return the maximum zoom level
*/
public float getMaximumZoomLevel() {
return mTileSource.getMaximumZoomLevel();
}
/**
* Get the tile size in pixels this tile provider provides.
*
* @return the tile size in pixels
*/
public int getTileSizePixels() {
return mTileSource.getTileSizePixels();
}
/**
* Get the tile provider bounding box.
*
* @return the tile source bounding box
*/
public BoundingBox getBoundingBox() {
return mTileSource.getBoundingBox();
}
/**
* Get the tile provider center.
*
* @return the tile source center
*/
public LatLng getCenterCoordinate() {
return mTileSource.getCenterCoordinate();
}
/**
* Get the tile provider suggested starting zoom.
*
* @return the tile suggested starting zoom
*/
public float getCenterZoom() {
return mTileSource.getCenterZoom();
}
/**
* Sets the tile source for this tile provider.
*
* @param pTileSource the tile source
*/
public void setTileSource(final ITileLayer pTileSource) {
if (mTileSource != null) {
mTileSource.detach();
}
mTileSource = pTileSource;
if (mTileSource != null) {
mCacheKey = mTileSource.getCacheKey();
}
}
/**
* Gets the tile source for this tile provider.
*
* @return the tile source
*/
public ITileLayer getTileSource() {
return mTileSource;
}
/**
* Gets the cache key for that layer
*
* @return the cache key
*/
public String getCacheKey() {
return mCacheKey;
}
/**
* Creates a {@link MapTileCache} to be used to cache tiles in memory.
*/
public MapTileCache createTileCache(final Context aContext) {
return new MapTileCache(aContext);
}
public MapTileLayerBase(final Context aContext, final ITileLayer pTileSource) {
this(aContext, pTileSource, null);
}
public MapTileLayerBase(final Context aContext, final ITileLayer pTileSource,
final Handler pDownloadFinishedListener) {
this.context = aContext;
mTileRequestCompleteHandler = pDownloadFinishedListener;
mTileSource = pTileSource;
mTileCache = this.createTileCache(aContext);
}
/**
* Called by implementation class methods indicating that they have completed the request as
* best it can. The tile is added to the cache, and a MAPTILE_SUCCESS_ID message is sent.
*
* @param pState the map tile request state object
* @param pDrawable the Drawable of the map tile
*/
@Override
public void mapTileRequestCompleted(final MapTileRequestState pState,
final Drawable pDrawable) {
// tell our caller we've finished and it should update its view
if (mTileRequestCompleteHandler != null) {
Message msg = new Message();
msg.obj = pState.getMapTile().getTileRect();
msg.what = MapTile.MAPTILE_SUCCESS_ID;
mTileRequestCompleteHandler.sendMessage(msg);
}
if (DEBUG_TILE_PROVIDERS) {
Log.d(TAG, "MapTileLayerBase.mapTileRequestCompleted(): " + pState.getMapTile());
}
}
/**
* Called by implementation class methods indicating that they have failed to retrieve the
* requested map tile. a MAPTILE_FAIL_ID message is sent.
*
* @param pState the map tile request state object
*/
@Override
public void mapTileRequestFailed(final MapTileRequestState pState) {
if (mTileRequestCompleteHandler != null) {
mTileRequestCompleteHandler.sendEmptyMessage(MapTile.MAPTILE_FAIL_ID);
}
if (DEBUG_TILE_PROVIDERS) {
Log.d(TAG, "MapTileLayerBase.mapTileRequestFailed(): " + pState.getMapTile());
}
}
/**
* Called by implementation class methods indicating that they have produced an expired result
* that can be used but better results may be delivered later. The tile is added to the cache,
* and a MAPTILE_SUCCESS_ID message is sent.
*
* @param pState the map tile request state object
* @param pDrawable the Drawable of the map tile
*/
@Override
public void mapTileRequestExpiredTile(MapTileRequestState pState,
CacheableBitmapDrawable pDrawable) {
// Put the expired tile into the cache
putExpiredTileIntoCache(pState.getMapTile(), pDrawable.getBitmap());
// tell our caller we've finished and it should update its view
if (mTileRequestCompleteHandler != null) {
mTileRequestCompleteHandler.sendEmptyMessage(MapTile.MAPTILE_SUCCESS_ID);
}
if (DEBUG_TILE_PROVIDERS) {
Log.i(TAG, "MapTileLayerBase.mapTileRequestExpiredTile(): " + pState.getMapTile());
}
}
private void putTileIntoCacheInternal(final MapTile pTile, final Drawable pDrawable) {
mTileCache.putTile(pTile, pDrawable);
}
private class CacheTask extends AsyncTask<Object, Void, Void> {
@Override
protected Void doInBackground(Object... params) {
putTileIntoCacheInternal((MapTile) params[0], (Drawable) params[1]);
return null;
}
}
private void putTileIntoCache(final MapTile pTile, final Drawable pDrawable) {
if (pDrawable != null) {
if (Looper.myLooper() == Looper.getMainLooper()) {
(new CacheTask()).execute(pTile, pDrawable);
} else {
putTileIntoCacheInternal(pTile, pDrawable);
}
}
}
protected void putTileIntoCache(final MapTileRequestState pState, final Drawable pDrawable) {
putTileIntoCache(pState.getMapTile(), pDrawable);
}
protected void removeTileFromCache(final MapTileRequestState pState) {
mTileCache.removeTileFromMemory(pState.getMapTile());
}
public void putExpiredTileIntoCache(final MapTile pTile, final Bitmap bitmap) {
if (bitmap == null) {
return;
}
CacheableBitmapDrawable drawable = mTileCache.putTileInMemoryCache(pTile, bitmap);
BitmapUtils.setCacheDrawableExpired(drawable);
}
public void setTileRequestCompleteHandler(final Handler handler) {
mTileRequestCompleteHandler = handler;
}
public void clearTileMemoryCache() {
mTileCache.purgeMemoryCache();
}
public void clearTileDiskCache() {
mTileCache.purgeDiskCache();
}
public void setDiskCacheEnabled(final boolean enabled) {
mTileCache.setDiskCacheEnabled(enabled);
}
/**
* Whether to use the network connection if it's available.
*/
@Override
public boolean useDataConnection() {
return mUseDataConnection;
}
/**
* Set whether to use the network connection if it's available.
*
* @param pMode if true use the network connection if it's available. if false don't use the
* network connection even if it's available.
*/
public void setUseDataConnection(final boolean pMode) {
mUseDataConnection = pMode;
}
public boolean hasNoSource() {
return mTileSource == null;
}
public CacheableBitmapDrawable getMapTileFromMemory(MapTile pTile) {
return (mTileCache != null) ? mTileCache.getMapTileFromMemory(pTile) : null;
}
public CacheableBitmapDrawable createCacheableBitmapDrawable(Bitmap bitmap, MapTile aTile) {
return (mTileCache != null) ? mTileCache.createCacheableBitmapDrawable(bitmap, aTile)
: null;
}
public Bitmap getBitmapFromRemoved(final int width, final int height) {
return (mTileCache != null) ? mTileCache.getBitmapFromRemoved(width, height) : null;
}
/**
* If a given MapTile is present in this cache, remove it from memory.
* @param aTile
*/
public void removeTileFromMemory(final MapTile aTile) {
if (mTileCache != null) {
mTileCache.removeTileFromMemory(aTile);
}
}
private static final String TAG = "MapTileLayerBase";
}
| RoProducts/rastertheque | MapboxLibrary/src/com/mapbox/mapboxsdk/tileprovider/MapTileLayerBase.java | Java | gpl-2.0 | 10,470 |
<?php
/**
* @version $Id: edit.php 132 2013-05-20 07:12:44Z michal $
* @package DJ-Catalog2
* @copyright Copyright (C) 2012 DJ-Extensions.com LTD, All rights reserved.
* @license http://www.gnu.org/licenses GNU/GPL
* @author url: http://dj-extensions.com
* @author email contact@dj-extensions.com
* @developer Michal Olczyk - michal.olczyk@design-joomla.eu
*
* DJ-Catalog2 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.
*
* DJ-Catalog2 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 DJ-Catalog2. If not, see <http://www.gnu.org/licenses/>.
*
*/
// no direct access
defined('_JEXEC') or die;
JHtml::_('behavior.tooltip');
JHtml::_('behavior.formvalidation');
JHtml::_('formbehavior.chosen', 'select');
$app = JFactory::getApplication();
?>
<script type="text/javascript">
Joomla.submitbutton = function(task)
{
if (task == 'category.cancel' || document.formvalidator.isValid(document.id('category-form'))) {
<?php echo $this->form->getField('description')->save(); ?>
Joomla.submitform(task, document.getElementById('category-form'));
}
else {
alert('<?php echo $this->escape(JText::_('JGLOBAL_VALIDATION_FORM_FAILED'));?>');
}
}
</script>
<form action="<?php echo JRoute::_('index.php?option=com_djcatalog2&view=category&layout=edit&id='.(int) $this->item->id); ?>" method="post" name="adminForm" id="category-form" class="form-validate" enctype="multipart/form-data">
<div class="row-fluid">
<div class="span12 form-horizontal">
<fieldset>
<ul class="nav nav-tabs">
<li class="active"><a href="#details" data-toggle="tab"><?php echo empty($this->item->id) ? JText::_('COM_DJCATALOG2_NEW') : JText::_('COM_DJCATALOG2_EDIT'); ?></a></li>
<li>
<a href="#publishing" data-toggle="tab"><?php echo JText::_('JGLOBAL_FIELDSET_PUBLISHING');?></a>
</li>
<li>
<a href="#images" data-toggle="tab"><?php echo JText::_('COM_DJCATALOG2_IMAGES'); ?></a>
</li>
<?php $fieldSets = $this->form->getFieldsets('params'); ?>
<?php foreach ($fieldSets as $name => $fieldSet) { ?>
<li>
<a href="#params-<?php echo $name; ?>" data-toggle="tab"><?php echo JText::_($fieldSet->label); ?></a>
</li>
<?php } ?>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="details">
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('name'); ?></div>
<div class="controls"><?php echo $this->form->getInput('name'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('alias'); ?></div>
<div class="controls"><?php echo $this->form->getInput('alias'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('parent_id'); ?></div>
<div class="controls"><?php echo $this->form->getInput('parent_id'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('published'); ?></div>
<div class="controls"><?php echo $this->form->getInput('published'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('id'); ?></div>
<div class="controls"><?php echo $this->form->getInput('id'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('created'); ?></div>
<div class="controls"><?php echo $this->form->getInput('created'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('created_by'); ?></div>
<div class="controls"><?php echo $this->form->getInput('created_by'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('description'); ?></div>
<div class="controls"><?php echo $this->form->getInput('description'); ?></div>
</div>
</div>
<div class="tab-pane" id="publishing">
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('metatitle'); ?></div>
<div class="controls"><?php echo $this->form->getInput('metatitle'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('metadesc'); ?></div>
<div class="controls"><?php echo $this->form->getInput('metadesc'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('metakey'); ?></div>
<div class="controls"><?php echo $this->form->getInput('metakey'); ?></div>
</div>
</div>
<div class="tab-pane" id="images">
<?php echo DJCatalog2ImageHelper::renderInput('category',$app->input->get('id', null, 'int')); ?>
</div>
<?php echo $this->loadTemplate('params'); ?>
</div>
</fieldset>
</div>
</div>
<input type="hidden" name="task" value="" />
<?php echo JHtml::_('form.token'); ?>
</form> | toandevitviet/vpan | administrator/components/com_djcatalog2/views/category/tmpl/edit.php | PHP | gpl-2.0 | 5,643 |
package org.nwnx.nwnx2.jvm.constants;
/**
* This class contains all unique constants beginning with "CREATURE".
* Non-distinct keys are filtered; only the LAST appearing was
* kept.
*/
public final class Creature {
private Creature() {}
public final static int MODEL_TYPE_NONE = 0;
public final static int MODEL_TYPE_SKIN = 1;
public final static int MODEL_TYPE_TATTOO = 2;
public final static int MODEL_TYPE_UNDEAD = 255;
public final static int PART_BELT = 8;
public final static int PART_HEAD = 20;
public final static int PART_LEFT_BICEP = 13;
public final static int PART_LEFT_FOOT = 1;
public final static int PART_LEFT_FOREARM = 11;
public final static int PART_LEFT_HAND = 17;
public final static int PART_LEFT_SHIN = 3;
public final static int PART_LEFT_SHOULDER = 15;
public final static int PART_LEFT_THIGH = 4;
public final static int PART_NECK = 9;
public final static int PART_PELVIS = 6;
public final static int PART_RIGHT_BICEP = 12;
public final static int PART_RIGHT_FOOT = 0;
public final static int PART_RIGHT_FOREARM = 10;
public final static int PART_RIGHT_HAND = 16;
public final static int PART_RIGHT_SHIN = 2;
public final static int PART_RIGHT_SHOULDER = 14;
public final static int PART_RIGHT_THIGH = 5;
public final static int PART_TORSO = 7;
public final static int SIZE_HUGE = 5;
public final static int SIZE_INVALID = 0;
public final static int SIZE_LARGE = 4;
public final static int SIZE_MEDIUM = 3;
public final static int SIZE_SMALL = 2;
public final static int SIZE_TINY = 1;
public final static int TAIL_TYPE_BONE = 2;
public final static int TAIL_TYPE_DEVIL = 3;
public final static int TAIL_TYPE_LIZARD = 1;
public final static int TAIL_TYPE_NONE = 0;
public final static int TYPE_CLASS = 2;
public final static int TYPE_DOES_NOT_HAVE_SPELL_EFFECT = 6;
public final static int TYPE_HAS_SPELL_EFFECT = 5;
public final static int TYPE_IS_ALIVE = 4;
public final static int TYPE_PERCEPTION = 7;
public final static int TYPE_PLAYER_CHAR = 1;
public final static int TYPE_RACIAL_TYPE = 0;
public final static int TYPE_REPUTATION = 3;
public final static int WING_TYPE_ANGEL = 2;
public final static int WING_TYPE_BAT = 3;
public final static int WING_TYPE_BIRD = 6;
public final static int WING_TYPE_BUTTERFLY = 5;
public final static int WING_TYPE_DEMON = 1;
public final static int WING_TYPE_DRAGON = 4;
public final static int WING_TYPE_NONE = 0;
public static String nameOf(int value) {
if (value == 0) return "Creature.MODEL_TYPE_NONE";
if (value == 1) return "Creature.MODEL_TYPE_SKIN";
if (value == 2) return "Creature.MODEL_TYPE_TATTOO";
if (value == 255) return "Creature.MODEL_TYPE_UNDEAD";
if (value == 8) return "Creature.PART_BELT";
if (value == 20) return "Creature.PART_HEAD";
if (value == 13) return "Creature.PART_LEFT_BICEP";
if (value == 1) return "Creature.PART_LEFT_FOOT";
if (value == 11) return "Creature.PART_LEFT_FOREARM";
if (value == 17) return "Creature.PART_LEFT_HAND";
if (value == 3) return "Creature.PART_LEFT_SHIN";
if (value == 15) return "Creature.PART_LEFT_SHOULDER";
if (value == 4) return "Creature.PART_LEFT_THIGH";
if (value == 9) return "Creature.PART_NECK";
if (value == 6) return "Creature.PART_PELVIS";
if (value == 12) return "Creature.PART_RIGHT_BICEP";
if (value == 0) return "Creature.PART_RIGHT_FOOT";
if (value == 10) return "Creature.PART_RIGHT_FOREARM";
if (value == 16) return "Creature.PART_RIGHT_HAND";
if (value == 2) return "Creature.PART_RIGHT_SHIN";
if (value == 14) return "Creature.PART_RIGHT_SHOULDER";
if (value == 5) return "Creature.PART_RIGHT_THIGH";
if (value == 7) return "Creature.PART_TORSO";
if (value == 5) return "Creature.SIZE_HUGE";
if (value == 0) return "Creature.SIZE_INVALID";
if (value == 4) return "Creature.SIZE_LARGE";
if (value == 3) return "Creature.SIZE_MEDIUM";
if (value == 2) return "Creature.SIZE_SMALL";
if (value == 1) return "Creature.SIZE_TINY";
if (value == 2) return "Creature.TAIL_TYPE_BONE";
if (value == 3) return "Creature.TAIL_TYPE_DEVIL";
if (value == 1) return "Creature.TAIL_TYPE_LIZARD";
if (value == 0) return "Creature.TAIL_TYPE_NONE";
if (value == 2) return "Creature.TYPE_CLASS";
if (value == 6) return "Creature.TYPE_DOES_NOT_HAVE_SPELL_EFFECT";
if (value == 5) return "Creature.TYPE_HAS_SPELL_EFFECT";
if (value == 4) return "Creature.TYPE_IS_ALIVE";
if (value == 7) return "Creature.TYPE_PERCEPTION";
if (value == 1) return "Creature.TYPE_PLAYER_CHAR";
if (value == 0) return "Creature.TYPE_RACIAL_TYPE";
if (value == 3) return "Creature.TYPE_REPUTATION";
if (value == 2) return "Creature.WING_TYPE_ANGEL";
if (value == 3) return "Creature.WING_TYPE_BAT";
if (value == 6) return "Creature.WING_TYPE_BIRD";
if (value == 5) return "Creature.WING_TYPE_BUTTERFLY";
if (value == 1) return "Creature.WING_TYPE_DEMON";
if (value == 4) return "Creature.WING_TYPE_DRAGON";
if (value == 0) return "Creature.WING_TYPE_NONE";
return "Creature.(not found: " + value + ")";
}
public static String nameOf(float value) {
return "Creature.(not found: " + value + ")";
}
public static String nameOf(String value) {
return "Creature.(not found: " + value + ")";
}
}
| Baaleos/nwnx2-linux | plugins/jvm/java/src/org/nwnx/nwnx2/jvm/constants/Creature.java | Java | gpl-2.0 | 5,415 |
# -*- coding: utf-8 -*-
# Copyright 2009,2014 Jaap Karssenberg <jaap.karssenberg@gmail.com>
'''This module contains helper classes for running external applications.
See L{zim.gui.applications} for classes with desktop integration for
applications defined in desktop entry files.
'''
import sys
import os
import logging
import subprocess
import gobject
import zim.fs
import zim.errors
from zim.fs import File
from zim.parsing import split_quoted_strings, is_uri_re, is_win32_path_re
from zim.environ import environ
logger = logging.getLogger('zim.applications')
def _main_is_frozen():
# Detect whether we are running py2exe compiled version
return hasattr(sys, 'frozen') and sys.frozen
class ApplicationError(zim.errors.Error):
'''Error raises for error in sub process errors'''
description = None
def __init__(self, cmd, args, retcode, stderr):
'''Constructor
@param cmd: the application command as string
@param args: tuple of arguments given to the command
@param retcode: the return code of the command (non-zero!)
@param stderr: the error output of the command
'''
self.msg = _('Failed to run application: %s') % cmd
# T: Error message when external application failed, %s is the command
self.description = \
_('%(cmd)s\nreturned non-zero exit status %(code)i') \
% {'cmd': cmd + ' "' + '" "'.join(args) + '"', 'code': retcode}
# T: Error message when external application failed, %(cmd)s is the command, %(code)i the exit code
if stderr:
self.description += '\n\n' + stderr
class Application(object):
'''Base class for objects representing an external application or
command.
@ivar name: the name of the command (default to first item of C{cmd})
@ivar cmd: the command and arguments as a tuple or a string
(when given as a string it will be parsed for quoted arguments)
@ivar tryexeccmd: the command to check in L{tryexec()}, if C{None}
fall back to first item of C{cmd}
'''
STATUS_OK = 0 #: return code when the command executed succesfully
def __init__(self, cmd, tryexeccmd=None, encoding=None):
'''Constructor
@param cmd: the command for the external application, either a
string for the command, or a tuple or list with the command
and arguments
@param tryexeccmd: command to check in L{tryexec()} as string.
If C{None} will default to C{cmd} or the first item of C{cmd}.
@param encoding: the encoding to use for commandline args
if known, else falls back to system default
'''
if isinstance(cmd, basestring):
cmd = split_quoted_strings(cmd)
else:
assert isinstance(cmd, (tuple, list))
assert tryexeccmd is None or isinstance(tryexeccmd, basestring)
self.cmd = tuple(cmd)
self.tryexeccmd = tryexeccmd
self.encoding = encoding or zim.fs.ENCODING
if self.encoding == 'mbcs':
self.encoding = 'utf-8'
def __repr__(self):
if hasattr(self, 'key'):
return '<%s: %s>' % (self.__class__.__name__, self.key)
elif hasattr(self, 'cmd'):
return '<%s: %s>' % (self.__class__.__name__, self.cmd)
else:
return '<%s: %s>' % (self.__class__.__name__, self.name)
@property
def name(self):
return self.cmd[0]
@staticmethod
def _lookup(cmd):
'''Lookup cmd in PATH'''
if zim.fs.isabs(cmd):
if zim.fs.isfile(cmd):
return cmd
else:
return None
elif os.name == 'nt':
# Check executable extensions from windows environment
extensions = environ.get_list('PATHEXT', '.com;.exe;.bat;.cmd')
for dir in environ.get_list('PATH'):
for ext in extensions:
file = os.sep.join((dir, cmd + ext))
if zim.fs.isfile(file) and os.access(file, os.X_OK):
return file
else:
return None
else:
# On POSIX no extension is needed to make scripts executable
for dir in environ.get_list('PATH'):
file = os.sep.join((dir, cmd))
if zim.fs.isfile(file) and os.access(file, os.X_OK):
return file
else:
return None
def _cmd(self, args):
# substitute args in the command - to be overloaded by child classes
if args:
return self.cmd + tuple(map(unicode, args))
else:
return self.cmd
def tryexec(self):
'''Check if the executable exists without calling it. This
method is used e.g. to decide what applications to show in the
gui. Uses the C{tryexeccmd}, or the first item of C{cmd} as the
executable name.
@returns: C{True} when the executable was found
'''
cmd = self.tryexeccmd or self.cmd[0]
return not self._lookup(cmd) is None
def _checkargs(self, cwd, args):
assert args is None or isinstance(args, (tuple, list))
argv = self._cmd(args)
# Expand home dir
if argv[0].startswith('~'):
cmd = File(argv[0]).path
argv = list(argv)
argv[0] = cmd
# if it is a python script, insert interpreter as the executable
if argv[0].endswith('.py') and not _main_is_frozen():
argv = list(argv)
argv.insert(0, sys.executable)
# TODO: consider an additional commandline arg to re-use compiled python interpreter
argv = [a.encode(self.encoding) for a in argv]
if cwd:
cwd = unicode(cwd).encode(zim.fs.ENCODING)
return cwd, argv
def run(self, args=None, cwd=None):
'''Run the application in a sub-process and wait for it to finish.
Even when the application runs successfully, any message to stderr
is logged as a warning by zim.
@param args: additional arguments to give to the command as tuple or list
@param cwd: the folder to set as working directory for the command
@raises ApplicationError: if the sub-process returned an error.
'''
cwd, argv = self._checkargs(cwd, args)
logger.info('Running: %s (cwd: %s)', argv, cwd)
if os.name == 'nt':
# http://code.activestate.com/recipes/409002/
info = subprocess.STARTUPINFO()
try:
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
except AttributeError:
info.dwFlags |= 1 # STARTF_USESHOWWINDOW = 0x01
p = subprocess.Popen(argv,
cwd=cwd,
stdout=open(os.devnull, 'w'),
stderr=subprocess.PIPE,
startupinfo=info,
bufsize=4096,
#~ close_fds=True
)
else:
p = subprocess.Popen(argv,
cwd=cwd,
stdout=open(os.devnull, 'w'),
stderr=subprocess.PIPE,
bufsize=4096,
close_fds=True
)
stdout, stderr = p.communicate()
if not p.returncode == self.STATUS_OK:
raise ApplicationError(argv[0], argv[1:], p.returncode, stderr)
#~ elif stderr:
#~ logger.warn(stderr)
def pipe(self, args=None, cwd=None, input=None):
'''Run the application in a sub-process and capture the output.
Like L{run()}, but connects to stdin and stdout for the sub-process.
@note: The data read is buffered in memory, so do not use this
method if the data size is large or unlimited.
@param args: additional arguments to give to the command as tuple or list
@param cwd: the folder to set as working directory for the command
@param input: input for the command as string
@returns: output as a list of lines
@raises ApplicationError: if the sub-process returned an error.
'''
cwd, argv = self._checkargs(cwd, args)
logger.info('Running: %s (cwd: %s)', argv, cwd)
p = subprocess.Popen(argv, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate(input)
# TODO: handle ApplicationERror here as well ?
#~ if not p.returncode == self.STATUS_OK:
#~ raise ApplicationError(argv[0], argv[1:], p.returncode, stderr)
#~ elif stderr:
if stderr:
logger.warn(stderr)
# TODO: allow user to get this error as well - e.g. for logging image generator cmd
# Explicit newline conversion, e.g. on windows \r\n -> \n
# FIXME Assume local encoding is respected (!?)
text = [unicode(line + '\n', errors='replace') for line in stdout.splitlines()]
if text and text[-1].endswith('\n') and not stdout.endswith('\n'):
text[-1] = text[-1][:-1] # strip additional \n
return text
def spawn(self, args=None, callback=None, data=None, cwd=None):
'''Start the application in the background and return immediately.
This is used to start an external in parallel with zim that is
not expected to exit immediatly, so we do not want to wait for
it - e.g. a webbrowser to show an URL that was clicked.
@param args: additional arguments to give to the command as tuple or list
@param callback: optional callback can be used to trigger when
the application exits. The signature is::
callback(status, data)
where 'C{status}' is the exit status of the process. The
application object provides a constant 'C{STATUS_OK}' which can
be used to test if the application was successful or not.
@param data: additional data for the callback
@param cwd: the folder to set as working directory for the command
@returns: the PID for the new process
'''
cwd, argv = self._checkargs(cwd, args)
opts = {}
flags = gobject.SPAWN_SEARCH_PATH
if callback:
flags |= gobject.SPAWN_DO_NOT_REAP_CHILD
# without this flag child is reaped automatically -> no zombies
if not cwd:
cwd = os.getcwd()
logger.info('Spawning: %s (cwd: %s)', argv, cwd)
try:
pid, stdin, stdout, stderr = \
gobject.spawn_async(argv, flags=flags, working_directory=cwd, **opts)
except gobject.GError:
from zim.gui.widgets import ErrorDialog
ErrorDialog(None, _('Failed running: %s') % argv[0]).run()
#~ # T: error when application failed to start
return None
else:
logger.debug('Process started with PID: %i', pid)
if callback:
# child watch does implicit reaping -> no zombies
if data is None:
gobject.child_watch_add(pid,
lambda pid, status: callback(status))
else:
gobject.child_watch_add(pid,
lambda pid, status, data: callback(status, data), data)
return pid
class WebBrowser(Application):
'''Application wrapper for the C{webbrowser} module. Can be used as
fallback if no webbrowser is configured.
'''
name = _('Default') + ' (webbrowser)' # T: label for default webbrowser
key = 'webbrowser' # Used by zim.gui.applications
def __init__(self, encoding=None):
import webbrowser
self.controller = None
try:
self.controller = webbrowser.get()
except webbrowser.Error:
pass # webbrowser throws an error when no browser is found
self.encoding = encoding or zim.fs.ENCODING
if self.encoding == 'mbcs':
self.encoding = 'utf-8'
def tryexec(self):
return not self.controller is None
def run(self, args):
'''This method is not supported by this class
@raises NotImplementedError: always
'''
raise NotImplementedError('WebBrowser can not run in foreground')
def spawn(self, args, callback=None):
if callback:
raise NotImplementedError('WebBrowser can not handle callback')
for url in args:
if isinstance(url, (zim.fs.File, zim.fs.Dir)):
url = url.uri
url = url.encode(self.encoding)
logger.info('Opening in webbrowser: %s', url)
self.controller.open(url)
class StartFile(Application):
'''Application wrapper for C{os.startfile()}. Can be used on
windows to open files and URLs with the default application.
'''
name = _('Default') + ' (os)' # T: label for default application
key = 'startfile' # Used by zim.gui.applications
def __init__(self):
pass
def tryexec(self):
return hasattr(os, 'startfile')
def run(self, args):
'''This method is not supported by this class
@raises NotImplementedError: always
'''
raise NotImplementedError('StartFile can not run in foreground')
def spawn(self, args, callback=None):
if callback:
logger.warn('os.startfile does not support a callback')
for arg in args:
if isinstance(arg, (zim.fs.File, zim.fs.Dir)):
path = os.path.normpath(arg.path)
elif is_uri_re.match(arg) and not is_win32_path_re.match(arg):
# URL or e.g. mailto: or outlook: URI
path = unicode(arg)
else:
# must be file
path = os.path.normpath(unicode(arg))
logger.info('Opening with os.startfile: %s', path)
os.startfile(path)
| Osndok/zim-desktop-wiki | zim/applications.py | Python | gpl-2.0 | 11,848 |
/*
* collection
* A collection of posts
*
* If fetch items are specified, then only gets those posts.
* Otherwise, gets the posts specified from a configuration endpoint.
*/
define([
"lodash",
"backbone",
"helpers/urls",
"helpers/types",
"helpers/params",
"components/content/entities/parser",
"module"
], function(_, Backbone, urls, types, params, parser, module) {
// Definition of a post collection
var PostCollection = Backbone.Collection.extend({
urlRoot: module.config().urlRoot,
initialize: function(models, options) {
options = options || {};
// preserve any options specified to constructor
this.options = _.extend(this.options || {}, options);
},
// remove fetch items as they become models
_maintainItems: function(model) {
this.options.items = _.reject(this.options.items, function(item) {
return item.object_id == model[types.objectIdType(item.object_id)];
});
if (this.options.items.length === 0) {
this.off("add", this.maintainItems, this);
}
},
// merge in additional fetch items after initialize
mergeItems: function(items) {
// remove any new fetch items that are already fetched
items = _.reject(items, function(item) {
return this.get(item.object_id);
}, this);
// create a union of previous fetch items and the new fetch items
this.options.items = _.union(this.options.items, items);
},
url: function() {
var fetchItems = this.options.items;
// if fetch items are specified, get the specific items
// object_ids all have to be homogenous (same types)
if (fetchItems && fetchItems.length > 0) {
var method = types.objectIdType(fetchItems[0].object_id);
var posts = params.collection[method](_.pluck(fetchItems, "object_id"));
// maintain the fetchItems as they are added
this.on("add", this._maintainItems, this);
return urls.normalizeUrlRoot(this.urlRoot) +
"?post_type=any" +
"&"+posts +
"&"+params.meta.custom_fields;
} else {
return module.config().endpoint;
}
},
parse: function(data) {
return parser(data);
}
});
return PostCollection;
}); | localnerve/wpspa | app/components/content/entities/collection.js | JavaScript | gpl-2.0 | 2,289 |
/***************************************************************************
globe_plugin.cpp
Globe Plugin
a QGIS plugin
--------------------------------------
Date : 08-Jul-2010
Copyright : (C) 2010 by Sourcepole
Email : info at sourcepole.ch
***************************************************************************
* *
* 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 "globe_plugin.h"
#include "qgsglobeplugindialog.h"
#include "qgsglobefeatureidentify.h"
#include "qgsglobefrustumhighlight.h"
#include "qgsglobetilesource.h"
#include "qgsglobevectorlayerproperties.h"
#include "qgsglobewidget.h"
#include "featuresource/qgsglobefeatureoptions.h"
#include <qgisinterface.h>
#include <qgslogger.h>
#include <qgsapplication.h>
#include <qgsmapcanvas.h>
#include <qgsvectorlayer.h>
#include <qgsfeature.h>
#include <qgsgeometry.h>
#include <qgspoint.h>
#include <qgsdistancearea.h>
#include <symbology/qgsrenderer.h>
#include <symbology/qgssymbol.h>
#include <qgspallabeling.h>
#include <qgssettings.h>
#include <qgsvectorlayerlabeling.h>
#include <qgsproject.h>
#include <QAction>
#include <QDir>
#include <QDockWidget>
#include <QStringList>
#include <osg/Light>
#include <osgDB/ReadFile>
#include <osgDB/Registry>
#include <osgGA/StateSetManipulator>
#include <osgGA/GUIEventHandler>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgEarthQt/ViewerWidget>
#include <osgEarth/ElevationQuery>
#include <osgEarth/Notify>
#include <osgEarth/Map>
#include <osgEarth/MapNode>
#include <osgEarth/Registry>
#if OSGEARTH_VERSION_GREATER_OR_EQUAL(2, 8, 0)
#include <osgEarth/TerrainEngineNode>
#endif
#include <osgEarth/TileSource>
#include <osgEarth/Version>
#include <osgEarthDrivers/engine_mp/MPTerrainEngineOptions>
#include <osgEarthUtil/Controls>
#include <osgEarthUtil/EarthManipulator>
#if OSGEARTH_VERSION_LESS_THAN( 2, 6, 0 )
#include <osgEarthUtil/SkyNode>
#else
#include <osgEarthUtil/Sky>
#endif
#include <osgEarthUtil/AutoClipPlaneHandler>
#include <osgEarthDrivers/gdal/GDALOptions>
#include <osgEarthDrivers/tms/TMSOptions>
#include <osgEarthDrivers/wms/WMSOptions>
#if OSGEARTH_VERSION_GREATER_OR_EQUAL( 2, 2, 0 )
#include <osgEarthDrivers/cache_filesystem/FileSystemCache>
#endif
#if OSGEARTH_VERSION_GREATER_OR_EQUAL( 2, 5, 0 )
#include <osgEarthUtil/VerticalScale>
#endif
#include <osgEarthDrivers/model_feature_geom/FeatureGeomModelOptions>
#include <osgEarthUtil/FeatureQueryTool>
#include <osgEarthFeatures/FeatureDisplayLayout>
#define MOVE_OFFSET 0.05
static const QString sName = QObject::tr( "Globe" );
static const QString sDescription = QObject::tr( "Overlay data on a 3D globe" );
static const QString sCategory = QObject::tr( "Plugins" );
static const QString sPluginVersion = QObject::tr( "Version 1.0" );
static const QgisPlugin::PluginType sPluginType = QgisPlugin::UI;
static const QString sIcon = ":/globe/icon.svg";
static const QString sExperimental = QString( "false" );
class NavigationControlHandler : public osgEarth::Util::Controls::ControlEventHandler
{
public:
virtual void onMouseDown() { }
virtual void onClick( const osgGA::GUIEventAdapter & /*ea*/, osgGA::GUIActionAdapter & /*aa*/ ) {}
};
class ZoomControlHandler : public NavigationControlHandler
{
public:
ZoomControlHandler( osgEarth::Util::EarthManipulator *manip, double dx, double dy )
: _manip( manip ), _dx( dx ), _dy( dy ) { }
void onMouseDown() override
{
_manip->zoom( _dx, _dy );
}
private:
osg::observer_ptr<osgEarth::Util::EarthManipulator> _manip;
double _dx;
double _dy;
};
class HomeControlHandler : public NavigationControlHandler
{
public:
HomeControlHandler( osgEarth::Util::EarthManipulator *manip ) : _manip( manip ) { }
void onClick( const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa ) override
{
_manip->home( ea, aa );
}
private:
osg::observer_ptr<osgEarth::Util::EarthManipulator> _manip;
};
class SyncExtentControlHandler : public NavigationControlHandler
{
public:
SyncExtentControlHandler( GlobePlugin *globe ) : mGlobe( globe ) { }
void onClick( const osgGA::GUIEventAdapter & /*ea*/, osgGA::GUIActionAdapter & /*aa*/ ) override
{
mGlobe->syncExtent();
}
private:
GlobePlugin *mGlobe = nullptr;
};
class PanControlHandler : public NavigationControlHandler
{
public:
PanControlHandler( osgEarth::Util::EarthManipulator *manip, double dx, double dy ) : _manip( manip ), _dx( dx ), _dy( dy ) { }
void onMouseDown() override
{
_manip->pan( _dx, _dy );
}
private:
osg::observer_ptr<osgEarth::Util::EarthManipulator> _manip;
double _dx;
double _dy;
};
class RotateControlHandler : public NavigationControlHandler
{
public:
RotateControlHandler( osgEarth::Util::EarthManipulator *manip, double dx, double dy ) : _manip( manip ), _dx( dx ), _dy( dy ) { }
void onMouseDown() override
{
if ( 0 == _dx && 0 == _dy )
_manip->setRotation( osg::Quat() );
else
_manip->rotate( _dx, _dy );
}
private:
osg::observer_ptr<osgEarth::Util::EarthManipulator> _manip;
double _dx;
double _dy;
};
// An event handler that will print out the coordinates at the clicked point
class QueryCoordinatesHandler : public osgGA::GUIEventHandler
{
public:
QueryCoordinatesHandler( GlobePlugin *globe ) : mGlobe( globe ) { }
bool handle( const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa )
{
if ( ea.getEventType() == osgGA::GUIEventAdapter::MOVE )
{
osgViewer::View *view = static_cast<osgViewer::View *>( aa.asView() );
osgUtil::LineSegmentIntersector::Intersections hits;
if ( view->computeIntersections( ea.getX(), ea.getY(), hits ) )
{
osgEarth::GeoPoint isectPoint;
isectPoint.fromWorld( mGlobe->mapNode()->getMapSRS()->getGeodeticSRS(), hits.begin()->getWorldIntersectPoint() );
mGlobe->showCurrentCoordinates( isectPoint );
}
}
return false;
}
private:
GlobePlugin *mGlobe = nullptr;
};
class KeyboardControlHandler : public osgGA::GUIEventHandler
{
public:
KeyboardControlHandler( osgEarth::Util::EarthManipulator *manip ) : _manip( manip ) { }
bool handle( const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa ) override;
private:
osg::observer_ptr<osgEarth::Util::EarthManipulator> _manip;
};
class NavigationControl : public osgEarth::Util::Controls::ImageControl
{
public:
NavigationControl( osg::Image *image = 0 ) : ImageControl( image ), mMousePressed( false ) {}
protected:
bool handle( const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa, osgEarth::Util::Controls::ControlContext &cx ) override;
private:
bool mMousePressed;
};
GlobePlugin::GlobePlugin( QgisInterface *qgisInterface )
: QgisPlugin( sName, sDescription, sCategory, sPluginVersion, sPluginType )
, mQGisIface( qgisInterface )
, mViewerWidget( 0 )
, mDockWidget( 0 )
, mSettingsDialog( 0 )
, mSelectedLat( 0. )
, mSelectedLon( 0. )
, mSelectedElevation( 0. )
, mLayerPropertiesFactory( 0 )
{
#ifdef Q_OS_MACX
// update path to osg plugins on Mac OS X
if ( !getenv( "OSG_LIBRARY_PATH" ) )
{
// OSG_PLUGINS_PATH value set by CMake option
QString ogsPlugins( OSG_PLUGINS_PATH );
QString bundlePlugins = QgsApplication::pluginPath() + "/../osgPlugins";
if ( QFile::exists( bundlePlugins ) )
{
// add internal osg plugin path if bundled osg
ogsPlugins = bundlePlugins;
}
if ( QFile::exists( ogsPlugins ) )
{
osgDB::Registry::instance()->setLibraryFilePathList( QDir::cleanPath( ogsPlugins ).toStdString() );
}
}
#endif
}
GlobePlugin::~GlobePlugin() {}
void GlobePlugin::initGui()
{
mSettingsDialog = new QgsGlobePluginDialog( mQGisIface->mainWindow(), QgsGuiUtils::ModalDialogFlags );
connect( mSettingsDialog, SIGNAL( settingsApplied() ), this, SLOT( applySettings() ) );
mActionToggleGlobe = new QAction( QIcon( ":/globe/globe.png" ), tr( "Launch Globe" ), this );
mActionToggleGlobe->setCheckable( true );
mQGisIface->addToolBarIcon( mActionToggleGlobe );
mQGisIface->addPluginToMenu( tr( "&Globe" ), mActionToggleGlobe );
mLayerPropertiesFactory = new QgsGlobeLayerPropertiesFactory( this );
mQGisIface->registerMapLayerConfigWidgetFactory( mLayerPropertiesFactory );
connect( mActionToggleGlobe, SIGNAL( triggered( bool ) ), this, SLOT( setGlobeEnabled( bool ) ) );
connect( mLayerPropertiesFactory, SIGNAL( layerSettingsChanged( QgsMapLayer * ) ), this, SLOT( layerChanged( QgsMapLayer * ) ) );
connect( this, SIGNAL( xyCoordinates( const QgsPointXY & ) ), mQGisIface->mapCanvas(), SIGNAL( xyCoordinates( const QgsPointXY & ) ) );
connect( mQGisIface->mainWindow(), SIGNAL( projectRead() ), this, SLOT( projectRead() ) );
}
void GlobePlugin::run()
{
if ( mViewerWidget != 0 )
{
return;
}
#ifdef GLOBE_SHOW_TILE_STATS
QgsGlobeTileStatistics *tileStats = new QgsGlobeTileStatistics();
connect( tileStats, SIGNAL( changed( int, int ) ), this, SLOT( updateTileStats( int, int ) ) );
#endif
QgsSettings settings;
// osgEarth::setNotifyLevel( osg::DEBUG_INFO );
mOsgViewer = new osgViewer::Viewer();
mOsgViewer->setThreadingModel( osgViewer::Viewer::SingleThreaded );
mOsgViewer->setRunFrameScheme( osgViewer::Viewer::ON_DEMAND );
// Set camera manipulator with default home position
osgEarth::Util::EarthManipulator *manip = new osgEarth::Util::EarthManipulator();
mOsgViewer->setCameraManipulator( manip );
osgEarth::Util::Viewpoint viewpoint;
viewpoint.focalPoint() = osgEarth::GeoPoint( osgEarth::SpatialReference::get( "wgs84" ), 0., 0., 0. );
viewpoint.heading() = 0.;
viewpoint.pitch() = -90.;
viewpoint.range() = 2e7;
manip->setHomeViewpoint( viewpoint, 1. );
manip->home( 0 );
setupProxy();
// Tile stats label
mStatsLabel = new osgEarth::Util::Controls::LabelControl( "", 10 );
mStatsLabel->setPosition( 0, 0 );
osgEarth::Util::Controls::ControlCanvas::get( mOsgViewer )->addControl( mStatsLabel.get() );
mDockWidget = new QgsGlobeWidget( mQGisIface, mQGisIface->mainWindow() );
connect( mDockWidget, SIGNAL( destroyed( QObject * ) ), this, SLOT( reset() ) );
connect( mDockWidget, SIGNAL( layersChanged() ), this, SLOT( updateLayers() ) );
connect( mDockWidget, SIGNAL( showSettings() ), this, SLOT( showSettings() ) );
connect( mDockWidget, SIGNAL( refresh() ), this, SLOT( rebuildQGISLayer() ) );
connect( mDockWidget, SIGNAL( syncExtent() ), this, SLOT( syncExtent() ) );
mQGisIface->addDockWidget( Qt::RightDockWidgetArea, mDockWidget );
if ( getenv( "GLOBE_MAPXML" ) )
{
char *mapxml = getenv( "GLOBE_MAPXML" );
QgsDebugMsg( mapxml );
osg::Node *node = osgDB::readNodeFile( mapxml );
if ( !node )
{
QgsDebugMsg( "Failed to load earth file " );
return;
}
mMapNode = osgEarth::MapNode::findMapNode( node );
mRootNode = new osg::Group();
mRootNode->addChild( node );
}
else
{
QString cacheDirectory = settings.value( "cache/directory" ).toString();
if ( cacheDirectory.isEmpty() )
cacheDirectory = QgsApplication::qgisSettingsDirPath() + "cache";
osgEarth::Drivers::FileSystemCacheOptions cacheOptions;
cacheOptions.rootPath() = cacheDirectory.toStdString();
osgEarth::MapOptions mapOptions;
mapOptions.cache() = cacheOptions;
osgEarth::Map *map = new osgEarth::Map( /*mapOptions*/ );
// The MapNode will render the Map object in the scene graph.
osgEarth::MapNodeOptions mapNodeOptions;
mMapNode = new osgEarth::MapNode( map, mapNodeOptions );
mRootNode = new osg::Group();
mRootNode->addChild( mMapNode );
osgEarth::Registry::instance()->unRefImageDataAfterApply() = false;
// Add draped layer
osgEarth::TileSourceOptions opts;
opts.L2CacheSize() = 0;
#if OSGEARTH_VERSION_LESS_THAN( 2, 9, 0 )
opts.tileSize() = 128;
#endif
mTileSource = new QgsGlobeTileSource( mQGisIface->mapCanvas(), opts );
#if OSGEARTH_VERSION_GREATER_OR_EQUAL( 2, 9, 0 )
mTileSource->open();
#endif
osgEarth::ImageLayerOptions options( "QGIS" );
options.driver()->L2CacheSize() = 0;
#if OSGEARTH_VERSION_GREATER_OR_EQUAL( 2, 9, 0 )
options.tileSize() = 128;
#endif
options.cachePolicy() = osgEarth::CachePolicy::USAGE_NO_CACHE;
mQgisMapLayer = new osgEarth::ImageLayer( options, mTileSource );
map->addImageLayer( mQgisMapLayer );
// Create the frustum highlight callback
mFrustumHighlightCallback = new QgsGlobeFrustumHighlightCallback(
mOsgViewer, mMapNode->getTerrain(), mQGisIface->mapCanvas(), QColor( 0, 0, 0, 50 ) );
}
mRootNode->addChild( osgEarth::Util::Controls::ControlCanvas::get( mOsgViewer ) );
mOsgViewer->setSceneData( mRootNode );
mOsgViewer->addEventHandler( new QueryCoordinatesHandler( this ) );
mOsgViewer->addEventHandler( new KeyboardControlHandler( manip ) );
mOsgViewer->addEventHandler( new osgViewer::StatsHandler() );
mOsgViewer->addEventHandler( new osgViewer::WindowSizeHandler() );
mOsgViewer->addEventHandler( new osgGA::StateSetManipulator( mOsgViewer->getCamera()->getOrCreateStateSet() ) );
mOsgViewer->getCamera()->addCullCallback( new osgEarth::Util::AutoClipPlaneCullCallback( mMapNode ) );
// osgEarth benefits from pre-compilation of GL objects in the pager. In newer versions of
// OSG, this activates OSG's IncrementalCompileOpeartion in order to avoid frame breaks.
mOsgViewer->getDatabasePager()->setDoPreCompile( true );
mViewerWidget = new osgEarth::QtGui::ViewerWidget( mOsgViewer );
QGLFormat glf = QGLFormat::defaultFormat();
#if OSGEARTH_VERSION_GREATER_OR_EQUAL( 2, 9, 0 )
glf.setVersion( 3, 3 );
glf.setProfile( QGLFormat::CoreProfile );
#endif
if ( settings.value( "/Plugin-Globe/anti-aliasing", true ).toBool() &&
settings.value( "/Plugin-Globe/anti-aliasing-level", "" ).toInt() > 0 )
{
glf.setSampleBuffers( true );
glf.setSamples( settings.value( "/Plugin-Globe/anti-aliasing-level", "" ).toInt() );
}
mViewerWidget->setFormat( glf );
mDockWidget->setWidget( mViewerWidget );
mViewerWidget->setParent( mDockWidget );
mFeatureQueryToolIdentifyCb = new QgsGlobeFeatureIdentifyCallback( mQGisIface->mapCanvas() );
mFeatureQueryTool = new osgEarth::Util::FeatureQueryTool();
mFeatureQueryTool->addChild( mMapNode );
mFeatureQueryTool->setDefaultCallback( mFeatureQueryToolIdentifyCb.get() );
setupControls();
// FIXME: Workaround for OpenGL errors, in some manner related to the SkyNode,
// which appear when launching the globe a second time:
// Delay applySettings one event loop iteration, i.e. one update call of the GL canvas
QTimer *timer = new QTimer();
QTimer *timer2 = new QTimer();
connect( timer, SIGNAL( timeout() ), timer, SLOT( deleteLater() ) );
connect( timer2, SIGNAL( timeout() ), timer2, SLOT( deleteLater() ) );
connect( timer, SIGNAL( timeout() ), this, SLOT( applySettings() ) );
connect( timer2, SIGNAL( timeout() ), this, SLOT( updateLayers() ) );
timer->start( 0 );
timer2->start( 100 );
}
void GlobePlugin::showSettings()
{
mSettingsDialog->exec();
}
void GlobePlugin::projectRead()
{
setGlobeEnabled( false ); // Hide globe when new projects loaded, on some systems it is very slow loading a new project with globe enabled
mSettingsDialog->readProjectSettings();
applyProjectSettings();
}
void GlobePlugin::applySettings()
{
if ( !mOsgViewer )
{
return;
}
osgEarth::Util::EarthManipulator *manip = dynamic_cast<osgEarth::Util::EarthManipulator *>( mOsgViewer->getCameraManipulator() );
osgEarth::Util::EarthManipulator::Settings *settings = manip->getSettings();
settings->setScrollSensitivity( mSettingsDialog->getScrollSensitivity() );
if ( !mSettingsDialog->getInvertScrollWheel() )
{
settings->bindScroll( osgEarth::Util::EarthManipulator::ACTION_ZOOM_IN, osgGA::GUIEventAdapter::SCROLL_UP );
settings->bindScroll( osgEarth::Util::EarthManipulator::ACTION_ZOOM_OUT, osgGA::GUIEventAdapter::SCROLL_DOWN );
}
else
{
settings->bindScroll( osgEarth::Util::EarthManipulator::ACTION_ZOOM_OUT, osgGA::GUIEventAdapter::SCROLL_UP );
settings->bindScroll( osgEarth::Util::EarthManipulator::ACTION_ZOOM_IN, osgGA::GUIEventAdapter::SCROLL_DOWN );
}
// Advanced settings
enableFrustumHighlight( mSettingsDialog->getFrustumHighlighting() );
enableFeatureIdentification( mSettingsDialog->getFeatureIdenification() );
applyProjectSettings();
}
void GlobePlugin::applyProjectSettings()
{
if ( mOsgViewer && !getenv( "GLOBE_MAPXML" ) )
{
// Imagery settings
QList<QgsGlobePluginDialog::LayerDataSource> imageryDataSources = mSettingsDialog->getImageryDataSources();
if ( imageryDataSources != mImagerySources )
{
mImagerySources = imageryDataSources;
QgsDebugMsg( "imageryLayersChanged: Globe Running, executing" );
osg::ref_ptr<osgEarth::Map> map = mMapNode->getMap();
// Remove image layers
osgEarth::ImageLayerVector list;
#if OSGEARTH_VERSION_GREATER_OR_EQUAL( 2, 9, 0 )
map->getLayers( list );
#else
map->getImageLayers( list );
#endif
for ( osgEarth::ImageLayerVector::iterator i = list.begin(); i != list.end(); ++i )
{
if ( *i != mQgisMapLayer )
map->removeImageLayer( *i );
}
if ( !list.empty() )
{
mOsgViewer->getDatabasePager()->clear();
}
// Add image layers
for ( const QgsGlobePluginDialog::LayerDataSource &datasource : mImagerySources )
{
osgEarth::ImageLayer *layer = 0;
if ( "Raster" == datasource.type )
{
osgEarth::Drivers::GDALOptions options;
options.url() = datasource.uri.toStdString();
layer = new osgEarth::ImageLayer( datasource.uri.toStdString(), options );
}
else if ( "TMS" == datasource.type )
{
osgEarth::Drivers::TMSOptions options;
options.url() = datasource.uri.toStdString();
layer = new osgEarth::ImageLayer( datasource.uri.toStdString(), options );
}
else if ( "WMS" == datasource.type )
{
osgEarth::Drivers::WMSOptions options;
options.url() = datasource.uri.toStdString();
layer = new osgEarth::ImageLayer( datasource.uri.toStdString(), options );
}
map->insertImageLayer( layer, 0 );
}
}
// Elevation settings
QList<QgsGlobePluginDialog::LayerDataSource> elevationDataSources = mSettingsDialog->getElevationDataSources();
if ( elevationDataSources != mElevationSources )
{
mElevationSources = elevationDataSources;
QgsDebugMsg( "elevationLayersChanged: Globe Running, executing" );
osg::ref_ptr<osgEarth::Map> map = mMapNode->getMap();
// Remove elevation layers
osgEarth::ElevationLayerVector list;
#if OSGEARTH_VERSION_GREATER_OR_EQUAL( 2, 9, 0 )
map->getLayers( list );
#else
map->getElevationLayers( list );
#endif
for ( osgEarth::ElevationLayerVector::iterator i = list.begin(); i != list.end(); ++i )
{
map->removeElevationLayer( *i );
}
if ( !list.empty() )
{
mOsgViewer->getDatabasePager()->clear();
}
// Add elevation layers
for ( const QgsGlobePluginDialog::LayerDataSource &datasource : mElevationSources )
{
osgEarth::ElevationLayer *layer = 0;
if ( "Raster" == datasource.type )
{
osgEarth::Drivers::GDALOptions options;
options.interpolation() = osgEarth::Drivers::INTERP_NEAREST;
options.url() = datasource.uri.toStdString();
layer = new osgEarth::ElevationLayer( datasource.uri.toStdString(), options );
}
else if ( "TMS" == datasource.type )
{
osgEarth::Drivers::TMSOptions options;
options.url() = datasource.uri.toStdString();
layer = new osgEarth::ElevationLayer( datasource.uri.toStdString(), options );
}
map->addElevationLayer( layer );
}
}
#if OSGEARTH_VERSION_GREATER_OR_EQUAL( 2, 5, 0 )
double verticalScaleValue = mSettingsDialog->getVerticalScale();
if ( !mVerticalScale.get() || mVerticalScale->getScale() != verticalScaleValue )
{
mMapNode->getTerrainEngine()->removeEffect( mVerticalScale );
mVerticalScale = new osgEarth::Util::VerticalScale();
mVerticalScale->setScale( verticalScaleValue );
mMapNode->getTerrainEngine()->addEffect( mVerticalScale );
}
#endif
// Sky settings
if ( mSettingsDialog->getSkyEnabled() )
{
// Create if not yet done
if ( !mSkyNode.get() )
{
mSkyNode = osgEarth::Util::SkyNode::create( mMapNode );
mSkyNode->attach( mOsgViewer );
mRootNode->addChild( mSkyNode );
// Insert sky between root and map
mSkyNode->addChild( mMapNode );
mRootNode->removeChild( mMapNode );
}
mSkyNode->setLighting( mSettingsDialog->getSkyAutoAmbience() ? osg::StateAttribute::ON : osg::StateAttribute::OFF );
double ambient = mSettingsDialog->getSkyMinAmbient();
mSkyNode->getSunLight()->setAmbient( osg::Vec4( ambient, ambient, ambient, 1 ) );
QDateTime dateTime = mSettingsDialog->getSkyDateTime();
mSkyNode->setDateTime( osgEarth::DateTime(
dateTime.date().year(),
dateTime.date().month(),
dateTime.date().day(),
dateTime.time().hour() + dateTime.time().minute() / 60.0 ) );
}
else if ( mSkyNode != 0 )
{
mRootNode->addChild( mMapNode );
mSkyNode->removeChild( mMapNode );
mRootNode->removeChild( mSkyNode );
mSkyNode = 0;
}
}
}
QgsRectangle GlobePlugin::getQGISLayerExtent() const
{
QList<QgsRectangle> extents = mLayerExtents.values();
QgsRectangle fullExtent = extents.isEmpty() ? QgsRectangle() : extents.front();
for ( int i = 1, n = extents.size(); i < n; ++i )
{
if ( !extents[i].isNull() )
fullExtent.combineExtentWith( extents[i] );
}
return fullExtent;
}
void GlobePlugin::showCurrentCoordinates( const osgEarth::GeoPoint &geoPoint )
{
osg::Vec3d pos = geoPoint.vec3d();
emit xyCoordinates( QgsCoordinateTransform( QgsCoordinateReferenceSystem( GEO_EPSG_CRS_AUTHID ), mQGisIface->mapCanvas()->mapSettings().destinationCrs(), QgsProject::instance()->transformContext() ).transform( QgsPointXY( pos.x(), pos.y() ) ) );
}
void GlobePlugin::setSelectedCoordinates( const osg::Vec3d &coords )
{
mSelectedLon = coords.x();
mSelectedLat = coords.y();
mSelectedElevation = coords.z();
emit newCoordinatesSelected( QgsPointXY( mSelectedLon, mSelectedLat ) );
}
osg::Vec3d GlobePlugin::getSelectedCoordinates()
{
return osg::Vec3d( mSelectedLon, mSelectedLat, mSelectedElevation );
}
void GlobePlugin::syncExtent()
{
const QgsMapSettings &mapSettings = mQGisIface->mapCanvas()->mapSettings();
QgsRectangle extent = mQGisIface->mapCanvas()->extent();
long epsgGlobe = 4326;
QgsCoordinateReferenceSystem globeCrs;
globeCrs.createFromOgcWmsCrs( QString( "EPSG:%1" ).arg( epsgGlobe ) );
// transform extent to WGS84
if ( mapSettings.destinationCrs().authid().compare( QString( "EPSG:%1" ).arg( epsgGlobe ), Qt::CaseInsensitive ) != 0 )
{
QgsCoordinateReferenceSystem srcCRS( mapSettings.destinationCrs() );
extent = QgsCoordinateTransform( srcCRS, globeCrs, QgsProject::instance()->transformContext() ).transformBoundingBox( extent );
}
QgsDistanceArea dist;
dist.setSourceCrs( globeCrs, QgsProject::instance()->transformContext() );
dist.setEllipsoid( "WGS84" );
QgsPointXY ll = QgsPointXY( extent.xMinimum(), extent.yMinimum() );
QgsPointXY ul = QgsPointXY( extent.xMinimum(), extent.yMaximum() );
double height = dist.measureLine( ll, ul );
// double height = dist.computeDistanceBearing( ll, ul );
double camViewAngle = 30;
double camDistance = height / tan( camViewAngle * osg::PI / 180 ); //c = b*cotan(B(rad))
#if OSGEARTH_VERSION_LESS_THAN(2, 7, 0)
osgEarth::Util::Viewpoint viewpoint( osg::Vec3d( extent.center().x(), extent.center().y(), 0.0 ), 0.0, -90.0, camDistance );
#else
osgEarth::Util::Viewpoint viewpoint;
viewpoint.focalPoint() = osgEarth::GeoPoint( osgEarth::SpatialReference::get( "wgs84" ), extent.center().x(), extent.center().y(), 0.0 );
viewpoint.heading() = 0.0;
viewpoint.pitch() = -90.0;
viewpoint.range() = camDistance;
#endif
OE_NOTICE << "map extent: " << height << " camera distance: " << camDistance << std::endl;
osgEarth::Util::EarthManipulator *manip = dynamic_cast<osgEarth::Util::EarthManipulator *>( mOsgViewer->getCameraManipulator() );
manip->setRotation( osg::Quat() );
manip->setViewpoint( viewpoint, 4.0 );
}
void GlobePlugin::addControl( osgEarth::Util::Controls::Control *control, int x, int y, int w, int h, osgEarth::Util::Controls::ControlEventHandler *handler )
{
control->setPosition( x, y );
control->setHeight( h );
control->setWidth( w );
control->addEventHandler( handler );
osgEarth::Util::Controls::ControlCanvas::get( mOsgViewer )->addControl( control );
}
void GlobePlugin::addImageControl( const std::string &imgPath, int x, int y, osgEarth::Util::Controls::ControlEventHandler *handler )
{
osg::Image *image = osgDB::readImageFile( imgPath );
osgEarth::Util::Controls::ImageControl *control = new NavigationControl( image );
control->setPosition( x, y );
control->setWidth( image->s() );
control->setHeight( image->t() );
if ( handler )
control->addEventHandler( handler );
osgEarth::Util::Controls::ControlCanvas::get( mOsgViewer )->addControl( control );
}
void GlobePlugin::setupControls()
{
std::string imgDir = QDir::cleanPath( QgsApplication::pkgDataPath() + "/globe/gui" ).toStdString();
if ( QgsApplication::isRunningFromBuildDir() )
{
imgDir = QDir::cleanPath( QgsApplication::buildSourcePath() + "/src/plugins/globe/images/gui" ).toStdString();
}
osgEarth::Util::EarthManipulator *manip = dynamic_cast<osgEarth::Util::EarthManipulator *>( mOsgViewer->getCameraManipulator() );
// Rotate and tiltcontrols
int imgLeft = 16;
int imgTop = 20;
addImageControl( imgDir + "/YawPitchWheel.png", 16, 20 );
addControl( new NavigationControl, imgLeft, imgTop + 18, 20, 22, new RotateControlHandler( manip, -MOVE_OFFSET, 0 ) );
addControl( new NavigationControl, imgLeft + 36, imgTop + 18, 20, 22, new RotateControlHandler( manip, MOVE_OFFSET, 0 ) );
addControl( new NavigationControl, imgLeft + 20, imgTop + 18, 16, 22, new RotateControlHandler( manip, 0, 0 ) );
addControl( new NavigationControl, imgLeft + 20, imgTop, 24, 19, new RotateControlHandler( manip, 0, -MOVE_OFFSET ) );
addControl( new NavigationControl, imgLeft + 16, imgTop + 36, 24, 19, new RotateControlHandler( manip, 0, MOVE_OFFSET ) );
// Move controls
imgTop = 80;
addImageControl( imgDir + "/MoveWheel.png", imgLeft, imgTop );
addControl( new NavigationControl, imgLeft, imgTop + 18, 20, 22, new PanControlHandler( manip, MOVE_OFFSET, 0 ) );
addControl( new NavigationControl, imgLeft + 36, imgTop + 18, 20, 22, new PanControlHandler( manip, -MOVE_OFFSET, 0 ) );
addControl( new NavigationControl, imgLeft + 20, imgTop, 24, 19, new PanControlHandler( manip, 0, -MOVE_OFFSET ) );
addControl( new NavigationControl, imgLeft + 16, imgTop + 36, 24, 19, new PanControlHandler( manip, 0, MOVE_OFFSET ) );
addControl( new NavigationControl, imgLeft + 20, imgTop + 18, 16, 22, new HomeControlHandler( manip ) );
// Zoom controls
imgLeft = 28;
imgTop = imgTop + 62;
addImageControl( imgDir + "/button-background.png", imgLeft, imgTop );
addImageControl( imgDir + "/zoom-in.png", imgLeft + 3, imgTop + 2, new ZoomControlHandler( manip, 0, -MOVE_OFFSET ) );
addImageControl( imgDir + "/zoom-out.png", imgLeft + 3, imgTop + 29, new ZoomControlHandler( manip, 0, MOVE_OFFSET ) );
}
void GlobePlugin::setupProxy()
{
QgsSettings settings;
settings.beginGroup( "proxy" );
if ( settings.value( "/proxyEnabled" ).toBool() )
{
osgEarth::ProxySettings proxySettings( settings.value( "/proxyHost" ).toString().toStdString(),
settings.value( "/proxyPort" ).toInt() );
if ( !settings.value( "/proxyUser" ).toString().isEmpty() )
{
QString auth = settings.value( "/proxyUser" ).toString() + ":" + settings.value( "/proxyPassword" ).toString();
qputenv( "OSGEARTH_CURL_PROXYAUTH", auth.toLocal8Bit() );
}
//TODO: settings.value("/proxyType")
//TODO: URL exlusions
osgEarth::HTTPClient::setProxySettings( proxySettings );
}
settings.endGroup();
}
void GlobePlugin::refreshQGISMapLayer( const QgsRectangle &dirtyRect )
{
if ( mTileSource )
{
mOsgViewer->getDatabasePager()->clear();
mTileSource->refresh( dirtyRect );
mOsgViewer->requestRedraw();
}
}
void GlobePlugin::updateTileStats( int queued, int tot )
{
if ( mStatsLabel )
mStatsLabel->setText( QString( "Queued tiles: %1\nTot tiles: %2" ).arg( queued ).arg( tot ).toStdString() );
}
void GlobePlugin::addModelLayer( QgsVectorLayer *vLayer, QgsGlobeVectorLayerConfig *layerConfig )
{
QgsGlobeFeatureOptions featureOpt;
featureOpt.setLayer( vLayer );
osgEarth::Style style;
QgsRenderContext ctx;
if ( !vLayer->renderer()->symbols( ctx ).isEmpty() )
{
for ( QgsSymbol *sym : vLayer->renderer()->symbols( ctx ) )
{
if ( sym->type() == QgsSymbol::Line )
{
osgEarth::LineSymbol *ls = style.getOrCreateSymbol<osgEarth::LineSymbol>();
QColor color = sym->color();
ls->stroke()->color() = osg::Vec4f( color.redF(), color.greenF(), color.blueF(), color.alphaF() * vLayer->opacity() );
ls->stroke()->width() = 1.0f;
}
else if ( sym->type() == QgsSymbol::Fill )
{
// TODO access border color, etc.
osgEarth::PolygonSymbol *poly = style.getOrCreateSymbol<osgEarth::PolygonSymbol>();
QColor color = sym->color();
poly->fill()->color() = osg::Vec4f( color.redF(), color.greenF(), color.blueF(), color.alphaF() * vLayer->opacity() );
style.addSymbol( poly );
}
}
}
else
{
osgEarth::PolygonSymbol *poly = style.getOrCreateSymbol<osgEarth::PolygonSymbol>();
poly->fill()->color() = osg::Vec4f( 1.f, 0, 0, vLayer->opacity() );
style.addSymbol( poly );
osgEarth::LineSymbol *ls = style.getOrCreateSymbol<osgEarth::LineSymbol>();
ls->stroke()->color() = osg::Vec4f( 1.f, 0, 0, vLayer->opacity() );
ls->stroke()->width() = 1.0f;
}
osgEarth::AltitudeSymbol *altitudeSymbol = style.getOrCreateSymbol<osgEarth::AltitudeSymbol>();
altitudeSymbol->clamping() = layerConfig->altitudeClamping;
altitudeSymbol->technique() = layerConfig->altitudeTechnique;
altitudeSymbol->binding() = layerConfig->altitudeBinding;
altitudeSymbol->verticalOffset() = layerConfig->verticalOffset;
altitudeSymbol->verticalScale() = layerConfig->verticalScale;
altitudeSymbol->clampingResolution() = layerConfig->clampingResolution;
style.addSymbol( altitudeSymbol );
if ( layerConfig->extrusionEnabled )
{
osgEarth::ExtrusionSymbol *extrusionSymbol = style.getOrCreateSymbol<osgEarth::ExtrusionSymbol>();
bool extrusionHeightOk = false;
float extrusionHeight = layerConfig->extrusionHeight.toFloat( &extrusionHeightOk );
if ( extrusionHeightOk )
{
extrusionSymbol->height() = extrusionHeight;
}
else
{
extrusionSymbol->heightExpression() = layerConfig->extrusionHeight.toStdString();
}
extrusionSymbol->flatten() = layerConfig->extrusionFlatten;
extrusionSymbol->wallGradientPercentage() = layerConfig->extrusionWallGradient;
style.addSymbol( extrusionSymbol );
}
if ( layerConfig->labelingEnabled )
{
osgEarth::TextSymbol *textSymbol = style.getOrCreateSymbol<osgEarth::TextSymbol>();
textSymbol->declutter() = layerConfig->labelingDeclutter;
QgsPalLayerSettings lyr = vLayer->labeling()->settings();
textSymbol->content() = QString( "[%1]" ).arg( lyr.fieldName ).toStdString();
textSymbol->font() = lyr.format().font().family().toStdString();
textSymbol->size() = lyr.format().font().pointSize();
textSymbol->alignment() = osgEarth::TextSymbol::ALIGN_CENTER_TOP;
osgEarth::Stroke stroke;
QColor bufferColor = lyr.format().buffer().color();
stroke.color() = osgEarth::Symbology::Color( bufferColor.redF(), bufferColor.greenF(), bufferColor.blueF(), bufferColor.alphaF() );
textSymbol->halo() = stroke;
textSymbol->haloOffset() = lyr.format().buffer().size();
}
osgEarth::RenderSymbol *renderSymbol = style.getOrCreateSymbol<osgEarth::RenderSymbol>();
renderSymbol->lighting() = layerConfig->lightingEnabled;
renderSymbol->backfaceCulling() = false;
style.addSymbol( renderSymbol );
osgEarth::Drivers::FeatureGeomModelOptions geomOpt;
geomOpt.featureOptions() = featureOpt;
geomOpt.styles() = new osgEarth::StyleSheet();
geomOpt.styles()->addStyle( style );
geomOpt.featureIndexing() = osgEarth::Features::FeatureSourceIndexOptions();
#if 0
FeatureDisplayLayout layout;
layout.tileSizeFactor() = 45.0;
layout.addLevel( FeatureLevel( 0.0f, 200000.0f ) );
geomOpt.layout() = layout;
#endif
osgEarth::ModelLayerOptions modelOptions( vLayer->id().toStdString(), geomOpt );
osgEarth::ModelLayer *nLayer = new osgEarth::ModelLayer( modelOptions );
mMapNode->getMap()->addModelLayer( nLayer );
}
void GlobePlugin::updateLayers()
{
if ( mOsgViewer )
{
// Get previous full extent
QgsRectangle dirtyExtent = getQGISLayerExtent();
mLayerExtents.clear();
QList<QgsMapLayer *> drapedLayers;
QStringList selectedLayerIds = mDockWidget->getSelectedLayerIds();
// Disconnect any previous repaintRequested signals
for ( QgsMapLayer *mapLayer : mTileSource->layers() )
{
if ( mapLayer )
disconnect( mapLayer, SIGNAL( repaintRequested() ), this, SLOT( layerChanged() ) );
if ( dynamic_cast<QgsVectorLayer *>( mapLayer ) )
disconnect( static_cast<QgsVectorLayer *>( mapLayer ), SIGNAL( layerTransparencyChanged( int ) ), this, SLOT( layerChanged() ) );
}
osgEarth::ModelLayerVector modelLayers;
#if OSGEARTH_VERSION_GREATER_OR_EQUAL( 2, 9, 0 )
mMapNode->getMap()->getLayers( modelLayers );
#else
mMapNode->getMap()->getModelLayers( modelLayers );
#endif
for ( const osg::ref_ptr<osgEarth::ModelLayer> &modelLayer : modelLayers )
{
QgsMapLayer *mapLayer = QgsProject::instance()->mapLayer( QString::fromStdString( modelLayer->getName() ) );
if ( mapLayer )
disconnect( mapLayer, SIGNAL( repaintRequested() ), this, SLOT( layerChanged() ) );
if ( dynamic_cast<QgsVectorLayer *>( mapLayer ) )
disconnect( static_cast<QgsVectorLayer *>( mapLayer ), SIGNAL( layerTransparencyChanged( int ) ), this, SLOT( layerChanged() ) );
if ( !selectedLayerIds.contains( QString::fromStdString( modelLayer->getName() ) ) )
mMapNode->getMap()->removeModelLayer( modelLayer );
}
for ( const QString &layerId : selectedLayerIds )
{
QgsMapLayer *mapLayer = QgsProject::instance()->mapLayer( layerId );
connect( mapLayer, SIGNAL( repaintRequested() ), this, SLOT( layerChanged() ) );
QgsGlobeVectorLayerConfig *layerConfig = 0;
if ( dynamic_cast<QgsVectorLayer *>( mapLayer ) )
{
layerConfig = QgsGlobeVectorLayerConfig::getConfig( static_cast<QgsVectorLayer *>( mapLayer ) );
connect( static_cast<QgsVectorLayer *>( mapLayer ), SIGNAL( layerTransparencyChanged( int ) ), this, SLOT( layerChanged() ) );
}
if ( layerConfig && ( layerConfig->renderingMode == QgsGlobeVectorLayerConfig::RenderingModeModelSimple || layerConfig->renderingMode == QgsGlobeVectorLayerConfig::RenderingModeModelAdvanced ) )
{
#if OSGEARTH_VERSION_GREATER_OR_EQUAL( 2, 9, 0 )
if ( !mMapNode->getMap()->getLayerByName( mapLayer->id().toStdString() ) )
#else
if ( !mMapNode->getMap()->getModelLayerByName( mapLayer->id().toStdString() ) )
#endif
addModelLayer( static_cast<QgsVectorLayer *>( mapLayer ), layerConfig );
}
else
{
drapedLayers.append( mapLayer );
QgsRectangle extent = QgsCoordinateTransform( mapLayer->crs(), QgsCoordinateReferenceSystem( GEO_EPSG_CRS_AUTHID ), QgsProject::instance()->transformContext() ).transform( mapLayer->extent() );
mLayerExtents.insert( mapLayer->id(), extent );
}
}
mTileSource->setLayers( drapedLayers );
QgsRectangle newExtent = getQGISLayerExtent();
if ( dirtyExtent.isNull() )
dirtyExtent = newExtent;
else if ( !newExtent.isNull() )
dirtyExtent.combineExtentWith( newExtent );
refreshQGISMapLayer( dirtyExtent );
}
}
void GlobePlugin::layerChanged( QgsMapLayer *mapLayer )
{
if ( !mapLayer )
{
mapLayer = qobject_cast<QgsMapLayer *>( QObject::sender() );
}
if ( mapLayer->isEditable() )
{
return;
}
if ( mMapNode )
{
QgsGlobeVectorLayerConfig *layerConfig = 0;
if ( dynamic_cast<QgsVectorLayer *>( mapLayer ) )
{
layerConfig = QgsGlobeVectorLayerConfig::getConfig( static_cast<QgsVectorLayer *>( mapLayer ) );
}
if ( layerConfig && ( layerConfig->renderingMode == QgsGlobeVectorLayerConfig::RenderingModeModelSimple || layerConfig->renderingMode == QgsGlobeVectorLayerConfig::RenderingModeModelAdvanced ) )
{
// If was previously a draped layer, refresh the draped layer
if ( mTileSource->layers().contains( mapLayer ) )
{
QList<QgsMapLayer *> layers = mTileSource->layers();
layers.removeAll( mapLayer );
mTileSource->setLayers( layers );
QgsRectangle dirtyExtent = mLayerExtents[mapLayer->id()];
mLayerExtents.remove( mapLayer->id() );
refreshQGISMapLayer( dirtyExtent );
}
#if OSGEARTH_VERSION_GREATER_OR_EQUAL( 2, 9, 0 )
mMapNode->getMap()->removeLayer( mMapNode->getMap()->getLayerByName( mapLayer->id().toStdString() ) );
#else
mMapNode->getMap()->removeModelLayer( mMapNode->getMap()->getModelLayerByName( mapLayer->id().toStdString() ) );
#endif
addModelLayer( static_cast<QgsVectorLayer *>( mapLayer ), layerConfig );
}
else
{
// Re-insert into layer set if necessary
if ( !mTileSource->layers().contains( mapLayer ) )
{
QList<QgsMapLayer *> layers;
for ( const QString &layerId : mDockWidget->getSelectedLayerIds() )
{
#if OSGEARTH_VERSION_GREATER_OR_EQUAL( 2, 9, 0 )
if ( ! mMapNode->getMap()->getLayerByName( layerId.toStdString() ) )
#else
if ( ! mMapNode->getMap()->getModelLayerByName( layerId.toStdString() ) )
#endif
{
QgsMapLayer *layer = QgsProject::instance()->mapLayer( layerId );
if ( layer )
{
layers.append( layer );
}
}
}
mTileSource->setLayers( layers );
QgsRectangle extent = QgsCoordinateTransform( mapLayer->crs(), QgsCoordinateReferenceSystem( GEO_EPSG_CRS_AUTHID ), QgsProject::instance()->transformContext() ).transform( mapLayer->extent() );
mLayerExtents.insert( mapLayer->id(), extent );
}
// Remove any model layer of that layer, in case one existed
#if OSGEARTH_VERSION_GREATER_OR_EQUAL( 2, 9, 0 )
mMapNode->getMap()->removeLayer( mMapNode->getMap()->getLayerByName( mapLayer->id().toStdString() ) );
#else
mMapNode->getMap()->removeModelLayer( mMapNode->getMap()->getModelLayerByName( mapLayer->id().toStdString() ) );
#endif
QgsRectangle layerExtent = QgsCoordinateTransform( mapLayer->crs(), QgsCoordinateReferenceSystem( GEO_EPSG_CRS_AUTHID ), QgsProject::instance()->transformContext() ).transform( mapLayer->extent() );
QgsRectangle dirtyExtent = layerExtent;
if ( mLayerExtents.contains( mapLayer->id() ) )
{
if ( dirtyExtent.isNull() )
dirtyExtent = mLayerExtents[mapLayer->id()];
else if ( !mLayerExtents[mapLayer->id()].isNull() )
dirtyExtent.combineExtentWith( mLayerExtents[mapLayer->id()] );
}
mLayerExtents[mapLayer->id()] = layerExtent;
refreshQGISMapLayer( dirtyExtent );
}
}
}
void GlobePlugin::rebuildQGISLayer()
{
if ( mMapNode )
{
mMapNode->getMap()->removeImageLayer( mQgisMapLayer );
mLayerExtents.clear();
osgEarth::TileSourceOptions opts;
opts.L2CacheSize() = 0;
#if OSGEARTH_VERSION_LESS_THAN( 2, 9, 0 )
opts.tileSize() = 128;
#endif
mTileSource = new QgsGlobeTileSource( mQGisIface->mapCanvas(), opts );
#if OSGEARTH_VERSION_GREATER_OR_EQUAL( 2, 9, 0 )
mTileSource->open();
#endif
osgEarth::ImageLayerOptions options( "QGIS" );
options.driver()->L2CacheSize() = 0;
#if OSGEARTH_VERSION_GREATER_OR_EQUAL( 2, 9, 0 )
options.tileSize() = 128;
#endif
options.cachePolicy() = osgEarth::CachePolicy::USAGE_NO_CACHE;
mQgisMapLayer = new osgEarth::ImageLayer( options, mTileSource );
mMapNode->getMap()->addImageLayer( mQgisMapLayer );
updateLayers();
}
}
void GlobePlugin::setGlobeEnabled( bool enabled )
{
if ( enabled )
{
run();
}
else if ( mDockWidget )
{
mDockWidget->close(); // triggers reset
}
}
void GlobePlugin::reset()
{
mStatsLabel = 0;
mActionToggleGlobe->blockSignals( true );
mActionToggleGlobe->setChecked( false );
mActionToggleGlobe->blockSignals( false );
mMapNode->getMap()->removeImageLayer( mQgisMapLayer ); // abort any rendering
mTileSource->waitForFinished();
mOsgViewer = 0;
mMapNode = 0;
mRootNode = 0;
mSkyNode = 0;
mBaseLayer = 0;
mBaseLayerUrl.clear();
mQgisMapLayer = 0;
mTileSource = 0;
mVerticalScale = 0;
mFrustumHighlightCallback = 0;
mFeatureQueryToolIdentifyCb = 0;
#if OSGEARTH_VERSION_LESS_THAN(2, 7, 0)
mFeatureQueryToolHighlightCb = 0;
#endif
mFeatureQueryTool = 0;
mViewerWidget = 0;
mDockWidget = 0;
mImagerySources.clear();
mElevationSources.clear();
mLayerExtents.clear();
#ifdef GLOBE_SHOW_TILE_STATS
disconnect( QgsGlobeTileStatistics::instance(), SIGNAL( changed( int, int ) ), this, SLOT( updateTileStats( int, int ) ) );
delete QgsGlobeTileStatistics::instance();
#endif
}
void GlobePlugin::unload()
{
if ( mDockWidget )
{
disconnect( mDockWidget, SIGNAL( destroyed( QObject * ) ), this, SLOT( reset() ) );
delete mDockWidget;
reset();
}
mQGisIface->removePluginMenu( tr( "&Globe" ), mActionToggleGlobe );
mQGisIface->removeToolBarIcon( mActionToggleGlobe );
mQGisIface->unregisterMapLayerConfigWidgetFactory( mLayerPropertiesFactory );
delete mLayerPropertiesFactory;
mLayerPropertiesFactory = 0;
delete mSettingsDialog;
mSettingsDialog = 0;
disconnect( this, SIGNAL( xyCoordinates( const QgsPointXY & ) ),
mQGisIface->mapCanvas(), SIGNAL( xyCoordinates( const QgsPointXY & ) ) );
}
void GlobePlugin::enableFrustumHighlight( bool status )
{
if ( status )
mMapNode->getTerrainEngine()->addUpdateCallback( mFrustumHighlightCallback );
else
mMapNode->getTerrainEngine()->removeUpdateCallback( mFrustumHighlightCallback );
}
void GlobePlugin::enableFeatureIdentification( bool status )
{
if ( status )
mOsgViewer->addEventHandler( mFeatureQueryTool );
else
mOsgViewer->removeEventHandler( mFeatureQueryTool );
}
bool NavigationControl::handle( const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa, osgEarth::Util::Controls::ControlContext &cx )
{
if ( ea.getEventType() == osgGA::GUIEventAdapter::PUSH )
{
mMousePressed = true;
}
else if ( ea.getEventType() == osgGA::GUIEventAdapter::FRAME && mMousePressed )
{
float canvasY = cx._vp->height() - ( ea.getY() - cx._view->getCamera()->getViewport()->y() );
float canvasX = ea.getX() - cx._view->getCamera()->getViewport()->x();
if ( intersects( canvasX, canvasY ) )
{
for ( osgEarth::Util::Controls::ControlEventHandlerList::const_iterator i = _eventHandlers.begin(); i != _eventHandlers.end(); ++i )
{
NavigationControlHandler *handler = dynamic_cast<NavigationControlHandler *>( i->get() );
if ( handler )
{
handler->onMouseDown();
}
}
}
else
{
mMousePressed = false;
}
}
else if ( ea.getEventType() == osgGA::GUIEventAdapter::RELEASE )
{
for ( osgEarth::Util::Controls::ControlEventHandlerList::const_iterator i = _eventHandlers.begin(); i != _eventHandlers.end(); ++i )
{
NavigationControlHandler *handler = dynamic_cast<NavigationControlHandler *>( i->get() );
if ( handler )
{
handler->onClick( ea, aa );
}
}
mMousePressed = false;
}
return Control::handle( ea, aa, cx );
}
bool KeyboardControlHandler::handle( const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa )
{
if ( ea.getEventType() == osgGA::GUIEventAdapter::KEYDOWN )
{
//move map
if ( ea.getKey() == '4' )
_manip->pan( -MOVE_OFFSET, 0 );
else if ( ea.getKey() == '6' )
_manip->pan( MOVE_OFFSET, 0 );
else if ( ea.getKey() == '2' )
_manip->pan( 0, MOVE_OFFSET );
else if ( ea.getKey() == '8' )
_manip->pan( 0, -MOVE_OFFSET );
//rotate
else if ( ea.getKey() == '/' )
_manip->rotate( MOVE_OFFSET, 0 );
else if ( ea.getKey() == '*' )
_manip->rotate( -MOVE_OFFSET, 0 );
//tilt
else if ( ea.getKey() == '9' )
_manip->rotate( 0, MOVE_OFFSET );
else if ( ea.getKey() == '3' )
_manip->rotate( 0, -MOVE_OFFSET );
//zoom
else if ( ea.getKey() == '-' )
_manip->zoom( 0, MOVE_OFFSET );
else if ( ea.getKey() == '+' )
_manip->zoom( 0, -MOVE_OFFSET );
//reset
else if ( ea.getKey() == '5' )
_manip->home( ea, aa );
}
return false;
}
/**
* Required extern functions needed for every plugin
* These functions can be called prior to creating an instance
* of the plugin class
*/
// Class factory to return a new instance of the plugin class
QGISEXTERN QgisPlugin *classFactory( QgisInterface *qgisInterfacePointer )
{
return new GlobePlugin( qgisInterfacePointer );
}
// Return the name of the plugin - note that we do not user class members as
// the class may not yet be insantiated when this method is called.
QGISEXTERN QString name()
{
return sName;
}
// Return the description
QGISEXTERN QString description()
{
return sDescription;
}
// Return the category
QGISEXTERN QString category()
{
return sCategory;
}
// Return the type (either UI or MapLayer plugin)
QGISEXTERN int type()
{
return sPluginType;
}
// Return the version number for the plugin
QGISEXTERN QString version()
{
return sPluginVersion;
}
// Return the icon
QGISEXTERN QString icon()
{
return sIcon;
}
// Return the experimental status for the plugin
QGISEXTERN QString experimental()
{
return sExperimental;
}
// Delete ourself
QGISEXTERN void unload( QgisPlugin *pluginPointer )
{
delete pluginPointer;
}
| dgoedkoop/QGIS | src/plugins/globe/globe_plugin.cpp | C++ | gpl-2.0 | 47,694 |
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <sys/stat.h>
#include "Constants.h"
#include "Converting.cpp"
#include "ProcessVideoRecording.cpp"
#include "ProcessScreenRecording.cpp"
using namespace std;
static void show_usage(string name)
{
cerr << "Usage: " << name << " Options:\n"
<< "\t--input <filepath> \t The filepath to the folder where the video files and settings are located\n"
<< "\t--output <foldername> \t The folder name for the output (will be created inside the input folder) \n"
<< "\t--eyealg <algorithm>\t The algorithm that is used for detecting the eye center. Possible Values: grad, isoph, comb \n"
<< "\t--gazealg <algorithm>\t The algorithm that is used for detecting the gaze. Possible Values: approx, geo \n"
<< "\t--fastwidth \t The window size of the scaled window that is used for detecting the eye center. (optional) Default: 50 for grad, 80 for isoph algo\n"
<< "\t--convertfps \t Indicates that we want to convert FPS (optional) Default: off\n"
<< "\t--drawonvideo \t Indicates that we want to draw the gaze points on the recorded video (optional) Default: off\n"
<< "\t--drawonscreen \t Indicates that we want to draw the gaze points on the recorded screen (optional but requires --convertfps) Default: off\n"
<< endl;
}
static bool existsFile (const string& name) {
ifstream f(name.c_str());
if (f.good()) {
f.close();
return true;
} else {
f.close();
return false;
}
}
int main (int argc, char *argv[]){
// Check if we have at least 7 arguments
if (argc < 7){
show_usage(argv[0]);
return 1;
}
// Check the arguments itself
string folderFilePath;
string outputFolderName;
string eyeCenterDetectAlgo;
string gazeTrackingAlgo;
bool convertFPS = false;
bool drawOnVideo = false;
bool drawOnScreen = false;
int fastEyeWidth = 0;
for (int i = 1; i < argc; ++i) {
// **** required parameters *****
//Check the video input option
if (string(argv[i]) == "--input") {
if (i + 1 < argc) {
folderFilePath = argv[++i];
} else {
cerr << "--input option requires one argument." << endl;
show_usage(argv[0]);
return 1;
}
}
//Check the output video option
if (string(argv[i]) == "--output") {
if (i + 1 < argc) {
outputFolderName = argv[++i];
outputFolderName += "/";
} else {
cerr << "--output option requires one argument." << endl;
show_usage(argv[0]);
return 1;
}
}
//Check the eye algorithm option
if (string(argv[i]) == "--eyealg") {
if (i + 1 < argc) {
eyeCenterDetectAlgo = argv[++i];
} else {
cerr << "--eyealg option requires one argument." << endl;
show_usage(argv[0]);
return 1;
}
}
//Check the gaze algorithm option
if (string(argv[i]) == "--gazealg") {
if (i + 1 < argc) {
gazeTrackingAlgo = argv[++i];
} else {
cerr << "--gazealg option requires one argument." << endl;
show_usage(argv[0]);
return 1;
}
}
// **** optional parameters *****
//Check the convertFPS option
if (string(argv[i]) == "--convertfps") {
convertFPS = true;
}
//Check the drawOnVideo option
if (string(argv[i]) == "--drawonvideo") {
drawOnVideo = true;
}
//Check the drawOnScreen option
if (string(argv[i]) == "--drawonscreen") {
drawOnScreen = true;
}
//Check the fastSizeWidth Argument
if (string(argv[i]) == "--fastwidth") {
if (i + 1 < argc) { //it must be one available
istringstream ss(argv[++i]);
if(!(ss >> fastEyeWidth)){ //it must be a valid number
cerr << "Invalid Number for argument --fastwidth" << endl;
show_usage(argv[0]);
return 1;
}
} else {
cerr << "--fastwidth option requires one argument." << endl;
show_usage(argv[0]);
return 1;
}
}
}
// **** check all argument requirements ****
// Check if the required files are available within the folder
if(!existsFile(folderFilePath+SETTINGS_FILE)){
cerr << "Missing file in folder: GazeTrackingSettings.txt" << endl;
return 1;
}
if(!existsFile(folderFilePath+RAW_INPUT_VIDEO)){
cerr << "Missing file in folder: video_recording_raw_vfr.mp4" << endl;
return 1;
}
if(outputFolderName.empty()){
cerr << "Invalid output folder. Either missing or empty/invalid string!" << endl;
return 1;
}
if(drawOnScreen){ //must only be available if we want to draw on the screen
if(!existsFile(folderFilePath+RAW_INPUT_SCREEN)){
cerr << "Missing file in folder: screen_recording_raw_vfr.txt" << endl;
return 1;
}
}
// Check if the eye center algorithm was specified correctly
if(eyeCenterDetectAlgo == "grad"){
eyeCenterDetectAlgo = "EYE_CENTER_ALGO_GRADIENTS";
//Set the default fast size if no fast size was specified
if(fastEyeWidth <= 0){
fastEyeWidth = 50;
}
} else if (eyeCenterDetectAlgo == "isoph"){
eyeCenterDetectAlgo = "EYE_CENTER_ALGO_ISOPHOTES";
if(fastEyeWidth <= 0){
fastEyeWidth = 80;
}
} else if (eyeCenterDetectAlgo == "comb"){
eyeCenterDetectAlgo = "EYE_CENTER_ALGO_COMBINED";
fastEyeWidth = 0; //we do not need this setting as we cannot specify it for the combined version (always uses 50/80)
} else {
cerr << "Invalid Eye Center Algorithm" << endl;
show_usage(argv[0]);
return 1;
}
// Check if the gaze tracking algorithm was specified correctly
if(gazeTrackingAlgo == "approx"){
gazeTrackingAlgo = "GAZE_TRACKING_ALGO_APPROX";
} else if (gazeTrackingAlgo == "geo"){
gazeTrackingAlgo = "GAZE_TRACKING_ALGO_GEO";
} else {
cerr << "Invalid Gaze Tracking Algorithm" << endl;
show_usage(argv[0]);
return 1;
}
// Create the post proc folder
mkdir((folderFilePath+outputFolderName).c_str(),0777);
//Depending on the availability start the corresponding steps
// Step1 => Check if we have to do a video conversion
if(convertFPS){
convert_fps(folderFilePath, outputFolderName, RAW_INPUT_VIDEO, RAW_INPUT_VIDEO_CFR);
if(drawOnScreen){
convert_fps(folderFilePath, outputFolderName, RAW_INPUT_SCREEN, RAW_INPUT_SCREEN_CFR);
}
}
// Step2 => Convert the video file (consider the different type of input files)
if(convertFPS){
string postProcFolder = folderFilePath+outputFolderName;
process_video(postProcFolder+RAW_INPUT_VIDEO_CFR, postProcFolder+PROC_VIDEO_RECORDING_CFR, folderFilePath+SETTINGS_FILE, postProcFolder+TEXT_GAZE_POINTS_CFR, drawOnVideo, eyeCenterDetectAlgo,gazeTrackingAlgo, fastEyeWidth);
} else {
string postProcFolder = folderFilePath+outputFolderName;
process_video(folderFilePath+RAW_INPUT_VIDEO, postProcFolder+PROC_VIDEO_RECORDING_VFR, folderFilePath+SETTINGS_FILE, postProcFolder+TEXT_GAZE_POINTS_VFR, drawOnVideo, eyeCenterDetectAlgo,gazeTrackingAlgo, fastEyeWidth);
}
// Step3 => Draw GazePoints on the Screen Recording file
if(drawOnScreen && convertFPS){
string postProcFolder = folderFilePath+outputFolderName;
process_screen(postProcFolder+RAW_INPUT_SCREEN_CFR, postProcFolder+PROC_SCREEN_RECORDING_CFR, postProcFolder+TEXT_GAZE_POINTS_CFR);
}
return 0;
}
| eyetrackingDB/GazeTrackingOfflineProcessing | PostProcessing.cpp | C++ | gpl-2.0 | 7,076 |
<?php
/**
* $Project: GeoGraph $
* $Id: moversboard.php 3001 2007-01-22 19:30:41Z barry $
*
* GeoGraph geographic photo archive project
* This file copyright (C) 2005 BArry Hunter (geo@barryhunter.co.uk)
*
* 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.
*/
require_once('geograph/global.inc.php');
init_session();
$smarty = new GeographPage;
$template='games_moversboard.tpl';
$l=inSetRequestInt('l',-1);
$g=inSetRequestInt('g',1);
$cacheid="$g.$l";
if (isset($_GET['more'])) {
$smarty->clear_cache($template, $cacheid);
}
if (!$smarty->is_cached($template, $cacheid))
{
$smarty->assign('gamelist',array('0'=>'-all games-','1'=>'Mark It','2'=>'Place Memory'));
$smarty->assign('levellist',array('-1'=>'-all-','1'=>'1','2'=>'2','3'=>'3','4'=>'4','5'=>'5'));
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$db=NewADOConnection($GLOBALS['DSN']);
if (!$db) die('Database connection failed');
/////////////
if ($l > -1) {
$where = "and level = $l";
} else {
$where = 'and level > 0';
}
if ($g > 0) {
$where .= " and game_id = $g";
}
$sql="select game_score_id,username,gs.user_id,realname,round(avg(level)) as level,sum(score) as score,sum(games) as games,sum(score)/sum(games) as average
from game_score gs
left join user using(user_id)
where gs.created > date_sub(now(), interval 7 day) and approved = 1 $where
group by if(gs.user_id>0,gs.user_id,concat(username,session))
order by average desc,score desc, games desc,username,realname ";
if ($_GET['debug'])
print $sql;
$topusers=$db->GetAssoc($sql);
//assign an ordinal
$i=1;$lastscore = '?';
$average = $games = $score = 0;
foreach($topusers as $id=>$entry)
{
if ($lastscore == $entry['average'])
$topusers[$id]['ordinal'] = '" ';
else {
$topusers[$id]['ordinal'] = smarty_function_ordinal($i);
$lastscore = $entry['average'];
}
$i++;
$average += $entry['average'];
$score += $entry['score'];
$games += $entry['games'];
}
if ($i > 1) {
$smarty->assign('average', sprintf("%.2f",$average/($i-1)));
} else {
$smarty->assign('average', 0);
}
$smarty->assign('score', $score);
$smarty->assign('games', $games);
$smarty->assign('l', $l);
$smarty->assign('g', $g);
$smarty->assign_by_ref('topusers', $topusers);
$smarty->assign('cutoff_time', time()-86400*7);
}
$smarty->display($template, $cacheid);
?>
| s-a-r-id/geograph-project | public_html/games/moversboard.php | PHP | gpl-2.0 | 3,154 |
/*
* File : IPBanned.java
* Created : 08-Jan-2007
* By : jstockall
* Copyright (C) Azureus Software, Inc, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details ( see the LICENSE file ).
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.biglybt.pif.ipfilter;
/**
* @author jstockall
* @since 2.5.0.2
*/
public interface
IPBanned
{
public String
getBannedIP();
/**
* returns the torrent name the IP was banned by the user
* @return
*/
public String
getBannedTorrentName();
public long
getBannedTime();
}
| BiglySoftware/BiglyBT | core/src/com/biglybt/pif/ipfilter/IPBanned.java | Java | gpl-2.0 | 1,197 |
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace MouseSimulation.Simulators
{
public class CursorSimulator
{
private double acceleration;
private double divisor;
public CursorSimulator()
{
this.ActivateEventLooperIncreasement();
}
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
[Flags]
public enum MouseEventFlags : uint
{
LEFTDOWN = 0x00000002,
LEFTUP = 0x00000004,
MIDDLEDOWN = 0x00000020,
MIDDLEUP = 0x00000040,
MOVE = 0x00000001,
ABSOLUTE = 0x00008000,
RIGHTDOWN = 0x00000008,
RIGHTUP = 0x00000010
}
private void DoMouseClick()
{
mouse_event((uint)(MouseEventFlags.LEFTDOWN | MouseEventFlags.LEFTUP | MouseEventFlags.ABSOLUTE),
(uint)Cursor.Position.X, (uint)Cursor.Position.Y, 0, (uint)UIntPtr.Zero);
}
private void DoMouseRightClick()
{
mouse_event((uint)(MouseEventFlags.RIGHTDOWN | MouseEventFlags.RIGHTUP | MouseEventFlags.ABSOLUTE),
(uint)Cursor.Position.X, (uint)Cursor.Position.Y, 0, (uint)UIntPtr.Zero);
}
public void SimulateClick()
{
this.DoMouseClick();
}
public void SimulateDoubleClick()
{
this.DoMouseClick();
this.DoMouseClick();
}
public void SimulateRightClick()
{
this.DoMouseRightClick();
}
public void MoveCursorToRight(uint distance)
{
int newDistance = this.ConvertDistance((int)distance);
this.MoveCursorToX(newDistance);
}
public void MoveCursorToLeft(uint distance)
{
int newDistance = this.ConvertDistance((int)distance);
this.MoveCursorToX(newDistance * -1);
}
public void MoveCursorToBottom(uint distance)
{
int newDistance = this.ConvertDistance((int)distance);
this.MoveCursorToY(newDistance);
}
public void MoveCursorToTop(uint distance)
{
int newDistance = this.ConvertDistance((int)distance);
this.MoveCursorToY(newDistance * -1);
}
private int ConvertDistance(int distance)
{
if (distance < 50)
return (int)Math.Pow(distance / this.divisor, this.acceleration);
if (distance < 300)
return (int)Math.Pow(distance / this.divisor, this.acceleration + 0.1);
return (int)Math.Pow(distance / this.divisor, this.acceleration + 0.2);
}
private void MoveCursorToX(int distance)
{
Cursor.Position = new Point(Cursor.Position.X + distance, Cursor.Position.Y);
}
private void MoveCursorToY(int distance)
{
Cursor.Position = new Point(Cursor.Position.X, Cursor.Position.Y + distance);
}
public void ActivateTaskLooperIncreasement()
{
//this.acceleration = 0.4;
//this.acceleration = 1.1;
//this.divisor = 7;
}
public void ActivateEventLooperIncreasement()
{
this.acceleration = 1.1;
this.divisor = 6;
}
}
} | tavotavotavo/beyondbody | scr/MouseSimulation/Simulators/CursorSimulator.cs | C# | gpl-2.0 | 3,567 |
<?php
Yii::import('ext.components.actions.base.BaseActionInlineUpdate');
class BaseActionUpdate extends BaseActionInlineUpdate
{
public $checkRelated = array();
public $decodeAttributes = array();
public $enableUrlAttributes = false;
public $loadParams = array();
public $inputMethod = 'POST';
public $createFromGlobals = false;
private $_relatedData = array();
private $_data = array();
public function runAction($params)
{
parent::runAction($params);
$id = Yii::app()->request->getQuery('id',null);
$controller = $this->controller;
$this->hanndleInput();
$this->onBeforeModelHandle(new CEvent($this));
$model = $controller->loadModel($id,$this->modelName,$this->loadParams);
$this->setModel($model);
$this->onAfterModelHandle(new CEvent($this));
}
protected function hanndleInput()
{
switch ($this->inputMethod)
{
case 'POST':
$this->_data = $_POST;
break;
case 'GET':
$this->_data = $_GET;
break;
case 'input':
$this->_data = CJSON::decode(file_get_contents("php://input"));
break;
}
}
public function onAfterModelHandle($event)
{
parent::onAfterModelHandle($event);
$this->processUrlAttributes();
$this->prepareAttributes();
$this->saveModel();
$this->prepareViewParams();
}
protected function processUrlAttributes()
{
if ($this->enableUrlAttributes)
{
$model = $this->getModel();
foreach ($model->attributeNames() as $attribute)
{
if (isset($_GET[$attribute]))
{
$model->$attribute = $_GET[$attribute];
}
}
$this->setModel($model);
}
}
protected function prepareAttributes()
{
$params = array();
$relatedData = array();
$model = $this->model;
$relations = $model->relations();
foreach ($this->related as $key=>$relation)
{
$relatedObject = $model->{$relation};
$relationModelName = $relations[$relation][1];
if (is_null($relatedObject))
{
$relatedObject = new $relationModelName;
}
if (isset($this->_data[$relation]))
{
if ($relations[$relation][0] == CActiveRecord::HAS_ONE)
{
$relatedObject->attributes = $this->_data[$relation];
$relatedData[$relation] = $relatedObject;
}
else
{
$relatedData[$relation] = $this->_data[$relation];
}
$params[$relation] = $relatedObject;
}
else if(isset($this->_data[$relationModelName]))
{
$relatedObject->attributes = $this->_data[$relationModelName];
$relatedData[$relation] = $this->_data[$relationModelName];
$relatedData[$relation] = $relations[$relation][0] == CActiveRecord::HAS_ONE ? $relatedObject : $this->_data[$relationModelName];
$params[$relation] = $relatedObject;
}
else
{
$params[$relation] = $relatedObject;
}
}
$this->setViewParams($params);
$this->_relatedData = $relatedData;
}
protected function saveModel()
{
$controller = $this->controller;
$model = $this->getModel();
$relatedData = $this->_relatedData;
if(isset($this->_data[$this->modelName]) || count($this->_data)&&$this->createFromGlobals)
{
$model->attributes = $this->createFromGlobals ? $this->_data : $this->_data[$this->modelName];
if (count($this->decodeAttributes))
{
foreach ($this->decodeAttributes as $attribute)
{
$model->$attribute = urldecode($model->$attribute);
}
}
$checkRelated = true;
if (count($this->checkRelated))
{
foreach ($this->checkRelated as $related)
{
if (!$relatedData[$related]->validate())
{
$checkRelated = false;
break;
}
}
}
if ($checkRelated)
{
$this->onBeforeModelSave(new CEvent($this));
if($model->saveWithRelated($relatedData))
{
$this->onAfterModelSave(new CEvent($this));
}
else
{
Yii::log(print_r($model->errors,true),'trace');
$this->setViewParams(array_merge($this->getViewParams(),array(
'errors' => $model->errors,
)));
}
}
}
$this->setModel($model);
}
protected function prepareViewParams()
{
$model = $this->model;
$params = $this->getViewParams();
$params['model'] = $model;
$this->setViewParams($params);
}
public function onAfterModelSave($event)
{
$this->raiseEvent('onAfterModelSave', $event);
}
public function onBeforeModelSave($event)
{
$this->raiseEvent('onBeforeModelSave', $event);
}
}
?> | UsefulWeb/yii-components-pack-lite | components/actions/base/BaseActionUpdate.php | PHP | gpl-2.0 | 4,366 |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
QuickMapServices
A QGIS plugin
Collection of internet map services
-------------------
begin : 2014-11-21
git sha : $Format:%H$
copyright : (C) 2014 by NextGIS
email : info@nextgis.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. *
* *
***************************************************************************/
"""
from __future__ import absolute_import
import codecs
import os
import sys
from qgis.PyQt.QtCore import QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QMenu
from qgis.core import QgsMessageLog
from .config_reader_helper import ConfigReaderHelper
from . import extra_sources
from .custom_translator import CustomTranslator
from .group_info import GroupInfo, GroupCategory
from .plugin_locale import Locale
from .compat import configparser, get_file_dir
from .compat2qgis import message_log_levels
CURR_PATH = get_file_dir(__file__)
INTERNAL_GROUP_PATHS = [os.path.join(CURR_PATH, extra_sources.GROUPS_DIR_NAME), ]
CONTRIBUTE_GROUP_PATHS = [os.path.join(extra_sources.CONTRIBUTE_DIR_PATH, extra_sources.GROUPS_DIR_NAME), ]
USER_GROUP_PATHS = [os.path.join(extra_sources.USER_DIR_PATH, extra_sources.GROUPS_DIR_NAME), ]
ALL_GROUP_PATHS = INTERNAL_GROUP_PATHS + CONTRIBUTE_GROUP_PATHS + USER_GROUP_PATHS
ROOT_MAPPING = {
INTERNAL_GROUP_PATHS[0]: GroupCategory.BASE,
CONTRIBUTE_GROUP_PATHS[0]: GroupCategory.CONTRIB,
USER_GROUP_PATHS[0]: GroupCategory.USER
}
class GroupsList(object):
def __init__(self, group_paths=ALL_GROUP_PATHS):
self.locale = Locale.get_locale()
self.translator = CustomTranslator()
self.paths = group_paths
self.groups = {}
self._fill_groups_list()
def _fill_groups_list(self):
self.groups = {}
for gr_path in self.paths:
if gr_path in ROOT_MAPPING.keys():
category = ROOT_MAPPING[gr_path]
else:
category = GroupCategory.USER
for root, dirs, files in os.walk(gr_path):
for ini_file in [f for f in files if f.endswith('.ini')]:
self._read_ini_file(root, ini_file, category)
def _read_ini_file(self, root, ini_file_path, category):
try:
ini_full_path = os.path.join(root, ini_file_path)
parser = configparser.ConfigParser()
with codecs.open(ini_full_path, 'r', 'utf-8') as ini_file:
if hasattr(parser, "read_file"):
parser.read_file(ini_file)
else:
parser.readfp(ini_file)
#read config
group_id = parser.get('general', 'id')
group_alias = parser.get('ui', 'alias')
icon_file = ConfigReaderHelper.try_read_config(parser, 'ui', 'icon')
group_icon_path = os.path.join(root, icon_file) if icon_file else None
#try read translations
posible_trans = parser.items('ui')
for key, val in posible_trans:
if type(key) is unicode and key == 'alias[%s]' % self.locale:
self.translator.append(group_alias, val)
break
#create menu
group_menu = QMenu(self.tr(group_alias))
group_menu.setIcon(QIcon(group_icon_path))
#append to all groups
# set contrib&user
self.groups[group_id] = GroupInfo(group_id, group_alias, group_icon_path, ini_full_path, group_menu, category)
except Exception as e:
error_message = self.tr('Group INI file can\'t be parsed: ') + e.message
QgsMessageLog.logMessage(error_message, level=message_log_levels["Critical"])
def get_group_menu(self, group_id):
if group_id in self.groups:
return self.groups[group_id].menu
else:
info = GroupInfo(group_id=group_id, menu=QMenu(group_id))
self.groups[group_id] = info
return info.menu
# noinspection PyMethodMayBeStatic
def tr(self, message):
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return self.translator.translate('QuickMapServices', message)
| nextgis/quickmapservices | src/groups_list.py | Python | gpl-2.0 | 5,024 |
<?php
/**
* Renders each course in the shortcode-courses.php template.
*
* @version 1.0.1
*/
$edr_courses = Edr_Courses::get_instance();
$course_id = get_the_ID();
$price = $edr_courses->get_course_price( $course_id );
$price_str = ( $price > 0 ) ? edr_format_price( $price ) : _x( 'Free', 'price', 'novolearn' );
$thumb_size = apply_filters( 'edr_courses_thumb_size', 'thumbnail' );
?>
<article id="course-<?php echo intval( $course_id ); ?>" class="edr-course">
<?php if ( has_post_thumbnail() ) : ?>
<div class="edr-course__image">
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( $thumb_size ); ?></a>
</div>
<?php endif; ?>
<header class="edr-course__header">
<h2 class="edr-course__title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<div class="edr-course__price"><?php echo $price_str; ?></div>
</header>
<div class="edr-course__summary">
<?php the_excerpt(); ?>
</div>
</article>
| educatorplugin/educator | templates/content-course.php | PHP | gpl-2.0 | 950 |
<?php
/* Site language */
define( 'BS_LANG', 'fr_FR' );
/* Site Name */
define( 'BS_NAME', 'BackStarter Demo' );
| Darklg/BackStarter | bs-default-config.php | PHP | gpl-2.0 | 115 |
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 100005, MOD = 99999997, inf = ~0u<<1;
int a[maxn], b[maxn], c[maxn], n, L[maxn], R[maxn], ans;
int find(int l, int r, int key) {
int m = (l+r) >> 1;
if(key == b[m]) return m;
return key < b[m] ? find(l, m, key) : find(m+1, r, key);
}
void merge_sort(int* arr, int l, int r) {
if(l < r-1) {
int m = (l+r) >> 1;
merge_sort(arr, l, m);
merge_sort(arr, m, r);
int i, j;
for(i = 0; i < m-l; ++i) L[i] = arr[l+i];
for(j = 0; j < r-m; ++j) R[j] = arr[m+j];
L[i] = R[j] = inf; i = j = 0;
while(l < r) {
if(L[i] > R[j]) {
ans = (ans+r-m-j)%MOD;
arr[l++] = L[i++];
}
else arr[l++] = R[j++];
}
}
}
int main() {
int i;
scanf("%d", &n);
for(i = 0; i < n; ++i) scanf("%d", &b[i]);
memcpy(c, b, sizeof(b));
sort(b, b+n);
for(i = 0; i < n; ++i) a[find(0, n-1, c[i])] = i;
for(i = 0; i < n; ++i) scanf("%d", &b[i]);
memcpy(c, b, sizeof(b));
sort(b, b+n);
for(i = 0; i < n; ++i) c[i] = a[find(0, n-1, c[i])];
merge_sort(c, 0, n);
printf("%d", ans);
return 0;
} | iwtwiioi/OnlineJudge | wikioi/Run_456570_Score_100_Date_2014-02-05.cpp | C++ | gpl-2.0 | 1,142 |
/**
* IRCAnywhere server/channels.js
*
* @title ChannelManager
* @copyright (c) 2013-2014 http://ircanywhere.com
* @license GPL v2
* @author Ricki Hastings
*/
var _ = require('lodash'),
hooks = require('hooks');
/**
* This object is responsible for managing everything related to channel records, such as
* the handling of joins/parts/mode changes/topic changes and such.
* As always these functions are extendable and can be prevented or extended by using hooks.
*
* @class ChannelManager
* @method ChannelManager
* @return void
*/
function ChannelManager() {
this.channel = {
network: '',
channel: '',
topic: {},
modes: ''
};
// a default channel object
}
/**
* Gets a tab record from the parameters passed in, strictly speaking this doesn't have to
* be a channel, a normal query window will also be returned. However this class doesn't
* need to work with anything other than channels.
*
* A new object is created but not inserted into the database if the channel doesn't exist.
*
* @method getChannel
* @param {String} network A network string such as 'freenode'
* @param {String} channel The name of a channel **with** the hash key '#ircanywhere'
* @return {Object} A channel object straight out of the database.
*/
ChannelManager.prototype.getChannel = function(network, channel) {
var chan = application.Tabs.sync.findOne({network: network, target: channel});
if (!chan) {
var chan = _.clone(this.channel);
chan.network = network;
chan.channel = channel;
}
return chan;
}
/**
* Inserts a user or an array of users into a channel record matching the network key
* network name and channel name, with the option to force an overwrite
*
* @method insertUsers
* @param {ObjectID} key A valid Mongo ObjectID for the networks collection
* @param {String} network The network name, such as 'freenode'
* @param {String} channel The channel name '#ircanywhere'
* @param {Array[Object]} users An array of valid user objects usually from a who/join output
* @param {Boolean} [force] Optional boolean whether to overwrite the contents of the channelUsers
* @return {Array} The final array of the users inserted
*/
ChannelManager.prototype.insertUsers = function(key, network, channel, users, force) {
var force = force || false,
channel = channel.toLowerCase(),
burst = (users.length > 1) ? true : false,
find = [],
chan = this.getChannel(key, channel),
finalArray = [];
for (var uid in users) {
var u = users[uid];
u.network = network;
u.channel = channel;
u._burst = burst;
find.push(u.nickname);
if (u.nickname == Clients[key].nick) {
application.Networks.sync.update({_id: key}, {$set: {hostname: u.hostname}});
}
// update hostname
}
// turn this into an array of nicknames
if (force) {
application.ChannelUsers.sync.remove({network: network, channel: channel});
} else {
application.ChannelUsers.sync.remove({network: network, channel: channel, nickname: {$in: find}});
}
// ok so here we've gotta remove any users in the channel already
// and all of them if we're being told to force the update
for (var uid in users) {
var u = users[uid],
prefix = eventManager.getPrefix(Clients[key], u);
u.sort = prefix.sort;
u.prefix = prefix.prefix;
finalArray.push(u);
}
// send the update out
if (finalArray.length > 0) {
return application.ChannelUsers.sync.insert(finalArray);
} else {
return [];
}
}
/**
* Removes a specific user from a channel, if users is omitted, channel should be equal to a nickname
* and that nickname will be removed from all channels records on that network.
*
* @method removeUsers
* @param {String} network A valid network name
* @param {String} [channel] A valid channel name
* @param {Array} users An array of users to remove from the network `or` channel
* @return void
*/
ChannelManager.prototype.removeUsers = function(network, channel, users) {
var channel = (_.isArray(channel)) ? channel : channel.toLowerCase(),
users = (_.isArray(channel)) ? channel : users;
// basically we check if channel is an array, if it is we're being told to
// just remove the user from the entire network (on quits etc)
if (users.length === 0) {
return false;
}
if (_.isArray(channel)) {
application.ChannelUsers.remove({network: network, nickname: {$in: users}}, {safe: false});
} else {
application.ChannelUsers.remove({network: network, channel: channel, nickname: {$in: users}}, {safe: false});
}
// send the update out
}
/**
* Updates a user or an array of users from the specific channel with the values passed in.
*
* @method updateUsers
* @param {ObjectID} key A valid Mongo ObjectID for the networks collection
* @param {String} network The name of the network
* @param {Array} users A valid users array
* @param {Object} values A hash of keys and values to be replaced in the users array
* @return void
*/
ChannelManager.prototype.updateUsers = function(key, network, users, values) {
var update = {};
for (var uid in users) {
var u = users[uid],
s = {network: network, nickname: u},
records = application.ChannelUsers.sync.find(s).sync.toArray();
for (var rid in records) {
var user = records[rid];
var updated = _.extend(user, values);
updated.sort = eventManager.getPrefix(Clients[key], updated).sort;
application.ChannelUsers.sync.update(s, _.omit(updated, '_id'));
// update the record
}
}
// this is hacky as hell I feel but it's getting done this way to
// comply with all the other functions in this class
}
/**
* Takes a mode string, parses it and handles any updates to any records relating to
* the specific channel. This handles user updates and such, it shouldn't really be called
* externally, however can be pre and post hooked like all other functions in this object.
*
* @method updateModes
* @param {ObjectID} key A valid Mongo ObjectID for the networks collection
* @param {Object} capab A valid capabilities object from the 'registered' event
* @param {String} network Network name
* @param {String} channel Channel name
* @param {String} mode Mode string
* @return void
*/
ChannelManager.prototype.updateModes = function(key, capab, network, channel, mode) {
var channel = channel.toLowerCase(),
chan = this.getChannel(key, channel),
us = {};
var users = application.ChannelUsers.sync.find({network: network, channel: channel}).sync.toArray(),
parsedModes = modeParser.sortModes(capab, mode);
// we're not arsed about the channel or network here
var modes = modeParser.changeModes(capab, chan.modes, parsedModes);
// we need to attempt to update the record now with the new info
application.Tabs.update({network: key, target: channel}, {$set: {modes: modes}}, {safe: false});
// update the record
users.forEach(function(u) {
delete u._id;
us[u.nickname] = u;
});
modeParser.handleParams(capab, us, parsedModes).forEach(function(u) {
var prefix = eventManager.getPrefix(Clients[key], u);
u.sort = prefix.sort;
u.prefix = prefix.prefix;
application.ChannelUsers.update({network: network, channel: channel, nickname: u.nickname}, u, {safe: false});
});
// update users now
}
/**
* Updates the specific channel's topic and setby in the internal records.
*
* @method updateTopic
* @param {ObjectID} key A valid Mongo ObjectID for the networks collection
* @param {String} channel A valid channel name
* @param {String} topic The new topic
* @param {String} setby A setter string, usually in the format of 'nickname!username@hostname'
* @return void
*/
ChannelManager.prototype.updateTopic = function(key, channel, topic, setby) {
var channel = channel.toLowerCase(),
chan = this.getChannel(key, channel);
var topic = {
topic: topic,
setter: setby || ''
};
// updat the topic record
application.Tabs.update({network: key, target: channel}, {$set: {topic: topic}}, {safe: false});
// update the record
}
exports.ChannelManager = _.extend(ChannelManager, hooks); | KenanSulayman/ircanywhere | server/channels.js | JavaScript | gpl-2.0 | 8,230 |
using System;
using System.Runtime.Serialization;
namespace Gwupe.Cloud.Messaging.Elements
{
[DataContract]
public class MembershipUpdateElement
{
public String uniqueHandle { get; set; }
public bool player { get; set; }
public bool admin { get; set; }
}
} | gwupe/Gwupe | BlitsMeCloudClient/Messaging/Elements/MembershipUpdateElement.cs | C# | gpl-2.0 | 300 |
<?php
/*####
#
# Name: PHx (Placeholders Xtended)
# Version: 2.1.2
# Author: Armand "bS" Pondman (apondman@zerobarrier.nl)
# Date: Feb 13, 2007 8:52 CET
#
####*/
class PHxParser {
var $placeholders = array();
function PHxParser($debug=0,$maxpass=50) {
global $modx;
$this->name = "PHx";
$this->version = "2.1.2";
$this->user["mgrid"] = intval(isset($_SESSION['mgrInternalKey']) ? $_SESSION['mgrInternalKey'] : 0);
$this->user["usrid"] = intval(isset($_SESSION['webInternalKey']) ? $_SESSION['webInternalKey'] : 0);
$this->user["id"] = ($this->user["usrid"] > 0 ) ? (-$this->user["usrid"]) : $this->user["mgrid"];
$this->cache["cm"] = array();
$this->cache["ui"] = array();
$this->cache["mo"] = array();
$this->safetags[0][0] = '~(?<![\[]|^\^)\[(?=[^\+\*\(\[]|$)~s';
$this->safetags[0][1] = '~(?<=[^\+\*\)\]]|^)\](?=[^\]]|$)~s';
$this->safetags[1][0] = '&_PHX_INTERNAL_091_&';
$this->safetags[1][1] = '&_PHX_INTERNAL_093_&';
$this->safetags[2][0] = '[';
$this->safetags[2][1] = ']';
$this->console = array();
$this->debug = ($debug!='') ? $debug : 0;
$this->debugLog = false;
$this->curPass = 0;
$this->maxPasses = ($maxpass!='') ? $maxpass : 50;
$this->swapSnippetCache = array();
$modx->setPlaceholder("phx", "&_PHX_INTERNAL_&");
}
// Plugin event hook for MODX
function OnParseDocument() {
global $modx;
// Get document output from MODX
$template = $modx->documentOutput;
// To the parse cave .. let's go! *insert batman tune here*
$template = $this->Parse($template);
// Set processed document output in MODX
$modx->documentOutput = $template;
}
// Parser: Preparation, cleaning and checkup
function Parse($template='') {
global $modx;
// If we already reached max passes don't get at it again.
if ($this->curPass == $this->maxPasses) return $template;
// Set template pre-process hash
$st = md5($template);
// Replace non-call characters in the template: [, ]
$template = preg_replace($this->safetags[0],$this->safetags[1],$template);
// To the parse mobile.. let's go! *insert batman tune here*
$template = $this->ParseValues($template);
// clean up unused placeholders that have modifiers attached (MODX can't clean them)
preg_match_all('~\[(\+|\*|\()([^:\+\[\]]+)([^\[\]]*?)(\1|\))\]~s', $template, $matches);
if ($matches[0]) {
$template = str_replace($matches[0], '', $template);
$this->Log("Cleaning unsolved tags: \n" . implode("\n",$matches[2]) );
}
// Restore non-call characters in the template: [, ]
$template = str_replace($this->safetags[1],$this->safetags[2],$template);
// Set template post-process hash
$et = md5($template);
// If template has changed, parse it once more...
if ($st!=$et) $template = $this->Parse($template);
// Write an event log if debugging is enabled and there is something to log
if ($this->debug && $this->debugLog) {
$modx->logEvent($this->curPass,1,$this->createEventLog(), $this->name.' '.$this->version);
$this->debugLog = false;
}
// Return the processed template
return $template;
}
// Parser: Tag detection and replacements
function ParseValues($template='') {
global $modx;
$this->curPass = $this->curPass + 1;
$st = md5($template);
//$this->LogSource($template);
$this->LogPass();
// MODX Chunks
$this->Log("MODX Chunks -> Merging all chunk tags");
$template = $modx->mergeChunkContent($template);
// MODX Snippets
//if ( preg_match_all('~\[(\[|!)([^\[]*?)(!|\])\]~s',$template, $matches)) {
if ( preg_match_all('~\[(\[)([^\[]*?)(\])\]~s',$template, $matches)) {
$count = count($matches[0]);
$var_search = array();
$var_replace = array();
// for each detected snippet
for($i=0; $i<$count; $i++) {
$snippet = $matches[2][$i]; // snippet call
$this->Log("MODX Snippet -> ".$snippet);
// Let MODX evaluate snippet
$replace = $modx->evalSnippets("[[".$snippet."]]");
$this->LogSnippet($replace);
// Replace values
$var_search[] = $matches[0][$i];
$var_replace[] = $replace;
}
$template = str_replace($var_search, $var_replace, $template);
}
// PHx / MODX Tags
if ( preg_match_all('~\[(\+|\*|\()([^:\+\[\]]+)([^\[\]]*?)(\1|\))\]~s',$template, $matches)) {
//$matches[0] // Complete string that's need to be replaced
//$matches[1] // Type
//$matches[2] // The placeholder(s)
//$matches[3] // The modifiers
//$matches[4] // Type (end character)
$count = count($matches[0]);
$var_search = array();
$var_replace = array();
for($i=0; $i<$count; $i++) {
$replace = NULL;
$match = $matches[0][$i];
$type = $matches[1][$i];
$type_end = $matches[4][$i];
$input = $matches[2][$i];
$modifiers = $matches[3][$i];
$var_search[] = $match;
switch($type) {
// Document / Template Variable eXtended
case "*":
$this->Log("MODX TV/DV: " . $input);
$input = $modx->mergeDocumentContent("[*".$input."*]");
$replace = $this->Filter($input,$modifiers);
break;
// MODX Setting eXtended
case "(":
$this->Log("MODX Setting variable: " . $input);
$input = $modx->mergeSettingsContent("[(".$input.")]");
$replace = $this->Filter($input,$modifiers);
break;
// MODX Placeholder eXtended
default:
$this->Log("MODX / PHx placeholder variable: " . $input);
// Check if placeholder is set
if ( !array_key_exists($input, $this->placeholders) && !array_key_exists($input, $modx->placeholders) ) {
// not set so try again later.
$replace = $match;
$this->Log(" |--- Skipping - hasn't been set yet.");
}
else {
// is set, get value and run filter
$input = $this->getPHxVariable($input);
$replace = $this->Filter($input,$modifiers);
}
break;
}
$var_replace[] = $replace;
}
$template = str_replace($var_search, $var_replace, $template);
}
$et = md5($template); // Post-process template hash
// Log an event if this was the maximum pass
if ($this->curPass == $this->maxPasses) $this->Log("Max passes reached. infinite loop protection so exiting.\n If you need the extra passes set the max passes to the highest count of nested tags in your template.");
// If this pass is not at maximum passes and the template hash is not the same, get at it again.
if (($this->curPass < $this->maxPasses) && ($st!=$et)) $template = $this->ParseValues($template);
return $template;
}
// Parser: modifier detection and eXtended processing if needed
function Filter($input, $modifiers) {
global $modx;
$output = $input;
$this->Log(" |--- Input = '". $output ."'");
if (preg_match_all('~:([^:=]+)(?:=`(.*?)`(?=:[^:=]+|$))?~s',$modifiers, $matches)) {
$modifier_cmd = $matches[1]; // modifier command
$modifier_value = $matches[2]; // modifier value
$count = count($modifier_cmd);
$condition = array();
for($i=0; $i<$count; $i++) {
$output = trim($output);
$this->Log(" |--- Modifier = '". $modifier_cmd[$i] ."'");
if ($modifier_value[$i] != '') $this->Log(" |--- Options = '". $modifier_value[$i] ."'");
switch ($modifier_cmd[$i]) {
##### Conditional Modifiers
case "input": case "if": $output = $modifier_value[$i]; break;
case "equals": case "is": case "eq": $condition[] = intval(($output==$modifier_value[$i])); break;
case "notequals": case "isnot": case "isnt": case "ne":$condition[] = intval(($output!=$modifier_value[$i]));break;
case "isgreaterthan": case "isgt": case "eg": $condition[] = intval(($output>=$modifier_value[$i]));break;
case "islowerthan": case "islt": case "el": $condition[] = intval(($output<=$modifier_value[$i]));break;
case "greaterthan": case "gt": $condition[] = intval(($output>$modifier_value[$i]));break;
case "lowerthan": case "lt":$condition[] = intval(($output<$modifier_value[$i]));break;
case "isinrole": case "ir": case "memberof": case "mo": // Is Member Of (same as inrole but this one can be stringed as a conditional)
if ($output == "&_PHX_INTERNAL_&") $output = $this->user["id"];
$grps = (strlen($modifier_value) > 0 ) ? array_filter(array_map('trim', explode(',', $modifier_value[$i]))) :array();
$condition[] = intval($this->isMemberOfWebGroupByUserId($output,$grps));
break;
case "or":$condition[] = "||";break;
case "and": $condition[] = "&&";break;
case "show":
$conditional = implode(' ',$condition);
$isvalid = intval(eval("return (". $conditional. ");"));
if (!$isvalid) { $output = NULL;}
case "then":
$conditional = implode(' ',$condition);
$isvalid = intval(eval("return (". $conditional. ");"));
if ($isvalid) { $output = $modifier_value[$i]; }
else { $output = NULL; }
break;
case "else":
$conditional = implode(' ',$condition);
$isvalid = intval(eval("return (". $conditional. ");"));
if (!$isvalid) { $output = $modifier_value[$i]; }
break;
case "select":
$raw = explode("&",$modifier_value[$i]);
$map = array();
for($m=0; $m<(count($raw)); $m++) {
$mi = explode("=",$raw[$m]);
$map[$mi[0]] = $mi[1];
}
$output = $map[$output];
break;
##### End of Conditional Modifiers
##### String Modifiers
case "lcase": $output = strtolower($output); break;
case "ucase": $output = strtoupper($output); break;
case "ucfirst": $output = ucfirst($output); break;
case "htmlent": $output = htmlentities($output,ENT_QUOTES,$modx->config['etomite_charset']); break;
case "esc":
$output = preg_replace("/&(#[0-9]+|[a-z]+);/i", "&$1;", htmlspecialchars($output));
$output = str_replace(array("[","]","`"),array("[","]","`"),$output);
break;
case "strip": $output = preg_replace("~([\n\r\t\s]+)~"," ",$output); break;
case "notags": $output = strip_tags($output); break;
case "length": case "len": $output = strlen($output); break;
case "reverse": $output = strrev($output); break;
case "wordwrap": // default: 70
$wrapat = intval($modifier_value[$i]) ? intval($modifier_value[$i]) : 70;
$output = preg_replace("~(\b\w+\b)~e","wordwrap('\\1',\$wrapat,' ',1)",$output);
break;
case "limit": // default: 100
$limit = intval($modifier_value[$i]) ? intval($modifier_value[$i]) : 100;
$output = substr($output,0,$limit);
break;
##### Special functions
case "math":
$filter = preg_replace("~([a-zA-Z\n\r\t\s])~","",$modifier_value[$i]);
$filter = str_replace("?",$output,$filter);
$output = eval("return ".$filter.";");
break;
case "ifempty": if (empty($output)) $output = $modifier_value[$i]; break;
case "nl2br": $output = nl2br($output); break;
case "date": $output = strftime($modifier_value[$i],0+$output); break;
case "set":
$c = $i+1;
if ($count>$c&&$modifier_cmd[$c]=="value") $output = preg_replace("~([^a-zA-Z0-9])~","",$modifier_value[$i]);
break;
case "value":
if ($i>0&&$modifier_cmd[$i-1]=="set") { $modx->SetPlaceholder("phx.".$output,$modifier_value[$i]); }
$output = NULL;
break;
case "md5": $output = md5($output); break;
case "userinfo":
if ($output == "&_PHX_INTERNAL_&") $output = $this->user["id"];
$output = $this->ModUser($output,$modifier_value[$i]);
break;
case "inrole": // deprecated
if ($output == "&_PHX_INTERNAL_&") $output = $this->user["id"];
$grps = (strlen($modifier_value) > 0 ) ? array_filter(array_map('trim', explode(',', $modifier_value[$i]))) :array();
$output = intval($this->isMemberOfWebGroupByUserId($output,$grps));
break;
default:
if (!array_key_exists($modifier_cmd[$i], $this->cache["cm"])) {
$result = $modx->db->select('snippet', $modx->getFullTableName("site_snippets"), "name='phx:".$modifier_cmd[$i]."'");
if ($snippet = $modx->db->getValue($result)) {
$cm = $this->cache["cm"][$modifier_cmd[$i]] = $snippet;
$this->Log(" |--- DB -> Custom Modifier");
}
} else {
$cm = $this->cache["cm"][$modifier_cmd[$i]];
$this->Log(" |--- Cache -> Custom Modifier");
}
ob_start();
$options = $modifier_value[$i];
$custom = eval($cm);
$msg = ob_get_contents();
$output = $msg.$custom;
ob_end_clean();
break;
}
if (count($condition)) $this->Log(" |--- Condition = '". $condition[count($condition)-1] ."'");
$this->Log(" |--- Output = '". $output ."'");
}
}
return $output;
}
// Event logging (debug)
function createEventLog() {
if($this->console) {
$console = implode("\n",$this->console);
$this->console = array();
return '<pre style="overflow: auto;">' . $console . '</pre>';
}
}
// Returns a cleaned string escaping the HTML and special MODX characters
function LogClean($string) {
$string = preg_replace("/&(#[0-9]+|[a-z]+);/i", "&$1;", htmlspecialchars($string));
$string = str_replace(array("[","]","`"),array("[","]","`"),$string);
return $string;
}
// Simple log entry
function Log($string) {
if ($this->debug) {$this->debugLog = true; $this->console[] = (count($this->console)+1-$this->curPass). " [". strftime("%H:%M:%S",time()). "] " . $this->LogClean($string);}
}
// Log snippet output
function LogSnippet($string) {
if ($this->debug) {$this->debugLog = true; $this->console[] = (count($this->console)+1-$this->curPass). " [". strftime("%H:%M:%S",time()). "] " . " |--- Returns: <div style='margin: 10px;'>".$this->LogClean($string)."</div>";}
}
// Log pass
function LogPass() {
$this->console[] = "<div style='margin: 2px;margin-top: 5px;border-bottom: 1px solid black;'>Pass " . $this->curPass . "</div>";
}
// Log pass
function LogSource($string) {
$this->console[] = "<div style='margin: 2px;margin-top: 5px;border-bottom: 1px solid black;'>Source:</div>" . $this->LogClean($string);
}
// Returns the specified field from the user record
// positive userid = manager, negative integer = webuser
function ModUser($userid,$field) {
global $modx;
if (!array_key_exists($userid, $this->cache["ui"])) {
if (intval($userid) < 0) {
$user = $modx->getWebUserInfo(-($userid));
} else {
$user = $modx->getUserInfo($userid);
}
$this->cache["ui"][$userid] = $user;
} else {
$user = $this->cache["ui"][$userid];
}
return $user[$field];
}
// Returns true if the user id is in one the specified webgroups
function isMemberOfWebGroupByUserId($userid=0,$groupNames=array()) {
global $modx;
// if $groupNames is not an array return false
if(!is_array($groupNames)) return false;
// if the user id is a negative number make it positive
if (intval($userid) < 0) { $userid = -($userid); }
// Creates an array with all webgroups the user id is in
if (!array_key_exists($userid, $this->cache["mo"])) {
$tbl = $modx->getFullTableName("webgroup_names");
$tbl2 = $modx->getFullTableName("web_groups");
$rs = $modx->db->select('wgn.name', "$tbl AS wgn INNER JOIN $tbl2 AS wg ON wg.webgroup=wgn.id AND wg.webuser='{$userid}'");
$this->cache["mo"][$userid] = $grpNames = $modx->db->getColumn("name",$rs);
} else {
$grpNames = $this->cache["mo"][$userid];
}
// Check if a supplied group matches a webgroup from the array we just created
foreach($groupNames as $k=>$v)
if(in_array(trim($v),$grpNames)) return true;
// If we get here the above logic did not find a match, so return false
return false;
}
// Returns the value of a PHx/MODX placeholder.
function getPHxVariable($name) {
global $modx;
// Check if this variable is created by PHx
if (array_key_exists($name, $this->placeholders)) {
// Return the value from PHx
return $this->placeholders[$name];
} else {
// Return the value from MODX
return $modx->getPlaceholder($name);
}
}
// Sets a placeholder variable which can only be access by PHx
function setPHxVariable($name, $value) {
if ($name != "phx") $this->placeholders[$name] = $value;
}
}
?>
| fortunto2/automodx | modx.evo.custom-master/assets/snippets/ditto/classes/phx.parser.class.inc.php | PHP | gpl-2.0 | 16,434 |
<?php
/**
* @version 2-0-6-0 // Y-m-d 2016-09-12
* @author Didldu e.K. Florian Häusler https://www.hr-it-solutions.com
* @copyright Copyright (C) 2011 - 2016 Didldu e.K. | HR IT-Solutions
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
**/
class DD_ImgCopyResized
{
protected $final_width;
protected $final_height;
protected $final_quality;
private $Unsupported = "Unsupported file format!";
private $MinimumSize = "your image is smaller than the minimum size required";
/**
* DD_ImgCopyResized constructor.
*
* @param $final_width int width of thumbnail
* @param $final_height int height of thumbnail
* @param $final_quality int optional (possible value 10-100) 80 is the recommended web jpg quality of thumbnails
*/
public function __construct($final_width = 400, $final_height = 300, $final_quality = 80)
{
$this->final_width = intval($final_width);
$this->final_height = intval($final_height);
$this->final_quality = $final_quality;
}
/**
* @param $file array $_FILE[]
* @param $savepath string savepath of images
*
* @return string src of thumbnail
*/
public function generateThumbnail($file = array(), $savepath = "/")
{
// get final thumbnail size
$final_width = &$this->final_width;
$final_height = &$this->final_height;
// get file name of image
$fname = $file['name'];
// get temporary file name of image
$tmpfname = $file['tmp_name'];
// reads Exif header
$exif = exif_read_data($file['tmp_name']);
// get extension of image and set to lowercase character
$extension = strtolower(substr(strrchr($fname, '.'), 1));
// get original width (X) and height (Y) of image
list($org_X, $org_Y) = getimagesize($tmpfname);
// Exif rotation check
$imagerotate = false;
if(!empty($exif['Orientation'])) {
switch($exif['Orientation']) {
case 3:
$imagerotate = 180;
break;
case 6:
$imagerotate = -90;
$tmp_X = $org_X; // Swap X and Y
$org_X = $org_Y;
$org_Y = $tmp_X;
break;
case 8:
$imagerotate = 90;
$tmp_X = $org_X; // Swap X and Y
$org_X = $org_Y;
$org_Y = $tmp_X;
break;
}
}
// minimum image size check
if ($org_X < $final_width OR $org_Y < $final_height)
{
die($this->MinimumSize);
}
// security check depending on image size
else if (getimagesize($tmpfname) === false)
{
die($this->Unsupported);
}
// security check depending on mime-type
elseif (!in_array(getimagesize($tmpfname)[2], array(IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF)))
{
die($this->Unsupported);
}
// security check depending on supported files format
elseif (($extension !== "jpg") && ($extension !== "jpeg") && ($extension !== "png") && ($extension !== "gif"))
{
die($this->Unsupported);
}
else
{
// build savepath for original image and thumbnail image, including file name for lowercase setup
$random = rand(0000, 9999);
// set random prefix of original image
$newfile = $random . "org_" . $fname;
$SavePathOrg = $savepath . strtolower($newfile);
// set random prefix of thumbnail image
$newfile = $random . "_" . $fname;
$SavePathThump = $savepath . strtolower($newfile);
// move uploaded original file to savepath
move_uploaded_file($tmpfname, $SavePathOrg);
// create image from
$src_image = '';
if ($extension === "jpg" || $extension === "jpeg")
{
$src_image = imagecreatefromjpeg($SavePathOrg);
}
else if ($extension === "png")
{
$src_image = imagecreatefrompng($SavePathOrg);
}
else if ($extension === "gif")
{
$src_image = imagecreatefromgif($SavePathOrg);
}
// Exif rotation fix
if($imagerotate != false){ // rotate image based on Exif rotation
$src_image = imagerotate($src_image,$imagerotate,0);
}
{
/**
* Calculation Process:
* horizontal or landscape format,
* cut always either from right side or from bottom to get final width and height without stretching.
*
* $org_X is original width of the image
* $org_Y is original height of the image
*
* $final_width is given width of the image
* $final_height is given height of the image
*/
// resize thumbnail without losing dimension ratio based on uploaded file size,
// checking whether to cut from right side or from bottom
if ((($org_Y / $org_X) * $final_width) < $final_height)
{
// height is smaller than x:y
$new_Y = $final_height;
$new_X = floor($final_height * ($org_X / $org_Y)); // Resize based on height
}
else
{
// height is heigher than x:y
$new_X = $final_width;
$new_Y = floor($final_width * ($org_Y / $org_X)); // Resize based on width
}
}
// Create truecolor image
$dst_image = imagecreatetruecolor($new_X, $new_Y);
if ($extension === "png" || $extension === "gif")
{ // Fill transparen background image
$whitecolor = imagecolorallocate($dst_image, 255, 255, 255);
imagefill($dst_image, 0, 0, $whitecolor);
}
imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $new_X, $new_Y, $org_X, $org_Y);
// Create thumbnail image
if ($extension === "jpg" || $extension === "jpeg")
{
imagejpeg($dst_image, $SavePathThump);
$src_image = imagecreatefromjpeg($SavePathThump);
}
else if ($extension === "png")
{
imagepng($dst_image, $SavePathThump);
$src_image = imagecreatefrompng($SavePathThump);
}
else if ($extension === "gif")
{
imagegif($dst_image, $SavePathThump);
$src_image = imagecreatefromgif($SavePathThump);
}
// Resize and crop
$tmp_dst_image = imagecreatetruecolor($final_width, $final_height);
imagecopyresampled($tmp_dst_image, $src_image, 0, 0, 0, 0, $final_width, $final_height, $final_width, $final_height);
imagejpeg($tmp_dst_image, $SavePathThump, $this->final_quality); // Output image to file
imagedestroy($dst_image); // Destroy destination image
imagedestroy($tmp_dst_image); // Destroy temporary image
// After successful completion, this class returns the src string of the generated thumbnail ( example string="/img/1372_image.jpg" )
return $SavePathThump;
}
}
/**
* Language setter method should be executed before generateThumbnail()
*
* @param $Unsupported string (language string for unsupported format or corrupt file)
* @param $MinimumSize string (language string for minimum file size
*/
public function setLanguage($Unsupported, $MinimumSize)
{
$this->Unsupported = $Unsupported;
$this->MinimumSize = $MinimumSize;
}
}
| hr-it-solutions/DD_imgcopyresized | library/imgcopyresized.php | PHP | gpl-2.0 | 6,648 |
<?php
/**
*
* @package phpBB Extension - tas2580 dejure
* @copyright (c) 2014 tas2580
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2
*
*/
if (!defined('IN_PHPBB'))
{
exit;
}
if (empty($lang) || !is_array($lang))
{
$lang = array();
}
$lang = array_merge($lang, array(
'ACP_DEJURE_TITLE' => 'dejure.org',
'ACP_DEJURE_EXPLAIN' => '',
'ACP_LINK_STYLE' => 'Link Stil',
'ACP_LINK_STYLE_EXPLAIN' => 'schmal: nur die Nummern der Vorschriften verlinken.<br>weit: möglichst lange Verlinkung',
'ACP_CLASS' => 'CSS Klasse',
'ACP_TARGET' => 'Link Target',
'ACP_TARGET_EXPLAIN' => 'Target für die Links, zum Beispiel für öffnen in neuem Fenster: "_blank"',
'ACP_CLASS_EXPLAIN' => 'Falls die Links zu dejure.org anders gestaltet werden sollen.',
'ACP_BUZER' => 'buzer',
'ACP_BUZER_EXPLAIN' => 'Zu http://buzer.de verlinken für Gesetze, die bei dejure.org nicht vorhanden sind.',
'ACP_CACHE_TIME' => 'Cache Zeit',
'ACP_CACHE_TIME_EXPLAIN' => 'In Tagen. Wie lange die Texte im Cache vorgehalten werden soll, bevor sie erneut vernetzt werden. 4 Tage reichen in der Regel.',
'LINK_STYLE_WEIT' => 'weit',
'LINK_STYLE_SCHMAL' => 'schmal',
'ACP_SUBMIT' => 'Einstellungen speichern',
'ACP_SAVED' => 'Die Einstellungen wurden geändert',
));
| tas2580/dejure | language/de/common.php | PHP | gpl-2.0 | 1,309 |
<?php
/* __
* _| |_
* ____ _ _ __ __ _ __ __ ____ |_ _|
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ __ |__|
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | _| |_
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ |_ _|
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| |__|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine++ Team
* @link http://pm-plus-plus.tk/
*/
namespace pocketmine\level;
use pocketmine\math\Vector3;
use pocketmine\utils\LevelException;
class Position extends Vector3
{
/** @var Level */
public $level = \null;
/**
* @param int $x
* @param int $y
* @param int $z
* @param Level $level
*/
public function __construct($x = 0, $y = 0, $z = 0, Level $level = \null)
{
$this->x = $x;
$this->y = $y;
$this->z = $z;
$this->level = $level;
}
public static function fromObject(Vector3 $pos, Level $level = \null)
{
return new Position($pos->x, $pos->y, $pos->z, $level);
}
/**
* @return Level
*/
public function getLevel()
{
return $this->level;
}
public function setLevel(Level $level)
{
$this->level = $level;
return $this;
}
/**
* Checks if this object has a valid reference to a Level
*
* @return bool
*/
public function isValid()
{
return $this->level !== \null;
}
/**
* Returns a side Vector
*
* @param int $side
* @param int $step
*
* @return Position
*
* @throws LevelException
*/
public function getSide($side, $step = 1)
{
\assert($this->isValid());
return Position::fromObject(parent::getSide($side, $step), $this->level);
}
public function __toString()
{
return "Position(level=" . ($this->isValid() ? $this->getLevel()->getName() : "null") . ",x=" . $this->x . ",y=" . $this->y . ",z=" . $this->z . ")";
}
/**
* @param $x
* @param $y
* @param $z
*
* @return Position
*/
public function setComponents($x, $y, $z)
{
$this->x = $x;
$this->y = $y;
$this->z = $z;
return $this;
}
}
| PocketMinePlusPlus/PocketMinePlusPlus | src/pocketmine/level/Position.php | PHP | gpl-2.0 | 2,863 |
using System;
using System.Xml;
using System.Xml.Serialization;
namespace grendgine_collada
{
[Serializable]
[XmlType(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(ElementName = "instance_rigid_constraint", Namespace = "http://www.collada.org/2005/11/COLLADASchema", IsNullable = true)]
public partial class Grendgine_Collada_Instance_Rigid_Constraint
{
[XmlAttribute("sid")]
public string sID;
[XmlAttribute("name")]
public string Name;
[XmlAttribute("constraint")]
public string Constraint;
[XmlElement(ElementName = "extra")]
public Grendgine_Collada_Extra[] Extra;
}
}
| Markemp/Cryengine-Converter | CgfConverter/External/Collada/Collada_Physics/Physics_Model/Grendgine_Collada_Instance_Rigid_Constraint.cs | C# | gpl-2.0 | 685 |
showWord(["v. ","korije, redrese."
]) | georgejhunt/HaitiDictionary.activity | data/words/rektifye.js | JavaScript | gpl-2.0 | 37 |
/* $Id$ */
/***************************************************************************
* (C) Copyright 2003-2010 - Stendhal *
***************************************************************************
***************************************************************************
* *
* 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. *
* *
***************************************************************************/
package games.stendhal.client;
/**
* A container for three objects.
*
* @param <P> type of first object
* @param <S> type of second object
* @param <T> type of third object
*/
public final class Triple<P, S, T> {
// they are used in equals and hashcode
private final P prim;
private final S sec;
private final T third;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
int add;
if (prim == null) {
add = 0;
} else {
add = prim.hashCode();
}
result = prime * result + add;
if (sec == null) {
add = 0;
} else {
add = sec.hashCode();
}
result = prime * result + add;
if (third == null) {
add = 0;
} else {
add = third.hashCode();
}
result = prime * result + add;
return result;
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Triple)) {
return false;
}
final Triple<P, S , T> other = (Triple <P, S, T>) obj;
return nullSafeEquals(prim, other.prim) && nullSafeEquals(sec, other.sec)
&& nullSafeEquals(third, other.third);
}
/**
* Null safe equality check for objects. <b>Note: this should be replaced
* with Objects.equals() once we start requiring java 7.</b>
*
* @param a first object
* @param b second object
* @return <code>true</code> if both <code>a</code> and <code>b</code> are
* <code>null</code> or if they are equal otherwise. In any other case the
* result is <code>false</code>
*/
private boolean nullSafeEquals(Object a, Object b) {
if (a == null) {
return b == null;
}
return a.equals(b);
}
/**
* Create a triple.
*
* @param prim first object
* @param sec second object
* @param third third object
*/
public Triple(final P prim, final S sec, final T third) {
this.prim = prim;
this.sec = sec;
this.third = third;
}
}
| dkfellows/stendhal | src/games/stendhal/client/Triple.java | Java | gpl-2.0 | 2,762 |
/*
* USE - UML based specification environment
* Copyright (C) 1999-2004 Mark Richters, University of Bremen
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* $ProjectHeader: use 2-1-0-release.1 Sun, 09 May 2004 13:57:11 +0200 mr $ */
package org.tzi.use.gui.views;
import java.awt.print.PageFormat;
/**
* Views with print facility implement this interface.
*
* @version $ProjectVersion: 2-1-0-release.1 $
* @author Mark Richters
*/
public interface PrintableView {
void printView(PageFormat pf);
}
| stormymauldin/stuff | src/main/org/tzi/use/gui/views/PrintableView.java | Java | gpl-2.0 | 1,182 |
################################################################
# LiveQ - An interactive volunteering computing batch system
# Copyright (C) 2013 Ioannis Charalampidis
#
# 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 numpy
import re
def parseFLATBuffer(buf, index=True):
"""
Parse FLAT buffer and return the structured data
"""
sections_list = []
section = None
activesection = None
# Pick appropriate return format
sections = None
if index:
sections = {}
else:
sections = []
# Start processing the buffer line-by-line
for line in buf.splitlines():
# Process lines
if not line:
# Empty line
pass
elif "# BEGIN " in line:
# Ignore labels found some times in AIDA files
dat = line.split(" ")
section = dat[2]
sectiontype = 0
# Get additional section title
title = ""
if len(dat) > 3:
title = " ".join(dat[3:])
# Allocate section record
activesection = { "d": { }, "v": [ ], "t": title }
elif ("# END " in line) and (section != None):
# Section end
if index:
sections[section] = activesection
else:
activesection['n'] = section
sections.append(activesection)
section = None
elif line.startswith("#") or line.startswith(";"):
# Comment
pass
elif section:
# Data inside section
# "SPECIAL" section is not parsable here
if section == "SPECIAL":
continue
# Try to split
data = line.split("=",1)
# Could not split : They are histogram data
if len(data) == 1:
# Split data values
data = FLATParser.WHITESPACE.split(line.strip())
# Check for faulty values
if len(data) < 3:
continue
# Otherwise collect
activesection['v'].append( numpy.array(data, dtype=numpy.float64) )
else:
# Store value
activesection['d'][data[0]] = data[1]
# Return sections
return sections
class FLATParser:
"""
Simple function to parser histograms in FLAT format
"""
# Precompiled regex entry
WHITESPACE = re.compile("\s+")
@staticmethod
def parseFileObject(fileobject, index=True):
"""
Function to read a FLAT file (by the file object descriptor) into python structures
"""
# Read entire file and use parseBuffer
return parseFLATBuffer(fileobject.read(), index)
@staticmethod
def parse(filename, index=True):
"""
Function to read a FLAT file into python structures
"""
# Open file
with open(filename, 'r') as f:
# Use FileObject parser to read the file
return parseFLATBuffer(f.read(), index)
def parseBuffer(buf, index=True):
"""
Parse FLAT file from buffer
"""
return parseFLATBuffer(buf, index) | wavesoft/LiveQ | liveq-common/liveq/utils/FLAT.py | Python | gpl-2.0 | 3,333 |
showWord(["n. "," aktivite pou al chase bèt sovaj pou vyann nan osnon pou po. Mwen pa janm al lachas, paske mwen pa gen kè pou mwen touye okenn bèt."
]) | georgejhunt/HaitiDictionary.activity | data/words/lachas.js | JavaScript | gpl-2.0 | 155 |
# -*- coding: utf-8 -*-
# $Id: $
ERROR_AUTH_FAILED = "Authorization failed"
NO_SUCH_BACKEND = "No such backend"
REDIRECTION_FAILED = "Redirection failed" | collective/ECSpooler | lib/util/errorcodes.py | Python | gpl-2.0 | 154 |
<?php die("Access Denied"); ?>#x#s:3682:" 1451729352
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-tw" lang="zh-tw">
<head>
<script type="text/javascript">
var siteurl='/';
var tmplurl='/templates/ja_mendozite/';
var isRTL = false;
</script>
<base href="http://www.zon-com-tw.sensetop.com/zh/faq-zh/19-web/about/24-where-the-materials-are-from" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="author" content="Super User" />
<meta name="robots" content="noindex, nofollow" />
<meta name="generator" content="榮憶橡膠工業股份有限公司" />
<title>Where the materials are from? | 榮憶橡膠工業股份有限公司</title>
<link href="http://www.zon-com-tw.sensetop.com/zh/faq-zh/19-web/about/24-where-the-materials-are-from?tmpl=component&print=1&page=" rel="canonical" />
<link rel="stylesheet" href="/t3-assets/css_9ce88.css" type="text/css" />
<link rel="stylesheet" href="/t3-assets/css_eb05a.css" type="text/css" />
<script src="/en/?jat3action=gzip&jat3type=js&jat3file=t3-assets%2Fjs_f2ed3.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(window).on('load', function() {
new JCaption('img.caption');
});
</script>
<script type="text/javascript">
var akoption = {
"colorTable" : true ,
"opacityEffect" : true ,
"foldContent" : true ,
"fixingElement" : true ,
"smoothScroll" : false
} ;
var akconfig = new Object();
akconfig.root = 'http://www.zon-com-tw.sensetop.com/' ;
akconfig.host = 'http://'+location.host+'/' ;
AsikartEasySet.init( akoption , akconfig );
</script>
<!--[if ie]><link href="/plugins/system/jat3/jat3/base-themes/default/css/template-ie.css" type="text/css" rel="stylesheet" /><![endif]-->
<!--[if ie 7]><link href="/plugins/system/jat3/jat3/base-themes/default/css/template-ie7.css" type="text/css" rel="stylesheet" /><![endif]-->
<!--[if ie 7]><link href="/templates/ja_mendozite/css/template-ie7.css" type="text/css" rel="stylesheet" /><![endif]-->
<link href="/plugins/system/jat3/jat3/base-themes/default/images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-60602086-1', 'auto');
ga('send', 'pageview');
</script>
<link rel="stylesheet" href="http://www.zon-com-tw.sensetop.com/easyset/css/custom-typo.css" type="text/css" />
<link rel="stylesheet" href="http://www.zon-com-tw.sensetop.com/easyset/css/custom.css" type="text/css" />
</head>
<body id="bd" class="fs3 com_content contentpane">
<div id="system-message-container">
<div id="system-message">
</div>
</div>
<div class="item-page clearfix">
<h2 class="contentheading">
<a href="/zh/faq-zh/19-web/about/24-where-the-materials-are-from">
Where the materials are from?</a>
</h2>
<div class="article-tools clearfix">
<ul class="actions">
<li>
<a href="#" onclick="window.print();return false;"><span class="icon-print"></span> 列印 </a> </li>
</ul>
</div>
<p><img style="width: 580px; height: 274px;" src="/images/Where%20the%20materials%20are%20from.jpg" alt="Where the materials are from.jpg" width="525" height="255" /></p>
</div>
</body>
</html>"; | ForAEdesWeb/AEW32 | cache/t3_pages/e8efe7956197beb28b5e158ad88f292e-cache-t3_pages-d4c7c6c0d4844a6328f8d49dea61811d.php | PHP | gpl-2.0 | 3,690 |
/*
* Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 2.0, as published by the
* Free Software Foundation.
*
* This program is also distributed with certain software (including but not
* limited to OpenSSL) that is licensed under separate terms, as designated in a
* particular file or component or in included license documentation. The
* authors of MySQL hereby grant you an additional permission to link the
* program and your derivative works with the separately licensed software that
* they have included with MySQL.
*
* Without limiting anything contained in the foregoing, this file, which is
* part of MySQL Connector/J, is also subject to the Universal FOSS Exception,
* version 1.0, a copy of which can be found at
* http://oss.oracle.com/licenses/universal-foss-exception.
*
* 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, version 2.0,
* for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.mysql.cj;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* Mapping between MySQL charset names and Java charset names. I've investigated placing these in a .properties file, but unfortunately under most appservers
* this complicates configuration because the security policy needs to be changed by the user to allow the driver to read them :(
*/
public class CharsetMapping {
public static final int MAP_SIZE = 2048; // Size of static maps
public static final String[] COLLATION_INDEX_TO_COLLATION_NAME;
public static final MysqlCharset[] COLLATION_INDEX_TO_CHARSET;
public static final Map<String, MysqlCharset> CHARSET_NAME_TO_CHARSET;
public static final Map<String, Integer> CHARSET_NAME_TO_COLLATION_INDEX;
private static final Map<String, List<MysqlCharset>> JAVA_ENCODING_UC_TO_MYSQL_CHARSET;
private static final Set<String> MULTIBYTE_ENCODINGS;
public static final Set<Integer> UTF8MB4_INDEXES;
private static final String MYSQL_CHARSET_NAME_armscii8 = "armscii8";
private static final String MYSQL_CHARSET_NAME_ascii = "ascii";
private static final String MYSQL_CHARSET_NAME_big5 = "big5";
private static final String MYSQL_CHARSET_NAME_binary = "binary";
private static final String MYSQL_CHARSET_NAME_cp1250 = "cp1250";
private static final String MYSQL_CHARSET_NAME_cp1251 = "cp1251";
private static final String MYSQL_CHARSET_NAME_cp1256 = "cp1256";
private static final String MYSQL_CHARSET_NAME_cp1257 = "cp1257";
private static final String MYSQL_CHARSET_NAME_cp850 = "cp850";
private static final String MYSQL_CHARSET_NAME_cp852 = "cp852";
private static final String MYSQL_CHARSET_NAME_cp866 = "cp866";
private static final String MYSQL_CHARSET_NAME_cp932 = "cp932";
private static final String MYSQL_CHARSET_NAME_dec8 = "dec8";
private static final String MYSQL_CHARSET_NAME_eucjpms = "eucjpms";
private static final String MYSQL_CHARSET_NAME_euckr = "euckr";
private static final String MYSQL_CHARSET_NAME_gb18030 = "gb18030";
private static final String MYSQL_CHARSET_NAME_gb2312 = "gb2312";
private static final String MYSQL_CHARSET_NAME_gbk = "gbk";
private static final String MYSQL_CHARSET_NAME_geostd8 = "geostd8";
private static final String MYSQL_CHARSET_NAME_greek = "greek";
private static final String MYSQL_CHARSET_NAME_hebrew = "hebrew";
private static final String MYSQL_CHARSET_NAME_hp8 = "hp8";
private static final String MYSQL_CHARSET_NAME_keybcs2 = "keybcs2";
private static final String MYSQL_CHARSET_NAME_koi8r = "koi8r";
private static final String MYSQL_CHARSET_NAME_koi8u = "koi8u";
private static final String MYSQL_CHARSET_NAME_latin1 = "latin1";
private static final String MYSQL_CHARSET_NAME_latin2 = "latin2";
private static final String MYSQL_CHARSET_NAME_latin5 = "latin5";
private static final String MYSQL_CHARSET_NAME_latin7 = "latin7";
private static final String MYSQL_CHARSET_NAME_macce = "macce";
private static final String MYSQL_CHARSET_NAME_macroman = "macroman";
private static final String MYSQL_CHARSET_NAME_sjis = "sjis";
private static final String MYSQL_CHARSET_NAME_swe7 = "swe7";
private static final String MYSQL_CHARSET_NAME_tis620 = "tis620";
private static final String MYSQL_CHARSET_NAME_ucs2 = "ucs2";
private static final String MYSQL_CHARSET_NAME_ujis = "ujis";
private static final String MYSQL_CHARSET_NAME_utf16 = "utf16";
private static final String MYSQL_CHARSET_NAME_utf16le = "utf16le";
private static final String MYSQL_CHARSET_NAME_utf32 = "utf32";
private static final String MYSQL_CHARSET_NAME_utf8 = "utf8";
private static final String MYSQL_CHARSET_NAME_utf8mb4 = "utf8mb4";
public static final String NOT_USED = MYSQL_CHARSET_NAME_latin1; // punting for not-used character sets
public static final String COLLATION_NOT_DEFINED = "none";
public static final int MYSQL_COLLATION_INDEX_utf8 = 33;
public static final int MYSQL_COLLATION_INDEX_binary = 63;
private static int numberOfEncodingsConfigured = 0;
static {
// complete list of mysql character sets and their corresponding java encoding names
MysqlCharset[] charset = new MysqlCharset[] { new MysqlCharset(MYSQL_CHARSET_NAME_ascii, 1, 0, new String[] { "US-ASCII", "ASCII" }),
new MysqlCharset(MYSQL_CHARSET_NAME_big5, 2, 0, new String[] { "Big5" }),
new MysqlCharset(MYSQL_CHARSET_NAME_gbk, 2, 0, new String[] { "GBK" }),
new MysqlCharset(MYSQL_CHARSET_NAME_sjis, 2, 0, new String[] { "SHIFT_JIS", "Cp943", "WINDOWS-31J" }), // SJIS is alias for SHIFT_JIS, Cp943 is rather a cp932 but we map it to sjis for years
new MysqlCharset(MYSQL_CHARSET_NAME_cp932, 2, 1, new String[] { "WINDOWS-31J" }), // MS932 is alias for WINDOWS-31J
new MysqlCharset(MYSQL_CHARSET_NAME_gb2312, 2, 0, new String[] { "GB2312" }),
new MysqlCharset(MYSQL_CHARSET_NAME_ujis, 3, 0, new String[] { "EUC_JP" }),
new MysqlCharset(MYSQL_CHARSET_NAME_eucjpms, 3, 0, new String[] { "EUC_JP_Solaris" }, new ServerVersion(5, 0, 3)), // "EUC_JP_Solaris = >5.0.3 eucjpms,"
new MysqlCharset(MYSQL_CHARSET_NAME_gb18030, 4, 0, new String[] { "GB18030" }, new ServerVersion(5, 7, 4)),
new MysqlCharset(MYSQL_CHARSET_NAME_euckr, 2, 0, new String[] { "EUC-KR" }),
new MysqlCharset(MYSQL_CHARSET_NAME_latin1, 1, 1, new String[] { "Cp1252", "ISO8859_1" }),
new MysqlCharset(MYSQL_CHARSET_NAME_swe7, 1, 0, new String[] { "Cp1252" }), // new mapping, Cp1252 ?
new MysqlCharset(MYSQL_CHARSET_NAME_hp8, 1, 0, new String[] { "Cp1252" }), // new mapping, Cp1252 ?
new MysqlCharset(MYSQL_CHARSET_NAME_dec8, 1, 0, new String[] { "Cp1252" }), // new mapping, Cp1252 ?
new MysqlCharset(MYSQL_CHARSET_NAME_armscii8, 1, 0, new String[] { "Cp1252" }), // new mapping, Cp1252 ?
new MysqlCharset(MYSQL_CHARSET_NAME_geostd8, 1, 0, new String[] { "Cp1252" }), // new mapping, Cp1252 ?
new MysqlCharset(MYSQL_CHARSET_NAME_latin2, 1, 0, new String[] { "ISO8859_2" }), // latin2 is an alias
new MysqlCharset(MYSQL_CHARSET_NAME_greek, 1, 0, new String[] { "ISO8859_7", "greek" }),
new MysqlCharset(MYSQL_CHARSET_NAME_latin7, 1, 0, new String[] { "ISO-8859-13" }), // was ISO8859_7, that's incorrect; also + "LATIN7 = latin7," is wrong java encoding name
new MysqlCharset(MYSQL_CHARSET_NAME_hebrew, 1, 0, new String[] { "ISO8859_8" }), // hebrew is an alias
new MysqlCharset(MYSQL_CHARSET_NAME_latin5, 1, 0, new String[] { "ISO8859_9" }), // LATIN5 is an alias
new MysqlCharset(MYSQL_CHARSET_NAME_cp850, 1, 0, new String[] { "Cp850", "Cp437" }),
new MysqlCharset(MYSQL_CHARSET_NAME_cp852, 1, 0, new String[] { "Cp852" }),
new MysqlCharset(MYSQL_CHARSET_NAME_keybcs2, 1, 0, new String[] { "Cp852" }), // new, Kamenicky encoding usually known as Cp895 but there is no official cp895 specification; close to Cp852, see http://ftp.muni.cz/pub/localization/charsets/cs-encodings-faq
new MysqlCharset(MYSQL_CHARSET_NAME_cp866, 1, 0, new String[] { "Cp866" }),
new MysqlCharset(MYSQL_CHARSET_NAME_koi8r, 1, 1, new String[] { "KOI8_R" }),
new MysqlCharset(MYSQL_CHARSET_NAME_koi8u, 1, 0, new String[] { "KOI8_R" }),
new MysqlCharset(MYSQL_CHARSET_NAME_tis620, 1, 0, new String[] { "TIS620" }),
new MysqlCharset(MYSQL_CHARSET_NAME_cp1250, 1, 0, new String[] { "Cp1250" }),
new MysqlCharset(MYSQL_CHARSET_NAME_cp1251, 1, 1, new String[] { "Cp1251" }),
new MysqlCharset(MYSQL_CHARSET_NAME_cp1256, 1, 0, new String[] { "Cp1256" }),
new MysqlCharset(MYSQL_CHARSET_NAME_cp1257, 1, 0, new String[] { "Cp1257" }),
new MysqlCharset(MYSQL_CHARSET_NAME_macroman, 1, 0, new String[] { "MacRoman" }),
new MysqlCharset(MYSQL_CHARSET_NAME_macce, 1, 0, new String[] { "MacCentralEurope" }),
new MysqlCharset(MYSQL_CHARSET_NAME_utf8, 3, 1, new String[] { "UTF-8" }),
new MysqlCharset(MYSQL_CHARSET_NAME_utf8mb4, 4, 0, new String[] { "UTF-8" }), // "UTF-8 = *> 5.5.2 utf8mb4,"
new MysqlCharset(MYSQL_CHARSET_NAME_ucs2, 2, 0, new String[] { "UnicodeBig" }),
new MysqlCharset(MYSQL_CHARSET_NAME_binary, 1, 1, new String[] { "ISO8859_1" }), // US-ASCII ?
new MysqlCharset(MYSQL_CHARSET_NAME_utf16, 4, 0, new String[] { "UTF-16" }),
new MysqlCharset(MYSQL_CHARSET_NAME_utf16le, 4, 0, new String[] { "UTF-16LE" }),
new MysqlCharset(MYSQL_CHARSET_NAME_utf32, 4, 0, new String[] { "UTF-32" })
};
HashMap<String, MysqlCharset> charsetNameToMysqlCharsetMap = new HashMap<>();
HashMap<String, List<MysqlCharset>> javaUcToMysqlCharsetMap = new HashMap<>();
Set<String> tempMultibyteEncodings = new HashSet<>(); // Character sets that we can't convert ourselves.
for (int i = 0; i < charset.length; i++) {
String charsetName = charset[i].charsetName;
charsetNameToMysqlCharsetMap.put(charsetName, charset[i]);
numberOfEncodingsConfigured += charset[i].javaEncodingsUc.size();
for (String encUC : charset[i].javaEncodingsUc) {
// fill javaUcToMysqlCharsetMap
List<MysqlCharset> charsets = javaUcToMysqlCharsetMap.get(encUC);
if (charsets == null) {
charsets = new ArrayList<>();
javaUcToMysqlCharsetMap.put(encUC, charsets);
}
charsets.add(charset[i]);
// fill multi-byte charsets
if (charset[i].mblen > 1) {
tempMultibyteEncodings.add(encUC);
}
}
}
CHARSET_NAME_TO_CHARSET = Collections.unmodifiableMap(charsetNameToMysqlCharsetMap);
JAVA_ENCODING_UC_TO_MYSQL_CHARSET = Collections.unmodifiableMap(javaUcToMysqlCharsetMap);
MULTIBYTE_ENCODINGS = Collections.unmodifiableSet(tempMultibyteEncodings);
// complete list of mysql collations and their corresponding character sets each element of collation[1]..collation[MAP_SIZE-1] must not be null
Collation[] collation = new Collation[MAP_SIZE];
collation[1] = new Collation(1, "big5_chinese_ci", 1, MYSQL_CHARSET_NAME_big5);
collation[2] = new Collation(2, "latin2_czech_cs", 0, MYSQL_CHARSET_NAME_latin2);
collation[3] = new Collation(3, "dec8_swedish_ci", 0, MYSQL_CHARSET_NAME_dec8);
collation[4] = new Collation(4, "cp850_general_ci", 1, MYSQL_CHARSET_NAME_cp850);
collation[5] = new Collation(5, "latin1_german1_ci", 1, MYSQL_CHARSET_NAME_latin1);
collation[6] = new Collation(6, "hp8_english_ci", 0, MYSQL_CHARSET_NAME_hp8);
collation[7] = new Collation(7, "koi8r_general_ci", 0, MYSQL_CHARSET_NAME_koi8r);
collation[8] = new Collation(8, "latin1_swedish_ci", 0, MYSQL_CHARSET_NAME_latin1);
collation[9] = new Collation(9, "latin2_general_ci", 1, MYSQL_CHARSET_NAME_latin2);
collation[10] = new Collation(10, "swe7_swedish_ci", 0, MYSQL_CHARSET_NAME_swe7);
collation[11] = new Collation(11, "ascii_general_ci", 0, MYSQL_CHARSET_NAME_ascii);
collation[12] = new Collation(12, "ujis_japanese_ci", 0, MYSQL_CHARSET_NAME_ujis);
collation[13] = new Collation(13, "sjis_japanese_ci", 0, MYSQL_CHARSET_NAME_sjis);
collation[14] = new Collation(14, "cp1251_bulgarian_ci", 0, MYSQL_CHARSET_NAME_cp1251);
collation[15] = new Collation(15, "latin1_danish_ci", 0, MYSQL_CHARSET_NAME_latin1);
collation[16] = new Collation(16, "hebrew_general_ci", 0, MYSQL_CHARSET_NAME_hebrew);
collation[18] = new Collation(18, "tis620_thai_ci", 0, MYSQL_CHARSET_NAME_tis620);
collation[19] = new Collation(19, "euckr_korean_ci", 0, MYSQL_CHARSET_NAME_euckr);
collation[20] = new Collation(20, "latin7_estonian_cs", 0, MYSQL_CHARSET_NAME_latin7);
collation[21] = new Collation(21, "latin2_hungarian_ci", 0, MYSQL_CHARSET_NAME_latin2);
collation[22] = new Collation(22, "koi8u_general_ci", 0, MYSQL_CHARSET_NAME_koi8u);
collation[23] = new Collation(23, "cp1251_ukrainian_ci", 0, MYSQL_CHARSET_NAME_cp1251);
collation[24] = new Collation(24, "gb2312_chinese_ci", 0, MYSQL_CHARSET_NAME_gb2312);
collation[25] = new Collation(25, "greek_general_ci", 0, MYSQL_CHARSET_NAME_greek);
collation[26] = new Collation(26, "cp1250_general_ci", 1, MYSQL_CHARSET_NAME_cp1250);
collation[27] = new Collation(27, "latin2_croatian_ci", 0, MYSQL_CHARSET_NAME_latin2);
collation[28] = new Collation(28, "gbk_chinese_ci", 1, MYSQL_CHARSET_NAME_gbk);
collation[29] = new Collation(29, "cp1257_lithuanian_ci", 0, MYSQL_CHARSET_NAME_cp1257);
collation[30] = new Collation(30, "latin5_turkish_ci", 1, MYSQL_CHARSET_NAME_latin5);
collation[31] = new Collation(31, "latin1_german2_ci", 0, MYSQL_CHARSET_NAME_latin1);
collation[32] = new Collation(32, "armscii8_general_ci", 0, MYSQL_CHARSET_NAME_armscii8);
collation[33] = new Collation(33, "utf8_general_ci", 1, MYSQL_CHARSET_NAME_utf8);
collation[34] = new Collation(34, "cp1250_czech_cs", 0, MYSQL_CHARSET_NAME_cp1250);
collation[35] = new Collation(35, "ucs2_general_ci", 1, MYSQL_CHARSET_NAME_ucs2);
collation[36] = new Collation(36, "cp866_general_ci", 1, MYSQL_CHARSET_NAME_cp866);
collation[37] = new Collation(37, "keybcs2_general_ci", 1, MYSQL_CHARSET_NAME_keybcs2);
collation[38] = new Collation(38, "macce_general_ci", 1, MYSQL_CHARSET_NAME_macce);
collation[39] = new Collation(39, "macroman_general_ci", 1, MYSQL_CHARSET_NAME_macroman);
collation[40] = new Collation(40, "cp852_general_ci", 1, MYSQL_CHARSET_NAME_cp852);
collation[41] = new Collation(41, "latin7_general_ci", 1, MYSQL_CHARSET_NAME_latin7);
collation[42] = new Collation(42, "latin7_general_cs", 0, MYSQL_CHARSET_NAME_latin7);
collation[43] = new Collation(43, "macce_bin", 0, MYSQL_CHARSET_NAME_macce);
collation[44] = new Collation(44, "cp1250_croatian_ci", 0, MYSQL_CHARSET_NAME_cp1250);
collation[45] = new Collation(45, "utf8mb4_general_ci", 1, MYSQL_CHARSET_NAME_utf8mb4);
collation[46] = new Collation(46, "utf8mb4_bin", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[47] = new Collation(47, "latin1_bin", 0, MYSQL_CHARSET_NAME_latin1);
collation[48] = new Collation(48, "latin1_general_ci", 0, MYSQL_CHARSET_NAME_latin1);
collation[49] = new Collation(49, "latin1_general_cs", 0, MYSQL_CHARSET_NAME_latin1);
collation[50] = new Collation(50, "cp1251_bin", 0, MYSQL_CHARSET_NAME_cp1251);
collation[51] = new Collation(51, "cp1251_general_ci", 1, MYSQL_CHARSET_NAME_cp1251);
collation[52] = new Collation(52, "cp1251_general_cs", 0, MYSQL_CHARSET_NAME_cp1251);
collation[53] = new Collation(53, "macroman_bin", 0, MYSQL_CHARSET_NAME_macroman);
collation[54] = new Collation(54, "utf16_general_ci", 1, MYSQL_CHARSET_NAME_utf16);
collation[55] = new Collation(55, "utf16_bin", 0, MYSQL_CHARSET_NAME_utf16);
collation[56] = new Collation(56, "utf16le_general_ci", 1, MYSQL_CHARSET_NAME_utf16le);
collation[57] = new Collation(57, "cp1256_general_ci", 1, MYSQL_CHARSET_NAME_cp1256);
collation[58] = new Collation(58, "cp1257_bin", 0, MYSQL_CHARSET_NAME_cp1257);
collation[59] = new Collation(59, "cp1257_general_ci", 1, MYSQL_CHARSET_NAME_cp1257);
collation[60] = new Collation(60, "utf32_general_ci", 1, MYSQL_CHARSET_NAME_utf32);
collation[61] = new Collation(61, "utf32_bin", 0, MYSQL_CHARSET_NAME_utf32);
collation[62] = new Collation(62, "utf16le_bin", 0, MYSQL_CHARSET_NAME_utf16le);
collation[63] = new Collation(63, "binary", 1, MYSQL_CHARSET_NAME_binary);
collation[64] = new Collation(64, "armscii8_bin", 0, MYSQL_CHARSET_NAME_armscii8);
collation[65] = new Collation(65, "ascii_bin", 0, MYSQL_CHARSET_NAME_ascii);
collation[66] = new Collation(66, "cp1250_bin", 0, MYSQL_CHARSET_NAME_cp1250);
collation[67] = new Collation(67, "cp1256_bin", 0, MYSQL_CHARSET_NAME_cp1256);
collation[68] = new Collation(68, "cp866_bin", 0, MYSQL_CHARSET_NAME_cp866);
collation[69] = new Collation(69, "dec8_bin", 0, MYSQL_CHARSET_NAME_dec8);
collation[70] = new Collation(70, "greek_bin", 0, MYSQL_CHARSET_NAME_greek);
collation[71] = new Collation(71, "hebrew_bin", 0, MYSQL_CHARSET_NAME_hebrew);
collation[72] = new Collation(72, "hp8_bin", 0, MYSQL_CHARSET_NAME_hp8);
collation[73] = new Collation(73, "keybcs2_bin", 0, MYSQL_CHARSET_NAME_keybcs2);
collation[74] = new Collation(74, "koi8r_bin", 0, MYSQL_CHARSET_NAME_koi8r);
collation[75] = new Collation(75, "koi8u_bin", 0, MYSQL_CHARSET_NAME_koi8u);
collation[76] = new Collation(76, "utf8_tolower_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[77] = new Collation(77, "latin2_bin", 0, MYSQL_CHARSET_NAME_latin2);
collation[78] = new Collation(78, "latin5_bin", 0, MYSQL_CHARSET_NAME_latin5);
collation[79] = new Collation(79, "latin7_bin", 0, MYSQL_CHARSET_NAME_latin7);
collation[80] = new Collation(80, "cp850_bin", 0, MYSQL_CHARSET_NAME_cp850);
collation[81] = new Collation(81, "cp852_bin", 0, MYSQL_CHARSET_NAME_cp852);
collation[82] = new Collation(82, "swe7_bin", 0, MYSQL_CHARSET_NAME_swe7);
collation[83] = new Collation(83, "utf8_bin", 0, MYSQL_CHARSET_NAME_utf8);
collation[84] = new Collation(84, "big5_bin", 0, MYSQL_CHARSET_NAME_big5);
collation[85] = new Collation(85, "euckr_bin", 0, MYSQL_CHARSET_NAME_euckr);
collation[86] = new Collation(86, "gb2312_bin", 0, MYSQL_CHARSET_NAME_gb2312);
collation[87] = new Collation(87, "gbk_bin", 0, MYSQL_CHARSET_NAME_gbk);
collation[88] = new Collation(88, "sjis_bin", 0, MYSQL_CHARSET_NAME_sjis);
collation[89] = new Collation(89, "tis620_bin", 0, MYSQL_CHARSET_NAME_tis620);
collation[90] = new Collation(90, "ucs2_bin", 0, MYSQL_CHARSET_NAME_ucs2);
collation[91] = new Collation(91, "ujis_bin", 0, MYSQL_CHARSET_NAME_ujis);
collation[92] = new Collation(92, "geostd8_general_ci", 0, MYSQL_CHARSET_NAME_geostd8);
collation[93] = new Collation(93, "geostd8_bin", 0, MYSQL_CHARSET_NAME_geostd8);
collation[94] = new Collation(94, "latin1_spanish_ci", 0, MYSQL_CHARSET_NAME_latin1);
collation[95] = new Collation(95, "cp932_japanese_ci", 1, MYSQL_CHARSET_NAME_cp932);
collation[96] = new Collation(96, "cp932_bin", 0, MYSQL_CHARSET_NAME_cp932);
collation[97] = new Collation(97, "eucjpms_japanese_ci", 1, MYSQL_CHARSET_NAME_eucjpms);
collation[98] = new Collation(98, "eucjpms_bin", 0, MYSQL_CHARSET_NAME_eucjpms);
collation[99] = new Collation(99, "cp1250_polish_ci", 0, MYSQL_CHARSET_NAME_cp1250);
collation[101] = new Collation(101, "utf16_unicode_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[102] = new Collation(102, "utf16_icelandic_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[103] = new Collation(103, "utf16_latvian_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[104] = new Collation(104, "utf16_romanian_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[105] = new Collation(105, "utf16_slovenian_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[106] = new Collation(106, "utf16_polish_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[107] = new Collation(107, "utf16_estonian_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[108] = new Collation(108, "utf16_spanish_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[109] = new Collation(109, "utf16_swedish_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[110] = new Collation(110, "utf16_turkish_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[111] = new Collation(111, "utf16_czech_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[112] = new Collation(112, "utf16_danish_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[113] = new Collation(113, "utf16_lithuanian_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[114] = new Collation(114, "utf16_slovak_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[115] = new Collation(115, "utf16_spanish2_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[116] = new Collation(116, "utf16_roman_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[117] = new Collation(117, "utf16_persian_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[118] = new Collation(118, "utf16_esperanto_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[119] = new Collation(119, "utf16_hungarian_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[120] = new Collation(120, "utf16_sinhala_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[121] = new Collation(121, "utf16_german2_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[122] = new Collation(122, "utf16_croatian_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[123] = new Collation(123, "utf16_unicode_520_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[124] = new Collation(124, "utf16_vietnamese_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[128] = new Collation(128, "ucs2_unicode_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[129] = new Collation(129, "ucs2_icelandic_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[130] = new Collation(130, "ucs2_latvian_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[131] = new Collation(131, "ucs2_romanian_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[132] = new Collation(132, "ucs2_slovenian_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[133] = new Collation(133, "ucs2_polish_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[134] = new Collation(134, "ucs2_estonian_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[135] = new Collation(135, "ucs2_spanish_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[136] = new Collation(136, "ucs2_swedish_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[137] = new Collation(137, "ucs2_turkish_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[138] = new Collation(138, "ucs2_czech_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[139] = new Collation(139, "ucs2_danish_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[140] = new Collation(140, "ucs2_lithuanian_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[141] = new Collation(141, "ucs2_slovak_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[142] = new Collation(142, "ucs2_spanish2_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[143] = new Collation(143, "ucs2_roman_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[144] = new Collation(144, "ucs2_persian_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[145] = new Collation(145, "ucs2_esperanto_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[146] = new Collation(146, "ucs2_hungarian_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[147] = new Collation(147, "ucs2_sinhala_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[148] = new Collation(148, "ucs2_german2_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[149] = new Collation(149, "ucs2_croatian_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[150] = new Collation(150, "ucs2_unicode_520_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[151] = new Collation(151, "ucs2_vietnamese_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[159] = new Collation(159, "ucs2_general_mysql500_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[160] = new Collation(160, "utf32_unicode_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[161] = new Collation(161, "utf32_icelandic_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[162] = new Collation(162, "utf32_latvian_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[163] = new Collation(163, "utf32_romanian_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[164] = new Collation(164, "utf32_slovenian_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[165] = new Collation(165, "utf32_polish_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[166] = new Collation(166, "utf32_estonian_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[167] = new Collation(167, "utf32_spanish_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[168] = new Collation(168, "utf32_swedish_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[169] = new Collation(169, "utf32_turkish_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[170] = new Collation(170, "utf32_czech_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[171] = new Collation(171, "utf32_danish_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[172] = new Collation(172, "utf32_lithuanian_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[173] = new Collation(173, "utf32_slovak_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[174] = new Collation(174, "utf32_spanish2_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[175] = new Collation(175, "utf32_roman_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[176] = new Collation(176, "utf32_persian_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[177] = new Collation(177, "utf32_esperanto_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[178] = new Collation(178, "utf32_hungarian_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[179] = new Collation(179, "utf32_sinhala_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[180] = new Collation(180, "utf32_german2_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[181] = new Collation(181, "utf32_croatian_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[182] = new Collation(182, "utf32_unicode_520_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[183] = new Collation(183, "utf32_vietnamese_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[192] = new Collation(192, "utf8_unicode_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[193] = new Collation(193, "utf8_icelandic_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[194] = new Collation(194, "utf8_latvian_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[195] = new Collation(195, "utf8_romanian_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[196] = new Collation(196, "utf8_slovenian_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[197] = new Collation(197, "utf8_polish_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[198] = new Collation(198, "utf8_estonian_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[199] = new Collation(199, "utf8_spanish_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[200] = new Collation(200, "utf8_swedish_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[201] = new Collation(201, "utf8_turkish_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[202] = new Collation(202, "utf8_czech_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[203] = new Collation(203, "utf8_danish_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[204] = new Collation(204, "utf8_lithuanian_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[205] = new Collation(205, "utf8_slovak_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[206] = new Collation(206, "utf8_spanish2_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[207] = new Collation(207, "utf8_roman_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[208] = new Collation(208, "utf8_persian_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[209] = new Collation(209, "utf8_esperanto_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[210] = new Collation(210, "utf8_hungarian_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[211] = new Collation(211, "utf8_sinhala_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[212] = new Collation(212, "utf8_german2_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[213] = new Collation(213, "utf8_croatian_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[214] = new Collation(214, "utf8_unicode_520_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[215] = new Collation(215, "utf8_vietnamese_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[223] = new Collation(223, "utf8_general_mysql500_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[224] = new Collation(224, "utf8mb4_unicode_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[225] = new Collation(225, "utf8mb4_icelandic_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[226] = new Collation(226, "utf8mb4_latvian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[227] = new Collation(227, "utf8mb4_romanian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[228] = new Collation(228, "utf8mb4_slovenian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[229] = new Collation(229, "utf8mb4_polish_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[230] = new Collation(230, "utf8mb4_estonian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[231] = new Collation(231, "utf8mb4_spanish_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[232] = new Collation(232, "utf8mb4_swedish_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[233] = new Collation(233, "utf8mb4_turkish_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[234] = new Collation(234, "utf8mb4_czech_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[235] = new Collation(235, "utf8mb4_danish_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[236] = new Collation(236, "utf8mb4_lithuanian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[237] = new Collation(237, "utf8mb4_slovak_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[238] = new Collation(238, "utf8mb4_spanish2_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[239] = new Collation(239, "utf8mb4_roman_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[240] = new Collation(240, "utf8mb4_persian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[241] = new Collation(241, "utf8mb4_esperanto_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[242] = new Collation(242, "utf8mb4_hungarian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[243] = new Collation(243, "utf8mb4_sinhala_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[244] = new Collation(244, "utf8mb4_german2_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[245] = new Collation(245, "utf8mb4_croatian_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[246] = new Collation(246, "utf8mb4_unicode_520_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[247] = new Collation(247, "utf8mb4_vietnamese_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[248] = new Collation(248, "gb18030_chinese_ci", 1, MYSQL_CHARSET_NAME_gb18030);
collation[249] = new Collation(249, "gb18030_bin", 0, MYSQL_CHARSET_NAME_gb18030);
collation[250] = new Collation(250, "gb18030_unicode_520_ci", 0, MYSQL_CHARSET_NAME_gb18030);
collation[255] = new Collation(255, "utf8mb4_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[256] = new Collation(256, "utf8mb4_de_pb_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[257] = new Collation(257, "utf8mb4_is_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[258] = new Collation(258, "utf8mb4_lv_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[259] = new Collation(259, "utf8mb4_ro_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[260] = new Collation(260, "utf8mb4_sl_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[261] = new Collation(261, "utf8mb4_pl_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[262] = new Collation(262, "utf8mb4_et_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[263] = new Collation(263, "utf8mb4_es_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[264] = new Collation(264, "utf8mb4_sv_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[265] = new Collation(265, "utf8mb4_tr_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[266] = new Collation(266, "utf8mb4_cs_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[267] = new Collation(267, "utf8mb4_da_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[268] = new Collation(268, "utf8mb4_lt_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[269] = new Collation(269, "utf8mb4_sk_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[270] = new Collation(270, "utf8mb4_es_trad_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[271] = new Collation(271, "utf8mb4_la_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[273] = new Collation(273, "utf8mb4_eo_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[274] = new Collation(274, "utf8mb4_hu_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[275] = new Collation(275, "utf8mb4_hr_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[277] = new Collation(277, "utf8mb4_vi_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[278] = new Collation(278, "utf8mb4_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[279] = new Collation(279, "utf8mb4_de_pb_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[280] = new Collation(280, "utf8mb4_is_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[281] = new Collation(281, "utf8mb4_lv_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[282] = new Collation(282, "utf8mb4_ro_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[283] = new Collation(283, "utf8mb4_sl_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[284] = new Collation(284, "utf8mb4_pl_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[285] = new Collation(285, "utf8mb4_et_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[286] = new Collation(286, "utf8mb4_es_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[287] = new Collation(287, "utf8mb4_sv_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[288] = new Collation(288, "utf8mb4_tr_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[289] = new Collation(289, "utf8mb4_cs_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[290] = new Collation(290, "utf8mb4_da_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[291] = new Collation(291, "utf8mb4_lt_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[292] = new Collation(292, "utf8mb4_sk_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[293] = new Collation(293, "utf8mb4_es_trad_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[294] = new Collation(294, "utf8mb4_la_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[296] = new Collation(296, "utf8mb4_eo_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[297] = new Collation(297, "utf8mb4_hu_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[298] = new Collation(298, "utf8mb4_hr_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[300] = new Collation(300, "utf8mb4_vi_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[303] = new Collation(303, "utf8mb4_ja_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[304] = new Collation(304, "utf8mb4_ja_0900_as_cs_ks", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[305] = new Collation(305, "utf8mb4_0900_as_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[306] = new Collation(306, "utf8mb4_ru_0900_ai_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[307] = new Collation(307, "utf8mb4_ru_0900_as_cs", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[326] = new Collation(326, "utf8mb4_test_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[327] = new Collation(327, "utf16_test_ci", 0, MYSQL_CHARSET_NAME_utf16);
collation[328] = new Collation(328, "utf8mb4_test_400_ci", 0, MYSQL_CHARSET_NAME_utf8mb4);
collation[336] = new Collation(336, "utf8_bengali_standard_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[337] = new Collation(337, "utf8_bengali_traditional_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[352] = new Collation(352, "utf8_phone_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[353] = new Collation(353, "utf8_test_ci", 0, MYSQL_CHARSET_NAME_utf8);
collation[354] = new Collation(354, "utf8_5624_1", 0, MYSQL_CHARSET_NAME_utf8);
collation[355] = new Collation(355, "utf8_5624_2", 0, MYSQL_CHARSET_NAME_utf8);
collation[356] = new Collation(356, "utf8_5624_3", 0, MYSQL_CHARSET_NAME_utf8);
collation[357] = new Collation(357, "utf8_5624_4", 0, MYSQL_CHARSET_NAME_utf8);
collation[358] = new Collation(358, "ucs2_test_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[359] = new Collation(359, "ucs2_vn_ci", 0, MYSQL_CHARSET_NAME_ucs2);
collation[360] = new Collation(360, "ucs2_5624_1", 0, MYSQL_CHARSET_NAME_ucs2);
collation[368] = new Collation(368, "utf8_5624_5", 0, MYSQL_CHARSET_NAME_utf8);
collation[391] = new Collation(391, "utf32_test_ci", 0, MYSQL_CHARSET_NAME_utf32);
collation[2047] = new Collation(2047, "utf8_maxuserid_ci", 0, MYSQL_CHARSET_NAME_utf8);
COLLATION_INDEX_TO_COLLATION_NAME = new String[MAP_SIZE];
COLLATION_INDEX_TO_CHARSET = new MysqlCharset[MAP_SIZE];
Map<String, Integer> charsetNameToCollationIndexMap = new TreeMap<>();
Map<String, Integer> charsetNameToCollationPriorityMap = new TreeMap<>();
Set<Integer> tempUTF8MB4Indexes = new HashSet<>();
Collation notUsedCollation = new Collation(0, COLLATION_NOT_DEFINED, 0, NOT_USED);
for (int i = 1; i < MAP_SIZE; i++) {
Collation coll = collation[i] != null ? collation[i] : notUsedCollation;
COLLATION_INDEX_TO_COLLATION_NAME[i] = coll.collationName;
COLLATION_INDEX_TO_CHARSET[i] = coll.mysqlCharset;
String charsetName = coll.mysqlCharset.charsetName;
if (!charsetNameToCollationIndexMap.containsKey(charsetName) || charsetNameToCollationPriorityMap.get(charsetName) < coll.priority) {
charsetNameToCollationIndexMap.put(charsetName, i);
charsetNameToCollationPriorityMap.put(charsetName, coll.priority);
}
// Filling indexes of utf8mb4 collations
if (charsetName.equals(MYSQL_CHARSET_NAME_utf8mb4)) {
tempUTF8MB4Indexes.add(i);
}
}
CHARSET_NAME_TO_COLLATION_INDEX = Collections.unmodifiableMap(charsetNameToCollationIndexMap);
UTF8MB4_INDEXES = Collections.unmodifiableSet(tempUTF8MB4Indexes);
collation = null;
}
public final static String getMysqlCharsetForJavaEncoding(String javaEncoding, ServerVersion version) {
List<MysqlCharset> mysqlCharsets = CharsetMapping.JAVA_ENCODING_UC_TO_MYSQL_CHARSET.get(javaEncoding.toUpperCase(Locale.ENGLISH));
if (mysqlCharsets != null) {
Iterator<MysqlCharset> iter = mysqlCharsets.iterator();
MysqlCharset currentChoice = null;
while (iter.hasNext()) {
MysqlCharset charset = iter.next();
if (version == null) {
// Take the first one we get
return charset.charsetName;
}
if (currentChoice == null || currentChoice.minimumVersion.compareTo(charset.minimumVersion) < 0
|| currentChoice.priority < charset.priority && currentChoice.minimumVersion.compareTo(charset.minimumVersion) == 0) {
if (charset.isOkayForVersion(version)) {
currentChoice = charset;
}
}
}
if (currentChoice != null) {
return currentChoice.charsetName;
}
}
return null;
}
public static int getCollationIndexForJavaEncoding(String javaEncoding, ServerVersion version) {
String charsetName = getMysqlCharsetForJavaEncoding(javaEncoding, version);
if (charsetName != null) {
Integer ci = CHARSET_NAME_TO_COLLATION_INDEX.get(charsetName);
if (ci != null) {
return ci.intValue();
}
}
return 0;
}
public static String getMysqlCharsetNameForCollationIndex(Integer collationIndex) {
if (collationIndex != null && collationIndex > 0 && collationIndex < MAP_SIZE) {
return COLLATION_INDEX_TO_CHARSET[collationIndex].charsetName;
}
return null;
}
/**
* MySQL charset could map to several Java encodings.
* So here we choose the one according to next rules:
* <ul>
* <li>if there is no static mapping for this charset then return javaEncoding value as is because this
* could be a custom charset for example
* <li>if static mapping exists and javaEncoding equals to one of Java encoding canonical names or aliases available
* for this mapping then javaEncoding value as is; this is required when result should match to connection encoding, for example if connection encoding is
* Cp943 we must avoid getting SHIFT_JIS for sjis mysql charset
* <li>if static mapping exists and javaEncoding doesn't match any Java encoding canonical
* names or aliases available for this mapping then return default Java encoding (the first in mapping list)
* </ul>
*
* @param mysqlCharsetName
* MySQL charset name
* @param javaEncoding
* fall-back java encoding name
* @return java encoding name
*/
public static String getJavaEncodingForMysqlCharset(String mysqlCharsetName, String javaEncoding) {
String res = javaEncoding;
MysqlCharset cs = CHARSET_NAME_TO_CHARSET.get(mysqlCharsetName);
if (cs != null) {
res = cs.getMatchingJavaEncoding(javaEncoding);
}
return res;
}
public static String getJavaEncodingForMysqlCharset(String mysqlCharsetName) {
return getJavaEncodingForMysqlCharset(mysqlCharsetName, null);
}
public static String getJavaEncodingForCollationIndex(Integer collationIndex, String javaEncoding) {
if (collationIndex != null && collationIndex > 0 && collationIndex < MAP_SIZE) {
MysqlCharset cs = COLLATION_INDEX_TO_CHARSET[collationIndex];
return cs.getMatchingJavaEncoding(javaEncoding);
}
return null;
}
public static String getJavaEncodingForCollationIndex(Integer collationIndex) {
return getJavaEncodingForCollationIndex(collationIndex, null);
}
public final static int getNumberOfCharsetsConfigured() {
return numberOfEncodingsConfigured;
}
/**
* Does the character set contain multi-byte encoded characters.
*
* @param javaEncodingName
* java encoding name
* @return true if the character set contains multi-byte encoded characters.
*/
final public static boolean isMultibyteCharset(String javaEncodingName) {
return MULTIBYTE_ENCODINGS.contains(javaEncodingName.toUpperCase(Locale.ENGLISH));
}
public static int getMblen(String charsetName) {
if (charsetName != null) {
MysqlCharset cs = CHARSET_NAME_TO_CHARSET.get(charsetName);
if (cs != null) {
return cs.mblen;
}
}
return 0;
}
}
class MysqlCharset {
public final String charsetName;
public final int mblen;
public final int priority;
public final List<String> javaEncodingsUc = new ArrayList<>();
public final ServerVersion minimumVersion;
/**
* Constructs MysqlCharset object
*
* @param charsetName
* MySQL charset name
* @param mblen
* Max number of bytes per character
* @param priority
* MysqlCharset with highest value of this param will be used for Java encoding --> Mysql charsets conversion.
* @param javaEncodings
* List of Java encodings corresponding to this MySQL charset; the first name in list is the default for mysql --> java data conversion
*/
public MysqlCharset(String charsetName, int mblen, int priority, String[] javaEncodings) {
this(charsetName, mblen, priority, javaEncodings, new ServerVersion(0, 0, 0));
}
private void addEncodingMapping(String encoding) {
String encodingUc = encoding.toUpperCase(Locale.ENGLISH);
if (!this.javaEncodingsUc.contains(encodingUc)) {
this.javaEncodingsUc.add(encodingUc);
}
}
public MysqlCharset(String charsetName, int mblen, int priority, String[] javaEncodings, ServerVersion minimumVersion) {
this.charsetName = charsetName;
this.mblen = mblen;
this.priority = priority;
for (int i = 0; i < javaEncodings.length; i++) {
String encoding = javaEncodings[i];
try {
Charset cs = Charset.forName(encoding);
addEncodingMapping(cs.name());
Set<String> als = cs.aliases();
Iterator<String> ali = als.iterator();
while (ali.hasNext()) {
addEncodingMapping(ali.next());
}
} catch (Exception e) {
// if there is no support of this charset in JVM it's still possible to use our converter for 1-byte charsets
if (mblen == 1) {
addEncodingMapping(encoding);
}
}
}
if (this.javaEncodingsUc.size() == 0) {
if (mblen > 1) {
addEncodingMapping("UTF-8");
} else {
addEncodingMapping("Cp1252");
}
}
this.minimumVersion = minimumVersion;
}
@Override
public String toString() {
StringBuilder asString = new StringBuilder();
asString.append("[");
asString.append("charsetName=");
asString.append(this.charsetName);
asString.append(",mblen=");
asString.append(this.mblen);
// asString.append(",javaEncoding=");
// asString.append(this.javaEncodings.toString());
asString.append("]");
return asString.toString();
}
boolean isOkayForVersion(ServerVersion version) {
return version.meetsMinimum(this.minimumVersion);
}
/**
* If javaEncoding parameter value is one of available java encodings for this charset
* then returns javaEncoding value as is. Otherwise returns first available java encoding name.
*
* @param javaEncoding
* java encoding name
* @return java encoding name
*/
String getMatchingJavaEncoding(String javaEncoding) {
if (javaEncoding != null && this.javaEncodingsUc.contains(javaEncoding.toUpperCase(Locale.ENGLISH))) {
return javaEncoding;
}
return this.javaEncodingsUc.get(0);
}
}
class Collation {
public final int index;
public final String collationName;
public final int priority;
public final MysqlCharset mysqlCharset;
public Collation(int index, String collationName, int priority, String charsetName) {
this.index = index;
this.collationName = collationName;
this.priority = priority;
this.mysqlCharset = CharsetMapping.CHARSET_NAME_TO_CHARSET.get(charsetName);
}
@Override
public String toString() {
StringBuilder asString = new StringBuilder();
asString.append("[");
asString.append("index=");
asString.append(this.index);
asString.append(",collationName=");
asString.append(this.collationName);
asString.append(",charsetName=");
asString.append(this.mysqlCharset.charsetName);
asString.append(",javaCharsetName=");
asString.append(this.mysqlCharset.getMatchingJavaEncoding(null));
asString.append("]");
return asString.toString();
}
}
| lamsfoundation/lams | 3rdParty_sources/mysql-connector/com/mysql/cj/CharsetMapping.java | Java | gpl-2.0 | 50,215 |
package main
import (
"fmt"
"time"
"flag"
// "os/exec"
"log"
// "bytes"
// "os"
// "syscall"
"github.com/samuel/go-zookeeper/zk"
"crypto/sha256"
"encoding/base64"
"strings"
"github.com/satori/go.uuid"
)
func zkConnect() *zk.Conn {
zks := []string{"wz-zk-1.dol.cx:2181", "wz-zk-2.dol.cx:2181", "wz-zk-3.dol.cx:2181"}
conn, _, err := zk.Connect(zks, time.Second)
if err != nil { log.Fatal(err) }
return conn
}
func zkSimpleParty(task_name string) error {
acl := zk.WorldACL(zk.PermAll)
var err error = nil
my_uuid := uuid.NewV4().String()
hasher := sha256.New()
task_hash := base64.URLEncoding.EncodeToString( hasher.Sum([]byte(task_name)) )
zk_path := strings.Join ([]string{"/cron_", task_hash}, "")
zk_path_uuid := strings.Join ([]string{zk_path, "/", my_uuid}, "")
log.Print(zk_path, "\n", zk_path_uuid)
zk_c := zkConnect()
defer zk_c.Close()
exist, stat, err := zk_c.Exists(zk_path)
if err != nil { log.Fatal(err); return err }
if exist != true {
msg, err := zk_c.Create(zk_path, []byte{}, 0, acl)
if err != nil { log.Fatal(err); return err}
log.Print(msg)
} else {
if stat.NumChildren == 0 {
if err := zk_c.Delete(zk_path, -1) ; err != nil { log.Fatal(err) }
msg, err := zk_c.Create(zk_path, []byte{}, 0, acl)
if err != nil { log.Fatal(err); return err }
log.Print(msg)
}
}
msg, err := zk_c.Create(zk_path_uuid, []byte{}, int32(zk.FlagEphemeral + zk.FlagSequence), acl)
if err != nil { log.Fatal(err); return err }
log.Print(msg)
children, stat, err := zk_c.Children(zk_path)
if err != nil { log.Fatal(err); return err }
log.Print(fmt.Sprintf("%+v %+v\n", children, stat))
return err
}
func main() {
var task_name = flag.String("task", "test", "task name")
// var task_timer = flag.Int("timer", 0, "task timer")
// var app_name = flag.String("app", "./test.sh", "app")
flag.Parse()
for i:=0; i<30000000; i++ { go zkSimpleParty(*task_name) }
}
| a15y87/go-stdin-logger | test-zk.go | GO | gpl-2.0 | 1,931 |
<?php
/**
* @package HikaShop for Joomla!
* @version 2.4.0
* @author hikashop.com
* @copyright (C) 2010-2015 HIKARI SOFTWARE. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><?php
class hikashopTax_zoneType{
function load(){
$this->values = array();
$this->values[] = JHTML::_('select.option', 'billing',JText::_('BILLING'));
$this->values[] = JHTML::_('select.option', 'shipping',JText::_('SHIPPING'));
}
function display($map,$value){
$this->load();
return JHTML::_('select.genericlist', $this->values, $map, 'class="inputbox" size="1"', 'value', 'text', $value );
}
}
| metalwork/anphates | administrator/components/com_hikashop/types/tax_zone.php | PHP | gpl-2.0 | 680 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_finder
*
* @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\Component\Finder\Administrator\Indexer\Parser;
defined('_JEXEC') or die;
use Joomla\Component\Finder\Administrator\Indexer\Parser;
/**
* Text Parser class for the Finder indexer package.
*
* @since 2.5
*/
class Txt extends Parser
{
/**
* Method to process Text input and extract the plain text.
*
* @param string $input The input to process.
*
* @return string The plain text input.
*
* @since 2.5
*/
protected function process($input)
{
return $input;
}
}
| astridx/joomla-cms | administrator/components/com_finder/Indexer/Parser/Txt.php | PHP | gpl-2.0 | 762 |
// PabstMirror
// async send msg to a discord webhook
// Requires CPR (curl wrapper) - https://github.com/whoshuu/cpr (and put libcurl.dll in base arma folder)
#include <iostream>
#include <String>
#include <future>
#include "cpr/cpr.h"
constexpr auto VERSION_STR = "v1.0.1";
extern "C" {
__declspec(dllexport) void __stdcall RVExtension(char* output, int outputSize, const char* function);
__declspec(dllexport) void __stdcall RVExtensionVersion(char* output, int outputSize);
__declspec (dllexport) void __stdcall RVExtensionRegisterCallback(int(*callbackProc)(char const* name, char const* function, char const* data));
}
std::function<int(char const*, char const*, char const*)> callbackPtr = [](char const*, char const*, char const*) { return 0; };
std::future<void> fWorker;
void __stdcall RVExtensionRegisterCallback(int(*callbackProc)(char const* name, char const* function, char const* data)) {
callbackPtr = callbackProc;
}
void postThread(const char * msg) {
cpr::Response r = cpr::Post(
cpr::Url{ "https://discordapp.com/api/webhooks/x/y" }, // don't commit this lol
cpr::Payload{ {"content", msg}, {"username", "POTATO"} }
);
std::stringstream outputStr;
outputStr << "Finished with code [" << r.status_code << "]"; // 200/204 is good, 400 is bad
callbackPtr("POTATO_webhook", "Webhook", outputStr.str().c_str());
}
void __stdcall RVExtensionVersion(char* output, int outputSize) {
strncpy(output, VERSION_STR, outputSize);
}
void __stdcall RVExtension(char* output, int outputSize, const char* function) {
if (!strcmp(function, "version")) {
RVExtensionVersion(output, outputSize);
return;
}
if (fWorker.valid()) { fWorker.wait_for(std::chrono::seconds(1)); } // if worker is busy wait for finish
fWorker = std::async(std::launch::async, &postThread, function); // start async so we don't block arma (~200ms to finish)
strncpy(output, "Dispatched Webhook", outputSize);
}
| BourbonWarfare/POTATO | backend/discordWebhook/Webhook.cpp | C++ | gpl-2.0 | 1,990 |
/* Copyright (c) 2002-2012 Croteam Ltd.
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of 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. */
#include "StdAfx.h"
extern CGame *_pGame;
extern INDEX gam_iQuickStartDifficulty;
extern INDEX gam_iQuickStartMode;
extern INDEX gam_iStartDifficulty;
extern INDEX gam_iStartMode;
// initialize game and load settings
void CGame::Initialize(const CTFileName &fnGameSettings)
{
gm_fnSaveFileName = fnGameSettings;
InitInternal();
}
// save settings and cleanup
void CGame::End(void)
{
EndInternal();
}
// automaticaly manage input enable/disable toggling
static BOOL _bInputEnabled = FALSE;
void UpdateInputEnabledState(CViewPort *pvp)
{
// input should be enabled if application is active
// and no menu is active and no console is active
BOOL bShouldBeEnabled = _pGame->gm_csConsoleState==CS_OFF && _pGame->gm_csComputerState==CS_OFF;
// if should be turned off
if (!bShouldBeEnabled && _bInputEnabled) {
// disable it
_pInput->DisableInput();
// remember new state
_bInputEnabled = FALSE;
}
// if should be turned on
if (bShouldBeEnabled && !_bInputEnabled) {
// enable it
_pInput->EnableInput(pvp);
// remember new state
_bInputEnabled = TRUE;
}
}
// automaticaly manage pause toggling
static void UpdatePauseState(void)
{
BOOL bShouldPause =
_pGame->gm_csConsoleState ==CS_ON || _pGame->gm_csConsoleState ==CS_TURNINGON || _pGame->gm_csConsoleState ==CS_TURNINGOFF ||
_pGame->gm_csComputerState==CS_ON || _pGame->gm_csComputerState==CS_TURNINGON || _pGame->gm_csComputerState==CS_TURNINGOFF;
_pNetwork->SetLocalPause(bShouldPause);
}
// run a quicktest game from within editor
void CGame::QuickTest(const CTFileName &fnMapName,
CDrawPort *pdp, CViewPort *pvp)
{
#ifdef PLATFORM_WIN32
UINT uiMessengerMsg = RegisterWindowMessage("Croteam Messenger: Incoming Message");
#else
UINT uiMessengerMsg = 0x7337d00d;
#endif
EnableLoadingHook(pdp);
// quick start game with the world
gm_strNetworkProvider = "Local";
gm_aiStartLocalPlayers[0] = gm_iWEDSinglePlayer;
gm_aiStartLocalPlayers[1] = -1;
gm_aiStartLocalPlayers[2] = -1;
gm_aiStartLocalPlayers[3] = -1;
gm_CurrentSplitScreenCfg = CGame::SSC_PLAY1;
// set properties for a quick start session
CSessionProperties sp;
SetQuickStartSession(sp);
// start the game
if( !NewGame( fnMapName, fnMapName, sp)) {
DisableLoadingHook();
return;
}
// enable input
_pInput->EnableInput(pvp);
// initialy, game is running
BOOL bRunning = TRUE;
// while it is still running
while( bRunning)
{
// while there are any messages in the message queue
MSG msg;
while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE)) {
// if it is not a mouse message
if( !(msg.message>=WM_MOUSEFIRST && msg.message<=WM_MOUSELAST)) {
// if not system key messages
if( !(msg.message==WM_KEYDOWN && msg.wParam==VK_F10
||msg.message==WM_SYSKEYDOWN)) {
// dispatch it
TranslateMessage(&msg);
}
// if paint message
if( msg.message==WM_PAINT) {
// dispatch it
DispatchMessage(&msg);
}
}
// if should stop
if ((msg.message==WM_QUIT)
||(msg.message==WM_CLOSE)
||(msg.message==WM_KEYDOWN && msg.wParam==VK_ESCAPE)
||(msg.message==WM_ACTIVATE)
||(msg.message==WM_CANCELMODE)
||(msg.message==WM_KILLFOCUS)
||(msg.message==WM_ACTIVATEAPP)) {
// stop running
bRunning = FALSE;
break;
}
if (msg.message==uiMessengerMsg)
{
if(!_pNetwork->IsPaused())
{
// pause it
_pNetwork->TogglePause();
}
char *pachrTemp=getenv("TEMP");
if( pachrTemp!=NULL)
{
FILE *pfileMessage=fopen(CTString(pachrTemp)+"Messenger.msg","r");
if( pfileMessage!=NULL)
{
char achrMessage[1024];
char *pachrMessage=fgets( achrMessage, 1024-1, pfileMessage);
if( pachrMessage!=NULL)
{
CPrintF("%s",pachrMessage);
}
}
}
}
// if pause pressed
if (msg.message==WM_KEYDOWN && msg.wParam==VK_PAUSE &&
_pGame->gm_csConsoleState==CS_OFF && _pGame->gm_csComputerState==CS_OFF) {
// toggle pause
_pNetwork->TogglePause();
}
if(msg.message==WM_KEYDOWN &&
// !!! FIXME: rcg11162001 This sucks.
#ifdef PLATFORM_UNIX
(msg.unicode == '~'
#else
(MapVirtualKey(msg.wParam, 0)==41 // scan code for '~'
#endif
||msg.wParam==VK_F1)) {
if (_pGame->gm_csConsoleState==CS_OFF || _pGame->gm_csConsoleState==CS_TURNINGOFF) {
_pGame->gm_csConsoleState = CS_TURNINGON;
} else {
_pGame->gm_csConsoleState = CS_TURNINGOFF;
}
}
extern INDEX con_bTalk;
if (con_bTalk && _pGame->gm_csConsoleState==CS_OFF) {
con_bTalk = FALSE;
_pGame->gm_csConsoleState = CS_TALK;
}
if (msg.message==WM_KEYDOWN) {
ConsoleKeyDown(msg);
if (_pGame->gm_csConsoleState!=CS_ON) {
ComputerKeyDown(msg);
}
} else if (msg.message==WM_KEYUP) {
// special handler for talk (not to invoke return key bind)
if( msg.wParam==VK_RETURN && _pGame->gm_csConsoleState==CS_TALK) _pGame->gm_csConsoleState = CS_OFF;
} else if (msg.message==WM_CHAR) {
ConsoleChar(msg);
}
if (msg.message==WM_LBUTTONDOWN
||msg.message==WM_RBUTTONDOWN
||msg.message==WM_LBUTTONDBLCLK
||msg.message==WM_RBUTTONDBLCLK
||msg.message==WM_LBUTTONUP
||msg.message==WM_RBUTTONUP) {
if (_pGame->gm_csConsoleState!=CS_ON) {
ComputerKeyDown(msg);
}
}
}
// get real cursor position
if (_pGame->gm_csComputerState != CS_OFF) {
POINT pt;
::GetCursorPos(&pt);
::ScreenToClient(pvp->vp_hWnd, &pt);
ComputerMouseMove(pt.x, pt.y);
}
UpdatePauseState();
UpdateInputEnabledState(pvp);
// if playing a demo and it is finished
if (_pNetwork->IsDemoPlayFinished()) {
// stop running
bRunning = FALSE;
}
// do the main game loop
GameMainLoop();
// redraw the view
if (pdp->Lock()) {
// if current view preferences will not clear the background, clear it here
if( _wrpWorldRenderPrefs.GetPolygonsFillType() == CWorldRenderPrefs::FT_NONE) {
// clear background
pdp->Fill(C_BLACK| CT_OPAQUE);
pdp->FillZBuffer(ZBUF_BACK);
}
// redraw view
if (_pGame->gm_csComputerState != CS_ON) {
GameRedrawView(pdp, (_pGame->gm_csConsoleState==CS_ON)?0:GRV_SHOWEXTRAS);
}
ComputerRender(pdp);
ConsoleRender(pdp);
pdp->Unlock();
// show it
pvp->SwapBuffers();
}
}
if (_pGame->gm_csConsoleState != CS_OFF) {
_pGame->gm_csConsoleState = CS_TURNINGOFF;
}
if (_pGame->gm_csComputerState != CS_OFF) {
_pGame->gm_csComputerState = CS_TURNINGOFF;
cmp_ppenPlayer = NULL;
}
_pInput->DisableInput();
StopGame();
DisableLoadingHook();
}
| stevenc99/Serious-Engine | Sources/GameMP/WEDInterface.cpp | C++ | gpl-2.0 | 7,788 |
using MongoDB.Driver;
using Repositories.Identity;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace Repositories.Database
{
internal static class MyMongoDB
{
private const string UserCollectionString = "AspNetUsers";
private static MongoDatabase database = null;
// TODO: Can this be removed?
public static MongoCollection<MyIdentityUser> UserCollection
{
get
{
return database.GetCollection<MyIdentityUser>(UserCollectionString);
}
}
public static MongoDatabase Database
{
get
{
if(database == null)
{
CreateDBConnection();
}
return database;
}
}
private static void CreateDBConnection()
{
var connectionstring = ConfigurationManager.AppSettings.Get("MONGOLAB_URI");
var url = new MongoUrl(connectionstring);
var client = new MongoClient(url);
var server = client.GetServer();
database = server.GetDatabase(url.DatabaseName);
}
}
}
| JohnDRoach/MGCCPointScore | Repositories/Database/Internal/MyMongoDB.cs | C# | gpl-2.0 | 1,258 |
/***************************************************************************
qgsgeometry.cpp - Geometry (stored as Open Geospatial Consortium WKB)
-------------------------------------------------------------------
Date : 02 May 2005
Copyright : (C) 2005 by Brendan Morley
email : morb at ozemail dot com dot au
***************************************************************************
* *
* 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 <limits>
#include <cstdarg>
#include <cstdio>
#include <cmath>
#include <nlohmann/json.hpp>
#include "qgis.h"
#include "qgsgeometry.h"
#include "qgsgeometryeditutils.h"
#include "qgsgeometryfactory.h"
#include "qgsgeometrymakevalid.h"
#include "qgsgeometryutils.h"
#include "qgsinternalgeometryengine.h"
#include "qgsgeos.h"
#include "qgsapplication.h"
#include "qgslogger.h"
#include "qgsmaptopixel.h"
#include "qgsmessagelog.h"
#include "qgspointxy.h"
#include "qgsrectangle.h"
#include "qgsvectorlayer.h"
#include "qgsgeometryvalidator.h"
#include "qgsmulticurve.h"
#include "qgsmultilinestring.h"
#include "qgsmultipoint.h"
#include "qgsmultipolygon.h"
#include "qgsmultisurface.h"
#include "qgspoint.h"
#include "qgspolygon.h"
#include "qgslinestring.h"
#include "qgscircle.h"
#include "qgscurve.h"
struct QgsGeometryPrivate
{
QgsGeometryPrivate(): ref( 1 ) {}
QAtomicInt ref;
std::unique_ptr< QgsAbstractGeometry > geometry;
};
QgsGeometry::QgsGeometry()
: d( new QgsGeometryPrivate() )
{
}
QgsGeometry::~QgsGeometry()
{
if ( !d->ref.deref() )
delete d;
}
QgsGeometry::QgsGeometry( QgsAbstractGeometry *geom )
: d( new QgsGeometryPrivate() )
{
d->geometry.reset( geom );
d->ref = QAtomicInt( 1 );
}
QgsGeometry::QgsGeometry( std::unique_ptr<QgsAbstractGeometry> geom )
: d( new QgsGeometryPrivate() )
{
d->geometry = std::move( geom );
d->ref = QAtomicInt( 1 );
}
QgsGeometry::QgsGeometry( const QgsGeometry &other )
{
d = other.d;
mLastError = other.mLastError;
d->ref.ref();
}
QgsGeometry &QgsGeometry::operator=( QgsGeometry const &other )
{
if ( !d->ref.deref() )
{
delete d;
}
mLastError = other.mLastError;
d = other.d;
d->ref.ref();
return *this;
}
void QgsGeometry::detach()
{
if ( d->ref <= 1 )
return;
std::unique_ptr< QgsAbstractGeometry > cGeom;
if ( d->geometry )
cGeom.reset( d->geometry->clone() );
reset( std::move( cGeom ) );
}
void QgsGeometry::reset( std::unique_ptr<QgsAbstractGeometry> newGeometry )
{
if ( d->ref > 1 )
{
( void )d->ref.deref();
d = new QgsGeometryPrivate();
}
d->geometry = std::move( newGeometry );
}
const QgsAbstractGeometry *QgsGeometry::constGet() const
{
return d->geometry.get();
}
QgsAbstractGeometry *QgsGeometry::get()
{
detach();
return d->geometry.get();
}
void QgsGeometry::set( QgsAbstractGeometry *geometry )
{
if ( d->geometry.get() == geometry )
{
return;
}
reset( std::unique_ptr< QgsAbstractGeometry >( geometry ) );
}
bool QgsGeometry::isNull() const
{
return !d->geometry;
}
QgsGeometry QgsGeometry::fromWkt( const QString &wkt )
{
std::unique_ptr< QgsAbstractGeometry > geom = QgsGeometryFactory::geomFromWkt( wkt );
if ( !geom )
{
return QgsGeometry();
}
return QgsGeometry( std::move( geom ) );
}
QgsGeometry QgsGeometry::fromPointXY( const QgsPointXY &point )
{
std::unique_ptr< QgsAbstractGeometry > geom( QgsGeometryFactory::fromPointXY( point ) );
if ( geom )
{
return QgsGeometry( geom.release() );
}
return QgsGeometry();
}
QgsGeometry QgsGeometry::fromPolylineXY( const QgsPolylineXY &polyline )
{
std::unique_ptr< QgsAbstractGeometry > geom = QgsGeometryFactory::fromPolylineXY( polyline );
if ( geom )
{
return QgsGeometry( std::move( geom ) );
}
return QgsGeometry();
}
QgsGeometry QgsGeometry::fromPolyline( const QgsPolyline &polyline )
{
return QgsGeometry( qgis::make_unique< QgsLineString >( polyline ) );
}
QgsGeometry QgsGeometry::fromPolygonXY( const QgsPolygonXY &polygon )
{
std::unique_ptr< QgsPolygon > geom = QgsGeometryFactory::fromPolygonXY( polygon );
if ( geom )
{
return QgsGeometry( std::move( geom.release() ) );
}
return QgsGeometry();
}
QgsGeometry QgsGeometry::fromMultiPointXY( const QgsMultiPointXY &multipoint )
{
std::unique_ptr< QgsMultiPoint > geom = QgsGeometryFactory::fromMultiPointXY( multipoint );
if ( geom )
{
return QgsGeometry( std::move( geom ) );
}
return QgsGeometry();
}
QgsGeometry QgsGeometry::fromMultiPolylineXY( const QgsMultiPolylineXY &multiline )
{
std::unique_ptr< QgsMultiLineString > geom = QgsGeometryFactory::fromMultiPolylineXY( multiline );
if ( geom )
{
return QgsGeometry( std::move( geom ) );
}
return QgsGeometry();
}
QgsGeometry QgsGeometry::fromMultiPolygonXY( const QgsMultiPolygonXY &multipoly )
{
std::unique_ptr< QgsMultiPolygon > geom = QgsGeometryFactory::fromMultiPolygonXY( multipoly );
if ( geom )
{
return QgsGeometry( std::move( geom ) );
}
return QgsGeometry();
}
QgsGeometry QgsGeometry::fromRect( const QgsRectangle &rect )
{
std::unique_ptr< QgsLineString > ext = qgis::make_unique< QgsLineString >(
QVector< double >() << rect.xMinimum()
<< rect.xMaximum()
<< rect.xMaximum()
<< rect.xMinimum()
<< rect.xMinimum(),
QVector< double >() << rect.yMinimum()
<< rect.yMinimum()
<< rect.yMaximum()
<< rect.yMaximum()
<< rect.yMinimum() );
std::unique_ptr< QgsPolygon > polygon = qgis::make_unique< QgsPolygon >();
polygon->setExteriorRing( ext.release() );
return QgsGeometry( std::move( polygon ) );
}
QgsGeometry QgsGeometry::collectGeometry( const QVector< QgsGeometry > &geometries )
{
QgsGeometry collected;
for ( const QgsGeometry &g : geometries )
{
if ( collected.isNull() )
{
collected = g;
collected.convertToMultiType();
}
else
{
if ( g.isMultipart() )
{
for ( auto p = g.const_parts_begin(); p != g.const_parts_end(); ++p )
{
collected.addPart( ( *p )->clone() );
}
}
else
{
collected.addPart( g );
}
}
}
return collected;
}
QgsGeometry QgsGeometry::createWedgeBuffer( const QgsPoint ¢er, const double azimuth, const double angularWidth, const double outerRadius, const double innerRadius )
{
if ( std::abs( angularWidth ) >= 360.0 )
{
std::unique_ptr< QgsCompoundCurve > outerCc = qgis::make_unique< QgsCompoundCurve >();
QgsCircle outerCircle = QgsCircle( center, outerRadius );
outerCc->addCurve( outerCircle.toCircularString() );
std::unique_ptr< QgsCurvePolygon > cp = qgis::make_unique< QgsCurvePolygon >();
cp->setExteriorRing( outerCc.release() );
if ( !qgsDoubleNear( innerRadius, 0.0 ) && innerRadius > 0 )
{
std::unique_ptr< QgsCompoundCurve > innerCc = qgis::make_unique< QgsCompoundCurve >();
QgsCircle innerCircle = QgsCircle( center, innerRadius );
innerCc->addCurve( innerCircle.toCircularString() );
cp->setInteriorRings( { innerCc.release() } );
}
return QgsGeometry( std::move( cp ) );
}
std::unique_ptr< QgsCompoundCurve > wedge = qgis::make_unique< QgsCompoundCurve >();
const double startAngle = azimuth - angularWidth * 0.5;
const double endAngle = azimuth + angularWidth * 0.5;
const QgsPoint outerP1 = center.project( outerRadius, startAngle );
const QgsPoint outerP2 = center.project( outerRadius, endAngle );
const bool useShortestArc = angularWidth <= 180.0;
wedge->addCurve( new QgsCircularString( QgsCircularString::fromTwoPointsAndCenter( outerP1, outerP2, center, useShortestArc ) ) );
if ( !qgsDoubleNear( innerRadius, 0.0 ) && innerRadius > 0 )
{
const QgsPoint innerP1 = center.project( innerRadius, startAngle );
const QgsPoint innerP2 = center.project( innerRadius, endAngle );
wedge->addCurve( new QgsLineString( outerP2, innerP2 ) );
wedge->addCurve( new QgsCircularString( QgsCircularString::fromTwoPointsAndCenter( innerP2, innerP1, center, useShortestArc ) ) );
wedge->addCurve( new QgsLineString( innerP1, outerP1 ) );
}
else
{
wedge->addCurve( new QgsLineString( outerP2, center ) );
wedge->addCurve( new QgsLineString( center, outerP1 ) );
}
std::unique_ptr< QgsCurvePolygon > cp = qgis::make_unique< QgsCurvePolygon >();
cp->setExteriorRing( wedge.release() );
return QgsGeometry( std::move( cp ) );
}
void QgsGeometry::fromWkb( unsigned char *wkb, int length )
{
QgsConstWkbPtr ptr( wkb, length );
reset( QgsGeometryFactory::geomFromWkb( ptr ) );
delete [] wkb;
}
void QgsGeometry::fromWkb( const QByteArray &wkb )
{
QgsConstWkbPtr ptr( wkb );
reset( QgsGeometryFactory::geomFromWkb( ptr ) );
}
QgsWkbTypes::Type QgsGeometry::wkbType() const
{
if ( !d->geometry )
{
return QgsWkbTypes::Unknown;
}
else
{
return d->geometry->wkbType();
}
}
QgsWkbTypes::GeometryType QgsGeometry::type() const
{
if ( !d->geometry )
{
return QgsWkbTypes::UnknownGeometry;
}
return static_cast< QgsWkbTypes::GeometryType >( QgsWkbTypes::geometryType( d->geometry->wkbType() ) );
}
bool QgsGeometry::isEmpty() const
{
if ( !d->geometry )
{
return true;
}
return d->geometry->isEmpty();
}
bool QgsGeometry::isMultipart() const
{
if ( !d->geometry )
{
return false;
}
return QgsWkbTypes::isMultiType( d->geometry->wkbType() );
}
QgsPointXY QgsGeometry::closestVertex( const QgsPointXY &point, int &atVertex, int &beforeVertex, int &afterVertex, double &sqrDist ) const
{
if ( !d->geometry )
{
sqrDist = -1;
return QgsPointXY( 0, 0 );
}
QgsPoint pt( point.x(), point.y() );
QgsVertexId id;
QgsPoint vp = QgsGeometryUtils::closestVertex( *( d->geometry ), pt, id );
if ( !id.isValid() )
{
sqrDist = -1;
return QgsPointXY( 0, 0 );
}
sqrDist = QgsGeometryUtils::sqrDistance2D( pt, vp );
QgsVertexId prevVertex;
QgsVertexId nextVertex;
d->geometry->adjacentVertices( id, prevVertex, nextVertex );
atVertex = vertexNrFromVertexId( id );
beforeVertex = vertexNrFromVertexId( prevVertex );
afterVertex = vertexNrFromVertexId( nextVertex );
return QgsPointXY( vp.x(), vp.y() );
}
double QgsGeometry::distanceToVertex( int vertex ) const
{
if ( !d->geometry )
{
return -1;
}
QgsVertexId id;
if ( !vertexIdFromVertexNr( vertex, id ) )
{
return -1;
}
return QgsGeometryUtils::distanceToVertex( *( d->geometry ), id );
}
double QgsGeometry::angleAtVertex( int vertex ) const
{
if ( !d->geometry )
{
return 0;
}
QgsVertexId v2;
if ( !vertexIdFromVertexNr( vertex, v2 ) )
{
return 0;
}
return d->geometry->vertexAngle( v2 );
}
void QgsGeometry::adjacentVertices( int atVertex, int &beforeVertex, int &afterVertex ) const
{
if ( !d->geometry )
{
return;
}
QgsVertexId id;
if ( !vertexIdFromVertexNr( atVertex, id ) )
{
beforeVertex = -1;
afterVertex = -1;
return;
}
QgsVertexId beforeVertexId, afterVertexId;
d->geometry->adjacentVertices( id, beforeVertexId, afterVertexId );
beforeVertex = vertexNrFromVertexId( beforeVertexId );
afterVertex = vertexNrFromVertexId( afterVertexId );
}
bool QgsGeometry::moveVertex( double x, double y, int atVertex )
{
if ( !d->geometry )
{
return false;
}
QgsVertexId id;
if ( !vertexIdFromVertexNr( atVertex, id ) )
{
return false;
}
detach();
return d->geometry->moveVertex( id, QgsPoint( x, y ) );
}
bool QgsGeometry::moveVertex( const QgsPoint &p, int atVertex )
{
if ( !d->geometry )
{
return false;
}
QgsVertexId id;
if ( !vertexIdFromVertexNr( atVertex, id ) )
{
return false;
}
detach();
return d->geometry->moveVertex( id, p );
}
bool QgsGeometry::deleteVertex( int atVertex )
{
if ( !d->geometry )
{
return false;
}
//maintain compatibility with < 2.10 API
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::MultiPoint )
{
detach();
//delete geometry instead of point
return static_cast< QgsGeometryCollection * >( d->geometry.get() )->removeGeometry( atVertex );
}
//if it is a point, set the geometry to nullptr
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::Point )
{
reset( nullptr );
return true;
}
QgsVertexId id;
if ( !vertexIdFromVertexNr( atVertex, id ) )
{
return false;
}
detach();
return d->geometry->deleteVertex( id );
}
bool QgsGeometry::insertVertex( double x, double y, int beforeVertex )
{
if ( !d->geometry )
{
return false;
}
//maintain compatibility with < 2.10 API
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::MultiPoint )
{
detach();
//insert geometry instead of point
return static_cast< QgsGeometryCollection * >( d->geometry.get() )->insertGeometry( new QgsPoint( x, y ), beforeVertex );
}
QgsVertexId id;
if ( !vertexIdFromVertexNr( beforeVertex, id ) )
{
return false;
}
detach();
return d->geometry->insertVertex( id, QgsPoint( x, y ) );
}
bool QgsGeometry::insertVertex( const QgsPoint &point, int beforeVertex )
{
if ( !d->geometry )
{
return false;
}
//maintain compatibility with < 2.10 API
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::MultiPoint )
{
detach();
//insert geometry instead of point
return static_cast< QgsGeometryCollection * >( d->geometry.get() )->insertGeometry( new QgsPoint( point ), beforeVertex );
}
QgsVertexId id;
if ( !vertexIdFromVertexNr( beforeVertex, id ) )
{
return false;
}
detach();
return d->geometry->insertVertex( id, point );
}
QgsPoint QgsGeometry::vertexAt( int atVertex ) const
{
if ( !d->geometry )
{
return QgsPoint();
}
QgsVertexId vId;
( void )vertexIdFromVertexNr( atVertex, vId );
if ( vId.vertex < 0 )
{
return QgsPoint();
}
return d->geometry->vertexAt( vId );
}
double QgsGeometry::sqrDistToVertexAt( QgsPointXY &point, int atVertex ) const
{
QgsPointXY vertexPoint = vertexAt( atVertex );
return QgsGeometryUtils::sqrDistance2D( QgsPoint( vertexPoint ), QgsPoint( point ) );
}
QgsGeometry QgsGeometry::nearestPoint( const QgsGeometry &other ) const
{
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometry result = geos.closestPoint( other );
result.mLastError = mLastError;
return result;
}
QgsGeometry QgsGeometry::shortestLine( const QgsGeometry &other ) const
{
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometry result = geos.shortestLine( other, &mLastError );
result.mLastError = mLastError;
return result;
}
double QgsGeometry::closestVertexWithContext( const QgsPointXY &point, int &atVertex ) const
{
if ( !d->geometry )
{
return -1;
}
QgsVertexId vId;
QgsPoint pt( point.x(), point.y() );
QgsPoint closestPoint = QgsGeometryUtils::closestVertex( *( d->geometry ), pt, vId );
if ( !vId.isValid() )
return -1;
atVertex = vertexNrFromVertexId( vId );
return QgsGeometryUtils::sqrDistance2D( closestPoint, pt );
}
double QgsGeometry::closestSegmentWithContext( const QgsPointXY &point,
QgsPointXY &minDistPoint,
int &afterVertex,
int *leftOf,
double epsilon ) const
{
if ( !d->geometry )
{
return -1;
}
QgsPoint segmentPt;
QgsVertexId vertexAfter;
double sqrDist = d->geometry->closestSegment( QgsPoint( point ), segmentPt, vertexAfter, leftOf, epsilon );
if ( sqrDist < 0 )
return -1;
minDistPoint.setX( segmentPt.x() );
minDistPoint.setY( segmentPt.y() );
afterVertex = vertexNrFromVertexId( vertexAfter );
return sqrDist;
}
QgsGeometry::OperationResult QgsGeometry::addRing( const QVector<QgsPointXY> &ring )
{
std::unique_ptr< QgsLineString > ringLine = qgis::make_unique< QgsLineString >( ring );
return addRing( ringLine.release() );
}
QgsGeometry::OperationResult QgsGeometry::addRing( QgsCurve *ring )
{
std::unique_ptr< QgsCurve > r( ring );
if ( !d->geometry )
{
return InvalidInputGeometryType;
}
detach();
return QgsGeometryEditUtils::addRing( d->geometry.get(), std::move( r ) );
}
QgsGeometry::OperationResult QgsGeometry::addPart( const QVector<QgsPointXY> &points, QgsWkbTypes::GeometryType geomType )
{
QgsPointSequence l;
convertPointList( points, l );
return addPart( l, geomType );
}
QgsGeometry::OperationResult QgsGeometry::addPart( const QgsPointSequence &points, QgsWkbTypes::GeometryType geomType )
{
std::unique_ptr< QgsAbstractGeometry > partGeom;
if ( points.size() == 1 )
{
partGeom = qgis::make_unique< QgsPoint >( points[0] );
}
else if ( points.size() > 1 )
{
std::unique_ptr< QgsLineString > ringLine = qgis::make_unique< QgsLineString >();
ringLine->setPoints( points );
partGeom = std::move( ringLine );
}
return addPart( partGeom.release(), geomType );
}
QgsGeometry::OperationResult QgsGeometry::addPart( QgsAbstractGeometry *part, QgsWkbTypes::GeometryType geomType )
{
std::unique_ptr< QgsAbstractGeometry > p( part );
if ( !d->geometry )
{
switch ( geomType )
{
case QgsWkbTypes::PointGeometry:
reset( qgis::make_unique< QgsMultiPoint >() );
break;
case QgsWkbTypes::LineGeometry:
reset( qgis::make_unique< QgsMultiLineString >() );
break;
case QgsWkbTypes::PolygonGeometry:
reset( qgis::make_unique< QgsMultiPolygon >() );
break;
default:
reset( nullptr );
return QgsGeometry::OperationResult::AddPartNotMultiGeometry;
}
}
else
{
detach();
}
convertToMultiType();
return QgsGeometryEditUtils::addPart( d->geometry.get(), std::move( p ) );
}
QgsGeometry::OperationResult QgsGeometry::addPart( const QgsGeometry &newPart )
{
if ( !d->geometry )
{
return QgsGeometry::InvalidBaseGeometry;
}
if ( newPart.isNull() || !newPart.d->geometry )
{
return QgsGeometry::AddPartNotMultiGeometry;
}
return addPart( newPart.d->geometry->clone() );
}
QgsGeometry QgsGeometry::removeInteriorRings( double minimumRingArea ) const
{
if ( !d->geometry || type() != QgsWkbTypes::PolygonGeometry )
{
return QgsGeometry();
}
if ( QgsWkbTypes::isMultiType( d->geometry->wkbType() ) )
{
const QVector<QgsGeometry> parts = asGeometryCollection();
QVector<QgsGeometry> results;
results.reserve( parts.count() );
for ( const QgsGeometry &part : parts )
{
QgsGeometry result = part.removeInteriorRings( minimumRingArea );
if ( !result.isNull() )
results << result;
}
if ( results.isEmpty() )
return QgsGeometry();
QgsGeometry first = results.takeAt( 0 );
for ( const QgsGeometry &result : qgis::as_const( results ) )
{
first.addPart( result );
}
return first;
}
else
{
std::unique_ptr< QgsCurvePolygon > newPoly( static_cast< QgsCurvePolygon * >( d->geometry->clone() ) );
newPoly->removeInteriorRings( minimumRingArea );
return QgsGeometry( std::move( newPoly ) );
}
}
QgsGeometry::OperationResult QgsGeometry::translate( double dx, double dy, double dz, double dm )
{
if ( !d->geometry )
{
return QgsGeometry::InvalidBaseGeometry;
}
detach();
d->geometry->transform( QTransform::fromTranslate( dx, dy ), dz, 1.0, dm );
return QgsGeometry::Success;
}
QgsGeometry::OperationResult QgsGeometry::rotate( double rotation, const QgsPointXY ¢er )
{
if ( !d->geometry )
{
return QgsGeometry::InvalidBaseGeometry;
}
detach();
QTransform t = QTransform::fromTranslate( center.x(), center.y() );
t.rotate( -rotation );
t.translate( -center.x(), -center.y() );
d->geometry->transform( t );
return QgsGeometry::Success;
}
QgsGeometry::OperationResult QgsGeometry::splitGeometry( const QVector<QgsPointXY> &splitLine, QVector<QgsGeometry> &newGeometries, bool topological, QVector<QgsPointXY> &topologyTestPoints, bool splitFeature )
{
QgsPointSequence split, topology;
convertPointList( splitLine, split );
convertPointList( topologyTestPoints, topology );
return splitGeometry( split, newGeometries, topological, topology, splitFeature );
}
QgsGeometry::OperationResult QgsGeometry::splitGeometry( const QgsPointSequence &splitLine, QVector<QgsGeometry> &newGeometries, bool topological, QgsPointSequence &topologyTestPoints, bool splitFeature )
{
if ( !d->geometry )
{
return QgsGeometry::OperationResult::InvalidBaseGeometry;
}
QVector<QgsGeometry > newGeoms;
QgsLineString splitLineString( splitLine );
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometryEngine::EngineOperationResult result = geos.splitGeometry( splitLineString, newGeoms, topological, topologyTestPoints, &mLastError );
if ( result == QgsGeometryEngine::Success )
{
if ( splitFeature )
*this = newGeoms.takeAt( 0 );
newGeometries = newGeoms;
}
switch ( result )
{
case QgsGeometryEngine::Success:
return QgsGeometry::OperationResult::Success;
case QgsGeometryEngine::MethodNotImplemented:
case QgsGeometryEngine::EngineError:
case QgsGeometryEngine::NodedGeometryError:
return QgsGeometry::OperationResult::GeometryEngineError;
case QgsGeometryEngine::InvalidBaseGeometry:
return QgsGeometry::OperationResult::InvalidBaseGeometry;
case QgsGeometryEngine::InvalidInput:
return QgsGeometry::OperationResult::InvalidInputGeometryType;
case QgsGeometryEngine::SplitCannotSplitPoint:
return QgsGeometry::OperationResult::SplitCannotSplitPoint;
case QgsGeometryEngine::NothingHappened:
return QgsGeometry::OperationResult::NothingHappened;
//default: do not implement default to handle properly all cases
}
// this should never be reached
Q_ASSERT( false );
return QgsGeometry::NothingHappened;
}
QgsGeometry::OperationResult QgsGeometry::reshapeGeometry( const QgsLineString &reshapeLineString )
{
if ( !d->geometry )
{
return InvalidBaseGeometry;
}
QgsGeos geos( d->geometry.get() );
QgsGeometryEngine::EngineOperationResult errorCode = QgsGeometryEngine::Success;
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > geom( geos.reshapeGeometry( reshapeLineString, &errorCode, &mLastError ) );
if ( errorCode == QgsGeometryEngine::Success && geom )
{
reset( std::move( geom ) );
return Success;
}
switch ( errorCode )
{
case QgsGeometryEngine::Success:
return Success;
case QgsGeometryEngine::MethodNotImplemented:
case QgsGeometryEngine::EngineError:
case QgsGeometryEngine::NodedGeometryError:
return GeometryEngineError;
case QgsGeometryEngine::InvalidBaseGeometry:
return InvalidBaseGeometry;
case QgsGeometryEngine::InvalidInput:
return InvalidInputGeometryType;
case QgsGeometryEngine::SplitCannotSplitPoint: // should not happen
return GeometryEngineError;
case QgsGeometryEngine::NothingHappened:
return NothingHappened;
}
// should not be reached
return GeometryEngineError;
}
int QgsGeometry::makeDifferenceInPlace( const QgsGeometry &other )
{
if ( !d->geometry || !other.d->geometry )
{
return 0;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > diffGeom( geos.intersection( other.constGet(), &mLastError ) );
if ( !diffGeom )
{
return 1;
}
reset( std::move( diffGeom ) );
return 0;
}
QgsGeometry QgsGeometry::makeDifference( const QgsGeometry &other ) const
{
if ( !d->geometry || other.isNull() )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > diffGeom( geos.intersection( other.constGet(), &mLastError ) );
if ( !diffGeom )
{
QgsGeometry result;
result.mLastError = mLastError;
return result;
}
return QgsGeometry( diffGeom.release() );
}
QgsRectangle QgsGeometry::boundingBox() const
{
if ( d->geometry )
{
return d->geometry->boundingBox();
}
return QgsRectangle();
}
QgsGeometry QgsGeometry::orientedMinimumBoundingBox( double &area, double &angle, double &width, double &height ) const
{
QgsRectangle minRect;
area = std::numeric_limits<double>::max();
angle = 0;
width = std::numeric_limits<double>::max();
height = std::numeric_limits<double>::max();
if ( !d->geometry || d->geometry->nCoordinates() < 2 )
return QgsGeometry();
QgsGeometry hull = convexHull();
if ( hull.isNull() )
return QgsGeometry();
QgsVertexId vertexId;
QgsPoint pt0;
QgsPoint pt1;
QgsPoint pt2;
// get first point
hull.constGet()->nextVertex( vertexId, pt0 );
pt1 = pt0;
double prevAngle = 0.0;
while ( hull.constGet()->nextVertex( vertexId, pt2 ) )
{
double currentAngle = QgsGeometryUtils::lineAngle( pt1.x(), pt1.y(), pt2.x(), pt2.y() );
double rotateAngle = 180.0 / M_PI * ( currentAngle - prevAngle );
prevAngle = currentAngle;
QTransform t = QTransform::fromTranslate( pt0.x(), pt0.y() );
t.rotate( rotateAngle );
t.translate( -pt0.x(), -pt0.y() );
hull.get()->transform( t );
QgsRectangle bounds = hull.constGet()->boundingBox();
double currentArea = bounds.width() * bounds.height();
if ( currentArea < area )
{
minRect = bounds;
area = currentArea;
angle = 180.0 / M_PI * currentAngle;
width = bounds.width();
height = bounds.height();
}
pt1 = pt2;
}
QgsGeometry minBounds = QgsGeometry::fromRect( minRect );
minBounds.rotate( angle, QgsPointXY( pt0.x(), pt0.y() ) );
// constrain angle to 0 - 180
if ( angle > 180.0 )
angle = std::fmod( angle, 180.0 );
return minBounds;
}
QgsGeometry QgsGeometry::orientedMinimumBoundingBox() const
{
double area, angle, width, height;
return orientedMinimumBoundingBox( area, angle, width, height );
}
static QgsCircle __recMinimalEnclosingCircle( QgsMultiPointXY points, QgsMultiPointXY boundary )
{
auto l_boundary = boundary.length();
QgsCircle circ_mec;
if ( ( points.length() == 0 ) || ( l_boundary == 3 ) )
{
switch ( l_boundary )
{
case 0:
circ_mec = QgsCircle();
break;
case 1:
circ_mec = QgsCircle( QgsPoint( boundary.last() ), 0 );
boundary.pop_back();
break;
case 2:
{
QgsPointXY p1 = boundary.last();
boundary.pop_back();
QgsPointXY p2 = boundary.last();
boundary.pop_back();
circ_mec = QgsCircle().from2Points( QgsPoint( p1 ), QgsPoint( p2 ) );
}
break;
default:
QgsPoint p1( boundary.at( 0 ) );
QgsPoint p2( boundary.at( 1 ) );
QgsPoint p3( boundary.at( 2 ) );
circ_mec = QgsCircle().minimalCircleFrom3Points( p1, p2, p3 );
break;
}
return circ_mec;
}
else
{
QgsPointXY pxy = points.last();
points.pop_back();
circ_mec = __recMinimalEnclosingCircle( points, boundary );
QgsPoint p( pxy );
if ( !circ_mec.contains( p ) )
{
boundary.append( pxy );
circ_mec = __recMinimalEnclosingCircle( points, boundary );
}
}
return circ_mec;
}
QgsGeometry QgsGeometry::minimalEnclosingCircle( QgsPointXY ¢er, double &radius, unsigned int segments ) const
{
center = QgsPointXY();
radius = 0;
if ( isEmpty() )
{
return QgsGeometry();
}
/* optimization */
QgsGeometry hull = convexHull();
if ( hull.isNull() )
return QgsGeometry();
QgsMultiPointXY P = hull.convertToPoint( true ).asMultiPoint();
QgsMultiPointXY R;
QgsCircle circ = __recMinimalEnclosingCircle( P, R );
center = QgsPointXY( circ.center() );
radius = circ.radius();
QgsGeometry geom;
geom.set( circ.toPolygon( segments ) );
return geom;
}
QgsGeometry QgsGeometry::minimalEnclosingCircle( unsigned int segments ) const
{
QgsPointXY center;
double radius;
return minimalEnclosingCircle( center, radius, segments );
}
QgsGeometry QgsGeometry::orthogonalize( double tolerance, int maxIterations, double angleThreshold ) const
{
QgsInternalGeometryEngine engine( *this );
return engine.orthogonalize( tolerance, maxIterations, angleThreshold );
}
QgsGeometry QgsGeometry::snappedToGrid( double hSpacing, double vSpacing, double dSpacing, double mSpacing ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
return QgsGeometry( d->geometry->snappedToGrid( hSpacing, vSpacing, dSpacing, mSpacing ) );
}
bool QgsGeometry::removeDuplicateNodes( double epsilon, bool useZValues )
{
if ( !d->geometry )
return false;
detach();
return d->geometry->removeDuplicateNodes( epsilon, useZValues );
}
bool QgsGeometry::intersects( const QgsRectangle &r ) const
{
// fast case, check bounding boxes
if ( !boundingBoxIntersects( r ) )
return false;
// optimise trivial case for point intersections -- the bounding box test has already given us the answer
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::Point )
{
return true;
}
QgsGeometry g = fromRect( r );
return intersects( g );
}
bool QgsGeometry::intersects( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.intersects( geometry.d->geometry.get(), &mLastError );
}
bool QgsGeometry::boundingBoxIntersects( const QgsRectangle &rectangle ) const
{
if ( !d->geometry )
{
return false;
}
// optimise trivial case for point intersections
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::Point )
{
const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( d->geometry.get() );
return rectangle.contains( QgsPointXY( point->x(), point->y() ) );
}
return d->geometry->boundingBox().intersects( rectangle );
}
bool QgsGeometry::boundingBoxIntersects( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
return d->geometry->boundingBox().intersects( geometry.constGet()->boundingBox() );
}
bool QgsGeometry::contains( const QgsPointXY *p ) const
{
if ( !d->geometry || !p )
{
return false;
}
QgsPoint pt( p->x(), p->y() );
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.contains( &pt, &mLastError );
}
bool QgsGeometry::contains( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.contains( geometry.d->geometry.get(), &mLastError );
}
bool QgsGeometry::disjoint( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.disjoint( geometry.d->geometry.get(), &mLastError );
}
bool QgsGeometry::equals( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
// fast check - are they shared copies of the same underlying geometry?
if ( d == geometry.d )
return true;
// fast check - distinct geometry types?
if ( type() != geometry.type() )
return false;
// slower check - actually test the geometries
return *d->geometry == *geometry.d->geometry;
}
bool QgsGeometry::touches( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.touches( geometry.d->geometry.get(), &mLastError );
}
bool QgsGeometry::overlaps( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.overlaps( geometry.d->geometry.get(), &mLastError );
}
bool QgsGeometry::within( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.within( geometry.d->geometry.get(), &mLastError );
}
bool QgsGeometry::crosses( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.crosses( geometry.d->geometry.get(), &mLastError );
}
QString QgsGeometry::asWkt( int precision ) const
{
if ( !d->geometry )
{
return QString();
}
return d->geometry->asWkt( precision );
}
QString QgsGeometry::asJson( int precision ) const
{
return QString::fromStdString( asJsonObject( precision ).dump() );
}
json QgsGeometry::asJsonObject( int precision ) const
{
if ( !d->geometry )
{
return nullptr;
}
return d->geometry->asJsonObject( precision );
}
QVector<QgsGeometry> QgsGeometry::coerceToType( const QgsWkbTypes::Type type ) const
{
QVector< QgsGeometry > res;
if ( isNull() )
return res;
if ( wkbType() == type || type == QgsWkbTypes::Unknown )
{
res << *this;
return res;
}
if ( type == QgsWkbTypes::NoGeometry )
{
return res;
}
QgsGeometry newGeom = *this;
// Curved -> straight
if ( !QgsWkbTypes::isCurvedType( type ) && QgsWkbTypes::isCurvedType( newGeom.wkbType() ) )
{
newGeom = QgsGeometry( d->geometry.get()->segmentize() );
}
// polygon -> line
if ( QgsWkbTypes::geometryType( type ) == QgsWkbTypes::LineGeometry &&
newGeom.type() == QgsWkbTypes::PolygonGeometry )
{
// boundary gives us a (multi)line string of exterior + interior rings
newGeom = QgsGeometry( newGeom.constGet()->boundary() );
}
// line -> polygon
if ( QgsWkbTypes::geometryType( type ) == QgsWkbTypes::PolygonGeometry &&
newGeom.type() == QgsWkbTypes::LineGeometry )
{
std::unique_ptr< QgsGeometryCollection > gc( QgsGeometryFactory::createCollectionOfType( type ) );
const QgsGeometry source = newGeom;
for ( auto part = source.const_parts_begin(); part != source.const_parts_end(); ++part )
{
std::unique_ptr< QgsAbstractGeometry > exterior( ( *part )->clone() );
if ( QgsCurve *curve = qgsgeometry_cast< QgsCurve * >( exterior.get() ) )
{
if ( QgsWkbTypes::isCurvedType( type ) )
{
std::unique_ptr< QgsCurvePolygon > cp = qgis::make_unique< QgsCurvePolygon >();
cp->setExteriorRing( curve );
exterior.release();
gc->addGeometry( cp.release() );
}
else
{
std::unique_ptr< QgsPolygon > p = qgis::make_unique< QgsPolygon >();
p->setExteriorRing( qgsgeometry_cast< QgsLineString * >( curve ) );
exterior.release();
gc->addGeometry( p.release() );
}
}
}
newGeom = QgsGeometry( std::move( gc ) );
}
// line/polygon -> points
if ( QgsWkbTypes::geometryType( type ) == QgsWkbTypes::PointGeometry &&
( newGeom.type() == QgsWkbTypes::LineGeometry ||
newGeom.type() == QgsWkbTypes::PolygonGeometry ) )
{
// lines/polygons to a point layer, extract all vertices
std::unique_ptr< QgsMultiPoint > mp = qgis::make_unique< QgsMultiPoint >();
const QgsGeometry source = newGeom;
QSet< QgsPoint > added;
for ( auto vertex = source.vertices_begin(); vertex != source.vertices_end(); ++vertex )
{
if ( added.contains( *vertex ) )
continue; // avoid duplicate points, e.g. start/end of rings
mp->addGeometry( ( *vertex ).clone() );
added.insert( *vertex );
}
newGeom = QgsGeometry( std::move( mp ) );
}
// Single -> multi
if ( QgsWkbTypes::isMultiType( type ) && ! newGeom.isMultipart( ) )
{
newGeom.convertToMultiType();
}
// Drop Z/M
if ( newGeom.constGet()->is3D() && ! QgsWkbTypes::hasZ( type ) )
{
newGeom.get()->dropZValue();
}
if ( newGeom.constGet()->isMeasure() && ! QgsWkbTypes::hasM( type ) )
{
newGeom.get()->dropMValue();
}
// Add Z/M back, set to 0
if ( ! newGeom.constGet()->is3D() && QgsWkbTypes::hasZ( type ) )
{
newGeom.get()->addZValue( 0.0 );
}
if ( ! newGeom.constGet()->isMeasure() && QgsWkbTypes::hasM( type ) )
{
newGeom.get()->addMValue( 0.0 );
}
// Multi -> single
if ( ! QgsWkbTypes::isMultiType( type ) && newGeom.isMultipart( ) )
{
const QgsGeometryCollection *parts( static_cast< const QgsGeometryCollection * >( newGeom.constGet() ) );
QgsAttributeMap attrMap;
res.reserve( parts->partCount() );
for ( int i = 0; i < parts->partCount( ); i++ )
{
res << QgsGeometry( parts->geometryN( i )->clone() );
}
}
else
{
res << newGeom;
}
return res;
}
QgsGeometry QgsGeometry::convertToType( QgsWkbTypes::GeometryType destType, bool destMultipart ) const
{
switch ( destType )
{
case QgsWkbTypes::PointGeometry:
return convertToPoint( destMultipart );
case QgsWkbTypes::LineGeometry:
return convertToLine( destMultipart );
case QgsWkbTypes::PolygonGeometry:
return convertToPolygon( destMultipart );
default:
return QgsGeometry();
}
}
bool QgsGeometry::convertToMultiType()
{
if ( !d->geometry )
{
return false;
}
if ( isMultipart() ) //already multitype, no need to convert
{
return true;
}
std::unique_ptr< QgsAbstractGeometry >geom = QgsGeometryFactory::geomFromWkbType( QgsWkbTypes::multiType( d->geometry->wkbType() ) );
QgsGeometryCollection *multiGeom = qgsgeometry_cast<QgsGeometryCollection *>( geom.get() );
if ( !multiGeom )
{
return false;
}
//try to avoid cloning existing geometry whenever we can
//want to see a magic trick?... gather round kiddies...
detach(); // maybe a clone, hopefully not if we're the only ref to the private data
// now we cheat a bit and steal the private geometry and add it direct to the multigeom
// we can do this because we're the only ref to this geometry, guaranteed by the detach call above
multiGeom->addGeometry( d->geometry.release() );
// and replace it with the multi geometry.
// TADA! a clone free conversion in some cases
d->geometry = std::move( geom );
return true;
}
bool QgsGeometry::convertToSingleType()
{
if ( !d->geometry )
{
return false;
}
if ( !isMultipart() ) //already single part, no need to convert
{
return true;
}
QgsGeometryCollection *multiGeom = qgsgeometry_cast<QgsGeometryCollection *>( d->geometry.get() );
if ( !multiGeom || multiGeom->partCount() < 1 )
return false;
std::unique_ptr< QgsAbstractGeometry > firstPart( multiGeom->geometryN( 0 )->clone() );
reset( std::move( firstPart ) );
return true;
}
bool QgsGeometry::convertGeometryCollectionToSubclass( QgsWkbTypes::GeometryType geomType )
{
const QgsGeometryCollection *origGeom = qgsgeometry_cast<const QgsGeometryCollection *>( constGet() );
if ( !origGeom )
return false;
std::unique_ptr<QgsGeometryCollection> resGeom;
switch ( geomType )
{
case QgsWkbTypes::PointGeometry:
resGeom = qgis::make_unique<QgsMultiPoint>();
break;
case QgsWkbTypes::LineGeometry:
resGeom = qgis::make_unique<QgsMultiLineString>();
break;
case QgsWkbTypes::PolygonGeometry:
resGeom = qgis::make_unique<QgsMultiPolygon>();
break;
default:
break;
}
if ( !resGeom )
return false;
resGeom->reserve( origGeom->numGeometries() );
for ( int i = 0; i < origGeom->numGeometries(); ++i )
{
const QgsAbstractGeometry *g = origGeom->geometryN( i );
if ( QgsWkbTypes::geometryType( g->wkbType() ) == geomType )
resGeom->addGeometry( g->clone() );
}
set( resGeom.release() );
return true;
}
QgsPointXY QgsGeometry::asPoint() const
{
if ( !d->geometry || QgsWkbTypes::flatType( d->geometry->wkbType() ) != QgsWkbTypes::Point )
{
return QgsPointXY();
}
QgsPoint *pt = qgsgeometry_cast<QgsPoint *>( d->geometry.get() );
if ( !pt )
{
return QgsPointXY();
}
return QgsPointXY( pt->x(), pt->y() );
}
QgsPolylineXY QgsGeometry::asPolyline() const
{
QgsPolylineXY polyLine;
if ( !d->geometry )
{
return polyLine;
}
bool doSegmentation = ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::CompoundCurve
|| QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::CircularString );
std::unique_ptr< QgsLineString > segmentizedLine;
QgsLineString *line = nullptr;
if ( doSegmentation )
{
QgsCurve *curve = qgsgeometry_cast<QgsCurve *>( d->geometry.get() );
if ( !curve )
{
return polyLine;
}
segmentizedLine.reset( curve->curveToLine() );
line = segmentizedLine.get();
}
else
{
line = qgsgeometry_cast<QgsLineString *>( d->geometry.get() );
if ( !line )
{
return polyLine;
}
}
int nVertices = line->numPoints();
polyLine.resize( nVertices );
QgsPointXY *data = polyLine.data();
const double *xData = line->xData();
const double *yData = line->yData();
for ( int i = 0; i < nVertices; ++i )
{
data->setX( *xData++ );
data->setY( *yData++ );
data++;
}
return polyLine;
}
QgsPolygonXY QgsGeometry::asPolygon() const
{
if ( !d->geometry )
return QgsPolygonXY();
bool doSegmentation = ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::CurvePolygon );
QgsPolygon *p = nullptr;
std::unique_ptr< QgsPolygon > segmentized;
if ( doSegmentation )
{
QgsCurvePolygon *curvePoly = qgsgeometry_cast<QgsCurvePolygon *>( d->geometry.get() );
if ( !curvePoly )
{
return QgsPolygonXY();
}
segmentized.reset( curvePoly->toPolygon() );
p = segmentized.get();
}
else
{
p = qgsgeometry_cast<QgsPolygon *>( d->geometry.get() );
}
if ( !p )
{
return QgsPolygonXY();
}
QgsPolygonXY polygon;
convertPolygon( *p, polygon );
return polygon;
}
QgsMultiPointXY QgsGeometry::asMultiPoint() const
{
if ( !d->geometry || QgsWkbTypes::flatType( d->geometry->wkbType() ) != QgsWkbTypes::MultiPoint )
{
return QgsMultiPointXY();
}
const QgsMultiPoint *mp = qgsgeometry_cast<QgsMultiPoint *>( d->geometry.get() );
if ( !mp )
{
return QgsMultiPointXY();
}
int nPoints = mp->numGeometries();
QgsMultiPointXY multiPoint( nPoints );
for ( int i = 0; i < nPoints; ++i )
{
const QgsPoint *pt = static_cast<const QgsPoint *>( mp->geometryN( i ) );
multiPoint[i].setX( pt->x() );
multiPoint[i].setY( pt->y() );
}
return multiPoint;
}
QgsMultiPolylineXY QgsGeometry::asMultiPolyline() const
{
if ( !d->geometry )
{
return QgsMultiPolylineXY();
}
QgsGeometryCollection *geomCollection = qgsgeometry_cast<QgsGeometryCollection *>( d->geometry.get() );
if ( !geomCollection )
{
return QgsMultiPolylineXY();
}
int nLines = geomCollection->numGeometries();
if ( nLines < 1 )
{
return QgsMultiPolylineXY();
}
QgsMultiPolylineXY mpl;
mpl.reserve( nLines );
for ( int i = 0; i < nLines; ++i )
{
const QgsLineString *line = qgsgeometry_cast<const QgsLineString *>( geomCollection->geometryN( i ) );
std::unique_ptr< QgsLineString > segmentized;
if ( !line )
{
const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( geomCollection->geometryN( i ) );
if ( !curve )
{
continue;
}
segmentized.reset( curve->curveToLine() );
line = segmentized.get();
}
QgsPolylineXY polyLine;
int nVertices = line->numPoints();
polyLine.resize( nVertices );
QgsPointXY *data = polyLine.data();
const double *xData = line->xData();
const double *yData = line->yData();
for ( int i = 0; i < nVertices; ++i )
{
data->setX( *xData++ );
data->setY( *yData++ );
data++;
}
mpl.append( polyLine );
}
return mpl;
}
QgsMultiPolygonXY QgsGeometry::asMultiPolygon() const
{
if ( !d->geometry )
{
return QgsMultiPolygonXY();
}
QgsGeometryCollection *geomCollection = qgsgeometry_cast<QgsGeometryCollection *>( d->geometry.get() );
if ( !geomCollection )
{
return QgsMultiPolygonXY();
}
int nPolygons = geomCollection->numGeometries();
if ( nPolygons < 1 )
{
return QgsMultiPolygonXY();
}
QgsMultiPolygonXY mp;
for ( int i = 0; i < nPolygons; ++i )
{
const QgsPolygon *polygon = qgsgeometry_cast<const QgsPolygon *>( geomCollection->geometryN( i ) );
if ( !polygon )
{
const QgsCurvePolygon *cPolygon = qgsgeometry_cast<const QgsCurvePolygon *>( geomCollection->geometryN( i ) );
if ( cPolygon )
{
polygon = cPolygon->toPolygon();
}
else
{
continue;
}
}
QgsPolygonXY poly;
convertPolygon( *polygon, poly );
mp.append( poly );
}
return mp;
}
double QgsGeometry::area() const
{
if ( !d->geometry )
{
return -1.0;
}
QgsGeos g( d->geometry.get() );
#if 0
//debug: compare geos area with calculation in QGIS
double geosArea = g.area();
double qgisArea = 0;
QgsSurface *surface = qgsgeometry_cast<QgsSurface *>( d->geometry );
if ( surface )
{
qgisArea = surface->area();
}
#endif
mLastError.clear();
return g.area( &mLastError );
}
double QgsGeometry::length() const
{
if ( !d->geometry )
{
return -1.0;
}
QgsGeos g( d->geometry.get() );
mLastError.clear();
return g.length( &mLastError );
}
double QgsGeometry::distance( const QgsGeometry &geom ) const
{
if ( !d->geometry || !geom.d->geometry )
{
return -1.0;
}
// avoid calling geos for trivial point-to-point distance calculations
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::Point && QgsWkbTypes::flatType( geom.wkbType() ) == QgsWkbTypes::Point )
{
return qgsgeometry_cast< const QgsPoint * >( d->geometry.get() )->distance( *qgsgeometry_cast< const QgsPoint * >( geom.constGet() ) );
}
QgsGeos g( d->geometry.get() );
mLastError.clear();
return g.distance( geom.d->geometry.get(), &mLastError );
}
double QgsGeometry::hausdorffDistance( const QgsGeometry &geom ) const
{
if ( !d->geometry || !geom.d->geometry )
{
return -1.0;
}
QgsGeos g( d->geometry.get() );
mLastError.clear();
return g.hausdorffDistance( geom.d->geometry.get(), &mLastError );
}
double QgsGeometry::hausdorffDistanceDensify( const QgsGeometry &geom, double densifyFraction ) const
{
if ( !d->geometry || !geom.d->geometry )
{
return -1.0;
}
QgsGeos g( d->geometry.get() );
mLastError.clear();
return g.hausdorffDistanceDensify( geom.d->geometry.get(), densifyFraction, &mLastError );
}
QgsAbstractGeometry::vertex_iterator QgsGeometry::vertices_begin() const
{
if ( !d->geometry || d->geometry.get()->isEmpty() )
return QgsAbstractGeometry::vertex_iterator();
return d->geometry->vertices_begin();
}
QgsAbstractGeometry::vertex_iterator QgsGeometry::vertices_end() const
{
if ( !d->geometry || d->geometry.get()->isEmpty() )
return QgsAbstractGeometry::vertex_iterator();
return d->geometry->vertices_end();
}
QgsVertexIterator QgsGeometry::vertices() const
{
if ( !d->geometry || d->geometry.get()->isEmpty() )
return QgsVertexIterator();
return QgsVertexIterator( d->geometry.get() );
}
QgsAbstractGeometry::part_iterator QgsGeometry::parts_begin()
{
if ( !d->geometry )
return QgsAbstractGeometry::part_iterator();
detach();
return d->geometry->parts_begin();
}
QgsAbstractGeometry::part_iterator QgsGeometry::parts_end()
{
if ( !d->geometry )
return QgsAbstractGeometry::part_iterator();
return d->geometry->parts_end();
}
QgsAbstractGeometry::const_part_iterator QgsGeometry::const_parts_begin() const
{
if ( !d->geometry )
return QgsAbstractGeometry::const_part_iterator();
return d->geometry->const_parts_begin();
}
QgsAbstractGeometry::const_part_iterator QgsGeometry::const_parts_end() const
{
if ( !d->geometry )
return QgsAbstractGeometry::const_part_iterator();
return d->geometry->const_parts_end();
}
QgsGeometryPartIterator QgsGeometry::parts()
{
if ( !d->geometry )
return QgsGeometryPartIterator();
detach();
return QgsGeometryPartIterator( d->geometry.get() );
}
QgsGeometryConstPartIterator QgsGeometry::constParts() const
{
if ( !d->geometry )
return QgsGeometryConstPartIterator();
return QgsGeometryConstPartIterator( d->geometry.get() );
}
QgsGeometry QgsGeometry::buffer( double distance, int segments ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeos g( d->geometry.get() );
mLastError.clear();
std::unique_ptr<QgsAbstractGeometry> geom( g.buffer( distance, segments, &mLastError ) );
if ( !geom )
{
QgsGeometry result;
result.mLastError = mLastError;
return result;
}
return QgsGeometry( std::move( geom ) );
}
QgsGeometry QgsGeometry::buffer( double distance, int segments, EndCapStyle endCapStyle, JoinStyle joinStyle, double miterLimit ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeos g( d->geometry.get() );
mLastError.clear();
QgsAbstractGeometry *geom = g.buffer( distance, segments, endCapStyle, joinStyle, miterLimit, &mLastError );
if ( !geom )
{
QgsGeometry result;
result.mLastError = mLastError;
return result;
}
return QgsGeometry( geom );
}
QgsGeometry QgsGeometry::offsetCurve( double distance, int segments, JoinStyle joinStyle, double miterLimit ) const
{
if ( !d->geometry || type() != QgsWkbTypes::LineGeometry )
{
return QgsGeometry();
}
if ( QgsWkbTypes::isMultiType( d->geometry->wkbType() ) )
{
const QVector<QgsGeometry> parts = asGeometryCollection();
QVector<QgsGeometry> results;
results.reserve( parts.count() );
for ( const QgsGeometry &part : parts )
{
QgsGeometry result = part.offsetCurve( distance, segments, joinStyle, miterLimit );
if ( !result.isNull() )
results << result;
}
if ( results.isEmpty() )
return QgsGeometry();
QgsGeometry first = results.takeAt( 0 );
for ( const QgsGeometry &result : qgis::as_const( results ) )
{
first.addPart( result );
}
return first;
}
else
{
QgsGeos geos( d->geometry.get() );
mLastError.clear();
// GEOS can flip the curve orientation in some circumstances. So record previous orientation and correct if required
const QgsCurve::Orientation prevOrientation = qgsgeometry_cast< const QgsCurve * >( d->geometry.get() )->orientation();
std::unique_ptr< QgsAbstractGeometry > offsetGeom( geos.offsetCurve( distance, segments, joinStyle, miterLimit, &mLastError ) );
if ( !offsetGeom )
{
QgsGeometry result;
result.mLastError = mLastError;
return result;
}
if ( const QgsCurve *offsetCurve = qgsgeometry_cast< const QgsCurve * >( offsetGeom.get() ) )
{
const QgsCurve::Orientation newOrientation = offsetCurve->orientation();
if ( newOrientation != prevOrientation )
{
// GEOS has flipped line orientation, flip it back
std::unique_ptr< QgsAbstractGeometry > flipped( offsetCurve->reversed() );
offsetGeom = std::move( flipped );
}
}
return QgsGeometry( std::move( offsetGeom ) );
}
}
QgsGeometry QgsGeometry::singleSidedBuffer( double distance, int segments, BufferSide side, JoinStyle joinStyle, double miterLimit ) const
{
if ( !d->geometry || type() != QgsWkbTypes::LineGeometry )
{
return QgsGeometry();
}
if ( QgsWkbTypes::isMultiType( d->geometry->wkbType() ) )
{
const QVector<QgsGeometry> parts = asGeometryCollection();
QVector<QgsGeometry> results;
results.reserve( parts.count() );
for ( const QgsGeometry &part : parts )
{
QgsGeometry result = part.singleSidedBuffer( distance, segments, side, joinStyle, miterLimit );
if ( !result.isNull() )
results << result;
}
if ( results.isEmpty() )
return QgsGeometry();
QgsGeometry first = results.takeAt( 0 );
for ( const QgsGeometry &result : qgis::as_const( results ) )
{
first.addPart( result );
}
return first;
}
else
{
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > bufferGeom = geos.singleSidedBuffer( distance, segments, side,
joinStyle, miterLimit, &mLastError );
if ( !bufferGeom )
{
QgsGeometry result;
result.mLastError = mLastError;
return result;
}
return QgsGeometry( std::move( bufferGeom ) );
}
}
QgsGeometry QgsGeometry::taperedBuffer( double startWidth, double endWidth, int segments ) const
{
QgsInternalGeometryEngine engine( *this );
return engine.taperedBuffer( startWidth, endWidth, segments );
}
QgsGeometry QgsGeometry::variableWidthBufferByM( int segments ) const
{
QgsInternalGeometryEngine engine( *this );
return engine.variableWidthBufferByM( segments );
}
QgsGeometry QgsGeometry::extendLine( double startDistance, double endDistance ) const
{
if ( !d->geometry || type() != QgsWkbTypes::LineGeometry )
{
return QgsGeometry();
}
if ( QgsWkbTypes::isMultiType( d->geometry->wkbType() ) )
{
const QVector<QgsGeometry> parts = asGeometryCollection();
QVector<QgsGeometry> results;
results.reserve( parts.count() );
for ( const QgsGeometry &part : parts )
{
QgsGeometry result = part.extendLine( startDistance, endDistance );
if ( !result.isNull() )
results << result;
}
if ( results.isEmpty() )
return QgsGeometry();
QgsGeometry first = results.takeAt( 0 );
for ( const QgsGeometry &result : qgis::as_const( results ) )
{
first.addPart( result );
}
return first;
}
else
{
QgsLineString *line = qgsgeometry_cast< QgsLineString * >( d->geometry.get() );
if ( !line )
return QgsGeometry();
std::unique_ptr< QgsLineString > newLine( line->clone() );
newLine->extend( startDistance, endDistance );
return QgsGeometry( std::move( newLine ) );
}
}
QgsGeometry QgsGeometry::simplify( double tolerance ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > simplifiedGeom( geos.simplify( tolerance, &mLastError ) );
if ( !simplifiedGeom )
{
QgsGeometry result;
result.mLastError = mLastError;
return result;
}
return QgsGeometry( std::move( simplifiedGeom ) );
}
QgsGeometry QgsGeometry::densifyByCount( int extraNodesPerSegment ) const
{
QgsInternalGeometryEngine engine( *this );
return engine.densifyByCount( extraNodesPerSegment );
}
QgsGeometry QgsGeometry::densifyByDistance( double distance ) const
{
QgsInternalGeometryEngine engine( *this );
return engine.densifyByDistance( distance );
}
QgsGeometry QgsGeometry::convertToCurves( double distanceTolerance, double angleTolerance ) const
{
QgsInternalGeometryEngine engine( *this );
return engine.convertToCurves( distanceTolerance, angleTolerance );
}
QgsGeometry QgsGeometry::centroid() const
{
if ( !d->geometry )
{
return QgsGeometry();
}
// avoid calling geos for trivial point centroids
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::Point )
{
QgsGeometry c = *this;
c.get()->dropZValue();
c.get()->dropMValue();
return c;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometry result( geos.centroid( &mLastError ) );
result.mLastError = mLastError;
return result;
}
QgsGeometry QgsGeometry::pointOnSurface() const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometry result( geos.pointOnSurface( &mLastError ) );
result.mLastError = mLastError;
return result;
}
QgsGeometry QgsGeometry::poleOfInaccessibility( double precision, double *distanceToBoundary ) const
{
QgsInternalGeometryEngine engine( *this );
return engine.poleOfInaccessibility( precision, distanceToBoundary );
}
QgsGeometry QgsGeometry::convexHull() const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > cHull( geos.convexHull( &mLastError ) );
if ( !cHull )
{
QgsGeometry geom;
geom.mLastError = mLastError;
return geom;
}
return QgsGeometry( std::move( cHull ) );
}
QgsGeometry QgsGeometry::voronoiDiagram( const QgsGeometry &extent, double tolerance, bool edgesOnly ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometry result = geos.voronoiDiagram( extent.constGet(), tolerance, edgesOnly, &mLastError );
result.mLastError = mLastError;
return result;
}
QgsGeometry QgsGeometry::delaunayTriangulation( double tolerance, bool edgesOnly ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometry result = geos.delaunayTriangulation( tolerance, edgesOnly );
result.mLastError = mLastError;
return result;
}
QgsGeometry QgsGeometry::subdivide( int maxNodes ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
const QgsAbstractGeometry *geom = d->geometry.get();
std::unique_ptr< QgsAbstractGeometry > segmentizedCopy;
if ( QgsWkbTypes::isCurvedType( d->geometry->wkbType() ) )
{
segmentizedCopy.reset( d->geometry->segmentize() );
geom = segmentizedCopy.get();
}
QgsGeos geos( geom );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > result( geos.subdivide( maxNodes, &mLastError ) );
if ( !result )
{
QgsGeometry geom;
geom.mLastError = mLastError;
return geom;
}
return QgsGeometry( std::move( result ) );
}
QgsGeometry QgsGeometry::interpolate( double distance ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeometry line = *this;
if ( type() == QgsWkbTypes::PointGeometry )
return QgsGeometry();
else if ( type() == QgsWkbTypes::PolygonGeometry )
{
line = QgsGeometry( d->geometry->boundary() );
}
const QgsCurve *curve = nullptr;
if ( line.isMultipart() )
{
// if multi part, iterate through parts to find target part
const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( line.constGet() );
for ( int part = 0; part < collection->numGeometries(); ++part )
{
const QgsCurve *candidate = qgsgeometry_cast< const QgsCurve * >( collection->geometryN( part ) );
if ( !candidate )
continue;
const double candidateLength = candidate->length();
if ( candidateLength >= distance )
{
curve = candidate;
break;
}
distance -= candidateLength;
}
}
else
{
curve = qgsgeometry_cast< const QgsCurve * >( line.constGet() );
}
if ( !curve )
return QgsGeometry();
std::unique_ptr< QgsPoint > result( curve->interpolatePoint( distance ) );
if ( !result )
{
return QgsGeometry();
}
return QgsGeometry( std::move( result ) );
}
double QgsGeometry::lineLocatePoint( const QgsGeometry &point ) const
{
if ( type() != QgsWkbTypes::LineGeometry )
return -1;
if ( QgsWkbTypes::flatType( point.wkbType() ) != QgsWkbTypes::Point )
return -1;
QgsGeometry segmentized = *this;
if ( QgsWkbTypes::isCurvedType( wkbType() ) )
{
segmentized = QgsGeometry( static_cast< QgsCurve * >( d->geometry.get() )->segmentize() );
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.lineLocatePoint( *( static_cast< QgsPoint * >( point.d->geometry.get() ) ), &mLastError );
}
double QgsGeometry::interpolateAngle( double distance ) const
{
if ( !d->geometry )
return 0.0;
// always operate on segmentized geometries
QgsGeometry segmentized = *this;
if ( QgsWkbTypes::isCurvedType( wkbType() ) )
{
segmentized = QgsGeometry( static_cast< QgsCurve * >( d->geometry.get() )->segmentize() );
}
QgsVertexId previous;
QgsVertexId next;
if ( !QgsGeometryUtils::verticesAtDistance( *segmentized.constGet(), distance, previous, next ) )
return 0.0;
if ( previous == next )
{
// distance coincided exactly with a vertex
QgsVertexId v2 = previous;
QgsVertexId v1;
QgsVertexId v3;
segmentized.constGet()->adjacentVertices( v2, v1, v3 );
if ( v1.isValid() && v3.isValid() )
{
QgsPoint p1 = segmentized.constGet()->vertexAt( v1 );
QgsPoint p2 = segmentized.constGet()->vertexAt( v2 );
QgsPoint p3 = segmentized.constGet()->vertexAt( v3 );
double angle1 = QgsGeometryUtils::lineAngle( p1.x(), p1.y(), p2.x(), p2.y() );
double angle2 = QgsGeometryUtils::lineAngle( p2.x(), p2.y(), p3.x(), p3.y() );
return QgsGeometryUtils::averageAngle( angle1, angle2 );
}
else if ( v3.isValid() )
{
QgsPoint p1 = segmentized.constGet()->vertexAt( v2 );
QgsPoint p2 = segmentized.constGet()->vertexAt( v3 );
return QgsGeometryUtils::lineAngle( p1.x(), p1.y(), p2.x(), p2.y() );
}
else
{
QgsPoint p1 = segmentized.constGet()->vertexAt( v1 );
QgsPoint p2 = segmentized.constGet()->vertexAt( v2 );
return QgsGeometryUtils::lineAngle( p1.x(), p1.y(), p2.x(), p2.y() );
}
}
else
{
QgsPoint p1 = segmentized.constGet()->vertexAt( previous );
QgsPoint p2 = segmentized.constGet()->vertexAt( next );
return QgsGeometryUtils::lineAngle( p1.x(), p1.y(), p2.x(), p2.y() );
}
}
QgsGeometry QgsGeometry::intersection( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > resultGeom( geos.intersection( geometry.d->geometry.get(), &mLastError ) );
if ( !resultGeom )
{
QgsGeometry geom;
geom.mLastError = mLastError;
return geom;
}
return QgsGeometry( std::move( resultGeom ) );
}
QgsGeometry QgsGeometry::combine( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > resultGeom( geos.combine( geometry.d->geometry.get(), &mLastError ) );
if ( !resultGeom )
{
QgsGeometry geom;
geom.mLastError = mLastError;
return geom;
}
return QgsGeometry( std::move( resultGeom ) );
}
QgsGeometry QgsGeometry::mergeLines() const
{
if ( !d->geometry )
{
return QgsGeometry();
}
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::LineString )
{
// special case - a single linestring was passed
return QgsGeometry( *this );
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometry result = geos.mergeLines( &mLastError );
result.mLastError = mLastError;
return result;
}
QgsGeometry QgsGeometry::difference( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > resultGeom( geos.difference( geometry.d->geometry.get(), &mLastError ) );
if ( !resultGeom )
{
QgsGeometry geom;
geom.mLastError = mLastError;
return geom;
}
return QgsGeometry( std::move( resultGeom ) );
}
QgsGeometry QgsGeometry::symDifference( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > resultGeom( geos.symDifference( geometry.d->geometry.get(), &mLastError ) );
if ( !resultGeom )
{
QgsGeometry geom;
geom.mLastError = mLastError;
return geom;
}
return QgsGeometry( std::move( resultGeom ) );
}
QgsGeometry QgsGeometry::extrude( double x, double y )
{
QgsInternalGeometryEngine engine( *this );
return engine.extrude( x, y );
}
///@cond PRIVATE // avoid dox warning
QVector<QgsPointXY> QgsGeometry::randomPointsInPolygon( int count, const std::function< bool( const QgsPointXY & ) > &acceptPoint, unsigned long seed, QgsFeedback *feedback ) const
{
if ( type() != QgsWkbTypes::PolygonGeometry )
return QVector< QgsPointXY >();
return QgsInternalGeometryEngine::randomPointsInPolygon( *this, count, acceptPoint, seed, feedback );
}
QVector<QgsPointXY> QgsGeometry::randomPointsInPolygon( int count, unsigned long seed, QgsFeedback *feedback ) const
{
if ( type() != QgsWkbTypes::PolygonGeometry )
return QVector< QgsPointXY >();
return QgsInternalGeometryEngine::randomPointsInPolygon( *this, count, []( const QgsPointXY & ) { return true; }, seed, feedback );
}
///@endcond
QByteArray QgsGeometry::asWkb() const
{
return d->geometry ? d->geometry->asWkb() : QByteArray();
}
QVector<QgsGeometry> QgsGeometry::asGeometryCollection() const
{
QVector<QgsGeometry> geometryList;
if ( !d->geometry )
{
return geometryList;
}
QgsGeometryCollection *gc = qgsgeometry_cast<QgsGeometryCollection *>( d->geometry.get() );
if ( gc )
{
int numGeom = gc->numGeometries();
geometryList.reserve( numGeom );
for ( int i = 0; i < numGeom; ++i )
{
geometryList.append( QgsGeometry( gc->geometryN( i )->clone() ) );
}
}
else //a singlepart geometry
{
geometryList.append( *this );
}
return geometryList;
}
QPointF QgsGeometry::asQPointF() const
{
QgsPointXY point = asPoint();
return point.toQPointF();
}
QPolygonF QgsGeometry::asQPolygonF() const
{
const QgsWkbTypes::Type type = wkbType();
const QgsLineString *line = nullptr;
if ( QgsWkbTypes::flatType( type ) == QgsWkbTypes::LineString )
{
line = qgsgeometry_cast< const QgsLineString * >( constGet() );
}
else if ( QgsWkbTypes::flatType( type ) == QgsWkbTypes::Polygon )
{
const QgsPolygon *polygon = qgsgeometry_cast< const QgsPolygon * >( constGet() );
if ( polygon )
line = qgsgeometry_cast< const QgsLineString * >( polygon->exteriorRing() );
}
if ( line )
{
const double *srcX = line->xData();
const double *srcY = line->yData();
const int count = line->numPoints();
QPolygonF res( count );
QPointF *dest = res.data();
for ( int i = 0; i < count; ++i )
{
*dest++ = QPointF( *srcX++, *srcY++ );
}
return res;
}
else
{
return QPolygonF();
}
}
bool QgsGeometry::deleteRing( int ringNum, int partNum )
{
if ( !d->geometry )
{
return false;
}
detach();
bool ok = QgsGeometryEditUtils::deleteRing( d->geometry.get(), ringNum, partNum );
return ok;
}
bool QgsGeometry::deletePart( int partNum )
{
if ( !d->geometry )
{
return false;
}
if ( !isMultipart() && partNum < 1 )
{
set( nullptr );
return true;
}
detach();
bool ok = QgsGeometryEditUtils::deletePart( d->geometry.get(), partNum );
return ok;
}
int QgsGeometry::avoidIntersections( const QList<QgsVectorLayer *> &avoidIntersectionsLayers, const QHash<QgsVectorLayer *, QSet<QgsFeatureId> > &ignoreFeatures )
{
if ( !d->geometry )
{
return 1;
}
std::unique_ptr< QgsAbstractGeometry > diffGeom = QgsGeometryEditUtils::avoidIntersections( *( d->geometry ), avoidIntersectionsLayers, ignoreFeatures );
if ( diffGeom )
{
reset( std::move( diffGeom ) );
}
return 0;
}
QgsGeometry QgsGeometry::makeValid() const
{
if ( !d->geometry )
return QgsGeometry();
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > g( _qgis_lwgeom_make_valid( d->geometry.get(), mLastError ) );
QgsGeometry result = QgsGeometry( std::move( g ) );
result.mLastError = mLastError;
return result;
}
QgsGeometry QgsGeometry::forceRHR() const
{
if ( !d->geometry )
return QgsGeometry();
if ( isMultipart() )
{
const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( d->geometry.get() );
std::unique_ptr< QgsGeometryCollection > newCollection( collection->createEmptyWithSameType() );
newCollection->reserve( collection->numGeometries() );
for ( int i = 0; i < collection->numGeometries(); ++i )
{
const QgsAbstractGeometry *g = collection->geometryN( i );
if ( const QgsCurvePolygon *cp = qgsgeometry_cast< const QgsCurvePolygon * >( g ) )
{
std::unique_ptr< QgsCurvePolygon > corrected( cp->clone() );
corrected->forceRHR();
newCollection->addGeometry( corrected.release() );
}
else
{
newCollection->addGeometry( g->clone() );
}
}
return QgsGeometry( std::move( newCollection ) );
}
else
{
if ( const QgsCurvePolygon *cp = qgsgeometry_cast< const QgsCurvePolygon * >( d->geometry.get() ) )
{
std::unique_ptr< QgsCurvePolygon > corrected( cp->clone() );
corrected->forceRHR();
return QgsGeometry( std::move( corrected ) );
}
else
{
// not a curve polygon, so return unchanged
return *this;
}
}
}
void QgsGeometry::validateGeometry( QVector<QgsGeometry::Error> &errors, const ValidationMethod method, const QgsGeometry::ValidityFlags flags ) const
{
errors.clear();
if ( !d->geometry )
return;
// avoid expensive calcs for trivial point geometries
if ( QgsWkbTypes::geometryType( d->geometry->wkbType() ) == QgsWkbTypes::PointGeometry )
{
return;
}
switch ( method )
{
case ValidatorQgisInternal:
QgsGeometryValidator::validateGeometry( *this, errors, method );
return;
case ValidatorGeos:
{
QgsGeos geos( d->geometry.get() );
QString error;
QgsGeometry errorLoc;
if ( !geos.isValid( &error, flags & FlagAllowSelfTouchingHoles, &errorLoc ) )
{
if ( errorLoc.isNull() )
{
errors.append( QgsGeometry::Error( error ) );
}
else
{
const QgsPointXY point = errorLoc.asPoint();
errors.append( QgsGeometry::Error( error, point ) );
}
return;
}
}
}
}
bool QgsGeometry::isGeosValid( const QgsGeometry::ValidityFlags flags ) const
{
if ( !d->geometry )
{
return false;
}
return d->geometry->isValid( mLastError, static_cast< int >( flags ) );
}
bool QgsGeometry::isSimple() const
{
if ( !d->geometry )
return false;
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.isSimple( &mLastError );
}
bool QgsGeometry::isGeosEqual( const QgsGeometry &g ) const
{
if ( !d->geometry || !g.d->geometry )
{
return false;
}
// fast check - are they shared copies of the same underlying geometry?
if ( d == g.d )
return true;
// fast check - distinct geometry types?
if ( type() != g.type() )
return false;
// avoid calling geos for trivial point case
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::Point
&& QgsWkbTypes::flatType( g.d->geometry->wkbType() ) == QgsWkbTypes::Point )
{
return equals( g );
}
// another nice fast check upfront -- if the bounding boxes aren't equal, the geometries themselves can't be equal!
if ( d->geometry->boundingBox() != g.d->geometry->boundingBox() )
return false;
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.isEqual( g.d->geometry.get(), &mLastError );
}
QgsGeometry QgsGeometry::unaryUnion( const QVector<QgsGeometry> &geometries )
{
QgsGeos geos( nullptr );
QString error;
std::unique_ptr< QgsAbstractGeometry > geom( geos.combine( geometries, &error ) );
QgsGeometry result( std::move( geom ) );
result.mLastError = error;
return result;
}
QgsGeometry QgsGeometry::polygonize( const QVector<QgsGeometry> &geometryList )
{
QgsGeos geos( nullptr );
QVector<const QgsAbstractGeometry *> geomV2List;
for ( const QgsGeometry &g : geometryList )
{
if ( !( g.isNull() ) )
{
geomV2List.append( g.constGet() );
}
}
QString error;
QgsGeometry result = geos.polygonize( geomV2List, &error );
result.mLastError = error;
return result;
}
void QgsGeometry::convertToStraightSegment( double tolerance, QgsAbstractGeometry::SegmentationToleranceType toleranceType )
{
if ( !d->geometry || !requiresConversionToStraightSegments() )
{
return;
}
std::unique_ptr< QgsAbstractGeometry > straightGeom( d->geometry->segmentize( tolerance, toleranceType ) );
reset( std::move( straightGeom ) );
}
bool QgsGeometry::requiresConversionToStraightSegments() const
{
if ( !d->geometry )
{
return false;
}
return d->geometry->hasCurvedSegments();
}
QgsGeometry::OperationResult QgsGeometry::transform( const QgsCoordinateTransform &ct, const QgsCoordinateTransform::TransformDirection direction, const bool transformZ )
{
if ( !d->geometry )
{
return QgsGeometry::InvalidBaseGeometry;
}
detach();
d->geometry->transform( ct, direction, transformZ );
return QgsGeometry::Success;
}
QgsGeometry::OperationResult QgsGeometry::transform( const QTransform &ct, double zTranslate, double zScale, double mTranslate, double mScale )
{
if ( !d->geometry )
{
return QgsGeometry::InvalidBaseGeometry;
}
detach();
d->geometry->transform( ct, zTranslate, zScale, mTranslate, mScale );
return QgsGeometry::Success;
}
void QgsGeometry::mapToPixel( const QgsMapToPixel &mtp )
{
if ( d->geometry )
{
detach();
d->geometry->transform( mtp.transform() );
}
}
QgsGeometry QgsGeometry::clipped( const QgsRectangle &rectangle )
{
if ( !d->geometry || rectangle.isNull() || rectangle.isEmpty() )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > resultGeom = geos.clip( rectangle, &mLastError );
if ( !resultGeom )
{
QgsGeometry result;
result.mLastError = mLastError;
return result;
}
return QgsGeometry( std::move( resultGeom ) );
}
void QgsGeometry::draw( QPainter &p ) const
{
if ( d->geometry )
{
d->geometry->draw( p );
}
}
static bool vertexIndexInfo( const QgsAbstractGeometry *g, int vertexIndex, int &partIndex, int &ringIndex, int &vertex )
{
if ( vertexIndex < 0 )
return false; // clearly something wrong
if ( const QgsGeometryCollection *geomCollection = qgsgeometry_cast<const QgsGeometryCollection *>( g ) )
{
partIndex = 0;
int offset = 0;
for ( int i = 0; i < geomCollection->numGeometries(); ++i )
{
const QgsAbstractGeometry *part = geomCollection->geometryN( i );
// count total number of vertices in the part
int numPoints = 0;
for ( int k = 0; k < part->ringCount(); ++k )
numPoints += part->vertexCount( 0, k );
if ( vertexIndex < numPoints )
{
int nothing;
return vertexIndexInfo( part, vertexIndex, nothing, ringIndex, vertex ); // set ring_index + index
}
vertexIndex -= numPoints;
offset += numPoints;
partIndex++;
}
}
else if ( const QgsCurvePolygon *curvePolygon = qgsgeometry_cast<const QgsCurvePolygon *>( g ) )
{
const QgsCurve *ring = curvePolygon->exteriorRing();
if ( vertexIndex < ring->numPoints() )
{
partIndex = 0;
ringIndex = 0;
vertex = vertexIndex;
return true;
}
vertexIndex -= ring->numPoints();
ringIndex = 1;
for ( int i = 0; i < curvePolygon->numInteriorRings(); ++i )
{
const QgsCurve *ring = curvePolygon->interiorRing( i );
if ( vertexIndex < ring->numPoints() )
{
partIndex = 0;
vertex = vertexIndex;
return true;
}
vertexIndex -= ring->numPoints();
ringIndex += 1;
}
}
else if ( const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( g ) )
{
if ( vertexIndex < curve->numPoints() )
{
partIndex = 0;
ringIndex = 0;
vertex = vertexIndex;
return true;
}
}
else if ( qgsgeometry_cast<const QgsPoint *>( g ) )
{
if ( vertexIndex == 0 )
{
partIndex = 0;
ringIndex = 0;
vertex = 0;
return true;
}
}
return false;
}
bool QgsGeometry::vertexIdFromVertexNr( int nr, QgsVertexId &id ) const
{
if ( !d->geometry )
{
return false;
}
id.type = QgsVertexId::SegmentVertex;
bool res = vertexIndexInfo( d->geometry.get(), nr, id.part, id.ring, id.vertex );
if ( !res )
return false;
// now let's find out if it is a straight or circular segment
const QgsAbstractGeometry *g = d->geometry.get();
if ( const QgsGeometryCollection *geomCollection = qgsgeometry_cast<const QgsGeometryCollection *>( g ) )
{
g = geomCollection->geometryN( id.part );
}
if ( const QgsCurvePolygon *curvePolygon = qgsgeometry_cast<const QgsCurvePolygon *>( g ) )
{
g = id.ring == 0 ? curvePolygon->exteriorRing() : curvePolygon->interiorRing( id.ring - 1 );
}
if ( const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( g ) )
{
QgsPoint p;
res = curve->pointAt( id.vertex, p, id.type );
if ( !res )
return false;
}
return true;
}
int QgsGeometry::vertexNrFromVertexId( QgsVertexId id ) const
{
if ( !d->geometry )
{
return -1;
}
return d->geometry->vertexNumberFromVertexId( id );
}
QString QgsGeometry::lastError() const
{
return mLastError;
}
void QgsGeometry::filterVertices( const std::function<bool ( const QgsPoint & )> &filter )
{
if ( !d->geometry )
return;
detach();
d->geometry->filterVertices( filter );
}
void QgsGeometry::transformVertices( const std::function<QgsPoint( const QgsPoint & )> &transform )
{
if ( !d->geometry )
return;
detach();
d->geometry->transformVertices( transform );
}
void QgsGeometry::convertPointList( const QVector<QgsPointXY> &input, QgsPointSequence &output )
{
output.clear();
for ( const QgsPointXY &p : input )
{
output.append( QgsPoint( p ) );
}
}
void QgsGeometry::convertPointList( const QgsPointSequence &input, QVector<QgsPointXY> &output )
{
output.clear();
for ( const QgsPoint &p : input )
{
output.append( QgsPointXY( p.x(), p.y() ) );
}
}
void QgsGeometry::convertToPolyline( const QgsPointSequence &input, QgsPolylineXY &output )
{
output.clear();
output.resize( input.size() );
for ( int i = 0; i < input.size(); ++i )
{
const QgsPoint &pt = input.at( i );
output[i].setX( pt.x() );
output[i].setY( pt.y() );
}
}
void QgsGeometry::convertPolygon( const QgsPolygon &input, QgsPolygonXY &output )
{
output.clear();
QgsCoordinateSequence coords = input.coordinateSequence();
if ( coords.empty() )
{
return;
}
const QgsRingSequence &rings = coords[0];
output.resize( rings.size() );
for ( int i = 0; i < rings.size(); ++i )
{
convertToPolyline( rings[i], output[i] );
}
}
QgsGeometry QgsGeometry::fromQPointF( QPointF point )
{
return QgsGeometry( qgis::make_unique< QgsPoint >( point.x(), point.y() ) );
}
QgsGeometry QgsGeometry::fromQPolygonF( const QPolygonF &polygon )
{
std::unique_ptr < QgsLineString > ring( QgsLineString::fromQPolygonF( polygon ) );
if ( polygon.isClosed() )
{
std::unique_ptr< QgsPolygon > poly = qgis::make_unique< QgsPolygon >();
poly->setExteriorRing( ring.release() );
return QgsGeometry( std::move( poly ) );
}
else
{
return QgsGeometry( std::move( ring ) );
}
}
QgsPolygonXY QgsGeometry::createPolygonFromQPolygonF( const QPolygonF &polygon )
{
Q_NOWARN_DEPRECATED_PUSH
QgsPolygonXY result;
result << createPolylineFromQPolygonF( polygon );
return result;
Q_NOWARN_DEPRECATED_POP
}
QgsPolylineXY QgsGeometry::createPolylineFromQPolygonF( const QPolygonF &polygon )
{
QgsPolylineXY result;
result.reserve( polygon.count() );
for ( const QPointF &p : polygon )
{
result.append( QgsPointXY( p ) );
}
return result;
}
bool QgsGeometry::compare( const QgsPolylineXY &p1, const QgsPolylineXY &p2, double epsilon )
{
if ( p1.count() != p2.count() )
return false;
for ( int i = 0; i < p1.count(); ++i )
{
if ( !p1.at( i ).compare( p2.at( i ), epsilon ) )
return false;
}
return true;
}
bool QgsGeometry::compare( const QgsPolygonXY &p1, const QgsPolygonXY &p2, double epsilon )
{
if ( p1.count() != p2.count() )
return false;
for ( int i = 0; i < p1.count(); ++i )
{
if ( !QgsGeometry::compare( p1.at( i ), p2.at( i ), epsilon ) )
return false;
}
return true;
}
bool QgsGeometry::compare( const QgsMultiPolygonXY &p1, const QgsMultiPolygonXY &p2, double epsilon )
{
if ( p1.count() != p2.count() )
return false;
for ( int i = 0; i < p1.count(); ++i )
{
if ( !QgsGeometry::compare( p1.at( i ), p2.at( i ), epsilon ) )
return false;
}
return true;
}
QgsGeometry QgsGeometry::smooth( const unsigned int iterations, const double offset, double minimumDistance, double maxAngle ) const
{
if ( !d->geometry || d->geometry->isEmpty() )
return QgsGeometry();
QgsGeometry geom = *this;
if ( QgsWkbTypes::isCurvedType( wkbType() ) )
geom = QgsGeometry( d->geometry->segmentize() );
switch ( QgsWkbTypes::flatType( geom.wkbType() ) )
{
case QgsWkbTypes::Point:
case QgsWkbTypes::MultiPoint:
//can't smooth a point based geometry
return geom;
case QgsWkbTypes::LineString:
{
QgsLineString *lineString = static_cast< QgsLineString * >( d->geometry.get() );
return QgsGeometry( smoothLine( *lineString, iterations, offset, minimumDistance, maxAngle ) );
}
case QgsWkbTypes::MultiLineString:
{
QgsMultiLineString *multiLine = static_cast< QgsMultiLineString * >( d->geometry.get() );
std::unique_ptr< QgsMultiLineString > resultMultiline = qgis::make_unique< QgsMultiLineString> ();
resultMultiline->reserve( multiLine->numGeometries() );
for ( int i = 0; i < multiLine->numGeometries(); ++i )
{
resultMultiline->addGeometry( smoothLine( *( static_cast< QgsLineString * >( multiLine->geometryN( i ) ) ), iterations, offset, minimumDistance, maxAngle ).release() );
}
return QgsGeometry( std::move( resultMultiline ) );
}
case QgsWkbTypes::Polygon:
{
QgsPolygon *poly = static_cast< QgsPolygon * >( d->geometry.get() );
return QgsGeometry( smoothPolygon( *poly, iterations, offset, minimumDistance, maxAngle ) );
}
case QgsWkbTypes::MultiPolygon:
{
QgsMultiPolygon *multiPoly = static_cast< QgsMultiPolygon * >( d->geometry.get() );
std::unique_ptr< QgsMultiPolygon > resultMultiPoly = qgis::make_unique< QgsMultiPolygon >();
resultMultiPoly->reserve( multiPoly->numGeometries() );
for ( int i = 0; i < multiPoly->numGeometries(); ++i )
{
resultMultiPoly->addGeometry( smoothPolygon( *( static_cast< QgsPolygon * >( multiPoly->geometryN( i ) ) ), iterations, offset, minimumDistance, maxAngle ).release() );
}
return QgsGeometry( std::move( resultMultiPoly ) );
}
case QgsWkbTypes::Unknown:
default:
return QgsGeometry( *this );
}
}
std::unique_ptr< QgsLineString > smoothCurve( const QgsLineString &line, const unsigned int iterations,
const double offset, double squareDistThreshold, double maxAngleRads,
bool isRing )
{
std::unique_ptr< QgsLineString > result = qgis::make_unique< QgsLineString >( line );
QgsPointSequence outputLine;
for ( unsigned int iteration = 0; iteration < iterations; ++iteration )
{
outputLine.resize( 0 );
outputLine.reserve( 2 * ( result->numPoints() - 1 ) );
bool skipFirst = false;
bool skipLast = false;
if ( isRing )
{
QgsPoint p1 = result->pointN( result->numPoints() - 2 );
QgsPoint p2 = result->pointN( 0 );
QgsPoint p3 = result->pointN( 1 );
double angle = QgsGeometryUtils::angleBetweenThreePoints( p1.x(), p1.y(), p2.x(), p2.y(),
p3.x(), p3.y() );
angle = std::fabs( M_PI - angle );
skipFirst = angle > maxAngleRads;
}
for ( int i = 0; i < result->numPoints() - 1; i++ )
{
QgsPoint p1 = result->pointN( i );
QgsPoint p2 = result->pointN( i + 1 );
double angle = M_PI;
if ( i == 0 && isRing )
{
QgsPoint p3 = result->pointN( result->numPoints() - 2 );
angle = QgsGeometryUtils::angleBetweenThreePoints( p1.x(), p1.y(), p2.x(), p2.y(),
p3.x(), p3.y() );
}
else if ( i < result->numPoints() - 2 )
{
QgsPoint p3 = result->pointN( i + 2 );
angle = QgsGeometryUtils::angleBetweenThreePoints( p1.x(), p1.y(), p2.x(), p2.y(),
p3.x(), p3.y() );
}
else if ( i == result->numPoints() - 2 && isRing )
{
QgsPoint p3 = result->pointN( 1 );
angle = QgsGeometryUtils::angleBetweenThreePoints( p1.x(), p1.y(), p2.x(), p2.y(),
p3.x(), p3.y() );
}
skipLast = angle < M_PI - maxAngleRads || angle > M_PI + maxAngleRads;
// don't apply distance threshold to first or last segment
if ( i == 0 || i >= result->numPoints() - 2
|| QgsGeometryUtils::sqrDistance2D( p1, p2 ) > squareDistThreshold )
{
if ( !isRing )
{
if ( !skipFirst )
outputLine << ( i == 0 ? result->pointN( i ) : QgsGeometryUtils::interpolatePointOnLine( p1, p2, offset ) );
if ( !skipLast )
outputLine << ( i == result->numPoints() - 2 ? result->pointN( i + 1 ) : QgsGeometryUtils::interpolatePointOnLine( p1, p2, 1.0 - offset ) );
else
outputLine << p2;
}
else
{
// ring
if ( !skipFirst )
outputLine << QgsGeometryUtils::interpolatePointOnLine( p1, p2, offset );
else if ( i == 0 )
outputLine << p1;
if ( !skipLast )
outputLine << QgsGeometryUtils::interpolatePointOnLine( p1, p2, 1.0 - offset );
else
outputLine << p2;
}
}
skipFirst = skipLast;
}
if ( isRing && outputLine.at( 0 ) != outputLine.at( outputLine.count() - 1 ) )
outputLine << outputLine.at( 0 );
result->setPoints( outputLine );
}
return result;
}
std::unique_ptr<QgsLineString> QgsGeometry::smoothLine( const QgsLineString &line, const unsigned int iterations, const double offset, double minimumDistance, double maxAngle ) const
{
double maxAngleRads = maxAngle * M_PI / 180.0;
double squareDistThreshold = minimumDistance > 0 ? minimumDistance * minimumDistance : -1;
return smoothCurve( line, iterations, offset, squareDistThreshold, maxAngleRads, false );
}
std::unique_ptr<QgsPolygon> QgsGeometry::smoothPolygon( const QgsPolygon &polygon, const unsigned int iterations, const double offset, double minimumDistance, double maxAngle ) const
{
double maxAngleRads = maxAngle * M_PI / 180.0;
double squareDistThreshold = minimumDistance > 0 ? minimumDistance * minimumDistance : -1;
std::unique_ptr< QgsPolygon > resultPoly = qgis::make_unique< QgsPolygon >();
resultPoly->setExteriorRing( smoothCurve( *( static_cast< const QgsLineString *>( polygon.exteriorRing() ) ), iterations, offset,
squareDistThreshold, maxAngleRads, true ).release() );
for ( int i = 0; i < polygon.numInteriorRings(); ++i )
{
resultPoly->addInteriorRing( smoothCurve( *( static_cast< const QgsLineString *>( polygon.interiorRing( i ) ) ), iterations, offset,
squareDistThreshold, maxAngleRads, true ).release() );
}
return resultPoly;
}
QgsGeometry QgsGeometry::convertToPoint( bool destMultipart ) const
{
switch ( type() )
{
case QgsWkbTypes::PointGeometry:
{
bool srcIsMultipart = isMultipart();
if ( ( destMultipart && srcIsMultipart ) ||
( !destMultipart && !srcIsMultipart ) )
{
// return a copy of the same geom
return QgsGeometry( *this );
}
if ( destMultipart )
{
// layer is multipart => make a multipoint with a single point
return fromMultiPointXY( QgsMultiPointXY() << asPoint() );
}
else
{
// destination is singlepart => make a single part if possible
QgsMultiPointXY multiPoint = asMultiPoint();
if ( multiPoint.count() == 1 )
{
return fromPointXY( multiPoint[0] );
}
}
return QgsGeometry();
}
case QgsWkbTypes::LineGeometry:
{
// only possible if destination is multipart
if ( !destMultipart )
return QgsGeometry();
// input geometry is multipart
if ( isMultipart() )
{
const QgsMultiPolylineXY multiLine = asMultiPolyline();
QgsMultiPointXY multiPoint;
for ( const QgsPolylineXY &l : multiLine )
for ( const QgsPointXY &p : l )
multiPoint << p;
return fromMultiPointXY( multiPoint );
}
// input geometry is not multipart: copy directly the line into a multipoint
else
{
QgsPolylineXY line = asPolyline();
if ( !line.isEmpty() )
return fromMultiPointXY( line );
}
return QgsGeometry();
}
case QgsWkbTypes::PolygonGeometry:
{
// can only transform if destination is multipoint
if ( !destMultipart )
return QgsGeometry();
// input geometry is multipart: make a multipoint from multipolygon
if ( isMultipart() )
{
const QgsMultiPolygonXY multiPolygon = asMultiPolygon();
QgsMultiPointXY multiPoint;
for ( const QgsPolygonXY &poly : multiPolygon )
for ( const QgsPolylineXY &line : poly )
for ( const QgsPointXY &pt : line )
multiPoint << pt;
return fromMultiPointXY( multiPoint );
}
// input geometry is not multipart: make a multipoint from polygon
else
{
const QgsPolygonXY polygon = asPolygon();
QgsMultiPointXY multiPoint;
for ( const QgsPolylineXY &line : polygon )
for ( const QgsPointXY &pt : line )
multiPoint << pt;
return fromMultiPointXY( multiPoint );
}
}
default:
return QgsGeometry();
}
}
QgsGeometry QgsGeometry::convertToLine( bool destMultipart ) const
{
switch ( type() )
{
case QgsWkbTypes::PointGeometry:
{
if ( !isMultipart() )
return QgsGeometry();
QgsMultiPointXY multiPoint = asMultiPoint();
if ( multiPoint.count() < 2 )
return QgsGeometry();
if ( destMultipart )
return fromMultiPolylineXY( QgsMultiPolylineXY() << multiPoint );
else
return fromPolylineXY( multiPoint );
}
case QgsWkbTypes::LineGeometry:
{
bool srcIsMultipart = isMultipart();
if ( ( destMultipart && srcIsMultipart ) ||
( !destMultipart && ! srcIsMultipart ) )
{
// return a copy of the same geom
return QgsGeometry( *this );
}
if ( destMultipart )
{
// destination is multipart => makes a multipoint with a single line
QgsPolylineXY line = asPolyline();
if ( !line.isEmpty() )
return fromMultiPolylineXY( QgsMultiPolylineXY() << line );
}
else
{
// destination is singlepart => make a single part if possible
QgsMultiPolylineXY multiLine = asMultiPolyline();
if ( multiLine.count() == 1 )
return fromPolylineXY( multiLine[0] );
}
return QgsGeometry();
}
case QgsWkbTypes::PolygonGeometry:
{
// input geometry is multipolygon
if ( isMultipart() )
{
const QgsMultiPolygonXY multiPolygon = asMultiPolygon();
QgsMultiPolylineXY multiLine;
for ( const QgsPolygonXY &poly : multiPolygon )
for ( const QgsPolylineXY &line : poly )
multiLine << line;
if ( destMultipart )
{
// destination is multipart
return fromMultiPolylineXY( multiLine );
}
else if ( multiLine.count() == 1 )
{
// destination is singlepart => make a single part if possible
return fromPolylineXY( multiLine[0] );
}
}
// input geometry is single polygon
else
{
QgsPolygonXY polygon = asPolygon();
// if polygon has rings
if ( polygon.count() > 1 )
{
// cannot fit a polygon with rings in a single line layer
// TODO: would it be better to remove rings?
if ( destMultipart )
{
const QgsPolygonXY polygon = asPolygon();
QgsMultiPolylineXY multiLine;
multiLine.reserve( polygon.count() );
for ( const QgsPolylineXY &line : polygon )
multiLine << line;
return fromMultiPolylineXY( multiLine );
}
}
// no rings
else if ( polygon.count() == 1 )
{
if ( destMultipart )
{
return fromMultiPolylineXY( polygon );
}
else
{
return fromPolylineXY( polygon[0] );
}
}
}
return QgsGeometry();
}
default:
return QgsGeometry();
}
}
QgsGeometry QgsGeometry::convertToPolygon( bool destMultipart ) const
{
switch ( type() )
{
case QgsWkbTypes::PointGeometry:
{
if ( !isMultipart() )
return QgsGeometry();
QgsMultiPointXY multiPoint = asMultiPoint();
if ( multiPoint.count() < 3 )
return QgsGeometry();
if ( multiPoint.last() != multiPoint.first() )
multiPoint << multiPoint.first();
QgsPolygonXY polygon = QgsPolygonXY() << multiPoint;
if ( destMultipart )
return fromMultiPolygonXY( QgsMultiPolygonXY() << polygon );
else
return fromPolygonXY( polygon );
}
case QgsWkbTypes::LineGeometry:
{
// input geometry is multiline
if ( isMultipart() )
{
QgsMultiPolylineXY multiLine = asMultiPolyline();
QgsMultiPolygonXY multiPolygon;
for ( QgsMultiPolylineXY::iterator multiLineIt = multiLine.begin(); multiLineIt != multiLine.end(); ++multiLineIt )
{
// do not create polygon for a 1 segment line
if ( ( *multiLineIt ).count() < 3 )
return QgsGeometry();
if ( ( *multiLineIt ).count() == 3 && ( *multiLineIt ).first() == ( *multiLineIt ).last() )
return QgsGeometry();
// add closing node
if ( ( *multiLineIt ).first() != ( *multiLineIt ).last() )
*multiLineIt << ( *multiLineIt ).first();
multiPolygon << ( QgsPolygonXY() << *multiLineIt );
}
// check that polygons were inserted
if ( !multiPolygon.isEmpty() )
{
if ( destMultipart )
{
return fromMultiPolygonXY( multiPolygon );
}
else if ( multiPolygon.count() == 1 )
{
// destination is singlepart => make a single part if possible
return fromPolygonXY( multiPolygon[0] );
}
}
}
// input geometry is single line
else
{
QgsPolylineXY line = asPolyline();
// do not create polygon for a 1 segment line
if ( line.count() < 3 )
return QgsGeometry();
if ( line.count() == 3 && line.first() == line.last() )
return QgsGeometry();
// add closing node
if ( line.first() != line.last() )
line << line.first();
// destination is multipart
if ( destMultipart )
{
return fromMultiPolygonXY( QgsMultiPolygonXY() << ( QgsPolygonXY() << line ) );
}
else
{
return fromPolygonXY( QgsPolygonXY() << line );
}
}
return QgsGeometry();
}
case QgsWkbTypes::PolygonGeometry:
{
bool srcIsMultipart = isMultipart();
if ( ( destMultipart && srcIsMultipart ) ||
( !destMultipart && ! srcIsMultipart ) )
{
// return a copy of the same geom
return QgsGeometry( *this );
}
if ( destMultipart )
{
// destination is multipart => makes a multipoint with a single polygon
QgsPolygonXY polygon = asPolygon();
if ( !polygon.isEmpty() )
return fromMultiPolygonXY( QgsMultiPolygonXY() << polygon );
}
else
{
QgsMultiPolygonXY multiPolygon = asMultiPolygon();
if ( multiPolygon.count() == 1 )
{
// destination is singlepart => make a single part if possible
return fromPolygonXY( multiPolygon[0] );
}
}
return QgsGeometry();
}
default:
return QgsGeometry();
}
}
QgsGeometryEngine *QgsGeometry::createGeometryEngine( const QgsAbstractGeometry *geometry )
{
return new QgsGeos( geometry );
}
QDataStream &operator<<( QDataStream &out, const QgsGeometry &geometry )
{
out << geometry.asWkb();
return out;
}
QDataStream &operator>>( QDataStream &in, QgsGeometry &geometry )
{
QByteArray byteArray;
in >> byteArray;
if ( byteArray.isEmpty() )
{
geometry.set( nullptr );
return in;
}
geometry.fromWkb( byteArray );
return in;
}
QString QgsGeometry::Error::what() const
{
return mMessage;
}
QgsPointXY QgsGeometry::Error::where() const
{
return mLocation;
}
bool QgsGeometry::Error::hasWhere() const
{
return mHasLocation;
}
| jef-n/QGIS | src/core/geometry/qgsgeometry.cpp | C++ | gpl-2.0 | 97,900 |
<?php
/****************************************************************************
* xestion/informes/uso_disco.inc.php
*
* Prepara los datos para mostrar el informe de uso de disco para las raíces
* que tengan limitado el espacio en disco
*******************************************************************************/
defined('OK') && defined('XESTION') or die();
$ud_ordenar = trim($PFN_vars->get('ud_ordenar'));
$ud_modo = trim($PFN_vars->get('ud_modo'));
$ud_ordenar = empty($ud_ordenar)?'nome':$ud_ordenar;
$ud_modo = ($ud_modo == 'DESC')?'DESC':'ASC';
$listado['id'] = $listado['nome'] = $listado['actual'] = $listado['limite'] = $listado['libre'] = array();
$PFN_usuarios->init('raices');
for (; $PFN_usuarios->mais(); $PFN_usuarios->seguinte()) {
$listado['id'][] = $PFN_usuarios->get('id');
$listado['nome'][] = $PFN_usuarios->get('nome');
if ($PFN_usuarios->get('peso_maximo') > 0) {
$actual = $PFN_usuarios->get('peso_actual');
$limite = $PFN_usuarios->get('peso_maximo');
$listado['actual'][] = $actual;
$listado['limite'][] = $limite;
$listado['libre'][] = intval((($limite - $actual) / $limite) * 100);
} else {
$listado['actual'][] = $listado['limite'][] = $listado['libre'][] = false;
}
}
if ($ud_modo == 'ASC') {
asort($listado[$ud_ordenar]);
} else {
arsort($listado[$ud_ordenar]);
}
$b = 1;
$txt = '<table class="tabla_informes" summary="">'
.'<tr><th style="text-align: left;">'
.'<a href="'.PFN_cambia_url(array('ud_ordenar','ud_modo','executa'), array('id',($ud_modo == 'ASC'?'DESC':'ASC'),'uso_disco'))
.'">'.PFN___('Xcol_id').'</a></th>'
.'<th style="text-align: left;">'
.'<a href="'.PFN_cambia_url(array('ud_ordenar','ud_modo','executa'), array('nome',($ud_modo == 'ASC'?'DESC':'ASC'),'uso_disco'))
.'">'.PFN___('Xcol_nome').'</a></th>'
.'<th style="text-align: left;">'
.'<a href="'.PFN_cambia_url(array('ud_ordenar','ud_modo','executa'), array('limite',($ud_modo == 'ASC'?'DESC':'ASC'),'uso_disco'))
.'">'.PFN___('Xcol_peso_limite').'</a></th>'
.'<th style="text-align: left;">'
.'<a href="'.PFN_cambia_url(array('ud_ordenar','ud_modo','executa'), array('actual',($ud_modo == 'ASC'?'DESC':'ASC'),'uso_disco'))
.'">'.PFN___('Xcol_peso_actual').'</a></th>'
.'<th style="text-align: left;">'
.'<a href="'.PFN_cambia_url(array('ud_ordenar','ud_modo','executa'), array('libre',($ud_modo == 'ASC'?'DESC':'ASC'),'uso_disco'))
.'">'.PFN___('Xcol_porcent_libre').'</a></th></tr>';
foreach ((array)$listado[$ud_ordenar] as $k => $v) {
$b++;
$txt .= '<tr'.((($b % 2) == 0)?' class="tr_par"':'').'><td>'.$listado['id'][$k].'</td>'
.'<td><a href="../raices/index.php?'
.PFN_cambia_url('id_raiz', $listado['id'][$k], false).'">'.$listado['nome'][$k].'</a></td>';
if ($listado['limite'][$k]) {
$libre = $listado['libre'][$k];
$cor_libre = ($libre > 50)?'0C0':(($libre > 25)?'FC6':(($libre > 10)?'F60':'F00'));
$txt .= '<td>'.PFN_peso($listado['limite'][$k]).'</td>'
.'<td>'.PFN_peso($listado['actual'][$k]).'</td>'
.'<td style="border: 1px solid #000;"><span style="display: block; border: 1px solid #CCC; width: '.$libre.'%; height: 15px; background-color: #'.$cor_libre.'; font-weight: bold;">'.$libre.'%</span></td></tr>';
} else {
$txt .= '<td colspan="3">'.PFN___('sen_limite').'</td></tr>';
}
}
$txt .= '</table>';
?>
| paxku/pfn | xestion/informes/uso_disco.inc.php | PHP | gpl-2.0 | 3,322 |
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information
* 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: Boss_Patchwerk
SD%Complete: 100
SDComment:
SDCategory: Naxxramas
EndScriptData
*/
#include "AI/ScriptDevAI/include/sc_common.h"
#include "naxxramas.h"
enum
{
SAY_AGGRO1 = -1533017,
SAY_AGGRO2 = -1533018,
SAY_SLAY = -1533019,
SAY_DEATH = -1533020,
EMOTE_GENERIC_BERSERK = -1000004,
EMOTE_GENERIC_ENRAGED = -1000003,
SPELL_HATEFULSTRIKE_PRIMER = 28307,
SPELL_ENRAGE = 28131,
SPELL_BERSERK = 26662,
SPELL_SLIMEBOLT = 32309
};
struct boss_patchwerkAI : public ScriptedAI
{
boss_patchwerkAI(Creature* creature) : ScriptedAI(creature)
{
m_instance = (instance_naxxramas*)creature->GetInstanceData();
Reset();
}
instance_naxxramas* m_instance;
uint32 m_hatefulStrikeTimer;
uint32 m_berserkTimer;
uint32 m_berserkSlimeBoltTimer;
uint32 m_slimeboltTimer;
bool m_isEnraged;
bool m_isBerserk;
void Reset() override
{
m_hatefulStrikeTimer = 1.2 * IN_MILLISECONDS;
m_berserkTimer = 7 * MINUTE * IN_MILLISECONDS; // Basic berserk
m_berserkSlimeBoltTimer = m_berserkTimer + 30 * IN_MILLISECONDS; // Slime Bolt berserk
m_slimeboltTimer = 10* IN_MILLISECONDS;
m_isEnraged = false;
m_isBerserk = false;
}
void KilledUnit(Unit* /*victim*/) override
{
if (urand(0, 4))
return;
DoScriptText(SAY_SLAY, m_creature);
}
void JustDied(Unit* /*killer*/) override
{
DoScriptText(SAY_DEATH, m_creature);
if (m_instance)
m_instance->SetData(TYPE_PATCHWERK, DONE);
}
void Aggro(Unit* /*who*/) override
{
DoScriptText(urand(0, 1) ? SAY_AGGRO1 : SAY_AGGRO2, m_creature);
if (m_instance)
m_instance->SetData(TYPE_PATCHWERK, IN_PROGRESS);
}
void JustReachedHome() override
{
if (m_instance)
m_instance->SetData(TYPE_PATCHWERK, FAIL);
}
void UpdateAI(const uint32 diff) override
{
if (!m_creature->SelectHostileTarget() || !m_creature->GetVictim())
return;
// Hateful Strike
if (m_hatefulStrikeTimer < diff)
{
if (DoCastSpellIfCan(m_creature, SPELL_HATEFULSTRIKE_PRIMER) == CAST_OK)
m_hatefulStrikeTimer = 1.2 * IN_MILLISECONDS;
}
else
m_hatefulStrikeTimer -= diff;
// Soft Enrage at 5%
if (!m_isEnraged)
{
if (m_creature->GetHealthPercent() < 5.0f)
{
if (DoCastSpellIfCan(m_creature, SPELL_ENRAGE) == CAST_OK)
{
DoScriptText(EMOTE_GENERIC_ENRAGED, m_creature);
m_isEnraged = true;
}
}
}
// Berserk after 7 minutes
if (!m_isBerserk)
{
if (m_berserkTimer < diff)
{
if (DoCastSpellIfCan(m_creature, SPELL_BERSERK) == CAST_OK)
{
DoScriptText(EMOTE_GENERIC_BERSERK, m_creature);
m_isBerserk = true;
}
}
else
m_berserkTimer -= diff;
}
else if (m_berserkSlimeBoltTimer < diff)
{
// Slimebolt - casted only 30 seconds after Berserking to prevent kiting
if (m_slimeboltTimer < diff)
{
DoCastSpellIfCan(m_creature->GetVictim(), SPELL_SLIMEBOLT);
m_slimeboltTimer = 1 * IN_MILLISECONDS;
}
else
m_slimeboltTimer -= diff;
}
DoMeleeAttackIfReady();
}
};
UnitAI* GetAI_boss_patchwerk(Creature* creature)
{
return new boss_patchwerkAI(creature);
}
void AddSC_boss_patchwerk()
{
Script* newScript = new Script;
newScript->Name = "boss_patchwerk";
newScript->GetAI = &GetAI_boss_patchwerk;
newScript->RegisterSelf();
}
| catterpiler74/mangos-classic | src/game/AI/ScriptDevAI/scripts/eastern_kingdoms/naxxramas/boss_patchwerk.cpp | C++ | gpl-2.0 | 4,895 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_actionlogs
*
* @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\Component\Actionlogs\Administrator\Controller;
defined('_JEXEC') or die;
use DateTimeZone;
use Exception;
use InvalidArgumentException;
use Joomla\CMS\Application\CMSApplication;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Date\Date;
use Joomla\CMS\Input\Input;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\AdminController;
use Joomla\CMS\MVC\Factory\MVCFactoryInterface;
use Joomla\CMS\Router\Route;
use Joomla\Component\Actionlogs\Administrator\Helper\ActionlogsHelper;
use Joomla\Component\Actionlogs\Administrator\Model\ActionlogsModel;
use Joomla\Utilities\ArrayHelper;
/**
* Actionlogs list controller class.
*
* @since 3.9.0
*/
class ActionlogsController extends AdminController
{
/**
* Constructor.
*
* @param array $config An optional associative array of configuration settings.
* Recognized key values include 'name', 'default_task', 'model_path', and
* 'view_path' (this list is not meant to be comprehensive).
* @param MVCFactoryInterface $factory The factory.
* @param CmsApplication $app The JApplication for the dispatcher
* @param Input $input Input
*
* @since 3.9.0
*
* @throws Exception
*/
public function __construct($config = [], MVCFactoryInterface $factory = null, $app = null, $input = null)
{
parent::__construct($config, $factory, $app, $input);
$this->registerTask('exportSelectedLogs', 'exportLogs');
}
/**
* Method to export logs
*
* @return void
*
* @since 3.9.0
*
* @throws Exception
*/
public function exportLogs()
{
// Check for request forgeries.
$this->checkToken();
$task = $this->getTask();
$pks = array();
if ($task == 'exportSelectedLogs')
{
// Get selected logs
$pks = ArrayHelper::toInteger(explode(',', $this->input->post->getString('cids')));
}
/** @var ActionlogsModel $model */
$model = $this->getModel();
// Get the logs data
$data = $model->getLogDataAsIterator($pks);
if (count($data))
{
try
{
$rows = ActionlogsHelper::getCsvData($data);
}
catch (InvalidArgumentException $exception)
{
$this->setMessage(Text::_('COM_ACTIONLOGS_ERROR_COULD_NOT_EXPORT_DATA'), 'error');
$this->setRedirect(Route::_('index.php?option=com_actionlogs&view=actionlogs', false));
return;
}
// Destroy the iterator now
unset($data);
$date = new Date('now', new DateTimeZone('UTC'));
$filename = 'logs_' . $date->format('Y-m-d_His_T');
$csvDelimiter = ComponentHelper::getComponent('com_actionlogs')->getParams()->get('csv_delimiter', ',');
$this->app->setHeader('Content-Type', 'application/csv', true)
->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '.csv"', true)
->setHeader('Cache-Control', 'must-revalidate', true)
->sendHeaders();
$output = fopen("php://output", "w");
foreach ($rows as $row)
{
fputcsv($output, $row, $csvDelimiter);
}
fclose($output);
$this->app->triggerEvent('onAfterLogExport', array());
$this->app->close();
}
else
{
$this->setMessage(Text::_('COM_ACTIONLOGS_NO_LOGS_TO_EXPORT'));
$this->setRedirect(Route::_('index.php?option=com_actionlogs&view=actionlogs', false));
}
}
/**
* Method to get a model object, loading it if required.
*
* @param string $name The model name. Optional.
* @param string $prefix The class prefix. Optional.
* @param array $config Configuration array for model. Optional.
*
* @return object The model.
*
* @since 3.9.0
*/
public function getModel($name = 'Actionlogs', $prefix = 'Administrator', $config = ['ignore_request' => true])
{
// Return the model
return parent::getModel($name, $prefix, $config);
}
/**
* Clean out the logs
*
* @return void
*
* @since 3.9.0
*/
public function purge()
{
// Check for request forgeries.
$this->checkToken();
$model = $this->getModel();
if ($model->purge())
{
$message = Text::_('COM_ACTIONLOGS_PURGE_SUCCESS');
}
else
{
$message = Text::_('COM_ACTIONLOGS_PURGE_FAIL');
}
$this->setRedirect(Route::_('index.php?option=com_actionlogs&view=actionlogs', false), $message);
}
}
| astridx/joomla-cms | administrator/components/com_actionlogs/Controller/ActionlogsController.php | PHP | gpl-2.0 | 4,575 |
<?php
/**
Template name:Homepage
*
* 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 web2feel
* @since web2feel 1.0
*/
get_header(); ?>
<img id="cycle-loader" src="../lib/images/ajax-loader.gif" />
<div id="maximage">
<?php $count = of_get_option('w2f_slide_number');
$slidecat =of_get_option('w2f_slide_categories');
$query = new WP_Query( array( 'cat' =>$slidecat,'posts_per_page' =>$count,'post_type' => 'slide' ) );
if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>
<?php $thumb = get_post_thumbnail_id();
$img_url = wp_get_attachment_url( $thumb,'full' ); ?>
<img class="slide-image" src="<?php echo $img_url ?>"/>
<?php endwhile; endif; ?>
</div>
<div class="mesh"></div>
<div class="dome">
<ul>
<li id="arrow_left"></li>
<li id="arrow_right"></li>
</ul>
</div>
<?php get_footer(); ?> | sota1236/blog.koe11.net | wp-content/themes/Helix/homepage.php | PHP | gpl-2.0 | 1,077 |
require 'fileutils'
require 'logger'
require 'xdg'
# Maid cleans up according to the given rules, logging what it does.
#
# TODO: Rename to something less ambiguous, e.g. "cleaning agent", "cleaner", "vacuum", etc. Having this class within
# the `Maid` module makes things confusing.
class Maid::Maid
DEFAULTS = {
:progname => 'Maid',
:log_device => File.expand_path('~/.maid/maid.log'),
:rules_path => File.expand_path('~/.maid/rules.rb'),
:file_options => { :noop => false }, # for `FileUtils`
}.freeze
attr_reader :file_options, :logger, :log_device, :rules, :rules_path, :trash_path
include ::Maid::Tools
# Make a new Maid, setting up paths for the log and trash.
#
# Sane defaults for a log and trash path are set for Mac OS X, but they can easily be overridden like so:
#
# Maid::Maid.new(:log_device => '/home/username/log/maid.log', :trash_path => '/home/username/my_trash')
#
def initialize(options = {})
options = DEFAULTS.merge(options.reject { |k, v| v.nil? })
# TODO: Refactor and simplify (see also https://github.com/benjaminoakes/maid/pull/48#discussion_r1683942)
@logger = unless options[:logger]
@log_device = options[:log_device]
FileUtils.mkdir_p(File.dirname(@log_device)) unless @log_device.kind_of?(IO)
Logger.new(@log_device)
else
options[:logger]
end
@logger.progname = options[:progname]
@logger.formatter = options[:log_formatter] if options[:log_formatter]
@rules_path = options[:rules_path]
@trash_path = options[:trash_path] || default_trash_path
@file_options = options[:file_options]
# Just in case they aren't there...
FileUtils.mkdir_p(File.expand_path('~/.maid'))
FileUtils.mkdir_p(@trash_path)
@rules = []
end
# Start cleaning, based on the rules defined at rules_path.
def clean
unless @log_device.kind_of?(IO)
@logger.info "v#{ Maid::VERSION }"
@logger.info 'Started'
end
follow_rules
unless @log_device.kind_of?(IO)
@logger.info 'Finished'
end
end
# Add the rules at rules_path.
def load_rules
path = @rules_path
Maid.with_instance(self) do
# Using `Kernel` here to help with testability.
#
# `Kernel.load` must be used for non-".rb" files to be required, it seems.
Kernel.load(path)
end
rescue LoadError => e
STDERR.puts e.message
end
# Register a rule with a description and instructions (lambda function).
def rule(description, &instructions)
@rules << ::Maid::Rule.new(description, instructions)
end
# Follow all registered rules.
def follow_rules
@rules.each do |rule|
@logger.info("Rule: #{ rule.description }")
rule.follow
end
end
# Run a shell command.
#--
# Delegates to `Kernel.\``. Made primarily for testing other commands and some error handling.
def cmd(command) #:nodoc:
if supported_command?(command)
%x(#{ command })
else
raise ArgumentError, "Unsupported system command: #{ command.inspect }"
end
end
private
# Does the OS support this command?
def supported_command?(command) #:nodoc:
@@supported_commands ||= {}
command_name = command.strip.split(/\s+/)[0]
supported = @@supported_commands[command_name]
# TODO: Instead of using `which`, use an alternative listed at:
#
# http://stackoverflow.com/questions/592620/check-if-a-program-exists-from-a-bash-script
@@supported_commands[command_name] = supported ? supported : !%x(which #{ command_name }).empty?
end
def default_trash_path
# TODO: Refactor module declaration so this can be `Platform`
if Maid::Platform.linux?
# See the [FreeDesktop.org Trash specification](http://www.ramendik.ru/docs/trashspec.html)
path = "#{ XDG['DATA_HOME'] }/Trash/files"
elsif Maid::Platform.osx?
path = File.expand_path('~/.Trash')
else
raise NotImplementedError, "Unknown default trash path (unsupported host OS: #{ Maid::Platform.host_os.inspect })"
end
"#{ path }/"
end
end
| nicosuave/maid | lib/maid/maid.rb | Ruby | gpl-2.0 | 4,091 |
/*
* Copyright 2013 IMOS
*
* The AODN/IMOS Portal is distributed under the terms of the GNU General Public License
*
*/
describe('Portal.data.GeoNetworkRecord', function() {
var record;
beforeEach(function() {
record = new Portal.data.GeoNetworkRecord({
abstract: 'the abstract',
links: [
{
href: 'http://geoserver.imos.org.au/geoserver/wms',
name: 'imos:radar_stations',
protocol: 'OGC:WMS-1.1.1-http-get-map',
title: 'ACORN Radar Stations',
type: 'application/vnd.ogc.wms_xml'
},
{
href: 'http://geonetwork.imos.org.au/1234',
name: 'imos:radar_stations',
protocol: 'WWW:LINK-1.0-http--metadata-URL',
title: 'ACORN Radar Stations',
type: 'text/html'
}
],
title: 'the layer title',
wmsLayer: {
server: {
uri: "server_url"
},
params: {
LAYERS: 'layer name',
CQL_FILTER: 'cql_filter'
},
someUnusedField: 'la la la'
}
});
});
describe('wms link', function() {
it('has wms link', function() {
record.get('links')[0].protocol = 'OGC:WMS-1.1.1-http-get-map';
expect(record.hasWmsLink()).toBeTruthy();
});
it('does not have wms link', function() {
record.get('links')[0].protocol = 'some protocol';
expect(record.hasWmsLink()).toBeFalsy();
});
it('does not have any links', function() {
record.set('links', undefined);
expect(record.hasWmsLink()).toBeFalsy();
});
it('get first wms link', function() {
record.get('links')[0].protocol = 'OGC:WMS-1.1.1-http-get-map';
var link = record.getFirstWmsLink();
expect(link.server.uri).toBe('http://geoserver.imos.org.au/geoserver/wms');
expect(link.protocol).toBe('OGC:WMS-1.1.1-http-get-map');
});
});
});
| IMASau/aodn-portal | src/test/javascript/portal/data/GeoNetworkRecordSpec.js | JavaScript | gpl-3.0 | 2,250 |
/*
Copyright (C) 2019-2020, Kevin Andre <hyperquantum@gmail.com>
This file is part of PMP (Party Music Player).
PMP 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.
PMP 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 PMP. If not, see <http://www.gnu.org/licenses/>.
*/
#include "test_networkutil.h"
#include "common/networkutil.h"
#include <QtTest/QTest>
using namespace PMP;
void TestNetworkUtil::fitsIn2BytesSigned()
{
QVERIFY(NetworkUtil::fitsIn2BytesSigned(0));
QVERIFY(NetworkUtil::fitsIn2BytesSigned(32767));
QVERIFY(NetworkUtil::fitsIn2BytesSigned(-32768));
QVERIFY(!NetworkUtil::fitsIn2BytesSigned(32768));
QVERIFY(!NetworkUtil::fitsIn2BytesSigned(-32769));
}
void TestNetworkUtil::to2BytesSigned()
{
{
bool error = false;
qint16 result = NetworkUtil::to2BytesSigned(32767, error, "test1");
QCOMPARE(result, 32767);
QCOMPARE(error, false);
}
{
bool error = false;
qint16 result = NetworkUtil::to2BytesSigned(-32768, error, "test1");
QCOMPARE(result, -32768);
QCOMPARE(error, false);
}
{
bool error = false;
qint16 result = NetworkUtil::to2BytesSigned(32768, error, "test1");
QCOMPARE(result, 0);
QCOMPARE(error, true);
}
{
bool error = false;
qint16 result = NetworkUtil::to2BytesSigned(-32769, error, "test1");
QCOMPARE(result, 0);
QCOMPARE(error, true);
}
}
void TestNetworkUtil::appendByte() {
QByteArray array;
NetworkUtil::appendByte(array, '\0');
NetworkUtil::appendByte(array, uchar(9));
NetworkUtil::appendByte(array, uchar(30));
NetworkUtil::appendByte(array, uchar(73));
NetworkUtil::appendByte(array, uchar(127));
NetworkUtil::appendByte(array, uchar(255));
QCOMPARE(array.size(), 6);
QCOMPARE(char(array[0]), '\0');
QCOMPARE(char(array[1]), char(9));
QCOMPARE(char(array[2]), char(30));
QCOMPARE(char(array[3]), char(73));
QCOMPARE(char(array[4]), char(127));
QCOMPARE(char(array[5]), char(255));
}
void TestNetworkUtil::getByte() {
QByteArray array;
array.append('\0');
array.append(char(9));
array.append(char(30));
array.append(char(73));
array.append(char(127));
array.append(char(255));
QCOMPARE(array.size(), 6);
QCOMPARE(NetworkUtil::getByte(array, 0), uchar('\0'));
QCOMPARE(NetworkUtil::getByte(array, 1), uchar(9));
QCOMPARE(NetworkUtil::getByte(array, 2), uchar(30));
QCOMPARE(NetworkUtil::getByte(array, 3), uchar(73));
QCOMPARE(NetworkUtil::getByte(array, 4), uchar(127));
QCOMPARE(NetworkUtil::getByte(array, 5), uchar(255));
}
void TestNetworkUtil::append2Bytes() {
QByteArray array;
NetworkUtil::append2Bytes(array, 0u);
NetworkUtil::append2Bytes(array, 30u);
NetworkUtil::append2Bytes(array, 127u);
NetworkUtil::append2Bytes(array, 255u);
NetworkUtil::append2Bytes(array, 256u);
NetworkUtil::append2Bytes(array, 8765u);
NetworkUtil::append2Bytes(array, 26587u);
NetworkUtil::append2Bytes(array, 65535u);
QCOMPARE(array.size(), 8 * 2);
QCOMPARE(char(array[0]), '\0');
QCOMPARE(char(array[1]), '\0');
QCOMPARE(char(array[2]), '\0');
QCOMPARE(char(array[3]), char(30));
QCOMPARE(char(array[4]), '\0');
QCOMPARE(char(array[5]), char(127));
QCOMPARE(char(array[6]), '\0');
QCOMPARE(char(array[7]), char(255));
QCOMPARE(char(array[8]), char(1));
QCOMPARE(char(array[9]), char(0));
QCOMPARE(char(array[10]), '\x22');
QCOMPARE(char(array[11]), '\x3D');
QCOMPARE(char(array[12]), '\x67');
QCOMPARE(char(array[13]), '\xDB');
QCOMPARE(char(array[14]), '\xFF');
QCOMPARE(char(array[15]), '\xFF');
}
void TestNetworkUtil::get2Bytes() {
QByteArray array;
array.append('\0');
array.append('\0');
array.append('\0');
array.append(char(30));
array.append('\0');
array.append(char(127));
array.append('\0');
array.append(char(255));
array.append(char(1));
array.append(char(0));
array.append('\x22');
array.append('\x3D');
array.append('\x67');
array.append('\xDB');
array.append('\xFF');
array.append('\xFF');
QCOMPARE(array.size(), 8 * 2);
QCOMPARE(NetworkUtil::get2Bytes(array, 0), quint16(0u));
QCOMPARE(NetworkUtil::get2Bytes(array, 2), quint16(30u));
QCOMPARE(NetworkUtil::get2Bytes(array, 4), quint16(127u));
QCOMPARE(NetworkUtil::get2Bytes(array, 6), quint16(255u));
QCOMPARE(NetworkUtil::get2Bytes(array, 8), quint16(256u));
QCOMPARE(NetworkUtil::get2Bytes(array, 10), quint16(8765u));
QCOMPARE(NetworkUtil::get2Bytes(array, 12), quint16(26587u));
QCOMPARE(NetworkUtil::get2Bytes(array, 14), quint16(65535u));
}
void TestNetworkUtil::append4Bytes() {
QByteArray array;
NetworkUtil::append4Bytes(array, 0u);
NetworkUtil::append4Bytes(array, 5544u);
NetworkUtil::append4Bytes(array, 34088u);
NetworkUtil::append4Bytes(array, 9605332u);
NetworkUtil::append4Bytes(array, 4222618390u);
QCOMPARE(array.size(), 5 * 4);
QCOMPARE(char(array[0]), '\0');
QCOMPARE(char(array[1]), '\0');
QCOMPARE(char(array[2]), '\0');
QCOMPARE(char(array[3]), '\0');
QCOMPARE(char(array[4]), '\0');
QCOMPARE(char(array[5]), '\0');
QCOMPARE(char(array[6]), '\x15');
QCOMPARE(char(array[7]), '\xA8');
QCOMPARE(char(array[8]), '\0');
QCOMPARE(char(array[9]), '\0');
QCOMPARE(char(array[10]), '\x85');
QCOMPARE(char(array[11]), '\x28');
QCOMPARE(char(array[12]), '\0');
QCOMPARE(char(array[13]), '\x92');
QCOMPARE(char(array[14]), '\x90');
QCOMPARE(char(array[15]), '\xD4');
QCOMPARE(char(array[16]), '\xFB');
QCOMPARE(char(array[17]), '\xB0');
QCOMPARE(char(array[18]), '\x0B');
QCOMPARE(char(array[19]), '\x16');
}
void TestNetworkUtil::get4Bytes() {
QByteArray array;
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\x15');
array.append('\xA8');
array.append('\0');
array.append('\0');
array.append('\x85');
array.append('\x28');
array.append('\0');
array.append('\x92');
array.append('\x90');
array.append('\xD4');
array.append('\xFB');
array.append('\xB0');
array.append('\x0B');
array.append('\x16');
QCOMPARE(array.size(), 5 * 4);
QCOMPARE(NetworkUtil::get4Bytes(array, 0), quint32(0u));
QCOMPARE(NetworkUtil::get4Bytes(array, 4), quint32(5544u));
QCOMPARE(NetworkUtil::get4Bytes(array, 8), quint32(34088u));
QCOMPARE(NetworkUtil::get4Bytes(array, 12), quint32(9605332u));
QCOMPARE(NetworkUtil::get4Bytes(array, 16), quint32(4222618390u));
}
void TestNetworkUtil::append8Bytes() {
QByteArray array;
NetworkUtil::append8Bytes(array, 0u);
NetworkUtil::append8Bytes(array, 56542215u);
NetworkUtil::append8Bytes(array, 9067630524680188ull);
NetworkUtil::append8Bytes(array, 0x8000000000000000ull);
NetworkUtil::append8Bytes(array, 0xFE2A54BB12CF5415ull);
QCOMPARE(array.size(), 5 * 8);
QCOMPARE(char(array[0]), '\0');
QCOMPARE(char(array[1]), '\0');
QCOMPARE(char(array[2]), '\0');
QCOMPARE(char(array[3]), '\0');
QCOMPARE(char(array[4]), '\0');
QCOMPARE(char(array[5]), '\0');
QCOMPARE(char(array[6]), '\0');
QCOMPARE(char(array[7]), '\0');
QCOMPARE(char(array[8]), '\0');
QCOMPARE(char(array[9]), '\0');
QCOMPARE(char(array[10]), '\0');
QCOMPARE(char(array[11]), '\0');
QCOMPARE(char(array[12]), '\x03');
QCOMPARE(char(array[13]), '\x5E');
QCOMPARE(char(array[14]), '\xC4');
QCOMPARE(char(array[15]), '\x07');
QCOMPARE(char(array[16]), '\0');
QCOMPARE(char(array[17]), '\x20');
QCOMPARE(char(array[18]), '\x36');
QCOMPARE(char(array[19]), '\xF6');
QCOMPARE(char(array[20]), '\x40');
QCOMPARE(char(array[21]), '\x60');
QCOMPARE(char(array[22]), '\xC7');
QCOMPARE(char(array[23]), '\xFC');
QCOMPARE(char(array[24]), '\x80');
QCOMPARE(char(array[25]), '\x00');
QCOMPARE(char(array[26]), '\x00');
QCOMPARE(char(array[27]), '\x00');
QCOMPARE(char(array[28]), '\x00');
QCOMPARE(char(array[29]), '\x00');
QCOMPARE(char(array[30]), '\x00');
QCOMPARE(char(array[31]), '\x00');
QCOMPARE(char(array[32]), '\xFE');
QCOMPARE(char(array[33]), '\x2A');
QCOMPARE(char(array[34]), '\x54');
QCOMPARE(char(array[35]), '\xBB');
QCOMPARE(char(array[36]), '\x12');
QCOMPARE(char(array[37]), '\xCF');
QCOMPARE(char(array[38]), '\x54');
QCOMPARE(char(array[39]), '\x15');
}
void TestNetworkUtil::get8Bytes() {
QByteArray array;
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\x03');
array.append('\x5E');
array.append('\xC4');
array.append('\x07');
array.append('\0');
array.append('\x20');
array.append('\x36');
array.append('\xF6');
array.append('\x40');
array.append('\x60');
array.append('\xC7');
array.append('\xFC');
array.append('\x80');
array.append('\x00');
array.append('\x00');
array.append('\x00');
array.append('\x00');
array.append('\x00');
array.append('\x00');
array.append('\x00');
array.append('\xFE');
array.append('\x2A');
array.append('\x54');
array.append('\xBB');
array.append('\x12');
array.append('\xCF');
array.append('\x54');
array.append('\x15');
QCOMPARE(array.size(), 5 * 8);
QCOMPARE(NetworkUtil::get8Bytes(array, 0), quint64(0u));
QCOMPARE(NetworkUtil::get8Bytes(array, 8), quint64(56542215u));
QCOMPARE(NetworkUtil::get8Bytes(array, 16), quint64(9067630524680188ull));
QCOMPARE(NetworkUtil::get8Bytes(array, 24), quint64(0x8000000000000000ull));
QCOMPARE(NetworkUtil::get8Bytes(array, 32), quint64(0xFE2A54BB12CF5415ull));
}
void TestNetworkUtil::get2BytesSigned() {
QByteArray array;
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFE');
array.append('\0');
array.append('\x05');
QCOMPARE(array.size(), 3 * 2);
QCOMPARE(NetworkUtil::get2BytesSigned(array, 0), qint16(-1));
QCOMPARE(NetworkUtil::get2BytesSigned(array, 2), qint16(-2));
QCOMPARE(NetworkUtil::get2BytesSigned(array, 4), qint16(5));
}
void TestNetworkUtil::get4BytesSigned() {
QByteArray array;
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFE');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\x05');
QCOMPARE(array.size(), 3 * 4);
QCOMPARE(NetworkUtil::get4BytesSigned(array, 0), qint32(-1));
QCOMPARE(NetworkUtil::get4BytesSigned(array, 4), qint32(-2));
QCOMPARE(NetworkUtil::get4BytesSigned(array, 8), qint32(5));
}
void TestNetworkUtil::get8BytesSigned() {
QByteArray array;
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFF');
array.append('\xFE');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\0');
array.append('\x05');
QCOMPARE(array.size(), 3 * 8);
QCOMPARE(NetworkUtil::get8BytesSigned(array, 0), qint64(-1));
QCOMPARE(NetworkUtil::get8BytesSigned(array, 8), qint64(-2));
QCOMPARE(NetworkUtil::get8BytesSigned(array, 16), qint64(5));
}
void TestNetworkUtil::getByteUnsignedToInt() {
QByteArray array;
array.append('\xFF');
array.append('\0');
array.append(char(30));
QCOMPARE(array.size(), 3 * 1);
QCOMPARE(NetworkUtil::getByteUnsignedToInt(array, 0), 255);
QCOMPARE(NetworkUtil::getByteUnsignedToInt(array, 1), 0);
QCOMPARE(NetworkUtil::getByteUnsignedToInt(array, 2), 30);
}
void TestNetworkUtil::get2BytesUnsignedToInt() {
QByteArray array;
array.append('\xFF');
array.append('\xFF');
array.append('\0');
array.append(char(30));
QCOMPARE(array.size(), 2 * 2);
QCOMPARE(NetworkUtil::get2BytesUnsignedToInt(array, 0), 65535);
QCOMPARE(NetworkUtil::get2BytesUnsignedToInt(array, 2), 30);
}
void TestNetworkUtil::appendByteUnsigned() {
QByteArray array;
NetworkUtil::appendByteUnsigned(array, 255);
NetworkUtil::appendByteUnsigned(array, 128);
NetworkUtil::appendByteUnsigned(array, 33);
NetworkUtil::appendByteUnsigned(array, 0);
QCOMPARE(array.size(), 4 * 1);
QCOMPARE(char(array[0]), '\xFF');
QCOMPARE(char(array[1]), char(128));
QCOMPARE(char(array[2]), char(33));
QCOMPARE(char(array[3]), char(0));
}
void TestNetworkUtil::append2BytesUnsigned() {
QByteArray array;
NetworkUtil::append2BytesUnsigned(array, 0xFFFF);
NetworkUtil::append2BytesUnsigned(array, 0xFF07);
NetworkUtil::append2BytesUnsigned(array, 256);
NetworkUtil::append2BytesUnsigned(array, 0);
QCOMPARE(array.size(), 4 * 2);
QCOMPARE(char(array[0]), '\xFF');
QCOMPARE(char(array[1]), '\xFF');
QCOMPARE(char(array[2]), '\xFF');
QCOMPARE(char(array[3]), '\x07');
QCOMPARE(char(array[4]), char(1));
QCOMPARE(char(array[5]), char(0));
QCOMPARE(char(array[6]), char(0));
QCOMPARE(char(array[7]), char(0));
}
void TestNetworkUtil::append2BytesSigned() {
QByteArray array;
NetworkUtil::append2BytesSigned(array, qint16(-1));
NetworkUtil::append2BytesSigned(array, qint16(-1000));
QCOMPARE(array.size(), 2 * 2);
QCOMPARE(char(array[0]), '\xFF');
QCOMPARE(char(array[1]), '\xFF');
QCOMPARE(char(array[2]), '\xFC');
QCOMPARE(char(array[3]), '\x18');
}
void TestNetworkUtil::append4BytesSigned() {
QByteArray array;
NetworkUtil::append4BytesSigned(array, qint32(-1));
NetworkUtil::append4BytesSigned(array, qint32(-1000));
NetworkUtil::append4BytesSigned(array, qint32(-1000000000));
QCOMPARE(array.size(), 3 * 4);
QCOMPARE(char(array[0]), '\xFF');
QCOMPARE(char(array[1]), '\xFF');
QCOMPARE(char(array[2]), '\xFF');
QCOMPARE(char(array[3]), '\xFF');
QCOMPARE(char(array[4]), '\xFF');
QCOMPARE(char(array[5]), '\xFF');
QCOMPARE(char(array[6]), '\xFC');
QCOMPARE(char(array[7]), '\x18');
QCOMPARE(char(array[8]), '\xC4');
QCOMPARE(char(array[9]), '\x65');
QCOMPARE(char(array[10]), '\x36');
QCOMPARE(char(array[11]), '\x00');
}
void TestNetworkUtil::append8BytesSigned() {
QByteArray array;
NetworkUtil::append8BytesSigned(array, qint64(-1));
NetworkUtil::append8BytesSigned(array, qint64(-1000));
NetworkUtil::append8BytesSigned(array, qint64(-1000000000));
NetworkUtil::append8BytesSigned(array, qint64(-1000000000000LL));
NetworkUtil::append8BytesSigned(array, qint64(-1000000000000001LL));
NetworkUtil::append8BytesSigned(array, qint64(-100000000000559010LL));
QCOMPARE(array.size(), 6 * 8);
QCOMPARE(char(array[0]), '\xFF');
QCOMPARE(char(array[1]), '\xFF');
QCOMPARE(char(array[2]), '\xFF');
QCOMPARE(char(array[3]), '\xFF');
QCOMPARE(char(array[4]), '\xFF');
QCOMPARE(char(array[5]), '\xFF');
QCOMPARE(char(array[6]), '\xFF');
QCOMPARE(char(array[7]), '\xFF');
QCOMPARE(char(array[8]), '\xFF');
QCOMPARE(char(array[9]), '\xFF');
QCOMPARE(char(array[10]), '\xFF');
QCOMPARE(char(array[11]), '\xFF');
QCOMPARE(char(array[12]), '\xFF');
QCOMPARE(char(array[13]), '\xFF');
QCOMPARE(char(array[14]), '\xFC');
QCOMPARE(char(array[15]), '\x18');
QCOMPARE(char(array[16]), '\xFF');
QCOMPARE(char(array[17]), '\xFF');
QCOMPARE(char(array[18]), '\xFF');
QCOMPARE(char(array[19]), '\xFF');
QCOMPARE(char(array[20]), '\xC4');
QCOMPARE(char(array[21]), '\x65');
QCOMPARE(char(array[22]), '\x36');
QCOMPARE(char(array[23]), '\x00');
QCOMPARE(char(array[24]), '\xFF');
QCOMPARE(char(array[25]), '\xFF');
QCOMPARE(char(array[26]), '\xFF');
QCOMPARE(char(array[27]), '\x17');
QCOMPARE(char(array[28]), '\x2B');
QCOMPARE(char(array[29]), '\x5A');
QCOMPARE(char(array[30]), '\xF0');
QCOMPARE(char(array[31]), '\x00');
QCOMPARE(char(array[32]), '\xFF');
QCOMPARE(char(array[33]), '\xFC');
QCOMPARE(char(array[34]), '\x72');
QCOMPARE(char(array[35]), '\x81');
QCOMPARE(char(array[36]), '\x5B');
QCOMPARE(char(array[37]), '\x39');
QCOMPARE(char(array[38]), '\x7F');
QCOMPARE(char(array[39]), '\xFF');
QCOMPARE(char(array[40]), '\xFE');
QCOMPARE(char(array[41]), '\x9C');
QCOMPARE(char(array[42]), '\xBA');
QCOMPARE(char(array[43]), '\x87');
QCOMPARE(char(array[44]), '\xA2');
QCOMPARE(char(array[45]), '\x6D');
QCOMPARE(char(array[46]), '\x78');
QCOMPARE(char(array[47]), '\x5E');
}
void TestNetworkUtil::getUtf8String() {
QByteArray array;
array.append('p');
array.append('i');
array.append('z');
array.append('z');
array.append('a');
QCOMPARE(NetworkUtil::getUtf8String(array, 0, 5), QString("pizza"));
QCOMPARE(NetworkUtil::getUtf8String(array, 0, 2), QString("pi"));
//array.clear();
// TODO : test with non-ascii characters
}
QTEST_MAIN(TestNetworkUtil)
| hyperquantum/PMP | testing/test_networkutil.cpp | C++ | gpl-3.0 | 18,365 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
corto = 10
largo = long(corto)
print type(corto)
print type(largo)
| psicobyte/ejemplos-python | cap5/p62.py | Python | gpl-3.0 | 112 |
package net.bounceme.chronos.utils.assemblers;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.bounceme.chronos.utils.common.Constantes;
import net.bounceme.chronos.utils.exceptions.AssembleException;
/**
* Clase genérica que implementa el comportamiento de Assembler. Sigue el patrón
* de diseño template-method.
*
* @author frederik
*
* @param <SOURCE>
* @param <TARGET>
*/
public abstract class GenericAssembler<SOURCE, TARGET> implements Assembler<SOURCE, TARGET> {
protected Logger logger = LoggerFactory.getLogger(GenericAssembler.class);
private Class<SOURCE> classSource;
private Class<TARGET> classTarget;
public GenericAssembler(Class<SOURCE> classSource, Class<TARGET> classTarget) {
this.classSource = classSource;
this.classTarget = classTarget;
}
/**
* @return
* @throws AssembleException
*/
protected SOURCE newSourceInstance() {
try {
return (classSource!=null) ? (SOURCE) classSource.newInstance() : null;
} catch (InstantiationException | IllegalAccessException e) {
return null;
}
}
/**
* @return
* @throws AssembleException
*/
protected TARGET newTargetInstance() {
try {
return (classTarget!=null) ? (TARGET) classTarget.newInstance() : null;
} catch (InstantiationException | IllegalAccessException e) {
logger.error(e.getMessage());
return null;
}
}
/**
* @return
*/
protected Class<SOURCE> getClassSource() {
return classSource;
}
/**
* @return
*/
protected Class<TARGET> getClassTarget() {
return classTarget;
}
/* (non-Javadoc)
* @see net.bounceme.chronos.utils.assemblers.Assembler#assemble(java.util.Collection)
*/
public final Collection<TARGET> assemble(Collection<SOURCE> source) {
if (source == null || source.isEmpty()) {
return new ArrayList<TARGET>(0);
}
List<TARGET> items = new ArrayList<TARGET>(source.size());
for (SOURCE s : source) {
items.add(assemble(s));
}
return items;
}
/* (non-Javadoc)
* @see net.bounceme.chronos.utils.assemblers.Assembler#assemble(java.util.Collection)
*/
@SuppressWarnings(Constantes.UNCHECKED)
public final TARGET[] assemble(SOURCE[] source) {
if (source == null || source.length == 0) {
return null;
}
TARGET[] items = (TARGET[]) Array.newInstance(classTarget, source.length);
int index = 0;
for (SOURCE s : source) {
items[index] = assemble(s);
index++;
}
return items;
}
}
| federicomartinlara1976/chronos-libs | chronos-utils/src/main/java/net/bounceme/chronos/utils/assemblers/GenericAssembler.java | Java | gpl-3.0 | 2,716 |
package com.forgeessentials.util.AreaSelector;
import net.minecraft.world.World;
import com.forgeessentials.data.api.SaveableObject.SaveableField;
import com.forgeessentials.data.api.SaveableObject.UniqueLoadingKey;
public class WorldArea extends AreaBase
{
@SaveableField
public int dim;
public WorldArea(World world, Point start, Point end)
{
super(start, end);
dim = world.provider.dimensionId;
}
public WorldArea(int dim, Point start, Point end)
{
super(start, end);
this.dim = dim;
}
public WorldArea(int dim, AreaBase area)
{
super(area.getHighPoint(), area.getLowPoint());
this.dim = dim;
}
public WorldArea(World world, AreaBase area)
{
super(area.getHighPoint(), area.getLowPoint());
dim = world.provider.dimensionId;
}
public boolean contains(WorldPoint p)
{
if (p.dim == dim)
return super.contains(p);
else
return false;
}
public boolean contains(WorldArea area)
{
if (area.dim == dim)
return super.contains(area);
else
return false;
}
public boolean intersectsWith(WorldArea area)
{
if (area.dim == dim)
return super.intersectsWith(area);
else
return false;
}
public AreaBase getIntersection(WorldArea area)
{
if (area.dim == dim)
return super.getIntersection(area);
else
return null;
}
public boolean makesCuboidWith(WorldArea area)
{
if (area.dim == dim)
return super.makesCuboidWith(area);
else
return false;
}
@UniqueLoadingKey()
private String getLoadingField()
{
return "WorldArea" + this;
}
@Override
public String toString()
{
return " { " + dim + " , " + getHighPoint().toString() + " , " + getLowPoint().toString() + " }";
}
}
| 14mRh4X0r/ForgeEssentialsMain | src/main/java/com/forgeessentials/util/AreaSelector/WorldArea.java | Java | gpl-3.0 | 1,671 |
/**
Template Controllers
@module Templates
*/
/**
The dashboard template
@class [template] views_dashboard
@constructor
*/
Template['views_dashboard'].helpers({
/**
Get all current wallets
@method (wallets)
*/
'wallets': function(disabled){
var wallets = Wallets.find({disabled: disabled}, {sort: {creationBlock: 1}}).fetch();
// sort wallets by balance
wallets.sort(Helpers.sortByBalance);
return wallets;
},
/**
Get all current accounts
@method (accounts)
*/
'accounts': function(){
// balance need to be present, to show only full inserted accounts (not ones added by mist.requestAccount)
var accounts = EthAccounts.find({name: {$exists: true}}, {sort: {name: 1}}).fetch();
accounts.sort(Helpers.sortByBalance);
return accounts;
},
/**
Are there any accounts?
@method (hasAccounts)
*/
'hasAccounts' : function() {
return (EthAccounts.find().count() > 0);
},
/**
Are there any accounts?
@method (hasAccounts)
*/
'hasMinimumBalance' : function() {
var enoughBalance = false;
_.each(_.pluck(EthAccounts.find({}).fetch(), 'balance'), function(bal){
if(new BigNumber(bal, '10').gt(1000000000000000000)) enoughBalance = true;
});
return enoughBalance;
},
/**
Get all transactions
@method (allTransactions)
*/
'allTransactions': function(){
return Transactions.find({}, {sort: {timestamp: -1}}).count();
},
/**
Returns an array of pending confirmations, from all accounts
@method (pendingConfirmations)
@return {Array}
*/
'pendingConfirmations': function(){
return _.pluck(PendingConfirmations.find({operation: {$exists: true}, confirmedOwners: {$ne: []}}).fetch(), '_id');
}
});
Template['views_dashboard'].events({
/**
Request to create an account in mist
@event click .create.account
*/
'click .create.account': function(e){
e.preventDefault();
mist.requestAccount(function(e, account) {
if(!e) {
account = account.toLowerCase();
EthAccounts.upsert({address: account}, {$set: {
address: account,
new: true
}});
}
});
}
}); | EarthDollar/ed-meteor-dapp-wallet | app/client/templates/views/dashboard.js | JavaScript | gpl-3.0 | 2,400 |
package io.robusta.upload.api;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/deletefiledropbox")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
public class DeleteFileDropboxServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
@EJB
private DropboxService dbs;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
String path = req.getParameter("filename");
dbs.delete("/"+path);
resp.sendRedirect(req.getContextPath() + "/accueil");
} catch (Exception e) {
e.printStackTrace();
req.setAttribute("message", "Erreur de fichier, réessayez");
resp.sendRedirect(req.getContextPath() + "/accueil");
}
}
}
| Quntn/projetPOX | src/main/java/io/robusta/upload/api/DeleteFileDropboxServlet.java | Java | gpl-3.0 | 1,142 |
#include <cstdio>
int b[8] = {0,1,10,11,100,101,110,111};
int main()
{
char c = getchar();
printf("%d", b[c-'0']);
while((c = getchar()) != '\n')
printf("%03d", b[c-'0']);
}
| Yoon-jae/Algorithm_BOJ | problem/1212/1212.cpp | C++ | gpl-3.0 | 194 |
/**
* @brief
*
* @file
* @ingroup python
*/
#include <src/common.hpp>
#include "genesis/genesis.hpp"
using namespace ::genesis::tree;
PYTHON_EXPORT_FUNCTIONS( tree_function_operators_export, ::genesis::tree, scope )
{
scope.def(
"convert",
( Tree ( * )( Tree const &, std::function< std::unique_ptr< BaseNodeData >(BaseNodeData const &node_data)>, std::function< std::unique_ptr< BaseEdgeData >(BaseEdgeData const &edge_data)> ))( &::genesis::tree::convert ),
pybind11::arg("source"),
pybind11::arg("node_data_converter"),
pybind11::arg("edge_data_converter")
);
scope.def(
"edge_between",
( TreeEdge * ( * )( TreeNode &, TreeNode & ))( &::genesis::tree::edge_between ),
pybind11::arg("lhs"),
pybind11::arg("rhs")
);
scope.def(
"edge_between",
( TreeEdge const * ( * )( TreeNode const &, TreeNode const & ))( &::genesis::tree::edge_between ),
pybind11::arg("lhs"),
pybind11::arg("rhs")
);
scope.def(
"belongs_to",
( bool ( * )( Tree const &, TreeEdge const & ))( &::genesis::tree::belongs_to ),
pybind11::arg("tree"),
pybind11::arg("edge")
);
scope.def(
"belongs_to",
( bool ( * )( Tree const &, TreeLink const & ))( &::genesis::tree::belongs_to ),
pybind11::arg("tree"),
pybind11::arg("link")
);
scope.def(
"belongs_to",
( bool ( * )( Tree const &, TreeNode const & ))( &::genesis::tree::belongs_to ),
pybind11::arg("tree"),
pybind11::arg("node")
);
scope.def(
"belongs_to",
( bool ( * )( TreeEdge const &, Tree const & ))( &::genesis::tree::belongs_to ),
pybind11::arg("edge"),
pybind11::arg("tree")
);
scope.def(
"belongs_to",
( bool ( * )( TreeLink const &, Tree const & ))( &::genesis::tree::belongs_to ),
pybind11::arg("link"),
pybind11::arg("tree")
);
scope.def(
"belongs_to",
( bool ( * )( TreeNode const &, Tree const & ))( &::genesis::tree::belongs_to ),
pybind11::arg("node"),
pybind11::arg("tree")
);
scope.def(
"equal",
( bool ( * )( Tree const &, Tree const &, std::function< bool(TreeNode const &, TreeNode const &) >, std::function< bool(TreeEdge const &, TreeEdge const &) > ))( &::genesis::tree::equal ),
pybind11::arg("lhs"),
pybind11::arg("rhs"),
pybind11::arg("node_comparator"),
pybind11::arg("edge_comparator")
);
scope.def(
"identical_topology",
( bool ( * )( Tree const &, Tree const & ))( &::genesis::tree::identical_topology ),
pybind11::arg("lhs"),
pybind11::arg("rhs")
);
scope.def(
"validate_topology",
( bool ( * )( Tree const & ))( &::genesis::tree::validate_topology ),
pybind11::arg("tree")
);
scope.def(
"print_gist",
( std::string ( * )( Tree const &, int ))( &::genesis::tree::print_gist ),
pybind11::arg("tree"),
pybind11::arg("items")=(int)(10)
);
scope.def(
"print_info",
( std::string ( * )( Tree const & ))( &::genesis::tree::print_info ),
pybind11::arg("tree")
);
scope.def(
"print_info",
( std::string ( * )( TreeEdge const & ))( &::genesis::tree::print_info ),
pybind11::arg("edge")
);
scope.def(
"print_info",
( std::string ( * )( TreeLink const & ))( &::genesis::tree::print_info ),
pybind11::arg("link")
);
scope.def(
"print_info",
( std::string ( * )( TreeNode const & ))( &::genesis::tree::print_info ),
pybind11::arg("node")
);
}
| lczech/genesis | python/src/tree/function/operators.cpp | C++ | gpl-3.0 | 3,899 |
/*
* Copyright (C) 2013 Man YUAN <epsilon@epsilony.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.epsilony.tb.implicit;
import java.awt.geom.Rectangle2D;
import java.util.List;
import net.epsilony.tb.solid.Line;
import net.epsilony.tb.analysis.Math2D;
import net.epsilony.tb.analysis.DifferentiableFunction;
import net.epsilony.tb.analysis.LogicalMaximum;
import net.epsilony.tb.solid.SegmentStartCoordIterable;
import net.epsilony.tb.solid.winged.WingedCell;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author <a href="mailto:epsilonyuan@gmail.com">Man YUAN</a>
*/
public class TrackContourBuilderTest {
public TrackContourBuilderTest() {
}
double diskCenterX = 10;
double diskCenterY = -20;
double diskRadius = 50;
double holeCenterX = 15;
double holeCenterY = -15;
double holeRadius = 20;
public class SampleOneDiskWithAHole implements DifferentiableFunction {
LogicalMaximum max = new LogicalMaximum();
private CircleLevelSet disk;
private CircleLevelSet hole;
public SampleOneDiskWithAHole() {
max.setK(diskRadius - holeRadius, 1e-10, true);
disk = new CircleLevelSet(diskCenterX, diskCenterY, diskRadius);
disk.setConcrete(true);
hole = new CircleLevelSet(holeCenterX, holeCenterY, holeRadius);
hole.setConcrete(false);
max.setFunctions(disk, hole);
}
@Override
public double[] value(double[] input, double[] output) {
return max.value(input, output);
}
@Override
public int getDiffOrder() {
return max.getDiffOrder();
}
@Override
public int getInputDimension() {
return max.getInputDimension();
}
@Override
public int getOutputDimension() {
return max.getOutputDimension();
}
@Override
public void setDiffOrder(int diffOrder) {
max.setDiffOrder(diffOrder);
}
}
@Test
public void testDiskWithAHole() {
TriangleContourCellFactory factory = new TriangleContourCellFactory();
double edgeLength = 5;
int expChainsSize = 2;
double errRatio = 0.05;
Rectangle2D range = new Rectangle2D.Double(diskCenterX - diskRadius - edgeLength * 2, diskCenterY - diskRadius
- edgeLength * 2, diskRadius * 2 + edgeLength * 4, diskRadius * 2 + edgeLength * 4);
SampleOneDiskWithAHole levelsetFunction = new SampleOneDiskWithAHole();
factory.setRectangle(range);
factory.setEdgeLength(edgeLength);
List<WingedCell> cells = factory.produce();
TrackContourBuilder builder = new TrackContourBuilder();
builder.setCells((List) cells);
builder.setLevelSetFunction(levelsetFunction);
SimpleGradientSolver solver = new SimpleGradientSolver();
solver.setMaxEval(200);
builder.setImplicitFunctionSolver(solver);
builder.genContour();
List<Line> contourHeads = builder.getContourHeads();
assertEquals(expChainsSize, contourHeads.size());
for (int i = 0; i < contourHeads.size(); i++) {
double x0, y0, rad;
Line head = contourHeads.get(i);
boolean b = Math2D.isAnticlockwise(new SegmentStartCoordIterable(head));
if (b) {
x0 = diskCenterX;
y0 = diskCenterY;
rad = diskRadius;
} else {
x0 = holeCenterX;
y0 = holeCenterY;
rad = holeRadius;
}
double expArea = Math.PI * rad * rad;
expArea *= b ? 1 : -1;
Line seg = head;
double actArea = 0;
double[] center = new double[] { x0, y0 };
do {
double[] startCoord = seg.getStart().getCoord();
double[] endCoord = seg.getEnd().getCoord();
actArea += 0.5 * Math2D.cross(endCoord[0] - startCoord[0], endCoord[1] - startCoord[1], x0
- startCoord[0], y0 - startCoord[1]);
seg = (Line) seg.getSucc();
double actRadius = Math2D.distance(startCoord, center);
assertEquals(rad, actRadius, 1e-5);
actRadius = Math2D.distance(endCoord, center);
assertEquals(rad, actRadius, 1e-5);
} while (seg != head);
assertEquals(expArea, actArea, Math.abs(expArea) * errRatio);
}
}
}
| epsilony/tb | src/test/java/net/epsilony/tb/implicit/TrackContourBuilderTest.java | Java | gpl-3.0 | 5,181 |
<?php
/**
* ./cis/application/views/errors/cli/error_404.php
*
* @package default
*/
defined('BASEPATH') or exit('No direct script access allowed');
echo "\nERROR: ",
$heading,
"\n\n",
$message,
"\n\n";
| FH-Complete/FHC-AddOn-Aufnahme | cis/application/views/errors/cli/error_404.php | PHP | gpl-3.0 | 210 |
/*
Copyright (C) 2013 Edwin Velds
This file is part of Polka 2.
Polka 2 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.
Polka 2 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 Polka 2. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ActionGrabFrame.h"
#include "AccelManager.h"
namespace Polka {
ActionGrabFrame::ActionGrabFrame()
{
set_can_focus();
add_events(Gdk::ENTER_NOTIFY_MASK | Gdk::BUTTON_PRESS_MASK | Gdk::KEY_PRESS_MASK);
}
ActionGrabFrame::~ActionGrabFrame()
{
}
IntIntSignal ActionGrabFrame::signalButtonGrabbed()
{
return m_SignalButtonGrabbed;
}
IntIntSignal ActionGrabFrame::signalKeyGrabbed()
{
return m_SignalKeyGrabbed;
}
bool ActionGrabFrame::on_draw( const Cairo::RefPtr<Cairo::Context>& cr )
{
Gtk::DrawingArea::on_draw(cr);
// draw the frame
const Gtk::Allocation& a = get_allocation();
auto sc = get_style_context();
sc->context_save();
// draw frame or focus
if( has_focus() ) {
sc->render_focus( cr, 0, 0, a.get_width(), a.get_height() );
} else {
sc->add_class( GTK_STYLE_CLASS_FRAME );
sc->render_frame( cr, 0, 0, a.get_width(), a.get_height() );
}
sc->context_restore();
return true;
}
bool ActionGrabFrame::on_enter_notify_event(GdkEventCrossing* event)
{
grab_focus();
return true;
}
bool ActionGrabFrame::on_button_press_event(GdkEventButton *event)
{
if( event->button < DBL_CLICK ) {
int b = event->button + (event->type == GDK_2BUTTON_PRESS ? DBL_CLICK:0);
m_SignalButtonGrabbed.emit( b, event->state & MOD_ALL );
}
return true;
}
bool ActionGrabFrame::on_key_press_event (GdkEventKey* event)
{
if( !event->is_modifier ) {
int k = gdk_keyval_to_upper(event->keyval);
m_SignalKeyGrabbed.emit( k, event->state & MOD_ALL );
}
return true;
}
} // namespace Polka
| edwin-v/polka2 | src/ActionGrabFrame.cc | C++ | gpl-3.0 | 2,236 |
package ch.cyberduck.core.sds.triplecrypt;
/*
* Copyright (c) 2002-2022 iterate GmbH. All rights reserved.
* https://cyberduck.io/
*
* 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.
*/
import ch.cyberduck.core.sds.SDSSession;
import ch.cyberduck.core.sds.io.swagger.client.model.FileKey;
import ch.cyberduck.core.transfer.TransferStatus;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.ProxyInputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import com.dracoon.sdk.crypto.CryptoUtils;
import com.dracoon.sdk.crypto.FileEncryptionCipher;
import com.dracoon.sdk.crypto.error.CryptoException;
import com.dracoon.sdk.crypto.model.EncryptedDataContainer;
import com.dracoon.sdk.crypto.model.PlainDataContainer;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
public class TripleCryptEncryptingInputStream extends ProxyInputStream {
private static final Logger log = LogManager.getLogger(TripleCryptEncryptingInputStream.class);
private final SDSSession session;
private final InputStream proxy;
private final FileEncryptionCipher cipher;
private final TransferStatus status;
// Buffer for encrypted content waiting to be read
private ByteBuffer buffer = ByteBuffer.allocate(0);
private boolean eof = false;
/**
* @param proxy the cleartext InputStream to use as source
*/
public TripleCryptEncryptingInputStream(final SDSSession session, final InputStream proxy,
final FileEncryptionCipher cipher, final TransferStatus status) {
super(proxy);
this.session = session;
this.proxy = proxy;
this.cipher = cipher;
this.status = status;
}
@Override
public int read(final byte[] b) throws IOException {
return this.read(b, 0, b.length);
}
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
try {
int read = 0;
if(buffer.hasRemaining()) {
// Buffer still has encrypted content available
read = Math.min(len, buffer.remaining());
System.arraycopy(buffer.array(), buffer.position(), b, off, read);
buffer.position(buffer.position() + read);
}
else if(eof) {
// Buffer is consumed and EOF flag set
return IOUtils.EOF;
}
if(buffer.hasRemaining()) {
return read;
}
if(!eof) {
this.fillBuffer(len);
}
return read;
}
catch(CryptoException e) {
throw new IOException(e);
}
}
private void fillBuffer(final int len) throws IOException, CryptoException {
// Read ahead to the next chunk end
final int allocate = (len / IOUtils.DEFAULT_BUFFER_SIZE) * IOUtils.DEFAULT_BUFFER_SIZE + IOUtils.DEFAULT_BUFFER_SIZE;
buffer = ByteBuffer.allocate(allocate);
final byte[] plain = new byte[allocate];
final int read = IOUtils.read(proxy, plain, 0, allocate);
if(read > 0) {
int position = 0;
for(int chunkOffset = 0; chunkOffset < read; chunkOffset += SDSSession.DEFAULT_CHUNKSIZE) {
int chunkLen = Math.min(SDSSession.DEFAULT_CHUNKSIZE, read - chunkOffset);
final byte[] bytes = Arrays.copyOfRange(plain, chunkOffset, chunkOffset + chunkLen);
final PlainDataContainer data = TripleCryptKeyPair.createPlainDataContainer(bytes, bytes.length);
final EncryptedDataContainer encrypted = cipher.processBytes(data);
final byte[] encBuf = encrypted.getContent();
System.arraycopy(encBuf, 0, buffer.array(), position, encBuf.length);
position += encBuf.length;
}
buffer.limit(position);
}
if(read < allocate) {
// EOF in proxy stream, finalize cipher and put remaining bytes into buffer
eof = true;
final EncryptedDataContainer encContainer = cipher.doFinal();
final byte[] content = encContainer.getContent();
buffer = this.combine(buffer, ByteBuffer.wrap(content));
final String tag = CryptoUtils.byteArrayToString(encContainer.getTag());
final ObjectReader reader = session.getClient().getJSON().getContext(null).readerFor(FileKey.class);
final FileKey fileKey = reader.readValue(status.getFilekey().array());
if(null == fileKey.getTag()) {
// Only override if not already set pre-computed in bulk feature
fileKey.setTag(tag);
final ObjectWriter writer = session.getClient().getJSON().getContext(null).writerFor(FileKey.class);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
writer.writeValue(out, fileKey);
status.setFilekey(ByteBuffer.wrap(out.toByteArray()));
}
else {
log.warn(String.format("Skip setting tag in file key already found in %s", status));
}
}
}
private ByteBuffer combine(final ByteBuffer b1, final ByteBuffer b2) {
final int pos = b1.position();
final ByteBuffer allocate = ByteBuffer.allocate(b1.limit() + b2.limit()).put(b1).put(b2);
allocate.position(pos);
return allocate;
}
}
| iterate-ch/cyberduck | dracoon/src/main/java/ch/cyberduck/core/sds/triplecrypt/TripleCryptEncryptingInputStream.java | Java | gpl-3.0 | 6,159 |
package com.oocl.mnlbc.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.oocl.mnlbc.model.User;
public class UserMapper implements RowMapper<User> {
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setUserName(rs.getString("USERNAME"));
user.setPassword(rs.getString("PASSWORD"));
user.setRemark(rs.getString("REMARK"));
return user;
}
}
| MNLBC/Group2Projects | 5. William Kalingasan/W5D3_Homework/Codes/Item1/W5D2_Homework/src/com/oocl/mnlbc/dao/UserMapper.java | Java | gpl-3.0 | 474 |
package world;
final class Stone extends AbstractWO {
Stone(int x, int y) {
super(x, y);
}
@Override
public boolean isWalkable() {
return false;
}
@Override
public WORating rating() {
return WORating.AVOID;
}
@Override
public boolean isBlocked() {
return true;
}
}
| rosario-raulin/SkunkmanAI | src/world/Stone.java | Java | gpl-3.0 | 290 |
#!/usr/bin/python
# FRANKEN CIPHER
# WRITTEN FOR ACADEMIC PURPOSES
#
# AUTHORED BY: Dan C and james@forscience.xyz
#
# THIS SCRIPT IS WRITTEN TO DEMONSTRATE A UNIQUE ENCRYPTION ALGORITHM THAT IS INSPIRED BY A NUMBER
# OF EXISTING ALGORITHMS.
# THE SCRIPT IS WRITTEN ENTIRELY FOR ACADEMIC PURPOSES. NO WARRANTY OR GUARANTEES ARE
# OFFERED BY THE AUTHORS IN RELATION TO THE USE OF THIS SCRIPT.
#
# Usage: franken.py <"-v" (verbose)> <"-d" (decrypt)> <"-k" (key phrase)> <"-m" (string to encrypt/decrypt)>
#
# indentation: TABS!
import sys
import getopt
import collections
import binascii
import hashlib
import itertools
# GLOBALS
# define -v and -d as false (-d defaults to encrypt mode)
verbose_opt = False
decrypt_opt = False
key_phrase = '' # clear text key phrase
key_hashed = '' # hashed key phrase
clear_text = '' # starting message input
pigpen_message = '' # message after pigpen stage
encrypted_message = '' # the encrypted message
decrypted_message = '' # the decrypted message
# GLOBALS
# pigpen dictionaries
pigpen_A = {'A':'ETL', 'B':'ETM', 'C':'ETR', 'D':'EML', 'E':'EMM', 'F':'EMR', 'G':'EBL', 'H':'EBM', 'I':'EBR', 'J':'DTL',
'K':'DTM', 'L':'DTR', 'M':'DML', 'N':'DMM', 'O':'DMR', 'P':'DBL', 'Q':'DBM', 'R':'DBR', 'S':'EXT', 'T':'EXL', 'U':'EXR',
'V':'EXB', 'W':'DXT', 'X':'DXL', 'Y':'DXR', 'Z':'DXB', ' ':'EPS', '.':'EPF', ',':'EPC', '!':'EPE', '?':'EPQ', '"':'EPD',
'@':'EPA','0':'NTL', '1':'NTM', '2':'NTR', '3':'NML', '4':'NMM', '5':'NMR', '6':'NBL', '7':'NBM', '8':'NBR','9':'NXT'}
pigpen_B = {'C':'ETL', 'D':'ETM', 'A':'ETR', 'B':'EML', 'G':'EMM', 'H':'EMR', 'E':'EBL', 'F':'EBM', 'K':'EBR', 'L':'DTL',
'I':'DTM', 'J':'DTR', 'O':'DML', 'P':'DMM', 'M':'DMR', 'N':'DBL', 'S':'DBM', 'T':'DBR', 'Q':'EXT', 'R':'EXL', 'W':'EXR',
'X':'EXB', 'U':'DXT', 'V':'DXL', ' ':'DXR', ',':'DXB', 'Y':'EPS', '!':'EPF', 'Z':'EPC', '.':'EPE', '@':'EPQ', '0':'EPD',
'?':'EPA','"':'NTL', '3':'NTM', '4':'NTR', '1':'NML', '2':'NMM', '7':'NMR', '8':'NBL', '9':'NBM', '5':'NBR', '6':'NXT'}
pigpen_C = {'K':'ETL', 'L':'ETM', 'M':'ETR', 'N':'EML', 'O':'EMM', 'P':'EMR', 'Q':'EBL', 'R':'EBM', 'S':'EBR', 'U':'DTL',
'V':'DTM', 'W':'DTR', 'X':'DML', 'Y':'DMM', 'Z':'DMR', ' ':'DBL', '.':'DBM', ',':'DBR', '!':'EXT', '"':'EXL', '?':'EXR',
'@':'EXB', '0':'DXT', '1':'DXL', '2':'DXR', '3':'DXB', '4':'EPS', '5':'EPF', '6':'EPC', '7':'EPE', '8':'EPQ', '9':'EPD',
'A':'EPA','B':'NTL', 'C':'NTM', 'D':'NTR', 'E':'NML', 'F':'NMM', 'G':'NMR', 'H':'NBL', 'I':'NBM', 'J':'NBR','T':'NXT'}
# creates hashes of the key phrase inputted by the user
# in order for it to be used as a key
# the clear text key phrase string is retained
def keyGenerate():
global key_hashed
# create the hashes of the key phrase string
md5_hash = hashlib.md5(key_phrase.encode())
sha256_hash = hashlib.sha256(key_phrase.encode())
sha512_hash = hashlib.sha512(key_phrase.encode())
# concatenate the hash digests into one key
key_hashed = md5_hash.hexdigest() + sha256_hash.hexdigest() + sha512_hash.hexdigest()
# hash the entire key (so far) one more time and concatenate to make 1024bit key
key_hashed_hash = hashlib.md5(key_hashed.encode())
key_hashed += key_hashed_hash.hexdigest()
# vebose mode if verbose option is set
if verbose_opt:
print("[KEY GENERATION]: The key phrase is: \"" + key_phrase + "\"")
print("[KEY GENERATION]: \"" + key_phrase + "\" is independantly hashed 3 times using MD5, SHA256 and SHA512")
print("[KEY GENERATION]: The 3 hashes are concatenated with 1 more md5 hash, resulting in the 1024bit key:")
print("[KEY GENERATION]: \"" + key_hashed + "\"\n")
return
# selects the appropriate pigpen dictionary based on summing all of the ascii
# values in the key phrase and modulating the sum of the integers by 3 in order to retrieve
# one of 3 values. Returns the appropriate dictionary
def selectDict():
# sum ASCII value of each character in the clear text key phrase
ascii_total = 0
for x in key_phrase:
ascii_total += ord(x)
# modulo 3 ascii_total to find 0-3 result to select pigpen dict
if ascii_total % 3 == 0:
pigpen_dict = pigpen_A
elif ascii_total % 3 == 1:
pigpen_dict = pigpen_B
elif ascii_total % 3 == 2:
pigpen_dict = pigpen_C
# return the dictionary
return pigpen_dict
# convert message into pigpen alphabet. compare each letter to dict key.
# first makes all chars uppercase and ignores some punctuation.
# itterates through pigpen dict to find value based on clear message char as key
def pigpenForward():
global pigpen_message
# convert clear message to uppercase
message = clear_text.upper()
# itterate through dict looking for chars
for letter in message:
if letter in selectDict():
pigpen_message += selectDict().get(letter)
# verbose mode if verbose option is set
if verbose_opt:
print("[ENCRYPTION - Phase 1]: The clear text is:")
print("[ENCRYPTION - Phase 1]: \"" + clear_text + "\"")
print("[ENCRYPTION - Phase 1]: 1 of 3 dictionaries is derived from the sum of the pre-hashed key ASCII values (mod 3)")
print("[ENCRYPTION - Phase 1]: The clear text is converted into pigpen cipher text using the selected dictionary:")
print("[ENCRYPTION - Phase 1]: \"" + pigpen_message + "\"\n")
return
# reverses the pigpen process. takes a pigpen string and converts it back to clear text
# first creates a list of each 3 values from the inputted string (each element has 3 chars)
# then compares those elements to the pigpen dictionary to create the decrypted string
def pigpenBackward():
global decrypted_message
# convert encrypted message (int array) back to a single ascii string
message = ''
try:
for i in decrypted_message:
message += chr(i)
except:
print("[ERROR]: Incorrect key. Cannot decrypt.")
usageText()
# retrieve each 3 chars (one pigpen value) and form a list
message_list = [message[i:i+3] for i in range(0, len(message), 3)]
# zero out decrypted message string in order to store pigpen deciphered characters
decrypted_message = ''
# itterate through list elements and compare against pigpen dict
# to find correct key (clear text letter) and create decrypted string
for element in message_list:
for key, value in selectDict().iteritems():
if value == element:
decrypted_message += key
# verbose mode if verbose option is set
if verbose_opt:
print("[DECRYPTION - Phase 3]: 1 of 3 dictionaries is derived from the sum of the pre-hashed key ASCII values (mod 3)")
print("[DECRYPTION - Phase 3]: The values of the pigpen cipher text are looked up in the selected dictionary")
print("[DECRYPTION - Phase 3]: The pigpen cipher text is converted back into clear text:\n")
print("[DECRYPTION - COMPLETE]: \"" + decrypted_message + "\"\n")
return
# XORs an int value derived from the hashed key to each ascii int value of the message.
# The key value is looked up by using the value stored in that key array position to reference
# the array position that value points to. That value is then XOR'ed with the corresponding value of the message
# this occurs three times. Inspired by DES key sub key generation and RC4
def keyConfusion(message):
# create array of base10 ints from ascii values of chars in hashed key
key = []
for x in key_hashed:
key.append(ord(x))
# create a variable for cycling through the key array (in case the message is longer than key)
key_cycle = itertools.cycle(key)
# loop through the key and XOR the resultant value with the corresponding value in the message
for i in range(len(message)):
# find the value pointed to by the value of each element of the key (for each value in the message array)
key_pointer = key_cycle.next() % 128 # get the next key byte. mod 128 because 128 bytes in 1024bits
key_byte = key[key_pointer]
# XOR message byte with current key_byte
message[i] = message[i] ^ key_byte
# XOR message byte with the key byte pointed to by previous key byte value
key_byte = key[(key_byte % 128)]
message[i] = message[i] ^ key_byte
# once again XOR message byte with the next key byte pointed to by previous key byte value
key_byte = key[(key_byte % 128)]
message[i] = message[i] ^ key_byte
# verbose mode if verbose option is set
if verbose_opt:
# are we decrypting or encrypting?
if decrypt_opt:
en_or_de = "[DECRYPTION - Phase 2]: "
en_or_de_text = " pigpen cipher text:"
else:
en_or_de = "[ENCRYPTION - Phase 2]: "
en_or_de_text = " partially encrypted string:"
# print the appropriate output for encrypting or decrypting
print(en_or_de + "Each byte of the pigpen cipher is then XOR'ed against 3 bytes of the key")
print(en_or_de + "The key byte is XOR'ed against the byte of the message and then used to select the")
print(en_or_de + "position in the key array of the next key byte value. This occurs three times.")
print(en_or_de + "Resulting in the" + en_or_de_text)
print(en_or_de + "\"" + message + "\"\n")
return message
# xors the hashed key against the pigpenned message
# each character in the message is xor'ed against each character
# in the hashed key, resulting in the encrypted message
def xorForward():
global encrypted_message
# convert key and message into ints for xoring
message = bytearray(pigpen_message)
key = bytearray(key_hashed)
# send pigpen message off for permution
message = keyConfusion(message)
# iterate over message and xor each character against each value in the key
for x in range(len(message)):
for y in range(len(key)):
xored = key[y] ^ message[x]
message[x] = xored
# store hex value of encrypted string in global variable
encrypted_message = binascii.hexlify(bytearray(message))
# verbose mode is verbose option is set
if verbose_opt:
print("[ENCRYPTION - Phase 3]: The partially encrypted cipher text and key are converted into a byte arrays")
print("[ENCRYPTION - Phase 3]: Each byte of the message is XOR'ed against each byte of the key")
print("[ENCRYPTION - Phase 3]: Resulting in the cipher text hex string:\n")
print("[ENCRYPTION - COMPLETE]: \"" + encrypted_message + "\"\n")
return
# the reverse of the encrypt function, whereby the supplied key is reversed
# and xored against the encrypted message. The message is first unhexlified
# to facilitate xoring
def xorBackward():
global decrypted_message
# create byte array for key and to store decrypted message
reverse_key = key_hashed[::-1]
key = bytearray(reverse_key)
# try to convert the encrypted message from hex to int, error if incorrect string
try:
message = bytearray(binascii.unhexlify(clear_text))
except:
print("[ERROR]: Incorrect string. Cannot decrypt.")
usageText()
# iterate over the encrypted message and xor each value against each value in the key
for x in range(len(message)):
for y in range(len(key)):
xored = key[y] ^ message[x]
message[x] = xored
# verbose mode is verbose option is set
if verbose_opt:
print("[DECRYPTION - Phase 1]: The cipher text is:")
print("[DECRYPTION - Phase 1]: \"" + clear_text + "\"")
print("[DECRYPTION - Phase 1]: The cipher text and key are converted into a byte arrays")
print("[DECRYPTION - Phase 1]: The key is reversed in order to reverse this stage of XOR'ing")
print("[DECRYPTION - Phase 1]: Each byte of the cipher text is XOR'ed against each byte of the key")
print("[DECRYPTION - Phase 1]: Resulting in the partially decrypted string:")
print("[DECRYPTION - Phase 1]: \"" + message + "\"\n")
# send decrypted array off for permutation (reverse encrypted XOR'ing)
decrypted_message = keyConfusion(message)
return
# text to be displayed on incorrect user input
def usageText():
print("\n[USAGE]: franken.py -v (verbose) -d (decrypt) --keyphrase (-k) <phrase> --message (-m) <message to encrypt>")
print("[USAGE]: -v and -d arguments are optional. --keyphrase(-k) and --message(-m) are required")
print("\n[EXAMPLE]: python franken.py -v --keyphrase \"super secret\" --message \"This is a super secret message\"\n")
print("[!] As with any cipher, your message is only as secure as your key phrase.")
print("[!] REMEMBER: The more complicated your key phrase, the stronger your encrypted message will be!\n")
sys.exit(2)
# USER INPUT HANDLING
# check that arguments have been supplied
if len(sys.argv) < 2:
usageText()
# define the arguments and necessity.
try:
opts, args = getopt.getopt(sys.argv[1:], 'vdk:m:', ["verbose", "decrypt", "keyphrase=", "message="])
except getopt.GetoptError:
usageText()
# check for presence of args and assign values
for opt, arg in opts:
if opt == '-v':
verbose_opt = True
if opt == '-d':
decrypt_opt = True
if opt in ('-k', '--keyphrase'):
key_phrase = arg
if opt in ('-m', '--message'):
clear_text = arg
# Check that a keyphrase and message has been set
if not key_phrase or not clear_text:
usageText()
print(
'''
__ _
/ _| | |
| |_ _ __ __ _ _ __ | | _____ _ __
| _| '__/ _` | '_ \| |/ / _ \ '_ \
| | | | | (_| | | | | < __/ | | |
|_| |_| \__,_|_| |_|_|\_\___|_| |_|
_ _
__(_)_ __| |_ ___ _ _
/ _| | '_ \ ' \/ -_) '_|
\__|_| .__/_||_\___|_|
|_|
[!] franken.py
An encryption algorithm inspired by a number of existing ciphers.
Created for CC6004 Course Work 1. 2016/17
[@] Dan C and james@forscience.xyz
__________________________________________________
'''
)
# are we decrypting or encrypting? defaults to encrypting
# decrypt
if decrypt_opt:
keyGenerate()
xorBackward()
pigpenBackward()
if not verbose_opt:
print("[DECRYPTED]: " + decrypted_message + "\n")
# encrypt
else:
keyGenerate()
pigpenForward()
xorForward()
if not verbose_opt:
print("[ENCRYPTED]: " + encrypted_message + "\n")
| forScie/FrankenCipher | franken.py | Python | gpl-3.0 | 13,770 |
/*
* #%L
* VisualWAS
* %%
* Copyright (C) 2013 - 2020 Andreas Veithen
* %%
* 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/gpl-3.0.html>.
* #L%
*/
package com.github.veithen.visualwas.client.pmi;
import java.io.Serializable;
import com.github.veithen.visualwas.connector.mapped.MappedClass;
@MappedClass("com.ibm.websphere.pmi.stat.StatDescriptor")
public class StatDescriptor implements Serializable {
private static final long serialVersionUID = -2844135786824830882L;
private final String[] subPath;
private final int dataId = -3;
public StatDescriptor(String... path) {
subPath = path;
}
public String[] getPath() {
return subPath;
}
}
| veithen/visualwas | clientlib/src/main/java/com/github/veithen/visualwas/client/pmi/StatDescriptor.java | Java | gpl-3.0 | 1,295 |
package org.biiig.foodbroker.stores;
/**
* Created by peet on 28.11.14.
*/
public interface StoreCombiner {
void add(Store store);
void combine();
}
| dbs-leipzig/foodbroker | src/main/java/org/biiig/foodbroker/stores/StoreCombiner.java | Java | gpl-3.0 | 160 |
/*
* Copyright © 2008-2012 Peter Colberg and Felix Höfling
*
* This file is part of HALMD.
*
* HALMD 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 <algorithm>
#include <boost/bind.hpp>
#include <cmath>
#include <memory>
#include <halmd/mdsim/host/integrators/verlet_nvt_andersen.hpp>
#include <halmd/utility/lua/lua.hpp>
namespace halmd {
namespace mdsim {
namespace host {
namespace integrators {
template <int dimension, typename float_type>
verlet_nvt_andersen<dimension, float_type>::verlet_nvt_andersen(
std::shared_ptr<particle_type> particle
, std::shared_ptr<box_type const> box
, std::shared_ptr<random_type> random
, float_type timestep
, float_type temperature
, float_type coll_rate
, std::shared_ptr<logger> logger
)
: particle_(particle)
, box_(box)
, random_(random)
, coll_rate_(coll_rate)
, logger_(logger)
{
set_timestep(timestep);
set_temperature(temperature);
LOG("collision rate with heat bath: " << coll_rate_);
}
template <int dimension, typename float_type>
void verlet_nvt_andersen<dimension, float_type>::set_timestep(double timestep)
{
timestep_ = timestep;
timestep_half_ = 0.5 * timestep;
coll_prob_ = coll_rate_ * timestep;
}
template <int dimension, typename float_type>
void verlet_nvt_andersen<dimension, float_type>::set_temperature(double temperature)
{
temperature_ = temperature;
sqrt_temperature_ = std::sqrt(temperature_);
LOG("temperature of heat bath: " << temperature_);
}
template <int dimension, typename float_type>
void verlet_nvt_andersen<dimension, float_type>::integrate()
{
LOG_TRACE("update positions and velocities")
force_array_type const& force = read_cache(particle_->force());
mass_array_type const& mass = read_cache(particle_->mass());
size_type nparticle = particle_->nparticle();
// invalidate the particle caches after accessing the force!
auto position = make_cache_mutable(particle_->position());
auto image = make_cache_mutable(particle_->image());
auto velocity = make_cache_mutable(particle_->velocity());
scoped_timer_type timer(runtime_.integrate);
for (size_type i = 0; i < nparticle; ++i) {
vector_type& v = (*velocity)[i];
vector_type& r = (*position)[i];
v += force[i] * timestep_half_ / mass[i];
r += v * timestep_;
(*image)[i] += box_->reduce_periodic(r);
}
}
template <int dimension, typename float_type>
void verlet_nvt_andersen<dimension, float_type>::finalize()
{
LOG_TRACE("update velocities")
force_array_type const& force = read_cache(particle_->force());
mass_array_type const& mass = read_cache(particle_->mass());
size_type nparticle = particle_->nparticle();
// invalidate the particle caches after accessing the force!
auto velocity = make_cache_mutable(particle_->velocity());
scoped_timer_type timer(runtime_.finalize);
// cache random numbers
float_type rng_cache = 0;
bool rng_cache_valid = false;
// loop over all particles
for (size_type i = 0; i < nparticle; ++i) {
vector_type& v = (*velocity)[i];
// is deterministic step?
if (random_->uniform<float_type>() > coll_prob_) {
v += force[i] * timestep_half_ / mass[i];
}
// stochastic coupling with heat bath
else {
// assign two velocity components at a time
for (unsigned int i = 0; i < dimension - 1; i += 2) {
std::tie(v[i], v[i + 1]) = random_->normal(sqrt_temperature_);
}
// handle last component separately for odd dimensions
if (dimension % 2 == 1) {
if (rng_cache_valid) {
v[dimension - 1] = rng_cache;
}
else {
std::tie(v[dimension - 1], rng_cache) = random_->normal(sqrt_temperature_);
}
rng_cache_valid = !rng_cache_valid;
}
}
}
}
template <int dimension, typename float_type>
void verlet_nvt_andersen<dimension, float_type>::luaopen(lua_State* L)
{
using namespace luaponte;
module(L, "libhalmd")
[
namespace_("mdsim")
[
namespace_("integrators")
[
class_<verlet_nvt_andersen>()
.def("integrate", &verlet_nvt_andersen::integrate)
.def("finalize", &verlet_nvt_andersen::finalize)
.def("set_timestep", &verlet_nvt_andersen::set_timestep)
.def("set_temperature", &verlet_nvt_andersen::set_temperature)
.property("timestep", &verlet_nvt_andersen::timestep)
.property("temperature", &verlet_nvt_andersen::temperature)
.property("collision_rate", &verlet_nvt_andersen::collision_rate)
.scope
[
class_<runtime>()
.def_readonly("integrate", &runtime::integrate)
.def_readonly("finalize", &runtime::finalize)
]
.def_readonly("runtime", &verlet_nvt_andersen::runtime_)
, def("verlet_nvt_andersen", &std::make_shared<verlet_nvt_andersen
, std::shared_ptr<particle_type>
, std::shared_ptr<box_type const>
, std::shared_ptr<random_type>
, float_type
, float_type
, float_type
, std::shared_ptr<logger>
>)
]
]
];
}
HALMD_LUA_API int luaopen_libhalmd_mdsim_host_integrators_verlet_nvt_andersen(lua_State* L)
{
#ifndef USE_HOST_SINGLE_PRECISION
verlet_nvt_andersen<3, double>::luaopen(L);
verlet_nvt_andersen<2, double>::luaopen(L);
#else
verlet_nvt_andersen<3, float>::luaopen(L);
verlet_nvt_andersen<2, float>::luaopen(L);
#endif
return 0;
}
// explicit instantiation
#ifndef USE_HOST_SINGLE_PRECISION
template class verlet_nvt_andersen<3, double>;
template class verlet_nvt_andersen<2, double>;
#else
template class verlet_nvt_andersen<3, float>;
template class verlet_nvt_andersen<2, float>;
#endif
} // namespace integrators
} // namespace host
} // namespace mdsim
} // namespace halmd
| the-nic/halmd | halmd/mdsim/host/integrators/verlet_nvt_andersen.cpp | C++ | gpl-3.0 | 6,901 |
package clock.socoolby.com.clock.protocol;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class WeatherResponse extends ResponseBase {
/*
{
"error": 0,
"status": "success",
"date": "2016-05-26",
"results": [{
"currentCity": "深圳",
"pm25": "31",
"index": [{
"title": "穿衣",
"zs": "热",
"tipt": "穿衣指数",
"des": "天气热,建议着短裙、短裤、短薄外套、T恤等夏季服装。"
},
{
"title": "洗车",
"zs": "不宜",
"tipt": "洗车指数",
"des": "不宜洗车,未来24小时内有雨,如果在此期间洗车,雨水和路上的泥水可能会再次弄脏您的爱车。"
},
{
"title": "旅游",
"zs": "较不宜",
"tipt": "旅游指数",
"des": "温度适宜,风力不大,但预计将有有强降水出现,会给您的出游增添很多麻烦,建议您最好选择室内活动。"
},
{
"title": "感冒",
"zs": "较易发",
"tipt": "感冒指数",
"des": "天气转凉,空气湿度较大,较易发生感冒,体质较弱的朋友请注意适当防护。"
},
{
"title": "运动",
"zs": "较不宜",
"tipt": "运动指数",
"des": "有较强降水,建议您选择在室内进行健身休闲运动。"
},
{
"title": "紫外线强度",
"zs": "弱",
"tipt": "紫外线强度指数",
"des": "紫外线强度较弱,建议出门前涂擦SPF在12-15之间、PA+的防晒护肤品。"
}],
"weather_data": [{
"date": "周四 05月26日 (实时:28℃)",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/dayu.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/dayu.png",
"weather": "大雨",
"wind": "微风",
"temperature": "31 ~ 25℃"
},
{
"date": "周五",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/baoyu.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/leizhenyu.png",
"weather": "暴雨转雷阵雨",
"wind": "微风",
"temperature": "29 ~ 25℃"
},
{
"date": "周六",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/leizhenyu.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/zhenyu.png",
"weather": "雷阵雨转阵雨",
"wind": "微风",
"temperature": "30 ~ 25℃"
},
{
"date": "周日",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/zhenyu.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/zhenyu.png",
"weather": "阵雨",
"wind": "微风",
"temperature": "31 ~ 26℃"
}]
}]
}
*/
private int mErrorCode;
private String mCurrentCity;
private int mPM25;
private Weather todayWeather;
public class Weather {
public String date;
public String weather;
public String wind;
public String temperature;
public void parse(JSONObject jsonObject) {
try {
date = jsonObject.getString("date");
weather = jsonObject.getString("weather");
wind = jsonObject.getString("wind");
temperature = jsonObject.getString("temperature");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public int getmErrorCode() {
return mErrorCode;
}
public void setmErrorCode(int mErrorCode) {
this.mErrorCode = mErrorCode;
}
public String getmCurrentCity() {
return mCurrentCity;
}
public void setmCurrentCity(String mCurrentCity) {
this.mCurrentCity = mCurrentCity;
}
public int getmPM25() {
return mPM25;
}
public void setmPM25(int mPM25) {
this.mPM25 = mPM25;
}
public Weather getTodayWeather() {
return todayWeather;
}
public void setTodayWeather(Weather todayWeather) {
this.todayWeather = todayWeather;
}
public WeatherResponse(JSONObject response) {
super.parseResponse(response);
}
@Override
protected boolean parse(JSONObject object) throws JSONException {
mErrorCode = object.getInt("error");
if (mErrorCode == 0) {
JSONArray results = object.getJSONArray("results");
JSONObject summary = (JSONObject) results.get(0);
mCurrentCity = summary.getString("currentCity");
mPM25 = summary.getInt("pm25");
JSONArray weathers = summary.getJSONArray("weather_data");
todayWeather = new Weather();
JSONObject todayJsonObject = (JSONObject) weathers.get(0);
todayWeather.parse(todayJsonObject);
}
return true;
}
}
| socoolby/CoolClock | app/src/main/java/clock/socoolby/com/clock/protocol/WeatherResponse.java | Java | gpl-3.0 | 4,725 |
<?php
/**
* Actor Browser 'Add New' Block Template
*
* @since 3.0.0
*
* @uses $id
* @uses $title
*/
?>
<div id="<?php echo esc_attr( $id ); ?>-block" data-controller="<?php echo esc_attr( $controller ); ?>" class="<?php echo esc_attr( $class ); ?>">
<button type="button" class="button arrow" data-action="collapse"><span class="wpmolicon icon-up-chevron"></span></button>
<h3 class="block-title"><?php echo esc_html( $title ); ?></h3>
<div class="block-content"></div>
</div>
| wpmovielibrary/wpmovielibrary | admin/templates/editors/blocks/terms/add-new.php | PHP | gpl-3.0 | 513 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"vorm.",
"nachm."
],
"DAY": [
"Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag"
],
"ERANAMES": [
"v. Chr.",
"n. Chr."
],
"ERAS": [
"v. Chr.",
"n. Chr."
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember"
],
"SHORTDAY": [
"So.",
"Mo.",
"Di.",
"Mi.",
"Do.",
"Fr.",
"Sa."
],
"SHORTMONTH": [
"Jan.",
"Feb.",
"M\u00e4rz",
"Apr.",
"Mai",
"Juni",
"Juli",
"Aug.",
"Sep.",
"Okt.",
"Nov.",
"Dez."
],
"STANDALONEMONTH": [
"Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d. MMMM y",
"longDate": "d. MMMM y",
"medium": "dd.MM.y HH:mm:ss",
"mediumDate": "dd.MM.y",
"mediumTime": "HH:mm:ss",
"short": "dd.MM.yy HH:mm",
"shortDate": "dd.MM.yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "CHF",
"DECIMAL_SEP": ".",
"GROUP_SEP": "'",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "de-ch",
"localeID": "de_CH",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| espringtran/travis-web-fonts | test/vendors/angular-1.5.5/i18n/angular-locale_de-ch.js | JavaScript | gpl-3.0 | 2,891 |
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2021 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
Espo.define('views/record/detail-small', 'views/record/detail', function (Dep) {
return Dep.extend({
bottomView: null
});
});
| ayman-alkom/espocrm | client/src/views/record/detail-small.js | JavaScript | gpl-3.0 | 1,503 |
Simpla CMS 2.3.8 = 1040075c69dc0e56580b73f479381087
| gohdan/DFC | known_files/hashes/simpla/design/js/codemirror/mode/octave/octave.js | JavaScript | gpl-3.0 | 52 |
Bitrix 16.5 Business Demo = e2e84ac05357fc4ff58dcdf6eef7ed3b
Bitrix 17.0.9 Business Demo = 48af8af937184b0386f83c8768b33355
| gohdan/DFC | known_files/hashes/bitrix/modules/sale/handlers/delivery/spsr/lang/ru/profile.php | PHP | gpl-3.0 | 124 |
//
// DO NOT MODIFY!!! This file was machine generated. DO NOT MODIFY!!!
//
// Copyright (c) 2014 Vincent W. Chen.
//
// This file is part of XJavaB.
//
// XJavaB is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// XJavaB 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 XJavaB. If not, see <http://www.gnu.org/licenses/>.
//
package com.noodlewiz.xjavab.ext.randr.internal;
import java.nio.ByteBuffer;
import com.noodlewiz.xjavab.core.XEvent;
public class EventDispatcher
implements com.noodlewiz.xjavab.core.internal.EventDispatcher
{
@Override
public XEvent dispatch(final ByteBuffer __xjb_buf, final int __xjb_code) {
switch (__xjb_code) {
case 0 :
return EventUnpacker.unpackScreenChangeNotify(__xjb_buf);
case 1 :
return EventUnpacker.unpackNotify(__xjb_buf);
default:
throw new IllegalArgumentException(("Invalid event code: "+ __xjb_code));
}
}
}
| noodlewiz/xjavab | xjavab-ext/src/main/java/com/noodlewiz/xjavab/ext/randr/internal/EventDispatcher.java | Java | gpl-3.0 | 1,464 |
<?php
/**
* AdminLte2 Timeline
* https://almsaeedstudio.com/themes/AdminLTE/pages/UI/timeline.html
*/
namespace LTE;
Class Timeline
{
//private $id ='';
//private $title='title';
public function __construct ()
{
//$this->id = md5(rand(0,time()));
//$this->title = $title;
//$this->body = $body;
//$this->footer = $footer;
//echo "Youpi !!";
}
public function id($str = ''){
$this->id=$str;
}
public function icon($str = ''){
$this->icon=$str;
}
public function html()
{
$HTML=[];
$HTML[]='<ul class="timeline">';
//<!-- timeline time label -->
$HTML[]='<li class="time-label">';
$HTML[]='<span class="bg-red">';
$HTML[]='10 Feb. 2014';
$HTML[]='</span>';
$HTML[]='</li>';
//<!-- /.timeline-label -->
//<!-- timeline item -->
$HTML[]='<li>';
//<!-- timeline icon -->
$HTML[]='<i class="fa fa-envelope bg-blue"></i>';
$HTML[]='<div class="timeline-item">';
$HTML[]='<span class="time"><i class="fa fa-clock-o"></i> 12:05</span>';
$HTML[]='<h3 class="timeline-header"><a href="#">Support Team</a> ...</h3>';
$HTML[]='<div class="timeline-body">';
//...
$HTML[]='Content goes here';
$HTML[]='</div>';
$HTML[]='<div class="timeline-footer">';
$HTML[]='<a class="btn btn-primary btn-xs">...</a>';
$HTML[]='</div>';
$HTML[]='</div>';
$HTML[]='</li>';
//<!-- END timeline item -->
$HTML[]='</ul>';
return implode("\n", $HTML);
}
public function __toString()
{
return $this->html();
}
}
/*
<ul class="timeline">
<!-- timeline time label -->
<li class="time-label">
<span class="bg-red">
10 Feb. 2014
</span>
</li>
<!-- /.timeline-label -->
<!-- timeline item -->
<li>
<!-- timeline icon -->
<i class="fa fa-envelope bg-blue"></i>
<div class="timeline-item">
<span class="time"><i class="fa fa-clock-o"></i> 12:05</span>
<h3 class="timeline-header"><a href="#">Support Team</a> ...</h3>
<div class="timeline-body">
...
Content goes here
</div>
<div class='timeline-footer'>
<a class="btn btn-primary btn-xs">...</a>
</div>
</div>
</li>
<!-- END timeline item -->
...
</ul>
*/ | ffinstitute/dataviz.ff.institute | src/LTE/Timeline.php | PHP | gpl-3.0 | 2,783 |
/*
Size3D.cs
This file is part of Morgan's CLR Advanced Runtime (MCART)
Author(s):
César Andrés Morgan <xds_xps_ivx@hotmail.com>
Copyright © 2011 - 2021 César Andrés Morgan
Morgan's CLR Advanced Runtime (MCART) 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.
Morgan's CLR Advanced Runtime (MCART) is distributed in the hope that it will
be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using TheXDS.MCART.Math;
using TheXDS.MCART.Misc;
using TheXDS.MCART.Types.Base;
using TheXDS.MCART.Types.Extensions;
namespace TheXDS.MCART.Types
{
/// <summary>
/// Estructura universal que describe el tamaño de un objeto en ancho y
/// alto en un espacio de dos dimensiones.
/// </summary>
public struct Size3D : IEquatable<Size3D>, I3DSize
{
/// <summary>
/// Obtiene un valor que no representa ningún tamaño. Este campo es
/// de solo lectura.
/// </summary>
public static readonly Size3D Nothing = new(double.NaN, double.NaN, double.NaN);
/// <summary>
/// Obtiene un valor que representa un tamaño nulo. Este campo es
/// de solo lectura.
/// </summary>
public static readonly Size3D Zero = new(0, 0, 0);
/// <summary>
/// Obtiene un valor que representa un tamaño infinito. Este campo
/// es de solo lectura.
/// </summary>
public static readonly Size3D Infinity = new(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity);
/// <summary>
/// Intenta crear un <see cref="Size"/> a partir de una cadena.
/// </summary>
/// <param name="value">
/// Valor a partir del cual crear un <see cref="Size"/>.
/// </param>
/// <param name="size">
/// <see cref="Size"/> que ha sido creado.
/// </param>
/// <returns>
/// <see langword="true"/> si la conversión ha tenido éxito,
/// <see langword="false"/> en caso contrario.
/// </returns>
public static bool TryParse(string value, out Size3D size)
{
switch (value)
{
case nameof(Nothing):
case null:
size = Nothing;
break;
case nameof(Zero):
case "0":
size = Zero;
break;
default:
string[]? separators = new[]
{
", ",
"; ",
" - ",
" : ",
" | ",
" ",
",",
";",
":",
"|",
};
return PrivateInternals.TryParseValues<double, Size3D>(separators, value.Without("()[]{}".ToCharArray()), 3, l => new(l[0], l[1], l[2]), out size);
}
return true;
}
/// <summary>
/// Crea un <see cref="Size"/> a partir de una cadena.
/// </summary>
/// <param name="value">
/// Valor a partir del cual crear un <see cref="Size"/>.
/// </param>
/// <exception cref="FormatException">
/// Se produce si la conversión ha fallado.
/// </exception>
/// <returns><see cref="Size"/> que ha sido creado.</returns>
public static Size3D Parse(string value)
{
if (TryParse(value, out Size3D retval)) return retval;
throw new FormatException();
}
/// <summary>
/// Compara la igualdad entre dos instancias de <see cref="Size"/>.
/// </summary>
/// <param name="size1">
/// Primer elemento a comparar.
/// </param>
/// <param name="size2">
/// Segundo elemento a comparar.
/// </param>
/// <returns>
/// <see langword="true"/> si los tamaños representados en ambos
/// objetos son iguales, <see langword="false"/> en caso contrario.
/// </returns>
public static bool operator ==(Size3D size1, Size3D size2)
{
return size1.Height == size2.Height && size1.Width == size2.Width && size1.Depth == size2.Depth;
}
/// <summary>
/// Compara la desigualdad entre dos instancias de
/// <see cref="Size"/>.
/// </summary>
/// <param name="size1">
/// Primer elemento a comparar.
/// </param>
/// <param name="size2">
/// Segundo elemento a comparar.
/// </param>
/// <returns>
/// <see langword="true"/> si los tamaños representados en ambos
/// objetos son distintos, <see langword="false"/> en caso
/// contrario.
/// </returns>
public static bool operator !=(Size3D size1, Size3D size2)
{
return !(size1 == size2);
}
/// <summary>
/// Obtiene el componente de altura del tamaño.
/// </summary>
public double Height { get; set; }
/// <summary>
/// Obtiene el componente de ancho del tamaño.
/// </summary>
public double Width { get; set; }
/// <summary>
/// Obtiene el componente de profundidad del tamaño.
/// </summary>
public double Depth { get; set; }
/// <summary>
/// Inicializa una nueva instancia de la estructura
/// <see cref="Size"/>.
/// </summary>
/// <param name="width">Valor de ancho.</param>
/// <param name="height">Valor de alto.</param>
/// <param name="depth">Valor de profundidad.</param>
public Size3D(double width, double height, double depth)
{
Width = width;
Height = height;
Depth = depth;
}
/// <summary>
/// Calcula el área cuadrada representada por este tamaño.
/// </summary>
public double CubeVolume => Height * Width * Depth;
/// <summary>
/// Calcula el perímetro cuadrado representado por este tamaño.
/// </summary>
public double CubePerimeter => (Height * 2) + (Width * 2) + (Depth * 2);
/// <summary>
/// Determina si esta instancia representa un tamaño nulo.
/// </summary>
/// <returns>
/// <see langword="true"/> si el tamaño es nulo,
/// <see langword="false"/> si el tamaño no contiene volumen, y
/// <see langword="null"/> si alguna magnitud está indefinida.
/// </returns>
public bool? IsZero
{
get
{
double a = CubeVolume;
return a.IsValid() ? a == 0 : (bool?)null;
}
}
/// <summary>
/// Convierte este <see cref="Size"/> en un valor
/// <see cref="I2DVector"/>.
/// </summary>
/// <returns>
/// Un valor <see cref="I2DVector"/> cuyos componentes son las
/// magnitudes de tamaño de esta instancia.
/// </returns>
public I3DVector To3DVector()
{
return new _3DVector { X = Width, Y = Height, Z = Depth};
}
/// <summary>
/// Determina si esta instancia de <see cref="Size"/> es igual a
/// otra.
/// </summary>
/// <param name="other">
/// Instancia de <see cref="Size"/> contra la cual comparar.
/// </param>
/// <returns>
/// <see langword="true"/> si los tamaños representados en ambos
/// objetos son iguales, <see langword="false"/> en caso contrario.
/// </returns>
public bool Equals(Size3D other) => this == other;
/// <summary>
/// Indica si esta instancia y un objeto especificado son iguales.
/// </summary>
/// <param name="obj">
/// Objeto que se va a compara con la instancia actual.
/// </param>
/// <returns>
/// <see langword="true" /> si esta instancia y <paramref name="obj" /> son iguales;
/// de lo contrario, <see langword="false" />.
/// </returns>
public override bool Equals(object? obj)
{
if (obj is not Size3D p) return false;
return this == p;
}
/// <summary>
/// Devuelve el código hash generado para esta instancia.
/// </summary>
/// <returns>
/// Un código hash que representa a esta instancia.
/// </returns>
public override int GetHashCode()
{
return HashCode.Combine(Height, Width, Depth);
}
}
} | TheXDS/MCART | src/MCART/Types/Size3D.cs | C# | gpl-3.0 | 9,182 |
<?php
/**
* Entrada [ http://www.entrada-project.org ]
*
* Entrada 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.
*
* Entrada 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 Entrada. If not, see <http://www.gnu.org/licenses/>.
*
* This is the default section that is loaded when the quizzes module is
* accessed without a defined section.
*
* @author Organisation: Queen's University
* @author Unit: School of Medicine
* @author Developer: Matt Simpson <matt.simpson@queensu.ca>
* @copyright Copyright 2010 Queen's University. All Rights Reserved.
*
*/
if((!defined("PARENT_INCLUDED")) || (!defined("IN_PUBLIC_GRADEBOOK"))) {
exit;
} elseif((!isset($_SESSION["isAuthorized"])) || (!$_SESSION["isAuthorized"])) {
header("Location: ".ENTRADA_URL);
exit;
}
?>
<h1>My Gradebooks</h1>
<?php
/**
* Update requested column to sort by.
* Valid: date, teacher, title, phase
*/
if (isset($_GET["sb"])) {
if (in_array(trim($_GET["sb"]), array("code", "title", "assessments"))) {
$_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["sb"] = trim($_GET["sb"]);
}
$_SERVER["QUERY_STRING"] = replace_query(array("sb" => false));
} else {
if (!isset($_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["sb"])) {
$_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["sb"] = "code";
}
}
/**
* Update requested order to sort by.
* Valid: asc, desc
*/
if (isset($_GET["so"])) {
$_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["so"] = ((strtolower($_GET["so"]) == "desc") ? "desc" : "asc");
$_SERVER["QUERY_STRING"] = replace_query(array("so" => false));
} else {
if (!isset($_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["so"])) {
$_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["so"] = "desc";
}
}
/**
* Provide the queries with the columns to order by.
*/
switch ($_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["sb"]) {
case "title" :
$sort_by = "a.`course_name` ".strtoupper($_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["so"]);
break;
case "assessments" :
$sort_by = "`assessments` ".strtoupper($_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["so"]);
break;
case "code" :
default :
$sort_by = "a.`course_code` ".strtoupper($_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["so"]);
break;
}
$group_ids = groups_get_enrolled_group_ids($ENTRADA_USER->getId());
$group_ids_string = implode(', ',$group_ids);
$query = " SELECT a.*, COUNT(b.`assessment_id`) AS `assessments`
FROM `courses` AS a
JOIN `assessments` AS b
ON a.`course_id` = b.`course_id`
AND b.`cohort` IN (".$group_ids_string.")
AND (b.`release_date` = '0' OR b.`release_date` <= ".$db->qstr(time()).")
AND (b.`release_until` = '0' OR b.`release_until` > ".$db->qstr(time()).")
AND b.`show_learner` = '1'
GROUP BY a.`course_id`
ORDER BY ".$sort_by;
$results = $db->GetAll($query);
if ($results) {
?>
<table class="tableList" cellspacing="0" summary="List of Gradebooks">
<colgroup>
<col class="date-small" />
<col class="title" />
<col class="general" />
</colgroup>
<thead>
<tr>
<td class="date-small borderl<?php echo (($_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["sb"] == "code") ? " sorted".strtoupper($_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["so"]) : ""); ?>"><?php echo public_order_link("code", "Course Code", ENTRADA_RELATIVE."/profile/gradebook"); ?></td>
<td class="title<?php echo (($_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["sb"] == "title") ? " sorted".strtoupper($_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["so"]) : ""); ?>"><?php echo public_order_link("title", "Course Title", ENTRADA_RELATIVE."/profile/gradebook"); ?></td>
<td class="general<?php echo (($_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["sb"] == "assessments") ? " sorted".strtoupper($_SESSION[APPLICATION_IDENTIFIER][$MODULE]["gradebook"]["so"]) : ""); ?>"><?php echo public_order_link("assessments", "Assessments", ENTRADA_RELATIVE."/profile/gradebook"); ?></td>
<?php
if (defined("GRADEBOOK_DISPLAY_WEIGHTED_TOTAL") && GRADEBOOK_DISPLAY_WEIGHTED_TOTAL) {
?>
<td class="general">Weighted Total</td>
<?php
}
?>
</tr>
</thead>
<tbody>
<?php
foreach ($results as $result) {
echo "<tr id=\"gradebook-".$result["course_id"]."\"".((!$result["course_active"]) ? " class=\"disabled\"" : "").">\n";
echo " <td".((!$result["course_active"]) ? " class=\"disabled\"" : "")."><a href=\"".ENTRADA_URL."/".$MODULE."/gradebook?section=view&id=".$result["course_id"]."\">".html_encode($result["course_code"])."</a></td>\n";
echo " <td".((!$result["course_active"]) ? " class=\"disabled\"" : "")."><a href=\"".ENTRADA_URL."/".$MODULE."/gradebook?section=view&id=".$result["course_id"]."\">".html_encode($result["course_name"])."</a></td>\n";
echo " <td".((!$result["course_active"]) ? " class=\"disabled\"" : "")."><a href=\"".ENTRADA_URL."/".$MODULE."/gradebook?section=view&id=".$result["course_id"]."\">".($result["assessments"])."</a></td>\n";
if (defined("GRADEBOOK_DISPLAY_WEIGHTED_TOTAL") && GRADEBOOK_DISPLAY_WEIGHTED_TOTAL) {
$gradebook = gradebook_get_weighted_grades($result["course_id"], $ENTRADA_USER->getCohort(), $ENTRADA_USER->getID());
echo " <td>".round(trim($gradebook["grade"]), 2)." / ".trim($gradebook["total"])."</td>\n";
}
echo "</tr>\n";
}
?>
</tbody>
</table>
<?php
} else {
echo "<div class=\"display-notice\">";
echo " <h3>No Course Gradebooks Available</h3>";
echo " There are currently no assessments in the system for your graduating year.";
echo "</div>";
}
?> | mattsimpson/entrada-1x | www-root/core/modules/public/profile/gradebook/index.inc.php | PHP | gpl-3.0 | 6,105 |
# -*- coding: utf-8 -*-
# Copyright 2009 James Hensman
# Licensed under the Gnu General Public license, see COPYING
#
# Gaussian Process Proper Orthogonal Decomposition.
| jameshensman/pythonGPLVM | GPPOD.py | Python | gpl-3.0 | 171 |
reportico_jquery = jQuery.noConflict();
var reportico_ajax_script = "index.php";
/*
** Reportico Javascript functions
*/
function setupDynamicGrids()
{
if (typeof reportico_dynamic_grids === 'undefined') {
return;
}
if ( reportico_jquery.type(reportico_dynamic_grids) != 'undefined' )
if ( reportico_dynamic_grids )
{
reportico_jquery(".swRepPage").each(function(){
reportico_jquery(this).dataTable(
{
"retrieve" : true,
"searching" : reportico_dynamic_grids_searchable,
"ordering" : reportico_dynamic_grids_sortable,
"paging" : reportico_dynamic_grids_paging,
"iDisplayLength": reportico_dynamic_grids_page_size
}
);
});
}
}
function setupDatePickers()
{
reportico_jquery(".swDateField").each(function(){
reportico_jquery(this).datepicker({dateFormat: reportico_datepicker_language});
});
}
function setupModals()
{
var options = {
}
reportico_jquery('#reporticoModal').modal(options);
}
function setupDropMenu()
{
if ( reportico_jquery('ul.jd_menu').length != 0 )
{
reportico_jquery('ul.jd_menu').jdMenu();
//reportico_jquery(document).bind('click', function() {
//reportico_jquery('ul.jd_menu ul:visible').jdMenuHide();
//});
}
}
/*
* Where multiple data tables exist due to graphs
* resize the columns of all tables to match the first
*/
function resizeHeaders()
{
// Size page header blocks to fit page headers
reportico_jquery(".swPageHeaderBlock").each(function() {
var maxheight = 0;
reportico_jquery(this).find(".swPageHeader").each(function() {
var headerheight = reportico_jquery(this).height();
if ( headerheight > maxheight )
maxheight = headerheight;
});
reportico_jquery(this).css("height", maxheight + "px");
});
//reportico_jquery(".swRepForm").columnize();
}
/*
* Where multiple data tables exist due to graphs
* resize the columns of all tables to match the first
*/
function resizeTables()
{
var tableArr = reportico_jquery('.swRepPage');
var tableDataRow = reportico_jquery('.swRepResultLine:first');
var cellWidths = new Array();
reportico_jquery(tableDataRow).each(function() {
for(j = 0; j < reportico_jquery(this)[0].cells.length; j++){
var cell = reportico_jquery(this)[0].cells[j];
if(!cellWidths[j] || cellWidths[j] < cell.clientWidth) cellWidths[j] = cell.clientWidth;
}
});
var tablect = 0;
reportico_jquery(tableArr).each(function() {
tablect++;
if ( tablect == 1 )
return;
reportico_jquery(this).find(".swRepResultLine:first").each(function() {
for(j = 0; j < reportico_jquery(this)[0].cells.length; j++){
reportico_jquery(this)[0].cells[j].style.width = cellWidths[j]+'px';
}
});
});
}
//reportico_jquery(document).on('click', 'ul.dropdown-menu li a, ul.dropdown-menu li ul li a, ul.jd_menu li a, ul.jd_menu li ul li a', function(event)
//{
//event.preventDefault();
//return false;
//});
reportico_jquery(document).on('click', 'a.reportico-dropdown-item, ul li.r1eportico-dropdown a, ul li ul.reportico-dropdown li a, ul.jd_menu li a, ul.jd_menu li ul li a', function(event)
{
if ( reportico_jquery.type(reportico_ajax_mode) === 'undefined' || !reportico_ajax_mode)
{
return true;
}
var url = reportico_jquery(this).prop('href');
runreport(url, this);
event.preventDefault();
return false;
});
/* Load Date Pickers */
reportico_jquery(document).ready(function()
{
setupDatePickers();
setupDropMenu();
resizeHeaders();
resizeTables();
setupDynamicGrids();
});
reportico_jquery(document).on('click', '.reportico-bootstrap-modal-close', function(event)
{
reportico_jquery("#swMiniMaintain").html("");
reportico_jquery('#reporticoModal').modal('hide');
});
reportico_jquery(document).on('click', '.reportico-modal-close', function(event)
{
reportico_jquery("#swMiniMaintain").html("");
reportico_jquery('#reporticoModal').hide();
});
reportico_jquery(document).on('click', '.swMiniMaintainSubmit', function(event)
{
if ( reportico_bootstrap_modal )
var loadpanel = reportico_jquery("#reporticoModal .modal-dialog .modal-content .modal-header");
else
var loadpanel = reportico_jquery("#reporticoModal .reportico-modal-dialog .reportico-modal-content .reportico-modal-header");
var expandpanel = reportico_jquery('#swPrpExpandCell');
reportico_jquery(loadpanel).addClass("modal-loading");
forms = reportico_jquery(this).closest('#reportico_container').find(".swPrpForm");
if ( reportico_jquery.type(reportico_ajax_script) === 'undefined' )
{
var ajaxaction = reportico_jquery(forms).prop("action");
}
else
{
ajaxaction = reportico_ajax_script;
}
params = forms.serialize();
params += "&" + reportico_jquery(this).prop("name") + "=1";
params += "&reportico_ajax_called=1";
params += "&execute_mode=PREPARE";
var cont = this;
reportico_jquery.ajax({
type: 'POST',
url: ajaxaction,
data: params,
dataType: 'html',
success: function(data, status)
{
reportico_jquery(loadpanel).removeClass("modal-loading");
if ( reportico_bootstrap_modal )
{
reportico_jquery('#reporticoModal').modal('hide');
reportico_jquery('.modal-backdrop').remove();
reportico_jquery('#reportico_container').closest('body').removeClass('modal-open');
}
else
reportico_jquery('#reporticoModal').hide();
reportico_jquery("#swMiniMaintain").html("");
//reportico_jquery(reportico_container).removeClass("loading");
fillDialog(data, cont);
},
error: function(xhr, desc, err) {
reportico_jquery("#swMiniMaintain").html("");
reportico_jquery('#reporticoModal').modal('hide');
reportico_jquery('.modal-backdrop').remove();
reportico_jquery(loadpanel).removeClass("modal-loading");
reportico_jquery(loadpanel).prop('innerHTML',"Ajax Error: " + xhr + "\nTextStatus: " + desc + "\nErrorThrown: " + err);
}
});
return false;
});
/*
** Trigger AJAX request for reportico button/link press if running in AJAX mode
** AJAX mode is in place when reportico session ("reportico_ajax_script") is set
** will generate full reportico output to replace the reportico_container tag
*/
reportico_jquery(document).on('click', '.swMiniMaintain', function(event)
{
var expandpanel = reportico_jquery(this).closest('#criteriaform').find('#swPrpExpandCell');
var reportico_container = reportico_jquery(this).closest("#reportico_container");
reportico_jquery(expandpanel).addClass("loading");
forms = reportico_jquery(this).closest('.swMntForm,.swPrpForm,form');
if ( reportico_jquery.type(reportico_ajax_script) === 'undefined' )
{
var ajaxaction = reportico_jquery(forms).prop("action");
}
else
{
ajaxaction = reportico_ajax_script;
}
maintainButton = reportico_jquery(this).prop("name");
reportico_jquery(".reportico-modal-title").html(reportico_jquery(this).prop("title"));
bits = maintainButton.split("_");
params = forms.serialize();
params += "&execute_mode=MAINTAIN&partialMaintain=" + maintainButton + "&partial_template=mini&submit_" + bits[0] + "_SHOW=1";
params += "&reportico_ajax_called=1";
reportico_jquery.ajax({
type: 'POST',
url: ajaxaction,
data: params,
dataType: 'html',
success: function(data, status)
{
reportico_jquery(expandpanel).removeClass("loading");
reportico_jquery(reportico_container).removeClass("loading");
if ( reportico_bootstrap_modal )
setupModals();
else
reportico_jquery("#reporticoModal").show();
reportico_jquery("#swMiniMaintain").html(data);
x = reportico_jquery(".swMntButton").prop("name");
reportico_jquery(".swMiniMaintainSubmit").prop("id", x);
},
error: function(xhr, desc, err) {
reportico_jquery(expandpanel).removeClass("loading");
reportico_jquery(reportico_container).removeClass("loading");
reportico_jquery(expandpanel).prop('innerHTML',"Ajax Error: " + xhr + "\nTextStatus: " + desc + "\nErrorThrown: " + err);
}
});
return false;
})
/*
** Trigger AJAX request for reportico button/link press if running in AJAX mode
** AJAX mode is in place when reportico session ("reportico_ajax_script") is set
** will generate full reportico output to replace the reportico_container tag
*/
reportico_jquery(document).on('click', '.swAdminButton, .swAdminButton2, .swMenuItemLink, .swPrpSubmit, .swLinkMenu, .swLinkMenu2, .reporticoSubmit', function(event)
{
if ( reportico_jquery(this).hasClass("swNoSubmit" ) )
{
return false;
}
if ( reportico_jquery(this).parents("#swMiniMaintain").length == 1 )
{
var expandpanel = reportico_jquery(this).closest('#criteriaform').find('#swPrpExpandCell');
if ( reportico_bootstrap_modal )
var loadpanel = reportico_jquery("#reporticoModal .modal-dialog .modal-content .modal-header");
else
var loadpanel = reportico_jquery("#reporticoModal .reportico-modal-dialog .reportico-modal-content .reportico-modal-header");
var reportico_container = reportico_jquery(this).closest("#reportico_container");
reportico_jquery(loadpanel).addClass("modal-loading");
forms = reportico_jquery(this).closest('.swMiniMntForm');
if ( reportico_jquery.type(reportico_ajax_script) === 'undefined' )
{
var ajaxaction = reportico_jquery(forms).prop("action");
}
else
{
ajaxaction = reportico_ajax_script;
}
params = forms.serialize();
maintainButton = reportico_jquery(this).prop("name");
params += "&execute_mode=MAINTAIN&partial_template=mini";
params += "&" + reportico_jquery(this).prop("name") + "=1";
params += "&reportico_ajax_called=1";
reportico_jquery.ajax({
type: 'POST',
url: ajaxaction,
data: params,
dataType: 'html',
success: function(data, status)
{
reportico_jquery(loadpanel).removeClass("modal-loading");
if ( reportico_bootstrap_modal )
setupModals();
reportico_jquery("#swMiniMaintain").html(data);
x = reportico_jquery(".swMntButton").prop("name");
reportico_jquery(".swMiniMaintainSubmit").prop("id", x);
},
error: function(xhr, desc, err) {
reportico_jquery(loadpanel).removeClass("modal-loading");
reportico_jquery(expandpanel).prop('innerHTML',"Ajax Error: " + xhr + "\nTextStatus: " + desc + "\nErrorThrown: " + err);
}
});
return false;
}
if ( reportico_jquery(this).parent().hasClass("swRepPrintBox" ) )
{
//var data = reportico_jquery(this).closest("#reportico_container").html();
//html_print(data);
window.print();
return false;
}
if ( reportico_jquery.type(reportico_ajax_mode) === 'undefined' || !reportico_ajax_mode)
{
return true;
}
var expandpanel = reportico_jquery(this).closest('#criteriaform').find('#swPrpExpandCell');
var reportico_container = reportico_jquery(this).closest("#reportico_container");
if ( !reportico_jquery(this).prop("href") )
{
reportico_jquery(expandpanel).addClass("loading");
reportico_jquery(reportico_container).addClass("loading");
forms = reportico_jquery(this).closest('.swMntForm,.swPrpForm,form');
if ( reportico_jquery.type(reportico_ajax_script) === 'undefined' )
{
var ajaxaction = reportico_jquery(forms).prop("action");
}
else
{
ajaxaction = reportico_ajax_script;
}
params = forms.serialize();
params += "&" + reportico_jquery(this).prop("name") + "=1";
params += "&reportico_ajax_called=1";
csvpdfoutput = false;
if ( reportico_jquery(this).prop("name") != "submit_design_mode" )
reportico_jquery(reportico_container).find("input:radio").each(function() {
d = 0;
nm = reportico_jquery(this).prop("value");
chk = reportico_jquery(this).prop("checked");
if ( chk && ( nm == "PDF" || nm == "CSV" ) )
csvpdfoutput = true;
});
if ( csvpdfoutput )
{
var windowSizeArray = [ "width=200,height=200",
"width=300,height=400,scrollbars=yes" ];
var url = ajaxaction +"?" + params;
var windowName = "popUp";//reportico_jquery(this).prop("name");
var windowSize = windowSizeArray[reportico_jquery(this).prop("rel")];
window.open(url, windowName, "width=200,height=200");
reportico_jquery(expandpanel).removeClass("loading");
reportico_jquery(reportico_container).removeClass("loading");
return false;
}
var cont = this;
reportico_jquery.ajax({
type: 'POST',
url: ajaxaction,
data: params,
dataType: 'html',
success: function(data, status)
{
reportico_jquery(expandpanel).removeClass("loading");
reportico_jquery(reportico_container).removeClass("loading");
fillDialog(data, cont);
},
error: function(xhr, desc, err) {
reportico_jquery(expandpanel).removeClass("loading");
reportico_jquery(reportico_container).removeClass("loading");
reportico_jquery(expandpanel).prop('innerHTML',"Ajax Error: " + xhr + "\nTextStatus: " + desc + "\nErrorThrown: " + err);
}
});
return false;
}
else
{
url = reportico_jquery(this).prop("href");
params = false;
runreport(url, this);
}
return false;
})
/*
** Called when used presses ok in expand mode to
** refresh middle prepare mode section with non expand mode
** text
*/
reportico_jquery(document).on('click', '#returnFromExpand', function() {
var critform = reportico_jquery(this).closest('#criteriaform');
var expandpanel = reportico_jquery(this).closest('#criteriaform').find('#swPrpExpandCell');
reportico_jquery(expandpanel).addClass("loading");
var params = reportico_jquery(critform).serialize();
params += "&execute_mode=PREPARE";
params += "&partial_template=critbody";
params += "&" + reportico_jquery(this).prop("name") + "=1";
forms = reportico_jquery(this).closest('.swMntForm,.swPrpForm,form');
ajaxaction = reportico_ajax_script;
fillPoint = reportico_jquery(this).closest('#criteriaform').find('#criteriabody');
reportico_jquery.ajax({
type: 'POST',
url: ajaxaction,
data: params,
dataType: 'html',
success: function(data, status) {
reportico_jquery(expandpanel).removeClass("loading");
reportico_jquery(fillPoint).html(data);
setupDatePickers();
setupDropMenu();
},
error: function(xhr, desc, err) {
reportico_jquery(expandpanel).removeClass("loading");
reportico_jquery(fillPoint).prop('innerHTML',"Ajax Error: " + xhr + "\nTextStatus: " + desc + "\nErrorThrown: " + err);
}
});
return false;
});
reportico_jquery(document).on('click', '#reporticoPerformExpand', function() {
forms = reportico_jquery(this).closest('.swMntForm,.swPrpForm,form');
var ajaxaction = reportico_jquery(forms).prop("action");
var critform = reportico_jquery(this).closest('#criteriaform');
ajaxaction = reportico_ajax_script;
var params = reportico_jquery(critform).serialize();
params += "&execute_mode=PREPARE";
params += "&partial_template=expand";
params += "&" + reportico_jquery(this).prop("name") + "=1";
var fillPoint = reportico_jquery(this).closest('#criteriaform').find('#swPrpExpandCell');
reportico_jquery(fillPoint).addClass("loading");
reportico_jquery.ajax({
type: 'POST',
url: ajaxaction,
data: params,
dataType: 'html',
success: function(data, status) {
reportico_jquery(fillPoint).removeClass("loading");
reportico_jquery(fillPoint).html(data);
},
error: function(xhr, desc, err) {
reportico_jquery(fillPoint).removeClass("loading");
reportico_jquery(fillPoint).prop('innerHTML',"Ajax Error: " + xhr + "\nTextStatus: " + desc + "\nErrorThrown: " + err);
}
});
return false;
});
/*
** AJAX call to run a report
** In pdf/csv mode this needs to trigger opening of a new browser window
** with output in rather that directing to screen
*/
reportico_jquery(document).on('click', '.swPrintBox,.prepareAjaxExecute,#prepareAjaxExecute', function() {
var reportico_container = reportico_jquery(this).closest("#reportico_container");
reportico_jquery(reportico_container).find("#rpt_format_pdf").prop("checked", false );
reportico_jquery(reportico_container).find("#rpt_format_csv").prop("checked", false );
reportico_jquery(reportico_container).find("#rpt_format_html").prop("checked", false );
reportico_jquery(reportico_container).find("#rpt_format_json").prop("checked", false );
reportico_jquery(reportico_container).find("#rpt_format_xml").prop("checked", false );
if ( reportico_jquery(this).hasClass("swPDFBox") )
reportico_jquery(reportico_container).find("#rpt_format_pdf").prop("checked", "checked");
if ( reportico_jquery(this).hasClass("swCSVBox") )
reportico_jquery(reportico_container).find("#rpt_format_csv").prop("checked", "checked");
if ( reportico_jquery(this).hasClass("swHTMLBox") )
reportico_jquery(reportico_container).find("#rpt_format_html").prop("checked", "checked");
if ( reportico_jquery(this).hasClass("swHTMLGoBox") )
reportico_jquery(reportico_container).find("#rpt_format_html").prop("checked", "checked");
if ( reportico_jquery(this).hasClass("swXMLBox") )
reportico_jquery(reportico_container).find("#rpt_format_xml").prop("checked", "checked");
if ( reportico_jquery(this).hasClass("swJSONBox") )
reportico_jquery(reportico_container).find("#rpt_format_json").prop("checked", "checked");
if ( reportico_jquery(this).hasClass("swPrintBox") )
reportico_jquery(reportico_container).find("#rpt_format_html").prop("checked", "checked");
if ( !reportico_jquery(this).hasClass("swPrintBox") )
if ( reportico_jquery.type(reportico_ajax_mode) === 'undefined' || !reportico_ajax_mode)
{
return true;
}
var expandpanel = reportico_jquery(this).closest('#criteriaform').find('#swPrpExpandCell');
var critform = reportico_jquery(this).closest('#criteriaform');
reportico_jquery(expandpanel).addClass("loading");
params = reportico_jquery(critform).serialize();
params += "&execute_mode=EXECUTE";
params += "&" + reportico_jquery(this).prop("name") + "=1";
forms = reportico_jquery(this).closest('.swMntForm,.swPrpForm,form');
if ( jQuery.type(reportico_ajax_script) === 'undefined' || !reportico_ajax_script )
{
var ajaxaction = reportico_jquery(forms).prop("action");
}
else
{
ajaxaction = reportico_ajax_script;
}
var csvpdfoutput = false;
var htmloutput = false;
reportico_report_title = reportico_jquery(this).closest('#reportico_container').find('.swTitle').html();
if ( !reportico_jquery(this).hasClass("swPrintBox") )
{
reportico_jquery(reportico_container).find("input:radio").each(function() {
d = 0;
nm = reportico_jquery(this).prop("value");
chk = reportico_jquery(this).prop("checked");
if ( chk && ( nm == "PDF" || nm == "CSV" ) )
csvpdfoutput = true;
//if ( chk && ( nm == "HTML" ) )
//htmloutput = true;
});
}
if ( csvpdfoutput )
{
var windowSizeArray = [ "width=200,height=200",
"width=300,height=400,scrollbars=yes" ];
var url = ajaxaction +"?" + params;
var windowName = "popUp";//reportico_jquery(this).prop("name");
var windowSize = windowSizeArray[reportico_jquery(this).prop("rel")];
window.open(url, windowName, "width=200,height=200");
reportico_jquery(expandpanel).removeClass("loading");
return false;
}
if ( reportico_jquery(this).hasClass("swPrintBox") )
{
htmloutput = true;
}
if ( !htmloutput )
params += "&reportico_ajax_called=1";
if ( reportico_jquery(this).hasClass("swPrintBox") )
params += "&printable_html=1&new_reportico_window=1";
var cont = this;
reportico_jquery.ajax({
type: 'POST',
url: ajaxaction,
data: params,
dataType: 'html',
success: function(data, status) {
reportico_jquery(expandpanel).removeClass("loading");
if ( htmloutput )
{
html_print(reportico_report_title, data);
}
else
fillDialog(data, cont);
},
error: function(xhr, desc, err) {
reportico_jquery(expandpanel).removeClass("loading");
try {
// a try/catch is recommended as the error handler
// could occur in many events and there might not be
// a JSON response from the server
var errstatus = reportico_jquery.parseJSON(xhr.responseText);
var msg = errstatus.errmsg;
//reportico_jquery(expandpanel).prop('innerHTML', msg);
alert(msg);
} catch(e) {
reportico_jquery(expandpanel).prop('innerHTML',"Error occurred in data request. Error " + xhr.status + ": " + xhr.statusText);
}
}
});
return false;
});
/*
** Runs an AJAX reportico request from a link
*/
function runreport(url, container)
{
url += "&reportico_template=";
url += "&reportico_ajax_called=1";
reportico_jquery(container).closest("#reportico_container").addClass("loading");
reportico_jquery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: url,
dataType: "html",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert ("Ajax Error: " + XMLHttpRequest.responseText + "\nTextStatus: " + textStatus + "\nErrorThrown: " + errorThrown);
},
success: function(data, status) {
reportico_jquery(container).closest("#reportico_container").removeClass("loading");
fillDialog(data,container);
}
});
}
function fillDialog(results, cont) {
x = reportico_jquery(cont).closest("#reportico_container");
reportico_jquery(cont).closest("#reportico_container").replaceWith(results);
setupDatePickers();
setupDropMenu();
setupDynamicGrids();
resizeHeaders();
resizeTables();
}
var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false;
/*
** Shows and hides a block of design items fields
*/
function toggleLine(id) {
var a = this;
var nm = a.id;
var togbut = document.getElementById(id);
var ele = document.getElementById("toggleText");
var elems = document.getElementsByTagName('*'),i;
for (i in elems)
{
if ( ie7 )
{
if((" "+elems[i].className+" ").indexOf(" "+id+" ") > -1)
{
if(elems[i].style.display == "inline") {
elems[i].style.display = "none";
togbut.innerHTML = "+";
}
else {
togbut.innerHTML = "-";
elems[i].style.display = "";
elems[i].style.display = "inline";
}
}
}
else
{
if((" "+elems[i].className+" ").indexOf(" "+id+" ") > -1)
{
if(elems[i].style.display == "table-row") {
elems[i].style.display = "none";
togbut.innerHTML = "+";
}
else {
togbut.innerHTML = "-";
elems[i].style.display = "";
elems[i].style.display = "table-row";
}
}
}
}
}
reporticohtmlwindow = null;
function html_div_print(data)
{
var reporticohtmlwindow = window.open('oooo', reportico_report_title, 'height=600,width=800');
reporticohtmlwindow.document.write('<html><head><title>' + reportico_report_title + '</title>');
reporticohtmlwindow.document.write('<link rel="stylesheet" href="' + reportico_css_path + '" type="text/css" />');
reporticohtmlwindow.document.write('</head><body >');
reporticohtmlwindow.document.write(data);
reporticohtmlwindow.document.write('</body></html>');
reporticohtmlwindow.print();
reporticohtmlwindow.close();
return true;
}
function html_print(title, data)
{
if (navigator.userAgent.indexOf('Chrome/') > 0) {
if (reporticohtmlwindow) {
reporticohtmlwindow.close();
reporticohtmlwindow = null;
}
}
reporticohtmlwindow = window.open('', "reportico_print", 'location=no,scrollbars=yes,status=no,height=600,width=800');
d = reporticohtmlwindow.document.open("text/html","replace");
reporticohtmlwindow.document.write(data);
reporticohtmlwindow.document.close();
setTimeout(html_print_fix,200);
reporticohtmlwindow.focus();
return true;
}
function html_print_fix()
{
if(!reporticohtmlwindow.resizeOutputTables)
{
setTimeout(html_print_fix,1000);
}
else
{
reporticohtmlwindow.resizeOutputTables(reporticohtmlwindow);
}
}
| grupo-glud/EcoHack | plugin/reportico/script/reportico/js/reportico.js | JavaScript | gpl-3.0 | 27,172 |
<?php
/**
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace pocketmine\event\entity;
use pocketmine\block\Block;
use pocketmine\entity\Entity;
class EntityDamageByBlockEvent extends EntityDamageEvent{
/** @var Block */
private $damager;
/**
* @param Block $damager
* @param Entity $entity
* @param int $cause
* @param int|int[] $damage
*/
public function __construct(Block $damager, Entity $entity, $cause, $damage){
$this->damager = $damager;
parent::__construct($entity, $cause, $damage);
}
/**
* @return Block
*/
public function getDamager(){
return $this->damager;
}
/**
* @return EventName|string
*/
public function getName(){
return "EntityDamageByBlockEvent";
}
} | Infernus101/Tesseract-Resurrected | src/pocketmine/event/entity/EntityDamageByBlockEvent.php | PHP | gpl-3.0 | 1,390 |
<?php
/**
* deepocean_theme.php
* Name: Deep Ocean
* Date: January 3, 2000
* Comment: Deep Ocean is a theme that is very blue.
*
* @author M.J. Prinsen
* @copyright 2000-2011 The SquirrelMail Project Team
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @version $Id: deepocean_theme.php 14084 2011-01-06 02:44:03Z pdontthink $
* @package squirrelmail
* @subpackage themes
*/
global $color;
$color[0] = '#6188a9'; // (light gray) TitleBar
$color[1] = '#800000'; // (red)
$color[2] = '#cc0000'; // (light red) Warning/Error Messages
$color[3] = '#294763'; // (green-blue) Left Bar Background
$color[4] = '#7a9cbf'; // (white) Normal Background
$color[5] = '#597d9d'; // (light yellow) Table Headers
$color[6] = '#ffffff'; // (black) Text on left bar
$color[7] = '#014070'; // (blue) Links
$color[8] = '#000000'; // (black) Normal text
$color[9] = '#587b99'; // (mid-gray) Darker version of #0
$color[10] = '#496e8b'; // (dark gray) Darker version of #9
$color[11] = '#a7c5f3'; // (dark red) Special Folders color
$color[12] = '#7092b4';
$color[15] = '#83a1da'; // (another blue) Unselectable folders color
| lantreff/dotlan_project | webmail/squirrelmail/themes/deepocean_theme.php | PHP | gpl-3.0 | 1,250 |
<?php
/**
* Donut Social Network - Yet another experimental social network.
* Copyright (C) 2016-2017, Dejan Angelov <angelovdejan92@gmail.com>
*
* This file is part of Donut Social Network.
*
* Donut Social Network 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.
*
* Donut Social Network 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 Donut Social Network. If not, see <http://www.gnu.org/licenses/>.
*
* @package Donut Social Network
* @copyright Copyright (C) 2016-2017, Dejan Angelov <angelovdejan92@gmail.com>
* @license https://github.com/angelov/donut/blob/master/LICENSE
* @author Dejan Angelov <angelovdejan92@gmail.com>
*/
namespace spec\Angelov\Donut\Communities\Handlers;
use Angelov\Donut\Core\Exceptions\ResourceNotFoundException;
use Angelov\Donut\Users\Repositories\UsersRepositoryInterface;
use Angelov\Donut\Users\User;
use Angelov\Donut\Communities\Commands\LeaveCommunityCommand;
use Angelov\Donut\Communities\Community;
use Angelov\Donut\Communities\Exceptions\CommunityMemberNotFoundException;
use Angelov\Donut\Communities\Handlers\LeaveCommunityCommandHandler;
use PhpSpec\ObjectBehavior;
use Angelov\Donut\Communities\Repositories\CommunitiesRepositoryInterface;
class LeaveCommunityCommandHandlerSpec extends ObjectBehavior
{
function let(
CommunitiesRepositoryInterface $communities,
UsersRepositoryInterface $users,
LeaveCommunityCommand $command,
User $user,
Community $community
) {
$this->beConstructedWith($communities, $users);
$command->getUserId()->willReturn('user id');
$command->getCommunityId()->willReturn('community id');
$communities->find('community id')->willReturn($community);
$users->find('user id')->willReturn($user);
}
function it_is_initializable()
{
$this->shouldHaveType(LeaveCommunityCommandHandler::class);
}
function it_throws_exception_if_the_user_is_not_found(LeaveCommunityCommand $command, UsersRepositoryInterface $users)
{
$users->find('user id')->shouldBeCalled()->willThrow(ResourceNotFoundException::class);
$this->shouldThrow(ResourceNotFoundException::class)->during('handle', [$command]);
}
function it_throws_exception_if_the_community_is_not_found(LeaveCommunityCommand $command, CommunitiesRepositoryInterface $communities)
{
$communities->find('community id')->shouldBeCalled()->willThrow(ResourceNotFoundException::class);
$this->shouldThrow(ResourceNotFoundException::class)->during('handle', [$command]);
}
function it_removes_the_member_from_the_community(
LeaveCommunityCommand $command,
CommunitiesRepositoryInterface $communities,
Community $community,
User $user
) {
$community->removeMember($user)->shouldBeCalled();
$communities->store($community)->shouldBeCalled();
$this->handle($command);
}
function it_throws_member_not_found_exception_when_trying_to_remove_non_member(
LeaveCommunityCommand $command,
Community $community,
User $user
) {
$community->removeMember($user)->willThrow(CommunityMemberNotFoundException::class);
$this->shouldThrow(CommunityMemberNotFoundException::class)->during('handle', [$command]);
}
}
| angelov/donut | spec/Donut/Communities/Handlers/LeaveCommunityCommandHandlerSpec.php | PHP | gpl-3.0 | 3,780 |
package org.um.feri.ears.problems.unconstrained.cec2014;
import org.um.feri.ears.problems.unconstrained.cec.Functions;
public class F2 extends CEC2014 {
public F2(int d) {
super(d, 2);
name = "F02 Bent Cigar Function";
}
@Override
public double eval(double[] x) {
return Functions.bent_cigar_func(x, numberOfDimensions, OShift, M, 1, 1) + funcNum * 100.0;
}
}
| UM-LPM/EARS | src/org/um/feri/ears/problems/unconstrained/cec2014/F2.java | Java | gpl-3.0 | 426 |
#!/usr/bin/env python
from distutils.core import setup
setup(
name="flowtools",
description="Tools for flow maps from modified Gromacs simulations",
long_description="See README.md",
license='GPLv3',
version='0.2.30',
url="https://github.com/pjohansson/flowtools",
author="Petter Johansson",
author_email="petter.johansson@scilifelab.se",
packages=['flowtools'],
requires=[
'numpy (>=1.7.0)',
'matplotlib (>=1.2.0)',
'pandas (>=0.10.1)',
'scipy (>=0.11.0)'
],
scripts=[
'scripts/f_collect_spread.py',
'scripts/f_combine_maps.py',
'scripts/f_flowmaps.py',
'scripts/f_print.py',
'scripts/f_spread_delta_t.py',
'scripts/f_spread_plot.py',
'scripts/f_spread_ttest.py',
'scripts/f_spread_com.py',
'scripts/f_spread_std.py',
'scripts/f_velprofile.py',
'scripts/f_average_maps.py',
'scripts/f_spread_vel.py',
'scripts/f_combine_cells.py',
'scripts/f_viscous_dissipation.py',
'scripts/f_interface.py',
'scripts/f_shearmax.py',
'scripts/f_contactline.py'
]
)
| pjohansson/flowtools | setup.py | Python | gpl-3.0 | 1,324 |
/*
* Copyright (C) 2005-2010 Erik Nilsson, software on versionstudio point 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/>.
*/
Ext.namespace("vibe.plugin.playlists");
vibe.plugin.playlists.PlaylistsDialog = Ext.extend(Ext.Window,
{
/**
* @cfg {Mixed} data
* The data records for the combo box simple store.
*/
data: [],
/**
* @cfg {String} emptyText
* The text to display if the combo box is empty.
*/
emptyText : "",
/**
* @cfg {String} requireSelection
* Require a selection in the list.
*/
requireSelection : false,
// private
closeButton : null,
// private
comboBox : null,
// private
okButton : null,
/**
* @override
*/
initComponent: function()
{
this.addEvents(
/**
* @event submit
* Fired when the dialog is successfully submitted through
* a click on the OK button.
* @param {String} name the name of the playlist
* @param {Number} playlistId the database id of the playlist or null if
* playlist does not exists in the database.
*/
"submit"
);
var store = new Ext.data.SimpleStore({
autoLoad: false,
data: this.data,
fields: ["name","playlistId"]
});
this.comboBox = new Ext.form.ComboBox({
displayField: "name",
emptyText: this.emptyText,
enableKeyEvents: true,
forceSelection: false,
mode: "local",
selectOnFocus: true,
store: store,
triggerAction: "all",
typeAhead: this.requireSelection
});
this.okButton = new Ext.Button({
disabled: true,
minWidth: 75,
scope: this,
text: vibe.Language.app.OK
});
this.closeButton = new Ext.Button({
minWidth: 75,
scope: this,
text: vibe.Language.app.CLOSE
});
Ext.apply(this,
{
bodyStyle: "padding: 10px 10px 10px 10px",
buttonAlign: "center",
buttons: [this.okButton,
this.closeButton],
height: 110,
items: [this.comboBox],
modal: true,
layout: "fit",
resizable: false,
shadowOffset: 6,
width: 300
});
vibe.plugin.playlists.PlaylistsDialog.superclass.initComponent.call(this);
this.closeButton.on("click",this.onCloseButtonClick,this);
this.comboBox.on("keyup",this.onComboBoxKeyUp,this);
this.comboBox.on("select",this.onComboBoxSelect,this);
this.okButton.on("click",this.onOkButtonClick,this);
},
// private
onComboBoxKeyUp : function(comboBox,e)
{
if ( this.comboBox.getValue().length==0 ) {
this.okButton.disable();
return;
}
if ( this.requireSelection && this.getSelectedRecord()==null ) {
this.okButton.disable();
}
else {
this.okButton.enable();
}
},
// private
onComboBoxSelect : function(comboBox,record,index)
{
this.okButton.enable();
},
// private
onCloseButtonClick : function()
{
this.close();
},
// private
onOkButtonClick : function()
{
var name = null;
var playlistId = null;
var record = this.getSelectedRecord();
if ( record!=null ) {
name = record.get("name");
playlistId = record.get("playlistId");
}
else {
name = this.comboBox.getValue();
}
this.fireEvent("submit",name,playlistId);
this.close();
},
// private
getSelectedRecord : function()
{
var selectedRecord = null;
var index = this.comboBox.selectedIndex;
if ( index!=-1 )
{
// make sure selected record matches exactly
// the combo box value
var record = this.comboBox.store.getAt(index);
if ( record.get("name")==this.comboBox.getValue() ) {
selectedRecord = record;
}
}
return selectedRecord;
}
}); | versionstudio/vibestreamer | client/vibe-ext/plugins/playlists/src/PlaylistsDialog.js | JavaScript | gpl-3.0 | 4,457 |
// Copyright (C) 2011, 2012 Google Inc.
//
// This file is part of ycmd.
//
// ycmd 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.
//
// ycmd 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 ycmd. If not, see <http://www.gnu.org/licenses/>.
#include "IdentifierUtils.h"
#include "Utils.h"
#include <boost/regex.hpp>
#include <unordered_map>
namespace YouCompleteMe {
namespace fs = boost::filesystem;
namespace {
// For details on the tag format supported, see here for details:
// http://ctags.sourceforge.net/FORMAT
// TL;DR: The only supported format is the one Exuberant Ctags emits.
// const char *const TAG_REGEX =
// "^([^\\t\\n\\r]+)" // The first field is the identifier
// "\\t" // A TAB char is the field separator
// // The second field is the path to the file that has the identifier; either
// // absolute or relative to the tags file.
// "([^\\t\\n\\r]+)"
// "\\t.*?" // Non-greedy everything
// "(?:language:([^\\t\\n\\r]+))?" // We want to capture the language of the file
// ;
// Only used as the equality comparer for the below unordered_map which stores
// const char* pointers and not std::string but needs to hash based on string
// values and not pointer values.
// When passed a const char* this will create a temporary std::string for
// comparison, but it's fast enough for our use case.
struct StringEqualityComparer :
std::binary_function< std::string, std::string, bool > {
bool operator()( const std::string &a, const std::string &b ) const {
return a == b;
}
};
typedef std::unordered_map < const char *,
const char *,
std::hash< std::string >,
StringEqualityComparer > StaticMap;
const StaticMap *EXT_TO_FILETYPE = new StaticMap {
{ ".rb", "ruby" },
{ ".h", "c" },
{ ".c", "c" },
{ ".lua", "lua" },
{ ".php", "php" },
};
// List of languages Universal Ctags supports:
// ctags --list-languages
// To map a language name to a filetype, see this file:
// :e $VIMRUNTIME/filetype.vim
// This is a map of const char* and not std::string to prevent issues with
// static initialization.
const StaticMap *LANG_TO_FILETYPE = new StaticMap {
{ "Ada" , "ada" },
{ "AnsiblePlaybook" , "ansibleplaybook" },
{ "Ant" , "ant" },
{ "Asm" , "asm" },
{ "Asp" , "asp" },
{ "Autoconf" , "autoconf" },
{ "Automake" , "automake" },
{ "Awk" , "awk" },
{ "Basic" , "basic" },
{ "BETA" , "beta" },
{ "C" , "c" },
{ "C#" , "cs" },
{ "C++" , "cpp" },
{ "Clojure" , "clojure" },
{ "Cobol" , "cobol" },
{ "CPreProcessor" , "cpreprocessor" },
{ "CSS" , "css" },
{ "ctags" , "ctags" },
{ "CUDA" , "cuda" },
{ "D" , "d" },
{ "DBusIntrospect" , "dbusintrospect" },
{ "Diff" , "diff" },
{ "DosBatch" , "dosbatch" },
{ "DTD" , "dtd" },
{ "DTS" , "dts" },
{ "Eiffel" , "eiffel" },
{ "elm" , "elm" },
{ "Erlang" , "erlang" },
{ "Falcon" , "falcon" },
{ "Flex" , "flex" },
{ "Fortran" , "fortran" },
{ "gdbinit" , "gdb" },
{ "Glade" , "glade" },
{ "Go" , "go" },
{ "HTML" , "html" },
{ "Iniconf" , "iniconf" },
{ "ITcl" , "itcl" },
{ "Java" , "java" },
{ "JavaProperties" , "jproperties" },
{ "JavaScript" , "javascript" },
{ "JSON" , "json" },
{ "LdScript" , "ldscript" },
{ "Lisp" , "lisp" },
{ "Lua" , "lua" },
{ "M4" , "m4" },
{ "Make" , "make" },
{ "man" , "man" },
{ "MatLab" , "matlab" },
{ "Maven2" , "maven2" },
{ "Myrddin" , "myrddin" },
{ "ObjectiveC" , "objc" },
{ "OCaml" , "ocaml" },
{ "Pascal" , "pascal" },
{ "passwd" , "passwd" },
{ "Perl" , "perl" },
{ "Perl6" , "perl6" },
{ "PHP" , "php" },
{ "PlistXML" , "plistxml" },
{ "pod" , "pod" },
{ "Protobuf" , "protobuf" },
{ "PuppetManifest" , "puppet" },
{ "Python" , "python" },
{ "PythonLoggingConfig" , "pythonloggingconfig" },
{ "QemuHX" , "qemuhx" },
{ "R" , "r" },
{ "RelaxNG" , "rng" },
{ "reStructuredText" , "rst" },
{ "REXX" , "rexx" },
{ "Robot" , "robot" },
{ "RpmSpec" , "spec" },
{ "RSpec" , "rspec" },
{ "Ruby" , "ruby" },
{ "Rust" , "rust" },
{ "Scheme" , "scheme" },
{ "Sh" , "sh" },
{ "SLang" , "slang" },
{ "SML" , "sml" },
{ "SQL" , "sql" },
{ "SVG" , "svg" },
{ "SystemdUnit" , "systemd" },
{ "SystemVerilog" , "systemverilog" },
{ "Tcl" , "tcl" },
{ "TclOO" , "tcloo" },
{ "Tex" , "tex" },
{ "TTCN" , "ttcn" },
{ "Vera" , "vera" },
{ "Verilog" , "verilog" },
{ "VHDL" , "vhdl" },
{ "Vim" , "vim" },
{ "WindRes" , "windres" },
{ "XSLT" , "xslt" },
{ "YACC" , "yacc" },
{ "Yaml" , "yaml" },
{ "YumRepo" , "yumrepo" },
{ "Zephir" , "zephir" }
};
} // unnamed namespace
FiletypeIdentifierMap ExtractIdentifiersFromTagsFile(
const fs::path &path_to_tag_file ) {
FiletypeIdentifierMap filetype_identifier_map;
std::string tags_file_contents;
try {
tags_file_contents = ReadUtf8File( path_to_tag_file );
} catch ( ... ) {
return filetype_identifier_map;
}
std::istringstream istring {tags_file_contents};
std::string line;
std::string const languageMarker{"language:"};
auto appendLine = [&]{
std::istringstream iline {line};
std::string identifier, p;
if (!std::getline(iline, identifier, '\t')) { return; }
if (!std::getline(iline, p, '\t')) { return; }
std::string language;
std::string filetype;
while (std::getline(iline, language, '\t')) {
if (language.size() <= languageMarker.size()) { break; }
auto v = std::mismatch(languageMarker.begin(), languageMarker.end(), language.begin());
if (v.first == languageMarker.end()) {
language.erase(language.begin(), v.second);
filetype = FindWithDefault( *LANG_TO_FILETYPE,
language.c_str(),
Lowercase( language ).c_str() );
}
}
fs::path path( std::move(p) );
if (filetype.empty()) {
language = boost::filesystem::extension(path);
auto it = EXT_TO_FILETYPE->find( language.c_str() );
if (it == EXT_TO_FILETYPE->end()) { return; } // skip unknown extension type
filetype = it->second;
}
path = NormalizePath( path, path_to_tag_file.parent_path() );
filetype_identifier_map[ std::move(filetype) ][ path.string() ].push_back( std::move(identifier) );
};
// skip prefix headerr
while (std::getline(istring, line)) {
if (!(line.length() > 0 && line[0] == '!')) {
appendLine();
break;
}
}
while (std::getline(istring, line)) {
appendLine();
}
return filetype_identifier_map;
}
} // namespace YouCompleteMe
| SolaWing/ycmd | cpp/ycm/IdentifierUtils.cpp | C++ | gpl-3.0 | 10,271 |
__productname__ = 'dotinstall'
__version__ = '0.1'
__copyright__ = "Copyright (C) 2014 Cinghio Pinghio"
__author__ = "Cinghio Pinghio"
__author_email__ = "cinghio@linuxmail.org"
__description__ = "Install dotfiles"
__long_description__ = "Install dofile based on some rules"
__url__ = "cinghiopinghio...."
__license__ = "Licensed under the GNU GPL v3+."
| cinghiopinghio/dotinstall | dotinstall/__init__.py | Python | gpl-3.0 | 354 |
__all__ = ['appie.appie', 'appie.extensions']
from appie.appie import *
from appie.extensions import *
| sphaero/appie | appie/__init__.py | Python | gpl-3.0 | 104 |
package edu.hm.cs.smc.channels.linkedin.models;
import javax.persistence.Entity;
import edu.hm.cs.smc.database.models.BaseEntity;
@Entity
public class LinkedInEmployeeCountRange extends BaseEntity {
private String code;
private String name;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| CCWI/SocialMediaCrawler | src/edu/hm/cs/smc/channels/linkedin/models/LinkedInEmployeeCountRange.java | Java | gpl-3.0 | 482 |
var _ = require('underscore'),
Backbone = require('backbone'),
DAL = require('../DAL');
var Message = Backbone.Model.extend(
/** @lends Message.prototype */
{
defaults: {
userId: null,
waveId: null,
parentId: null,
message: '',
unread: true,
created_at: null
},
idAttribute: '_id',
/** @constructs */
initialize: function () {
if (this.isNew()) {
this.set('created_at', Date.now());
}
},
save: function () {
return DAL.saveMessage(this);
},
validate: function (attrs) {
if (0 === attrs.message.trim().length) {
return 'Empty message';
}
}
}
);
/** @class */
var MessageCollection = Backbone.Collection.extend(
/** @lends MessageCollection.prototype */
{
model: Message
}
);
module.exports = { Model: Message, Collection: MessageCollection }; | tofuseng/SURF | code/model/Message.js | JavaScript | gpl-3.0 | 1,029 |
///////////////////////////////////////////////////////////
// //
// SAGA //
// //
// System for Automated Geoscientific Analyses //
// //
// Module Library: //
// ta_lighting //
// //
//-------------------------------------------------------//
// //
// View_Shed.cpp //
// //
// Copyright (C) 2008 by //
// Olaf Conrad //
// //
//-------------------------------------------------------//
// //
// This file is part of 'SAGA - System for Automated //
// Geoscientific Analyses'. SAGA is free software; you //
// can redistribute it and/or modify it under the terms //
// of the GNU General Public License as published by the //
// Free Software Foundation; version 2 of the License. //
// //
// SAGA 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. //
// //
//-------------------------------------------------------//
// //
// e-mail: oconrad@saga-gis.org //
// //
// contact: Olaf Conrad //
// Institute of Geography //
// University of Hamburg //
// Bundesstr. 55 //
// 20146 Hamburg //
// Germany //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
#include "view_shed.h"
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
CView_Shed::CView_Shed(void)
{
//-----------------------------------------------------
Set_Name (_TL("Sky View Factor"));
Set_Author (SG_T("(c) 2008 by O.Conrad"));
Set_Description (_TW(
"\n"
"\n"
"References:\n"
"Boehner, J., Antonic, O. (2008): "
"'Land-suface parameters specific to topo-climatology'. "
"in: Hengl, T., Reuter, H. (Eds.): 'Geomorphometry - Concepts, Software, Applications', in press\n"
"\n"
"Hantzschel, J., Goldberg, V., Bernhofer, C. (2005): "
"'GIS-based regionalisation of radiation, temperature and coupling measures in complex terrain for low mountain ranges'. "
"Meteorological Applications, V.12:01, p.3342, doi:10.1017/S1350482705001489\n"
"\n"
"Oke, T.R. (2000): "
"'Boundary Layer Climates'. "
"Taylor & Francis, New York. 435pp.\n"
));
//-----------------------------------------------------
Parameters.Add_Grid(
NULL , "DEM" , _TL("Elevation"),
_TL(""),
PARAMETER_INPUT
);
Parameters.Add_Grid(
NULL , "VISIBLE" , _TL("Visible Sky"),
_TL("The unobstructed hemisphere given as percentage."),
PARAMETER_OUTPUT
);
Parameters.Add_Grid(
NULL , "SVF" , _TL("Sky View Factor"),
_TL(""),
PARAMETER_OUTPUT
);
Parameters.Add_Grid(
NULL , "SIMPLE" , _TL("Sky View Factor (Simplified)"),
_TL(""),
PARAMETER_OUTPUT_OPTIONAL
);
Parameters.Add_Grid(
NULL , "TERRAIN" , _TL("Terrain View Factor"),
_TL(""),
PARAMETER_OUTPUT_OPTIONAL
);
Parameters.Add_Value(
NULL , "MAXRADIUS" , _TL("Maximum Search Radius"),
_TL("This value is ignored if set to zero."),
PARAMETER_TYPE_Double , 10000.0, 0.0, true
);
Parameters.Add_Choice(
NULL , "METHOD" , _TL("Method"),
_TL(""),
CSG_String::Format(SG_T("%s|%s|"),
_TL("multi scale"),
_TL("sectors")
), 0
);
Parameters.Add_Value(
NULL , "LEVEL_INC" , _TL("Multi Scale Factor"),
_TL(""),
PARAMETER_TYPE_Double , 3.0, 1.25, true
);
Parameters.Add_Value(
NULL , "NDIRS" , _TL("Number of Sectors"),
_TL(""),
PARAMETER_TYPE_Int , 8.0, 3, true
);
}
//---------------------------------------------------------
CView_Shed::~CView_Shed(void)
{}
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
bool CView_Shed::On_Execute(void)
{
bool bResult = false;
int nDirections;
double Visible, SVF, Simple, Terrain, Level_Inc;
CSG_Grid *pVisible, *pSVF, *pSimple, *pTerrain;
m_pDEM = Parameters("DEM") ->asGrid();
pVisible = Parameters("VISIBLE") ->asGrid();
pSVF = Parameters("SVF") ->asGrid();
pSimple = Parameters("SIMPLE") ->asGrid();
pTerrain = Parameters("TERRAIN") ->asGrid();
m_MaxRadius = Parameters("MAXRADIUS") ->asDouble();
m_Method = Parameters("METHOD") ->asInt();
Level_Inc = Parameters("LEVEL_INC") ->asDouble();
nDirections = Parameters("NDIRS") ->asInt();
DataObject_Set_Colors(pVisible , 100, SG_COLORS_BLACK_WHITE);
DataObject_Set_Colors(pSVF , 100, SG_COLORS_BLACK_WHITE);
DataObject_Set_Colors(pSimple , 100, SG_COLORS_BLACK_WHITE);
DataObject_Set_Colors(pTerrain , 100, SG_COLORS_BLACK_WHITE, true);
//-----------------------------------------------------
switch( m_Method )
{
case 0: // multi scale
if( m_Pyramid.Create(m_pDEM, Level_Inc, GRID_PYRAMID_Mean) )
{
m_MaxLevel = m_Pyramid.Get_Count();
if( m_MaxRadius > 0.0 )
{
while( m_MaxLevel > 0 && m_Pyramid.Get_Grid(m_MaxLevel - 1)->Get_Cellsize() > m_MaxRadius )
{
m_MaxLevel--;
}
}
bResult = Initialise(8);
}
break;
case 1: // sectors
bResult = Initialise(nDirections);
break;
}
if( m_Method != 0 && m_MaxRadius <= 0.0 )
{
m_MaxRadius = Get_Cellsize() * M_GET_LENGTH(Get_NX(), Get_NY());
}
//-----------------------------------------------------
if( bResult )
{
for(int y=0; y<Get_NY() && Set_Progress(y); y++)
{
for(int x=0; x<Get_NX(); x++)
{
if( Get_View_Shed(x, y, Visible, SVF, Simple, Terrain) )
{
if( pVisible ) pVisible->Set_Value (x, y, Visible);
if( pSVF ) pSVF ->Set_Value (x, y, SVF);
if( pSimple ) pSimple ->Set_Value (x, y, Simple);
if( pTerrain ) pTerrain->Set_Value (x, y, Terrain);
}
else
{
if( pVisible ) pVisible->Set_NoData(x, y);
if( pSVF ) pSVF ->Set_NoData(x, y);
if( pSimple ) pSimple ->Set_NoData(x, y);
if( pTerrain ) pTerrain->Set_NoData(x, y);
}
}
}
}
//-----------------------------------------------------
m_Pyramid .Destroy();
m_Angles .Destroy();
m_Direction .Clear();
return( bResult );
}
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
bool CView_Shed::Initialise(int nDirections)
{
m_Angles .Create (nDirections);
m_Direction .Set_Count (nDirections);
for(int iDirection=0; iDirection<nDirections; iDirection++)
{
m_Direction[iDirection].z = (M_PI_360 * iDirection) / nDirections;
m_Direction[iDirection].x = sin(m_Direction[iDirection].z);
m_Direction[iDirection].y = cos(m_Direction[iDirection].z);
}
return( true );
}
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
bool CView_Shed::Get_View_Shed(int x, int y, double &Sky_Visible, double &Sky_Factor, double &Sky_Simple, double &Sky_Terrain)
{
double slope, aspect;
if( m_pDEM->Get_Gradient(x, y, slope, aspect) )
{
bool bResult;
switch( m_Method )
{
case 0: bResult = Get_Angles_Multi_Scale(x, y); break;
default: bResult = Get_Angles_Sectoral (x, y); break;
}
if( bResult )
{
double sinSlope, cosSlope, Phi, sinPhi, cosPhi;
Sky_Visible = 0.0;
Sky_Factor = 0.0;
sinSlope = sin(slope);
cosSlope = cos(slope);
for(int iDirection=0; iDirection<m_Angles.Get_N(); iDirection++)
{
Phi = atan(m_Angles[iDirection]);
cosPhi = cos(Phi);
sinPhi = sin(Phi);
Sky_Visible += (M_PI_090 - Phi) * 100.0 / M_PI_090;
Sky_Factor += cosSlope * cosPhi*cosPhi + sinSlope * cos(m_Direction[iDirection].z - aspect) * ((M_PI_090 - Phi) - sinPhi * cosPhi);
}
Sky_Visible /= m_Angles.Get_N();
Sky_Factor /= m_Angles.Get_N();
Sky_Simple = (1.0 + cosSlope) / 2.0;
Sky_Terrain = Sky_Simple - Sky_Factor;
return( true );
}
}
return( false );
}
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
bool CView_Shed::Get_Angles_Multi_Scale(int x, int y)
{
if( !m_pDEM->is_NoData(x, y) )
{
double z, d;
TSG_Point p, q;
z = m_pDEM->asDouble(x, y);
p = Get_System()->Get_Grid_to_World(x, y);
m_Angles.Assign(0.0);
//-------------------------------------------------
for(int iGrid=-1; iGrid<m_MaxLevel; iGrid++)
{
CSG_Grid *pGrid = m_Pyramid.Get_Grid(iGrid);
for(int iDirection=0; iDirection<8; iDirection++)
{
q.x = p.x + pGrid->Get_Cellsize() * m_Direction[iDirection].x;
q.y = p.y + pGrid->Get_Cellsize() * m_Direction[iDirection].y;
if( pGrid->Get_Value(q, d) && (d = (d - z) / pGrid->Get_Cellsize()) > m_Angles[iDirection] )
{
m_Angles[iDirection] = d;
}
}
}
return( true );
}
return( false );
}
//---------------------------------------------------------
bool CView_Shed::Get_Angles_Sectoral(int x, int y)
{
if( !m_pDEM->is_NoData(x, y) )
{
m_Angles.Assign(0.0);
//-------------------------------------------------
for(int iDirection=0; iDirection<m_Angles.Get_N(); iDirection++)
{
m_Angles[iDirection] = Get_Angle_Sectoral(x, y, m_Direction[iDirection].x, m_Direction[iDirection].y);
}
return( true );
}
return( false );
}
//---------------------------------------------------------
double CView_Shed::Get_Angle_Sectoral(int x, int y, double dx, double dy)
{
double Angle, Distance, dDistance, ix, iy, d, z;
z = m_pDEM->asDouble(x, y);
ix = x;
iy = y;
Angle = 0.0;
Distance = 0.0;
dDistance = Get_Cellsize() * M_GET_LENGTH(dx, dy);
while( is_InGrid(x, y) && Distance <= m_MaxRadius )
{
ix += dx; x = (int)(0.5 + ix);
iy += dy; y = (int)(0.5 + iy);
Distance += dDistance;
if( m_pDEM->is_InGrid(x, y) && (d = (m_pDEM->asDouble(x, y) - z) / Distance) > Angle )
{
Angle = d;
}
}
return( Angle );
}
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
| gregorburger/SAGA-GIS | src/modules_terrain_analysis/terrain_analysis/ta_lighting/view_shed.cpp | C++ | gpl-3.0 | 12,838 |
<?php
/**
* Handles viewing a certificate
*
* @package mod
* @subpackage simplecertificate
* @copyright Carlos Fonseca <carlos.alexandre@outlook.com>, Chardelle Busch, Mark Nelson <mark@moodle.com.au>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(dirname(dirname(dirname(__FILE__))).'/config.php');
require_once("$CFG->dirroot/mod/simplecertificate/lib.php");
require_once("$CFG->libdir/pdflib.php");
require_once("$CFG->dirroot/mod/simplecertificate/locallib.php");
$id = required_param('id', PARAM_INT); // Course Module ID
$action = optional_param('action', '', PARAM_ALPHA);
$tab = optional_param('tab', simplecertificate::DEFAULT_VIEW, PARAM_INT);
$type = optional_param('type', '', PARAM_ALPHA);
$page = optional_param('page', 0, PARAM_INT);
$perpage = optional_param('perpage', get_config('simplecertificate', 'perpage'), PARAM_INT);
$orderby = optional_param('orderby', 'username', PARAM_RAW);
$issuelist = optional_param('issuelist', null, PARAM_ALPHA);
$selectedusers = optional_param_array('selectedusers', null, PARAM_INT);
if (!$cm = get_coursemodule_from_id( 'simplecertificate', $id)) {
print_error('Course Module ID was incorrect');
}
if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
print_error('course is misconfigured');
}
if (!$certificate = $DB->get_record('simplecertificate', array('id' => $cm->instance))) {
print_error('course module is incorrect');
}
$context = context_module::instance ($cm->id);
$url = new moodle_url('/mod/simplecertificate/view.php', array (
'id' => $cm->id,
'tab' => $tab,
'page' => $page,
'perpage' => $perpage,
));
if ($type) {
$url->param('type', $type);
}
if ($orderby) {
$url->param ('orderby', $orderby);
}
if ($action) {
$url->param ('action', $action);
}
if ($issuelist) {
$url->param ('issuelist', $issuelist);
}
// Initialize $PAGE, compute blocks
$PAGE->set_url($url);
$PAGE->set_context($context);
$PAGE->set_cm($cm);
require_login( $course->id, false, $cm);
require_capability('mod/simplecertificate:view', $context);
$canmanage = has_capability('mod/simplecertificate:manage', $context);
// log update
$simplecertificate = new simplecertificate($context, $cm, $course);
$simplecertificate->set_instance($certificate);
$completion = new completion_info($course);
$completion->set_module_viewed($cm);
$PAGE->set_title(format_string($certificate->name));
$PAGE->set_heading(format_string($course->fullname));
switch ($tab) {
case $simplecertificate::ISSUED_CERTIFCADES_VIEW :
$simplecertificate->view_issued_certificates($url);
break;
case $simplecertificate::BULK_ISSUE_CERTIFCADES_VIEW :
$simplecertificate->view_bulk_certificates($url, $selectedusers);
break;
default :
$simplecertificate->view_default($url, $canmanage);
break;
}
| nitro2010/moodle | mod/simplecertificate/view.php | PHP | gpl-3.0 | 2,818 |
package com.personal.allutil;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;
import android.app.Application;
import android.content.Context;
/**
* Created by zzz on 8/18/2016.
*/
public class ZApplication extends Application {
private static final String TAG = "ZApp";
private static ZApplication instance;
private static Context context;
/**
* Called when the application is starting, before any activity, service,
* or receiver objects (excluding content providers) have been created.
* Implementations should be as quick as possible (for example using
* lazy initialization of state) since the time spent in this function
* directly impacts the performance of starting the first activity,
* service, or receiver in a process.
* If you override this method, be sure to call super.onCreate().
*/
@Override
public void onCreate() {
super.onCreate();
instance = this;
context = getApplicationContext();
Logger.init(TAG);
}
public static ZApplication getInstance() {
return instance;
}
public static Context getContext() {
return context;
}
}
| portguas/androidsc | Demons/allutil/src/main/java/com/personal/allutil/ZApplication.java | Java | gpl-3.0 | 1,215 |
package org.gvsig.gpe.gml.parser.sfp0.geometries;
import java.io.IOException;
import javax.xml.namespace.QName;
import org.gvsig.gpe.gml.parser.GPEDefaultGmlParser;
import org.gvsig.gpe.gml.utils.GMLTags;
import org.gvsig.gpe.xml.stream.IXmlStreamReader;
import org.gvsig.gpe.xml.stream.XmlStreamException;
import org.gvsig.gpe.xml.utils.CompareUtils;
/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana
*
* Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA.
*
* For more information, contact:
*
* Generalitat Valenciana
* Conselleria d'Infraestructures i Transport
* Av. Blasco Ibáñez, 50
* 46010 VALENCIA
* SPAIN
*
* +34 963862235
* gvsig@gva.es
* www.gvsig.gva.es
*
* or
*
* IVER T.I. S.A
* Salamanca 50
* 46005 Valencia
* Spain
*
* +34 963163400
* dac@iver.es
*/
/* CVS MESSAGES:
*
* $Id$
* $Log$
*
*/
/**
* @author Jorge Piera LLodrá (jorge.piera@iver.es)
*/
public class GeometryBinding extends org.gvsig.gpe.gml.parser.v2.geometries.GeometryBinding{
/*
* (non-Javadoc)
* @see org.gvsig.gpe.gml.bindings.v2.geometries.GeometryBinding#parseTag(org.xmlpull.v1.XmlPullParser, org.gvsig.gpe.gml.GPEDefaultGmlParser, java.lang.String)
*/
protected Object parseTag(IXmlStreamReader parser,GPEDefaultGmlParser handler, QName tag) throws XmlStreamException, IOException{
Object geometry = super.parseTag(parser, handler, tag);
if (geometry != null){
return geometry;
}
if (CompareUtils.compareWithNamespace(tag,GMLTags.GML_MULTICURVEPROPERTY)){
geometry = handler.getProfile().getCurvePropertyTypeBinding().
parse(parser, handler);
}else if (CompareUtils.compareWithNamespace(tag,GMLTags.GML_CURVEPROPERTY)){
geometry = handler.getProfile().getCurvePropertyTypeBinding().
parse(parser, handler);
}else if (CompareUtils.compareWithNamespace(tag,GMLTags.GML_MULTICURVE)){
geometry = handler.getProfile().getMultiCurveTypeBinding().
parse(parser, handler);
}
//MULTIPOLYGON PROPERTY ALIASES
else if (CompareUtils.compareWithNamespace(tag,GMLTags.GML_MULTISURFACE)){
geometry = handler.getProfile().getMultiPolygonTypeBinding().
parse(parser, handler);
}else if (CompareUtils.compareWithNamespace(tag,GMLTags.GML_SURFACE)){
geometry = handler.getProfile().getPolygonTypeBinding().
parse(parser, handler);
}
return geometry;
}
}
| iCarto/siga | libGPE-GML/src/org/gvsig/gpe/gml/parser/sfp0/geometries/GeometryBinding.java | Java | gpl-3.0 | 3,114 |
function parse(req) {
var arreglo_parametros = [], parametros = {};
if (req.url.indexOf("?") > 0 ){
var url_data = req.url.split("?");
var arreglo_parametros = url_data[1].split("&");
}
for (var i = arreglo_parametros.length - 1; i >= 0; i--) {
var parametro = arreglo_parametros[i]
var param_data = parametro.split("=");
parametros[param_data[0]] = [param_data[1]];
}
return parametros;
}
module.exports.parse = parse; | fcojulio/Test-NodeJS | params_parser.js | JavaScript | gpl-3.0 | 445 |
#include "omp_target_update.hpp"
TC_OMP_TARGET_UPDATE aOMP_TARGET_UPDATE;
void
TC_OMP_TARGET_UPDATE::finish_type (tree t)
{
cerr << "finish_type: OMP_TARGET_UPDATE" << t << endl;
};
void
TC_OMP_TARGET_UPDATE::finish_decl (tree t)
{
cerr << "finish_decl: OMP_TARGET_UPDATE" << t << endl;
};
void
TC_OMP_TARGET_UPDATE::finish_unit (tree t)
{
cerr << "finish_unit: OMP_TARGET_UPDATE" << t << endl;
};
| h4ck3rm1k3/gcc-plugin-cpp-template | tree-nodes/omp_target_update.cpp | C++ | gpl-3.0 | 408 |
#!/usr/bin/env python
#
# This file is part of pacman-mirrors.
#
# pacman-mirrors 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.
#
# pacman-mirrors 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 pacman-mirrors. If not, see <http://www.gnu.org/licenses/>.
#
# from https://wiki.maemo.org/Internationalize_a_Python_application
"""Pacman-Mirrors Translation Module"""
import os
import sys
import locale
import gettext
# The translation files will be under
# @LOCALE_DIR@/@LANGUAGE@/LC_MESSAGES/@APP_NAME@.mo
APP_NAME = "pacman_mirrors"
APP_DIR = os.path.join(sys.prefix, "share")
LOCALE_DIR = os.path.join(APP_DIR, "locale")
CODESET = "utf-8"
# Now we need to choose the language. We will provide a list, and gettext
# will use the first translation available in the list
LANGUAGES = []
try:
user_locale = locale.getdefaultlocale()[0]
if user_locale:
LANGUAGES += user_locale
except ValueError:
pass
LANGUAGES += os.environ.get("LANGUAGE", "").split(":")
LANGUAGES += ["en_US"]
# Lets tell those details to gettext
# (nothing to change here for you)
gettext.install(True)
gettext.bindtextdomain(APP_NAME, LOCALE_DIR)
gettext.bind_textdomain_codeset(APP_NAME, codeset=CODESET)
gettext.textdomain(APP_NAME)
language = gettext.translation(APP_NAME, LOCALE_DIR, LANGUAGES, fallback=True)
# Add this to every module:
#
# import i18n
# _ = i18n.language.gettext
| fhdk/pacman-mirrors | pacman_mirrors/translation/i18n.py | Python | gpl-3.0 | 1,832 |
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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.
#
# qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""A QProcess which shows notifications in the GUI."""
import locale
import shlex
from PyQt5.QtCore import (pyqtSlot, pyqtSignal, QObject, QProcess,
QProcessEnvironment)
from qutebrowser.utils import message, log, utils
from qutebrowser.browser import qutescheme
class GUIProcess(QObject):
"""An external process which shows notifications in the GUI.
Args:
cmd: The command which was started.
args: A list of arguments which gets passed.
verbose: Whether to show more messages.
_output_messages: Show output as messages.
_started: Whether the underlying process is started.
_proc: The underlying QProcess.
_what: What kind of thing is spawned (process/editor/userscript/...).
Used in messages.
Signals:
error/finished/started signals proxied from QProcess.
"""
error = pyqtSignal(QProcess.ProcessError)
finished = pyqtSignal(int, QProcess.ExitStatus)
started = pyqtSignal()
def __init__(self, what, *, verbose=False, additional_env=None,
output_messages=False, parent=None):
super().__init__(parent)
self._what = what
self.verbose = verbose
self._output_messages = output_messages
self._started = False
self.cmd = None
self.args = None
self._proc = QProcess(self)
self._proc.errorOccurred.connect(self._on_error)
self._proc.errorOccurred.connect(self.error)
self._proc.finished.connect(self._on_finished)
self._proc.finished.connect(self.finished)
self._proc.started.connect(self._on_started)
self._proc.started.connect(self.started)
if additional_env is not None:
procenv = QProcessEnvironment.systemEnvironment()
for k, v in additional_env.items():
procenv.insert(k, v)
self._proc.setProcessEnvironment(procenv)
@pyqtSlot(QProcess.ProcessError)
def _on_error(self, error):
"""Show a message if there was an error while spawning."""
if error == QProcess.Crashed and not utils.is_windows:
# Already handled via ExitStatus in _on_finished
return
msg = self._proc.errorString()
message.error("Error while spawning {}: {}".format(self._what, msg))
@pyqtSlot(int, QProcess.ExitStatus)
def _on_finished(self, code, status):
"""Show a message when the process finished."""
self._started = False
log.procs.debug("Process finished with code {}, status {}.".format(
code, status))
encoding = locale.getpreferredencoding(do_setlocale=False)
stderr = self._proc.readAllStandardError().data().decode(
encoding, 'replace')
stdout = self._proc.readAllStandardOutput().data().decode(
encoding, 'replace')
if self._output_messages:
if stdout:
message.info(stdout.strip())
if stderr:
message.error(stderr.strip())
if status == QProcess.CrashExit:
exitinfo = "{} crashed.".format(self._what.capitalize())
message.error(exitinfo)
elif status == QProcess.NormalExit and code == 0:
exitinfo = "{} exited successfully.".format(
self._what.capitalize())
if self.verbose:
message.info(exitinfo)
else:
assert status == QProcess.NormalExit
# We call this 'status' here as it makes more sense to the user -
# it's actually 'code'.
exitinfo = ("{} exited with status {}, see :messages for "
"details.").format(self._what.capitalize(), code)
message.error(exitinfo)
if stdout:
log.procs.error("Process stdout:\n" + stdout.strip())
if stderr:
log.procs.error("Process stderr:\n" + stderr.strip())
qutescheme.spawn_output = self._spawn_format(exitinfo, stdout, stderr)
def _spawn_format(self, exitinfo, stdout, stderr):
"""Produce a formatted string for spawn output."""
stdout = (stdout or "(No output)").strip()
stderr = (stderr or "(No output)").strip()
spawn_string = ("{}\n"
"\nProcess stdout:\n {}"
"\nProcess stderr:\n {}").format(exitinfo,
stdout, stderr)
return spawn_string
@pyqtSlot()
def _on_started(self):
"""Called when the process started successfully."""
log.procs.debug("Process started.")
assert not self._started
self._started = True
def _pre_start(self, cmd, args):
"""Prepare starting of a QProcess."""
if self._started:
raise ValueError("Trying to start a running QProcess!")
self.cmd = cmd
self.args = args
fake_cmdline = ' '.join(shlex.quote(e) for e in [cmd] + list(args))
log.procs.debug("Executing: {}".format(fake_cmdline))
if self.verbose:
message.info('Executing: ' + fake_cmdline)
def start(self, cmd, args):
"""Convenience wrapper around QProcess::start."""
log.procs.debug("Starting process.")
self._pre_start(cmd, args)
self._proc.start(cmd, args)
self._proc.closeWriteChannel()
def start_detached(self, cmd, args):
"""Convenience wrapper around QProcess::startDetached."""
log.procs.debug("Starting detached.")
self._pre_start(cmd, args)
ok, _pid = self._proc.startDetached(
cmd, args, None) # type: ignore[call-arg]
if not ok:
message.error("Error while spawning {}".format(self._what))
return False
log.procs.debug("Process started.")
self._started = True
return True
def exit_status(self):
return self._proc.exitStatus()
| forkbong/qutebrowser | qutebrowser/misc/guiprocess.py | Python | gpl-3.0 | 6,787 |