prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>wc.js<|end_file_name|><|fim▁begin|>Parse.initialize("AQxY526I5fcCPVkniY6ONnaBqU5qh1qDMqcOCORz", "y0cZ5QAGDU1SN1o1DtsQA8mHAKL3TKetrRvGwv3Y"); calculateSteps(); <|fim▁hole|> var count = 0; var Trips = Parse.Object.extend("Trip"); var query = new Parse.Query(Trips); query.greaterThan("StepsCompleted", 0); query.find({ success: function(results) { for (var i = 0; i < results.length; i++) { var object = results[i]; var stepsTaken = object.get("StepsCompleted"); count += stepsTaken; document.getElementById('stepsContainer').innerHTML = count.toLocaleString(); var dollarsSaved = (count / 2000) * 2.5; document.getElementById('moneyContainer').innerHTML = dollarsSaved.toFixed(2); var co2Emissions = count * 0.0128; document.getElementById('co2EmissionsContainer').innerHTML = co2Emissions.toFixed(2); } }, error: function(error) { console.log("Error: " + error.code + " " + error.message); } }); //var timer = setInterval(refresh, 3000); } var myVar = setInterval(function(){ refresh() }, 1000); function refresh(){ calculateSteps(); }<|fim▁end|>
function calculateSteps(){
<|file_name|>workspace.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import import logging import os import shlex import shutil import sys import traceback from flask import current_app from subprocess import PIPE, Popen, STDOUT from uuid import uuid1 from freight.exceptions import CommandError class Workspace(object): log = logging.getLogger('workspace') def __init__(self, path, log=None): self.path = path if log is not None: self.log = log def whereis(self, program, env): for path in env.get('PATH', '').split(':'): if os.path.exists(os.path.join(path, program)) and \ not os.path.isdir(os.path.join(path, program)): return os.path.join(path, program) return None def _get_writer(self, pipe):<|fim▁hole|> def _run_process(self, command, *args, **kwargs): stdout = kwargs.get('stdout', sys.stdout) stderr = kwargs.get('stderr', sys.stderr) kwargs.setdefault('cwd', self.path) if isinstance(command, basestring): command = shlex.split(command) command = map(str, command) env = os.environ.copy() env['PYTHONUNBUFFERED'] = '1' if kwargs.get('env'): for key, value in kwargs['env'].iteritems(): env[key] = value kwargs['env'] = env kwargs['bufsize'] = 0 self.log.info('Running {}'.format(command)) try: proc = Popen(command, *args, **kwargs) except OSError as exc: if not self.whereis(command[0], env): msg = 'ERROR: Command not found: {}'.format(command[0]) else: msg = traceback.format_exc() raise CommandError(command, 1, stdout=None, stderr=msg) return proc def capture(self, command, *args, **kwargs): kwargs['stdout'] = PIPE kwargs['stderr'] = STDOUT proc = self._run_process(command, *args, **kwargs) (stdout, stderr) = proc.communicate() if proc.returncode != 0: raise CommandError(command, proc.returncode, stdout, stderr) return stdout def run(self, command, *args, **kwargs): proc = self._run_process(command, *args, **kwargs) proc.wait() if proc.returncode != 0: raise CommandError(command, proc.returncode) def remove(self): if os.path.exists(self.path): shutil.rmtree(self.path) class TemporaryWorkspace(Workspace): def __init__(self, *args, **kwargs): path = os.path.join( current_app.config['WORKSPACE_ROOT'], 'freight-workspace-{}'.format(uuid1().hex), ) super(TemporaryWorkspace, self).__init__(path, *args, **kwargs)<|fim▁end|>
if not isinstance(pipe, int): pipe = pipe.fileno() return os.fdopen(pipe, 'w')
<|file_name|>031_version_2_2_3.py<|end_file_name|><|fim▁begin|>import logging from sqlalchemy import * from kallithea.lib.dbmigrate.migrate import * from kallithea.lib.dbmigrate.migrate.changeset import * from kallithea.model import meta from kallithea.lib.dbmigrate.versions import _reset_base, notify log = logging.getLogger(__name__) def upgrade(migrate_engine): """ Upgrade operations go here. Don't create your own engine; bind migrate_engine to your metadata """ _reset_base(migrate_engine) from kallithea.lib.dbmigrate.schema import db_2_2_3 # issue fixups fixups(db_2_2_3, meta.Session) def downgrade(migrate_engine): meta = MetaData()<|fim▁hole|> meta.bind = migrate_engine def fixups(models, _SESSION): notify('Creating repository states') for repo in models.Repository.get_all(): _state = models.Repository.STATE_CREATED print 'setting repo %s state to "%s"' % (repo, _state) repo.repo_state = _state _SESSION().add(repo) _SESSION().commit()<|fim▁end|>
<|file_name|>XMLexport.cpp<|end_file_name|><|fim▁begin|>/*************************************************************************** * Copyright (C) 2008-2013 by Heiko Koehn - [email protected] * * Copyright (C) 2014 by Ahmed Charles - [email protected] * * Copyright (C) 2016 by Ian Adkins - [email protected] * * Copyright (C) 2017 by Stephen Lyons - [email protected] * * *<|fim▁hole|> * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "XMLexport.h" #include "Host.h" #include "LuaInterface.h" #include "TAction.h" #include "TAlias.h" #include "TKey.h" #include "TScript.h" #include "TTimer.h" #include "TTrigger.h" #include "TVar.h" #include "VarUnit.h" #include "mudlet.h" using namespace std; XMLexport::XMLexport( Host * pH ) : mpHost( pH ) , mpTrigger( Q_NULLPTR ) , mpTimer( Q_NULLPTR ) , mpAlias( Q_NULLPTR ) , mpAction( Q_NULLPTR ) , mpScript( Q_NULLPTR ) , mpKey( Q_NULLPTR ) { setAutoFormatting(true); } XMLexport::XMLexport( TTrigger * pT ) : mpHost( Q_NULLPTR ) , mpTrigger( pT ) , mpTimer( Q_NULLPTR ) , mpAlias( Q_NULLPTR ) , mpAction( Q_NULLPTR ) , mpScript( Q_NULLPTR ) , mpKey( Q_NULLPTR ) { setAutoFormatting(true); } XMLexport::XMLexport( TTimer * pT ) : mpHost( Q_NULLPTR ) , mpTrigger( Q_NULLPTR ) , mpTimer( pT ) , mpAlias( Q_NULLPTR ) , mpAction( Q_NULLPTR ) , mpScript( Q_NULLPTR ) , mpKey( Q_NULLPTR ) { setAutoFormatting(true); } XMLexport::XMLexport( TAlias * pT ) : mpHost( Q_NULLPTR ) , mpTrigger( Q_NULLPTR ) , mpTimer( Q_NULLPTR ) , mpAlias( pT ) , mpAction( Q_NULLPTR ) , mpScript( Q_NULLPTR ) , mpKey( Q_NULLPTR ) { setAutoFormatting(true); } XMLexport::XMLexport( TAction * pT ) : mpHost( Q_NULLPTR ) , mpTrigger( Q_NULLPTR ) , mpTimer( Q_NULLPTR ) , mpAlias( Q_NULLPTR ) , mpAction( pT ) , mpScript( Q_NULLPTR ) , mpKey( Q_NULLPTR ) { setAutoFormatting(true); } XMLexport::XMLexport( TScript * pT ) : mpHost( Q_NULLPTR ) , mpTrigger( Q_NULLPTR ) , mpTimer( Q_NULLPTR ) , mpAlias( Q_NULLPTR ) , mpAction( Q_NULLPTR ) , mpScript( pT ) , mpKey( Q_NULLPTR ) { setAutoFormatting(true); } XMLexport::XMLexport( TKey * pT ) : mpHost( Q_NULLPTR ) , mpTrigger( Q_NULLPTR ) , mpTimer( Q_NULLPTR ) , mpAlias( Q_NULLPTR ) , mpAction( Q_NULLPTR ) , mpScript( Q_NULLPTR ) , mpKey( pT ) { setAutoFormatting(true); } bool XMLexport::writeModuleXML(QIODevice* device, QString moduleName) { Host* pHost = mpHost; bool isOk = true; bool isNodeWritten = false; setDevice(device); writeStartDocument(); // Assume that if there is a file writing problem it will show up on first // write to file... if (hasError() || !pHost) { return false; } writeDTD("<!DOCTYPE MudletPackage>"); writeStartElement("MudletPackage"); writeAttribute(QStringLiteral("version"), mudlet::self()->scmMudletXmlDefaultVersion); if (isOk) { writeStartElement("TriggerPackage"); //we go a level down for all these functions so as to not infinitely nest the module for (auto it = pHost->mTriggerUnit.mTriggerRootNodeList.begin(); isOk && it != pHost->mTriggerUnit.mTriggerRootNodeList.end(); ++it) { if (!(*it) || (*it)->mPackageName != moduleName) { continue; } if (!(*it)->isTempTrigger() && (*it)->mModuleMember) { if (!writeTrigger(*it)) { isOk = false; } else { isNodeWritten = true; } } } if (isNodeWritten) { isNodeWritten = false; } else { writeEndElement(); // </TriggerPackage> } } if (isOk) { writeStartElement("TimerPackage"); for (auto it = pHost->mTimerUnit.mTimerRootNodeList.begin(); isOk && it != pHost->mTimerUnit.mTimerRootNodeList.end(); ++it) { if (!(*it) || (*it)->mPackageName != moduleName) { continue; } if (!(*it)->isTempTimer() && (*it)->mModuleMember) { if (!writeTimer(*it)) { isOk = false; } else { isNodeWritten = true; } } } if (isNodeWritten) { isNodeWritten = false; } else { writeEndElement(); // </TimerPackage> } } if (isOk) { writeStartElement("AliasPackage"); for (auto it = pHost->mAliasUnit.mAliasRootNodeList.begin(); isOk && it != pHost->mAliasUnit.mAliasRootNodeList.end(); ++it) { if (!(*it) || (*it)->mPackageName != moduleName) { continue; } if (!(*it)->isTempAlias() && (*it)->mModuleMember) { if (!writeAlias(*it)) { isOk = false; } else { isNodeWritten = true; } } } if (isNodeWritten) { isNodeWritten = false; } else { writeEndElement(); // </AliasPackage> } } if (isOk) { writeStartElement("ActionPackage"); for (auto it = pHost->mActionUnit.mActionRootNodeList.begin(); isOk && it != pHost->mActionUnit.mActionRootNodeList.end(); ++it) { if (!(*it) || (*it)->mPackageName != moduleName) { continue; } if ((*it)->mModuleMember) { if (!writeAction(*it)) { isOk = false; } else { isNodeWritten = true; } } } if (isNodeWritten) { isNodeWritten = false; } else { writeEndElement(); // </ActionPackage> } } if (isOk) { writeStartElement("ScriptPackage"); for (auto it = pHost->mScriptUnit.mScriptRootNodeList.begin(); isOk && it != pHost->mScriptUnit.mScriptRootNodeList.end(); ++it) { if (!(*it) || (*it)->mPackageName != moduleName) { continue; } if ((*it)->mModuleMember) { if (!writeScript(*it)) { isOk = false; } else { isNodeWritten = true; } } } if (isNodeWritten) { isNodeWritten = false; } else { writeEndElement(); // </ScriptPackage> } } if (isOk) { writeStartElement("KeyPackage"); for (auto it = pHost->mKeyUnit.mKeyRootNodeList.begin(); isOk && it != pHost->mKeyUnit.mKeyRootNodeList.end(); ++it) { if (!(*it) || (*it)->mPackageName != moduleName) { continue; } if (!(*it)->isTempKey() && (*it)->mModuleMember) { if (!writeKey(*it)) { isOk = false; } else { isNodeWritten = true; } } } if (isNodeWritten) { isNodeWritten = false; } else { writeEndElement(); // </KeyPackage> } } if (isOk) { writeStartElement("HelpPackage"); if (pHost->moduleHelp.contains(moduleName) && pHost->moduleHelp.value(moduleName).contains("helpURL")) { writeTextElement("helpURL", pHost->moduleHelp.value(moduleName).value("helpURL")); } else { writeEmptyElement("helpURL"); } writeEndElement(); // </HelpPackage> } // writeEndElement();//end hostpackage - NOT NEEDED HERE! writeEndElement(); // </MudletPackage> writeEndDocument(); return (isOk && (!hasError())); } bool XMLexport::exportHost(QIODevice* device) { bool isOk = true; setDevice(device); writeStartDocument(); if (hasError()) { return false; } writeDTD("<!DOCTYPE MudletPackage>"); writeStartElement("MudletPackage"); writeAttribute(QStringLiteral("version"), mudlet::self()->scmMudletXmlDefaultVersion); writeStartElement("HostPackage"); if (!writeHost(mpHost)) { isOk = false; } writeEndElement(); // </HostPackage> writeEndElement(); // </MudletPackage> writeEndDocument(); return (isOk && (!hasError())); } bool XMLexport::writeHost(Host* pHost) { bool isOk = true; writeStartElement("Host"); writeAttribute("autoClearCommandLineAfterSend", pHost->mAutoClearCommandLineAfterSend ? "yes" : "no"); writeAttribute("disableAutoCompletion", pHost->mDisableAutoCompletion ? "yes" : "no"); writeAttribute("printCommand", pHost->mPrintCommand ? "yes" : "no"); writeAttribute("USE_IRE_DRIVER_BUGFIX", pHost->mUSE_IRE_DRIVER_BUGFIX ? "yes" : "no"); writeAttribute("mUSE_FORCE_LF_AFTER_PROMPT", pHost->mUSE_FORCE_LF_AFTER_PROMPT ? "yes" : "no"); writeAttribute("mUSE_UNIX_EOL", pHost->mUSE_UNIX_EOL ? "yes" : "no"); writeAttribute("mNoAntiAlias", pHost->mNoAntiAlias ? "yes" : "no"); writeAttribute("mEchoLuaErrors", pHost->mEchoLuaErrors ? "yes" : "no"); // FIXME: Change to a string or integer property when possible to support more // than false (perhaps 0 or "PlainText") or true (perhaps 1 or "HTML") in the // future - phpBB code might be useful if it can be done. writeAttribute("mRawStreamDump", pHost->mIsNextLogFileInHtmlFormat ? "yes" : "no"); writeAttribute("mIsLoggingTimestamps", pHost->mIsLoggingTimestamps ? "yes" : "no"); writeAttribute("mAlertOnNewData", pHost->mAlertOnNewData ? "yes" : "no"); writeAttribute("mFORCE_NO_COMPRESSION", pHost->mFORCE_NO_COMPRESSION ? "yes" : "no"); writeAttribute("mFORCE_GA_OFF", pHost->mFORCE_GA_OFF ? "yes" : "no"); writeAttribute("mFORCE_SAVE_ON_EXIT", pHost->mFORCE_SAVE_ON_EXIT ? "yes" : "no"); writeAttribute("mEnableGMCP", pHost->mEnableGMCP ? "yes" : "no"); writeAttribute("mEnableMSDP", pHost->mEnableMSDP ? "yes" : "no"); writeAttribute("mMapStrongHighlight", pHost->mMapStrongHighlight ? "yes" : "no"); writeAttribute("mLogStatus", pHost->mLogStatus ? "yes" : "no"); writeAttribute("mEnableSpellCheck", pHost->mEnableSpellCheck ? "yes" : "no"); writeAttribute("mShowInfo", pHost->mShowInfo ? "yes" : "no"); writeAttribute("mAcceptServerGUI", pHost->mAcceptServerGUI ? "yes" : "no"); writeAttribute("mMapperUseAntiAlias", pHost->mMapperUseAntiAlias ? "yes" : "no"); writeAttribute("mFORCE_MXP_NEGOTIATION_OFF", pHost->mFORCE_MXP_NEGOTIATION_OFF ? "yes" : "no"); writeAttribute("mRoomSize", QString::number(pHost->mRoomSize, 'f', 1)); writeAttribute("mLineSize", QString::number(pHost->mLineSize, 'f', 1)); writeAttribute("mBubbleMode", pHost->mBubbleMode ? "yes" : "no"); writeAttribute("mShowRoomIDs", pHost->mShowRoomID ? "yes" : "no"); writeAttribute("mShowPanel", pHost->mShowPanel ? "yes" : "no"); writeAttribute("mHaveMapperScript", pHost->mHaveMapperScript ? "yes" : "no"); QString ignore; QSetIterator<QChar> it(pHost->mDoubleClickIgnore); while (it.hasNext()) { ignore = ignore.append(it.next()); } writeAttribute("mDoubleClickIgnore", ignore); { // Blocked so that indentation reflects that of the XML file writeTextElement("name", pHost->mHostName); writeStartElement("mInstalledPackages"); for (int i = 0; i < pHost->mInstalledPackages.size(); ++i) { writeTextElement("string", pHost->mInstalledPackages.at(i)); } writeEndElement(); // </mInstalledPackages> if (pHost->mInstalledModules.size()) { writeStartElement("mInstalledModules"); QMapIterator<QString, QStringList> it(pHost->mInstalledModules); pHost->modulesToWrite.clear(); while (it.hasNext()) { it.next(); writeTextElement("key", it.key()); QStringList entry = it.value(); writeTextElement("filepath", entry.at(0)); writeTextElement("globalSave", entry.at(1)); if (entry.at(1).toInt()) { pHost->modulesToWrite.insert(it.key(), entry); } writeTextElement("priority", QString::number(pHost->mModulePriorities.value(it.key()))); } writeEndElement(); // </mInstalledModules> } // CHECK: Do we need: // else { // writeEmptyElement( "mInstalledModules" ); // i.e. <mInstalledModules /> // } writeTextElement("url", pHost->mUrl); writeTextElement("serverPackageName", pHost->mServerGUI_Package_name); writeTextElement("serverPackageVersion", QString::number(pHost->mServerGUI_Package_version)); writeTextElement("port", QString::number(pHost->mPort)); writeTextElement("borderTopHeight", QString::number(pHost->mBorderTopHeight)); writeTextElement("borderBottomHeight", QString::number(pHost->mBorderBottomHeight)); writeTextElement("borderLeftWidth", QString::number(pHost->mBorderLeftWidth)); writeTextElement("borderRightWidth", QString::number(pHost->mBorderRightWidth)); writeTextElement("wrapAt", QString::number(pHost->mWrapAt)); writeTextElement("wrapIndentCount", QString::number(pHost->mWrapIndentCount)); writeTextElement("mFgColor", pHost->mFgColor.name()); writeTextElement("mBgColor", pHost->mBgColor.name()); writeTextElement("mCommandFgColor", pHost->mCommandFgColor.name()); writeTextElement("mCommandBgColor", pHost->mCommandBgColor.name()); writeTextElement("mCommandLineFgColor", pHost->mCommandLineFgColor.name()); writeTextElement("mCommandLineBgColor", pHost->mCommandLineBgColor.name()); writeTextElement("mBlack", pHost->mBlack.name()); writeTextElement("mLightBlack", pHost->mLightBlack.name()); writeTextElement("mRed", pHost->mRed.name()); writeTextElement("mLightRed", pHost->mLightRed.name()); writeTextElement("mBlue", pHost->mBlue.name()); writeTextElement("mLightBlue", pHost->mLightBlue.name()); writeTextElement("mGreen", pHost->mGreen.name()); writeTextElement("mLightGreen", pHost->mLightGreen.name()); writeTextElement("mYellow", pHost->mYellow.name()); writeTextElement("mLightYellow", pHost->mLightYellow.name()); writeTextElement("mCyan", pHost->mCyan.name()); writeTextElement("mLightCyan", pHost->mLightCyan.name()); writeTextElement("mMagenta", pHost->mMagenta.name()); writeTextElement("mLightMagenta", pHost->mLightMagenta.name()); writeTextElement("mWhite", pHost->mWhite.name()); writeTextElement("mLightWhite", pHost->mLightWhite.name()); writeTextElement("mDisplayFont", pHost->mDisplayFont.toString()); writeTextElement("mCommandLineFont", pHost->mCommandLineFont.toString()); // There was a mis-spelt duplicate commandSeperator above but it is now gone writeTextElement("mCommandSeparator", pHost->mCommandSeparator); writeTextElement("commandLineMinimumHeight", QString::number(pHost->commandLineMinimumHeight)); writeTextElement("mFgColor2", pHost->mFgColor_2.name()); writeTextElement("mBgColor2", pHost->mBgColor_2.name()); writeTextElement("mBlack2", pHost->mBlack_2.name()); writeTextElement("mLightBlack2", pHost->mLightBlack_2.name()); writeTextElement("mRed2", pHost->mRed_2.name()); writeTextElement("mLightRed2", pHost->mLightRed_2.name()); writeTextElement("mBlue2", pHost->mBlue_2.name()); writeTextElement("mLightBlue2", pHost->mLightBlue_2.name()); writeTextElement("mGreen2", pHost->mGreen_2.name()); writeTextElement("mLightGreen2", pHost->mLightGreen_2.name()); writeTextElement("mYellow2", pHost->mYellow_2.name()); writeTextElement("mLightYellow2", pHost->mLightYellow_2.name()); writeTextElement("mCyan2", pHost->mCyan_2.name()); writeTextElement("mLightCyan2", pHost->mLightCyan_2.name()); writeTextElement("mMagenta2", pHost->mMagenta_2.name()); writeTextElement("mLightMagenta2", pHost->mLightMagenta_2.name()); writeTextElement("mWhite2", pHost->mWhite_2.name()); writeTextElement("mLightWhite2", pHost->mLightWhite_2.name()); writeTextElement("mSpellDic", pHost->mSpellDic); // TODO: Consider removing these sub-elements that duplicate the same // attributes - which WERE bugged - when we update the XML format, must leave // them in place for now even though we no longer use them for compatibility // with older version of Mudlet writeTextElement("mLineSize", QString::number(pHost->mLineSize, 'f', 1)); writeTextElement("mRoomSize", QString::number(pHost->mRoomSize, 'f', 1)); writeEndElement(); // </Host> } writeEndElement(); // </HostPackage> if (hasError()) { isOk = false; } // Use if() to block each XXXXPackage element to limit scope of iterator so // we can use more of the same code in each block - and to escape quicker on // error... if (isOk) { writeStartElement("TriggerPackage"); for (auto it = pHost->mTriggerUnit.mTriggerRootNodeList.begin(); isOk && it != pHost->mTriggerUnit.mTriggerRootNodeList.end(); ++it) { if (!(*it) || (*it)->mModuleMember) { continue; } if (!(*it)->isTempTrigger()) { if (!writeTrigger(*it)) { isOk = false; } } } writeEndElement(); // </TriggerPackage> } if (isOk) { writeStartElement("TimerPackage"); for (auto it = pHost->mTimerUnit.mTimerRootNodeList.begin(); isOk && it != pHost->mTimerUnit.mTimerRootNodeList.end(); ++it) { if (!(*it) || (*it)->mModuleMember) { continue; } if (!(*it)->isTempTimer()) { if (!writeTimer(*it)) { isOk = false; } } } writeEndElement(); // </TimerPackage> } if (isOk) { writeStartElement("AliasPackage"); for (auto it = pHost->mAliasUnit.mAliasRootNodeList.begin(); isOk && it != pHost->mAliasUnit.mAliasRootNodeList.end(); ++it) { if (!(*it) || (*it)->mModuleMember) { continue; } if (!(*it)->isTempAlias()) { if (!writeAlias(*it)) { isOk = false; } } } writeEndElement(); // </AliasPackage> } if (isOk) { writeStartElement("ActionPackage"); for (auto it = pHost->mActionUnit.mActionRootNodeList.begin(); isOk && it != pHost->mActionUnit.mActionRootNodeList.end(); ++it) { if (!(*it) || (*it)->mModuleMember) { continue; } if (!writeAction(*it)) { isOk = false; } } writeEndElement(); // </ActionPackage> } if (isOk) { writeStartElement("ScriptPackage"); for (auto it = pHost->mScriptUnit.mScriptRootNodeList.begin(); isOk && it != pHost->mScriptUnit.mScriptRootNodeList.end(); ++it) { if (!(*it) || (*it)->mModuleMember) { continue; } if (!writeScript(*it)) { isOk = false; } } writeEndElement(); // </ScriptPackage> } if (isOk) { writeStartElement("KeyPackage"); for( auto it = pHost->mKeyUnit.mKeyRootNodeList.begin(); isOk && it != pHost->mKeyUnit.mKeyRootNodeList.end(); ++it ) { if( ! (*it) || (*it)->isTempKey() || (*it)->mModuleMember) { continue; } if (!writeKey(*it)) { isOk = false; } } writeEndElement(); // </KeyPackage> } if (isOk) { writeStartElement("VariablePackage"); LuaInterface* lI = pHost->getLuaInterface(); VarUnit* vu = lI->getVarUnit(); //do hidden variables first { // Blocked so that indentation reflects that of the XML file writeStartElement("HiddenVariables"); QSetIterator<QString> itHiddenVariableName(vu->hiddenByUser); while (itHiddenVariableName.hasNext()) { writeTextElement("name", itHiddenVariableName.next()); } writeEndElement(); // </HiddenVariables> } TVar* base = vu->getBase(); if (!base) { lI->getVars(false); base = vu->getBase(); } if (base) { QListIterator<TVar*> itVariable(base->getChildren(false)); while (isOk && itVariable.hasNext()) { if (!writeVariable(itVariable.next(), lI, vu)) { isOk = false; } } } writeEndElement(); // </VariablePackage> } return (isOk && (!hasError())); } bool XMLexport::writeVariable(TVar* pVar, LuaInterface* pLuaInterface, VarUnit* pVariableUnit) { bool isOk = true; if (pVariableUnit->isSaved(pVar)) { if (pVar->getValueType() == LUA_TTABLE) { writeStartElement("VariableGroup"); writeTextElement("name", pVar->getName()); writeTextElement("keyType", QString::number(pVar->getKeyType())); writeTextElement("value", pLuaInterface->getValue(pVar)); writeTextElement("valueType", QString::number(pVar->getValueType())); QListIterator<TVar*> itNestedVariable(pVar->getChildren(false)); while (isOk && itNestedVariable.hasNext()) { if (!writeVariable(itNestedVariable.next(), pLuaInterface, pVariableUnit)) { isOk = false; } } writeEndElement(); // </VariableGroup> } else { writeStartElement("Variable"); writeTextElement("name", pVar->getName()); writeTextElement("keyType", QString::number(pVar->getKeyType())); writeTextElement("value", pLuaInterface->getValue(pVar)); writeTextElement("valueType", QString::number(pVar->getValueType())); writeEndElement(); // </Variable> } } return (isOk && (!hasError())); } bool XMLexport::exportGenericPackage(QIODevice* device) { setDevice(device); writeStartDocument(); if (hasError()) { return false; } writeDTD("<!DOCTYPE MudletPackage>"); writeStartElement("MudletPackage"); writeAttribute(QStringLiteral("version"), mudlet::self()->scmMudletXmlDefaultVersion); bool isOk = writeGenericPackage(mpHost); writeEndElement(); // </MudletPackage> writeEndDocument(); return (isOk && (!hasError())); } bool XMLexport::writeGenericPackage(Host* pHost) { bool isOk = true; if (isOk) { writeStartElement("TriggerPackage"); for (auto it = pHost->mTriggerUnit.mTriggerRootNodeList.begin(); isOk && it != pHost->mTriggerUnit.mTriggerRootNodeList.end(); ++it) { if (!(*it) || (*it)->isTempTrigger()) { continue; } if (!writeTrigger(*it)) { isOk = false; } } writeEndElement(); // </TriggerPackage> } if (isOk) { writeStartElement("TimerPackage"); for (auto it = pHost->mTimerUnit.mTimerRootNodeList.begin(); isOk && it != pHost->mTimerUnit.mTimerRootNodeList.end(); ++it) { if (!(*it) || (*it)->isTempTimer()) { continue; } if (!writeTimer(*it)) { isOk = false; } } writeEndElement(); // </TimerPackage> } if (isOk) { writeStartElement("AliasPackage"); for (auto it = pHost->mAliasUnit.mAliasRootNodeList.begin(); isOk && it != pHost->mAliasUnit.mAliasRootNodeList.end(); ++it) { if (!(*it) || (*it)->isTempAlias()) { continue; } if (!writeAlias(*it)) { isOk = false; } } writeEndElement(); // </AliasPackage> } if (isOk) { writeStartElement("ActionPackage"); for (auto it = pHost->mActionUnit.mActionRootNodeList.begin(); isOk && it != pHost->mActionUnit.mActionRootNodeList.end(); ++it) { if (!(*it)) { continue; } if (!writeAction(*it)) { isOk = false; } } writeEndElement(); // </ActionPackage> } if (isOk) { writeStartElement("ScriptPackage"); for (auto it = pHost->mScriptUnit.mScriptRootNodeList.begin(); isOk && it != pHost->mScriptUnit.mScriptRootNodeList.end(); ++it) { if (!(*it)) { continue; } if (!writeScript(*it)) { isOk = false; } } writeEndElement(); // </ScriptPackage> } if( isOk ) { writeStartElement( "KeyPackage" ); for( auto it = pHost->mKeyUnit.mKeyRootNodeList.begin(); isOk && it != pHost->mKeyUnit.mKeyRootNodeList.end(); ++it ) { if( ! (*it) || (*it)->isTempKey() ) { continue; } if (!writeKey(*it)) { isOk = false; } } writeEndElement(); // </KeyPackage> } return (isOk && (!hasError())); } bool XMLexport::exportTrigger(QIODevice* device) { setDevice(device); writeStartDocument(); if (hasError()) { return false; } writeDTD("<!DOCTYPE MudletPackage>"); writeStartElement("MudletPackage"); writeAttribute(QStringLiteral("version"), mudlet::self()->scmMudletXmlDefaultVersion); writeStartElement("TriggerPackage"); bool isOk = writeTrigger(mpTrigger); writeEndElement(); // </TriggerPackage> writeEndElement(); // </MudletPackage> writeEndDocument(); return (isOk && (!hasError())); } bool XMLexport::writeTrigger(TTrigger* pT) { bool isOk = true; if (!pT->mModuleMasterFolder && pT->exportItem) { writeStartElement(pT->mIsFolder ? "TriggerGroup" : "Trigger"); writeAttribute("isActive", pT->shouldBeActive() ? "yes" : "no"); writeAttribute("isFolder", pT->mIsFolder ? "yes" : "no"); writeAttribute("isTempTrigger", pT->mIsTempTrigger ? "yes" : "no"); writeAttribute("isMultiline", pT->mIsMultiline ? "yes" : "no"); writeAttribute("isPerlSlashGOption", pT->mPerlSlashGOption ? "yes" : "no"); writeAttribute("isColorizerTrigger", pT->mIsColorizerTrigger ? "yes" : "no"); writeAttribute("isFilterTrigger", pT->mFilterTrigger ? "yes" : "no"); writeAttribute("isSoundTrigger", pT->mSoundTrigger ? "yes" : "no"); writeAttribute("isColorTrigger", pT->mColorTrigger ? "yes" : "no"); writeAttribute("isColorTriggerFg", pT->mColorTriggerFg ? "yes" : "no"); writeAttribute("isColorTriggerBg", pT->mColorTriggerBg ? "yes" : "no"); { // Blocked so that indentation reflects that of the XML file writeTextElement("name", pT->mName); writeScriptElement(pT->mScript); writeTextElement("triggerType", QString::number(pT->mTriggerType)); writeTextElement("conditonLineDelta", QString::number(pT->mConditionLineDelta)); writeTextElement("mStayOpen", QString::number(pT->mStayOpen)); writeTextElement("mCommand", pT->mCommand); writeTextElement("packageName", pT->mPackageName); writeTextElement("mFgColor", pT->mFgColor.name()); writeTextElement("mBgColor", pT->mBgColor.name()); writeTextElement("mSoundFile", pT->mSoundFile); writeTextElement("colorTriggerFgColor", pT->mColorTriggerFgColor.name()); writeTextElement("colorTriggerBgColor", pT->mColorTriggerBgColor.name()); // TODO: The next bit could be revised for a new - not BACKWARD COMPATIBLE form: // int elementCount = qMin( pTt->mRegexCodeList.size(), pT->mRegexCodePropertyList.size() ): // writeStartElement( "RegexList" ); // writeAttribute( "size", QString::number( elementCount ) ); // for( int i = 0; i < elementCount; ++i ) { // writeEmptyElement( "RegexCode" ); // writeAttribute( "name", pT->mRegexCodeList.at(i) ); // writeAttribute( "type", pT->mRegexCodePropertyList.at(i) ); // } // writeEndElement(); // </RegexList> writeStartElement("regexCodeList"); for (int i = 0; i < pT->mRegexCodeList.size(); ++i) { writeTextElement("string", pT->mRegexCodeList.at(i)); } writeEndElement(); // </regexCodeList> writeStartElement("regexCodePropertyList"); for (int i : pT->mRegexCodePropertyList) { writeTextElement("integer", QString::number(i)); } writeEndElement(); // </regexCodePropertyList> } isOk = !hasError(); } for (auto it = pT->mpMyChildrenList->begin(); isOk && it != pT->mpMyChildrenList->end(); ++it) { if (!writeTrigger(*it)) { isOk = false; } } if (pT->exportItem) { // CHECK: doesn't it also need a "&& (! pT->mModuleMasterFolder)" writeEndElement(); // </TriggerGroup> or </Trigger> } return (isOk && (!hasError())); } bool XMLexport::exportAlias(QIODevice* device) { setDevice(device); writeStartDocument(); if (hasError()) { return false; } writeDTD("<!DOCTYPE MudletPackage>"); writeStartElement("MudletPackage"); writeAttribute(QStringLiteral("version"), mudlet::self()->scmMudletXmlDefaultVersion); writeStartElement("AliasPackage"); bool isOk = writeAlias(mpAlias); writeEndElement(); // </AliasPackage> writeEndElement(); // </MudletPackage> writeEndDocument(); return (isOk && (!hasError())); } bool XMLexport::writeAlias(TAlias* pT) { bool isOk = true; if (!pT->mModuleMasterFolder && pT->exportItem) { writeStartElement(pT->mIsFolder ? "AliasGroup" : "Alias"); writeAttribute("isActive", pT->shouldBeActive() ? "yes" : "no"); writeAttribute("isFolder", pT->mIsFolder ? "yes" : "no"); { // Blocked so that indentation reflects that of the XML file writeTextElement("name", pT->mName); writeScriptElement(pT->mScript); writeTextElement("command", pT->mCommand); writeTextElement("packageName", pT->mPackageName); writeTextElement("regex", pT->mRegexCode); } isOk = !hasError(); } for (auto it = pT->mpMyChildrenList->begin(); isOk && it != pT->mpMyChildrenList->end(); ++it) { if (!writeAlias(*it)) { isOk = false; } } if (pT->exportItem) { // CHECK: doesn't it also need a (! pT->mModuleMasterFolder) writeEndElement(); // </AliasGroup> or </Alias> } return (isOk && (!hasError())); } bool XMLexport::exportAction(QIODevice* device) { setDevice(device); writeStartDocument(); if (hasError()) { return false; } writeDTD("<!DOCTYPE MudletPackage>"); writeStartElement("MudletPackage"); writeAttribute(QStringLiteral("version"), mudlet::self()->scmMudletXmlDefaultVersion); writeStartElement("ActionPackage"); bool isOk = writeAction(mpAction); writeEndElement(); // </ActionPackage> writeEndElement(); // </MudletPackage> writeEndDocument(); return (isOk && (!hasError())); } bool XMLexport::writeAction(TAction* pT) { bool isOk = true; if (!pT->mModuleMasterFolder && pT->exportItem) { writeStartElement(pT->mIsFolder ? "ActionGroup" : "Action"); writeAttribute("isActive", pT->shouldBeActive() ? "yes" : "no"); writeAttribute("isFolder", pT->mIsFolder ? "yes" : "no"); writeAttribute("isPushButton", pT->mIsPushDownButton ? "yes" : "no"); writeAttribute("isFlatButton", pT->mButtonFlat ? "yes" : "no"); writeAttribute("useCustomLayout", pT->mUseCustomLayout ? "yes" : "no"); { // Blocked so that indentation reflects that of the XML file writeTextElement("name", pT->mName); writeTextElement("packageName", pT->mPackageName); writeScriptElement(pT->mScript); writeTextElement("css", pT->css); writeTextElement("commandButtonUp", pT->mCommandButtonUp); writeTextElement("commandButtonDown", pT->mCommandButtonDown); writeTextElement("icon", pT->mIcon); writeTextElement("orientation", QString::number(pT->mOrientation)); writeTextElement("location", QString::number(pT->mLocation)); writeTextElement("posX", QString::number(pT->mPosX)); writeTextElement("posY", QString::number(pT->mPosY)); // We now use a boolean but file must use original "1" (false) // or "2" (true) for backward compatibility writeTextElement("mButtonState", QString::number(pT->mButtonState ? 2 : 1)); writeTextElement("sizeX", QString::number(pT->mSizeX)); writeTextElement("sizeY", QString::number(pT->mSizeY)); writeTextElement("buttonColumn", QString::number(pT->mButtonColumns)); writeTextElement("buttonRotation", QString::number(pT->mButtonRotation)); writeTextElement("buttonColor", pT->mButtonColor.name()); } isOk = !hasError(); } for (auto it = pT->mpMyChildrenList->begin(); isOk && it != pT->mpMyChildrenList->end(); ++it) { if (!writeAction(*it)) { isOk = false; } } if (pT->exportItem) { // CHECK: doesn't it also need a "&& (! pT->mModuleMasterFolder)" writeEndElement(); // </ActionGroup> or </Action> } return (isOk && (!hasError())); } bool XMLexport::exportTimer(QIODevice* device) { setDevice(device); writeStartDocument(); if (hasError()) { return false; } writeDTD("<!DOCTYPE MudletPackage>"); writeStartElement("MudletPackage"); writeAttribute(QStringLiteral("version"), mudlet::self()->scmMudletXmlDefaultVersion); writeStartElement("TimerPackage"); bool isOk = writeTimer(mpTimer); writeEndElement(); // </TimerPackage> writeEndElement(); // </MudletPackage> writeEndDocument(); return (isOk && (!hasError())); } bool XMLexport::writeTimer(TTimer* pT) { bool isOk = true; if (!pT->mModuleMasterFolder && pT->exportItem) { writeStartElement(pT->mIsFolder ? "TimerGroup" : "Timer"); writeAttribute("isActive", pT->shouldBeActive() ? "yes" : "no"); writeAttribute("isFolder", pT->mIsFolder ? "yes" : "no"); writeAttribute("isTempTimer", pT->mIsTempTimer ? "yes" : "no"); writeAttribute("isOffsetTimer", pT->isOffsetTimer() ? "yes" : "no"); { // Blocked so that indentation reflects that of the XML file writeTextElement("name", pT->mName); writeScriptElement(pT->mScript); writeTextElement("command", pT->mCommand); writeTextElement("packageName", pT->mPackageName); writeTextElement("time", pT->mTime.toString("hh:mm:ss.zzz")); } isOk = !hasError(); } for (auto it = pT->mpMyChildrenList->begin(); isOk && it != pT->mpMyChildrenList->end(); ++it) { if (!writeTimer(*it)) { isOk = false; } } if (pT->exportItem) { // CHECK: doesn't it also need a "&& (! pT->mModuleMasterFolder)" writeEndElement(); // </TimerGroup> or </Timer> } return (isOk && (!hasError())); } bool XMLexport::exportScript(QIODevice* device) { setDevice(device); writeStartDocument(); if (hasError()) { return false; } writeDTD("<!DOCTYPE MudletPackage>"); writeStartElement("MudletPackage"); writeAttribute(QStringLiteral("version"), mudlet::self()->scmMudletXmlDefaultVersion); writeStartElement("ScriptPackage"); bool isOk = writeScript(mpScript); writeEndElement(); // </ScriptPackage> writeEndElement(); // </MudletPackage> writeEndDocument(); return (isOk && (!hasError())); } bool XMLexport::writeScript(TScript* pT) { bool isOk = true; if (!pT->mModuleMasterFolder && pT->exportItem) { writeStartElement(pT->mIsFolder ? "ScriptGroup" : "Script"); writeAttribute("isActive", pT->shouldBeActive() ? "yes" : "no"); writeAttribute("isFolder", pT->mIsFolder ? "yes" : "no"); { // Blocked so that indentation reflects that of the XML file writeTextElement("name", pT->mName); writeTextElement("packageName", pT->mPackageName); writeScriptElement(pT->mScript); writeStartElement("eventHandlerList"); for (int i = 0; i < pT->mEventHandlerList.size(); ++i) { writeTextElement("string", pT->mEventHandlerList.at(i)); } writeEndElement(); // </eventHandlerList> } isOk = !hasError(); } for (auto it = pT->mpMyChildrenList->begin(); isOk && it != pT->mpMyChildrenList->end(); it++) { if (!writeScript(*it)) { isOk = false; } } if (pT->exportItem) { // CHECK: doesn't it also need a "&& (! pT->mModuleMasterFolder)" writeEndElement(); // </ScriptGroup> or </Script> } return (isOk && (!hasError())); } bool XMLexport::exportKey(QIODevice* device) { setDevice(device); writeStartDocument(); if (hasError()) { return false; } writeDTD("<!DOCTYPE MudletPackage>"); writeStartElement("MudletPackage"); writeAttribute(QStringLiteral("version"), mudlet::self()->scmMudletXmlDefaultVersion); writeStartElement("KeyPackage"); bool isOk = writeKey(mpKey); writeEndElement(); // </KeyPackage> writeEndElement(); // </MudletPackage> writeEndDocument(); return (isOk && (!hasError())); } bool XMLexport::writeKey(TKey* pT) { bool isOk = true; if (!pT->mModuleMasterFolder && pT->exportItem) { writeStartElement(pT->mIsFolder ? "KeyGroup" : "Key"); writeAttribute("isActive", pT->shouldBeActive() ? "yes" : "no"); writeAttribute("isFolder", pT->mIsFolder ? "yes" : "no"); { // Blocked so that indentation reflects that of the XML file writeTextElement("name", pT->mName); writeTextElement("packageName", pT->mPackageName); writeScriptElement(pT->mScript); writeTextElement("command", pT->mCommand); writeTextElement("keyCode", QString::number(pT->mKeyCode)); writeTextElement("keyModifier", QString::number(pT->mKeyModifier)); } isOk = !hasError(); } for (auto it = pT->mpMyChildrenList->begin(); isOk && it != pT->mpMyChildrenList->end(); ++it) { if (!writeKey(*it)) { isOk = false; } } if (pT->exportItem) { // CHECK: doesn't it also need a "&& (! pT->mModuleMasterFolder)" writeEndElement(); // </KeyGroup> or </Key> } return (isOk && (!hasError())); } bool XMLexport::writeScriptElement(const QString & script) { QString localScript = script; localScript.replace(QChar('\x01'), QStringLiteral("\xFFFC\x2401")); // SOH localScript.replace(QChar('\x02'), QStringLiteral("\xFFFC\x2402")); // STX localScript.replace(QChar('\x03'), QStringLiteral("\xFFFC\x2403")); // ETX localScript.replace(QChar('\x04'), QStringLiteral("\xFFFC\x2404")); // EOT localScript.replace(QChar('\x05'), QStringLiteral("\xFFFC\x2405")); // ENQ localScript.replace(QChar('\x06'), QStringLiteral("\xFFFC\x2406")); // ACK localScript.replace(QChar('\x07'), QStringLiteral("\xFFFC\x2407")); // BEL localScript.replace(QChar('\x08'), QStringLiteral("\xFFFC\x2408")); // BS localScript.replace(QChar('\x0B'), QStringLiteral("\xFFFC\x240B")); // VT localScript.replace(QChar('\x0C'), QStringLiteral("\xFFFC\x240C")); // FF localScript.replace(QChar('\x0E'), QStringLiteral("\xFFFC\x240E")); // SS localScript.replace(QChar('\x0F'), QStringLiteral("\xFFFC\x240F")); // SI localScript.replace(QChar('\x10'), QStringLiteral("\xFFFC\x2410")); // DLE localScript.replace(QChar('\x11'), QStringLiteral("\xFFFC\x2411")); // DC1 localScript.replace(QChar('\x12'), QStringLiteral("\xFFFC\x2412")); // DC2 localScript.replace(QChar('\x13'), QStringLiteral("\xFFFC\x2413")); // DC3 localScript.replace(QChar('\x14'), QStringLiteral("\xFFFC\x2414")); // DC4 localScript.replace(QChar('\x15'), QStringLiteral("\xFFFC\x2415")); // NAK localScript.replace(QChar('\x16'), QStringLiteral("\xFFFC\x2416")); // SYN localScript.replace(QChar('\x17'), QStringLiteral("\xFFFC\x2417")); // ETB localScript.replace(QChar('\x18'), QStringLiteral("\xFFFC\x2418")); // CAN localScript.replace(QChar('\x19'), QStringLiteral("\xFFFC\x2419")); // EM localScript.replace(QChar('\x1A'), QStringLiteral("\xFFFC\x241A")); // SUB localScript.replace(QChar('\x1B'), QStringLiteral("\xFFFC\x241B")); // ESC localScript.replace(QChar('\x1C'), QStringLiteral("\xFFFC\x241C")); // FS localScript.replace(QChar('\x1D'), QStringLiteral("\xFFFC\x241D")); // GS localScript.replace(QChar('\x1E'), QStringLiteral("\xFFFC\x241E")); // RS localScript.replace(QChar('\x1F'), QStringLiteral("\xFFFC\x241F")); // US localScript.replace(QChar('\x7F'), QStringLiteral("\xFFFC\x2421")); // DEL writeTextElement(QLatin1String("script"), localScript); }<|fim▁end|>
<|file_name|>pathBasicShapeCircleTest.js<|end_file_name|><|fim▁begin|>/* global suite test internalScope */ (function () { suite('offsetPath', function () { test('basicShapeCircle', function () { var assertTransformInterpolation = internalScope.assertTransformInterpolation; assertTransformInterpolation([ {'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '0%'}, {'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '100%'}], [ {at: 0, is: 'translate3d(0px, -10px, 0px)'}, {at: 0.25, is: 'translate3d(10px, 0px, 0px) rotate(90deg)'}, {at: 0.5, is: 'translate3d(0px, 10px, 0px) rotate(180deg)'}, {at: 0.75, is: 'translate3d(-10px, 0px, 0px) rotate(-90deg)'}, {at: 1, is: 'translate3d(0px, -10px, 0px)'} ] ); assertTransformInterpolation([ {'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '0px'}, {'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '62.83px'}], [ {at: 0, is: 'translate3d(0px, -10px, 0px)'}, {at: 0.25, is: 'translate3d(10px, 0px, 0px) rotate(89.45deg)'}, {at: 0.5, is: 'translate3d(0.01px, 10px, 0px) rotate(180deg)'}, {at: 0.75, is: 'translate3d(-10px, 0.01px, 0px) rotate(-90deg)'}, {at: 1, is: 'translate3d(-0.01px, -10px, 0px) rotate(-0.55deg)'} ] ); assertTransformInterpolation([ {'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '0%'}, {'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '50%'}], [ {at: 0, is: 'translate3d(0px, -10px, 0px)'}, {at: 0.5, is: 'translate3d(10px, 0px, 0px) rotate(90deg)'}, {at: 1, is: 'translate3d(0px, 10px, 0px) rotate(180deg)'}<|fim▁hole|> assertTransformInterpolation([ {'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '0px'}, {'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '31.42px'}], [ {at: 0, is: 'translate3d(0px, -10px, 0px)'}, {at: 0.5, is: 'translate3d(10px, 0px, 0px) rotate(90deg)'}, {at: 1, is: 'translate3d(0px, 10px, 0px) rotate(179.45deg)'} ] ); assertTransformInterpolation([ {'offsetPath': 'circle(10px at 100px 100px)', 'offsetDistance': '0%'}, {'offsetPath': 'circle(10px at 100px 100px)', 'offsetDistance': '100%'}], [ {at: 0, is: 'translate3d(100px, 90px, 0px)'}, {at: 0.25, is: 'translate3d(110px, 100px, 0px) rotate(90deg)'}, {at: 0.5, is: 'translate3d(100px, 110px, 0px) rotate(180deg)'}, {at: 0.75, is: 'translate3d(90px, 100px, 0px) rotate(-90deg)'}, {at: 1, is: 'translate3d(100px, 90px, 0px)'} ] ); // TODO: Support path interpolation for basic shapes. assertTransformInterpolation([ {'offsetPath': 'circle(0px at 100px 200px)', 'offsetDistance': '1000px', 'offsetRotate': '0deg', 'offsetAnchor': '50% 50%'}, {'offsetPath': 'circle(0px at 300px 400px)', 'offsetDistance': '1000px', 'offsetRotate': '0deg', 'offsetAnchor': '50% 50%'}], [ {at: 0, is: 'translate3d(100px, 200px, 0px)'}, {at: 1, is: 'translate3d(300px, 400px, 0px)'} ] ); }); }); })();<|fim▁end|>
] );
<|file_name|>status_updater.py<|end_file_name|><|fim▁begin|># Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import webnotes from webnotes.utils import flt, cstr from webnotes import msgprint from webnotes.model.controller import DocListController status_map = { "Contact": [ ["Replied", "communication_sent"], ["Open", "communication_received"] ], "Job Applicant": [ ["Replied", "communication_sent"], ["Open", "communication_received"] ], "Lead": [ ["Replied", "communication_sent"], ["Converted", "has_customer"], ["Opportunity", "has_opportunity"], ["Open", "communication_received"], ], "Opportunity": [ ["Draft", None], ["Submitted", "eval:self.doc.docstatus==1"], ["Lost", "eval:self.doc.status=='Lost'"], ["Quotation", "has_quotation"], ["Replied", "communication_sent"], ["Cancelled", "eval:self.doc.docstatus==2"], ["Open", "communication_received"], ], "Quotation": [ ["Draft", None], ["Submitted", "eval:self.doc.docstatus==1"], ["Lost", "eval:self.doc.status=='Lost'"], ["Ordered", "has_sales_order"], ["Replied", "communication_sent"], ["Cancelled", "eval:self.doc.docstatus==2"], ["Open", "communication_received"], ], "Sales Order": [ ["Draft", None], ["Submitted", "eval:self.doc.docstatus==1"], ["Stopped", "eval:self.doc.status=='Stopped'"], ["Cancelled", "eval:self.doc.docstatus==2"], ], "Support Ticket": [ ["Replied", "communication_sent"], ["Open", "communication_received"] ], } class StatusUpdater(DocListController): """ Updates the status of the calling records Delivery Note: Update Delivered Qty, Update Percent and Validate over delivery Sales Invoice: Update Billed Amt, Update Percent and Validate over billing Installation Note: Update Installed Qty, Update Percent Qty and Validate over installation """ def update_prevdoc_status(self): self.update_qty() self.validate_qty() def set_status(self, update=False): if self.doc.get("__islocal"): return if self.doc.doctype in status_map: sl = status_map[self.doc.doctype][:] sl.reverse() for s in sl: if not s[1]: self.doc.status = s[0] break elif s[1].startswith("eval:"): if eval(s[1][5:]): self.doc.status = s[0] break elif getattr(self, s[1])(): self.doc.status = s[0] break if update: webnotes.conn.set_value(self.doc.doctype, self.doc.name, "status", self.doc.status) def on_communication(self): self.communication_set = True self.set_status(update=True) del self.communication_set def communication_received(self): if getattr(self, "communication_set", False): last_comm = self.doclist.get({"doctype":"Communication"}) if last_comm: return last_comm[-1].sent_or_received == "Received" def communication_sent(self): if getattr(self, "communication_set", False): last_comm = self.doclist.get({"doctype":"Communication"}) if last_comm: return last_comm[-1].sent_or_received == "Sent" def validate_qty(self): """ Validates qty at row level """ self.tolerance = {} self.global_tolerance = None for args in self.status_updater: # get unique transactions to update for d in self.doclist: if d.doctype == args['source_dt'] and d.fields.get(args["join_field"]): args['name'] = d.fields[args['join_field']] # get all qty where qty > target_field item = webnotes.conn.sql("""select item_code, `%(target_ref_field)s`, `%(target_field)s`, parenttype, parent from `tab%(target_dt)s` where `%(target_ref_field)s` < `%(target_field)s` and name="%(name)s" and docstatus=1""" % args, as_dict=1) if item: item = item[0] item['idx'] = d.idx item['target_ref_field'] = args['target_ref_field'].replace('_', ' ') if not item[args['target_ref_field']]: msgprint("""As %(target_ref_field)s for item: %(item_code)s in \ %(parenttype)s: %(parent)s is zero, system will not check \ over-delivery or over-billed""" % item) elif args.get('no_tolerance'): item['reduce_by'] = item[args['target_field']] - \ item[args['target_ref_field']] if item['reduce_by'] > .01: msgprint(""" Row #%(idx)s: Max %(target_ref_field)s allowed for <b>Item \ %(item_code)s</b> against <b>%(parenttype)s %(parent)s</b> \ is <b>""" % item + cstr(item[args['target_ref_field']]) + """</b>.<br>You must reduce the %(target_ref_field)s by \ %(reduce_by)s""" % item, raise_exception=1) else: self.check_overflow_with_tolerance(item, args) def check_overflow_with_tolerance(self, item, args): """ Checks if there is overflow condering a relaxation tolerance """ # check if overflow is within tolerance tolerance, self.tolerance, self.global_tolerance = get_tolerance_for(item['item_code'], self.tolerance, self.global_tolerance) overflow_percent = ((item[args['target_field']] - item[args['target_ref_field']]) / item[args['target_ref_field']]) * 100 if overflow_percent - tolerance > 0.01: item['max_allowed'] = flt(item[args['target_ref_field']] * (100+tolerance)/100) item['reduce_by'] = item[args['target_field']] - item['max_allowed'] msgprint(""" Row #%(idx)s: Max %(target_ref_field)s allowed for <b>Item %(item_code)s</b> \ against <b>%(parenttype)s %(parent)s</b> is <b>%(max_allowed)s</b>. If you want to increase your overflow tolerance, please increase tolerance %% in \ Global Defaults or Item master. Or, you must reduce the %(target_ref_field)s by %(reduce_by)s<|fim▁hole|> Also, please check if the order item has already been billed in the Sales Order""" % item, raise_exception=1) def update_qty(self, change_modified=True): """ Updates qty at row level """ for args in self.status_updater: # condition to include current record (if submit or no if cancel) if self.doc.docstatus == 1: args['cond'] = ' or parent="%s"' % self.doc.name else: args['cond'] = ' and parent!="%s"' % self.doc.name args['modified_cond'] = '' if change_modified: args['modified_cond'] = ', modified = now()' # update quantities in child table for d in self.doclist: if d.doctype == args['source_dt']: # updates qty in the child table args['detail_id'] = d.fields.get(args['join_field']) args['second_source_condition'] = "" if args.get('second_source_dt') and args.get('second_source_field') \ and args.get('second_join_field'): args['second_source_condition'] = """ + (select sum(%(second_source_field)s) from `tab%(second_source_dt)s` where `%(second_join_field)s`="%(detail_id)s" and (docstatus=1))""" % args if args['detail_id']: webnotes.conn.sql("""update `tab%(target_dt)s` set %(target_field)s = (select sum(%(source_field)s) from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s" and (docstatus=1 %(cond)s)) %(second_source_condition)s where name='%(detail_id)s'""" % args) # get unique transactions to update for name in set([d.fields.get(args['percent_join_field']) for d in self.doclist if d.doctype == args['source_dt']]): if name: args['name'] = name # update percent complete in the parent table webnotes.conn.sql("""update `tab%(target_parent_dt)s` set %(target_parent_field)s = (select sum(if(%(target_ref_field)s > ifnull(%(target_field)s, 0), %(target_field)s, %(target_ref_field)s))/sum(%(target_ref_field)s)*100 from `tab%(target_dt)s` where parent="%(name)s") %(modified_cond)s where name='%(name)s'""" % args) # update field if args.get('status_field'): webnotes.conn.sql("""update `tab%(target_parent_dt)s` set %(status_field)s = if(ifnull(%(target_parent_field)s,0)<0.001, 'Not %(keyword)s', if(%(target_parent_field)s>=99.99, 'Fully %(keyword)s', 'Partly %(keyword)s')) where name='%(name)s'""" % args) def get_tolerance_for(item_code, item_tolerance={}, global_tolerance=None): """ Returns the tolerance for the item, if not set, returns global tolerance """ if item_tolerance.get(item_code): return item_tolerance[item_code], item_tolerance, global_tolerance tolerance = flt(webnotes.conn.get_value('Item',item_code,'tolerance') or 0) if not tolerance: if global_tolerance == None: global_tolerance = flt(webnotes.conn.get_value('Global Defaults', None, 'tolerance')) tolerance = global_tolerance item_tolerance[item_code] = tolerance return tolerance, item_tolerance, global_tolerance<|fim▁end|>
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(box_syntax)] #![feature(collections)] #![feature(core)] #[macro_use] extern crate log; extern crate azure; extern crate devtools_traits; extern crate geom; extern crate gfx; extern crate layers; extern crate layout_traits; extern crate png; extern crate script_traits; extern crate msg; extern crate net; extern crate num; extern crate profile_traits; extern crate net_traits; extern crate gfx_traits; extern crate style; #[macro_use] extern crate util; extern crate gleam; extern crate clipboard; extern crate libc; extern crate time; extern crate url; #[cfg(target_os="macos")] extern crate core_graphics; #[cfg(target_os="macos")]<|fim▁hole|>extern crate core_text; pub use compositor_task::{CompositorEventListener, CompositorProxy, CompositorTask}; pub use constellation::Constellation; pub mod compositor_task; mod compositor_layer; mod compositor; mod headless; mod scrolling; pub mod pipeline; pub mod constellation; pub mod windowing;<|fim▁end|>
<|file_name|>file_data_source.cc<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/filters/file_data_source.h" #include <algorithm> #include "base/logging.h" namespace media { FileDataSource::FileDataSource() : force_read_errors_(false), force_streaming_(false) { } bool FileDataSource::Initialize(const FilePath& file_path) { DCHECK(!file_.IsValid()); if (!file_.Initialize(file_path)) return false;<|fim▁hole|> void FileDataSource::set_host(DataSourceHost* host) { DataSource::set_host(host); UpdateHostBytes(); } void FileDataSource::Stop(const base::Closure& callback) { callback.Run(); } void FileDataSource::Read(int64 position, int size, uint8* data, const DataSource::ReadCB& read_cb) { if (force_read_errors_ || !file_.IsValid()) { read_cb.Run(kReadError); return; } int64 file_size = file_.length(); CHECK_GE(file_size, 0); CHECK_GE(position, 0); CHECK_GE(size, 0); // Cap position and size within bounds. position = std::min(position, file_size); int64 clamped_size = std::min(static_cast<int64>(size), file_size - position); memcpy(data, file_.data() + position, clamped_size); read_cb.Run(clamped_size); } bool FileDataSource::GetSize(int64* size_out) { *size_out = file_.length(); return true; } bool FileDataSource::IsStreaming() { return force_streaming_; } void FileDataSource::SetBitrate(int bitrate) {} FileDataSource::~FileDataSource() {} void FileDataSource::UpdateHostBytes() { if (host() && file_.IsValid()) { host()->SetTotalBytes(file_.length()); host()->AddBufferedByteRange(0, file_.length()); } } } // namespace media<|fim▁end|>
UpdateHostBytes(); return true; }
<|file_name|>era_prep.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ This module preprocesses ERA-Interim data, units, accumulated to instantaneous values and timestep interpolation for 6 h to 3 h values. Example: as import: from getERA import era_prep as prep prep.main(wd, config['main']['startDate'], config['main']['endDate']) Attributes: wd = "/home/joel/sim/topomap_test/" plotshp = TRUE Todo: """<|fim▁hole|># main def main(wd, startDate, endDate): """Main entry point for the script.""" run_rscript_fileout(path2script,[wd, startDate, endDate]) # functions def run_rscript_stdout(path2script , args): """ Function to define comands to run an Rscript. Returns an object. """ import subprocess command = 'Rscript' cmd = [command, path2script] + args print("Running:" + str(cmd)) x = subprocess.check_output(cmd, universal_newlines=True) return(x) def run_rscript_fileout(path2script , args): """ Function to define comands to run an Rscript. Outputs a file. """ import subprocess command = 'Rscript' cmd = [command, path2script] + args print("Running:" + str(cmd)) subprocess.check_output(cmd) # calling main if __name__ == '__main__': import sys wd = sys.argv[1] startDate = sys.argv[2] endDate = sys.argv[3] main(wd, startDate, endDate)<|fim▁end|>
path2script = "./rsrc/toposcale_pre2.R"
<|file_name|>util.js<|end_file_name|><|fim▁begin|>var path = require('path'); var fs = require('fs'); var spawn = require('child_process').spawn; function noop() {} exports.noop = noop; if (process.env.HTTP2_LOG) { var logOutput = process.stderr; if (process.stderr.isTTY) { var bin = path.resolve(path.dirname(require.resolve('bunyan')), '..', 'bin', 'bunyan'); if(bin && fs.existsSync(bin)) { logOutput = spawn(bin, ['-o', 'short'], { stdio: [null, process.stderr, process.stderr] }).stdin; } } exports.createLogger = function(name) { return require('bunyan').createLogger({ name: name, stream: logOutput, level: process.env.HTTP2_LOG, serializers: require('../lib/http').serializers }); }; exports.log = exports.createLogger('test'); exports.clientLog = exports.createLogger('client'); exports.serverLog = exports.createLogger('server'); } else { exports.createLogger = function() { return exports.log; }; exports.log = exports.clientLog = exports.serverLog = { fatal: noop, error: noop, warn : noop, info : noop, debug: noop, trace: noop, child: function() { return this; } }; } exports.callNTimes = function callNTimes(limit, done) { if (limit === 0) { done(); } else { var i = 0; return function() { i += 1; if (i === limit) { done(); } }; } }; // Concatenate an array of buffers into a new buffer exports.concat = function concat(buffers) { var size = 0; for (var i = 0; i < buffers.length; i++) { size += buffers[i].length; } var concatenated = new Buffer(size); for (var cursor = 0, j = 0; j < buffers.length; cursor += buffers[j].length, j++) { buffers[j].copy(concatenated, cursor); } return concatenated; }; exports.random = function random(min, max) { return min + Math.floor(Math.random() * (max - min + 1)); }; // Concatenate an array of buffers and then cut them into random size buffers exports.shuffleBuffers = function shuffleBuffers(buffers) { var concatenated = exports.concat(buffers), output = [], written = 0; <|fim▁hole|> written += chunk_size; } return output; };<|fim▁end|>
while (written < concatenated.length) { var chunk_size = Math.min(concatenated.length - written, Math.ceil(Math.random()*20)); output.push(concatenated.slice(written, written + chunk_size));
<|file_name|>grid.js<|end_file_name|><|fim▁begin|>'use strict'; angular.module('tucha') .controller('GridCtrl', function ($rootScope, $scope, $location, $http, $timeout, states, columns) { var stateName = $location.path().split('/')[1]; for (var i = 0; i < states.length; i++) { if (states[i].name === stateName) { $scope.state = states[i]; states[i].active = true; $scope.title = states[i].title; } else { states[i].active = false; } } $http.get('/r/' + stateName).then(function (data) { //$scope.data = data.data; var columnDefs = []; if (stateName === 'animal') { columnDefs.push({ field: 'id', name: '', width: 50, cellTemplate: '<div class="grid-image-cell"><img width="50" src="r/animal/{{row.entity.id}}/photo_wh50"/></div>' }); } else if (stateName === 'associate') { $scope.feesDueList = []; $scope.currentYear = new Date().getFullYear(); for (var i = 0; i < data.data.length; i++) { if (!data.data[i].last_paid_fee || data.data[i].last_paid_fee < $scope.currentYear) { $scope.feesDueList.push(data.data[i]); } } }<|fim▁hole|> columnDefs.push(columns[key]); } $scope.gridOptions = { data: data.data, columnDefs: columnDefs, minRowsToShow: data.data.length + 0.1, enableHorizontalScrollbar: 0, enableVerticalScrollbar: 0, enableGridMenu: true, rowTemplate: 'views/directives/rowTemplate.html', rowHeight: 50, onRegisterApi: function (gridApi) { $scope.gridApi = gridApi; }, appScopeProvider: { rowClick: function (row) { if (stateName === 'animal') { // generate current sort ids for the next and previous button to work $rootScope.animalsSequence = []; var rows = $scope.gridApi.core.getVisibleRows(); for (var i = 0; i < rows.length; i++) { $rootScope.animalsSequence.push(rows[i].entity.id); } } else if (stateName === 'volunteer' || stateName === 'associate') { // theese 2 sections are only shortcuts to persons with different filtered lists stateName = 'person'; } $location.path('/' + stateName + '/' + row.entity.id); } } }; }); $scope.add = function () { $location.path('/' + stateName + "/new"); }; });<|fim▁end|>
for (var key in data.data[0]) {
<|file_name|>3.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from math import * def i321(): n = 0L mn = 0L tn = 0L sn = 0L n3 = 0L n9 = 0L n = 372889431 mn = 139046528497282623<|fim▁hole|> print "M(%i) = %i\n" % (n, mn) print "sqrt(%d) = %i\n" % (n, sqrt(n)) print "sqrt(%d) = %i\n" % (tn, sqrt(tn)) print "sqrt(%i) mod 1 = %i\n" % (tn, sqrt(tn) % 1) print "%i mod 3 = %i\n %i mod 9 = %i\n" % (mn, mn % 3L, mn, mn % 9L) i321()<|fim▁end|>
tn = 1L + 8L * mn
<|file_name|>compare.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import argparse import json import csv import sys sys.path.append('python') import plotting import utils from opener import opener parser = argparse.ArgumentParser() parser.add_argument('-b', action='store_true') # passed on to ROOT when plotting parser.add_argument('--outdir', required=True) parser.add_argument('--plotdirs', required=True) parser.add_argument('--names', required=True) parser.add_argument('--stats', default='') parser.add_argument('--no-errors', action='store_true') parser.add_argument('--plot-performance', action='store_true') parser.add_argument('--scale-errors') parser.add_argument('--rebin', type=int) parser.add_argument('--colors') parser.add_argument('--linestyles') parser.add_argument('--datadir', default='data/imgt') parser.add_argument('--leaves-per-tree') parser.add_argument('--linewidths') parser.add_argument('--markersizes') parser.add_argument('--dont-calculate-mean-info', action='store_true') parser.add_argument('--normalize', action='store_true') parser.add_argument('--graphify', action='store_true') parser.add_argument('--strings-to-ignore') # remove this string from the plot names in each dir (e.g. '-mean-bins') NOTE replaces '_' with '-' args = parser.parse_args() if args.strings_to_ignore is not None: args.strings_to_ignore = args.strings_to_ignore.replace('_', '-') args.plotdirs = utils.get_arg_list(args.plotdirs) args.scale_errors = utils.get_arg_list(args.scale_errors) args.colors = utils.get_arg_list(args.colors, intify=True) args.linestyles = utils.get_arg_list(args.linestyles, intify=True) args.names = utils.get_arg_list(args.names) args.leaves_per_tree = utils.get_arg_list(args.leaves_per_tree, intify=True) args.strings_to_ignore = utils.get_arg_list(args.strings_to_ignore) args.markersizes = utils.get_arg_list(args.markersizes, intify=True) args.linewidths = utils.get_arg_list(args.linewidths, intify=True) for iname in range(len(args.names)): args.names[iname] = args.names[iname].replace('@', ' ') assert len(args.plotdirs) == len(args.names) with opener('r')(args.datadir + '/v-meta.json') as json_file: # get location of <begin> cysteine in each v region<|fim▁hole|>with opener('r')(args.datadir + '/j_tryp.csv') as csv_file: # get location of <end> tryptophan in each j region (TGG) tryp_reader = csv.reader(csv_file) args.tryp_positions = {row[0]:row[1] for row in tryp_reader} # WARNING: this doesn't filter out the header line plotting.compare_directories(args)<|fim▁end|>
args.cyst_positions = json.load(json_file)
<|file_name|>CTBitset.java<|end_file_name|><|fim▁begin|>/** * Copyright 2017 Matthieu Jimenez. All rights reserved. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package paw.graph.customTypes.bitset; import greycat.base.BaseCustomType; import greycat.struct.EStructArray; import greycat.utility.HashHelper; import org.roaringbitmap.IntIterator; import java.util.List; public abstract class CTBitset extends BaseCustomType{ public static final String BITS = "bits"; protected static final int BITS_H = HashHelper.hash(BITS); public CTBitset(EStructArray p_backend) { super(p_backend); } public abstract void save(); <|fim▁hole|> public abstract boolean add(int index); public abstract boolean addAll(List<Integer> indexs); public abstract void clear(int index); public abstract int size(); public abstract int cardinality(); public abstract boolean get(int index); public abstract int nextSetBit(int startIndex); public abstract IntIterator iterator(); }<|fim▁end|>
public abstract void clear();
<|file_name|>regions-close-object-into-object-5.rs<|end_file_name|><|fim▁begin|>#![allow(warnings)] trait A<T><|fim▁hole|>} struct B<'a, T: 'a>(&'a (A<T> + 'a)); trait X { fn foo(&self) {} } impl<'a, T> X for B<'a, T> {} fn f<'a, T, U>(v: Box<A<T> + 'static>) -> Box<X + 'static> { // oh dear! Box::new(B(&*v)) as Box<dyn X> //~^ ERROR the parameter type `T` may not live long enough //~| ERROR the parameter type `T` may not live long enough //~| ERROR the parameter type `T` may not live long enough //~| ERROR the parameter type `T` may not live long enough //~| ERROR the parameter type `T` may not live long enough //~| ERROR the parameter type `T` may not live long enough //~| ERROR the parameter type `T` may not live long enough } fn main() {}<|fim▁end|>
{ fn get(&self) -> T { panic!() }
<|file_name|>aws_ebs_test.go<|end_file_name|><|fim▁begin|>// +build !providerless /* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package awsebs import ( "fmt" "os" "path/filepath" "reflect" "testing" "github.com/stretchr/testify/assert" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/kubernetes/fake" utiltesting "k8s.io/client-go/util/testing" "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/volume" volumetest "k8s.io/kubernetes/pkg/volume/testing" "k8s.io/legacy-cloud-providers/aws" ) func TestCanSupport(t *testing.T) { tmpDir, err := utiltesting.MkTmpdir("awsebsTest") if err != nil { t.Fatalf("can't make a temp dir: %v", err) } defer os.RemoveAll(tmpDir) plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, nil, nil)) plug, err := plugMgr.FindPluginByName("kubernetes.io/aws-ebs") if err != nil { t.Errorf("Can't find the plugin by name") } if plug.GetPluginName() != "kubernetes.io/aws-ebs" { t.Errorf("Wrong name: %s", plug.GetPluginName()) } if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{}}}}) { t.Errorf("Expected true") } if !plug.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{}}}}}) { t.Errorf("Expected true") } } func TestGetAccessModes(t *testing.T) { tmpDir, err := utiltesting.MkTmpdir("awsebsTest") if err != nil { t.Fatalf("can't make a temp dir: %v", err) } defer os.RemoveAll(tmpDir) plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, nil, nil)) plug, err := plugMgr.FindPersistentPluginByName("kubernetes.io/aws-ebs") if err != nil { t.Errorf("Can't find the plugin by name") } if !volumetest.ContainsAccessMode(plug.GetAccessModes(), v1.ReadWriteOnce) { t.Errorf("Expected to support AccessModeTypes: %s", v1.ReadWriteOnce) } if volumetest.ContainsAccessMode(plug.GetAccessModes(), v1.ReadOnlyMany) { t.Errorf("Expected not to support AccessModeTypes: %s", v1.ReadOnlyMany) } } type fakePDManager struct { } // TODO(jonesdl) To fully test this, we could create a loopback device // and mount that instead. func (fake *fakePDManager) CreateVolume(c *awsElasticBlockStoreProvisioner, node *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (volumeID aws.KubernetesVolumeID, volumeSizeGB int, labels map[string]string, fstype string, err error) { labels = make(map[string]string) labels["fakepdmanager"] = "yes" return "test-aws-volume-name", 100, labels, "", nil } func (fake *fakePDManager) DeleteVolume(cd *awsElasticBlockStoreDeleter) error { if cd.volumeID != "test-aws-volume-name" { return fmt.Errorf("Deleter got unexpected volume name: %s", cd.volumeID) } return nil } func TestPlugin(t *testing.T) { tmpDir, err := utiltesting.MkTmpdir("awsebsTest") if err != nil { t.Fatalf("can't make a temp dir: %v", err) } defer os.RemoveAll(tmpDir) plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, nil, nil)) plug, err := plugMgr.FindPluginByName("kubernetes.io/aws-ebs") if err != nil { t.Errorf("Can't find the plugin by name") } spec := &v1.Volume{ Name: "vol1", VolumeSource: v1.VolumeSource{ AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: "pd", FSType: "ext4", }, }, } fakeManager := &fakePDManager{} fakeMounter := &mount.FakeMounter{} mounter, err := plug.(*awsElasticBlockStorePlugin).newMounterInternal(volume.NewSpecFromVolume(spec), types.UID("poduid"), fakeManager, fakeMounter) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) } if mounter == nil { t.Errorf("Got a nil Mounter") } volPath := filepath.Join(tmpDir, "pods/poduid/volumes/kubernetes.io~aws-ebs/vol1") path := mounter.GetPath() if path != volPath { t.Errorf("Got unexpected path: %s", path) } if err := mounter.SetUp(volume.MounterArgs{}); err != nil { t.Errorf("Expected success, got: %v", err) } if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { t.Errorf("SetUp() failed, volume path not created: %s", path) } else { t.Errorf("SetUp() failed: %v", err) } } fakeManager = &fakePDManager{} unmounter, err := plug.(*awsElasticBlockStorePlugin).newUnmounterInternal("vol1", types.UID("poduid"), fakeManager, fakeMounter) if err != nil { t.Errorf("Failed to make a new Unmounter: %v", err) } if unmounter == nil { t.Errorf("Got a nil Unmounter") } if err := unmounter.TearDown(); err != nil { t.Errorf("Expected success, got: %v", err) } if _, err := os.Stat(path); err == nil { t.Errorf("TearDown() failed, volume path still exists: %s", path) } else if !os.IsNotExist(err) { t.Errorf("TearDown() failed: %v", err) } // Test Provisioner options := volume.VolumeOptions{ PVC: volumetest.CreateTestPVC("100Mi", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}), PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete, } provisioner, err := plug.(*awsElasticBlockStorePlugin).newProvisionerInternal(options, &fakePDManager{}) if err != nil { t.Errorf("Error creating new provisioner:%v", err) } persistentSpec, err := provisioner.Provision(nil, nil) if err != nil { t.Errorf("Provision() failed: %v", err) } if persistentSpec.Spec.PersistentVolumeSource.AWSElasticBlockStore.VolumeID != "test-aws-volume-name" { t.Errorf("Provision() returned unexpected volume ID: %s", persistentSpec.Spec.PersistentVolumeSource.AWSElasticBlockStore.VolumeID) } cap := persistentSpec.Spec.Capacity[v1.ResourceStorage] size := cap.Value() if size != 100*1024*1024*1024 { t.Errorf("Provision() returned unexpected volume size: %v", size) } if persistentSpec.Labels["fakepdmanager"] != "yes" { t.Errorf("Provision() returned unexpected labels: %v", persistentSpec.Labels) } // check nodeaffinity members if persistentSpec.Spec.NodeAffinity == nil { t.Errorf("Provision() returned unexpected nil NodeAffinity") } if persistentSpec.Spec.NodeAffinity.Required == nil { t.Errorf("Provision() returned unexpected nil NodeAffinity.Required") } n := len(persistentSpec.Spec.NodeAffinity.Required.NodeSelectorTerms) if n != 1 { t.Errorf("Provision() returned unexpected number of NodeSelectorTerms %d. Expected %d", n, 1) } n = len(persistentSpec.Spec.NodeAffinity.Required.NodeSelectorTerms[0].MatchExpressions) if n != 1 { t.Errorf("Provision() returned unexpected number of MatchExpressions %d. Expected %d", n, 1) } req := persistentSpec.Spec.NodeAffinity.Required.NodeSelectorTerms[0].MatchExpressions[0] if req.Key != "fakepdmanager" { t.Errorf("Provision() returned unexpected requirement key in NodeAffinity %v", req.Key) } if req.Operator != v1.NodeSelectorOpIn { t.Errorf("Provision() returned unexpected requirement operator in NodeAffinity %v", req.Operator) } if len(req.Values) != 1 || req.Values[0] != "yes" { t.Errorf("Provision() returned unexpected requirement value in NodeAffinity %v", req.Values) } // Test Deleter volSpec := &volume.Spec{ PersistentVolume: persistentSpec, } deleter, err := plug.(*awsElasticBlockStorePlugin).newDeleterInternal(volSpec, &fakePDManager{}) if err != nil { t.Errorf("Error creating new deleter:%v", err) } err = deleter.Delete() if err != nil { t.Errorf("Deleter() failed: %v", err) } } func TestPersistentClaimReadOnlyFlag(t *testing.T) { pv := &v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ Name: "pvA", }, Spec: v1.PersistentVolumeSpec{ PersistentVolumeSource: v1.PersistentVolumeSource{ AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{}, }, ClaimRef: &v1.ObjectReference{ Name: "claimA", }, }, } claim := &v1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: "claimA", Namespace: "nsA", }, Spec: v1.PersistentVolumeClaimSpec{ VolumeName: "pvA", }, Status: v1.PersistentVolumeClaimStatus{ Phase: v1.ClaimBound, }, } clientset := fake.NewSimpleClientset(pv, claim) tmpDir, err := utiltesting.MkTmpdir("awsebsTest") if err != nil { t.Fatalf("can't make a temp dir: %v", err) } defer os.RemoveAll(tmpDir) plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, clientset, nil)) plug, _ := plugMgr.FindPluginByName(awsElasticBlockStorePluginName) // readOnly bool is supplied by persistent-claim volume source when its mounter creates other volumes spec := volume.NewSpecFromPersistentVolume(pv, true) pod := &v1.Pod{ObjectMeta: metav1.ObjectMeta{UID: types.UID("poduid")}} mounter, _ := plug.NewMounter(spec, pod, volume.VolumeOptions{}) if !mounter.GetAttributes().ReadOnly { t.Errorf("Expected true for mounter.IsReadOnly") } } func TestMounterAndUnmounterTypeAssert(t *testing.T) { tmpDir, err := utiltesting.MkTmpdir("awsebsTest") if err != nil { t.Fatalf("can't make a temp dir: %v", err) } defer os.RemoveAll(tmpDir) plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, nil, nil)) plug, err := plugMgr.FindPluginByName("kubernetes.io/aws-ebs") if err != nil { t.Errorf("Can't find the plugin by name") } spec := &v1.Volume{ Name: "vol1", VolumeSource: v1.VolumeSource{ AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: "pd", FSType: "ext4", }, }, } mounter, err := plug.(*awsElasticBlockStorePlugin).newMounterInternal(volume.NewSpecFromVolume(spec), types.UID("poduid"), &fakePDManager{}, &mount.FakeMounter{}) if err != nil { t.Errorf("Error creating new mounter:%v", err) } if _, ok := mounter.(volume.Unmounter); ok { t.Errorf("Volume Mounter can be type-assert to Unmounter") } unmounter, err := plug.(*awsElasticBlockStorePlugin).newUnmounterInternal("vol1", types.UID("poduid"), &fakePDManager{}, &mount.FakeMounter{}) if err != nil { t.Errorf("Error creating new unmounter:%v", err) } if _, ok := unmounter.(volume.Mounter); ok { t.Errorf("Volume Unmounter can be type-assert to Mounter") } } func TestMountOptions(t *testing.T) {<|fim▁hole|> } defer os.RemoveAll(tmpDir) plugMgr := volume.VolumePluginMgr{} plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, nil, nil)) plug, err := plugMgr.FindPluginByName("kubernetes.io/aws-ebs") if err != nil { t.Errorf("Can't find the plugin by name") } pv := &v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ Name: "pvA", }, Spec: v1.PersistentVolumeSpec{ PersistentVolumeSource: v1.PersistentVolumeSource{ AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{}, }, ClaimRef: &v1.ObjectReference{ Name: "claimA", }, MountOptions: []string{"_netdev"}, }, } fakeManager := &fakePDManager{} fakeMounter := &mount.FakeMounter{} mounter, err := plug.(*awsElasticBlockStorePlugin).newMounterInternal(volume.NewSpecFromPersistentVolume(pv, false), types.UID("poduid"), fakeManager, fakeMounter) if err != nil { t.Errorf("Failed to make a new Mounter: %v", err) } if mounter == nil { t.Errorf("Got a nil Mounter") } if err := mounter.SetUp(volume.MounterArgs{}); err != nil { t.Errorf("Expected success, got: %v", err) } mountOptions := fakeMounter.MountPoints[0].Opts expectedMountOptions := []string{"_netdev", "bind"} if !reflect.DeepEqual(mountOptions, expectedMountOptions) { t.Errorf("Expected mount options to be %v got %v", expectedMountOptions, mountOptions) } } func TestGetCandidateZone(t *testing.T) { const testZone = "my-zone-1a" // TODO: add test case for immediate bind volume when we have a good way to mock Cloud outside cloudprovider tests := []struct { cloud *aws.Cloud node *v1.Node expectedZones sets.String }{ { cloud: nil, node: &v1.Node{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ v1.LabelZoneFailureDomain: testZone, }, }, }, expectedZones: sets.NewString(), }, { cloud: nil, node: &v1.Node{}, expectedZones: sets.NewString(), }, } for _, test := range tests { zones, err := getCandidateZones(test.cloud, test.node) assert.Nil(t, err) assert.Equal(t, test.expectedZones, zones) } }<|fim▁end|>
tmpDir, err := utiltesting.MkTmpdir("aws-ebs") if err != nil { t.Fatalf("can't make a temp dir: %v", err)
<|file_name|>index.js<|end_file_name|><|fim▁begin|>var Promise = require('ember-cli/lib/ext/promise'); <|fim▁hole|> afterInstall: function() { var addonContext = this; return this.addBowerPackageToProject('jquery-ui', '1.10.1') .then(function() { return addonContext.addBowerPackageToProject('jquery-mousewheel', '~3.1.4'); }) .then(function() { return addonContext.addBowerPackageToProject('taras/antiscroll', '92505e0e0d0ef9383630df509883bce558215b22'); }); } };<|fim▁end|>
module.exports = { normalizeEntityName: function() {},
<|file_name|>MspImagePlugin.py<|end_file_name|><|fim▁begin|># # The Python Imaging Library. # $Id$ # # MSP file handling # # This is the format used by the Paint program in Windows 1 and 2. # # History: # 95-09-05 fl Created # 97-01-03 fl Read/write MSP images # # Copyright (c) Secret Labs AB 1997. # Copyright (c) Fredrik Lundh 1995-97. # # See the README file for information on usage and redistribution. # __version__ = "0.1" from PIL import Image, ImageFile, _binary # # read MSP files i16 = _binary.i16le def _accept(prefix): return prefix[:4] in [b"DanM", b"LinS"] ## # Image plugin for Windows MSP images. This plugin supports both # uncompressed (Windows 1.0). class MspImageFile(ImageFile.ImageFile): format = "MSP" format_description = "Windows Paint" def _open(self): # Header s = self.fp.read(32) if s[:4] not in [b"DanM", b"LinS"]: raise SyntaxError("not an MSP file") # Header checksum sum = 0 for i in range(0, 32, 2): sum = sum ^ i16(s[i:i+2]) if sum != 0: raise SyntaxError("bad MSP checksum") self.mode = "1" self.size = i16(s[4:]), i16(s[6:]) if s[:4] == b"DanM": self.tile = [("raw", (0,0)+self.size, 32, ("1", 0, 1))] else: self.tile = [("msp", (0,0)+self.size, 32+2*self.size[1], None)] # # write MSP files (uncompressed only) o16 = _binary.o16le def _save(im, fp, filename): if im.mode != "1": raise IOError("cannot write mode %s as MSP" % im.mode) # create MSP header header = [0] * 16 header[0], header[1] = i16(b"Da"), i16(b"nM") # version 1 header[2], header[3] = im.size header[4], header[5] = 1, 1 header[6], header[7] = 1, 1 header[8], header[9] = im.size <|fim▁hole|> sum = 0 for h in header: sum = sum ^ h header[12] = sum # FIXME: is this the right field? # header for h in header: fp.write(o16(h)) # image body ImageFile._save(im, fp, [("raw", (0,0)+im.size, 32, ("1", 0, 1))]) # # registry Image.register_open("MSP", MspImageFile, _accept) Image.register_save("MSP", _save) Image.register_extension("MSP", ".msp")<|fim▁end|>
<|file_name|>system4.py<|end_file_name|><|fim▁begin|>import os import select fds = os.open("data", os.O_RDONLY) while True: reads, _, _ = select.select(fds, [], [], 2.0)<|fim▁hole|> d = os.read(reads[0], 10) if d: print "-> ", d else: break else: print "timeout"<|fim▁end|>
if 0 < len(reads):
<|file_name|>ViewGeneratorService.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import Config import Database import atexit, os, time from flask import Flask from concurrent.futures import ThreadPoolExecutor from classes import CRONTask # Generate a thread pool executor = ThreadPoolExecutor(5) app = Flask( __name__ ) @app.route( "/" ) def index( ) : return "View Generator Service is Active!" @app.route( "/View" ) def view( ) : executor.submit(runTask) return "" <|fim▁hole|> cron = CRONTask.CRONTask( ) cron.run( ) cron.killPID( ) sys.exit(0) if __name__ == '__main__' : app.run( debug=True, port=Config.PORT, host=Config.HOST )<|fim▁end|>
def runTask( ) :
<|file_name|>0057_expire_all_sessions.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2020-05-08 17:49 from __future__ import unicode_literals from django.db import migrations from django.core import management from django.contrib.sessions.models import Session from django.utils.timezone import now def expire_all_sessions(apps, schema_editor): # Clear any expired sessions. management.call_command("clearsessions") # Set any remaining sessions to expire. sessions = Session.objects.all() for session in sessions: session.expire_date = now() session.save() # Clear those sessions too. management.call_command("clearsessions") class Migration(migrations.Migration): <|fim▁hole|><|fim▁end|>
dependencies = [("users", "0056_remove_authorization_partner")] operations = [migrations.RunPython(expire_all_sessions)]
<|file_name|>BsWhiteImplicitReverseFkRef.java<|end_file_name|><|fim▁begin|>/* * Copyright 2004-2013 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.docksidestage.mysql.dbflute.bsentity; import java.util.List; import java.util.ArrayList; import org.dbflute.dbmeta.DBMeta; import org.dbflute.dbmeta.AbstractEntity; import org.dbflute.dbmeta.accessory.DomainEntity; import org.docksidestage.mysql.dbflute.allcommon.DBMetaInstanceHandler; import org.docksidestage.mysql.dbflute.exentity.*; /** * The entity of WHITE_IMPLICIT_REVERSE_FK_REF as TABLE. <br> * <pre> * [primary-key] * WHITE_IMPLICIT_REVERSE_FK_REF_ID * * [column] * WHITE_IMPLICIT_REVERSE_FK_REF_ID, WHITE_IMPLICIT_REVERSE_FK_ID, VALID_BEGIN_DATE, VALID_END_DATE * * [sequence] * * * [identity] * WHITE_IMPLICIT_REVERSE_FK_REF_ID * * [version-no] * * * [foreign table] * * * [referrer table] * * * [foreign property] * * * [referrer property] * * * [get/set template] * /= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * Integer whiteImplicitReverseFkRefId = entity.getWhiteImplicitReverseFkRefId(); * Integer whiteImplicitReverseFkId = entity.getWhiteImplicitReverseFkId(); * java.time.LocalDate validBeginDate = entity.getValidBeginDate(); * java.time.LocalDate validEndDate = entity.getValidEndDate(); * entity.setWhiteImplicitReverseFkRefId(whiteImplicitReverseFkRefId); * entity.setWhiteImplicitReverseFkId(whiteImplicitReverseFkId); * entity.setValidBeginDate(validBeginDate); * entity.setValidEndDate(validEndDate); * = = = = = = = = = =/ * </pre> * @author DBFlute(AutoGenerator) */ public abstract class BsWhiteImplicitReverseFkRef extends AbstractEntity implements DomainEntity { // =================================================================================== // Definition // ========== /** The serial version UID for object serialization. (Default) */ private static final long serialVersionUID = 1L; // =================================================================================== // Attribute // ========= /** WHITE_IMPLICIT_REVERSE_FK_REF_ID: {PK, ID, NotNull, INT(10)} */ protected Integer _whiteImplicitReverseFkRefId; /** WHITE_IMPLICIT_REVERSE_FK_ID: {UQ+, NotNull, INT(10)} */ protected Integer _whiteImplicitReverseFkId; /** VALID_BEGIN_DATE: {+UQ, NotNull, DATE(10)} */ protected java.time.LocalDate _validBeginDate; /** VALID_END_DATE: {NotNull, DATE(10)} */ protected java.time.LocalDate _validEndDate; // =================================================================================== // DB Meta // ======= /** {@inheritDoc} */ public DBMeta asDBMeta() { return DBMetaInstanceHandler.findDBMeta(asTableDbName()); } /** {@inheritDoc} */ public String asTableDbName() { return "white_implicit_reverse_fk_ref"; } // =================================================================================== // Key Handling // ============ /** {@inheritDoc} */ public boolean hasPrimaryKeyValue() { if (_whiteImplicitReverseFkRefId == null) { return false; } return true; } <|fim▁hole|> * @param whiteImplicitReverseFkId : UQ+, NotNull, INT(10). (NotNull) * @param validBeginDate : +UQ, NotNull, DATE(10). (NotNull) */ public void uniqueBy(Integer whiteImplicitReverseFkId, java.time.LocalDate validBeginDate) { __uniqueDrivenProperties.clear(); __uniqueDrivenProperties.addPropertyName("whiteImplicitReverseFkId"); __uniqueDrivenProperties.addPropertyName("validBeginDate"); setWhiteImplicitReverseFkId(whiteImplicitReverseFkId);setValidBeginDate(validBeginDate); } // =================================================================================== // Foreign Property // ================ // =================================================================================== // Referrer Property // ================= protected <ELEMENT> List<ELEMENT> newReferrerList() { // overriding to import return new ArrayList<ELEMENT>(); } // =================================================================================== // Basic Override // ============== @Override protected boolean doEquals(Object obj) { if (obj instanceof BsWhiteImplicitReverseFkRef) { BsWhiteImplicitReverseFkRef other = (BsWhiteImplicitReverseFkRef)obj; if (!xSV(_whiteImplicitReverseFkRefId, other._whiteImplicitReverseFkRefId)) { return false; } return true; } else { return false; } } @Override protected int doHashCode(int initial) { int hs = initial; hs = xCH(hs, asTableDbName()); hs = xCH(hs, _whiteImplicitReverseFkRefId); return hs; } @Override protected String doBuildStringWithRelation(String li) { return ""; } @Override protected String doBuildColumnString(String dm) { StringBuilder sb = new StringBuilder(); sb.append(dm).append(xfND(_whiteImplicitReverseFkRefId)); sb.append(dm).append(xfND(_whiteImplicitReverseFkId)); sb.append(dm).append(xfND(_validBeginDate)); sb.append(dm).append(xfND(_validEndDate)); if (sb.length() > dm.length()) { sb.delete(0, dm.length()); } sb.insert(0, "{").append("}"); return sb.toString(); } @Override protected String doBuildRelationString(String dm) { return ""; } @Override public WhiteImplicitReverseFkRef clone() { return (WhiteImplicitReverseFkRef)super.clone(); } // =================================================================================== // Accessor // ======== /** * [get] WHITE_IMPLICIT_REVERSE_FK_REF_ID: {PK, ID, NotNull, INT(10)} <br> * @return The value of the column 'WHITE_IMPLICIT_REVERSE_FK_REF_ID'. (basically NotNull if selected: for the constraint) */ public Integer getWhiteImplicitReverseFkRefId() { checkSpecifiedProperty("whiteImplicitReverseFkRefId"); return _whiteImplicitReverseFkRefId; } /** * [set] WHITE_IMPLICIT_REVERSE_FK_REF_ID: {PK, ID, NotNull, INT(10)} <br> * @param whiteImplicitReverseFkRefId The value of the column 'WHITE_IMPLICIT_REVERSE_FK_REF_ID'. (basically NotNull if update: for the constraint) */ public void setWhiteImplicitReverseFkRefId(Integer whiteImplicitReverseFkRefId) { registerModifiedProperty("whiteImplicitReverseFkRefId"); _whiteImplicitReverseFkRefId = whiteImplicitReverseFkRefId; } /** * [get] WHITE_IMPLICIT_REVERSE_FK_ID: {UQ+, NotNull, INT(10)} <br> * @return The value of the column 'WHITE_IMPLICIT_REVERSE_FK_ID'. (basically NotNull if selected: for the constraint) */ public Integer getWhiteImplicitReverseFkId() { checkSpecifiedProperty("whiteImplicitReverseFkId"); return _whiteImplicitReverseFkId; } /** * [set] WHITE_IMPLICIT_REVERSE_FK_ID: {UQ+, NotNull, INT(10)} <br> * @param whiteImplicitReverseFkId The value of the column 'WHITE_IMPLICIT_REVERSE_FK_ID'. (basically NotNull if update: for the constraint) */ public void setWhiteImplicitReverseFkId(Integer whiteImplicitReverseFkId) { registerModifiedProperty("whiteImplicitReverseFkId"); _whiteImplicitReverseFkId = whiteImplicitReverseFkId; } /** * [get] VALID_BEGIN_DATE: {+UQ, NotNull, DATE(10)} <br> * @return The value of the column 'VALID_BEGIN_DATE'. (basically NotNull if selected: for the constraint) */ public java.time.LocalDate getValidBeginDate() { checkSpecifiedProperty("validBeginDate"); return _validBeginDate; } /** * [set] VALID_BEGIN_DATE: {+UQ, NotNull, DATE(10)} <br> * @param validBeginDate The value of the column 'VALID_BEGIN_DATE'. (basically NotNull if update: for the constraint) */ public void setValidBeginDate(java.time.LocalDate validBeginDate) { registerModifiedProperty("validBeginDate"); _validBeginDate = validBeginDate; } /** * [get] VALID_END_DATE: {NotNull, DATE(10)} <br> * @return The value of the column 'VALID_END_DATE'. (basically NotNull if selected: for the constraint) */ public java.time.LocalDate getValidEndDate() { checkSpecifiedProperty("validEndDate"); return _validEndDate; } /** * [set] VALID_END_DATE: {NotNull, DATE(10)} <br> * @param validEndDate The value of the column 'VALID_END_DATE'. (basically NotNull if update: for the constraint) */ public void setValidEndDate(java.time.LocalDate validEndDate) { registerModifiedProperty("validEndDate"); _validEndDate = validEndDate; } }<|fim▁end|>
/** * To be unique by the unique column. <br> * You can update the entity by the key when entity update (NOT batch update).
<|file_name|>header_chain.rs<|end_file_name|><|fim▁begin|>// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Light client header chain. //! //! Unlike a full node's `BlockChain` this doesn't store much in the database. //! It stores candidates for the last 2048-4096 blocks as well as CHT roots for //! historical blocks all the way to the genesis. //! //! This is separate from the `BlockChain` for two reasons: //! - It stores only headers (and a pruned subset of them) //! - To allow for flexibility in the database layout once that's incorporated. // TODO: use DB instead of memory. DB Layout: just the contents of `candidates`/`headers` // use std::collections::{BTreeMap, HashMap}; use cht; use ethcore::block_status::BlockStatus; use ethcore::error::BlockError; use ethcore::ids::BlockId; use ethcore::views::HeaderView; use util::{Bytes, H256, U256, HeapSizeOf, Mutex, RwLock}; use smallvec::SmallVec; /// Store at least this many candidate headers at all times. /// Also functions as the delay for computing CHTs as they aren't /// relevant to any blocks we've got in memory. const HISTORY: u64 = 2048; /// Information about a block. #[derive(Debug, Clone)] pub struct BlockDescriptor { /// The block's hash pub hash: H256, /// The block's number pub number: u64, /// The block's total difficulty. pub total_difficulty: U256, } // candidate block description. struct Candidate { hash: H256, parent_hash: H256, total_difficulty: U256, } struct Entry { candidates: SmallVec<[Candidate; 3]>, // 3 arbitrarily chosen canonical_hash: H256, } impl HeapSizeOf for Entry { fn heap_size_of_children(&self) -> usize { match self.candidates.spilled() { false => 0, true => self.candidates.capacity() * ::std::mem::size_of::<Candidate>(), } } } /// Header chain. See module docs for more details. pub struct HeaderChain { genesis_header: Bytes, // special-case the genesis. candidates: RwLock<BTreeMap<u64, Entry>>, headers: RwLock<HashMap<H256, Bytes>>, best_block: RwLock<BlockDescriptor>, cht_roots: Mutex<Vec<H256>>, } impl HeaderChain { /// Create a new header chain given this genesis block. pub fn new(genesis: &[u8]) -> Self { let g_view = HeaderView::new(genesis); HeaderChain {<|fim▁hole|> hash: g_view.hash(), number: 0, total_difficulty: g_view.difficulty(), }), candidates: RwLock::new(BTreeMap::new()), headers: RwLock::new(HashMap::new()), cht_roots: Mutex::new(Vec::new()), } } /// Insert a pre-verified header. /// /// This blindly trusts that the data given to it is /// a) valid RLP encoding of a header and /// b) has sensible data contained within it. pub fn insert(&self, header: Bytes) -> Result<(), BlockError> { let view = HeaderView::new(&header); let hash = view.hash(); let number = view.number(); let parent_hash = view.parent_hash(); // hold candidates the whole time to guard import order. let mut candidates = self.candidates.write(); // find parent details. let parent_td = if number == 1 { let g_view = HeaderView::new(&self.genesis_header); g_view.difficulty() } else { candidates.get(&(number - 1)) .and_then(|entry| entry.candidates.iter().find(|c| c.hash == parent_hash)) .map(|c| c.total_difficulty) .ok_or_else(|| BlockError::UnknownParent(parent_hash))? }; let total_difficulty = parent_td + view.difficulty(); // insert headers and candidates entries. candidates.entry(number).or_insert_with(|| Entry { candidates: SmallVec::new(), canonical_hash: hash }) .candidates.push(Candidate { hash: hash, parent_hash: parent_hash, total_difficulty: total_difficulty, }); self.headers.write().insert(hash, header.clone()); // reorganize ancestors so canonical entries are first in their // respective candidates vectors. if self.best_block.read().total_difficulty < total_difficulty { let mut canon_hash = hash; for (&height, entry) in candidates.iter_mut().rev().skip_while(|&(height, _)| *height > number) { if height != number && entry.canonical_hash == canon_hash { break; } trace!(target: "chain", "Setting new canonical block {} for block height {}", canon_hash, height); let canon_pos = entry.candidates.iter().position(|x| x.hash == canon_hash) .expect("blocks are only inserted if parent is present; or this is the block we just added; qed"); // move the new canonical entry to the front and set the // era's canonical hash. entry.candidates.swap(0, canon_pos); entry.canonical_hash = canon_hash; // what about reorgs > cht::SIZE + HISTORY? // resetting to the last block of a given CHT should be possible. canon_hash = entry.candidates[0].parent_hash; } trace!(target: "chain", "New best block: ({}, {}), TD {}", number, hash, total_difficulty); *self.best_block.write() = BlockDescriptor { hash: hash, number: number, total_difficulty: total_difficulty, }; // produce next CHT root if it's time. let earliest_era = *candidates.keys().next().expect("at least one era just created; qed"); if earliest_era + HISTORY + cht::SIZE <= number { let mut values = Vec::with_capacity(cht::SIZE as usize); { let mut headers = self.headers.write(); for i in (0..cht::SIZE).map(|x| x + earliest_era) { let era_entry = candidates.remove(&i) .expect("all eras are sequential with no gaps; qed"); for ancient in &era_entry.candidates { headers.remove(&ancient.hash); } values.push(( ::rlp::encode(&i).to_vec(), ::rlp::encode(&era_entry.canonical_hash).to_vec(), )); } } let cht_root = ::util::triehash::trie_root(values); debug!(target: "chain", "Produced CHT {} root: {:?}", (earliest_era - 1) % cht::SIZE, cht_root); self.cht_roots.lock().push(cht_root); } } Ok(()) } /// Get a block header. In the case of query by number, only canonical blocks /// will be returned. pub fn get_header(&self, id: BlockId) -> Option<Bytes> { match id { BlockId::Earliest | BlockId::Number(0) => Some(self.genesis_header.clone()), BlockId::Hash(hash) => self.headers.read().get(&hash).map(|x| x.to_vec()), BlockId::Number(num) => { if self.best_block.read().number < num { return None } self.candidates.read().get(&num).map(|entry| entry.canonical_hash) .and_then(|hash| self.headers.read().get(&hash).map(|x| x.to_vec())) } BlockId::Latest | BlockId::Pending => { let hash = self.best_block.read().hash; self.headers.read().get(&hash).map(|x| x.to_vec()) } } } /// Get the nth CHT root, if it's been computed. /// /// CHT root 0 is from block `1..2048`. /// CHT root 1 is from block `2049..4096` /// and so on. /// /// This is because it's assumed that the genesis hash is known, /// so including it within a CHT would be redundant. pub fn cht_root(&self, n: usize) -> Option<H256> { self.cht_roots.lock().get(n).map(|h| h.clone()) } /// Get the genesis hash. pub fn genesis_hash(&self) -> H256 { ::util::Hashable::sha3(&self.genesis_header) } /// Get the best block's data. pub fn best_block(&self) -> BlockDescriptor { self.best_block.read().clone() } /// If there is a gap between the genesis and the rest /// of the stored blocks, return the first post-gap block. pub fn first_block(&self) -> Option<BlockDescriptor> { let candidates = self.candidates.read(); match candidates.iter().next() { None | Some((&1, _)) => None, Some((&height, entry)) => Some(BlockDescriptor { number: height, hash: entry.canonical_hash, total_difficulty: entry.candidates.iter().find(|x| x.hash == entry.canonical_hash) .expect("entry always stores canonical candidate; qed").total_difficulty, }) } } /// Get block status. pub fn status(&self, hash: &H256) -> BlockStatus { match self.headers.read().contains_key(hash) { true => BlockStatus::InChain, false => BlockStatus::Unknown, } } } impl HeapSizeOf for HeaderChain { fn heap_size_of_children(&self) -> usize { self.candidates.read().heap_size_of_children() + self.headers.read().heap_size_of_children() + self.cht_roots.lock().heap_size_of_children() } } #[cfg(test)] mod tests { use super::HeaderChain; use ethcore::ids::BlockId; use ethcore::header::Header; use ethcore::spec::Spec; #[test] fn basic_chain() { let spec = Spec::new_test(); let genesis_header = spec.genesis_header(); let chain = HeaderChain::new(&::rlp::encode(&genesis_header)); let mut parent_hash = genesis_header.hash(); let mut rolling_timestamp = genesis_header.timestamp(); for i in 1..10000 { let mut header = Header::new(); header.set_parent_hash(parent_hash); header.set_number(i); header.set_timestamp(rolling_timestamp); header.set_difficulty(*genesis_header.difficulty() * i.into()); chain.insert(::rlp::encode(&header).to_vec()).unwrap(); parent_hash = header.hash(); rolling_timestamp += 10; } assert!(chain.get_header(BlockId::Number(10)).is_none()); assert!(chain.get_header(BlockId::Number(9000)).is_some()); assert!(chain.cht_root(2).is_some()); assert!(chain.cht_root(3).is_none()); } #[test] fn reorganize() { let spec = Spec::new_test(); let genesis_header = spec.genesis_header(); let chain = HeaderChain::new(&::rlp::encode(&genesis_header)); let mut parent_hash = genesis_header.hash(); let mut rolling_timestamp = genesis_header.timestamp(); for i in 1..6 { let mut header = Header::new(); header.set_parent_hash(parent_hash); header.set_number(i); header.set_timestamp(rolling_timestamp); header.set_difficulty(*genesis_header.difficulty() * i.into()); chain.insert(::rlp::encode(&header).to_vec()).unwrap(); parent_hash = header.hash(); rolling_timestamp += 10; } { let mut rolling_timestamp = rolling_timestamp; let mut parent_hash = parent_hash; for i in 6..16 { let mut header = Header::new(); header.set_parent_hash(parent_hash); header.set_number(i); header.set_timestamp(rolling_timestamp); header.set_difficulty(*genesis_header.difficulty() * i.into()); chain.insert(::rlp::encode(&header).to_vec()).unwrap(); parent_hash = header.hash(); rolling_timestamp += 10; } } assert_eq!(chain.best_block().number, 15); { let mut rolling_timestamp = rolling_timestamp; let mut parent_hash = parent_hash; // import a shorter chain which has better TD. for i in 6..13 { let mut header = Header::new(); header.set_parent_hash(parent_hash); header.set_number(i); header.set_timestamp(rolling_timestamp); header.set_difficulty(*genesis_header.difficulty() * (i * i).into()); chain.insert(::rlp::encode(&header).to_vec()).unwrap(); parent_hash = header.hash(); rolling_timestamp += 11; } } let (mut num, mut canon_hash) = (chain.best_block().number, chain.best_block().hash); assert_eq!(num, 12); while num > 0 { let header: Header = ::rlp::decode(&chain.get_header(BlockId::Number(num)).unwrap()); assert_eq!(header.hash(), canon_hash); canon_hash = *header.parent_hash(); num -= 1; } } }<|fim▁end|>
genesis_header: genesis.to_owned(), best_block: RwLock::new(BlockDescriptor {
<|file_name|>timedmute.py<|end_file_name|><|fim▁begin|># Timed mute: !tm <player> <seconds> <reason> # default time 5 minutes, default reason None # by topologist June 30th 2012 from scheduler import Scheduler from commands import add, admin, get_player, join_arguments, name @name('tm') @admin def timed_mute(connection, *args): protocol = connection.protocol <|fim▁hole|> player = get_player(protocol, nick) if time < 0: raise ValueError() if not player.mute: TimedMute(player, time, reason) else: return '%s is already muted!' % nick add(timed_mute) class TimedMute(object): player = None time = None def __init__(self, player, time = 300, reason = 'None'): if time == 0: player.mute = True player.protocol.send_chat('%s was muted indefinitely (Reason: %s)' % ( player.name, reason), irc = True) return schedule = Scheduler(player.protocol) schedule.call_later(time, self.end) player.mute_schedule = schedule player.protocol.send_chat('%s was muted for %s seconds (Reason: %s)' % ( player.name, time, reason), irc = True) player.mute = True self.player = player self.time = time def end(self): self.player.mute = False message = '%s was unmuted after %s seconds' % (self.player.name, self.time) self.player.protocol.send_chat(message, irc = True) def apply_script(protocol, connection, config): class TimedMuteConnection(connection): mute_schedule = None def on_disconnect(self): if self.mute_schedule: del self.mute_schedule connection.on_disconnect(self) return protocol, TimedMuteConnection<|fim▁end|>
nick = args[0] time = int(args[1]) reason = join_arguments(args[2:])
<|file_name|>hhfit.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # hhfit.py --- # Description: # Author: # Maintainer: # Created: Tue May 21 16:31:56 2013 (+0530) # Commentary: # Functions for fitting common equations for Hodgkin-Huxley type gate # equations. import traceback import warnings import numpy as np import logging logger_ = logging.getLogger('moose.nml2.hhfit') try: import scipy.optimize as _SO except ImportError: raise RuntimeError("To use this feature/module, please install scipy") def exponential2(x, a, scale, x0, y0=0): res = a * np.exp((x - x0) / scale) + y0 #print('============ Calculating exponential2 for %s, a=%s, scale=%s, x0=%s, y0=%s; = %s'%(x, a, scale, x0, y0, res)) return res def exponential(x, a, k, x0, y0=0): res = a * np.exp(k * (x - x0)) + y0 #print('============ Calculating exponential for %s, a=%s, k=%s, x0=%s, y0=%s; = %s'%(x, a, k, x0, y0, res)) return res def sigmoid2(x, a, scale, x0, y0=0): res = a / (np.exp(-1 * (x - x0) / scale) + 1.0) + y0 #print('============ Calculating sigmoid for %s, a=%s, scale=%s, x0=%s, y0=%s; = %s'%(x, a, scale, x0, y0, res)) return res def sigmoid(x, a, k, x0, y0=0): res = a / (np.exp(k * (x - x0)) + 1.0) + y0 #print('============ Calculating sigmoid for %s, a=%s, k=%s, x0=%s, y0=%s; = %s'%(x, a, k, x0, y0, res)) return res def linoid2(x, a, scale, x0, y0=0): """The so called linoid function. Called explinear in neuroml.""" denominator = 1 - np.exp(-1 * (x - x0) / scale) # Linoid often includes a zero denominator - we need to fill those # points with interpolated values (interpolation is simpler than # finding limits). ret = (a / scale) * (x - x0) / denominator infidx = np.flatnonzero((ret == np.inf) | (ret == -np.inf)) if len(infidx) > 0: for ii in infidx: if ii == 0: ret[ii] = ret[ii + 1] - (ret[ii + 2] - ret[ii + 1]) elif ii == len(ret): ret[ii] = ret[ii - 1] + (ret[ii - 1] - ret[ii - 2]) else: ret[ii] = (ret[ii + 1] + ret[ii + 2]) * 0.5 res = ret + y0 #print('============ Calculating linoid2 for %s, a=%s, scale=%s, x0=%s, y0=%s; res=%s'%(x, a, scale, x0, y0,res)) return res def linoid(x, a, k, x0, y0=0): """The so called linoid function. Called explinear in neuroml.""" denominator = np.exp(k * (x - x0)) - 1.0 # Linoid often includes a zero denominator - we need to fill those # points with interpolated values (interpolation is simpler than # finding limits). ret = a * (x - x0) / denominator infidx = np.flatnonzero((ret == np.inf) | (ret == -np.inf)) if len(infidx) > 0: for ii in infidx: if ii == 0: ret[ii] = ret[ii + 1] - (ret[ii + 2] - ret[ii + 1]) elif ii == len(ret): ret[ii] = ret[ii - 1] + (ret[ii - 1] - ret[ii - 2]) else: ret[ii] = (ret[ii + 1] + ret[ii + 2]) * 0.5 res = ret + y0 #print('============ Calculating linoid for %s, a=%s, k=%s, x0=%s, y0=%s; res=%s'%(x, a, k, x0, y0,res)) return res def double_exp(x, a, k1, x1, k2, x2, y0=0): """For functions of the form: a / (exp(k1 * (x - x1)) + exp(k2 * (x - x2))) """ ret = np.zeros(len(x)) try: ret = a / (np.exp(k1 * (x - x1)) + np.exp(k2 * (x - x2))) + y0 except RuntimeWarning as e: logger_.warn(e) return ret # Map from the above functions to corresponding neuroml class fn_rate_map = { exponential: 'HHExpRate', sigmoid: 'HHSigmoidRate', linoid: 'HHExpLinearRate', double_exp: None, } # These are default starting parameter values fn_p0_map = { exponential: (1.0, -100, 20e-3, 0.0), sigmoid: (1.0, 1.0, 0.0, 0.0), linoid: (1.0, 1.0, 0.0, 0.0), double_exp: (1e-3, -1.0, 0.0, 1.0, 0.0, 0.0), } def randomized_curve_fit(fn, x, y, maxiter=10, best=True): """Repeatedly search for a good fit for common gate functions for HHtype channels with randomly generated initial parameter set. This function first tries with default p0 for fn. If that fails to find a good fit, (correlation coeff returned by curve_fit being inf is an indication of this), it goes on to generate random p0 arrays and try scipy.optimize.curve_fit using this p0 until it finds a good fit or the number of iterations reaches maxiter. Ideally we should be doing something like stochastic gradient descent, but I don't know if that might have performance issue in pure python. The random parameterization in the present function uses uniformly distributed random numbers within the half-open interval [min(x), max(x)). The reason for choosing this: the<|fim▁hole|> equations are usually within the domain of x. I also invert the second entry (p0[1], because it is always (one of) the scale factor(s) and usually 1/v for some v in the domain of x. I have not tested the utility of this inversion. Even without this inversion, with maxiter=100 this function is successful for the test cases. Parameters ---------- x: ndarray values of the independent variable y: ndarray sample values of the dependent variable maxiter: int maximum number of iterations best: bool if true, repeat curve_fit for maxiter and return the case of least squared error. Returns ------- The return value of scipy.optimize.curve_fit which succeed, or the last call to it if maxiter iterations is reached.. """ bad = True p0 = fn_p0_map[fn] p = None p_best = None min_err = 1e10 # A large value as placeholder for ii in range(maxiter): try: p = _SO.curve_fit(fn, x, y, p0=p0) except (RuntimeError, RuntimeWarning): p = None # The last entry returned by scipy.optimize.leastsq used by # curve_fit is 1, 2, 3 or 4 if it succeeds. bad = (p is None) or (p[1] == np.inf).any() if not bad: if not best: return p err = sum((y - fn(x, *tuple(p[0])))**2) if err < min_err: min_err = err p_best = p p0 = np.random.uniform(low=min(x), high=max(x), size=len(fn_p0_map[fn])) if p0[1] != 0.0: p0[1] = 1 / p0[1] # k = 1/v_scale - could help faster convergence if p_best is None: if p is not None: msg = p[-2] else: msg = '' warnings.warn( 'Maximum iteration %d reached. Could not find a decent fit. %s' % (maxiter, msg), RuntimeWarning) return p_best def find_ratefn(x, y, **kwargs): """Find the function that fits the rate function best. This will try exponential, sigmoid and linoid and return the best fit. Needed until NeuroML2 supports tables or MOOSE supports functions. Parameters ---------- x: 1D array independent variable. y: 1D array function values. **kwargs: keyword arguments passed to randomized_curve_fit. Returns ------- best_fn: function the best fit function. best_p: tuple the optimal parameter values for the best fit function. """ rms_error = 1e10 # arbitrarily setting this best_fn = None best_p = None for fn in fn_rate_map: p = randomized_curve_fit(fn, x, y, **kwargs) if p is None: continue popt = p[0] error = y - fn(x, *popt) erms = np.sqrt(np.mean(error**2)) # Ideally I want a fuzzy selection criterion here - a # preference for fewer parameters, but if the errors are # really small then we go for functions with more number of # parameters. Some kind of weighted decision would have been # nice. I am arbitrarily setting less than 0.1% relative error # as a strong argument for taking a longer parameter function # as a really better fit. Even with 1%, double exponential # betters detected sigmoid for sigmoid curve in test case. if erms < rms_error and ((best_p is None) or len(popt) <= len(best_p) or erms / (max(y) - min(y)) < 0.001): rms_error = erms best_fn = fn best_p = popt return (best_fn, best_p)<|fim▁end|>
offset used in the exponential parts of Boltzman-type/HH-type
<|file_name|>iwatchonline.py<|end_file_name|><|fim▁begin|>import urllib,urllib2,re,string,sys,os import xbmc, xbmcgui, xbmcaddon, xbmcplugin from resources.libs import main #Mash Up - by Mash2k3 2012. addon_id = 'plugin.video.movie25' selfAddon = xbmcaddon.Addon(id=addon_id) art = main.art prettyName = 'iWatchOnline' def AtoZiWATCHtv(): main.addDir('0-9','http://www.iwatchonline.to/tv-show?startwith=09&p=0',589,art+'/09.png') for i in string.ascii_uppercase: main.addDir(i,'http://www.iwatchonline.to/tv-show?startwith='+i.lower()+'&p=0',589,art+'/'+i.lower()+'.png') main.GA("Tvshows","A-ZTV") main.VIEWSB() def AtoZiWATCHm(): main.addDir('0-9','http://www.iwatchonline.to/movies?startwith=09&p=0',587,art+'/09.png') for i in string.ascii_uppercase: main.addDir(i,'http://www.iwatchonline.to/movies?startwith='+i.lower()+'&p=0',587,art+'/'+i.lower()+'.png') main.GA("Movies","A-ZM") main.VIEWSB() def iWatchMAIN(): main.addDir('Movies','http://www.iwatchonline.org/',586,art+'/iwatchm.png') main.addDir('Tv Shows','http://www.iwatchonline.org/',585,art+'/iwatcht.png') main.addDir('Todays Episodes','http://www.iwatchonline.to/tv-schedule',592,art+'/iwatcht.png') main.GA("Plugin","iWatchonline") main.VIEWSB2() def iWatchMOVIES(): main.addDir('Search Movies','http://www.iwatchonline.to',644,art+'/search.png') main.addDir('A-Z','http://www.iwatchonline.to',595,art+'/az.png') main.addDir('Popular','http://www.iwatchonline.to/movies?sort=popular&p=0',587,art+'/iwatchm.png') main.addDir('Latest Added','http://www.iwatchonline.to/movies?sort=latest&p=0',587,art+'/iwatchm.png') main.addDir('Featured Movies','http://www.iwatchonline.to/movies?sort=featured&p=0',587,art+'/iwatchm.png') main.addDir('Latest HD Movies','http://www.iwatchonline.to/movies?quality=hd&sort=latest&p=0',587,art+'/iwatchm.png') main.addDir('Upcoming','http://www.iwatchonline.to/movies?sort=upcoming&p=0',587,art+'/iwatchm.png') main.addDir('Genre','http://www.iwatchonline.to',596,art+'/genre.png') main.GA("iWatchonline","Movies") main.VIEWSB2() def iWatchTV(): main.addDir('Search TV Shows','http://www.iwatchonline.to',642,art+'/search.png') main.addDir('A-Z','http://www.iwatchonline.to',593,art+'/az.png') main.addDir('Todays Episodes','http://www.iwatchonline.to/tv-schedule',592,art+'/iwatcht.png') main.addDir('Featured Shows','http://www.iwatchonline.to/tv-show?sort=featured&p=0',589,art+'/iwatcht.png') main.addDir('Popular Shows','http://www.iwatchonline.to/tv-show?sort=popular&p=0',589,art+'/iwatcht.png') main.addDir('Latest Additions','http://www.iwatchonline.to/tv-show?sort=latest&p=0',589,art+'/iwatcht.png') main.addDir('Genre','http://www.iwatchonline.to',594,art+'/genre.png') main.GA("iWatchonline","Tvshows") main.VIEWSB2() def SearchhistoryTV(): seapath=os.path.join(main.datapath,'Search') SeaFile=os.path.join(seapath,'SearchHistoryTv') if not os.path.exists(SeaFile): SEARCHTV() else: main.addDir('Search TV Shows','###',643,art+'/search.png') main.addDir('Clear History',SeaFile,128,art+'/cleahis.png') thumb=art+'/link.png' searchis=re.compile('search="(.+?)",').findall(open(SeaFile,'r').read()) for seahis in reversed(searchis): seahis=seahis.replace('%20',' ') url=seahis main.addDir(seahis,url,643,thumb) def superSearch(encode,type): try: if type=='Movies': type='m' else: type='t' returnList=[] search_url = 'http://www.iwatchonline.to/search' from t0mm0.common.net import Net as net search_content = net().http_POST(search_url, { 'searchquery' : encode, 'searchin' : type} ).content.encode('utf-8') r = re.findall('(?s)<table(.+?)</table>',search_content) r=main.unescapes(r[0]) match=re.compile('<img.+?src=\"(.+?)\".+?<a.+?href=\"(.+?)\">(.+?)</a>').findall(r) for thumb,url,name in match: if type=='m': returnList.append((name,prettyName,url,thumb,588,True)) else: returnList.append((name,prettyName,url,thumb,590,True)) return returnList except: return [] def SEARCHTV(murl = ''): encode = main.updateSearchFile(murl,'TV') if not encode: return False search_url = 'http://www.iwatchonline.to/search' from t0mm0.common.net import Net as net search_content = net().http_POST(search_url, { 'searchquery' : encode, 'searchin' : 't'} ).content.encode('utf-8') r = re.findall('(?s)<table(.+?)</table>',search_content) r=main.unescapes(r[0]) match=re.compile('<img[^>]+?src="([^"]+?)\".+?<a[^>]+?href="([^"]+?)">([^<]+?)</a>').findall(r) for thumb,url,name in match: main.addDirT(name,url,590,thumb,'','','','','') main.GA("iWatchonline","Search") def SearchhistoryM(): seapath=os.path.join(main.datapath,'Search') SeaFile=os.path.join(seapath,'SearchHistory25') if not os.path.exists(SeaFile): SEARCHM('') else: main.addDir('Search Movies','###',645,art+'/search.png') main.addDir('Clear History',SeaFile,128,art+'/cleahis.png') thumb=art+'/link.png' searchis=re.compile('search="(.+?)",').findall(open(SeaFile,'r').read()) for seahis in reversed(searchis): seahis=seahis.replace('%20',' ') url=seahis main.addDir(seahis,url,645,thumb) def SEARCHM(murl): encode = main.updateSearchFile(murl,'Movies') if not encode: return False search_url = 'http://www.iwatchonline.to/search' from t0mm0.common.net import Net as net search_content = net().http_POST(search_url, { 'searchquery' : encode, 'searchin' : 'm'} ).content.encode('utf-8') r = re.findall('(?s)<table(.+?)</table>',search_content) r=main.unescapes(r[0]) match=re.compile('<img.+?src=\"(.+?)\".+?<a.+?href=\"(.+?)\">(.+?)</a>').findall(r) dialogWait = xbmcgui.DialogProgress() ret = dialogWait.create('Please wait until Movie list is cached.') totalLinks = len(match) loadedLinks = 0<|fim▁hole|> for thumb,url,name in match: main.addDirM(name,url,588,thumb,'','','','','') loadedLinks = loadedLinks + 1 percent = (loadedLinks * 100)/totalLinks remaining_display = 'Movies loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(percent,'[B]Will load instantly from now on[/B]',remaining_display) if dialogWait.iscanceled(): return False dialogWait.close() del dialogWait main.GA("iWatchonline","Search") def ENTYEAR(): dialog = xbmcgui.Dialog() d = dialog.numeric(0, 'Enter Year') if d: encode=urllib.quote(d) if encode < '2014' and encode > '1900': surl='http://www.iwatchonline.to/main/content_more/movies/?year='+encode+'&start=0' iWatchLISTMOVIES(surl) else: dialog = xbmcgui.Dialog() ret = dialog.ok('Wrong Entry', 'Must enter year in four digit format like 1999','Enrty must be between 1900 and 2014') def GotoPage(url): dialog = xbmcgui.Dialog() r=re.findall('http://www.iwatchonline.to/movies(.+?)&p=.+?',url) d = dialog.numeric(0, 'Please Enter Page number.') if d: temp=int(d)-1 page= int(temp)*25 encode=str(page) url='http://www.iwatchonline.to/movies'+r[0] surl=url+'&p='+encode iWatchLISTMOVIES(surl) else: dialog = xbmcgui.Dialog() xbmcplugin.endOfDirectory(int(sys.argv[1]), False, False) return False def iWatchGenreTV(): link=main.OPENURL('http://www.iwatchonline.to/tv-show') link=link.replace('\r','').replace('\n','').replace('\t','').replace('&nbsp;','') match=re.compile('<li.+?a href=".?gener=([^<]+)">(.+?)</a>.+?/li>').findall(link) for url,genre in match: genre=genre.replace(' ','') if not 'Adult' in genre: main.addDir(genre,'http://www.iwatchonline.to/tv-show?sort=popular&gener='+url+'',589,art+'/folder.png') main.GA("Tvshows","GenreT") def iWatchGenreM(): link=main.OPENURL('http://www.iwatchonline.to/movies') link=link.replace('\r','').replace('\n','').replace('\t','').replace('&nbsp;','') match=re.compile('<li.+?a href=".?gener=([^<]+)">(.+?)</a>.+?/li>').findall(link) for url,genre in match: genre=genre.replace(' ','') if not 'Adult' in genre: main.addDir(genre,'http://www.iwatchonline.to/movies?sort=popular&gener='+url+'&p=0',587,art+'/folder.png') main.GA("Movies","GenreM") def iWatchYearM(): main.addDir('2013','http://www.iwatchonline.to/main/content_more/movies/?year=2013&start=0',587,art+'/year.png') main.addDir('2012','http://www.iwatchonline.to/main/content_more/movies/?year=2012&start=0',587,art+'/2012.png') main.addDir('2011','http://www.iwatchonline.to/main/content_more/movies/?year=2011&start=0',587,art+'/2011.png') main.addDir('2010','http://www.iwatchonline.to/main/content_more/movies/?year=2010&start=0',587,art+'/2010.png') main.addDir('2009','http://www.iwatchonline.to/main/content_more/movies/?year=2009&start=0',587,art+'/2009.png') main.addDir('2008','http://www.iwatchonline.to/main/content_more/movies/?year=2008&start=0',587,art+'/2008.png') main.addDir('2007','http://www.iwatchonline.to/main/content_more/movies/?year=2007&start=0',587,art+'/2007.png') main.addDir('2006','http://www.iwatchonline.to/main/content_more/movies/?year=2006&start=0',587,art+'/2006.png') main.addDir('2005','http://www.iwatchonline.to/main/content_more/movies/?year=2005&start=0',587,art+'/2005.png') main.addDir('2004','http://www.iwatchonline.to/main/content_more/movies/?year=2004&start=0',587,art+'/2004.png') main.addDir('2003','http://www.iwatchonline.to/main/content_more/movies/?year=2003&start=0',587,art+'/2003.png') main.addDir('Enter Year','iwatchonline',653,art+'/enteryear.png') def iWatchLISTMOVIES(murl): main.GA("Movies","List") link=main.OPENURL(murl) link=link.replace('\r','').replace('\n','').replace('\t','').replace('&nbsp;','') videos = re.search('<ul class="thumbnails">(.+?)</ul>', link) if videos: videos = videos.group(1) match=re.compile('<li.+?<a.+?href=\"(.+?)\".+?<img.+?src=\"(.+?)\".+?<div class=\"title.+?>(.+?)<div').findall(videos) dialogWait = xbmcgui.DialogProgress() ret = dialogWait.create('Please wait until Movie list is cached.') totalLinks = len(match) loadedLinks = 0 remaining_display = 'Movies loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(0,'[B]Will load instantly from now on[/B]',remaining_display) xbmc.executebuiltin("XBMC.Dialog.Close(busydialog,true)") for url,thumb,name in match: main.addDirIWO(name,url,588,thumb,'','','','','') loadedLinks = loadedLinks + 1 percent = (loadedLinks * 100)/totalLinks remaining_display = 'Movies loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(percent,'[B]Will load instantly from now on[/B]',remaining_display) if (dialogWait.iscanceled()): return False dialogWait.close() del dialogWait if len(match)==25: paginate=re.compile('([^<]+)&p=([^<]+)').findall(murl) for purl,page in paginate: i=int(page)+25 pg=(int(page)/25)+2 # if pg >2: # main.addDir('[COLOR red]Home[/COLOR]','',2000,art+'/home.png') main.addDir('[COLOR red]Enter Page #[/COLOR]',murl,654,art+'/gotopage.png') main.addDir('[COLOR blue]Page '+ str(pg)+'[/COLOR]',purl+'&p='+str(i),587,art+'/next2.png') xbmcplugin.setContent(int(sys.argv[1]), 'Movies') main.VIEWS() def iWatchToday(murl): main.GA("Tvshows","TodaysList") link=main.OPENURL(murl) daysback = 2 for x in range(0, daysback): match = re.findall(r"</i></a> <a href='(.*?)'" , link) if(match): link = link + main.OPENURL("http://www.iwatchonline.to/tv-schedule" + match[x]) link=link.replace('\r','').replace('\n','').replace('\t','').replace('&nbsp;','') link = re.sub('>\s*','>',link) link = re.sub('\s*<','<',link) match=re.compile('<img src="([^"]+?)"[^<]+?<br /><a href="([^"]+?)">(.+?)</a></td><td.+?>([^<]+?)</td><td.+?>([^<]+?)</td>.*?>(\d{,2}) Link\(s\)', re.M).findall(link) dialogWait = xbmcgui.DialogProgress() ret = dialogWait.create('Please wait until Show list is cached.') totalLinks = len(match) loadedLinks = 0 remaining_display = 'Episodes loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(0,'[B]Will load instantly from now on[/B]',remaining_display) xbmc.executebuiltin("XBMC.Dialog.Close(busydialog,true)") for thumb,url,name,episea,epiname,active in match: if(active == '0'): totalLinks -= 1 continue name=name.strip() thumb=thumb.strip() url=url.strip() episea=episea.strip() epiname=epiname.strip() name=name.replace('(','').replace(')','') name=name.replace('(\d{4})','') main.addDirTE(name+' '+episea+' [COLOR blue]'+epiname+'[/COLOR]',url,588,thumb,'','','','','') loadedLinks = loadedLinks + 1 percent = (loadedLinks * 100)/totalLinks remaining_display = 'Episodes loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(percent,'[B]Will load instantly from now on[/B]',remaining_display) if (dialogWait.iscanceled()): return False dialogWait.close() del dialogWait def iWatchLISTSHOWS(murl): main.GA("Tvshows","List") link=main.OPENURL(murl) link=link.replace('\r','').replace('\n','').replace('\t','').replace('&nbsp;','') videos = re.search('<ul class="thumbnails">(.+?)</ul>', link) if videos: videos = videos.group(1) match=re.compile('<li.+?<a[^>]+?href=\"([^"]+?)\".+?<img[^>]+?src=\"([^"]+?)\".+?<div class=\"title[^>]+?>([^>]+?)<div').findall(videos) for url,thumb,name in match: main.addDirT(name,url,590,thumb,'','','','','') if len(match)==25: paginate=re.compile('([^<]+)&p=([^<]+)').findall(murl) for purl,page in paginate: i=int(page)+25 main.addDir('[COLOR blue]Next[/COLOR]',purl+'&p='+str(i),589,art+'/next2.png') xbmcplugin.setContent(int(sys.argv[1]), 'Movies') main.VIEWS() def iWatchSeason(name,murl,thumb): link=main.OPENURL(murl) link=link.replace('\r','').replace('\n','').replace('\t','').replace('&nbsp;','') match=re.compile('<h5><i.+?</i>.*?(.+?)</h5>').findall(link) for season in match: main.addDir(name.strip()+' '+season.strip(),murl,591,thumb,'') def GET_HTML(url): req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3') response = urllib2.urlopen(req) link = response.read() response.close() link = link.replace('\\','') return link def _decode_callback(matches): id = matches.group(1) try: return unichr(int(id)) except: return id def decode(data): return re.sub("&#(\d+)(;|(?=\s))", _decode_callback, data).strip() def PANEL_REPLACER(content): panel_exists = True panel_id = 0 while panel_exists == True: panel_name = "panel-id." + str(panel_id) panel_search_pattern = "(?s)\"" + panel_name + "\"\:\[\{(.+?)\}\]" panel_data = re.search(panel_search_pattern, content) if panel_data: panel_data = panel_data.group(1) content = re.sub("begin " + panel_name, "-->" + panel_data + "<!--", content) content = re.sub(panel_search_pattern, "panel used", content) panel_id = panel_id + 1 else: panel_exists = False content = main.unescapes(content) content = re.sub("\\\"", "\"", content) from resources.universal import _common as univ_common content = univ_common.str_conv(decode(content)) return content def iWatchEpisode(mname,murl): seanum = mname.split('Season ')[1] tv_content=main.OPENURL(murl) link = PANEL_REPLACER(tv_content) descs=re.compile('<meta name="description" content="(.+?)">').findall(link) if len(descs)>0: desc=descs[0] else: desc='' thumbs=re.compile('<div class="movie-cover span2"><img src="(.+?)" alt=".+?" class=".+?" />').findall(link) if len(thumbs)>0: thumb=thumbs[0] else: thumb='' episodes = re.search('(?sim)season'+seanum+'(.+?)</table>', link) if episodes: episodes = episodes.group(1) match=re.compile('<a[^>]+?href=\"([^"]+?)\".+?</i>([^<]+?)</a>.+?<td>([^<]+?)</td>').findall(episodes) dialogWait = xbmcgui.DialogProgress() ret = dialogWait.create('Please wait until Show list is cached.') totalLinks = len(match) loadedLinks = 0 remaining_display = 'Episodes loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(0,'[B]Will load instantly from now on[/B]',remaining_display) for url,epi,name in match: mname=mname.replace('(','').replace(')','') mname = re.sub(" \d{4}", "", mname) sea=re.compile('s'+str(seanum)).findall(url) if len(sea)>0: main.addDirTE(mname.strip()+' '+epi.strip()+' [COLOR blue]'+name.strip()+'[/COLOR]',url,588,thumb,desc,'','','','') loadedLinks = loadedLinks + 1 percent = (loadedLinks * 100)/totalLinks remaining_display = 'Episodes loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(percent,'[B]Will load instantly from now on[/B]',remaining_display) if (dialogWait.iscanceled()): return False dialogWait.close() del dialogWait if selfAddon.getSetting('auto-view') == 'true': xbmc.executebuiltin("Container.SetViewMode(%s)" % selfAddon.getSetting('episodes-view')) def GetUrl(url): link=main.OPENURL(url) link=link.replace('\r','').replace('\n','').replace('\t','').replace('&nbsp;','') match=re.compile('<iframe.+?src=\"(.+?)\"').findall(link) link=match[0] return link def iWatchLINK(mname,url): link=main.OPENURL(url) movie_content = main.unescapes(link) movie_content = re.sub("\\\"", "\"", movie_content) movie_content=movie_content.replace('\'','') from resources.universal import _common as univ_common link2 = univ_common.str_conv(decode(movie_content)) if selfAddon.getSetting("hide-download-instructions") != "true": main.addLink("[COLOR red]For Download Options, Bring up Context Menu Over Selected Link.[/COLOR]",'','') links = re.search('<tbody>(.+?)</tbody>', link2) if links: links = links.group(1) match=re.compile('<a href="([^"]+?)".+?<img.+?> ([^<]+?)</a>.+?<td>.+?<td>.+?<td>([^<]+?)</td>', re.DOTALL).findall(links) import urlresolver for url, name, qua in match: name=name.replace(' ','') if name[0:1]=='.': name=name[1:] name=name.split('.')[0] hosted_media = urlresolver.HostedMediaFile(host=name.lower(), media_id=name.lower()) if hosted_media: main.addDown2(mname+' [COLOR red]('+qua+')[/COLOR]'+' [COLOR blue]'+name.upper()+'[/COLOR]',url,649,art+'/hosts/'+name.lower()+'.png',art+'/hosts/'+name.lower()+'.png') def iWatchLINKB(mname,url): main.GA("iWatchonline","Watched") ok=True hname=mname xbmc.executebuiltin("XBMC.Notification(Please Wait!,Opening Link,3000)") mname=mname.split(' [COLOR red]')[0] r = re.findall('Season(.+?)Episode([^<]+)',mname) if r: infoLabels =main.GETMETAEpiT(mname,'','') video_type='episode' season=infoLabels['season'] episode=infoLabels['episode'] else: infoLabels =main.GETMETAT(mname,'','','') video_type='movie' season='' episode='' img=infoLabels['cover_url'] fanart =infoLabels['backdrop_url'] imdb_id=infoLabels['imdb_id'] infolabels = { 'supports_meta' : 'true', 'video_type':video_type, 'name':str(infoLabels['title']), 'imdb_id':str(infoLabels['imdb_id']), 'season':str(season), 'episode':str(episode), 'year':str(infoLabels['year']) } link=main.OPENURL(url) link=main.unescapes(link) match=re.compile('<(?:iframe|pagespeed_iframe).+?src=\"(.+?)\"').findall(link) try : xbmc.executebuiltin("XBMC.Notification(Please Wait!,Resolving Link,3000)") stream_url = main.resolve_url(match[0]) if stream_url == False: return infoL={'Title': infoLabels['title'], 'Plot': infoLabels['plot'], 'Genre': infoLabels['genre'],'originalTitle': main.removeColoredText(infoLabels['title'])} # play with bookmark from resources.universal import playbackengine player = playbackengine.PlayWithoutQueueSupport(resolved_url=stream_url, addon_id=addon_id, video_type=video_type, title=str(infoLabels['title']),season=str(season), episode=str(episode), year=str(infoLabels['year']),img=img,infolabels=infoL, watchedCallbackwithParams=main.WatchedCallbackwithParams,imdb_id=imdb_id) #WatchHistory if selfAddon.getSetting("whistory") == "true": from resources.universal import watchhistory wh = watchhistory.WatchHistory('plugin.video.movie25') wh.add_item(hname+' '+'[COLOR green]'+prettyName+'[/COLOR]', sys.argv[0]+sys.argv[2], infolabels=infolabels, img=str(img), fanart=str(fanart), is_folder=False) player.KeepAlive() return ok except Exception, e: if stream_url != False: main.ErrorReport(e) return ok<|fim▁end|>
remaining_display = 'Movies loaded :: [B]'+str(loadedLinks)+' / '+str(totalLinks)+'[/B].' dialogWait.update(0,'[B]Will load instantly from now on[/B]',remaining_display) xbmc.executebuiltin("XBMC.Dialog.Close(busydialog,true)")
<|file_name|>routing.hpp<|end_file_name|><|fim▁begin|>/**<|fim▁hole|> * @author nocotan * @date 2016/11/4 */ #ifndef ROUTING_HPP #define ROUTING_HPP #include <functional> #include <string> namespace ots { /** * @struct header * @brief header */ struct header { const std::string name; const std::string value; }; /** * @struct request * @brief request */ struct request { const std::string method; const std::string path; const std::string source; const std::string destination; const std::string body; const std::vector<header> headers; }; /** * @struct otusRouting * @brief routing */ struct otusRouting { const std::string route; const std::string method; const std::function<std::string(request)> action; }; } #endif<|fim▁end|>
* @file routing.hpp * @brief this file implements the application routing.
<|file_name|>bitmap_image.hpp<|end_file_name|><|fim▁begin|>/* *************************************************************************** * * * Platform Independent * * Bitmap Image Reader Writer Library * * * * Author: Arash Partow - 2002 * * URL: http://partow.net/programming/bitmap/index.html * * * * Note: This library only supports 24-bits per pixel bitmap format files. * * * * Copyright notice: * * Free use of the Platform Independent Bitmap Image Reader Writer Library * * is permitted under the guidelines and in accordance with the most * * current version of the Common Public License. * * http://www.opensource.org/licenses/cpl1.0.php * * * *************************************************************************** */ #ifndef INCLUDE_BITMAP_IMAGE_HPP #define INCLUDE_BITMAP_IMAGE_HPP #include <algorithm> #include <cmath> #include <cstdlib> #include <fstream> #include <iostream> #include <iterator> #include <limits> #include <string> class bitmap_image { public: enum channel_mode { rgb_mode = 0, bgr_mode = 1 }; enum color_plane { blue_plane = 0, green_plane = 1, red_plane = 2 }; bitmap_image() : file_name_(""), data_(0), length_(0), width_(0), height_(0), row_increment_(0), bytes_per_pixel_(3), channel_mode_(bgr_mode) {} bitmap_image(const std::string& filename) : file_name_(filename), data_(0), length_(0), width_(0), height_(0), row_increment_(0), bytes_per_pixel_(0), channel_mode_(bgr_mode) { load_bitmap(); } bitmap_image(const unsigned int width, const unsigned int height) : file_name_(""), data_(0), length_(0), width_(width), height_(height), row_increment_(0), bytes_per_pixel_(3), channel_mode_(bgr_mode) { create_bitmap(); } bitmap_image(const bitmap_image& image) : file_name_(image.file_name_), data_(0), width_(image.width_), height_(image.height_), row_increment_(0), bytes_per_pixel_(3), channel_mode_(bgr_mode) { create_bitmap(); std::copy(image.data_, image.data_ + image.length_, data_); } ~bitmap_image() { delete[] data_; } bitmap_image& operator=(const bitmap_image& image) { if (this != &image) { file_name_ = image.file_name_; bytes_per_pixel_ = image.bytes_per_pixel_; width_ = image.width_; height_ = image.height_; row_increment_ = 0; channel_mode_ = image.channel_mode_; create_bitmap(); std::copy(image.data_, image.data_ + image.length_, data_); } return *this; } inline bool operator!() { return (data_ == 0) || (length_ == 0) || (width_ == 0) || (height_ == 0) || (row_increment_ == 0); } inline void clear(const unsigned char v = 0x00) { std::fill(data_, data_ + length_, v); } inline unsigned char red_channel(const unsigned int x, const unsigned int y) const { return data_[(y * row_increment_) + (x * bytes_per_pixel_ + 2)]; } inline unsigned char green_channel(const unsigned int x, const unsigned int y) const { return data_[(y * row_increment_) + (x * bytes_per_pixel_ + 1)]; } inline unsigned char blue_channel(const unsigned int x, const unsigned int y) const { return data_[(y * row_increment_) + (x * bytes_per_pixel_ + 0)]; } inline void red_channel(const unsigned int x, const unsigned int y, const unsigned char value) { data_[(y * row_increment_) + (x * bytes_per_pixel_ + 2)] = value; } inline void green_channel(const unsigned int x, const unsigned int y, const unsigned char value) { data_[(y * row_increment_) + (x * bytes_per_pixel_ + 1)] = value; } inline void blue_channel(const unsigned int x, const unsigned int y, const unsigned char value) { data_[(y * row_increment_) + (x * bytes_per_pixel_ + 0)] = value; } inline unsigned char* row(unsigned int row_index) const { return data_ + (row_index * row_increment_); } inline void get_pixel(const unsigned int x, const unsigned int y, unsigned char& red, unsigned char& green, unsigned char& blue) { const unsigned int y_offset = y * row_increment_; const unsigned int x_offset = x * bytes_per_pixel_; blue = data_[y_offset + x_offset + 0]; green = data_[y_offset + x_offset + 1]; red = data_[y_offset + x_offset + 2]; } inline void set_pixel(const unsigned int x, const unsigned int y, const unsigned char red, const unsigned char green, const unsigned char blue) { const unsigned int y_offset = y * row_increment_; const unsigned int x_offset = x * bytes_per_pixel_; data_[y_offset + x_offset + 0] = blue; data_[y_offset + x_offset + 1] = green; data_[y_offset + x_offset + 2] = red; } inline bool copy_from(const bitmap_image& image) { if ((image.height_ != height_) || (image.width_ != width_)) { return false; } std::copy(image.data_, image.data_ + image.length_, data_); return true; } inline bool copy_from(const bitmap_image& source_image, const unsigned int& x_offset, const unsigned int& y_offset) { if ((x_offset + source_image.width_) > width_) { return false; } if ((y_offset + source_image.height_) > height_) { return false; } for (unsigned int y = 0; y < source_image.height_; ++y) { unsigned char* itr1 = row(y + y_offset) + x_offset * bytes_per_pixel_; const unsigned char* itr2 = source_image.row(y); const unsigned char* itr2_end = itr2 + source_image.width_ * bytes_per_pixel_; std::copy(itr2, itr2_end, itr1); } return true; } inline bool region(const unsigned int& x, const unsigned int& y, const unsigned int& width, const unsigned int& height, bitmap_image& dest_image) { if ((x + width) > width_) { return false; } if ((y + height) > height_) { return false; } if ((dest_image.width_ < width_) || (dest_image.height_ < height_)) { dest_image.setwidth_height(width, height); } for (unsigned int r = 0; r < height; ++r) { unsigned char* itr1 = row(r + y) + x * bytes_per_pixel_; unsigned char* itr1_end = itr1 + (width * bytes_per_pixel_); unsigned char* itr2 = dest_image.row(r); std::copy(itr1, itr1_end, itr2); } return true; } inline bool set_region(const unsigned int& x, const unsigned int& y, const unsigned int& width, const unsigned int& height, const unsigned char& value) { if ((x + width) > width_) { return false; } if ((y + height) > height_) { return false; } for (unsigned int r = 0; r < height; ++r) { unsigned char* itr = row(r + y) + x * bytes_per_pixel_; unsigned char* itr_end = itr + (width * bytes_per_pixel_); std::fill(itr, itr_end, value); } return true; } inline bool set_region(const unsigned int& x, const unsigned int& y, const unsigned int& width, const unsigned int& height, const color_plane color, const unsigned char& value) { if ((x + width) > width_) { return false; } if ((y + height) > height_) { return false; } const unsigned int color_plane_offset = offset(color); for (unsigned int r = 0; r < height; ++r) { unsigned char* itr = row(r + y) + x * bytes_per_pixel_ + color_plane_offset; unsigned char* itr_end = itr + (width * bytes_per_pixel_); while (itr != itr_end) { *itr = value; itr += bytes_per_pixel_; } } return true; } inline bool set_region(const unsigned int& x, const unsigned int& y, const unsigned int& width, const unsigned int& height, const unsigned char& red, const unsigned char& green, const unsigned char& blue) { if ((x + width) > width_) { return false; } if ((y + height) > height_) { return false; } for (unsigned int r = 0; r < height; ++r) { unsigned char* itr = row(r + y) + x * bytes_per_pixel_; unsigned char* itr_end = itr + (width * bytes_per_pixel_); while (itr != itr_end) { *(itr++) = blue; *(itr++) = green; *(itr++) = red; } } return true; } void reflective_image(bitmap_image& image) { image.setwidth_height(3 * width_, 3 * height_, true); image.copy_from(*this, width_, height_); vertical_flip(); image.copy_from(*this, width_, 0); image.copy_from(*this, width_, 2 * height_); vertical_flip(); horizontal_flip(); image.copy_from(*this, 0, height_); image.copy_from(*this, 2 * width_, height_); horizontal_flip(); } inline unsigned int width() const { return width_; } inline unsigned int height() const { return height_; } inline unsigned int bytes_per_pixel() const { return bytes_per_pixel_; } inline unsigned int pixel_count() const { return width_ * height_; } inline void setwidth_height(const unsigned int width, const unsigned int height, const bool clear = false) { delete[] data_; data_ = 0; width_ = width; height_ = height; create_bitmap(); if (clear) { std::fill(data_, data_ + length_, 0x00); } } void save_image(const std::string& file_name) { std::ofstream stream(file_name.c_str(), std::ios::binary); if (!stream) { std::cout << "bitmap_image::save_image(): Error - Could not open file " << file_name << " for writing!" << std::endl; return; } bitmap_file_header bfh; bitmap_information_header bih; bih.width = width_; bih.height = height_; bih.bit_count = static_cast<unsigned short>(bytes_per_pixel_ << 3); bih.clr_important = 0; bih.clr_used = 0; bih.compression = 0; bih.planes = 1; bih.size = 40; bih.x_pels_per_meter = 0; bih.y_pels_per_meter = 0; bih.size_image = (((bih.width * bytes_per_pixel_) + 3) & 0x0000FFFC) * bih.height; bfh.type = 19778; bfh.size = 55 + bih.size_image; bfh.reserved1 = 0; bfh.reserved2 = 0; bfh.off_bits = bih.struct_size() + bfh.struct_size(); write_bfh(stream, bfh); write_bih(stream, bih); unsigned int padding = (4 - ((3 * width_) % 4)) % 4; char padding_data[4] = {0x0, 0x0, 0x0, 0x0}; for (unsigned int i = 0; i < height_; ++i) { unsigned char* data_ptr = data_ + (row_increment_ * (height_ - i - 1)); stream.write(reinterpret_cast<char*>(data_ptr), sizeof(unsigned char) * bytes_per_pixel_ * width_); stream.write(padding_data, padding); } stream.close(); } inline void set_all_ith_bits_low(const unsigned int bitr_index) { unsigned char mask = static_cast<unsigned char>(~(1 << bitr_index)); for (unsigned char* itr = data_; itr != data_ + length_; ++itr) { *itr &= mask; } } inline void set_all_ith_bits_high(const unsigned int bitr_index) { unsigned char mask = static_cast<unsigned char>(1 << bitr_index); for (unsigned char* itr = data_; itr != data_ + length_; ++itr) { *itr |= mask; } } inline void set_all_ith_channels(const unsigned int& channel, const unsigned char& value) { for (unsigned char* itr = (data_ + channel); itr < (data_ + length_); itr += bytes_per_pixel_) { *itr = value; } } inline void set_channel(const color_plane color, const unsigned char& value) { for (unsigned char* itr = (data_ + offset(color)); itr < (data_ + length_); itr += bytes_per_pixel_) { *itr = value; } } inline void ror_channel(const color_plane color, const unsigned int& ror) { for (unsigned char* itr = (data_ + offset(color)); itr < (data_ + length_); itr += bytes_per_pixel_) { *itr = static_cast<unsigned char>(((*itr) >> ror) | ((*itr) << (8 - ror))); } } inline void set_all_channels(const unsigned char& value) { for (unsigned char* itr = data_; itr < (data_ + length_);) { *(itr++) = value; } } inline void set_all_channels(const unsigned char& r_value, const unsigned char& g_value, const unsigned char& b_value) { for (unsigned char* itr = (data_ + 0); itr < (data_ + length_); itr += bytes_per_pixel_) { *(itr + 0) = b_value; *(itr + 1) = g_value; *(itr + 2) = r_value; } } inline void invert_color_planes() { for (unsigned char* itr = data_; itr < (data_ + length_); *itr = ~(*itr), ++itr) ; } inline void add_to_color_plane(const color_plane color, const unsigned char& value) { for (unsigned char* itr = (data_ + offset(color)); itr < (data_ + length_); (*itr) += value, itr += bytes_per_pixel_) ; } inline void convert_to_grayscale() { double r_scaler = 0.299; double g_scaler = 0.587; double b_scaler = 0.114; if (rgb_mode == channel_mode_) { double tmp = r_scaler; r_scaler = b_scaler; b_scaler = tmp; } for (unsigned char* itr = data_; itr < (data_ + length_);) { unsigned char gray_value = static_cast<unsigned char>( (r_scaler * (*(itr + 2))) + (g_scaler * (*(itr + 1))) + (b_scaler * (*(itr + 0)))); *(itr++) = gray_value; *(itr++) = gray_value; *(itr++) = gray_value; } } inline const unsigned char* data() { return data_; } inline void bgr_to_rgb() { if ((bgr_mode == channel_mode_) && (3 == bytes_per_pixel_)) { reverse_channels(); channel_mode_ = rgb_mode; } } inline void rgb_to_bgr() { if ((rgb_mode == channel_mode_) && (3 == bytes_per_pixel_)) { reverse_channels(); channel_mode_ = bgr_mode; } } inline void reverse() { unsigned char* itr1 = data_; unsigned char* itr2 = (data_ + length_) - bytes_per_pixel_; while (itr1 < itr2) { for (std::size_t i = 0; i < bytes_per_pixel_; ++i) { unsigned char* citr1 = itr1 + i; unsigned char* citr2 = itr2 + i; unsigned char tmp = *citr1; *citr1 = *citr2; *citr2 = tmp; } itr1 += bytes_per_pixel_; itr2 -= bytes_per_pixel_; } } inline void horizontal_flip() { for (unsigned int y = 0; y < height_; ++y) { unsigned char* itr1 = row(y); unsigned char* itr2 = itr1 + row_increment_ - bytes_per_pixel_; while (itr1 < itr2) { for (unsigned int i = 0; i < bytes_per_pixel_; ++i) { unsigned char* p1 = (itr1 + i); unsigned char* p2 = (itr2 + i); unsigned char tmp = *p1; *p1 = *p2; *p2 = tmp; } itr1 += bytes_per_pixel_; itr2 -= bytes_per_pixel_; } } } inline void vertical_flip() { for (unsigned int y = 0; y < (height_ / 2); ++y) { unsigned char* itr1 = row(y); unsigned char* itr2 = row(height_ - y - 1); for (std::size_t x = 0; x < row_increment_; ++x) { unsigned char tmp = *(itr1 + x); *(itr1 + x) = *(itr2 + x); *(itr2 + x) = tmp; } } } inline void export_color_plane(const color_plane color, unsigned char* image) { for (unsigned char* itr = (data_ + offset(color)); itr < (data_ + length_); ++image, itr += bytes_per_pixel_) { (*image) = (*itr); } } inline void export_color_plane(const color_plane color, bitmap_image& image) { if ((width_ != image.width_) || (height_ != image.height_)) { image.setwidth_height(width_, height_); } image.clear(); unsigned char* itr1 = (data_ + offset(color)); unsigned char* itr1_end = (data_ + length_); unsigned char* itr2 = (image.data_ + offset(color)); while (itr1 < itr1_end) { (*itr2) = (*itr1); itr1 += bytes_per_pixel_; itr2 += bytes_per_pixel_; } } inline void export_response_image(const color_plane color, double* response_image) { for (unsigned char* itr = (data_ + offset(color)); itr < (data_ + length_); ++response_image, itr += bytes_per_pixel_) { (*response_image) = (1.0 * (*itr)) / 256.0; } } inline void export_gray_scale_response_image(double* response_image) { for (unsigned char* itr = data_; itr < (data_ + length_); itr += bytes_per_pixel_) { unsigned char gray_value = static_cast<unsigned char>( (0.299 * (*(itr + 2))) + (0.587 * (*(itr + 1))) + (0.114 * (*(itr + 0)))); (*response_image) = (1.0 * gray_value) / 256.0; } } inline void export_rgb(double* red, double* green, double* blue) const { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data_; itr < (data_ + length_); ++red, ++green, ++blue) { (*blue) = (1.0 * (*(itr++))) / 256.0; (*green) = (1.0 * (*(itr++))) / 256.0; (*red) = (1.0 * (*(itr++))) / 256.0; } } inline void export_rgb(float* red, float* green, float* blue) const { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data_; itr < (data_ + length_); ++red, ++green, ++blue) { (*blue) = (1.0f * (*(itr++))) / 256.0f; (*green) = (1.0f * (*(itr++))) / 256.0f; (*red) = (1.0f * (*(itr++))) / 256.0f; } } inline void export_rgb(unsigned char* red, unsigned char* green, unsigned char* blue) const { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data_; itr < (data_ + length_); ++red, ++green, ++blue) { (*blue) = *(itr++); (*green) = *(itr++); (*red) = *(itr++); } } inline void export_ycbcr(double* y, double* cb, double* cr) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data_; itr < (data_ + length_); ++y, ++cb, ++cr) { double blue = (1.0 * (*(itr++))); double green = (1.0 * (*(itr++))); double red = (1.0 * (*(itr++))); (*y) = clamp<double>( 16.0 + (1.0 / 256.0) * (65.738 * red + 129.057 * green + 25.064 * blue), 1.0, 254); (*cb) = clamp<double>( 128.0 + (1.0 / 256.0) * (-37.945 * red - 74.494 * green + 112.439 * blue), 1.0, 254); (*cr) = clamp<double>( 128.0 + (1.0 / 256.0) * (112.439 * red - 94.154 * green - 18.285 * blue), 1.0, 254); } } inline void export_rgb_normal(double* red, double* green, double* blue) const { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data_; itr < (data_ + length_); ++red, ++green, ++blue) { (*blue) = (1.0 * (*(itr++))); (*green) = (1.0 * (*(itr++))); (*red) = (1.0 * (*(itr++))); } } inline void export_rgb_normal(float* red, float* green, float* blue) const { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data_; itr < (data_ + length_); ++red, ++green, ++blue) { (*blue) = (1.0f * (*(itr++))); (*green) = (1.0f * (*(itr++))); (*red) = (1.0f * (*(itr++))); } } inline void import_rgb(double* red, double* green, double* blue) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data_; itr < (data_ + length_); ++red, ++green, ++blue) { *(itr++) = static_cast<unsigned char>(256.0 * (*blue)); *(itr++) = static_cast<unsigned char>(256.0 * (*green)); *(itr++) = static_cast<unsigned char>(256.0 * (*red)); } } inline void import_rgb(float* red, float* green, float* blue) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data_; itr < (data_ + length_); ++red, ++green, ++blue) { *(itr++) = static_cast<unsigned char>(256.0f * (*blue)); *(itr++) = static_cast<unsigned char>(256.0f * (*green)); *(itr++) = static_cast<unsigned char>(256.0f * (*red)); } } inline void import_rgb(unsigned char* red, unsigned char* green, unsigned char* blue) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data_; itr < (data_ + length_); ++red, ++green, ++blue) { *(itr++) = (*blue); *(itr++) = (*green); *(itr++) = (*red); } } inline void import_ycbcr(double* y, double* cb, double* cr) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data_; itr < (data_ + length_); ++y, ++cb, ++cr) { double y_ = (*y); double cb_ = (*cb); double cr_ = (*cr); *(itr++) = static_cast<unsigned char>( clamp((298.082 * y_ + 516.412 * cb_) / 256.0 - 276.836, 0.0, 255.0)); *(itr++) = static_cast<unsigned char>(clamp( (298.082 * y_ - 100.291 * cb_ - 208.120 * cr_) / 256.0 + 135.576, 0.0, 255.0)); *(itr++) = static_cast<unsigned char>( clamp((298.082 * y_ + 408.583 * cr_) / 256.0 - 222.921, 0.0, 255.0)); } } inline void import_rgb_clamped(double* red, double* green, double* blue) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data_; itr < (data_ + length_); ++red, ++green, ++blue) { *(itr++) = static_cast<unsigned char>( clamp<double>(256.0 * (*blue), 0.0, 255.0)); *(itr++) = static_cast<unsigned char>( clamp<double>(256.0 * (*green), 0.0, 255.0)); *(itr++) = static_cast<unsigned char>(clamp<double>(256.0 * (*red), 0.0, 255.0)); } } inline void import_rgb_clamped(float* red, float* green, float* blue) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data_; itr < (data_ + length_); ++red, ++green, ++blue) { *(itr++) = static_cast<unsigned char>( clamp<double>(256.0f * (*blue), 0.0, 255.0)); *(itr++) = static_cast<unsigned char>( clamp<double>(256.0f * (*green), 0.0, 255.0)); *(itr++) = static_cast<unsigned char>( clamp<double>(256.0f * (*red), 0.0, 255.0)); } } inline void import_rgb_normal(double* red, double* green, double* blue) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data_; itr < (data_ + length_); ++red, ++green, ++blue) { *(itr++) = static_cast<unsigned char>(*blue); *(itr++) = static_cast<unsigned char>(*green); *(itr++) = static_cast<unsigned char>(*red); } } inline void import_rgb_normal(float* red, float* green, float* blue) { if (bgr_mode != channel_mode_) return; for (unsigned char* itr = data_; itr < (data_ + length_); ++red, ++green, ++blue) { *(itr++) = static_cast<unsigned char>(*blue); *(itr++) = static_cast<unsigned char>(*green); *(itr++) = static_cast<unsigned char>(*red); } } inline void subsample(bitmap_image& dest) { /* Half sub-sample of original image. */ unsigned int w = 0; unsigned int h = 0; bool odd_width = false; bool odd_height = false; if (0 == (width_ % 2)) w = width_ / 2; else { w = 1 + (width_ / 2); odd_width = true; } if (0 == (height_ % 2)) h = height_ / 2; else { h = 1 + (height_ / 2); odd_height = true; } unsigned int horizontal_upper = (odd_width) ? (w - 1) : w; unsigned int vertical_upper = (odd_height) ? (h - 1) : h; dest.setwidth_height(w, h); dest.clear(); unsigned char* s_itr[3]; const unsigned char* itr1[3]; const unsigned char* itr2[3]; s_itr[0] = dest.data_ + 0; s_itr[1] = dest.data_ + 1; s_itr[2] = dest.data_ + 2; itr1[0] = data_ + 0; itr1[1] = data_ + 1; itr1[2] = data_ + 2; itr2[0] = data_ + row_increment_ + 0; itr2[1] = data_ + row_increment_ + 1; itr2[2] = data_ + row_increment_ + 2; unsigned int total = 0; for (unsigned int j = 0; j < vertical_upper; ++j) { for (unsigned int i = 0; i < horizontal_upper; ++i) { for (unsigned int k = 0; k < bytes_per_pixel_; s_itr[k] += bytes_per_pixel_, ++k) { total = 0; total += *(itr1[k]); itr1[k] += bytes_per_pixel_; total += *(itr1[k]); itr1[k] += bytes_per_pixel_; total += *(itr2[k]); itr2[k] += bytes_per_pixel_; total += *(itr2[k]); itr2[k] += bytes_per_pixel_; *(s_itr[k]) = static_cast<unsigned char>(total >> 2); } } if (odd_width) { for (unsigned int k = 0; k < bytes_per_pixel_; s_itr[k] += bytes_per_pixel_, ++k) { total = 0; total += *(itr1[k]); itr1[k] += bytes_per_pixel_; total += *(itr2[k]); itr2[k] += bytes_per_pixel_; *(s_itr[k]) = static_cast<unsigned char>(total >> 1); } } for (unsigned int k = 0; k < bytes_per_pixel_; itr1[k] += row_increment_, ++k) ; if (j != (vertical_upper - 1)) { for (unsigned int k = 0; k < bytes_per_pixel_; itr2[k] += row_increment_, ++k) ; } } if (odd_height) { for (unsigned int i = 0; i < horizontal_upper; ++i) { for (unsigned int k = 0; k < bytes_per_pixel_; s_itr[k] += bytes_per_pixel_, ++k) { total = 0; total += *(itr1[k]); itr1[k] += bytes_per_pixel_; total += *(itr2[k]); itr2[k] += bytes_per_pixel_; *(s_itr[k]) = static_cast<unsigned char>(total >> 1); } } if (odd_width) { for (unsigned int k = 0; k < bytes_per_pixel_; ++k) { (*(s_itr[k])) = *(itr1[k]); } } } } inline void upsample(bitmap_image& dest) { /* 2x up-sample of original image. */ dest.setwidth_height(2 * width_, 2 * height_); dest.clear(); const unsigned char* s_itr[3]; unsigned char* itr1[3]; unsigned char* itr2[3]; s_itr[0] = data_ + 0; s_itr[1] = data_ + 1; s_itr[2] = data_ + 2; itr1[0] = dest.data_ + 0; itr1[1] = dest.data_ + 1; itr1[2] = dest.data_ + 2; itr2[0] = dest.data_ + dest.row_increment_ + 0; itr2[1] = dest.data_ + dest.row_increment_ + 1; itr2[2] = dest.data_ + dest.row_increment_ + 2; for (unsigned int j = 0; j < height_; ++j) { for (unsigned int i = 0; i < width_; ++i) { for (unsigned int k = 0; k < bytes_per_pixel_; s_itr[k] += bytes_per_pixel_, ++k) { *(itr1[k]) = *(s_itr[k]); itr1[k] += bytes_per_pixel_; *(itr1[k]) = *(s_itr[k]); itr1[k] += bytes_per_pixel_; *(itr2[k]) = *(s_itr[k]); itr2[k] += bytes_per_pixel_; *(itr2[k]) = *(s_itr[k]); itr2[k] += bytes_per_pixel_; } } for (unsigned int k = 0; k < bytes_per_pixel_; ++k) { itr1[k] += dest.row_increment_; itr2[k] += dest.row_increment_; } } } inline void alpha_blend(const double& alpha, const bitmap_image& image) { if ((image.width_ != width_) || (image.height_ != height_)) { return; } if ((alpha < 0.0) || (alpha > 1.0)) { return; } unsigned char* itr1 = data_; unsigned char* itr1_end = data_ + length_; unsigned char* itr2 = image.data_; double alpha_compliment = 1.0 - alpha; while (itr1 != itr1_end) { *(itr1) = static_cast<unsigned char>((alpha * (*itr2)) + (alpha_compliment * (*itr1))); ++itr1; ++itr2; } } inline double psnr(const bitmap_image& image) { if ((image.width_ != width_) || (image.height_ != height_)) { return 0.0; } unsigned char* itr1 = data_; unsigned char* itr2 = image.data_; double mse = 0.0; while (itr1 != (data_ + length_)) { double v = (static_cast<double>(*itr1) - static_cast<double>(*itr2)); mse += v * v; ++itr1; ++itr2; } if (mse <= 0.0000001) { return 1000000.0; } else { mse /= (3.0 * width_ * height_); return 20.0 * std::log10(255.0 / std::sqrt(mse)); } } inline double psnr(const unsigned int& x, const unsigned int& y, const bitmap_image& image) { if ((x + image.width()) > width_) { return 0.0; } if ((y + image.height()) > height_) { return 0.0; } double mse = 0.0; const unsigned int height = image.height(); const unsigned int width = image.width(); for (unsigned int r = 0; r < height; ++r) { unsigned char* itr1 = row(r + y) + x * bytes_per_pixel_; unsigned char* itr1_end = itr1 + (width * bytes_per_pixel_); const unsigned char* itr2 = image.row(r); while (itr1 != itr1_end) { double v = (static_cast<double>(*itr1) - static_cast<double>(*itr2)); mse += v * v; ++itr1; ++itr2; } } if (mse <= 0.0000001) { return 1000000.0; } else { mse /= (3.0 * image.width() * image.height()); return 20.0 * std::log10(255.0 / std::sqrt(mse)); } } inline void histogram(const color_plane color, double hist[256]) { std::fill(hist, hist + 256, 0.0); for (unsigned char* itr = (data_ + offset(color)); itr < (data_ + length_); itr += bytes_per_pixel_) { ++hist[(*itr)]; } } inline void histogram_normalized(const color_plane color, double hist[256]) { histogram(color, hist); double* h_itr = hist; const double* h_end = hist + 256; const double pixel_count = static_cast<double>(width_ * height_); while (h_end != h_itr) { *(h_itr++) /= pixel_count; } } inline unsigned int offset(const color_plane color) { switch (channel_mode_) { case rgb_mode: { switch (color) { case red_plane: return 0; case green_plane: return 1; case blue_plane: return 2; default: return std::numeric_limits<unsigned int>::max(); } } case bgr_mode: { switch (color) { case red_plane: return 2; case green_plane: return 1; case blue_plane: return 0; default: return std::numeric_limits<unsigned int>::max(); } } default: return std::numeric_limits<unsigned int>::max(); } } inline void incremental() { unsigned char current_color = 0; for (unsigned char* itr = data_; itr < (data_ + length_);) { (*itr++) = (current_color); (*itr++) = (current_color); (*itr++) = (current_color); ++current_color; } } private: struct bitmap_file_header { unsigned short type; unsigned int size; unsigned short reserved1; unsigned short reserved2; unsigned int off_bits; unsigned int struct_size() { return sizeof(type) + sizeof(size) + sizeof(reserved1) + sizeof(reserved2) + sizeof(off_bits); } }; struct bitmap_information_header { unsigned int size; unsigned int width; unsigned int height; unsigned short planes; unsigned short bit_count; unsigned int compression; unsigned int size_image; unsigned int x_pels_per_meter; unsigned int y_pels_per_meter; unsigned int clr_used; unsigned int clr_important; unsigned int struct_size() { return sizeof(size) + sizeof(width) + sizeof(height) + sizeof(planes) + sizeof(bit_count) + sizeof(compression) + sizeof(size_image) + sizeof(x_pels_per_meter) + sizeof(y_pels_per_meter) + sizeof(clr_used) + sizeof(clr_important); } }; inline bool big_endian() { unsigned int v = 0x01; return (1 != reinterpret_cast<char*>(&v)[0]); } inline unsigned short flip(const unsigned short& v) { return ((v >> 8) | (v << 8)); } inline unsigned int flip(const unsigned int& v) { return (((v & 0xFF000000) >> 0x18) | ((v & 0x000000FF) << 0x18) | ((v & 0x00FF0000) >> 0x08) | ((v & 0x0000FF00) << 0x08)); } template <typename T> inline void read_from_stream(std::ifstream& stream, T& t) { stream.read(reinterpret_cast<char*>(&t), sizeof(T)); } template <typename T> inline void write_to_stream(std::ofstream& stream, const T& t) { stream.write(reinterpret_cast<const char*>(&t), sizeof(T)); } inline void read_bfh(std::ifstream& stream, bitmap_file_header& bfh) { read_from_stream(stream, bfh.type); read_from_stream(stream, bfh.size); read_from_stream(stream, bfh.reserved1); read_from_stream(stream, bfh.reserved2); read_from_stream(stream, bfh.off_bits); if (big_endian()) { bfh.type = flip(bfh.type); bfh.size = flip(bfh.size); bfh.reserved1 = flip(bfh.reserved1); bfh.reserved2 = flip(bfh.reserved2); bfh.off_bits = flip(bfh.off_bits); } } inline void write_bfh(std::ofstream& stream, const bitmap_file_header& bfh) { if (big_endian()) { write_to_stream(stream, flip(bfh.type)); write_to_stream(stream, flip(bfh.size)); write_to_stream(stream, flip(bfh.reserved1)); write_to_stream(stream, flip(bfh.reserved2)); write_to_stream(stream, flip(bfh.off_bits)); } else { write_to_stream(stream, bfh.type); write_to_stream(stream, bfh.size); write_to_stream(stream, bfh.reserved1); write_to_stream(stream, bfh.reserved2); write_to_stream(stream, bfh.off_bits); } } inline void read_bih(std::ifstream& stream, bitmap_information_header& bih) { read_from_stream(stream, bih.size); read_from_stream(stream, bih.width); read_from_stream(stream, bih.height); read_from_stream(stream, bih.planes); read_from_stream(stream, bih.bit_count); read_from_stream(stream, bih.compression); read_from_stream(stream, bih.size_image); read_from_stream(stream, bih.x_pels_per_meter); read_from_stream(stream, bih.y_pels_per_meter); read_from_stream(stream, bih.clr_used); read_from_stream(stream, bih.clr_important); if (big_endian()) { bih.size = flip(bih.size); bih.width = flip(bih.width); bih.height = flip(bih.height); bih.planes = flip(bih.planes); bih.bit_count = flip(bih.bit_count); bih.compression = flip(bih.compression); bih.size_image = flip(bih.size_image); bih.x_pels_per_meter = flip(bih.x_pels_per_meter); bih.y_pels_per_meter = flip(bih.y_pels_per_meter); bih.clr_used = flip(bih.clr_used); bih.clr_important = flip(bih.clr_important); } } inline void write_bih(std::ofstream& stream, const bitmap_information_header& bih) { if (big_endian()) { write_to_stream(stream, flip(bih.size)); write_to_stream(stream, flip(bih.width)); write_to_stream(stream, flip(bih.height)); write_to_stream(stream, flip(bih.planes)); write_to_stream(stream, flip(bih.bit_count)); write_to_stream(stream, flip(bih.compression)); write_to_stream(stream, flip(bih.size_image)); write_to_stream(stream, flip(bih.x_pels_per_meter)); write_to_stream(stream, flip(bih.y_pels_per_meter)); write_to_stream(stream, flip(bih.clr_used)); write_to_stream(stream, flip(bih.clr_important)); } else { write_to_stream(stream, bih.size); write_to_stream(stream, bih.width); write_to_stream(stream, bih.height); write_to_stream(stream, bih.planes); write_to_stream(stream, bih.bit_count); write_to_stream(stream, bih.compression); write_to_stream(stream, bih.size_image); write_to_stream(stream, bih.x_pels_per_meter); write_to_stream(stream, bih.y_pels_per_meter); write_to_stream(stream, bih.clr_used); write_to_stream(stream, bih.clr_important); } } void create_bitmap() { length_ = width_ * height_ * bytes_per_pixel_; row_increment_ = width_ * bytes_per_pixel_; if (0 != data_) { delete[] data_; } data_ = new unsigned char[length_]; } void load_bitmap() { std::ifstream stream(file_name_.c_str(), std::ios::binary); if (!stream) { std::cerr << "bitmap_image::load_bitmap() ERROR: bitmap_image - file " << file_name_ << " not found!" << std::endl; return; } bitmap_file_header bfh; bitmap_information_header bih; read_bfh(stream, bfh); read_bih(stream, bih); if (bfh.type != 19778) { stream.close(); std::cerr << "bitmap_image::load_bitmap() ERROR: bitmap_image - Invalid " "type value " << bfh.type << " expected 19778." << std::endl; return; } if (bih.bit_count != 24) { stream.close(); std::cerr << "bitmap_image::load_bitmap() ERROR: bitmap_image - Invalid " "bit depth " << bih.bit_count << " expected 24." << std::endl; return; } height_ = bih.height; width_ = bih.width; bytes_per_pixel_ = bih.bit_count >> 3; unsigned int padding = (4 - ((3 * width_) % 4)) % 4; char padding_data[4] = {0, 0, 0, 0}; create_bitmap(); for (unsigned int i = 0; i < height_; ++i) { unsigned char* data_ptr = row(height_ - i - 1); // read in inverted row order stream.read(reinterpret_cast<char*>(data_ptr), sizeof(char) * bytes_per_pixel_ * width_); stream.read(padding_data, padding); } } inline void reverse_channels() { if (3 != bytes_per_pixel_) return; for (unsigned char* itr = data_; itr < (data_ + length_); itr += bytes_per_pixel_) { unsigned char tmp = *(itr + 0); *(itr + 0) = *(itr + 2); *(itr + 2) = tmp; } } template <typename T> inline T clamp(const T& v, const T& lower_range, const T& upper_range) { if (v < lower_range) return lower_range; else if (v > upper_range) return upper_range; else return v; } std::string file_name_; unsigned char* data_; unsigned int length_; unsigned int width_; unsigned int height_; unsigned int row_increment_; unsigned int bytes_per_pixel_; channel_mode channel_mode_; }; struct rgb_store { unsigned char red; unsigned char green; unsigned char blue; }; inline void rgb_to_ycbcr(const unsigned int& length, double* red, double* green, double* blue, double* y, double* cb, double* cr) { unsigned int i = 0; while (i < length) { (*y) = 16.0 + (65.481 * (*red) + 128.553 * (*green) + 24.966 * (*blue)); (*cb) = 128.0 + (-37.797 * (*red) + -74.203 * (*green) + 112.000 * (*blue)); (*cr) = 128.0 + (112.000 * (*red) + -93.786 * (*green) - 18.214 * (*blue)); ++i; ++red; ++green; ++blue; ++y; ++cb; ++cr; } } inline void ycbcr_to_rgb(const unsigned int& length, double* y, double* cb, double* cr, double* red, double* green, double* blue) { unsigned int i = 0; while (i < length) { double y_ = (*y) - 16.0; double cb_ = (*cb) - 128.0; double cr_ = (*cr) - 128.0; (*red) = 0.000456621 * y_ + 0.00625893 * cr_; (*green) = 0.000456621 * y_ - 0.00153632 * cb_ - 0.00318811 * cr_; (*blue) = 0.000456621 * y_ + 0.00791071 * cb_; ++i; ++red; ++green; ++blue; ++y; ++cb; ++cr; } } inline void subsample(const unsigned int& width, const unsigned int& height, const double* source, unsigned int& w, unsigned int& h, double** dest) { /* Single channel. */ w = 0; h = 0; bool odd_width = false; bool odd_height = false; if (0 == (width % 2)) w = width / 2; else { w = 1 + (width / 2); odd_width = true; } if (0 == (height % 2)) h = height / 2; else { h = 1 + (height / 2); odd_height = true; } unsigned int horizontal_upper = (odd_width) ? w - 1 : w; unsigned int vertical_upper = (odd_height) ? h - 1 : h; *dest = new double[w * h]; double* s_itr = *dest; const double* itr1 = source; const double* itr2 = source + width; for (unsigned int j = 0; j < vertical_upper; ++j) { for (unsigned int i = 0; i < horizontal_upper; ++i, ++s_itr) { (*s_itr) = *(itr1++); (*s_itr) += *(itr1++); (*s_itr) += *(itr2++); (*s_itr) += *(itr2++); (*s_itr) /= 4.0; } if (odd_width) { (*(s_itr++)) = ((*itr1++) + (*itr2++)) / 2.0; } itr1 += width; if (j != (vertical_upper - 1)) { itr2 += width; } } if (odd_height) { for (unsigned int i = 0; i < horizontal_upper; ++i, ++s_itr) { (*s_itr) += (*(itr1++)); (*s_itr) += (*(itr1++)); (*s_itr) /= 2.0; } if (odd_width) { (*(s_itr++)) = (*itr1); } } } inline void upsample(const unsigned int& width, const unsigned int& height, const double* source, unsigned int& w, unsigned int& h, double** dest) { /* Single channel. */ w = 2 * width; h = 2 * height; *dest = new double[w * h]; const double* s_itr = source; double* itr1 = *dest; double* itr2 = *dest + w; for (unsigned int j = 0; j < height; ++j) { for (unsigned int i = 0; i < width; ++i, ++s_itr) { *(itr1++) = (*s_itr); *(itr1++) = (*s_itr); *(itr2++) = (*s_itr); *(itr2++) = (*s_itr); } itr1 += w; itr2 += w; } } inline void checkered_pattern(const unsigned int x_width, const unsigned int y_width, const unsigned char value, const bitmap_image::color_plane color, bitmap_image& image) { if ((x_width >= image.width()) || (y_width >= image.height())) { return; } bool setter_x = false; bool setter_y = true; const unsigned int color_plane_offset = image.offset(color); const unsigned int height = image.height(); const unsigned int width = image.width(); for (unsigned int y = 0; y < height; ++y) { if (0 == (y % y_width)) { setter_y = !setter_y; } unsigned char* row = image.row(y) + color_plane_offset; for (unsigned int x = 0; x < width; ++x, row += image.bytes_per_pixel()) { if (0 == (x % x_width)) { setter_x = !setter_x; } if (setter_x ^ setter_y) { *row = value; } } } } inline void checkered_pattern(const unsigned int x_width, const unsigned int y_width, const unsigned char red, const unsigned char green, const unsigned char blue, bitmap_image& image) { if ((x_width >= image.width()) || (y_width >= image.height())) { return; } bool setter_x = false; bool setter_y = true; const unsigned int height = image.height(); const unsigned int width = image.width(); for (unsigned int y = 0; y < height; ++y) { if (0 == (y % y_width)) { setter_y = !setter_y; } unsigned char* row = image.row(y); for (unsigned int x = 0; x < width; ++x, row += image.bytes_per_pixel()) { if (0 == (x % x_width)) { setter_x = !setter_x; } if (setter_x ^ setter_y) { *(row + 0) = blue; *(row + 1) = green; *(row + 2) = red; } } } } inline void plasma(bitmap_image& image, const double& x, const double& y, const double& width, const double& height, const double& c1, const double& c2, const double& c3, const double& c4, const double& roughness = 3.0, const rgb_store colormap[] = 0) { // Note: c1,c2,c3,c4 -> [0.0,1.0] double half_width = (width / 2.0); double half_height = (height / 2.0); if ((width >= 1.0) || (height >= 1.0)) { double corner1 = (c1 + c2) / 2.0; double corner2 = (c2 + c3) / 2.0; double corner3 = (c3 + c4) / 2.0; double corner4 = (c4 + c1) / 2.0; double center = (c1 + c2 + c3 + c4) / 4.0 + ((1.0 * ::rand() / (1.0 * RAND_MAX)) - 0.5) * // should use a better rng ((1.0 * half_width + half_height) / (image.width() + image.height()) * roughness); center = std::min<double>(std::max<double>(0.0, center), 1.0); plasma(image, x, y, half_width, half_height, c1, corner1, center, corner4, roughness, colormap); plasma(image, x + half_width, y, half_width, half_height, corner1, c2, corner2, center, roughness, colormap); plasma(image, x + half_width, y + half_height, half_width, half_height, center, corner2, c3, corner3, roughness, colormap); plasma(image, x, y + half_height, half_width, half_height, corner4, center, corner3, c4, roughness, colormap); } else { rgb_store color = colormap[static_cast<unsigned int>( 1000.0 * ((c1 + c2 + c3 + c4) / 4.0)) % 1000]; image.set_pixel(static_cast<unsigned int>(x), static_cast<unsigned int>(y), color.red, color.green, color.blue); } } inline double psnr_region(const unsigned int& x, const unsigned int& y, const unsigned int& width, const unsigned int& height, const bitmap_image& image1, const bitmap_image& image2) { if ((image1.width() != image2.width()) || (image1.height() != image2.height())) { return 0.0; } if ((x + width) > image1.width()) { return 0.0; } if ((y + height) > image1.height()) { return 0.0; } double mse = 0.0; for (unsigned int r = 0; r < height; ++r) { const unsigned char* itr1 = image1.row(r + y) + x * image1.bytes_per_pixel(); const unsigned char* itr1_end = itr1 + (width * image1.bytes_per_pixel()); const unsigned char* itr2 = image2.row(r + y) + x * image2.bytes_per_pixel(); while (itr1 != itr1_end) { double v = (static_cast<double>(*itr1) - static_cast<double>(*itr2)); mse += v * v; ++itr1; ++itr2; } } if (mse <= 0.0000001) { return 1000000.0; } else { mse /= (3.0 * width * height); return 20.0 * std::log10(255.0 / std::sqrt(mse)); } } inline void hierarchical_psnr_r(const double& x, const double& y, const double& width, const double& height, const bitmap_image& image1, bitmap_image& image2, const double& threshold, const rgb_store colormap[]) { if ((width <= 4.0) || (height <= 4.0)) { double psnr = psnr_region(static_cast<unsigned int>(x), static_cast<unsigned int>(y), static_cast<unsigned int>(width), static_cast<unsigned int>(height), image1, image2); if (psnr < threshold) { rgb_store c = colormap[static_cast<unsigned int>( 1000.0 * (1.0 - (psnr / threshold)))]; image2.set_region( static_cast<unsigned int>(x), static_cast<unsigned int>(y), static_cast<unsigned int>(width + 1), static_cast<unsigned int>(height + 1), c.red, c.green, c.blue); } } else { double half_width = (width / 2.0); double half_height = (height / 2.0); hierarchical_psnr_r(x, y, half_width, half_height, image1, image2, threshold, colormap); hierarchical_psnr_r(x + half_width, y, half_width, half_height, image1, image2, threshold, colormap); hierarchical_psnr_r(x + half_width, y + half_height, half_width, half_height, image1, image2, threshold, colormap); hierarchical_psnr_r(x, y + half_height, half_width, half_height, image1, image2, threshold, colormap); } } inline void hierarchical_psnr(bitmap_image& image1, bitmap_image& image2, const double threshold, const rgb_store colormap[]) { if ((image1.width() != image2.width()) || (image1.height() != image2.height())) { return; } double psnr = psnr_region(0, 0, image1.width(), image1.height(), image1, image2); if (psnr < threshold) { hierarchical_psnr_r(0, 0, image1.width(), image1.height(), image1, image2, threshold, colormap); } } class image_drawer { public: image_drawer(bitmap_image& image) : image_(image), pen_width_(1), pen_color_red_(0), pen_color_green_(0), pen_color_blue_(0) {} void rectangle(int x1, int y1, int x2, int y2) { line_segment(x1, y1, x2, y1); line_segment(x2, y1, x2, y2); line_segment(x2, y2, x1, y2); line_segment(x1, y2, x1, y1); } void triangle(int x1, int y1, int x2, int y2, int x3, int y3) { line_segment(x1, y1, x2, y2); line_segment(x2, y2, x3, y3); line_segment(x3, y3, x1, y1); } void quadix(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { line_segment(x1, y1, x2, y2); line_segment(x2, y2, x3, y3); line_segment(x3, y3, x4, y4); line_segment(x4, y4, x1, y1); } void line_segment(int x1, int y1, int x2, int y2) { int steep = 0; int sx = ((x2 - x1) > 0) ? 1 : -1; int sy = ((y2 - y1) > 0) ? 1 : -1; int dx = abs(x2 - x1); int dy = abs(y2 - y1); if (dy > dx) { steep = x1; x1 = y1; y1 = steep; /* swap x1 and y1 */ steep = dx; dx = dy; dy = steep; /* swap dx and dy */ steep = sx; sx = sy; sy = steep; /* swap sx and sy */ steep = 1; } int e = 2 * dy - dx; for (int i = 0; i < dx; ++i) { if (steep) plot_pen_pixel(y1, x1); else plot_pen_pixel(x1, y1); while (e >= 0) { y1 += sy; e -= (dx << 1); } x1 += sx; e += (dy << 1); } plot_pen_pixel(x2, y2); } void horiztonal_line_segment(int x1, int x2, int y) { if (x1 > x2) { std::swap(x1, x2); } for (int i = 0; i < (x2 - x1); ++i) { plot_pen_pixel(x1 + i, y); } } void vertical_line_segment(int y1, int y2, int x) { if (y1 > y2) { std::swap(y1, y2); } for (int i = 0; i < (y2 - y1); ++i) { plot_pen_pixel(x, y1 + i); } } void ellipse(int centerx, int centery, int a, int b) { int t1 = a * a; int t2 = t1 << 1; int t3 = t2 << 1; int t4 = b * b; int t5 = t4 << 1; int t6 = t5 << 1; int t7 = a * t5; int t8 = t7 << 1; int t9 = 0; int d1 = t2 - t7 + (t4 >> 1); int d2 = (t1 >> 1) - t8 + t5; int x = a; int y = 0; int negative_tx = centerx - x; int positive_tx = centerx + x; int negative_ty = centery - y; int positive_ty = centery + y; while (d2 < 0) { plot_pen_pixel(positive_tx, positive_ty); plot_pen_pixel(positive_tx, negative_ty); plot_pen_pixel(negative_tx, positive_ty); plot_pen_pixel(negative_tx, negative_ty); ++y; t9 = t9 + t3; if (d1 < 0) { d1 = d1 + t9 + t2; d2 = d2 + t9; } else { x--; t8 = t8 - t6; d1 = d1 + (t9 + t2 - t8); d2 = d2 + (t9 + t5 - t8); negative_tx = centerx - x; positive_tx = centerx + x; } negative_ty = centery - y; positive_ty = centery + y; } do { plot_pen_pixel(positive_tx, positive_ty); plot_pen_pixel(positive_tx, negative_ty); plot_pen_pixel(negative_tx, positive_ty); plot_pen_pixel(negative_tx, negative_ty); x--; t8 = t8 - t6; if (d2 < 0) { ++y; t9 = t9 + t3; d2 = d2 + (t9 + t5 - t8); negative_ty = centery - y; positive_ty = centery + y; } else d2 = d2 + (t5 - t8); negative_tx = centerx - x; positive_tx = centerx + x; } while (x >= 0); } void circle(int centerx, int centery, int radius) { int x = 0; int d = (1 - radius) << 1; while (radius >= 0) { plot_pen_pixel(centerx + x, centery + radius); plot_pen_pixel(centerx + x, centery - radius); plot_pen_pixel(centerx - x, centery + radius); plot_pen_pixel(centerx - x, centery - radius); if ((d + radius) > 0) d -= ((--radius) << 1) - 1; if (x > d) d += ((++x) << 1) + 1; } } void plot_pen_pixel(int x, int y) { switch (pen_width_) { case 1: plot_pixel(x, y); break; case 2: { plot_pixel(x, y); plot_pixel(x + 1, y); plot_pixel(x + 1, y + 1); plot_pixel(x, y + 1); } break; case 3: { plot_pixel(x, y - 1); plot_pixel(x - 1, y - 1); plot_pixel(x + 1, y - 1); plot_pixel(x, y); plot_pixel(x - 1, y); plot_pixel(x + 1, y); plot_pixel(x, y + 1); plot_pixel(x - 1, y + 1); plot_pixel(x + 1, y + 1); } break; default: plot_pixel(x, y); break; } } void plot_pixel(int x, int y) { image_.set_pixel(x, y, pen_color_red_, pen_color_green_, pen_color_blue_); } void pen_width(const unsigned int& width) { if ((width > 0) && (width < 4)) { pen_width_ = width; } } void pen_color(const unsigned char& red, const unsigned char& green, const unsigned char& blue) { pen_color_red_ = red; pen_color_green_ = green; pen_color_blue_ = blue; } private: image_drawer(const image_drawer& id); image_drawer& operator=(const image_drawer& id); bitmap_image& image_; unsigned int pen_width_; unsigned char pen_color_red_; unsigned char pen_color_green_; unsigned char pen_color_blue_; }; const rgb_store autumn_colormap[1000] = { {255, 0, 0}, {255, 0, 0}, {255, 1, 0}, {255, 1, 0}, {255, 1, 0}, {255, 1, 0}, {255, 2, 0}, {255, 2, 0}, {255, 2, 0}, {255, 2, 0}, {255, 3, 0}, {255, 3, 0}, {255, 3, 0}, {255, 3, 0}, {255, 4, 0}, {255, 4, 0}, {255, 4, 0}, {255, 4, 0}, {255, 5, 0}, {255, 5, 0}, {255, 5, 0}, {255, 5, 0}, {255, 6, 0}, {255, 6, 0}, {255, 6, 0}, {255, 6, 0}, {255, 7, 0}, {255, 7, 0}, {255, 7, 0}, {255, 7, 0}, {255, 8, 0}, {255, 8, 0}, {255, 8, 0}, {255, 8, 0}, {255, 9, 0}, {255, 9, 0}, {255, 9, 0}, {255, 9, 0}, {255, 10, 0}, {255, 10, 0}, {255, 10, 0}, {255, 10, 0}, {255, 11, 0}, {255, 11, 0}, {255, 11, 0}, {255, 11, 0}, {255, 12, 0}, {255, 12, 0}, {255, 12, 0}, {255, 13, 0}, {255, 13, 0}, {255, 13, 0}, {255, 13, 0}, {255, 14, 0}, {255, 14, 0}, {255, 14, 0}, {255, 14, 0}, {255, 15, 0}, {255, 15, 0}, {255, 15, 0}, {255, 15, 0}, {255, 16, 0}, {255, 16, 0}, {255, 16, 0}, {255, 16, 0}, {255, 17, 0}, {255, 17, 0}, {255, 17, 0}, {255, 17, 0}, {255, 18, 0}, {255, 18, 0}, {255, 18, 0}, {255, 18, 0}, {255, 19, 0}, {255, 19, 0}, {255, 19, 0}, {255, 19, 0}, {255, 20, 0}, {255, 20, 0}, {255, 20, 0}, {255, 20, 0}, {255, 21, 0}, {255, 21, 0}, {255, 21, 0}, {255, 21, 0}, {255, 22, 0}, {255, 22, 0}, {255, 22, 0}, {255, 22, 0}, {255, 23, 0}, {255, 23, 0}, {255, 23, 0}, {255, 23, 0}, {255, 24, 0}, {255, 24, 0}, {255, 24, 0}, {255, 25, 0}, {255, 25, 0}, {255, 25, 0}, {255, 25, 0}, {255, 26, 0}, {255, 26, 0}, {255, 26, 0}, {255, 26, 0}, {255, 27, 0}, {255, 27, 0}, {255, 27, 0}, {255, 27, 0}, {255, 28, 0}, {255, 28, 0}, {255, 28, 0}, {255, 28, 0}, {255, 29, 0}, {255, 29, 0}, {255, 29, 0}, {255, 29, 0}, {255, 30, 0}, {255, 30, 0}, {255, 30, 0}, {255, 30, 0}, {255, 31, 0}, {255, 31, 0}, {255, 31, 0}, {255, 31, 0}, {255, 32, 0}, {255, 32, 0}, {255, 32, 0}, {255, 32, 0}, {255, 33, 0}, {255, 33, 0}, {255, 33, 0}, {255, 33, 0}, {255, 34, 0}, {255, 34, 0}, {255, 34, 0}, {255, 34, 0}, {255, 35, 0}, {255, 35, 0}, {255, 35, 0}, {255, 35, 0}, {255, 36, 0}, {255, 36, 0}, {255, 36, 0}, {255, 37, 0}, {255, 37, 0}, {255, 37, 0}, {255, 37, 0}, {255, 38, 0}, {255, 38, 0}, {255, 38, 0}, {255, 38, 0}, {255, 39, 0}, {255, 39, 0}, {255, 39, 0}, {255, 39, 0}, {255, 40, 0}, {255, 40, 0}, {255, 40, 0}, {255, 40, 0}, {255, 41, 0}, {255, 41, 0}, {255, 41, 0}, {255, 41, 0}, {255, 42, 0}, {255, 42, 0}, {255, 42, 0}, {255, 42, 0}, {255, 43, 0}, {255, 43, 0}, {255, 43, 0}, {255, 43, 0}, {255, 44, 0}, {255, 44, 0}, {255, 44, 0}, {255, 44, 0}, {255, 45, 0}, {255, 45, 0}, {255, 45, 0}, {255, 45, 0}, {255, 46, 0}, {255, 46, 0}, {255, 46, 0}, {255, 46, 0}, {255, 47, 0}, {255, 47, 0}, {255, 47, 0}, {255, 47, 0}, {255, 48, 0}, {255, 48, 0}, {255, 48, 0}, {255, 48, 0}, {255, 49, 0}, {255, 49, 0}, {255, 49, 0}, {255, 50, 0}, {255, 50, 0}, {255, 50, 0}, {255, 50, 0}, {255, 51, 0}, {255, 51, 0}, {255, 51, 0}, {255, 51, 0}, {255, 52, 0}, {255, 52, 0}, {255, 52, 0}, {255, 52, 0}, {255, 53, 0}, {255, 53, 0}, {255, 53, 0}, {255, 53, 0}, {255, 54, 0}, {255, 54, 0}, {255, 54, 0}, {255, 54, 0}, {255, 55, 0}, {255, 55, 0}, {255, 55, 0}, {255, 55, 0}, {255, 56, 0}, {255, 56, 0}, {255, 56, 0}, {255, 56, 0}, {255, 57, 0}, {255, 57, 0}, {255, 57, 0}, {255, 57, 0}, {255, 58, 0}, {255, 58, 0}, {255, 58, 0}, {255, 58, 0}, {255, 59, 0}, {255, 59, 0}, {255, 59, 0}, {255, 59, 0}, {255, 60, 0}, {255, 60, 0}, {255, 60, 0}, {255, 60, 0}, {255, 61, 0}, {255, 61, 0}, {255, 61, 0}, {255, 62, 0}, {255, 62, 0}, {255, 62, 0}, {255, 62, 0}, {255, 63, 0}, {255, 63, 0}, {255, 63, 0}, {255, 63, 0}, {255, 64, 0}, {255, 64, 0}, {255, 64, 0}, {255, 64, 0}, {255, 65, 0}, {255, 65, 0}, {255, 65, 0}, {255, 65, 0}, {255, 66, 0}, {255, 66, 0}, {255, 66, 0}, {255, 66, 0}, {255, 67, 0}, {255, 67, 0}, {255, 67, 0}, {255, 67, 0}, {255, 68, 0}, {255, 68, 0}, {255, 68, 0}, {255, 68, 0}, {255, 69, 0}, {255, 69, 0}, {255, 69, 0}, {255, 69, 0}, {255, 70, 0}, {255, 70, 0}, {255, 70, 0}, {255, 70, 0}, {255, 71, 0}, {255, 71, 0}, {255, 71, 0}, {255, 71, 0}, {255, 72, 0}, {255, 72, 0}, {255, 72, 0}, {255, 72, 0}, {255, 73, 0}, {255, 73, 0}, {255, 73, 0}, {255, 74, 0}, {255, 74, 0}, {255, 74, 0}, {255, 74, 0}, {255, 75, 0}, {255, 75, 0}, {255, 75, 0}, {255, 75, 0}, {255, 76, 0}, {255, 76, 0}, {255, 76, 0}, {255, 76, 0}, {255, 77, 0}, {255, 77, 0}, {255, 77, 0}, {255, 77, 0}, {255, 78, 0}, {255, 78, 0}, {255, 78, 0}, {255, 78, 0}, {255, 79, 0}, {255, 79, 0}, {255, 79, 0}, {255, 79, 0}, {255, 80, 0}, {255, 80, 0}, {255, 80, 0}, {255, 80, 0}, {255, 81, 0}, {255, 81, 0}, {255, 81, 0}, {255, 81, 0}, {255, 82, 0}, {255, 82, 0}, {255, 82, 0}, {255, 82, 0}, {255, 83, 0}, {255, 83, 0}, {255, 83, 0}, {255, 83, 0}, {255, 84, 0}, {255, 84, 0}, {255, 84, 0}, {255, 84, 0}, {255, 85, 0}, {255, 85, 0}, {255, 85, 0}, {255, 86, 0}, {255, 86, 0}, {255, 86, 0}, {255, 86, 0}, {255, 87, 0}, {255, 87, 0}, {255, 87, 0}, {255, 87, 0}, {255, 88, 0}, {255, 88, 0}, {255, 88, 0}, {255, 88, 0}, {255, 89, 0}, {255, 89, 0}, {255, 89, 0}, {255, 89, 0}, {255, 90, 0}, {255, 90, 0}, {255, 90, 0}, {255, 90, 0}, {255, 91, 0}, {255, 91, 0}, {255, 91, 0}, {255, 91, 0}, {255, 92, 0}, {255, 92, 0}, {255, 92, 0}, {255, 92, 0}, {255, 93, 0}, {255, 93, 0}, {255, 93, 0}, {255, 93, 0}, {255, 94, 0}, {255, 94, 0}, {255, 94, 0}, {255, 94, 0}, {255, 95, 0}, {255, 95, 0}, {255, 95, 0}, {255, 95, 0}, {255, 96, 0}, {255, 96, 0}, {255, 96, 0}, {255, 96, 0}, {255, 97, 0}, {255, 97, 0}, {255, 97, 0}, {255, 98, 0}, {255, 98, 0}, {255, 98, 0}, {255, 98, 0}, {255, 99, 0}, {255, 99, 0}, {255, 99, 0}, {255, 99, 0}, {255, 100, 0}, {255, 100, 0}, {255, 100, 0}, {255, 100, 0}, {255, 101, 0}, {255, 101, 0}, {255, 101, 0}, {255, 101, 0}, {255, 102, 0}, {255, 102, 0}, {255, 102, 0}, {255, 102, 0}, {255, 103, 0}, {255, 103, 0}, {255, 103, 0}, {255, 103, 0}, {255, 104, 0}, {255, 104, 0}, {255, 104, 0}, {255, 104, 0}, {255, 105, 0}, {255, 105, 0}, {255, 105, 0}, {255, 105, 0}, {255, 106, 0}, {255, 106, 0}, {255, 106, 0}, {255, 106, 0}, {255, 107, 0}, {255, 107, 0}, {255, 107, 0}, {255, 107, 0}, {255, 108, 0}, {255, 108, 0}, {255, 108, 0}, {255, 108, 0}, {255, 109, 0}, {255, 109, 0}, {255, 109, 0}, {255, 110, 0}, {255, 110, 0}, {255, 110, 0}, {255, 110, 0}, {255, 111, 0}, {255, 111, 0}, {255, 111, 0}, {255, 111, 0}, {255, 112, 0}, {255, 112, 0}, {255, 112, 0}, {255, 112, 0}, {255, 113, 0}, {255, 113, 0}, {255, 113, 0}, {255, 113, 0}, {255, 114, 0}, {255, 114, 0}, {255, 114, 0}, {255, 114, 0}, {255, 115, 0}, {255, 115, 0}, {255, 115, 0}, {255, 115, 0}, {255, 116, 0}, {255, 116, 0}, {255, 116, 0}, {255, 116, 0}, {255, 117, 0}, {255, 117, 0}, {255, 117, 0}, {255, 117, 0}, {255, 118, 0}, {255, 118, 0}, {255, 118, 0}, {255, 118, 0}, {255, 119, 0}, {255, 119, 0}, {255, 119, 0}, {255, 119, 0}, {255, 120, 0}, {255, 120, 0}, {255, 120, 0}, {255, 120, 0}, {255, 121, 0}, {255, 121, 0}, {255, 121, 0}, {255, 122, 0}, {255, 122, 0}, {255, 122, 0}, {255, 122, 0}, {255, 123, 0}, {255, 123, 0}, {255, 123, 0}, {255, 123, 0}, {255, 124, 0}, {255, 124, 0}, {255, 124, 0}, {255, 124, 0}, {255, 125, 0}, {255, 125, 0}, {255, 125, 0}, {255, 125, 0}, {255, 126, 0}, {255, 126, 0}, {255, 126, 0}, {255, 126, 0}, {255, 127, 0}, {255, 127, 0}, {255, 127, 0}, {255, 127, 0}, {255, 128, 0}, {255, 128, 0}, {255, 128, 0}, {255, 128, 0}, {255, 129, 0}, {255, 129, 0}, {255, 129, 0}, {255, 129, 0}, {255, 130, 0}, {255, 130, 0}, {255, 130, 0}, {255, 130, 0}, {255, 131, 0}, {255, 131, 0}, {255, 131, 0}, {255, 131, 0}, {255, 132, 0}, {255, 132, 0}, {255, 132, 0}, {255, 132, 0}, {255, 133, 0}, {255, 133, 0}, {255, 133, 0}, {255, 133, 0}, {255, 134, 0}, {255, 134, 0}, {255, 134, 0}, {255, 135, 0}, {255, 135, 0}, {255, 135, 0}, {255, 135, 0}, {255, 136, 0}, {255, 136, 0}, {255, 136, 0}, {255, 136, 0}, {255, 137, 0}, {255, 137, 0}, {255, 137, 0}, {255, 137, 0}, {255, 138, 0}, {255, 138, 0}, {255, 138, 0}, {255, 138, 0}, {255, 139, 0}, {255, 139, 0}, {255, 139, 0}, {255, 139, 0}, {255, 140, 0}, {255, 140, 0}, {255, 140, 0}, {255, 140, 0}, {255, 141, 0}, {255, 141, 0}, {255, 141, 0}, {255, 141, 0}, {255, 142, 0}, {255, 142, 0}, {255, 142, 0}, {255, 142, 0}, {255, 143, 0}, {255, 143, 0}, {255, 143, 0}, {255, 143, 0}, {255, 144, 0}, {255, 144, 0}, {255, 144, 0}, {255, 144, 0}, {255, 145, 0}, {255, 145, 0}, {255, 145, 0}, {255, 145, 0}, {255, 146, 0}, {255, 146, 0}, {255, 146, 0}, {255, 147, 0}, {255, 147, 0}, {255, 147, 0}, {255, 147, 0}, {255, 148, 0}, {255, 148, 0}, {255, 148, 0}, {255, 148, 0}, {255, 149, 0}, {255, 149, 0}, {255, 149, 0}, {255, 149, 0}, {255, 150, 0}, {255, 150, 0}, {255, 150, 0}, {255, 150, 0}, {255, 151, 0}, {255, 151, 0}, {255, 151, 0}, {255, 151, 0}, {255, 152, 0}, {255, 152, 0}, {255, 152, 0}, {255, 152, 0}, {255, 153, 0}, {255, 153, 0}, {255, 153, 0}, {255, 153, 0}, {255, 154, 0}, {255, 154, 0}, {255, 154, 0}, {255, 154, 0}, {255, 155, 0}, {255, 155, 0}, {255, 155, 0}, {255, 155, 0}, {255, 156, 0}, {255, 156, 0}, {255, 156, 0}, {255, 156, 0}, {255, 157, 0}, {255, 157, 0}, {255, 157, 0}, {255, 157, 0}, {255, 158, 0}, {255, 158, 0}, {255, 158, 0}, {255, 159, 0}, {255, 159, 0}, {255, 159, 0}, {255, 159, 0}, {255, 160, 0}, {255, 160, 0}, {255, 160, 0}, {255, 160, 0}, {255, 161, 0}, {255, 161, 0}, {255, 161, 0}, {255, 161, 0}, {255, 162, 0}, {255, 162, 0}, {255, 162, 0}, {255, 162, 0}, {255, 163, 0}, {255, 163, 0}, {255, 163, 0}, {255, 163, 0}, {255, 164, 0}, {255, 164, 0}, {255, 164, 0}, {255, 164, 0}, {255, 165, 0}, {255, 165, 0}, {255, 165, 0}, {255, 165, 0}, {255, 166, 0}, {255, 166, 0}, {255, 166, 0}, {255, 166, 0}, {255, 167, 0}, {255, 167, 0}, {255, 167, 0}, {255, 167, 0}, {255, 168, 0}, {255, 168, 0}, {255, 168, 0}, {255, 168, 0}, {255, 169, 0}, {255, 169, 0}, {255, 169, 0}, {255, 169, 0}, {255, 170, 0}, {255, 170, 0}, {255, 170, 0}, {255, 171, 0}, {255, 171, 0}, {255, 171, 0}, {255, 171, 0}, {255, 172, 0}, {255, 172, 0}, {255, 172, 0}, {255, 172, 0}, {255, 173, 0}, {255, 173, 0}, {255, 173, 0}, {255, 173, 0}, {255, 174, 0}, {255, 174, 0}, {255, 174, 0}, {255, 174, 0}, {255, 175, 0}, {255, 175, 0}, {255, 175, 0}, {255, 175, 0}, {255, 176, 0}, {255, 176, 0}, {255, 176, 0}, {255, 176, 0}, {255, 177, 0}, {255, 177, 0}, {255, 177, 0}, {255, 177, 0}, {255, 178, 0}, {255, 178, 0}, {255, 178, 0}, {255, 178, 0}, {255, 179, 0}, {255, 179, 0}, {255, 179, 0}, {255, 179, 0}, {255, 180, 0}, {255, 180, 0}, {255, 180, 0}, {255, 180, 0}, {255, 181, 0}, {255, 181, 0}, {255, 181, 0}, {255, 181, 0}, {255, 182, 0}, {255, 182, 0}, {255, 182, 0}, {255, 183, 0}, {255, 183, 0}, {255, 183, 0}, {255, 183, 0}, {255, 184, 0}, {255, 184, 0}, {255, 184, 0}, {255, 184, 0}, {255, 185, 0}, {255, 185, 0}, {255, 185, 0}, {255, 185, 0}, {255, 186, 0}, {255, 186, 0}, {255, 186, 0}, {255, 186, 0}, {255, 187, 0}, {255, 187, 0}, {255, 187, 0}, {255, 187, 0}, {255, 188, 0}, {255, 188, 0}, {255, 188, 0}, {255, 188, 0}, {255, 189, 0}, {255, 189, 0}, {255, 189, 0}, {255, 189, 0}, {255, 190, 0}, {255, 190, 0}, {255, 190, 0}, {255, 190, 0}, {255, 191, 0}, {255, 191, 0}, {255, 191, 0}, {255, 191, 0}, {255, 192, 0}, {255, 192, 0}, {255, 192, 0}, {255, 192, 0}, {255, 193, 0}, {255, 193, 0}, {255, 193, 0}, {255, 193, 0}, {255, 194, 0}, {255, 194, 0}, {255, 194, 0}, {255, 195, 0}, {255, 195, 0}, {255, 195, 0}, {255, 195, 0}, {255, 196, 0}, {255, 196, 0}, {255, 196, 0}, {255, 196, 0}, {255, 197, 0}, {255, 197, 0}, {255, 197, 0}, {255, 197, 0}, {255, 198, 0}, {255, 198, 0}, {255, 198, 0}, {255, 198, 0}, {255, 199, 0}, {255, 199, 0}, {255, 199, 0}, {255, 199, 0}, {255, 200, 0}, {255, 200, 0}, {255, 200, 0}, {255, 200, 0}, {255, 201, 0}, {255, 201, 0}, {255, 201, 0}, {255, 201, 0}, {255, 202, 0}, {255, 202, 0}, {255, 202, 0}, {255, 202, 0}, {255, 203, 0}, {255, 203, 0}, {255, 203, 0}, {255, 203, 0}, {255, 204, 0}, {255, 204, 0}, {255, 204, 0}, {255, 204, 0}, {255, 205, 0}, {255, 205, 0}, {255, 205, 0}, {255, 205, 0}, {255, 206, 0}, {255, 206, 0}, {255, 206, 0}, {255, 207, 0}, {255, 207, 0}, {255, 207, 0}, {255, 207, 0}, {255, 208, 0}, {255, 208, 0}, {255, 208, 0}, {255, 208, 0}, {255, 209, 0}, {255, 209, 0}, {255, 209, 0}, {255, 209, 0}, {255, 210, 0}, {255, 210, 0}, {255, 210, 0}, {255, 210, 0}, {255, 211, 0}, {255, 211, 0}, {255, 211, 0}, {255, 211, 0}, {255, 212, 0}, {255, 212, 0}, {255, 212, 0}, {255, 212, 0}, {255, 213, 0}, {255, 213, 0}, {255, 213, 0}, {255, 213, 0}, {255, 214, 0}, {255, 214, 0}, {255, 214, 0}, {255, 214, 0}, {255, 215, 0}, {255, 215, 0}, {255, 215, 0}, {255, 215, 0}, {255, 216, 0}, {255, 216, 0}, {255, 216, 0}, {255, 216, 0}, {255, 217, 0}, {255, 217, 0}, {255, 217, 0}, {255, 217, 0}, {255, 218, 0}, {255, 218, 0}, {255, 218, 0}, {255, 218, 0}, {255, 219, 0}, {255, 219, 0}, {255, 219, 0}, {255, 220, 0}, {255, 220, 0}, {255, 220, 0}, {255, 220, 0}, {255, 221, 0}, {255, 221, 0}, {255, 221, 0}, {255, 221, 0}, {255, 222, 0}, {255, 222, 0}, {255, 222, 0}, {255, 222, 0}, {255, 223, 0}, {255, 223, 0}, {255, 223, 0}, {255, 223, 0}, {255, 224, 0}, {255, 224, 0}, {255, 224, 0}, {255, 224, 0}, {255, 225, 0}, {255, 225, 0}, {255, 225, 0}, {255, 225, 0}, {255, 226, 0}, {255, 226, 0}, {255, 226, 0}, {255, 226, 0}, {255, 227, 0}, {255, 227, 0}, {255, 227, 0}, {255, 227, 0}, {255, 228, 0}, {255, 228, 0}, {255, 228, 0}, {255, 228, 0}, {255, 229, 0}, {255, 229, 0}, {255, 229, 0}, {255, 229, 0}, {255, 230, 0}, {255, 230, 0}, {255, 230, 0}, {255, 230, 0}, {255, 231, 0}, {255, 231, 0}, {255, 231, 0}, {255, 232, 0}, {255, 232, 0}, {255, 232, 0}, {255, 232, 0}, {255, 233, 0}, {255, 233, 0}, {255, 233, 0}, {255, 233, 0}, {255, 234, 0}, {255, 234, 0}, {255, 234, 0}, {255, 234, 0}, {255, 235, 0}, {255, 235, 0}, {255, 235, 0}, {255, 235, 0}, {255, 236, 0}, {255, 236, 0}, {255, 236, 0}, {255, 236, 0}, {255, 237, 0}, {255, 237, 0}, {255, 237, 0}, {255, 237, 0}, {255, 238, 0}, {255, 238, 0}, {255, 238, 0}, {255, 238, 0}, {255, 239, 0}, {255, 239, 0}, {255, 239, 0}, {255, 239, 0}, {255, 240, 0}, {255, 240, 0}, {255, 240, 0}, {255, 240, 0}, {255, 241, 0}, {255, 241, 0}, {255, 241, 0}, {255, 241, 0}, {255, 242, 0}, {255, 242, 0}, {255, 242, 0}, {255, 242, 0}, {255, 243, 0}, {255, 243, 0}, {255, 243, 0}, {255, 244, 0}, {255, 244, 0}, {255, 244, 0}, {255, 244, 0}, {255, 245, 0}, {255, 245, 0}, {255, 245, 0}, {255, 245, 0}, {255, 246, 0}, {255, 246, 0}, {255, 246, 0}, {255, 246, 0}, {255, 247, 0}, {255, 247, 0}, {255, 247, 0}, {255, 247, 0}, {255, 248, 0}, {255, 248, 0}, {255, 248, 0}, {255, 248, 0}, {255, 249, 0}, {255, 249, 0}, {255, 249, 0}, {255, 249, 0}, {255, 250, 0}, {255, 250, 0}, {255, 250, 0}, {255, 250, 0}, {255, 251, 0}, {255, 251, 0}, {255, 251, 0}, {255, 251, 0}, {255, 252, 0}, {255, 252, 0}, {255, 252, 0}, {255, 252, 0}, {255, 253, 0}, {255, 253, 0}, {255, 253, 0}, {255, 253, 0}, {255, 254, 0}, {255, 254, 0}, {255, 254, 0}, {255, 254, 0}, {255, 255, 0}, {255, 255, 0}}; const rgb_store copper_colormap[1000] = { {0, 0, 0}, {0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {2, 1, 1}, {2, 1, 1}, {2, 1, 1}, {3, 2, 1}, {3, 2, 1}, {3, 2, 1}, {4, 2, 1}, {4, 2, 2}, {4, 3, 2}, {4, 3, 2}, {5, 3, 2}, {5, 3, 2}, {5, 3, 2}, {6, 4, 2}, {6, 4, 2}, {6, 4, 3}, {7, 4, 3}, {7, 4, 3}, {7, 5, 3}, {8, 5, 3}, {8, 5, 3}, {8, 5, 3}, {9, 5, 3}, {9, 6, 4}, {9, 6, 4}, {10, 6, 4}, {10, 6, 4}, {10, 6, 4}, {11, 7, 4}, {11, 7, 4}, {11, 7, 4}, {11, 7, 5}, {12, 7, 5}, {12, 8, 5}, {12, 8, 5}, {13, 8, 5}, {13, 8, 5}, {13, 8, 5}, {14, 9, 5}, {14, 9, 6}, {14, 9, 6}, {15, 9, 6}, {15, 9, 6}, {15, 10, 6}, {16, 10, 6}, {16, 10, 6}, {16, 10, 6}, {17, 10, 7}, {17, 11, 7}, {17, 11, 7}, {18, 11, 7}, {18, 11, 7}, {18, 11, 7}, {19, 12, 7}, {19, 12, 7}, {19, 12, 8}, {19, 12, 8}, {20, 12, 8}, {20, 13, 8}, {20, 13, 8}, {21, 13, 8}, {21, 13, 8}, {21, 13, 9}, {22, 14, 9}, {22, 14, 9}, {22, 14, 9}, {23, 14, 9}, {23, 14, 9}, {23, 15, 9}, {24, 15, 9}, {24, 15, 10}, {24, 15, 10}, {25, 15, 10}, {25, 16, 10}, {25, 16, 10}, {26, 16, 10}, {26, 16, 10}, {26, 16, 10}, {26, 17, 11}, {27, 17, 11}, {27, 17, 11}, {27, 17, 11}, {28, 17, 11}, {28, 18, 11}, {28, 18, 11}, {29, 18, 11}, {29, 18, 12}, {29, 18, 12}, {30, 19, 12}, {30, 19, 12}, {30, 19, 12}, {31, 19, 12}, {31, 19, 12}, {31, 20, 12}, {32, 20, 13}, {32, 20, 13}, {32, 20, 13}, {33, 20, 13}, {33, 21, 13}, {33, 21, 13}, {34, 21, 13}, {34, 21, 13}, {34, 21, 14}, {34, 22, 14}, {35, 22, 14}, {35, 22, 14}, {35, 22, 14}, {36, 22, 14}, {36, 23, 14}, {36, 23, 14}, {37, 23, 15}, {37, 23, 15}, {37, 23, 15}, {38, 24, 15}, {38, 24, 15}, {38, 24, 15}, {39, 24, 15}, {39, 24, 15}, {39, 25, 16}, {40, 25, 16}, {40, 25, 16}, {40, 25, 16}, {41, 25, 16}, {41, 26, 16}, {41, 26, 16}, {41, 26, 17}, {42, 26, 17}, {42, 26, 17}, {42, 27, 17}, {43, 27, 17}, {43, 27, 17}, {43, 27, 17}, {44, 27, 17}, {44, 28, 18}, {44, 28, 18}, {45, 28, 18}, {45, 28, 18}, {45, 28, 18}, {46, 29, 18}, {46, 29, 18}, {46, 29, 18}, {47, 29, 19}, {47, 29, 19}, {47, 30, 19}, {48, 30, 19}, {48, 30, 19}, {48, 30, 19}, {48, 30, 19}, {49, 31, 19}, {49, 31, 20}, {49, 31, 20}, {50, 31, 20}, {50, 31, 20}, {50, 32, 20}, {51, 32, 20}, {51, 32, 20}, {51, 32, 20}, {52, 32, 21}, {52, 33, 21}, {52, 33, 21}, {53, 33, 21}, {53, 33, 21}, {53, 33, 21}, {54, 34, 21}, {54, 34, 21}, {54, 34, 22}, {55, 34, 22}, {55, 34, 22}, {55, 34, 22}, {56, 35, 22}, {56, 35, 22}, {56, 35, 22}, {56, 35, 22}, {57, 35, 23}, {57, 36, 23}, {57, 36, 23}, {58, 36, 23}, {58, 36, 23}, {58, 36, 23}, {59, 37, 23}, {59, 37, 23}, {59, 37, 24}, {60, 37, 24}, {60, 37, 24}, {60, 38, 24}, {61, 38, 24}, {61, 38, 24}, {61, 38, 24}, {62, 38, 25}, {62, 39, 25}, {62, 39, 25}, {63, 39, 25}, {63, 39, 25}, {63, 39, 25}, {63, 40, 25}, {64, 40, 25}, {64, 40, 26}, {64, 40, 26}, {65, 40, 26}, {65, 41, 26}, {65, 41, 26}, {66, 41, 26}, {66, 41, 26}, {66, 41, 26}, {67, 42, 27}, {67, 42, 27}, {67, 42, 27}, {68, 42, 27}, {68, 42, 27}, {68, 43, 27}, {69, 43, 27}, {69, 43, 27}, {69, 43, 28}, {70, 43, 28}, {70, 44, 28}, {70, 44, 28}, {71, 44, 28}, {71, 44, 28}, {71, 44, 28}, {71, 45, 28}, {72, 45, 29}, {72, 45, 29}, {72, 45, 29}, {73, 45, 29}, {73, 46, 29}, {73, 46, 29}, {74, 46, 29}, {74, 46, 29}, {74, 46, 30}, {75, 47, 30}, {75, 47, 30}, {75, 47, 30}, {76, 47, 30}, {76, 47, 30}, {76, 48, 30}, {77, 48, 30}, {77, 48, 31}, {77, 48, 31}, {78, 48, 31}, {78, 49, 31}, {78, 49, 31}, {78, 49, 31}, {79, 49, 31}, {79, 49, 31}, {79, 50, 32}, {80, 50, 32}, {80, 50, 32}, {80, 50, 32}, {81, 50, 32}, {81, 51, 32}, {81, 51, 32}, {82, 51, 33}, {82, 51, 33}, {82, 51, 33}, {83, 52, 33}, {83, 52, 33}, {83, 52, 33}, {84, 52, 33}, {84, 52, 33}, {84, 53, 34}, {85, 53, 34}, {85, 53, 34}, {85, 53, 34}, {86, 53, 34}, {86, 54, 34}, {86, 54, 34}, {86, 54, 34}, {87, 54, 35}, {87, 54, 35}, {87, 55, 35}, {88, 55, 35}, {88, 55, 35}, {88, 55, 35}, {89, 55, 35}, {89, 56, 35}, {89, 56, 36}, {90, 56, 36}, {90, 56, 36}, {90, 56, 36}, {91, 57, 36}, {91, 57, 36}, {91, 57, 36}, {92, 57, 36}, {92, 57, 37}, {92, 58, 37}, {93, 58, 37}, {93, 58, 37}, {93, 58, 37}, {93, 58, 37}, {94, 59, 37}, {94, 59, 37}, {94, 59, 38}, {95, 59, 38}, {95, 59, 38}, {95, 60, 38}, {96, 60, 38}, {96, 60, 38}, {96, 60, 38}, {97, 60, 38}, {97, 61, 39}, {97, 61, 39}, {98, 61, 39}, {98, 61, 39}, {98, 61, 39}, {99, 62, 39}, {99, 62, 39}, {99, 62, 39}, {100, 62, 40}, {100, 62, 40}, {100, 63, 40}, {101, 63, 40}, {101, 63, 40}, {101, 63, 40}, {101, 63, 40}, {102, 64, 41}, {102, 64, 41}, {102, 64, 41}, {103, 64, 41}, {103, 64, 41}, {103, 65, 41}, {104, 65, 41}, {104, 65, 41}, {104, 65, 42}, {105, 65, 42}, {105, 66, 42}, {105, 66, 42}, {106, 66, 42}, {106, 66, 42}, {106, 66, 42}, {107, 67, 42}, {107, 67, 43}, {107, 67, 43}, {108, 67, 43}, {108, 67, 43}, {108, 68, 43}, {108, 68, 43}, {109, 68, 43}, {109, 68, 43}, {109, 68, 44}, {110, 69, 44}, {110, 69, 44}, {110, 69, 44}, {111, 69, 44}, {111, 69, 44}, {111, 70, 44}, {112, 70, 44}, {112, 70, 45}, {112, 70, 45}, {113, 70, 45}, {113, 71, 45}, {113, 71, 45}, {114, 71, 45}, {114, 71, 45}, {114, 71, 45}, {115, 72, 46}, {115, 72, 46}, {115, 72, 46}, {116, 72, 46}, {116, 72, 46}, {116, 73, 46}, {116, 73, 46}, {117, 73, 46}, {117, 73, 47}, {117, 73, 47}, {118, 74, 47}, {118, 74, 47}, {118, 74, 47}, {119, 74, 47}, {119, 74, 47}, {119, 75, 47}, {120, 75, 48}, {120, 75, 48}, {120, 75, 48}, {121, 75, 48}, {121, 76, 48}, {121, 76, 48}, {122, 76, 48}, {122, 76, 49}, {122, 76, 49}, {123, 77, 49}, {123, 77, 49}, {123, 77, 49}, {123, 77, 49}, {124, 77, 49}, {124, 78, 49}, {124, 78, 50}, {125, 78, 50}, {125, 78, 50}, {125, 78, 50}, {126, 79, 50}, {126, 79, 50}, {126, 79, 50}, {127, 79, 50}, {127, 79, 51}, {127, 80, 51}, {128, 80, 51}, {128, 80, 51}, {128, 80, 51}, {129, 80, 51}, {129, 81, 51}, {129, 81, 51}, {130, 81, 52}, {130, 81, 52}, {130, 81, 52}, {130, 82, 52}, {131, 82, 52}, {131, 82, 52}, {131, 82, 52}, {132, 82, 52}, {132, 83, 53}, {132, 83, 53}, {133, 83, 53}, {133, 83, 53}, {133, 83, 53}, {134, 84, 53}, {134, 84, 53}, {134, 84, 53}, {135, 84, 54}, {135, 84, 54}, {135, 85, 54}, {136, 85, 54}, {136, 85, 54}, {136, 85, 54}, {137, 85, 54}, {137, 86, 54}, {137, 86, 55}, {138, 86, 55}, {138, 86, 55}, {138, 86, 55}, {138, 87, 55}, {139, 87, 55}, {139, 87, 55}, {139, 87, 55}, {140, 87, 56}, {140, 88, 56}, {140, 88, 56}, {141, 88, 56}, {141, 88, 56}, {141, 88, 56}, {142, 89, 56}, {142, 89, 57}, {142, 89, 57}, {143, 89, 57}, {143, 89, 57}, {143, 90, 57}, {144, 90, 57}, {144, 90, 57}, {144, 90, 57}, {145, 90, 58}, {145, 91, 58}, {145, 91, 58}, {145, 91, 58}, {146, 91, 58}, {146, 91, 58}, {146, 92, 58}, {147, 92, 58}, {147, 92, 59}, {147, 92, 59}, {148, 92, 59}, {148, 93, 59}, {148, 93, 59}, {149, 93, 59}, {149, 93, 59}, {149, 93, 59}, {150, 94, 60}, {150, 94, 60}, {150, 94, 60}, {151, 94, 60}, {151, 94, 60}, {151, 95, 60}, {152, 95, 60}, {152, 95, 60}, {152, 95, 61}, {153, 95, 61}, {153, 96, 61}, {153, 96, 61}, {153, 96, 61}, {154, 96, 61}, {154, 96, 61}, {154, 97, 61}, {155, 97, 62}, {155, 97, 62}, {155, 97, 62}, {156, 97, 62}, {156, 98, 62}, {156, 98, 62}, {157, 98, 62}, {157, 98, 62}, {157, 98, 63}, {158, 99, 63}, {158, 99, 63}, {158, 99, 63}, {159, 99, 63}, {159, 99, 63}, {159, 100, 63}, {160, 100, 63}, {160, 100, 64}, {160, 100, 64}, {160, 100, 64}, {161, 101, 64}, {161, 101, 64}, {161, 101, 64}, {162, 101, 64}, {162, 101, 65}, {162, 101, 65}, {163, 102, 65}, {163, 102, 65}, {163, 102, 65}, {164, 102, 65}, {164, 102, 65}, {164, 103, 65}, {165, 103, 66}, {165, 103, 66}, {165, 103, 66}, {166, 103, 66}, {166, 104, 66}, {166, 104, 66}, {167, 104, 66}, {167, 104, 66}, {167, 104, 67}, {168, 105, 67}, {168, 105, 67}, {168, 105, 67}, {168, 105, 67}, {169, 105, 67}, {169, 106, 67}, {169, 106, 67}, {170, 106, 68}, {170, 106, 68}, {170, 106, 68}, {171, 107, 68}, {171, 107, 68}, {171, 107, 68}, {172, 107, 68}, {172, 107, 68}, {172, 108, 69}, {173, 108, 69}, {173, 108, 69}, {173, 108, 69}, {174, 108, 69}, {174, 109, 69}, {174, 109, 69}, {175, 109, 69}, {175, 109, 70}, {175, 109, 70}, {175, 110, 70}, {176, 110, 70}, {176, 110, 70}, {176, 110, 70}, {177, 110, 70}, {177, 111, 70}, {177, 111, 71}, {178, 111, 71}, {178, 111, 71}, {178, 111, 71}, {179, 112, 71}, {179, 112, 71}, {179, 112, 71}, {180, 112, 71}, {180, 112, 72}, {180, 113, 72}, {181, 113, 72}, {181, 113, 72}, {181, 113, 72}, {182, 113, 72}, {182, 114, 72}, {182, 114, 73}, {183, 114, 73}, {183, 114, 73}, {183, 114, 73}, {183, 115, 73}, {184, 115, 73}, {184, 115, 73}, {184, 115, 73}, {185, 115, 74}, {185, 116, 74}, {185, 116, 74}, {186, 116, 74}, {186, 116, 74}, {186, 116, 74}, {187, 117, 74}, {187, 117, 74}, {187, 117, 75}, {188, 117, 75}, {188, 117, 75}, {188, 118, 75}, {189, 118, 75}, {189, 118, 75}, {189, 118, 75}, {190, 118, 75}, {190, 119, 76}, {190, 119, 76}, {190, 119, 76}, {191, 119, 76}, {191, 119, 76}, {191, 120, 76}, {192, 120, 76}, {192, 120, 76}, {192, 120, 77}, {193, 120, 77}, {193, 121, 77}, {193, 121, 77}, {194, 121, 77}, {194, 121, 77}, {194, 121, 77}, {195, 122, 77}, {195, 122, 78}, {195, 122, 78}, {196, 122, 78}, {196, 122, 78}, {196, 123, 78}, {197, 123, 78}, {197, 123, 78}, {197, 123, 78}, {198, 123, 79}, {198, 124, 79}, {198, 124, 79}, {198, 124, 79}, {199, 124, 79}, {199, 124, 79}, {199, 125, 79}, {200, 125, 79}, {200, 125, 80}, {200, 125, 80}, {201, 125, 80}, {201, 126, 80}, {201, 126, 80}, {202, 126, 80}, {202, 126, 80}, {202, 126, 81}, {203, 127, 81}, {203, 127, 81}, {203, 127, 81}, {204, 127, 81}, {204, 127, 81}, {204, 128, 81}, {205, 128, 81}, {205, 128, 82}, {205, 128, 82}, {205, 128, 82}, {206, 129, 82}, {206, 129, 82}, {206, 129, 82}, {207, 129, 82}, {207, 129, 82}, {207, 130, 83}, {208, 130, 83}, {208, 130, 83}, {208, 130, 83}, {209, 130, 83}, {209, 131, 83}, {209, 131, 83}, {210, 131, 83}, {210, 131, 84}, {210, 131, 84}, {211, 132, 84}, {211, 132, 84}, {211, 132, 84}, {212, 132, 84}, {212, 132, 84}, {212, 133, 84}, {212, 133, 85}, {213, 133, 85}, {213, 133, 85}, {213, 133, 85}, {214, 134, 85}, {214, 134, 85}, {214, 134, 85}, {215, 134, 85}, {215, 134, 86}, {215, 135, 86}, {216, 135, 86}, {216, 135, 86}, {216, 135, 86}, {217, 135, 86}, {217, 136, 86}, {217, 136, 86}, {218, 136, 87}, {218, 136, 87}, {218, 136, 87}, {219, 137, 87}, {219, 137, 87}, {219, 137, 87}, {220, 137, 87}, {220, 137, 87}, {220, 138, 88}, {220, 138, 88}, {221, 138, 88}, {221, 138, 88}, {221, 138, 88}, {222, 139, 88}, {222, 139, 88}, {222, 139, 89}, {223, 139, 89}, {223, 139, 89}, {223, 140, 89}, {224, 140, 89}, {224, 140, 89}, {224, 140, 89}, {225, 140, 89}, {225, 141, 90}, {225, 141, 90}, {226, 141, 90}, {226, 141, 90}, {226, 141, 90}, {227, 142, 90}, {227, 142, 90}, {227, 142, 90}, {227, 142, 91}, {228, 142, 91}, {228, 143, 91}, {228, 143, 91}, {229, 143, 91}, {229, 143, 91}, {229, 143, 91}, {230, 144, 91}, {230, 144, 92}, {230, 144, 92}, {231, 144, 92}, {231, 144, 92}, {231, 145, 92}, {232, 145, 92}, {232, 145, 92}, {232, 145, 92}, {233, 145, 93}, {233, 146, 93}, {233, 146, 93}, {234, 146, 93}, {234, 146, 93}, {234, 146, 93}, {235, 147, 93}, {235, 147, 93}, {235, 147, 94}, {235, 147, 94}, {236, 147, 94}, {236, 148, 94}, {236, 148, 94}, {237, 148, 94}, {237, 148, 94}, {237, 148, 94}, {238, 149, 95}, {238, 149, 95}, {238, 149, 95}, {239, 149, 95}, {239, 149, 95}, {239, 150, 95}, {240, 150, 95}, {240, 150, 95}, {240, 150, 96}, {241, 150, 96}, {241, 151, 96}, {241, 151, 96}, {242, 151, 96}, {242, 151, 96}, {242, 151, 96}, {242, 152, 97}, {243, 152, 97}, {243, 152, 97}, {243, 152, 97}, {244, 152, 97}, {244, 153, 97}, {244, 153, 97}, {245, 153, 97}, {245, 153, 98}, {245, 153, 98}, {246, 154, 98}, {246, 154, 98}, {246, 154, 98}, {247, 154, 98}, {247, 154, 98}, {247, 155, 98}, {248, 155, 99}, {248, 155, 99}, {248, 155, 99}, {249, 155, 99}, {249, 156, 99}, {249, 156, 99}, {250, 156, 99}, {250, 156, 99}, {250, 156, 100}, {250, 157, 100}, {251, 157, 100}, {251, 157, 100}, {251, 157, 100}, {252, 157, 100}, {252, 158, 100}, {252, 158, 100}, {253, 158, 101}, {253, 158, 101}, {253, 158, 101}, {253, 159, 101}, {253, 159, 101}, {254, 159, 101}, {254, 159, 101}, {254, 159, 101}, {254, 160, 102}, {254, 160, 102}, {254, 160, 102}, {254, 160, 102}, {254, 160, 102}, {255, 161, 102}, {255, 161, 102}, {255, 161, 102}, {255, 161, 103}, {255, 161, 103}, {255, 162, 103}, {255, 162, 103}, {255, 162, 103}, {255, 162, 103}, {255, 162, 103}, {255, 163, 103}, {255, 163, 104}, {255, 163, 104}, {255, 163, 104}, {255, 163, 104}, {255, 164, 104}, {255, 164, 104}, {255, 164, 104}, {255, 164, 105}, {255, 164, 105}, {255, 165, 105}, {255, 165, 105}, {255, 165, 105}, {255, 165, 105}, {255, 165, 105}, {255, 166, 105}, {255, 166, 106}, {255, 166, 106}, {255, 166, 106}, {255, 166, 106}, {255, 167, 106}, {255, 167, 106}, {255, 167, 106}, {255, 167, 106}, {255, 167, 107}, {255, 168, 107}, {255, 168, 107}, {255, 168, 107}, {255, 168, 107}, {255, 168, 107}, {255, 168, 107}, {255, 169, 107}, {255, 169, 108}, {255, 169, 108}, {255, 169, 108}, {255, 169, 108}, {255, 170, 108}, {255, 170, 108}, {255, 170, 108}, {255, 170, 108}, {255, 170, 109}, {255, 171, 109}, {255, 171, 109}, {255, 171, 109}, {255, 171, 109}, {255, 171, 109}, {255, 172, 109}, {255, 172, 109}, {255, 172, 110}, {255, 172, 110}, {255, 172, 110}, {255, 173, 110}, {255, 173, 110}, {255, 173, 110}, {255, 173, 110}, {255, 173, 110}, {255, 174, 111}, {255, 174, 111}, {255, 174, 111}, {255, 174, 111}, {255, 174, 111}, {255, 175, 111}, {255, 175, 111}, {255, 175, 111}, {255, 175, 112}, {255, 175, 112}, {255, 176, 112}, {255, 176, 112}, {255, 176, 112}, {255, 176, 112}, {255, 176, 112}, {255, 177, 113}, {255, 177, 113}, {255, 177, 113}, {255, 177, 113}, {255, 177, 113}, {255, 178, 113}, {255, 178, 113}, {255, 178, 113}, {255, 178, 114}, {255, 178, 114}, {255, 179, 114}, {255, 179, 114}, {255, 179, 114}, {255, 179, 114}, {255, 179, 114}, {255, 180, 114}, {255, 180, 115}, {255, 180, 115}, {255, 180, 115}, {255, 180, 115}, {255, 181, 115}, {255, 181, 115}, {255, 181, 115}, {255, 181, 115}, {255, 181, 116}, {255, 182, 116}, {255, 182, 116}, {255, 182, 116}, {255, 182, 116}, {255, 182, 116}, {255, 183, 116}, {255, 183, 116}, {255, 183, 117}, {255, 183, 117}, {255, 183, 117}, {255, 184, 117}, {255, 184, 117}, {255, 184, 117}, {255, 184, 117}, {255, 184, 117}, {255, 185, 118}, {255, 185, 118}, {255, 185, 118}, {255, 185, 118}, {255, 185, 118}, {255, 186, 118}, {255, 186, 118}, {255, 186, 118}, {255, 186, 119}, {255, 186, 119}, {255, 187, 119}, {255, 187, 119}, {255, 187, 119}, {255, 187, 119}, {255, 187, 119}, {255, 188, 119}, {255, 188, 120}, {255, 188, 120}, {255, 188, 120}, {255, 188, 120}, {255, 189, 120}, {255, 189, 120}, {255, 189, 120}, {255, 189, 121}, {255, 189, 121}, {255, 190, 121}, {255, 190, 121}, {255, 190, 121}, {255, 190, 121}, {255, 190, 121}, {255, 191, 121}, {255, 191, 122}, {255, 191, 122}, {255, 191, 122}, {255, 191, 122}, {255, 192, 122}, {255, 192, 122}, {255, 192, 122}, {255, 192, 122}, {255, 192, 123}, {255, 193, 123}, {255, 193, 123}, {255, 193, 123}, {255, 193, 123}, {255, 193, 123}, {255, 194, 123}, {255, 194, 123}, {255, 194, 124}, {255, 194, 124}, {255, 194, 124}, {255, 195, 124}, {255, 195, 124}, {255, 195, 124}, {255, 195, 124}, {255, 195, 124}, {255, 196, 125}, {255, 196, 125}, {255, 196, 125}, {255, 196, 125}, {255, 196, 125}, {255, 197, 125}, {255, 197, 125}, {255, 197, 125}, {255, 197, 126}, {255, 197, 126}, {255, 198, 126}, {255, 198, 126}, {255, 198, 126}, {255, 198, 126}, {255, 198, 126}, {255, 199, 126}, {255, 199, 127}, {255, 199, 127}, {255, 199, 127}}; const rgb_store gray_colormap[1000] = { {255}, {255}, {254, 254, 254}, {254, 254, 254}, {254, 254, 254}, {254, 254, 254}, {253, 253, 253}, {253, 253, 253}, {253, 253, 253}, {253, 253, 253}, {252, 252, 252}, {252, 252, 252}, {252, 252, 252}, {252, 252, 252}, {251, 251, 251}, {251, 251, 251}, {251, 251, 251}, {251, 251, 251}, {250, 250, 250}, {250, 250, 250}, {250, 250, 250}, {250, 250, 250}, {249, 249, 249}, {249, 249, 249}, {249, 249, 249}, {249, 249, 249}, {248, 248, 248}, {248, 248, 248}, {248, 248, 248}, {248, 248, 248}, {247, 247, 247}, {247, 247, 247}, {247, 247, 247}, {247, 247, 247}, {246, 246, 246}, {246, 246, 246}, {246, 246, 246}, {246, 246, 246}, {245, 245, 245}, {245, 245, 245}, {245, 245, 245}, {245, 245, 245}, {244, 244, 244}, {244, 244, 244}, {244, 244, 244}, {244, 244, 244}, {243, 243, 243}, {243, 243, 243}, {243, 243, 243}, {242, 242, 242}, {242, 242, 242}, {242, 242, 242}, {242, 242, 242}, {241, 241, 241}, {241, 241, 241}, {241, 241, 241}, {241, 241, 241}, {240, 240, 240}, {240, 240, 240}, {240, 240, 240}, {240, 240, 240}, {239, 239, 239}, {239, 239, 239}, {239, 239, 239}, {239, 239, 239}, {238, 238, 238}, {238, 238, 238}, {238, 238, 238}, {238, 238, 238}, {237, 237, 237}, {237, 237, 237}, {237, 237, 237}, {237, 237, 237}, {236, 236, 236}, {236, 236, 236}, {236, 236, 236}, {236, 236, 236}, {235, 235, 235}, {235, 235, 235}, {235, 235, 235}, {235, 235, 235}, {234, 234, 234}, {234, 234, 234}, {234, 234, 234}, {234, 234, 234}, {233, 233, 233}, {233, 233, 233}, {233, 233, 233}, {233, 233, 233}, {232, 232, 232}, {232, 232, 232}, {232, 232, 232}, {232, 232, 232}, {231, 231, 231}, {231, 231, 231}, {231, 231, 231}, {230, 230, 230}, {230, 230, 230}, {230, 230, 230}, {230, 230, 230}, {229, 229, 229}, {229, 229, 229}, {229, 229, 229}, {229, 229, 229}, {228, 228, 228}, {228, 228, 228}, {228, 228, 228}, {228, 228, 228}, {227, 227, 227}, {227, 227, 227}, {227, 227, 227}, {227, 227, 227}, {226, 226, 226}, {226, 226, 226}, {226, 226, 226}, {226, 226, 226}, {225, 225, 225}, {225, 225, 225}, {225, 225, 225}, {225, 225, 225}, {224, 224, 224}, {224, 224, 224}, {224, 224, 224}, {224, 224, 224}, {223, 223, 223}, {223, 223, 223}, {223, 223, 223}, {223, 223, 223}, {222, 222, 222}, {222, 222, 222}, {222, 222, 222}, {222, 222, 222}, {221, 221, 221}, {221, 221, 221}, {221, 221, 221}, {221, 221, 221}, {220, 220, 220}, {220, 220, 220}, {220, 220, 220}, {220, 220, 220}, {219, 219, 219}, {219, 219, 219}, {219, 219, 219}, {218, 218, 218}, {218, 218, 218}, {218, 218, 218}, {218, 218, 218}, {217, 217, 217}, {217, 217, 217}, {217, 217, 217}, {217, 217, 217}, {216, 216, 216}, {216, 216, 216}, {216, 216, 216}, {216, 216, 216}, {215, 215, 215}, {215, 215, 215}, {215, 215, 215}, {215, 215, 215}, {214, 214, 214}, {214, 214, 214}, {214, 214, 214}, {214, 214, 214}, {213, 213, 213}, {213, 213, 213}, {213, 213, 213}, {213, 213, 213}, {212, 212, 212}, {212, 212, 212}, {212, 212, 212}, {212, 212, 212}, {211, 211, 211}, {211, 211, 211}, {211, 211, 211}, {211, 211, 211}, {210, 210, 210}, {210, 210, 210}, {210, 210, 210}, {210, 210, 210}, {209, 209, 209}, {209, 209, 209}, {209, 209, 209}, {209, 209, 209}, {208, 208, 208}, {208, 208, 208}, {208, 208, 208}, {208, 208, 208}, {207, 207, 207}, {207, 207, 207}, {207, 207, 207}, {207, 207, 207}, {206, 206, 206}, {206, 206, 206}, {206, 206, 206}, {205, 205, 205}, {205, 205, 205}, {205, 205, 205}, {205, 205, 205}, {204, 204, 204}, {204, 204, 204}, {204, 204, 204}, {204, 204, 204}, {203, 203, 203}, {203, 203, 203}, {203, 203, 203}, {203, 203, 203}, {202, 202, 202}, {202, 202, 202}, {202, 202, 202}, {202, 202, 202}, {201, 201, 201}, {201, 201, 201}, {201, 201, 201}, {201, 201, 201}, {200, 200, 200}, {200, 200, 200}, {200, 200, 200}, {200, 200, 200}, {199, 199, 199}, {199, 199, 199}, {199, 199, 199}, {199, 199, 199}, {198, 198, 198}, {198, 198, 198}, {198, 198, 198}, {198, 198, 198}, {197, 197, 197}, {197, 197, 197}, {197, 197, 197}, {197, 197, 197}, {196, 196, 196}, {196, 196, 196}, {196, 196, 196}, {196, 196, 196}, {195, 195, 195}, {195, 195, 195}, {195, 195, 195}, {195, 195, 195}, {194, 194, 194}, {194, 194, 194}, {194, 194, 194}, {193, 193, 193}, {193, 193, 193}, {193, 193, 193}, {193, 193, 193}, {192, 192, 192}, {192, 192, 192}, {192, 192, 192}, {192, 192, 192}, {191, 191, 191}, {191, 191, 191}, {191, 191, 191}, {191, 191, 191}, {190, 190, 190}, {190, 190, 190}, {190, 190, 190}, {190, 190, 190}, {189, 189, 189}, {189, 189, 189}, {189, 189, 189}, {189, 189, 189}, {188, 188, 188}, {188, 188, 188}, {188, 188, 188}, {188, 188, 188}, {187, 187, 187}, {187, 187, 187}, {187, 187, 187}, {187, 187, 187}, {186, 186, 186}, {186, 186, 186}, {186, 186, 186}, {186, 186, 186}, {185, 185, 185}, {185, 185, 185}, {185, 185, 185}, {185, 185, 185}, {184, 184, 184}, {184, 184, 184}, {184, 184, 184}, {184, 184, 184}, {183, 183, 183}, {183, 183, 183}, {183, 183, 183}, {183, 183, 183}, {182, 182, 182}, {182, 182, 182}, {182, 182, 182}, {181, 181, 181}, {181, 181, 181}, {181, 181, 181}, {181, 181, 181}, {180, 180, 180}, {180, 180, 180}, {180, 180, 180}, {180, 180, 180}, {179, 179, 179}, {179, 179, 179}, {179, 179, 179}, {179, 179, 179}, {178, 178, 178}, {178, 178, 178}, {178, 178, 178}, {178, 178, 178}, {177, 177, 177}, {177, 177, 177}, {177, 177, 177}, {177, 177, 177}, {176, 176, 176}, {176, 176, 176}, {176, 176, 176}, {176, 176, 176}, {175, 175, 175}, {175, 175, 175}, {175, 175, 175}, {175, 175, 175}, {174, 174, 174}, {174, 174, 174}, {174, 174, 174}, {174, 174, 174}, {173, 173, 173}, {173, 173, 173}, {173, 173, 173}, {173, 173, 173}, {172, 172, 172}, {172, 172, 172}, {172, 172, 172}, {172, 172, 172}, {171, 171, 171}, {171, 171, 171}, {171, 171, 171}, {171, 171, 171}, {170, 170, 170}, {170, 170, 170}, {170, 170, 170}, {169, 169, 169}, {169, 169, 169}, {169, 169, 169}, {169, 169, 169}, {168, 168, 168}, {168, 168, 168}, {168, 168, 168}, {168, 168, 168}, {167, 167, 167}, {167, 167, 167}, {167, 167, 167}, {167, 167, 167}, {166, 166, 166}, {166, 166, 166}, {166, 166, 166}, {166, 166, 166}, {165, 165, 165}, {165, 165, 165}, {165, 165, 165}, {165, 165, 165}, {164, 164, 164}, {164, 164, 164}, {164, 164, 164}, {164, 164, 164}, {163, 163, 163}, {163, 163, 163}, {163, 163, 163}, {163, 163, 163}, {162, 162, 162}, {162, 162, 162}, {162, 162, 162}, {162, 162, 162}, {161, 161, 161}, {161, 161, 161}, {161, 161, 161}, {161, 161, 161}, {160, 160, 160}, {160, 160, 160}, {160, 160, 160}, {160, 160, 160}, {159, 159, 159}, {159, 159, 159}, {159, 159, 159}, {159, 159, 159}, {158, 158, 158}, {158, 158, 158}, {158, 158, 158}, {157, 157, 157}, {157, 157, 157}, {157, 157, 157}, {157, 157, 157}, {156, 156, 156}, {156, 156, 156}, {156, 156, 156}, {156, 156, 156}, {155, 155, 155}, {155, 155, 155}, {155, 155, 155}, {155, 155, 155}, {154, 154, 154}, {154, 154, 154}, {154, 154, 154}, {154, 154, 154}, {153, 153, 153}, {153, 153, 153}, {153, 153, 153}, {153, 153, 153}, {152, 152, 152}, {152, 152, 152}, {152, 152, 152}, {152, 152, 152}, {151, 151, 151}, {151, 151, 151}, {151, 151, 151}, {151, 151, 151}, {150, 150, 150}, {150, 150, 150}, {150, 150, 150}, {150, 150, 150}, {149, 149, 149}, {149, 149, 149}, {149, 149, 149}, {149, 149, 149}, {148, 148, 148}, {148, 148, 148}, {148, 148, 148}, {148, 148, 148}, {147, 147, 147}, {147, 147, 147}, {147, 147, 147}, {147, 147, 147}, {146, 146, 146}, {146, 146, 146}, {146, 146, 146}, {145, 145, 145}, {145, 145, 145}, {145, 145, 145}, {145, 145, 145}, {144, 144, 144}, {144, 144, 144}, {144, 144, 144}, {144, 144, 144}, {143, 143, 143}, {143, 143, 143}, {143, 143, 143}, {143, 143, 143}, {142, 142, 142}, {142, 142, 142}, {142, 142, 142}, {142, 142, 142}, {141, 141, 141}, {141, 141, 141}, {141, 141, 141}, {141, 141, 141}, {140, 140, 140}, {140, 140, 140}, {140, 140, 140}, {140, 140, 140}, {139, 139, 139}, {139, 139, 139}, {139, 139, 139}, {139, 139, 139}, {138, 138, 138}, {138, 138, 138}, {138, 138, 138}, {138, 138, 138}, {137, 137, 137}, {137, 137, 137}, {137, 137, 137}, {137, 137, 137}, {136, 136, 136}, {136, 136, 136}, {136, 136, 136}, {136, 136, 136}, {135, 135, 135}, {135, 135, 135}, {135, 135, 135}, {135, 135, 135}, {134, 134, 134}, {134, 134, 134}, {134, 134, 134}, {133, 133, 133}, {133, 133, 133}, {133, 133, 133}, {133, 133, 133}, {132, 132, 132}, {132, 132, 132}, {132, 132, 132}, {132, 132, 132}, {131, 131, 131}, {131, 131, 131}, {131, 131, 131}, {131, 131, 131}, {130, 130, 130}, {130, 130, 130}, {130, 130, 130}, {130, 130, 130}, {129, 129, 129}, {129, 129, 129}, {129, 129, 129}, {129, 129, 129}, {128, 128, 128}, {128, 128, 128}, {128, 128, 128}, {128, 128, 128}, {127, 127, 127}, {127, 127, 127}, {127, 127, 127}, {127, 127, 127}, {126, 126, 126}, {126, 126, 126}, {126, 126, 126}, {126, 126, 126}, {125, 125, 125}, {125, 125, 125}, {125, 125, 125}, {125, 125, 125}, {124, 124, 124}, {124, 124, 124}, {124, 124, 124}, {124, 124, 124}, {123, 123, 123}, {123, 123, 123}, {123, 123, 123}, {123, 123, 123}, {122, 122, 122}, {122, 122, 122}, {122, 122, 122}, {122, 122, 122}, {121, 121, 121}, {121, 121, 121}, {121, 121, 121}, {120, 120, 120}, {120, 120, 120}, {120, 120, 120}, {120, 120, 120}, {119, 119, 119}, {119, 119, 119}, {119, 119, 119}, {119, 119, 119}, {118, 118, 118}, {118, 118, 118}, {118, 118, 118}, {118, 118, 118}, {117, 117, 117}, {117, 117, 117}, {117, 117, 117}, {117, 117, 117}, {116, 116, 116}, {116, 116, 116}, {116, 116, 116}, {116, 116, 116}, {115, 115, 115}, {115, 115, 115}, {115, 115, 115}, {115, 115, 115}, {114, 114, 114}, {114, 114, 114}, {114, 114, 114}, {114, 114, 114}, {113, 113, 113}, {113, 113, 113}, {113, 113, 113}, {113, 113, 113}, {112, 112, 112}, {112, 112, 112}, {112, 112, 112}, {112, 112, 112}, {111, 111, 111}, {111, 111, 111}, {111, 111, 111}, {111, 111, 111}, {110, 110, 110}, {110, 110, 110}, {110, 110, 110}, {110, 110, 110}, {109, 109, 109}, {109, 109, 109}, {109, 109, 109}, {108, 108, 108}, {108, 108, 108}, {108, 108, 108}, {108, 108, 108}, {107, 107, 107}, {107, 107, 107}, {107, 107, 107}, {107, 107, 107}, {106, 106, 106}, {106, 106, 106}, {106, 106, 106}, {106, 106, 106}, {105, 105, 105}, {105, 105, 105}, {105, 105, 105}, {105, 105, 105}, {104, 104, 104}, {104, 104, 104}, {104, 104, 104}, {104, 104, 104}, {103, 103, 103}, {103, 103, 103}, {103, 103, 103}, {103, 103, 103}, {102, 102, 102}, {102, 102, 102}, {102, 102, 102}, {102, 102, 102}, {101, 101, 101}, {101, 101, 101}, {101, 101, 101}, {101, 101, 101}, {100, 100, 100}, {100, 100, 100}, {100, 100, 100}, {100, 100, 100}, {99, 99, 99}, {99, 99, 99}, {99, 99, 99}, {99, 99, 99}, {98, 98, 98}, {98, 98, 98}, {98, 98, 98}, {98, 98, 98}, {97, 97, 97}, {97, 97, 97}, {97, 97, 97}, {96, 96, 96}, {96, 96, 96}, {96, 96, 96}, {96, 96, 96}, {95, 95, 95}, {95, 95, 95}, {95, 95, 95}, {95, 95, 95}, {94, 94, 94}, {94, 94, 94}, {94, 94, 94}, {94, 94, 94}, {93, 93, 93}, {93, 93, 93}, {93, 93, 93}, {93, 93, 93}, {92, 92, 92}, {92, 92, 92}, {92, 92, 92}, {92, 92, 92}, {91, 91, 91}, {91, 91, 91}, {91, 91, 91}, {91, 91, 91}, {90, 90, 90}, {90, 90, 90}, {90, 90, 90}, {90, 90, 90}, {89, 89, 89}, {89, 89, 89}, {89, 89, 89}, {89, 89, 89}, {88, 88, 88}, {88, 88, 88}, {88, 88, 88}, {88, 88, 88}, {87, 87, 87}, {87, 87, 87}, {87, 87, 87}, {87, 87, 87}, {86, 86, 86}, {86, 86, 86}, {86, 86, 86}, {86, 86, 86}, {85, 85, 85}, {85, 85, 85}, {85, 85, 85}, {84, 84, 84}, {84, 84, 84}, {84, 84, 84}, {84, 84, 84}, {83, 83, 83}, {83, 83, 83}, {83, 83, 83}, {83, 83, 83}, {82, 82, 82}, {82, 82, 82}, {82, 82, 82}, {82, 82, 82}, {81, 81, 81}, {81, 81, 81}, {81, 81, 81}, {81, 81, 81}, {80, 80, 80}, {80, 80, 80}, {80, 80, 80}, {80, 80, 80}, {79, 79, 79}, {79, 79, 79}, {79, 79, 79}, {79, 79, 79}, {78, 78, 78}, {78, 78, 78}, {78, 78, 78}, {78, 78, 78}, {77, 77, 77}, {77, 77, 77}, {77, 77, 77}, {77, 77, 77}, {76, 76, 76}, {76, 76, 76}, {76, 76, 76}, {76, 76, 76}, {75, 75, 75}, {75, 75, 75}, {75, 75, 75}, {75, 75, 75}, {74, 74, 74}, {74, 74, 74}, {74, 74, 74}, {74, 74, 74}, {73, 73, 73}, {73, 73, 73}, {73, 73, 73}, {72, 72, 72}, {72, 72, 72}, {72, 72, 72}, {72, 72, 72}, {71, 71, 71}, {71, 71, 71}, {71, 71, 71}, {71, 71, 71}, {70, 70, 70}, {70, 70, 70}, {70, 70, 70}, {70, 70, 70}, {69, 69, 69}, {69, 69, 69}, {69, 69, 69}, {69, 69, 69}, {68, 68, 68}, {68, 68, 68}, {68, 68, 68}, {68, 68, 68}, {67, 67, 67}, {67, 67, 67}, {67, 67, 67}, {67, 67, 67}, {66, 66, 66}, {66, 66, 66}, {66, 66, 66}, {66, 66, 66}, {65, 65, 65}, {65, 65, 65}, {65, 65, 65}, {65, 65, 65}, {64, 64, 64}, {64, 64, 64}, {64, 64, 64}, {64, 64, 64}, {63, 63, 63}, {63, 63, 63}, {63, 63, 63}, {63, 63, 63}, {62, 62, 62}, {62, 62, 62}, {62, 62, 62}, {62, 62, 62}, {61, 61, 61}, {61, 61, 61}, {61, 61, 61}, {60, 60, 60}, {60, 60, 60}, {60, 60, 60}, {60, 60, 60}, {59, 59, 59}, {59, 59, 59}, {59, 59, 59}, {59, 59, 59}, {58, 58, 58}, {58, 58, 58}, {58, 58, 58}, {58, 58, 58}, {57, 57, 57}, {57, 57, 57}, {57, 57, 57}, {57, 57, 57}, {56, 56, 56}, {56, 56, 56}, {56, 56, 56}, {56, 56, 56}, {55, 55, 55}, {55, 55, 55}, {55, 55, 55}, {55, 55, 55}, {54, 54, 54}, {54, 54, 54}, {54, 54, 54}, {54, 54, 54}, {53, 53, 53}, {53, 53, 53}, {53, 53, 53}, {53, 53, 53}, {52, 52, 52}, {52, 52, 52}, {52, 52, 52}, {52, 52, 52}, {51, 51, 51}, {51, 51, 51}, {51, 51, 51}, {51, 51, 51}, {50, 50, 50}, {50, 50, 50}, {50, 50, 50}, {50, 50, 50}, {49, 49, 49}, {49, 49, 49}, {49, 49, 49}, {48, 48, 48}, {48, 48, 48}, {48, 48, 48}, {48, 48, 48}, {47, 47, 47}, {47, 47, 47}, {47, 47, 47}, {47, 47, 47}, {46, 46, 46}, {46, 46, 46}, {46, 46, 46}, {46, 46, 46}, {45, 45, 45}, {45, 45, 45}, {45, 45, 45}, {45, 45, 45}, {44, 44, 44}, {44, 44, 44}, {44, 44, 44}, {44, 44, 44}, {43, 43, 43}, {43, 43, 43}, {43, 43, 43}, {43, 43, 43}, {42, 42, 42}, {42, 42, 42}, {42, 42, 42}, {42, 42, 42}, {41, 41, 41}, {41, 41, 41}, {41, 41, 41}, {41, 41, 41}, {40, 40, 40}, {40, 40, 40}, {40, 40, 40}, {40, 40, 40}, {39, 39, 39}, {39, 39, 39}, {39, 39, 39}, {39, 39, 39}, {38, 38, 38}, {38, 38, 38}, {38, 38, 38}, {38, 38, 38}, {37, 37, 37}, {37, 37, 37}, {37, 37, 37}, {37, 37, 37}, {36, 36, 36}, {36, 36, 36}, {36, 36, 36}, {35, 35, 35}, {35, 35, 35}, {35, 35, 35}, {35, 35, 35}, {34, 34, 34}, {34, 34, 34}, {34, 34, 34}, {34, 34, 34}, {33, 33, 33}, {33, 33, 33}, {33, 33, 33}, {33, 33, 33}, {32, 32, 32}, {32, 32, 32}, {32, 32, 32}, {32, 32, 32}, {31, 31, 31}, {31, 31, 31}, {31, 31, 31}, {31, 31, 31}, {30, 30, 30}, {30, 30, 30}, {30, 30, 30}, {30, 30, 30}, {29, 29, 29}, {29, 29, 29}, {29, 29, 29}, {29, 29, 29}, {28, 28, 28}, {28, 28, 28}, {28, 28, 28}, {28, 28, 28}, {27, 27, 27}, {27, 27, 27}, {27, 27, 27}, {27, 27, 27}, {26, 26, 26}, {26, 26, 26}, {26, 26, 26}, {26, 26, 26}, {25, 25, 25}, {25, 25, 25}, {25, 25, 25}, {25, 25, 25}, {24, 24, 24}, {24, 24, 24}, {24, 24, 24}, {23, 23, 23}, {23, 23, 23}, {23, 23, 23}, {23, 23, 23}, {22, 22, 22}, {22, 22, 22}, {22, 22, 22}, {22, 22, 22}, {21, 21, 21}, {21, 21, 21}, {21, 21, 21}, {21, 21, 21}, {20, 20, 20}, {20, 20, 20}, {20, 20, 20}, {20, 20, 20}, {19, 19, 19}, {19, 19, 19}, {19, 19, 19}, {19, 19, 19}, {18, 18, 18}, {18, 18, 18}, {18, 18, 18}, {18, 18, 18}, {17, 17, 17}, {17, 17, 17}, {17, 17, 17}, {17, 17, 17}, {16, 16, 16}, {16, 16, 16}, {16, 16, 16}, {16, 16, 16}, {15, 15, 15}, {15, 15, 15}, {15, 15, 15}, {15, 15, 15}, {14, 14, 14}, {14, 14, 14}, {14, 14, 14}, {14, 14, 14}, {13, 13, 13}, {13, 13, 13}, {13, 13, 13}, {13, 13, 13}, {12, 12, 12}, {12, 12, 12}, {12, 12, 12}, {11, 11, 11}, {11, 11, 11}, {11, 11, 11}, {11, 11, 11}, {10, 10, 10}, {10, 10, 10}, {10, 10, 10}, {10, 10, 10}, {9, 9, 9}, {9, 9, 9}, {9, 9, 9}, {9, 9, 9}, {8, 8, 8}, {8, 8, 8}, {8, 8, 8}, {8, 8, 8}, {7, 7, 7}, {7, 7, 7}, {7, 7, 7}, {7, 7, 7}, {6, 6, 6}, {6, 6, 6}, {6, 6, 6}, {6, 6, 6}, {5, 5, 5}, {5, 5, 5}, {5, 5, 5}, {5, 5, 5}, {4, 4, 4}, {4, 4, 4}, {4, 4, 4}, {4, 4, 4}, {3, 3, 3}, {3, 3, 3}, {3, 3, 3}, {3, 3, 3}, {2, 2, 2}, {2, 2, 2}, {2, 2, 2}, {2, 2, 2}, {1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {0, 0, 0}, {0, 0, 0}}; const rgb_store hot_colormap[1000] = { {11, 0, 0}, {11, 0, 0}, {12, 0, 0}, {13, 0, 0}, {13, 0, 0}, {14, 0, 0}, {15, 0, 0}, {15, 0, 0}, {16, 0, 0}, {17, 0, 0}, {17, 0, 0}, {18, 0, 0}, {19, 0, 0}, {19, 0, 0}, {20, 0, 0}, {21, 0, 0}, {21, 0, 0}, {22, 0, 0}, {23, 0, 0}, {23, 0, 0}, {24, 0, 0}, {25, 0, 0}, {25, 0, 0}, {26, 0, 0}, {27, 0, 0}, {27, 0, 0}, {28, 0, 0}, {29, 0, 0}, {29, 0, 0}, {30, 0, 0}, {31, 0, 0}, {31, 0, 0}, {32, 0, 0}, {33, 0, 0}, {33, 0, 0}, {34, 0, 0}, {35, 0, 0}, {35, 0, 0}, {36, 0, 0}, {37, 0, 0}, {37, 0, 0}, {38, 0, 0}, {39, 0, 0}, {39, 0, 0}, {40, 0, 0}, {41, 0, 0}, {41, 0, 0}, {42, 0, 0}, {43, 0, 0}, {43, 0, 0}, {44, 0, 0}, {45, 0, 0}, {45, 0, 0}, {46, 0, 0}, {47, 0, 0}, {47, 0, 0}, {48, 0, 0}, {49, 0, 0}, {49, 0, 0}, {50, 0, 0}, {51, 0, 0}, {51, 0, 0}, {52, 0, 0}, {53, 0, 0}, {54, 0, 0}, {54, 0, 0}, {55, 0, 0}, {56, 0, 0}, {56, 0, 0}, {57, 0, 0}, {58, 0, 0}, {58, 0, 0}, {59, 0, 0}, {60, 0, 0}, {60, 0, 0}, {61, 0, 0}, {62, 0, 0}, {62, 0, 0}, {63, 0, 0}, {64, 0, 0}, {64, 0, 0}, {65, 0, 0}, {66, 0, 0}, {66, 0, 0}, {67, 0, 0}, {68, 0, 0}, {68, 0, 0}, {69, 0, 0}, {70, 0, 0}, {70, 0, 0}, {71, 0, 0}, {72, 0, 0}, {72, 0, 0}, {73, 0, 0}, {74, 0, 0}, {74, 0, 0}, {75, 0, 0}, {76, 0, 0}, {76, 0, 0}, {77, 0, 0}, {78, 0, 0}, {78, 0, 0}, {79, 0, 0}, {80, 0, 0}, {80, 0, 0}, {81, 0, 0}, {82, 0, 0}, {82, 0, 0}, {83, 0, 0}, {84, 0, 0}, {84, 0, 0}, {85, 0, 0}, {86, 0, 0}, {86, 0, 0}, {87, 0, 0}, {88, 0, 0}, {88, 0, 0}, {89, 0, 0}, {90, 0, 0}, {90, 0, 0}, {91, 0, 0}, {92, 0, 0}, {92, 0, 0}, {93, 0, 0}, {94, 0, 0}, {94, 0, 0}, {95, 0, 0}, {96, 0, 0}, {96, 0, 0}, {97, 0, 0}, {98, 0, 0}, {98, 0, 0}, {99, 0, 0}, {100, 0, 0}, {100, 0, 0}, {101, 0, 0}, {102, 0, 0}, {102, 0, 0}, {103, 0, 0}, {104, 0, 0}, {104, 0, 0}, {105, 0, 0}, {106, 0, 0}, {106, 0, 0}, {107, 0, 0}, {108, 0, 0}, {108, 0, 0}, {109, 0, 0}, {110, 0, 0}, {110, 0, 0}, {111, 0, 0}, {112, 0, 0}, {112, 0, 0}, {113, 0, 0}, {114, 0, 0}, {114, 0, 0}, {115, 0, 0}, {116, 0, 0}, {116, 0, 0}, {117, 0, 0}, {118, 0, 0}, {119, 0, 0}, {119, 0, 0}, {120, 0, 0}, {121, 0, 0}, {121, 0, 0}, {122, 0, 0}, {123, 0, 0}, {123, 0, 0}, {124, 0, 0}, {125, 0, 0}, {125, 0, 0}, {126, 0, 0}, {127, 0, 0}, {127, 0, 0}, {128, 0, 0}, {129, 0, 0}, {129, 0, 0}, {130, 0, 0}, {131, 0, 0}, {131, 0, 0}, {132, 0, 0}, {133, 0, 0}, {133, 0, 0}, {134, 0, 0}, {135, 0, 0}, {135, 0, 0}, {136, 0, 0}, {137, 0, 0}, {137, 0, 0}, {138, 0, 0}, {139, 0, 0}, {139, 0, 0}, {140, 0, 0}, {141, 0, 0}, {141, 0, 0}, {142, 0, 0}, {143, 0, 0}, {143, 0, 0}, {144, 0, 0}, {145, 0, 0}, {145, 0, 0}, {146, 0, 0}, {147, 0, 0}, {147, 0, 0}, {148, 0, 0}, {149, 0, 0}, {149, 0, 0}, {150, 0, 0}, {151, 0, 0}, {151, 0, 0}, {152, 0, 0}, {153, 0, 0}, {153, 0, 0}, {154, 0, 0}, {155, 0, 0}, {155, 0, 0}, {156, 0, 0}, {157, 0, 0}, {157, 0, 0}, {158, 0, 0}, {159, 0, 0}, {159, 0, 0}, {160, 0, 0}, {161, 0, 0}, {161, 0, 0}, {162, 0, 0}, {163, 0, 0}, {163, 0, 0}, {164, 0, 0}, {165, 0, 0}, {165, 0, 0}, {166, 0, 0}, {167, 0, 0}, {167, 0, 0}, {168, 0, 0}, {169, 0, 0}, {169, 0, 0}, {170, 0, 0}, {171, 0, 0}, {171, 0, 0}, {172, 0, 0}, {173, 0, 0}, {173, 0, 0}, {174, 0, 0}, {175, 0, 0}, {175, 0, 0}, {176, 0, 0}, {177, 0, 0}, {177, 0, 0}, {178, 0, 0}, {179, 0, 0}, {179, 0, 0}, {180, 0, 0}, {181, 0, 0}, {181, 0, 0}, {182, 0, 0}, {183, 0, 0}, {183, 0, 0}, {184, 0, 0}, {185, 0, 0}, {186, 0, 0}, {186, 0, 0}, {187, 0, 0}, {188, 0, 0}, {188, 0, 0}, {189, 0, 0}, {190, 0, 0}, {190, 0, 0}, {191, 0, 0}, {192, 0, 0}, {192, 0, 0}, {193, 0, 0}, {194, 0, 0}, {194, 0, 0}, {195, 0, 0}, {196, 0, 0}, {196, 0, 0}, {197, 0, 0}, {198, 0, 0}, {198, 0, 0}, {199, 0, 0}, {200, 0, 0}, {200, 0, 0}, {201, 0, 0}, {202, 0, 0}, {202, 0, 0}, {203, 0, 0}, {204, 0, 0}, {204, 0, 0}, {205, 0, 0}, {206, 0, 0}, {206, 0, 0}, {207, 0, 0}, {208, 0, 0}, {208, 0, 0}, {209, 0, 0}, {210, 0, 0}, {210, 0, 0}, {211, 0, 0}, {212, 0, 0}, {212, 0, 0}, {213, 0, 0}, {214, 0, 0}, {214, 0, 0}, {215, 0, 0}, {216, 0, 0}, {216, 0, 0}, {217, 0, 0}, {218, 0, 0}, {218, 0, 0}, {219, 0, 0}, {220, 0, 0}, {220, 0, 0}, {221, 0, 0}, {222, 0, 0}, {222, 0, 0}, {223, 0, 0}, {224, 0, 0}, {224, 0, 0}, {225, 0, 0}, {226, 0, 0}, {226, 0, 0}, {227, 0, 0}, {228, 0, 0}, {228, 0, 0}, {229, 0, 0}, {230, 0, 0}, {230, 0, 0}, {231, 0, 0}, {232, 0, 0}, {232, 0, 0}, {233, 0, 0}, {234, 0, 0}, {234, 0, 0}, {235, 0, 0}, {236, 0, 0}, {236, 0, 0}, {237, 0, 0}, {238, 0, 0}, {238, 0, 0}, {239, 0, 0}, {240, 0, 0}, {240, 0, 0}, {241, 0, 0}, {242, 0, 0}, {242, 0, 0}, {243, 0, 0}, {244, 0, 0}, {244, 0, 0}, {245, 0, 0}, {246, 0, 0}, {246, 0, 0}, {247, 0, 0}, {248, 0, 0}, {248, 0, 0}, {249, 0, 0}, {250, 0, 0}, {251, 0, 0}, {251, 0, 0}, {252, 0, 0}, {253, 0, 0}, {253, 0, 0}, {254, 0, 0}, {255, 0, 0}, {255, 0, 0}, {255, 1, 0}, {255, 2, 0}, {255, 2, 0}, {255, 3, 0}, {255, 4, 0}, {255, 4, 0}, {255, 5, 0}, {255, 6, 0}, {255, 6, 0}, {255, 7, 0}, {255, 8, 0}, {255, 8, 0}, {255, 9, 0}, {255, 10, 0}, {255, 10, 0}, {255, 11, 0}, {255, 12, 0}, {255, 12, 0}, {255, 13, 0}, {255, 14, 0}, {255, 14, 0}, {255, 15, 0}, {255, 16, 0}, {255, 16, 0}, {255, 17, 0}, {255, 18, 0}, {255, 18, 0}, {255, 19, 0}, {255, 20, 0}, {255, 20, 0}, {255, 21, 0}, {255, 22, 0}, {255, 22, 0}, {255, 23, 0}, {255, 24, 0}, {255, 24, 0}, {255, 25, 0}, {255, 26, 0}, {255, 26, 0}, {255, 27, 0}, {255, 28, 0}, {255, 28, 0}, {255, 29, 0}, {255, 30, 0}, {255, 30, 0}, {255, 31, 0}, {255, 32, 0}, {255, 32, 0}, {255, 33, 0}, {255, 34, 0}, {255, 34, 0}, {255, 35, 0}, {255, 36, 0}, {255, 36, 0}, {255, 37, 0}, {255, 38, 0}, {255, 38, 0}, {255, 39, 0}, {255, 40, 0}, {255, 40, 0}, {255, 41, 0}, {255, 42, 0}, {255, 42, 0}, {255, 43, 0}, {255, 44, 0}, {255, 44, 0}, {255, 45, 0}, {255, 46, 0}, {255, 46, 0}, {255, 47, 0}, {255, 48, 0}, {255, 48, 0}, {255, 49, 0}, {255, 50, 0}, {255, 50, 0}, {255, 51, 0}, {255, 52, 0}, {255, 52, 0}, {255, 53, 0}, {255, 54, 0}, {255, 54, 0}, {255, 55, 0}, {255, 56, 0}, {255, 56, 0}, {255, 57, 0}, {255, 58, 0}, {255, 58, 0}, {255, 59, 0}, {255, 60, 0}, {255, 60, 0}, {255, 61, 0}, {255, 62, 0}, {255, 63, 0}, {255, 63, 0}, {255, 64, 0}, {255, 65, 0}, {255, 65, 0}, {255, 66, 0}, {255, 67, 0}, {255, 67, 0}, {255, 68, 0}, {255, 69, 0}, {255, 69, 0}, {255, 70, 0}, {255, 71, 0}, {255, 71, 0}, {255, 72, 0}, {255, 73, 0}, {255, 73, 0}, {255, 74, 0}, {255, 75, 0}, {255, 75, 0}, {255, 76, 0}, {255, 77, 0}, {255, 77, 0}, {255, 78, 0}, {255, 79, 0}, {255, 79, 0}, {255, 80, 0}, {255, 81, 0}, {255, 81, 0}, {255, 82, 0}, {255, 83, 0}, {255, 83, 0}, {255, 84, 0}, {255, 85, 0}, {255, 85, 0}, {255, 86, 0}, {255, 87, 0}, {255, 87, 0}, {255, 88, 0}, {255, 89, 0}, {255, 89, 0}, {255, 90, 0}, {255, 91, 0}, {255, 91, 0}, {255, 92, 0}, {255, 93, 0}, {255, 93, 0}, {255, 94, 0}, {255, 95, 0}, {255, 95, 0}, {255, 96, 0}, {255, 97, 0}, {255, 97, 0}, {255, 98, 0}, {255, 99, 0}, {255, 99, 0}, {255, 100, 0}, {255, 101, 0}, {255, 101, 0}, {255, 102, 0}, {255, 103, 0}, {255, 103, 0}, {255, 104, 0}, {255, 105, 0}, {255, 105, 0}, {255, 106, 0}, {255, 107, 0}, {255, 107, 0}, {255, 108, 0}, {255, 109, 0}, {255, 109, 0}, {255, 110, 0}, {255, 111, 0}, {255, 111, 0}, {255, 112, 0}, {255, 113, 0}, {255, 113, 0}, {255, 114, 0}, {255, 115, 0}, {255, 115, 0}, {255, 116, 0}, {255, 117, 0}, {255, 117, 0}, {255, 118, 0}, {255, 119, 0}, {255, 119, 0}, {255, 120, 0}, {255, 121, 0}, {255, 121, 0}, {255, 122, 0}, {255, 123, 0}, {255, 123, 0}, {255, 124, 0}, {255, 125, 0}, {255, 125, 0}, {255, 126, 0}, {255, 127, 0}, {255, 128, 0}, {255, 128, 0}, {255, 129, 0}, {255, 130, 0}, {255, 130, 0}, {255, 131, 0}, {255, 132, 0}, {255, 132, 0}, {255, 133, 0}, {255, 134, 0}, {255, 134, 0}, {255, 135, 0}, {255, 136, 0}, {255, 136, 0}, {255, 137, 0}, {255, 138, 0}, {255, 138, 0}, {255, 139, 0}, {255, 140, 0}, {255, 140, 0}, {255, 141, 0}, {255, 142, 0}, {255, 142, 0}, {255, 143, 0}, {255, 144, 0}, {255, 144, 0}, {255, 145, 0}, {255, 146, 0}, {255, 146, 0}, {255, 147, 0}, {255, 148, 0}, {255, 148, 0}, {255, 149, 0}, {255, 150, 0}, {255, 150, 0}, {255, 151, 0}, {255, 152, 0}, {255, 152, 0}, {255, 153, 0}, {255, 154, 0}, {255, 154, 0}, {255, 155, 0}, {255, 156, 0}, {255, 156, 0}, {255, 157, 0}, {255, 158, 0}, {255, 158, 0}, {255, 159, 0}, {255, 160, 0}, {255, 160, 0}, {255, 161, 0}, {255, 162, 0}, {255, 162, 0}, {255, 163, 0}, {255, 164, 0}, {255, 164, 0}, {255, 165, 0}, {255, 166, 0}, {255, 166, 0}, {255, 167, 0}, {255, 168, 0}, {255, 168, 0}, {255, 169, 0}, {255, 170, 0}, {255, 170, 0}, {255, 171, 0}, {255, 172, 0}, {255, 172, 0}, {255, 173, 0}, {255, 174, 0}, {255, 174, 0}, {255, 175, 0}, {255, 176, 0}, {255, 176, 0}, {255, 177, 0}, {255, 178, 0}, {255, 178, 0}, {255, 179, 0}, {255, 180, 0}, {255, 180, 0}, {255, 181, 0}, {255, 182, 0}, {255, 182, 0}, {255, 183, 0}, {255, 184, 0}, {255, 184, 0}, {255, 185, 0}, {255, 186, 0}, {255, 186, 0}, {255, 187, 0}, {255, 188, 0}, {255, 188, 0}, {255, 189, 0}, {255, 190, 0}, {255, 190, 0}, {255, 191, 0}, {255, 192, 0}, {255, 192, 0}, {255, 193, 0}, {255, 194, 0}, {255, 195, 0}, {255, 195, 0}, {255, 196, 0}, {255, 197, 0}, {255, 197, 0}, {255, 198, 0}, {255, 199, 0}, {255, 199, 0}, {255, 200, 0}, {255, 201, 0}, {255, 201, 0}, {255, 202, 0}, {255, 203, 0}, {255, 203, 0}, {255, 204, 0}, {255, 205, 0}, {255, 205, 0}, {255, 206, 0}, {255, 207, 0}, {255, 207, 0}, {255, 208, 0}, {255, 209, 0}, {255, 209, 0}, {255, 210, 0}, {255, 211, 0}, {255, 211, 0}, {255, 212, 0}, {255, 213, 0}, {255, 213, 0}, {255, 214, 0}, {255, 215, 0}, {255, 215, 0}, {255, 216, 0}, {255, 217, 0}, {255, 217, 0}, {255, 218, 0}, {255, 219, 0}, {255, 219, 0}, {255, 220, 0}, {255, 221, 0}, {255, 221, 0}, {255, 222, 0}, {255, 223, 0}, {255, 223, 0}, {255, 224, 0}, {255, 225, 0}, {255, 225, 0}, {255, 226, 0}, {255, 227, 0}, {255, 227, 0}, {255, 228, 0}, {255, 229, 0}, {255, 229, 0}, {255, 230, 0}, {255, 231, 0}, {255, 231, 0}, {255, 232, 0}, {255, 233, 0}, {255, 233, 0}, {255, 234, 0}, {255, 235, 0}, {255, 235, 0}, {255, 236, 0}, {255, 237, 0}, {255, 237, 0}, {255, 238, 0}, {255, 239, 0}, {255, 239, 0}, {255, 240, 0}, {255, 241, 0}, {255, 241, 0}, {255, 242, 0}, {255, 243, 0}, {255, 243, 0}, {255, 244, 0}, {255, 245, 0}, {255, 245, 0}, {255, 246, 0}, {255, 247, 0}, {255, 247, 0}, {255, 248, 0}, {255, 249, 0}, {255, 249, 0}, {255, 250, 0}, {255, 251, 0}, {255, 251, 0}, {255, 252, 0}, {255, 253, 0}, {255, 253, 0}, {255, 254, 0}, {255, 255, 0}, {255, 255, 1}, {255, 255, 2}, {255, 255, 3}, {255, 255, 4}, {255, 255, 5}, {255, 255, 6}, {255, 255, 7}, {255, 255, 8}, {255, 255, 9}, {255, 255, 10}, {255, 255, 11}, {255, 255, 12}, {255, 255, 13}, {255, 255, 14}, {255, 255, 15}, {255, 255, 16}, {255, 255, 17}, {255, 255, 18}, {255, 255, 19}, {255, 255, 20}, {255, 255, 21}, {255, 255, 22}, {255, 255, 23}, {255, 255, 24}, {255, 255, 25}, {255, 255, 26}, {255, 255, 27}, {255, 255, 28}, {255, 255, 29}, {255, 255, 30}, {255, 255, 31}, {255, 255, 32}, {255, 255, 33}, {255, 255, 34}, {255, 255, 35}, {255, 255, 36}, {255, 255, 37}, {255, 255, 38}, {255, 255, 39}, {255, 255, 40}, {255, 255, 41}, {255, 255, 42}, {255, 255, 43}, {255, 255, 44}, {255, 255, 45}, {255, 255, 46}, {255, 255, 47}, {255, 255, 48}, {255, 255, 49}, {255, 255, 50}, {255, 255, 51}, {255, 255, 52}, {255, 255, 53}, {255, 255, 54}, {255, 255, 55}, {255, 255, 56}, {255, 255, 57}, {255, 255, 58}, {255, 255, 59}, {255, 255, 60}, {255, 255, 61}, {255, 255, 62}, {255, 255, 63}, {255, 255, 64}, {255, 255, 65}, {255, 255, 66}, {255, 255, 67}, {255, 255, 68}, {255, 255, 69}, {255, 255, 70}, {255, 255, 71}, {255, 255, 72}, {255, 255, 73}, {255, 255, 74}, {255, 255, 75}, {255, 255, 76}, {255, 255, 77}, {255, 255, 78}, {255, 255, 79}, {255, 255, 80}, {255, 255, 81}, {255, 255, 82}, {255, 255, 83}, {255, 255, 84}, {255, 255, 85}, {255, 255, 86}, {255, 255, 87}, {255, 255, 88}, {255, 255, 89}, {255, 255, 90}, {255, 255, 91}, {255, 255, 92}, {255, 255, 93}, {255, 255, 94}, {255, 255, 95}, {255, 255, 96}, {255, 255, 97}, {255, 255, 98}, {255, 255, 99}, {255, 255, 100}, {255, 255, 101}, {255, 255, 102}, {255, 255, 103}, {255, 255, 104}, {255, 255, 105}, {255, 255, 106}, {255, 255, 107}, {255, 255, 108}, {255, 255, 109}, {255, 255, 110}, {255, 255, 111}, {255, 255, 112}, {255, 255, 113}, {255, 255, 114}, {255, 255, 115}, {255, 255, 116}, {255, 255, 117}, {255, 255, 118}, {255, 255, 119}, {255, 255, 120}, {255, 255, 121}, {255, 255, 122}, {255, 255, 123}, {255, 255, 124}, {255, 255, 125}, {255, 255, 126}, {255, 255, 127}, {255, 255, 128}, {255, 255, 129}, {255, 255, 130}, {255, 255, 131}, {255, 255, 132}, {255, 255, 133}, {255, 255, 134}, {255, 255, 135}, {255, 255, 136}, {255, 255, 137}, {255, 255, 138}, {255, 255, 139}, {255, 255, 140}, {255, 255, 141}, {255, 255, 142}, {255, 255, 143}, {255, 255, 144}, {255, 255, 145}, {255, 255, 146}, {255, 255, 147}, {255, 255, 148}, {255, 255, 149}, {255, 255, 150}, {255, 255, 151}, {255, 255, 152}, {255, 255, 153}, {255, 255, 154}, {255, 255, 155}, {255, 255, 157}, {255, 255, 158}, {255, 255, 159}, {255, 255, 160}, {255, 255, 161}, {255, 255, 162}, {255, 255, 163}, {255, 255, 164}, {255, 255, 165}, {255, 255, 166}, {255, 255, 167}, {255, 255, 168}, {255, 255, 169}, {255, 255, 170}, {255, 255, 171}, {255, 255, 172}, {255, 255, 173}, {255, 255, 174}, {255, 255, 175}, {255, 255, 176}, {255, 255, 177}, {255, 255, 178}, {255, 255, 179}, {255, 255, 180}, {255, 255, 181}, {255, 255, 182}, {255, 255, 183}, {255, 255, 184}, {255, 255, 185}, {255, 255, 186}, {255, 255, 187}, {255, 255, 188}, {255, 255, 189}, {255, 255, 190}, {255, 255, 191}, {255, 255, 192}, {255, 255, 193}, {255, 255, 194}, {255, 255, 195}, {255, 255, 196}, {255, 255, 197}, {255, 255, 198}, {255, 255, 199}, {255, 255, 200}, {255, 255, 201}, {255, 255, 202}, {255, 255, 203}, {255, 255, 204}, {255, 255, 205}, {255, 255, 206}, {255, 255, 207}, {255, 255, 208}, {255, 255, 209}, {255, 255, 210}, {255, 255, 211}, {255, 255, 212}, {255, 255, 213}, {255, 255, 214}, {255, 255, 215}, {255, 255, 216}, {255, 255, 217}, {255, 255, 218}, {255, 255, 219}, {255, 255, 220}, {255, 255, 221}, {255, 255, 222}, {255, 255, 223}, {255, 255, 224}, {255, 255, 225}, {255, 255, 226}, {255, 255, 227}, {255, 255, 228}, {255, 255, 229}, {255, 255, 230}, {255, 255, 231}, {255, 255, 232}, {255, 255, 233}, {255, 255, 234}, {255, 255, 235}, {255, 255, 236}, {255, 255, 237}, {255, 255, 238}, {255, 255, 239}, {255, 255, 240}, {255, 255, 241}, {255, 255, 242}, {255, 255, 243}, {255, 255, 244}, {255, 255, 245}, {255, 255, 246}, {255, 255, 247}, {255, 255, 248}, {255, 255, 249}, {255, 255, 250}, {255, 255, 251}, {255, 255, 252}, {255, 255, 253}, {255, 255, 254}, {255}}; const rgb_store hsv_colormap[1000] = { {255, 0, 0}, {255, 2, 0}, {255, 3, 0}, {255, 5, 0}, {255, 6, 0}, {255, 8, 0}, {255, 9, 0}, {255, 11, 0}, {255, 12, 0}, {255, 14, 0}, {255, 15, 0}, {255, 17, 0}, {255, 18, 0}, {255, 20, 0}, {255, 21, 0}, {255, 23, 0}, {255, 24, 0}, {255, 26, 0}, {255, 27, 0}, {255, 29, 0}, {255, 30, 0}, {255, 32, 0}, {255, 33, 0}, {255, 35, 0}, {255, 36, 0}, {255, 38, 0}, {255, 39, 0}, {255, 41, 0}, {255, 42, 0}, {255, 44, 0}, {255, 45, 0}, {255, 47, 0}, {255, 48, 0}, {255, 50, 0}, {255, 51, 0}, {255, 53, 0}, {255, 54, 0}, {255, 56, 0}, {255, 57, 0}, {255, 59, 0}, {255, 60, 0}, {255, 62, 0}, {255, 63, 0}, {255, 65, 0}, {255, 66, 0}, {255, 68, 0}, {255, 69, 0}, {255, 71, 0}, {255, 72, 0}, {255, 74, 0}, {255, 75, 0}, {255, 77, 0}, {255, 78, 0}, {255, 80, 0}, {255, 81, 0}, {255, 83, 0}, {255, 84, 0}, {255, 86, 0}, {255, 87, 0}, {255, 89, 0}, {255, 90, 0}, {255, 92, 0}, {255, 93, 0}, {255, 95, 0}, {255, 96, 0}, {255, 98, 0}, {255, 100, 0}, {255, 101, 0}, {255, 103, 0}, {255, 104, 0}, {255, 106, 0}, {255, 107, 0}, {255, 109, 0}, {255, 110, 0}, {255, 112, 0}, {255, 113, 0}, {255, 115, 0}, {255, 116, 0}, {255, 118, 0}, {255, 119, 0}, {255, 121, 0}, {255, 122, 0}, {255, 124, 0}, {255, 125, 0}, {255, 127, 0}, {255, 128, 0}, {255, 130, 0}, {255, 131, 0}, {255, 133, 0}, {255, 134, 0}, {255, 136, 0}, {255, 137, 0}, {255, 139, 0}, {255, 140, 0}, {255, 142, 0}, {255, 143, 0}, {255, 145, 0}, {255, 146, 0}, {255, 148, 0}, {255, 149, 0}, {255, 151, 0}, {255, 152, 0}, {255, 154, 0}, {255, 155, 0}, {255, 157, 0}, {255, 158, 0}, {255, 160, 0}, {255, 161, 0}, {255, 163, 0}, {255, 164, 0}, {255, 166, 0}, {255, 167, 0}, {255, 169, 0}, {255, 170, 0}, {255, 172, 0}, {255, 173, 0}, {255, 175, 0}, {255, 176, 0}, {255, 178, 0}, {255, 179, 0}, {255, 181, 0}, {255, 182, 0}, {255, 184, 0}, {255, 185, 0}, {255, 187, 0}, {255, 188, 0}, {255, 190, 0}, {255, 191, 0}, {255, 193, 0}, {255, 194, 0}, {255, 196, 0}, {255, 197, 0}, {255, 199, 0}, {255, 201, 0}, {255, 202, 0}, {255, 204, 0}, {255, 205, 0}, {255, 207, 0}, {255, 208, 0}, {255, 210, 0}, {255, 211, 0}, {255, 213, 0}, {255, 214, 0}, {255, 216, 0}, {255, 217, 0}, {255, 219, 0}, {255, 220, 0}, {255, 222, 0}, {255, 223, 0}, {255, 225, 0}, {255, 226, 0}, {255, 228, 0}, {255, 229, 0}, {255, 231, 0}, {255, 232, 0}, {255, 234, 0}, {255, 235, 0}, {255, 237, 0}, {255, 238, 0}, {255, 239, 0}, {254, 240, 0}, {254, 242, 0}, {253, 243, 0}, {253, 244, 0}, {252, 245, 0}, {252, 246, 0}, {251, 247, 0}, {251, 248, 0}, {250, 249, 0}, {250, 250, 0}, {249, 251, 0}, {249, 252, 0}, {248, 253, 0}, {248, 254, 0}, {247, 255, 0}, {246, 255, 0}, {245, 255, 0}, {243, 255, 0}, {242, 255, 0}, {240, 255, 0}, {239, 255, 0}, {237, 255, 0}, {236, 255, 0}, {234, 255, 0}, {233, 255, 0}, {231, 255, 0}, {230, 255, 0}, {228, 255, 0}, {227, 255, 0}, {225, 255, 0}, {224, 255, 0}, {222, 255, 0}, {221, 255, 0}, {219, 255, 0}, {218, 255, 0}, {216, 255, 0}, {215, 255, 0}, {213, 255, 0}, {211, 255, 0}, {210, 255, 0}, {208, 255, 0}, {207, 255, 0}, {205, 255, 0}, {204, 255, 0}, {202, 255, 0}, {201, 255, 0}, {199, 255, 0}, {198, 255, 0}, {196, 255, 0}, {195, 255, 0}, {193, 255, 0}, {192, 255, 0}, {190, 255, 0}, {189, 255, 0}, {187, 255, 0}, {186, 255, 0}, {184, 255, 0}, {183, 255, 0}, {181, 255, 0}, {180, 255, 0}, {178, 255, 0}, {177, 255, 0}, {175, 255, 0}, {174, 255, 0}, {172, 255, 0}, {171, 255, 0}, {169, 255, 0}, {168, 255, 0}, {166, 255, 0}, {165, 255, 0}, {163, 255, 0}, {162, 255, 0}, {160, 255, 0}, {159, 255, 0}, {157, 255, 0}, {156, 255, 0}, {154, 255, 0}, {153, 255, 0}, {151, 255, 0}, {150, 255, 0}, {148, 255, 0}, {147, 255, 0}, {145, 255, 0}, {144, 255, 0}, {142, 255, 0}, {141, 255, 0}, {139, 255, 0}, {138, 255, 0}, {136, 255, 0}, {135, 255, 0}, {133, 255, 0}, {132, 255, 0}, {130, 255, 0}, {129, 255, 0}, {127, 255, 0}, {126, 255, 0}, {124, 255, 0}, {123, 255, 0}, {121, 255, 0}, {120, 255, 0}, {118, 255, 0}, {117, 255, 0}, {115, 255, 0}, {114, 255, 0}, {112, 255, 0}, {110, 255, 0}, {109, 255, 0}, {107, 255, 0}, {106, 255, 0}, {104, 255, 0}, {103, 255, 0}, {101, 255, 0}, {100, 255, 0}, {98, 255, 0}, {97, 255, 0}, {95, 255, 0}, {94, 255, 0}, {92, 255, 0}, {91, 255, 0}, {89, 255, 0}, {88, 255, 0}, {86, 255, 0}, {85, 255, 0}, {83, 255, 0}, {82, 255, 0}, {80, 255, 0}, {79, 255, 0}, {77, 255, 0}, {76, 255, 0}, {74, 255, 0}, {73, 255, 0}, {71, 255, 0}, {70, 255, 0}, {68, 255, 0}, {67, 255, 0}, {65, 255, 0}, {64, 255, 0}, {62, 255, 0}, {61, 255, 0}, {59, 255, 0}, {58, 255, 0}, {56, 255, 0}, {55, 255, 0}, {53, 255, 0}, {52, 255, 0}, {50, 255, 0}, {49, 255, 0}, {47, 255, 0}, {46, 255, 0}, {44, 255, 0}, {43, 255, 0}, {41, 255, 0}, {40, 255, 0}, {38, 255, 0}, {37, 255, 0}, {35, 255, 0}, {34, 255, 0}, {32, 255, 0}, {31, 255, 0}, {29, 255, 0}, {28, 255, 0}, {26, 255, 0}, {25, 255, 0}, {23, 255, 0}, {22, 255, 0}, {20, 255, 0}, {19, 255, 0}, {17, 255, 0}, {16, 255, 0}, {14, 255, 0}, {12, 255, 0}, {11, 255, 0}, {9, 255, 0}, {8, 255, 0}, {7, 255, 1}, {7, 255, 2}, {6, 255, 3}, {6, 255, 4}, {5, 255, 5}, {5, 255, 6}, {4, 255, 7}, {4, 255, 8}, {3, 255, 9}, {3, 255, 10}, {2, 255, 11}, {2, 255, 12}, {1, 255, 13}, {1, 255, 14}, {0, 255, 15}, {0, 255, 16}, {0, 255, 18}, {0, 255, 19}, {0, 255, 21}, {0, 255, 22}, {0, 255, 24}, {0, 255, 25}, {0, 255, 27}, {0, 255, 28}, {0, 255, 30}, {0, 255, 31}, {0, 255, 33}, {0, 255, 34}, {0, 255, 36}, {0, 255, 37}, {0, 255, 39}, {0, 255, 40}, {0, 255, 42}, {0, 255, 43}, {0, 255, 45}, {0, 255, 46}, {0, 255, 48}, {0, 255, 49}, {0, 255, 51}, {0, 255, 52}, {0, 255, 54}, {0, 255, 55}, {0, 255, 57}, {0, 255, 58}, {0, 255, 60}, {0, 255, 61}, {0, 255, 63}, {0, 255, 64}, {0, 255, 66}, {0, 255, 67}, {0, 255, 69}, {0, 255, 70}, {0, 255, 72}, {0, 255, 73}, {0, 255, 75}, {0, 255, 76}, {0, 255, 78}, {0, 255, 79}, {0, 255, 81}, {0, 255, 82}, {0, 255, 84}, {0, 255, 86}, {0, 255, 87}, {0, 255, 89}, {0, 255, 90}, {0, 255, 92}, {0, 255, 93}, {0, 255, 95}, {0, 255, 96}, {0, 255, 98}, {0, 255, 99}, {0, 255, 101}, {0, 255, 102}, {0, 255, 104}, {0, 255, 105}, {0, 255, 107}, {0, 255, 108}, {0, 255, 110}, {0, 255, 111}, {0, 255, 113}, {0, 255, 114}, {0, 255, 116}, {0, 255, 117}, {0, 255, 119}, {0, 255, 120}, {0, 255, 122}, {0, 255, 123}, {0, 255, 125}, {0, 255, 126}, {0, 255, 128}, {0, 255, 129}, {0, 255, 131}, {0, 255, 132}, {0, 255, 134}, {0, 255, 135}, {0, 255, 137}, {0, 255, 138}, {0, 255, 140}, {0, 255, 141}, {0, 255, 143}, {0, 255, 144}, {0, 255, 146}, {0, 255, 147}, {0, 255, 149}, {0, 255, 150}, {0, 255, 152}, {0, 255, 153}, {0, 255, 155}, {0, 255, 156}, {0, 255, 158}, {0, 255, 159}, {0, 255, 161}, {0, 255, 162}, {0, 255, 164}, {0, 255, 165}, {0, 255, 167}, {0, 255, 168}, {0, 255, 170}, {0, 255, 171}, {0, 255, 173}, {0, 255, 174}, {0, 255, 176}, {0, 255, 177}, {0, 255, 179}, {0, 255, 180}, {0, 255, 182}, {0, 255, 183}, {0, 255, 185}, {0, 255, 187}, {0, 255, 188}, {0, 255, 190}, {0, 255, 191}, {0, 255, 193}, {0, 255, 194}, {0, 255, 196}, {0, 255, 197}, {0, 255, 199}, {0, 255, 200}, {0, 255, 202}, {0, 255, 203}, {0, 255, 205}, {0, 255, 206}, {0, 255, 208}, {0, 255, 209}, {0, 255, 211}, {0, 255, 212}, {0, 255, 214}, {0, 255, 215}, {0, 255, 217}, {0, 255, 218}, {0, 255, 220}, {0, 255, 221}, {0, 255, 223}, {0, 255, 224}, {0, 255, 226}, {0, 255, 227}, {0, 255, 229}, {0, 255, 230}, {0, 255, 232}, {0, 255, 233}, {0, 255, 235}, {0, 255, 236}, {0, 255, 238}, {0, 255, 239}, {0, 255, 241}, {0, 255, 242}, {0, 255, 244}, {0, 255, 245}, {0, 255, 247}, {0, 255, 248}, {0, 255, 250}, {0, 255, 251}, {0, 255, 253}, {0, 255, 254}, {0, 254, 255}, {0, 253, 255}, {0, 251, 255}, {0, 250, 255}, {0, 248, 255}, {0, 247, 255}, {0, 245, 255}, {0, 244, 255}, {0, 242, 255}, {0, 241, 255}, {0, 239, 255}, {0, 238, 255}, {0, 236, 255}, {0, 235, 255}, {0, 233, 255}, {0, 232, 255}, {0, 230, 255}, {0, 229, 255}, {0, 227, 255}, {0, 225, 255}, {0, 224, 255}, {0, 222, 255}, {0, 221, 255}, {0, 219, 255}, {0, 218, 255}, {0, 216, 255}, {0, 215, 255}, {0, 213, 255}, {0, 212, 255}, {0, 210, 255}, {0, 209, 255}, {0, 207, 255}, {0, 206, 255}, {0, 204, 255}, {0, 203, 255}, {0, 201, 255}, {0, 200, 255}, {0, 198, 255}, {0, 197, 255}, {0, 195, 255}, {0, 194, 255}, {0, 192, 255}, {0, 191, 255}, {0, 189, 255}, {0, 188, 255}, {0, 186, 255}, {0, 185, 255}, {0, 183, 255}, {0, 182, 255}, {0, 180, 255}, {0, 179, 255}, {0, 177, 255}, {0, 176, 255}, {0, 174, 255}, {0, 173, 255}, {0, 171, 255}, {0, 170, 255}, {0, 168, 255}, {0, 167, 255}, {0, 165, 255}, {0, 164, 255}, {0, 162, 255}, {0, 161, 255}, {0, 159, 255}, {0, 158, 255}, {0, 156, 255}, {0, 155, 255}, {0, 153, 255}, {0, 152, 255}, {0, 150, 255}, {0, 149, 255}, {0, 147, 255}, {0, 146, 255}, {0, 144, 255}, {0, 143, 255}, {0, 141, 255}, {0, 140, 255}, {0, 138, 255}, {0, 137, 255}, {0, 135, 255}, {0, 134, 255}, {0, 132, 255}, {0, 131, 255}, {0, 129, 255}, {0, 128, 255}, {0, 126, 255}, {0, 124, 255}, {0, 123, 255}, {0, 121, 255}, {0, 120, 255}, {0, 118, 255}, {0, 117, 255}, {0, 115, 255}, {0, 114, 255}, {0, 112, 255}, {0, 111, 255}, {0, 109, 255}, {0, 108, 255}, {0, 106, 255}, {0, 105, 255}, {0, 103, 255}, {0, 102, 255}, {0, 100, 255}, {0, 99, 255}, {0, 97, 255}, {0, 96, 255}, {0, 94, 255}, {0, 93, 255}, {0, 91, 255}, {0, 90, 255}, {0, 88, 255}, {0, 87, 255}, {0, 85, 255}, {0, 84, 255}, {0, 82, 255}, {0, 81, 255}, {0, 79, 255}, {0, 78, 255}, {0, 76, 255}, {0, 75, 255}, {0, 73, 255}, {0, 72, 255}, {0, 70, 255}, {0, 69, 255}, {0, 67, 255}, {0, 66, 255}, {0, 64, 255}, {0, 63, 255}, {0, 61, 255}, {0, 60, 255}, {0, 58, 255}, {0, 57, 255}, {0, 55, 255}, {0, 54, 255}, {0, 52, 255}, {0, 51, 255}, {0, 49, 255}, {0, 48, 255}, {0, 46, 255}, {0, 45, 255}, {0, 43, 255}, {0, 42, 255}, {0, 40, 255}, {0, 39, 255}, {0, 37, 255}, {0, 36, 255}, {0, 34, 255}, {0, 33, 255}, {0, 31, 255}, {0, 30, 255}, {0, 28, 255}, {0, 26, 255}, {0, 25, 255}, {0, 23, 255}, {0, 22, 255}, {0, 20, 255}, {0, 19, 255}, {0, 17, 255}, {0, 16, 255}, {1, 15, 255}, {1, 14, 255}, {2, 13, 255}, {2, 12, 255}, {3, 11, 255}, {3, 10, 255}, {4, 9, 255}, {4, 8, 255}, {5, 7, 255}, {5, 6, 255}, {6, 5, 255}, {6, 4, 255}, {7, 3, 255}, {7, 2, 255}, {8, 1, 255}, {8, 0, 255}, {10, 0, 255}, {11, 0, 255}, {13, 0, 255}, {14, 0, 255}, {16, 0, 255}, {17, 0, 255}, {19, 0, 255}, {20, 0, 255}, {22, 0, 255}, {23, 0, 255}, {25, 0, 255}, {26, 0, 255}, {28, 0, 255}, {29, 0, 255}, {31, 0, 255}, {32, 0, 255}, {34, 0, 255}, {35, 0, 255}, {37, 0, 255}, {38, 0, 255}, {40, 0, 255}, {41, 0, 255}, {43, 0, 255}, {44, 0, 255}, {46, 0, 255}, {47, 0, 255}, {49, 0, 255}, {50, 0, 255}, {52, 0, 255}, {53, 0, 255}, {55, 0, 255}, {56, 0, 255}, {58, 0, 255}, {59, 0, 255}, {61, 0, 255}, {62, 0, 255}, {64, 0, 255}, {65, 0, 255}, {67, 0, 255}, {68, 0, 255}, {70, 0, 255}, {72, 0, 255}, {73, 0, 255}, {75, 0, 255}, {76, 0, 255}, {78, 0, 255}, {79, 0, 255}, {81, 0, 255}, {82, 0, 255}, {84, 0, 255}, {85, 0, 255}, {87, 0, 255}, {88, 0, 255}, {90, 0, 255}, {91, 0, 255}, {93, 0, 255}, {94, 0, 255}, {96, 0, 255}, {97, 0, 255}, {99, 0, 255}, {100, 0, 255}, {102, 0, 255}, {103, 0, 255}, {105, 0, 255}, {106, 0, 255}, {108, 0, 255}, {109, 0, 255}, {111, 0, 255}, {112, 0, 255}, {114, 0, 255}, {115, 0, 255}, {117, 0, 255}, {118, 0, 255}, {120, 0, 255}, {121, 0, 255}, {123, 0, 255}, {124, 0, 255}, {126, 0, 255}, {127, 0, 255}, {129, 0, 255}, {130, 0, 255}, {132, 0, 255}, {133, 0, 255}, {135, 0, 255}, {136, 0, 255}, {138, 0, 255}, {139, 0, 255}, {141, 0, 255}, {142, 0, 255}, {144, 0, 255}, {145, 0, 255}, {147, 0, 255}, {148, 0, 255}, {150, 0, 255}, {151, 0, 255}, {153, 0, 255}, {154, 0, 255}, {156, 0, 255}, {157, 0, 255}, {159, 0, 255}, {160, 0, 255}, {162, 0, 255}, {163, 0, 255}, {165, 0, 255}, {166, 0, 255}, {168, 0, 255}, {169, 0, 255}, {171, 0, 255}, {173, 0, 255}, {174, 0, 255}, {176, 0, 255}, {177, 0, 255}, {179, 0, 255}, {180, 0, 255}, {182, 0, 255}, {183, 0, 255}, {185, 0, 255}, {186, 0, 255}, {188, 0, 255}, {189, 0, 255}, {191, 0, 255}, {192, 0, 255}, {194, 0, 255}, {195, 0, 255}, {197, 0, 255}, {198, 0, 255}, {200, 0, 255}, {201, 0, 255}, {203, 0, 255}, {204, 0, 255}, {206, 0, 255}, {207, 0, 255}, {209, 0, 255}, {210, 0, 255}, {212, 0, 255}, {213, 0, 255}, {215, 0, 255}, {216, 0, 255}, {218, 0, 255}, {219, 0, 255}, {221, 0, 255}, {222, 0, 255}, {224, 0, 255}, {225, 0, 255}, {227, 0, 255}, {228, 0, 255}, {230, 0, 255}, {231, 0, 255}, {233, 0, 255}, {234, 0, 255}, {236, 0, 255}, {237, 0, 255}, {239, 0, 255}, {240, 0, 255}, {242, 0, 255}, {243, 0, 255}, {245, 0, 255}, {246, 0, 255}, {247, 0, 254}, {248, 0, 253}, {248, 0, 252}, {249, 0, 251}, {249, 0, 250}, {250, 0, 249}, {250, 0, 248}, {251, 0, 247}, {251, 0, 246}, {252, 0, 245}, {252, 0, 244}, {253, 0, 243}, {253, 0, 242}, {254, 0, 241}, {254, 0, 240}, {255, 0, 239}, {255, 0, 238}, {255, 0, 236}, {255, 0, 235}, {255, 0, 233}, {255, 0, 232}, {255, 0, 230}, {255, 0, 229}, {255, 0, 227}, {255, 0, 226}, {255, 0, 224}, {255, 0, 223}, {255, 0, 221}, {255, 0, 220}, {255, 0, 218}, {255, 0, 217}, {255, 0, 215}, {255, 0, 214}, {255, 0, 212}, {255, 0, 211}, {255, 0, 209}, {255, 0, 208}, {255, 0, 206}, {255, 0, 205}, {255, 0, 203}, {255, 0, 202}, {255, 0, 200}, {255, 0, 199}, {255, 0, 197}, {255, 0, 196}, {255, 0, 194}, {255, 0, 193}, {255, 0, 191}, {255, 0, 190}, {255, 0, 188}, {255, 0, 187}, {255, 0, 185}, {255, 0, 184}, {255, 0, 182}, {255, 0, 181}, {255, 0, 179}, {255, 0, 178}, {255, 0, 176}, {255, 0, 175}, {255, 0, 173}, {255, 0, 172}, {255, 0, 170}, {255, 0, 169}, {255, 0, 167}, {255, 0, 166}, {255, 0, 164}, {255, 0, 163}, {255, 0, 161}, {255, 0, 160}, {255, 0, 158}, {255, 0, 157}, {255, 0, 155}, {255, 0, 154}, {255, 0, 152}, {255, 0, 151}, {255, 0, 149}, {255, 0, 148}, {255, 0, 146}, {255, 0, 145}, {255, 0, 143}, {255, 0, 141}, {255, 0, 140}, {255, 0, 138}, {255, 0, 137}, {255, 0, 135}, {255, 0, 134}, {255, 0, 132}, {255, 0, 131}, {255, 0, 129}, {255, 0, 128}, {255, 0, 126}, {255, 0, 125}, {255, 0, 123}, {255, 0, 122}, {255, 0, 120}, {255, 0, 119}, {255, 0, 117}, {255, 0, 116}, {255, 0, 114}, {255, 0, 113}, {255, 0, 111}, {255, 0, 110}, {255, 0, 108}, {255, 0, 107}, {255, 0, 105}, {255, 0, 104}, {255, 0, 102}, {255, 0, 101}, {255, 0, 99}, {255, 0, 98}, {255, 0, 96}, {255, 0, 95}, {255, 0, 93}, {255, 0, 92}, {255, 0, 90}, {255, 0, 89}, {255, 0, 87}, {255, 0, 86}, {255, 0, 84}, {255, 0, 83}, {255, 0, 81}, {255, 0, 80}, {255, 0, 78}, {255, 0, 77}, {255, 0, 75}, {255, 0, 74}, {255, 0, 72}, {255, 0, 71}, {255, 0, 69}, {255, 0, 68}, {255, 0, 66}, {255, 0, 65}, {255, 0, 63}, {255, 0, 62}, {255, 0, 60}, {255, 0, 59}, {255, 0, 57}, {255, 0, 56}, {255, 0, 54}, {255, 0, 53}, {255, 0, 51}, {255, 0, 50}, {255, 0, 48}, {255, 0, 47}, {255, 0, 45}, {255, 0, 44}, {255, 0, 42}, {255, 0, 40}, {255, 0, 39}, {255, 0, 37}, {255, 0, 36}, {255, 0, 34}, {255, 0, 33}, {255, 0, 31}, {255, 0, 30}, {255, 0, 28}, {255, 0, 27}, {255, 0, 25}, {255, 0, 24}}; const rgb_store jet_colormap[1000] = { {29, 0, 102}, {23, 0, 107}, {17, 0, 112}, {12, 0, 117}, {6, 0, 122}, {0, 0, 127}, {0, 0, 128}, {0, 0, 129}, {0, 0, 129}, {0, 0, 130}, {0, 0, 131}, {0, 0, 132}, {0, 0, 133}, {0, 0, 133}, {0, 0, 134}, {0, 0, 135}, {0, 0, 136}, {0, 0, 137}, {0, 0, 138}, {0, 0, 140}, {0, 0, 141}, {0, 0, 142}, {0, 0, 143}, {0, 0, 145}, {0, 0, 146}, {0, 0, 147}, {0, 0, 148}, {0, 0, 150}, {0, 0, 151}, {0, 0, 152}, {0, 0, 153}, {0, 0, 154}, {0, 0, 156}, {0, 0, 157}, {0, 0, 158}, {0, 0, 159}, {0, 0, 160}, {0, 0, 161}, {0, 0, 163}, {0, 0, 164}, {0, 0, 165}, {0, 0, 166}, {0, 0, 168}, {0, 0, 169}, {0, 0, 170}, {0, 0, 171}, {0, 0, 173}, {0, 0, 174}, {0, 0, 175}, {0, 0, 176}, {0, 0, 178}, {0, 0, 179}, {0, 0, 180}, {0, 0, 181}, {0, 0, 183}, {0, 0, 184}, {0, 0, 185}, {0, 0, 186}, {0, 0, 188}, {0, 0, 189}, {0, 0, 190}, {0, 0, 191}, {0, 0, 193}, {0, 0, 194}, {0, 0, 195}, {0, 0, 196}, {0, 0, 197}, {0, 0, 198}, {0, 0, 200}, {0, 0, 201}, {0, 0, 202}, {0, 0, 203}, {0, 0, 204}, {0, 0, 206}, {0, 0, 207}, {0, 0, 208}, {0, 0, 209}, {0, 0, 211}, {0, 0, 212}, {0, 0, 213}, {0, 0, 214}, {0, 0, 216}, {0, 0, 217}, {0, 0, 218}, {0, 0, 219}, {0, 0, 221}, {0, 0, 222}, {0, 0, 223}, {0, 0, 225}, {0, 0, 226}, {0, 0, 227}, {0, 0, 228}, {0, 0, 230}, {0, 0, 231}, {0, 0, 232}, {0, 0, 233}, {0, 0, 234}, {0, 0, 234}, {0, 0, 235}, {0, 0, 236}, {0, 0, 237}, {0, 0, 238}, {0, 0, 239}, {0, 0, 239}, {0, 0, 240}, {0, 0, 241}, {0, 0, 242}, {0, 0, 243}, {0, 0, 244}, {0, 0, 246}, {0, 0, 247}, {0, 0, 248}, {0, 0, 249}, {0, 0, 250}, {0, 0, 251}, {0, 0, 253}, {0, 0, 254}, {0, 0, 254}, {0, 0, 254}, {0, 0, 254}, {0, 0, 254}, {0, 0, 254}, {0, 0, 255}, {0, 0, 255}, {0, 0, 255}, {0, 0, 255}, {0, 0, 255}, {0, 0, 255}, {0, 1, 255}, {0, 1, 255}, {0, 2, 255}, {0, 3, 255}, {0, 3, 255}, {0, 4, 255}, {0, 5, 255}, {0, 6, 255}, {0, 6, 255}, {0, 7, 255}, {0, 8, 255}, {0, 9, 255}, {0, 10, 255}, {0, 11, 255}, {0, 12, 255}, {0, 13, 255}, {0, 14, 255}, {0, 15, 255}, {0, 16, 255}, {0, 17, 255}, {0, 18, 255}, {0, 19, 255}, {0, 21, 255}, {0, 22, 255}, {0, 23, 255}, {0, 24, 255}, {0, 25, 255}, {0, 26, 255}, {0, 27, 255}, {0, 28, 255}, {0, 29, 255}, {0, 30, 255}, {0, 31, 255}, {0, 32, 255}, {0, 34, 255}, {0, 35, 255}, {0, 36, 255}, {0, 37, 255}, {0, 38, 255}, {0, 39, 255}, {0, 40, 255}, {0, 41, 255}, {0, 42, 255}, {0, 43, 255}, {0, 44, 255}, {0, 45, 255}, {0, 46, 255}, {0, 48, 255}, {0, 49, 255}, {0, 50, 255}, {0, 51, 255}, {0, 52, 255}, {0, 53, 255}, {0, 54, 255}, {0, 55, 255}, {0, 56, 255}, {0, 57, 255}, {0, 58, 255}, {0, 58, 255}, {0, 59, 255}, {0, 60, 255}, {0, 60, 255}, {0, 61, 255}, {0, 62, 255}, {0, 63, 255}, {0, 63, 255}, {0, 64, 255}, {0, 65, 255}, {0, 66, 255}, {0, 67, 255}, {0, 68, 255}, {0, 69, 255}, {0, 71, 255}, {0, 72, 255}, {0, 73, 255}, {0, 74, 255}, {0, 75, 255}, {0, 76, 255}, {0, 77, 255}, {0, 78, 255}, {0, 79, 255}, {0, 80, 255}, {0, 81, 255}, {0, 82, 255}, {0, 84, 255}, {0, 85, 255}, {0, 86, 255}, {0, 87, 255}, {0, 88, 255}, {0, 89, 255}, {0, 90, 255}, {0, 91, 255}, {0, 92, 255}, {0, 93, 255}, {0, 94, 255}, {0, 95, 255}, {0, 96, 255}, {0, 98, 255}, {0, 99, 255}, {0, 100, 255}, {0, 101, 255}, {0, 102, 255}, {0, 103, 255}, {0, 104, 255}, {0, 105, 255}, {0, 106, 255}, {0, 107, 255}, {0, 108, 255}, {0, 109, 255}, {0, 111, 255}, {0, 112, 255}, {0, 113, 255}, {0, 114, 255}, {0, 115, 255}, {0, 116, 255}, {0, 117, 255}, {0, 118, 255}, {0, 119, 255}, {0, 120, 255}, {0, 121, 255}, {0, 122, 255}, {0, 123, 255}, {0, 125, 255}, {0, 126, 255}, {0, 127, 255}, {0, 128, 255}, {0, 129, 255}, {0, 130, 255}, {0, 131, 255}, {0, 132, 255}, {0, 133, 255}, {0, 134, 255}, {0, 135, 255}, {0, 136, 255}, {0, 138, 255}, {0, 139, 255}, {0, 140, 255}, {0, 141, 255}, {0, 142, 255}, {0, 143, 255}, {0, 144, 255}, {0, 145, 255}, {0, 146, 255}, {0, 147, 255}, {0, 148, 255}, {0, 149, 255}, {0, 150, 255}, {0, 150, 255}, {0, 151, 255}, {0, 152, 255}, {0, 153, 255}, {0, 153, 255}, {0, 154, 255}, {0, 155, 255}, {0, 155, 255}, {0, 156, 255}, {0, 157, 255}, {0, 158, 255}, {0, 159, 255}, {0, 161, 255}, {0, 162, 255}, {0, 163, 255}, {0, 164, 255}, {0, 165, 255}, {0, 166, 255}, {0, 167, 255}, {0, 168, 255}, {0, 169, 255}, {0, 170, 255}, {0, 171, 255}, {0, 172, 255}, {0, 173, 255}, {0, 175, 255}, {0, 176, 255}, {0, 177, 255}, {0, 178, 255}, {0, 179, 255}, {0, 180, 255}, {0, 181, 255}, {0, 182, 255}, {0, 183, 255}, {0, 184, 255}, {0, 185, 255}, {0, 186, 255}, {0, 188, 255}, {0, 189, 255}, {0, 190, 255}, {0, 191, 255}, {0, 192, 255}, {0, 193, 255}, {0, 194, 255}, {0, 195, 255}, {0, 196, 255}, {0, 197, 255}, {0, 198, 255}, {0, 199, 255}, {0, 200, 255}, {0, 202, 255}, {0, 203, 255}, {0, 204, 255}, {0, 205, 255}, {0, 206, 255}, {0, 207, 255}, {0, 208, 255}, {0, 209, 255}, {0, 210, 255}, {0, 211, 255}, {0, 212, 255}, {0, 213, 255}, {0, 215, 255}, {0, 216, 255}, {0, 217, 255}, {0, 218, 254}, {0, 219, 253}, {0, 220, 252}, {0, 221, 252}, {0, 222, 251}, {0, 223, 250}, {0, 224, 250}, {0, 225, 249}, {0, 226, 248}, {0, 227, 247}, {0, 229, 247}, {1, 230, 246}, {2, 231, 245}, {3, 232, 244}, {3, 233, 243}, {4, 234, 242}, {5, 235, 241}, {5, 236, 240}, {6, 237, 239}, {7, 238, 238}, {8, 239, 238}, {8, 240, 237}, {9, 241, 236}, {10, 242, 236}, {10, 242, 235}, {11, 243, 235}, {11, 244, 234}, {12, 245, 234}, {13, 245, 233}, {13, 246, 232}, {14, 247, 232}, {15, 247, 231}, {15, 248, 231}, {16, 249, 230}, {17, 249, 229}, {18, 250, 228}, {18, 251, 227}, {19, 251, 226}, {20, 252, 225}, {21, 253, 224}, {22, 253, 224}, {23, 254, 223}, {23, 254, 222}, {24, 255, 221}, {25, 255, 220}, {26, 255, 219}, {27, 255, 218}, {28, 255, 218}, {29, 255, 217}, {30, 255, 216}, {30, 255, 215}, {31, 255, 214}, {32, 255, 214}, {33, 255, 213}, {34, 255, 212}, {35, 255, 211}, {36, 255, 210}, {37, 255, 209}, {38, 255, 208}, {39, 255, 207}, {39, 255, 207}, {40, 255, 206}, {41, 255, 205}, {42, 255, 204}, {43, 255, 203}, {44, 255, 202}, {45, 255, 201}, {46, 255, 200}, {47, 255, 199}, {48, 255, 198}, {48, 255, 198}, {49, 255, 197}, {50, 255, 196}, {51, 255, 195}, {52, 255, 194}, {53, 255, 193}, {54, 255, 192}, {55, 255, 191}, {55, 255, 191}, {56, 255, 190}, {57, 255, 189}, {58, 255, 188}, {59, 255, 187}, {60, 255, 186}, {60, 255, 186}, {61, 255, 185}, {62, 255, 184}, {63, 255, 183}, {64, 255, 182}, {65, 255, 181}, {65, 255, 181}, {66, 255, 180}, {67, 255, 179}, {68, 255, 178}, {69, 255, 177}, {70, 255, 176}, {71, 255, 175}, {72, 255, 174}, {73, 255, 173}, {74, 255, 172}, {74, 255, 172}, {75, 255, 171}, {76, 255, 170}, {77, 255, 169}, {78, 255, 168}, {79, 255, 167}, {80, 255, 166}, {81, 255, 165}, {82, 255, 164}, {83, 255, 163}, {83, 255, 163}, {84, 255, 162}, {84, 255, 162}, {85, 255, 161}, {85, 255, 161}, {86, 255, 160}, {87, 255, 159}, {87, 255, 159}, {88, 255, 158}, {88, 255, 158}, {89, 255, 157}, {89, 255, 157}, {90, 255, 156}, {91, 255, 155}, {92, 255, 154}, {93, 255, 153}, {94, 255, 152}, {95, 255, 151}, {96, 255, 150}, {97, 255, 149}, {97, 255, 149}, {98, 255, 148}, {99, 255, 147}, {100, 255, 146}, {101, 255, 145}, {102, 255, 144}, {102, 255, 143}, {103, 255, 142}, {104, 255, 141}, {105, 255, 140}, {106, 255, 140}, {107, 255, 139}, {107, 255, 138}, {108, 255, 137}, {109, 255, 136}, {110, 255, 135}, {111, 255, 134}, {112, 255, 134}, {113, 255, 133}, {114, 255, 132}, {114, 255, 131}, {115, 255, 130}, {116, 255, 130}, {117, 255, 129}, {118, 255, 128}, {119, 255, 127}, {120, 255, 126}, {121, 255, 125}, {122, 255, 124}, {123, 255, 123}, {123, 255, 123}, {124, 255, 122}, {125, 255, 121}, {126, 255, 120}, {127, 255, 119}, {128, 255, 118}, {129, 255, 117}, {130, 255, 116}, {130, 255, 115}, {131, 255, 114}, {132, 255, 114}, {133, 255, 113}, {134, 255, 112}, {134, 255, 111}, {135, 255, 110}, {136, 255, 109}, {137, 255, 108}, {138, 255, 107}, {139, 255, 107}, {140, 255, 106}, {140, 255, 105}, {141, 255, 104}, {142, 255, 103}, {143, 255, 102}, {144, 255, 102}, {145, 255, 101}, {146, 255, 100}, {147, 255, 99}, {148, 255, 98}, {149, 255, 97}, {149, 255, 97}, {150, 255, 96}, {151, 255, 95}, {152, 255, 94}, {153, 255, 93}, {154, 255, 92}, {155, 255, 91}, {156, 255, 90}, {157, 255, 89}, {157, 255, 89}, {158, 255, 88}, {158, 255, 88}, {159, 255, 87}, {159, 255, 87}, {160, 255, 86}, {161, 255, 85}, {161, 255, 85}, {162, 255, 84}, {162, 255, 84}, {163, 255, 83}, {163, 255, 83}, {164, 255, 82}, {165, 255, 81}, {166, 255, 80}, {167, 255, 79}, {168, 255, 78}, {169, 255, 77}, {170, 255, 76}, {171, 255, 75}, {172, 255, 74}, {172, 255, 74}, {173, 255, 73}, {174, 255, 72}, {175, 255, 71}, {176, 255, 70}, {177, 255, 69}, {178, 255, 68}, {179, 255, 67}, {180, 255, 66}, {181, 255, 65}, {181, 255, 65}, {182, 255, 64}, {183, 255, 63}, {184, 255, 62}, {185, 255, 61}, {186, 255, 60}, {186, 255, 60}, {187, 255, 59}, {188, 255, 58}, {189, 255, 57}, {190, 255, 56}, {191, 255, 55}, {191, 255, 55}, {192, 255, 54}, {193, 255, 53}, {194, 255, 52}, {195, 255, 51}, {196, 255, 50}, {197, 255, 49}, {198, 255, 48}, {198, 255, 48}, {199, 255, 47}, {200, 255, 46}, {201, 255, 45}, {202, 255, 44}, {203, 255, 43}, {204, 255, 42}, {205, 255, 41}, {206, 255, 40}, {207, 255, 39}, {207, 255, 39}, {208, 255, 38}, {209, 255, 37}, {210, 255, 36}, {211, 255, 35}, {212, 255, 34}, {213, 255, 33}, {214, 255, 32}, {214, 255, 31}, {215, 255, 30}, {216, 255, 30}, {217, 255, 29}, {218, 255, 28}, {218, 255, 27}, {219, 255, 26}, {220, 255, 25}, {221, 255, 24}, {222, 255, 23}, {223, 255, 23}, {224, 255, 22}, {224, 255, 21}, {225, 255, 20}, {226, 255, 19}, {227, 255, 18}, {228, 255, 18}, {229, 255, 17}, {230, 255, 16}, {231, 255, 15}, {231, 255, 15}, {232, 255, 14}, {232, 255, 13}, {233, 255, 13}, {234, 255, 12}, {234, 255, 11}, {235, 255, 11}, {235, 255, 10}, {236, 255, 10}, {236, 255, 9}, {237, 255, 8}, {238, 254, 8}, {238, 253, 7}, {239, 252, 6}, {240, 251, 5}, {241, 250, 5}, {242, 249, 4}, {243, 248, 3}, {244, 247, 3}, {245, 246, 2}, {246, 246, 1}, {247, 245, 0}, {247, 243, 0}, {248, 242, 0}, {249, 242, 0}, {250, 241, 0}, {250, 240, 0}, {251, 239, 0}, {252, 238, 0}, {252, 237, 0}, {253, 236, 0}, {254, 235, 0}, {255, 234, 0}, {255, 233, 0}, {255, 232, 0}, {255, 231, 0}, {255, 230, 0}, {255, 229, 0}, {255, 228, 0}, {255, 227, 0}, {255, 226, 0}, {255, 225, 0}, {255, 224, 0}, {255, 223, 0}, {255, 222, 0}, {255, 221, 0}, {255, 220, 0}, {255, 219, 0}, {255, 218, 0}, {255, 217, 0}, {255, 216, 0}, {255, 215, 0}, {255, 214, 0}, {255, 213, 0}, {255, 212, 0}, {255, 211, 0}, {255, 210, 0}, {255, 209, 0}, {255, 208, 0}, {255, 207, 0}, {255, 206, 0}, {255, 205, 0}, {255, 204, 0}, {255, 203, 0}, {255, 202, 0}, {255, 201, 0}, {255, 200, 0}, {255, 199, 0}, {255, 198, 0}, {255, 197, 0}, {255, 196, 0}, {255, 195, 0}, {255, 194, 0}, {255, 193, 0}, {255, 192, 0}, {255, 191, 0}, {255, 190, 0}, {255, 189, 0}, {255, 188, 0}, {255, 187, 0}, {255, 186, 0}, {255, 185, 0}, {255, 184, 0}, {255, 183, 0}, {255, 182, 0}, {255, 180, 0}, {255, 179, 0}, {255, 178, 0}, {255, 177, 0}, {255, 176, 0}, {255, 176, 0}, {255, 175, 0}, {255, 175, 0}, {255, 174, 0}, {255, 173, 0}, {255, 173, 0}, {255, 172, 0}, {255, 171, 0}, {255, 171, 0}, {255, 170, 0}, {255, 169, 0}, {255, 168, 0}, {255, 167, 0}, {255, 166, 0}, {255, 165, 0}, {255, 164, 0}, {255, 163, 0}, {255, 162, 0}, {255, 161, 0}, {255, 160, 0}, {255, 159, 0}, {255, 158, 0}, {255, 157, 0}, {255, 156, 0}, {255, 155, 0}, {255, 154, 0}, {255, 153, 0}, {255, 152, 0}, {255, 151, 0}, {255, 150, 0}, {255, 150, 0}, {255, 149, 0}, {255, 147, 0}, {255, 146, 0}, {255, 146, 0}, {255, 145, 0}, {255, 144, 0}, {255, 143, 0}, {255, 142, 0}, {255, 141, 0}, {255, 140, 0}, {255, 139, 0}, {255, 138, 0}, {255, 137, 0}, {255, 136, 0}, {255, 135, 0}, {255, 134, 0}, {255, 133, 0}, {255, 132, 0}, {255, 131, 0}, {255, 130, 0}, {255, 129, 0}, {255, 128, 0}, {255, 127, 0}, {255, 126, 0}, {255, 125, 0}, {255, 124, 0}, {255, 123, 0}, {255, 122, 0}, {255, 121, 0}, {255, 120, 0}, {255, 119, 0}, {255, 118, 0}, {255, 117, 0}, {255, 116, 0}, {255, 115, 0}, {255, 114, 0}, {255, 113, 0}, {255, 112, 0}, {255, 111, 0}, {255, 109, 0}, {255, 108, 0}, {255, 107, 0}, {255, 106, 0}, {255, 105, 0}, {255, 104, 0}, {255, 103, 0}, {255, 102, 0}, {255, 101, 0}, {255, 100, 0}, {255, 99, 0}, {255, 98, 0}, {255, 97, 0}, {255, 96, 0}, {255, 95, 0}, {255, 94, 0}, {255, 93, 0}, {255, 92, 0}, {255, 91, 0}, {255, 91, 0}, {255, 90, 0}, {255, 90, 0}, {255, 89, 0}, {255, 88, 0}, {255, 88, 0}, {255, 87, 0}, {255, 86, 0}, {255, 86, 0},<|fim▁hole|> {255, 73, 0}, {255, 72, 0}, {255, 71, 0}, {255, 70, 0}, {255, 69, 0}, {255, 68, 0}, {255, 67, 0}, {255, 66, 0}, {255, 65, 0}, {255, 64, 0}, {255, 63, 0}, {255, 62, 0}, {255, 61, 0}, {255, 60, 0}, {255, 59, 0}, {255, 58, 0}, {255, 57, 0}, {255, 56, 0}, {255, 55, 0}, {255, 54, 0}, {255, 54, 0}, {255, 53, 0}, {255, 51, 0}, {255, 50, 0}, {255, 49, 0}, {255, 48, 0}, {255, 47, 0}, {255, 46, 0}, {255, 45, 0}, {255, 44, 0}, {255, 43, 0}, {255, 42, 0}, {255, 41, 0}, {255, 40, 0}, {255, 39, 0}, {255, 38, 0}, {255, 37, 0}, {255, 36, 0}, {255, 35, 0}, {255, 34, 0}, {255, 33, 0}, {255, 32, 0}, {255, 31, 0}, {255, 30, 0}, {255, 29, 0}, {255, 28, 0}, {255, 27, 0}, {255, 26, 0}, {255, 25, 0}, {255, 24, 0}, {254, 23, 0}, {254, 22, 0}, {254, 21, 0}, {254, 20, 0}, {254, 19, 0}, {254, 18, 0}, {253, 17, 0}, {251, 16, 0}, {250, 15, 0}, {249, 14, 0}, {248, 13, 0}, {247, 12, 0}, {246, 11, 0}, {244, 10, 0}, {243, 9, 0}, {242, 8, 0}, {241, 7, 0}, {240, 6, 0}, {239, 6, 0}, {239, 5, 0}, {238, 4, 0}, {237, 4, 0}, {236, 3, 0}, {235, 3, 0}, {234, 2, 0}, {234, 1, 0}, {233, 1, 0}, {232, 0, 0}, {231, 0, 0}, {230, 0, 0}, {228, 0, 0}, {227, 0, 0}, {226, 0, 0}, {225, 0, 0}, {223, 0, 0}, {222, 0, 0}, {221, 0, 0}, {219, 0, 0}, {218, 0, 0}, {217, 0, 0}, {216, 0, 0}, {214, 0, 0}, {213, 0, 0}, {212, 0, 0}, {211, 0, 0}, {209, 0, 0}, {208, 0, 0}, {207, 0, 0}, {206, 0, 0}, {204, 0, 0}, {203, 0, 0}, {202, 0, 0}, {201, 0, 0}, {200, 0, 0}, {198, 0, 0}, {197, 0, 0}, {196, 0, 0}, {195, 0, 0}, {194, 0, 0}, {193, 0, 0}, {191, 0, 0}, {190, 0, 0}, {189, 0, 0}, {188, 0, 0}, {186, 0, 0}, {185, 0, 0}, {184, 0, 0}, {183, 0, 0}, {181, 0, 0}, {180, 0, 0}, {179, 0, 0}, {178, 0, 0}, {176, 0, 0}, {175, 0, 0}, {174, 0, 0}, {173, 0, 0}, {171, 0, 0}, {170, 0, 0}, {169, 0, 0}, {168, 0, 0}, {166, 0, 0}, {165, 0, 0}, {164, 0, 0}, {163, 0, 0}, {161, 0, 0}, {160, 0, 0}, {159, 0, 0}, {158, 0, 0}, {157, 0, 0}, {156, 0, 0}, {154, 0, 0}, {153, 0, 0}, {152, 0, 0}, {151, 0, 0}, {150, 0, 0}, {148, 0, 0}, {147, 0, 0}, {146, 0, 0}, {145, 0, 0}, {143, 0, 0}, {142, 0, 0}, {141, 0, 0}, {140, 0, 0}, {138, 0, 0}, {137, 0, 0}, {136, 0, 0}, {135, 0, 0}, {134, 0, 0}, {133, 0, 0}, {133, 0, 0}, {132, 0, 0}, {131, 0, 0}, {130, 0, 0}, {129, 0, 0}, {129, 0, 0}, {128, 0, 0}, {127, 0, 0}, {122, 0, 9}, {117, 0, 18}, {112, 0, 27}, {107, 0, 36}, {102, 0, 45}}; const rgb_store prism_colormap[1000] = { {255, 0, 0}, {255, 2, 0}, {255, 4, 0}, {255, 6, 0}, {255, 8, 0}, {255, 10, 0}, {255, 11, 0}, {255, 13, 0}, {255, 15, 0}, {255, 17, 0}, {255, 19, 0}, {255, 21, 0}, {255, 23, 0}, {255, 25, 0}, {255, 27, 0}, {255, 29, 0}, {255, 31, 0}, {255, 33, 0}, {255, 34, 0}, {255, 36, 0}, {255, 38, 0}, {255, 40, 0}, {255, 42, 0}, {255, 44, 0}, {255, 46, 0}, {255, 48, 0}, {255, 50, 0}, {255, 52, 0}, {255, 54, 0}, {255, 56, 0}, {255, 57, 0}, {255, 59, 0}, {255, 61, 0}, {255, 63, 0}, {255, 65, 0}, {255, 67, 0}, {255, 69, 0}, {255, 71, 0}, {255, 73, 0}, {255, 75, 0}, {255, 77, 0}, {255, 78, 0}, {255, 80, 0}, {255, 82, 0}, {255, 84, 0}, {255, 86, 0}, {255, 88, 0}, {255, 90, 0}, {255, 92, 0}, {255, 94, 0}, {255, 96, 0}, {255, 98, 0}, {255, 100, 0}, {255, 101, 0}, {255, 103, 0}, {255, 105, 0}, {255, 107, 0}, {255, 109, 0}, {255, 111, 0}, {255, 113, 0}, {255, 115, 0}, {255, 117, 0}, {255, 119, 0}, {255, 121, 0}, {255, 123, 0}, {255, 124, 0}, {255, 126, 0}, {255, 128, 0}, {255, 130, 0}, {255, 132, 0}, {255, 134, 0}, {255, 136, 0}, {255, 138, 0}, {255, 140, 0}, {255, 142, 0}, {255, 144, 0}, {255, 145, 0}, {255, 147, 0}, {255, 149, 0}, {255, 151, 0}, {255, 153, 0}, {255, 155, 0}, {255, 157, 0}, {255, 159, 0}, {255, 161, 0}, {255, 163, 0}, {255, 165, 0}, {255, 167, 0}, {255, 168, 0}, {255, 170, 0}, {255, 172, 0}, {255, 174, 0}, {255, 176, 0}, {255, 178, 0}, {255, 180, 0}, {255, 182, 0}, {255, 184, 0}, {255, 186, 0}, {255, 188, 0}, {255, 190, 0}, {255, 191, 0}, {255, 193, 0}, {255, 195, 0}, {255, 197, 0}, {255, 199, 0}, {255, 201, 0}, {255, 203, 0}, {255, 205, 0}, {255, 207, 0}, {255, 209, 0}, {255, 211, 0}, {255, 212, 0}, {255, 214, 0}, {255, 216, 0}, {255, 218, 0}, {255, 220, 0}, {255, 222, 0}, {255, 224, 0}, {255, 226, 0}, {255, 228, 0}, {255, 230, 0}, {255, 232, 0}, {255, 234, 0}, {255, 235, 0}, {255, 237, 0}, {255, 239, 0}, {255, 241, 0}, {255, 243, 0}, {255, 245, 0}, {255, 247, 0}, {255, 249, 0}, {255, 251, 0}, {255, 253, 0}, {255, 255, 0}, {252, 255, 0}, {248, 255, 0}, {244, 255, 0}, {240, 255, 0}, {237, 255, 0}, {233, 255, 0}, {229, 255, 0}, {225, 255, 0}, {221, 255, 0}, {217, 255, 0}, {214, 255, 0}, {210, 255, 0}, {206, 255, 0}, {202, 255, 0}, {198, 255, 0}, {195, 255, 0}, {191, 255, 0}, {187, 255, 0}, {183, 255, 0}, {179, 255, 0}, {175, 255, 0}, {172, 255, 0}, {168, 255, 0}, {164, 255, 0}, {160, 255, 0}, {156, 255, 0}, {152, 255, 0}, {149, 255, 0}, {145, 255, 0}, {141, 255, 0}, {137, 255, 0}, {133, 255, 0}, {129, 255, 0}, {126, 255, 0}, {122, 255, 0}, {118, 255, 0}, {114, 255, 0}, {110, 255, 0}, {106, 255, 0}, {103, 255, 0}, {99, 255, 0}, {95, 255, 0}, {91, 255, 0}, {87, 255, 0}, {83, 255, 0}, {80, 255, 0}, {76, 255, 0}, {72, 255, 0}, {68, 255, 0}, {64, 255, 0}, {60, 255, 0}, {57, 255, 0}, {53, 255, 0}, {49, 255, 0}, {45, 255, 0}, {41, 255, 0}, {38, 255, 0}, {34, 255, 0}, {30, 255, 0}, {26, 255, 0}, {22, 255, 0}, {18, 255, 0}, {15, 255, 0}, {11, 255, 0}, {7, 255, 0}, {3, 255, 0}, {0, 254, 1}, {0, 250, 5}, {0, 247, 8}, {0, 243, 12}, {0, 239, 16}, {0, 235, 20}, {0, 231, 24}, {0, 227, 28}, {0, 224, 31}, {0, 220, 35}, {0, 216, 39}, {0, 212, 43}, {0, 208, 47}, {0, 204, 51}, {0, 201, 54}, {0, 197, 58}, {0, 193, 62}, {0, 189, 66}, {0, 185, 70}, {0, 181, 74}, {0, 178, 77}, {0, 174, 81}, {0, 170, 85}, {0, 166, 89}, {0, 162, 93}, {0, 159, 96}, {0, 155, 100}, {0, 151, 104}, {0, 147, 108}, {0, 143, 112}, {0, 139, 116}, {0, 136, 119}, {0, 132, 123}, {0, 128, 127}, {0, 124, 131}, {0, 120, 135}, {0, 116, 139}, {0, 113, 142}, {0, 109, 146}, {0, 105, 150}, {0, 101, 154}, {0, 97, 158}, {0, 93, 162}, {0, 90, 165}, {0, 86, 169}, {0, 82, 173}, {0, 78, 177}, {0, 74, 181}, {0, 70, 185}, {0, 67, 188}, {0, 63, 192}, {0, 59, 196}, {0, 55, 200}, {0, 51, 204}, {0, 47, 208}, {0, 44, 211}, {0, 40, 215}, {0, 36, 219}, {0, 32, 223}, {0, 28, 227}, {0, 25, 230}, {0, 21, 234}, {0, 17, 238}, {0, 13, 242}, {0, 9, 246}, {0, 5, 250}, {0, 2, 253}, {2, 0, 255}, {4, 0, 255}, {7, 0, 255}, {9, 0, 255}, {12, 0, 255}, {14, 0, 255}, {17, 0, 255}, {19, 0, 255}, {22, 0, 255}, {25, 0, 255}, {27, 0, 255}, {30, 0, 255}, {32, 0, 255}, {35, 0, 255}, {37, 0, 255}, {40, 0, 255}, {42, 0, 255}, {45, 0, 255}, {47, 0, 255}, {50, 0, 255}, {53, 0, 255}, {55, 0, 255}, {58, 0, 255}, {60, 0, 255}, {63, 0, 255}, {65, 0, 255}, {68, 0, 255}, {70, 0, 255}, {73, 0, 255}, {76, 0, 255}, {78, 0, 255}, {81, 0, 255}, {83, 0, 255}, {86, 0, 255}, {88, 0, 255}, {91, 0, 255}, {93, 0, 255}, {96, 0, 255}, {99, 0, 255}, {101, 0, 255}, {104, 0, 255}, {106, 0, 255}, {109, 0, 255}, {111, 0, 255}, {114, 0, 255}, {116, 0, 255}, {119, 0, 255}, {122, 0, 255}, {124, 0, 255}, {127, 0, 255}, {129, 0, 255}, {132, 0, 255}, {134, 0, 255}, {137, 0, 255}, {139, 0, 255}, {142, 0, 255}, {144, 0, 255}, {147, 0, 255}, {150, 0, 255}, {152, 0, 255}, {155, 0, 255}, {157, 0, 255}, {160, 0, 255}, {162, 0, 255}, {165, 0, 255}, {167, 0, 255}, {170, 0, 255}, {171, 0, 251}, {173, 0, 247}, {174, 0, 244}, {175, 0, 240}, {176, 0, 236}, {178, 0, 232}, {179, 0, 228}, {180, 0, 224}, {181, 0, 221}, {183, 0, 217}, {184, 0, 213}, {185, 0, 209}, {187, 0, 205}, {188, 0, 201}, {189, 0, 198}, {190, 0, 194}, {192, 0, 190}, {193, 0, 186}, {194, 0, 182}, {196, 0, 178}, {197, 0, 175}, {198, 0, 171}, {199, 0, 167}, {201, 0, 163}, {202, 0, 159}, {203, 0, 155}, {204, 0, 152}, {206, 0, 148}, {207, 0, 144}, {208, 0, 140}, {210, 0, 136}, {211, 0, 132}, {212, 0, 129}, {213, 0, 125}, {215, 0, 121}, {216, 0, 117}, {217, 0, 113}, {218, 0, 110}, {220, 0, 106}, {221, 0, 102}, {222, 0, 98}, {224, 0, 94}, {225, 0, 90}, {226, 0, 87}, {227, 0, 83}, {229, 0, 79}, {230, 0, 75}, {231, 0, 71}, {233, 0, 67}, {234, 0, 64}, {235, 0, 60}, {236, 0, 56}, {238, 0, 52}, {239, 0, 48}, {240, 0, 44}, {241, 0, 41}, {243, 0, 37}, {244, 0, 33}, {245, 0, 29}, {247, 0, 25}, {248, 0, 21}, {249, 0, 18}, {250, 0, 14}, {252, 0, 10}, {253, 0, 6}, {254, 0, 2}, {255, 1, 0}, {255, 3, 0}, {255, 5, 0}, {255, 7, 0}, {255, 8, 0}, {255, 10, 0}, {255, 12, 0}, {255, 14, 0}, {255, 16, 0}, {255, 18, 0}, {255, 20, 0}, {255, 22, 0}, {255, 24, 0}, {255, 26, 0}, {255, 28, 0}, {255, 29, 0}, {255, 31, 0}, {255, 33, 0}, {255, 35, 0}, {255, 37, 0}, {255, 39, 0}, {255, 41, 0}, {255, 43, 0}, {255, 45, 0}, {255, 47, 0}, {255, 49, 0}, {255, 51, 0}, {255, 52, 0}, {255, 54, 0}, {255, 56, 0}, {255, 58, 0}, {255, 60, 0}, {255, 62, 0}, {255, 64, 0}, {255, 66, 0}, {255, 68, 0}, {255, 70, 0}, {255, 72, 0}, {255, 74, 0}, {255, 75, 0}, {255, 77, 0}, {255, 79, 0}, {255, 81, 0}, {255, 83, 0}, {255, 85, 0}, {255, 87, 0}, {255, 89, 0}, {255, 91, 0}, {255, 93, 0}, {255, 95, 0}, {255, 96, 0}, {255, 98, 0}, {255, 100, 0}, {255, 102, 0}, {255, 104, 0}, {255, 106, 0}, {255, 108, 0}, {255, 110, 0}, {255, 112, 0}, {255, 114, 0}, {255, 116, 0}, {255, 118, 0}, {255, 119, 0}, {255, 121, 0}, {255, 123, 0}, {255, 125, 0}, {255, 127, 0}, {255, 129, 0}, {255, 131, 0}, {255, 133, 0}, {255, 135, 0}, {255, 137, 0}, {255, 139, 0}, {255, 141, 0}, {255, 142, 0}, {255, 144, 0}, {255, 146, 0}, {255, 148, 0}, {255, 150, 0}, {255, 152, 0}, {255, 154, 0}, {255, 156, 0}, {255, 158, 0}, {255, 160, 0}, {255, 162, 0}, {255, 163, 0}, {255, 165, 0}, {255, 167, 0}, {255, 169, 0}, {255, 171, 0}, {255, 173, 0}, {255, 175, 0}, {255, 177, 0}, {255, 179, 0}, {255, 181, 0}, {255, 183, 0}, {255, 185, 0}, {255, 186, 0}, {255, 188, 0}, {255, 190, 0}, {255, 192, 0}, {255, 194, 0}, {255, 196, 0}, {255, 198, 0}, {255, 200, 0}, {255, 202, 0}, {255, 204, 0}, {255, 206, 0}, {255, 208, 0}, {255, 209, 0}, {255, 211, 0}, {255, 213, 0}, {255, 215, 0}, {255, 217, 0}, {255, 219, 0}, {255, 221, 0}, {255, 223, 0}, {255, 225, 0}, {255, 227, 0}, {255, 229, 0}, {255, 230, 0}, {255, 232, 0}, {255, 234, 0}, {255, 236, 0}, {255, 238, 0}, {255, 240, 0}, {255, 242, 0}, {255, 244, 0}, {255, 246, 0}, {255, 248, 0}, {255, 250, 0}, {255, 252, 0}, {255, 253, 0}, {254, 255, 0}, {250, 255, 0}, {247, 255, 0}, {243, 255, 0}, {239, 255, 0}, {235, 255, 0}, {231, 255, 0}, {227, 255, 0}, {224, 255, 0}, {220, 255, 0}, {216, 255, 0}, {212, 255, 0}, {208, 255, 0}, {204, 255, 0}, {201, 255, 0}, {197, 255, 0}, {193, 255, 0}, {189, 255, 0}, {185, 255, 0}, {181, 255, 0}, {178, 255, 0}, {174, 255, 0}, {170, 255, 0}, {166, 255, 0}, {162, 255, 0}, {159, 255, 0}, {155, 255, 0}, {151, 255, 0}, {147, 255, 0}, {143, 255, 0}, {139, 255, 0}, {136, 255, 0}, {132, 255, 0}, {128, 255, 0}, {124, 255, 0}, {120, 255, 0}, {116, 255, 0}, {113, 255, 0}, {109, 255, 0}, {105, 255, 0}, {101, 255, 0}, {97, 255, 0}, {93, 255, 0}, {90, 255, 0}, {86, 255, 0}, {82, 255, 0}, {78, 255, 0}, {74, 255, 0}, {70, 255, 0}, {67, 255, 0}, {63, 255, 0}, {59, 255, 0}, {55, 255, 0}, {51, 255, 0}, {47, 255, 0}, {44, 255, 0}, {40, 255, 0}, {36, 255, 0}, {32, 255, 0}, {28, 255, 0}, {25, 255, 0}, {21, 255, 0}, {17, 255, 0}, {13, 255, 0}, {9, 255, 0}, {5, 255, 0}, {2, 255, 0}, {0, 253, 2}, {0, 249, 6}, {0, 245, 10}, {0, 241, 14}, {0, 237, 18}, {0, 234, 21}, {0, 230, 25}, {0, 226, 29}, {0, 222, 33}, {0, 218, 37}, {0, 214, 41}, {0, 211, 44}, {0, 207, 48}, {0, 203, 52}, {0, 199, 56}, {0, 195, 60}, {0, 191, 64}, {0, 188, 67}, {0, 184, 71}, {0, 180, 75}, {0, 176, 79}, {0, 172, 83}, {0, 168, 87}, {0, 165, 90}, {0, 161, 94}, {0, 157, 98}, {0, 153, 102}, {0, 149, 106}, {0, 145, 110}, {0, 142, 113}, {0, 138, 117}, {0, 134, 121}, {0, 130, 125}, {0, 126, 129}, {0, 123, 132}, {0, 119, 136}, {0, 115, 140}, {0, 111, 144}, {0, 107, 148}, {0, 103, 152}, {0, 100, 155}, {0, 96, 159}, {0, 92, 163}, {0, 88, 167}, {0, 84, 171}, {0, 80, 175}, {0, 77, 178}, {0, 73, 182}, {0, 69, 186}, {0, 65, 190}, {0, 61, 194}, {0, 57, 198}, {0, 54, 201}, {0, 50, 205}, {0, 46, 209}, {0, 42, 213}, {0, 38, 217}, {0, 34, 221}, {0, 31, 224}, {0, 27, 228}, {0, 23, 232}, {0, 19, 236}, {0, 15, 240}, {0, 11, 244}, {0, 8, 247}, {0, 4, 251}, {0, 0, 255}, {3, 0, 255}, {5, 0, 255}, {8, 0, 255}, {10, 0, 255}, {13, 0, 255}, {15, 0, 255}, {18, 0, 255}, {20, 0, 255}, {23, 0, 255}, {26, 0, 255}, {28, 0, 255}, {31, 0, 255}, {33, 0, 255}, {36, 0, 255}, {38, 0, 255}, {41, 0, 255}, {43, 0, 255}, {46, 0, 255}, {48, 0, 255}, {51, 0, 255}, {54, 0, 255}, {56, 0, 255}, {59, 0, 255}, {61, 0, 255}, {64, 0, 255}, {66, 0, 255}, {69, 0, 255}, {71, 0, 255}, {74, 0, 255}, {77, 0, 255}, {79, 0, 255}, {82, 0, 255}, {84, 0, 255}, {87, 0, 255}, {89, 0, 255}, {92, 0, 255}, {94, 0, 255}, {97, 0, 255}, {100, 0, 255}, {102, 0, 255}, {105, 0, 255}, {107, 0, 255}, {110, 0, 255}, {112, 0, 255}, {115, 0, 255}, {117, 0, 255}, {120, 0, 255}, {123, 0, 255}, {125, 0, 255}, {128, 0, 255}, {130, 0, 255}, {133, 0, 255}, {135, 0, 255}, {138, 0, 255}, {140, 0, 255}, {143, 0, 255}, {145, 0, 255}, {148, 0, 255}, {151, 0, 255}, {153, 0, 255}, {156, 0, 255}, {158, 0, 255}, {161, 0, 255}, {163, 0, 255}, {166, 0, 255}, {168, 0, 255}, {171, 0, 253}, {172, 0, 250}, {173, 0, 246}, {174, 0, 242}, {176, 0, 238}, {177, 0, 234}, {178, 0, 230}, {179, 0, 227}, {181, 0, 223}, {182, 0, 219}, {183, 0, 215}, {185, 0, 211}, {186, 0, 208}, {187, 0, 204}, {188, 0, 200}, {190, 0, 196}, {191, 0, 192}, {192, 0, 188}, {193, 0, 185}, {195, 0, 181}, {196, 0, 177}, {197, 0, 173}, {199, 0, 169}, {200, 0, 165}, {201, 0, 162}, {202, 0, 158}, {204, 0, 154}, {205, 0, 150}, {206, 0, 146}, {208, 0, 142}, {209, 0, 139}, {210, 0, 135}, {211, 0, 131}, {213, 0, 127}, {214, 0, 123}, {215, 0, 119}, {216, 0, 116}, {218, 0, 112}, {219, 0, 108}, {220, 0, 104}, {222, 0, 100}, {223, 0, 96}, {224, 0, 93}, {225, 0, 89}, {227, 0, 85}, {228, 0, 81}, {229, 0, 77}, {230, 0, 74}, {232, 0, 70}, {233, 0, 66}, {234, 0, 62}, {236, 0, 58}, {237, 0, 54}, {238, 0, 51}, {239, 0, 47}, {241, 0, 43}, {242, 0, 39}, {243, 0, 35}, {245, 0, 31}, {246, 0, 28}, {247, 0, 24}, {248, 0, 20}, {250, 0, 16}, {251, 0, 12}, {252, 0, 8}, {253, 0, 5}, {255, 0, 1}, {255, 2, 0}, {255, 3, 0}, {255, 5, 0}, {255, 7, 0}, {255, 9, 0}, {255, 11, 0}, {255, 13, 0}, {255, 15, 0}, {255, 17, 0}, {255, 19, 0}, {255, 21, 0}, {255, 23, 0}, {255, 25, 0}, {255, 26, 0}, {255, 28, 0}, {255, 30, 0}, {255, 32, 0}, {255, 34, 0}, {255, 36, 0}, {255, 38, 0}, {255, 40, 0}, {255, 42, 0}, {255, 44, 0}, {255, 46, 0}, {255, 47, 0}, {255, 49, 0}, {255, 51, 0}, {255, 53, 0}, {255, 55, 0}, {255, 57, 0}, {255, 59, 0}, {255, 61, 0}, {255, 63, 0}, {255, 65, 0}, {255, 67, 0}, {255, 69, 0}, {255, 70, 0}, {255, 72, 0}, {255, 74, 0}, {255, 76, 0}, {255, 78, 0}, {255, 80, 0}, {255, 82, 0}, {255, 84, 0}, {255, 86, 0}, {255, 88, 0}, {255, 90, 0}, {255, 92, 0}, {255, 93, 0}, {255, 95, 0}, {255, 97, 0}, {255, 99, 0}, {255, 101, 0}, {255, 103, 0}, {255, 105, 0}, {255, 107, 0}, {255, 109, 0}, {255, 111, 0}, {255, 113, 0}, {255, 114, 0}, {255, 116, 0}, {255, 118, 0}, {255, 120, 0}, {255, 122, 0}, {255, 124, 0}, {255, 126, 0}, {255, 128, 0}, {255, 130, 0}, {255, 132, 0}, {255, 134, 0}, {255, 136, 0}, {255, 137, 0}, {255, 139, 0}, {255, 141, 0}, {255, 143, 0}, {255, 145, 0}, {255, 147, 0}, {255, 149, 0}, {255, 151, 0}, {255, 153, 0}, {255, 155, 0}, {255, 157, 0}, {255, 159, 0}, {255, 160, 0}, {255, 162, 0}, {255, 164, 0}, {255, 166, 0}, {255, 168, 0}, {255, 170, 0}, {255, 172, 0}, {255, 174, 0}, {255, 176, 0}, {255, 178, 0}, {255, 180, 0}, {255, 181, 0}, {255, 183, 0}, {255, 185, 0}, {255, 187, 0}, {255, 189, 0}, {255, 191, 0}, {255, 193, 0}, {255, 195, 0}, {255, 197, 0}, {255, 199, 0}, {255, 201, 0}, {255, 203, 0}, {255, 204, 0}, {255, 206, 0}, {255, 208, 0}, {255, 210, 0}, {255, 212, 0}, {255, 214, 0}, {255, 216, 0}, {255, 218, 0}, {255, 220, 0}, {255, 222, 0}, {255, 224, 0}, {255, 226, 0}, {255, 227, 0}, {255, 229, 0}, {255, 231, 0}, {255, 233, 0}, {255, 235, 0}, {255, 237, 0}, {255, 239, 0}, {255, 241, 0}, {255, 243, 0}, {255, 245, 0}, {255, 247, 0}, {255, 248, 0}, {255, 250, 0}, {255, 252, 0}, {255, 254, 0}, {253, 255, 0}, {249, 255, 0}, {245, 255, 0}, {241, 255, 0}, {237, 255, 0}, {234, 255, 0}, {230, 255, 0}, {226, 255, 0}, {222, 255, 0}, {218, 255, 0}, {214, 255, 0}, {211, 255, 0}, {207, 255, 0}, {203, 255, 0}, {199, 255, 0}, {195, 255, 0}, {191, 255, 0}, {188, 255, 0}, {184, 255, 0}, {180, 255, 0}, {176, 255, 0}, {172, 255, 0}, {168, 255, 0}, {165, 255, 0}, {161, 255, 0}, {157, 255, 0}, {153, 255, 0}, {149, 255, 0}, {145, 255, 0}, {142, 255, 0}, {138, 255, 0}, {134, 255, 0}, {130, 255, 0}, {126, 255, 0}, {123, 255, 0}, {119, 255, 0}, {115, 255, 0}, {111, 255, 0}, {107, 255, 0}, {103, 255, 0}, {100, 255, 0}, {96, 255, 0}, {92, 255, 0}, {88, 255, 0}, {84, 255, 0}, {80, 255, 0}, {77, 255, 0}, {73, 255, 0}, {69, 255, 0}, {65, 255, 0}, {61, 255, 0}, {57, 255, 0}, {54, 255, 0}, {50, 255, 0}, {46, 255, 0}, {42, 255, 0}, {38, 255, 0}, {34, 255, 0}, {31, 255, 0}, {27, 255, 0}, {23, 255, 0}, {19, 255, 0}, {15, 255, 0}, {11, 255, 0}, {8, 255, 0}, {4, 255, 0}, {0, 255, 0}}; const rgb_store vga_colormap[1000] = { {255}, {254, 254, 254}, {253, 253, 253}, {252, 252, 252}, {251, 251, 251}, {250, 250, 250}, {249, 249, 249}, {248, 248, 248}, {247, 247, 247}, {246, 246, 246}, {245, 245, 245}, {244, 244, 244}, {244, 244, 244}, {243, 243, 243}, {242, 242, 242}, {241, 241, 241}, {240, 240, 240}, {239, 239, 239}, {238, 238, 238}, {237, 237, 237}, {236, 236, 236}, {235, 235, 235}, {234, 234, 234}, {233, 233, 233}, {232, 232, 232}, {231, 231, 231}, {230, 230, 230}, {229, 229, 229}, {228, 228, 228}, {227, 227, 227}, {226, 226, 226}, {225, 225, 225}, {224, 224, 224}, {223, 223, 223}, {222, 222, 222}, {221, 221, 221}, {221, 221, 221}, {220, 220, 220}, {219, 219, 219}, {218, 218, 218}, {217, 217, 217}, {216, 216, 216}, {215, 215, 215}, {214, 214, 214}, {213, 213, 213}, {212, 212, 212}, {211, 211, 211}, {210, 210, 210}, {209, 209, 209}, {208, 208, 208}, {207, 207, 207}, {206, 206, 206}, {205, 205, 205}, {204, 204, 204}, {203, 203, 203}, {202, 202, 202}, {201, 201, 201}, {200, 200, 200}, {199, 199, 199}, {199, 199, 199}, {198, 198, 198}, {197, 197, 197}, {196, 196, 196}, {195, 195, 195}, {194, 194, 194}, {193, 193, 193}, {192, 192, 192}, {192, 190, 190}, {193, 187, 187}, {194, 184, 184}, {195, 181, 181}, {195, 179, 179}, {196, 176, 176}, {197, 173, 173}, {198, 170, 170}, {199, 167, 167}, {200, 164, 164}, {201, 161, 161}, {202, 159, 159}, {203, 156, 156}, {204, 153, 153}, {205, 150, 150}, {206, 147, 147}, {207, 144, 144}, {208, 141, 141}, {209, 138, 138}, {210, 136, 136}, {211, 133, 133}, {212, 130, 130}, {213, 127, 127}, {214, 124, 124}, {215, 121, 121}, {216, 118, 118}, {217, 115, 115}, {217, 113, 113}, {218, 110, 110}, {219, 107, 107}, {220, 104, 104}, {221, 101, 101}, {222, 98, 98}, {223, 95, 95}, {224, 92, 92}, {225, 90, 90}, {226, 87, 87}, {227, 84, 84}, {228, 81, 81}, {229, 78, 78}, {230, 75, 75}, {231, 72, 72}, {232, 69, 69}, {233, 67, 67}, {234, 64, 64}, {235, 61, 61}, {236, 58, 58}, {237, 55, 55}, {238, 52, 52}, {239, 49, 49}, {239, 47, 47}, {240, 44, 44}, {241, 41, 41}, {242, 38, 38}, {243, 35, 35}, {244, 32, 32}, {245, 29, 29}, {246, 26, 26}, {247, 24, 24}, {248, 21, 21}, {249, 18, 18}, {250, 15, 15}, {251, 12, 12}, {252, 9, 9}, {253, 6, 6}, {254, 3, 3}, {255, 1, 1}, {255, 3, 0}, {255, 7, 0}, {255, 11, 0}, {255, 15, 0}, {255, 18, 0}, {255, 22, 0}, {255, 26, 0}, {255, 30, 0}, {255, 34, 0}, {255, 38, 0}, {255, 41, 0}, {255, 45, 0}, {255, 49, 0}, {255, 53, 0}, {255, 57, 0}, {255, 60, 0}, {255, 64, 0}, {255, 68, 0}, {255, 72, 0}, {255, 76, 0}, {255, 80, 0}, {255, 83, 0}, {255, 87, 0}, {255, 91, 0}, {255, 95, 0}, {255, 99, 0}, {255, 103, 0}, {255, 106, 0}, {255, 110, 0}, {255, 114, 0}, {255, 118, 0}, {255, 122, 0}, {255, 126, 0}, {255, 129, 0}, {255, 133, 0}, {255, 137, 0}, {255, 141, 0}, {255, 145, 0}, {255, 149, 0}, {255, 152, 0}, {255, 156, 0}, {255, 160, 0}, {255, 164, 0}, {255, 168, 0}, {255, 172, 0}, {255, 175, 0}, {255, 179, 0}, {255, 183, 0}, {255, 187, 0}, {255, 191, 0}, {255, 195, 0}, {255, 198, 0}, {255, 202, 0}, {255, 206, 0}, {255, 210, 0}, {255, 214, 0}, {255, 217, 0}, {255, 221, 0}, {255, 225, 0}, {255, 229, 0}, {255, 233, 0}, {255, 237, 0}, {255, 240, 0}, {255, 244, 0}, {255, 248, 0}, {255, 252, 0}, {254, 255, 0}, {250, 255, 0}, {247, 255, 0}, {243, 255, 0}, {239, 255, 0}, {235, 255, 0}, {231, 255, 0}, {227, 255, 0}, {224, 255, 0}, {220, 255, 0}, {216, 255, 0}, {212, 255, 0}, {208, 255, 0}, {204, 255, 0}, {201, 255, 0}, {197, 255, 0}, {193, 255, 0}, {189, 255, 0}, {185, 255, 0}, {181, 255, 0}, {178, 255, 0}, {174, 255, 0}, {170, 255, 0}, {166, 255, 0}, {162, 255, 0}, {159, 255, 0}, {155, 255, 0}, {151, 255, 0}, {147, 255, 0}, {143, 255, 0}, {139, 255, 0}, {136, 255, 0}, {132, 255, 0}, {128, 255, 0}, {124, 255, 0}, {120, 255, 0}, {116, 255, 0}, {113, 255, 0}, {109, 255, 0}, {105, 255, 0}, {101, 255, 0}, {97, 255, 0}, {93, 255, 0}, {90, 255, 0}, {86, 255, 0}, {82, 255, 0}, {78, 255, 0}, {74, 255, 0}, {70, 255, 0}, {67, 255, 0}, {63, 255, 0}, {59, 255, 0}, {55, 255, 0}, {51, 255, 0}, {47, 255, 0}, {44, 255, 0}, {40, 255, 0}, {36, 255, 0}, {32, 255, 0}, {28, 255, 0}, {25, 255, 0}, {21, 255, 0}, {17, 255, 0}, {13, 255, 0}, {9, 255, 0}, {5, 255, 0}, {2, 255, 0}, {0, 255, 2}, {0, 255, 6}, {0, 255, 10}, {0, 255, 14}, {0, 255, 18}, {0, 255, 21}, {0, 255, 25}, {0, 255, 29}, {0, 255, 33}, {0, 255, 37}, {0, 255, 41}, {0, 255, 44}, {0, 255, 48}, {0, 255, 52}, {0, 255, 56}, {0, 255, 60}, {0, 255, 64}, {0, 255, 67}, {0, 255, 71}, {0, 255, 75}, {0, 255, 79}, {0, 255, 83}, {0, 255, 87}, {0, 255, 90}, {0, 255, 94}, {0, 255, 98}, {0, 255, 102}, {0, 255, 106}, {0, 255, 110}, {0, 255, 113}, {0, 255, 117}, {0, 255, 121}, {0, 255, 125}, {0, 255, 129}, {0, 255, 132}, {0, 255, 136}, {0, 255, 140}, {0, 255, 144}, {0, 255, 148}, {0, 255, 152}, {0, 255, 155}, {0, 255, 159}, {0, 255, 163}, {0, 255, 167}, {0, 255, 171}, {0, 255, 175}, {0, 255, 178}, {0, 255, 182}, {0, 255, 186}, {0, 255, 190}, {0, 255, 194}, {0, 255, 198}, {0, 255, 201}, {0, 255, 205}, {0, 255, 209}, {0, 255, 213}, {0, 255, 217}, {0, 255, 221}, {0, 255, 224}, {0, 255, 228}, {0, 255, 232}, {0, 255, 236}, {0, 255, 240}, {0, 255, 244}, {0, 255, 247}, {0, 255, 251}, {0, 255, 255}, {0, 251, 255}, {0, 247, 255}, {0, 244, 255}, {0, 240, 255}, {0, 236, 255}, {0, 232, 255}, {0, 228, 255}, {0, 224, 255}, {0, 221, 255}, {0, 217, 255}, {0, 213, 255}, {0, 209, 255}, {0, 205, 255}, {0, 201, 255}, {0, 198, 255}, {0, 194, 255}, {0, 190, 255}, {0, 186, 255}, {0, 182, 255}, {0, 178, 255}, {0, 175, 255}, {0, 171, 255}, {0, 167, 255}, {0, 163, 255}, {0, 159, 255}, {0, 155, 255}, {0, 152, 255}, {0, 148, 255}, {0, 144, 255}, {0, 140, 255}, {0, 136, 255}, {0, 132, 255}, {0, 129, 255}, {0, 125, 255}, {0, 121, 255}, {0, 117, 255}, {0, 113, 255}, {0, 110, 255}, {0, 106, 255}, {0, 102, 255}, {0, 98, 255}, {0, 94, 255}, {0, 90, 255}, {0, 87, 255}, {0, 83, 255}, {0, 79, 255}, {0, 75, 255}, {0, 71, 255}, {0, 67, 255}, {0, 64, 255}, {0, 60, 255}, {0, 56, 255}, {0, 52, 255}, {0, 48, 255}, {0, 44, 255}, {0, 41, 255}, {0, 37, 255}, {0, 33, 255}, {0, 29, 255}, {0, 25, 255}, {0, 21, 255}, {0, 18, 255}, {0, 14, 255}, {0, 10, 255}, {0, 6, 255}, {0, 2, 255}, {2, 0, 255}, {5, 0, 255}, {9, 0, 255}, {13, 0, 255}, {17, 0, 255}, {21, 0, 255}, {25, 0, 255}, {28, 0, 255}, {32, 0, 255}, {36, 0, 255}, {40, 0, 255}, {44, 0, 255}, {47, 0, 255}, {51, 0, 255}, {55, 0, 255}, {59, 0, 255}, {63, 0, 255}, {67, 0, 255}, {70, 0, 255}, {74, 0, 255}, {78, 0, 255}, {82, 0, 255}, {86, 0, 255}, {90, 0, 255}, {93, 0, 255}, {97, 0, 255}, {101, 0, 255}, {105, 0, 255}, {109, 0, 255}, {113, 0, 255}, {116, 0, 255}, {120, 0, 255}, {124, 0, 255}, {128, 0, 255}, {132, 0, 255}, {136, 0, 255}, {139, 0, 255}, {143, 0, 255}, {147, 0, 255}, {151, 0, 255}, {155, 0, 255}, {159, 0, 255}, {162, 0, 255}, {166, 0, 255}, {170, 0, 255}, {174, 0, 255}, {178, 0, 255}, {181, 0, 255}, {185, 0, 255}, {189, 0, 255}, {193, 0, 255}, {197, 0, 255}, {201, 0, 255}, {204, 0, 255}, {208, 0, 255}, {212, 0, 255}, {216, 0, 255}, {220, 0, 255}, {224, 0, 255}, {227, 0, 255}, {231, 0, 255}, {235, 0, 255}, {239, 0, 255}, {243, 0, 255}, {247, 0, 255}, {250, 0, 255}, {254, 0, 255}, {252, 0, 252}, {248, 0, 248}, {244, 0, 244}, {240, 0, 240}, {237, 0, 237}, {233, 0, 233}, {229, 0, 229}, {225, 0, 225}, {221, 0, 221}, {217, 0, 217}, {214, 0, 214}, {210, 0, 210}, {206, 0, 206}, {202, 0, 202}, {198, 0, 198}, {195, 0, 195}, {191, 0, 191}, {187, 0, 187}, {183, 0, 183}, {179, 0, 179}, {175, 0, 175}, {172, 0, 172}, {168, 0, 168}, {164, 0, 164}, {160, 0, 160}, {156, 0, 156}, {152, 0, 152}, {149, 0, 149}, {145, 0, 145}, {141, 0, 141}, {137, 0, 137}, {133, 0, 133}, {129, 0, 129}, {126, 0, 126}, {122, 0, 122}, {118, 0, 118}, {114, 0, 114}, {110, 0, 110}, {106, 0, 106}, {103, 0, 103}, {99, 0, 99}, {95, 0, 95}, {91, 0, 91}, {87, 0, 87}, {83, 0, 83}, {80, 0, 80}, {76, 0, 76}, {72, 0, 72}, {68, 0, 68}, {64, 0, 64}, {60, 0, 60}, {57, 0, 57}, {53, 0, 53}, {49, 0, 49}, {45, 0, 45}, {41, 0, 41}, {38, 0, 38}, {34, 0, 34}, {30, 0, 30}, {26, 0, 26}, {22, 0, 22}, {18, 0, 18}, {15, 0, 15}, {11, 0, 11}, {7, 0, 7}, {3, 0, 3}, {0, 0, 0}, {2, 2, 2}, {4, 4, 4}, {6, 6, 6}, {8, 8, 8}, {10, 10, 10}, {12, 12, 12}, {14, 14, 14}, {16, 16, 16}, {18, 18, 18}, {20, 20, 20}, {21, 21, 21}, {23, 23, 23}, {25, 25, 25}, {27, 27, 27}, {29, 29, 29}, {31, 31, 31}, {33, 33, 33}, {35, 35, 35}, {37, 37, 37}, {39, 39, 39}, {41, 41, 41}, {43, 43, 43}, {44, 44, 44}, {46, 46, 46}, {48, 48, 48}, {50, 50, 50}, {52, 52, 52}, {54, 54, 54}, {56, 56, 56}, {58, 58, 58}, {60, 60, 60}, {62, 62, 62}, {64, 64, 64}, {65, 65, 65}, {67, 67, 67}, {69, 69, 69}, {71, 71, 71}, {73, 73, 73}, {75, 75, 75}, {77, 77, 77}, {79, 79, 79}, {81, 81, 81}, {83, 83, 83}, {85, 85, 85}, {87, 87, 87}, {88, 88, 88}, {90, 90, 90}, {92, 92, 92}, {94, 94, 94}, {96, 96, 96}, {98, 98, 98}, {100, 100, 100}, {102, 102, 102}, {104, 104, 104}, {106, 106, 106}, {108, 108, 108}, {110, 110, 110}, {111, 111, 111}, {113, 113, 113}, {115, 115, 115}, {117, 117, 117}, {119, 119, 119}, {121, 121, 121}, {123, 123, 123}, {125, 125, 125}, {127, 127, 127}, {128, 126, 126}, {128, 124, 124}, {128, 123, 123}, {128, 121, 121}, {128, 119, 119}, {128, 117, 117}, {128, 115, 115}, {128, 113, 113}, {128, 111, 111}, {128, 109, 109}, {128, 107, 107}, {128, 105, 105}, {128, 103, 103}, {128, 101, 101}, {128, 100, 100}, {128, 98, 98}, {128, 96, 96}, {128, 94, 94}, {128, 92, 92}, {128, 90, 90}, {128, 88, 88}, {128, 86, 86}, {128, 84, 84}, {128, 82, 82}, {128, 80, 80}, {128, 78, 78}, {128, 77, 77}, {128, 75, 75}, {128, 73, 73}, {128, 71, 71}, {128, 69, 69}, {128, 67, 67}, {128, 65, 65}, {128, 63, 63}, {128, 61, 61}, {128, 59, 59}, {128, 57, 57}, {128, 56, 56}, {128, 54, 54}, {128, 52, 52}, {128, 50, 50}, {128, 48, 48}, {128, 46, 46}, {128, 44, 44}, {128, 42, 42}, {128, 40, 40}, {128, 38, 38}, {128, 36, 36}, {128, 34, 34}, {128, 33, 33}, {128, 31, 31}, {128, 29, 29}, {128, 27, 27}, {128, 25, 25}, {128, 23, 23}, {128, 21, 21}, {128, 19, 19}, {128, 17, 17}, {128, 15, 15}, {128, 13, 13}, {128, 11, 11}, {128, 10, 10}, {128, 8, 8}, {128, 6, 6}, {128, 4, 4}, {128, 2, 2}, {128, 0, 0}, {128, 2, 0}, {128, 4, 0}, {128, 6, 0}, {128, 8, 0}, {128, 10, 0}, {128, 11, 0}, {128, 13, 0}, {128, 15, 0}, {128, 17, 0}, {128, 19, 0}, {128, 21, 0}, {128, 23, 0}, {128, 25, 0}, {128, 27, 0}, {128, 29, 0}, {128, 31, 0}, {128, 33, 0}, {128, 34, 0}, {128, 36, 0}, {128, 38, 0}, {128, 40, 0}, {128, 42, 0}, {128, 44, 0}, {128, 46, 0}, {128, 48, 0}, {128, 50, 0}, {128, 52, 0}, {128, 54, 0}, {128, 56, 0}, {128, 57, 0}, {128, 59, 0}, {128, 61, 0}, {128, 63, 0}, {128, 65, 0}, {128, 67, 0}, {128, 69, 0}, {128, 71, 0}, {128, 73, 0}, {128, 75, 0}, {128, 77, 0}, {128, 78, 0}, {128, 80, 0}, {128, 82, 0}, {128, 84, 0}, {128, 86, 0}, {128, 88, 0}, {128, 90, 0}, {128, 92, 0}, {128, 94, 0}, {128, 96, 0}, {128, 98, 0}, {128, 100, 0}, {128, 101, 0}, {128, 103, 0}, {128, 105, 0}, {128, 107, 0}, {128, 109, 0}, {128, 111, 0}, {128, 113, 0}, {128, 115, 0}, {128, 117, 0}, {128, 119, 0}, {128, 121, 0}, {128, 123, 0}, {128, 124, 0}, {128, 126, 0}, {127, 128, 0}, {125, 128, 0}, {123, 128, 0}, {121, 128, 0}, {119, 128, 0}, {117, 128, 0}, {115, 128, 0}, {113, 128, 0}, {111, 128, 0}, {110, 128, 0}, {108, 128, 0}, {106, 128, 0}, {104, 128, 0}, {102, 128, 0}, {100, 128, 0}, {98, 128, 0}, {96, 128, 0}, {94, 128, 0}, {92, 128, 0}, {90, 128, 0}, {88, 128, 0}, {87, 128, 0}, {85, 128, 0}, {83, 128, 0}, {81, 128, 0}, {79, 128, 0}, {77, 128, 0}, {75, 128, 0}, {73, 128, 0}, {71, 128, 0}, {69, 128, 0}, {67, 128, 0}, {65, 128, 0}, {64, 128, 0}, {62, 128, 0}, {60, 128, 0}, {58, 128, 0}, {56, 128, 0}, {54, 128, 0}, {52, 128, 0}, {50, 128, 0}, {48, 128, 0}, {46, 128, 0}, {44, 128, 0}, {43, 128, 0}, {41, 128, 0}, {39, 128, 0}, {37, 128, 0}, {35, 128, 0}, {33, 128, 0}, {31, 128, 0}, {29, 128, 0}, {27, 128, 0}, {25, 128, 0}, {23, 128, 0}, {21, 128, 0}, {20, 128, 0}, {18, 128, 0}, {16, 128, 0}, {14, 128, 0}, {12, 128, 0}, {10, 128, 0}, {8, 128, 0}, {6, 128, 0}, {4, 128, 0}, {2, 128, 0}, {0, 128, 0}, {0, 128, 2}, {0, 128, 3}, {0, 128, 5}, {0, 128, 7}, {0, 128, 9}, {0, 128, 11}, {0, 128, 13}, {0, 128, 15}, {0, 128, 17}, {0, 128, 19}, {0, 128, 21}, {0, 128, 23}, {0, 128, 25}, {0, 128, 26}, {0, 128, 28}, {0, 128, 30}, {0, 128, 32}, {0, 128, 34}, {0, 128, 36}, {0, 128, 38}, {0, 128, 40}, {0, 128, 42}, {0, 128, 44}, {0, 128, 46}, {0, 128, 47}, {0, 128, 49}, {0, 128, 51}, {0, 128, 53}, {0, 128, 55}, {0, 128, 57}, {0, 128, 59}, {0, 128, 61}, {0, 128, 63}, {0, 128, 65}, {0, 128, 67}, {0, 128, 69}, {0, 128, 70}, {0, 128, 72}, {0, 128, 74}, {0, 128, 76}, {0, 128, 78}, {0, 128, 80}, {0, 128, 82}, {0, 128, 84}, {0, 128, 86}, {0, 128, 88}, {0, 128, 90}, {0, 128, 92}, {0, 128, 93}, {0, 128, 95}, {0, 128, 97}, {0, 128, 99}, {0, 128, 101}, {0, 128, 103}, {0, 128, 105}, {0, 128, 107}, {0, 128, 109}, {0, 128, 111}, {0, 128, 113}, {0, 128, 114}, {0, 128, 116}, {0, 128, 118}, {0, 128, 120}, {0, 128, 122}, {0, 128, 124}, {0, 128, 126}, {0, 127, 128}, {0, 125, 128}, {0, 123, 128}, {0, 121, 128}, {0, 119, 128}, {0, 118, 128}, {0, 116, 128}, {0, 114, 128}, {0, 112, 128}, {0, 110, 128}, {0, 108, 128}, {0, 106, 128}, {0, 104, 128}, {0, 102, 128}, {0, 100, 128}, {0, 98, 128}, {0, 96, 128}, {0, 95, 128}, {0, 93, 128}, {0, 91, 128}, {0, 89, 128}, {0, 87, 128}, {0, 85, 128}, {0, 83, 128}, {0, 81, 128}, {0, 79, 128}, {0, 77, 128}, {0, 75, 128}, {0, 74, 128}, {0, 72, 128}, {0, 70, 128}, {0, 68, 128}, {0, 66, 128}, {0, 64, 128}, {0, 62, 128}, {0, 60, 128}, {0, 58, 128}, {0, 56, 128}, {0, 54, 128}, {0, 52, 128}, {0, 51, 128}, {0, 49, 128}, {0, 47, 128}, {0, 45, 128}, {0, 43, 128}, {0, 41, 128}, {0, 39, 128}, {0, 37, 128}, {0, 35, 128}, {0, 33, 128}, {0, 31, 128}, {0, 29, 128}, {0, 28, 128}, {0, 26, 128}, {0, 24, 128}, {0, 22, 128}, {0, 20, 128}, {0, 18, 128}, {0, 16, 128}, {0, 14, 128}, {0, 12, 128}, {0, 10, 128}, {0, 8, 128}, {0, 7, 128}, {0, 5, 128}, {0, 3, 128}, {0, 1, 128}, {1, 0, 128}, {3, 0, 128}, {5, 0, 128}, {7, 0, 128}, {9, 0, 128}, {11, 0, 128}, {13, 0, 128}, {15, 0, 128}, {16, 0, 128}, {18, 0, 128}, {20, 0, 128}, {22, 0, 128}, {24, 0, 128}, {26, 0, 128}, {28, 0, 128}, {30, 0, 128}, {32, 0, 128}, {34, 0, 128}, {36, 0, 128}, {38, 0, 128}, {39, 0, 128}, {41, 0, 128}, {43, 0, 128}, {45, 0, 128}, {47, 0, 128}, {49, 0, 128}, {51, 0, 128}, {53, 0, 128}, {55, 0, 128}, {57, 0, 128}, {59, 0, 128}, {60, 0, 128}, {62, 0, 128}, {64, 0, 128}, {66, 0, 128}, {68, 0, 128}, {70, 0, 128}, {72, 0, 128}, {74, 0, 128}, {76, 0, 128}, {78, 0, 128}, {80, 0, 128}, {82, 0, 128}, {83, 0, 128}, {85, 0, 128}, {87, 0, 128}, {89, 0, 128}, {91, 0, 128}, {93, 0, 128}, {95, 0, 128}, {97, 0, 128}, {99, 0, 128}, {101, 0, 128}, {103, 0, 128}, {105, 0, 128}, {106, 0, 128}, {108, 0, 128}, {110, 0, 128}, {112, 0, 128}, {114, 0, 128}, {116, 0, 128}, {118, 0, 128}, {120, 0, 128}, {122, 0, 128}, {124, 0, 128}, {126, 0, 128}, {128, 0, 128}}; const rgb_store yarg_colormap[1000] = { {0, 0, 0}, {0, 0, 0}, {1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {2, 2, 2}, {2, 2, 2}, {2, 2, 2}, {2, 2, 2}, {3, 3, 3}, {3, 3, 3}, {3, 3, 3}, {3, 3, 3}, {4, 4, 4}, {4, 4, 4}, {4, 4, 4}, {4, 4, 4}, {5, 5, 5}, {5, 5, 5}, {5, 5, 5}, {5, 5, 5}, {6, 6, 6}, {6, 6, 6}, {6, 6, 6}, {6, 6, 6}, {7, 7, 7}, {7, 7, 7}, {7, 7, 7}, {7, 7, 7}, {8, 8, 8}, {8, 8, 8}, {8, 8, 8}, {8, 8, 8}, {9, 9, 9}, {9, 9, 9}, {9, 9, 9}, {9, 9, 9}, {10, 10, 10}, {10, 10, 10}, {10, 10, 10}, {10, 10, 10}, {11, 11, 11}, {11, 11, 11}, {11, 11, 11}, {11, 11, 11}, {12, 12, 12}, {12, 12, 12}, {12, 12, 12}, {13, 13, 13}, {13, 13, 13}, {13, 13, 13}, {13, 13, 13}, {14, 14, 14}, {14, 14, 14}, {14, 14, 14}, {14, 14, 14}, {15, 15, 15}, {15, 15, 15}, {15, 15, 15}, {15, 15, 15}, {16, 16, 16}, {16, 16, 16}, {16, 16, 16}, {16, 16, 16}, {17, 17, 17}, {17, 17, 17}, {17, 17, 17}, {17, 17, 17}, {18, 18, 18}, {18, 18, 18}, {18, 18, 18}, {18, 18, 18}, {19, 19, 19}, {19, 19, 19}, {19, 19, 19}, {19, 19, 19}, {20, 20, 20}, {20, 20, 20}, {20, 20, 20}, {20, 20, 20}, {21, 21, 21}, {21, 21, 21}, {21, 21, 21}, {21, 21, 21}, {22, 22, 22}, {22, 22, 22}, {22, 22, 22}, {22, 22, 22}, {23, 23, 23}, {23, 23, 23}, {23, 23, 23}, {23, 23, 23}, {24, 24, 24}, {24, 24, 24}, {24, 24, 24}, {25, 25, 25}, {25, 25, 25}, {25, 25, 25}, {25, 25, 25}, {26, 26, 26}, {26, 26, 26}, {26, 26, 26}, {26, 26, 26}, {27, 27, 27}, {27, 27, 27}, {27, 27, 27}, {27, 27, 27}, {28, 28, 28}, {28, 28, 28}, {28, 28, 28}, {28, 28, 28}, {29, 29, 29}, {29, 29, 29}, {29, 29, 29}, {29, 29, 29}, {30, 30, 30}, {30, 30, 30}, {30, 30, 30}, {30, 30, 30}, {31, 31, 31}, {31, 31, 31}, {31, 31, 31}, {31, 31, 31}, {32, 32, 32}, {32, 32, 32}, {32, 32, 32}, {32, 32, 32}, {33, 33, 33}, {33, 33, 33}, {33, 33, 33}, {33, 33, 33}, {34, 34, 34}, {34, 34, 34}, {34, 34, 34}, {34, 34, 34}, {35, 35, 35}, {35, 35, 35}, {35, 35, 35}, {35, 35, 35}, {36, 36, 36}, {36, 36, 36}, {36, 36, 36}, {37, 37, 37}, {37, 37, 37}, {37, 37, 37}, {37, 37, 37}, {38, 38, 38}, {38, 38, 38}, {38, 38, 38}, {38, 38, 38}, {39, 39, 39}, {39, 39, 39}, {39, 39, 39}, {39, 39, 39}, {40, 40, 40}, {40, 40, 40}, {40, 40, 40}, {40, 40, 40}, {41, 41, 41}, {41, 41, 41}, {41, 41, 41}, {41, 41, 41}, {42, 42, 42}, {42, 42, 42}, {42, 42, 42}, {42, 42, 42}, {43, 43, 43}, {43, 43, 43}, {43, 43, 43}, {43, 43, 43}, {44, 44, 44}, {44, 44, 44}, {44, 44, 44}, {44, 44, 44}, {45, 45, 45}, {45, 45, 45}, {45, 45, 45}, {45, 45, 45}, {46, 46, 46}, {46, 46, 46}, {46, 46, 46}, {46, 46, 46}, {47, 47, 47}, {47, 47, 47}, {47, 47, 47}, {47, 47, 47}, {48, 48, 48}, {48, 48, 48}, {48, 48, 48}, {48, 48, 48}, {49, 49, 49}, {49, 49, 49}, {49, 49, 49}, {50, 50, 50}, {50, 50, 50}, {50, 50, 50}, {50, 50, 50}, {51, 51, 51}, {51, 51, 51}, {51, 51, 51}, {51, 51, 51}, {52, 52, 52}, {52, 52, 52}, {52, 52, 52}, {52, 52, 52}, {53, 53, 53}, {53, 53, 53}, {53, 53, 53}, {53, 53, 53}, {54, 54, 54}, {54, 54, 54}, {54, 54, 54}, {54, 54, 54}, {55, 55, 55}, {55, 55, 55}, {55, 55, 55}, {55, 55, 55}, {56, 56, 56}, {56, 56, 56}, {56, 56, 56}, {56, 56, 56}, {57, 57, 57}, {57, 57, 57}, {57, 57, 57}, {57, 57, 57}, {58, 58, 58}, {58, 58, 58}, {58, 58, 58}, {58, 58, 58}, {59, 59, 59}, {59, 59, 59}, {59, 59, 59}, {59, 59, 59}, {60, 60, 60}, {60, 60, 60}, {60, 60, 60}, {60, 60, 60}, {61, 61, 61}, {61, 61, 61}, {61, 61, 61}, {62, 62, 62}, {62, 62, 62}, {62, 62, 62}, {62, 62, 62}, {63, 63, 63}, {63, 63, 63}, {63, 63, 63}, {63, 63, 63}, {64, 64, 64}, {64, 64, 64}, {64, 64, 64}, {64, 64, 64}, {65, 65, 65}, {65, 65, 65}, {65, 65, 65}, {65, 65, 65}, {66, 66, 66}, {66, 66, 66}, {66, 66, 66}, {66, 66, 66}, {67, 67, 67}, {67, 67, 67}, {67, 67, 67}, {67, 67, 67}, {68, 68, 68}, {68, 68, 68}, {68, 68, 68}, {68, 68, 68}, {69, 69, 69}, {69, 69, 69}, {69, 69, 69}, {69, 69, 69}, {70, 70, 70}, {70, 70, 70}, {70, 70, 70}, {70, 70, 70}, {71, 71, 71}, {71, 71, 71}, {71, 71, 71}, {71, 71, 71}, {72, 72, 72}, {72, 72, 72}, {72, 72, 72}, {72, 72, 72}, {73, 73, 73}, {73, 73, 73}, {73, 73, 73}, {74, 74, 74}, {74, 74, 74}, {74, 74, 74}, {74, 74, 74}, {75, 75, 75}, {75, 75, 75}, {75, 75, 75}, {75, 75, 75}, {76, 76, 76}, {76, 76, 76}, {76, 76, 76}, {76, 76, 76}, {77, 77, 77}, {77, 77, 77}, {77, 77, 77}, {77, 77, 77}, {78, 78, 78}, {78, 78, 78}, {78, 78, 78}, {78, 78, 78}, {79, 79, 79}, {79, 79, 79}, {79, 79, 79}, {79, 79, 79}, {80, 80, 80}, {80, 80, 80}, {80, 80, 80}, {80, 80, 80}, {81, 81, 81}, {81, 81, 81}, {81, 81, 81}, {81, 81, 81}, {82, 82, 82}, {82, 82, 82}, {82, 82, 82}, {82, 82, 82}, {83, 83, 83}, {83, 83, 83}, {83, 83, 83}, {83, 83, 83}, {84, 84, 84}, {84, 84, 84}, {84, 84, 84}, {84, 84, 84}, {85, 85, 85}, {85, 85, 85}, {85, 85, 85}, {86, 86, 86}, {86, 86, 86}, {86, 86, 86}, {86, 86, 86}, {87, 87, 87}, {87, 87, 87}, {87, 87, 87}, {87, 87, 87}, {88, 88, 88}, {88, 88, 88}, {88, 88, 88}, {88, 88, 88}, {89, 89, 89}, {89, 89, 89}, {89, 89, 89}, {89, 89, 89}, {90, 90, 90}, {90, 90, 90}, {90, 90, 90}, {90, 90, 90}, {91, 91, 91}, {91, 91, 91}, {91, 91, 91}, {91, 91, 91}, {92, 92, 92}, {92, 92, 92}, {92, 92, 92}, {92, 92, 92}, {93, 93, 93}, {93, 93, 93}, {93, 93, 93}, {93, 93, 93}, {94, 94, 94}, {94, 94, 94}, {94, 94, 94}, {94, 94, 94}, {95, 95, 95}, {95, 95, 95}, {95, 95, 95}, {95, 95, 95}, {96, 96, 96}, {96, 96, 96}, {96, 96, 96}, {96, 96, 96}, {97, 97, 97}, {97, 97, 97}, {97, 97, 97}, {98, 98, 98}, {98, 98, 98}, {98, 98, 98}, {98, 98, 98}, {99, 99, 99}, {99, 99, 99}, {99, 99, 99}, {99, 99, 99}, {100, 100, 100}, {100, 100, 100}, {100, 100, 100}, {100, 100, 100}, {101, 101, 101}, {101, 101, 101}, {101, 101, 101}, {101, 101, 101}, {102, 102, 102}, {102, 102, 102}, {102, 102, 102}, {102, 102, 102}, {103, 103, 103}, {103, 103, 103}, {103, 103, 103}, {103, 103, 103}, {104, 104, 104}, {104, 104, 104}, {104, 104, 104}, {104, 104, 104}, {105, 105, 105}, {105, 105, 105}, {105, 105, 105}, {105, 105, 105}, {106, 106, 106}, {106, 106, 106}, {106, 106, 106}, {106, 106, 106}, {107, 107, 107}, {107, 107, 107}, {107, 107, 107}, {107, 107, 107}, {108, 108, 108}, {108, 108, 108}, {108, 108, 108}, {108, 108, 108}, {109, 109, 109}, {109, 109, 109}, {109, 109, 109}, {110, 110, 110}, {110, 110, 110}, {110, 110, 110}, {110, 110, 110}, {111, 111, 111}, {111, 111, 111}, {111, 111, 111}, {111, 111, 111}, {112, 112, 112}, {112, 112, 112}, {112, 112, 112}, {112, 112, 112}, {113, 113, 113}, {113, 113, 113}, {113, 113, 113}, {113, 113, 113}, {114, 114, 114}, {114, 114, 114}, {114, 114, 114}, {114, 114, 114}, {115, 115, 115}, {115, 115, 115}, {115, 115, 115}, {115, 115, 115}, {116, 116, 116}, {116, 116, 116}, {116, 116, 116}, {116, 116, 116}, {117, 117, 117}, {117, 117, 117}, {117, 117, 117}, {117, 117, 117}, {118, 118, 118}, {118, 118, 118}, {118, 118, 118}, {118, 118, 118}, {119, 119, 119}, {119, 119, 119}, {119, 119, 119}, {119, 119, 119}, {120, 120, 120}, {120, 120, 120}, {120, 120, 120}, {120, 120, 120}, {121, 121, 121}, {121, 121, 121}, {121, 121, 121}, {122, 122, 122}, {122, 122, 122}, {122, 122, 122}, {122, 122, 122}, {123, 123, 123}, {123, 123, 123}, {123, 123, 123}, {123, 123, 123}, {124, 124, 124}, {124, 124, 124}, {124, 124, 124}, {124, 124, 124}, {125, 125, 125}, {125, 125, 125}, {125, 125, 125}, {125, 125, 125}, {126, 126, 126}, {126, 126, 126}, {126, 126, 126}, {126, 126, 126}, {127, 127, 127}, {127, 127, 127}, {127, 127, 127}, {127, 127, 127}, {128, 128, 128}, {128, 128, 128}, {128, 128, 128}, {128, 128, 128}, {129, 129, 129}, {129, 129, 129}, {129, 129, 129}, {129, 129, 129}, {130, 130, 130}, {130, 130, 130}, {130, 130, 130}, {130, 130, 130}, {131, 131, 131}, {131, 131, 131}, {131, 131, 131}, {131, 131, 131}, {132, 132, 132}, {132, 132, 132}, {132, 132, 132}, {132, 132, 132}, {133, 133, 133}, {133, 133, 133}, {133, 133, 133}, {133, 133, 133}, {134, 134, 134}, {134, 134, 134}, {134, 134, 134}, {135, 135, 135}, {135, 135, 135}, {135, 135, 135}, {135, 135, 135}, {136, 136, 136}, {136, 136, 136}, {136, 136, 136}, {136, 136, 136}, {137, 137, 137}, {137, 137, 137}, {137, 137, 137}, {137, 137, 137}, {138, 138, 138}, {138, 138, 138}, {138, 138, 138}, {138, 138, 138}, {139, 139, 139}, {139, 139, 139}, {139, 139, 139}, {139, 139, 139}, {140, 140, 140}, {140, 140, 140}, {140, 140, 140}, {140, 140, 140}, {141, 141, 141}, {141, 141, 141}, {141, 141, 141}, {141, 141, 141}, {142, 142, 142}, {142, 142, 142}, {142, 142, 142}, {142, 142, 142}, {143, 143, 143}, {143, 143, 143}, {143, 143, 143}, {143, 143, 143}, {144, 144, 144}, {144, 144, 144}, {144, 144, 144}, {144, 144, 144}, {145, 145, 145}, {145, 145, 145}, {145, 145, 145}, {145, 145, 145}, {146, 146, 146}, {146, 146, 146}, {146, 146, 146}, {147, 147, 147}, {147, 147, 147}, {147, 147, 147}, {147, 147, 147}, {148, 148, 148}, {148, 148, 148}, {148, 148, 148}, {148, 148, 148}, {149, 149, 149}, {149, 149, 149}, {149, 149, 149}, {149, 149, 149}, {150, 150, 150}, {150, 150, 150}, {150, 150, 150}, {150, 150, 150}, {151, 151, 151}, {151, 151, 151}, {151, 151, 151}, {151, 151, 151}, {152, 152, 152}, {152, 152, 152}, {152, 152, 152}, {152, 152, 152}, {153, 153, 153}, {153, 153, 153}, {153, 153, 153}, {153, 153, 153}, {154, 154, 154}, {154, 154, 154}, {154, 154, 154}, {154, 154, 154}, {155, 155, 155}, {155, 155, 155}, {155, 155, 155}, {155, 155, 155}, {156, 156, 156}, {156, 156, 156}, {156, 156, 156}, {156, 156, 156}, {157, 157, 157}, {157, 157, 157}, {157, 157, 157}, {157, 157, 157}, {158, 158, 158}, {158, 158, 158}, {158, 158, 158}, {159, 159, 159}, {159, 159, 159}, {159, 159, 159}, {159, 159, 159}, {160, 160, 160}, {160, 160, 160}, {160, 160, 160}, {160, 160, 160}, {161, 161, 161}, {161, 161, 161}, {161, 161, 161}, {161, 161, 161}, {162, 162, 162}, {162, 162, 162}, {162, 162, 162}, {162, 162, 162}, {163, 163, 163}, {163, 163, 163}, {163, 163, 163}, {163, 163, 163}, {164, 164, 164}, {164, 164, 164}, {164, 164, 164}, {164, 164, 164}, {165, 165, 165}, {165, 165, 165}, {165, 165, 165}, {165, 165, 165}, {166, 166, 166}, {166, 166, 166}, {166, 166, 166}, {166, 166, 166}, {167, 167, 167}, {167, 167, 167}, {167, 167, 167}, {167, 167, 167}, {168, 168, 168}, {168, 168, 168}, {168, 168, 168}, {168, 168, 168}, {169, 169, 169}, {169, 169, 169}, {169, 169, 169}, {169, 169, 169}, {170, 170, 170}, {170, 170, 170}, {170, 170, 170}, {171, 171, 171}, {171, 171, 171}, {171, 171, 171}, {171, 171, 171}, {172, 172, 172}, {172, 172, 172}, {172, 172, 172}, {172, 172, 172}, {173, 173, 173}, {173, 173, 173}, {173, 173, 173}, {173, 173, 173}, {174, 174, 174}, {174, 174, 174}, {174, 174, 174}, {174, 174, 174}, {175, 175, 175}, {175, 175, 175}, {175, 175, 175}, {175, 175, 175}, {176, 176, 176}, {176, 176, 176}, {176, 176, 176}, {176, 176, 176}, {177, 177, 177}, {177, 177, 177}, {177, 177, 177}, {177, 177, 177}, {178, 178, 178}, {178, 178, 178}, {178, 178, 178}, {178, 178, 178}, {179, 179, 179}, {179, 179, 179}, {179, 179, 179}, {179, 179, 179}, {180, 180, 180}, {180, 180, 180}, {180, 180, 180}, {180, 180, 180}, {181, 181, 181}, {181, 181, 181}, {181, 181, 181}, {181, 181, 181}, {182, 182, 182}, {182, 182, 182}, {182, 182, 182}, {183, 183, 183}, {183, 183, 183}, {183, 183, 183}, {183, 183, 183}, {184, 184, 184}, {184, 184, 184}, {184, 184, 184}, {184, 184, 184}, {185, 185, 185}, {185, 185, 185}, {185, 185, 185}, {185, 185, 185}, {186, 186, 186}, {186, 186, 186}, {186, 186, 186}, {186, 186, 186}, {187, 187, 187}, {187, 187, 187}, {187, 187, 187}, {187, 187, 187}, {188, 188, 188}, {188, 188, 188}, {188, 188, 188}, {188, 188, 188}, {189, 189, 189}, {189, 189, 189}, {189, 189, 189}, {189, 189, 189}, {190, 190, 190}, {190, 190, 190}, {190, 190, 190}, {190, 190, 190}, {191, 191, 191}, {191, 191, 191}, {191, 191, 191}, {191, 191, 191}, {192, 192, 192}, {192, 192, 192}, {192, 192, 192}, {192, 192, 192}, {193, 193, 193}, {193, 193, 193}, {193, 193, 193}, {193, 193, 193}, {194, 194, 194}, {194, 194, 194}, {194, 194, 194}, {195, 195, 195}, {195, 195, 195}, {195, 195, 195}, {195, 195, 195}, {196, 196, 196}, {196, 196, 196}, {196, 196, 196}, {196, 196, 196}, {197, 197, 197}, {197, 197, 197}, {197, 197, 197}, {197, 197, 197}, {198, 198, 198}, {198, 198, 198}, {198, 198, 198}, {198, 198, 198}, {199, 199, 199}, {199, 199, 199}, {199, 199, 199}, {199, 199, 199}, {200, 200, 200}, {200, 200, 200}, {200, 200, 200}, {200, 200, 200}, {201, 201, 201}, {201, 201, 201}, {201, 201, 201}, {201, 201, 201}, {202, 202, 202}, {202, 202, 202}, {202, 202, 202}, {202, 202, 202}, {203, 203, 203}, {203, 203, 203}, {203, 203, 203}, {203, 203, 203}, {204, 204, 204}, {204, 204, 204}, {204, 204, 204}, {204, 204, 204}, {205, 205, 205}, {205, 205, 205}, {205, 205, 205}, {205, 205, 205}, {206, 206, 206}, {206, 206, 206}, {206, 206, 206}, {207, 207, 207}, {207, 207, 207}, {207, 207, 207}, {207, 207, 207}, {208, 208, 208}, {208, 208, 208}, {208, 208, 208}, {208, 208, 208}, {209, 209, 209}, {209, 209, 209}, {209, 209, 209}, {209, 209, 209}, {210, 210, 210}, {210, 210, 210}, {210, 210, 210}, {210, 210, 210}, {211, 211, 211}, {211, 211, 211}, {211, 211, 211}, {211, 211, 211}, {212, 212, 212}, {212, 212, 212}, {212, 212, 212}, {212, 212, 212}, {213, 213, 213}, {213, 213, 213}, {213, 213, 213}, {213, 213, 213}, {214, 214, 214}, {214, 214, 214}, {214, 214, 214}, {214, 214, 214}, {215, 215, 215}, {215, 215, 215}, {215, 215, 215}, {215, 215, 215}, {216, 216, 216}, {216, 216, 216}, {216, 216, 216}, {216, 216, 216}, {217, 217, 217}, {217, 217, 217}, {217, 217, 217}, {217, 217, 217}, {218, 218, 218}, {218, 218, 218}, {218, 218, 218}, {218, 218, 218}, {219, 219, 219}, {219, 219, 219}, {219, 219, 219}, {220, 220, 220}, {220, 220, 220}, {220, 220, 220}, {220, 220, 220}, {221, 221, 221}, {221, 221, 221}, {221, 221, 221}, {221, 221, 221}, {222, 222, 222}, {222, 222, 222}, {222, 222, 222}, {222, 222, 222}, {223, 223, 223}, {223, 223, 223}, {223, 223, 223}, {223, 223, 223}, {224, 224, 224}, {224, 224, 224}, {224, 224, 224}, {224, 224, 224}, {225, 225, 225}, {225, 225, 225}, {225, 225, 225}, {225, 225, 225}, {226, 226, 226}, {226, 226, 226}, {226, 226, 226}, {226, 226, 226}, {227, 227, 227}, {227, 227, 227}, {227, 227, 227}, {227, 227, 227}, {228, 228, 228}, {228, 228, 228}, {228, 228, 228}, {228, 228, 228}, {229, 229, 229}, {229, 229, 229}, {229, 229, 229}, {229, 229, 229}, {230, 230, 230}, {230, 230, 230}, {230, 230, 230}, {230, 230, 230}, {231, 231, 231}, {231, 231, 231}, {231, 231, 231}, {232, 232, 232}, {232, 232, 232}, {232, 232, 232}, {232, 232, 232}, {233, 233, 233}, {233, 233, 233}, {233, 233, 233}, {233, 233, 233}, {234, 234, 234}, {234, 234, 234}, {234, 234, 234}, {234, 234, 234}, {235, 235, 235}, {235, 235, 235}, {235, 235, 235}, {235, 235, 235}, {236, 236, 236}, {236, 236, 236}, {236, 236, 236}, {236, 236, 236}, {237, 237, 237}, {237, 237, 237}, {237, 237, 237}, {237, 237, 237}, {238, 238, 238}, {238, 238, 238}, {238, 238, 238}, {238, 238, 238}, {239, 239, 239}, {239, 239, 239}, {239, 239, 239}, {239, 239, 239}, {240, 240, 240}, {240, 240, 240}, {240, 240, 240}, {240, 240, 240}, {241, 241, 241}, {241, 241, 241}, {241, 241, 241}, {241, 241, 241}, {242, 242, 242}, {242, 242, 242}, {242, 242, 242}, {242, 242, 242}, {243, 243, 243}, {243, 243, 243}, {243, 243, 243}, {244, 244, 244}, {244, 244, 244}, {244, 244, 244}, {244, 244, 244}, {245, 245, 245}, {245, 245, 245}, {245, 245, 245}, {245, 245, 245}, {246, 246, 246}, {246, 246, 246}, {246, 246, 246}, {246, 246, 246}, {247, 247, 247}, {247, 247, 247}, {247, 247, 247}, {247, 247, 247}, {248, 248, 248}, {248, 248, 248}, {248, 248, 248}, {248, 248, 248}, {249, 249, 249}, {249, 249, 249}, {249, 249, 249}, {249, 249, 249}, {250, 250, 250}, {250, 250, 250}, {250, 250, 250}, {250, 250, 250}, {251, 251, 251}, {251, 251, 251}, {251, 251, 251}, {251, 251, 251}, {252, 252, 252}, {252, 252, 252}, {252, 252, 252}, {252, 252, 252}, {253, 253, 253}, {253, 253, 253}, {253, 253, 253}, {253, 253, 253}, {254, 254, 254}, {254, 254, 254}, {254, 254, 254}, {254, 254, 254}, {255}, {255}}; #endif<|fim▁end|>
{255, 85, 0}, {255, 84, 0}, {255, 83, 0}, {255, 82, 0}, {255, 81, 0}, {255, 80, 0}, {255, 79, 0}, {255, 78, 0}, {255, 77, 0}, {255, 76, 0}, {255, 75, 0}, {255, 74, 0},
<|file_name|>jumbles nontrobo.py<|end_file_name|><|fim▁begin|>"""return a jumbled version of a string. eg, the lazy hamster is jumping becomes the lzay hmasetr si jmunipg shuffles insides of words. """ import random import string #okay, so this will be the jmuble algorythim <|fim▁hole|> def string_jumble(string_to_jumble, jumble_mode = True): #variables, internal string_to_return = "" #New string string_words = [""] #array containing the words of the string current_word = [] #array containing the letters of the current word punctuation_ = [] #array containing the punctuation i = 0 j = 0 #put the words in an array for char in string_to_jumble: #each space signifies a new word if char not in string.ascii_letters: punctuation_.append(char) i += 1 ##make sure there's something to put it in! string_words.append("") else: #otherwise add to the entry string_words[i] += char #print(string_words) THIS IS WORKING #put the letters of the word into an array, and then switch 'em for word in string_words: #if the word is two long and mode is true switch 'em if (len(word) >= 0) and (len(word) <= 3) : if jumble_mode == True: # for char in word: current_word.append(str(char)) #print(current_word) random.shuffle(current_word) #pop the word and a space into the return string for char in current_word: string_to_return += char string_to_return += punctuation_[string_words.index(word)] #print(string_to_return) current_word.clear() #that's all for this word continue #ok now for the REAL real deal #take away the first letter and put it in string_to_return bc it souldn't be jumbled i = 0 for char in word: if i == 0: string_to_return += char #print(string_to_return) i = 1 #assert bluh WORKING continue #then put almost all of the word in current_word[] #current_word.append("") if (i+1) < len(word): current_word.append(str(char)) #print(current_word) i +=1 #we should be at the last character now #print(i) print(len(word)+100) #jumble it #random.shuffle(current_word) #add to the new string for char in current_word: string_to_return += char #add the last lettr pus a space #if word[i]: string_to_return += word[i] #string_to_return += punctuation_[i] string_to_return += punctuation_[string_words.index(word)] print(punctuation_[string_words.index(word)]) #flush the string current_word.clear() #next word! print(string_to_return) print(punctuation_) #done #string_jumble("a0boop1boop3boop4boop5hey") string_jumble("I1think2my3dog4is5terribly6lazy;7I8-9I!mean,£he$-%is^really&quite*fat.")#looks like list.index won't work for us #string_jumble("")#fix this too<|fim▁end|>
#variables, passed #string_to_jumble = "" #yeah #jumble_mode = true # do u switch words of two letters
<|file_name|>sentimentAnalyzerVader.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Jan 27 16:23:07 2017 @author: user """ ## FOUND HERE http://www.nltk.org/howto/sentiment.html ## Source code http://www.nltk.org/_modules/nltk/sentiment/vader.html ## http://www.nltk.org/api/nltk.sentiment.html ## Hutto, C.J. & Gilbert, E.E. (2014). VADER: A Parsimonious Rule-based Model ##for Sentiment Analysis of Social Media Text. Eighth International Conference on ## Weblogs and Social Media (ICWSM-14). Ann Arbor, MI, June 2014. ## http://www.postgresqltutorial.com/postgresql-python from nltk.sentiment.vader import SentimentIntensityAnalyzer import psycopg2 import sys reload(sys) #Prevents errors with utf-8 encoding not working properly sys.setdefaultencoding('utf8') def SentimentAnalyzer(tweets): sid = SentimentIntensityAnalyzer() #need to nltk.download() to use all the packages sentiment_tweets = [] #for i in range(10): for tweet in tweets: tweet_id = tweet[0] tweet_id = str(tweet_id) tweet_id = int(tweet_id) ss = sid.polarity_scores(tweet[11]) if ss['compound'] <= -0.293: label = 'negative' elif ss['compound'] >= 0.293: label = 'positive' else: label = 'neutral' sentiment = ss['compound'] <|fim▁hole|> return sentiment_tweets<|fim▁end|>
sentiment_tweets.append((tweet_id,sentiment,label))
<|file_name|>0007_auto_20151117_1038.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models<|fim▁hole|> class Migration(migrations.Migration): dependencies = [ ('maximo', '0006_auto_20151111_2021'), ] operations = [ migrations.AlterField( model_name='maximoticket', name='number', field=models.CharField(validators=[django.core.validators.RegexValidator(regex='\\d{5,6}')], max_length=7), ), ]<|fim▁end|>
import django.core.validators
<|file_name|>SearchManager.java<|end_file_name|><|fim▁begin|>/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ package multiverse.server.engine; import java.util.Collection; import java.util.Map; import java.util.HashMap; import java.util.LinkedList; import multiverse.server.util.Log; import multiverse.server.objects.ObjectType; import multiverse.server.engine.Searchable; import multiverse.server.messages.SearchMessageFilter; import multiverse.server.messages.SearchMessage; import multiverse.msgsys.*; /** Object search framework. You can search for objects matching your criteria. <p> The platform provides the following searchable collections: <ul> <li>Markers - Search for markers in an instance by marker properties. Use SearchClause {@link multiverse.server.objects.Marker.Search Marker.Search} <li>Regions - Search for regions in an instance by region properties. Use SearchClause {@link multiverse.server.objects.Region.Search Region.Search} <li>Instances - Search for instances by instance properties. Use SearchClass {@link multiverse.server.engine.PropertySearch PropertySearch} </ul> <p> Plugins can register searchable object collections using {@link #registerSearchable registerSearchable()}. */ public class SearchManager { private SearchManager() { } /** Search for matching objects and get selected information. Search occurs for a single ObjectType. Information indicated in the 'SearchSelection' is returned for objects matching the 'SearchClause'. <p> The search clause is a SearchClass sub-class designed specifically for an object type (or class of object types). @param objectType Search for this object type @param searchClause Object matching criteria @param selection Information selection; only the indicated information will be returned. @return Collection of matching objects. */ public static Collection searchObjects(ObjectType objectType, SearchClause searchClause, SearchSelection selection) { SearchMessage message = new SearchMessage(objectType, searchClause, selection); Collector collector = new Collector(message); return collector.getResults(); } static class Collector implements ResponseCallback { public Collector(SearchMessage message) { searchMessage = message;<|fim▁hole|> { int expectedResponses = Engine.getAgent().sendBroadcastRPC(searchMessage, this); synchronized (this) { responders += expectedResponses; while (responders != 0) { try { this.wait(); } catch (InterruptedException e) { } } } return results; } public synchronized void handleResponse(ResponseMessage rr) { responders --; GenericResponseMessage response = (GenericResponseMessage) rr; Collection list = (Collection)response.getData(); if (list != null) results.addAll(list); if (responders == 0) this.notify(); } Collection results = new LinkedList(); SearchMessage searchMessage; int responders = 0; } /** Register a new searchable object collection. @param objectType Collection object type. @param searchable Object search implementation. */ public static void registerSearchable(ObjectType objectType, Searchable searchable) { SearchMessageFilter filter = new SearchMessageFilter(objectType); Engine.getAgent().createSubscription(filter, new SearchMessageCallback(searchable), MessageAgent.RESPONDER); } /** Register object match factory. A MatcherFactory returns a Matcher object that works for the given search clause and object class. @param searchClauseClass A SearchClause sub-class. @param instanceClass Instance object class. @param matcherFactory Can return a Matcher object capable of running the SearchClause against the instance object. */ public static void registerMatcher(Class searchClauseClass, Class instanceClass, MatcherFactory matcherFactory) { matchers.put(new MatcherKey(searchClauseClass,instanceClass), matcherFactory); } /** Get object matcher that can apply 'searchClause' to objects of 'instanceClass'. @param searchClause The matching criteria. @param instanceClass Instance object class. */ public static Matcher getMatcher(SearchClause searchClause, Class instanceClass) { MatcherFactory matcherFactory; matcherFactory = matchers.get(new MatcherKey(searchClause.getClass(), instanceClass)); if (matcherFactory == null) { Log.error("runSearch: No matcher for "+searchClause.getClass()+" "+instanceClass); return null; } return matcherFactory.createMatcher(searchClause); } static class MatcherKey { public MatcherKey(Class qt, Class it) { queryType = qt; instanceType = it; } public Class queryType; public Class instanceType; public boolean equals(Object key) { return (((MatcherKey)key).queryType == queryType) && (((MatcherKey)key).instanceType == instanceType); } public int hashCode() { return queryType.hashCode() + instanceType.hashCode(); } } static class SearchMessageCallback implements MessageCallback { public SearchMessageCallback(Searchable searchable) { this.searchable = searchable; } public void handleMessage(Message msg, int flags) { SearchMessage message = (SearchMessage) msg; Collection result = null; try { result = searchable.runSearch( message.getSearchClause(), message.getSearchSelection()); } catch (Exception e) { Log.exception("runSearch failed", e); } Engine.getAgent().sendObjectResponse(message, result); } Searchable searchable; } static Map<MatcherKey,MatcherFactory> matchers = new HashMap<MatcherKey,MatcherFactory>(); }<|fim▁end|>
} public Collection getResults()
<|file_name|>weight.pipe.ts<|end_file_name|><|fim▁begin|>import {Pipe, PipeTransform} from '@angular/core'; import { TopicObject } from './topic.model'; @Pipe({ name: 'weightSorting' })<|fim▁hole|>export class TopicWeightSort implements PipeTransform{ transform(array: Array<TopicObject>, args: string): Array<TopicObject> { if(!array || array === undefined || array.length === 0) return null; array.sort((a: TopicObject, b: TopicObject) => { if (a.weight > b.weight) { return -1; } else if (a.weight < b.weight) { return 1; } else { return 0; } }); return array; } }<|fim▁end|>
<|file_name|>ClientHandshakeSequenceTest.java<|end_file_name|><|fim▁begin|>package org.ovirt.engine.core.itests; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNotNull; import org.ovirt.engine.core.common.queries.*; import org.ovirt.engine.core.common.action.LoginUserParameters; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.RunVmParams; import org.ovirt.engine.core.compat.Guid; /** * Created by IntelliJ IDEA. User: gmostizk Date: Aug 31, 2009 Time: 11:28:01 AM To change this template use File | * Settings | File Templates. */ @Ignore public class ClientHandshakeSequenceTest extends AbstractBackendTest { @Test public void getDomainList() { VdcQueryReturnValue value = backend.RunPublicQuery(VdcQueryType.GetDomainList, new VdcQueryParametersBase()); assertTrue(value.getSucceeded()); assertNotNull(value.getReturnValue()); System.out.println(value.getReturnValue()); } @Test public void getVersion() { VdcQueryReturnValue value = backend.RunPublicQuery(VdcQueryType.GetConfigurationValue, new GetConfigurationValueParameters(ConfigurationValues.VdcVersion)); assertNotNull(value); assertNotNull(value.getReturnValue()); System.out.println("Version: " + value.getReturnValue()); } @Test public void loginAdmin() { VdcReturnValueBase value = backend.Login(new LoginUserParameters("admin", "admin", "domain", "os", "browser", "client_type")); assertTrue(value.getSucceeded()); assertNotNull(value.getActionReturnValue()); } <|fim▁hole|> RunVmParams params = new RunVmParams(Guid.NewGuid()); VdcReturnValueBase result = backend.runInternalAction(VdcActionType.RunVm, params); } }<|fim▁end|>
@Test public void testRunVm() {
<|file_name|>paint_listener.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use LayerId; use LayerProperties;<|fim▁hole|> /// The interface used by the painter to acquire draw targets for each paint frame and /// submit them to be drawn to the display. pub trait PaintListener { fn native_display(&mut self) -> Option<NativeDisplay>; /// Informs the compositor of the layers for the given pipeline. The compositor responds by /// creating and/or destroying paint layers as necessary. fn initialize_layers_for_pipeline(&mut self, pipeline_id: PipelineId, properties: Vec<LayerProperties>, epoch: Epoch); /// Sends new buffers for the given layers to the compositor. fn assign_painted_buffers(&mut self, pipeline_id: PipelineId, epoch: Epoch, replies: Vec<(LayerId, Box<LayerBufferSet>)>, frame_tree_id: FrameTreeId); /// Inform the compositor that these buffer requests will be ignored. fn ignore_buffer_requests(&mut self, buffer_requests: Vec<BufferRequest>); // Notification that the paint task wants to exit. fn notify_paint_thread_exiting(&mut self, pipeline_id: PipelineId); }<|fim▁end|>
use layers::layers::{BufferRequest, LayerBufferSet}; use layers::platform::surface::NativeDisplay; use msg::compositor_msg::{Epoch, FrameTreeId}; use msg::constellation_msg::PipelineId;
<|file_name|>nuvnfthresholdpolicy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from .fetchers import NUPermissionsFetcher from .fetchers import NUMetadatasFetcher from .fetchers import NUGlobalMetadatasFetcher from bambou import NURESTObject class NUVNFThresholdPolicy(NURESTObject): """ Represents a VNFThresholdPolicy in the VSD Notes: VNF Threshold Policy represents thresholds for resources consumed by VNF instance running on NS Gateway and action to be taken when resource utilization crosses configured thresholds. """ __rest_name__ = "vnfthresholdpolicy" __resource_name__ = "vnfthresholdpolicies" ## Constants CONST_ENTITY_SCOPE_GLOBAL = "GLOBAL" CONST_ACTION_SHUTOFF = "SHUTOFF" CONST_ACTION_NONE = "NONE" CONST_ENTITY_SCOPE_ENTERPRISE = "ENTERPRISE" def __init__(self, **kwargs): """ Initializes a VNFThresholdPolicy instance Notes: You can specify all parameters while calling this methods. A special argument named `data` will enable you to load the object from a Python dictionary Examples: >>> vnfthresholdpolicy = NUVNFThresholdPolicy(id=u'xxxx-xxx-xxx-xxx', name=u'VNFThresholdPolicy') >>> vnfthresholdpolicy = NUVNFThresholdPolicy(data=my_dict) """ super(NUVNFThresholdPolicy, self).__init__() # Read/Write Attributes self._cpu_threshold = None self._name = None self._last_updated_by = None self._last_updated_date = None self._action = None self._memory_threshold = None self._description = None self._min_occurrence = None self._embedded_metadata = None self._entity_scope = None self._monit_interval = None self._creation_date = None self._assoc_entity_type = None self._storage_threshold = None self._owner = None self._external_id = None self.expose_attribute(local_name="cpu_threshold", remote_name="CPUThreshold", attribute_type=int, is_required=False, is_unique=False) self.expose_attribute(local_name="name", remote_name="name", attribute_type=str, is_required=True, is_unique=False) self.expose_attribute(local_name="last_updated_by", remote_name="lastUpdatedBy", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name="last_updated_date", remote_name="lastUpdatedDate", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name="action", remote_name="action", attribute_type=str, is_required=False, is_unique=False, choices=[u'NONE', u'SHUTOFF']) self.expose_attribute(local_name="memory_threshold", remote_name="memoryThreshold", attribute_type=int, is_required=False, is_unique=False) self.expose_attribute(local_name="description", remote_name="description", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name="min_occurrence", remote_name="minOccurrence", attribute_type=int, is_required=False, is_unique=False) self.expose_attribute(local_name="embedded_metadata", remote_name="embeddedMetadata", attribute_type=list, is_required=False, is_unique=False) self.expose_attribute(local_name="entity_scope", remote_name="entityScope", attribute_type=str, is_required=False, is_unique=False, choices=[u'ENTERPRISE', u'GLOBAL']) self.expose_attribute(local_name="monit_interval", remote_name="monitInterval", attribute_type=int, is_required=False, is_unique=False) self.expose_attribute(local_name="creation_date", remote_name="creationDate", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name="assoc_entity_type", remote_name="assocEntityType", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name="storage_threshold", remote_name="storageThreshold", attribute_type=int, is_required=False, is_unique=False) self.expose_attribute(local_name="owner", remote_name="owner", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name="external_id", remote_name="externalID", attribute_type=str, is_required=False, is_unique=True) # Fetchers self.permissions = NUPermissionsFetcher.fetcher_with_object(parent_object=self, relationship="child") self.metadatas = NUMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child") self.global_metadatas = NUGlobalMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child") self._compute_args(**kwargs) # Properties @property def cpu_threshold(self): """ Get cpu_threshold value. Notes: Threshold for CPU usage This attribute is named `CPUThreshold` in VSD API. """ return self._cpu_threshold @cpu_threshold.setter def cpu_threshold(self, value): """ Set cpu_threshold value. Notes: Threshold for CPU usage This attribute is named `CPUThreshold` in VSD API. """ self._cpu_threshold = value @property def name(self): """ Get name value. Notes: Name of VNF agent policy """ return self._name @name.setter def name(self, value): """ Set name value. Notes: Name of VNF agent policy """ self._name = value @property def last_updated_by(self): """ Get last_updated_by value. Notes: ID of the user who last updated the object. This attribute is named `lastUpdatedBy` in VSD API. """ return self._last_updated_by @last_updated_by.setter def last_updated_by(self, value): """ Set last_updated_by value. Notes: ID of the user who last updated the object. This attribute is named `lastUpdatedBy` in VSD API. """ self._last_updated_by = value @property def last_updated_date(self): """ Get last_updated_date value. Notes: Time stamp when this object was last updated. This attribute is named `lastUpdatedDate` in VSD API. """ return self._last_updated_date @last_updated_date.setter def last_updated_date(self, value): """ Set last_updated_date value. Notes: Time stamp when this object was last updated. This attribute is named `lastUpdatedDate` in VSD API. """ self._last_updated_date = value @property def action(self): """ Get action value. Notes: Action to be taken on threshold crossover """ return self._action @action.setter def action(self, value): """ Set action value. Notes: Action to be taken on threshold crossover """ self._action = value @property def memory_threshold(self): """ Get memory_threshold value. Notes: Threshold for memory usage This attribute is named `memoryThreshold` in VSD API. """ return self._memory_threshold @memory_threshold.setter def memory_threshold(self, value): """ Set memory_threshold value. Notes: Threshold for memory usage This attribute is named `memoryThreshold` in VSD API. """ self._memory_threshold = value @property def description(self): """ Get description value. Notes: Description of VNF agent policy """ return self._description @description.setter def description(self, value): """ Set description value. Notes: Description of VNF agent policy """ self._description = value @property def min_occurrence(self): """ Get min_occurrence value. Notes: Minimum number of threshold crossover occurrence during monitoring interval before taking specified action <|fim▁hole|> This attribute is named `minOccurrence` in VSD API. """ return self._min_occurrence @min_occurrence.setter def min_occurrence(self, value): """ Set min_occurrence value. Notes: Minimum number of threshold crossover occurrence during monitoring interval before taking specified action This attribute is named `minOccurrence` in VSD API. """ self._min_occurrence = value @property def embedded_metadata(self): """ Get embedded_metadata value. Notes: Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration. This attribute is named `embeddedMetadata` in VSD API. """ return self._embedded_metadata @embedded_metadata.setter def embedded_metadata(self, value): """ Set embedded_metadata value. Notes: Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration. This attribute is named `embeddedMetadata` in VSD API. """ self._embedded_metadata = value @property def entity_scope(self): """ Get entity_scope value. Notes: Specify if scope of entity is Data center or Enterprise level This attribute is named `entityScope` in VSD API. """ return self._entity_scope @entity_scope.setter def entity_scope(self, value): """ Set entity_scope value. Notes: Specify if scope of entity is Data center or Enterprise level This attribute is named `entityScope` in VSD API. """ self._entity_scope = value @property def monit_interval(self): """ Get monit_interval value. Notes: Monitoring interval (minutes) for threshold crossover occurrences to be considered This attribute is named `monitInterval` in VSD API. """ return self._monit_interval @monit_interval.setter def monit_interval(self, value): """ Set monit_interval value. Notes: Monitoring interval (minutes) for threshold crossover occurrences to be considered This attribute is named `monitInterval` in VSD API. """ self._monit_interval = value @property def creation_date(self): """ Get creation_date value. Notes: Time stamp when this object was created. This attribute is named `creationDate` in VSD API. """ return self._creation_date @creation_date.setter def creation_date(self, value): """ Set creation_date value. Notes: Time stamp when this object was created. This attribute is named `creationDate` in VSD API. """ self._creation_date = value @property def assoc_entity_type(self): """ Get assoc_entity_type value. Notes: Type of the entity to which the Metadata is associated to. This attribute is named `assocEntityType` in VSD API. """ return self._assoc_entity_type @assoc_entity_type.setter def assoc_entity_type(self, value): """ Set assoc_entity_type value. Notes: Type of the entity to which the Metadata is associated to. This attribute is named `assocEntityType` in VSD API. """ self._assoc_entity_type = value @property def storage_threshold(self): """ Get storage_threshold value. Notes: Threshold for storage usage This attribute is named `storageThreshold` in VSD API. """ return self._storage_threshold @storage_threshold.setter def storage_threshold(self, value): """ Set storage_threshold value. Notes: Threshold for storage usage This attribute is named `storageThreshold` in VSD API. """ self._storage_threshold = value @property def owner(self): """ Get owner value. Notes: Identifies the user that has created this object. """ return self._owner @owner.setter def owner(self, value): """ Set owner value. Notes: Identifies the user that has created this object. """ self._owner = value @property def external_id(self): """ Get external_id value. Notes: External object ID. Used for integration with third party systems This attribute is named `externalID` in VSD API. """ return self._external_id @external_id.setter def external_id(self, value): """ Set external_id value. Notes: External object ID. Used for integration with third party systems This attribute is named `externalID` in VSD API. """ self._external_id = value<|fim▁end|>
<|file_name|>multi_line_uncomment_after.rs<|end_file_name|><|fim▁begin|>fn doub<selection>le(x: i32) -> i32 {<|fim▁hole|><|fim▁end|>
x</selection> * 2 }
<|file_name|>index.tmpl.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 10 _modified_time = 1440369075.543512 _enable_loop = True _template_filename = u'themes/monospace/templates/index.tmpl' _template_uri = u'index.tmpl' _source_encoding = 'utf-8' _exports = [u'content'] def _mako_get_namespace(context, name): try: return context.namespaces[(__name__, name)] except KeyError: _mako_generate_namespaces(context) return context.namespaces[(__name__, name)] def _mako_generate_namespaces(context): ns = runtime.TemplateNamespace(u'comments', context._clean_inheritance_tokens(), templateuri=u'comments_helper.tmpl', callables=None, calling_uri=_template_uri) context.namespaces[(__name__, u'comments')] = ns ns = runtime.TemplateNamespace(u'helper', context._clean_inheritance_tokens(), templateuri=u'index_helper.tmpl', callables=None, calling_uri=_template_uri) context.namespaces[(__name__, u'helper')] = ns def _mako_inherit(template, context): _mako_generate_namespaces(context) return runtime._inherit_from(context, u'base.tmpl', _template_uri) def render_body(context,**pageargs): __M_caller = context.caller_stack._push_frame() try: __M_locals = __M_dict_builtin(pageargs=pageargs) date_format = context.get('date_format', UNDEFINED) helper = _mako_get_namespace(context, 'helper') messages = context.get('messages', UNDEFINED) posts = context.get('posts', UNDEFINED) _link = context.get('_link', UNDEFINED) def content(): return render_content(context._locals(__M_locals)) comments = _mako_get_namespace(context, 'comments') index_teasers = context.get('index_teasers', UNDEFINED) __M_writer = context.writer() __M_writer(u'\n') __M_writer(u'\n')<|fim▁hole|> context['self'].content(**pageargs) __M_writer(u'\n') return '' finally: context.caller_stack._pop_frame() def render_content(context,**pageargs): __M_caller = context.caller_stack._push_frame() try: date_format = context.get('date_format', UNDEFINED) helper = _mako_get_namespace(context, 'helper') messages = context.get('messages', UNDEFINED) posts = context.get('posts', UNDEFINED) _link = context.get('_link', UNDEFINED) def content(): return render_content(context) comments = _mako_get_namespace(context, 'comments') index_teasers = context.get('index_teasers', UNDEFINED) __M_writer = context.writer() __M_writer(u'\n') for post in posts: __M_writer(u' <div class="postbox">\n <h1><a href="') __M_writer(unicode(post.permalink())) __M_writer(u'">') __M_writer(unicode(post.title())) __M_writer(u'</a></h1>\n <div class="meta" style="background-color: rgb(234, 234, 234); ">\n <span class="authordate">\n ') __M_writer(unicode(messages("Posted:"))) __M_writer(u' <time class="published" datetime="') __M_writer(unicode(post.date.isoformat())) __M_writer(u'">') __M_writer(unicode(post.formatted_date(date_format))) __M_writer(u'</time>\n </span>\n <br>\n <span class="tags">Tags:&nbsp;\n') if post.tags: for tag in post.tags: __M_writer(u' <a class="tag" href="') __M_writer(unicode(_link('tag', tag))) __M_writer(u'"><span>') __M_writer(unicode(tag)) __M_writer(u'</span></a>\n') __M_writer(u' </span>\n </div>\n ') __M_writer(unicode(post.text(teaser_only=index_teasers))) __M_writer(u'\n') if not post.meta('nocomments'): __M_writer(u' ') __M_writer(unicode(comments.comment_link(post.permalink(), post.base_path))) __M_writer(u'\n') __M_writer(u' </div>\n') __M_writer(u' ') __M_writer(unicode(helper.html_pager())) __M_writer(u'\n ') __M_writer(unicode(comments.comment_link_script())) __M_writer(u'\n\t') __M_writer(unicode(helper.mathjax_script(posts))) __M_writer(u'\n') return '' finally: context.caller_stack._pop_frame() """ __M_BEGIN_METADATA {"source_encoding": "utf-8", "line_map": {"22": 3, "25": 2, "31": 0, "45": 2, "46": 3, "47": 4, "52": 31, "58": 5, "71": 5, "72": 6, "73": 7, "74": 8, "75": 8, "76": 8, "77": 8, "78": 11, "79": 11, "80": 11, "81": 11, "82": 11, "83": 11, "84": 15, "85": 16, "86": 17, "87": 17, "88": 17, "89": 17, "90": 17, "91": 20, "92": 22, "93": 22, "94": 23, "95": 24, "96": 24, "97": 24, "98": 26, "99": 28, "100": 28, "101": 28, "102": 29, "103": 29, "104": 30, "105": 30, "111": 105}, "uri": "index.tmpl", "filename": "themes/monospace/templates/index.tmpl"} __M_END_METADATA """<|fim▁end|>
__M_writer(u'\n') if 'parent' not in context._data or not hasattr(context._data['parent'], 'content'):
<|file_name|>permission.js<|end_file_name|><|fim▁begin|>const PERM_NOT_FOUND = "Permission '_perm_' not found on '_role_' for '_res_'."; const Types = { ALL: 'ALL', CREATE: 'CREATE', READ: 'READ', UPDATE: 'UPDATE', DELETE: 'DELETE' }; /** * The map of role-resource tuple to permissions. * The first level key is the tuple, the second level key is the action. * Available actions are "ALL", "CREATE", "READ", "UPDATE", "DELETE". * @name Permission * @constructor */ function Permission() { //map of string to map of string-bool this.perms = {}; this.makeDefaultDeny(); } Permission.DEFAULT_KEY = '*::*'; <|fim▁hole|> * Visualization of the permissions in tuples. * @memberof Permission */ Permission.prototype.toString = function () { var action, entry, tuple, out = ['Size: ']; out.push(this.size()); out.push('\n-------\n'); for (tuple in this.perms) { if (this.perms.hasOwnProperty(tuple)) { out.push('- '); out.push(tuple); out.push('\n'); entry = this.perms[tuple]; for (action in entry) { if (entry.hasOwnProperty(action)) { out.push('\t'); out.push(action); out.push('\t'); out.push(entry[action]); out.push('\n'); } } } } return out.join(''); }; /** * Grants action permission on resource to role. * Adds the action permission to any existing actions. Overrides the * existing action permission if any. * * @param {string} role - The ID of the access request object. * @param {string} resource - The ID of the access control object. * @param {string} [action=ALL] - The access action. * @memberof Permission */ Permission.prototype.allow = function (role, resource, action) { var perm, key = this.makeKey(role, resource); if (!action) { action = Types.ALL; } if (this.has(key)) { perm = this.perms[key]; perm[action] = true; } else { this.perms[key] = this.makePermission(action, true); } }; /** * Removes all permissions. * @memberof Permission */ Permission.prototype.clear = function () { this.perms = {}; }; /** * Denies action permission on resource to role. * Adds the action permission to any existing actions. Overrides the * existing action permission if any. * * @param {string} role - The ID of the access request object. * @param {string} resource - The ID of the access control object. * @param {string} [action=ALL] - The access action. * @memberof Permission */ Permission.prototype.deny = function (role, resource, action) { var perm, key = this.makeKey(role, resource); if (!action) { action = Types.ALL; } if (this.has(key)) { perm = this.perms[key]; perm[action] = false; } else { this.perms[key] = this.makePermission(action, false); } }; /** * Exports a snapshot of the permissions map. * * @return {Object} A map with string keys and map values where * the values are maps of string to boolean entries. Typically * meant for persistent storage. * @memberof Permission */ Permission.prototype.export = function () { var i, j, clone = {}; for (i in this.perms) { if (this.perms.hasOwnProperty(i)) { clone[i] = {}; for (j in this.perms[i]) { if (this.perms[i].hasOwnProperty(j)) { clone[i][j] = this.perms[i][j]; } } } } return clone; }; /** * Determines if the role-resource tuple is available. * * @param {string} key - The tuple of role and resource. * @return {Boolean} Returns true if the permission is available for this tuple. * @memberof Permission */ Permission.prototype.has = function (key) { return this.perms.hasOwnProperty(key); }; /** * Re-creates the permission map with a new of permissions. * * @param {Object} map - The map of string-string-boolean * tuples. The first-level string is a permission key * (<aco>::<aro>); the second-level string is the set of * actions; the boolean value indicates whether the permission * is explicitly granted/denied. * @memberof Permission */ Permission.prototype.importMap = function (map) { var i, j; this.perms = {}; for (i in map) { if (map.hasOwnProperty(i)) { this.perms[i] = {}; for (j in map[i]) { if (map[i].hasOwnProperty(j)) { this.perms[i][j] = map[i][j]; } } } } }; /** * Determines if the role has access on the resource. * * @param {string} role - The ID of the access request object. * @param {string} resource - The ID of the access control object. * @return {Boolean} Returns true only if the role has been * explicitly given access to all actions on the resource. * Returns false if the role has been explicitly denied access. * Returns null otherwise. * @memberof Permission */ Permission.prototype.isAllowedAll = function (role, resource) { var k, perm, allSet = 0, key = this.makeKey(role, resource); if (!this.has(key)) { return null; } perm = this.perms[key]; for (k in perm) { if (perm.hasOwnProperty(k)) { if (perm[k] === false) { return false; } if (k !== Types.ALL) { allSet++; } } } if (perm.hasOwnProperty(Types.ALL)) { return true; //true because ALL=false would be caught in the loop } if (allSet === 4) { return true; } return null; }; /** * Determines if the role has access on the resource for the specific action. * The permission on the specific action is evaluated to see if it has been * specified. If not specified, the permission on the <code>ALL</code> * permission is evaluated. If both are not specified, <code>null</code> is * returned. * * @param {string} role - The ID of the access request object. * @param {string} resource - The ID of the access control object. * @param {string} action - The access action. * @return {Boolean} Returns true if the role has access to the specified * action on the resource. Returns false if the role is denied * access. Returns null if no permission is specified. * @memberof Permission */ Permission.prototype.isAllowed = function (role, resource, action) { var perm, key = this.makeKey(role, resource); if (!this.has(key)) { return null; } perm = this.perms[key]; if (perm[action] === undefined) { //if specific action is not present, check for ALL if (perm[Types.ALL] === undefined) { return null; } return perm[Types.ALL]; } //else specific action is present return perm[action]; }; /** * Determines if the role is denied access on the resource. * * @param {string} role - The ID of the access request object. * @param {string} resource - The ID of the access control object. * @return {Boolean} Returns true only if the role has been * explicitly denied access to all actions on the resource. * Returns false if the role has been explicitly granted access. * Returns null otherwise. * @memberof Permission */ Permission.prototype.isDeniedAll = function (role, resource) { var k, perm, allSet = 0, key = this.makeKey(role, resource); if (!this.has(key)) { return null; } perm = this.perms[key]; for (k in perm) { if (perm.hasOwnProperty(k)) { //if any entry is true, resource is NOT denied if (perm[k]) { return false; } if (k !== Types.ALL) { allSet++; } } } if (perm.hasOwnProperty(Types.ALL)) { return true; //true because ALL=true would be caught in the loop } if (allSet === 4) { return true; } return null; }; /** * Determines if the role is denied access on the resource for the specific * action. * The permission on the specific action is evaluated to see if it has been * specified. If not specified, the permission on the <code>ALL</code> * permission is evaluated. If both are not specified, <code>null</code> is * returned. * * @param {string} role - The ID of the access request object. * @param {string} resource - The ID of the access control object. * @param {string} action - The access action. * @return {Boolean} Returns true if the role is denied access * to the specified action on the resource. Returns false if the * role has access. Returns null if no permission is specified. * @memberof Permission */ Permission.prototype.isDenied = function (role, resource, action) { var perm, key = this.makeKey(role, resource); if (!this.has(key)) { return null; } perm = this.perms[key]; if (perm[action] === undefined) { //if specific action is not present, check for ALL if (perm[Types.ALL] === undefined) { return null; } return !perm[Types.ALL]; } //else specific action is present return !perm[action]; }; /** * Makes the default permission allow. * @memberof Permission */ Permission.prototype.makeDefaultAllow = function () { this.perms[Permission.DEFAULT_KEY] = this.makePermission(Types.ALL, true); }; /** * Makes the default permission deny. * @memberof Permission */ Permission.prototype.makeDefaultDeny = function () { this.perms[Permission.DEFAULT_KEY] = this.makePermission(Types.ALL, false); }; /** * Removes the specified permission on resource from role. * * @param {string} role - The ID of the access request object. * @param {string} resource - The ID of the access control object. * @param {string} [action=ALL] - The access action. * @throws Will throw an error if the permission is not available. * @memberof Permission */ Permission.prototype.remove = function (role, resource, action) { var orig, perm, type, key = this.makeKey(role, resource), resId = resource ? resource : '*', roleId = role ? role : '*'; if (!action) { action = Types.ALL; } if (!this.has(key)) { throw new Error(PERM_NOT_FOUND.replace(/_perm_/g, key) .replace(/_res_/g, resId) .replace(/_role_/g, roleId)); } perm = this.perms[key]; if (perm[action] !== undefined) { //i.e. if action is defined if (action === Types.ALL) { delete this.perms[key]; return; } else { //remove specific action delete perm[action]; } } else if (perm[Types.ALL] !== undefined) { //has ALL - remove and put in the others orig = perm[Types.ALL]; delete perm[Types.ALL]; for (type in Types) { if (Types.hasOwnProperty(type)) { if (type !== action && type !== Types.ALL) { perm[type] = orig; } } } } else if (action === Types.ALL) { delete this.perms[key]; return; } else { //i.e. action is not defined throw new Error(PERM_NOT_FOUND.replace(/_perm_/g, action) .replace(/_res_/g, resId) .replace(/_role_/g, roleId)); } if (Object.keys(perm).length === 0) { delete this.perms[key]; } else { this.perms[key] = perm; } }; /** * Removes all permissions related to the resource. * * @param {string} resourceId - The ID of the resource to remove. * @return {Number} The number of removed permissions. * @memberof Permission */ Permission.prototype.removeByResource = function (resourceId) { var key, toRemove = [], resId = '::' + resourceId; for (key in this.perms) { if (this.perms.hasOwnProperty(key)) { if (key.endsWith(resId)) { toRemove.push(key); } } } return remove(this.perms, toRemove); }; /** * Removes all permissions related to the role. * * @param {string} roleId - The ID of the role to remove. * @return {Number} The number of removed permissions. * @memberof Permission */ Permission.prototype.removeByRole = function (roleId) { var key, toRemove = [], rolId = roleId + '::'; for (key in this.perms) { if (this.perms.hasOwnProperty(key)) { if (key.startsWith(rolId)) { toRemove.push(key); } } } return remove(this.perms, toRemove); }; /** * The number of specified permissions. * * @return {Number} The number of permissions in the registry. * @memberof Permission */ Permission.prototype.size = function () { return Object.keys(this.perms).length; }; /** * Creates the key in the form "<aro>::<aco>" where "<aro>" is * the ID of the role, and "<aco>" is the ID of the resource. * * @param {string} role The ID of the role. * @param {string} resource The ID of the resource. * @return {string} The key of the permission. * @memberof Permission */ Permission.prototype.makeKey = function (role, resource) { var aco = resource ? resource : '*', aro = role ? role : '*'; return aro + '::' + aco; }; /** * Creates a permissions map. * * @param {string} action The action to set. Accepted values are * "ALL", "CREATE", "READ", "UPDATE", "DELETE". * @param {Boolean} allow Either true or false to grant or deny access. * @return {Object} The map of string-boolean values. * @memberof Permission */ Permission.prototype.makePermission = function (action, allow) { var perm = {}; perm[action] = allow; return perm; }; /** * Helper function called by remove functions to remove permissions. * @param {Object} perms - The map of permissions - Permission.perms. * @param {string[]} keys - The array of keys to remove from the permission. * @return {Number} Returns the number of removed permissions. */ function remove(perms, keys) { var i, removed = 0; for (i = 0; i < keys.length; i++) { if (perms.hasOwnProperty(keys[i])) { delete perms[keys[i]]; removed++; } } return removed; } module.exports = { Permission, Types, };<|fim▁end|>
/**
<|file_name|>tensorNetwork.cpp<|end_file_name|><|fim▁begin|>// Xerus - A General Purpose Tensor Library // Copyright (C) 2014-2017 Benjamin Huber and Sebastian Wolf. // // Xerus is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // Xerus is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with Xerus. If not, see <http://www.gnu.org/licenses/>. // // For further information on Xerus visit https://libXerus.org // or contact us at [email protected]. /** * @file * @brief Implementation of the TensorNetwork class. */ #include <xerus/tensorNetwork.h> #include <fstream> #include <xerus/misc/stringUtilities.h> #include <xerus/misc/containerSupport.h> #include <xerus/misc/math.h> #include <xerus/misc/missingFunctions.h> #include <xerus/misc/fileIO.h> #include <xerus/misc/internal.h> #include <xerus/basic.h> #include <xerus/index.h> #include <xerus/tensor.h> #include <xerus/indexedTensorList.h> #include <xerus/indexedTensorMoveable.h> #include <xerus/indexedTensor_tensor_factorisations.h> #include <xerus/contractionHeuristic.h> namespace xerus { /*- - - - - - - - - - - - - - - - - - - - - - - - - - Constructors - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ TensorNetwork::TensorNetwork() { nodes.emplace_back(TensorNode(std::make_unique<Tensor>())); } TensorNetwork::TensorNetwork(Tensor _other) : dimensions(_other.dimensions) { //NOTE don't use std::move here, because we need _other to be untouched to move it later nodes.emplace_back(std::make_unique<Tensor>(std::move(_other)), init_from_dimension_array()); } TensorNetwork::TensorNetwork( std::unique_ptr<Tensor>&& _tensor) : dimensions(_tensor->dimensions) { nodes.emplace_back(std::move(_tensor), init_from_dimension_array()); } TensorNetwork::TensorNetwork(size_t _degree) : dimensions(std::vector<size_t>(_degree, 1)) { nodes.emplace_back(std::make_unique<Tensor>(std::vector<size_t>(_degree, 1)), init_from_dimension_array()); } TensorNetwork::TensorNetwork(const ZeroNode _nodeStatus) { if(_nodeStatus == ZeroNode::Add) { nodes.emplace_back(TensorNode(std::make_unique<Tensor>())); } } TensorNetwork* TensorNetwork::get_copy() const { return new TensorNetwork(*this); } /*- - - - - - - - - - - - - - - - - - - - - - - - - - Internal Helper functions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ std::vector<TensorNetwork::Link> TensorNetwork::init_from_dimension_array() { std::vector<TensorNetwork::Link> newLinks; for (size_t d = 0; d < dimensions.size(); ++d) { externalLinks.emplace_back(0, d, dimensions[d], false); newLinks.emplace_back(-1, d, dimensions[d], true); } return newLinks; } TensorNetwork TensorNetwork::stripped_subnet(const std::function<bool(size_t)>& _idF) const { TensorNetwork cpy(ZeroNode::None); cpy.nodes.resize(nodes.size()); cpy.dimensions = dimensions; cpy.externalLinks = externalLinks; for (size_t id = 0; id < nodes.size(); ++id) { if (!_idF(id)) { continue; } cpy.nodes[id] = nodes[id].strippped_copy(); for (size_t i = 0; i < cpy.nodes[id].neighbors.size(); ++i) { TensorNetwork::Link &l = cpy.nodes[id].neighbors[i]; if (!l.external) { // Link was not external before if (!_idF(l.other)) { // ...but is "external" to this subnet l.external = true; l.indexPosition = cpy.externalLinks.size(); cpy.dimensions.emplace_back(l.dimension); cpy.externalLinks.emplace_back(id, i, l.dimension, false); } } } } size_t correction = 0; std::vector<long> toErase; for (size_t eid = 0; eid < cpy.externalLinks.size(); ++eid) { TensorNetwork::Link &l = cpy.externalLinks[eid]; if (!_idF(l.other)) { toErase.emplace_back(long(eid)); correction++; } else { INTERNAL_CHECK(cpy.nodes[l.other].neighbors[l.indexPosition].external, "ie"); INTERNAL_CHECK(cpy.nodes[l.other].neighbors[l.indexPosition].indexPosition == eid, "ie"); cpy.nodes[l.other].neighbors[l.indexPosition].indexPosition -= correction; } } for (size_t i = toErase.size(); i > 0; --i) { cpy.dimensions.erase(cpy.dimensions.begin()+toErase[i-1]); cpy.externalLinks.erase(cpy.externalLinks.begin()+toErase[i-1]); } cpy.require_valid_network(false); return cpy; } void TensorNetwork::contract_unconnected_subnetworks() { require_valid_network(); if(degree() == 0) { std::set<size_t> all; for(size_t i = 0; i < nodes.size(); ++i) { all.emplace_hint(all.end(), i); } contract(all); } else { std::vector<bool> seen(nodes.size(), false); std::vector<size_t> expansionStack; expansionStack.reserve(nodes.size()); // Starting at every external link... for (const TensorNetwork::Link& el : externalLinks) { if(!seen[el.other]) { seen[el.other] = true; expansionStack.push_back(el.other); } } // ...traverse the connected nodes in a depth-first manner. while (!expansionStack.empty()) { const size_t curr = expansionStack.back(); expansionStack.pop_back(); // Add unseen neighbors for (const TensorNetwork::Link& n : nodes[curr].neighbors) { if ( !n.external && !seen[n.other] ) { seen[n.other] = true; expansionStack.push_back(n.other); } } } // Construct set of all unseen nodes... std::set<size_t> toContract; for (size_t i = 0; i < nodes.size(); ++i) { if (!seen[i]) { toContract.emplace_hint(toContract.end(), i); } } // ...and contract them if (!toContract.empty()) { const size_t remaining = contract(toContract); INTERNAL_CHECK(nodes[remaining].degree() == 0, "Internal Error."); // Remove contracted degree-0 tensor nodes[remaining].erased = true; for(size_t i = 0; i < nodes.size(); ++i) { if(!nodes[i].erased) { *nodes[i].tensorObject *= (*nodes[remaining].tensorObject)[0]; break; } INTERNAL_CHECK(i < nodes.size()-1, "Internal Error."); } } } sanitize(); INTERNAL_CHECK(!nodes.empty(), "Internal error"); } std::pair< size_t, size_t > TensorNetwork::find_common_edge(const size_t _nodeA, const size_t _nodeB) const { size_t posA=~0ul, posB=~0ul; // Find common edge in nodeA IF_CHECK(bool foundCommon = false;) for(size_t i = 0; i < nodes[_nodeA].neighbors.size(); ++i) { if(nodes[_nodeA].neighbors[i].other == _nodeB) { posA = i; REQUIRE(!foundCommon, "TN round/move core does not work if the two nodes share more than one link."); IF_CHECK( foundCommon = true; ) IF_NO_CHECK( break; ) } } REQUIRE(foundCommon, "TN round does not work if the two nodes share no link."); posB = nodes[_nodeA].neighbors[posA].indexPosition; return std::pair<size_t, size_t>(posA, posB); } void TensorNetwork::perform_traces(const size_t _nodeId) { for (size_t i = 0; i < nodes[_nodeId].degree(); ++i) { const TensorNetwork::Link &link = nodes[_nodeId].neighbors[i]; if (link.links(_nodeId)) { nodes[_nodeId].tensorObject->perform_trace(i, link.indexPosition); const std::vector<Link> linkCopy(nodes[_nodeId].neighbors); for(size_t j = i+1; j < link.indexPosition; ++j) { const Link& otherLink = linkCopy[j]; if(otherLink.external) { externalLinks[otherLink.indexPosition].indexPosition -= 1; } else { nodes[otherLink.other].neighbors[otherLink.indexPosition].indexPosition -= 1; } } for(size_t j = link.indexPosition+1; j < nodes[_nodeId].degree(); ++j) { const Link& otherLink = linkCopy[j]; if(otherLink.external) { externalLinks[otherLink.indexPosition].indexPosition -= 2; } else { nodes[otherLink.other].neighbors[otherLink.indexPosition].indexPosition -= 2; } } nodes[_nodeId].neighbors.erase(nodes[_nodeId].neighbors.begin() + link.indexPosition); nodes[_nodeId].neighbors.erase(nodes[_nodeId].neighbors.begin() + i); //Redo this index i -= 1; } } } void TensorNetwork::sanitize() { std::vector<size_t> idMap(nodes.size()); // Move nodes size_t newId = 0, oldId = 0; for (; oldId < nodes.size(); ++oldId) { if (!nodes[oldId].erased) { idMap[oldId] = newId; if (newId != oldId) { std::swap(nodes[newId], nodes[oldId]); } newId++; } } // Update links nodes.resize(newId); for (TensorNode &n : nodes) { for (TensorNetwork::Link &l : n.neighbors) { if (!l.external) { l.other = idMap[l.other]; } } } // Update external links for (TensorNetwork::Link &l : externalLinks) { l.other = idMap[l.other]; } } /*- - - - - - - - - - - - - - - - - - - - - - - - - - Conversions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ TensorNetwork::operator Tensor() const { require_valid_network(); std::set<size_t> all; for(size_t i = 0; i < nodes.size(); ++i) { all.emplace_hint(all.end(), i); } TensorNetwork cpy(*this); size_t res = cpy.contract(all); std::vector<size_t> shuffle(degree()); for(size_t i = 0; i < cpy.nodes[res].neighbors.size(); ++i) { INTERNAL_CHECK(cpy.nodes[res].neighbors[i].external, "Internal Error"); shuffle[i] = cpy.nodes[res].neighbors[i].indexPosition; } Tensor result; reshuffle(result, *cpy.nodes[res].tensorObject, shuffle); return result; } /*- - - - - - - - - - - - - - - - - - - - - - - - - - Access - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ value_t TensorNetwork::operator[](const size_t _position) const { require_valid_network(); if (degree() == 0) { REQUIRE(_position == 0, "Tried to access non-existing entry of TN"); value_t value = 1.0; for(const TensorNode& node : nodes) { value *= (*node.tensorObject)[0]; } return value; } std::vector<size_t> positions(degree()); size_t remains = _position; for(size_t i = degree(); i > 1; --i) { positions[i-1] = remains%dimensions[i-1]; remains /= dimensions[i-1]; } positions[0] = remains; return operator[](positions); } value_t TensorNetwork::operator[](const Tensor::MultiIndex& _positions) const { require_valid_network(); TensorNetwork partialCopy; partialCopy.nodes = nodes; // Set all external indices in copy to the fixed values and evaluate the tensorObject accordingly for(TensorNode& node : partialCopy.nodes) { // Fix slates in external links size_t killedDimensions = 0; for(size_t i = 0; i < node.neighbors.size(); ++i) { if(node.neighbors[i].external) { node.tensorObject->fix_mode(i-killedDimensions, _positions[node.neighbors[i].indexPosition]); killedDimensions++; } } // Remove all external links, because they don't exist anymore node.neighbors.erase(std::remove_if(node.neighbors.begin(), node.neighbors.end(), [](const TensorNetwork::Link& _test){return _test.external;}), node.neighbors.end()); // Adjust the Links for(size_t i = 0; i < node.neighbors.size(); ++i) { partialCopy.nodes[node.neighbors[i].other].neighbors[node.neighbors[i].indexPosition].indexPosition = i; } } // Contract the complete network (there are not external Links) partialCopy.contract_unconnected_subnetworks(); INTERNAL_CHECK(partialCopy.nodes.size() == 1, "Internal Error."); return (*partialCopy.nodes[0].tensorObject)[0]; } /*- - - - - - - - - - - - - - - - - - - - - - - - - - Basic arithmetics - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ void TensorNetwork::operator*=(const value_t _factor) { REQUIRE(!nodes.empty(), "There must not be a TTNetwork without any node"); REQUIRE(!nodes[0].erased, "There must not be an erased node."); *nodes[0].tensorObject *= _factor; } void TensorNetwork::operator/=(const value_t _divisor) { REQUIRE(!nodes.empty(), "There must not be a TTNetwork without any node"); REQUIRE(!nodes[0].erased, "There must not be an erased node."); *nodes[0].tensorObject /= _divisor; } /*- - - - - - - - - - - - - - - - - - - - - - - - - - Indexing - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ internal::IndexedTensor<TensorNetwork> TensorNetwork::operator()(const std::vector<Index> & _indices) { return internal::IndexedTensor<TensorNetwork>(this, _indices, false); } internal::IndexedTensor<TensorNetwork> TensorNetwork::operator()( std::vector<Index>&& _indices) { return internal::IndexedTensor<TensorNetwork>(this, std::move(_indices), false); } internal::IndexedTensorReadOnly<TensorNetwork> TensorNetwork::operator()(const std::vector<Index> & _indices) const { return internal::IndexedTensorReadOnly<TensorNetwork>(this, _indices); } internal::IndexedTensorReadOnly<TensorNetwork> TensorNetwork::operator()( std::vector<Index>&& _indices) const { return internal::IndexedTensorReadOnly<TensorNetwork>(this, std::move(_indices)); } /*- - - - - - - - - - - - - - - - - - - - - - - - - - Operator specializations - - - - - - - - - - - - - - - - - - - - - - - - - - */ bool TensorNetwork::specialized_contraction(std::unique_ptr<internal::IndexedTensorMoveable<TensorNetwork>>& /*_out*/, internal::IndexedTensorReadOnly<TensorNetwork>&& /*_me*/ , internal::IndexedTensorReadOnly<TensorNetwork>&& /*_other*/ ) const { return false; // A general tensor Network can't do anything specialized } bool TensorNetwork::specialized_sum(std::unique_ptr<internal::IndexedTensorMoveable<TensorNetwork>>& /*_out*/, internal::IndexedTensorReadOnly<TensorNetwork>&& /*_me*/, internal::IndexedTensorReadOnly<TensorNetwork>&& /*_other*/) const { return false; // A general tensor Network can't do anything specialized } void TensorNetwork::specialized_evaluation(internal::IndexedTensorWritable<TensorNetwork>&& _me, internal::IndexedTensorReadOnly<TensorNetwork>&& _other) { TensorNetwork& me = *_me.tensorObject; const TensorNetwork& other = *_other.tensorObjectReadOnly; me = other; _other.assign_indices(); link_traces_and_fix((me)(_other.indices)); _me.assign_indices(); // Needed if &me == &other const std::vector<size_t> otherDimensions = other.dimensions; const std::vector<Link> otherExtLinks = other.externalLinks; for (size_t i = 0, dimPosA = 0; i < _me.indices.size(); dimPosA += _me.indices[i].span, ++i) { size_t j = 0, dimPosB = 0; while (_me.indices[i] != _other.indices[j]) { dimPosB += _other.indices[j].span; ++j; REQUIRE( j < _other.indices.size(), "LHS Index " << _me.indices[i] << " not found in RHS " << _other.indices); } REQUIRE(_me.indices[i].span == _other.indices[j].span, "Index spans must coincide"); for (size_t s = 0; s < _me.indices[i].span; ++s) { me.dimensions[dimPosA+s] = otherDimensions[dimPosB+s]; me.externalLinks[dimPosA+s] = otherExtLinks[dimPosB+s]; me.nodes[me.externalLinks[dimPosA+s].other].neighbors[me.externalLinks[dimPosA+s].indexPosition].indexPosition = dimPosA+s; me.nodes[me.externalLinks[dimPosA+s].other].neighbors[me.externalLinks[dimPosA+s].indexPosition].dimension = me.dimensions[dimPosA+s]; } } } /*- - - - - - - - - - - - - - - - - - - - - - - - - - Miscellaneous - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ size_t TensorNetwork::degree() const { return dimensions.size(); } size_t TensorNetwork::datasize() const { size_t result = 0; for (const TensorNode& node : nodes) { result += node.tensorObject->size; } return result; } void TensorNetwork::reshuffle_nodes(const std::function<size_t(size_t)>& _f) { std::vector<TensorNode> newNodes(nodes.size()); size_t newSize = 0; for (size_t i = 0; i < nodes.size(); ++i) { if (nodes[i].erased) { continue; } const size_t newIndex = _f(i); newSize = std::max(newSize, newIndex+1); REQUIRE(newNodes[newIndex].erased, "Tried to shuffle two nodes to the same new position " << newIndex << " i= " << i); newNodes[newIndex] = nodes[i]; for (TensorNetwork::Link &l : newNodes[newIndex].neighbors) { if (!l.external) { l.other = _f(l.other); } } } nodes = newNodes; nodes.resize(newSize); for (auto &link : externalLinks) { link.other = _f(link.other); } } #ifndef XERUS_DISABLE_RUNTIME_CHECKS void TensorNetwork::require_valid_network(const bool _check_erased) const { REQUIRE(externalLinks.size() == dimensions.size(), "externalLinks.size() != dimensions.size()"); REQUIRE(!nodes.empty(), "There must always be at least one node!"); // Per external link for (size_t n = 0; n < externalLinks.size(); ++n) { const TensorNetwork::Link& el = externalLinks[n]; REQUIRE(el.other < nodes.size(), "External link " << n << " is inconsitent. The linked node " << el.other << " does not exist, as there are only " << nodes.size() << " nodes."); REQUIRE(el.dimension > 0, "External link " << n << " is corrupted. The link specifies zero as dimension."); REQUIRE(el.dimension == dimensions[n], "External link " << n << " is inconsitent. The specified dimension " << el.dimension << " does not match the " << n << "-th dimension of the Network, which is " << dimensions[n] << "."); REQUIRE(!el.external, "External link " << n << " is corrupted. It specifies itself to be external, but must link to a node."); const TensorNode& otherNode = nodes[el.other]; const TensorNetwork::Link& otherLink = otherNode.neighbors[el.indexPosition]; REQUIRE(otherNode.degree() > el.indexPosition, "External link " << n << " is inconsitent. The link points to node " << el.other << " at IP " << el.indexPosition << ", but the target node only has " << otherNode.degree() << " links."); REQUIRE(otherLink.external, "External link " << n << " is inconsitent. The link points to node " << el.other << " at IP " << el.indexPosition << ", but the target link says it is not external."); REQUIRE(otherLink.indexPosition == n, "External link " << n << " is inconsitent. The link points to node " << el.other << " at IP " << el.indexPosition << ", but the nodes link points to IP " << otherLink.indexPosition << " instead of " << n << "."); REQUIRE(otherLink.dimension == el.dimension, "External link " << n << " is inconsitent. The link points to node " << el.other << " at IP " << el.indexPosition << ". The dimension specified by the external link is " << el.dimension << " but the one of the target link is " << otherLink.dimension << "."); } // Per node for (size_t n = 0; n < nodes.size(); ++n) { const TensorNode &currNode = nodes[n]; REQUIRE(!_check_erased || !currNode.erased, "Node " << n << " is marked erased, although this was not allowed."); if (currNode.tensorObject) { REQUIRE(currNode.degree() == currNode.tensorObject->degree(), "Node " << n << " has is inconsitent, as its tensorObject has degree " << currNode.tensorObject->degree() << " but there are " << currNode.degree() << " links."); } // Per neighbor for (size_t i = 0; i < currNode.neighbors.size(); ++i) { const TensorNetwork::Link &el = currNode.neighbors[i]; REQUIRE(el.dimension > 0, "n=" << n << " i=" << i); if (currNode.tensorObject) { REQUIRE(el.dimension == currNode.tensorObject->dimensions[i], "n=" << n << " i=" << i << " " << el.dimension << " vs " << currNode.tensorObject->dimensions[i]); } if(!el.external) { // externals were already checked REQUIRE(el.other < nodes.size(), "Inconsitent Link from node " << n << " to node " << el.other << " from IP " << i << " to IP " << el.indexPosition << ". The target node does not exist, as there are only " << nodes.size() << " nodes."); const TensorNode &other = nodes[el.other]; REQUIRE(other.degree() > el.indexPosition, "Inconsitent Link from node " << n << " to node " << el.other << " from IP " << i << " to IP " << el.indexPosition << ". Link at target does not exist as there are only " << other.degree() << " links."); REQUIRE(!other.neighbors[el.indexPosition].external, "Inconsitent Link from node " << n << " to node " << el.other << " from IP " << i << " to IP " << el.indexPosition << ". Link at target says it is external."); REQUIRE(other.neighbors[el.indexPosition].other == n, "Inconsitent Link from node " << n << " to node " << el.other << " from IP " << i << " to IP " << el.indexPosition << ". Link at target links to node " << other.neighbors[el.indexPosition].other << " at IP " << other.neighbors[el.indexPosition].indexPosition); REQUIRE(other.neighbors[el.indexPosition].indexPosition == i, "Inconsitent Link from node " << n << " to node " << el.other << " from IP " << i << " to IP " << el.indexPosition << ". Link at target links to node " << other.neighbors[el.indexPosition].other << " at IP " << other.neighbors[el.indexPosition].indexPosition); REQUIRE(other.neighbors[el.indexPosition].dimension == el.dimension, "Inconsitent Link from node " << n << " to node " << el.other << " from IP " << i << " to IP " << el.indexPosition << ". Dimension of this link is " << el.dimension << " but the target link says the dimension is " << other.neighbors[el.indexPosition].dimension); } } } } #else /// No checks are performed with disabled checks... void TensorNetwork::require_valid_network(bool _check_erased) const { } #endif void TensorNetwork::require_correct_format() const { require_valid_network(); } void TensorNetwork::swap_external_links(const size_t _i, const size_t _j) { const TensorNetwork::Link& li = externalLinks[_i]; const TensorNetwork::Link& lj = externalLinks[_j]; nodes[li.other].neighbors[li.indexPosition].indexPosition = _j; nodes[lj.other].neighbors[lj.indexPosition].indexPosition = _i; std::swap(externalLinks[_i], externalLinks[_j]); std::swap(dimensions[_i], dimensions[_j]); } void TensorNetwork::add_network_to_network(internal::IndexedTensorWritable<TensorNetwork>&& _base, internal::IndexedTensorReadOnly<TensorNetwork>&& _toInsert) { _base.assign_indices(); _toInsert.assign_indices(); TensorNetwork &base = *_base.tensorObject; const TensorNetwork &toInsert = *_toInsert.tensorObjectReadOnly; const size_t firstNew = base.nodes.size(); const size_t firstNewExternal = base.externalLinks.size(); // Insert everything _base.indices.insert(_base.indices.end(), _toInsert.indices.begin(), _toInsert.indices.end()); base.dimensions.insert(base.dimensions.end(), toInsert.dimensions.begin(), toInsert.dimensions.end()); base.externalLinks.insert(base.externalLinks.end(), toInsert.externalLinks.begin(), toInsert.externalLinks.end()); base.nodes.insert(base.nodes.end(), toInsert.nodes.begin(), toInsert.nodes.end()); IF_CHECK ( for (const Index &idx : _base.indices) { REQUIRE(misc::count(_base.indices, idx) < 3, "Index must not appear three (or more) times."); } ) // Sanitize the externalLinks for (size_t i = firstNewExternal; i < base.externalLinks.size(); ++i) { base.externalLinks[i].other += firstNew; } // Sanitize the nodes (treating all external links as new external links) for (size_t i = firstNew; i < base.nodes.size(); ++i) { for(TensorNetwork::Link &l : base.nodes[i].neighbors) { if (!l.external) { // Link inside the added network l.other += firstNew; } else { // External link l.indexPosition += firstNewExternal; } } } // Find traces (former contractions may have become traces due to the joining) link_traces_and_fix(std::move(_base)); _base.tensorObject->require_valid_network(); } void TensorNetwork::link_traces_and_fix(internal::IndexedTensorWritable<TensorNetwork>&& _base) { TensorNetwork &base = *_base.tensorObject; _base.assign_indices(); base.require_valid_network(); IF_CHECK( std::set<Index> contractedIndices; ) size_t passedDegree = 0; for(size_t i = 0; i < _base.indices.size(); ) { const Index& idx = _base.indices[i]; // Search for a second occurance size_t j = i+1; size_t passedDegreeSecond = passedDegree + idx.span; for( ; j < _base.indices.size(); passedDegreeSecond += _base.indices[j].span, ++j) { if(idx == _base.indices[j]) { break; } } if(j < _base.indices.size()) { // There is a second occurance. REQUIRE(!misc::contains(contractedIndices, idx), "Indices must occur at most twice per contraction"); REQUIRE(idx.span == _base.indices[j].span, "Index spans do not coincide " << idx << " vs " << _base.indices[j]); IF_CHECK( contractedIndices.insert(idx); ) for (size_t n = 0; n < idx.span; ++n) { const TensorNetwork::Link &link1 = base.externalLinks[passedDegree+n]; const TensorNetwork::Link &link2 = base.externalLinks[passedDegreeSecond+n]; REQUIRE(link1.dimension == link2.dimension, "Index dimensions do not coincide: ["<<n<<"] " << link1.dimension << " vs " << link2.dimension << " Indices are " << idx << " and " << _base.indices[j] << " from " << _base.indices); base.nodes[link1.other].neighbors[link1.indexPosition] = link2; base.nodes[link2.other].neighbors[link2.indexPosition] = link1; } // Remove external links and dimensions from network base.externalLinks.erase(base.externalLinks.begin()+long(passedDegreeSecond), base.externalLinks.begin()+long(passedDegreeSecond+idx.span)); // note that passedDegreeSecond > passedDegree base.externalLinks.erase(base.externalLinks.begin()+long(passedDegree), base.externalLinks.begin()+long(passedDegree+idx.span)); base.dimensions.erase(base.dimensions.begin()+long(passedDegreeSecond), base.dimensions.begin()+long(passedDegreeSecond+idx.span)); base.dimensions.erase(base.dimensions.begin()+long(passedDegree), base.dimensions.begin()+long(passedDegree+idx.span)); // Sanitize external links for(size_t k = passedDegree; k < passedDegreeSecond-idx.span; ++k) { base.nodes[base.externalLinks[k].other].neighbors[base.externalLinks[k].indexPosition].indexPosition -= idx.span; } for(size_t k = passedDegreeSecond-idx.span; k < base.externalLinks.size(); ++k) { base.nodes[base.externalLinks[k].other].neighbors[base.externalLinks[k].indexPosition].indexPosition -= 2*idx.span; } // Remove indices _base.indices.erase(_base.indices.begin()+j); _base.indices.erase(_base.indices.begin()+i); } else { passedDegree += idx.span; ++i; } } // Apply fixed indices passedDegree = 0; for(size_t i = 0; i < _base.indices.size(); ) { const Index& idx = _base.indices[i]; if(idx.fixed()) { // Fix the slates for(size_t k = passedDegree; k < passedDegree+idx.span; ++k) { base.fix_mode(passedDegree, idx.fixed_position()); } // Remove index _base.indices.erase(_base.indices.begin()+i); } else { passedDegree += idx.span; ++i; } } base.contract_unconnected_subnetworks(); } void TensorNetwork::round_edge(const size_t _nodeA, const size_t _nodeB, const size_t _maxRank, const double _eps, const double _softThreshold) { require_valid_network(); size_t fromPos, toPos; std::tie(fromPos, toPos) = find_common_edge(_nodeA, _nodeB); Tensor& fromTensor = *nodes[_nodeA].tensorObject; Tensor& toTensor = *nodes[_nodeB].tensorObject; const size_t fromDegree = fromTensor.degree(); const size_t toDegree = toTensor.degree(); const size_t currRank = fromTensor.dimensions[fromPos]; // Reshuffle From if nessecary const bool transFrom = (fromPos == 0); const bool reshuffleFrom = (!transFrom && fromPos != fromDegree-1); std::vector<size_t> forwardShuffleFrom; std::vector<size_t> backwardShuffleFrom; if(reshuffleFrom) { forwardShuffleFrom.resize(fromDegree); backwardShuffleFrom.resize(fromDegree); for(size_t i = 0; i < fromPos; ++i) { forwardShuffleFrom[i] = i; backwardShuffleFrom[i] = i; } for(size_t i = fromPos; i+1 < fromDegree; ++i) { forwardShuffleFrom[i+1] = i; backwardShuffleFrom[i] = i+1; } forwardShuffleFrom[fromPos] = fromDegree-1; backwardShuffleFrom[fromDegree-1] = fromPos; reshuffle(fromTensor, fromTensor, forwardShuffleFrom); } // Reshuffle To if nessecary const bool transTo = (toPos == toDegree-1); const bool reshuffleTo = (!transTo && toPos != 0); std::vector<size_t> forwardShuffleTo; std::vector<size_t> backwardShuffleTo; if(reshuffleTo) { forwardShuffleTo.resize(toDegree); backwardShuffleTo.resize(toDegree); for(size_t i = 0; i < toPos; ++i) { forwardShuffleTo[i] = i+1; backwardShuffleTo[i+1] = i; } for(size_t i = toPos+1; i < toDegree; ++i) { forwardShuffleTo[i] = i; backwardShuffleTo[i] = i; } forwardShuffleTo[toPos] = 0; backwardShuffleTo[0] = toPos; reshuffle(toTensor, toTensor, forwardShuffleTo); } Tensor X, S; // Check whether prior QR makes sense if (5*fromTensor.size*toTensor.size >= 6*misc::pow(currRank, 4) ) { // Seperate the cores ... Tensor coreA, coreB; if(transFrom) { calculate_cq(coreA, fromTensor, fromTensor, 1); } else { calculate_qc(fromTensor, coreA, fromTensor, fromDegree-1); } if(transTo) { calculate_qc(toTensor, coreB, toTensor, toDegree-1); } else { calculate_cq(coreB, toTensor, toTensor, 1); } // ... contract them ... xerus::contract(X, coreA, transFrom, coreB, transTo, 1); // ... calculate svd ... calculate_svd(coreA, S, coreB, X, 1, _maxRank, _eps); S.modify_diagonal_entries([&](value_t& _d){ _d = std::max(0.0, _d - _softThreshold); }); // ... contract S to the right ... xerus::contract(coreB, S, false, coreB, false, 1); // ... and contract the cores back to their origins. if(transFrom) { xerus::contract(fromTensor, coreA, true, fromTensor, false, 1); } else { xerus::contract(fromTensor, fromTensor, false, coreA, false, 1); } if(transTo) { xerus::contract(toTensor, toTensor, false, coreB, true, 1); } else { xerus::contract(toTensor, coreB, false, toTensor, false, 1); } } else { xerus::contract(X, fromTensor, transFrom, toTensor, transTo, 1); calculate_svd(fromTensor, S, toTensor, X, fromDegree-1, _maxRank, _eps); S.modify_diagonal_entries([&](value_t& _d){ _d = std::max(0.0, _d - _softThreshold); }); if(transTo) { xerus::contract(toTensor, toTensor, true, S, true, 1); } else { xerus::contract(toTensor, S, false, toTensor, false, 1); } if(transFrom) { backwardShuffleFrom.resize(fromDegree); for(size_t i = 0; i+1 < fromDegree; ++i) { backwardShuffleFrom[i] = i+1; } backwardShuffleFrom[fromDegree-1] = 0; reshuffle(fromTensor, fromTensor, backwardShuffleFrom); } } if(reshuffleFrom) { reshuffle(fromTensor, fromTensor, backwardShuffleFrom); } if(reshuffleTo) { reshuffle(toTensor, toTensor, backwardShuffleTo); } // Set the new dimension in the nodes nodes[_nodeA].neighbors[fromPos].dimension = nodes[_nodeA].tensorObject->dimensions[fromPos]; nodes[_nodeB].neighbors[toPos].dimension = nodes[_nodeB].tensorObject->dimensions[toPos]; } void TensorNetwork::transfer_core(const size_t _from, const size_t _to, const bool _allowRankReduction) { REQUIRE(_from < nodes.size() && _to < nodes.size(), " Illegal node IDs " << _from << "/" << _to << " as there are only " << nodes.size() << " nodes"); require_valid_network(); Tensor Q, R; size_t posA, posB; std::tie(posA, posB) = find_common_edge(_from, _to); Tensor& fromTensor = *nodes[_from].tensorObject; Tensor& toTensor = *nodes[_to].tensorObject; bool transR = false; if(posA == 0) { if(_allowRankReduction) { calculate_cq(R, Q, fromTensor, 1); } else { calculate_rq(R, Q, fromTensor, 1); } fromTensor = Q; transR = true; } else if(posA == nodes[_from].degree()-1) { if(_allowRankReduction) { calculate_qc(Q, R, fromTensor, nodes[_from].degree()-1); } else { calculate_qr(Q, R, fromTensor, nodes[_from].degree()-1); } fromTensor = Q; } else { std::vector<size_t> forwardShuffle(nodes[_from].degree()); std::vector<size_t> backwardShuffle(nodes[_from].degree()); for(size_t i = 0; i < posA; ++i) { forwardShuffle[i] = i; backwardShuffle[i] = i; } for(size_t i = posA; i+1 < nodes[_from].degree(); ++i) { forwardShuffle[i+1] = i; backwardShuffle[i] = i+1; } forwardShuffle[posA] = nodes[_from].degree()-1; backwardShuffle[nodes[_from].degree()-1] = posA; reshuffle(fromTensor, fromTensor, forwardShuffle); if(_allowRankReduction) { calculate_qc(Q, R, fromTensor, nodes[_from].degree()-1); } else { calculate_qr(Q, R, fromTensor, nodes[_from].degree()-1); } reshuffle(fromTensor, Q, backwardShuffle); } if( posB == 0 ) { xerus::contract(toTensor, R, transR, toTensor, false, 1); } else if( posB == nodes[_to].degree()-1 ) { xerus::contract(toTensor, toTensor, false, R, !transR, 1); } else { std::vector<size_t> forwardShuffle(nodes[_to].degree()); std::vector<size_t> backwardShuffle(nodes[_to].degree()); for(size_t i = 0; i < posB; ++i) { forwardShuffle[i] = i+1; backwardShuffle[i+1] = i; } for(size_t i = posB+1; i < nodes[_to].degree(); ++i) { forwardShuffle[i] = i; backwardShuffle[i] = i; } forwardShuffle[posB] = 0; backwardShuffle[0] = posB; reshuffle(toTensor, toTensor, forwardShuffle); xerus::contract(toTensor, R, posA == 0, toTensor, false, 1); reshuffle(toTensor, toTensor, backwardShuffle); } // Set the new dimension in the nodes nodes[_from].neighbors[posA].dimension = fromTensor.dimensions[posA]; nodes[_to].neighbors[posB].dimension = toTensor.dimensions[posB]; } void TensorNetwork::fix_mode(const size_t _mode, const size_t _slatePosition) { require_valid_network(); REQUIRE(_mode < degree(), "Invalid dimension to remove"); REQUIRE(_slatePosition < dimensions[_mode], "Invalide _slatePosition to choose"); const size_t extNode = externalLinks[_mode].other; const size_t extNodeIndexPos = externalLinks[_mode].indexPosition; // Correct the nodes external links for(size_t i = _mode+1; i < dimensions.size(); ++i) { REQUIRE(nodes[externalLinks[i].other].neighbors[externalLinks[i].indexPosition].indexPosition > 0, "Woo"); nodes[externalLinks[i].other].neighbors[externalLinks[i].indexPosition].indexPosition--; } externalLinks.erase(externalLinks.begin()+_mode); dimensions.erase(dimensions.begin()+_mode); // Correct the others links of the affected node. for(size_t i = extNodeIndexPos+1; i < nodes[extNode].neighbors.size(); ++i) { const Link& link = nodes[extNode].neighbors[i]; if(link.external) { externalLinks[link.indexPosition].indexPosition--; } else { // Check critical self links (i.e. where index position was allready modified). if(link.other == extNode && link.indexPosition+1 > extNodeIndexPos && link.indexPosition < i) { nodes[link.other].neighbors[link.indexPosition+1].indexPosition--; } else { nodes[link.other].neighbors[link.indexPosition].indexPosition--; } } } nodes[extNode].tensorObject->fix_mode(extNodeIndexPos, _slatePosition); nodes[extNode].neighbors.erase(nodes[extNode].neighbors.begin() + extNodeIndexPos); require_valid_network(); contract_unconnected_subnetworks(); } void TensorNetwork::remove_slate(const size_t _mode, const size_t _slatePosition) { require_valid_network(); REQUIRE(_mode < degree(), "invalid dimension to remove a slate from"); REQUIRE(_slatePosition < dimensions[_mode], "invalide slate position to choose"); REQUIRE(dimensions[_mode] > 0, "removing the last possible slate from this index position would result a dimension of size 0"); const size_t extNode = externalLinks[_mode].other; const size_t extNodeIndexPos = externalLinks[_mode].indexPosition; externalLinks[_mode].dimension -= 1; dimensions[_mode] -= 1; if (nodes[extNode].tensorObject) { nodes[extNode].tensorObject->remove_slate(extNodeIndexPos, _slatePosition); } nodes[extNode].neighbors[extNodeIndexPos].dimension -= 1; } void TensorNetwork::resize_mode(const size_t _mode, const size_t _newDim, const size_t _cutPos) { REQUIRE(_mode < degree(), "Invalid dimension given for resize_mode"); require_valid_network(); const size_t extNode = externalLinks[_mode].other; const size_t extNodeIndexPos = externalLinks[_mode].indexPosition; nodes[extNode].tensorObject->resize_mode(extNodeIndexPos, _newDim, _cutPos); nodes[extNode].neighbors[extNodeIndexPos].dimension = _newDim; externalLinks[_mode].dimension = _newDim; dimensions[_mode] = _newDim; require_valid_network(); } void TensorNetwork::reduce_representation() { require_valid_network(); TensorNetwork strippedNet = stripped_subnet(); std::vector<std::set<size_t>> contractions(strippedNet.nodes.size()); for (size_t id1=0; id1 < strippedNet.nodes.size(); ++id1) { TensorNode &currNode = strippedNet.nodes[id1]; if (currNode.erased) { continue; } for (Link &l : currNode.neighbors) { if (l.external) { continue; } size_t r=1; for (Link &l2 : currNode.neighbors) { if (l2.other == l.other) { r *= l2.dimension; } } if (r*r >= currNode.size() || r*r >= strippedNet.nodes[l.other].size()) { if (contractions[id1].empty()) { contractions[id1].insert(id1); } if (contractions[l.other].empty()) { contractions[id1].insert(l.other); } else { contractions[id1].insert(contractions[l.other].begin(), contractions[l.other].end()); contractions[l.other].clear(); } strippedNet.contract(id1, l.other); id1 -= 1; // check the same node again in the next iteration break; // for-each iterator is broken, so we have to break } } } // perform the collected contractions from above for (std::set<size_t> &ids : contractions) { if (ids.size() > 1) { contract(ids);<|fim▁hole|> } } sanitize(); require_valid_network(); } void TensorNetwork::contract(const size_t _nodeId1, const size_t _nodeId2) { TensorNode &node1 = nodes[_nodeId1]; TensorNode &node2 = nodes[_nodeId2]; REQUIRE(!node1.erased, "It appears node1 = " << _nodeId1 << " was already contracted?"); REQUIRE(!node2.erased, "It appears node2 = " << _nodeId2 << " was already contracted?"); INTERNAL_CHECK(externalLinks.size() == degree(), "Internal Error: " << externalLinks.size() << " != " << degree()); std::vector<TensorNetwork::Link> newLinks; newLinks.reserve(node1.degree() + node2.degree()); if (!node1.tensorObject) { INTERNAL_CHECK(!node2.tensorObject, "Internal Error."); // Determine the links of the resulting tensor (first half) for ( const Link& l : node1.neighbors ) { if (!l.links(_nodeId1) && !l.links(_nodeId2)) { newLinks.emplace_back(l); } } // Determine the links of the resulting tensor (second half) for ( const Link& l : node2.neighbors ) { if (!l.links(_nodeId2) && !l.links(_nodeId1)) { newLinks.emplace_back(l); } } } else { INTERNAL_CHECK(node2.tensorObject, "Internal Error."); size_t contractedDimCount = 0; bool separated1; bool separated2; bool matchingOrder; // first pass of the links of node1 to determine // 1. the number of links between the two nodes, // 2. determine whether node1 is separated (ownlinks-commonlinks) or transposed separated (commonlinks-ownlinks) // 3. determine the links of the resulting tensor (first half) if(node1.degree() > 1) { uint_fast8_t switches = 0; bool previous = node1.neighbors[0].links(_nodeId2); for (const Link& l : node1.neighbors) { if (l.links(_nodeId2)) { contractedDimCount++; if (!previous) { switches++; previous = true; } } else { newLinks.emplace_back(l); if (previous) { switches++; previous = false; } } } separated1 = (switches < 2); } else { if(!node1.neighbors.empty()) { if(node1.neighbors[0].links(_nodeId2)) { contractedDimCount = 1; } else { newLinks.emplace_back(node1.neighbors[0]); } } separated1 = true; } // first pass of the links of node2 to determine // 1. whether the order of common links is correct // 2. whether any self-links exist // 3. whether the second node is separated // 4. determine the links of the resulting tensor (second half) if(node2.degree() > 1 && contractedDimCount > 0) { bool previous = node2.neighbors[0].links(_nodeId1); uint_fast8_t switches = 0; size_t lastPosOfCommon = 0; matchingOrder = true; for (const Link& l : node2.neighbors) { if (l.links(_nodeId1)) { if (l.indexPosition < lastPosOfCommon) { matchingOrder = false; } lastPosOfCommon = l.indexPosition; if (!previous) { switches++; previous = true; } } else { newLinks.emplace_back(l); if (previous) { switches++; previous = false; } } } separated2 = (switches < 2); } else { if(contractedDimCount == 0) { newLinks.insert(newLinks.end(), node2.neighbors.begin(), node2.neighbors.end()); } separated2 = true; matchingOrder = true; } // Determine which (if any) node should be reshuffled // if order of common links does not match, reshuffle the smaller one if (!matchingOrder && separated1 && separated2) { if (node1.size() < node2.size()) { separated1 = false; } else { separated2 = false; } } // reshuffle first node if (!separated1) { std::vector<size_t> shuffle(node1.degree()); size_t pos = 0; for (size_t d = 0; d < node1.degree(); ++d) { if (!node1.neighbors[d].links(_nodeId2)) { shuffle[d] = pos++; } } for (const Link& l : node2.neighbors) { if (l.links(_nodeId1)) { shuffle[l.indexPosition] = pos++; } } INTERNAL_CHECK(pos == node1.degree(), "IE"); reshuffle(*node1.tensorObject, *node1.tensorObject, shuffle); matchingOrder = true; } // reshuffle second node if (!separated2) { std::vector<size_t> shuffle(node2.degree()); size_t pos = 0; if (matchingOrder) { // Add common links in order as they appear in node2 to avoid both nodes changing to the opposite link order for (size_t d = 0; d < node2.degree(); ++d) { if (node2.neighbors[d].links(_nodeId1)) { shuffle[d] = pos++; } } } else { for (const Link& l : node1.neighbors) { if (l.links(_nodeId2)) { shuffle[l.indexPosition] = pos++; } } } for (size_t d = 0; d < node2.degree(); ++d) { if (!node2.neighbors[d].links(_nodeId1)) { shuffle[d] = pos++; } } INTERNAL_CHECK(pos == node2.degree(), "IE"); reshuffle(*node2.tensorObject, *node2.tensorObject, shuffle); } const bool trans1 = separated1 && !node1.neighbors.empty() && node1.neighbors[0].links(_nodeId2); const bool trans2 = separated2 &&!node2.neighbors.empty() &&!(node2.neighbors[0].links(_nodeId1)); xerus::contract(*node1.tensorObject, *node1.tensorObject, trans1, *node2.tensorObject, trans2, contractedDimCount); } // Set Nodes nodes[_nodeId1].neighbors = std::move(newLinks); nodes[_nodeId2].erase(); // Fix indices of other nodes // note that the indices that were previously part of node1 might also have changed for (size_t d = 0; d < nodes[_nodeId1].neighbors.size(); ++d) { const Link& l = nodes[_nodeId1].neighbors[d]; if (l.external) { externalLinks[l.indexPosition].other = _nodeId1; externalLinks[l.indexPosition].indexPosition = d; } else { nodes[l.other].neighbors[l.indexPosition].other = _nodeId1; nodes[l.other].neighbors[l.indexPosition].indexPosition = d; } } require_valid_network(false); } double TensorNetwork::contraction_cost(const size_t _nodeId1, const size_t _nodeId2) const { REQUIRE(!nodes[_nodeId1].erased, "It appears node1 = " << _nodeId1 << " was already contracted?"); REQUIRE(!nodes[_nodeId2].erased, "It appears node2 = " << _nodeId2 << " was already contracted?"); if (_nodeId1 == _nodeId2) { return static_cast<double>(nodes[_nodeId1].size()); // Costs of a trace } //TODO add correct calculation for sparse matrices // Assume cost of mxr * rxn = m*n*r (which is a rough approximation of the actual cost for openBlas/Atlas) size_t cost = nodes[_nodeId1].size(); for(const Link& neighbor : nodes[_nodeId2].neighbors) { if(!neighbor.links(_nodeId1)) { cost *= neighbor.dimension; } } return static_cast<double>(cost); } size_t TensorNetwork::contract(const std::set<size_t>& _ids) { // Trace out all single-node traces for ( const size_t id : _ids ) { perform_traces(id); } if (_ids.empty()) { return ~0ul; } if (_ids.size() == 1) { return *_ids.begin(); } if (_ids.size() == 2) { auto secItr = _ids.begin(); ++secItr; contract(*_ids.begin(), *secItr); return *_ids.begin(); } if (_ids.size() == 3) { auto idItr = _ids.begin(); const size_t a = *idItr; TensorNode &na = nodes[a]; ++idItr; const size_t b = *idItr; TensorNode &nb = nodes[b]; ++idItr; const size_t c = *idItr; TensorNode &nc = nodes[c]; double sa = 1, sb = 1, sc = 1; // sizes devided by the link dimensions between a,b,c double sab = 1, sbc = 1, sac = 1; // link dimensions for (size_t d = 0; d < na.degree(); ++d) { if (na.neighbors[d].links(b)) { sab *= static_cast<double>(na.neighbors[d].dimension); } else if (na.neighbors[d].links(c)) { sac *= static_cast<double>(na.neighbors[d].dimension); } else { sa *= static_cast<double>(na.neighbors[d].dimension); } } for (size_t d = 0; d < nb.degree(); ++d) { if (nb.neighbors[d].links(c)) { sbc *= static_cast<double>(nb.neighbors[d].dimension); } else if (!nb.neighbors[d].links(a)) { sb *= static_cast<double>(nb.neighbors[d].dimension); } } for (size_t d = 0; d < nc.degree(); ++d) { if (!nc.neighbors[d].links(a) && !nc.neighbors[d].links(b)) { sc *= static_cast<double>(nc.neighbors[d].dimension); } } // cost of contraction a-b first etc. double costAB = sa*sb*sac*sbc*(sab+sc); // (sa*sac)*sab*(sb*sbc) + sa*sb*sac*sbc*sc; double costAC = sa*sc*sab*sbc*(sac+sb); double costBC = sb*sc*sab*sac*(sbc+sa); if (costAB < costAC && costAB < costBC) { LOG(TNContract, "contraction of ab first " << sa << " " << sb << " " << sc << " " << sab << " " << sbc << " " << sac); contract(a, b); contract(a, c); } else if (costAC < costBC) { LOG(TNContract, "contraction of ac first " << sa << " " << sb << " " << sc << " " << sab << " " << sbc << " " << sac); contract(a, c); contract(a, b); } else { LOG(TNContract, "contraction of bc first " << sa << " " << sb << " " << sc << " " << sab << " " << sbc << " " << sac); contract(b, c); contract(a, b); } return a; } TensorNetwork strippedNetwork = stripped_subnet([&](size_t _id){ return misc::contains(_ids, _id); }); double bestCost = std::numeric_limits<double>::max(); std::vector<std::pair<size_t, size_t>> bestOrder; // Ask the heuristics for (const internal::ContractionHeuristic &c : internal::contractionHeuristics) { c(bestCost, bestOrder, strippedNetwork); } INTERNAL_CHECK(bestCost < std::numeric_limits<double>::max() && !bestOrder.empty(), "Internal Error."); for (const std::pair<size_t,size_t> &c : bestOrder) { contract(c.first, c.second); } // Note: no sanitization as eg. TTStacks require the indices not to change after calling this function return bestOrder.back().first; } value_t TensorNetwork::frob_norm() const { const Index i; Tensor res; res() = (*this)(i&0) * (*this)(i&0); return std::sqrt(res[0]); } void TensorNetwork::draw(const std::string& _filename) const { std::stringstream graphLayout; graphLayout << "graph G {" << std::endl; graphLayout << "graph [mclimit=1000, maxiter=1000, overlap = false, splines = true]" << std::endl; for(size_t i = 0; i < nodes.size(); ++i) { // Create the Nodes if(nodes[i].erased) { graphLayout << "\tN"<<i<<" [label=\"N"<<i<<"\", shape=circle, fixedsize=shape, height=0.45];" << std::endl; } else { graphLayout << "\tN"<<i<<" [label=\""; for(size_t k=0; k+1 < nodes[i].degree(); ++k) { if(nodes[i].degree()/2 == k) { if(nodes[i].degree()%2 == 0) { graphLayout << "<i"<<k<<"> "<<i<<"| "; } else { graphLayout << "<i"<<k<<"> N"<<i<<"| "; } } else if(nodes[i].degree()%2 == 0 && nodes[i].degree()/2 == k+1) { graphLayout << "<i"<<k<<"> N| "; } else { graphLayout << "<i"<<k<<"> | "; } } if(nodes[i].degree() <= 2) { graphLayout << "<i"<<nodes[i].degree()-1<<"> N"<<i<<"\", shape=record, fixedsize=shape, height=0.45, style=\"rounded,filled\"];" << std::endl; } else { graphLayout << "<i"<<nodes[i].degree()-1<<">\", shape=record, fixedsize=shape, height=0.45, style=\"rounded,filled\"];" << std::endl; } // Add all links to nodes with smaller index and externals for(size_t j = 0; j < nodes[i].neighbors.size(); ++j) { if(nodes[i].neighbors[j].external) { graphLayout << "\t"<<nodes[i].neighbors[j].indexPosition<<" [shape=diamond, fixedsize=shape, height=0.38, width=0.38, style=filled];" << std::endl; graphLayout << "\tN"<<i<<":i"<<j<<" -- " << nodes[i].neighbors[j].indexPosition << " [len=1, label=\""<<nodes[i].neighbors[j].dimension<<"\"];" << std::endl; } else if(nodes[i].neighbors[j].other < i) { graphLayout << "\tN"<<i<<":i"<<j<<" -- " << "N"<<nodes[i].neighbors[j].other << ":i"<< nodes[i].neighbors[j].indexPosition<<" [label=\""<<nodes[i].neighbors[j].dimension<<"\"];" << std::endl; } } } } graphLayout << "}" << std::endl; misc::exec(std::string("dot -Tsvg > ") + _filename+".svg", graphLayout.str()); } TensorNetwork operator*(TensorNetwork &_lhs, value_t _factor) { TensorNetwork res(*_lhs.get_copy()); res *= _factor; return res; } TensorNetwork operator*(value_t _factor, TensorNetwork &_rhs) { TensorNetwork res(*_rhs.get_copy()); res *= _factor; return res; } TensorNetwork operator/(TensorNetwork &_lhs, value_t _factor) { TensorNetwork res(*_lhs.get_copy()); res *= 1.0/_factor; return res; } bool approx_equal(const TensorNetwork& _a, const TensorNetwork& _b, const value_t _eps) { REQUIRE(_a.dimensions == _b.dimensions, "The dimensions of the compared tensors don't match: " << _a.dimensions <<" vs. " << _b.dimensions); const Index i; // TODO no indices return frob_norm(_a(i&0) - _b(i&0)) <= _eps*(_a.frob_norm() + _b.frob_norm())/2.0; } bool approx_equal(const TensorNetwork& _a, const Tensor& _b, const value_t _eps) { return approx_equal(Tensor(_a), _b, _eps); } bool approx_equal(const Tensor& _a, const TensorNetwork& _b, const value_t _eps) { return approx_equal(_a, Tensor(_b), _eps); } namespace misc { void stream_writer(std::ostream &_stream, const TensorNetwork &_obj, const FileFormat _format) { if(_format == FileFormat::TSV) { _stream << std::setprecision(std::numeric_limits<value_t>::digits10 + 1); } // storage version number write_to_stream<size_t>(_stream, 1, _format); // Save dimensions write_to_stream(_stream, _obj.dimensions, _format); if(_format == FileFormat::TSV) { _stream << '\n'; } // save external links for(const TensorNetwork::Link& el : _obj.externalLinks) { write_to_stream<size_t>(_stream, el.other, _format); write_to_stream<size_t>(_stream, el.indexPosition, _format); write_to_stream<size_t>(_stream, el.dimension, _format); } if(_format == FileFormat::TSV) { _stream << "\n\n"; } // Save nodes with their links write_to_stream<size_t>(_stream, _obj.nodes.size(), _format); if(_format == FileFormat::TSV) { _stream << '\n'; } for(const TensorNetwork::TensorNode& node : _obj.nodes) { write_to_stream<size_t>(_stream, node.neighbors.size(), _format); for(const TensorNetwork::Link& link : node.neighbors) { write_to_stream<bool>(_stream, link.external, _format); write_to_stream<size_t>(_stream, link.other, _format); write_to_stream<size_t>(_stream, link.indexPosition, _format); write_to_stream<size_t>(_stream, link.dimension, _format); } } if(_format == FileFormat::TSV) { _stream << '\n'; } // Save tensorObjects for(const TensorNetwork::TensorNode& node : _obj.nodes) { write_to_stream(_stream, *node.tensorObject, _format); if(_format == FileFormat::TSV) { _stream << '\n'; } } } void stream_reader(std::istream& _stream, TensorNetwork &_obj, const FileFormat _format) { IF_CHECK( size_t ver = ) read_from_stream<size_t>(_stream, _format); REQUIRE(ver == 1, "Unknown stream version to open (" << ver << ")"); // Load dimensions read_from_stream(_stream, _obj.dimensions, _format); // load external links _obj.externalLinks.resize(_obj.dimensions.size()); for(TensorNetwork::Link& el : _obj.externalLinks) { el.external = false; el.other = read_from_stream<size_t>(_stream, _format); el.indexPosition = read_from_stream<size_t>(_stream, _format); el.dimension = read_from_stream<size_t>(_stream, _format); } // Load nodes with their links _obj.nodes.resize(read_from_stream<size_t>(_stream, _format)); for(TensorNetwork::TensorNode& node : _obj.nodes) { node.neighbors.resize(read_from_stream<size_t>(_stream, _format)); node.erased = false; for(TensorNetwork::Link& link : node.neighbors) { link.external = read_from_stream<bool>(_stream, _format); link.other = read_from_stream<size_t>(_stream, _format); link.indexPosition = read_from_stream<size_t>(_stream, _format); link.dimension = read_from_stream<size_t>(_stream, _format); } } // load tensorObjects for(TensorNetwork::TensorNode& node : _obj.nodes) { node.tensorObject.reset(new Tensor()); read_from_stream<Tensor>(_stream, *node.tensorObject, _format); } _obj.require_valid_network(); } } // namespace misc } // namespace xerus<|fim▁end|>
<|file_name|>__openerp__.py<|end_file_name|><|fim▁begin|>{ "name" : "GII", "version" : "1.0", "depends" : ['sale','product'], <|fim▁hole|> """, 'website': 'http://www.novasoftindia.com', 'data': ['giisa.xml', ], 'demo': [], 'installable': True, 'auto_install': False, 'application': True, }<|fim▁end|>
"author" : "Novasoft Consultancy Services Pvt. Ltd.", 'category' : 'Generic Modules/Others', "description": """ GII - Management Module
<|file_name|>hardware.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2 # -*- coding: utf-8 -*- # # The Qubes OS Project, http://www.qubes-os.org # # Copyright (C) 2016 Marek Marczykowski-Górecki # <[email protected]> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, see <https://www.gnu.org/licenses/>. # # import os import qubes.tests import time import subprocess from unittest import expectedFailure class TC_00_HVM(qubes.tests.SystemTestsMixin, qubes.tests.QubesTestCase): def setUp(self): super(TC_00_HVM, self).setUp() self.vm = self.qc.add_new_vm("QubesHVm", name=self.make_vm_name('vm1')) self.vm.create_on_disk(verbose=False) @expectedFailure def test_000_pci_passthrough_presence(self): pcidev = os.environ.get('QUBES_TEST_PCIDEV', None) if pcidev is None: self.skipTest('Specify PCI device with QUBES_TEST_PCIDEV ' 'environment variable') self.vm.pcidevs = [pcidev] self.vm.pci_strictreset = False<|fim▁hole|> init_script = ( "#!/bin/sh\n" "set -e\n" "lspci -n > /dev/xvdb\n" "poweroff\n" ) self.prepare_hvm_system_linux(self.vm, init_script, ['/usr/sbin/lspci']) self.vm.start() timeout = 60 while timeout > 0: if not self.vm.is_running(): break time.sleep(1) timeout -= 1 if self.vm.is_running(): self.fail("Timeout while waiting for VM shutdown") with open(self.vm.storage.private_img, 'r') as f: lspci_vm = f.read(512).strip('\0') p = subprocess.Popen(['lspci', '-ns', pcidev], stdout=subprocess.PIPE) (lspci_host, _) = p.communicate() # strip BDF, as it is different in VM pcidev_desc = ' '.join(lspci_host.strip().split(' ')[1:]) self.assertIn(pcidev_desc, lspci_vm)<|fim▁end|>
self.qc.save() self.qc.unlock_db()
<|file_name|>RenderLoom.java<|end_file_name|><|fim▁begin|>package com.bioxx.tfc.Render.Blocks; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.world.IBlockAccess; import org.lwjgl.opengl.GL11; import com.bioxx.tfc.TileEntities.TELoom; import com.bioxx.tfc.api.TFCBlocks; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; public class RenderLoom implements ISimpleBlockRenderingHandler { static float minX = 0F; static float maxX = 1F; static float minY = 0F; static float maxY = 1F; static float minZ = 0F; static float maxZ = 1F; @Override public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { TELoom te = (TELoom) world.getTileEntity(x, y, z); Block materialBlock; if(te.loomType < 16) { materialBlock = TFCBlocks.WoodSupportH; } else { materialBlock = TFCBlocks.WoodSupportH2; } renderer.renderAllFaces = true; GL11.glPushMatrix(); //Arms this.setRotatedRenderBounds(renderer, te.rotation, minX+0.1F, minY, minZ+0.75F, maxX-0.8F, maxY, maxZ-0.15F); renderer.renderStandardBlock(materialBlock, x, y, z); <|fim▁hole|> //Arm holding sections //L this.setRotatedRenderBounds(renderer, te.rotation, minX+0.1F, minY+0.25F, minZ+0.5F, maxX-0.8F, maxY-0.7F, maxZ-0.25F); renderer.renderStandardBlock(materialBlock, x, y, z); this.setRotatedRenderBounds(renderer, te.rotation, minX+0.1F, minY+0.05F, minZ+0.5F, maxX-0.8F, maxY-0.9F, maxZ-0.25F); renderer.renderStandardBlock(materialBlock, x, y, z); //R this.setRotatedRenderBounds(renderer, te.rotation, minX+0.8F, minY+0.25F, minZ+0.5F, maxX-0.1F, maxY-0.7F, maxZ-0.25F); renderer.renderStandardBlock(materialBlock, x, y, z); this.setRotatedRenderBounds(renderer, te.rotation, minX+0.8F, minY+0.05F, minZ+0.5F, maxX-0.1F, maxY-0.9F, maxZ-0.25F); renderer.renderStandardBlock(materialBlock, x, y, z); //cross this.setRotatedRenderBounds(renderer, te.rotation, maxX-0.8F, minY+0.8F, minZ+0.75F, minX+0.8F, maxY-0.1F, maxZ-0.15F); renderer.renderStandardBlock(materialBlock, x, y, z); this.setRotatedRenderBounds(renderer, te.rotation, maxX-0.8F, 0F, minZ+0.75F, minX+0.8F, minY+0.1F, maxZ-0.15F); renderer.renderStandardBlock(materialBlock, x, y, z); rotate(renderer, 0); renderer.renderAllFaces = false; GL11.glPopMatrix(); return true; } public void rotate(RenderBlocks renderer, int i) { renderer.uvRotateEast = i; renderer.uvRotateWest = i; renderer.uvRotateNorth = i; renderer.uvRotateSouth = i; } private void setRotatedRenderBounds(RenderBlocks renderer, byte rotation , float x, float y, float z, float X, float Y, float Z){ switch(rotation){ case 0: renderer.setRenderBounds(x,y,z,X,Y,Z); break; case 1: renderer.setRenderBounds(maxZ-Z,y,x,maxZ-z,Y,X); break; case 2: renderer.setRenderBounds(x,y,maxZ-Z,X,Y,maxZ-z); break; case 3: renderer.setRenderBounds(z,y,x,Z,Y,X); break; default: break; } } @Override public void renderInventoryBlock(Block block, int meta, int modelID, RenderBlocks renderer) { Block materialBlock; if(meta < 16) { materialBlock = TFCBlocks.WoodSupportH; } else { materialBlock = TFCBlocks.WoodSupportH2; } GL11.glPushMatrix(); GL11.glRotatef(180, 0, 1, 0); //Arms renderer.setRenderBounds(minX+0.1F, minY, minZ+0.75F, maxX-0.8F, maxY, maxZ-0.15F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); renderer.setRenderBounds(minX+0.8F, minY, minZ+0.75F, maxX-0.1F, maxY, maxZ-0.15F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); //Arm holding sections //L renderer.setRenderBounds(minX+0.1F, minY+0.35F, minZ+0.6F, maxX-0.8F, maxY-0.6F, maxZ-0.25F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); renderer.setRenderBounds(minX+0.1F, minY+0.15F, minZ+0.6F, maxX-0.8F, maxY-0.8F, maxZ-0.25F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); //R renderer.setRenderBounds(minX+0.8F, minY+0.35F, minZ+0.6F, maxX-0.1F, maxY-0.6F, maxZ-0.25F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); renderer.setRenderBounds(minX+0.8F, minY+0.15F, minZ+0.6F, maxX-0.1F, maxY-0.8F, maxZ-0.25F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); //cross renderer.setRenderBounds(maxX-0.8F, minY+0.8F, minZ+0.75F, minX+0.8F, maxY-0.1F, maxZ-0.15F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); renderer.setRenderBounds(maxX-0.8F, 0F, minZ+0.75F, minX+0.8F, minY+0.1F, maxZ-0.15F); rotate(renderer, 1); renderInvBlock(materialBlock, meta, renderer); rotate(renderer, 0); GL11.glPopMatrix(); } @Override public boolean shouldRender3DInInventory(int modelId) { return true; } @Override public int getRenderId() { return 0; } public static void renderInvBlock(Block block, int m, RenderBlocks renderer) { Tessellator var14 = Tessellator.instance; GL11.glTranslatef(-0.5F, -0.5F, -0.5F); var14.startDrawingQuads(); var14.setNormal(0.0F, -1.0F, 0.0F); renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(0, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(0.0F, 1.0F, 0.0F); renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(1, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(0.0F, 0.0F, -1.0F); renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(2, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(0.0F, 0.0F, 1.0F); renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(3, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(-1.0F, 0.0F, 0.0F); renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(4, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(1.0F, 0.0F, 0.0F); renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(5, m)); var14.draw(); GL11.glTranslatef(0.5F, 0.5F, 0.5F); } public static void renderInvBlockHoop(Block block, int m, RenderBlocks renderer) { Tessellator var14 = Tessellator.instance; GL11.glTranslatef(-0.5F, -0.5F, -0.5F); var14.startDrawingQuads(); var14.setNormal(0.0F, -1.0F, 0.0F); renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(10, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(0.0F, 1.0F, 0.0F); renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(11, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(0.0F, 0.0F, -1.0F); renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(12, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(0.0F, 0.0F, 1.0F); renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(13, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(-1.0F, 0.0F, 0.0F); renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(14, m)); var14.draw(); var14.startDrawingQuads(); var14.setNormal(1.0F, 0.0F, 0.0F); renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(15, m)); var14.draw(); GL11.glTranslatef(0.5F, 0.5F, 0.5F); } }<|fim▁end|>
this.setRotatedRenderBounds(renderer, te.rotation, minX+0.8F, minY, minZ+0.75F, maxX-0.1F, maxY, maxZ-0.15F); renderer.renderStandardBlock(materialBlock, x, y, z);
<|file_name|>RouteAdder.java<|end_file_name|><|fim▁begin|>package org.dfhu.thpwa.routing; abstract class RouteAdder<T extends Route> { /** * Get the url pattern for this route */ protected abstract String getPath(); /** * get the HTTP request method<|fim▁hole|> */ protected abstract Route.METHOD getMethod(); public void doGet(RouteAdder<T> routeAdder) { Halting.haltNotImplemented(); } public void doPost(RouteAdder<T> routeAdder) { Halting.haltNotImplemented(); } public void addRoute() { Route.METHOD method = getMethod(); switch (method) { case GET: doGet(this); break; case POST: doPost(this); break; default: throw new RuntimeException("Request Method not implemented"); } } }<|fim▁end|>
<|file_name|>gradienteditor.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- import gtk from objects.gradientcolor import GradientColor from objects.gradient import Gradient from interfaces.signalizable import Signalizable class GradientLine(gtk.Viewport): def __init__(self, moving_callback=None, color_callback=None, gradient=None): """ moving_callback - callback function to be called when changing position of the selected color(for spin widget) gradient - editable gradient """ gtk.Viewport.__init__(self) self.set_size_request(-1, 70) self.set_shadow_type(gtk.SHADOW_NONE) self.width = 0 self.height = 0 self._motion = False self.selected = -1 self.x = 0 self.move = False self.gradient = gradient self.gradient.change_size(0, 0, 1, 0) self.moving_callback = moving_callback self.color_callback = color_callback self.layout = gtk.Layout() self.add(self.layout) self.layout.set_events(0) self.layout.add_events(gtk.gdk.BUTTON_PRESS_MASK) self.layout.connect("button-press-event", self.press) self.layout.add_events(gtk.gdk.EXPOSURE_MASK) self.layout.connect("expose-event", self.expose) self.layout.add_events(gtk.gdk.BUTTON_RELEASE_MASK) self.layout.connect("button-release-event", self.release) self.layout.add_events(gtk.gdk.POINTER_MOTION_MASK) self.layout.connect("motion-notify-event", self.motion) self.layout.add_events(gtk.gdk.ENTER_NOTIFY_MASK) self.layout.connect("enter-notify-event", self.enter) self.layout.add_events(gtk.gdk.LEAVE_NOTIFY_MASK) self.layout.connect("leave-notify-event", self.leave) def update(self): self.queue_draw() def set_position_for_selected(self, x): self.gradient.set_position(self.selected, x) def set_color_for_selected(self, color): color.position = self.gradient.colors[self.selected].position self.gradient.set_color(self.selected, color) def motion(self, widget, event): self._motion = True self.x = event.x if self.move: if self.selected >= 0: if self.moving_callback: self.moving_callback(event.x / self.width) self.set_position_for_selected(event.x / self.width) self.gradient.update() self.queue_draw() return True def enter(self, widget, event): return True def leave(self, widget, event): self._motion = False self.x = event.x self.queue_draw() return True def press(self, widget, event): self.move = True cnt = len(self.gradient.colors) if cnt > 0: for col in range(0, cnt): if (self.gradient.colors[col].position > (event.x / self.width - 0.01)) and ( self.gradient.colors[col].position < (event.x / self.width + 0.01)): self.selected = col self.moving_callback(self.gradient.colors[col].position) self.color_callback(self.gradient.colors[col]) break else: self.selected = -1 if self.selected == -1 or not cnt: self.gradient.add_new_color(GradientColor(1, 1, 0.1, 1.0, event.x / self.width)) self.selected = len(self.gradient.colors)-1 self.moving_callback(self.gradient.colors[self.selected].position) self.color_callback(self.gradient.colors[self.selected]) self.gradient.update() self.queue_draw() def release(self, widget, event): self.move = False self.queue_draw() def expose(self, widget, event): context = widget.bin_window.cairo_create() self.width, self.height = widget.window.get_size() context.save() context.new_path() #context.translate(0, 0) if (self.width > 0) and (self.height > 0): context.scale(self.width, self.height) context.rectangle(0, 0, 1, 1) context.set_source(self.gradient.gradient) context.fill_preserve() context.restore() if self._motion and not self.move: context.new_path() dash = list() context.set_dash(dash) context.set_line_width(2) context.move_to(self.x, 0) context.line_to(self.x, 30) context.move_to(self.x, self.height - 30) context.line_to(self.x, self.height) scol = sorted(self.gradient.colors, key=lambda color: color.position) # better in __init__ and update when necessary cnt = len(scol) rx = self.x / self.width index = 0 for col in scol: if rx < col.position: for c in range(0, cnt): if self.gradient.colors[c].position == col.position: index = c break break r = self.gradient.colors[index].red g = self.gradient.colors[index].green b = self.gradient.colors[index].blue l = 1 - (r + g + b) / 3.0 if l >= 0.5: l = 1 else: l = 0 r, g, b = l, l, l context.set_source_rgba(r, g, b, 1.0) context.stroke() for color in range(len(self.gradient.colors)): if color == self.selected: delta = 10 else: delta = 0 context.new_path() pos = int(self.width * self.gradient.colors[color].position) context.move_to(pos - 5, 0) context.line_to(pos + 5, 0) context.line_to(pos, 20) context.line_to(pos - 5, 0) context.set_source_rgb(self.gradient.colors[color].alpha, self.gradient.colors[color].alpha, self.gradient.colors[color].alpha) context.fill_preserve() if delta: context.move_to(pos, 20) context.line_to(pos, 20 + delta) context.set_source_rgb(0.44, 0.62, 0.81) context.stroke() class LinearGradientEditor(gtk.VBox, Signalizable): def __init__(self): gtk.VBox.__init__(self) from canvas import Canvas<|fim▁hole|> table = gtk.Table(4, 4, False) self.pack_start(table) self.combobox = gtk.combo_box_new_text() table.attach(self.combobox, 1, 2, 0, 1, gtk.FILL, 0) gradient = Gradient() self.gl = GradientLine(self.moving_callback, self.color_callback, gradient) table.attach(self.gl, 1, 2, 1, 2, gtk.FILL | gtk.EXPAND, 0) new_color = gtk.Button() image = gtk.Image() image.set_from_stock(gtk.STOCK_NEW, gtk.ICON_SIZE_MENU) new_color.add(image) table.attach(new_color, 2, 3, 0, 1, 0, 0, 0) button = gtk.Button() image = gtk.Image() image.set_from_stock(gtk.STOCK_GO_FORWARD, gtk.ICON_SIZE_MENU) button.add(image) button.connect("clicked", self.forward) table.attach(button, 2, 3, 1, 2, 0, gtk.FILL, 0) button = gtk.Button() image = gtk.Image() image.set_from_stock(gtk.STOCK_GO_BACK, gtk.ICON_SIZE_MENU) button.add(image) button.connect("clicked", self.back) table.attach(button, 0, 1, 1, 2, 0, gtk.FILL, 0) hbox = gtk.HBox() label = gtk.Label(_("Color:")) hbox.pack_start(label) self.color_button = gtk.ColorButton() self.color_button.set_use_alpha(True) self.color_button.connect("color-set", self.set_gradient_color) hbox.pack_start(self.color_button) label = gtk.Label(_("Position:")) hbox.pack_start(label) self.sel_position = gtk.SpinButton(climb_rate=0.00001, digits=5) self.sel_position.set_range(0.0, 1.0) self.sel_position.set_wrap(True) self.sel_position.set_increments(0.00001, 0.1) self.sel_position.connect("value-changed", self.move_color) hbox.pack_start(self.sel_position) table.attach(hbox, 1, 2, 2, 3, gtk.FILL, 0, 0) self.install_signal("update") self.show_all() def set_value(self, value): self.gl.gradient = Gradient(string=str(value)) def forward(self, widget): if self.gl: if self.gl.selected < len(self.gl.gradient.colors) - 1: self.gl.selected += 1 else: self.gl.selected = -1 self.moving_callback(self.gl.gradient.colors[self.gl.selected].position) self.update() def back(self, widget): if self.gl: if self.gl.selected > -1: self.gl.selected -= 1 else: self.gl.selected = len(self.gl.gradient.colors) - 1 self.moving_callback(self.gl.gradient.colors[self.gl.selected].position) self.update() def moving_callback(self, x): self.sel_position.set_value(x) self.update() def color_callback(self, color): self.color_button.set_color(gtk.gdk.Color(float(color.red), float(color.green), float(color.blue))) self.color_button.set_alpha(int(color.alpha * 65535)) self.update() def move_color(self, widget): if self.gl: self.gl.set_position_for_selected(widget.get_value()) self.update() def set_gradient_color(self, widget): if self.gl: col = GradientColor(widget.get_color().red_float, widget.get_color().green_float, widget.get_color().blue_float, widget.get_alpha() / 65535.0,0) self.gl.set_color_for_selected(col) self.update() def update(self): self.gl.update() self.emit("update", self) #self.canvas.update() if __name__ == '__main__': horizontal_window = gtk.Window() horizontal_window.set_default_size(500, 100) horizontal_window.connect("delete-event", gtk.main_quit) ge = LinearGradientEditor() horizontal_window.add(ge) horizontal_window.show_all() gtk.main()<|fim▁end|>
self.canvas = Canvas()
<|file_name|>tt_postscript.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2015, Michael Droettboom All rights reserved. <|fim▁hole|># 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # The views and conclusions contained in the software and # documentation are those of the authors and should not be interpreted # as representing official policies, either expressed or implied, of # the FreeBSD Project. from __future__ import print_function, unicode_literals, absolute_import TT_Postscript__init__ = """ A TrueType PostScript table. """ TT_Postscript_format_type = """ Format of this table. """ TT_Postscript_italic_angle = """ Italic angle in degrees. """ TT_Postscript_underline_position = """ Underline position. """ TT_Postscript_underline_thickness = """ Underline thickness. """ TT_Postscript_is_fixed_pitch = """ If `True`, the font is monospaced. """ TT_Postscript_min_mem_type42 = """ Minimum memory usage when the font is downloaded as a Type 42 font. """ TT_Postscript_max_mem_type42 = """ Maximum memory usage when the font is downloaded as a Type 42 font. """ TT_Postscript_min_mem_type1 = """ Minimum memory usage when the font is downloaded as a Type 1 font. """ TT_Postscript_max_mem_type1 = """ Maximum memory usage when the font is downloaded as a Type 1 font. """<|fim▁end|>
# Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met:
<|file_name|>bitcoin_es.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="es" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About TakeiCoin</source> <translation>Acerca de TakeiCoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;TakeiCoin&lt;/b&gt; version</source> <translation>Versión de &lt;b&gt;TakeiCoin&lt;/b&gt;</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> Este es un software experimental. Distribuido bajo la licencia MIT/X11, vea el archivo adjunto COPYING o http://www.opensource.org/licenses/mit-license.php. Este producto incluye software desarrollado por OpenSSL Project para su uso en el OpenSSL Toolkit (http://www.openssl.org/) y software criptográfico escrito por Eric Young ([email protected]) y el software UPnP escrito por Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <location line="+0"/> <source>The TakeiCoin developers</source> <translation>Los programadores TakeiCoin</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Libreta de direcciones</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Haga doble clic para editar una dirección o etiqueta</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Crear una nueva dirección</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copiar la dirección seleccionada al portapapeles del sistema</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Añadir dirección</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your TakeiCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Estas son sus direcciones TakeiCoin para recibir pagos. Puede utilizar una diferente por cada persona emisora para saber quién le está pagando.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Copiar dirección</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Mostrar código &amp;QR </translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a TakeiCoin address</source> <translation>Firmar un mensaje para demostrar que se posee una dirección TakeiCoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Firmar mensaje</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Borrar de la lista la dirección seleccionada</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Exportar a un archivo los datos de esta pestaña</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified TakeiCoin address</source> <translation>Verificar un mensaje para comprobar que fue firmado con la dirección TakeiCoin indicada</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verificar mensaje</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Eliminar</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your TakeiCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Estas son sus direcciones TakeiCoin para enviar pagos. Compruebe siempre la cantidad y la dirección receptora antes de transferir monedas.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Copiar &amp;etiqueta</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Editar</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Enviar &amp;monedas</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Exportar datos de la libreta de direcciones</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Archivos de columnas separadas por coma (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Error al exportar</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>No se pudo escribir en el archivo %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Dirección</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Diálogo de contraseña</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Introducir contraseña</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nueva contraseña</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Repita la nueva contraseña</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Introduzca la nueva contraseña del monedero.&lt;br/&gt;Por favor elija una con &lt;b&gt;10 o más caracteres aleatorios&lt;/b&gt; u &lt;b&gt;ocho o más palabras&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Cifrar el monedero</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Esta operación requiere su contraseña para desbloquear el monedero.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Desbloquear monedero</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Esta operación requiere su contraseña para descifrar el monedero.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Descifrar el monedero</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Cambiar contraseña</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Introduzca la contraseña anterior del monedero y la nueva. </translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Confirmar cifrado del monedero</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR TAKEICOINS&lt;/b&gt;!</source> <translation>Atencion: ¡Si cifra su monedero y pierde la contraseña perderá &lt;b&gt;TODOS SUS TAKEICOINS&lt;/b&gt;!&quot;</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>¿Seguro que desea cifrar su monedero?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>IMPORTANTE: Cualquier copia de seguridad que haya realizado previamente de su archivo de monedero debe reemplazarse con el nuevo archivo de monedero cifrado. Por razones de seguridad, las copias de seguridad previas del archivo de monedero no cifradas serán inservibles en cuanto comience a usar el nuevo monedero cifrado.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Aviso: ¡La tecla de bloqueo de mayúsculas está activada!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Monedero cifrado</translation> </message> <message> <location line="-56"/> <source>TakeiCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your takeicoins from being stolen by malware infecting your computer.</source> <translation>TakeiCoin se cerrará para finalizar el proceso de cifrado. Recuerde que el cifrado de su monedero no puede proteger totalmente sus takeicoins de robo por malware que infecte su sistema.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Ha fallado el cifrado del monedero</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Ha fallado el cifrado del monedero debido a un error interno. El monedero no ha sido cifrado.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Las contraseñas no coinciden.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Ha fallado el desbloqueo del monedero</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La contraseña introducida para descifrar el monedero es incorrecta.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Ha fallado el descifrado del monedero</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Se ha cambiado correctamente la contraseña del monedero.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Firmar &amp;mensaje...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Sincronizando con la red…</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Vista general</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Mostrar vista general del monedero</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transacciones</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Examinar el historial de transacciones</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Editar la lista de las direcciones y etiquetas almacenadas</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Mostrar la lista de direcciones utilizadas para recibir pagos</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Salir</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Salir de la aplicación</translation> </message> <message> <location line="+4"/> <source>Show information about TakeiCoin</source> <translation>Mostrar información acerca de TakeiCoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Acerca de &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Mostrar información acerca de Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opciones...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Cifrar monedero…</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>Copia de &amp;respaldo del monedero...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Cambiar la contraseña…</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importando bloques de disco...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Reindexando bloques en disco...</translation> </message> <message> <location line="-347"/> <source>Send coins to a TakeiCoin address</source> <translation>Enviar monedas a una dirección TakeiCoin</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for TakeiCoin</source> <translation>Modificar las opciones de configuración de TakeiCoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Copia de seguridad del monedero en otra ubicación</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Cambiar la contraseña utilizada para el cifrado del monedero</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>Ventana de &amp;depuración</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Abrir la consola de depuración y diagnóstico</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Verificar mensaje...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>TakeiCoin</source> <translation>TakeiCoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Monedero</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Enviar</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Recibir</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Direcciones</translation> </message> <message> <location line="+22"/> <source>&amp;About TakeiCoin</source> <translation>&amp;Acerca de TakeiCoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>Mo&amp;strar/ocultar</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Mostrar u ocultar la ventana principal</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Cifrar las claves privadas de su monedero</translation> </message> <message> <location line="+7"/> <source>Sign messages with your TakeiCoin addresses to prove you own them</source> <translation>Firmar mensajes con sus direcciones TakeiCoin para demostrar la propiedad</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified TakeiCoin addresses</source> <translation>Verificar mensajes comprobando que están firmados con direcciones TakeiCoin concretas</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Archivo</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Configuración</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>A&amp;yuda</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Barra de pestañas</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>TakeiCoin client</source> <translation>Cliente TakeiCoin</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to TakeiCoin network</source> <translation><numerusform>%n conexión activa hacia la red TakeiCoin</numerusform><numerusform>%n conexiones activas hacia la red TakeiCoin</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>Ninguna fuente de bloques disponible ...</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>Se han procesado %1 de %2 bloques (estimados) del historial de transacciones.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Procesados %1 bloques del historial de transacciones.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n día</numerusform><numerusform>%n días</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n semana</numerusform><numerusform>%n semanas</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 atrás</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>El último bloque recibido fue generado hace %1.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Las transacciones posteriores a esta aún no están visibles.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>Error</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Aviso</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Información</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Esta transacción supera el límite de tamaño. Puede enviarla con una comisión de %1, destinada a los nodos que procesen su transacción para contribuir al mantenimiento de la red. ¿Desea pagar esta comisión?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Actualizado</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Actualizando...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Confirme la tarifa de la transacción</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Transacción enviada</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Transacción entrante</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Fecha: %1 Cantidad: %2 Tipo: %3 Dirección: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Gestión de URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid TakeiCoin address or malformed URI parameters.</source> <translation>¡No se puede interpretar la URI! Esto puede deberse a una dirección TakeiCoin inválida o a parámetros de URI mal formados.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>El monedero está &lt;b&gt;cifrado&lt;/b&gt; y actualmente &lt;b&gt;desbloqueado&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>El monedero está &lt;b&gt;cifrado&lt;/b&gt; y actualmente &lt;b&gt;bloqueado&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. TakeiCoin can no longer continue safely and will quit.</source> <translation>Ha ocurrido un error crítico. TakeiCoin ya no puede continuar con seguridad y se cerrará.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Alerta de red</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Editar Dirección</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etiqueta</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>La etiqueta asociada con esta entrada en la libreta</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Dirección</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>La dirección asociada con esta entrada en la guía. Solo puede ser modificada para direcciones de envío.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nueva dirección para recibir</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nueva dirección para enviar</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Editar dirección de recepción</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Editar dirección de envío</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>La dirección introducida &quot;%1&quot; ya está presente en la libreta de direcciones.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid TakeiCoin address.</source> <translation>La dirección introducida &quot;%1&quot; no es una dirección TakeiCoin válida.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>No se pudo desbloquear el monedero.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Ha fallado la generación de la nueva clave.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>TakeiCoin-Qt</source> <translation>TakeiCoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versión</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Uso:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>opciones de la línea de órdenes</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Opciones GUI</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Establecer el idioma, por ejemplo, &quot;es_ES&quot; (predeterminado: configuración regional del sistema)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Arrancar minimizado</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Mostrar pantalla de bienvenida en el inicio (predeterminado: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opciones</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Principal</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>Tarifa de transacción opcional por kB que ayuda a asegurar que sus transacciones sean procesadas rápidamente. La mayoría de transacciones son de 1kB.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Comisión de &amp;transacciones</translation> </message> <message> <location line="+31"/> <source>Automatically start TakeiCoin after logging in to the system.</source> <translation>Iniciar TakeiCoin automáticamente al encender el sistema.</translation> </message> <message> <location line="+3"/> <source>&amp;Start TakeiCoin on system login</source> <translation>&amp;Iniciar TakeiCoin al iniciar el sistema</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Restablecer todas las opciones del cliente a las predeterminadas.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>&amp;Restablecer opciones</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Red</translation> </message> <message> <location line="+6"/> <source>Automatically open the TakeiCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Abrir automáticamente el puerto del cliente TakeiCoin en el router. Esta opción solo funciona si el router admite UPnP y está activado.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mapear el puerto usando &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the TakeiCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Conectar a la red TakeiCoin a través de un proxy SOCKS (ej. para conectar con la red Tor)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Conectar a través de un proxy SOCKS:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Dirección &amp;IP del proxy:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Dirección IP del proxy (ej. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Puerto:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Puerto del servidor proxy (ej. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>&amp;Versión SOCKS:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versión del proxy SOCKS (ej. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Ventana</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Minimizar la ventana a la bandeja de iconos del sistema.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizar a la bandeja en vez de a la barra de tareas</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimizar en lugar de salir de la aplicación al cerrar la ventana.Cuando esta opción está activa, la aplicación solo se puede cerrar seleccionando Salir desde el menú.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimizar al cerrar</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Interfaz</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>I&amp;dioma de la interfaz de usuario</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting TakeiCoin.</source> <translation>El idioma de la interfaz de usuario puede establecerse aquí. Este ajuste se aplicará cuando se reinicie TakeiCoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>Mostrar las cantidades en la &amp;unidad:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Elegir la subdivisión predeterminada para mostrar cantidades en la interfaz y cuando se envían monedas.</translation> </message> <message> <location line="+9"/> <source>Whether to show TakeiCoin addresses in the transaction list or not.</source> <translation>Mostrar o no las direcciones TakeiCoin en la lista de transacciones.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Mostrar las direcciones en la lista de transacciones</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;Aceptar</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancelar</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Aplicar</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>predeterminado</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Confirme el restablecimiento de las opciones</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Algunas configuraciones pueden requerir un reinicio del cliente para que sean efectivas.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>¿Quiere proceder?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Aviso</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting TakeiCoin.</source> <translation>Esta configuración tendrá efecto tras reiniciar TakeiCoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>La dirección proxy indicada es inválida.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Desde</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the TakeiCoin network after a connection is established, but this process has not completed yet.</source> <translation>La información mostrada puede estar desactualizada. Su monedero se sincroniza automáticamente con la red TakeiCoin después de que se haya establecido una conexión , pero este proceso aún no se ha completado.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>No confirmado(s):</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Monedero</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>No disponible:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Saldo recién minado que aún no está disponible.</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Movimientos recientes&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Su saldo actual</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Total de las transacciones que faltan por confirmar y que no contribuyen al saldo actual</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>desincronizado</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start takeicoin: click-to-pay handler</source> <translation>No se pudo iniciar takeicoin: manejador de pago-al-clic</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Diálogo de códigos QR</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Solicitud de pago</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Cuantía:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Etiqueta:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Mensaje:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Guardar como...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Error al codificar la URI en el código QR.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>La cantidad introducida es inválida. Compruébela, por favor.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>URI esultante demasiado larga. Intente reducir el texto de la etiqueta / mensaje.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Guardar código QR</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>Imágenes PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nombre del cliente</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>N/D</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Versión del cliente</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Información</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Utilizando la versión OpenSSL</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Hora de inicio</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Red</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Número de conexiones</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>En la red de pruebas</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Cadena de bloques</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Número actual de bloques</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Bloques totales estimados</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Hora del último bloque</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Abrir</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Opciones de la línea de órdenes</translation> </message> <message> <location line="+7"/> <source>Show the TakeiCoin-Qt help message to get a list with possible TakeiCoin command-line options.</source> <translation>Mostrar el mensaje de ayuda de TakeiCoin-Qt que enumera las opciones disponibles de línea de órdenes para TakeiCoin.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Mostrar</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Consola</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Fecha de compilación</translation> </message> <message> <location line="-104"/> <source>TakeiCoin - Debug window</source> <translation>TakeiCoin - Ventana de depuración</translation> </message> <message> <location line="+25"/> <source>TakeiCoin Core</source> <translation>Núcleo de TakeiCoin</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Archivo de registro de depuración</translation> </message> <message> <location line="+7"/> <source>Open the TakeiCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Abrir el archivo de registro de depuración en el directorio actual de datos. Esto puede llevar varios segundos para archivos de registro grandes.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Borrar consola</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the TakeiCoin RPC console.</source> <translation>Bienvenido a la consola RPC de TakeiCoin</translation> </message> <message><|fim▁hole|> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Escriba &lt;b&gt;help&lt;/b&gt; para ver un resumen de los comandos disponibles.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Enviar monedas</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Enviar a multiples destinatarios de una vez</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Añadir &amp;destinatario</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Eliminar todos los campos de las transacciones</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Limpiar &amp;todo</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Confirmar el envío</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Enviar</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; a %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Confirmar el envío de monedas</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>¿Está seguro de que desea enviar %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>y</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>La dirección de recepción no es válida, compruébela de nuevo.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>La cantidad por pagar tiene que ser mayor de 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>La cantidad sobrepasa su saldo.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>El total sobrepasa su saldo cuando se incluye la tasa de envío de %1</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Se ha encontrado una dirección duplicada. Solo se puede enviar a cada dirección una vez por operación de envío.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Error: ¡Ha fallado la creación de la transacción!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Error: transacción rechazada. Puede haber ocurrido si alguna de las monedas ya estaba gastada o si ha usado una copia de wallet.dat y las monedas se gastaron en la copia pero no se han marcado así aquí.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Envío</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Ca&amp;ntidad:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Pagar a:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>La dirección a la que enviar el pago (p. ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Etiquete esta dirección para añadirla a la libreta</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Etiqueta:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Elija una dirección de la libreta de direcciones</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Pegar dirección desde portapapeles</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Eliminar destinatario</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a TakeiCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Introduzca una dirección TakeiCoin (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Firmas - Firmar / verificar un mensaje</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Firmar mensaje</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Puede firmar mensajes con sus direcciones para demostrar que las posee. Tenga cuidado de no firmar cualquier cosa vaga, ya que los ataques de phishing pueden tratar de engañarle para suplantar su identidad. Firme solo declaraciones totalmente detalladas con las que usted esté de acuerdo.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>La dirección con la que firmar el mensaje (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Elija una dirección de la libreta de direcciones</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Pegar dirección desde portapapeles</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Introduzca el mensaje que desea firmar aquí</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Firma</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Copiar la firma actual al portapapeles del sistema</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this TakeiCoin address</source> <translation>Firmar el mensaje para demostrar que se posee esta dirección TakeiCoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Firmar &amp;mensaje</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Limpiar todos los campos de la firma de mensaje</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Limpiar &amp;todo</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Verificar mensaje</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Introduzca la dirección para la firma, el mensaje (asegurándose de copiar tal cual los saltos de línea, espacios, tabulaciones, etc.) y la firma a continuación para verificar el mensaje. Tenga cuidado de no asumir más información de lo que dice el propio mensaje firmado para evitar fraudes basados en ataques de tipo man-in-the-middle.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>La dirección con la que se firmó el mensaje (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified TakeiCoin address</source> <translation>Verificar el mensaje para comprobar que fue firmado con la dirección TakeiCoin indicada</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Verificar &amp;mensaje</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Limpiar todos los campos de la verificación de mensaje</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a TakeiCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Introduzca una dirección TakeiCoin (ej. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Haga clic en &quot;Firmar mensaje&quot; para generar la firma</translation> </message> <message> <location line="+3"/> <source>Enter TakeiCoin signature</source> <translation>Introduzca una firma TakeiCoin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>La dirección introducida es inválida.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Verifique la dirección e inténtelo de nuevo.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>La dirección introducida no corresponde a una clave.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Se ha cancelado el desbloqueo del monedero. </translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>No se dispone de la clave privada para la dirección introducida.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Ha fallado la firma del mensaje.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Mensaje firmado.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>No se puede decodificar la firma.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Compruebe la firma e inténtelo de nuevo.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>La firma no coincide con el resumen del mensaje.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>La verificación del mensaje ha fallado.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Mensaje verificado.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+25"/> <source>The TakeiCoin developers</source> <translation>Los programadores TakeiCoin</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Abierto hasta %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/fuera de línea</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/no confirmado</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 confirmaciones</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Estado</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, transmitir a través de %n nodo</numerusform><numerusform>, transmitir a través de %n nodos</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Fecha</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Fuente</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generado</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>De</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Para</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>dirección propia</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etiqueta</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Crédito</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>disponible en %n bloque más</numerusform><numerusform>disponible en %n bloques más</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>no aceptada</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Débito</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Comisión de transacción</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Cantidad neta</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Mensaje</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Comentario</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Identificador de transacción</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Las monedas generadas deben esperar 120 bloques antes de que se puedan gastar. Cuando se generó este bloque, se emitió a la red para ser agregado a la cadena de bloques. Si no consigue incorporarse a la cadena, su estado cambiará a &quot;no aceptado&quot; y las monedas no se podrán gastar. Esto puede ocurrir ocasionalmente si otro nodo genera un bloque casi al mismo tiempo que el suyo.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Información de depuración</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transacción</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>entradas</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Cantidad</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>verdadero</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falso</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, todavía no se ha sido difundido satisfactoriamente</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Abrir para %n bloque más</numerusform><numerusform>Abrir para %n bloques más</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>desconocido</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detalles de transacción</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Esta ventana muestra información detallada sobre la transacción</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Fecha</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Dirección</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Cantidad</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Abrir para %n bloque más</numerusform><numerusform>Abrir para %n bloques más</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Abierto hasta %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Fuera de línea (%1 confirmaciones)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>No confirmado (%1 de %2 confirmaciones)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Confirmado (%1 confirmaciones)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>El saldo recién minado estará disponible cuando venza el plazo en %n bloque más</numerusform><numerusform>El saldo recién minado estará disponible cuando venza el plazo en %n bloques más</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Este bloque no ha sido recibido por otros nodos y probablemente no sea aceptado!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generado pero no aceptado</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Recibido con</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Recibidos de</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Enviado a</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pago propio</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Minado</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(nd)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Estado de transacción. Pasa el ratón sobre este campo para ver el número de confirmaciones.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Fecha y hora en que se recibió la transacción.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipo de transacción.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Dirección de destino de la transacción.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Cantidad retirada o añadida al saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Todo</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Hoy</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Esta semana</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Este mes</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Mes pasado</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Este año</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Rango...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Recibido con</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Enviado a</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>A usted mismo</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Minado</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Otra</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Introduzca una dirección o etiqueta que buscar</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Cantidad mínima</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copiar dirección</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copiar etiqueta</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copiar cuantía</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Copiar identificador de transacción</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Editar etiqueta</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Mostrar detalles de la transacción</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Exportar datos de la transacción</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Archivos de columnas separadas por coma (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confirmado</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Fecha</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Dirección</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Cantidad</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Error exportando</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>No se pudo escribir en el archivo %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Rango:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>para</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Enviar monedas</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Exportar a un archivo los datos de esta pestaña</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Respaldo de monedero</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Datos de monedero (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Ha fallado el respaldo</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Se ha producido un error al intentar guardar los datos del monedero en la nueva ubicación.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Se ha completado con éxito la copia de respaldo</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Los datos del monedero se han guardado con éxito en la nueva ubicación.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>TakeiCoin version</source> <translation>Versión de TakeiCoin</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Uso:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or takeicoind</source> <translation>Envíar comando a -server o takeicoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Muestra comandos </translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Recibir ayuda para un comando </translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opciones: </translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: takeicoin.conf)</source> <translation>Especificar archivo de configuración (predeterminado: takeicoin.conf) </translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: takeicoind.pid)</source> <translation>Especificar archivo pid (predeterminado: takeicoin.pid) </translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Especificar directorio para los datos</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Establecer el tamaño de caché de la base de datos en megabytes (predeterminado: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation>Escuchar conexiones en &lt;puerto&gt; (predeterminado: 8333 o testnet: 18333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Mantener como máximo &lt;n&gt; conexiones a pares (predeterminado: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Conectar a un nodo para obtener direcciones de pares y desconectar</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Especifique su propia dirección pública</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Umbral para la desconexión de pares con mal comportamiento (predeterminado: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Número de segundos en que se evita la reconexión de pares con mal comportamiento (predeterminado: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Ha ocurrido un error al configurar el puerto RPC %u para escucha en IPv4: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation>Escuchar conexiones JSON-RPC en &lt;puerto&gt; (predeterminado: 8332 o testnet:18332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Aceptar comandos consola y JSON-RPC </translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Correr como demonio y aceptar comandos </translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Usar la red de pruebas </translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Aceptar conexiones desde el exterior (predeterminado: 1 si no -proxy o -connect)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=takeicoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;TakeiCoin Alert&quot; [email protected] </source> <translation>%s, debe establecer un valor rpcpassword en el archivo de configuración: %s Se recomienda utilizar la siguiente contraseña aleatoria: rpcuser=takeicoinrpc rpcpassword=%s (no es necesario recordar esta contraseña) El nombre de usuario y la contraseña DEBEN NO ser iguales. Si el archivo no existe, créelo con permisos de archivo de solo lectura. Se recomienda también establecer alertnotify para recibir notificaciones de problemas. Por ejemplo: alertnotify=echo %%s | mail -s &quot;TakeiCoin Alert&quot; [email protected] </translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Ha ocurrido un error al configurar el puerto RPC %u para escuchar mediante IPv6. Recurriendo a IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Vincular a la dirección dada y escuchar siempre en ella. Utilice la notación [host]:port para IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. TakeiCoin is probably already running.</source> <translation>No se puede bloquear el directorio de datos %s. Probablemente TakeiCoin ya se está ejecutando.</translation> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>¡Error: se ha rechazado la transacción! Esto puede ocurrir si ya se han gastado algunas de las monedas del monedero, como ocurriría si hubiera hecho una copia de wallet.dat y se hubieran gastado monedas a partir de la copia, con lo que no se habrían marcado aquí como gastadas.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>¡Error: Esta transacción requiere una comisión de al menos %s debido a su monto, complejidad, o al uso de fondos recién recibidos!</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Ejecutar orden cuando se reciba un aviso relevante (%s en cmd se reemplazará por el mensaje)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Ejecutar comando cuando una transacción del monedero cambia (%s en cmd se remplazará por TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Establecer el tamaño máximo de las transacciones de alta prioridad/comisión baja en bytes (predeterminado:27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Esta es una versión de pre-prueba - utilícela bajo su propio riesgo. No la utilice para usos comerciales o de minería.</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Aviso: ¡-paytxfee tiene un valor muy alto! Esta es la comisión que pagará si envía una transacción.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Aviso: ¡Las transacciones mostradas pueden no ser correctas! Puede necesitar una actualización o bien otros nodos necesitan actualizarse.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong TakeiCoin will not work properly.</source> <translation>Precaución: Por favor, ¡revise que la fecha y hora de su ordenador son correctas! Si su reloj está mal, TakeiCoin no funcionará correctamente.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Aviso: ¡Error al leer wallet.dat! Todas las claves se han leído correctamente, pero podrían faltar o ser incorrectos los datos de transacciones o las entradas de la libreta de direcciones.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Aviso: ¡Recuperados datos de wallet.dat corrupto! El wallet.dat original se ha guardado como wallet.{timestamp}.bak en %s; si hubiera errores en su saldo o transacciones, deberá restaurar una copia de seguridad.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Intento de recuperar claves privadas de un wallet.dat corrupto</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Opciones de creación de bloques:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Conectar sólo a los nodos (o nodo) especificados</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Corrupción de base de datos de bloques detectada.</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Descubrir dirección IP propia (predeterminado: 1 al escuchar sin -externalip)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>¿Quieres reconstruir la base de datos de bloques ahora?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Error al inicializar la base de datos de bloques</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Error al inicializar el entorno de la base de datos del monedero %s</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Error cargando base de datos de bloques</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Error al abrir base de datos de bloques.</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Error: ¡Espacio en disco bajo!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Error: ¡El monedero está bloqueado; no se puede crear la transacción!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Error: error de sistema: </translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Ha fallado la escucha en todos los puertos. Use -listen=0 si desea esto.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>No se ha podido leer la información de bloque</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>No se ha podido leer el bloque</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>No se ha podido sincronizar el índice de bloques</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>No se ha podido escribir en el índice de bloques</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>No se ha podido escribir la información de bloques</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>No se ha podido escribir el bloque</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>No se ha podido escribir la información de archivo</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>No se ha podido escribir en la base de datos de monedas</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>No se ha podido escribir en el índice de transacciones</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>No se han podido escribir los datos de deshacer</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Encontrar pares mediante búsqueda de DNS (predeterminado: 1 salvo con -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>Generar monedas (por defecto: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Cuántos bloques comprobar al iniciar (predeterminado: 288, 0 = todos)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>Como es de exhaustiva la verificación de bloques (0-4, por defecto 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation>No hay suficientes descriptores de archivo disponibles. </translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Reconstruir el índice de la cadena de bloques a partir de los archivos blk000??.dat actuales</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>Establecer el número de hilos para atender las llamadas RPC (predeterminado: 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Verificando bloques...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Verificando monedero...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importa los bloques desde un archivo blk000??.dat externo</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>Configura el número de hilos para el script de verificación (hasta 16, 0 = auto, &lt;0 = leave that many cores free, por fecto: 0)</translation> </message> <message> <location line="+77"/> <source>Information</source> <translation>Información</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Dirección -tor inválida: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Inválido por el monto -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Inválido por el monto -mintxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>Mantener índice de transacciones completo (predeterminado: 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Búfer de recepción máximo por conexión, &lt;n&gt;*1000 bytes (predeterminado: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Búfer de recepción máximo por conexión, , &lt;n&gt;*1000 bytes (predeterminado: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Aceptar solamente cadena de bloques que concuerde con los puntos de control internos (predeterminado: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Conectarse solo a nodos de la red &lt;net&gt; (IPv4, IPv6 o Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Mostrar información de depuración adicional. Implica todos los demás opciones -debug*</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Mostrar información de depuración adicional</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Anteponer marca temporal a la información de depuración</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>Opciones SSL: (ver la Bitcoin Wiki para instrucciones de configuración SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Elija la versión del proxy socks a usar (4-5, predeterminado: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Enviar información de trazas/depuración a la consola en lugar de al archivo debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Enviar información de trazas/depuración al depurador</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Establecer tamaño máximo de bloque en bytes (predeterminado: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Establecer tamaño mínimo de bloque en bytes (predeterminado: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Reducir el archivo debug.log al iniciar el cliente (predeterminado: 1 sin -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>Transacción falló</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Especificar el tiempo máximo de conexión en milisegundos (predeterminado: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Error de sistema: </translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>Monto de la transacción muy pequeño</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>Montos de transacciones deben ser positivos</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>Transacción demasiado grande</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Usar UPnP para asignar el puerto de escucha (predeterminado: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Usar UPnP para asignar el puerto de escucha (predeterminado: 1 al escuchar)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Utilizar proxy para conectar a Tor servicios ocultos (predeterminado: igual que -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Nombre de usuario para las conexiones JSON-RPC </translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Aviso</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Aviso: Esta versión es obsoleta, actualización necesaria!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>Necesita reconstruir las bases de datos con la opción -reindex para modificar -txindex</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrupto. Ha fallado la recuperación.</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Contraseña para las conexiones JSON-RPC </translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Permitir conexiones JSON-RPC desde la dirección IP especificada </translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Enviar comando al nodo situado en &lt;ip&gt; (predeterminado: 127.0.0.1) </translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Ejecutar un comando cuando cambia el mejor bloque (%s en cmd se sustituye por el hash de bloque)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Actualizar el monedero al último formato</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Ajustar el número de claves en reserva &lt;n&gt; (predeterminado: 100) </translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Volver a examinar la cadena de bloques en busca de transacciones del monedero perdidas</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Usar OpenSSL (https) para las conexiones JSON-RPC </translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Certificado del servidor (predeterminado: server.cert) </translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Clave privada del servidor (predeterminado: server.pem) </translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Cifrados aceptados (predeterminado: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH) </translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Este mensaje de ayuda </translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>No es posible conectar con %s en este sistema (bind ha dado el error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Conectar mediante proxy socks</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Permitir búsquedas DNS para -addnode, -seednode y -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Cargando direcciones...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Error al cargar wallet.dat: el monedero está dañado</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of TakeiCoin</source> <translation>Error al cargar wallet.dat: El monedero requiere una versión más reciente de TakeiCoin</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart TakeiCoin to complete</source> <translation>El monedero ha necesitado ser reescrito. Reinicie TakeiCoin para completar el proceso</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Error al cargar wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Dirección -proxy inválida: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>La red especificada en -onlynet &apos;%s&apos; es desconocida</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Solicitada versión de proxy -socks desconocida: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>No se puede resolver la dirección de -bind: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>No se puede resolver la dirección de -externalip: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Cantidad inválida para -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Cuantía no válida</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Fondos insuficientes</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Cargando el índice de bloques...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Añadir un nodo al que conectarse y tratar de mantener la conexión abierta</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. TakeiCoin is probably already running.</source> <translation>No es posible conectar con %s en este sistema. Probablemente TakeiCoin ya está ejecutándose.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Tarifa por KB que añadir a las transacciones que envíe</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Cargando monedero...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>No se puede rebajar el monedero</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>No se puede escribir la dirección predeterminada</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Reexplorando...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Generado pero no aceptado</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Para utilizar la opción %s</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Error</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Tiene que establecer rpcpassword=&lt;contraseña&gt; en el fichero de configuración: ⏎ %s ⏎ Si el archivo no existe, créelo con permiso de lectura solamente del propietario.</translation> </message> </context> </TS><|fim▁end|>
<location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Use las flechas arriba y abajo para navegar por el historial y &lt;b&gt;Control+L&lt;/b&gt; para limpiar la pantalla.</translation>
<|file_name|>swig.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # Copyright (c) 2010 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Wrapper around swig. Sets the SWIG_LIB environment var to point to Lib dir and defers control to the platform-specific swig binary. Depends on swig binaries being available at ../../third_party/swig. """ import os import subprocess import sys def main(): swig_dir = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), os.pardir, os.pardir, 'third_party', 'swig')) lib_dir = os.path.join(swig_dir, "Lib") os.putenv("SWIG_LIB", lib_dir) dir_map = { 'darwin': 'mac', 'linux2': 'linux', 'win32': 'win', } # Swig documentation lies that platform macros are provided to swig<|fim▁hole|> 'win32': '-DSWIGWIN', } swig_bin = os.path.join(swig_dir, dir_map[sys.platform], 'swig') args = [swig_bin, platform_flags[sys.platform]] + sys.argv[1:] args = [x.replace('/', os.sep) for x in args] print "Executing", args sys.exit(subprocess.call(args)) if __name__ == "__main__": main()<|fim▁end|>
# preprocessor. Provide them ourselves. platform_flags = { 'darwin': '-DSWIGMAC', 'linux2': '-DSWIGLINUX',
<|file_name|>email.py<|end_file_name|><|fim▁begin|>from oscar.core.loading import get_class OrderPlacementMixin = get_class("checkout.mixins", "OrderPlacementMixin")<|fim▁hole|> class OrderMessageSender(OrderPlacementMixin): def __init__(self, request): self.request = request<|fim▁end|>
<|file_name|>typeahead.js<|end_file_name|><|fim▁begin|>'use strict'; angular.module('mgcrea.ngStrap.typeahead', ['mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.parseOptions']) .provider('$typeahead', function() { var defaults = this.defaults = { animation: 'am-fade', prefixClass: 'typeahead', prefixEvent: '$typeahead', placement: 'bottom-left', template: 'typeahead/typeahead.tpl.html', trigger: 'focus', container: false, keyboard: true, html: false, delay: 0, minLength: 1, filter: 'filter', limit: 6 }; this.$get = function($window, $rootScope, $tooltip) { var bodyEl = angular.element($window.document.body); function TypeaheadFactory(element, controller, config) { var $typeahead = {}; // Common vars var options = angular.extend({}, defaults, config); $typeahead = $tooltip(element, options); var parentScope = config.scope; var scope = $typeahead.$scope; scope.$resetMatches = function(){ scope.$matches = []; scope.$activeIndex = 0; }; scope.$resetMatches(); scope.$activate = function(index) { scope.$$postDigest(function() { $typeahead.activate(index); }); }; scope.$select = function(index, evt) { scope.$$postDigest(function() { $typeahead.select(index); }); }; scope.$isVisible = function() { return $typeahead.$isVisible(); }; // Public methods $typeahead.update = function(matches) { scope.$matches = matches; if(scope.$activeIndex >= matches.length) { scope.$activeIndex = 0; } }; $typeahead.activate = function(index) { scope.$activeIndex = index; }; $typeahead.select = function(index) { var value = scope.$matches[index].value; controller.$setViewValue(value); controller.$render(); scope.$resetMatches(); if(parentScope) parentScope.$digest(); // Emit event scope.$emit(options.prefixEvent + '.select', value, index); }; // Protected methods $typeahead.$isVisible = function() { if(!options.minLength || !controller) { return !!scope.$matches.length; } // minLength support return scope.$matches.length && angular.isString(controller.$viewValue) && controller.$viewValue.length >= options.minLength; }; $typeahead.$getIndex = function(value) { var l = scope.$matches.length, i = l; if(!l) return; for(i = l; i--;) { if(scope.$matches[i].value === value) break; } if(i < 0) return; return i; }; $typeahead.$onMouseDown = function(evt) { // Prevent blur on mousedown evt.preventDefault(); evt.stopPropagation(); }; $typeahead.$onKeyDown = function(evt) { if(!/(38|40|13)/.test(evt.keyCode)) return; // Let ngSubmit pass if the typeahead tip is hidden if($typeahead.$isVisible()) { evt.preventDefault(); evt.stopPropagation(); } // Select with enter if(evt.keyCode === 13 && scope.$matches.length) { $typeahead.select(scope.$activeIndex); } // Navigate with keyboard else if(evt.keyCode === 38 && scope.$activeIndex > 0) scope.$activeIndex--; else if(evt.keyCode === 40 && scope.$activeIndex < scope.$matches.length - 1) scope.$activeIndex++; else if(angular.isUndefined(scope.$activeIndex)) scope.$activeIndex = 0; scope.$digest(); }; // Overrides var show = $typeahead.show; $typeahead.show = function() { show(); setTimeout(function() { $typeahead.$element.on('mousedown', $typeahead.$onMouseDown); if(options.keyboard) { element.on('keydown', $typeahead.$onKeyDown); } }); }; var hide = $typeahead.hide; $typeahead.hide = function() { $typeahead.$element.off('mousedown', $typeahead.$onMouseDown); if(options.keyboard) { element.off('keydown', $typeahead.$onKeyDown); } hide(); }; return $typeahead; } TypeaheadFactory.defaults = defaults; return TypeaheadFactory; }; }) .directive('bsTypeahead', function($window, $parse, $q, $typeahead, $parseOptions) { var defaults = $typeahead.defaults; return { restrict: 'EAC', require: 'ngModel', link: function postLink(scope, element, attr, controller) { // Directive options var options = {scope: scope}; angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'filter', 'limit', 'minLength', 'watchOptions', 'selectMode'], function(key) { if(angular.isDefined(attr[key])) options[key] = attr[key]; }); // Build proper ngOptions var filter = options.filter || defaults.filter; var limit = options.limit || defaults.limit; var ngOptions = attr.ngOptions; if(filter) ngOptions += ' | ' + filter + ':$viewValue'; if(limit) ngOptions += ' | limitTo:' + limit; var parsedOptions = $parseOptions(ngOptions); // Initialize typeahead var typeahead = $typeahead(element, controller, options); // Watch options on demand if(options.watchOptions) { // Watch ngOptions values before filtering for changes, drop function calls var watchedOptions = parsedOptions.$match[7].replace(/\|.+/, '').replace(/\(.*\)/g, '').trim(); scope.$watch(watchedOptions, function (newValue, oldValue) { // console.warn('scope.$watch(%s)', watchedOptions, newValue, oldValue); parsedOptions.valuesFn(scope, controller).then(function (values) { typeahead.update(values); controller.$render(); }); }, true); } // Watch model for changes scope.$watch(attr.ngModel, function(newValue, oldValue) { // console.warn('$watch', element.attr('ng-model'), newValue); scope.$modelValue = newValue; // Publish modelValue on scope for custom templates<|fim▁hole|> .then(function(values) { // Prevent input with no future prospect if selectMode is truthy // @TODO test selectMode if(options.selectMode && !values.length && newValue.length > 0) { controller.$setViewValue(controller.$viewValue.substring(0, controller.$viewValue.length - 1)); return; } if(values.length > limit) values = values.slice(0, limit); var isVisible = typeahead.$isVisible(); isVisible && typeahead.update(values); // Do not re-queue an update if a correct value has been selected if(values.length === 1 && values[0].value === newValue) return; !isVisible && typeahead.update(values); // Queue a new rendering that will leverage collection loading controller.$render(); }); }); // Model rendering in view controller.$render = function () { // console.warn('$render', element.attr('ng-model'), 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue, 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue); if(controller.$isEmpty(controller.$viewValue)) return element.val(''); var index = typeahead.$getIndex(controller.$modelValue); var selected = angular.isDefined(index) ? typeahead.$scope.$matches[index].label : controller.$viewValue; selected = angular.isObject(selected) ? selected.label : selected; element.val(selected.replace(/<(?:.|\n)*?>/gm, '').trim()); }; // Garbage collection scope.$on('$destroy', function() { if (typeahead) typeahead.destroy(); options = null; typeahead = null; }); } }; });<|fim▁end|>
parsedOptions.valuesFn(scope, controller)
<|file_name|>turtle.py<|end_file_name|><|fim▁begin|>""" Turtle RDF graph serializer for RDFLib. See <http://www.w3.org/TeamSubmission/turtle/> for syntax specification. """ from collections import defaultdict from rdflib.term import BNode, Literal, URIRef from rdflib.exceptions import Error from rdflib.serializer import Serializer from rdflib.namespace import RDF, RDFS __all__ = ['RecursiveSerializer', 'TurtleSerializer'] class RecursiveSerializer(Serializer): topClasses = [RDFS.Class] predicateOrder = [RDF.type, RDFS.label] maxDepth = 10 indentString = u" " def __init__(self, store): super(RecursiveSerializer, self).__init__(store) self.stream = None self.reset() def addNamespace(self, prefix, uri): self.namespaces[prefix] = uri def checkSubject(self, subject): """Check to see if the subject should be serialized yet""" if ((self.isDone(subject)) or (subject not in self._subjects) or ((subject in self._topLevels) and (self.depth > 1)) or (isinstance(subject, URIRef) and (self.depth >= self.maxDepth))): return False return True def isDone(self, subject): """Return true if subject is serialized""" return subject in self._serialized def orderSubjects(self): seen = {} subjects = [] for classURI in self.topClasses: members = list(self.store.subjects(RDF.type, classURI)) members.sort() for member in members: subjects.append(member) self._topLevels[member] = True seen[member] = True recursable = [ (isinstance(subject, BNode), self._references[subject], subject) for subject in self._subjects if subject not in seen] recursable.sort() subjects.extend([subject for (isbnode, refs, subject) in recursable]) return subjects def preprocess(self): for triple in self.store.triples((None, None, None)): self.preprocessTriple(triple) def preprocessTriple(self, (s, p, o)): self._references[o]+=1 self._subjects[s] = True def reset(self): self.depth = 0 self.lists = {} self.namespaces = {} self._references = defaultdict(int) self._serialized = {} self._subjects = {} self._topLevels = {} for prefix, ns in self.store.namespaces(): self.addNamespace(prefix, ns) def buildPredicateHash(self, subject): """ Build a hash key by predicate to a list of objects for the given subject """ properties = {} for s, p, o in self.store.triples((subject, None, None)): oList = properties.get(p, []) oList.append(o) properties[p] = oList return properties def sortProperties(self, properties): """Take a hash from predicate uris to lists of values. Sort the lists of values. Return a sorted list of properties.""" # Sort object lists for prop, objects in properties.items(): objects.sort() # Make sorted list of properties propList = [] seen = {} for prop in self.predicateOrder: if (prop in properties) and (prop not in seen): propList.append(prop) seen[prop] = True props = properties.keys() props.sort() for prop in props: if prop not in seen: propList.append(prop) seen[prop] = True return propList def subjectDone(self, subject): """Mark a subject as done.""" self._serialized[subject] = True def indent(self, modifier=0): """Returns indent string multiplied by the depth""" return (self.depth + modifier) * self.indentString def write(self, text): """Write text in given encoding.""" self.stream.write(text.encode(self.encoding, 'replace')) SUBJECT = 0 VERB = 1 OBJECT = 2 _GEN_QNAME_FOR_DT = False _SPACIOUS_OUTPUT = False class TurtleSerializer(RecursiveSerializer): short_name = "turtle" indentString = ' ' def __init__(self, store): self._ns_rewrite = {} super(TurtleSerializer, self).__init__(store) self.keywords = { RDF.type: 'a' } self.reset() self.stream = None self._spacious = _SPACIOUS_OUTPUT def addNamespace(self, prefix, namespace): # Turtle does not support prefix that start with _ # if they occur in the graph, rewrite to p_blah # this is more complicated since we need to make sure p_blah # does not already exist. And we register namespaces as we go, i.e. # we may first see a triple with prefix _9 - rewrite it to p_9 # and then later find a triple with a "real" p_9 prefix # so we need to keep track of ns rewrites we made so far. if (prefix > '' and prefix[0] == '_') \ or self.namespaces.get(prefix, namespace) != namespace: if prefix not in self._ns_rewrite: p = "p" + prefix while p in self.namespaces: p = "p" + p self._ns_rewrite[prefix] = p prefix = self._ns_rewrite.get(prefix, prefix) super(TurtleSerializer, self).addNamespace(prefix, namespace) return prefix def reset(self): super(TurtleSerializer, self).reset() self._shortNames = {} self._started = False self._ns_rewrite = {} def serialize(self, stream, base=None, encoding=None, spacious=None, **args): self.reset() self.stream = stream self.base = base if spacious is not None: self._spacious = spacious self.preprocess() subjects_list = self.orderSubjects() self.startDocument() firstTime = True for subject in subjects_list: if self.isDone(subject): continue if firstTime: firstTime = False if self.statement(subject) and not firstTime: self.write('\n') self.endDocument() stream.write(u"\n".encode('ascii')) def preprocessTriple(self, triple): super(TurtleSerializer, self).preprocessTriple(triple) for i, node in enumerate(triple): if node in self.keywords: continue # Don't use generated prefixes for subjects and objects self.getQName(node, gen_prefix=(i == VERB)) if isinstance(node, Literal) and node.datatype: self.getQName(node.datatype, gen_prefix=_GEN_QNAME_FOR_DT) p = triple[1] if isinstance(p, BNode): # hmm - when is P ever a bnode? self._references[p]+=1 def getQName(self, uri, gen_prefix=True): if not isinstance(uri, URIRef): return None parts = None try: parts = self.store.compute_qname(uri, generate=gen_prefix) except: # is the uri a namespace in itself? pfx = self.store.store.prefix(uri) if pfx is not None: parts = (pfx, uri, '') else: # nothing worked return None prefix, namespace, local = parts # QName cannot end with . if local.endswith("."): return None prefix = self.addNamespace(prefix, namespace) return u'%s:%s' % (prefix, local) def startDocument(self): self._started = True ns_list = sorted(self.namespaces.items()) for prefix, uri in ns_list: self.write(self.indent() + '@prefix %s: <%s> .\n' % (prefix, uri)) if ns_list and self._spacious: self.write('\n') def endDocument(self): if self._spacious: self.write('\n') def statement(self, subject): self.subjectDone(subject) return self.s_squared(subject) or self.s_default(subject) def s_default(self, subject): self.write('\n' + self.indent()) self.path(subject, SUBJECT) self.predicateList(subject) self.write(' .') return True def s_squared(self, subject): if (self._references[subject] > 0) or not isinstance(subject, BNode): return False<|fim▁hole|> self.write(' .') return True def path(self, node, position, newline=False): if not (self.p_squared(node, position, newline) or self.p_default(node, position, newline)): raise Error("Cannot serialize node '%s'" % (node, )) def p_default(self, node, position, newline=False): if position != SUBJECT and not newline: self.write(' ') self.write(self.label(node, position)) return True def label(self, node, position): if node == RDF.nil: return '()' if position is VERB and node in self.keywords: return self.keywords[node] if isinstance(node, Literal): return node._literal_n3( use_plain=True, qname_callback=lambda dt: self.getQName( dt, _GEN_QNAME_FOR_DT)) else: node = self.relativize(node) return self.getQName(node, position == VERB) or node.n3() def p_squared(self, node, position, newline=False): if (not isinstance(node, BNode) or node in self._serialized or self._references[node] > 1 or position == SUBJECT): return False if not newline: self.write(' ') if self.isValidList(node): # this is a list self.write('(') self.depth += 1 # 2 self.doList(node) self.depth -= 1 # 2 self.write(' )') else: self.subjectDone(node) self.depth += 2 # self.write('[\n' + self.indent()) self.write('[') self.depth -= 1 # self.predicateList(node, newline=True) self.predicateList(node, newline=False) # self.write('\n' + self.indent() + ']') self.write(' ]') self.depth -= 1 return True def isValidList(self, l): """ Checks if l is a valid RDF list, i.e. no nodes have other properties. """ try: if not self.store.value(l, RDF.first): return False except: return False while l: if l != RDF.nil and len( list(self.store.predicate_objects(l))) != 2: return False l = self.store.value(l, RDF.rest) return True def doList(self, l): while l: item = self.store.value(l, RDF.first) if item is not None: self.path(item, OBJECT) self.subjectDone(l) l = self.store.value(l, RDF.rest) def predicateList(self, subject, newline=False): properties = self.buildPredicateHash(subject) propList = self.sortProperties(properties) if len(propList) == 0: return self.verb(propList[0], newline=newline) self.objectList(properties[propList[0]]) for predicate in propList[1:]: self.write(' ;\n' + self.indent(1)) self.verb(predicate, newline=True) self.objectList(properties[predicate]) def verb(self, node, newline=False): self.path(node, VERB, newline) def objectList(self, objects): count = len(objects) if count == 0: return depthmod = (count == 1) and 0 or 1 self.depth += depthmod self.path(objects[0], OBJECT) for obj in objects[1:]: self.write(',\n' + self.indent(1)) self.path(obj, OBJECT, newline=True) self.depth -= depthmod<|fim▁end|>
self.write('\n' + self.indent() + '[]') self.predicateList(subject)
<|file_name|>block_quotation.rs<|end_file_name|><|fim▁begin|>use parser::Block; use parser::attributes::parse_block_attributes; use parser::block::parse_block; use parser::block::paragraph::parse_paragraph; use parser::inline::parse_inline_elements; use parser::patterns::BLOCK_QUOTATION_PATTERN; pub fn parse_block_quotation(lines: &[&str]) -> Option<(Block, usize)> { let mut cur_line = 1; if BLOCK_QUOTATION_PATTERN.is_match(lines[0]) { let caps = BLOCK_QUOTATION_PATTERN.captures(lines[0]).unwrap(); let mut bq_attrs = parse_block_attributes(caps.name("attributes").unwrap()); let p_attrs = bq_attrs.clone(); let mut blocks = Vec::new(); let mut strings = Vec::new(); strings.push(&lines[0][caps.at(0).unwrap().len()..]); if let Some(cite) = caps.name("cite") { bq_attrs.insert("cite".to_string(), cite.to_string()); } if caps.name("mode").unwrap().len() == 1 { // Breaks parsing if line is empty. for line in &lines[1..] { cur_line += 1; if line.is_empty() { break; } strings.push(line); } blocks.push(Block::Paragraph { attributes: p_attrs.clone(), elements: parse_inline_elements(&strings), starts_with_p: false, }); } else { // Breaks parsing if line is block element. for (idx, line) in (&lines[1..]).iter().enumerate() { cur_line += 1; if lines[idx].is_empty() { match parse_block(&[line]) { Some((Block::Paragraph { starts_with_p, .. }, _)) => { if starts_with_p { cur_line -= 1; break; } } Some(_) => { cur_line -= 1; break; } _ => {} } } strings.push(line); } let mut line_pos = 0; while line_pos < strings.len() { if let Some((mut paragraph, lines_count)) = parse_paragraph(&strings[line_pos..strings.len()]) { if let Block::Paragraph { ref mut attributes, .. } = paragraph { *attributes = p_attrs.clone(); } line_pos += lines_count; blocks.push(paragraph); } } } Some(( Block::BlockQuotation { attributes: bq_attrs, elements: blocks, }, cur_line )) } else { None } } #[cfg(test)] mod tests { use parser::{Attributes, Block, Inline}; use super::*; #[test] fn parses_block_quotation_correctly() { assert_eq!( parse_block_quotation(&["bq. *My quote*"]), Some(( Block::BlockQuotation { attributes: Attributes::new(), elements: vec![ Block::Paragraph { attributes: Attributes::new(), elements: vec![ Inline::Bold { attributes: Attributes::new(), elements: vec![ Inline::Text("My quote".to_string()), ],<|fim▁hole|> } ], }, 1 )) ); } #[test] fn parses_multiline_block_quotation_correctly() { assert_eq!( parse_block_quotation(&["bq.. Block quotation", "", "in multiline mode"]), Some(( Block::BlockQuotation { attributes: Attributes::new(), elements: vec![ Block::Paragraph { attributes: Attributes::new(), elements: vec![ Inline::Text("Block quotation".to_string()), ], starts_with_p: false, }, Block::Paragraph { attributes: Attributes::new(), elements: vec![ Inline::Text("in multiline mode".to_string()), ], starts_with_p: false, }, ], }, 3 )) ); assert_eq!( parse_block_quotation(&["bq.. Block quotation", "", "in multiline mode", "", "h1. Heading"]), Some(( Block::BlockQuotation { attributes: Attributes::new(), elements: vec![ Block::Paragraph { attributes: Attributes::new(), elements: vec![ Inline::Text("Block quotation".to_string()), ], starts_with_p: false, }, Block::Paragraph { attributes: Attributes::new(), elements: vec![ Inline::Text("in multiline mode".to_string()), ], starts_with_p: false, }, ], }, 4 )) ); } #[test] fn parses_block_quotation_with_cite_correctly() { assert_eq!( parse_block_quotation(&["bq.:http://example.com Block quotation"]), Some(( Block::BlockQuotation { attributes: hashmap!{ "cite".to_string() => "http://example.com".to_string(), }, elements: vec![ Block::Paragraph { attributes: Attributes::new(), elements: vec![ Inline::Text("Block quotation".to_string()), ], starts_with_p: false, }, ], }, 1 )) ); } }<|fim▁end|>
tag_type: "strong".to_string(), }, ], starts_with_p: false,
<|file_name|>debug_test.js<|end_file_name|><|fim▁begin|>// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. goog.setTestOnly(); goog.require('goog.testing.asserts'); // CommonJS-LoadFromFile: google-protobuf goog.require('jspb.debug'); // CommonJS-LoadFromFile: test_pb<|fim▁hole|> describe('debugTest', function() { it('testSimple1', function() { if (COMPILED) { return; } var message = new proto.jspb.test.Simple1(); message.setAString('foo'); assertObjectEquals({ $name: 'proto.jspb.test.Simple1', 'aString': 'foo', 'aRepeatedStringList': [] }, jspb.debug.dump(message)); message.setABoolean(true); message.setARepeatedStringList(['1', '2']); assertObjectEquals({ $name: 'proto.jspb.test.Simple1', 'aString': 'foo', 'aRepeatedStringList': ['1', '2'], 'aBoolean': true }, jspb.debug.dump(message)); message.setAString(undefined); assertObjectEquals({ $name: 'proto.jspb.test.Simple1', 'aRepeatedStringList': ['1', '2'], 'aBoolean': true }, jspb.debug.dump(message)); }); it('testExtensions', function() { if (COMPILED) { return; } var extension = new proto.jspb.test.IsExtension(); extension.setExt1('ext1field'); var extendable = new proto.jspb.test.HasExtensions(); extendable.setStr1('v1'); extendable.setStr2('v2'); extendable.setStr3('v3'); extendable.setExtension(proto.jspb.test.IsExtension.extField, extension); assertObjectEquals({ '$name': 'proto.jspb.test.HasExtensions', 'str1': 'v1', 'str2': 'v2', 'str3': 'v3', '$extensions': { 'extField': { '$name': 'proto.jspb.test.IsExtension', 'ext1': 'ext1field' }, 'repeatedSimpleList': [] } }, jspb.debug.dump(extendable)); }); });<|fim▁end|>
goog.require('proto.jspb.test.HasExtensions'); goog.require('proto.jspb.test.IsExtension'); goog.require('proto.jspb.test.Simple1');
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>import { A } from '@ember/array'; import Route from '@ember/routing/route'; import Ember from 'ember'; import Pretender from 'pretender'; const { testing } = Ember; const LEGACY_PAYLOAD = { fruit: [ { id: 1, name: 'apple' }, { id: 2, name: 'pear' }, { id: 3, name: 'orange' }, { id: 4, name: 'grape' } ] }; const PAYLOAD = { data: [ { type: 'fruit', id: 1, attributes: { name: 'apple' } }, { type: 'fruit', id: 2, attributes: { name: 'pear' } }, { type: 'fruit', id: 3, attributes: { name: 'orange' } }, { type: 'fruit', id: 4, attributes: { name: 'grape' } } ] }; export default Route.extend({ server: undefined as any, requests: [] as any[], currentModel: undefined as any, model() { let arr: any = []; this.store.pushPayload('fruit', !this.store.peekAll ? LEGACY_PAYLOAD : PAYLOAD); if (!this.store.peekAll) { arr = [1, 2, 3, 4].map(id => (this.store as any).getById('fruit', id)); } else { arr = this.store.peekAll('fruit'); } return A(arr); }, beforeModel() { this._super(...arguments); if (!testing) { this._setupPretender(); } }, deactivate() { this._super(...arguments); }, willDestroy() { this._super(...arguments); if (!this.get('currentModel').constructor) { this.get('currentModel').constructor = {}; } }, _setupPretender() { const server = new Pretender(); // server.get('/fruits', request => { // return [200, {}, JSON.stringify({ // fruits: // })]; // }); server.put('/fruits/:id/doRipen', (request: any) => { const controller: any = this.get('controller'); controller.get('requests').addObject({ url: request.url, data: JSON.parse(request.requestBody) }); return [200, {}, '{"status": "ok"}']; }); server.put('/fruits/ripenEverything', (request: any) => { const controller: any = this.get('controller'); controller.get('requests').addObject({ url: request.url, data: JSON.parse(request.requestBody) }); return [200, {}, '{"status": "ok"}']; }); server.get('/fruits/:id/info', (request: any) => { const controller: any = this.get('controller'); controller.get('requests').addObject({ url: request.url }); return [200, {}, '{"status": "ok"}']; }); server.get('/fruits/fresh', (request: any) => { const controller: any = this.get('controller'); controller.get('requests').addObject({<|fim▁hole|> }); return [200, {}, '{"status": "ok"}']; }); this.set('server', server); }, _teardownPretender() { this.get('server').shutdown(); } });<|fim▁end|>
url: request.url
<|file_name|>hateoas.py<|end_file_name|><|fim▁begin|># -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PyBossa is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with PyBossa. If not, see <http://www.gnu.org/licenses/>. from flask import url_for class Hateoas(object): def link(self, rel, title, href): return "<link rel='%s' title='%s' href='%s'/>" % (rel, title, href) def create_link(self, item, rel='self'): title = item.__class__.__name__.lower() method = ".api_%s" % title href = url_for(method, id=item.id, _external=True) return self.link(rel, title, href) def create_links(self, item): cls = item.__class__.__name__.lower() if cls == 'taskrun': link = self.create_link(item) links = [] if item.app_id is not None: links.append(self.create_link(item.app, rel='parent')) if item.task_id is not None: links.append(self.create_link(item.task, rel='parent')) return links, link elif cls == 'task': link = self.create_link(item) links = [] if item.app_id is not None:<|fim▁hole|> elif cls == 'category': return None, self.create_link(item) elif cls == 'app': link = self.create_link(item) links = [] if item.category_id is not None: links.append(self.create_link(item.category, rel='category')) return links, link else: return False def remove_links(self, item): """Remove HATEOAS link and links from item""" if item.get('link'): item.pop('link') if item.get('links'): item.pop('links') return item<|fim▁end|>
links = [self.create_link(item.app, rel='parent')] return links, link
<|file_name|>HtmlUtil.java<|end_file_name|><|fim▁begin|>/* Copyright 2005-2006 Tim Fennell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sourceforge.stripes.util; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.regex.Pattern; /** * Provides simple utility methods for dealing with HTML. * * @author Tim Fennell */ public class HtmlUtil { private static final String FIELD_DELIMITER_STRING = "||"; private static final Pattern FIELD_DELIMITER_PATTERN = Pattern.compile("\\|\\|"); /** * Replaces special HTML characters from the set {@literal [<, >, ", ', &]} with their HTML * escape codes. Note that because the escape codes are multi-character that the returned * String could be longer than the one passed in.<|fim▁hole|> */ public static String encode(String fragment) { // If the input is null, then the output is null if (fragment == null) return null; StringBuilder builder = new StringBuilder(fragment.length() + 10); // a little wiggle room char[] characters = fragment.toCharArray(); // This loop used to also look for and replace single ticks with &apos; but it // turns out that it's not strictly necessary since Stripes uses double-quotes // around all form fields, and stupid IE6 will render &apos; verbatim instead // of as a single quote. for (int i=0; i<characters.length; ++i) { switch (characters[i]) { case '<' : builder.append("&lt;"); break; case '>' : builder.append("&gt;"); break; case '"' : builder.append("&quot;"); break; case '&' : builder.append("&amp;"); break; default: builder.append(characters[i]); } } return builder.toString(); } /** * One of a pair of methods (the other is splitValues) that is used to combine several * un-encoded values into a single delimited, encoded value for placement into a * hidden field. * * @param values One or more values which are to be combined * @return a single HTML-encoded String that contains all the values in such a way that * they can be converted back into a Collection of Strings with splitValues(). */ public static String combineValues(Collection<String> values) { if (values == null || values.size() == 0) { return ""; } else { StringBuilder builder = new StringBuilder(values.size() * 30); for (String value : values) { builder.append(value).append(FIELD_DELIMITER_STRING); } return encode(builder.toString()); } } /** * Takes in a String produced by combineValues and returns a Collection of values that * contains the same values as originally supplied to combineValues. Note that the order * or items in the collection (and indeed the type of Collection used) are not guaranteed * to be the same. * * @param value a String value produced by * @return a Collection of zero or more Strings */ public static Collection<String> splitValues(String value) { if (value == null || value.length() == 0) { return Collections.emptyList(); } else { String[] splits = FIELD_DELIMITER_PATTERN.split(value); return Arrays.asList(splits); } } }<|fim▁end|>
* * @param fragment a String fragment that might have HTML special characters in it * @return the fragment with special characters escaped
<|file_name|>App.java<|end_file_name|><|fim▁begin|>public class App { public static void main(String[] args) { System.out.println("Old man, look at my life...");<|fim▁hole|><|fim▁end|>
} }
<|file_name|>try-macro.rs<|end_file_name|><|fim▁begin|>// run-pass #![allow(deprecated)] // for deprecated `try!()` macro use std::num::{ParseFloatError, ParseIntError}; <|fim▁hole|> assert_eq!(nested(), Ok(2)); assert_eq!(merge_ok(), Ok(3.0)); assert_eq!(merge_int_err(), Err(Error::Int)); assert_eq!(merge_float_err(), Err(Error::Float)); } fn simple() -> Result<i32, ParseIntError> { Ok(try!("1".parse())) } fn nested() -> Result<i32, ParseIntError> { Ok(try!(try!("2".parse::<i32>()).to_string().parse::<i32>())) } fn merge_ok() -> Result<f32, Error> { Ok(try!("1".parse::<i32>()) as f32 + try!("2.0".parse::<f32>())) } fn merge_int_err() -> Result<f32, Error> { Ok(try!("a".parse::<i32>()) as f32 + try!("2.0".parse::<f32>())) } fn merge_float_err() -> Result<f32, Error> { Ok(try!("1".parse::<i32>()) as f32 + try!("b".parse::<f32>())) } #[derive(Debug, PartialEq)] enum Error { Int, Float, } impl From<ParseIntError> for Error { fn from(_: ParseIntError) -> Error { Error::Int } } impl From<ParseFloatError> for Error { fn from(_: ParseFloatError) -> Error { Error::Float } }<|fim▁end|>
fn main() { assert_eq!(simple(), Ok(1));
<|file_name|>SecureDict.py<|end_file_name|><|fim▁begin|>def interactiveConsole(a,b=None): ''' Useful function for debugging Placing interactiveConsole(locals(),globals()) into code will<|fim▁hole|> ''' import code d = {} if b: d.update(b) d.update(a) c=code.InteractiveConsole(locals=d) c.interact() class SecureDict(object): __slots__ = ('__items__',) def __init__(self, *a, **kw): self.__items__ = dict(*a, **kw) def getItem(self, item, default = None): if default!=None: return self.__items__.get(item,default) try: return self.__items__[item] except KeyError: raise KeyError('Key Error: %s'%item) def setItem(self, item, value): self.__items__[item] = value def __len__(self): return len(self.__items__) def __repr__(self): return 'SecureDict(%r)' % self.__items__ __str__ = __repr__ def keys(self): return self.__items__.keys() def values(self): return self.__items__.values() def pop(self,key): return self.__items__.pop(key)<|fim▁end|>
drop into an interactive console when run
<|file_name|>textbuf.cpp<|end_file_name|><|fim▁begin|>/////////////////////////////////////////////////////////////////////////////// // Name: src/common/textbuf.cpp // Purpose: implementation of wxTextBuffer class // Created: 14.11.01 // Author: Morten Hanssen, Vadim Zeitlin // Copyright: (c) 1998-2001 wxWidgets team // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // headers // ============================================================================ #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/string.h" #include "wx/intl.h" #include "wx/log.h" #endif #include "wx/textbuf.h" // ============================================================================ // wxTextBuffer class implementation // ============================================================================ // ---------------------------------------------------------------------------- // static methods (always compiled in) // ---------------------------------------------------------------------------- // default type is the native one const wxTextFileType wxTextBuffer::typeDefault = #if defined(__WINDOWS__) wxTextFileType_Dos; #elif defined(__UNIX__) wxTextFileType_Unix; #else wxTextFileType_None; #error "wxTextBuffer: unsupported platform." #endif const wxChar *wxTextBuffer::GetEOL(wxTextFileType type) { switch ( type ) { default: wxFAIL_MSG(wxT("bad buffer type in wxTextBuffer::GetEOL.")); wxFALLTHROUGH; // fall through nevertheless - we must return something... <|fim▁hole|> case wxTextFileType_Dos: return wxT("\r\n"); case wxTextFileType_Mac: return wxT("\r"); } } wxString wxTextBuffer::Translate(const wxString& text, wxTextFileType type) { // don't do anything if there is nothing to do if ( type == wxTextFileType_None ) return text; // nor if it is empty if ( text.empty() ) return text; wxString eol = GetEOL(type), result; // optimization: we know that the length of the new string will be about // the same as the length of the old one, so prealloc memory to avoid // unnecessary relocations result.Alloc(text.Len()); wxChar chLast = 0; for ( wxString::const_iterator i = text.begin(); i != text.end(); ++i ) { wxChar ch = *i; switch ( ch ) { case wxT('\n'): // Dos/Unix line termination result += eol; chLast = 0; break; case wxT('\r'): if ( chLast == wxT('\r') ) { // Mac empty line result += eol; } else { // just remember it: we don't know whether it is just "\r" // or "\r\n" yet chLast = wxT('\r'); } break; default: if ( chLast == wxT('\r') ) { // Mac line termination result += eol; // reset chLast to avoid inserting another eol before the // next character chLast = 0; } // add to the current line result += ch; } } if ( chLast ) { // trailing '\r' result += eol; } return result; } #if wxUSE_TEXTBUFFER wxString wxTextBuffer::ms_eof; // ---------------------------------------------------------------------------- // ctors & dtor // ---------------------------------------------------------------------------- wxTextBuffer::wxTextBuffer(const wxString& strBufferName) : m_strBufferName(strBufferName) { m_nCurLine = 0; m_isOpened = false; } wxTextBuffer::~wxTextBuffer() { // required here for Darwin } // ---------------------------------------------------------------------------- // buffer operations // ---------------------------------------------------------------------------- bool wxTextBuffer::Exists() const { return OnExists(); } bool wxTextBuffer::Create(const wxString& strBufferName) { m_strBufferName = strBufferName; return Create(); } bool wxTextBuffer::Create() { // buffer name must be either given in ctor or in Create(const wxString&) wxASSERT( !m_strBufferName.empty() ); // if the buffer already exists do nothing if ( Exists() ) return false; if ( !OnOpen(m_strBufferName, WriteAccess) ) return false; OnClose(); return true; } bool wxTextBuffer::Open(const wxString& strBufferName, const wxMBConv& conv) { m_strBufferName = strBufferName; return Open(conv); } bool wxTextBuffer::Open(const wxMBConv& conv) { // buffer name must be either given in ctor or in Open(const wxString&) wxASSERT( !m_strBufferName.empty() ); // open buffer in read-only mode if ( !OnOpen(m_strBufferName, ReadAccess) ) return false; // read buffer into memory m_isOpened = OnRead(conv); OnClose(); return m_isOpened; } // analyse some lines of the buffer trying to guess it's type. // if it fails, it assumes the native type for our platform. wxTextFileType wxTextBuffer::GuessType() const { wxASSERT( IsOpened() ); // scan the buffer lines size_t nUnix = 0, // number of '\n's alone nDos = 0, // number of '\r\n' nMac = 0; // number of '\r's // we take MAX_LINES_SCAN in the beginning, middle and the end of buffer #define MAX_LINES_SCAN (10) size_t nCount = m_aLines.GetCount() / 3, nScan = nCount > 3*MAX_LINES_SCAN ? MAX_LINES_SCAN : nCount / 3; #define AnalyseLine(n) \ switch ( m_aTypes[n] ) { \ case wxTextFileType_Unix: nUnix++; break; \ case wxTextFileType_Dos: nDos++; break; \ case wxTextFileType_Mac: nMac++; break; \ default: wxFAIL_MSG(wxT("unknown line terminator")); \ } size_t n; for ( n = 0; n < nScan; n++ ) // the beginning AnalyseLine(n); for ( n = (nCount - nScan)/2; n < (nCount + nScan)/2; n++ ) AnalyseLine(n); for ( n = nCount - nScan; n < nCount; n++ ) AnalyseLine(n); #undef AnalyseLine // interpret the results (FIXME far from being even 50% fool proof) if ( nScan > 0 && nDos + nUnix + nMac == 0 ) { // no newlines at all wxLogWarning(_("'%s' is probably a binary buffer."), m_strBufferName.c_str()); } else { #define GREATER_OF(t1, t2) n##t1 == n##t2 ? typeDefault \ : n##t1 > n##t2 \ ? wxTextFileType_##t1 \ : wxTextFileType_##t2 if ( nDos > nUnix ) return GREATER_OF(Dos, Mac); else if ( nDos < nUnix ) return GREATER_OF(Unix, Mac); else { // nDos == nUnix return nMac > nDos ? wxTextFileType_Mac : typeDefault; } #undef GREATER_OF } return typeDefault; } bool wxTextBuffer::Close() { Clear(); m_isOpened = false; return true; } bool wxTextBuffer::Write(wxTextFileType typeNew, const wxMBConv& conv) { return OnWrite(typeNew, conv); } #endif // wxUSE_TEXTBUFFER<|fim▁end|>
case wxTextFileType_None: return wxEmptyString; case wxTextFileType_Unix: return wxT("\n");
<|file_name|>responses.py<|end_file_name|><|fim▁begin|># This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. <|fim▁hole|> from marshmallow import fields from marshmallow.decorators import post_dump from indico.core.config import config from indico.core.marshmallow import mm class HTTPAPIError(Exception): def __init__(self, message, code=None): self.message = message self.code = code class HTTPAPIResult: def __init__(self, results, path='', query='', ts=None, extra=None): if ts is None: ts = int(time.time()) self.results = results self.path = path self.query = query self.ts = ts self.extra = extra or {} @property def url(self): prefix = config.BASE_URL if self.query: return f'{prefix}{self.path}?{self.query}' return prefix + self.path @property def count(self): return len(self.results) class HTTPAPIResultSchema(mm.Schema): count = fields.Integer() extra = fields.Raw(data_key='additionalInfo') ts = fields.Integer() url = fields.String() results = fields.Raw() @post_dump def _add_type(self, data, **kwargs): data['_type'] = 'HTTPAPIResult' return data<|fim▁end|>
import time
<|file_name|>testsuite_shared.cc<|end_file_name|><|fim▁begin|>// Copyright (C) 2004-2016 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <string> #include <stdexcept> #include <iostream> #include <sstream> #include <set> #include <map> #include <ext/mt_allocator.h> #include <bits/functexcept.h> namespace __gnu_test { // libstdc++/22309 extern "C" void try_allocation() { typedef char value_t; typedef __gnu_cxx::__mt_alloc<value_t> allocator_t; typedef std::char_traits<value_t> traits_t; typedef std::basic_string<value_t, traits_t, allocator_t> string_t; string_t s; s += "west beach, indiana dunes"; } // libstdc++/23591 extern "C" void try_throw_exception() { try { std::__throw_bad_exception(); } catch (const std::exception& e) { } } extern "C" void try_function_random_fail() { long seed = lrand48(); if (seed < 2000) seed = 2000; { std::ostringstream s; s << "random_throw, seed: " << seed << std::endl; std::cout << s.str(); } while (--seed > 0) { try_throw_exception(); } // Randomly throw. See if other threads cleanup. std::__throw_bad_exception();<|fim▁hole|>// "must be compiled with C++98" void erase_external(std::set<int>& s) { s.erase(s.begin()); } void erase_external(std::multiset<int>& s) { s.erase(s.begin()); } void erase_external(std::map<int, int>& s) { s.erase(s.begin()); } void erase_external(std::multimap<int, int>& s) { s.erase(s.begin()); } void erase_external_iterators(std::set<int>& s) { typedef typename std::set<int>::iterator iterator_type; iterator_type iter = s.begin(); s.erase(iter, ++iter); } void erase_external_iterators(std::multiset<int>& s) { typedef typename std::multiset<int>::iterator iterator_type; iterator_type iter = s.begin(); s.erase(iter, ++iter); } void erase_external_iterators(std::map<int, int>& s) { typedef typename std::map<int, int>::iterator iterator_type; iterator_type iter = s.begin(); s.erase(iter, ++iter); } void erase_external_iterators(std::multimap<int, int>& s) { typedef typename std::multimap<int, int>::iterator iterator_type; iterator_type iter = s.begin(); s.erase(iter, ++iter); } #endif } // end namepace __gnu_test<|fim▁end|>
} #if __cplusplus < 201103L
<|file_name|>common.rs<|end_file_name|><|fim▁begin|>// delila - a desktop version of lila. // // Copyright (C) 2017 Lakin Wecker <[email protected]> // // 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<|fim▁hole|>// 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/>. //------------------------------------------------------------------------------ // Scid common datatypes //------------------------------------------------------------------------------ // General types pub type UByte = u8; pub type UShort = u16; pub type UInt = u32; pub type SInt = i32; // Comparison type pub type Compare = i32; pub const LESS_THAN: Compare = -1; pub const EQUAL_TO: Compare = -1; pub const GREATER_THAN: Compare = -1; // Piece types pub type Piece = i8; // e.g ROOK or WHITE_KING pub type Color = i8; // WHITE or BLACK pub type Square = i8; // e.g. A3 pub type Direction = i8; // e.g. UP_LEFT pub type Rank = i8; // Chess board rank pub type File = i8; // Chess board file pub type LeftDiagonal = i8; // Up-left diagonals pub type RightDiagonal = i8; // Up-right diagonals // Game information types pub type GameNumber = UInt; pub type ELO = UShort; pub type ECO = UShort; // pub type typedef char ecoStringT [6]; /* "A00j1" */ pub const ECO_NONE: ECO = 0; // PIECE TYPES (without color; same value as a white piece) pub const KING: Piece = 1; pub const QUEEN: Piece = 2; pub const ROOK: Piece = 3; pub const BISHOP: Piece = 4; pub const KNIGHT: Piece = 5; pub const PAWN: Piece = 6; // PIECES: // Note that color(x) == ((x & 0x8) >> 3) and type(x) == (x & 0x7) // EMPTY is deliberately nonzero, and END_OF_BOARD is zero, so that // a board can be used as a regular 0-terminated string, provided // that board[NULL_SQUARE] == END_OF_BOARD, as it always should be. pub const EMPTY: Piece = 7; pub const END_OF_BOARD: Piece = 0; pub const WK: Piece = 1; pub const WQ: Piece = 2; pub const WR: Piece = 3; pub const WB: Piece = 4; pub const WN: Piece = 5; pub const WP: Piece = 6; pub const BK: Piece = 9; pub const BQ: Piece = 10; pub const BR: Piece = 11; pub const BB: Piece = 12; pub const BN: Piece = 13; pub const BP: Piece = 14; // Minor piece definitions, used for searching by material only: pub const WM: Piece = 16; pub const BM: Piece = 17;<|fim▁end|>
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
<|file_name|>app.js<|end_file_name|><|fim▁begin|>(function(angular) { 'use strict'; angular.module('nonStringSelect', []) .run(function($rootScope) { $rootScope.model = { id: 2 }; }) .directive('convertToNumber', function() { return { require: 'ngModel', link: function(scope, element, attrs, ngModel) { ngModel.$parsers.push(function(val) {<|fim▁hole|> ngModel.$formatters.push(function(val) { return '' + val; }); } }; }); })(window.angular);<|fim▁end|>
return parseInt(val, 10); });
<|file_name|>utils.py<|end_file_name|><|fim▁begin|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at<|fim▁hole|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class DummyKeyResponse(object): def __init__(self, gen=1): self.generation = gen self.name = "" def request(self, path, method, **kwargs): self.name = path.split('/')[-1] return self def json(self): return {"generation": self.generation, "name": self.name} class DummyTicketResponse(object): def __init__(self, signature, metadata, ticket): self.signature = signature self.metadata = metadata self.ticket = ticket def request(self, path, method, **kwargs): return self def json(self): return {"signature": self.signature, "metadata": self.metadata, "ticket": self.ticket} class DummyGroupResponse(object): def __init__(self, name): self.name = name def request(self, path, method, **kwargs): return self def json(self): return {"name": self.name} class DummyGroupKeyResponse(object): def __init__(self, signature, metadata, group_key): self.signature = signature self.metadata = metadata self.group_key = group_key def request(self, path, method, **kwargs): return self def json(self): return {"signature": self.signature, "metadata": self.metadata, "group_key": self.group_key}<|fim▁end|>
# # http://www.apache.org/licenses/LICENSE-2.0
<|file_name|>RemoteInvocationCallData.java<|end_file_name|><|fim▁begin|>/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.service.base.client; import net.sf.mmm.service.api.RemoteInvocationCall; import net.sf.mmm.util.lang.api.function.Consumer; /** * This is a simple container for the data corresponding to a {@link RemoteInvocationCall}. * * @param <RESULT> is the generic type of the method return-type. * @param <CALL> is the generic type of the {@link #getCall() call} data. * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.0.0 */ public class RemoteInvocationCallData<RESULT, CALL extends RemoteInvocationCall> { /** The callback to receive the service result on success. */ private final Consumer<? extends RESULT> successCallback; /** The callback to receive a potential service failure. */ private final Consumer<Throwable> failureCallback; /** @see #getCall() */<|fim▁hole|> * The constructor. * * @param successCallback is the callback that {@link Consumer#accept(Object) receives} the result on * success. * @param failureCallback is the callback that {@link Consumer#accept(Object) receives} the failure on * error. */ public RemoteInvocationCallData(Consumer<? extends RESULT> successCallback, Consumer<Throwable> failureCallback) { super(); this.successCallback = successCallback; this.failureCallback = failureCallback; } /** * @return the successCallback. */ public Consumer<? extends RESULT> getSuccessCallback() { return this.successCallback; } /** * @return the failureCallback. */ public Consumer<Throwable> getFailureCallback() { return this.failureCallback; } /** * @return the actual call data (either {@link net.sf.mmm.service.api.command.RemoteInvocationCommand} * itself or {@link net.sf.mmm.service.base.rpc.GenericRemoteInvocationRpcCall}). */ public CALL getCall() { return this.call; } /** * @param call is the new value of {@link #getCall()}. */ public void setCall(CALL call) { assert (this.call == null); assert (call != null); this.call = call; } }<|fim▁end|>
private CALL call; /**
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![feature(const_fn)]<|fim▁hole|> #![plugin(stainless)] #![plugin(clippy)] // for stainless before_each #![allow(unused_mut, unused_variables)] extern crate concrust; #[macro_use(expect)] extern crate expectest; mod test_primitives; mod test_array_queue; mod test_linked_queue; mod test_maps;<|fim▁end|>
#![feature(plugin)]
<|file_name|>MagicCubeRender.java<|end_file_name|><|fim▁begin|>/* * Copyright 2011-2014 Zhaotian Wang <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package flex.android.magiccube; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.util.Vector; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import flex.android.magiccube.R; import flex.android.magiccube.bluetooth.MessageSender; import flex.android.magiccube.interfaces.OnStateListener; import flex.android.magiccube.interfaces.OnStepListener; import flex.android.magiccube.solver.MagicCubeSolver; import flex.android.magiccube.solver.SolverFactory; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLSurfaceView; import android.opengl.GLU; import android.opengl.GLUtils; import android.opengl.Matrix; public class MagicCubeRender implements GLSurfaceView.Renderer { protected Context context; private int width; private int height; //eye-coordinate private float eyex; private float eyey; protected float eyez; private float angle = 65.f; protected float ratio = 0.6f; protected float zfar = 25.5f; private float bgdist = 25.f; //background texture private int[] BgTextureID = new int[1]; private Bitmap[] bitmap = new Bitmap[1]; private FloatBuffer bgtexBuffer; // Texture Coords Buffer for background private FloatBuffer bgvertexBuffer; // Vertex Buffer for background protected final int nStep = 9;//nstep for one rotate protected int volume; private boolean solved = false; //indicate if the cube has been solved //background position //... //rotation variable public float rx, ry; protected Vector<Command> commands; private Vector<Command> commandsBack; //backward command private Vector<Command> commandsForward; //forward command private Vector<Command> commandsAuto; //forward command protected int[] command; protected boolean HasCommand; protected int CommandLoop; private String CmdStrBefore = ""; private String CmdStrAfter = ""; public static final boolean ROTATE = true; public static final boolean MOVE = false; //matrix public float[] pro_matrix = new float[16]; public int [] view_matrix = new int[4]; public float[] mod_matrix = new float[16]; //minimal valid move distance private float MinMovedist; //the cubes! protected Magiccube magiccube; private boolean DrawCube; private boolean Finished = false; private boolean Resetting = false; protected OnStateListener stateListener = null; private MessageSender messageSender = null; private OnStepListener stepListener = null; public MagicCubeRender(Context context, int w, int h) { this.context = context; this.width = w; this.height = h; this.eyex = 0.f; this.eyey = 0.f; this.eyez = 20.f; this.rx = 22.f; this.ry = -34.f; this.HasCommand = false; this.commands = new Vector<Command>(1,1); this.commandsBack = new Vector<Command>(100, 10); this.commandsForward = new Vector<Command>(100, 10); this.commandsAuto = new Vector<Command>(40,5); //this.Command = new int[3]; magiccube = new Magiccube(); DrawCube = true; solved = false; volume = MagiccubePreference.GetPreference(MagiccubePreference.MoveVolume, context); //SetCommands("L- R2 F- D+ L+ U2 L2 D2 R+ D2 L+ F- D+ L2 D2 R2 B+ L+ U2 R2 U2 F2 R+ D2 U+"); //SetCommands("F- U+ F- D- L- D- F- U- L2 D-"); // SetCommands("U+"); // mediaPlayer = MediaPlayer.create(context, R.raw.move2); } public void SetDrawCube(boolean DrawCube) { this.DrawCube = DrawCube; } private void LoadBgTexture(GL10 gl) { //Load texture bitmap bitmap[0] = BitmapFactory.decodeStream( context.getResources().openRawResource(R.drawable.mainbg2)); gl.glGenTextures(1, BgTextureID, 0); // Generate texture-ID array for 6 IDs //Set texture uv float[] texCoords = { 0.0f, 1.0f, // A. left-bottom 1.0f, 1.0f, // B. right-bottom 0.0f, 0.0f, // C. left-top 1.0f, 0.0f // D. right-top }; ByteBuffer tbb = ByteBuffer.allocateDirect(texCoords.length * 4 ); tbb.order(ByteOrder.nativeOrder()); bgtexBuffer = tbb.asFloatBuffer(); bgtexBuffer.put(texCoords); bgtexBuffer.position(0); // Rewind // Generate OpenGL texture images gl.glBindTexture(GL10.GL_TEXTURE_2D, BgTextureID[0]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); // Build Texture from loaded bitmap for the currently-bind texture ID GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap[0], 0); bitmap[0].recycle(); } protected void DrawBg(GL10 gl) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, bgvertexBuffer); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, bgtexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); // Enable texture (NEW) gl.glPushMatrix(); gl.glBindTexture(GL10.GL_TEXTURE_2D, this.BgTextureID[0]); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4); gl.glPopMatrix(); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); } @Override public void onDrawFrame(GL10 gl) { // Clear color and depth buffers using clear-value set earlier gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // You OpenGL|ES rendering code here gl.glLoadIdentity(); GLU.gluLookAt(gl, eyex, eyey, eyez, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f); Matrix.setIdentityM(mod_matrix, 0); Matrix.setLookAtM(mod_matrix, 0, eyex, eyey, eyez, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f); DrawScene(gl); } private void SetBackgroundPosition() { float halfheight = (float)Math.tan(angle/2.0/180.0*Math.PI)*bgdist*1.f; float halfwidth = halfheight/this.height*this.width; float[] vertices = { -halfwidth, -halfheight, eyez-bgdist, // 0. left-bottom-front halfwidth, -halfheight, eyez-bgdist, // 1. right-bottom-front -halfwidth, halfheight,eyez-bgdist, // 2. left-top-front halfwidth, halfheight, eyez-bgdist, // 3. right-top-front }; ByteBuffer vbb = ByteBuffer.allocateDirect(12 * 4); vbb.order(ByteOrder.nativeOrder()); bgvertexBuffer = vbb.asFloatBuffer(); bgvertexBuffer.put(vertices); // Populate bgvertexBuffer.position(0); // Rewind } @Override public void onSurfaceChanged(GL10 gl, int w, int h) { //reset the width and the height; //Log.e("screen", w+" "+h); if (h == 0) h = 1; // To prevent divide by zero this.width = w; this.height = h; float aspect = (float)w / h; // Set the viewport (display area) to cover the entire window gl.glViewport(0, 0, w, h); this.view_matrix[0] = 0; this.view_matrix[1] = 0; this.view_matrix[2] = w; this.view_matrix[3] = h; // Setup perspective projection, with aspect ratio matches viewport gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix gl.glLoadIdentity(); // Reset projection matrix // Use perspective projection angle = 60; //calculate the angle to adjust the screen resolution //float idealwidth = Cube.CubeSize*3.f/(Math.abs(this.eyez-Cube.CubeSize*1.5f))*zfar/ratio; float idealwidth = Cube.CubeSize*3.f/(Math.abs(this.eyez-Cube.CubeSize*1.5f))*zfar/ratio; float idealheight = idealwidth/(float)w*(float)h; angle = (float)(Math.atan2(idealheight/2.f, Math.abs(zfar))*2.f*180.f/Math.PI); SetBackgroundPosition(); GLU.gluPerspective(gl, angle, aspect, 0.1f, zfar); MinMovedist = w*ratio/3.f*0.15f; float r = (float)w/(float)h; float size = (float)(0.1*Math.tan(angle/2.0/180.0*Math.PI)); Matrix.setIdentityM(pro_matrix, 0); Matrix.frustumM(pro_matrix, 0, -size*r, size*r, -size , size, 0.1f, zfar); gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix gl.glLoadIdentity(); // Reset /* // You OpenGL|ES display re-sizing code here gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE); //float []lightparam = {0.6f, 0.2f, 0.2f, 0.6f, 0.2f, 0.2f, 0, 0, 10}; float []lightparam = {1f, 1f, 1f, 3f, 1f, 1f, 0, 0, 5}; gl.glEnable(GL10.GL_LIGHTING); // ���û����� gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, lightparam, 0); // ��������� gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightparam, 3); // ���þ��淴�� gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_SPECULAR, lightparam, 3); // ���ù�Դλ�� gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightparam, 6); // ������Դ gl.glEnable(GL10.GL_LIGHT0); */ // ������� //gl.glEnable(GL10.GL_BLEND); if( this.stateListener != null ) { stateListener.OnStateChanged(OnStateListener.LOADED); } } @Override public void onSurfaceCreated(GL10 gl, EGLConfig arg1) { gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set color's clear-value to black gl.glClearDepthf(1.0f); // Set depth's clear-value to farthest gl.glEnable(GL10.GL_DEPTH_TEST); // Enables depth-buffer for hidden surface removal gl.glDepthFunc(GL10.GL_LEQUAL); // The type of depth testing to do gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); // nice perspective view gl.glShadeModel(GL10.GL_SMOOTH); // Enable smooth shading of color gl.glDisable(GL10.GL_DITHER); // Disable dithering for better performance // You OpenGL|ES initialization code here //Initial the cubes magiccube.LoadTexture(gl, context); //this.MessUp(50); LoadBgTexture(gl); } public void SetMessageSender(MessageSender messageSender) { this.messageSender = messageSender; } protected void DrawScene(GL10 gl) { this.DrawBg(gl); if( !DrawCube) { return; } if(Resetting) { //Resetting = false; //reset(); } if(HasCommand) { Command command = commands.firstElement(); if( CommandLoop == 0 && messageSender != null) { messageSender.SendMessage(command.toString()); } int nsteps = command.N*this.nStep; //rotate nsteps if(CommandLoop%nStep == 0 && CommandLoop != nsteps) { MusicPlayThread musicPlayThread = new MusicPlayThread(context, R.raw.move2, volume); musicPlayThread.start(); } if(command.Type == Command.ROTATE_ROW) { magiccube.RotateRow(command.RowID, command.Direction, 90.f/nStep,CommandLoop%nStep==nStep-1); } else if(command.Type == Command.ROTATE_COL) { magiccube.RotateCol(command.RowID, command.Direction, 90.f/nStep,CommandLoop%nStep==nStep-1); } else { magiccube.RotateFace(command.RowID, command.Direction, 90.f/nStep,CommandLoop%nStep==nStep-1); } CommandLoop++; if(CommandLoop==nsteps) { CommandLoop = 0; if(commands.size() > 1) { //Log.e("full", "full"+commands.size()); } this.CmdStrAfter += command.toString() + " "; commands.removeElementAt(0); //Log.e("e", commands.size()+""); if( commands.size() <= 0) { HasCommand = false; } if( stepListener != null) { stepListener.AddStep(); } //this.ReportFaces(); //Log.e("state", this.GetState()); if(Finished && !this.IsComplete()) { Finished = false; if(this.stateListener != null) { stateListener.OnStateNotify(OnStateListener.CANAUTOSOLVE); } } } if(this.stateListener != null && this.IsComplete()) { if( !Finished ) { Finished = true; stateListener.OnStateChanged(OnStateListener.FINISH); stateListener.OnStateNotify(OnStateListener.CANNOTAUTOSOLVE); } } } DrawCubes(gl); } protected void DrawCubes(GL10 gl) { gl.glPushMatrix(); gl.glRotatef(rx, 1, 0, 0); //rotate gl.glRotatef(ry, 0, 1, 0); // Log.e("rxry", rx + " " + ry); if(this.HasCommand) { magiccube.Draw(gl); } else { magiccube.DrawSimple(gl); } gl.glPopMatrix(); } public void SetOnStateListener(OnStateListener stateListener) { this.stateListener = stateListener; } public void SetOnStepListnener(OnStepListener stepListener) { this.stepListener = stepListener; } public boolean GetPos(float[] point, int[] Pos) { //deal with the touch-point is out of the cube if( true) { //return false; } if( rx > 0 && rx < 90.f) { } return ROTATE; } public String SetCommand(Command command) { HasCommand = true; this.commands.add(command); this.commandsForward.clear(); this.commandsBack.add(command.Reverse()); if(this.stateListener != null) { stateListener.OnStateNotify(OnStateListener.CANMOVEBACK); stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD); } return command.CmdToCmdStr(); } public void SetForwardCommand(String CmdStr) { //Log.e("cmdstr", CmdStr); this.commandsForward = Reverse(Command.CmdStrsToCmd(CmdStr)); } public String SetCommand(int ColOrRowOrFace, int ID, int Direction) { solved = false; return SetCommand(new Command(ColOrRowOrFace, ID, Direction)); } public boolean IsSolved() { return solved; } public String MoveBack() { if( this.commandsBack.size() <= 0) { return null; } Command command = commandsBack.lastElement(); HasCommand = true; this.commands.add(command); this.commandsBack.remove(this.commandsBack.size()-1); if(this.commandsBack.size() <= 0 && stateListener != null) { stateListener.OnStateNotify(OnStateListener.CANNOTMOVEBACK); } if( solved) { this.commandsAuto.add(command.Reverse()); } else { this.commandsForward.add(command.Reverse()); if(stateListener != null) { stateListener.OnStateNotify(OnStateListener.CANMOVEFORWARD); } } return command.CmdToCmdStr(); } public String MoveForward() { if( this.commandsForward.size() <= 0) { return null; } Command command = commandsForward.lastElement(); HasCommand = true; this.commands.add(command); this.commandsBack.add(command.Reverse()); this.commandsForward.remove(commandsForward.size()-1); if( this.commandsForward.size() <= 0 && stateListener != null) { this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD); } if( this.stateListener != null) { this.stateListener.OnStateNotify(OnStateListener.CANMOVEBACK); } return command.CmdToCmdStr(); } public int MoveForward2() { if( this.commandsForward.size() <= 0) { return 0; } int n = commandsForward.size(); HasCommand = true; this.commands.addAll(Reverse(commandsForward)); for( int i=commandsForward.size()-1; i>=0; i--) { this.commandsBack.add(commandsForward.get(i).Reverse()); } this.commandsForward.clear(); if( this.commandsForward.size() <= 0 && stateListener != null) { this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD); } if( this.stateListener != null) { this.stateListener.OnStateNotify(OnStateListener.CANMOVEBACK); } return n; } public int IsInCubeArea(float []Win) { int[] HitedFaceIndice = new int[6]; int HitNumber = 0; for(int i=0; i<6; i++) { if(IsInQuad3D(magiccube.faces[i], Win)) { HitedFaceIndice[HitNumber] = i; HitNumber++; } } if( HitNumber <=0) { return -1; } else { if( HitNumber == 1) { return HitedFaceIndice[0]; } else //if more than one hitted, then choose the max z-value face as the hitted one { float maxzvalue = -1000.f; int maxzindex = -1; for( int i = 0; i< HitNumber; i++) { float thisz = this.GetCenterZ(magiccube.faces[HitedFaceIndice[i]]); if( thisz > maxzvalue) { maxzvalue = thisz; maxzindex = HitedFaceIndice[i]; } } return maxzindex; } } } private float GetLength2D(float []P1, float []P2) { float dx = P1[0]-P2[0]; float dy = P1[1]-P2[1]; return (float)Math.sqrt(dx*dx + dy*dy); } private boolean IsInQuad3D(Face f, float []Win) { return IsInQuad3D(f.P1, f.P2, f.P3, f.P4, Win); } private boolean IsInQuad3D(float []Point1, float []Point2, float []Point3, float Point4[], float []Win) { float[] Win1 = new float[2]; float[] Win2 = new float[2]; float[] Win3 = new float[2]; float[] Win4 = new float[2]; Project(Point1, Win1); Project(Point2, Win2); Project(Point3, Win3); Project(Point4, Win4); /* Log.e("P1", Win1[0] + " " + Win1[1]); Log.e("P2", Win2[0] + " " + Win2[1]); Log.e("P3", Win3[0] + " " + Win3[1]); Log.e("P4", Win4[0] + " " + Win4[1]);*/ float []WinXY = new float[2]; WinXY[0] = Win[0]; WinXY[1] = this.view_matrix[3] - Win[1]; //Log.e("WinXY", WinXY[0] + " " + WinXY[1]); return IsInQuad2D(Win1, Win2, Win3, Win4, WinXY); } private boolean IsInQuad2D(float []Point1, float []Point2, float []Point3, float Point4[], float []Win) { float angle = 0.f; final float ZERO = 0.0001f; angle += GetAngle(Win, Point1, Point2); //Log.e("angle" , angle + " "); angle += GetAngle(Win, Point2, Point3); //Log.e("angle" , angle + " "); angle += GetAngle(Win, Point3, Point4); //Log.e("angle" , angle + " "); angle += GetAngle(Win, Point4, Point1); //Log.e("angle" , angle + " "); if( Math.abs(angle-Math.PI*2.f) <= ZERO ) { return true; } return false; } public String CalcCommand(float [] From, float [] To, int faceindex) { float [] from = new float[2]; float [] to = new float[2]; float angle, angleVertical, angleHorizon; from[0] = From[0]; from[1] = this.view_matrix[3] - From[1]; to[0] = To[0]; to[1] = this.view_matrix[3] - To[1]; angle = GetAngle(from, to);//(float)Math.atan((to[1]-from[1])/(to[0]-from[0]))/(float)Math.PI*180.f; //calc horizon angle float ObjFrom[] = new float[3]; float ObjTo[] = new float[3]; float WinFrom[] = new float[2]; float WinTo[] = new float[2]; for(int i=0; i<3; i++) { ObjFrom[i] = (magiccube.faces[faceindex].P1[i] + magiccube.faces[faceindex].P4[i])/2.f; ObjTo[i] = (magiccube.faces[faceindex].P2[i] + magiccube.faces[faceindex].P3[i])/2.f; } //Log.e("obj", ObjFrom[0]+" "+ObjFrom[1]+" "+ObjFrom[2]); this.Project(ObjFrom, WinFrom); this.Project(ObjTo, WinTo); angleHorizon = GetAngle(WinFrom, WinTo);//(float)Math.atan((WinTo[1]-WinFrom[1])/(WinTo[0]-WinFrom[0]))/(float)Math.PI*180.f; //calc vertical angle for(int i=0; i<3; i++) { ObjFrom[i] = (magiccube.faces[faceindex].P1[i] + magiccube.faces[faceindex].P2[i])/2.f; ObjTo[i] = (magiccube.faces[faceindex].P3[i] + magiccube.faces[faceindex].P4[i])/2.f; } this.Project(ObjFrom, WinFrom); this.Project(ObjTo, WinTo); angleVertical = GetAngle(WinFrom, WinTo);//(float)Math.atan((WinTo[1]-WinFrom[1])/(WinTo[0]-WinFrom[0]))/(float)Math.PI*180.f; //Log.e("angle", angle +" " + angleHorizon + " " + angleVertical); float dangle = DeltaAngle(angleHorizon, angleVertical); float threshold = Math.min(dangle/2.f, 90.f-dangle/2.f)*0.75f; //this........... if( DeltaAngle(angle, angleHorizon) < threshold || DeltaAngle(angle, (angleHorizon+180.f)%360.f) < threshold) //the direction { if(this.IsInQuad3D(magiccube.faces[faceindex].GetHorizonSubFace(0), From)) { if( faceindex == Face.FRONT) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise); } } else if(faceindex == Face.BACK) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise); } } else if(faceindex == Face.LEFT) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise); } } else if(faceindex == Face.RIGHT) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise); } } else if(faceindex == Face.TOP) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise); } else { return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise); } } else if(faceindex == Face.BOTTOM) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise); } } } else if(this.IsInQuad3D(magiccube.faces[faceindex].GetHorizonSubFace(1), From)) { if( faceindex == Face.FRONT) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise); } } else if( faceindex == Face.BACK) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise); } } else if(faceindex == Face.LEFT) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise); } } else if(faceindex == Face.RIGHT) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise); } } else if(faceindex == Face.TOP) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise); } else { return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise); } } else if(faceindex == Face.BOTTOM) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise); } } } else if(this.IsInQuad3D(magiccube.faces[faceindex].GetHorizonSubFace(2), From)) { if( faceindex == Face.FRONT) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise); } } else if( faceindex == Face.BACK) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise); } } else if(faceindex == Face.LEFT) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise); } } else if(faceindex == Face.RIGHT) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise); } } else if(faceindex == Face.TOP) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise); } else { return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise); } } else if(faceindex == Face.BOTTOM) { if(DeltaAngle(angle, angleHorizon) < threshold) { return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise); } } } } else if( DeltaAngle(angle, angleVertical) < threshold || DeltaAngle(angle, (angleVertical+180.f)%360.f) < threshold) { if(this.IsInQuad3D(magiccube.faces[faceindex].GetVerticalSubFace(0), From)) { if( faceindex == Face.FRONT) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise); } else { return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise); } } else if(faceindex == Face.BACK) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise); } } else if(faceindex == Face.LEFT) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise); } else { return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise); } } else if(faceindex == Face.RIGHT) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise); } } else if(faceindex == Face.TOP) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise); } else { return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise); } } else if(faceindex == Face.BOTTOM) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise); } else { return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise); } } } else if(this.IsInQuad3D(magiccube.faces[faceindex].GetVerticalSubFace(1), From)) { if( faceindex == Face.FRONT) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise); } else { return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise); } } else if(faceindex == Face.BACK) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise); } } else if(faceindex == Face.LEFT) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise); } else { return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise); } } else if(faceindex == Face.RIGHT) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise); } } else if(faceindex == Face.TOP) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise); } else { return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise); } } else if(faceindex == Face.BOTTOM) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise); } else { return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise); } } } else if(this.IsInQuad3D(magiccube.faces[faceindex].GetVerticalSubFace(2), From)) { if( faceindex == Face.FRONT) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise); } else { return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise); } } else if(faceindex == Face.BACK) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise); } } else if(faceindex == Face.LEFT) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise); } else { return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise); } } else if(faceindex == Face.RIGHT) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise); } else { return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise); } } else if(faceindex == Face.TOP) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise); } else { return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise); } } else if(faceindex == Face.BOTTOM) { if(DeltaAngle(angle, angleVertical) < threshold) { return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise); } else { return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise); } } } } return null; } private float GetAngle(float[] From, float[] To) { float angle = (float)Math.atan((To[1]-From[1])/(To[0]-From[0]))/(float)Math.PI*180.f; float dy = To[1]-From[1]; float dx = To[0]-From[0]; if( dy >= 0.f && dx > 0.f) { angle = (float)Math.atan(dy/dx)/(float)Math.PI*180.f; } else if( dx == 0.f) { if( dy > 0.f) { angle = 90.f; } else { angle = 270.f; } } else if( dy >= 0.f && dx < 0.f) { angle = 180.f + (float)Math.atan(dy/dx)/(float)Math.PI*180.f; } else if( dy < 0.f && dx < 0.f) { angle = 180.f + (float)Math.atan(dy/dx)/(float)Math.PI*180.f; } else if(dy <0.f && dx > 0.f) { angle = 360.f + (float)Math.atan(dy/dx)/(float)Math.PI*180.f; } return angle; } private float DeltaAngle(float angle1, float angle2) { float a1 = Math.max(angle1, angle2); float a2 = Math.min(angle1, angle2); float delta = a1 - a2; if( delta >= 180.f ) { delta = 360.f - delta; } return delta; } private float GetCenterZ(Face f) { float zvalue = 0.f; float [] matrix1 = new float[16]; float [] matrix2 = new float[16]; float [] matrix = new float[16]; Matrix.setIdentityM(matrix1, 0); Matrix.setIdentityM(matrix2, 0); Matrix.setIdentityM(matrix, 0); Matrix.rotateM(matrix1, 0, rx, 1, 0, 0); Matrix.rotateM(matrix2, 0, ry, 0, 1, 0); Matrix.multiplyMM(matrix, 0, matrix1, 0, matrix2, 0); float xyz[] = new float[3]; xyz[0] = f.P1[0]; xyz[1] = f.P1[1]; xyz[2] = f.P1[2]; Transform(matrix, xyz); zvalue += xyz[2]; xyz[0] = f.P2[0]; xyz[1] = f.P2[1]; xyz[2] = f.P2[2]; Transform(matrix, xyz); zvalue += xyz[2]; xyz[0] = f.P3[0]; xyz[1] = f.P3[1]; xyz[2] = f.P3[2]; Transform(matrix, xyz); zvalue += xyz[2]; xyz[0] = f.P4[0]; xyz[1] = f.P4[1]; xyz[2] = f.P4[2]; Transform(matrix, xyz); zvalue += xyz[2]; return zvalue/4.f; } private float GetAngle(float []Point0, float []Point1, float[]Point2) { float cos_value = (Point2[0]-Point0[0])*(Point1[0]-Point0[0]) + (Point1[1]-Point0[1])*(Point2[1]-Point0[1]); cos_value /= Math.sqrt((Point2[0]-Point0[0])*(Point2[0]-Point0[0]) + (Point2[1]-Point0[1])*(Point2[1]-Point0[1])) * Math.sqrt((Point1[0]-Point0[0])*(Point1[0]-Point0[0]) + (Point1[1]-Point0[1])*(Point1[1]-Point0[1])); return (float)Math.acos(cos_value); } private void Project(float[] ObjXYZ, float [] WinXY) { float [] matrix1 = new float[16]; float [] matrix2 = new float[16]; float [] matrix = new float[16]; Matrix.setIdentityM(matrix1, 0); Matrix.setIdentityM(matrix2, 0); Matrix.setIdentityM(matrix, 0); Matrix.rotateM(matrix1, 0, rx, 1, 0, 0); Matrix.rotateM(matrix2, 0, ry, 0, 1, 0); Matrix.multiplyMM(matrix, 0, matrix1, 0, matrix2, 0); float xyz[] = new float[3]; xyz[0] = ObjXYZ[0]; xyz[1] = ObjXYZ[1]; xyz[2] = ObjXYZ[2]; Transform(matrix, xyz); //Log.e("xyz", xyz[0] + " " + xyz[1] + " " + xyz[2]); float []Win = new float[3]; GLU.gluProject(xyz[0], xyz[1], xyz[2], mod_matrix, 0, pro_matrix, 0, view_matrix, 0, Win, 0); WinXY[0] = Win[0]; WinXY[1] = Win[1]; } private void Transform(float[]matrix, float[]Point) { float w = 1.f; float x, y, z, ww; x = matrix[0]*Point[0] + matrix[4]*Point[1] + matrix[8]*Point[2] + matrix[12]*w; y = matrix[1]*Point[0] + matrix[5]*Point[1] + matrix[9]*Point[2] + matrix[13]*w; z = matrix[2]*Point[0] + matrix[6]*Point[1] + matrix[10]*Point[2] + matrix[14]*w; ww = matrix[3]*Point[0] + matrix[7]*Point[1] + matrix[11]*Point[2] + matrix[15]*w; Point[0] = x/ww; Point[1] = y/ww; Point[2] = z/ww; } public boolean IsComplete() { boolean r = true; for( int i=0; i<6; i++) { r = r&&magiccube.faces[i].IsSameColor(); } return magiccube.IsComplete(); } public String MessUp(int nStep) { this.solved = false; this.Finished = false; if( this.stateListener != null) { stateListener.OnStateNotify(OnStateListener.CANAUTOSOLVE); } return magiccube.MessUp(nStep); } public void MessUp(String cmdstr) { this.solved = false; magiccube.MessUp(cmdstr); this.Finished = false; if( this.stateListener != null) { stateListener.OnStateNotify(OnStateListener.CANAUTOSOLVE); } } public boolean IsMoveValid(float[]From, float []To) { return this.GetLength2D(From, To) > this.MinMovedist; } public void SetCommands(String cmdStr) { this.commands = Command.CmdStrsToCmd(cmdStr); this.HasCommand = true; } public String SetCommand(String cmdStr) { return SetCommand(Command.CmdStrToCmd(cmdStr)); } public void AutoSolve(String SolverName) { if( !solved) { MagicCubeSolver solver = SolverFactory.CreateSolver(SolverName); if(solver == null) { return; } //Log.e("state", this.GetState()); String SolveCmd = solver.AutoSolve(magiccube.GetState()); //Log.e("solve", SolveCmd); this.commands.clear(); this.commandsBack.clear(); this.commandsForward.clear(); if( this.stateListener != null) { this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEBACK); this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD); } this.commandsAuto = Reverse(Command.CmdStrsToCmd(SolveCmd)); this.solved = true; } else if(commandsAuto.size() > 0) { Command command = commandsAuto.lastElement(); HasCommand = true; this.commands.add(command); this.commandsBack.add(command.Reverse()); this.commandsAuto.remove(commandsAuto.size()-1); if( this.stateListener != null) { this.stateListener.OnStateNotify(OnStateListener.CANMOVEBACK); } } } public void AutoSolve2(String SolverName) { if( !solved) { MagicCubeSolver solver = SolverFactory.CreateSolver(SolverName); if(solver == null) { return; } //Log.e("state", this.GetState()); String SolveCmd = solver.AutoSolve(magiccube.GetState()); //Log.e("solve", SolveCmd); this.commands.clear(); this.commandsBack.clear(); this.commandsForward.clear(); this.commands = Command.CmdStrsToCmd(SolveCmd); for( int i=0; i<commands.size(); i++) { commandsBack.add(commands.get(i).Reverse()); } this.HasCommand = true; this.solved = true; } else { commands.addAll(Reverse(commandsAuto)); for( int i=commandsAuto.size()-1; i>=0; i--) { commandsBack.add(commandsAuto.get(i).Reverse()); } commandsAuto.clear(); HasCommand = true; } }<|fim▁hole|> { if( !solved) { MagicCubeSolver solver = SolverFactory.CreateSolver(SolverName); if(solver == null) { return; } //Log.e("state", this.GetState()); String SolveCmd = solver.AutoSolve(magiccube.GetState()); //Log.e("solve", SolveCmd); this.commands.clear(); this.commandsBack.clear(); this.commandsForward.clear(); this.commands = Command.CmdStrsToCmd(SolveCmd); commands.remove(commands.size()-1); commands.remove(commands.size()-1); for( int i=0; i<commands.size(); i++) { commandsBack.add(commands.get(i).Reverse()); } this.HasCommand = true; this.solved = true; } else { commands.addAll(Reverse(commandsAuto)); for( int i=commandsAuto.size()-1; i>=0; i--) { commandsBack.add(commandsAuto.get(i).Reverse()); } commandsAuto.clear(); HasCommand = true; } } private Vector<Command> Reverse(Vector<Command> v) { Vector<Command> v2 = new Vector<Command>(v.size()); for(int i=v.size()-1; i>=0; i--) { v2.add(v.elementAt(i)); } return v2; } public void Reset() { Resetting = true; reset(); } private void reset() { this.rx = 22.f; this.ry = -34.f; this.HasCommand = false; Finished = false; this.CommandLoop = 0; this.commands.clear(); this.commandsBack.clear(); this.commandsForward.clear(); this.CmdStrAfter = ""; this.CmdStrBefore = ""; magiccube.Reset(); if( this.stateListener != null) { this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEBACK); this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD); this.stateListener.OnStateNotify(OnStateListener.CANNOTAUTOSOLVE); } } public String GetCmdStrBefore() { return this.CmdStrBefore; } public void SetCmdStrBefore(String CmdStrBefore) { this.CmdStrBefore = CmdStrBefore; } public void SetCmdStrAfter(String CmdStrAfter) { this.CmdStrAfter = CmdStrAfter; } public String GetCmdStrAfter() { return this.CmdStrAfter; } public void setVolume(int volume) { this.volume = volume; } }<|fim▁end|>
public void AutoSolve3(String SolverName)
<|file_name|>testmodule.py<|end_file_name|><|fim▁begin|>import time from Rpyc import Async def threadfunc(callback): """this function will call the callback every second""" callback = Async(callback)<|fim▁hole|> try: while True: print "!" callback() time.sleep(1) except: print "thread exiting" def printer(text): print text def caller(func, *args): func(*args)<|fim▁end|>
<|file_name|>process_thread_impl.cc<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/utility/source/process_thread_impl.h" #include "webrtc/base/checks.h" #include "webrtc/modules/interface/module.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/tick_util.h" namespace webrtc { namespace { // We use this constant internally to signal that a module has requested // a callback right away. When this is set, no call to TimeUntilNextProcess // should be made, but Process() should be called directly. const int64_t kCallProcessImmediately = -1; int64_t GetNextCallbackTime(Module* module, int64_t time_now) { int64_t interval = module->TimeUntilNextProcess(); // Currently some implementations erroneously return error codes from // TimeUntilNextProcess(). So, as is, we correct that and log an error. if (interval < 0) { LOG(LS_ERROR) << "TimeUntilNextProcess returned an invalid value " << interval; interval = 0; } return time_now + interval; } } ProcessThread::~ProcessThread() {} // static rtc::scoped_ptr<ProcessThread> ProcessThread::Create() { return rtc::scoped_ptr<ProcessThread>(new ProcessThreadImpl()).Pass(); } ProcessThreadImpl::ProcessThreadImpl() : wake_up_(EventWrapper::Create()), stop_(false) { } ProcessThreadImpl::~ProcessThreadImpl() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!thread_.get()); DCHECK(!stop_); while (!queue_.empty()) { delete queue_.front(); queue_.pop(); } } void ProcessThreadImpl::Start() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!thread_.get()); if (thread_.get()) return; DCHECK(!stop_); { // TODO(tommi): Since DeRegisterModule is currently being called from // different threads in some cases (ChannelOwner), we need to lock access to // the modules_ collection even on the controller thread. // Once we've cleaned up those places, we can remove this lock. rtc::CritScope lock(&lock_); for (ModuleCallback& m : modules_) m.module->ProcessThreadAttached(this); } thread_ = ThreadWrapper::CreateThread( &ProcessThreadImpl::Run, this, "ProcessThread"); CHECK(thread_->Start()); } void ProcessThreadImpl::Stop() { DCHECK(thread_checker_.CalledOnValidThread()); if(!thread_.get()) return; { rtc::CritScope lock(&lock_); stop_ = true; } wake_up_->Set(); CHECK(thread_->Stop()); stop_ = false; // TODO(tommi): Since DeRegisterModule is currently being called from // different threads in some cases (ChannelOwner), we need to lock access to // the modules_ collection even on the controller thread. // Since DeRegisterModule also checks thread_, we also need to hold the // lock for the .reset() operation. // Once we've cleaned up those places, we can remove this lock. rtc::CritScope lock(&lock_); thread_.reset(); for (ModuleCallback& m : modules_) m.module->ProcessThreadAttached(nullptr); } void ProcessThreadImpl::WakeUp(Module* module) { // Allowed to be called on any thread. { rtc::CritScope lock(&lock_); for (ModuleCallback& m : modules_) { if (m.module == module) m.next_callback = kCallProcessImmediately; } } wake_up_->Set(); } void ProcessThreadImpl::PostTask(rtc::scoped_ptr<ProcessTask> task) { // Allowed to be called on any thread. { rtc::CritScope lock(&lock_); queue_.push(task.release()); } wake_up_->Set(); } void ProcessThreadImpl::RegisterModule(Module* module) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(module); #if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)) { // Catch programmer error. rtc::CritScope lock(&lock_); for (const ModuleCallback& mc : modules_) DCHECK(mc.module != module); } #endif // Now that we know the module isn't in the list, we'll call out to notify // the module that it's attached to the worker thread. We don't hold // the lock while we make this call. if (thread_.get()) module->ProcessThreadAttached(this); { rtc::CritScope lock(&lock_); modules_.push_back(ModuleCallback(module));<|fim▁hole|> // shorter than all other registered modules. wake_up_->Set(); } void ProcessThreadImpl::DeRegisterModule(Module* module) { // Allowed to be called on any thread. // TODO(tommi): Disallow this ^^^ DCHECK(module); { rtc::CritScope lock(&lock_); modules_.remove_if([&module](const ModuleCallback& m) { return m.module == module; }); // TODO(tommi): we currently need to hold the lock while calling out to // ProcessThreadAttached. This is to make sure that the thread hasn't been // destroyed while we attach the module. Once we can make sure // DeRegisterModule isn't being called on arbitrary threads, we can move the // |if (thread_.get())| check and ProcessThreadAttached() call outside the // lock scope. // Notify the module that it's been detached. if (thread_.get()) module->ProcessThreadAttached(nullptr); } } // static bool ProcessThreadImpl::Run(void* obj) { return static_cast<ProcessThreadImpl*>(obj)->Process(); } bool ProcessThreadImpl::Process() { int64_t now = TickTime::MillisecondTimestamp(); int64_t next_checkpoint = now + (1000 * 60); { rtc::CritScope lock(&lock_); if (stop_) return false; for (ModuleCallback& m : modules_) { // TODO(tommi): Would be good to measure the time TimeUntilNextProcess // takes and dcheck if it takes too long (e.g. >=10ms). Ideally this // operation should not require taking a lock, so querying all modules // should run in a matter of nanoseconds. if (m.next_callback == 0) m.next_callback = GetNextCallbackTime(m.module, now); if (m.next_callback <= now || m.next_callback == kCallProcessImmediately) { m.module->Process(); // Use a new 'now' reference to calculate when the next callback // should occur. We'll continue to use 'now' above for the baseline // of calculating how long we should wait, to reduce variance. int64_t new_now = TickTime::MillisecondTimestamp(); m.next_callback = GetNextCallbackTime(m.module, new_now); } if (m.next_callback < next_checkpoint) next_checkpoint = m.next_callback; } while (!queue_.empty()) { ProcessTask* task = queue_.front(); queue_.pop(); lock_.Leave(); task->Run(); delete task; lock_.Enter(); } } int64_t time_to_wait = next_checkpoint - TickTime::MillisecondTimestamp(); if (time_to_wait > 0) wake_up_->Wait(static_cast<unsigned long>(time_to_wait)); return true; } } // namespace webrtc<|fim▁end|>
} // Wake the thread calling ProcessThreadImpl::Process() to update the // waiting time. The waiting time for the just registered module may be
<|file_name|>IntNode.java<|end_file_name|><|fim▁begin|>package com.fasterxml.jackson.databind.node; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.io.NumberOutput; import com.fasterxml.jackson.databind.SerializerProvider; /** * Numeric node that contains simple 32-bit integer values. */ @SuppressWarnings("serial") public class IntNode extends NumericNode { // // // Let's cache small set of common value final static int MIN_CANONICAL = -1; final static int MAX_CANONICAL = 10; private final static IntNode[] CANONICALS; static { int count = MAX_CANONICAL - MIN_CANONICAL + 1; CANONICALS = new IntNode[count]; for (int i = 0; i < count; ++i) { CANONICALS[i] = new IntNode(MIN_CANONICAL + i); } } /** * Integer value this node contains */ protected final int _value; /* ************************************************ * Construction ************************************************ */ public IntNode(int v) { _value = v; } public static IntNode valueOf(int i) { if (i > MAX_CANONICAL || i < MIN_CANONICAL) return new IntNode(i); return CANONICALS[i - MIN_CANONICAL]; } /* /********************************************************** /* BaseJsonNode extended API /********************************************************** */ @Override public JsonToken asToken() { return JsonToken.VALUE_NUMBER_INT; } @Override public JsonParser.NumberType numberType() { return JsonParser.NumberType.INT; } /* /********************************************************** /* Overrridden JsonNode methods /********************************************************** */ @Override public boolean isIntegralNumber() { return true; } @Override public boolean isInt() { return true; } @Override public boolean canConvertToInt() { return true; } @Override public boolean canConvertToLong() { return true; }<|fim▁hole|> @Override public Number numberValue() { return Integer.valueOf(_value); } @Override public short shortValue() { return (short) _value; } @Override public int intValue() { return _value; } @Override public long longValue() { return (long) _value; } @Override public float floatValue() { return (float) _value; } @Override public double doubleValue() { return (double) _value; } @Override public BigDecimal decimalValue() { return BigDecimal.valueOf(_value); } @Override public BigInteger bigIntegerValue() { return BigInteger.valueOf(_value); } @Override public String asText() { return NumberOutput.toString(_value); } @Override public boolean asBoolean(boolean defaultValue) { return _value != 0; } @Override public final void serialize(JsonGenerator g, SerializerProvider provider) throws IOException { g.writeNumber(_value); } @Override public boolean equals(Object o) { if (o == this) return true; if (o == null) return false; if (o instanceof IntNode) { return ((IntNode) o)._value == _value; } return false; } @Override public int hashCode() { return _value; } }<|fim▁end|>
<|file_name|>index.py<|end_file_name|><|fim▁begin|>"""Routines related to PyPI, indexes""" import sys import os import re import mimetypes import posixpath <|fim▁hole|>from pip.exceptions import (DistributionNotFound, BestVersionAlreadyInstalled, InstallationError, InvalidWheelFilename, UnsupportedWheel) from pip.backwardcompat import urlparse, url2pathname from pip.download import PipSession, url_to_path, path_to_url from pip.wheel import Wheel, wheel_ext from pip.pep425tags import supported_tags, supported_tags_noarch, get_platform from pip._vendor import html5lib, requests, pkg_resources from pip._vendor.requests.exceptions import SSLError __all__ = ['PackageFinder'] DEFAULT_MIRROR_HOSTNAME = "last.pypi.python.org" INSECURE_SCHEMES = { "http": ["https"], } class PackageFinder(object): """This finds packages. This is meant to match easy_install's technique for looking for packages, by reading pages and looking for appropriate links """ def __init__(self, find_links, index_urls, use_wheel=True, allow_external=[], allow_unverified=[], allow_all_external=False, allow_all_prereleases=False, process_dependency_links=False, session=None): self.find_links = find_links self.index_urls = index_urls self.dependency_links = [] self.cache = PageCache() # These are boring links that have already been logged somehow: self.logged_links = set() self.use_wheel = use_wheel # Do we allow (safe and verifiable) externally hosted files? self.allow_external = set(normalize_name(n) for n in allow_external) # Which names are allowed to install insecure and unverifiable files? self.allow_unverified = set( normalize_name(n) for n in allow_unverified ) # Anything that is allowed unverified is also allowed external self.allow_external |= self.allow_unverified # Do we allow all (safe and verifiable) externally hosted files? self.allow_all_external = allow_all_external # Stores if we ignored any external links so that we can instruct # end users how to install them if no distributions are available self.need_warn_external = False # Stores if we ignored any unsafe links so that we can instruct # end users how to install them if no distributions are available self.need_warn_unverified = False # Do we want to allow _all_ pre-releases? self.allow_all_prereleases = allow_all_prereleases # Do we process dependency links? self.process_dependency_links = process_dependency_links self._have_warned_dependency_links = False # The Session we'll use to make requests self.session = session or PipSession() def add_dependency_links(self, links): ## FIXME: this shouldn't be global list this, it should only ## apply to requirements of the package that specifies the ## dependency_links value ## FIXME: also, we should track comes_from (i.e., use Link) if self.process_dependency_links: if not self._have_warned_dependency_links: logger.deprecated( "1.6", "Dependency Links processing has been deprecated with an " "accelerated time schedule and will be removed in pip 1.6", ) self._have_warned_dependency_links = True self.dependency_links.extend(links) def _sort_locations(self, locations): """ Sort locations into "files" (archives) and "urls", and return a pair of lists (files,urls) """ files = [] urls = [] # puts the url for the given file path into the appropriate list def sort_path(path): url = path_to_url(path) if mimetypes.guess_type(url, strict=False)[0] == 'text/html': urls.append(url) else: files.append(url) for url in locations: is_local_path = os.path.exists(url) is_file_url = url.startswith('file:') is_find_link = url in self.find_links if is_local_path or is_file_url: if is_local_path: path = url else: path = url_to_path(url) if is_find_link and os.path.isdir(path): path = os.path.realpath(path) for item in os.listdir(path): sort_path(os.path.join(path, item)) elif is_file_url and os.path.isdir(path): urls.append(url) elif os.path.isfile(path): sort_path(path) else: urls.append(url) return files, urls def _link_sort_key(self, link_tuple): """ Function used to generate link sort key for link tuples. The greater the return value, the more preferred it is. If not finding wheels, then sorted by version only. If finding wheels, then the sort order is by version, then: 1. existing installs 2. wheels ordered via Wheel.support_index_min() 3. source archives Note: it was considered to embed this logic into the Link comparison operators, but then different sdist links with the same version, would have to be considered equal """ parsed_version, link, _ = link_tuple if self.use_wheel: support_num = len(supported_tags) if link == INSTALLED_VERSION: pri = 1 elif link.ext == wheel_ext: wheel = Wheel(link.filename) # can raise InvalidWheelFilename if not wheel.supported(): raise UnsupportedWheel("%s is not a supported wheel for this platform. It can't be sorted." % wheel.filename) pri = -(wheel.support_index_min()) else: # sdist pri = -(support_num) return (parsed_version, pri) else: return parsed_version def _sort_versions(self, applicable_versions): """ Bring the latest version (and wheels) to the front, but maintain the existing ordering as secondary. See the docstring for `_link_sort_key` for details. This function is isolated for easier unit testing. """ return sorted(applicable_versions, key=self._link_sort_key, reverse=True) def find_requirement(self, req, upgrade): def mkurl_pypi_url(url): loc = posixpath.join(url, url_name) # For maximum compatibility with easy_install, ensure the path # ends in a trailing slash. Although this isn't in the spec # (and PyPI can handle it without the slash) some other index # implementations might break if they relied on easy_install's behavior. if not loc.endswith('/'): loc = loc + '/' return loc url_name = req.url_name # Only check main index if index URL is given: main_index_url = None if self.index_urls: # Check that we have the url_name correctly spelled: main_index_url = Link(mkurl_pypi_url(self.index_urls[0]), trusted=True) # This will also cache the page, so it's okay that we get it again later: page = self._get_page(main_index_url, req) if page is None: url_name = self._find_url_name(Link(self.index_urls[0], trusted=True), url_name, req) or req.url_name if url_name is not None: locations = [ mkurl_pypi_url(url) for url in self.index_urls] + self.find_links else: locations = list(self.find_links) for version in req.absolute_versions: if url_name is not None and main_index_url is not None: locations = [ posixpath.join(main_index_url.url, version)] + locations file_locations, url_locations = self._sort_locations(locations) _flocations, _ulocations = self._sort_locations(self.dependency_links) file_locations.extend(_flocations) # We trust every url that the user has given us whether it was given # via --index-url or --find-links locations = [Link(url, trusted=True) for url in url_locations] # We explicitly do not trust links that came from dependency_links locations.extend([Link(url) for url in _ulocations]) logger.debug('URLs to search for versions for %s:' % req) for location in locations: logger.debug('* %s' % location) # Determine if this url used a secure transport mechanism parsed = urlparse.urlparse(str(location)) if parsed.scheme in INSECURE_SCHEMES: secure_schemes = INSECURE_SCHEMES[parsed.scheme] if len(secure_schemes) == 1: ctx = (location, parsed.scheme, secure_schemes[0], parsed.netloc) logger.warn("%s uses an insecure transport scheme (%s). " "Consider using %s if %s has it available" % ctx) elif len(secure_schemes) > 1: ctx = (location, parsed.scheme, ", ".join(secure_schemes), parsed.netloc) logger.warn("%s uses an insecure transport scheme (%s). " "Consider using one of %s if %s has any of " "them available" % ctx) else: ctx = (location, parsed.scheme) logger.warn("%s uses an insecure transport scheme (%s)." % ctx) found_versions = [] found_versions.extend( self._package_versions( # We trust every directly linked archive in find_links [Link(url, '-f', trusted=True) for url in self.find_links], req.name.lower())) page_versions = [] for page in self._get_pages(locations, req): logger.debug('Analyzing links from page %s' % page.url) logger.indent += 2 try: page_versions.extend(self._package_versions(page.links, req.name.lower())) finally: logger.indent -= 2 dependency_versions = list(self._package_versions( [Link(url) for url in self.dependency_links], req.name.lower())) if dependency_versions: logger.info('dependency_links found: %s' % ', '.join([link.url for parsed, link, version in dependency_versions])) file_versions = list(self._package_versions( [Link(url) for url in file_locations], req.name.lower())) if not found_versions and not page_versions and not dependency_versions and not file_versions: logger.fatal('Could not find any downloads that satisfy the requirement %s' % req) if self.need_warn_external: logger.warn("Some externally hosted files were ignored (use " "--allow-external %s to allow)." % req.name) if self.need_warn_unverified: logger.warn("Some insecure and unverifiable files were ignored" " (use --allow-unverified %s to allow)." % req.name) raise DistributionNotFound('No distributions at all found for %s' % req) installed_version = [] if req.satisfied_by is not None: installed_version = [(req.satisfied_by.parsed_version, INSTALLED_VERSION, req.satisfied_by.version)] if file_versions: file_versions.sort(reverse=True) logger.info('Local files found: %s' % ', '.join([url_to_path(link.url) for parsed, link, version in file_versions])) #this is an intentional priority ordering all_versions = installed_version + file_versions + found_versions + page_versions + dependency_versions applicable_versions = [] for (parsed_version, link, version) in all_versions: if version not in req.req: logger.info("Ignoring link %s, version %s doesn't match %s" % (link, version, ','.join([''.join(s) for s in req.req.specs]))) continue elif is_prerelease(version) and not (self.allow_all_prereleases or req.prereleases): # If this version isn't the already installed one, then # ignore it if it's a pre-release. if link is not INSTALLED_VERSION: logger.info("Ignoring link %s, version %s is a pre-release (use --pre to allow)." % (link, version)) continue applicable_versions.append((parsed_version, link, version)) applicable_versions = self._sort_versions(applicable_versions) existing_applicable = bool([link for parsed_version, link, version in applicable_versions if link is INSTALLED_VERSION]) if not upgrade and existing_applicable: if applicable_versions[0][1] is INSTALLED_VERSION: logger.info('Existing installed version (%s) is most up-to-date and satisfies requirement' % req.satisfied_by.version) else: logger.info('Existing installed version (%s) satisfies requirement (most up-to-date version is %s)' % (req.satisfied_by.version, applicable_versions[0][2])) return None if not applicable_versions: logger.fatal('Could not find a version that satisfies the requirement %s (from versions: %s)' % (req, ', '.join([version for parsed_version, link, version in all_versions]))) if self.need_warn_external: logger.warn("Some externally hosted files were ignored (use " "--allow-external to allow).") if self.need_warn_unverified: logger.warn("Some insecure and unverifiable files were ignored" " (use --allow-unverified %s to allow)." % req.name) raise DistributionNotFound('No distributions matching the version for %s' % req) if applicable_versions[0][1] is INSTALLED_VERSION: # We have an existing version, and its the best version logger.info('Installed version (%s) is most up-to-date (past versions: %s)' % (req.satisfied_by.version, ', '.join([version for parsed_version, link, version in applicable_versions[1:]]) or 'none')) raise BestVersionAlreadyInstalled if len(applicable_versions) > 1: logger.info('Using version %s (newest of versions: %s)' % (applicable_versions[0][2], ', '.join([version for parsed_version, link, version in applicable_versions]))) selected_version = applicable_versions[0][1] if (selected_version.internal is not None and not selected_version.internal): logger.warn("%s an externally hosted file and may be " "unreliable" % req.name) if (selected_version.verifiable is not None and not selected_version.verifiable): logger.warn("%s is potentially insecure and " "unverifiable." % req.name) if selected_version._deprecated_regex: logger.deprecated( "1.7", "%s discovered using a deprecated method of parsing, " "in the future it will no longer be discovered" % req.name ) return selected_version def _find_url_name(self, index_url, url_name, req): """Finds the true URL name of a package, when the given name isn't quite correct. This is usually used to implement case-insensitivity.""" if not index_url.url.endswith('/'): # Vaguely part of the PyPI API... weird but true. ## FIXME: bad to modify this? index_url.url += '/' page = self._get_page(index_url, req) if page is None: logger.fatal('Cannot fetch index base URL %s' % index_url) return norm_name = normalize_name(req.url_name) for link in page.links: base = posixpath.basename(link.path.rstrip('/')) if norm_name == normalize_name(base): logger.notify('Real name of requirement %s is %s' % (url_name, base)) return base return None def _get_pages(self, locations, req): """ Yields (page, page_url) from the given locations, skipping locations that have errors, and adding download/homepage links """ all_locations = list(locations) seen = set() while all_locations: location = all_locations.pop(0) if location in seen: continue seen.add(location) page = self._get_page(location, req) if page is None: continue yield page for link in page.rel_links(): normalized = normalize_name(req.name).lower() if (not normalized in self.allow_external and not self.allow_all_external): self.need_warn_external = True logger.debug("Not searching %s for files because external " "urls are disallowed." % link) continue if (link.trusted is not None and not link.trusted and not normalized in self.allow_unverified): logger.debug("Not searching %s for urls, it is an " "untrusted link and cannot produce safe or " "verifiable files." % link) self.need_warn_unverified = True continue all_locations.append(link) _egg_fragment_re = re.compile(r'#egg=([^&]*)') _egg_info_re = re.compile(r'([a-z0-9_.]+)-([a-z0-9_.-]+)', re.I) _py_version_re = re.compile(r'-py([123]\.?[0-9]?)$') def _sort_links(self, links): "Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates" eggs, no_eggs = [], [] seen = set() for link in links: if link not in seen: seen.add(link) if link.egg_fragment: eggs.append(link) else: no_eggs.append(link) return no_eggs + eggs def _package_versions(self, links, search_name): for link in self._sort_links(links): for v in self._link_package_versions(link, search_name): yield v def _known_extensions(self): extensions = ('.tar.gz', '.tar.bz2', '.tar', '.tgz', '.zip') if self.use_wheel: return extensions + (wheel_ext,) return extensions def _link_package_versions(self, link, search_name): """ Return an iterable of triples (pkg_resources_version_key, link, python_version) that can be extracted from the given link. Meant to be overridden by subclasses, not called by clients. """ platform = get_platform() version = None if link.egg_fragment: egg_info = link.egg_fragment else: egg_info, ext = link.splitext() if not ext: if link not in self.logged_links: logger.debug('Skipping link %s; not a file' % link) self.logged_links.add(link) return [] if egg_info.endswith('.tar'): # Special double-extension case: egg_info = egg_info[:-4] ext = '.tar' + ext if ext not in self._known_extensions(): if link not in self.logged_links: logger.debug('Skipping link %s; unknown archive format: %s' % (link, ext)) self.logged_links.add(link) return [] if "macosx10" in link.path and ext == '.zip': if link not in self.logged_links: logger.debug('Skipping link %s; macosx10 one' % (link)) self.logged_links.add(link) return [] if ext == wheel_ext: try: wheel = Wheel(link.filename) except InvalidWheelFilename: logger.debug('Skipping %s because the wheel filename is invalid' % link) return [] if wheel.name.lower() != search_name.lower(): logger.debug('Skipping link %s; wrong project name (not %s)' % (link, search_name)) return [] if not wheel.supported(): logger.debug('Skipping %s because it is not compatible with this Python' % link) return [] # This is a dirty hack to prevent installing Binary Wheels from # PyPI unless it is a Windows or Mac Binary Wheel. This is # paired with a change to PyPI disabling uploads for the # same. Once we have a mechanism for enabling support for binary # wheels on linux that deals with the inherent problems of # binary distribution this can be removed. comes_from = getattr(link, "comes_from", None) if (( not platform.startswith('win') and not platform.startswith('macosx') ) and comes_from is not None and urlparse.urlparse(comes_from.url).netloc.endswith( "pypi.python.org")): if not wheel.supported(tags=supported_tags_noarch): logger.debug( "Skipping %s because it is a pypi-hosted binary " "Wheel on an unsupported platform" % link ) return [] version = wheel.version if not version: version = self._egg_info_matches(egg_info, search_name, link) if version is None: logger.debug('Skipping link %s; wrong project name (not %s)' % (link, search_name)) return [] if (link.internal is not None and not link.internal and not normalize_name(search_name).lower() in self.allow_external and not self.allow_all_external): # We have a link that we are sure is external, so we should skip # it unless we are allowing externals logger.debug("Skipping %s because it is externally hosted." % link) self.need_warn_external = True return [] if (link.verifiable is not None and not link.verifiable and not (normalize_name(search_name).lower() in self.allow_unverified)): # We have a link that we are sure we cannot verify it's integrity, # so we should skip it unless we are allowing unsafe installs # for this requirement. logger.debug("Skipping %s because it is an insecure and " "unverifiable file." % link) self.need_warn_unverified = True return [] match = self._py_version_re.search(version) if match: version = version[:match.start()] py_version = match.group(1) if py_version != sys.version[:3]: logger.debug('Skipping %s because Python version is incorrect' % link) return [] logger.debug('Found link %s, version: %s' % (link, version)) return [(pkg_resources.parse_version(version), link, version)] def _egg_info_matches(self, egg_info, search_name, link): match = self._egg_info_re.search(egg_info) if not match: logger.debug('Could not parse version from link: %s' % link) return None name = match.group(0).lower() # To match the "safe" name that pkg_resources creates: name = name.replace('_', '-') # project name and version must be separated by a dash look_for = search_name.lower() + "-" if name.startswith(look_for): return match.group(0)[len(look_for):] else: return None def _get_page(self, link, req): return HTMLPage.get_page(link, req, cache=self.cache, session=self.session, ) class PageCache(object): """Cache of HTML pages""" failure_limit = 3 def __init__(self): self._failures = {} self._pages = {} self._archives = {} def too_many_failures(self, url): return self._failures.get(url, 0) >= self.failure_limit def get_page(self, url): return self._pages.get(url) def is_archive(self, url): return self._archives.get(url, False) def set_is_archive(self, url, value=True): self._archives[url] = value def add_page_failure(self, url, level): self._failures[url] = self._failures.get(url, 0)+level def add_page(self, urls, page): for url in urls: self._pages[url] = page class HTMLPage(object): """Represents one page, along with its URL""" ## FIXME: these regexes are horrible hacks: _homepage_re = re.compile(r'<th>\s*home.html\s*page', re.I) _download_re = re.compile(r'<th>\s*download\s+url', re.I) _href_re = re.compile('href=(?:"([^"]*)"|\'([^\']*)\'|([^>\\s\\n]*))', re.I|re.S) def __init__(self, content, url, headers=None, trusted=None): self.content = content self.parsed = html5lib.parse(self.content, namespaceHTMLElements=False) self.url = url self.headers = headers self.trusted = trusted def __str__(self): return self.url @classmethod def get_page(cls, link, req, cache=None, skip_archives=True, session=None): if session is None: session = PipSession() url = link.url url = url.split('#', 1)[0] if cache.too_many_failures(url): return None # Check for VCS schemes that do not support lookup as web pages. from pip.vcs import VcsSupport for scheme in VcsSupport.schemes: if url.lower().startswith(scheme) and url[len(scheme)] in '+:': logger.debug('Cannot look at %(scheme)s URL %(link)s' % locals()) return None if cache is not None: inst = cache.get_page(url) if inst is not None: return inst try: if skip_archives: if cache is not None: if cache.is_archive(url): return None filename = link.filename for bad_ext in ['.tar', '.tar.gz', '.tar.bz2', '.tgz', '.zip']: if filename.endswith(bad_ext): content_type = cls._get_content_type(url, session=session, ) if content_type.lower().startswith('text/html'): break else: logger.debug('Skipping page %s because of Content-Type: %s' % (link, content_type)) if cache is not None: cache.set_is_archive(url) return None logger.debug('Getting page %s' % url) # Tack index.html onto file:// URLs that point to directories (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url) if scheme == 'file' and os.path.isdir(url2pathname(path)): # add trailing slash if not present so urljoin doesn't trim final segment if not url.endswith('/'): url += '/' url = urlparse.urljoin(url, 'index.html') logger.debug(' file: URL is directory, getting %s' % url) resp = session.get(url, headers={"Accept": "text/html"}) resp.raise_for_status() # The check for archives above only works if the url ends with # something that looks like an archive. However that is not a # requirement. For instance http://sourceforge.net/projects/docutils/files/docutils/0.8.1/docutils-0.8.1.tar.gz/download # redirects to http://superb-dca3.dl.sourceforge.net/project/docutils/docutils/0.8.1/docutils-0.8.1.tar.gz # Unless we issue a HEAD request on every url we cannot know # ahead of time for sure if something is HTML or not. However we # can check after we've downloaded it. content_type = resp.headers.get('Content-Type', 'unknown') if not content_type.lower().startswith("text/html"): logger.debug('Skipping page %s because of Content-Type: %s' % (link, content_type)) if cache is not None: cache.set_is_archive(url) return None inst = cls(resp.text, resp.url, resp.headers, trusted=link.trusted) except requests.HTTPError as exc: level = 2 if exc.response.status_code == 404 else 1 cls._handle_fail(req, link, exc, url, cache=cache, level=level) except requests.ConnectionError as exc: cls._handle_fail( req, link, "connection error: %s" % exc, url, cache=cache, ) except requests.Timeout: cls._handle_fail(req, link, "timed out", url, cache=cache) except SSLError as exc: reason = ("There was a problem confirming the ssl certificate: " "%s" % exc) cls._handle_fail(req, link, reason, url, cache=cache, level=2, meth=logger.notify, ) else: if cache is not None: cache.add_page([url, resp.url], inst) return inst @staticmethod def _handle_fail(req, link, reason, url, cache=None, level=1, meth=None): if meth is None: meth = logger.info meth("Could not fetch URL %s: %s", link, reason) meth("Will skip URL %s when looking for download links for %s" % (link.url, req)) if cache is not None: cache.add_page_failure(url, level) @staticmethod def _get_content_type(url, session=None): """Get the Content-Type of the given url, using a HEAD request""" if session is None: session = PipSession() scheme, netloc, path, query, fragment = urlparse.urlsplit(url) if not scheme in ('http', 'https', 'ftp', 'ftps'): ## FIXME: some warning or something? ## assertion error? return '' resp = session.head(url, allow_redirects=True) resp.raise_for_status() return resp.headers.get("Content-Type", "") @property def api_version(self): if not hasattr(self, "_api_version"): _api_version = None metas = [x for x in self.parsed.findall(".//meta") if x.get("name", "").lower() == "api-version"] if metas: try: _api_version = int(metas[0].get("value", None)) except (TypeError, ValueError): _api_version = None self._api_version = _api_version return self._api_version @property def base_url(self): if not hasattr(self, "_base_url"): base = self.parsed.find(".//base") if base is not None and base.get("href"): self._base_url = base.get("href") else: self._base_url = self.url return self._base_url @property def links(self): """Yields all links in the page""" for anchor in self.parsed.findall(".//a"): if anchor.get("href"): href = anchor.get("href") url = self.clean_link(urlparse.urljoin(self.base_url, href)) # Determine if this link is internal. If that distinction # doesn't make sense in this context, then we don't make # any distinction. internal = None if self.api_version and self.api_version >= 2: # Only api_versions >= 2 have a distinction between # external and internal links internal = bool(anchor.get("rel") and "internal" in anchor.get("rel").split()) yield Link(url, self, internal=internal) def rel_links(self): for url in self.explicit_rel_links(): yield url for url in self.scraped_rel_links(): yield url def explicit_rel_links(self, rels=('homepage', 'download')): """Yields all links with the given relations""" rels = set(rels) for anchor in self.parsed.findall(".//a"): if anchor.get("rel") and anchor.get("href"): found_rels = set(anchor.get("rel").split()) # Determine the intersection between what rels were found and # what rels were being looked for if found_rels & rels: href = anchor.get("href") url = self.clean_link(urlparse.urljoin(self.base_url, href)) yield Link(url, self, trusted=False) def scraped_rel_links(self): # Can we get rid of this horrible horrible method? for regex in (self._homepage_re, self._download_re): match = regex.search(self.content) if not match: continue href_match = self._href_re.search(self.content, pos=match.end()) if not href_match: continue url = href_match.group(1) or href_match.group(2) or href_match.group(3) if not url: continue url = self.clean_link(urlparse.urljoin(self.base_url, url)) yield Link(url, self, trusted=False, _deprecated_regex=True) _clean_re = re.compile(r'[^a-z0-9$&+,/:;=?@.#%_\\|-]', re.I) def clean_link(self, url): """Makes sure a link is fully encoded. That is, if a ' ' shows up in the link, it will be rewritten to %20 (while not over-quoting % or other characters).""" return self._clean_re.sub( lambda match: '%%%2x' % ord(match.group(0)), url) class Link(object): def __init__(self, url, comes_from=None, internal=None, trusted=None, _deprecated_regex=False): self.url = url self.comes_from = comes_from self.internal = internal self.trusted = trusted self._deprecated_regex = _deprecated_regex def __str__(self): if self.comes_from: return '%s (from %s)' % (self.url, self.comes_from) else: return str(self.url) def __repr__(self): return '<Link %s>' % self def __eq__(self, other): return self.url == other.url def __ne__(self, other): return self.url != other.url def __lt__(self, other): return self.url < other.url def __le__(self, other): return self.url <= other.url def __gt__(self, other): return self.url > other.url def __ge__(self, other): return self.url >= other.url def __hash__(self): return hash(self.url) @property def filename(self): _, netloc, path, _, _ = urlparse.urlsplit(self.url) name = posixpath.basename(path.rstrip('/')) or netloc assert name, ('URL %r produced no filename' % self.url) return name @property def scheme(self): return urlparse.urlsplit(self.url)[0] @property def path(self): return urlparse.urlsplit(self.url)[2] def splitext(self): return splitext(posixpath.basename(self.path.rstrip('/'))) @property def ext(self): return self.splitext()[1] @property def url_without_fragment(self): scheme, netloc, path, query, fragment = urlparse.urlsplit(self.url) return urlparse.urlunsplit((scheme, netloc, path, query, None)) _egg_fragment_re = re.compile(r'#egg=([^&]*)') @property def egg_fragment(self): match = self._egg_fragment_re.search(self.url) if not match: return None return match.group(1) _hash_re = re.compile(r'(sha1|sha224|sha384|sha256|sha512|md5)=([a-f0-9]+)') @property def hash(self): match = self._hash_re.search(self.url) if match: return match.group(2) return None @property def hash_name(self): match = self._hash_re.search(self.url) if match: return match.group(1) return None @property def show_url(self): return posixpath.basename(self.url.split('#', 1)[0].split('?', 1)[0]) @property def verifiable(self): """ Returns True if this link can be verified after download, False if it cannot, and None if we cannot determine. """ trusted = self.trusted or getattr(self.comes_from, "trusted", None) if trusted is not None and trusted: # This link came from a trusted source. It *may* be verifiable but # first we need to see if this page is operating under the new # API version. try: api_version = getattr(self.comes_from, "api_version", None) api_version = int(api_version) except (ValueError, TypeError): api_version = None if api_version is None or api_version <= 1: # This link is either trusted, or it came from a trusted, # however it is not operating under the API version 2 so # we can't make any claims about if it's safe or not return if self.hash: # This link came from a trusted source and it has a hash, so we # can consider it safe. return True else: # This link came from a trusted source, using the new API # version, and it does not have a hash. It is NOT verifiable return False elif trusted is not None: # This link came from an untrusted source and we cannot trust it return False # An object to represent the "link" for the installed version of a requirement. # Using Inf as the url makes it sort higher. INSTALLED_VERSION = Link(Inf) def get_requirement_from_url(url): """Get a requirement from the URL, if possible. This looks for #egg in the URL""" link = Link(url) egg_info = link.egg_fragment if not egg_info: egg_info = splitext(link.filename)[0] return package_to_requirement(egg_info) def package_to_requirement(package_name): """Translate a name like Foo-1.2 to Foo==1.3""" match = re.search(r'^(.*?)-(dev|\d.*)', package_name) if match: name = match.group(1) version = match.group(2) else: name = package_name version = '' if version: return '%s==%s' % (name, version) else: return name<|fim▁end|>
from pip.log import logger from pip.util import Inf, normalize_name, splitext, is_prerelease
<|file_name|>file_atomic_replace_write_file.cc<|end_file_name|><|fim▁begin|>// Copyright 2019 The Cobalt Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "starboard/shared/starboard/file_atomic_replace_write_file.h" #include <algorithm> #include "starboard/common/log.h" #include "starboard/file.h" #if SB_API_VERSION >= 12 namespace starboard { namespace shared { namespace starboard { bool SbFileAtomicReplaceWriteFile(const char* path, const char* data, int64_t data_size) { SbFileError error; SbFile temp_file = SbFileOpen( path, kSbFileCreateAlways | kSbFileWrite | kSbFileRead, NULL, &error);<|fim▁hole|> if (error != kSbFileOk) { return false; } SbFileTruncate(temp_file, 0); const char* source = data; int64_t to_write = data_size; while (to_write > 0) { const int to_write_max = static_cast<int>(std::min(to_write, static_cast<int64_t>(kSbInt32Max))); const int bytes_written = SbFileWrite(temp_file, source, to_write_max); if (bytes_written < 0) { SbFileClose(temp_file); SbFileDelete(path); return false; } source += bytes_written; to_write -= bytes_written; } SbFileFlush(temp_file); if (!SbFileClose(temp_file)) { return false; } return true; } } // namespace starboard } // namespace shared } // namespace starboard #endif // SB_API_VERSION >= 12<|fim▁end|>
<|file_name|>integration_test.rs<|end_file_name|><|fim▁begin|>extern crate rcalc; use std::sync::Arc; use rcalc::{ Calculator, RuntimeItem, Value }; #[test] fn test_atom() { let mut calculator = Calculator::new(); assert_eq!(calculator.calc("1"), Result::Ok(&RuntimeItem::Value(Value::Integer(1)))); } #[test] fn test_it() { let mut calculator = Calculator::new(); assert_eq!(calculator.calc(r"1"), Result::Ok(&RuntimeItem::Value(Value::Integer(1)))); assert_eq!(calculator.calc(r"it + 1"), Result::Ok(&RuntimeItem::Value(Value::Integer(2)))); } #[test] fn test_term() { let mut calculator = Calculator::new(); assert_eq!(calculator.calc("1 + 1"), Result::Ok(&RuntimeItem::Value(Value::Integer(2)))); } #[test] fn test_float() { let mut calculator = Calculator::new(); assert_eq!(calculator.calc("(1 + 1 + 0.5) / 0.5"), Result::Ok(&RuntimeItem::Value(Value::Float(5.0)))); } #[test] fn test_complex_1() { let mut calculator = Calculator::new(); assert_eq!(calculator.calc(r"sin (pi/2) \ 1"), Result::Ok(&RuntimeItem::Value(Value::Integer(1)))); } #[test] fn test_complex_2() { let mut calculator = Calculator::new(); assert_eq!(calculator.calc(r"(0b0000_0001 << 7) & 0x80"), Result::Ok(&RuntimeItem::Value(Value::Integer(128)))); } #[test] fn test_function_decl() { let mut calculator = Calculator::new(); let src = "let f(x) = x**2"; match calculator.calc(src) { Result::Ok(&RuntimeItem::Function(..)) => (), _ => assert!(false), } } #[test] fn test_function_call() { let mut calculator = Calculator::new(); let src = "let f(x) = x**2"; match calculator.calc(src) { Result::Ok(&RuntimeItem::Function(..)) => (), _ => assert!(false), } assert_eq!(calculator.calc(r"f(2)"), Result::Ok(&RuntimeItem::Value(Value::Float(4.0)))); } #[test] fn test_binding_ref() { let mut calculator = Calculator::new(); assert_eq!(calculator.calc("let a = 1"), Result::Ok(&RuntimeItem::Value(Value::Integer(1)))); assert_eq!(calculator.calc("a + 1"), Result::Ok(&RuntimeItem::Value(Value::Integer(2)))); } #[test] fn test_vectors() { let mut calculator = Calculator::new(); assert_eq!(calculator.calc(r"[1, 2] + 1"), Result::Ok(&RuntimeItem::Value(Value::Vector(Arc::new(vec![Value::Integer(2), Value::Integer(3)]))))); } #[test] fn test_calc_parallel() { let mut calculator = Calculator::new(); assert_eq!(calculator.calc_parallel(vec!["1 + 1".to_string(), "2 + 2".to_string()]), &RuntimeItem::Value(Value::Vector(Arc::new(vec![Value::Integer(2), Value::Integer(4)])))); } <|fim▁hole|> let mut calculator = Calculator::new(); assert!(calculator.calc("let one = 1").is_ok()); assert!(calculator.calc("let two = 2").is_ok()); assert_eq!(calculator.calc_parallel(vec!["let a = one + one".to_string(), "let b = two + two".to_string()]), &RuntimeItem::Value(Value::Vector(Arc::new(vec![Value::Integer(2), Value::Integer(4)])))); } #[test] fn test_calc_parallel_with_context_2() { let mut calculator = Calculator::new(); assert_eq!(calculator.calc_parallel(vec!["let a = 1 + 1".to_string(), "let b = 2 + 2".to_string()]), &RuntimeItem::Value(Value::Vector(Arc::new(vec![Value::Integer(2), Value::Integer(4)])))); assert_eq!(calculator.calc("a"), Result::Ok(&RuntimeItem::Value(Value::Integer(2)))); assert_eq!(calculator.calc("b"), Result::Ok(&RuntimeItem::Value(Value::Integer(4)))); }<|fim▁end|>
#[test] fn test_calc_parallel_with_context_1() {
<|file_name|>test_tag.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import fauxfactory import pytest from cfme import test_requirements from cfme.cloud.provider import CloudProvider from cfme.infrastructure.provider import InfraProvider from cfme.markers.env_markers.provider import ONE from cfme.markers.env_markers.provider import ONE_PER_CATEGORY from cfme.rest.gen_data import categories as _categories from cfme.rest.gen_data import service_templates as _service_templates from cfme.rest.gen_data import tags as _tags from cfme.rest.gen_data import tenants as _tenants from cfme.rest.gen_data import users as _users from cfme.rest.gen_data import vm as _vm from cfme.utils.appliance.implementations.ui import navigator from cfme.utils.log import logger from cfme.utils.rest import assert_response from cfme.utils.rest import delete_resources_from_collection from cfme.utils.rest import delete_resources_from_detail from cfme.utils.update import update from cfme.utils.wait import wait_for CLOUD_COLLECTION = [ "availability_zones", "cloud_networks", "cloud_subnets", "flavors", "network_routers", "security_groups", ] INFRA_COLLECTION = [ "clusters", "hosts", "data_stores", "providers", "resource_pools", "services", "service_templates", "tenants", "vms", "users", ] pytestmark = [ pytest.mark.provider(classes=[InfraProvider], selector=ONE), pytest.mark.usefixtures('setup_provider') ] @pytest.fixture def category(appliance): cg = appliance.collections.categories.create( name=fauxfactory.gen_alphanumeric(8).lower(), description=fauxfactory.gen_alphanumeric(32), display_name=fauxfactory.gen_alphanumeric(32) ) yield cg if cg.exists: cg.delete() @pytest.fixture def tag(category): tag = category.collections.tags.create( name=fauxfactory.gen_alphanumeric(8).lower(), display_name=fauxfactory.gen_alphanumeric(32) ) yield tag tag.delete_if_exists() @pytest.mark.sauce @pytest.mark.tier(2) @test_requirements.tag def test_tag_crud(tag): """ Polarion: assignee: anikifor initialEstimate: 1/8h casecomponent: Tagging """ assert tag.exists tag.update({ 'name': fauxfactory.gen_alphanumeric(8).lower(), 'display_name': fauxfactory.gen_alphanumeric(32) }) @test_requirements.tag def test_map_tagging_crud(appliance, category, soft_assert): """Test map tag crud with flash message assertion Polarion: assignee: anikifor initialEstimate: 1/4h casecomponent: Tagging Bugzilla: 1707328 """ label = fauxfactory.gen_alphanumeric(8) map_tags_collection = appliance.collections.map_tags map_tag_entity = map_tags_collection.create('Container Project', label, category.name) view = appliance.browser.create_view(navigator.get_class(map_tags_collection, 'All').VIEW) view.flash.assert_success_message('Container Label Tag Mapping "{}" was added' .format(label)) # use label var to validate create method with update(map_tag_entity): map_tag_entity.category = fauxfactory.gen_alphanumeric(8) view = appliance.browser.create_view(navigator.get_class(map_tags_collection, 'All').VIEW) view.flash.assert_success_message( 'Container Label Tag Mapping "{}" was saved' .format(map_tag_entity.label) # use entity label since it may get updated ) row = next(view.table.rows(resource_label=map_tag_entity.label)) soft_assert(row.tag_category.text == map_tag_entity.category) map_tag_entity.delete() view = appliance.browser.create_view(navigator.get_class(map_tags_collection, 'All').VIEW) if appliance.version >= "5.11": # BZ 1707328 is fixed only for 5.11 view.flash.assert_success_message('Container Label Tag Mapping "{}": Delete successful' .format(map_tag_entity.label)) @test_requirements.tag def test_updated_tag_name_on_vm(provider, tag, request): """ This test checks that tags don't disappear from the UI after their name (not displayed name) is changed. Bugzilla: 1668730 Polarion: assignee: anikifor casecomponent: Configuration caseimportance: high initialEstimate: 1/8h testSteps: 1. create a tag 2. assign the tag to some vm, observe the tag in Smart Management section of vm 3. change name of the tag 4. on VM screen: still the same tag in Smart Management section of vm """ coll = provider.appliance.provider_based_collection(provider, coll_type='vms') # need some VM to assign tags to, nothing specific is needed, so take the first one vm = coll.all()[0] vm.add_tag(tag) request.addfinalizer(lambda: vm.remove_tag(tag)) # assert the tag is correctly assigned vm_tags = vm.get_tags() assert any( tag.category.display_name == vm_tag.category.display_name and tag.display_name == vm_tag.display_name for vm_tag in vm_tags ), "tag is not assigned" # update the name of the tag new_tag_name = '{}_{}'.format(tag.name, fauxfactory.gen_alphanumeric(4).lower()) tag.update({'name': new_tag_name}) vm_tags = vm.get_tags() # assert the tag was not changed in the UI assert any( tag.category.display_name == vm_tag.category.display_name and tag.display_name == vm_tag.display_name for vm_tag in vm_tags ), 'tag is not assigned' @test_requirements.rest class TestTagsViaREST(object): COLLECTIONS_BULK_TAGS = ("services", "vms", "users") def _service_body(self, **kwargs): uid = fauxfactory.gen_alphanumeric(5) body = { 'name': 'test_rest_service_{}'.format(uid), 'description': 'Test REST Service {}'.format(uid), } body.update(kwargs) return body def _create_services(self, request, rest_api, num=3): # create simple service using REST API bodies = [self._service_body() for __ in range(num)] collection = rest_api.collections.services new_services = collection.action.create(*bodies) assert_response(rest_api) new_services_backup = list(new_services) @request.addfinalizer def _finished(): collection.reload() ids = [service.id for service in new_services_backup] delete_entities = [service for service in collection if service.id in ids] if delete_entities: collection.action.delete(*delete_entities) return new_services @pytest.fixture(scope="function") def services(self, request, appliance): return self._create_services(request, appliance.rest_api) @pytest.fixture(scope="function") def categories(self, request, appliance, num=3): return _categories(request, appliance, num) @pytest.fixture(scope="function") def tags(self, request, appliance, categories): return _tags(request, appliance, categories) @pytest.fixture(scope="module") def services_mod(self, request, appliance): return self._create_services(request, appliance.rest_api) @pytest.fixture(scope="module") def categories_mod(self, request, appliance, num=3): return _categories(request, appliance, num) @pytest.fixture(scope="module") def tags_mod(self, request, appliance, categories_mod): return _tags(request, appliance, categories_mod) @pytest.fixture(scope="module") def tenants(self, request, appliance): return _tenants(request, appliance, num=1) @pytest.fixture(scope="module") def service_templates(self, request, appliance): return _service_templates(request, appliance) @pytest.fixture(scope="function") def vm(self, request, provider, appliance): return _vm(request, provider, appliance) @pytest.fixture(scope="function") def users(self, request, appliance, num=3): return _users(request, appliance, num=num) @pytest.mark.tier(2) def test_edit_tags_rest(self, appliance, tags): """Tests tags editing from collection. Metadata: test_flag: rest Polarion: assignee: pvala casecomponent: Configuration caseimportance: high initialEstimate: 1/6h """ collection = appliance.rest_api.collections.tags tags_len = len(tags) tags_data_edited = [] for tag in tags: tags_data_edited.append({ "href": tag.href, "name": "test_tag_{}".format(fauxfactory.gen_alphanumeric().lower()), }) edited = collection.action.edit(*tags_data_edited) assert_response(appliance, results_num=tags_len) for index in range(tags_len): record, _ = wait_for(lambda: collection.find_by(name="%/{}".format(tags_data_edited[index]["name"])) or False, num_sec=180, delay=10) assert record[0].id == edited[index].id assert record[0].name == edited[index].name @pytest.mark.tier(2) def test_edit_tag_from_detail(self, appliance, tags): """Tests tag editing from detail. Metadata: test_flag: rest Polarion: assignee: pvala casecomponent: Configuration caseimportance: high initialEstimate: 1/30h """ edited = [] new_names = [] for tag in tags: new_name = 'test_tag_{}'.format(fauxfactory.gen_alphanumeric()) new_names.append(new_name) edited.append(tag.action.edit(name=new_name)) assert_response(appliance) for index, name in enumerate(new_names): record, _ = wait_for(lambda: appliance.rest_api.collections.tags.find_by(name="%/{}".format(name)) or False, num_sec=180, delay=10) assert record[0].id == edited[index].id assert record[0].name == edited[index].name @pytest.mark.tier(3) @pytest.mark.parametrize("method", ["post", "delete"], ids=["POST", "DELETE"]) def test_delete_tags_from_detail(self, tags, method): """Tests deleting tags from detail. Metadata: test_flag: rest Polarion: assignee: pvala casecomponent: Configuration caseimportance: high initialEstimate: 1/30h """ delete_resources_from_detail(tags, method=method) @pytest.mark.tier(3) def test_delete_tags_from_collection(self, tags): """Tests deleting tags from collection. Metadata: test_flag: rest Polarion: assignee: pvala casecomponent: Configuration caseimportance: high initialEstimate: 1/30h """ delete_resources_from_collection(tags, not_found=True) @pytest.mark.tier(3) def test_create_tag_with_wrong_arguments(self, appliance): """Tests creating tags with missing category "id", "href" or "name". Metadata: test_flag: rest Polarion: assignee: pvala casecomponent: Configuration caseimportance: high initialEstimate: 1/30h """ data = { "name": "test_tag_{}".format(fauxfactory.gen_alphanumeric().lower()), "description": "test_tag_{}".format(fauxfactory.gen_alphanumeric().lower()) } msg = "BadRequestError: Category id, href or name needs to be specified" with pytest.raises(Exception, match=msg): appliance.rest_api.collections.tags.action.create(data) assert_response(appliance, http_status=400) @pytest.mark.tier(3) @pytest.mark.provider( [CloudProvider, InfraProvider], selector=ONE_PER_CATEGORY, override=True ) @pytest.mark.parametrize("collection_name", INFRA_COLLECTION + CLOUD_COLLECTION) @pytest.mark.uncollectif( lambda appliance, collection_name, provider: ( provider.one_of(CloudProvider) and collection_name in INFRA_COLLECTION ) or ( provider.one_of(InfraProvider) and collection_name in CLOUD_COLLECTION ) ) def test_assign_and_unassign_tag(self, appliance, tags_mod, provider, services_mod, service_templates, tenants, vm, collection_name, users): """Tests assigning and unassigning tags. Metadata: test_flag: rest Polarion: assignee: pvala casecomponent: Configuration caseimportance: high initialEstimate: 1/5h """ collection = getattr(appliance.rest_api.collections, collection_name) collection.reload() if not collection.all: pytest.skip("No available entity in {} to assign tag".format(collection_name)) entity = collection[-1] tag = tags_mod[0] try: entity.tags.action.assign(tag) except AttributeError: msg = ('Missing tag attribute in parametrized REST collection {} for entity: {}' .format(collection_name, entity)) logger.exception(msg) pytest.fail(msg) assert_response(appliance) entity.reload() assert tag.id in [t.id for t in entity.tags.all] entity.tags.action.unassign(tag) assert_response(appliance) entity.reload() assert tag.id not in [t.id for t in entity.tags.all] @pytest.mark.tier(3) @pytest.mark.parametrize( "collection_name", COLLECTIONS_BULK_TAGS) def test_bulk_assign_and_unassign_tag(self, appliance, tags_mod, services_mod, vm, collection_name, users): """Tests bulk assigning and unassigning tags. Metadata: test_flag: rest Polarion: assignee: pvala casecomponent: Configuration caseimportance: high initialEstimate: 1/5h """ collection = getattr(appliance.rest_api.collections, collection_name) collection.reload() entities = collection.all[-2:] new_tags = [] for index, tag in enumerate(tags_mod): identifiers = [{'href': tag._href}, {'id': tag.id}] new_tags.append(identifiers[index % 2]) # add some more tags in supported formats new_tags.append({'category': 'department', 'name': 'finance'}) new_tags.append({'name': '/managed/department/presales'}) tags_ids = {t.id for t in tags_mod} tags_ids.add( appliance.rest_api.collections.tags.get(name='/managed/department/finance').id) tags_ids.add( appliance.rest_api.collections.tags.get(name='/managed/department/presales').id) tags_count = len(new_tags) * len(entities) response = collection.action.assign_tags(*entities, tags=new_tags)<|fim▁hole|> entities_hrefs = [e.href for e in entities] for result in results: assert result['href'] in entities_hrefs for index, entity in enumerate(entities): entity.tags.reload() response[index].id = entity.id assert tags_ids.issubset({t.id for t in entity.tags.all}) collection.action.unassign_tags(*entities, tags=new_tags) assert_response(appliance, results_num=tags_count) for entity in entities: entity.tags.reload() assert len({t.id for t in entity.tags.all} - tags_ids) == entity.tags.subcount @pytest.mark.tier(3) @pytest.mark.parametrize( "collection_name", COLLECTIONS_BULK_TAGS) def test_bulk_assign_and_unassign_invalid_tag(self, appliance, services_mod, vm, collection_name, users): """Tests bulk assigning and unassigning invalid tags. Metadata: test_flag: rest Polarion: assignee: pvala casecomponent: Configuration caseimportance: high initialEstimate: 1/5h """ collection = getattr(appliance.rest_api.collections, collection_name) collection.reload() entities = collection.all[-2:] new_tags = ['invalid_tag1', 'invalid_tag2'] tags_count = len(new_tags) * len(entities) tags_per_entities_count = [] for entity in entities: entity.tags.reload() tags_per_entities_count.append(entity.tags.subcount) def _check_tags_counts(): for index, entity in enumerate(entities): entity.tags.reload() assert entity.tags.subcount == tags_per_entities_count[index] collection.action.assign_tags(*entities, tags=new_tags) assert_response(appliance, success=False, results_num=tags_count) _check_tags_counts() collection.action.unassign_tags(*entities, tags=new_tags) assert_response(appliance, success=False, results_num=tags_count) _check_tags_counts() @pytest.mark.tier(3) def test_query_by_multiple_tags(self, appliance, tags, services): """Tests support for multiple tag specification in query. Metadata: test_flag: rest Polarion: assignee: pvala casecomponent: Configuration caseimportance: high initialEstimate: 1/30h """ collection = appliance.rest_api.collections.services collection.reload() new_tags = [tag._ref_repr() for tag in tags] tagged_services = services[1:] # assign tags to selected services collection.action.assign_tags(*tagged_services, tags=new_tags) assert_response(appliance) # get only services that has all the tags assigned by_tag = ','.join([tag.name.replace('/managed', '') for tag in tags]) query_results = collection.query_string(by_tag=by_tag) assert len(tagged_services) == len(query_results) result_ids = {item.id for item in query_results} tagged_ids = {item.id for item in tagged_services} assert result_ids == tagged_ids<|fim▁end|>
assert_response(appliance, results_num=tags_count) # testing BZ 1460257 results = appliance.rest_api.response.json()['results']
<|file_name|>ColumnTransformer.java<|end_file_name|><|fim▁begin|>package info.yongli.statistic.table; <|fim▁hole|>public class ColumnTransformer { }<|fim▁end|>
/** * Created by yangyongli on 25/04/2017. */
<|file_name|>game-play.component.ts<|end_file_name|><|fim▁begin|><|fim▁hole|>@Component({ template: 'play' }) export class GamePlayComponent {}<|fim▁end|>
import { Component } from '@angular/core';
<|file_name|>plot_undirected_grid_graph_watersheds.py<|end_file_name|><|fim▁begin|>""" Edge/Node Weighted Watersheds ==================================== Compare edge weighted watersheds and node weighted on a grid graph. """ #################################### # sphinx_gallery_thumbnail_number = 5 from __future__ import print_function import nifty.graph import skimage.data import skimage.segmentation import vigra import matplotlib import pylab import numpy # increase default figure size a,b = pylab.rcParams['figure.figsize'] pylab.rcParams['figure.figsize'] = 2.0*a, 2.0*b #################################### # load some image img = skimage.data.astronaut().astype('float32') shape = img.shape[0:2] #plot the image pylab.imshow(img/255) pylab.show() ################################################ # get some edge indicator taggedImg = vigra.taggedView(img,'xyc') edgeStrength = vigra.filters.structureTensorEigenvalues(taggedImg, 1.5, 1.9)[:,:,0] edgeStrength = edgeStrength.squeeze() edgeStrength = numpy.array(edgeStrength) pylab.imshow(edgeStrength) pylab.show() ################################################### # get seeds via local minima seeds = vigra.analysis.localMinima(edgeStrength) seeds = vigra.analysis.labelImageWithBackground(seeds) # plot seeds cmap = numpy.random.rand ( seeds.max()+1,3) cmap[0,:] = 0 cmap = matplotlib.colors.ListedColormap ( cmap) pylab.imshow(seeds, cmap=cmap) pylab.show() ######################################### # grid graph gridGraph = nifty.graph.undirectedGridGraph(shape) ######################################### # run node weighted watershed algorithm oversegNodeWeighted = nifty.graph.nodeWeightedWatershedsSegmentation(graph=gridGraph, seeds=seeds.ravel(), nodeWeights=edgeStrength.ravel()) oversegNodeWeighted = oversegNodeWeighted.reshape(shape) ######################################### # run edge weighted watershed algorithm gridGraphEdgeStrength = gridGraph.imageToEdgeMap(edgeStrength, mode='sum') numpy.random.permutation(gridGraphEdgeStrength) oversegEdgeWeightedA = nifty.graph.edgeWeightedWatershedsSegmentation(graph=gridGraph, seeds=seeds.ravel(), edgeWeights=gridGraphEdgeStrength) oversegEdgeWeightedA = oversegEdgeWeightedA.reshape(shape) ######################################### # run edge weighted watershed algorithm # on interpixel weights. # To do so we need to resample the image # and compute the edge indicator # on the reampled image interpixelShape = [2*s-1 for s in shape] imgBig = vigra.sampling.resize(taggedImg, interpixelShape) edgeStrength = vigra.filters.structureTensorEigenvalues(imgBig, 2*1.5, 2*1.9)[:,:,0] edgeStrength = edgeStrength.squeeze() edgeStrength = numpy.array(edgeStrength) gridGraphEdgeStrength = gridGraph.imageToEdgeMap(edgeStrength, mode='interpixel') oversegEdgeWeightedB = nifty.graph.edgeWeightedWatershedsSegmentation( graph=gridGraph, seeds=seeds.ravel(), edgeWeights=gridGraphEdgeStrength) oversegEdgeWeightedB = oversegEdgeWeightedB.reshape(shape) ######################################### # plot results f = pylab.figure() f.add_subplot(2,2, 1) b_img = skimage.segmentation.mark_boundaries(img/255, oversegEdgeWeightedA.astype('uint32'), mode='inner', color=(0.1,0.1,0.2)) pylab.imshow(b_img)<|fim▁hole|>f.add_subplot(2,2, 2) b_img = skimage.segmentation.mark_boundaries(img/255, oversegEdgeWeightedB.astype('uint32'), mode='inner', color=(0.1,0.1,0.2)) pylab.imshow(b_img) pylab.title('Edge Weighted Watershed (interpixel weights)') f.add_subplot(2,2, 3) b_img = skimage.segmentation.mark_boundaries(img/255, oversegNodeWeighted.astype('uint32'), mode='inner', color=(0.1,0.1,0.2)) pylab.imshow(b_img) pylab.title('Node Weighted Watershed') pylab.show()<|fim▁end|>
pylab.title('Edge Weighted Watershed (sum weights)')
<|file_name|>pe_region.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ A list of Peru regions as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ from __future__ import unicode_literals REGION_CHOICES = ( ('AMA', 'Amazonas'), ('ANC', 'Ancash'), ('APU', 'Apurímac'), ('ARE', 'Arequipa'), ('AYA', 'Ayacucho'), ('CAJ', 'Cajamarca'), ('CAL', 'Callao'), ('CUS', 'Cusco'), ('HUV', 'Huancavelica'), ('HUC', 'Huánuco'), ('ICA', 'Ica'), ('JUN', 'Junín'), ('LAL', 'La Libertad'), ('LAM', 'Lambayeque'), ('LIM', 'Lima'), ('LOR', 'Loreto'), ('MDD', 'Madre de Dios'), ('MOQ', 'Moquegua'), ('PAS', 'Pasco'), ('PIU', 'Piura'), ('PUN', 'Puno'), ('SAM', 'San Martín'), ('TAC', 'Tacna'), ('TUM', 'Tumbes'),<|fim▁hole|> ('UCA', 'Ucayali'), )<|fim▁end|>
<|file_name|>televigo.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of PyDownTV. # # PyDownTV 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. # # PyDownTV 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 PyDownTV. If not, see <http://www.gnu.org/licenses/>. # Pequeña descripción de qué canal de tv es el módulo __author__="aabilio" __date__ ="$15-may-2011 11:03:38$" from Descargar import Descargar from utiles import salir, formatearNombre, printt import sys class TeleVigo(object): ''' Clase que maneja la descarga los vídeos de TeleVigo ''' <|fim▁hole|> def getURL(self): return self._URL_recibida def setURL(self, url): self._URL_recibida = url url = property(getURL, setURL) # Funciones privadas que ayuden a procesarDescarga(self): def __descHTML(self, url2down): ''' Método que utiliza la clase descargar para descargar el HTML ''' D = Descargar(url2down) return D.descargar() def procesarDescarga(self): ''' Procesa lo necesario para obtener la url final del vídeo a descargar y devuelve esta y el nombre como se quiere que se descarge el archivo de la siguiente forma: return [ruta_url, nombre] Si no se quiere especificar un nombre para el archivo resultante en disco, o no se conoce un procedimiento para obtener este automáticamente se utilizará: return [ruta_url, None] Y el método de Descargar que descarga utilizará el nombre por defecto según la url. Tanto "ruta_url" como "nombre" pueden ser listas (por supuesto, el nombre del ruta_url[0] tiene que ser nombre[0] y así sucesivamente). ''' streamHTML = self.__descHTML(self._URL_recibida) xmlURL = streamHTML.split("_url_xml_datos:\"")[1].split("\"")[0] streamXML = self.__descHTML(xmlURL) url = streamXML.split("<url>")[1].split("<")[0] ext = "." + url.split(".")[-1] name = streamXML.split("<title><![CDATA[")[1].split("]")[0] + ext if name: name = formatearNombre(name) return [url, name]<|fim▁end|>
URL_TeleVigo = "http://www.televigo.com/" def __init__(self, url=""): self._URL_recibida = url
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
pub mod klondike;
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .depth import * from .camera import *<|fim▁hole|><|fim▁end|>
from .contact import * from .imagefeature import * from .arduino import *
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># flake8: noqa from .config import INFER_HOST<|fim▁hole|>from .main import run_app, runserver, serve_static<|fim▁end|>
<|file_name|>inkscape-export.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python <|fim▁hole|>import sys INKSCAPE = '/usr/bin/inkscape' def list_layers(svg): layers = [ ] for g in svg.getElementsByTagName("g"): if g.attributes.has_key("inkscape:label"): layers.append(g.attributes["inkscape:label"].value) return layers def export_layer(svg, directory, layer, stay): if layer in stay: return print layer, "..." for g in svg.getElementsByTagName("g"): if g.attributes.has_key("inkscape:label"): label = g.attributes["inkscape:label"].value if label == layer or label in stay: g.attributes['style'] = 'display:inline' else: g.attributes['style'] = 'display:none' dest = os.path.join(directory, layer + ".svg") codecs.open(dest, "w", encoding="utf8").write(svg.toxml()) png = os.path.join(directory, layer + ".png") subprocess.check_call([INKSCAPE, "--export-png", png, dest]) os.unlink(dest) def main(): from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument('--stay', action='append', default=[], help='layer to always have visible') parser.add_argument('src', help='source SVG file.') args = parser.parse_args() svg = minidom.parse(open(args.src)) for layer in list_layers(svg): export_layer(svg, os.path.dirname(args.src), layer, args.stay) if __name__ == '__main__': main()<|fim▁end|>
import os import codecs from xml.dom import minidom import subprocess
<|file_name|>MachineTypeEnum.java<|end_file_name|><|fim▁begin|>/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.events.cloud.cloudbuild.v1; import java.io.IOException; public enum MachineTypeEnum { N1_HIGHCPU_32, N1_HIGHCPU_8, UNSPECIFIED; public String toValue() { switch (this) { case N1_HIGHCPU_32: return "N1_HIGHCPU_32"; case N1_HIGHCPU_8: return "N1_HIGHCPU_8"; case UNSPECIFIED: return "UNSPECIFIED"; } return null; } public static MachineTypeEnum forValue(String value) throws IOException { if (value.equals("N1_HIGHCPU_32")) return N1_HIGHCPU_32; if (value.equals("N1_HIGHCPU_8")) return N1_HIGHCPU_8; if (value.equals("UNSPECIFIED")) return UNSPECIFIED; throw new IOException("Cannot deserialize MachineTypeEnum");<|fim▁hole|><|fim▁end|>
} }
<|file_name|>generate.go<|end_file_name|><|fim▁begin|>/* Copyright */ //go:generate rm -vf autogen/gen.go<|fim▁hole|> //go:generate mkdir -p vendor/github.com/docker/docker/autogen/dockerversion //go:generate cp script/dockerversion vendor/github.com/docker/docker/autogen/dockerversion/dockerversion.go package main<|fim▁end|>
//go:generate go-bindata -pkg autogen -o autogen/gen.go ./static/... ./templates/...
<|file_name|>TransactionWriteTakeIfExistsTest.java<|end_file_name|><|fim▁begin|>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.river.test.spec.javaspace.conformance; import java.util.logging.Level; // net.jini import net.jini.core.transaction.Transaction; // org.apache.river import org.apache.river.qa.harness.TestException; import org.apache.river.qa.harness.QAConfig; /** * TransactionWriteTakeIfExistsTest asserts that if the entry is written and * after that is taken by takeIfExists method within the non null * transaction, the entry will never be visible outside the transaction and * will not be added to the space when the transaction commits. * * @author Mikhail A. Markov */ public class TransactionWriteTakeIfExistsTest extends TransactionTest { /** * This method asserts that if the entry is written and * after that is taken by takeIfExists method within the non null * transaction, the entry will never be visible outside the transaction and * will not be added to the space when the transaction commits. * * <P>Notes:<BR>For more information see the JavaSpaces specification * section 3.1</P> */ public void run() throws Exception { SimpleEntry sampleEntry1 = new SimpleEntry("TestEntry #1", 1); SimpleEntry sampleEntry2 = new SimpleEntry("TestEntry #2", 2); SimpleEntry result; Transaction txn; // first check that space is empty if (!checkSpace(space)) { throw new TestException( "Space is not empty in the beginning."); } // create the non null transaction txn = getTransaction(); /* * write 1-st sample and 2-nd sample entries twice * to the space within the transaction */ space.write(sampleEntry1, txn, leaseForeverTime); space.write(sampleEntry1, txn, leaseForeverTime); space.write(sampleEntry2, txn, leaseForeverTime); space.write(sampleEntry2, txn, leaseForeverTime); <|fim▁hole|> * takeIfExists all written entries from the space * within the transaction */ space.takeIfExists(sampleEntry1, txn, checkTime); space.takeIfExists(sampleEntry1, txn, checkTime); space.takeIfExists(sampleEntry2, txn, checkTime); space.takeIfExists(sampleEntry2, txn, checkTime); // commit the transaction txnCommit(txn); // check that there are no entries in the space result = (SimpleEntry) space.read(null, null, checkTime); if (result != null) { throw new TestException( "there is " + result + " still available in the" + " space after transaction's committing" + " but null is expected."); } logDebugText("There are no entries in the space after" + " transaction's committing, as expected."); } }<|fim▁end|>
/*
<|file_name|>light_data.hpp<|end_file_name|><|fim▁begin|>/*** * Copyright 2013, 2014 Moises J. Bonilla Caraballo (Neodivert) * * This file is part of COMO. * * COMO is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License v3 as published by * the Free Software Foundation. * * COMO 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 COMO. If not, see <http://www.gnu.org/licenses/>. ***/ #ifndef LIGHT_DATA_HPP #define LIGHT_DATA_HPP #include <glm/vec3.hpp> namespace como { const glm::vec3 DEFAULT_LIGHT_COLOR( 1.0f ); const float DEFAULT_LIGHT_AMBIENT_COEFFICIENT = 0.3f; struct LightData { glm::vec3 color; float ambientCoefficient;<|fim▁hole|> * 1. Construction ***/ LightData() : color( DEFAULT_LIGHT_COLOR ), ambientCoefficient( DEFAULT_LIGHT_AMBIENT_COEFFICIENT ){} }; } // namespace como #endif // LIGHT_DATA_HPP<|fim▁end|>
/***
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*- """ Verion: 1.0 Author: zhangjian Site: http://iliangqunru.com File: __init__.py.py Time: 2017/7/22 2:19<|fim▁hole|>"""<|fim▁end|>
<|file_name|>gast.py<|end_file_name|><|fim▁begin|>import sys as _sys import ast as _ast from ast import boolop, cmpop, excepthandler, expr, expr_context, operator from ast import slice, stmt, unaryop, mod, AST def _make_node(Name, Fields, Attributes, Bases): def create_node(self, *args, **kwargs): nbparam = len(args) + len(kwargs) assert nbparam in (0, len(Fields)), \ "Bad argument number for {}: {}, expecting {}".\ format(Name, nbparam, len(Fields)) self._fields = Fields self._attributes = Attributes for argname, argval in zip(self._fields, args): setattr(self, argname, argval) for argname, argval in kwargs.items(): assert argname in Fields, \ "Invalid Keyword argument for {}: {}".format(Name, argname) setattr(self, argname, argval) setattr(_sys.modules[__name__], Name, type(Name, Bases, {'__init__': create_node})) _nodes = { # mod 'Module': (('body',), (), (mod,)), 'Interactive': (('body',), (), (mod,)), 'Expression': (('body',), (), (mod,)), 'Suite': (('body',), (), (mod,)), # stmt 'FunctionDef': (('name', 'args', 'body', 'decorator_list', 'returns',), ('lineno', 'col_offset',), (stmt,)), 'AsyncFunctionDef': (('name', 'args', 'body', 'decorator_list', 'returns',), ('lineno', 'col_offset',), (stmt,)), 'ClassDef': (('name', 'bases', 'keywords', 'body', 'decorator_list',), ('lineno', 'col_offset',), (stmt,)), 'Return': (('value',), ('lineno', 'col_offset',), (stmt,)), 'Delete': (('targets',), ('lineno', 'col_offset',), (stmt,)), 'Assign': (('targets', 'value',), ('lineno', 'col_offset',), (stmt,)), 'AugAssign': (('target', 'op', 'value',), ('lineno', 'col_offset',), (stmt,)), 'Print': (('dest', 'values', 'nl',), ('lineno', 'col_offset',), (stmt,)), 'For': (('target', 'iter', 'body', 'orelse',), ('lineno', 'col_offset',), (stmt,)), 'AsyncFor': (('target', 'iter', 'body', 'orelse',), ('lineno', 'col_offset',), (stmt,)), 'While': (('test', 'body', 'orelse',), ('lineno', 'col_offset',), (stmt,)), 'If': (('test', 'body', 'orelse',), ('lineno', 'col_offset',), (stmt,)), 'With': (('items', 'body',), ('lineno', 'col_offset',), (stmt,)), 'AsyncWith': (('items', 'body',), ('lineno', 'col_offset',), (stmt,)), 'Raise': (('exc', 'cause',), ('lineno', 'col_offset',), (stmt,)), 'Try': (('body', 'handlers', 'orelse', 'finalbody',), ('lineno', 'col_offset',), (stmt,)), 'Assert': (('test', 'msg',), ('lineno', 'col_offset',), (stmt,)), 'Import': (('names',), ('lineno', 'col_offset',), (stmt,)), 'ImportFrom': (('module', 'names', 'level',), ('lineno', 'col_offset',), (stmt,)), 'Exec': (('body', 'globals', 'locals',), ('lineno', 'col_offset',), (stmt,)), 'Global': (('names',), ('lineno', 'col_offset',), (stmt,)), 'Nonlocal': (('names',), ('lineno', 'col_offset',), (stmt,)), 'Expr': (('value',), ('lineno', 'col_offset',), (stmt,)), 'Pass': ((), ('lineno', 'col_offset',), (stmt,)), 'Break': ((), ('lineno', 'col_offset',), (stmt,)), 'Continue': ((), ('lineno', 'col_offset',), (stmt,)), # expr 'BoolOp': (('op', 'values',), ('lineno', 'col_offset',), (expr,)), 'BinOp': (('left', 'op', 'right',), ('lineno', 'col_offset',), (expr,)), 'UnaryOp': (('op', 'operand',), ('lineno', 'col_offset',), (expr,)), 'Lambda': (('args', 'body',), ('lineno', 'col_offset',), (expr,)), 'IfExp': (('test', 'body', 'orelse',), ('lineno', 'col_offset',), (expr,)), 'Dict': (('keys', 'values',), ('lineno', 'col_offset',), (expr,)), 'Set': (('elts',), ('lineno', 'col_offset',), (expr,)), 'ListComp': (('elt', 'generators',), ('lineno', 'col_offset',), (expr,)), 'SetComp': (('elt', 'generators',), ('lineno', 'col_offset',), (expr,)), 'DictComp': (('key', 'value', 'generators',), ('lineno', 'col_offset',), (expr,)), 'GeneratorExp': (('elt', 'generators',), ('lineno', 'col_offset',), (expr,)), 'Await': (('value',), ('lineno', 'col_offset',), (expr,)), 'Yield': (('value',), ('lineno', 'col_offset',), (expr,)), 'YieldFrom': (('value',), ('lineno', 'col_offset',), (expr,)), 'Compare': (('left', 'ops', 'comparators',), ('lineno', 'col_offset',), (expr,)), 'Call': (('func', 'args', 'keywords',), ('lineno', 'col_offset',), (expr,)), 'Repr': (('value',), ('lineno', 'col_offset',), (expr,)), 'Num': (('n',), ('lineno', 'col_offset',), (expr,)), 'Str': (('s',), ('lineno', 'col_offset',), (expr,)), 'FormattedValue': (('value', 'conversion', 'format_spec',), ('lineno', 'col_offset',), (expr,)), 'JoinedStr': (('values',), ('lineno', 'col_offset',), (expr,)), 'Bytes': (('s',), ('lineno', 'col_offset',), (expr,)), 'NameConstant': (('value',), ('lineno', 'col_offset',), (expr,)), 'Ellipsis': ((), ('lineno', 'col_offset',), (expr,)), 'Attribute': (('value', 'attr', 'ctx',), ('lineno', 'col_offset',), (expr,)), 'Subscript': (('value', 'slice', 'ctx',), ('lineno', 'col_offset',), (expr,)), 'Starred': (('value', 'ctx',), ('lineno', 'col_offset',), (expr,)), 'Name': (('id', 'ctx', 'annotation'), ('lineno', 'col_offset',), (expr,)), 'List': (('elts', 'ctx',), ('lineno', 'col_offset',), (expr,)), 'Tuple': (('elts', 'ctx',), ('lineno', 'col_offset',), (expr,)), # expr_context 'Load': ((), (), (expr_context,)), 'Store': ((), (), (expr_context,)), 'Del': ((), (), (expr_context,)), 'AugLoad': ((), (), (expr_context,)), 'AugStore': ((), (), (expr_context,)), 'Param': ((), (), (expr_context,)), # slice 'Slice': (('lower', 'upper', 'step'), (), (slice,)), 'ExtSlice': (('dims',), (), (slice,)), 'Index': (('value',), (), (slice,)), # boolop 'And': ((), (), (boolop,)), 'Or': ((), (), (boolop,)), # operator 'Add': ((), (), (operator,)), 'Sub': ((), (), (operator,)), 'Mult': ((), (), (operator,)), 'MatMult': ((), (), (operator,)), 'Div': ((), (), (operator,)), 'Mod': ((), (), (operator,)), 'Pow': ((), (), (operator,)), 'LShift': ((), (), (operator,)), 'RShift': ((), (), (operator,)), 'BitOr': ((), (), (operator,)), 'BitXor': ((), (), (operator,)), 'BitAnd': ((), (), (operator,)), 'FloorDiv': ((), (), (operator,)), # unaryop 'Invert': ((), (), (unaryop, AST,)), 'Not': ((), (), (unaryop, AST,)), 'UAdd': ((), (), (unaryop, AST,)), 'USub': ((), (), (unaryop, AST,)), # cmpop 'Eq': ((), (), (cmpop,)), 'NotEq': ((), (), (cmpop,)), 'Lt': ((), (), (cmpop,)), 'LtE': ((), (), (cmpop,)), 'Gt': ((), (), (cmpop,)), 'GtE': ((), (), (cmpop,)), 'Is': ((), (), (cmpop,)), 'IsNot': ((), (), (cmpop,)), 'In': ((), (), (cmpop,)), 'NotIn': ((), (), (cmpop,)), # comprehension 'comprehension': (('target', 'iter', 'ifs', 'is_async'), (), (AST,)), # excepthandler 'ExceptHandler': (('type', 'name', 'body'), ('lineno', 'col_offset'), (excepthandler,)), # arguments 'arguments': (('args', 'vararg', 'kwonlyargs', 'kw_defaults', 'kwarg', 'defaults'), (), (AST,)), # keyword 'keyword': (('arg', 'value'), (), (AST,)), # alias 'alias': (('name', 'asname'), (), (AST,)), # withitem 'withitem': (('context_expr', 'optional_vars'), (), (AST,)),<|fim▁hole|> for name, descr in _nodes.items(): _make_node(name, *descr) if _sys.version_info.major == 2: from .ast2 import ast_to_gast, gast_to_ast if _sys.version_info.major == 3: from .ast3 import ast_to_gast, gast_to_ast def parse(*args, **kwargs): return ast_to_gast(_ast.parse(*args, **kwargs)) def literal_eval(node_or_string): if isinstance(node_or_string, AST): node_or_string = gast_to_ast(node_or_string) return _ast.literal_eval(node_or_string) def get_docstring(node, clean=True): if not isinstance(node, (FunctionDef, ClassDef, Module)): raise TypeError("%r can't have docstrings" % node.__class__.__name__) if node.body and isinstance(node.body[0], Expr) and \ isinstance(node.body[0].value, Str): if clean: import inspect return inspect.cleandoc(node.body[0].value.s) return node.body[0].value.s<|fim▁end|>
}
<|file_name|>qqGroupBackend.go<|end_file_name|><|fim▁begin|>package main import "log" import "time" import "strings" import "strconv" import "net/http" import "io/ioutil" import "database/sql" import "encoding/json" import "math/rand" //import "zhuji" import _ "github.com/go-sql-driver/mysql" // #cgo LDFLAGS: -L. -lLetsChat // #include "c/letsChat/detect.h" import "C" var sqlConn *sql.DB var stmtQueryGroupSign *sql.Stmt var stmtInsertGroupSign *sql.Stmt var zhujiMsgChannels map[int64]chan string var zhujiOutputChannels map[int64]chan string func checkError(err error) { if err!=nil { log.Fatal(err) } } func initDatabase() *sql.DB { cfg,err := ioutil.ReadFile("sqlConnString_qqbot.txt") checkError(err) db,err := sql.Open("mysql",string(cfg)) checkError(err) err = db.Ping() checkError(err) return db } func initGlobalMaps() { zhujiMsgChannels = make(map[int64]chan string) zhujiOutputChannels = make(map[int64]chan string) } func prepareStmt() { var err error stmtQueryGroupSign,err = sqlConn.Prepare("SELECT id FROM group_sign WHERE gid = ? AND uid = ? AND sign_time >= ?") checkError(err) stmtInsertGroupSign,err = sqlConn.Prepare("INSERT INTO group_sign (gid,uid,sign_time) VALUES(?,?,?)") checkError(err) } /* func handleZhuji(gid int64, req string) string { needStart := false msgChan,ok := zhujiMsgChannels[gid] if !ok { zhujiMsgChannels[gid]=make(chan string) msgChan = zhujiMsgChannels[gid] needStart=true } outChan,ok := zhujiOutputChannels[gid] if !ok { zhujiOutputChannels[gid] = make(chan string) outChan = zhujiOutputChannels[gid] needStart=true } log.Println("New Zhuji request from group",gid,"-",req) if needStart { log.Println("Starting goroutine for group",gid) go zhuji.Start(msgChan,outChan) } msgChan <- req+"\n" return <-outChan } */ <|fim▁hole|> dayStart,_ := time.Parse("2006/01/02",timeData.Format("2006/01/02")) timeStampStart := dayStart.Unix() groupAccount := strconv.FormatInt(int64(ginfo["account"].(float64)),10) userName := uinfo["nick"].(string) res := stmtQueryGroupSign.QueryRow(groupAccount,userName,timeStampStart) if res==nil { return "doGroupSign failed: QueryRow" } signDataID := 0 err := res.Scan(&signDataID) if err==nil { return "你今天已经签到过了。" } execRes,err := stmtInsertGroupSign.Exec(groupAccount,userName,timeData.Unix()) if err!=nil { return err.Error() } lastInsert,_ := execRes.LastInsertId() return "签到成功,签到数据行 ID: "+strconv.FormatInt(lastInsert,10) } func generateTouZi() string { return strconv.Itoa(rand.Intn(5)+1) } func onNewMessage(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() requestBody,err := ioutil.ReadAll(r.Body) if err!=nil { w.Write([]byte(err.Error())) return } requestData := make(map[string]interface{}) err = json.Unmarshal(requestBody,&requestData) if err!=nil { w.Write([]byte(err.Error())) return } userMessageInterface,ok := requestData["content"] if !ok { w.Write([]byte("Bad value: content")) return } userMessage := "" switch userMessageInterface.(type) { case string: userMessage=userMessageInterface.(string) default: w.Write([]byte("Bad data type: content")) return } userMessage = strings.TrimSpace(userMessage) log.Println("GID",int64(requestData["ginfo"].(map[string]interface{})["account"].(float64)),"-",userMessage) apiReturnString := "" /* if len(userMessage)>2 && userMessage[0:1]=="." { apiReturnString = handleZhuji(int64(requestData["ginfo"].(map[string]interface{})["account"].(float64)),userMessage[1:len(userMessage)]) goto writeOut } */ groupId := int64(requestData["ginfo"].(map[string]interface{})["account"].(float64)) C.chatMsgInput(C.CString(userMessage),C.id_type(groupId)) /* if C.chatGetTotalWeight(C.id_type(groupId))>=1.0 { C.chatClearTotalWeight(C.id_type(groupId)) w.Write([]byte("这群风气不太对啊。")) return } */ letsChatReturn := C.GoString(C.chatGetOutputText(C.id_type(groupId))) if letsChatReturn != "OK" { w.Write([]byte(letsChatReturn)) return } switch userMessage { case "签到": apiReturnString = doGroupSign(requestData["ginfo"].(map[string]interface{}),requestData["uinfo"].(map[string]interface{})) case "抛骰子": apiReturnString = generateTouZi() case "+1s": apiReturnString = "已禁用。" case "续一秒": apiReturnString = "已禁用。" default: apiReturnString = "UNSUPPORTED" } // writeOut: w.Write([]byte(apiReturnString)) } func main() { sqlConn = initDatabase() initGlobalMaps() prepareStmt() http.HandleFunc("/newMessage/",onNewMessage) http.ListenAndServe(":6086",nil) }<|fim▁end|>
func doGroupSign(ginfo,uinfo map[string]interface{}) string { timeData := time.Now()
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.views.generic import TemplateView from django.shortcuts import render_to_response<|fim▁hole|>class DashboardView(LoginRequiredMixin, TemplateView): template_name = 'dashboard.html' def get(self, *args, **kwargs): return render_to_response(self.template_name, {}, context_instance=RequestContext(self.request)) def get_context_data(self, **kwargs): context_data = super(DashboardView, self).get_context_data(**kwargs) context_data['number_livestock'] = None return context_data<|fim▁end|>
from django.template import RequestContext from braces.views import LoginRequiredMixin
<|file_name|>menu.py<|end_file_name|><|fim▁begin|>import pygame import sys from game import constants, gamestate from game.ai.easy import EasyAI from game.media import media from game.scene import Scene <|fim▁hole|># List of menu options (text, action_method, condition) where condition is None or a callable. # If it is a callable that returns False, the option is not shown. CONTINUE = 0 NEW_GAME = 1 QUIT = 2 OPTIONS = [ ('Continue', 'opt_continue', lambda scene: scene.game_running), ('2 Player', 'start_2_player', None), ('Vs CPU', 'start_vs_cpu', None), ('Computer Battle!', 'start_cpu_vs_cpu', None), ('Quit', 'opt_quit', None), ] class MenuScene(Scene): def load(self): self.font = pygame.font.Font(constants.MENU_FONT, constants.MENU_FONT_SIZE) self.active_font = pygame.font.Font(constants.MENU_FONT, constants.MENU_FONT_SIZE_ACTIVE) media.play_music('intro') def setup(self, first_time=False): # Selected menu choice - if "Continue" is there, have that selected self._current_option = NEW_GAME if first_time else CONTINUE self.game_running = self.manager.get_state('main', 'running') def render_options(self, screen): x, y = 30, 30 for index, (text, action, show) in enumerate(OPTIONS): if show is not None and not show(self): continue active = index == self._current_option font = self.active_font if active else self.font surf = font.render(text, True, constants.MENU_FONT_COLOR) screen.blit(surf, (x, y)) if active: screen.blit(media['img.arrow'], (x - 25, y + 12)) y += surf.get_height() + 10 def render(self, screen): screen.blit(media['img.title'], (0, 0)) self.render_options(screen) def opt_continue(self): self.manager.switch_scene('main') return True def new_match(self, player1, player2): media.fade_music(1000) gamestate.new_game(player1, player2) self.manager.switch_scene('main') return True def start_2_player(self): self.new_match(gamestate.HUMAN, gamestate.HUMAN) def start_vs_cpu(self): self.new_match(gamestate.HUMAN, EasyAI()) def start_cpu_vs_cpu(self): self.new_match(EasyAI(), EasyAI()) def opt_quit(self): sys.exit() def do_event(self, event): if event.type == pygame.KEYUP: if event.key == pygame.K_ESCAPE: if self.game_running: self.manager.switch_scene('main') return elif event.key in (pygame.K_UP, pygame.K_DOWN): media['snd.button'].play() move = -1 if event.key == pygame.K_UP else 1 self._current_option = (self._current_option + move) % len(OPTIONS) if self._current_option == CONTINUE and not self.game_running: self._current_option = NEW_GAME if event.key == pygame.K_DOWN else (len(OPTIONS) - 1) elif event.key == pygame.K_RETURN: if self._current_option != NEW_GAME: media['snd.button_press'].play() action = OPTIONS[self._current_option][1] return getattr(self, action)() return False<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from quicktions import Fraction from . import ( _update, deprecated, enumerate, format, get, illustrators, io, iterate, iterpitches, lyconst, lyenv, makers, mutate, persist, string, wf, ) from ._version import __version__, __version_info__ from .bind import Wrapper, annotate, attach, detach from .bundle import LilyPondFormatBundle, SlotContributions from .configuration import ( Configuration, list_all_classes, list_all_functions, yield_all_modules, ) from .contextmanagers import ( ContextManager, FilesystemState, ForbidUpdate, NullContextManager, ProgressIndicator, RedirectedStreams, TemporaryDirectory, TemporaryDirectoryChange, Timer, ) from .cyclictuple import CyclicTuple from .duration import Duration, Multiplier, NonreducedFraction, Offset from .dynamic import Dynamic from .enums import ( Center, Comparison, Down, Exact, HorizontalAlignment, Left, Less, Middle, More, Right, Up, VerticalAlignment, ) from .exceptions import ( AssignabilityError, ImpreciseMetronomeMarkError, LilyPondParserError, MissingMetronomeMarkError, ParentageError, PersistentIndicatorError, SchemeParserFinishedError, UnboundedTimeIntervalError, WellformednessError, ) from .format import lilypond from .get import Lineage from .illustrators import illustrate from .indicators import ( Arpeggio, Articulation, BarLine, BeamCount, BendAfter, BreathMark, Clef, ColorFingering, Fermata, Glissando, KeyCluster, KeySignature, LaissezVibrer, MarginMarkup, MetronomeMark, Mode, Ottava, RehearsalMark, Repeat, RepeatTie, StaffChange, StaffPosition, StartBeam, StartGroup, StartHairpin, StartMarkup, StartPhrasingSlur, StartPianoPedal, StartSlur, StartTextSpan, StartTrillSpan, StemTremolo, StopBeam, StopGroup, StopHairpin, StopPhrasingSlur, StopPianoPedal, StopSlur, StopTextSpan, StopTrillSpan, Tie, TimeSignature, ) from .instruments import ( Accordion, AltoFlute, AltoSaxophone, AltoTrombone, AltoVoice, BaritoneSaxophone, BaritoneVoice, BassClarinet, BassFlute, BassSaxophone, BassTrombone, BassVoice, Bassoon, Cello, ClarinetInA, ClarinetInBFlat, ClarinetInEFlat, Contrabass, ContrabassClarinet, ContrabassFlute, ContrabassSaxophone, Contrabassoon, EnglishHorn, Flute, FrenchHorn, Glockenspiel, Guitar, Harp, Harpsichord, Instrument, Marimba, MezzoSopranoVoice, Oboe, Percussion, Piano, Piccolo, SopraninoSaxophone, SopranoSaxophone, SopranoVoice, StringNumber, TenorSaxophone, TenorTrombone, TenorVoice, Trumpet, Tuba, Tuning, Vibraphone, Viola, Violin, Xylophone, ) from .io import graph, show from .label import ColorMap from .lilypondfile import Block, LilyPondFile from .lyproxy import ( LilyPondContext, LilyPondEngraver, LilyPondGrob, LilyPondGrobInterface, ) from .makers import LeafMaker, NoteMaker from .markups import Markup from .math import Infinity, NegativeInfinity from .meter import Meter, MeterList, MetricAccentKernel from .metricmodulation import MetricModulation from .obgc import OnBeatGraceContainer, on_beat_grace_container from .overrides import ( IndexedTweakManager, IndexedTweakManagers, Interface, LilyPondLiteral, LilyPondOverride, LilyPondSetting, OverrideInterface, SettingInterface, TweakInterface, override, setting, tweak, ) from .parentage import Parentage from .parsers import parser from .parsers.base import Parser from .parsers.parse import parse from .pattern import Pattern, PatternTuple from .pcollections import ( IntervalClassSegment, IntervalClassSet, IntervalSegment, IntervalSet, PitchClassSegment, PitchClassSet, PitchRange, PitchSegment, PitchSet, Segment, Set, TwelveToneRow, ) from .pitch import ( Accidental, Interval, IntervalClass, NamedInterval, NamedIntervalClass, NamedInversionEquivalentIntervalClass, NamedPitch, NamedPitchClass, NumberedInterval, NumberedIntervalClass, NumberedInversionEquivalentIntervalClass, NumberedPitch, NumberedPitchClass, Octave, Pitch, PitchClass, PitchTyping, ) from .ratio import NonreducedRatio, Ratio from .score import ( AfterGraceContainer, BeforeGraceContainer, Chord, Cluster, Component, Container, Context, DrumNoteHead, Leaf, MultimeasureRest, Note, NoteHead, NoteHeadList, Rest, Score, Skip, Staff, StaffGroup, TremoloContainer, Tuplet, Voice, ) from .select import LogicalTie, Selection from .setclass import SetClass from .spanners import ( beam, glissando, hairpin, horizontal_bracket, ottava, phrasing_slur, piano_pedal, slur, text_spanner, tie, trill_spanner, ) from .tag import Line, Tag, activate, deactivate from .timespan import OffsetCounter, Timespan, TimespanList from .typedcollections import TypedCollection, TypedFrozenset, TypedList, TypedTuple from .typings import ( DurationSequenceTyping, DurationTyping, IntegerPair, IntegerSequence, Number, NumberPair, PatternTyping, Prototype, RatioSequenceTyping, RatioTyping, Strings, ) from .verticalmoment import ( VerticalMoment, iterate_leaf_pairs, iterate_pitch_pairs, iterate_vertical_moments, ) index = Pattern.index index_all = Pattern.index_all index_first = Pattern.index_first index_last = Pattern.index_last __all__ = [ "Accidental", "Accordion", "AfterGraceContainer", "AltoFlute", "AltoSaxophone", "AltoTrombone", "AltoVoice", "Arpeggio", "Articulation", "AssignabilityError", "BarLine", "BaritoneSaxophone", "BaritoneVoice", "BassClarinet", "BassFlute", "BassSaxophone", "BassTrombone", "BassVoice", "Bassoon", "BeamCount", "BeforeGraceContainer", "BendAfter", "Block", "BreathMark", "Cello", "Center", "Chord", "ClarinetInA", "ClarinetInBFlat", "ClarinetInEFlat", "Clef", "Cluster", "ColorFingering", "ColorMap", "Comparison", "Component", "Configuration", "Container", "Context", "ContextManager", "Contrabass", "ContrabassClarinet", "ContrabassFlute", "ContrabassSaxophone", "Contrabassoon", "CyclicTuple", "Down", "DrumNoteHead", "Duration", "DurationSequenceTyping", "DurationTyping", "Dynamic", "EnglishHorn", "Exact", "Expression", "Fermata", "FilesystemState", "Flute", "ForbidUpdate", "Fraction", "FrenchHorn", "Glissando", "Glockenspiel", "Guitar", "Harp", "Harpsichord", "HorizontalAlignment", "ImpreciseMetronomeMarkError", "IndexedTweakManager", "IndexedTweakManagers", "Infinity", "Instrument", "IntegerPair", "IntegerSequence", "Interface", "Interval", "IntervalClass", "IntervalClassSegment", "IntervalClassSet", "IntervalSegment", "IntervalSet", "KeyCluster", "KeySignature", "LaissezVibrer",<|fim▁hole|> "Less", "LilyPondContext", "LilyPondEngraver", "LilyPondFile", "LilyPondFormatBundle", "LilyPondGrob", "LilyPondGrobInterface", "LilyPondLiteral", "LilyPondOverride", "LilyPondParserError", "LilyPondSetting", "Line", "Lineage", "LogicalTie", "MarginMarkup", "Marimba", "Markup", "Meter", "MeterList", "MetricAccentKernel", "MetricModulation", "MetronomeMark", "MezzoSopranoVoice", "Middle", "MissingMetronomeMarkError", "Mode", "More", "MultimeasureRest", "Multiplier", "NamedInterval", "NamedIntervalClass", "NamedInversionEquivalentIntervalClass", "NamedPitch", "NamedPitchClass", "NegativeInfinity", "NonreducedFraction", "NonreducedRatio", "Note", "NoteHead", "NoteHeadList", "NoteMaker", "NullContextManager", "Number", "NumberPair", "NumberedInterval", "NumberedIntervalClass", "NumberedInversionEquivalentIntervalClass", "NumberedPitch", "NumberedPitchClass", "Oboe", "Octave", "Offset", "OffsetCounter", "OnBeatGraceContainer", "Ottava", "OverrideInterface", "Parentage", "ParentageError", "Parser", "Pattern", "PatternTuple", "PatternTyping", "Percussion", "PersistentIndicatorError", "Piano", "Piccolo", "Pitch", "PitchClass", "PitchClassSegment", "PitchClassSet", "PitchRange", "PitchSegment", "PitchSet", "PitchTyping", "ProgressIndicator", "Prototype", "Ratio", "RatioSequenceTyping", "RatioTyping", "RedirectedStreams", "RehearsalMark", "Repeat", "RepeatTie", "Rest", "Right", "SchemeParserFinishedError", "Score", "Segment", "Selection", "Set", "SetClass", "SettingInterface", "Skip", "SlotContributions", "SopraninoSaxophone", "SopranoSaxophone", "SopranoVoice", "Staff", "StaffChange", "StaffGroup", "StaffPosition", "StartBeam", "StartGroup", "StartHairpin", "StartMarkup", "StartPhrasingSlur", "StartPianoPedal", "StartSlur", "StartTextSpan", "StartTrillSpan", "StemTremolo", "StopBeam", "StopGroup", "StopHairpin", "StopPhrasingSlur", "StopPianoPedal", "StopSlur", "StopTextSpan", "StopTrillSpan", "StringNumber", "Strings", "Tag", "TemporaryDirectory", "TemporaryDirectoryChange", "TenorSaxophone", "TenorTrombone", "TenorVoice", "Tie", "TimeSignature", "Timer", "Timespan", "TimespanList", "TremoloContainer", "Trumpet", "Tuba", "Tuning", "Tuplet", "TweakInterface", "TwelveToneRow", "TypedCollection", "TypedFrozenset", "TypedList", "TypedTuple", "UnboundedTimeIntervalError", "Up", "VerticalAlignment", "VerticalMoment", "Vibraphone", "Viola", "Violin", "Voice", "WellformednessError", "Wrapper", "Xylophone", "__version__", "__version_info__", "_update", "activate", "annotate", "attach", "beam", "deactivate", "deprecated", "detach", "enumerate", "format", "glissando", "graph", "hairpin", "horizontal_bracket", "illustrate", "illustrators", "index", "index_all", "index_first", "index_last", "get", "io", "iterate", "iterate_leaf_pairs", "iterate_pitch_pairs", "iterate_vertical_moments", "iterpitches", "label", "list_all_classes", "list_all_functions", "lilypond", "lyconst", "lyenv", "makers", "mutate", "on_beat_grace_container", "ottava", "override", "parse", "parser", "persist", "phrasing_slur", "piano_pedal", "select", "setting", "show", "slur", "string", "text_spanner", "tie", "trill_spanner", "tweak", "wf", "yield_all_modules", ]<|fim▁end|>
"Leaf", "LeafMaker", "Left",
<|file_name|>Email.ts<|end_file_name|><|fim▁begin|>/* * Copyright 2015-2017 Atomist Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { GraphNode } from "@atomist/rug/tree/PathExpression"; import * as api from "../Email"; import { Person } from "./Person"; export { Email }; /* * Type Email * * Generated class exposing Atomist Cortex. * Fluent builder style class for use in testing and query by example.<|fim▁hole|> private _address: string; private _of: Person; nodeName(): string { return "Email"; } nodeTags(): string[] { return [ "Email", "-dynamic" ]; } /** * String * * @returns {string} */ address(): string { return this._address; } withAddress(address: string): Email { this._address = address; return this; } /** * of - Email -> Person * * @returns {Person} */ of(): Person { return this._of; } withOf(of: Person): Email { this._of = of; return this; } }<|fim▁end|>
*/ class Email implements api.Email {
<|file_name|>InterfaceMethodBuilder.java<|end_file_name|><|fim▁begin|>package com.mistraltech.smogen.codegenerator.javabuilder;<|fim▁hole|>public class InterfaceMethodBuilder extends MethodSignatureBuilder<InterfaceMethodBuilder> { private InterfaceMethodBuilder() { } public static InterfaceMethodBuilder anInterfaceMethod() { return new InterfaceMethodBuilder(); } @Override public String build(JavaBuilderContext context) { return super.build(context) + ";"; } }<|fim▁end|>
<|file_name|>webpackfile.js<|end_file_name|><|fim▁begin|>const Webpack = require('webpack') const CopyWebpackPlugin = require('copy-webpack-plugin')<|fim▁hole|> const dependencies = package.dependencies return Object .keys(dependencies) .reduce((modules, module) => Object.assign({}, modules, { [module]: `commonjs ${module}` }), {} ) } module.exports = { context: join(__dirname, './build'), entry: { boleto: './resources/boleto/index.js', database: './functions/database/index.js' }, output: { path: join(__dirname, './dist'), libraryTarget: 'commonjs2', filename: '[name].js' }, devtool: 'inline-source-map', target: 'node', externals: externals(), module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: ['source-map-loader'], enforce: 'pre' } ] }, plugins: [ new Webpack.DefinePlugin({ 'process.env.ENV': JSON.stringify('production'), 'process.env.NODE_ENV': JSON.stringify('production'), }), new Webpack.BannerPlugin({ banner: ` require("source-map-support").install(); require("core-js"); `, raw: true, entryOnly: false }), new CopyWebpackPlugin([{ from: './database/migrations', to: './migrations', context: join(__dirname, './build') }]) ] }<|fim▁end|>
const package = require('./package.json') const { join } = require('path') const externals = () => {
<|file_name|>model_list.go<|end_file_name|><|fim▁begin|>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package automl contains samples for Google Cloud AutoML API v1. package automl // [START automl_list_models] import ( "context" "fmt" "io" automl "cloud.google.com/go/automl/apiv1" "google.golang.org/api/iterator" automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" ) // listModels lists existing models. func listModels(w io.Writer, projectID string, location string) error { // projectID := "my-project-id" // location := "us-central1" ctx := context.Background() client, err := automl.NewClient(ctx) if err != nil { return fmt.Errorf("NewClient: %v", err) } defer client.Close() req := &automlpb.ListModelsRequest{ Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location), } it := client.ListModels(ctx, req) // Iterate over all results for { model, err := it.Next() if err == iterator.Done { break } if err != nil { return fmt.Errorf("ListModels.Next: %v", err) } // Retrieve deployment state. deploymentState := "undeployed" if model.GetDeploymentState() == automlpb.Model_DEPLOYED { deploymentState = "deployed" } // Display the model information. fmt.Fprintf(w, "Model name: %v\n", model.GetName()) fmt.Fprintf(w, "Model display name: %v\n", model.GetDisplayName()) fmt.Fprintf(w, "Model create time:\n") fmt.Fprintf(w, "\tseconds: %v\n", model.GetCreateTime().GetSeconds()) fmt.Fprintf(w, "\tnanos: %v\n", model.GetCreateTime().GetNanos())<|fim▁hole|> fmt.Fprintf(w, "Model deployment state: %v\n", deploymentState) } return nil } // [END automl_list_models]<|fim▁end|>
<|file_name|>draw.js<|end_file_name|><|fim▁begin|>'use strict'; angular.module('depthyApp') .controller('DrawCtrl', function ($scope, $element, depthy, $window, $timeout) { var drawer = depthy.drawMode, viewer = depthy.getViewer(), lastPointerPos = null, oldViewerOpts = angular.extend({}, depthy.viewer); drawer.setOptions(depthy.drawOptions || { depth: 0.5, size: 0.05, hardness: 0.5, opacity: 0.25, }); angular.extend(depthy.viewer, { animate: false, fit: 'contain', upscale: 2, // depthPreview: 0.75, // orient: false, // hover: false, }); $scope.drawer = drawer; $scope.drawOpts = drawer.getOptions(); $scope.preview = 1; $scope.brushMode = false; $scope.$watch('drawOpts', function(options) { if (drawer && options) { drawer.setOptions(options); } }, true); $scope.$watch('preview', function(preview) { depthy.viewer.orient = preview === 2; depthy.viewer.hover = preview === 2; depthy.viewer.animate = preview === 2 && oldViewerOpts.animate; depthy.viewer.quality = preview === 2 ? false : 1; depthy.animateOption(depthy.viewer, { depthPreview: preview === 0 ? 1 : preview === 1 ? 0.75 : 0, depthScale: preview === 2 ? oldViewerOpts.depthScale : 0, depthBlurSize: preview === 2 ? oldViewerOpts.depthBlurSize : 0, enlarge: 1.0, }, 250); }); $scope.togglePreview = function() { console.log('togglePreview', $scope.preview); // $scope.preview = ++$scope.preview % 3; $scope.preview = $scope.preview === 1 ? 2 : 1; }; $scope.done = function() { $window.history.back(); }; $scope.cancel = function() { drawer.cancel(); $window.history.back(); }; $scope.brushIcon = function() { switch($scope.brushMode) { case 'picker': return 'target'; case 'level': return 'magnet'; default: return 'draw'; } }; $element.on('touchstart mousedown', function(e) { console.log('mousedown'); var event = e.originalEvent, pointerEvent = event.touches ? event.touches[0] : event; if (event.target.id !== 'draw') return; lastPointerPos = viewer.screenToImagePos({x: pointerEvent.pageX, y: pointerEvent.pageY}); if ($scope.brushMode === 'picker' || $scope.brushMode === 'level') { $scope.drawOpts.depth = drawer.getDepthAtPos(lastPointerPos); console.log('Picked %s', $scope.drawOpts.depth); if ($scope.brushMode === 'picker') { $scope.brushMode = false; lastPointerPos = null; $scope.$safeApply(); event.preventDefault(); event.stopPropagation(); return; } else { $scope.$safeApply(); } } drawer.drawBrush(lastPointerPos); // updateDepthMap(); event.preventDefault(); event.stopPropagation(); }); $element.on('touchmove mousemove', function(e) { if (lastPointerPos) { var event = e.originalEvent, pointerEvent = event.touches ? event.touches[0] : event, pointerPos = viewer.screenToImagePos({x: pointerEvent.pageX, y: pointerEvent.pageY}); drawer.drawBrushTo(pointerPos); lastPointerPos = pointerPos; } }); $element.on('touchend mouseup', function(event) { console.log('mouseup', event); if (lastPointerPos) { lastPointerPos = null; $scope.$safeApply(); } // if(window.location.href.indexOf('preview')<0){ // updateDepthMap(); // } }); $element.on('click', function(e) { console.log('click'); // updateDepthMap(); }); function getSliderForKey(e) { var id = 'draw-brush-depth'; if (e.shiftKey && e.altKey) { id = 'draw-brush-hardness'; } else if (e.altKey) { id = 'draw-brush-opacity'; } else if (e.shiftKey) { id = 'draw-brush-size'; } var el = $element.find('.' + id + ' [range-stepper]'); el.click(); // simulate click to notify change return el.controller('rangeStepper'); } function onKeyDown(e) { console.log('keydown', e); var s, handled = false; console.log('keydown which %d shift %s alt %s ctrl %s', e.which, e.shiftKey, e.altKey, e.ctrlKey); if (e.which === 48) { // 0 getSliderForKey(e).percent(0.5); handled = true; } else if (e.which >= 49 && e.which <= 57) { // 1-9 getSliderForKey(e).percent((e.which - 49) / 8); handled = true; } else if (e.which === 189) { // - s = getSliderForKey(e); s.percent(s.percent() - 0.025); handled = true; } else if (e.which === 187) { // + s = getSliderForKey(e); s.percent(s.percent() + 0.025); handled = true; } else if (e.which === 32) { $element.find('.draw-preview').click(); handled = true; } else if (e.which === 90) { // z $element.find('.draw-undo').click(); handled = true; } else if (e.which === 80) { // p $element.find('.draw-picker').click(); handled = true; } else if (e.which === 76) { // l $element.find('.draw-level').click(); handled = true; } else if (e.which === 81) { // l $scope.preview = $scope.preview === 1 ? 2 : 1; handled = true; } if (handled) { e.preventDefault(); $scope.$safeApply(); } } $($window).on('keydown', onKeyDown); $element.find('.draw-brush-depth').on('touchstart mousedown click', function() { $scope.brushMode = false; }); $element.on('$destroy', function() { $element.off('touchstart mousedown'); $element.off('touchmove mousemove'); $($window).off('keydown', onKeyDown); <|fim▁hole|> enlarge: oldViewerOpts.enlarge, }, 250); $timeout(function() { angular.extend(depthy.viewer, oldViewerOpts); }, 251); if (drawer.isCanceled()) { // restore opened depthmap viewer.setDepthmap(depthy.opened.depthSource, depthy.opened.depthUsesAlpha); } else { if (drawer.isModified()) { updateDepthMap(); } } drawer.destroy(true); }); function updateDepthMap(){ depthy.drawOptions = drawer.getOptions(); // remember drawn depthmap // store it as jpg console.log('updateDepthMap',viewer); viewer.exportDepthmap().then(function(url) { depthy.opened.markAsModified(); depthy.opened.depthSource = url; //viewer.getDepthmap().texture; depthy.opened.depthUsesAlpha = false; viewer.setDepthmap(url); depthy.opened.onDepthmapOpened(); localStorage.depthMapUrl = url; var intercom = Intercom.getInstance(); intercom.emit('depthMapUrl', {message: url}); }); } });<|fim▁end|>
depthy.animateOption(depthy.viewer, { depthPreview: oldViewerOpts.depthPreview, depthScale: oldViewerOpts.depthScale, depthBlurSize: oldViewerOpts.depthBlurSize,
<|file_name|>typo-suggestion.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let foo = 1; // `foo` shouldn't be suggested, it is too dissimilar from `bar`. println!("Hello {}", bar); //~ ERROR cannot find value // But this is close enough.<|fim▁hole|><|fim▁end|>
println!("Hello {}", fob); //~ ERROR cannot find value }