code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// RUN: %clang_cc1 -std=c++11 -triple x86_64-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix=LINUX // RUN: %clang_cc1 -std=c++11 -triple x86_64-windows-pc -emit-llvm %s -o - | FileCheck %s --check-prefix=WINDOWS int __attribute__((target("sse4.2"))) foo_overload(int) { return 0; } int __attribute__((target("arch=sandybridge"))) foo_overload(int); int __attribute__((target("arch=ivybridge"))) foo_overload(int) {return 1;} int __attribute__((target("default"))) foo_overload(int) { return 2; } int __attribute__((target("sse4.2"))) foo_overload(void) { return 0; } int __attribute__((target("arch=sandybridge"))) foo_overload(void); int __attribute__((target("arch=ivybridge"))) foo_overload(void) {return 1;} int __attribute__((target("default"))) foo_overload(void) { return 2; } int bar2() { return foo_overload() + foo_overload(1); } // LINUX: @_Z12foo_overloadv.ifunc = weak_odr ifunc i32 (), i32 ()* ()* @_Z12foo_overloadv.resolver // LINUX: @_Z12foo_overloadi.ifunc = weak_odr ifunc i32 (i32), i32 (i32)* ()* @_Z12foo_overloadi.resolver // LINUX: define{{.*}} i32 @_Z12foo_overloadi.sse4.2(i32 %0) // LINUX: ret i32 0 // LINUX: define{{.*}} i32 @_Z12foo_overloadi.arch_ivybridge(i32 %0) // LINUX: ret i32 1 // LINUX: define{{.*}} i32 @_Z12foo_overloadi(i32 %0) // LINUX: ret i32 2 // LINUX: define{{.*}} i32 @_Z12foo_overloadv.sse4.2() // LINUX: ret i32 0 // LINUX: define{{.*}} i32 @_Z12foo_overloadv.arch_ivybridge() // LINUX: ret i32 1 // LINUX: define{{.*}} i32 @_Z12foo_overloadv() // LINUX: ret i32 2 // WINDOWS: define dso_local i32 @"?foo_overload@@YAHH@Z.sse4.2"(i32 %0) // WINDOWS: ret i32 0 // WINDOWS: define dso_local i32 @"?foo_overload@@YAHH@Z.arch_ivybridge"(i32 %0) // WINDOWS: ret i32 1 // WINDOWS: define dso_local i32 @"?foo_overload@@YAHH@Z"(i32 %0) // WINDOWS: ret i32 2 // WINDOWS: define dso_local i32 @"?foo_overload@@YAHXZ.sse4.2"() // WINDOWS: ret i32 0 // WINDOWS: define dso_local i32 @"?foo_overload@@YAHXZ.arch_ivybridge"() // WINDOWS: ret i32 1 // WINDOWS: define dso_local i32 @"?foo_overload@@YAHXZ"() // WINDOWS: ret i32 2 // LINUX: define{{.*}} i32 @_Z4bar2v() // LINUX: call i32 @_Z12foo_overloadv.ifunc() // LINUX: call i32 @_Z12foo_overloadi.ifunc(i32 1) // WINDOWS: define dso_local i32 @"?bar2@@YAHXZ"() // WINDOWS: call i32 @"?foo_overload@@YAHXZ.resolver"() // WINDOWS: call i32 @"?foo_overload@@YAHH@Z.resolver"(i32 1) // LINUX: define weak_odr i32 ()* @_Z12foo_overloadv.resolver() comdat // LINUX: ret i32 ()* @_Z12foo_overloadv.arch_sandybridge // LINUX: ret i32 ()* @_Z12foo_overloadv.arch_ivybridge // LINUX: ret i32 ()* @_Z12foo_overloadv.sse4.2 // LINUX: ret i32 ()* @_Z12foo_overloadv // WINDOWS: define weak_odr dso_local i32 @"?foo_overload@@YAHXZ.resolver"() comdat // WINDOWS: call i32 @"?foo_overload@@YAHXZ.arch_sandybridge" // WINDOWS: call i32 @"?foo_overload@@YAHXZ.arch_ivybridge" // WINDOWS: call i32 @"?foo_overload@@YAHXZ.sse4.2" // WINDOWS: call i32 @"?foo_overload@@YAHXZ" // LINUX: define weak_odr i32 (i32)* @_Z12foo_overloadi.resolver() comdat // LINUX: ret i32 (i32)* @_Z12foo_overloadi.arch_sandybridge // LINUX: ret i32 (i32)* @_Z12foo_overloadi.arch_ivybridge // LINUX: ret i32 (i32)* @_Z12foo_overloadi.sse4.2 // LINUX: ret i32 (i32)* @_Z12foo_overloadi // WINDOWS: define weak_odr dso_local i32 @"?foo_overload@@YAHH@Z.resolver"(i32 %0) comdat // WINDOWS: call i32 @"?foo_overload@@YAHH@Z.arch_sandybridge" // WINDOWS: call i32 @"?foo_overload@@YAHH@Z.arch_ivybridge" // WINDOWS: call i32 @"?foo_overload@@YAHH@Z.sse4.2" // WINDOWS: call i32 @"?foo_overload@@YAHH@Z" // LINUX: declare i32 @_Z12foo_overloadv.arch_sandybridge() // LINUX: declare i32 @_Z12foo_overloadi.arch_sandybridge(i32) // WINDOWS: declare dso_local i32 @"?foo_overload@@YAHXZ.arch_sandybridge"() // WINDOWS: declare dso_local i32 @"?foo_overload@@YAHH@Z.arch_sandybridge"(i32)
sabel83/metashell
3rd/templight/clang/test/CodeGenCXX/attr-target-mv-overloads.cpp
C++
gpl-3.0
3,859
/* * #%L * GeoWE Project * %% * Copyright (C) 2015 - 2016 GeoWE.org * %% * This file is part of GeoWE.org. * * GeoWE 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. * * GeoWE 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 GeoWE. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.geowe.client.local.main.tool.project; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import org.geowe.client.local.ImageProvider; import org.geowe.client.local.main.tool.ButtonTool; import org.geowe.client.local.messages.UIMessages; import org.geowe.client.local.ui.ProgressBarDialog; import org.jboss.errai.common.client.api.tasks.ClientTaskManager; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.DOM; import com.google.inject.Inject; import com.sencha.gxt.core.client.Style.Side; import com.sencha.gxt.widget.core.client.Dialog.PredefinedButton; import com.sencha.gxt.widget.core.client.box.AlertMessageBox; import com.sencha.gxt.widget.core.client.event.SelectEvent; import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler; import com.sencha.gxt.widget.core.client.event.SubmitCompleteEvent; import com.sencha.gxt.widget.core.client.event.SubmitCompleteEvent.SubmitCompleteHandler; /** * Responsable de cargar la configuración de un proyecto de geowe * * @author jose@geowe.org * @since 11-02-2017 * @author rafa@geowe.org * fix issue 303 * */ @ApplicationScoped public class OpenProjectTool extends ButtonTool { private ProgressBarDialog autoMessageBox; @Inject private ClientTaskManager taskManager; @Inject private OpenProjectDialog openProjectDialog; @Inject private ProjectLoader projectLoader; @Inject private URLProjectLoader urlProjectLoader; public OpenProjectTool() { super(UIMessages.INSTANCE.openProject(), ImageProvider.INSTANCE .openProject24()); setToolTipConfig(createTooltipConfig(UIMessages.INSTANCE.openProject(), UIMessages.INSTANCE.openProjectToolTipText(), Side.LEFT)); } @Override protected void onRelease() { openProjectDialog.clear(); openProjectDialog.show(); } @PostConstruct private void initialize() { addDialogListener(); addCloseButtonHandler(); openProjectDialog.getUploadPanel().addSubmitCompleteHandler(new SubmitCompleteHandler() { public void onSubmitComplete(final SubmitCompleteEvent event) { final Element label = DOM.createLabel(); label.setInnerHTML(event.getResults()); final String jsonProject = label.getInnerText(); openProjectDialog.hide(); if (hasError(jsonProject)) { autoMessageBox.hide(); showAlert("Error: " + jsonProject); return; } projectLoader.load(jsonProject); autoMessageBox.hide(); } private boolean hasError(final String contentFile) { return contentFile.startsWith("413") || contentFile.startsWith("500") || contentFile.startsWith("204") || contentFile.startsWith("406"); } }); } private void showAlert(final String errorMsg) { AlertMessageBox messageBox = new AlertMessageBox( UIMessages.INSTANCE.warning(), errorMsg); messageBox.show(); } private void addDialogListener() { openProjectDialog.getButton(PredefinedButton.OK).addSelectHandler(new SelectHandler() { @Override public void onSelect(final SelectEvent event) { taskManager.execute(new Runnable() { @Override public void run() { if (openProjectDialog.getActiveTab().equals(UIMessages.INSTANCE.file())) { if(openProjectDialog.isFileFieldCorrectFilled()){ autoMessageBox = new ProgressBarDialog(false, UIMessages.INSTANCE.processing()); autoMessageBox.show(); openProjectDialog.getUploadPanel().submit(); }else{ showAlert(UIMessages.INSTANCE.lrasterdAlertMessageBoxLabel(UIMessages.INSTANCE.file())); } } if (openProjectDialog.getActiveTab().equals(UIMessages.INSTANCE.url())) { if(openProjectDialog.isurlFieldCorrectFilled()){ urlProjectLoader.open(urlProjectLoader, openProjectDialog.getUrl()); openProjectDialog.hide(); }else{ showAlert(UIMessages.INSTANCE.lrasterdAlertMessageBoxLabel(UIMessages.INSTANCE.url())); } } } }); } }); } protected void addCloseButtonHandler() { openProjectDialog.getButton(PredefinedButton.CANCEL).addSelectHandler( new SelectHandler() { @Override public void onSelect(SelectEvent event) { openProjectDialog.hide(); } }); } }
geowe/geowe-core
src/main/java/org/geowe/client/local/main/tool/project/OpenProjectTool.java
Java
gpl-3.0
5,059
<?php /** * The template for displaying all WooCommerce pages. * * @package zerif-lite */ get_header(); ?> <div class="clear"></div> </header> <!-- / END HOME SECTION --> <?php zerif_after_header_trigger(); ?> <div id="content" class="site-content"> <div class="container"> <div class="content-left-wrap col-md-12"> <div id="primary" class="content-area"> <main id="main" class="site-main"> <?php woocommerce_content(); ?> </main><!-- #main --> </div><!-- #primary --> </div><!-- .content-left-wrap --> </div><!-- .container --> <?php get_footer(); ?>
Codeinwp/zerif-lite
woocommerce.php
PHP
gpl-3.0
594
namespace OmniXaml.Wpf { using System.Threading.Tasks; using System.Windows; using Services.Mvvm; public class WpfWindow : Window, IView { public new Task ShowDialog() { return new Task(() => this.ShowDialog()); } public void SetViewModel(object viewModel) { this.DataContext = viewModel; } } }
grokys/OmniXAML
Source/OmniXaml.Wpf/WpfWindow.cs
C#
gpl-3.0
400
/* * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. * * 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 <ORGANIZATION> 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. * */ /* * cci_log.cpp - */ #include <errno.h> #include <stdarg.h> #if defined(WINDOWS) #include <winsock2.h> #include <windows.h> #include <time.h> #include <direct.h> #include <io.h> #else #include <sys/time.h> #include <sys/stat.h> #if !defined(AIX) #include <sys/syscall.h> #endif #include <unistd.h> #endif #include <iostream> #include <fstream> #include <string> #include <map> #include <list> #include <sstream> #include "cci_common.h" #include "cci_mutex.h" #include "cci_log.h" static const int ONE_DAY = 86400; static const int LOG_BUFFER_SIZE = 1024 * 20; static const int LOG_ER_OPEN = -1; static const long int LOG_FLUSH_SIZE = 1024 * 1024; /* byte */ static const long int LOG_FLUSH_USEC = 1 * 1000000; /* usec */ static const long int LOG_CHECK_FILE_INTERVAL_USEC = 10 * 1000000; /* usec */ static const char *cci_log_level_string[] = { "OFF", "ERROR", "WARN", "INFO", "DEBUG" }; struct _LoggerContext; class _Logger; class _LogAppender { public: _LogAppender(const _LoggerContext &context); virtual ~_LogAppender() {} virtual void open() = 0; virtual void close() = 0; virtual void write(const char *msg) = 0; virtual void flush() = 0; protected: const _LoggerContext &context; }; class _LogAppenderBase : public _LogAppender { public: _LogAppenderBase(const _LoggerContext &context); virtual ~_LogAppenderBase(); virtual void open(); virtual void close(); virtual void write(const char *msg); virtual void flush(); protected: virtual void roll() = 0; virtual bool isRolling() = 0; std::string rename(const char *newPath, const char *postfix); int getLogSizeKBytes(); std::string getCurrDate(); std::string getCurrDateTime(); void makeLogDir(); private: void checkFileIsOpen(); protected: std::ofstream out; long int nextCheckTime; }; class _PostFixAppender : public _LogAppenderBase { public: _PostFixAppender(const _LoggerContext &context, CCI_LOG_POSTFIX postfix); virtual ~_PostFixAppender() {} virtual void open(); protected: virtual void roll(); virtual bool isRolling(); private: void checkFileIsOpen(); std::string getNewPath(); private: CCI_LOG_POSTFIX postfix; int prevDate; }; class _MaxSizeLogAppender : public _LogAppenderBase { public: _MaxSizeLogAppender(const _LoggerContext &context, int maxFileSizeKBytes, int maxBackupCount); virtual ~_MaxSizeLogAppender() {} protected: virtual void roll(); virtual bool isRolling(); private: int maxFileSizeKBytes; int maxBackupCount; int currBackupCount; std::list<std::string> backupList; }; class _DailyLogAppender : public _LogAppenderBase { public: _DailyLogAppender(const _LoggerContext &context); virtual ~_DailyLogAppender() {} protected: virtual void roll(); virtual bool isRolling(); private: int prevDate; }; struct _LoggerContext { std::string path; struct timeval now; }; class _Logger { public: _Logger(const char *path); virtual ~_Logger(); void setLogLevel(CCI_LOG_LEVEL level); void setUseDefaultPrefix(bool useDefaultPrefix); void setUseDefaultNewLine(bool useDefaultNewLine); void setForceFlush(bool isForceFlush); void log(CCI_LOG_LEVEL level, const char *msg); void changeMaxFileSizeAppender(int maxFileSizeKBytes, int maxBackupCount); void changePostfixAppender(CCI_LOG_POSTFIX postfix); public: const char *getPath(); bool isWritable(CCI_LOG_LEVEL level); private: void write(const char *msg); void logPrefix(CCI_LOG_LEVEL level); private: cci::_Mutex critical; _LoggerContext context; _LogAppender *logAppender; CCI_LOG_LEVEL level; bool useDefaultPrefix; bool useDefaultNewLine; bool isForceFlush; int unflushedBytes; unsigned long nextFlushTime; }; _LogAppender::_LogAppender(const _LoggerContext &context) : context(context) { } _LogAppenderBase::_LogAppenderBase(const _LoggerContext &context) : _LogAppender(context), nextCheckTime(0) { open(); } _LogAppenderBase::~_LogAppenderBase() { close(); } void _LogAppenderBase::open() { if (out.is_open()) { return; } makeLogDir(); out.open(context.path.c_str(), std::fstream::out | std::fstream::app); if (out.fail()) { out.open(context.path.c_str(), std::fstream::out | std::fstream::app); if (out.fail()) { throw LOG_ER_OPEN; } } } void _LogAppenderBase::close() { if (!out.is_open()) { return; } out.close(); } void _LogAppenderBase::write(const char *msg) { checkFileIsOpen(); try { if (!out.is_open()) { open(); } if (this->isRolling()) { this->roll(); } out << msg; } catch (...) { } } void _LogAppenderBase::flush() { if (!out.is_open()) { return; } out.flush(); } std::string _LogAppenderBase::rename(const char *newPath, const char *postfix) { std::stringstream newPathStream; newPathStream << newPath; close(); if (access(newPath, F_OK) == 0 && postfix != NULL) { newPathStream << postfix; } int e = std::rename(context.path.c_str(), newPathStream.str().c_str()); if (e != 0) { } try { open(); } catch (...) { } return newPathStream.str(); } int _LogAppenderBase::getLogSizeKBytes() { if (!out.is_open()) { return 0; } else { return out.tellp() / 1024; } } std::string _LogAppenderBase::getCurrDate() { struct tm cal; char buf[16]; time_t t = context.now.tv_sec; localtime_r(&t, &cal); cal.tm_year += 1900; cal.tm_mon += 1; snprintf(buf, 16, "%d-%02d-%02d", cal.tm_year, cal.tm_mon, cal.tm_mday); return buf; } std::string _LogAppenderBase::getCurrDateTime() { struct tm cal; char buf[16]; time_t t = context.now.tv_sec; localtime_r(&t, &cal); cal.tm_year += 1900; cal.tm_mon += 1; snprintf(buf, 16, "%d%02d%02d%02d%02d%02d", cal.tm_year, cal.tm_mon, cal.tm_mday, cal.tm_hour, cal.tm_min, cal.tm_sec); return buf; } void _LogAppenderBase::makeLogDir() { const char *sep = "/\\"; char dir[FILENAME_MAX]; char *p = dir; const char *q = context.path.c_str(); while (*q) { *p++ = *q; *p = '\0'; if (*q == sep[0] || *q == sep[1]) { mkdir(dir, 0755); } q++; } } void _LogAppenderBase::checkFileIsOpen() { long int currentTime = context.now.tv_sec * 1000000 + context.now.tv_usec; if (nextCheckTime == 0 || currentTime >= nextCheckTime) { if (access(context.path.c_str(), F_OK) != 0) { if (out.is_open()) { out.close(); } try { open(); } catch (...) { } } nextCheckTime = currentTime + LOG_CHECK_FILE_INTERVAL_USEC; } } _PostFixAppender::_PostFixAppender(const _LoggerContext &context, CCI_LOG_POSTFIX postfix) : _LogAppenderBase(context), postfix(postfix), prevDate(time(NULL) / ONE_DAY) { } void _PostFixAppender::open() { if (out.is_open()) { return; } makeLogDir(); std::string newPath = getNewPath(); out.open(newPath.c_str(), std::fstream::out | std::fstream::app); if (out.fail()) { out.open(newPath.c_str(), std::fstream::out | std::fstream::app); if (out.fail()) { throw LOG_ER_OPEN; } } } void _PostFixAppender::roll() { close(); try { open(); } catch (...) { } prevDate = context.now.tv_sec / ONE_DAY; } bool _PostFixAppender::isRolling() { if (postfix == CCI_LOG_POSTFIX_DATE) { int nowDay = context.now.tv_sec / ONE_DAY; return prevDate < nowDay; } else { return false; } } void _PostFixAppender::checkFileIsOpen() { long int currentTime = context.now.tv_sec * 1000000 + context.now.tv_usec; if (nextCheckTime == 0 || currentTime >= nextCheckTime) { std::string newPath = getNewPath(); if (access(newPath.c_str(), F_OK) != 0) { if (out.is_open()) { out.close(); } try { open(); } catch (...) { } } nextCheckTime = currentTime + LOG_CHECK_FILE_INTERVAL_USEC; } } std::string _PostFixAppender::getNewPath() { std::stringstream newPath; newPath << context.path; if (postfix == CCI_LOG_POSTFIX_DATE) { newPath << "." << getCurrDate(); } return newPath.str(); } _MaxSizeLogAppender::_MaxSizeLogAppender(const _LoggerContext &context, int maxFileSizeKBytes, int maxBackupCount) : _LogAppenderBase(context), maxFileSizeKBytes(maxFileSizeKBytes), maxBackupCount(maxBackupCount), currBackupCount(0) { } void _MaxSizeLogAppender::roll() { std::stringstream newPath_stream; newPath_stream << context.path << "." << getCurrDateTime(); std::stringstream postfix_stream; postfix_stream << "(" << currBackupCount++ << ")"; std::string newPath = rename(newPath_stream.str().c_str(), postfix_stream.str().c_str()); backupList.push_back(newPath); if (backupList.size() > (size_t) maxBackupCount) { std::string remove_path = backupList.front(); backupList.pop_front(); int e = remove(remove_path.c_str()); if (e != 0) { perror("remove"); } } } bool _MaxSizeLogAppender::isRolling() { return getLogSizeKBytes() > maxFileSizeKBytes; } _DailyLogAppender::_DailyLogAppender(const _LoggerContext &context) : _LogAppenderBase(context), prevDate(time(NULL) / ONE_DAY) { } void _DailyLogAppender::roll() { prevDate = context.now.tv_sec / ONE_DAY; std::stringstream newPathStream; newPathStream << context.path << "." << getCurrDate(); rename(newPathStream.str().c_str(), NULL); } bool _DailyLogAppender::isRolling() { int nowDay = context.now.tv_sec / ONE_DAY; return prevDate < nowDay; } _Logger::_Logger(const char *path) : logAppender(NULL), level(CCI_LOG_LEVEL_INFO), useDefaultPrefix(true), useDefaultNewLine(true), isForceFlush(true), unflushedBytes(0), nextFlushTime(0) { context.path = path; gettimeofday(&context.now, NULL); nextFlushTime = context.now.tv_usec + LOG_FLUSH_USEC; logAppender = new _DailyLogAppender(context); } _Logger::~_Logger() { cci::_MutexAutolock lock(&critical); if (logAppender != NULL) { delete logAppender; } } void _Logger::setLogLevel(CCI_LOG_LEVEL level) { cci::_MutexAutolock lock(&critical); this->level = level; } void _Logger::setUseDefaultPrefix(bool useDefaultPrefix) { cci::_MutexAutolock lock(&critical); this->useDefaultPrefix = useDefaultPrefix; } void _Logger::setUseDefaultNewLine(bool useDefaultNewLine) { cci::_MutexAutolock lock(&critical); this->useDefaultNewLine = useDefaultNewLine; } void _Logger::setForceFlush(bool isForceFlush) { cci::_MutexAutolock lock(&critical); this->isForceFlush = isForceFlush; } void _Logger::log(CCI_LOG_LEVEL level, const char *msg) { cci::_MutexAutolock lock(&critical); gettimeofday(&context.now, NULL); if (useDefaultPrefix) { logPrefix(level); } write(msg); if (useDefaultNewLine) { write("\n"); } } void _Logger::changeMaxFileSizeAppender(int maxFileSizeKBytes, int maxBackupCount) { cci::_MutexAutolock lock(&critical); if (this->logAppender != NULL) { delete this->logAppender; } this->logAppender = new _MaxSizeLogAppender(context, maxFileSizeKBytes, maxBackupCount); } void _Logger::changePostfixAppender(CCI_LOG_POSTFIX postfix) { cci::_MutexAutolock lock(&critical); if (this->logAppender != NULL) { delete this->logAppender; } if (postfix == CCI_LOG_POSTFIX_NONE) { this->logAppender = new _DailyLogAppender(context); } else { this->logAppender = new _PostFixAppender(context, postfix); } } const char *_Logger::getPath() { cci::_MutexAutolock lock(&critical); return context.path.c_str(); } bool _Logger::isWritable(CCI_LOG_LEVEL level) { cci::_MutexAutolock lock(&critical); return this->level >= level; } void _Logger::write(const char *msg) { logAppender->write(msg); unflushedBytes += strlen(msg); if (isForceFlush || unflushedBytes >= LOG_FLUSH_SIZE || nextFlushTime >= (unsigned long) context.now.tv_usec) { logAppender->flush(); unflushedBytes = 0; nextFlushTime = context.now.tv_usec + LOG_FLUSH_USEC; } } void _Logger::logPrefix(CCI_LOG_LEVEL level) { struct tm cal; time_t t; t = context.now.tv_sec; localtime_r((const time_t *) &t, &cal); cal.tm_year += 1900; cal.tm_mon += 1; char buf[128]; unsigned long tid = gettid(); snprintf(buf, 128, "%d-%02d-%02d %02d:%02d:%02d.%03d [TID:%lu] [%5s]", cal.tm_year, cal.tm_mon, cal.tm_mday, cal.tm_hour, cal.tm_min, cal.tm_sec, (int)(context.now.tv_usec / 1000), tid, cci_log_level_string[level]); write(buf); } typedef std::pair<_Logger *, int> _LoggerReference; typedef std::map<std::string, _LoggerReference> _LoggerMap; class _LoggerManager { public: _LoggerManager() {} virtual ~_LoggerManager() {} _Logger *getLogger(const char *path); void removeLogger(const char *path); void clearLogger(); private: cci::_Mutex critical; _LoggerMap map; }; _Logger *_LoggerManager::getLogger(const char *path) { cci::_MutexAutolock lock(&critical); _LoggerMap::iterator it = map.find(path); if (it == map.end()) { try { _Logger *logger = new _Logger(path); map[path] = _LoggerReference(logger, 1); return logger; } catch (...) { return NULL; } } else { it->second.second++; } return it->second.first; } void _LoggerManager::removeLogger(const char *path) { cci::_MutexAutolock lock(&critical); _LoggerMap::iterator it = map.find(path); if (it != map.end()) { it->second.second--; if (it->second.second == 0) { delete it->second.first; map.erase(it); } } } void _LoggerManager::clearLogger() { cci::_MutexAutolock lock(&critical); _LoggerMap::iterator it = map.begin(); for (; it != map.end(); it++) { delete it->second.first; } map.clear(); } static _LoggerManager loggerManager; Logger cci_log_add(const char *path) { return loggerManager.getLogger(path); } Logger cci_log_get(const char *path) { return loggerManager.getLogger(path); } void cci_log_finalize(void) { loggerManager.clearLogger(); } void cci_log_writef(CCI_LOG_LEVEL level, Logger logger, const char *format, ...) { _Logger *l = (_Logger *) logger; if (l == NULL) { return; } char buf[LOG_BUFFER_SIZE]; va_list vl; va_start(vl, format); vsnprintf(buf, LOG_BUFFER_SIZE, format, vl); va_end(vl); l->log(level, buf); } void cci_log_write(CCI_LOG_LEVEL level, Logger logger, const char *log) { _Logger *l = (_Logger *) logger; if (l == NULL) { return; } l->log(level, (char *) log); } void cci_log_remove(const char *path) { loggerManager.removeLogger(path); } void cci_log_set_level(Logger logger, CCI_LOG_LEVEL level) { _Logger *l = (_Logger *) logger; if (l == NULL) { return; } l->setLogLevel(level); } bool cci_log_is_writable(Logger logger, CCI_LOG_LEVEL level) { _Logger *l = (_Logger *) logger; if (l == NULL) { return false; } return l->isWritable(level); } void cci_log_set_force_flush(Logger logger, bool force_flush) { _Logger *l = (_Logger *) logger; if (l == NULL) { return; } l->setForceFlush(force_flush); } void cci_log_use_default_newline(Logger logger, bool use_default_newline) { _Logger *l = (_Logger *) logger; if (l == NULL) { return; } l->setUseDefaultNewLine(use_default_newline); } void cci_log_use_default_prefix(Logger logger, bool use_default_prefix) { _Logger *l = (_Logger *) logger; if (l == NULL) { return; } l->setUseDefaultPrefix(use_default_prefix); } void cci_log_change_max_file_size_appender(Logger logger, int maxFileSizeKBytes, int maxBackupCount) { _Logger *l = (_Logger *) logger; if (l == NULL) { return; } try { l->changeMaxFileSizeAppender(maxFileSizeKBytes, maxBackupCount); } catch (...) { } } void cci_log_set_default_postfix(Logger logger, CCI_LOG_POSTFIX postfix) { _Logger *l = (_Logger *) logger; if (l == NULL) { return; } l->changePostfixAppender(postfix); }
andrei14vl/cubrid
src/cci/cci_log.cpp
C++
gpl-3.0
18,272
export function QuerySelectorAllIterate(el:HTMLElement, query:string) : HTMLElement[] { let els :HTMLElement[] = []; if ('function'==typeof el.matches) { if (el.matches(query)) { els.push(el); } } else if ('function'==typeof (el as any).matchesSelector) { if ((el as any).matchesSelector(query)) { els.push(el as HTMLElement); } } let childSelector = el.querySelectorAll(query); for (let i=0; i<childSelector.length; i++) { els.push(childSelector.item(i) as HTMLElement); } return els; }
katmutua/electric-book-gui
src/ts/querySelectorAll-extensions.ts
TypeScript
gpl-3.0
514
package de.persosim.simulator.tlv; import java.util.Comparator; import de.persosim.simulator.utils.Utils; /** * This class implements a comparator for sorting TLV data objects in DER-TLV * order. Sorting is performed based on the sorting of tags. In detail tags * again are sorted based on their indicated class and tag number. * * !Attention!: Sorting is performed without checking either explicitly or * implicitly for valid DER encoding of the objects to be sorted. Checks for * valid DER encoding must be performed separately. Sorting however will also * work correctly for valid BER but not DER encoded TLV data objects. * * @author slutters * */ public class TlvDataObjectComparatorDer implements Comparator<TlvDataObject> { @Override public int compare(TlvDataObject tlvdo1, TlvDataObject tlvdo2) { TlvTag tlvTag1; TlvTag tlvTag2; tlvTag1 = tlvdo1.getTlvTag(); tlvTag2 = tlvdo2.getTlvTag(); return compare(tlvTag1, tlvTag2); } /** * Performs Comparator's sorting based on tags * @param tlvTag1 tag 1 * @param tlvTag2 tag 2 * @return the Comparator's compare result */ private int compare(TlvTag tlvTag1, TlvTag tlvTag2) { short class1 = Utils.maskUnsignedByteToShort(tlvTag1.getEncodedClass()); short class2 = Utils.maskUnsignedByteToShort(tlvTag2.getEncodedClass()); short classDiff = (short) (class1 - class2); if(classDiff != 0) { return classDiff; } else{ return tlvTag1.getIndicatedTagNo() - tlvTag2.getIndicatedTagNo(); } } }
PersoSim/de.persosim.simulator
de.persosim.simulator/src/de/persosim/simulator/tlv/TlvDataObjectComparatorDer.java
Java
gpl-3.0
1,516
<?php /* * ©2013 Croce Rossa Italiana */ paginaPrivata(); caricaSelettore(); controllaParametri(['id'], 'attivita.gestione&err'); $a = Attivita::id($_GET['id']); paginaAttivita($a); if (!$a->haPosizione()) { redirect('attivita.localita&id=' . $a->id); } $del = $me->delegazioni(APP_ATTIVITA); $comitati = $me->comitatiDelegazioni(APP_ATTIVITA); $domini = $me->dominiDelegazioni(APP_ATTIVITA); $g = GeoPolitica::daOid($a->comitato); $visMinima = $a->visibilitaMinima($g); ?> <form action="?p=attivita.modifica.ok" method="POST"> <input type="hidden" name="id" value="<?php echo $a->id; ?>" /> <div class="row-fluid"> <div class="span7"> <h2><i class="icon-flag muted"></i> Dettagli dell'attività</h2> </div> <div class="btn-group pull-right"> <button type="submit" name="azione" value="salva" class="btn btn-success btn-large"> <i class="icon-save"></i> Salva l'attività </button> </div> </div> <hr /> <div class="row-fluid"> <div class="span8"> <div class="alert alert-info"> <i class="icon-info-sign"></i> Presta molta attenzione quando decidi <strong> quali volontari possono partecipare </strong>:</br> <ul> <li>Se selezioni <strong>Tutti i Volontari della Croce Rossa Italiana</strong> permetti a tutti gli iscritti su Gaia di dare disponibilità per l'attività. </li> <li>Se selezioni <strong>Pubblica</strong> permetti anche a chi <strong>non</strong> è Volontario di partecipare. </li> </ul> </div> <div class="form-horizontal"> <div class="control-group"> <label class="control-label" for="inputNome">Nome</label> <div class="controls"> <input class="input-xlarge grassetto" value="<?php echo $a->nome; ?>" type="text" id="inputNome" name="inputNome" placeholder="Es.: Aggiungi un Posto a Tavola" required autofocus pattern=".{2,}" /> </div> </div> <div class="control-group"> <label class="control-label" for="inputVisibilita">Quali volontari possono chiedere di partecipare?</label> <div class="controls"> <select class="input-xxlarge" name="inputVisibilita"> <?php foreach ( $conf['att_vis'] as $num => $nom ) { if ($num < $visMinima) { continue; }?> <option value="<?php echo $num; ?>" <?php if ( $a->visibilita == $num ) { ?> selected="selected" <?php } ?> > <?php echo $nom; ?> </option> <?php } ?> </select> <p class="text-info"><i class="icon-info-sign"></i> I volontari al di fuori di questa selezione non vedranno l'attività nel calendario.</p> </div> </div> <div class="control-group"> <label class="control-label" for="inputDescrizione">Descrizione ed informazioni per i volontari</label> <div class="controls"> <textarea rows="10" class="input-xlarge conEditor" type="text" id="inputDescrizione" name="inputDescrizione"><?php echo $a->descrizione; ?></textarea> </div> </div> </div> </div> <div class="span4"> <p> <strong>Referente</strong><br /> <?php echo $a->referente()->nomeCompleto(); ?> </p> <p> <strong>Organizzatore</strong><br /> <?php echo $g->nomeCompleto(); ?> </p> <p> <strong>Area d'intervento</strong><br /> <?php echo $a->area()->nomeCompleto(); ?> </p> <p> <strong>Posizione geografica</strong><br /> <?php echo $a->luogo; ?><br /> <a href='?p=attivita.localita&id=<?= $a->id; ?>'> <i class='icon-pencil'></i> modifica la località </a> </p> </div> </div> </form>
CroceRossaCatania/gaia
inc/attivita.modifica.php
PHP
gpl-3.0
4,359
<?php $rangeid=122; $prevcid=126; $prevwidth=754; $interval=false; $range=array ( 32 => array ( 0 => 286, 1 => 360, 2 => 414, 3 => 754, 4 => 572, 5 => 855, 6 => 702, 7 => 247, ), 40 => array ( 0 => 351, 1 => 351, 'interval' => true, ), 42 => array ( 0 => 450, 1 => 754, 2 => 286, 3 => 325, 4 => 286, 5 => 303, ), 48 => array ( 0 => 572, 1 => 572, 'interval' => true, 2 => 572, 3 => 572, 4 => 572, 5 => 572, 6 => 572, 7 => 572, 8 => 572, 9 => 572, ), 58 => array ( 0 => 303, 1 => 303, 'interval' => true, ), 60 => array ( 0 => 754, 1 => 754, 'interval' => true, 2 => 754, ), 63 => array ( 0 => 478, 1 => 900, 2 => 615, 3 => 617, 4 => 628, 5 => 693, 6 => 568, 7 => 518, 8 => 697, 9 => 677, ), 73 => array ( 0 => 265, 1 => 265, 'interval' => true, ), 75 => array ( 0 => 590, 1 => 501, 2 => 776, 3 => 673, 4 => 708, 5 => 542, 6 => 708, 7 => 625, 8 => 571, 9 => 549, 10 => 659, 11 => 615, 12 => 890, 13 => 616, 14 => 549, 15 => 616, 16 => 351, 17 => 303, 18 => 351, 19 => 754, ), 95 => array ( 0 => 450, 1 => 450, 'interval' => true, ), 97 => array ( 0 => 551, 1 => 571, 2 => 495, 3 => 571, 4 => 554, 5 => 316, 6 => 571, 7 => 570, ), 105 => array ( 0 => 250, 1 => 250, 'interval' => true, ), 107 => array ( 0 => 521, 1 => 250, 2 => 876, 3 => 570, 4 => 550, ), 112 => array ( 0 => 571, 1 => 571, 'interval' => true, ), 114 => array ( 0 => 370, 1 => 469, 2 => 353, 3 => 570, 4 => 532, 5 => 736, ), 120 => array ( 0 => 532, 1 => 532, 'interval' => true, ), 122 => array ( 0 => 472, 1 => 572, 2 => 303, 3 => 572, 4 => 754, ), );
Tinchosan/wingpanel
admin/lib/vendor/mpdf/mpdf/tmp/ttfontdata/dejavusanscondensed.cw127.php
PHP
gpl-3.0
2,055
/* ************************************************************************ Copyright: License: Authors: ************************************************************************ */ qx.Theme.define("${Namespace}.theme.modern.Decoration", { decorations : { } });
09zwcbupt/undergrad_thesis
ext/poxdesk/qx/component/skeleton/contribution/trunk/source/class/custom/theme/modern/Decoration.tmpl.js
JavaScript
gpl-3.0
280
<?php include ('lib/twitese.php'); $title = "Settings"; include ('inc/header.php'); if (!loginStatus()) header('location: login.php'); ?> <script src="js/colorpicker.js"></script> <script src="js/setting.js"></script> <link rel="stylesheet" href="css/colorpicker.css" /> <div id="statuses" class="column round-left"> <div id="setting"> <div id="setting_nav"> <?php $settingType = isset($_GET['t'])? $_GET['t'] : 1; switch($settingType){ case 'profile': ?> <span class="subnavLink"><a href="setting.php">Customize</a></span><span class="subnavNormal">Profile</span> <?php break; default: ?> <span class="subnavNormal">Customize</span><span class="subnavLink"><a href="setting.php?t=profile">Profile</a></span> <?php } ?> </div> <?php switch($settingType){ case 'profile': $user = getTwitter()->veverify(true); ?> <form id="setting_form" action="ajax/uploadImage.php?do=profile" method="post" enctype="multipart/form-data"> <fieldset class="settings"> <legend>Avatar</legend> <ol> <li style="display:inline-block"><img src="<?php echo isset($_COOKIE['imgurl']) ? $_COOKIE['imgurl'] : getAvatar($user->profile_image_url)?>" id="avatarimg"></img></li> <ol style="margin-left:29px"> <li><input type="file" name="image" id="profile_image"/></li> <li><input type="submit" id="AvatarUpload" class="btn" value="Upload"/><small style="margin-left:10px;vertical-align: middle;">BMP,JPG or PNG accepted, less than 800K.</small></li> </ol></ol> </fieldset> </form> <form id="setting_form" action="ajax/uploadImage.php?do=background" method="post" enctype="multipart/form-data"> <fieldset class="settings"> <legend>Background</legend> <ol> <li style="display:inline-block"><img src="<?php echo getAvatar($user->profile_background_image_url)?>" id="backgroundimg" style="max-width: 460px;"></img></li> <li><input type="file" name="image" id="profile_background"/></li> <li><input type="submit" id="BackgroundUpload" class="btn" value="Upload"/><small style="margin-left:10px;vertical-align: middle;">BMP,JPG or PNG accepted, less than 800K.</small></li> <li> <input id="tile" type="checkbox" <?php echo $user->profile_background_tile ? 'checked="checked"' : '' ?> /> <label>Tile the profile background</label> </li> </ol> </fieldset> </form> <form id="setting_form" action="ajax/updateProfile.php" method="post"> <fieldset class="settings"> <legend>Literature</legend> <table id="setting_table"> <tr> <td class="setting_title">Name: </td> <td><input class="setting_input" type="text" name="name" value="<?php echo isset($user->name) ? $user->name : ''?>" /></td> </tr> <tr> <td class="setting_title">URL: </td> <td><input class="setting_input" type="text" name="url" value="<?php if (!isset($user->url)) echo ''; else { $hops = array(); $newurl = expandRedirect($user->url, $hops); echo $newurl; } ?>" /></td> </tr> <tr> <td class="setting_title">Location: </td> <td><input class="setting_input" type="text" name="location" value="<?php echo isset($user->location) ? $user->location : '' ?>" /></td> </tr> <tr> <td class="setting_title">Bio: </td><td><small style="margin-left:5px;vertical-align: top;">*Max 160 chars</small></td> </tr><tr> <td></td> <td><textarea id="setting_text" name="description"><?php echo isset($user->description) ? $user->description : '' ?></textarea></td> </tr> </table> <input type="submit" id="saveProfile" class="btn" value="Save" /> </fieldset> <?php break; default: ?> <form id="style_form" action="setting.php" method="post"> <fieldset class="settings"> <legend>Utility</legend> <input id="proxifyAvatar" type="checkbox" /> <label>Proxify the Avatar</label> <br /><br /> <input id="autoscroll" type="checkbox" /> <label>Timeline Autopaging</label> <br /><br /> <input id="sidebarscroll" type="checkbox" /> <label>Fixed Sidebar</label> <br /><br /> Share to Twitter: <a class="share" title="Drag me to share!" href="javascript:var%20d=document,w=window,f='<?php echo $base_url."/share.php" ?>',l=d.location,e=encodeURIComponent,p='?u='+e(l.href)+'&t='+e(d.title)+'&d='+e(w.getSelection?w.getSelection().toString():d.getSelection?d.getSelection():d.selection.createRange().text)+'&s=bm';a=function(){if(!w.open(f+p,'sharer','toolbar=0,status=0,resizable=0,width=600,height=300,left=175,top=150'))l.href=f+'.new'+p};if(/Firefox/.test(navigator.userAgent))setTimeout(a,0);else{a()}void(0);">Share</a> <small>(Bookmark this link for future use)</small> </fieldset> <fieldset class="settings"> <legend>Media Preview</legend> <input id="showpic" type="checkbox" checked="checked" /> <label>Enable Images Preview</label> <small>(Supports common image hostings)</small> <br /><br /> <input id="mediaPreSelect" type="checkbox" checked="checked" /> <label>Enable Videos Preview</label> <small>(Supports Xiami and Tudou)</small><br /> </fieldset> <fieldset class="settings"> <legend>Auto Refresh Interval</legend> <label>Home Page</label> <select id="homeInterval" name="homeInterval" value="<?php echo getCookie('homeInterval')?>"> <option value="1">1 min</option> <option value="2" selected="selected">2 min (Default)</option> <option value="3">3 min</option> <option value="5">5 min</option> <option value="10">10 min</option> <option value="0">Never</option> </select> <label>Updates Page</label> <select id="updatesInterval" name="updatesInterval" value="<?php echo getCookie('updatesInterval')?>"> <option value="1">1 min</option> <option value="2">2 min</option> <option value="3" selected="selected">3 min (Default)</option> <option value="5">5 min</option> <option value="10">10 min</option> <option value="0">Never</option> </select> </fieldset> <fieldset class="settings"> <legend>UI Preferences</legend> <input id="twitterbg" type="checkbox" /> <label>Use twitter account background</label> <br /><br /> <input id="shownick" type="checkbox" /> <label>Use nickname instead of username</label> <br /><br /> <label>Background Color</label> <input class="bg_input" type="text" id="bodyBg" name="bodyBg" value="<?php echo getDefCookie("Bgcolor","") ?>" /> <small>(Choose your favorite color here)</small> <br /><br /> <label>Font Size</label> <select id="fontsize" name="fontsize" value="<?php echo getCookie('fontsize')?>"> <option value="12px">Small</option> <option value="13px" selected="selected">Middle(Default)</option> <option value="14px">Large</option> <option value="15px">Extra Large</option> </select> <small>(Set the font size)</small> <br /><br /> <label>Customize CSS</label> <small>(You can put your own CSS hack here, or your Twitter style code)</small> <br /> <label>Tips:</label> <small>You must use <a href="http://i.zou.lu/csstidy/" target="_blank" title="Powered by Showfom">CSSTidy</a> to compress your stylesheet.</small> <br /> <textarea type="text" id="myCSS" name="myCSS" value="" /><?php echo getDefCookie("myCSS","") ?></textarea> </fieldset> <?php } ?> <a id="reset_link" href="#" title="You will lose all customized settings!">Reset to default</a> </form> </div> </div> <?php include ('inc/sidebar.php'); include ('inc/footer.php'); ?>
xctcc/embrr
setting.php
PHP
gpl-3.0
7,543
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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. ----------------------------------------------------------------------------- */ #include "OgreGLRenderSystemCommon.h" #include "OgreFrustum.h" #if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN #include <OgreEGLWindow.h> #endif namespace Ogre { void GLRenderSystemCommon::_makeProjectionMatrix(const Radian& fovy, Real aspect, Real nearPlane, Real farPlane, Matrix4& dest, bool forGpuProgram) { Radian thetaY(fovy / 2.0f); Real tanThetaY = Math::Tan(thetaY); // Calc matrix elements Real w = (1.0f / tanThetaY) / aspect; Real h = 1.0f / tanThetaY; Real q, qn; if (farPlane == 0) { // Infinite far plane q = Frustum::INFINITE_FAR_PLANE_ADJUST - 1; qn = nearPlane * (Frustum::INFINITE_FAR_PLANE_ADJUST - 2); } else { q = -(farPlane + nearPlane) / (farPlane - nearPlane); qn = -2 * (farPlane * nearPlane) / (farPlane - nearPlane); } // NB This creates Z in range [-1,1] // // [ w 0 0 0 ] // [ 0 h 0 0 ] // [ 0 0 q qn ] // [ 0 0 -1 0 ] dest = Matrix4::ZERO; dest[0][0] = w; dest[1][1] = h; dest[2][2] = q; dest[2][3] = qn; dest[3][2] = -1; } void GLRenderSystemCommon::_makeProjectionMatrix(Real left, Real right, Real bottom, Real top, Real nearPlane, Real farPlane, Matrix4& dest, bool forGpuProgram) { Real width = right - left; Real height = top - bottom; Real q, qn; if (farPlane == 0) { // Infinite far plane q = Frustum::INFINITE_FAR_PLANE_ADJUST - 1; qn = nearPlane * (Frustum::INFINITE_FAR_PLANE_ADJUST - 2); } else { q = -(farPlane + nearPlane) / (farPlane - nearPlane); qn = -2 * (farPlane * nearPlane) / (farPlane - nearPlane); } dest = Matrix4::ZERO; dest[0][0] = 2 * nearPlane / width; dest[0][2] = (right+left) / width; dest[1][1] = 2 * nearPlane / height; dest[1][2] = (top+bottom) / height; dest[2][2] = q; dest[2][3] = qn; dest[3][2] = -1; } void GLRenderSystemCommon::_makeOrthoMatrix(const Radian& fovy, Real aspect, Real nearPlane, Real farPlane, Matrix4& dest, bool forGpuProgram) { Radian thetaY(fovy / 2.0f); Real tanThetaY = Math::Tan(thetaY); // Real thetaX = thetaY * aspect; Real tanThetaX = tanThetaY * aspect; // Math::Tan(thetaX); Real half_w = tanThetaX * nearPlane; Real half_h = tanThetaY * nearPlane; Real iw = 1.0f / half_w; Real ih = 1.0f / half_h; Real q; if (farPlane == 0) { q = 0; } else { q = 2.0f / (farPlane - nearPlane); } dest = Matrix4::ZERO; dest[0][0] = iw; dest[1][1] = ih; dest[2][2] = -q; dest[2][3] = -(farPlane + nearPlane) / (farPlane - nearPlane); dest[3][3] = 1; } void GLRenderSystemCommon::_applyObliqueDepthProjection(Matrix4& matrix, const Plane& plane, bool forGpuProgram) { // Thanks to Eric Lenyel for posting this calculation at www.terathon.com // Calculate the clip-space corner point opposite the clipping plane // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and // transform it into camera space by multiplying it // by the inverse of the projection matrix Vector4 q; q.x = (Math::Sign(plane.normal.x) + matrix[0][2]) / matrix[0][0]; q.y = (Math::Sign(plane.normal.y) + matrix[1][2]) / matrix[1][1]; q.z = -1.0F; q.w = (1.0F + matrix[2][2]) / matrix[2][3]; // Calculate the scaled plane vector Vector4 clipPlane4d(plane.normal.x, plane.normal.y, plane.normal.z, plane.d); Vector4 c = clipPlane4d * (2.0F / (clipPlane4d.dotProduct(q))); // Replace the third row of the projection matrix matrix[2][0] = c.x; matrix[2][1] = c.y; matrix[2][2] = c.z + 1.0F; matrix[2][3] = c.w; } #if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN void GLRenderSystemCommon::_destroyInternalResources(RenderWindow* pRenderWnd) { static_cast<EGLWindow*>(pRenderWnd)->_destroyInternalResources(); } void GLRenderSystemCommon::_createInternalResources(RenderWindow* pRenderWnd, void* window, void* config) { static_cast<EGLWindow*>(pRenderWnd) ->_createInternalResources(reinterpret_cast<EGLNativeWindowType>(window), config); } #endif }
GDevs/mission-farpoint
ogre/RenderSystems/GLSupport/src/OgreGLRenderSystemCommon.cpp
C++
gpl-3.0
6,592
// -*- Mode: Go; indent-tabs-mode: t -*- /* * Copyright (C) 2016-2017 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package builtin import ( "github.com/snapcore/snapd/osutil" ) const networkControlSummary = `allows configuring networking and network namespaces` const networkControlBaseDeclarationSlots = ` network-control: allow-installation: slot-snap-type: - core deny-auto-connection: true ` const networkControlConnectedPlugAppArmor = ` # Description: Can configure networking and network namespaces via the standard # 'ip netns' command (man ip-netns(8)). This interface is restricted because it # gives wide, privileged access to networking and should only be used with # trusted apps. #include <abstractions/nameservice> /run/systemd/resolve/stub-resolv.conf rk, # systemd-resolved (not yet included in nameservice abstraction) # # Allow access to the safe members of the systemd-resolved D-Bus API: # # https://www.freedesktop.org/wiki/Software/systemd/resolved/ # # This API may be used directly over the D-Bus system bus or it may be used # indirectly via the nss-resolve plugin: # # https://www.freedesktop.org/software/systemd/man/nss-resolve.html # #include <abstractions/dbus-strict> dbus send bus=system path="/org/freedesktop/resolve1" interface="org.freedesktop.resolve1.Manager" member="Resolve{Address,Hostname,Record,Service}" peer=(name="org.freedesktop.resolve1"), dbus (send) bus=system path="/org/freedesktop/resolve1" interface="org.freedesktop.resolve1.Manager" member="SetLink{DNS,MulticastDNS,Domains,LLMNR}" peer=(label=unconfined), #include <abstractions/ssl_certs> capability net_admin, capability net_raw, capability setuid, # ping capability net_broadcast, # openvswitchd # Allow protocols except those that we blacklist in # /etc/modprobe.d/blacklist-rare-network.conf network appletalk, network bridge, network inet, network inet6, network ipx, network packet, network pppox, network sna, @{PROC}/@{pid}/net/ r, @{PROC}/@{pid}/net/** r, # used by sysctl, et al @{PROC}/sys/ r, @{PROC}/sys/net/ r, @{PROC}/sys/net/core/ r, @{PROC}/sys/net/core/** rw, @{PROC}/sys/net/ipv{4,6}/ r, @{PROC}/sys/net/ipv{4,6}/** rw, @{PROC}/sys/net/netfilter/ r, @{PROC}/sys/net/netfilter/** rw, @{PROC}/sys/net/nf_conntrack_max rw, # For advanced wireless configuration /sys/kernel/debug/ieee80211/ r, /sys/kernel/debug/ieee80211/** rw, # read netfilter module parameters /sys/module/nf_*/ r, /sys/module/nf_*/parameters/{,*} r, # networking tools /{,usr/}{,s}bin/arp ixr, /{,usr/}{,s}bin/arpd ixr, /{,usr/}{,s}bin/bridge ixr, /{,usr/}{,s}bin/dhclient Pxr, # use ixr instead if want to limit to snap dirs /{,usr/}{,s}bin/dhclient-script ixr, /{,usr/}{,s}bin/ifconfig ixr, /{,usr/}{,s}bin/ifdown ixr, /{,usr/}{,s}bin/ifquery ixr, /{,usr/}{,s}bin/ifup ixr, /{,usr/}{,s}bin/ip ixr, /{,usr/}{,s}bin/ipmaddr ixr, /{,usr/}{,s}bin/iptunnel ixr, /{,usr/}{,s}bin/iw ixr, /{,usr/}{,s}bin/nameif ixr, /{,usr/}{,s}bin/netstat ixr, # -p not supported /{,usr/}{,s}bin/nstat ixr, /{,usr/}{,s}bin/ping ixr, /{,usr/}{,s}bin/ping6 ixr, /{,usr/}{,s}bin/pppd ixr, /{,usr/}{,s}bin/pppdump ixr, /{,usr/}{,s}bin/pppoe-discovery ixr, #/{,usr/}{,s}bin/pppstats ixr, # needs sys_module /{,usr/}{,s}bin/route ixr, /{,usr/}{,s}bin/routef ixr, /{,usr/}{,s}bin/routel ixr, /{,usr/}{,s}bin/rtacct ixr, /{,usr/}{,s}bin/rtmon ixr, /{,usr/}{,s}bin/ss ixr, /{,usr/}{,s}bin/sysctl ixr, /{,usr/}{,s}bin/tc ixr, /{,usr/}{,s}bin/wpa_action ixr, /{,usr/}{,s}bin/wpa_cli ixr, /{,usr/}{,s}bin/wpa_passphrase ixr, /{,usr/}{,s}bin/wpa_supplicant ixr, /dev/rfkill rw, /sys/class/rfkill/ r, /sys/devices/{pci[0-9a-f]*,platform,virtual}/**/rfkill[0-9]*/{,**} r, /sys/devices/{pci[0-9a-f]*,platform,virtual}/**/rfkill[0-9]*/state w, # For reading the address of a particular ethernet interface /sys/devices/{pci[0-9a-f]*,platform,virtual}/**/net/*/address r, # arp network netlink dgram, # ip, et al /etc/iproute2/{,**} r, /etc/iproute2/rt_{protos,realms,scopes,tables} w, /etc/iproute2/rt_{protos,tables}.d/* w, # ping - child profile would be nice but seccomp causes problems with that /{,usr/}{,s}bin/ping ixr, /{,usr/}{,s}bin/ping6 ixr, network inet raw, network inet6 raw, # pppd capability setuid, @{PROC}/@{pid}/loginuid r, @{PROC}/@{pid}/mounts r, # static host tables /etc/hosts w, # resolvconf /{,usr/}sbin/resolvconf ixr, /run/resolvconf/{,**} rk, /run/resolvconf/** w, /etc/resolvconf/{,**} r, /{,usr/}lib/resolvconf/* ix, # Required by resolvconf /{,usr/}bin/run-parts ixr, /etc/resolvconf/update.d/* ix, # wpa_suplicant /{,var/}run/wpa_supplicant/ w, /{,var/}run/wpa_supplicant/** rw, /etc/wpa_supplicant/{,**} ixr, #ifup,ifdown, dhclient /{,var/}run/dhclient.*.pid rw, /var/lib/dhcp/ r, /var/lib/dhcp/** rw, /run/network/ifstate* rw, /run/network/.ifstate* rw, /run/network/ifup-* rw, /run/network/ifdown-* rw, # route /etc/networks r, /etc/ethers r, /etc/rpc r, # TUN/TAP - https://www.kernel.org/doc/Documentation/networking/tuntap.txt # # We only need to tag /dev/net/tun since the tap[0-9]* and tun[0-9]* devices # are virtual and don't show up in /dev /dev/net/tun rw, # Access to sysfs interfaces for tun/tap device settings. /sys/devices/virtual/net/tap*/** rw, # access to bridge sysfs interfaces for bridge settings /sys/devices/virtual/net/*/bridge/* rw, # Network namespaces via 'ip netns'. In order to create network namespaces # that persist outside of the process and be entered (eg, via # 'ip netns exec ...') the ip command uses mount namespaces such that # applications can open the /run/netns/NAME object and use it with setns(2). # For 'ip netns exec' it will also create a mount namespace and bind mount # network configuration files into /etc in that namespace. See man ip-netns(8) # for details. capability sys_admin, # for setns() network netlink raw, / r, /run/netns/ r, # only 'r' since snap-confine will create this for us /run/netns/* rw, mount options=(rw, rshared) -> /run/netns/, mount options=(rw, bind) /run/netns/ -> /run/netns/, mount options=(rw, bind) / -> /run/netns/*, umount /, # 'ip netns identify <pid>' and 'ip netns pids foo'. Intenionally omit 'ptrace # (trace)' here since ip netns doesn't actually need to trace other processes. capability sys_ptrace, # 'ip netns exec foo /bin/sh' mount options=(rw, rslave) /, mount options=(rw, rslave), # LP: #1648245 umount /sys/, # Eg, nsenter --net=/run/netns/... <command> /{,usr/}{,s}bin/nsenter ixr, ` const networkControlConnectedPlugSecComp = ` # Description: Can configure networking and network namespaces via the standard # 'ip netns' command (man ip-netns(8)). This interface is restricted because it # gives wide, privileged access to networking and should only be used with # trusted apps. # for ping and ping6 capset # Network namespaces via 'ip netns'. In order to create network namespaces # that persist outside of the process and be entered (eg, via # 'ip netns exec ...') the ip command uses mount namespaces such that # applications can open the /run/netns/NAME object and use it with setns(2). # For 'ip netns exec' it will also create a mount namespace and bind mount # network configuration files into /etc in that namespace. See man ip-netns(8) # for details. bind mount umount umount2 unshare setns - CLONE_NEWNET # For various network related netlink sockets socket AF_NETLINK - NETLINK_ROUTE socket AF_NETLINK - NETLINK_FIB_LOOKUP socket AF_NETLINK - NETLINK_INET_DIAG socket AF_NETLINK - NETLINK_XFRM socket AF_NETLINK - NETLINK_DNRTMSG socket AF_NETLINK - NETLINK_ISCSI socket AF_NETLINK - NETLINK_RDMA socket AF_NETLINK - NETLINK_GENERIC # for receiving kobject_uevent() net messages from the kernel socket AF_NETLINK - NETLINK_KOBJECT_UEVENT ` /* https://www.kernel.org/doc/Documentation/networking/tuntap.txt * * We only need to tag /dev/net/tun since the tap[0-9]* and tun[0-9]* devices * are virtual and don't show up in /dev */ var networkControlConnectedPlugUDev = []string{ `KERNEL=="rfkill"`, `KERNEL=="tun"`, } var networkControlConnectedPlugMount = []osutil.MountEntry{{ Name: "/var/lib/snapd/hostfs/var/lib/dhcp", Dir: "/var/lib/dhcp", Options: []string{"bind", "rw", osutil.XSnapdIgnoreMissing()}, }} // TODO: Add a layer that derives this sort of data from mount entry, like the // one above, into a set of apparmor rules for snap-update-ns, like the ones // below. // // When setting up a mount entry, we also need corresponding // snap-updates-ns rules. Eg, if have: // []osutil.MountEntry{{ // Name: "/foo/bar", // Dir: "/bar", // Options: []string{"rw", "bind"}, // }} // Then you can expect to need: // /foo/ r, // /foo/bar/ r, // mount options=(rw bind) /foo/bar/ -> /bar/, // umount /bar/, // ... // You'll need 'r' rules for all the directories that need to be traversed, // starting from the root directory all the way down to the directory being // mounted. This is required by the safe bind mounting trick employed by // snap-update-ns. // // You'll need 'rw' rules to support cases when snap-update-ns is expected to // create the missing directory, before performing the bind mount. Note that // there are two sides, one side is the host visible through // /var/lib/snapd/hostfs and the other side is everything else. To support // writes to the host side you need to coordinate with the trespassing rules // implemented in snap-update-ns/system.go. var networkControlConnectedPlugUpdateNSAppArmor = ` /var/ r, /var/lib/ r, /var/lib/snapd/ r, /var/lib/snapd/hostfs/ r, /var/lib/snapd/hostfs/var/ r, /var/lib/snapd/hostfs/var/lib/ r, /var/lib/snapd/hostfs/var/lib/dhcp/ r, /var/lib/dhcp/ r, mount options=(rw bind) /var/lib/snapd/hostfs/var/lib/dhcp/ -> /var/lib/dhcp/, umount /var/lib/dhcp/, ` func init() { registerIface(&commonInterface{ name: "network-control", summary: networkControlSummary, implicitOnCore: true, implicitOnClassic: true, baseDeclarationSlots: networkControlBaseDeclarationSlots, connectedPlugAppArmor: networkControlConnectedPlugAppArmor, connectedPlugSecComp: networkControlConnectedPlugSecComp, connectedPlugUDev: networkControlConnectedPlugUDev, connectedPlugMount: networkControlConnectedPlugMount, connectedPlugUpdateNSAppArmor: networkControlConnectedPlugUpdateNSAppArmor, suppressPtraceTrace: true, suppressSysModuleCapability: true, // affects the plug snap because of mount backend affectsPlugOnRefresh: true, }) }
sergiocazzolato/snapd
interfaces/builtin/network_control.go
GO
gpl-3.0
11,137
// Copyright 2014 the V8 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. #include "src/v8.h" #include "src/arguments.h" #include "src/compiler.h" #include "src/deoptimizer.h" #include "src/frames.h" #include "src/full-codegen.h" #include "src/messages.h" #include "src/runtime/runtime-utils.h" #include "src/v8threads.h" #include "src/vm-state-inl.h" namespace v8 { namespace internal { RUNTIME_FUNCTION(Runtime_CompileLazy) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); #ifdef DEBUG if (FLAG_trace_lazy && !function->shared()->is_compiled()) { PrintF("[unoptimized: "); function->PrintName(); PrintF("]\n"); } #endif // Compile the target function. DCHECK(function->shared()->allows_lazy_compilation()); Handle<Code> code; ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, code, Compiler::GetLazyCode(function)); DCHECK(code->kind() == Code::FUNCTION || code->kind() == Code::OPTIMIZED_FUNCTION); function->ReplaceCode(*code); return *code; } RUNTIME_FUNCTION(Runtime_CompileOptimized) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); CONVERT_BOOLEAN_ARG_CHECKED(concurrent, 1); Compiler::ConcurrencyMode mode = concurrent ? Compiler::CONCURRENT : Compiler::NOT_CONCURRENT; Handle<Code> code; Handle<Code> unoptimized(function->shared()->code()); if (Compiler::GetOptimizedCode(function, unoptimized, mode).ToHandle(&code)) { // Optimization succeeded, return optimized code. function->ReplaceCode(*code); } else { // Optimization failed, get unoptimized code. if (isolate->has_pending_exception()) { // Possible stack overflow. return isolate->heap()->exception(); } code = Handle<Code>(function->shared()->code(), isolate); if (code->kind() != Code::FUNCTION && code->kind() != Code::OPTIMIZED_FUNCTION) { ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, code, Compiler::GetUnoptimizedCode(function)); } function->ReplaceCode(*code); } DCHECK(function->code()->kind() == Code::FUNCTION || function->code()->kind() == Code::OPTIMIZED_FUNCTION || function->IsInOptimizationQueue()); return function->code(); } RUNTIME_FUNCTION(Runtime_NotifyStubFailure) { HandleScope scope(isolate); DCHECK(args.length() == 0); Deoptimizer* deoptimizer = Deoptimizer::Grab(isolate); DCHECK(AllowHeapAllocation::IsAllowed()); delete deoptimizer; return isolate->heap()->undefined_value(); } class ActivationsFinder : public ThreadVisitor { public: Code* code_; bool has_code_activations_; explicit ActivationsFinder(Code* code) : code_(code), has_code_activations_(false) {} void VisitThread(Isolate* isolate, ThreadLocalTop* top) { JavaScriptFrameIterator it(isolate, top); VisitFrames(&it); } void VisitFrames(JavaScriptFrameIterator* it) { for (; !it->done(); it->Advance()) { JavaScriptFrame* frame = it->frame(); if (code_->contains(frame->pc())) has_code_activations_ = true; } } }; RUNTIME_FUNCTION(Runtime_NotifyDeoptimized) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_SMI_ARG_CHECKED(type_arg, 0); Deoptimizer::BailoutType type = static_cast<Deoptimizer::BailoutType>(type_arg); Deoptimizer* deoptimizer = Deoptimizer::Grab(isolate); DCHECK(AllowHeapAllocation::IsAllowed()); Handle<JSFunction> function = deoptimizer->function(); Handle<Code> optimized_code = deoptimizer->compiled_code(); DCHECK(optimized_code->kind() == Code::OPTIMIZED_FUNCTION); DCHECK(type == deoptimizer->bailout_type()); // Make sure to materialize objects before causing any allocation. JavaScriptFrameIterator it(isolate); deoptimizer->MaterializeHeapObjects(&it); delete deoptimizer; JavaScriptFrame* frame = it.frame(); RUNTIME_ASSERT(frame->function()->IsJSFunction()); DCHECK(frame->function() == *function); // Avoid doing too much work when running with --always-opt and keep // the optimized code around. if (FLAG_always_opt || type == Deoptimizer::LAZY) { return isolate->heap()->undefined_value(); } // Search for other activations of the same function and code. ActivationsFinder activations_finder(*optimized_code); activations_finder.VisitFrames(&it); isolate->thread_manager()->IterateArchivedThreads(&activations_finder); if (!activations_finder.has_code_activations_) { if (function->code() == *optimized_code) { if (FLAG_trace_deopt) { PrintF("[removing optimized code for: "); function->PrintName(); PrintF("]\n"); } function->ReplaceCode(function->shared()->code()); // Evict optimized code for this function from the cache so that it // doesn't get used for new closures. function->shared()->EvictFromOptimizedCodeMap(*optimized_code, "notify deoptimized"); } } else { // TODO(titzer): we should probably do DeoptimizeCodeList(code) // unconditionally if the code is not already marked for deoptimization. // If there is an index by shared function info, all the better. Deoptimizer::DeoptimizeFunction(*function); } return isolate->heap()->undefined_value(); } static bool IsSuitableForOnStackReplacement(Isolate* isolate, Handle<JSFunction> function) { // Keep track of whether we've succeeded in optimizing. if (function->shared()->optimization_disabled()) return false; // If we are trying to do OSR when there are already optimized // activations of the function, it means (a) the function is directly or // indirectly recursive and (b) an optimized invocation has been // deoptimized so that we are currently in an unoptimized activation. // Check for optimized activations of this function. for (JavaScriptFrameIterator it(isolate); !it.done(); it.Advance()) { JavaScriptFrame* frame = it.frame(); if (frame->is_optimized() && frame->function() == *function) return false; } return true; } RUNTIME_FUNCTION(Runtime_CompileForOnStackReplacement) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); Handle<Code> caller_code(function->shared()->code()); // We're not prepared to handle a function with arguments object. DCHECK(!function->shared()->uses_arguments()); RUNTIME_ASSERT(FLAG_use_osr); // Passing the PC in the javascript frame from the caller directly is // not GC safe, so we walk the stack to get it. JavaScriptFrameIterator it(isolate); JavaScriptFrame* frame = it.frame(); if (!caller_code->contains(frame->pc())) { // Code on the stack may not be the code object referenced by the shared // function info. It may have been replaced to include deoptimization data. caller_code = Handle<Code>(frame->LookupCode()); } uint32_t pc_offset = static_cast<uint32_t>(frame->pc() - caller_code->instruction_start()); #ifdef DEBUG DCHECK_EQ(frame->function(), *function); DCHECK_EQ(frame->LookupCode(), *caller_code); DCHECK(caller_code->contains(frame->pc())); #endif // DEBUG BailoutId ast_id = caller_code->TranslatePcOffsetToAstId(pc_offset); DCHECK(!ast_id.IsNone()); Compiler::ConcurrencyMode mode = isolate->concurrent_osr_enabled() && (function->shared()->ast_node_count() > 512) ? Compiler::CONCURRENT : Compiler::NOT_CONCURRENT; Handle<Code> result = Handle<Code>::null(); OptimizedCompileJob* job = NULL; if (mode == Compiler::CONCURRENT) { // Gate the OSR entry with a stack check. BackEdgeTable::AddStackCheck(caller_code, pc_offset); // Poll already queued compilation jobs. OptimizingCompileDispatcher* dispatcher = isolate->optimizing_compile_dispatcher(); if (dispatcher->IsQueuedForOSR(function, ast_id)) { if (FLAG_trace_osr) { PrintF("[OSR - Still waiting for queued: "); function->PrintName(); PrintF(" at AST id %d]\n", ast_id.ToInt()); } return NULL; } job = dispatcher->FindReadyOSRCandidate(function, ast_id); } if (job != NULL) { if (FLAG_trace_osr) { PrintF("[OSR - Found ready: "); function->PrintName(); PrintF(" at AST id %d]\n", ast_id.ToInt()); } result = Compiler::GetConcurrentlyOptimizedCode(job); } else if (IsSuitableForOnStackReplacement(isolate, function)) { if (FLAG_trace_osr) { PrintF("[OSR - Compiling: "); function->PrintName(); PrintF(" at AST id %d]\n", ast_id.ToInt()); } MaybeHandle<Code> maybe_result = Compiler::GetOptimizedCode(function, caller_code, mode, ast_id); if (maybe_result.ToHandle(&result) && result.is_identical_to(isolate->builtins()->InOptimizationQueue())) { // Optimization is queued. Return to check later. return NULL; } } // Revert the patched back edge table, regardless of whether OSR succeeds. BackEdgeTable::Revert(isolate, *caller_code); // Check whether we ended up with usable optimized code. if (!result.is_null() && result->kind() == Code::OPTIMIZED_FUNCTION) { DeoptimizationInputData* data = DeoptimizationInputData::cast(result->deoptimization_data()); if (data->OsrPcOffset()->value() >= 0) { DCHECK(BailoutId(data->OsrAstId()->value()) == ast_id); if (FLAG_trace_osr) { PrintF("[OSR - Entry at AST id %d, offset %d in optimized code]\n", ast_id.ToInt(), data->OsrPcOffset()->value()); } // TODO(titzer): this is a massive hack to make the deopt counts // match. Fix heuristics for reenabling optimizations! function->shared()->increment_deopt_count(); if (result->is_turbofanned()) { // TurboFanned OSR code cannot be installed into the function. // But the function is obviously hot, so optimize it next time. function->ReplaceCode( isolate->builtins()->builtin(Builtins::kCompileOptimized)); } else { // Crankshafted OSR code can be installed into the function. function->ReplaceCode(*result); } return *result; } } // Failed. if (FLAG_trace_osr) { PrintF("[OSR - Failed: "); function->PrintName(); PrintF(" at AST id %d]\n", ast_id.ToInt()); } if (!function->IsOptimized()) { function->ReplaceCode(function->shared()->code()); } return NULL; } RUNTIME_FUNCTION(Runtime_TryInstallOptimizedCode) { HandleScope scope(isolate); DCHECK(args.length() == 1); CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0); // First check if this is a real stack overflow. StackLimitCheck check(isolate); if (check.JsHasOverflowed()) { SealHandleScope shs(isolate); return isolate->StackOverflow(); } isolate->optimizing_compile_dispatcher()->InstallOptimizedFunctions(); return (function->IsOptimized()) ? function->code() : function->shared()->code(); } bool CodeGenerationFromStringsAllowed(Isolate* isolate, Handle<Context> context) { DCHECK(context->allow_code_gen_from_strings()->IsFalse()); // Check with callback if set. AllowCodeGenerationFromStringsCallback callback = isolate->allow_code_gen_callback(); if (callback == NULL) { // No callback set and code generation disallowed. return false; } else { // Callback set. Let it decide if code generation is allowed. VMState<EXTERNAL> state(isolate); return callback(v8::Utils::ToLocal(context)); } } RUNTIME_FUNCTION(Runtime_CompileString) { HandleScope scope(isolate); DCHECK(args.length() == 2); CONVERT_ARG_HANDLE_CHECKED(String, source, 0); CONVERT_BOOLEAN_ARG_CHECKED(function_literal_only, 1); // Extract native context. Handle<Context> context(isolate->native_context()); // Check if native context allows code generation from // strings. Throw an exception if it doesn't. if (context->allow_code_gen_from_strings()->IsFalse() && !CodeGenerationFromStringsAllowed(isolate, context)) { Handle<Object> error_message = context->ErrorMessageForCodeGenerationFromStrings(); THROW_NEW_ERROR_RETURN_FAILURE( isolate, NewEvalError(MessageTemplate::kCodeGenFromStrings, error_message)); } // Compile source string in the native context. ParseRestriction restriction = function_literal_only ? ONLY_SINGLE_FUNCTION_LITERAL : NO_PARSE_RESTRICTION; Handle<SharedFunctionInfo> outer_info(context->closure()->shared(), isolate); Handle<JSFunction> fun; ASSIGN_RETURN_FAILURE_ON_EXCEPTION( isolate, fun, Compiler::GetFunctionFromEval(source, outer_info, context, SLOPPY, restriction, RelocInfo::kNoPosition)); return *fun; } static ObjectPair CompileGlobalEval(Isolate* isolate, Handle<String> source, Handle<SharedFunctionInfo> outer_info, Handle<Object> receiver, LanguageMode language_mode, int scope_position) { Handle<Context> context = Handle<Context>(isolate->context()); Handle<Context> native_context = Handle<Context>(context->native_context()); // Check if native context allows code generation from // strings. Throw an exception if it doesn't. if (native_context->allow_code_gen_from_strings()->IsFalse() && !CodeGenerationFromStringsAllowed(isolate, native_context)) { Handle<Object> error_message = native_context->ErrorMessageForCodeGenerationFromStrings(); Handle<Object> error; MaybeHandle<Object> maybe_error = isolate->factory()->NewEvalError( MessageTemplate::kCodeGenFromStrings, error_message); if (maybe_error.ToHandle(&error)) isolate->Throw(*error); return MakePair(isolate->heap()->exception(), NULL); } // Deal with a normal eval call with a string argument. Compile it // and return the compiled function bound in the local context. static const ParseRestriction restriction = NO_PARSE_RESTRICTION; Handle<JSFunction> compiled; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, compiled, Compiler::GetFunctionFromEval(source, outer_info, context, language_mode, restriction, scope_position), MakePair(isolate->heap()->exception(), NULL)); return MakePair(*compiled, *receiver); } RUNTIME_FUNCTION_RETURN_PAIR(Runtime_ResolvePossiblyDirectEval) { HandleScope scope(isolate); DCHECK(args.length() == 6); Handle<Object> callee = args.at<Object>(0); // If "eval" didn't refer to the original GlobalEval, it's not a // direct call to eval. // (And even if it is, but the first argument isn't a string, just let // execution default to an indirect call to eval, which will also return // the first argument without doing anything). if (*callee != isolate->native_context()->global_eval_fun() || !args[1]->IsString()) { return MakePair(*callee, isolate->heap()->undefined_value()); } DCHECK(args[4]->IsSmi()); DCHECK(is_valid_language_mode(args.smi_at(4))); LanguageMode language_mode = static_cast<LanguageMode>(args.smi_at(4)); DCHECK(args[5]->IsSmi()); Handle<SharedFunctionInfo> outer_info(args.at<JSFunction>(2)->shared(), isolate); return CompileGlobalEval(isolate, args.at<String>(1), outer_info, args.at<Object>(3), language_mode, args.smi_at(5)); } } // namespace internal } // namespace v8
zhangf911/fibjs
vender/v8/src/runtime/runtime-compiler.cc
C++
gpl-3.0
15,913
<?php /* * This file is part of the symfony package. * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * sfCacheFilter deals with page caching and action caching. * * @package symfony * @subpackage filter * @author Fabien Potencier <fabien.potencier@symfony-project.com> * @version SVN: $Id: sfCacheFilter.class.php 13564 2008-11-30 21:34:25Z fabien $ */ class sfCacheFilter extends sfFilter { protected $cacheManager = null, $request = null, $response = null, $routing = null, $cache = array(); /** * Initializes this Filter. * * @param sfContext $context The current application context * @param array $parameters An associative array of initialization parameters * * @return bool true, if initialization completes successfully, otherwise false * * @throws <b>sfInitializationException</b> If an error occurs while initializing this Filter */ public function initialize($context, $parameters = array()) { parent::initialize($context, $parameters); $this->cacheManager = $context->getViewCacheManager(); $this->request = $context->getRequest(); $this->response = $context->getResponse(); $this->routing = $context->getRouting(); } /** * Executes this filter. * * @param sfFilterChain $filterChain A sfFilterChain instance */ public function execute($filterChain) { // execute this filter only once, if cache is set and no GET or POST parameters if (!sfConfig::get('sf_cache')) { $filterChain->execute(); return; } if ($this->executeBeforeExecution()) { $filterChain->execute(); } $this->executeBeforeRendering(); } public function executeBeforeExecution() { // register our cache configuration $this->cacheManager->registerConfiguration($this->context->getModuleName()); $uri = $this->routing->getCurrentInternalUri(); if (is_null($uri)) { return true; } // page cache $cacheable = $this->cacheManager->isCacheable($uri); if ($cacheable && $this->cacheManager->withLayout($uri)) { $inCache = $this->cacheManager->getPageCache($uri); $this->cache[$uri] = $inCache; if ($inCache) { // page is in cache, so no need to run execution filter return false; } } return true; } /** * Executes this filter. */ public function executeBeforeRendering() { // cache only 200 HTTP status if (200 != $this->response->getStatusCode()) { return; } $uri = $this->routing->getCurrentInternalUri(); // save page in cache if (isset($this->cache[$uri]) && false === $this->cache[$uri]) { $this->setCacheExpiration($uri); $this->setCacheValidation($uri); // set Vary headers foreach ($this->cacheManager->getVary($uri, 'page') as $vary) { $this->response->addVaryHttpHeader($vary); } $this->cacheManager->setPageCache($uri); } // cache validation $this->checkCacheValidation(); } /** * Sets cache expiration headers. * * @param string An internal URI */ protected function setCacheExpiration($uri) { // don't add cache expiration (Expires) if // * the client lifetime is not set // * the response already has a cache validation (Last-Modified header) // * the Expires header has already been set if (!$lifetime = $this->cacheManager->getClientLifeTime($uri, 'page')) { return; } if ($this->response->hasHttpHeader('Last-Modified')) { return; } if (!$this->response->hasHttpHeader('Expires')) { $this->response->setHttpHeader('Expires', $this->response->getDate(time() + $lifetime), false); $this->response->addCacheControlHttpHeader('max-age', $lifetime); } } /** * Sets cache validation headers. * * @param string An internal URI */ protected function setCacheValidation($uri) { // don't add cache validation (Last-Modified) if // * the client lifetime is set (cache.yml) // * the response already has a Last-Modified header if ($this->cacheManager->getClientLifeTime($uri, 'page')) { return; } if (!$this->response->hasHttpHeader('Last-Modified')) { $this->response->setHttpHeader('Last-Modified', $this->response->getDate(time()), false); } if (sfConfig::get('sf_etag')) { $etag = '"'.md5($this->response->getContent()).'"'; $this->response->setHttpHeader('ETag', $etag); } } /** * Checks cache validation headers. */ protected function checkCacheValidation() { // Etag support if (sfConfig::get('sf_etag')) { $etag = '"'.md5($this->response->getContent()).'"'; if ($this->request->getHttpHeader('IF_NONE_MATCH') == $etag) { $this->response->setStatusCode(304); $this->response->setHeaderOnly(true); if (sfConfig::get('sf_logging_enabled')) { $this->context->getEventDispatcher()->notify(new sfEvent($this, 'application.log', array('ETag matches If-None-Match (send 304)'))); } } } // conditional GET support // never in debug mode if ($this->response->hasHttpHeader('Last-Modified') && !sfConfig::get('sf_debug')) { $lastModified = $this->response->getHttpHeader('Last-Modified'); $lastModified = $lastModified[0]; if ($this->request->getHttpHeader('IF_MODIFIED_SINCE') == $lastModified) { $this->response->setStatusCode(304); $this->response->setHeaderOnly(true); if (sfConfig::get('sf_logging_enabled')) { $this->context->getEventDispatcher()->notify(new sfEvent($this, 'application.log', array('Last-Modified matches If-Modified-Since (send 304)'))); } } } } }
sandaru1/codejam
www/lib/symfony/filter/sfCacheFilter.class.php
PHP
gpl-3.0
6,072
package org.apache.bcel.generic; /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache BCEL" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * "Apache BCEL", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import org.apache.bcel.Constants; import org.apache.bcel.ExceptionConstants; /** * GETFIELD - Fetch field from object * <PRE>Stack: ..., objectref -&gt; ..., value</PRE> * OR * <PRE>Stack: ..., objectref -&gt; ..., value.word1, value.word2</PRE> * * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A> * @version $Id: GETFIELD.java,v 1.2 2006/08/23 13:48:30 andos Exp $ */ public class GETFIELD extends FieldInstruction implements ExceptionThrower, StackConsumer, StackProducer { /** * */ private static final long serialVersionUID = -6510928743515082496L; /** * Empty constructor needed for the Class.newInstance() statement in * Instruction.readInstruction(). Not to be used otherwise. */ GETFIELD() { } public GETFIELD(int index) { super(Constants.GETFIELD, index); } public int produceStack(ConstantPoolGen cpg) { return getFieldSize(cpg); } public Class[] getExceptions() { Class[] cs = new Class[2 + ExceptionConstants.EXCS_FIELD_AND_METHOD_RESOLUTION.length]; System.arraycopy(ExceptionConstants.EXCS_FIELD_AND_METHOD_RESOLUTION, 0, cs, 0, ExceptionConstants.EXCS_FIELD_AND_METHOD_RESOLUTION.length); cs[ExceptionConstants.EXCS_FIELD_AND_METHOD_RESOLUTION.length + 1] = ExceptionConstants.INCOMPATIBLE_CLASS_CHANGE_ERROR; cs[ExceptionConstants.EXCS_FIELD_AND_METHOD_RESOLUTION.length] = ExceptionConstants.NULL_POINTER_EXCEPTION; return cs; } /** * Call corresponding visitor method(s). The order is: * Call visitor methods of implemented interfaces first, then * call methods according to the class hierarchy in descending order, * i.e., the most specific visitXXX() call comes last. * * @param v Visitor object */ public void accept(Visitor v) { v.visitExceptionThrower(this); v.visitStackConsumer(this); v.visitStackProducer(this); v.visitTypedInstruction(this); v.visitLoadClass(this); v.visitCPInstruction(this); v.visitFieldOrMethod(this); v.visitFieldInstruction(this); v.visitGETFIELD(this); } }
miuirussia/KJBE
src/org/apache/bcel/generic/GETFIELD.java
Java
gpl-3.0
4,938
exports.play = 'afplay'; exports.raise_volume = 'osascript -e "set Volume 10"'; // unmutes as well
prey/prey-node-client
lib/agent/actions/alarm/mac.js
JavaScript
gpl-3.0
98
package de.metas.ui.web.window.exceptions; import org.adempiere.exceptions.AdempiereException; import de.metas.ui.web.window.datatypes.DocumentPath; import de.metas.ui.web.window.model.Document; /* * #%L * metasfresh-webui-api * %% * Copyright (C) 2016 metas GmbH * %% * 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, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ @SuppressWarnings("serial") public class InvalidDocumentStateException extends AdempiereException { public InvalidDocumentStateException(final Document document, final String reason) { super(buildMsg(document.getDocumentPath(), reason)); } public InvalidDocumentStateException(final DocumentPath documentPath, final String reason) { super(buildMsg(documentPath, reason)); } private static String buildMsg(final DocumentPath documentPath, final String reason) { return "Document " + documentPath + " state is invalid: " + reason; } }
metasfresh/metasfresh-webui-api
src/main/java/de/metas/ui/web/window/exceptions/InvalidDocumentStateException.java
Java
gpl-3.0
1,498
/* * 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.commons.math3.ode; import org.apache.commons.math3.RealFieldElement; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.MaxCountExceededException; /** * This interface allows users to add secondary differential equations to a primary * set of differential equations. * <p> * In some cases users may need to integrate some problem-specific equations along * with a primary set of differential equations. One example is optimal control where * adjoined parameters linked to the minimized Hamiltonian must be integrated. * </p> * <p> * This interface allows users to add such equations to a primary set of {@link * FirstOrderFieldDifferentialEquations first order differential equations} * thanks to the {@link FieldExpandableODE#addSecondaryEquations(FieldSecondaryEquations)} * method. * </p> * @see FirstOrderFieldDifferentialEquations * @see FieldExpandableODE * @param <T> the type of the field elements * @since 3.6 */ public interface FieldSecondaryEquations<T extends RealFieldElement<T>> { /** Get the dimension of the secondary state parameters. * @return dimension of the secondary state parameters */ int getDimension(); /** Initialize equations at the start of an ODE integration. * <p> * This method is called once at the start of the integration. It * may be used by the equations to initialize some internal data * if needed. * </p> * @param t0 value of the independent <I>time</I> variable at integration start * @param primary0 array containing the value of the primary state vector at integration start * @param secondary0 array containing the value of the secondary state vector at integration start * @param finalTime target time for the integration */ void init(T t0, T[] primary0, T[] secondary0, T finalTime); /** Compute the derivatives related to the secondary state parameters. * @param t current value of the independent <I>time</I> variable * @param primary array containing the current value of the primary state vector * @param primaryDot array containing the derivative of the primary state vector * @param secondary array containing the current value of the secondary state vector * @return derivative of the secondary state vector * @exception MaxCountExceededException if the number of functions evaluations is exceeded * @exception DimensionMismatchException if arrays dimensions do not match equations settings */ T[] computeDerivatives(T t, T[] primary, T[] primaryDot, T[] secondary) throws MaxCountExceededException, DimensionMismatchException; }
happyjack27/autoredistrict
src/org/apache/commons/math3/ode/FieldSecondaryEquations.java
Java
gpl-3.0
3,524
using GitCommands; using GitCommands.Utils; namespace GitUI.CommandsDialogs.SettingsDialog.Pages { public partial class FormBrowseRepoSettingsPage : SettingsPageWithHeader { public FormBrowseRepoSettingsPage() { InitializeComponent(); Text = "Browse repository window"; Translate(); } protected override void Init(ISettingsPageHost aPageHost) { base.Init(aPageHost); BindSettingsWithControls(); } protected override void SettingsToPage() { chkShowRevisionInfoNextToRevisionGrid.Checked = AppSettings.ShowRevisionInfoNextToRevisionGrid; chkShowRevisionInfoNextToRevisionGrid.Visible = !EnvUtils.IsMonoRuntime(); base.SettingsToPage(); } protected override void PageToSettings() { AppSettings.ShowRevisionInfoNextToRevisionGrid = chkShowRevisionInfoNextToRevisionGrid.Checked; base.PageToSettings(); } private void BindSettingsWithControls() { AddSettingBinding(AppSettings.ShowConEmuTab, chkChowConsoleTab); AddSettingBinding(AppSettings.ConEmuStyle, _NO_TRANSLATE_cboStyle); AddSettingBinding(AppSettings.ConEmuTerminal, cboTerminal); AddSettingBinding(AppSettings.ConEmuFontSize, cboFontSize); AddSettingBinding(AppSettings.ShowGpgInformation, chkShowGpgInformation); } private void chkChowConsoleTab_CheckedChanged(object sender, System.EventArgs e) { groupBoxConsoleSettings.Enabled = chkChowConsoleTab.Checked; } public static SettingsPageReference GetPageReference() { return new SettingsPageReferenceByType(typeof(FormBrowseRepoSettingsPage)); } } }
gencer/gitextensions
GitUI/CommandsDialogs/SettingsDialog/Pages/FormBrowseRepoSettingsPage.cs
C#
gpl-3.0
1,850
module Genome module Importers module DSL module WithDrugsAndGenes attr_accessor :gene_claim, :drug_claim def initialize(item_id, importer_instance, row_instance) super(item_id, importer_instance, row_instance, 'interaction_claim') end def gene(column, opts = {}, &block) opts = @defaults.merge opts val = opts[:transform].call(@row.send(column)) if !opts[:unless].call(val) @gene_claim_id = @importer.create_gene_claim(name: val, nomenclature: opts[:nomenclature]) node = GeneNode.new(@gene_claim_id, @importer, @row) node.instance_eval(&block) end end def drug(column, opts = {}, &block) opts = @defaults.merge opts val = opts[:transform].call(@row.send(column)) if !opts[:unless].call(val) @drug_claim_id = @importer.create_drug_claim(name: val, nomenclature: opts[:nomenclature], primary_name: opts[:transform].call(@row.send(opts[:primary_name]))) node = DrugNode.new(@drug_claim_id, @importer, @row) node.instance_eval(&block) end end end end end end
genome/dgi-db
lib/genome/importers/dsl/with_drugs_and_genes.rb
Ruby
gpl-3.0
1,201
package buildcraftAdditions.ModIntegration.Buildcraft.Triggers; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; import buildcraft.api.statements.IStatementContainer; import buildcraft.api.statements.IStatementParameter; import buildcraftAdditions.tileEntities.TileChargingStation; /** * Copyright (c) 2014, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of GNU GPL v3.0 * Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public class TriggerDoneCharging extends BasicTrigger { public TriggerDoneCharging() { super("doneCharging", "TriggerDoneCharging"); } @Override public boolean isTriggerActive(TileEntity target, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { if (target instanceof TileChargingStation) { TileChargingStation chargingStation = (TileChargingStation) target; return chargingStation.getProgress() == 1; } return false; } }
AEnterprise/Buildcraft-Additions
src/main/java/buildcraftAdditions/ModIntegration/Buildcraft/Triggers/TriggerDoneCharging.java
Java
gpl-3.0
1,093
/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- #include "AP_BattMonitor.h" #include "AP_BattMonitor_Analog.h" #include "AP_BattMonitor_SMBus.h" #include "AP_BattMonitor_Bebop.h" extern const AP_HAL::HAL& hal; const AP_Param::GroupInfo AP_BattMonitor::var_info[] = { // @Param: _MONITOR // @DisplayName: Battery monitoring // @Description: Controls enabling monitoring of the battery's voltage and current // @Values: 0:Disabled,3:Analog Voltage Only,4:Analog Voltage and Current,5:SMBus,6:Bebop // @User: Standard AP_GROUPINFO("_MONITOR", 0, AP_BattMonitor, _monitoring[0], BattMonitor_TYPE_NONE), // @Param: _VOLT_PIN // @DisplayName: Battery Voltage sensing pin // @Description: Setting this to 0 ~ 13 will enable battery voltage sensing on pins A0 ~ A13. For the 3DR power brick on APM2.5 it should be set to 13. On the PX4 it should be set to 100. On the Pixhawk powered from the PM connector it should be set to 2. // @Values: -1:Disabled, 0:A0, 1:A1, 2:Pixhawk, 13:A13, 100:PX4 // @User: Standard AP_GROUPINFO("_VOLT_PIN", 1, AP_BattMonitor, _volt_pin[0], AP_BATT_VOLT_PIN), // @Param: _CURR_PIN // @DisplayName: Battery Current sensing pin // @Description: Setting this to 0 ~ 13 will enable battery current sensing on pins A0 ~ A13. For the 3DR power brick on APM2.5 it should be set to 12. On the PX4 it should be set to 101. On the Pixhawk powered from the PM connector it should be set to 3. // @Values: -1:Disabled, 1:A1, 2:A2, 3:Pixhawk, 12:A12, 101:PX4 // @User: Standard AP_GROUPINFO("_CURR_PIN", 2, AP_BattMonitor, _curr_pin[0], AP_BATT_CURR_PIN), // @Param: _VOLT_MULT // @DisplayName: Voltage Multiplier // @Description: Used to convert the voltage of the voltage sensing pin (BATT_VOLT_PIN) to the actual battery's voltage (pin_voltage * VOLT_MULT). For the 3DR Power brick on APM2 or Pixhawk, this should be set to 10.1. For the Pixhawk with the 3DR 4in1 ESC this should be 12.02. For the PX4 using the PX4IO power supply this should be set to 1. // @User: Advanced AP_GROUPINFO("_VOLT_MULT", 3, AP_BattMonitor, _volt_multiplier[0], AP_BATT_VOLTDIVIDER_DEFAULT), // @Param: _AMP_PERVOLT // @DisplayName: Amps per volt // @Description: Number of amps that a 1V reading on the current sensor corresponds to. On the APM2 or Pixhawk using the 3DR Power brick this should be set to 17. For the Pixhawk with the 3DR 4in1 ESC this should be 17. // @Units: Amps/Volt // @User: Standard AP_GROUPINFO("_AMP_PERVOLT", 4, AP_BattMonitor, _curr_amp_per_volt[0], AP_BATT_CURR_AMP_PERVOLT_DEFAULT), // @Param: _AMP_OFFSET // @DisplayName: AMP offset // @Description: Voltage offset at zero current on current sensor // @Units: Volts // @User: Standard AP_GROUPINFO("_AMP_OFFSET", 5, AP_BattMonitor, _curr_amp_offset[0], 0), // @Param: _CAPACITY // @DisplayName: Battery capacity // @Description: Capacity of the battery in mAh when full // @Units: mAh // @Increment: 50 // @User: Standard AP_GROUPINFO("_CAPACITY", 6, AP_BattMonitor, _pack_capacity[0], AP_BATT_CAPACITY_DEFAULT), // 7 & 8 were used for VOLT2_PIN and VOLT2_MULT #if APM_BUILD_TYPE(APM_BUILD_ArduPlane) // @Param: _WATT_MAX // @DisplayName: Maximum allowed power (Watts) // @Description: If battery wattage (voltage * current) exceeds this value then the system will reduce max throttle (THR_MAX, TKOFF_THR_MAX and THR_MIN for reverse thrust) to satisfy this limit. This helps limit high current to low C rated batteries regardless of battery voltage. The max throttle will slowly grow back to THR_MAX (or TKOFF_THR_MAX ) and THR_MIN if demanding the current max and under the watt max. Use 0 to disable. // @Units: Watts // @Increment: 1 // @User: Advanced AP_GROUPINFO("_WATT_MAX", 9, AP_BattMonitor, _watt_max[0], AP_BATT_MAX_WATT_DEFAULT), #endif // 10 is left for future expansion #if AP_BATT_MONITOR_MAX_INSTANCES > 1 // @Param: 2_MONITOR // @DisplayName: Battery monitoring // @Description: Controls enabling monitoring of the battery's voltage and current // @Values: 0:Disabled,3:Analog Voltage Only,4:Analog Voltage and Current,5:SMBus,6:Bebop // @User: Standard AP_GROUPINFO("2_MONITOR", 11, AP_BattMonitor, _monitoring[1], BattMonitor_TYPE_NONE), // @Param: 2_VOLT_PIN // @DisplayName: Battery Voltage sensing pin // @Description: Setting this to 0 ~ 13 will enable battery voltage sensing on pins A0 ~ A13. For the 3DR power brick on APM2.5 it should be set to 13. On the PX4 it should be set to 100. On the Pixhawk powered from the PM connector it should be set to 2. // @Values: -1:Disabled, 0:A0, 1:A1, 2:Pixhawk, 13:A13, 100:PX4 // @User: Standard AP_GROUPINFO("2_VOLT_PIN", 12, AP_BattMonitor, _volt_pin[1], AP_BATT_VOLT_PIN), // @Param: 2_CURR_PIN // @DisplayName: Battery Current sensing pin // @Description: Setting this to 0 ~ 13 will enable battery current sensing on pins A0 ~ A13. For the 3DR power brick on APM2.5 it should be set to 12. On the PX4 it should be set to 101. On the Pixhawk powered from the PM connector it should be set to 3. // @Values: -1:Disabled, 1:A1, 2:A2, 3:Pixhawk, 12:A12, 101:PX4 // @User: Standard AP_GROUPINFO("2_CURR_PIN", 13, AP_BattMonitor, _curr_pin[1], AP_BATT_CURR_PIN), // @Param: 2_VOLT_MULT // @DisplayName: Voltage Multiplier // @Description: Used to convert the voltage of the voltage sensing pin (BATT_VOLT_PIN) to the actual battery's voltage (pin_voltage * VOLT_MULT). For the 3DR Power brick on APM2 or Pixhawk, this should be set to 10.1. For the Pixhawk with the 3DR 4in1 ESC this should be 12.02. For the PX4 using the PX4IO power supply this should be set to 1. // @User: Advanced AP_GROUPINFO("2_VOLT_MULT", 14, AP_BattMonitor, _volt_multiplier[1], AP_BATT_VOLTDIVIDER_DEFAULT), // @Param: 2_AMP_PERVOL // @DisplayName: Amps per volt // @Description: Number of amps that a 1V reading on the current sensor corresponds to. On the APM2 or Pixhawk using the 3DR Power brick this should be set to 17. For the Pixhawk with the 3DR 4in1 ESC this should be 17. // @Units: Amps/Volt // @User: Standard AP_GROUPINFO("2_AMP_PERVOL", 15, AP_BattMonitor, _curr_amp_per_volt[1], AP_BATT_CURR_AMP_PERVOLT_DEFAULT), // @Param: 2_AMP_OFFSET // @DisplayName: AMP offset // @Description: Voltage offset at zero current on current sensor // @Units: Volts // @User: Standard AP_GROUPINFO("2_AMP_OFFSET", 16, AP_BattMonitor, _curr_amp_offset[1], 0), // @Param: 2_CAPACITY // @DisplayName: Battery capacity // @Description: Capacity of the battery in mAh when full // @Units: mAh // @Increment: 50 // @User: Standard AP_GROUPINFO("2_CAPACITY", 17, AP_BattMonitor, _pack_capacity[1], AP_BATT_CAPACITY_DEFAULT), #if APM_BUILD_TYPE(APM_BUILD_ArduPlane) // @Param: 2_WATT_MAX // @DisplayName: Maximum allowed current // @Description: If battery wattage (voltage * current) exceeds this value then the system will reduce max throttle (THR_MAX, TKOFF_THR_MAX and THR_MIN for reverse thrust) to satisfy this limit. This helps limit high current to low C rated batteries regardless of battery voltage. The max throttle will slowly grow back to THR_MAX (or TKOFF_THR_MAX ) and THR_MIN if demanding the current max and under the watt max. Use 0 to disable. // @Units: Amps // @Increment: 1 // @User: Advanced AP_GROUPINFO("2_WATT_MAX", 18, AP_BattMonitor, _watt_max[1], AP_BATT_MAX_WATT_DEFAULT), #endif #endif // AP_BATT_MONITOR_MAX_INSTANCES > 1 AP_GROUPEND }; // Default constructor. // Note that the Vector/Matrix constructors already implicitly zero // their values. // AP_BattMonitor::AP_BattMonitor(void) : _num_instances(0) { AP_Param::setup_object_defaults(this, var_info); } // init - instantiate the battery monitors void AP_BattMonitor::init() { // check init has not been called before if (_num_instances != 0) { return; } #if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_BEBOP || CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_DISCO // force monitor for bebop _monitoring[0] = BattMonitor_TYPE_BEBOP; #endif // create each instance for (uint8_t instance=0; instance<AP_BATT_MONITOR_MAX_INSTANCES; instance++) { uint8_t monitor_type = _monitoring[instance]; switch (monitor_type) { case BattMonitor_TYPE_ANALOG_VOLTAGE_ONLY: case BattMonitor_TYPE_ANALOG_VOLTAGE_AND_CURRENT: state[instance].instance = instance; drivers[instance] = new AP_BattMonitor_Analog(*this, instance, state[instance]); _num_instances++; break; case BattMonitor_TYPE_SMBUS: state[instance].instance = instance; #if CONFIG_HAL_BOARD == HAL_BOARD_PX4 drivers[instance] = new AP_BattMonitor_SMBus_PX4(*this, instance, state[instance]); #else drivers[instance] = new AP_BattMonitor_SMBus_I2C(*this, instance, state[instance]); #endif _num_instances++; break; case BattMonitor_TYPE_BEBOP: #if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_BEBOP || CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_DISCO state[instance].instance = instance; drivers[instance] = new AP_BattMonitor_Bebop(*this, instance, state[instance]); _num_instances++; #endif break; } // call init function for each backend if (drivers[instance] != NULL) { drivers[instance]->init(); } } } // read - read the voltage and current for all instances void AP_BattMonitor::read() { for (uint8_t i=0; i<_num_instances; i++) { if (drivers[i] != NULL && _monitoring[i] != BattMonitor_TYPE_NONE) { drivers[i]->read(); } } } // healthy - returns true if monitor is functioning bool AP_BattMonitor::healthy(uint8_t instance) const { return instance < _num_instances && _BattMonitor_STATE(instance).healthy; } bool AP_BattMonitor::is_powering_off(uint8_t instance) const { return instance < _num_instances && _BattMonitor_STATE(instance).is_powering_off; } /// has_current - returns true if battery monitor instance provides current info bool AP_BattMonitor::has_current(uint8_t instance) const { // check for analog voltage and current monitor or smbus monitor if (instance < _num_instances && drivers[instance] != NULL) { return (_monitoring[instance] == BattMonitor_TYPE_ANALOG_VOLTAGE_AND_CURRENT || _monitoring[instance] == BattMonitor_TYPE_SMBUS || _monitoring[instance] == BattMonitor_TYPE_BEBOP); } // not monitoring current return false; } /// voltage - returns battery voltage in volts float AP_BattMonitor::voltage(uint8_t instance) const { if (instance < _num_instances) { return _BattMonitor_STATE(instance).voltage; } else { return 0.0f; } } /// current_amps - returns the instantaneous current draw in amperes float AP_BattMonitor::current_amps(uint8_t instance) const { if (instance < _num_instances) { return _BattMonitor_STATE(instance).current_amps; } else { return 0.0f; } } /// current_total_mah - returns total current drawn since start-up in amp-hours float AP_BattMonitor::current_total_mah(uint8_t instance) const { if (instance < _num_instances) { return _BattMonitor_STATE(instance).current_total_mah; } else { return 0.0f; } } /// capacity_remaining_pct - returns the % battery capacity remaining (0 ~ 100) uint8_t AP_BattMonitor::capacity_remaining_pct(uint8_t instance) const { if (instance < _num_instances && drivers[instance] != NULL) { return drivers[instance]->capacity_remaining_pct(); } else { return 0; } } /// exhausted - returns true if the voltage remains below the low_voltage for 10 seconds or remaining capacity falls below min_capacity_mah bool AP_BattMonitor::exhausted(uint8_t instance, float low_voltage, float min_capacity_mah) { // exit immediately if no monitors setup if (_num_instances == 0 || instance >= _num_instances) { return false; } // check voltage if ((state[instance].voltage > 0) && (low_voltage > 0) && (state[instance].voltage < low_voltage)) { // this is the first time our voltage has dropped below minimum so start timer if (state[instance].low_voltage_start_ms == 0) { state[instance].low_voltage_start_ms = AP_HAL::millis(); } else if (AP_HAL::millis() - state[instance].low_voltage_start_ms > AP_BATT_LOW_VOLT_TIMEOUT_MS) { return true; } } else { // acceptable voltage so reset timer state[instance].low_voltage_start_ms = 0; } // check capacity if current monitoring is enabled if (has_current(instance) && (min_capacity_mah > 0) && (_pack_capacity[instance] - state[instance].current_total_mah < min_capacity_mah)) { return true; } // if we've gotten this far then battery is ok return false; } #if APM_BUILD_TYPE(APM_BUILD_ArduPlane) // return true if any battery is pushing too much power bool AP_BattMonitor::overpower_detected() const { bool result = false; for (int instance = 0; instance < _num_instances; instance++) { result |= overpower_detected(instance); } return result; } bool AP_BattMonitor::overpower_detected(uint8_t instance) const { if (instance < _num_instances && _watt_max[instance] > 0) { float power = _BattMonitor_STATE(instance).current_amps * _BattMonitor_STATE(instance).voltage; return _BattMonitor_STATE(instance).healthy && (power > _watt_max[instance]); } return false; } #endif
Boyang--Li/ardupilot
libraries/AP_BattMonitor/AP_BattMonitor.cpp
C++
gpl-3.0
14,002
using uint8_t = System.Byte; using uint16_t = System.UInt16; using uint32_t = System.UInt32; using uint64_t = System.UInt64; using int8_t = System.SByte; using int16_t = System.Int16; using int32_t = System.Int32; using int64_t = System.Int64; using float32 = System.Single; using System; using System.Linq; using System.Runtime.InteropServices; using System.Collections.Generic; namespace DroneCAN { public partial class DroneCAN { static void encode_uavcan_protocol_debug_LogLevel(uavcan_protocol_debug_LogLevel msg, dronecan_serializer_chunk_cb_ptr_t chunk_cb, object ctx) { uint8_t[] buffer = new uint8_t[8]; _encode_uavcan_protocol_debug_LogLevel(buffer, msg, chunk_cb, ctx, true); } static uint32_t decode_uavcan_protocol_debug_LogLevel(CanardRxTransfer transfer, uavcan_protocol_debug_LogLevel msg) { uint32_t bit_ofs = 0; _decode_uavcan_protocol_debug_LogLevel(transfer, ref bit_ofs, msg, true); return (bit_ofs+7)/8; } static void _encode_uavcan_protocol_debug_LogLevel(uint8_t[] buffer, uavcan_protocol_debug_LogLevel msg, dronecan_serializer_chunk_cb_ptr_t chunk_cb, object ctx, bool tao) { memset(buffer,0,8); canardEncodeScalar(buffer, 0, 3, msg.value); chunk_cb(buffer, 3, ctx); } static void _decode_uavcan_protocol_debug_LogLevel(CanardRxTransfer transfer,ref uint32_t bit_ofs, uavcan_protocol_debug_LogLevel msg, bool tao) { canardDecodeScalar(transfer, bit_ofs, 3, false, ref msg.value); bit_ofs += 3; } } }
ArduPilot/MissionPlanner
ExtLibs/DroneCAN/out/src/uavcan.protocol.debug.LogLevel.cs
C#
gpl-3.0
1,660
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /** * Copyright (c) 2014, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, * Washington University in St. Louis, * Beijing Institute of Technology, * The University of Memphis * * This file is part of NFD (Named Data Networking Forwarding Daemon). * See AUTHORS.md for complete list of NFD authors and contributors. * * NFD 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. * * NFD 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 * NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>. * * @author Jerald Paul Abraham <jeraldabraham@email.arizona.edu> */ #include "version.hpp" #include <ndn-cxx/face.hpp> #include <ndn-cxx/name.hpp> #include <ndn-cxx/interest.hpp> #include <ndn-cxx/encoding/buffer-stream.hpp> #include <ndn-cxx/management/nfd-forwarder-status.hpp> #include <ndn-cxx/management/nfd-channel-status.hpp> #include <ndn-cxx/management/nfd-face-status.hpp> #include <ndn-cxx/management/nfd-fib-entry.hpp> #include <ndn-cxx/management/nfd-rib-entry.hpp> #include <ndn-cxx/management/nfd-strategy-choice.hpp> #include <boost/algorithm/string/replace.hpp> #include <list> namespace ndn { class NfdStatus { public: explicit NfdStatus(char* toolName) : m_toolName(toolName) , m_needVersionRetrieval(false) , m_needChannelStatusRetrieval(false) , m_needFaceStatusRetrieval(false) , m_needFibEnumerationRetrieval(false) , m_needRibStatusRetrieval(false) , m_needStrategyChoiceRetrieval(false) , m_isOutputXml(false) { } void usage() { std::cout << "Usage: \n " << m_toolName << " [options]\n\n" "Show NFD version and status information\n\n" "Options:\n" " [-h] - print this help message\n" " [-v] - retrieve version information\n" " [-c] - retrieve channel status information\n" " [-f] - retrieve face status information\n" " [-b] - retrieve FIB information\n" " [-r] - retrieve RIB information\n" " [-s] - retrieve configured strategy choice for NDN namespaces\n" " [-x] - output NFD status information in XML format\n" "\n" " [-V] - show version information of nfd-status and exit\n" "\n" "If no options are provided, all information is retrieved.\n" "If -x is provided, other options(-v, -c, etc.) are ignored, and all information is printed in XML format.\n" ; } void enableVersionRetrieval() { m_needVersionRetrieval = true; } void enableChannelStatusRetrieval() { m_needChannelStatusRetrieval = true; } void enableFaceStatusRetrieval() { m_needFaceStatusRetrieval = true; } void enableFibEnumerationRetrieval() { m_needFibEnumerationRetrieval = true; } void enableStrategyChoiceRetrieval() { m_needStrategyChoiceRetrieval = true; } void enableRibStatusRetrieval() { m_needRibStatusRetrieval = true; } void enableXmlOutput() { m_isOutputXml = true; } void onTimeout() { std::cerr << "Request timed out" << std::endl; runNextStep(); } void fetchSegments(const Data& data, void (NfdStatus::*onDone)()) { m_buffer->write((const char*)data.getContent().value(), data.getContent().value_size()); uint64_t currentSegment = data.getName().get(-1).toSegment(); const name::Component& finalBlockId = data.getMetaInfo().getFinalBlockId(); if (finalBlockId.empty() || finalBlockId.toSegment() > currentSegment) { m_face.expressInterest(data.getName().getPrefix(-1).appendSegment(currentSegment+1), bind(&NfdStatus::fetchSegments, this, _2, onDone), bind(&NfdStatus::onTimeout, this)); } else { return (this->*onDone)(); } } void escapeSpecialCharacters(std::string *data) { using boost::algorithm::replace_all; replace_all(*data, "&", "&amp;"); replace_all(*data, "\"", "&quot;"); replace_all(*data, "\'", "&apos;"); replace_all(*data, "<", "&lt;"); replace_all(*data, ">", "&gt;"); } ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// void fetchVersionInformation() { Interest interest("/localhost/nfd/status"); interest.setChildSelector(1); interest.setMustBeFresh(true); m_face.expressInterest( interest, bind(&NfdStatus::afterFetchedVersionInformation, this, _2), bind(&NfdStatus::onTimeout, this)); } void afterFetchedVersionInformation(const Data& data) { nfd::ForwarderStatus status(data.getContent()); std::string nfdId; if (data.getSignature().hasKeyLocator()) { const ndn::KeyLocator& locator = data.getSignature().getKeyLocator(); if (locator.getType() == KeyLocator::KeyLocator_Name) nfdId = locator.getName().toUri(); //todo: KeyDigest supporting } if (m_isOutputXml) { std::cout << "<generalStatus>"; std::cout << "<nfdId>" << nfdId << "</nfdId>"; std::cout << "<version>" << status.getNfdVersion() << "</version>"; std::cout << "<startTime>" << time::toString(status.getStartTimestamp(), "%Y-%m-%dT%H:%M:%S%F") << "</startTime>"; std::cout << "<currentTime>" << time::toString(status.getCurrentTimestamp(), "%Y-%m-%dT%H:%M:%S%F") << "</currentTime>"; std::cout << "<uptime>PT" << time::duration_cast<time::seconds>(status.getCurrentTimestamp() - status.getStartTimestamp()).count() << "S</uptime>"; std::cout << "<nNameTreeEntries>" << status.getNNameTreeEntries() << "</nNameTreeEntries>"; std::cout << "<nFibEntries>" << status.getNFibEntries() << "</nFibEntries>"; std::cout << "<nPitEntries>" << status.getNPitEntries() << "</nPitEntries>"; std::cout << "<nMeasurementsEntries>" << status.getNMeasurementsEntries() << "</nMeasurementsEntries>"; std::cout << "<nCsEntries>" << status.getNCsEntries() << "</nCsEntries>"; std::cout << "<packetCounters>"; std::cout << "<incomingPackets>"; std::cout << "<nInterests>" << status.getNInInterests() << "</nInterests>"; std::cout << "<nDatas>" << status.getNInDatas() << "</nDatas>"; std::cout << "</incomingPackets>"; std::cout << "<outgoingPackets>"; std::cout << "<nInterests>" << status.getNOutInterests() << "</nInterests>"; std::cout << "<nDatas>" << status.getNOutDatas() << "</nDatas>"; std::cout << "</outgoingPackets>"; std::cout << "</packetCounters>"; std::cout << "</generalStatus>"; } else { std::cout << "General NFD status:" << std::endl; std::cout << " nfdId=" << nfdId << std::endl; std::cout << " version=" << status.getNfdVersion() << std::endl; std::cout << " startTime=" << time::toIsoString(status.getStartTimestamp()) << std::endl; std::cout << " currentTime=" << time::toIsoString(status.getCurrentTimestamp()) << std::endl; std::cout << " uptime=" << time::duration_cast<time::seconds>(status.getCurrentTimestamp() - status.getStartTimestamp()) << std::endl; std::cout << " nNameTreeEntries=" << status.getNNameTreeEntries() << std::endl; std::cout << " nFibEntries=" << status.getNFibEntries() << std::endl; std::cout << " nPitEntries=" << status.getNPitEntries() << std::endl; std::cout << " nMeasurementsEntries=" << status.getNMeasurementsEntries() << std::endl; std::cout << " nCsEntries=" << status.getNCsEntries() << std::endl; std::cout << " nInInterests=" << status.getNInInterests() << std::endl; std::cout << " nOutInterests=" << status.getNOutInterests() << std::endl; std::cout << " nInDatas=" << status.getNInDatas() << std::endl; std::cout << " nOutDatas=" << status.getNOutDatas() << std::endl; } runNextStep(); } ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// void fetchChannelStatusInformation() { m_buffer = make_shared<OBufferStream>(); Interest interest("/localhost/nfd/faces/channels"); interest.setChildSelector(1); interest.setMustBeFresh(true); m_face.expressInterest(interest, bind(&NfdStatus::fetchSegments, this, _2, &NfdStatus::afterFetchedChannelStatusInformation), bind(&NfdStatus::onTimeout, this)); } void afterFetchedChannelStatusInformation() { ConstBufferPtr buf = m_buffer->buf(); if (m_isOutputXml) { std::cout << "<channels>"; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode ChannelStatus TLV" << std::endl; break; } offset += block.size(); nfd::ChannelStatus channelStatus(block); std::cout << "<channel>"; std::string localUri(channelStatus.getLocalUri()); escapeSpecialCharacters(&localUri); std::cout << "<localUri>" << localUri << "</localUri>"; std::cout << "</channel>"; } std::cout << "</channels>"; } else { std::cout << "Channels:" << std::endl; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode ChannelStatus TLV" << std::endl; break; } offset += block.size(); nfd::ChannelStatus channelStatus(block); std::cout << " " << channelStatus.getLocalUri() << std::endl; } } runNextStep(); } ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// void fetchFaceStatusInformation() { m_buffer = make_shared<OBufferStream>(); Interest interest("/localhost/nfd/faces/list"); interest.setChildSelector(1); interest.setMustBeFresh(true); m_face.expressInterest(interest, bind(&NfdStatus::fetchSegments, this, _2, &NfdStatus::afterFetchedFaceStatusInformation), bind(&NfdStatus::onTimeout, this)); } void afterFetchedFaceStatusInformation() { ConstBufferPtr buf = m_buffer->buf(); if (m_isOutputXml) { std::cout << "<faces>"; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode FaceStatus TLV" << std::endl; break; } offset += block.size(); nfd::FaceStatus faceStatus(block); std::cout << "<face>"; std::cout << "<faceId>" << faceStatus.getFaceId() << "</faceId>"; std::string remoteUri(faceStatus.getRemoteUri()); escapeSpecialCharacters(&remoteUri); std::cout << "<remoteUri>" << remoteUri << "</remoteUri>"; std::string localUri(faceStatus.getLocalUri()); escapeSpecialCharacters(&localUri); std::cout << "<localUri>" << localUri << "</localUri>"; if (faceStatus.hasExpirationPeriod()) { std::cout << "<expirationPeriod>PT" << time::duration_cast<time::seconds>(faceStatus.getExpirationPeriod()) .count() << "S" << "</expirationPeriod>"; } std::cout << "<packetCounters>"; std::cout << "<incomingPackets>"; std::cout << "<nInterests>" << faceStatus.getNInInterests() << "</nInterests>"; std::cout << "<nDatas>" << faceStatus.getNInDatas() << "</nDatas>"; std::cout << "</incomingPackets>"; std::cout << "<outgoingPackets>"; std::cout << "<nInterests>" << faceStatus.getNOutInterests() << "</nInterests>"; std::cout << "<nDatas>" << faceStatus.getNOutDatas() << "</nDatas>"; std::cout << "</outgoingPackets>"; std::cout << "</packetCounters>"; std::cout << "<byteCounters>"; std::cout << "<incomingBytes>" << faceStatus.getNInBytes() << "</incomingBytes>"; std::cout << "<outgoingBytes>" << faceStatus.getNOutBytes() << "</outgoingBytes>"; std::cout << "</byteCounters>"; if (faceStatus.getFlags() != 0) { std::cout << "<flags>"; if (faceStatus.isLocal()) { std::cout << "<local/>"; } if (faceStatus.isOnDemand()) { std::cout << "<on-demand/>"; } std::cout << "</flags>"; } std::cout << "</face>"; } std::cout << "</faces>"; } else { std::cout << "Faces:" << std::endl; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode FaceStatus TLV" << std::endl; break; } offset += block.size(); nfd::FaceStatus faceStatus(block); std::cout << " faceid=" << faceStatus.getFaceId() << " remote=" << faceStatus.getRemoteUri() << " local=" << faceStatus.getLocalUri(); if (faceStatus.hasExpirationPeriod()) { std::cout << " expires=" << time::duration_cast<time::seconds>(faceStatus.getExpirationPeriod()) .count() << "s"; } std::cout << " counters={" << "in={" << faceStatus.getNInInterests() << "i " << faceStatus.getNInDatas() << "d " << faceStatus.getNInBytes() << "B}" << " out={" << faceStatus.getNOutInterests() << "i " << faceStatus.getNOutDatas() << "d " << faceStatus.getNOutBytes() << "B}" << "}"; if (faceStatus.isLocal()) std::cout << " local"; if (faceStatus.isOnDemand()) std::cout << " on-demand"; std::cout << std::endl; } } runNextStep(); } ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// void fetchFibEnumerationInformation() { m_buffer = make_shared<OBufferStream>(); Interest interest("/localhost/nfd/fib/list"); interest.setChildSelector(1); interest.setMustBeFresh(true); m_face.expressInterest(interest, bind(&NfdStatus::fetchSegments, this, _2, &NfdStatus::afterFetchedFibEnumerationInformation), bind(&NfdStatus::onTimeout, this)); } void afterFetchedFibEnumerationInformation() { ConstBufferPtr buf = m_buffer->buf(); if (m_isOutputXml) { std::cout << "<fib>"; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode FibEntry TLV"; break; } offset += block.size(); nfd::FibEntry fibEntry(block); std::cout << "<fibEntry>"; std::string prefix(fibEntry.getPrefix().toUri()); escapeSpecialCharacters(&prefix); std::cout << "<prefix>" << prefix << "</prefix>"; std::cout << "<nextHops>"; for (std::list<nfd::NextHopRecord>::const_iterator nextHop = fibEntry.getNextHopRecords().begin(); nextHop != fibEntry.getNextHopRecords().end(); ++nextHop) { std::cout << "<nextHop>" ; std::cout << "<faceId>" << nextHop->getFaceId() << "</faceId>"; std::cout << "<cost>" << nextHop->getCost() << "</cost>"; std::cout << "</nextHop>"; } std::cout << "</nextHops>"; std::cout << "</fibEntry>"; } std::cout << "</fib>"; } else { std::cout << "FIB:" << std::endl; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode FibEntry TLV" << std::endl; break; } offset += block.size(); nfd::FibEntry fibEntry(block); std::cout << " " << fibEntry.getPrefix() << " nexthops={"; for (std::list<nfd::NextHopRecord>::const_iterator nextHop = fibEntry.getNextHopRecords().begin(); nextHop != fibEntry.getNextHopRecords().end(); ++nextHop) { if (nextHop != fibEntry.getNextHopRecords().begin()) std::cout << ", "; std::cout << "faceid=" << nextHop->getFaceId() << " (cost=" << nextHop->getCost() << ")"; } std::cout << "}" << std::endl; } } runNextStep(); } ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// void fetchStrategyChoiceInformation() { m_buffer = make_shared<OBufferStream>(); Interest interest("/localhost/nfd/strategy-choice/list"); interest.setChildSelector(1); interest.setMustBeFresh(true); m_face.expressInterest(interest, bind(&NfdStatus::fetchSegments, this, _2, &NfdStatus::afterFetchedStrategyChoiceInformationInformation), bind(&NfdStatus::onTimeout, this)); } void afterFetchedStrategyChoiceInformationInformation() { ConstBufferPtr buf = m_buffer->buf(); if (m_isOutputXml) { std::cout << "<strategyChoices>"; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode StrategyChoice TLV"; break; } offset += block.size(); nfd::StrategyChoice strategyChoice(block); std::cout << "<strategyChoice>"; std::string name(strategyChoice.getName().toUri()); escapeSpecialCharacters(&name); std::cout << "<namespace>" << name << "</namespace>"; std::cout << "<strategy>"; std::string strategy(strategyChoice.getStrategy().toUri()); escapeSpecialCharacters(&strategy); std::cout << "<name>" << strategy << "</name>"; std::cout << "</strategy>"; std::cout << "</strategyChoice>"; } std::cout << "</strategyChoices>"; } else { std::cout << "Strategy choices:" << std::endl; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode StrategyChoice TLV" << std::endl; break; } offset += block.size(); nfd::StrategyChoice strategyChoice(block); std::cout << " " << strategyChoice.getName() << " strategy=" << strategyChoice.getStrategy() << std::endl; } } runNextStep(); } void fetchRibStatusInformation() { m_buffer = make_shared<OBufferStream>(); Interest interest("/localhost/nfd/rib/list"); interest.setChildSelector(1); interest.setMustBeFresh(true); m_face.expressInterest(interest, bind(&NfdStatus::fetchSegments, this, _2, &NfdStatus::afterFetchedRibStatusInformation), bind(&NfdStatus::onTimeout, this)); } void afterFetchedRibStatusInformation() { ConstBufferPtr buf = m_buffer->buf(); if (m_isOutputXml) { std::cout << "<rib>"; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode RibEntry TLV"; break; } offset += block.size(); nfd::RibEntry ribEntry(block); std::cout << "<ribEntry>"; std::string prefix(ribEntry.getName().toUri()); escapeSpecialCharacters(&prefix); std::cout << "<prefix>" << prefix << "</prefix>"; std::cout << "<routes>"; for (std::list<nfd::Route>::const_iterator nextRoute = ribEntry.begin(); nextRoute != ribEntry.end(); ++nextRoute) { std::cout << "<route>" ; std::cout << "<faceId>" << nextRoute->getFaceId() << "</faceId>"; std::cout << "<origin>" << nextRoute->getOrigin() << "</origin>"; std::cout << "<cost>" << nextRoute->getCost() << "</cost>"; std::cout << "<flags>"; if (nextRoute->isChildInherit()) std::cout << "<childInherit/>"; if (nextRoute->isRibCapture()) std::cout << "<ribCapture/>"; std::cout << "</flags>"; if (!nextRoute->hasInfiniteExpirationPeriod()) { std::cout << "<expirationPeriod>PT" << time::duration_cast<time::seconds>(nextRoute->getExpirationPeriod()) .count() << "S" << "</expirationPeriod>"; } std::cout << "</route>"; } std::cout << "</routes>"; std::cout << "</ribEntry>"; } std::cout << "</rib>"; } else { std::cout << "Rib:" << std::endl; Block block; size_t offset = 0; while (offset < buf->size()) { bool ok = Block::fromBuffer(buf, offset, block); if (!ok) { std::cerr << "ERROR: cannot decode RibEntry TLV" << std::endl; break; } offset += block.size(); nfd::RibEntry ribEntry(block); std::cout << " " << ribEntry.getName().toUri() << " route={"; for (std::list<nfd::Route>::const_iterator nextRoute = ribEntry.begin(); nextRoute != ribEntry.end(); ++nextRoute) { if (nextRoute != ribEntry.begin()) std::cout << ", "; std::cout << "faceid=" << nextRoute->getFaceId() << " (origin=" << nextRoute->getOrigin() << " cost=" << nextRoute->getCost(); if (!nextRoute->hasInfiniteExpirationPeriod()) { std::cout << " expires=" << time::duration_cast<time::seconds>(nextRoute->getExpirationPeriod()) .count() << "s"; } if (nextRoute->isChildInherit()) std::cout << " ChildInherit"; if (nextRoute->isRibCapture()) std::cout << " RibCapture"; std::cout << ")"; } std::cout << "}" << std::endl; } } runNextStep(); } void fetchInformation() { if (m_isOutputXml || (!m_needVersionRetrieval && !m_needChannelStatusRetrieval && !m_needFaceStatusRetrieval && !m_needFibEnumerationRetrieval && !m_needRibStatusRetrieval && !m_needStrategyChoiceRetrieval)) { enableVersionRetrieval(); enableChannelStatusRetrieval(); enableFaceStatusRetrieval(); enableFibEnumerationRetrieval(); enableRibStatusRetrieval(); enableStrategyChoiceRetrieval(); } if (m_isOutputXml) m_fetchSteps.push_back(bind(&NfdStatus::printXmlHeader, this)); if (m_needVersionRetrieval) m_fetchSteps.push_back(bind(&NfdStatus::fetchVersionInformation, this)); if (m_needChannelStatusRetrieval) m_fetchSteps.push_back(bind(&NfdStatus::fetchChannelStatusInformation, this)); if (m_needFaceStatusRetrieval) m_fetchSteps.push_back(bind(&NfdStatus::fetchFaceStatusInformation, this)); if (m_needFibEnumerationRetrieval) m_fetchSteps.push_back(bind(&NfdStatus::fetchFibEnumerationInformation, this)); if (m_needRibStatusRetrieval) m_fetchSteps.push_back(bind(&NfdStatus::fetchRibStatusInformation, this)); if (m_needStrategyChoiceRetrieval) m_fetchSteps.push_back(bind(&NfdStatus::fetchStrategyChoiceInformation, this)); if (m_isOutputXml) m_fetchSteps.push_back(bind(&NfdStatus::printXmlFooter, this)); runNextStep(); m_face.processEvents(); } private: void printXmlHeader() { std::cout << "<?xml version=\"1.0\"?>"; std::cout << "<nfdStatus xmlns=\"ndn:/localhost/nfd/status/1\">"; runNextStep(); } void printXmlFooter() { std::cout << "</nfdStatus>"; runNextStep(); } void runNextStep() { if (m_fetchSteps.empty()) return; function<void()> nextStep = m_fetchSteps.front(); m_fetchSteps.pop_front(); nextStep(); } private: std::string m_toolName; bool m_needVersionRetrieval; bool m_needChannelStatusRetrieval; bool m_needFaceStatusRetrieval; bool m_needFibEnumerationRetrieval; bool m_needRibStatusRetrieval; bool m_needStrategyChoiceRetrieval; bool m_isOutputXml; Face m_face; shared_ptr<OBufferStream> m_buffer; std::deque<function<void()> > m_fetchSteps; }; } int main(int argc, char* argv[]) { int option; ndn::NfdStatus nfdStatus(argv[0]); while ((option = getopt(argc, argv, "hvcfbrsxV")) != -1) { switch (option) { case 'h': nfdStatus.usage(); return 0; case 'v': nfdStatus.enableVersionRetrieval(); break; case 'c': nfdStatus.enableChannelStatusRetrieval(); break; case 'f': nfdStatus.enableFaceStatusRetrieval(); break; case 'b': nfdStatus.enableFibEnumerationRetrieval(); break; case 'r': nfdStatus.enableRibStatusRetrieval(); break; case 's': nfdStatus.enableStrategyChoiceRetrieval(); break; case 'x': nfdStatus.enableXmlOutput(); break; case 'V': std::cout << NFD_VERSION_BUILD_STRING << std::endl; return 0; default: nfdStatus.usage(); return 1; } } try { nfdStatus.fetchInformation(); } catch (std::exception& e) { std::cerr << "ERROR: " << e.what() << std::endl; return 2; } return 0; }
dibenede/NFD-NDNcomm2014
tools/nfd-status.cpp
C++
gpl-3.0
29,976
#include "MantidAPI/WorkspaceProperty.h" #include "MantidAPI/WorkspaceFactory.h" #include "MantidAPI/WorkspaceGroup.h" #include "MantidSINQ/PoldiFitPeaks1D.h" #include "MantidDataObjects/Workspace2D.h" #include "MantidDataObjects/TableWorkspace.h" #include "MantidAPI/FunctionFactory.h" #include "MantidKernel/BoundedValidator.h" #include "MantidKernel/ListValidator.h" #include "MantidAPI/TableRow.h" #include "MantidSINQ/PoldiUtilities/UncertainValue.h" #include "MantidSINQ/PoldiUtilities/UncertainValueIO.h" #include "MantidAPI/CompositeFunction.h" namespace Mantid { namespace Poldi { using namespace Kernel; using namespace API; using namespace DataObjects; using namespace CurveFitting; // Register the algorithm into the AlgorithmFactory DECLARE_ALGORITHM(PoldiFitPeaks1D) /// Algorithm's name for identification. @see Algorithm::name const std::string PoldiFitPeaks1D::name() const { return "PoldiFitPeaks1D"; } /// Algorithm's version for identification. @see Algorithm::version int PoldiFitPeaks1D::version() const { return 1; } /// Algorithm's category for identification. @see Algorithm::category const std::string PoldiFitPeaks1D::category() const { return "SINQ\\Poldi"; } void PoldiFitPeaks1D::init() { declareProperty( make_unique<WorkspaceProperty<Workspace2D>>("InputWorkspace", "", Direction::Input), "An input workspace containing a POLDI auto-correlation spectrum."); boost::shared_ptr<BoundedValidator<double>> minFwhmPerDirection = boost::make_shared<BoundedValidator<double>>(); minFwhmPerDirection->setLower(2.0); declareProperty( "FwhmMultiples", 2.0, minFwhmPerDirection, "Each peak will be fitted using x times FWHM data in each direction.", Direction::Input); std::vector<std::string> peakFunctions = FunctionFactory::Instance().getFunctionNames<IPeakFunction>(); auto peakFunctionNames = boost::make_shared<ListValidator<std::string>>(peakFunctions); declareProperty("PeakFunction", "Gaussian", peakFunctionNames, "Peak function that will be fitted to all peaks.", Direction::Input); declareProperty(make_unique<WorkspaceProperty<TableWorkspace>>( "PoldiPeakTable", "", Direction::Input), "A table workspace containing POLDI peak data."); declareProperty(make_unique<WorkspaceProperty<TableWorkspace>>( "OutputWorkspace", "RefinedPeakTable", Direction::Output), "Output workspace with refined peak data."); declareProperty(make_unique<WorkspaceProperty<Workspace>>( "FitPlotsWorkspace", "FitPlots", Direction::Output), "Plots of all peak fits."); m_backgroundTemplate = FunctionFactory::Instance().createInitialized( "name=UserFunction, Formula=A0 + A1*(x - x0)^2"); m_profileTies = "f1.x0 = f0.PeakCentre"; } void PoldiFitPeaks1D::setPeakFunction(const std::string &peakFunction) { m_profileTemplate = peakFunction; } PoldiPeakCollection_sptr PoldiFitPeaks1D::getInitializedPeakCollection( const DataObjects::TableWorkspace_sptr &peakTable) const { auto peakCollection = boost::make_shared<PoldiPeakCollection>(peakTable); peakCollection->setProfileFunctionName(m_profileTemplate); return peakCollection; } IFunction_sptr PoldiFitPeaks1D::getPeakProfile(const PoldiPeak_sptr &poldiPeak) const { IPeakFunction_sptr clonedProfile = boost::dynamic_pointer_cast<IPeakFunction>( FunctionFactory::Instance().createFunction(m_profileTemplate)); clonedProfile->setCentre(poldiPeak->q()); clonedProfile->setFwhm(poldiPeak->fwhm(PoldiPeak::AbsoluteQ)); clonedProfile->setHeight(poldiPeak->intensity()); IFunction_sptr clonedBackground = m_backgroundTemplate->clone(); auto totalProfile = boost::make_shared<CompositeFunction>(); totalProfile->initialize(); totalProfile->addFunction(clonedProfile); totalProfile->addFunction(clonedBackground); if (!m_profileTies.empty()) { totalProfile->addTies(m_profileTies); } return totalProfile; } void PoldiFitPeaks1D::setValuesFromProfileFunction( PoldiPeak_sptr poldiPeak, const IFunction_sptr &fittedFunction) const { CompositeFunction_sptr totalFunction = boost::dynamic_pointer_cast<CompositeFunction>(fittedFunction); if (totalFunction) { IPeakFunction_sptr peakFunction = boost::dynamic_pointer_cast<IPeakFunction>( totalFunction->getFunction(0)); if (peakFunction) { poldiPeak->setIntensity( UncertainValue(peakFunction->height(), peakFunction->getError(0))); poldiPeak->setQ( UncertainValue(peakFunction->centre(), peakFunction->getError(1))); poldiPeak->setFwhm(UncertainValue(peakFunction->fwhm(), getFwhmWidthRelation(peakFunction) * peakFunction->getError(2))); } } } double PoldiFitPeaks1D::getFwhmWidthRelation(IPeakFunction_sptr peakFunction) const { return peakFunction->fwhm() / peakFunction->getParameter(2); } void PoldiFitPeaks1D::exec() { setPeakFunction(getProperty("PeakFunction")); // Number of points around the peak center to use for the fit m_fwhmMultiples = getProperty("FwhmMultiples"); // try to construct PoldiPeakCollection from provided TableWorkspace TableWorkspace_sptr poldiPeakTable = getProperty("PoldiPeakTable"); m_peaks = getInitializedPeakCollection(poldiPeakTable); g_log.information() << "Peaks to fit: " << m_peaks->peakCount() << '\n'; Workspace2D_sptr dataWorkspace = getProperty("InputWorkspace"); auto fitPlotGroup = boost::make_shared<WorkspaceGroup>(); for (size_t i = 0; i < m_peaks->peakCount(); ++i) { PoldiPeak_sptr currentPeak = m_peaks->peak(i); IFunction_sptr currentProfile = getPeakProfile(currentPeak); IAlgorithm_sptr fit = getFitAlgorithm(dataWorkspace, currentPeak, currentProfile); bool fitSuccess = fit->execute(); if (fitSuccess) { setValuesFromProfileFunction(currentPeak, fit->getProperty("Function")); MatrixWorkspace_sptr fpg = fit->getProperty("OutputWorkspace"); fitPlotGroup->addWorkspace(fpg); } } setProperty("OutputWorkspace", m_peaks->asTableWorkspace()); setProperty("FitPlotsWorkspace", fitPlotGroup); } IAlgorithm_sptr PoldiFitPeaks1D::getFitAlgorithm(const Workspace2D_sptr &dataWorkspace, const PoldiPeak_sptr &peak, const IFunction_sptr &profile) { double width = peak->fwhm(); double extent = std::min(0.05, std::max(0.002, width)) * m_fwhmMultiples; std::pair<double, double> xBorders(peak->q() - extent, peak->q() + extent); IAlgorithm_sptr fitAlgorithm = createChildAlgorithm("Fit", -1, -1, false); fitAlgorithm->setProperty("CreateOutput", true); fitAlgorithm->setProperty("Output", "FitPeaks1D"); fitAlgorithm->setProperty("CalcErrors", true); fitAlgorithm->setProperty("Function", profile); fitAlgorithm->setProperty("InputWorkspace", dataWorkspace); fitAlgorithm->setProperty("WorkspaceIndex", 0); fitAlgorithm->setProperty("StartX", xBorders.first); fitAlgorithm->setProperty("EndX", xBorders.second); return fitAlgorithm; } } // namespace Poldi } // namespace Mantid
dymkowsk/mantid
Framework/SINQ/src/PoldiFitPeaks1D.cpp
C++
gpl-3.0
7,337
<?php /* ************************************************************************************************************************** ** CORAL Organizations Module v. 1.0 ** ** Copyright (c) 2010 University of Notre Dame ** ** This file is part of CORAL. ** ** CORAL 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. ** ** CORAL 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 CORAL. If not, see <http://www.gnu.org/licenses/>. ** ************************************************************************************************************************** */ class ExternalLogin extends DatabaseObject { protected function defineRelationships() {} protected function overridePrimaryKeyName() {} } ?>
NathanAhlstrom/CORAL
usage/old/admin/classes/domain/ExternalLogin.php
PHP
gpl-3.0
1,138
using System; using System.Collections.Generic; using System.Linq; using Challenger_Series.Utils; using LeagueSharp; using LeagueSharp.SDK; using SharpDX; using Color = System.Drawing.Color; using Challenger_Series.Utils; using System.Windows.Forms; using LeagueSharp.Data.Enumerations; using LeagueSharp.SDK.Enumerations; using LeagueSharp.SDK.UI; using LeagueSharp.SDK.Utils; using Menu = LeagueSharp.SDK.UI.Menu; using EloBuddy; using LeagueSharp.SDK; namespace Challenger_Series.Plugins { public class Teemo : CSPlugin { public Teemo() { Q = new Spell(SpellSlot.Q, 680); W = new Spell(SpellSlot.W); E = new Spell(SpellSlot.E); R = new Spell(SpellSlot.R, 300); Q.SetTargetted(0.5f, 1500f); R.SetSkillshot(0.5f, 120f, 1000f, false, SkillshotType.SkillshotCircle); InitMenu(); Orbwalker.OnAction += OnAction; DelayedOnUpdate += OnUpdate; Drawing.OnDraw += OnDraw; Obj_AI_Base.OnProcessSpellCast += OnProcessSpellCast; Events.OnGapCloser += OnGapCloser; Events.OnInterruptableTarget += OnInterruptableTarget; } public override void OnUpdate(EventArgs args) { if (Q.IsReady()) this.QLogic(); if (W.IsReady()) this.WLogic(); if (R.IsReady()) this.RLogic(); } private void OnGapCloser(object oSender, Events.GapCloserEventArgs args) { /*var sender = args.Sender; if (UseEAntiGapclose) { if (args.IsDirectedToPlayer && args.Sender.Distance(ObjectManager.Player) < 750) { if (E.IsReady()) { E.Cast(sender.ServerPosition); } } }*/ } private void OnInterruptableTarget(object oSender, Events.InterruptableTargetEventArgs args) { /*var sender = args.Sender; if (!GameObjects.AllyMinions.Any(m => !m.IsDead && m.CharData.BaseSkinName.Contains("trap") && m.Distance(sender.ServerPosition) < 100) && ObjectManager.Player.Distance(sender) < 550) { W.Cast(sender.ServerPosition); }*/ } private void OnProcessSpellCast(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { base.OnProcessSpellCast(sender, args); /*if (sender is AIHeroClient && sender.IsEnemy) { if (args.SData.Name == "summonerflash" && args.End.Distance(ObjectManager.Player.ServerPosition) < 650) { var pred = Prediction.GetPrediction((AIHeroClient)args.Target, E); if (!pred.Item3.Any(o => o.IsMinion && !o.IsDead && !o.IsAlly)) { E.Cast(args.End); } } }*/ } public override void OnDraw(EventArgs args) { var drawRange = DrawRange.Value; if (drawRange > 0) { Render.Circle.DrawCircle(ObjectManager.Player.Position, drawRange, Color.Gold); } } private void OnAction(object sender, OrbwalkingActionArgs orbwalkingActionArgs) { if (orbwalkingActionArgs.Type == OrbwalkingType.BeforeAttack) { /*if (orbwalkingActionArgs.Target is Obj_AI_Minion && HasPassive && FocusOnHeadShotting && Orbwalker.ActiveMode == OrbwalkingMode.LaneClear) { var target = orbwalkingActionArgs.Target as Obj_AI_Minion; if (target != null && !target.CharData.BaseSkinName.Contains("MinionSiege") && target.Health > 60) { var tg = (AIHeroClient)TargetSelector.GetTarget(715, DamageType.Physical); if (tg != null && tg.IsHPBarRendered) { Orbwalker.ForceTarget = tg; orbwalkingActionArgs.Process = false; } } }*/ } if (orbwalkingActionArgs.Type == OrbwalkingType.AfterAttack) { Orbwalker.ForceTarget = null; if (E.IsReady() && this.UseECombo) { if (!OnlyUseEOnMelees) { var eTarget = TargetSelector.GetTarget(UseEOnEnemiesCloserThanSlider.Value, DamageType.Physical); if (eTarget != null) { var pred = Prediction.GetPrediction(eTarget, E); if (pred.Item3.Count == 0 && (int)pred.Item1 >= (int)HitChance.High) { E.Cast(pred.Item2); } } } else { var eTarget = ValidTargets.FirstOrDefault( e => e.IsMelee && e.Distance(ObjectManager.Player) < UseEOnEnemiesCloserThanSlider.Value && !e.IsZombie); var pred = Prediction.GetPrediction(eTarget, E); if (pred.Item3.Count == 0 && (int)pred.Item1 > (int)HitChance.Medium) { E.Cast(pred.Item2); } } } } } private Menu ComboMenu; private MenuBool UseQCombo; private MenuBool UseWChase; private MenuBool UseECombo; private MenuKeyBind UseRCombo; private MenuBool AlwaysQAfterE; private MenuBool FocusOnHeadShotting; private MenuList<string> QHarassMode; private MenuBool UseWInterrupt; private Menu AutoRConfig; private MenuSlider UseEOnEnemiesCloserThanSlider; private MenuBool OnlyUseEOnMelees; private MenuBool UseEAntiGapclose; private MenuSlider DrawRange; public void InitMenu() { ComboMenu = MainMenu.Add(new Menu("teemocombomenu", "Combo Settings: ")); UseQCombo = ComboMenu.Add(new MenuBool("teemoqcombo", "Use Q", true)); UseWChase = ComboMenu.Add(new MenuBool("usewchase", "Use W when chasing")); UseECombo = ComboMenu.Add(new MenuBool("teemorcombo", "Use R", true)); AutoRConfig = MainMenu.Add(new Menu("teemoautor", "R Settings: ")); new Utils.Logic.PositionSaver(AutoRConfig, R); MainMenu.Attach(); } #region Logic void QLogic() { if (Orbwalker.ActiveMode == OrbwalkingMode.Combo) { if (UseQCombo && Q.IsReady() && ObjectManager.Player.CountEnemyHeroesInRange(800) == 0 && ObjectManager.Player.CountEnemyHeroesInRange(1100) > 0) { Q.CastIfWillHit(TargetSelector.GetTarget(900, DamageType.Physical), 2); var goodQTarget = ValidTargets.FirstOrDefault( t => t.Distance(ObjectManager.Player) < 950 && t.Health < Q.GetDamage(t) || SquishyTargets.Contains(t.CharData.BaseSkinName)); if (goodQTarget != null) { var pred = Prediction.GetPrediction(goodQTarget, Q); if ((int)pred.Item1 > (int)HitChance.Medium) { Q.Cast(pred.Item2); } } } } if (Orbwalker.ActiveMode != OrbwalkingMode.None && Orbwalker.ActiveMode != OrbwalkingMode.Combo && ObjectManager.Player.CountEnemyHeroesInRange(850) == 0) { var qHarassMode = QHarassMode.SelectedValue; if (qHarassMode != "DISABLED") { var qTarget = TargetSelector.GetTarget(1100, DamageType.Physical); if (qTarget != null) { var pred = Prediction.GetPrediction(qTarget, Q); if ((int)pred.Item1 > (int)HitChance.Medium) { if (qHarassMode == "ALLOWMINIONS") { Q.Cast(pred.Item2); } else if (pred.Item3.Count == 0) { Q.Cast(pred.Item2); } } } } } } void WLogic() { var goodTarget = ValidTargets.FirstOrDefault( e => !e.IsDead && e.HasBuffOfType(BuffType.Knockup) || e.HasBuffOfType(BuffType.Snare) || e.HasBuffOfType(BuffType.Stun) || e.HasBuffOfType(BuffType.Suppression) || e.IsCharmed || e.IsCastingInterruptableSpell() || !e.CanMove); if (goodTarget != null) { var pos = goodTarget.ServerPosition; if (!GameObjects.AllyMinions.Any(m => !m.IsDead && m.CharData.BaseSkinName.Contains("trap") && m.Distance(goodTarget.ServerPosition) < 100) && pos.Distance(ObjectManager.Player.ServerPosition) < 820) { W.Cast(goodTarget.ServerPosition); } } foreach (var enemyMinion in ObjectManager.Get<Obj_AI_Base>() .Where( m => m.IsEnemy && m.ServerPosition.Distance(ObjectManager.Player.ServerPosition) < W.Range && m.HasBuff("teleport_target"))) { W.Cast(enemyMinion.ServerPosition); } foreach (var hero in GameObjects.EnemyHeroes.Where(h => h.Distance(ObjectManager.Player) < W.Range)) { var pred = Prediction.GetPrediction(hero, W); if (!GameObjects.AllyMinions.Any(m => !m.IsDead && m.CharData.BaseSkinName.Contains("trap") && m.Distance(pred.Item2) < 100) && (int)pred.Item1 > (int)HitChance.Medium) { W.Cast(pred.Item2); } } } void RLogic() { if (UseRCombo.Active && R.IsReady() && ObjectManager.Player.CountEnemyHeroesInRange(900) == 0) { foreach (var rTarget in ValidTargets.Where( e => SquishyTargets.Contains(e.CharData.BaseSkinName) && R.GetDamage(e) > 0.1 * e.MaxHealth || R.GetDamage(e) > e.Health)) { if (rTarget.Distance(ObjectManager.Player) > 1400) { var pred = Prediction.GetPrediction(rTarget, R); if (!pred.Item3.Any(obj => obj is AIHeroClient)) { R.CastOnUnit(rTarget); } break; } R.CastOnUnit(rTarget); } } } #endregion private bool HasPassive => ObjectManager.Player.HasBuff("caitlynheadshot"); private string[] SquishyTargets = { "Ahri", "Anivia", "Annie", "Ashe", "Azir", "Brand", "Caitlyn", "Cassiopeia", "Corki", "Draven", "Ezreal", "Graves", "Jinx", "Kalista", "Karma", "Karthus", "Katarina", "Kennen", "KogMaw", "Kindred", "Leblanc", "Lucian", "Lux", "MissFortune", "Orianna", "Quinn", "Sivir", "Syndra", "Talon", "Teemo", "Tristana", "TwistedFate", "Twitch", "Varus", "Vayne", "Veigar", "Velkoz", "Viktor", "Xerath", "Zed", "Ziggs", "Jhin", "Soraka" }; } }
saophaisau/port
Core/SDK Ports/ChallengerSeriesAIO/Plugins/Teemo.cs
C#
gpl-3.0
12,392
<?php /* Copyright (C) 2017 Alexandre Spangaro <aspangaro@zendsi.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * or see http://www.gnu.org/ */ /** * \file htdocs/compta/bank/various_payment/document.php * \ingroup banque * \brief Page of linked files onto various_payment */ require '../../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php'; $langs->load("other"); $langs->load("bank"); $langs->load("companies"); $id = GETPOST('id','int'); $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action','alpha'); $confirm = GETPOST('confirm','alpha'); // Security check if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'salaries', $id, ''); // Get parameters $sortfield = GETPOST('sortfield','alpha'); $sortorder = GETPOST('sortorder','alpha'); $page = GETPOST('page','int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="name"; $object = new PaymentVarious($db); $object->fetch($id, $ref); $upload_dir = $conf->banque->dir_output.'/'.dol_sanitizeFileName($object->id); $modulepart='banque'; /* * Actions */ include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; /* * View */ $form = new Form($db); llxHeader("",$langs->trans("VariousPayment")); if ($object->id) { $head=various_payment_prepare_head($object); dol_fiche_head($head, 'documents', $langs->trans("VariousPayment"), 0, 'payment'); // Construit liste des fichiers $filearray=dol_dir_list($upload_dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1); $totalsize=0; foreach($filearray as $key => $file) { $totalsize+=$file['size']; } print '<table class="border" width="100%">'; $linkback = '<a href="'.DOL_URL_ROOT.'/compta/bank/various_payment/index.php'.(! empty($socid)?'?socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>'; // Ref print '<tr><td class="titlefield">'.$langs->trans("Ref").'</td><td>'; print $form->showrefnav($object, 'id', $linkback, 1, 'rowid', 'ref', ''); print '</td></tr>'; // Societe //print "<tr><td>".$langs->trans("Company")."</td><td>".$object->client->getNomUrl(1)."</td></tr>"; print '<tr><td>'.$langs->trans("NbOfAttachedFiles").'</td><td colspan="3">'.count($filearray).'</td></tr>'; print '<tr><td>'.$langs->trans("TotalSizeOfAttachedFiles").'</td><td colspan="3">'.$totalsize.' '.$langs->trans("bytes").'</td></tr>'; print '</table>'; print '</div>'; $modulepart = 'banque'; $permission = $user->rights->banque->modifier; $param = '&id=' . $object->id; include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; } else { print $langs->trans("ErrorUnknown"); } llxFooter(); $db->close();
guerrierk/dolibarr
htdocs/compta/bank/various_payment/document.php
PHP
gpl-3.0
3,783
using System; using System.Collections.Generic; using System.Linq; using System.Text; using WiimoteLib; namespace WiiApi { /// <summary> /// Klasa koriscena za prikaz polozaja i orijentacije glave u prostoru. Sadrzi samo metode za dobavljanje informacija. /// </summary> public class PolozajGlave { /// <summary> /// Plozaj glave u milimetrima, vrednost je validna za pracenje 2 i 3 izvora. /// </summary> private Point3F polozaj; /// <summary> /// Vektor koji pokazuje na gore. Odredjuje rotaciju oko z ose. Vrednost je validna samo ako se prate 3 izvora. /// </summary> private Point3F goreVektor; /// <summary> /// Pravac pogleda. Odredjuje rotaciju oko x i y osa. Vrednost je validna samo ako se prate 3 izvora. /// </summary> private Point3F pogledVektor; /// <summary> /// Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja. Ako je vrednost false podaci nisu validni. /// </summary> private bool uspesno; /// <summary> /// Konstruktor koji se koristi za postavljanje vrednosti prilikom pracenja 2 izvora /// </summary> /// <param name="uspesno">Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja.</param> /// <param name="polozaj">Polozaj glave u milimetrima. </param> public PolozajGlave(bool uspesno, Point3F polozaj) { this.uspesno = uspesno; this.polozaj = polozaj; } /// <summary> /// Konstruktor koji se koristi za postavljanje vrednosti prilikom pracenja 3 izvora /// </summary> /// <param name="uspesno">Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja.</param> /// <param name="polozaj">Polozaj glave u milimetrima. </param> /// <param name="goreVektor">Vektor na gore. </param> /// /// <param name="pogledVektor">Pravac pogleda. </param> public PolozajGlave(bool uspesno, Point3F polozaj, Point3F goreVektor, Point3F pogledVektor) { this.uspesno = uspesno; this.polozaj = polozaj; this.goreVektor = goreVektor; this.pogledVektor = pogledVektor; } /// <summary> /// Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja. Ako je vrednost false podaci nisu validni. /// </summary> public bool Uspesno { get { return uspesno; } } /// <summary> /// Plozaj glave u milimetrima, vrednost je validna za pracenje 2 i 3 izvora. /// </summary> public Point3F Polozaj { get { return polozaj; } } /// <summary> /// Vektor koji pokazuje na gore. Odredjuje rotaciju oko z ose. Vrednost je validna samo ako se prate 3 izvora. /// </summary> public Point3F GoreVektor { get { return goreVektor; } } /// <summary> /// Pravac pogleda. Odredjuje rotaciju oko x i y osa. Vrednost je validna samo ako se prate 3 izvora. /// </summary> public Point3F PogledVektor { get { return pogledVektor; } } } }
ljsimin/gimii
WiiApi/WiiApi/PolozajGlave.cs
C#
gpl-3.0
3,610
var UniteSettingsRev = new function(){ var arrControls = {}; var colorPicker; var t=this; this.getSettingsObject = function(formID){ var obj = new Object(); var form = document.getElementById(formID); var name,value,type,flagUpdate; //enabling all form items connected to mx var len = form.elements.length; for(var i=0; i<len; i++){ var element = form.elements[i]; if(element.name == "##NAME##[]") continue; //ignore dummy from multi text name = element.name; value = element.value; type = element.type; if(jQuery(element).hasClass("wp-editor-area")) type = "editor"; //trace(name + " " + type); flagUpdate = true; switch(type){ case "checkbox": value = form.elements[i].checked; break; case "radio": if(form.elements[i].checked == false) flagUpdate = false; break; case "editor": value = tinyMCE.get(name).getContent(); break; case "select-multiple": value = jQuery(element).val(); if(value) value = value.toString(); break; } if(flagUpdate == true && name != undefined){ if(name.indexOf('[]') > -1){ name = name.replace('[]', ''); if(typeof obj[name] !== 'object') obj[name] = []; obj[name][Object.keys(obj[name]).length] = value; }else{ obj[name] = value; } } } return(obj); } this.getsdsformvalue = function(formID){ var obj = new Object(); var form = document.getElementById(formID); var name,value,type,flagUpdate; //enabling all form items connected to mx var len = form.elements.length; for(var i=0; i<len; i++){ var element = form.elements[i]; if(element.name == "##NAME##[]") continue; //ignore dummy from multi text name = element.name; value = element.value; type = element.type; if(jQuery(element).hasClass("wp-editor-area")) type = "editor"; //trace(name + " " + type); flagUpdate = true; switch(type){ case "checkbox": value = form.elements[i].checked; break; case "radio": if(form.elements[i].checked == false) flagUpdate = false; break; case "editor": value = tinyMCE.get(name).getContent(); break; case "select-multiple": value = jQuery(element).val(); if(value) value = value.toString(); break; } if(flagUpdate == true && name != undefined){ if(name.indexOf('[]') > -1){ name = name.replace('[]', ''); if(typeof obj[name] !== 'object') obj[name] = []; obj[name][Object.keys(obj[name]).length] = value; }else{ obj[name] = value; } } } return(obj); } /** * on selects change - impiment the hide/show, enabled/disables functionality */ var onSettingChange = function(){ var controlValue = this.value.toLowerCase(); var controlName = this.name; if(!arrControls[this.name]) return(false); jQuery(arrControls[this.name]).each(function(){ var childInput = document.getElementById(this.name); var childRow = document.getElementById(this.name + "_row"); var value = this.value.toLowerCase(); var isChildRadio = (childInput && childInput.tagName == "SPAN" && jQuery(childInput).hasClass("radio_wrapper")); switch(this.type){ case "enable": case "disable": if(childInput){ //disable if(this.type == "enable" && controlValue != this.value || this.type == "disable" && controlValue == this.value){ childRow.className = "disabled"; if(childInput){ childInput.disabled = true; childInput.style.color = ""; } if(isChildRadio) jQuery(childInput).children("input").prop("disabled","disabled").addClass("disabled"); } else{ //enable childRow.className = ""; if(childInput) childInput.disabled = false; if(isChildRadio) jQuery(childInput).children("input").prop("disabled","").removeClass("disabled"); //color the input again if(jQuery(childInput).hasClass("inputColorPicker")) g_picker.linkTo(childInput); } } break; case "show": if(controlValue == this.value) jQuery(childRow).show(); else jQuery(childRow).hide(); break; case "hide": if(controlValue == this.value) jQuery(childRow).hide(); else jQuery(childRow).show(); break; } }); } /** * combine controls to one object, and init control events. */ var initControls = function(){ //combine controls for(key in g_settingsObj){ var obj = g_settingsObj[key]; for(controlKey in obj.controls){ arrControls[controlKey] = obj.controls[controlKey]; } } //init events jQuery(".settings_wrapper select").change(onSettingChange); jQuery(".settings_wrapper input[type='radio']").change(onSettingChange); } //init color picker var initColorPicker = function(){ var colorPickerWrapper = jQuery('#divColorPicker'); colorPicker = jQuery.farbtastic('#divColorPicker'); jQuery(".inputColorPicker").focus(function(){ colorPicker.linkTo(this); colorPickerWrapper.show(); var input = jQuery(this); var offset = input.offset(); var offsetView = jQuery("#viewWrapper").offset(); colorPickerWrapper.css({ "left":offset.left + input.width()+20-offsetView.left, "top":offset.top - colorPickerWrapper.height() + 100-offsetView.top }); if (jQuery(input.data('linkto'))) { var oldval = jQuery(this).val(); jQuery(this).data('int',setInterval(function() { if(input.val() != oldval){ oldval = input.val(); jQuery('#css_preview').css(input.data('linkto'), oldval); jQuery('input[name="css_'+input.data('linkto')+'"]').val(oldval); } } ,200)); } }).blur(function() { clearInterval(jQuery(this).data('int')); }).click(function(){ return(false); //prevent body click }).change(function(){ colorPicker.linkTo(this); colorPicker.setColor(jQuery(this).val()); }); colorPickerWrapper.click(function(){ return(false); //prevent body click }); jQuery("body").click(function(){ colorPickerWrapper.hide(); }); } /** * close all accordion items */ var closeAllAccordionItems = function(formID){ jQuery("#"+formID+" .unite-postbox .inside").slideUp("fast"); jQuery("#"+formID+" .unite-postbox h3").addClass("box_closed"); } /** * init side settings accordion - started from php */ t.initAccordion = function(formID){ var classClosed = "box_closed"; jQuery("#"+formID+" .unite-postbox h3").click(function(){ var handle = jQuery(this); //open if(handle.hasClass(classClosed)){ closeAllAccordionItems(formID); handle.removeClass(classClosed).siblings(".inside").slideDown("fast"); }else{ //close handle.addClass(classClosed).siblings(".inside").slideUp("fast"); } }); } /** * image search */ var initImageSearch = function(){ jQuery(".button-image-select").click(function(){ var settingID = this.id.replace("_button",""); UniteAdminRev.openAddImageDialog("Choose Image",function(urlImage, imageID){ //update input: jQuery("#"+settingID).val(urlImage); //update preview image: var urlShowImage = UniteAdminRev.getUrlShowImage(imageID,100,70,true); jQuery("#" + settingID + "_button_preview").html('<div style="width:100px;height:70px;background:url(\''+urlShowImage+'\'); background-position:center center; background-size:cover;"></div>'); }); }); jQuery(".button-image-remove").click(function(){ var settingID = this.id.replace("_button_remove",""); jQuery("#"+settingID).val(''); jQuery("#" + settingID + "_button_preview").html(''); }); jQuery(".button-image-select-video").click(function(){ UniteAdminRev.openAddImageDialog("Choose Image",function(urlImage, imageID){ //update input: jQuery("#input_video_preview").val(urlImage); //update preview image: var urlShowImage = UniteAdminRev.getUrlShowImage(imageID,200,150,true); jQuery("#video-thumbnail-preview").attr('src', urlShowImage); }); }); jQuery(".button-image-remove-video").click(function(){ jQuery("#input_video_preview").val(''); if(jQuery('#video_block_vimeo').css('display') != 'none') jQuery("#button_vimeo_search").trigger("click"); if(jQuery('#video_block_youtube').css('display') != 'none') jQuery("#button_youtube_search").trigger("click"); }); } /** * init the settings function, set the tootips on sidebars. */ var init = function(){ //init tipsy jQuery(".list_settings li .setting_text").tipsy({ gravity:"e", delayIn: 70 }); jQuery(".tipsy_enabled_top").tipsy({ gravity:"s", delayIn: 70 }); jQuery(".button-primary").tipsy({ gravity:"s", delayIn: 70 }); //init controls initControls(); initColorPicker(); initImageSearch(); //init checklist jQuery(".settings_wrapper .input_checklist").each(function(){ var select = jQuery(this); var ominWidth = select.data("minwidth"); if (ominWidth==undefined) ominWidth="none" select.dropdownchecklist({ zIndex:1000, minWidth:ominWidth, onItemClick: function(checkbox,selector) { for (var i=0;i<20;i++) if (checkbox.val()=="notselectable"+i) { //console.log(checkbox.val()); checkbox.attr("checked",false); } } }); select.parent().find('input').each(function() { var option = jQuery(this); for (var i=0;i<20;i++) if (option.val()=="notselectable"+i) option.parent().addClass("dropdowntitleoption"); }) }); } //call "constructor" jQuery(document).ready(function(){ init(); }); } // UniteSettings class end
fwahyudi17/ofiskita
system/configa/revslider/js/settings.js
JavaScript
gpl-3.0
9,972
package cloudstack import ( "fmt" "io/ioutil" "regexp" "github.com/hashicorp/packer/packer" "github.com/mitchellh/multistep" "github.com/xanzy/go-cloudstack/cloudstack" ) type stepPrepareConfig struct{} func (s *stepPrepareConfig) Run(state multistep.StateBag) multistep.StepAction { client := state.Get("client").(*cloudstack.CloudStackClient) config := state.Get("config").(*Config) ui := state.Get("ui").(packer.Ui) ui.Say("Preparing config...") var err error var errs *packer.MultiError // First get the project and zone UUID's so we can use them in other calls when needed. if config.Project != "" && !isUUID(config.Project) { config.Project, _, err = client.Project.GetProjectID(config.Project) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"project", config.Project, err}) } } if config.UserDataFile != "" { userdata, err := ioutil.ReadFile(config.UserDataFile) if err != nil { errs = packer.MultiErrorAppend(errs, fmt.Errorf("problem reading user data file: %s", err)) } config.UserData = string(userdata) } if !isUUID(config.Zone) { config.Zone, _, err = client.Zone.GetZoneID(config.Zone) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"zone", config.Zone, err}) } } // Then try to get the remaining UUID's. if config.DiskOffering != "" && !isUUID(config.DiskOffering) { config.DiskOffering, _, err = client.DiskOffering.GetDiskOfferingID(config.DiskOffering) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"disk offering", config.DiskOffering, err}) } } if config.PublicIPAddress != "" && !isUUID(config.PublicIPAddress) { // Save the public IP address before replacing it with it's UUID. config.hostAddress = config.PublicIPAddress p := client.Address.NewListPublicIpAddressesParams() p.SetIpaddress(config.PublicIPAddress) if config.Project != "" { p.SetProjectid(config.Project) } ipAddrs, err := client.Address.ListPublicIpAddresses(p) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"IP address", config.PublicIPAddress, err}) } if err == nil && ipAddrs.Count != 1 { errs = packer.MultiErrorAppend(errs, &retrieveErr{"IP address", config.PublicIPAddress, ipAddrs}) } if err == nil && ipAddrs.Count == 1 { config.PublicIPAddress = ipAddrs.PublicIpAddresses[0].Id } } if !isUUID(config.Network) { config.Network, _, err = client.Network.GetNetworkID(config.Network, cloudstack.WithProject(config.Project)) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"network", config.Network, err}) } } if !isUUID(config.ServiceOffering) { config.ServiceOffering, _, err = client.ServiceOffering.GetServiceOfferingID(config.ServiceOffering) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"service offering", config.ServiceOffering, err}) } } if config.SourceISO != "" { if isUUID(config.SourceISO) { config.instanceSource = config.SourceISO } else { config.instanceSource, _, err = client.ISO.GetIsoID(config.SourceISO, "executable", config.Zone) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"ISO", config.SourceISO, err}) } } } if config.SourceTemplate != "" { if isUUID(config.SourceTemplate) { config.instanceSource = config.SourceTemplate } else { config.instanceSource, _, err = client.Template.GetTemplateID(config.SourceTemplate, "executable", config.Zone) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"template", config.SourceTemplate, err}) } } } if !isUUID(config.TemplateOS) { p := client.GuestOS.NewListOsTypesParams() p.SetDescription(config.TemplateOS) types, err := client.GuestOS.ListOsTypes(p) if err != nil { errs = packer.MultiErrorAppend(errs, &retrieveErr{"OS type", config.TemplateOS, err}) } if err == nil && types.Count != 1 { errs = packer.MultiErrorAppend(errs, &retrieveErr{"OS type", config.TemplateOS, types}) } if err == nil && types.Count == 1 { config.TemplateOS = types.OsTypes[0].Id } } // This is needed because nil is not always nil. When returning *packer.MultiError(nil) // as an error interface, that interface will no longer be equal to nil but it will be // an interface with type *packer.MultiError and value nil which is different then a // nil interface. if errs != nil && len(errs.Errors) > 0 { ui.Error(errs.Error()) return multistep.ActionHalt } ui.Message("Config has been prepared!") return multistep.ActionContinue } func (s *stepPrepareConfig) Cleanup(state multistep.StateBag) { // Nothing to cleanup for this step. } type retrieveErr struct { name string value string result interface{} } func (e *retrieveErr) Error() string { if err, ok := e.result.(error); ok { e.result = err.Error() } return fmt.Sprintf("Error retrieving UUID of %s %s: %v", e.name, e.value, e.result) } var uuidRegex = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) func isUUID(uuid string) bool { return uuidRegex.MatchString(uuid) }
dayglojesus/packer
builder/cloudstack/step_prepare_config.go
GO
mpl-2.0
5,108
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; namespace Hatfield.EnviroData.DataAcquisition.XML { public class XMLDataSourceLocation: IDataSourceLocation { public string _elementName; public string _attributeName; public int _index = 0; public XMLDataSourceLocation(string elementName, string attributeName) { _elementName = elementName; _attributeName = attributeName; } public XMLDataSourceLocation(string elementName, string attributeName, int index) { _elementName = elementName; _attributeName = attributeName; _index = index; } public string AttributeName { get { return _attributeName; } } public string ElementName { get { return _elementName; } } public int Index { get { return _index; } } public override string ToString() { return string.Format("Node: {0}, {1}", _elementName, _attributeName); } } }
HatfieldConsultants/Hatfield.EnviroData.DataAcquisition
Source/Hatfield.EnviroData.DataAcquisition.XML/XMLDataSourceLocation.cs
C#
mpl-2.0
1,295
package cabf_br /* * ZLint Copyright 2021 Regents of the University of Michigan * * 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 ( "github.com/zmap/zcrypto/x509" "github.com/zmap/zlint/v3/lint" "github.com/zmap/zlint/v3/util" ) type subCertAiaMissing struct{} /************************************************************************************************** BRs: 7.1.2.3 authorityInformationAccess With the exception of stapling, which is noted below, this extension MUST be present. It MUST NOT be marked critical, and it MUST contain the HTTP URL of the Issuing CA’s OCSP responder (accessMethod = 1.3.6.1.5.5.7.48.1). It SHOULD also contain the HTTP URL of the Issuing CA’s certificate (accessMethod = 1.3.6.1.5.5.7.48.2). See Section 13.2.1 for details. ***************************************************************************************************/ func init() { lint.RegisterLint(&lint.Lint{ Name: "e_sub_cert_aia_missing", Description: "Subscriber Certificate: authorityInformationAccess MUST be present.", Citation: "BRs: 7.1.2.3", Source: lint.CABFBaselineRequirements, EffectiveDate: util.CABEffectiveDate, Lint: NewSubCertAiaMissing, }) } func NewSubCertAiaMissing() lint.LintInterface { return &subCertAiaMissing{} } func (l *subCertAiaMissing) CheckApplies(c *x509.Certificate) bool { return !util.IsCACert(c) } func (l *subCertAiaMissing) Execute(c *x509.Certificate) *lint.LintResult { if util.IsExtInCert(c, util.AiaOID) { return &lint.LintResult{Status: lint.Pass} } else { return &lint.LintResult{Status: lint.Error} } }
jcjones/boulder
vendor/github.com/zmap/zlint/v3/lints/cabf_br/lint_sub_cert_aia_missing.go
GO
mpl-2.0
2,127
/** * This file is part of mycollab-mobile. * * mycollab-mobile 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. * * mycollab-mobile 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 mycollab-mobile. If not, see <http://www.gnu.org/licenses/>. */ package com.esofthead.mycollab.mobile.module.project.view; import com.esofthead.mycollab.mobile.mvp.AbstractPresenter; import com.esofthead.mycollab.vaadin.mvp.ScreenData; import com.vaadin.addon.touchkit.ui.NavigationManager; import com.vaadin.ui.ComponentContainer; /** * @author MyCollab Ltd. * * @since 4.4.0 * */ public class ProjectLoginPresenter extends AbstractPresenter<ProjectLoginView> { private static final long serialVersionUID = -750325026975907368L; public ProjectLoginPresenter() { super(ProjectLoginView.class); } @Override protected void onGo(ComponentContainer navigationManager, ScreenData<?> data) { ((NavigationManager) navigationManager).navigateTo(view.getWidget()); } }
maduhu/mycollab
mycollab-mobile/src/main/java/com/esofthead/mycollab/mobile/module/project/view/ProjectLoginPresenter.java
Java
agpl-3.0
1,424
using System; namespace ACE.Server.Network.GameAction.Actions { public static class GameActionUseItem { [GameAction(GameActionType.Use)] public static void Handle(ClientMessage message, Session session) { uint itemGuid = message.Payload.ReadUInt32(); //Console.WriteLine($"{session.Player.Name}.GameAction 0x36 - Use({itemGuid:X8})"); session.Player.HandleActionUseItem(itemGuid); } } }
LtRipley36706/ACE
Source/ACE.Server/Network/GameAction/Actions/GameActionUseItem.cs
C#
agpl-3.0
470
<?php /** * class.reportTables.php * * @package workflow.engine.ProcessMaker * * ProcessMaker Open Source Edition * Copyright (C) 2004 - 2011 Colosa Inc. * * This program 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. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * For more information, contact Colosa Inc, 2566 Le Jeune Rd., * Coral Gables, FL, 33134, USA, or email info@colosa.com. * */ G::LoadClass( 'case' ); /** * ReportTables - Report tables class * * @package workflow.engine.ProcessMaker * @author Julio Cesar Laura Avenda�o * @copyright 2007 COLOSA */ class ReportTables { private $aDef = array ('mysql' => array ('number' => 'DOUBLE','char' => 'VARCHAR(255)','text' => 'TEXT','date' => 'DATETIME' ),'pgsql' => array ('number' => 'DOUBLE','char' => 'VARCHAR(255)','text' => 'TEXT','date' => 'DATETIME' ),'mssql' => array ('number' => 'FLOAT','char' => 'NVARCHAR(255)','text' => 'TEXT','date' => 'CHAR(19)' ) /* Changed DATETIME CHAR(19) for compatibility issues. */ ); //private $sPrefix = 'REP_'; private $sPrefix = ''; /** * Function deleteAllReportVars * This function delete all reports * * @access public * @param string $$sRepTabUid * @return void */ public function deleteAllReportVars ($sRepTabUid = '') { try { $oCriteria = new Criteria( 'workflow' ); $oCriteria->add( ReportVarPeer::REP_TAB_UID, $sRepTabUid ); ReportVarPeer::doDelete( $oCriteria ); } catch (Exception $oError) { throw ($oError); } } /** * Function prepareQuery * This function removes the table * * @access public * @param string $sTableName Table name * @param string $sConnection Conexion * @return void */ public function dropTable ($sTableName, $sConnection = 'report') { $sTableName = $this->sPrefix . $sTableName; //we have to do the propel connection $PropelDatabase = $this->chooseDB( $sConnection ); $con = Propel::getConnection( $PropelDatabase ); $stmt = $con->createStatement(); try { switch (DB_ADAPTER) { case 'mysql': $rs = $stmt->executeQuery( 'DROP TABLE IF EXISTS `' . $sTableName . '`' ); break; case 'mssql': $rs = $stmt->executeQuery( "IF OBJECT_ID (N'" . $sTableName . "', N'U') IS NOT NULL DROP TABLE [" . $sTableName . "]" ); break; } } catch (Exception $oError) { throw ($oError); } } /** * Function createTable * This Function creates the table * * @access public * @param string $sTableName Table name * @param string $sConnection Connection name * @param string $sType * @param array $aFields * @param string $bDefaultFields * @return void */ public function createTable ($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $bDefaultFields = true) { $sTableName = $this->sPrefix . $sTableName; //we have to do the propel connection $PropelDatabase = $this->chooseDB( $sConnection ); $con = Propel::getConnection( $PropelDatabase ); $stmt = $con->createStatement(); try { switch (DB_ADAPTER) { case 'mysql': $sQuery = 'CREATE TABLE IF NOT EXISTS `' . $sTableName . '` ('; if ($bDefaultFields) { $sQuery .= "`APP_UID` VARCHAR(32) NOT NULL DEFAULT '',`APP_NUMBER` INT NOT NULL,"; if ($sType == 'GRID') { $sQuery .= "`ROW` INT NOT NULL,"; } } foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NOT NULL DEFAULT '0',"; break; case 'char': $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NOT NULL DEFAULT '',"; break; case 'text': $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " ,"; break; case 'date': $sQuery .= '`' . $aField['sFieldName'] . '` ' . $this->aDef['mysql'][$aField['sType']] . " NULL,"; break; } } if ($bDefaultFields) { $sQuery .= 'PRIMARY KEY (APP_UID' . ($sType == 'GRID' ? ',ROW' : '') . ')) '; } $sQuery .= ' DEFAULT CHARSET=utf8;'; $rs = $stmt->executeQuery( $sQuery ); break; case 'mssql': $sQuery = 'CREATE TABLE [' . $sTableName . '] ('; if ($bDefaultFields) { $sQuery .= "[APP_UID] VARCHAR(32) NOT NULL DEFAULT '', [APP_NUMBER] INT NOT NULL,"; if ($sType == 'GRID') { $sQuery .= "[ROW] INT NOT NULL,"; } } foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NOT NULL DEFAULT '0',"; break; case 'char': $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NOT NULL DEFAULT '',"; break; case 'text': $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NOT NULL DEFAULT '',"; break; case 'date': $sQuery .= '[' . $aField['sFieldName'] . '] ' . $this->aDef['mssql'][$aField['sType']] . " NULL,"; break; } } if ($bDefaultFields) { $sQuery .= 'PRIMARY KEY (APP_UID' . ($sType == 'GRID' ? ',ROW' : '') . ')) '; } else { $sQuery .= ' '; } $rs = $stmt->executeQuery( $sQuery ); break; } } catch (Exception $oError) { throw ($oError); } } /** * Function populateTable * This Function fills the table * * @access public * @param string $sTableName Table name * @param string $sConnection Connection name * @param string $sType * @param array $aFields * @param string $sProcessUid * @param string $sGrid * @return void */ public function populateTable ($sTableName, $sConnection = 'report', $sType = 'NORMAL', $aFields = array(), $sProcessUid = '', $sGrid = '') { $sTableName = $this->sPrefix . $sTableName; //we have to do the propel connection $PropelDatabase = $this->chooseDB( $sConnection ); $con = Propel::getConnection( $PropelDatabase ); $stmt = $con->createStatement(); if ($sType == 'GRID') { $aAux = explode( '-', $sGrid ); $sGrid = $aAux[0]; } try { switch (DB_ADAPTER) { case 'mysql': //select cases for this Process, ordered by APP_NUMBER $oCriteria = new Criteria( 'workflow' ); $oCriteria->add( ApplicationPeer::PRO_UID, $sProcessUid ); $oCriteria->addAscendingOrderByColumn( ApplicationPeer::APP_NUMBER ); $oDataset = ApplicationPeer::doSelectRS( $oCriteria ); $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); while ($aRow = $oDataset->getRow()) { $aData = unserialize( $aRow['APP_DATA'] ); //delete previous record from this report table ( previous records in case this is a grid ) $deleteSql = 'DELETE FROM `' . $sTableName . "` WHERE APP_UID = '" . $aRow['APP_UID'] . "'"; $rsDel = $stmt->executeQuery( $deleteSql ); if ($sType == 'NORMAL') { $sQuery = 'INSERT INTO `' . $sTableName . '` ('; $sQuery .= '`APP_UID`,`APP_NUMBER`'; foreach ($aFields as $aField) { $sQuery .= ',`' . $aField['sFieldName'] . '`'; } $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER']; foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aData[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aData[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aData[$aField['sFieldName']] )) { $aData[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aData[$aField['sFieldName']] ) ? @mysql_real_escape_string( $aData[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $value = (isset( $aData[$aField['sFieldName']] ) && trim( $aData[$aField['sFieldName']] )) != '' ? "'" . $aData[$aField['sFieldName']] . "'" : 'NULL'; $sQuery .= "," . $value; break; } } $sQuery .= ')'; $rs = $stmt->executeQuery( $sQuery ); } else { if (isset( $aData[$sGrid] )) { foreach ($aData[$sGrid] as $iRow => $aGridRow) { $sQuery = 'INSERT INTO `' . $sTableName . '` ('; $sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`'; foreach ($aFields as $aField) { $sQuery .= ',`' . $aField['sFieldName'] . '`'; } $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER'] . ',' . $iRow; foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aGridRow[$aField['sFieldName']] )) { $aGridRow[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $value = (isset( $aGridRow[$aField['sFieldName']] ) && trim( $aGridRow[$aField['sFieldName']] )) != '' ? "'" . $aGridRow[$aField['sFieldName']] . "'" : 'NULL'; $sQuery .= "," . $value; break; } } $sQuery .= ')'; $rs = $stmt->executeQuery( $sQuery ); } } } $oDataset->next(); } break; /** * For SQLServer code */ case 'mssql': $oCriteria = new Criteria( 'workflow' ); $oCriteria->add( ApplicationPeer::PRO_UID, $sProcessUid ); $oCriteria->addAscendingOrderByColumn( ApplicationPeer::APP_NUMBER ); $oDataset = ApplicationPeer::doSelectRS( $oCriteria ); $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); while ($aRow = $oDataset->getRow()) { $aData = unserialize( $aRow['APP_DATA'] ); mysql_query( 'DELETE FROM [' . $sTableName . "] WHERE APP_UID = '" . $aRow['APP_UID'] . "'" ); if ($sType == 'NORMAL') { $sQuery = 'INSERT INTO [' . $sTableName . '] ('; $sQuery .= '[APP_UID],[APP_NUMBER]'; foreach ($aFields as $aField) { $sQuery .= ',[' . $aField['sFieldName'] . ']'; } $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER']; foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aData[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aData[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aData[$aField['sFieldName']] )) { $aData[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aData[$aField['sFieldName']] ) ? mysql_real_escape_string( $aData[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $sQuery .= ",'" . (isset( $aData[$aField['sFieldName']] ) ? $aData[$aField['sFieldName']] : '') . "'"; break; } } $sQuery .= ')'; $rs = $stmt->executeQuery( $sQuery ); } else { if (isset( $aData[$sGrid] )) { foreach ($aData[$sGrid] as $iRow => $aGridRow) { $sQuery = 'INSERT INTO [' . $sTableName . '] ('; $sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`'; foreach ($aFields as $aField) { $sQuery .= ',[' . $aField['sFieldName'] . ']'; } $sQuery .= ") VALUES ('" . $aRow['APP_UID'] . "'," . (int) $aRow['APP_NUMBER'] . ',' . $iRow; foreach ($aFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aGridRow[$aField['sFieldName']] )) { $aGridRow[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? $aGridRow[$aField['sFieldName']] : '') . "'"; break; } } $sQuery .= ')'; $rs = $stmt->executeQuery( $sQuery ); } } } $oDataset->next(); } break; } } catch (Exception $oError) { throw ($oError); } } /** * Function getTableVars * * @access public * @param string $sRepTabUid * @param boolean $bWhitType * @return void */ public function getTableVars ($sRepTabUid, $bWhitType = false) { try { $oCriteria = new Criteria( 'workflow' ); $oCriteria->add( ReportVarPeer::REP_TAB_UID, $sRepTabUid ); $oDataset = ReportVarPeer::doSelectRS( $oCriteria ); $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); $aVars = array (); $aImportedVars = array (); //This array will help to control if the variable already exist while ($aRow = $oDataset->getRow()) { if ($bWhitType) { if (! in_array( $aRow['REP_VAR_NAME'], $aImportedVars )) { $aImportedVars[] = $aRow['REP_VAR_NAME']; $aVars[] = array ('sFieldName' => $aRow['REP_VAR_NAME'],'sType' => $aRow['REP_VAR_TYPE'] ); } } else { $aVars[] = $aRow['REP_VAR_NAME']; } $oDataset->next(); } return $aVars; } catch (Exception $oError) { throw ($oError); } } /** * Function deleteReportTable * This Function deletes report table * * @access public * @param string $sRepTabUid * @return void */ public function deleteReportTable ($sRepTabUid) { try { $oReportTable = new ReportTable(); $aFields = $oReportTable->load( $sRepTabUid ); if (! (empty( $aFields ))) { $this->dropTable( $aFields['REP_TAB_NAME'], $aFields['REP_TAB_CONNECTION'] ); $oCriteria = new Criteria( 'workflow' ); $oCriteria->add( ReportVarPeer::REP_TAB_UID, $sRepTabUid ); $oDataset = ReportVarPeer::doDelete( $oCriteria ); $oReportTable->remove( $sRepTabUid ); } } catch (Exception $oError) { throw ($oError); } } /** * Function getSplitDate * This function gets the split date * * @access public * @param date $date * @param string $mask * @return array */ public function getSplitDate ($date, $mask) { $sw1 = false; for ($i = 0; $i < 3; $i ++) { $item = substr( $mask, $i * 2, 1 ); switch ($item) { case 'Y': switch ($i) { case 0: $d1 = substr( $date, 0, 4 ); break; case 1: $d1 = substr( $date, 3, 4 ); break; case 2: $d1 = substr( $date, 6, 4 ); break; } $sw1 = true; break; case 'y': switch ($i) { case 0: $d1 = substr( $date, 0, 2 ); break; case 1: $d1 = substr( $date, 3, 2 ); break; case 2: $d1 = substr( $date, 6, 2 ); break; } break; case 'm': switch ($i) { case 0: $d2 = substr( $date, 0, 2 ); break; case 1: $d2 = ($sw1) ? substr( $date, 5, 2 ) : substr( $date, 3, 2 ); break; case 2: $d2 = ($sw1) ? substr( $date, 8, 2 ) : substr( $date, 5, 2 ); break; } break; case 'd': switch ($i) { case 0: $d3 = substr( $date, 0, 2 ); break; case 1: $d3 = ($sw1) ? substr( $date, 5, 2 ) : substr( $date, 3, 2 ); break; case 2: $d3 = ($sw1) ? substr( $date, 8, 2 ) : substr( $date, 5, 2 ); break; } break; } } return Array (isset( $d1 ) ? $d1 : '',isset( $d2 ) ? $d2 : '',isset( $d3 ) ? $d3 : '' ); } /** * Function getFormatDate * This function returns the date formated * * @access public * @param date $sDate * @param date $sMask * @return date */ public function getFormatDate ($sDate, $sMask) { //print $sDate." *** ". $sMask."<BR>"; $dateTime = explode( " ", $sDate ); //To accept the Hour part $aDate = explode( '-', str_replace( "/", "-", $dateTime[0] ) ); $bResult = true; foreach ($aDate as $sDate) { if (! is_numeric( $sDate )) { $bResult = false; break; } } if ($sMask != '') { $aDate = $this->getSplitDate( $dateTime[0], $sMask ); $aDate[0] = ($aDate[0] == '') ? date( 'Y' ) : $aDate[0]; $aDate[1] = ($aDate[1] == '') ? date( 'm' ) : $aDate[1]; $aDate[2] = ($aDate[2] == '') ? date( 'd' ) : $aDate[2]; if (checkdate( $aDate[1], $aDate[2], $aDate[0] )) { } else { return false; } } $sDateC = ''; for ($i = 0; $i < count( $aDate ); $i ++) { $sDateC .= (($i == 0) ? "" : "-") . $aDate[$i]; } return ($sDateC); } /** * Function updateTables * This function updated the Report Tables * * @access public * @param string $sProcessUid * @param string $sApplicationUid * @param string $iApplicationNumber * @param string $aFields * @return void */ public function updateTables ($sProcessUid, $sApplicationUid, $iApplicationNumber, $aFields) { try { $c = new Criteria('workflow'); $c->addSelectColumn(BpmnProjectPeer::PRJ_UID); $c->add(BpmnProjectPeer::PRJ_UID, $sProcessUid, Criteria::EQUAL); $ds = ProcessPeer::doSelectRS($c); $ds->setFetchmode(ResultSet::FETCHMODE_ASSOC); $ds->next(); $row = $ds->getRow(); $isBpmn = isset($row['PRJ_UID']); if (!class_exists('ReportTablePeer')) { require_once 'classes/model/ReportTablePeer.php'; } //get all Active Report Tables $oCriteria = new Criteria( 'workflow' ); $oCriteria->add( ReportTablePeer::PRO_UID, $sProcessUid ); $oCriteria->add( ReportTablePeer::REP_TAB_STATUS, 'ACTIVE' ); $oDataset = ReportTablePeer::doSelectRS( $oCriteria ); $oDataset->setFetchmode( ResultSet::FETCHMODE_ASSOC ); $oDataset->next(); $aVars = array (); while ($aRow = $oDataset->getRow()) { $aRow['REP_TAB_NAME'] = $this->sPrefix . $aRow['REP_TAB_NAME']; $PropelDatabase = $this->chooseDB( $aRow['REP_TAB_CONNECTION'] ); $con = Propel::getConnection( $PropelDatabase ); $stmt = $con->createStatement(); switch (DB_ADAPTER) { case 'mysql': $aTableFields = $this->getTableVars( $aRow['REP_TAB_UID'], true ); if ($aRow['REP_TAB_TYPE'] == 'NORMAL') { $sqlExists = "SELECT * FROM `" . $aRow['REP_TAB_NAME'] . "` WHERE APP_UID = '" . $sApplicationUid . "'"; $rsExists = $stmt->executeQuery( $sqlExists, ResultSet::FETCHMODE_ASSOC ); $rsExists->next(); $aRow2 = $rsExists->getRow(); if (is_array( $aRow2 )) { $sQuery = 'UPDATE `' . $aRow['REP_TAB_NAME'] . '` SET '; foreach ($aTableFields as $aField) { $sQuery .= '`' . $aField['sFieldName'] . '` = '; if(!$isBpmn && !isset($aFields[$aField['sFieldName']])){ foreach($aFields as $row){ if(is_array($row) && isset($row[count($row)])){ $aFields = $row[count($row)]; } } } switch ($aField['sType']) { case 'number': $sQuery .= (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0') . ','; break; case 'char': case 'text': if (! isset( $aFields[$aField['sFieldName']] )) { $aFields[$aField['sFieldName']] = ''; } if (! isset( $aFields[$aField['sFieldName'] . '_label'] )) { $aFields[$aField['sFieldName'] . '_label'] = ''; } if(is_array($aFields[$aField['sFieldName']])){ $sQuery .= "'" . (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']][0] : '') . "',"; }else{ $sQuery .= '\'' . ((isset($aFields[$aField['sFieldName']]))? @mysql_real_escape_string($aFields[$aField['sFieldName']]) : '') . '\','; } break; case 'date': $mysqlDate = (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : ''); if ($mysqlDate != '') { $mysqlDate = str_replace( '/', '-', $mysqlDate ); $mysqlDate = date( 'Y-m-d', strtotime( $mysqlDate ) ); } $value = trim( $mysqlDate ) != '' ? "'" . $mysqlDate . "'" : 'NULL'; $sQuery .= $value . ","; break; } } $sQuery = substr( $sQuery, 0, - 1 ); $sQuery .= " WHERE APP_UID = '" . $sApplicationUid . "'"; } else { $sQuery = 'INSERT INTO `' . $aRow['REP_TAB_NAME'] . '` ('; $sQuery .= '`APP_UID`,`APP_NUMBER`'; foreach ($aTableFields as $aField) { $sQuery .= ',`' . $aField['sFieldName'] . '`'; } $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber; foreach ($aTableFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aFields[$aField['sFieldName']] )) { $aFields[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $mysqlDate = (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : ''); if ($mysqlDate != '') { $mysqlDate = str_replace( '/', '-', $mysqlDate ); $mysqlDate = date( 'Y-m-d', strtotime( $mysqlDate ) ); } $value = trim( $mysqlDate ) != '' ? "'" . $mysqlDate . "'" : 'NULL'; $sQuery .= "," . $value; break; } } $sQuery .= ')'; } $rs = $stmt->executeQuery( $sQuery ); } else { //remove old rows from database $sqlDelete = 'DELETE FROM `' . $aRow['REP_TAB_NAME'] . "` WHERE APP_UID = '" . $sApplicationUid . "'"; $rsDelete = $stmt->executeQuery( $sqlDelete ); $aAux = explode( '-', $aRow['REP_TAB_GRID'] ); if (isset( $aFields[$aAux[0]] )) { if (is_array($aFields[$aAux[0]])) { foreach ($aFields[$aAux[0]] as $iRow => $aGridRow) { $sQuery = 'INSERT INTO `' . $aRow['REP_TAB_NAME'] . '` ('; $sQuery .= '`APP_UID`,`APP_NUMBER`,`ROW`'; foreach ($aTableFields as $aField) { $sQuery .= ',`' . $aField['sFieldName'] . '`'; } $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber . ',' . $iRow; foreach ($aTableFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aGridRow[$aField['sFieldName']] )) { $aGridRow[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? $aGridRow[$aField['sFieldName']] : '') . "'"; break; } } $sQuery .= ')'; $rs = $stmt->executeQuery( $sQuery ); } } } } break; /** * For SQLServer code */ case 'mssql': $aTableFields = $this->getTableVars( $aRow['REP_TAB_UID'], true ); if ($aRow['REP_TAB_TYPE'] == 'NORMAL') { $oDataset2 = mssql_query( "SELECT * FROM [" . $aRow['REP_TAB_NAME'] . "] WHERE APP_UID = '" . $sApplicationUid . "'" ); if ($aRow2 = mssql_fetch_row( $oDataset2 )) { $sQuery = 'UPDATE [' . $aRow['REP_TAB_NAME'] . '] SET '; foreach ($aTableFields as $aField) { $sQuery .= '[' . $aField['sFieldName'] . '] = '; switch ($aField['sType']) { case 'number': $sQuery .= (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0') . ','; break; case 'char': case 'text': if (! isset( $aFields[$aField['sFieldName']] )) { $aFields[$aField['sFieldName']] = ''; } $sQuery .= "'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "',"; break; case 'date': $sQuery .= "'" . (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : '') . "',"; break; } } $sQuery = substr( $sQuery, 0, - 1 ); $sQuery .= " WHERE APP_UID = '" . $sApplicationUid . "'"; } else { $sQuery = 'INSERT INTO [' . $aRow['REP_TAB_NAME'] . '] ('; $sQuery .= '[APP_UID],[APP_NUMBER]'; foreach ($aTableFields as $aField) { $sQuery .= ',[' . $aField['sFieldName'] . ']'; } $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber; foreach ($aTableFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aFields[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aFields[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aFields[$aField['sFieldName']] )) { $aFields[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aFields[$aField['sFieldName']] ) ? mysql_real_escape_string( $aFields[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $sQuery .= ",'" . (isset( $aFields[$aField['sFieldName']] ) ? $aFields[$aField['sFieldName']] : '') . "'"; break; } } $sQuery .= ')'; } $rs = $stmt->executeQuery( $sQuery ); } else { mysql_query( 'DELETE FROM [' . $aRow['REP_TAB_NAME'] . "] WHERE APP_UID = '" . $sApplicationUid . "'" ); $aAux = explode( '-', $aRow['REP_TAB_GRID'] ); if (isset( $aFields[$aAux[0]] )) { foreach ($aFields[$aAux[0]] as $iRow => $aGridRow) { $sQuery = 'INSERT INTO [' . $aRow['REP_TAB_NAME'] . '] ('; $sQuery .= '[APP_UID],[APP_NUMBER],[ROW]'; foreach ($aTableFields as $aField) { $sQuery .= ',[' . $aField['sFieldName'] . ']'; } $sQuery .= ") VALUES ('" . $sApplicationUid . "'," . (int) $iApplicationNumber . ',' . $iRow; foreach ($aTableFields as $aField) { switch ($aField['sType']) { case 'number': $sQuery .= ',' . (isset( $aGridRow[$aField['sFieldName']] ) ? (float) str_replace( ',', '', $aGridRow[$aField['sFieldName']] ) : '0'); break; case 'char': case 'text': if (! isset( $aGridRow[$aField['sFieldName']] )) { $aGridRow[$aField['sFieldName']] = ''; } $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? mysql_real_escape_string( $aGridRow[$aField['sFieldName']] ) : '') . "'"; break; case 'date': $sQuery .= ",'" . (isset( $aGridRow[$aField['sFieldName']] ) ? $aGridRow[$aField['sFieldName']] : '') . "'"; break; } } $sQuery .= ')'; $rs = $stmt->executeQuery( $sQuery ); } } } break; } $oDataset->next(); } } catch (Exception $oError) { throw ($oError); } } /** * Function tableExist * Check if table exists * * @access public * @return boolean */ public function tableExist () { /* $bExists = true; $oConnection = mysql_connect(DB_HOST, DB_USER, DB_PASS); mysql_select_db(DB_NAME); $oDataset = mysql_query('SELECT COUNT(*) FROM REPORT_TABLE') || ($bExists = false); return $bExists; */ $bExists = true; $sDataBase = 'database_' . strtolower( DB_ADAPTER ); if (G::LoadSystemExist( $sDataBase )) { G::LoadSystem( $sDataBase ); $oDataBase = new database(); $bExists = $oDataBase->reportTableExist(); } return $bExists; } /** * Function chooseDB * Choose the database to connect * * @access public * @param string $TabConnectionk * @return string */ public function chooseDB ($TabConnectionk) { $repTabConnection = trim( strtoupper( $TabConnectionk ) ); $PropelDatabase = 'rp'; if ($repTabConnection == '' || $repTabConnection == 'REPORT') { $PropelDatabase = 'rp'; } if ($repTabConnection == 'RBAC') { $PropelDatabase = 'rbac'; } if ($repTabConnection == 'WF') { $PropelDatabase = 'workflow'; } return ($PropelDatabase); } }
BathnesDevelopment/processmaker-3.1.2.b2-community
workflow/engine/classes/class.reportTables.php
PHP
agpl-3.0
43,778
<?php namespace League\OAuth2\Client\Provider; use League\OAuth2\Client\Exception\HostedDomainException; use League\OAuth2\Client\Provider\Exception\IdentityProviderException; use League\OAuth2\Client\Token\AccessToken; use League\OAuth2\Client\Tool\BearerAuthorizationTrait; use Psr\Http\Message\ResponseInterface; class Google extends AbstractProvider { use BearerAuthorizationTrait; /** * @var string If set, this will be sent to google as the "access_type" parameter. * @link https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters */ protected $accessType; /** * @var string If set, this will be sent to google as the "hd" parameter. * @link https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters */ protected $hostedDomain; /** * @var string If set, this will be sent to google as the "prompt" parameter. * @link https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters */ protected $prompt; /** * @var array List of scopes that will be used for authentication. * @link https://developers.google.com/identity/protocols/googlescopes */ protected $scopes = []; public function getBaseAuthorizationUrl() { return 'https://accounts.google.com/o/oauth2/v2/auth'; } public function getBaseAccessTokenUrl(array $params) { return 'https://oauth2.googleapis.com/token'; } public function getResourceOwnerDetailsUrl(AccessToken $token) { return 'https://openidconnect.googleapis.com/v1/userinfo'; } protected function getAuthorizationParameters(array $options) { if (empty($options['hd']) && $this->hostedDomain) { $options['hd'] = $this->hostedDomain; } if (empty($options['access_type']) && $this->accessType) { $options['access_type'] = $this->accessType; } if (empty($options['prompt']) && $this->prompt) { $options['prompt'] = $this->prompt; } // Default scopes MUST be included for OpenID Connect. // Additional scopes MAY be added by constructor or option. $scopes = array_merge($this->getDefaultScopes(), $this->scopes); if (!empty($options['scope'])) { $scopes = array_merge($scopes, $options['scope']); } $options['scope'] = array_unique($scopes); $options = parent::getAuthorizationParameters($options); // The "approval_prompt" MUST be removed as it is not supported by Google, use "prompt" instead: // https://developers.google.com/identity/protocols/oauth2/openid-connect#prompt unset($options['approval_prompt']); return $options; } protected function getDefaultScopes() { // "openid" MUST be the first scope in the list. return [ 'openid', 'email', 'profile', ]; } protected function getScopeSeparator() { return ' '; } protected function checkResponse(ResponseInterface $response, $data) { // @codeCoverageIgnoreStart if (empty($data['error'])) { return; } // @codeCoverageIgnoreEnd $code = 0; $error = $data['error']; if (is_array($error)) { $code = $error['code']; $error = $error['message']; } throw new IdentityProviderException($error, $code, $data); } protected function createResourceOwner(array $response, AccessToken $token) { $user = new GoogleUser($response); $this->assertMatchingDomain($user->getHostedDomain()); return $user; } /** * @throws HostedDomainException If the domain does not match the configured domain. */ protected function assertMatchingDomain($hostedDomain) { if ($this->hostedDomain === null) { // No hosted domain configured. return; } if ($this->hostedDomain === '*' && $hostedDomain) { // Any hosted domain is allowed. return; } if ($this->hostedDomain === $hostedDomain) { // Hosted domain is correct. return; } throw HostedDomainException::notMatchingDomain($this->hostedDomain); } }
colosa/processmaker
vendor/league/oauth2-google/src/Provider/Google.php
PHP
agpl-3.0
4,424
define([ 'database', 'backbone' ], function (DB, Backbone) { var MessageModel = Backbone.Model.extend({ defaults: { messageId: 0, sender: '', title: '', content: '', hasAttachment: false, sendDate: new Date(), url: '' }, save: function (attributes) { var deferred = $.Deferred(); var self = this; var transaction = DB.conx.transaction([ DB.TABLE_MESSAGE ], 'readwrite'); var store = transaction.objectStore(DB.TABLE_MESSAGE); var request; if (!attributes) { request = store.add(this.toJSON()); } else { self.set(attributes); request = store.put(this.toJSON(), this.cid); } request.onsuccess = function (e) { if (!attributes) { self.cid = e.target.result; } deferred.resolve(); }; request.onerror = function () { deferred.reject(); }; return deferred.promise(); }, getData: function (cid) { var self = this; var deferred = $.Deferred(); var transaction = DB.conx.transaction([ DB.TABLE_MESSAGE ]); var store = transaction.objectStore(DB.TABLE_MESSAGE); var request = store.get(cid); request.onsuccess = function (e) { if (request.result) { var data = request.result; self.cid = cid; self.set(data); deferred.resolve(); } else { deferred.reject(); } }; request.onerror = function () { deferred.reject(); }; return deferred.promise(); }, getNext: function (currentKey) { var deferred = $.Deferred(); var range = IDBKeyRange.lowerBound(this.get('messageId'), true); var transaction = DB.conx.transaction([ DB.TABLE_MESSAGE ], 'readonly'); var store = transaction.objectStore(DB.TABLE_MESSAGE); var index = store.index('messageId'); var request = index.openCursor(range); request.onsuccess = function (e) { var nextMessage = null; var cursor = e.target.result; if (cursor) { nextMessage = new MessageModel(cursor.value); nextMessage.cid = cursor.primaryKey; } deferred.resolve(nextMessage); }; request.onerror = function () { deferred.reject(); }; return deferred.promise(); }, getPrevious: function () { var deferred = $.Deferred(); var range = IDBKeyRange.upperBound(this.get('messageId'), true); var transaction = DB.conx.transaction([ DB.TABLE_MESSAGE ], 'readonly'); var store = transaction.objectStore(DB.TABLE_MESSAGE); var index = store.index('messageId'); var request = index.openCursor(range, 'prev'); request.onsuccess = function (e) { var previousMessage = null; var cursor = e.target.result; if (cursor) { previousMessage = new MessageModel(cursor.value); previousMessage.cid = cursor.primaryKey; } deferred.resolve(previousMessage); }; request.onerror = function () { deferred.reject(); }; return deferred.promise(); }, delete: function () { var deferred = $.Deferred(); var transaction = DB.conx.transaction([ DB.TABLE_MESSAGE ], 'readwrite'); var store = transaction.objectStore(DB.TABLE_MESSAGE); var request = store.clear(); request.onsuccess = function () { deferred.resolve(); }; request.onerror = function () { deferred.reject(); }; return deferred.promise(); } }); return MessageModel; });
sanyaade-teachings/mobile-messaging
www/js/models/message.js
JavaScript
agpl-3.0
4,522
/* * sones GraphDB - Community Edition - http://www.sones.com * Copyright (C) 2007-2011 sones GmbH * * This file is part of sones GraphDB Community Edition. * * sones GraphDB 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, version 3 of the License. * * sones GraphDB 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 sones GraphDB. If not, see <http://www.gnu.org/licenses/>. * */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IdentityModel.Selectors; using sones.GraphDSServer; using System.IdentityModel.Tokens; using System.Diagnostics; using sones.GraphDB; using sones.Library.VersionedPluginManager; using sones.GraphDS.PluginManager; using sones.Library.Commons.Security; using System.Net; using System.Threading; using sones.GraphDB.Manager.Plugin; using System.IO; using System.Globalization; using sones.Library.DiscordianDate; using System.Security.AccessControl; using sones.GraphDSServer.ErrorHandling; using sones.GraphDS.GraphDSRemoteClient; using sones.GraphDS.GraphDSRESTClient; using sones.GraphDB.TypeSystem; using sones.GraphDB.Request; using sones.Library.PropertyHyperGraph; using sones.GraphQL.Result; using sones.Library.Network.HttpServer; namespace TagExampleWithGraphMappingFramework { public class TagExampleWithGraphMappingFramework { #region sones GraphDB Startup private bool quiet = false; private bool shutdown = false; private IGraphDSServer _dsServer; private bool _ctrlCPressed; private IGraphDSClient GraphDSClient; private sones.Library.Commons.Security.SecurityToken SecToken; private long TransToken; public TagExampleWithGraphMappingFramework(String[] myArgs) { Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-us"); if (myArgs.Count() > 0) { foreach (String parameter in myArgs) { if (parameter.ToUpper() == "--Q") quiet = true; } } #region Start RemoteAPI, WebDAV and WebAdmin services, send GraphDS notification IGraphDB GraphDB; GraphDB = new SonesGraphDB(null, true, new CultureInfo("en-us")); #region Configure PlugIns // Plugins are loaded by the GraphDS with their according PluginDefinition and only if they are listed // below - there is no auto-discovery for plugin types in GraphDS (!) #region Query Languages // the GQL Query Language Plugin needs the GraphDB instance as a parameter List<PluginDefinition> QueryLanguages = new List<PluginDefinition>(); Dictionary<string, object> GQL_Parameters = new Dictionary<string, object>(); GQL_Parameters.Add("GraphDB", GraphDB); QueryLanguages.Add(new PluginDefinition("sones.gql", GQL_Parameters)); #endregion #region GraphDS Service Plugins List<PluginDefinition> GraphDSServices = new List<PluginDefinition>(); #endregion List<PluginDefinition> UsageDataCollector = new List<PluginDefinition>(); #endregion GraphDSPlugins PluginsAndParameters = new GraphDSPlugins(QueryLanguages); _dsServer = new GraphDS_Server(GraphDB, PluginsAndParameters); #region Start GraphDS Services #region Remote API Service Dictionary<string, object> RemoteAPIParameter = new Dictionary<string, object>(); RemoteAPIParameter.Add("IPAddress", IPAddress.Parse("127.0.0.1")); RemoteAPIParameter.Add("Port", (ushort)9970); _dsServer.StartService("sones.RemoteAPIService", RemoteAPIParameter); #endregion #endregion #endregion #endregion #region Some helping lines... if (!quiet) { Console.WriteLine("This GraphDB Instance offers the following options:"); Console.WriteLine(" * If you want to suppress console output add --Q as a"); Console.WriteLine(" parameter."); Console.WriteLine(); Console.WriteLine(" * the following GraphDS Service Plugins are initialized and started: "); foreach (var Service in _dsServer.AvailableServices) { Console.WriteLine(" * " + Service.PluginName); } Console.WriteLine(); foreach (var Service in _dsServer.AvailableServices) { Console.WriteLine(Service.ServiceDescription); Console.WriteLine(); } Console.WriteLine("Enter 'shutdown' to initiate the shutdown of this instance."); } Run(); Console.CancelKeyPress += OnCancelKeyPress; while (!shutdown) { String command = Console.ReadLine(); if (!_ctrlCPressed) { if (command != null) { if (command.ToUpper() == "SHUTDOWN") shutdown = true; } } } Console.WriteLine("Shutting down GraphDS Server"); _dsServer.Shutdown(null); Console.WriteLine("Shutdown complete"); #endregion } #region Cancel KeyPress /// <summary> /// Cancel KeyPress /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public virtual void OnCancelKeyPress(object sender, ConsoleCancelEventArgs e) { e.Cancel = true; //do not abort Console here. _ctrlCPressed = true; Console.Write("Shutdown GraphDB (y/n)?"); string input; do { input = Console.ReadLine(); } while (input == null); switch (input.ToUpper()) { case "Y": shutdown = true; return; default: shutdown = false; return; } }//method #endregion #region the actual example public void Run() { GraphDSClient = new GraphDS_RemoteClient(new Uri("http://localhost:9970/rpc")); SecToken = GraphDSClient.LogOn(new RemoteUserPasswordCredentials("test", "test")); TransToken = GraphDSClient.BeginTransaction(SecToken); GraphDSClient.Clear<IRequestStatistics>(SecToken, TransToken, new RequestClear(), (Statistics, DeletedTypes) => Statistics); #region create types, create instances and additional work using the GraphDB API GraphDSClient.Clear<IRequestStatistics>(SecToken, TransToken, new RequestClear(), (Statistics, DeletedTypes) => Statistics); Console.WriteLine("Press enter to start example"); Console.ReadLine(); GraphDBRequests(); #endregion //clear the DB (delete all created types) to create them again using the QueryLanguage GraphDSClient.Clear<IRequestStatistics>(SecToken, TransToken, new RequestClear(), (Statistics, DeletedTypes) => Statistics); #region create some types and insert values using the SonesQueryLanguage GraphQLQueries(); #endregion #region make some SELECTS SELECTS(); #endregion Console.WriteLine(); Console.WriteLine("Finished Example. Type a key to finish!"); Console.ReadKey(); } private void GraphDBRequests() { Console.WriteLine("performing DB requests..."); #region define type "Tag" //create a VertexTypePredefinition var Tag_VertexTypePredefinition = new VertexTypePredefinition("Tag"); //create property var PropertyName = new PropertyPredefinition("Name", "String") .SetComment("This is a property on type 'Tag' named 'Name' and is of type 'String'"); //add property Tag_VertexTypePredefinition.AddProperty(PropertyName); //create outgoing edge to "Website" var OutgoingEdgesTaggedWebsites = new OutgoingEdgePredefinition("TaggedWebsites", "Website") .SetMultiplicityAsMultiEdge() .SetComment(@"This is an outgoing edge on type 'Tag' wich points to the type 'Website' (the AttributeType) and is defined as 'MultiEdge', which means that this edge can contain multiple single edges"); //add outgoing edge Tag_VertexTypePredefinition.AddOutgoingEdge(OutgoingEdgesTaggedWebsites); #endregion #region define type "Website" //create a VertexTypePredefinition var Website_VertexTypePredefinition = new VertexTypePredefinition("Website"); //create properties PropertyName = new PropertyPredefinition("Name", "String") .SetComment("This is a property on type 'Website' named 'Name' and is of type 'String'"); var PropertyUrl = new PropertyPredefinition("URL", "String") .SetAsMandatory(); //add properties Website_VertexTypePredefinition.AddProperty(PropertyName); Website_VertexTypePredefinition.AddProperty(PropertyUrl); #region create an index on type "Website" on property "Name" //there are three ways to set an index on property "Name" //Beware: Use just one of them! //1. create an index definition and specifie the property- and type name var MyIndex = new IndexPredefinition("MyIndex").SetIndexType("SonesIndex").AddProperty("Name").SetVertexType("Website"); //add index Website_VertexTypePredefinition.AddIndex((IndexPredefinition)MyIndex); //2. on creating the property definition of property "Name" call the SetAsIndexed() method, the GraphDB will create the index //PropertyName = new PropertyPredefinition("Name") // .SetAttributeType("String") // .SetComment("This is a property on type 'Website' with name 'Name' and is of type 'String'") // .SetAsIndexed(); //3. make a create index request, like creating a type //BEWARE: This statement must be execute AFTER the type "Website" is created. //var MyIndex = GraphDSServer.CreateIndex<IIndexDefinition>(SecToken, // TransToken, // new RequestCreateIndex( // new IndexPredefinition("MyIndex") // .SetIndexType("SonesIndex") // .AddProperty("Name") // .SetVertexType("Website")), (Statistics, Index) => Index); #endregion //add IncomingEdge "Tags", the related OutgoingEdge is "TaggedWebsites" on type "Tag" Website_VertexTypePredefinition.AddIncomingEdge(new IncomingEdgePredefinition("Tags", "Tag", "TaggedWebsites")); #endregion #region create types by sending requests //create the types "Tag" and "Website" var DBTypes = GraphDSClient.CreateVertexTypes<IEnumerable<IVertexType>>(SecToken, TransToken, new RequestCreateVertexTypes( new List<VertexTypePredefinition> { Tag_VertexTypePredefinition, Website_VertexTypePredefinition }), (Statistics, VertexTypes) => VertexTypes); /* * BEWARE: The following two operations won't work because the two types "Tag" and "Website" depending on each other, * because one type has an incoming edge to the other and the other one has an incoming edge, * so they cannot be created separate (by using create type), * they have to be created at the same time (by using create types) * * //create the type "Website" * var Website = GraphDSServer.CreateVertexType<IVertexType>(SecToken, * TransToken, * new RequestCreateVertexType(Website_VertexTypePredefinition), * (Statistics, VertexType) => VertexType); * * //create the type "Tag" * var Tag = GraphDSServer.CreateVertexType<IVertexType>(SecToken, * TransToken, * new RequestCreateVertexType(Tag_VertexTypePredefinition), * (Statistics, VertexType) => VertexType); */ var Tag = DBTypes.Where(type => type.Name == "Tag").FirstOrDefault(); if (Tag != null) Console.WriteLine("Vertex Type 'Tag' created"); var Website = DBTypes.Where(type => type.Name == "Website").FirstOrDefault(); if(Website != null) Console.WriteLine("Vertex Type 'Website' created"); #endregion #region insert some Websites by sending requests var sones = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website") .AddStructuredProperty("Name", "Sones") .AddStructuredProperty("URL", "http://sones.com/"), (Statistics, Result) => Result); var cnn = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website") .AddStructuredProperty("Name", "CNN") .AddStructuredProperty("URL", "http://cnn.com/"), (Statistics, Result) => Result); var xkcd = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website") .AddStructuredProperty("Name", "xkcd") .AddStructuredProperty("URL", "http://xkcd.com/"), (Statistics, Result) => Result); var onion = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website") .AddStructuredProperty("Name", "onion") .AddStructuredProperty("URL", "http://theonion.com/"), (Statistics, Result) => Result); //adding an unknown property means the property isn't defined before var test = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website") .AddStructuredProperty("Name", "Test") .AddStructuredProperty("URL", "") .AddUnknownProperty("Unknown", "unknown property"), (Statistics, Result) => Result); if (sones != null) Console.WriteLine("Website 'sones' successfully inserted"); if (cnn != null) Console.WriteLine("Website 'cnn' successfully inserted"); if (xkcd != null) Console.WriteLine("Website 'xkcd' successfully inserted"); if (onion != null) Console.WriteLine("Website 'onion' successfully inserted"); if (test != null) Console.WriteLine("Website 'test' successfully inserted"); #endregion #region insert some Tags by sending requests //insert a "Tag" with an OutgoingEdge to a "Website" include that the GraphDB creates an IncomingEdge on the given Website instances //(because we created an IncomingEdge on type "Website") --> as a consequence we never have to set any IncomingEdge var good = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Tag") .AddStructuredProperty("Name", "good") .AddEdge(new EdgePredefinition("TaggedWebsites") .AddVertexID(Website.ID, cnn.VertexID) .AddVertexID(Website.ID, xkcd.VertexID)), (Statistics, Result) => Result); var funny = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Tag") .AddStructuredProperty("Name", "funny") .AddEdge(new EdgePredefinition("TaggedWebsites") .AddVertexID(Website.ID, xkcd.VertexID) .AddVertexID(Website.ID, onion.VertexID)), (Statistics, Result) => Result); if (good != null) Console.WriteLine("Tag 'good' successfully inserted"); if (funny != null) Console.WriteLine("Tag 'funny' successfully inserted"); #endregion #region how to get a type from the DB, properties of the type, instances of a specific type and read out property values //how to get a type from the DB var TagDBType = GraphDSClient.GetVertexType<IVertexType>(SecToken, TransToken, new RequestGetVertexType(Tag.Name), (Statistics, Type) => Type); //how to get a type from the DB var WebsiteDBType = GraphDSClient.GetVertexType<IVertexType>(SecToken, TransToken, new RequestGetVertexType(Website.Name), (Statistics, Type) => Type); //read informations from type var typeName = TagDBType.Name; //are there other types wich extend the type "Tag" var hasChildTypes = TagDBType.HasChildTypes; var hasPropName = TagDBType.HasProperty("Name"); //get the definition of the property "Name" var propName = TagDBType.GetPropertyDefinition("Name"); //how to get all instances of a type from the DB var TagInstances = GraphDSClient.GetVertices(SecToken, TransToken, new RequestGetVertices(TagDBType.Name), (Statistics, Vertices) => Vertices); foreach (var item in TagInstances) { //to get the value of a property of an instance, you need the property ID //(that's why we fetched the type from DB an read out the property definition of property "Name") var name = item.GetPropertyAsString(propName.ID); } Console.WriteLine("API operations finished..."); #endregion } #endregion #region Graph Query Language /// <summary> /// Describes how to send queries using the GraphQL. /// </summary> private void GraphQLQueries() { #region create types //create types at the same time, because of the circular dependencies (Tag has OutgoingEdge to Website, Website has IncomingEdge from Tag) //like shown before, using the GraphQL there are also three different ways to create create an index on property "Name" of type "Website" //1. create an index definition and specifie the property name and index type var Types = GraphDSClient.Query(SecToken, TransToken, @"CREATE VERTEX TYPES Tag ATTRIBUTES (String Name, SET<Website> TaggedWebsites), Website ATTRIBUTES (String Name, String URL) INCOMINGEDGES (Tag.TaggedWebsites Tags) INDICES (MyIndex INDEXTYPE SonesIndex ON ATTRIBUTES Name)", "sones.gql"); //2. on creating the type with the property "Name", just define the property "Name" under INDICES //var Types = GraphQL.Query(SecToken, TransToken, @"CREATE VERTEX TYPES Tag ATTRIBUTES (String Name, SET<Website> TaggedWebsites), // Website ATTRIBUTES (String Name, String URL) INCOMINGEDGES (Tag.TaggedWebsites Tags) INDICES (Name)"); //3. make a create index query //var Types = GraphQL.Query(SecToken, TransToken, @"CREATE VERTEX TYPES Tag ATTRIBUTES (String Name, SET<Website> TaggedWebsites), // Website ATTRIBUTES (String Name, String URL) INCOMINGEDGES (Tag.TaggedWebsites Tags)"); //var MyIndex = GraphQL.Query(SecToken, TransToken, "CREATE INDEX MyIndex ON VERTEX TYPE Website (Name) INDEXTYPE SonesIndex"); CheckResult(Types); #endregion #region create instances of type "Website" var cnnResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'CNN', URL = 'http://cnn.com/')", "sones.gql"); CheckResult(cnnResult); var xkcdResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'xkcd', URL = 'http://xkcd.com/')", "sones.gql"); CheckResult(xkcdResult); var onionResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'onion', URL = 'http://theonion.com/')", "sones.gql"); CheckResult(onionResult); //adding an unknown property ("Unknown") means the property isn't defined before var unknown = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'Test', URL = '', Unknown = 'unknown property')", "sones.gql"); CheckResult(onionResult); #endregion #region create instances of type "Tag" var goodResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Tag VALUES (Name = 'good', TaggedWebsites = SETOF(Name = 'CNN', Name = 'xkcd'))", "sones.gql"); CheckResult(goodResult); var funnyResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Tag VALUES (Name = 'funny', TaggedWebsites = SETOF(Name = 'xkcd', Name = 'onion'))", "sones.gql"); CheckResult(funnyResult); #endregion Console.WriteLine("GQL Queries finished..."); } /// <summary> /// Executes some select statements. /// </summary> private void SELECTS() { // find out which tags xkcd is tagged with var _xkcdtags = GraphDSClient.Query(SecToken, TransToken, "FROM Website w SELECT w.Tags WHERE w.Name = 'xkcd' DEPTH 1", "sones.gql"); CheckResult(_xkcdtags); foreach (var _tag in _xkcdtags.Vertices) foreach (var edge in _tag.GetHyperEdge("Tags").GetAllEdges()) Console.WriteLine(edge.GetTargetVertex().GetPropertyAsString("Name")); // List tagged sites names and the count of there tags var _taggedsites = GraphDSClient.Query(SecToken, TransToken, "FROM Website w SELECT w.Name, w.Tags.Count() AS Counter", "sones.gql"); CheckResult(_taggedsites); foreach (var _sites in _taggedsites.Vertices) Console.WriteLine("{0} => {1}", _sites.GetPropertyAsString("Name"), _sites.GetPropertyAsString("Counter")); // find out the URL's of the website of each Tag var _urls = GraphDSClient.Query(SecToken, TransToken, "FROM Tag t SELECT t.Name, t.TaggedWebsites.URL", "sones.gql"); CheckResult(_urls); foreach (var _tag in _urls.Vertices) foreach (var edge in _tag.GetHyperEdge("TaggedWebsites").GetAllEdges()) Console.WriteLine(_tag.GetPropertyAsString("Name") + " - " + edge.GetTargetVertex().GetPropertyAsString("URL")); Console.WriteLine("SELECT operations finished..."); } /// <summary> /// This private method analyses the QueryResult, shows the ResultType and Errors if existing. /// </summary> /// <param name="myQueryResult">The result of a query.</param> private bool CheckResult(IQueryResult myQueryResult) { if (myQueryResult.Error != null) { if (myQueryResult.Error.InnerException != null) Console.WriteLine(myQueryResult.Error.InnerException.Message); else Console.WriteLine(myQueryResult.Error.Message); return false; } else { Console.WriteLine("Query " + myQueryResult.TypeOfResult); return true; } } #endregion } public class sonesGraphDBStarter { static void Main(string[] args) { bool quiet = false; if (args.Count() > 0) { foreach (String parameter in args) { if (parameter.ToUpper() == "--Q") quiet = true; } } if (!quiet) { DiscordianDate ddate = new DiscordianDate(); Console.WriteLine("sones GraphDB version 2.0 - " + ddate.ToString()); Console.WriteLine("(C) sones GmbH 2007-2011 - http://www.sones.com"); Console.WriteLine("-----------------------------------------------"); Console.WriteLine(); Console.WriteLine("Starting up GraphDB..."); } try { var sonesGraphDBStartup = new TagExampleWithGraphMappingFramework(args); } catch (ServiceException e) { if (!quiet) { Console.WriteLine(e.Message); Console.WriteLine("InnerException: " + e.InnerException.ToString()); Console.WriteLine(); Console.WriteLine("Press <return> to exit."); Console.ReadLine(); } } } } }
sones/sones
Applications/TagExampleWithGraphMappingFramework/Example.cs
C#
agpl-3.0
29,686
/* * Copyright (c) 1996 Sun Microsystems, Inc. All Rights Reserved. * * Permission to use, copy, modify, and distribute this software * and its documentation for NON-COMMERCIAL purposes and without * fee is hereby granted provided that this copyright notice * appears in all copies. Please refer to the file "copyright.html" * for further important copyright and licensing information. * * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ package javax.telephony; import javax.telephony.capabilities.ConnectionCapabilities; /** * A <CODE>Connection</CODE> represents a link (i&#46e&#46 an association) between * a {@link Call} object and an {@link Address} object. * * <H4>Introduction</H4> * * The purpose of a Connection object is to describe * the relationship between a Call object and an Address object. A Connection * object exists if the Address is a part of the telephone call. Each * Connection has a <EM>state</EM> which describes the particular stage of the * relationship between the Call and Address. These states and their meanings * are described below. Applications use the <CODE>Connection.getCall()</CODE> * and <CODE>Connection.getAddress()</CODE> methods to obtain the Call and * Address associated with this Connection, respectively. * <p> * From one perspective, an application may view a Call only in terms of the * Address/Connection objects which are part of the Call. This is termed a * <EM>logical</EM> view of the Call because it ignores the details provided * by the Terminal and TerminalConnection objects which are also associated * with a Call. In many instances, simple applications (such as an * <EM>outcall</EM> program) may only need to concern itself with the logical * view. In this logical view, a telephone call is views as two or more * endpoint addresses in communication. The Connection object describes the * state of each of these endpoint addresses with respect to the Call. * * <H4>Calls and Addresses</H4> * * Connection objects are immutable in terms of their Call and Address * references. In other words, the Call and Address object references do * not change throughout the lifetime of the Connection object instance. The * same Connection object may not be used in another telephone call. The * existence of a Connection implies that its Address is associated with its * Call in the manner described by the Connection's state. * <p> * Although a Connection's Address and Call references remain valid throughout * the lifetime of the Connection object, the same is not true for the Call * and Address object's references to this Connection. Particularly, when a * Connection moves into the Connection.DISCONNECTED state, it is no longer * listed by the <CODE>Call.getConnections()</CODE> and * <CODE>Address.getConnections()</CODE> methods. Typically, when a Connection * moves into the <CODE>Connection.DISCONNECTED</CODE> state, the application * loses its references to it to facilitate its garbage collection. * * <H4>TerminalConnections</H4> * * Connections objects are containers for zero or more TerminalConnection * objects. Connection objects are containers for zero or more TerminalConnection * objects. Connection objects represent the relationship between the Call and * the Address, whereas TerminalConnection objects represent the relationship * between the Connection and the Terminal. The relationship between the Call and * the Address may be viewed as a logical view of the Call. The relationship * between a Connection and a Terminal represents the physical view of the * Call, i.e. at which Terminal the telephone calls terminates. The * TerminalConnection object specification provides further information. * * <H4>Connection States</H4> * * Below is a description of each Connection state in real-world terms. These * real-world descriptions have no bearing on the specifications of methods, * they only serve to provide a more intuitive understanding of what is going * on. Several methods in this specification state pre-conditions based upon * the state of the Connection. * <p> * <TABLE CELLPADDING=2> * * <TR> * <TD WIDTH="15%"><CODE>Connection.IDLE</CODE></TD> * <TD WIDTH="85%"> * This state is the initial state for all new Connections. Connections which * are in the <CODE>Connection.IDLE</CODE> state are not actively part of a * telephone call, yet their references to the Call and Address objects are * valid. Connections typically do not stay in the <CODE>Connection.IDLE</CODE> * state for long, quickly transitioning to other states. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.DISCONNECTED</CODE></TD> * <TD WIDTH="85%"> * This state implies it is no longer part of the telephone call, although its * references to Call and Address still remain valid. A Connection in this * state is interpreted as once previously belonging to this telephone call. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.INPROGRESS</CODE></TD> * <TD WIDTH="85%"> * This state implies that the Connection, which represents the destination * end of a telephone call, is in the process of contacting the destination * side. Under certain circumstances, the Connection may not progress beyond * this state. Extension packages elaborate further on this state in various * situations. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.ALERTING</CODE></TD> * <TD WIDTH="85%"> * This state implies that the Address is being notified of an incoming call. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.CONNECTED</CODE></TD> * <TD WIDTH="85%"> * This state implies that a Connection and its Address is actively part of a * telephone call. In common terms, two people talking to one another are * represented by two Connections in the <CODE>Connection.CONNECTED</CODE> * state. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.UNKNOWN</CODE></TD> * <TD WIDTH="85%"> * This state implies that the implementation is unable to determine the * current state of the Connection. Typically, methods are invalid on * Connections which are in this state. Connections may move in and out of the * <CODE>Connection.UNKNOWN</CODE> state at any time. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.FAILED</CODE></TD> * <TD WIDTH="85%"> * This state indicates that a Connection to that end of the call has failed * for some reason. One reason why a Connection would be in the * <CODE>Connection.FAILED</CODE> state is because the party was busy. * </TD> * </TR> * </TABLE> * * <H4>Connection State Transitions</H4> * * With these loose, real-world meanings in the back of one's mind, the * Connection class defines a finite-state diagram which describes the * allowable Connection state transitions. This finite-state diagram must be * guaranteed by the implementation. Each method which causes a change in * a Connection state must be consistent with this state diagram. This finite * state diagram is below: * <P> * Note there is a general left-to-right progression of the state transitions. * A Connection object may transition into and out of the * <CODE>Connection.UNKNOWN</CODE> state at any time (hence, the asterisk * qualifier next to its bidirectional transition arrow). * <p> * <IMG SRC="doc-files/core-connectionstates.gif" ALIGN="center"> * </P> * * <H4>The Connection.disconnect() Method</H4> * * The primary method supported on the core package's Connection interface is * the <CODE>Connection.disconnect()</CODE> method. This method drops an entire * Connection from a telephone call. The result of this method is to move the * Connection object into the <CODE>Connection.DISCONNECTED</CODE> state. See * the specification of the <CODE>Connection.disconnect()</CODE> method on * this page for more detailed information. * * <H4>Listeners and Events</H4> * * All events pertaining to the Connection object are reported via the * <CODE>CallListener</CODE> interface on the Call object associated with this * Connection. In the core package, events are reported to a CallListener when * a new Connection is created and whenever a Connection changes state. * Listeners are added to Call objects via the <CODE>Call.addCallListener()</CODE> * method and more indirectly via the <CODE>Address.addCallListener()</CODE> * and <CODE>Terminal.addCallListener()</CODE> methods. See the specifications * for the Call, Address, and Terminal interfaces for more information. * <p> * The following Connection-related events are defined in the core package. * Each of these events extend the <CODE>ConnectionEvent</CODE> interface (which, in * turn, extends the <CODE>CallEvent</CODE> interface). * <p> * <TABLE CELLPADDING=2> * <TR> * <TD WIDTH="20%"><CODE>ConnectionCreated</CODE></TD> * <TD WIDTH="80%"> * Indicates a new Connection has been created on a Call. * </TD> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionInProgress</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the * <CODE>Connection.INPROGRESS</CODE> state. * </TD> * </TR> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionAlerting</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the <CODE>Connection.ALERTING</CODE> * state. * </TD> * </TR> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionConnected</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the * <CODE>Connection.CONNECTED</CODE> state. * </TD> * </TR> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionDisconnected</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the * <CODE>Connection.DISCONNECTED</CODE> state. * </TD> * </TR> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionFailed</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the <CODE>Connection.FAILED</CODE> * state. * </TD> * </TR> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionUnknown</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the <CODE>Connection.UNKNOWN</CODE> * state. * </TD> * </TR> * </TABLE> * <p> * @see javax.telephony.ConnectionEvent * @see javax.telephony.ConnectionListener * @version 04/05/99 1.48 */ public interface Connection { /** * The <CODE>Connection&#46IDLE</CODE> state is the initial state for all new * Connections. Connections which are in the Connection.IDLE state are not * actively part of a telephone call, yet their references to the Call and * Address objects are valid. Connections typically do not stay in the * <CODE>Connection.IDLE</CODE> state for long, quickly transitioning to * other states. */ public static final int IDLE = 0x30; /** * The <CODE>Connection&#46INPROGRESS</CODE> state implies that the Connection, * which represents the destination end of a telephone call, is in the * process of contacting the destination side. Under certain circumstances, * the Connection may not progress beyond this state. Extension packages * elaborate further on this state in various situations. */ public static final int INPROGRESS = 0x31; /** * The <CODE>Connection&#46ALERTING</CODE> state implies that the Address is * being notified of an incoming call. */ public static final int ALERTING = 0x32; /** * The <CODE>Connection&#46CONNECTED</CODE> state implies that a Connection and * its Address is actively part of a telephone call. In common terms, two * people talking to one another are represented by two Connections in the * <CODE>Connection.CONNECTED</CODE> state. */ public static final int CONNECTED = 0x33; /** * The <CODE>Connection&#46DISCONNECTED</CODE> state implies it is no longer * part of the telephone call, although its references to Call and Address * still remain valid. A Connection in the * <CODE>Connection.DISCONNECTED</CODE> state is interpreted as once * previously belonging to this telephone call. */ public static final int DISCONNECTED = 0x34; /** * The <CODE>Connection&#46FAILED</CODE> state indicates that a Connection to * that end of the call has failed for some reason. One reason why a * Connection would be in the <CODE>Connection.FAILED</CODE> state is * because the party was busy. */ public static final int FAILED = 0x35; /** * The <CODE>Connection&#46UNKNOWN</CODE> state implies that the implementation * is unable to determine the current state of the Connection. Typically, * method are invalid on Connections which are in the * <CODE>Connection.UNKNOWN</CODE> state. Connections may move in and out of * this state at any time. */ public static final int UNKNOWN = 0x36; /** * Returns the current state of the Connection. The return value will * be one of states defined above. * <p> * @return The current state of the Connection. */ public int getState(); /** * Returns the Call object associated with this Connection. This Call * reference remains valid throughout the lifetime of the Connection object, * despite the state of the Connection object. This Call reference does not * change once the Connection object has been created. * <p> * @return The call object associated with this Connection. */ public Call getCall(); /** * Returns the Address object associated with this Connection. This Address * object reference remains valid throughout the lifetime of the Connection * object despite the state of the Connection object. This Address reference * does not change once the Connection object has been created. * <p> * @return The Address associated with this Connection. */ public Address getAddress(); /** * Returns an array of TerminalConnection objects associated with this * Connection. TerminalConnection objects represent the relationship between * a Connection and a specific Terminal endpoint. There may be zero * TerminalConnections associated with this Connection. In that case, this * method returns null. Connection objects lose their reference to a * TerminalConnection once the TerminalConnection moves into the * <CODE>TerminalConnection.DROPPED</CODE> state. * <p> * <B>Post-conditions:</B> * <OL> * <LI>Let TerminalConnection tc[] = this.getTerminalConnections() * <LI>tc == null or tc.length >= 1 * <LI>For all i, tc[i].getState() != TerminalConnection.DROPPED * </OL> * @return An array of TerminalConnection objects associated with this * Connection, null if there are no TerminalConnections. */ public TerminalConnection[] getTerminalConnections(); /** * Drops a Connection from an active telephone call. The Connection's Address * is no longer associated with the telephone call. This method does not * necessarily drop the entire telephone call, only the particular * Connection on the telephone call. This method provides the ability to * disconnect a specific party from a telephone call, which is especially * useful in telephone calls consisting of three or more parties. Invoking * this method may result in the entire telephone call being dropped, which * is a permitted outcome of this method. In that case, the appropriate * events are delivered to the application, indicating that more than just * a single Connection has been dropped from the telephone call. * * <H5>Allowable Connection States</H5> * * The Connection object must be in one of several states in order for * this method to be successfully invoked. These allowable states are: * <CODE>Connection.CONNECTED</CODE>, <CODE>Connection.ALERTING</CODE>, * <CODE>Connection.INPROGRESS</CODE>, or <CODE>Connection.FAILED</CODE>. If * the Connection is not in one of these allowable states when this method is * invoked, this method throws InvalidStateException. Having the Connection * in one of the allowable states does not guarantee a successful invocation * of this method. * * <H5>Method Return Conditions</H5> * * This method returns successfully only after the Connection has been * disconnected from the telephone call and has transitioned into the * <CODE>Connection.DISCONNECTED</CODE>. This method may return * unsuccessfully by throwing one of the exceptions listed below. Note that * this method waits (i.e. the invocating thread blocks) until either the * Connection is actually disconnected from the telephone call or an error * is detected and an exception thrown. Also, all of the TerminalConnections * associated with this Connection are moved into the * <CODE>TerminalConnection.DROPPED</CODE> state. As a result, they are no * longer reported via the Connection by the * <CODE>Connection.getTerminalConnections()</CODE> method. * <p> * As a result of this method returning successfully, one or more events * are delivered to the application. These events are listed below: * <p> * <OL> * <LI>A ConnectionDisconnected event for this Connection. * <LI>A TerminalConnectionDropped event for all TerminalConnections associated with * this Connection. * </OL> * * <H5>Dropping Additional Connections</H5> * * Additional Connections may be dropped indirectly as a result of this * method. For example, dropping the destination Connection of a two-party * Call may result in the entire telephone call being dropped. It is up to * the implementation to determine which Connections are dropped as a result * of this method. Implementations should not, however, drop additional * Connections if it does not reflect the natural response of the underlying * telephone hardware. * <p> * Dropping additional Connections implies that their TerminalConnections are * dropped as well. Also, if all of the Connections on a telephone call are * dropped as a result of this method, the Call will move into the * <CODE>Call.INVALID</CODE> state. The following lists additional events * which may be delivered to the application. * <p> * <OL> * <LI>ConnectionDisconnected/TerminalConnectionDropped are delivered for all other * Connections and TerminalConnections dropped indirectly as a result of * this method. * <LI>CallInvalid if all of the Connections are dropped indirectly as a * result of this method. * </OL> * <p> * <B>Pre-conditions:</B> * <OL> * <LI>((this.getCall()).getProvider()).getState() == Provider.IN_SERVICE * <LI>this.getState() == Connection.CONNECTED or Connection.ALERTING * or Connection.INPROGRESS or Connection.FAILED * <LI>Let TerminalConnection tc[] = this.getTerminalConnections (see post- * conditions) * </OL> * <B>Post-conditions:</B> * <OL> * <LI>((this.getCall()).getProvider()).getState() == Provider.IN_SERVICE * <LI>this.getState() == Connection.DISCONNECTED * <LI>For all i, tc[i].getState() == TerminalConnection.DROPPED * <LI>this.getTerminalConnections() == null. * <LI>this is not an element of (this.getCall()).getConnections() * <LI>ConnectionDisconnected is delivered for this Connection. * <LI>TerminalConnectionDropped is delivered for all TerminalConnections associated * with this Connection. * <LI>ConnectionDisconnected/TerminalConnectionDropped are delivered for all other * Connections and TerminalConnections dropped indirectly as a result of * this method. * <LI>CallInvalid if all of the Connections are dropped indirectly as a * result of this method. * </OL> * <p> * @see javax.telephony.ConnectionListener * @see javax.telephony.ConnectionEvent * @exception PrivilegeViolationException The application does not have * the authority or permission to disconnected the Connection. For example, * the Address associated with this Connection may not be controllable in * the Provider's domain. * @exception ResourceUnavailableException An internal resource required * to drop a connection is not available. * @exception MethodNotSupportedException This method is not supported by * the implementation. * @exception InvalidStateException Some object required for the successful * invocation of this method is not in the proper state as given by this * method's pre-conditions. For example, the Provider may not be in the * Provider.IN_SERVICE state or the Connection may not be in one of the * allowable states. */ public void disconnect() throws PrivilegeViolationException, ResourceUnavailableException, MethodNotSupportedException, InvalidStateException; /** * Returns the dynamic capabilities for the instance of the Connection * object. Dynamic capabilities tell the application which actions are * possible at the time this method is invoked based upon the implementations * knowledge of its ability to successfully perform the action. This * determination may be based upon the current state of the call model * or some implementation-specific knowledge. These indications do not * guarantee that a particular method can be successfully invoked, however. * <p> * The dynamic Connection capabilities require no additional arguments. * <p> * @return The dynamic Connection capabilities. */ public ConnectionCapabilities getCapabilities(); /** * Gets the ConnectionCapabilities object with respect to a Terminal and * an Address. If null is passed as a Terminal parameter, the general/ * provider-wide Connection capabilities are returned. * <p> * <STRONG>Note:</STRONG> This method has been replaced in JTAPI v1.2. The * <CODE>Connection.getCapabilities()</CODE> method returns the dynamic * Connection capabilities. This method now should simply invoke the * <CODE>Connection.getCapabilities()</CODE> method. * <p> * @deprecated Since JTAPI v1.2. This method has been replaced by the * Connection.getCapabilities() method. * @param terminal This argument is ignored in JTAPI v1.2 and later. * @param address This argument is ignored in JTAPI v1.2 and later. * @exception InvalidArgumentException This exception is never thrown in * JTAPI v1.2 and later. * @exception PlatformException A platform-specific exception occurred. * @return The dynamic ConnectionCapabilities capabilities. */ public ConnectionCapabilities getConnectionCapabilities(Terminal terminal, Address address) throws InvalidArgumentException, PlatformException; }
kerr-huang/openss7
src/java/javax/telephony/Connection.java
Java
agpl-3.0
22,953
/* * Copyright (c) 2018. Wise Wild Web * * This File is part of Caipi and under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License * Full license at https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode * * @author : Nathanael Braun * @contact : caipilabs@gmail.com */ var cfg = require('$super'), p = (APP_PORT != 80) ? (":" + APP_PORT) : "", domain = (__LOCAL__ ? 'mamasound.fr.local' + p : 'mamasound.fr' + p), url = cfg.wwwDomain ? 'www.' + domain : domain; export default { ...require('$super'), PROJECT_NAME : "www.mamasound.fr", PUBLIC_URL : url, ROOT_DOMAIN : domain, API_URL : 'api.' + domain, UPLOAD_URL : 'upload.' + domain, STATIC_URL : 'static.' + domain, STATIC_REDIRECT_URL: __LOCAL__ && 'static.mamasound.fr', OSM_URL: "http://{s}.tile.osm.org/{z}/{x}/{y}.png", DB_URL : "mongodb://localhost:27017/www_mamasound_fr", UPLOAD_DIR : "./uploads/", CACHE_TM : 1000 * 60 * 2, SESSION_CHECK_TM: 1000 * 60 * 1, defaultRootMenuId: "Menu.HyInIUM8.html", htmlRefs: [ { "type": "script", "src" : "https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyA7XcGxipnIMdSSBJHn3tzeJe-fU3ilCak" }, ...(cfg.htmlRefs || []) ] };
nathb2b/mamasound.fr
App/config.js
JavaScript
agpl-3.0
1,324
## Note: you must install Levenshtein module # pip install python-Levenshtein # for this Microsoft Visual C++ 9.0 is required. Get it from http://aka.ms/vcpython27 # more info - see: http://stackoverflow.com/questions/18134437/where-can-the-documentation-for-python-levenshtein-be-found-online from pymongo import MongoClient import pymongo import pprint import bson import pandas import Levenshtein EXPECTED_STREET_PATTERN = \ u"^.*(?<![Ss]tra\u00dfe)(?<![Ww]eg)(?<![Aa]llee)(?<![Rr]ing)(?<![Bb]erg)" + \ u"(?<![Pp]ark)(?<![Hh]\u00f6he)(?<![Pp]latz)(?<![Bb]r\u00fccke)(?<![Gg]rund)$" def audit_streets(collection): return list(collection.distinct("name", { "type": "way", "name": {"$regex": EXPECTED_STREET_PATTERN} })) def audit_buildings(db): result = db.eval(''' db.osmnodes.ensureIndex({pos:"2dsphere"}); result = []; db.osmnodes.find( {"building": {"$exists": true}, "address.street": {"$exists": true}, "pos": {"$exists": true}}, {"address.street": "", "pos": ""} ).forEach(function(val, idx) { val.nearby = db.osmnodes.distinct("address.street", {"_id": {"$ne": val._id}, "pos": {"$near": {"$geometry": {"type": "Point", "coordinates": val.pos}, "$maxDistance": 50, "$minDistance": 0}}} ); result.push(val); }) return result; ''') df_list = [] for row in result: street_name = row["address"]["street"] nb_best_dist = None nb_best = "" nb_worst_dist = None nb_worst = "" for nearby_street in row["nearby"]: d = Levenshtein.distance(nearby_street, street_name) if nb_best_dist == None or d < nb_best_dist: nb_best_dist = d nb_best = nearby_street if nb_worst_dist == None or d > nb_worst_dist: nb_worst_dist = d nb_worst = nearby_street df_list += [{ "_id": row["_id"], "street_name": street_name, "num_nearby": len(row["nearby"]), "nb_best": nb_best, "nb_worst": nb_worst, "nb_best_dist": nb_best_dist, "nb_worst_dist": nb_worst_dist }] return pandas.DataFrame(df_list, columns=["_id", "street_name", "num_nearby", "nb_best", "nb_best_dist", "nb_worst", "nb_worst_dist"]) def audit_phone_numbers(collection): return list(collection.aggregate([ {"$match": {"$or": [ {"phone": {"$exists": True}}, {"mobile_phone": {"$exists": True}}, {"address.phone": {"$exists": True}} ]}}, {"$project": { "_id": 1, "phone": {"$ifNull": ["$phone", {"$ifNull": ["$mobile_phone", "$address.phone"]}]} }} ])) def audit_quality_map(mongoServer, mongoPort, csvFilePattern, csvEncoding): client = MongoClient(mongoServer + ":" + mongoPort) db = client.udacity c = client.udacity.osmnodes print print "Auditing way descriptions..." print "These are the 'unusual' street names" r = audit_streets(c) pprint.pprint(r) print print "Auditing streets close to buildings..." r = audit_buildings(db) r.to_csv(csvFilePattern.format("audit_buildings.csv"), encoding=csvEncoding) pprint.pprint(r) print print "Auditing phone numbers..." r = audit_phone_numbers(c) pprint.pprint(r)
benjaminsoellner/2015_Data_Analyst_Project_3
Project/audit_quality_map.py
Python
agpl-3.0
3,625
<?php class Cloudsponge_Integration { var $enabled; var $key; /** * PHP 5 Constructor * * @package Invite Anyone * @since 0.8 */ function __construct() { if ( empty( $options ) ) $options = get_option( 'invite_anyone' ); $this->enabled = !empty( $options['cloudsponge_enabled'] ) ? $options['cloudsponge_enabled'] : false; $this->key = !empty( $options['cloudsponge_key'] ) ? $options['cloudsponge_key'] : false; if ( $this->enabled && $this->key ) { define( 'INVITE_ANYONE_CS_ENABLED', true ); add_action( 'invite_anyone_after_addresses', array( $this, 'import_markup' ) ); add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_script' ) ); } } /** * Registers and loads CS JS. * * @package Invite Anyone * @since 0.8.8 */ function enqueue_script() { wp_register_script( 'ia_cloudsponge_address_books', 'https://api.cloudsponge.com/address_books.js', array(), false, true ); wp_register_script( 'ia_cloudsponge', WP_PLUGIN_URL . '/invite-anyone/by-email/cloudsponge-js.js', array( 'ia_cloudsponge_address_books' ), false, true ); // The domain key must be printed as a javascript object so it's accessible to the // script $strings = array( 'domain_key' => $this->key ); if ( $locale = apply_filters( 'ia_cloudsponge_locale', '' ) ) { $strings['locale'] = $locale; } if ( $stylesheet = apply_filters( 'ia_cloudsponge_stylesheet', '' ) ) { $strings['stylesheet'] = $stylesheet; } wp_localize_script( 'ia_cloudsponge', 'ia_cloudsponge', $strings ); } /** * Inserts the Cloudsponge markup into the Send Invites front end page. * * Also responsible for enqueuing the necessary assets. * * @package Invite Anyone * @since 0.8 * * @param array $options Invite Anyone settings. Check em so we can bail if necessary */ function import_markup( $options = false ) { wp_enqueue_script( 'ia_cloudsponge' ); ?> <input type="hidden" id="cloudsponge-emails" name="cloudsponge-emails" value="" /> <?php _e( 'You can also add email addresses <a class="cs_import">from your Address Book</a>.', 'invite-anyone' ) ?> <?php } } $cloudsponge_integration = new Cloudsponge_Integration;
empirical-org/Empirical-Wordpress
wp-content/plugins/invite-anyone/by-email/cloudsponge-integration.php
PHP
agpl-3.0
2,189
package rocks.inspectit.ui.rcp.repository.service.cmr.proxy; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.framework.ReflectiveMethodInvocation; import com.google.common.base.Defaults; import rocks.inspectit.ui.rcp.repository.CmrRepositoryDefinition; import rocks.inspectit.ui.rcp.repository.service.cmr.ICmrService; /** * Utilities that will be used in interceptors. * * @author Ivan Senic * */ public final class InterceptorUtils { /** * Private constructor. */ private InterceptorUtils() { } /** * Is service method. * * @param methodInvocation * Method invocation. * @return Return if it is service method. */ public static boolean isServiceMethod(MethodInvocation methodInvocation) { return !methodInvocation.getMethod().getDeclaringClass().equals(ICmrService.class); } /** * Checks if the method being executed is executed on the proxy containing {@link ICmrService} * and service defines the default value on error value. * * @param methodInvocation * Method invocation. * @return <code>true</code> if {@link ICmrService} objects defines return default on error */ public static boolean isReturnDefaultReturnValue(MethodInvocation methodInvocation) { ICmrService cmrService = getCmrService(methodInvocation); return (null != cmrService) && cmrService.isDefaultValueOnError(); } /** * Tries to get the {@link CmrRepositoryDefinition} from the proxied {@link ICmrService} object. * * @param methodInvocation * {@link MethodInvocation}. * @return CMR invoked or null. */ public static CmrRepositoryDefinition getRepositoryDefinition(MethodInvocation methodInvocation) { ICmrService cmrService = getCmrService(methodInvocation); if (null != cmrService) { CmrRepositoryDefinition cmrRepositoryDefinition = cmrService.getCmrRepositoryDefinition(); return cmrRepositoryDefinition; } return null; } /** * Returns {@link ICmrService} object if one is bounded to the proxy being invoked in the given * {@link MethodInvocation} or <code>null</code> if one can not be obtained. * * @param methodInvocation * {@link MethodInvocation}. * @return {@link ICmrService} bounded on proxy or <code>null</code> */ private static ICmrService getCmrService(MethodInvocation methodInvocation) { if (methodInvocation instanceof ReflectiveMethodInvocation) { ReflectiveMethodInvocation reflectiveMethodInvocation = (ReflectiveMethodInvocation) methodInvocation; Object service = reflectiveMethodInvocation.getThis(); if (service instanceof ICmrService) { return (ICmrService) service; } } return null; } /** * Checks if the return type of the {@link java.lang.reflect.Method} invoked by * {@link MethodInvocation} is one of tree major collection types (List, Map, Set) and if it is * returns the empty collection of correct type. Otherwise it returns null. * * @param paramMethodInvocation * {@link MethodInvocation} * @return If the method invoked by {@link MethodInvocation} is one of tree major collection * types (List, Map, Set) method returns the empty collection of correct type. Otherwise * it returns null. */ public static Object getDefaultReturnValue(MethodInvocation paramMethodInvocation) { Class<?> returnType = paramMethodInvocation.getMethod().getReturnType(); if (returnType.isAssignableFrom(List.class)) { return Collections.emptyList(); } else if (returnType.isAssignableFrom(Map.class)) { return Collections.emptyMap(); } else if (returnType.isAssignableFrom(Set.class)) { return Collections.emptySet(); } else if (returnType.isPrimitive()) { try { return Defaults.defaultValue(returnType); } catch (Exception e) { return null; } } else { return null; } } }
inspectIT/inspectIT
inspectit.ui.rcp/src/main/java/rocks/inspectit/ui/rcp/repository/service/cmr/proxy/InterceptorUtils.java
Java
agpl-3.0
3,959
// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved. // See License.txt for license information. package model import ( "bytes" "fmt" "io" "io/ioutil" "mime/multipart" "net/http" "net/url" "strconv" "strings" "time" l4g "github.com/alecthomas/log4go" ) const ( HEADER_REQUEST_ID = "X-Request-ID" HEADER_VERSION_ID = "X-Version-ID" HEADER_CLUSTER_ID = "X-Cluster-ID" HEADER_ETAG_SERVER = "ETag" HEADER_ETAG_CLIENT = "If-None-Match" HEADER_FORWARDED = "X-Forwarded-For" HEADER_REAL_IP = "X-Real-IP" HEADER_FORWARDED_PROTO = "X-Forwarded-Proto" HEADER_TOKEN = "token" HEADER_BEARER = "BEARER" HEADER_AUTH = "Authorization" HEADER_REQUESTED_WITH = "X-Requested-With" HEADER_REQUESTED_WITH_XML = "XMLHttpRequest" STATUS = "status" STATUS_OK = "OK" STATUS_FAIL = "FAIL" STATUS_REMOVE = "REMOVE" CLIENT_DIR = "webapp/dist" API_URL_SUFFIX_V1 = "/api/v1" API_URL_SUFFIX_V3 = "/api/v3" API_URL_SUFFIX_V4 = "/api/v4" API_URL_SUFFIX = API_URL_SUFFIX_V4 ) type Result struct { RequestId string Etag string Data interface{} } type ResponseMetadata struct { StatusCode int Error *AppError RequestId string Etag string } type Client struct { Url string // The location of the server like "http://localhost:8065" ApiUrl string // The api location of the server like "http://localhost:8065/api/v3" HttpClient *http.Client // The http client AuthToken string AuthType string TeamId string RequestId string Etag string ServerVersion string } // NewClient constructs a new client with convienence methods for talking to // the server. func NewClient(url string) *Client { return &Client{url, url + API_URL_SUFFIX_V3, &http.Client{}, "", "", "", "", "", ""} } func closeBody(r *http.Response) { if r.Body != nil { ioutil.ReadAll(r.Body) r.Body.Close() } } func (c *Client) SetOAuthToken(token string) { c.AuthToken = token c.AuthType = HEADER_TOKEN } func (c *Client) ClearOAuthToken() { c.AuthToken = "" c.AuthType = HEADER_BEARER } func (c *Client) SetTeamId(teamId string) { c.TeamId = teamId } func (c *Client) GetTeamId() string { if len(c.TeamId) == 0 { println(`You are trying to use a route that requires a team_id, but you have not called SetTeamId() in client.go`) } return c.TeamId } func (c *Client) ClearTeamId() { c.TeamId = "" } func (c *Client) GetTeamRoute() string { return fmt.Sprintf("/teams/%v", c.GetTeamId()) } func (c *Client) GetChannelRoute(channelId string) string { return fmt.Sprintf("/teams/%v/channels/%v", c.GetTeamId(), channelId) } func (c *Client) GetUserRequiredRoute(userId string) string { return fmt.Sprintf("/users/%v", userId) } func (c *Client) GetChannelNameRoute(channelName string) string { return fmt.Sprintf("/teams/%v/channels/name/%v", c.GetTeamId(), channelName) } func (c *Client) GetEmojiRoute() string { return "/emoji" } func (c *Client) GetGeneralRoute() string { return "/general" } func (c *Client) GetFileRoute(fileId string) string { return fmt.Sprintf("/files/%v", fileId) } func (c *Client) DoPost(url, data, contentType string) (*http.Response, *AppError) { rq, _ := http.NewRequest("POST", c.Url+url, strings.NewReader(data)) rq.Header.Set("Content-Type", contentType) rq.Close = true if rp, err := c.HttpClient.Do(rq); err != nil { return nil, NewLocAppError(url, "model.client.connecting.app_error", nil, err.Error()) } else if rp.StatusCode >= 300 { defer closeBody(rp) return nil, AppErrorFromJson(rp.Body) } else { return rp, nil } } func (c *Client) DoApiPost(url string, data string) (*http.Response, *AppError) { rq, _ := http.NewRequest("POST", c.ApiUrl+url, strings.NewReader(data)) rq.Close = true if len(c.AuthToken) > 0 { rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) } if rp, err := c.HttpClient.Do(rq); err != nil { return nil, NewLocAppError(url, "model.client.connecting.app_error", nil, err.Error()) } else if rp.StatusCode >= 300 { defer closeBody(rp) return nil, AppErrorFromJson(rp.Body) } else { return rp, nil } } func (c *Client) DoApiGet(url string, data string, etag string) (*http.Response, *AppError) { rq, _ := http.NewRequest("GET", c.ApiUrl+url, strings.NewReader(data)) rq.Close = true if len(etag) > 0 { rq.Header.Set(HEADER_ETAG_CLIENT, etag) } if len(c.AuthToken) > 0 { rq.Header.Set(HEADER_AUTH, c.AuthType+" "+c.AuthToken) } if rp, err := c.HttpClient.Do(rq); err != nil { return nil, NewLocAppError(url, "model.client.connecting.app_error", nil, err.Error()) } else if rp.StatusCode == 304 { return rp, nil } else if rp.StatusCode >= 300 { defer closeBody(rp) return rp, AppErrorFromJson(rp.Body) } else { return rp, nil } } func getCookie(name string, resp *http.Response) *http.Cookie { for _, cookie := range resp.Cookies() { if cookie.Name == name { return cookie } } return nil } // Must is a convenience function used for testing. func (c *Client) Must(result *Result, err *AppError) *Result { if err != nil { l4g.Close() time.Sleep(time.Second) panic(err) } return result } // MustGeneric is a convenience function used for testing. func (c *Client) MustGeneric(result interface{}, err *AppError) interface{} { if err != nil { l4g.Close() time.Sleep(time.Second) panic(err) } return result } // CheckStatusOK is a convenience function for checking the return of Web Service // call that return the a map of status=OK. func (c *Client) CheckStatusOK(r *http.Response) bool { m := MapFromJson(r.Body) defer closeBody(r) if m != nil && m[STATUS] == STATUS_OK { return true } return false } func (c *Client) fillInExtraProperties(r *http.Response) { c.RequestId = r.Header.Get(HEADER_REQUEST_ID) c.Etag = r.Header.Get(HEADER_ETAG_SERVER) c.ServerVersion = r.Header.Get(HEADER_VERSION_ID) } func (c *Client) clearExtraProperties() { c.RequestId = "" c.Etag = "" c.ServerVersion = "" } // General Routes Section // GetClientProperties returns properties needed by the client to show/hide // certian features. It returns a map of strings. func (c *Client) GetClientProperties() (map[string]string, *AppError) { c.clearExtraProperties() if r, err := c.DoApiGet(c.GetGeneralRoute()+"/client_props", "", ""); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return MapFromJson(r.Body), nil } } // LogClient is a convenience Web Service call so clients can log messages into // the server-side logs. For example we typically log javascript error messages // into the server-side. It returns true if the logging was successful. func (c *Client) LogClient(message string) (bool, *AppError) { c.clearExtraProperties() m := make(map[string]string) m["level"] = "ERROR" m["message"] = message if r, err := c.DoApiPost(c.GetGeneralRoute()+"/log_client", MapToJson(m)); err != nil { return false, err } else { defer closeBody(r) c.fillInExtraProperties(r) return c.CheckStatusOK(r), nil } } // GetPing returns a map of strings with server time, server version, and node Id. // Systems that want to check on health status of the server should check the // url /api/v3/ping for a 200 status response. func (c *Client) GetPing() (map[string]string, *AppError) { c.clearExtraProperties() if r, err := c.DoApiGet(c.GetGeneralRoute()+"/ping", "", ""); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return MapFromJson(r.Body), nil } } // Team Routes Section // CreateTeam creates a team based on the provided Team struct. On success it returns // the Team struct with the Id, CreateAt and other server-decided fields populated. func (c *Client) CreateTeam(team *Team) (*Result, *AppError) { if r, err := c.DoApiPost("/teams/create", team.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamFromJson(r.Body)}, nil } } // GetAllTeams returns a map of all teams using team ids as the key. func (c *Client) GetAllTeams() (*Result, *AppError) { if r, err := c.DoApiGet("/teams/all", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamMapFromJson(r.Body)}, nil } } // GetAllTeamListings returns a map of all teams that are available to join // using team ids as the key. Must be authenticated. func (c *Client) GetAllTeamListings() (*Result, *AppError) { if r, err := c.DoApiGet("/teams/all_team_listings", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamMapFromJson(r.Body)}, nil } } // FindTeamByName returns the strings "true" or "false" depending on if a team // with the provided name was found. func (c *Client) FindTeamByName(name string) (*Result, *AppError) { m := make(map[string]string) m["name"] = name if r, err := c.DoApiPost("/teams/find_team_by_name", MapToJson(m)); err != nil { return nil, err } else { val := false if body, _ := ioutil.ReadAll(r.Body); string(body) == "true" { val = true } defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), val}, nil } } // Adds a user directly to the team without sending an invite. // The teamId and userId are required. You must be a valid member of the team and/or // have the correct role to add new users to the team. Returns a map of user_id=userId // if successful, otherwise returns an AppError. func (c *Client) AddUserToTeam(teamId string, userId string) (*Result, *AppError) { if len(teamId) == 0 { teamId = c.GetTeamId() } data := make(map[string]string) data["user_id"] = userId if r, err := c.DoApiPost(fmt.Sprintf("/teams/%v", teamId)+"/add_user_to_team", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // AddUserToTeamFromInvite adds a user to a team based off data provided in an invite link. // Either hash and dataToHash are required or inviteId is required. func (c *Client) AddUserToTeamFromInvite(hash, dataToHash, inviteId string) (*Result, *AppError) { data := make(map[string]string) data["hash"] = hash data["data"] = dataToHash data["invite_id"] = inviteId if r, err := c.DoApiPost("/teams/add_user_to_team_from_invite", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamFromJson(r.Body)}, nil } } // Removes a user directly from the team. // The teamId and userId are required. You must be a valid member of the team and/or // have the correct role to remove a user from the team. Returns a map of user_id=userId // if successful, otherwise returns an AppError. func (c *Client) RemoveUserFromTeam(teamId string, userId string) (*Result, *AppError) { if len(teamId) == 0 { teamId = c.GetTeamId() } data := make(map[string]string) data["user_id"] = userId if r, err := c.DoApiPost(fmt.Sprintf("/teams/%v", teamId)+"/remove_user_from_team", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) InviteMembers(invites *Invites) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/invite_members", invites.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), InvitesFromJson(r.Body)}, nil } } // UpdateTeam updates a team based on the changes in the provided team struct. On success // it returns a sanitized version of the updated team. Must be authenticated as a team admin // for that team or a system admin. func (c *Client) UpdateTeam(team *Team) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/update", team.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // User Routes Section // CreateUser creates a user in the system based on the provided user struct. func (c *Client) CreateUser(user *User, hash string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/create", user.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } // CreateUserWithInvite creates a user based on the provided user struct. Either the hash and // data strings or the inviteId is required from the invite. func (c *Client) CreateUserWithInvite(user *User, hash string, data string, inviteId string) (*Result, *AppError) { url := "/users/create?d=" + url.QueryEscape(data) + "&h=" + url.QueryEscape(hash) + "&iid=" + url.QueryEscape(inviteId) if r, err := c.DoApiPost(url, user.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } func (c *Client) CreateUserFromSignup(user *User, data string, hash string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/create?d="+url.QueryEscape(data)+"&h="+hash, user.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } // GetUser returns a user based on a provided user id string. Must be authenticated. func (c *Client) GetUser(id string, etag string) (*Result, *AppError) { if r, err := c.DoApiGet("/users/"+id+"/get", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } // getByUsername returns a user based on a provided username string. Must be authenticated. func (c *Client) GetByUsername(username string, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf("/users/name/%v", username), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } // getByEmail returns a user based on a provided username string. Must be authenticated. func (c *Client) GetByEmail(email string, etag string) (*User, *ResponseMetadata) { if r, err := c.DoApiGet(fmt.Sprintf("/users/email/%v", email), "", etag); err != nil { return nil, &ResponseMetadata{StatusCode: r.StatusCode, Error: err} } else { defer closeBody(r) return UserFromJson(r.Body), &ResponseMetadata{ StatusCode: r.StatusCode, RequestId: r.Header.Get(HEADER_REQUEST_ID), Etag: r.Header.Get(HEADER_ETAG_SERVER), } } } // GetMe returns the current user. func (c *Client) GetMe(etag string) (*Result, *AppError) { if r, err := c.DoApiGet("/users/me", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } // GetProfiles returns a map of users using user id as the key. Must be authenticated. func (c *Client) GetProfiles(offset int, limit int, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf("/users/%v/%v", offset, limit), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil } } // GetProfilesInTeam returns a map of users for a team using user id as the key. Must // be authenticated. func (c *Client) GetProfilesInTeam(teamId string, offset int, limit int, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf("/teams/%v/users/%v/%v", teamId, offset, limit), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil } } // GetProfilesInChannel returns a map of users for a channel using user id as the key. Must // be authenticated. func (c *Client) GetProfilesInChannel(channelId string, offset int, limit int, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf(c.GetChannelRoute(channelId)+"/users/%v/%v", offset, limit), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil } } // GetProfilesNotInChannel returns a map of users not in a channel but on the team using user id as the key. Must // be authenticated. func (c *Client) GetProfilesNotInChannel(channelId string, offset int, limit int, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf(c.GetChannelRoute(channelId)+"/users/not_in_channel/%v/%v", offset, limit), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil } } // GetProfilesByIds returns a map of users based on the user ids provided. Must // be authenticated. func (c *Client) GetProfilesByIds(userIds []string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/ids", ArrayToJson(userIds)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil } } // SearchUsers returns a list of users that have a username matching or similar to the search term. Must // be authenticated. func (c *Client) SearchUsers(params UserSearch) (*Result, *AppError) { if r, err := c.DoApiPost("/users/search", params.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserListFromJson(r.Body)}, nil } } // AutocompleteUsersInChannel returns two lists for autocompletion of users in a channel. The first list "in_channel", // specifies users in the channel. The second list "out_of_channel" specifies users outside of the // channel. Term, the string to search against, is required, channel id is also required. Must be authenticated. func (c *Client) AutocompleteUsersInChannel(term string, channelId string) (*Result, *AppError) { url := fmt.Sprintf("%s/users/autocomplete?term=%s", c.GetChannelRoute(channelId), url.QueryEscape(term)) if r, err := c.DoApiGet(url, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserAutocompleteInChannelFromJson(r.Body)}, nil } } // AutocompleteUsersInTeam returns a list for autocompletion of users in a team. The list "in_team" specifies // the users in the team that match the provided term, matching against username, full name and // nickname. Must be authenticated. func (c *Client) AutocompleteUsersInTeam(term string) (*Result, *AppError) { url := fmt.Sprintf("%s/users/autocomplete?term=%s", c.GetTeamRoute(), url.QueryEscape(term)) if r, err := c.DoApiGet(url, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserAutocompleteInTeamFromJson(r.Body)}, nil } } // AutocompleteUsers returns a list for autocompletion of users on the system that match the provided term, // matching against username, full name and nickname. Must be authenticated. func (c *Client) AutocompleteUsers(term string) (*Result, *AppError) { url := fmt.Sprintf("/users/autocomplete?term=%s", url.QueryEscape(term)) if r, err := c.DoApiGet(url, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserListFromJson(r.Body)}, nil } } // LoginById authenticates a user by user id and password. func (c *Client) LoginById(id string, password string) (*Result, *AppError) { m := make(map[string]string) m["id"] = id m["password"] = password return c.login(m) } // Login authenticates a user by login id, which can be username, email or some sort // of SSO identifier based on configuration, and a password. func (c *Client) Login(loginId string, password string) (*Result, *AppError) { m := make(map[string]string) m["login_id"] = loginId m["password"] = password return c.login(m) } // LoginByLdap authenticates a user by LDAP id and password. func (c *Client) LoginByLdap(loginId string, password string) (*Result, *AppError) { m := make(map[string]string) m["login_id"] = loginId m["password"] = password m["ldap_only"] = "true" return c.login(m) } // LoginWithDevice authenticates a user by login id (username, email or some sort // of SSO identifier based on configuration), password and attaches a device id to // the session. func (c *Client) LoginWithDevice(loginId string, password string, deviceId string) (*Result, *AppError) { m := make(map[string]string) m["login_id"] = loginId m["password"] = password m["device_id"] = deviceId return c.login(m) } func (c *Client) login(m map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/login", MapToJson(m)); err != nil { return nil, err } else { c.AuthToken = r.Header.Get(HEADER_TOKEN) c.AuthType = HEADER_BEARER sessionToken := getCookie(SESSION_COOKIE_TOKEN, r) if c.AuthToken != sessionToken.Value { NewLocAppError("/users/login", "model.client.login.app_error", nil, "") } defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } // Logout terminates the current user's session. func (c *Client) Logout() (*Result, *AppError) { if r, err := c.DoApiPost("/users/logout", ""); err != nil { return nil, err } else { c.AuthToken = "" c.AuthType = HEADER_BEARER c.TeamId = "" defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // CheckMfa returns a map with key "mfa_required" with the string value "true" or "false", // indicating whether MFA is required to log the user in, based on a provided login id // (username, email or some sort of SSO identifier based on configuration). func (c *Client) CheckMfa(loginId string) (*Result, *AppError) { m := make(map[string]string) m["login_id"] = loginId if r, err := c.DoApiPost("/users/mfa", MapToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // GenerateMfaSecret returns a QR code image containing the secret, to be scanned // by a multi-factor authentication mobile application. It also returns the secret // for manual entry. Must be authenticated. func (c *Client) GenerateMfaSecret() (*Result, *AppError) { if r, err := c.DoApiGet("/users/generate_mfa_secret", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // UpdateMfa activates multi-factor authenticates for the current user if activate // is true and a valid token is provided. If activate is false, then token is not // required and multi-factor authentication is disabled for the current user. func (c *Client) UpdateMfa(activate bool, token string) (*Result, *AppError) { m := make(map[string]interface{}) m["activate"] = activate m["token"] = token if r, err := c.DoApiPost("/users/update_mfa", StringInterfaceToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) AdminResetMfa(userId string) (*Result, *AppError) { m := make(map[string]string) m["user_id"] = userId if r, err := c.DoApiPost("/admin/reset_mfa", MapToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) RevokeSession(sessionAltId string) (*Result, *AppError) { m := make(map[string]string) m["id"] = sessionAltId if r, err := c.DoApiPost("/users/revoke_session", MapToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) GetSessions(id string) (*Result, *AppError) { if r, err := c.DoApiGet("/users/"+id+"/sessions", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), SessionsFromJson(r.Body)}, nil } } func (c *Client) EmailToOAuth(m map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/claim/email_to_oauth", MapToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) OAuthToEmail(m map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/claim/oauth_to_email", MapToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) LDAPToEmail(m map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/claim/ldap_to_email", MapToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) EmailToLDAP(m map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/claim/ldap_to_email", MapToJson(m)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) Command(channelId string, command string) (*Result, *AppError) { args := &CommandArgs{ChannelId: channelId, Command: command} if r, err := c.DoApiPost(c.GetTeamRoute()+"/commands/execute", args.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), CommandResponseFromJson(r.Body)}, nil } } func (c *Client) ListCommands() (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/commands/list", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), CommandListFromJson(r.Body)}, nil } } func (c *Client) ListTeamCommands() (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/commands/list_team_commands", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), CommandListFromJson(r.Body)}, nil } } func (c *Client) CreateCommand(cmd *Command) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/commands/create", cmd.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), CommandFromJson(r.Body)}, nil } } func (c *Client) UpdateCommand(cmd *Command) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/commands/update", cmd.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), CommandFromJson(r.Body)}, nil } } func (c *Client) RegenCommandToken(data map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/commands/regen_token", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), CommandFromJson(r.Body)}, nil } } func (c *Client) DeleteCommand(data map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/commands/delete", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) GetAudits(id string, etag string) (*Result, *AppError) { if r, err := c.DoApiGet("/users/"+id+"/audits", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), AuditsFromJson(r.Body)}, nil } } func (c *Client) GetLogs() (*Result, *AppError) { if r, err := c.DoApiGet("/admin/logs", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ArrayFromJson(r.Body)}, nil } } func (c *Client) GetClusterStatus() ([]*ClusterInfo, *AppError) { if r, err := c.DoApiGet("/admin/cluster_status", "", ""); err != nil { return nil, err } else { defer closeBody(r) return ClusterInfosFromJson(r.Body), nil } } // GetRecentlyActiveUsers returns a map of users including lastActivityAt using user id as the key func (c *Client) GetRecentlyActiveUsers(teamId string) (*Result, *AppError) { if r, err := c.DoApiGet("/admin/recently_active_users/"+teamId, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserMapFromJson(r.Body)}, nil } } func (c *Client) GetAllAudits() (*Result, *AppError) { if r, err := c.DoApiGet("/admin/audits", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), AuditsFromJson(r.Body)}, nil } } func (c *Client) GetConfig() (*Result, *AppError) { if r, err := c.DoApiGet("/admin/config", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ConfigFromJson(r.Body)}, nil } } // ReloadConfig will reload the config.json file from disk. Properties // requiring a server restart will still need a server restart. You must // have the system admin role to call this method. It will return status=OK // if it's successfully reloaded the config file, otherwise check the returned error. func (c *Client) ReloadConfig() (bool, *AppError) { c.clearExtraProperties() if r, err := c.DoApiGet("/admin/reload_config", "", ""); err != nil { return false, err } else { c.fillInExtraProperties(r) return c.CheckStatusOK(r), nil } } func (c *Client) InvalidateAllCaches() (bool, *AppError) { c.clearExtraProperties() if r, err := c.DoApiGet("/admin/invalidate_all_caches", "", ""); err != nil { return false, err } else { c.fillInExtraProperties(r) return c.CheckStatusOK(r), nil } } func (c *Client) SaveConfig(config *Config) (*Result, *AppError) { if r, err := c.DoApiPost("/admin/save_config", config.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // RecycleDatabaseConnection will attempt to recycle the database connections. // You must have the system admin role to call this method. It will return status=OK // if it's successfully recycled the connections, otherwise check the returned error. func (c *Client) RecycleDatabaseConnection() (bool, *AppError) { c.clearExtraProperties() if r, err := c.DoApiGet("/admin/recycle_db_conn", "", ""); err != nil { return false, err } else { c.fillInExtraProperties(r) return c.CheckStatusOK(r), nil } } func (c *Client) TestEmail(config *Config) (*Result, *AppError) { if r, err := c.DoApiPost("/admin/test_email", config.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // TestLdap will run a connection test on the current LDAP settings. // It will return the standard OK response if settings work. Otherwise // it will return an appropriate error. func (c *Client) TestLdap(config *Config) (*Result, *AppError) { if r, err := c.DoApiPost("/admin/ldap_test", config.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) GetComplianceReports() (*Result, *AppError) { if r, err := c.DoApiGet("/admin/compliance_reports", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), CompliancesFromJson(r.Body)}, nil } } func (c *Client) SaveComplianceReport(job *Compliance) (*Result, *AppError) { if r, err := c.DoApiPost("/admin/save_compliance_report", job.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ComplianceFromJson(r.Body)}, nil } } func (c *Client) DownloadComplianceReport(id string) (*Result, *AppError) { var rq *http.Request rq, _ = http.NewRequest("GET", c.ApiUrl+"/admin/download_compliance_report/"+id, nil) rq.Close = true if len(c.AuthToken) > 0 { rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken) } if rp, err := c.HttpClient.Do(rq); err != nil { return nil, NewLocAppError("/admin/download_compliance_report", "model.client.connecting.app_error", nil, err.Error()) } else if rp.StatusCode >= 300 { defer rp.Body.Close() return nil, AppErrorFromJson(rp.Body) } else { defer closeBody(rp) return &Result{rp.Header.Get(HEADER_REQUEST_ID), rp.Header.Get(HEADER_ETAG_SERVER), rp.Body}, nil } } func (c *Client) GetTeamAnalytics(teamId, name string) (*Result, *AppError) { if r, err := c.DoApiGet("/admin/analytics/"+teamId+"/"+name, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), AnalyticsRowsFromJson(r.Body)}, nil } } func (c *Client) GetSystemAnalytics(name string) (*Result, *AppError) { if r, err := c.DoApiGet("/admin/analytics/"+name, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), AnalyticsRowsFromJson(r.Body)}, nil } } // Initiate immediate synchronization of LDAP users. // The synchronization will be performed asynchronously and this function will // always return OK unless you don't have permissions. // You must be the system administrator to use this function. func (c *Client) LdapSyncNow() (*Result, *AppError) { if r, err := c.DoApiPost("/admin/ldap_sync_now", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) CreateChannel(channel *Channel) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/create", channel.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil } } func (c *Client) CreateDirectChannel(userId string) (*Result, *AppError) { data := make(map[string]string) data["user_id"] = userId if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/create_direct", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil } } func (c *Client) CreateGroupChannel(userIds []string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/create_group", ArrayToJson(userIds)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil } } func (c *Client) UpdateChannel(channel *Channel) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/update", channel.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil } } func (c *Client) UpdateChannelHeader(data map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/update_header", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil } } func (c *Client) UpdateChannelPurpose(data map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/update_purpose", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil } } func (c *Client) UpdateNotifyProps(data map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/update_notify_props", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) GetMyChannelMembers() (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/channels/members", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelMembersFromJson(r.Body)}, nil } } func (c *Client) GetChannel(id, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(id)+"/", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelDataFromJson(r.Body)}, nil } } // SCHEDULED FOR DEPRECATION IN 3.7 - use GetMoreChannelsPage instead func (c *Client) GetMoreChannels(etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/channels/more", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelListFromJson(r.Body)}, nil } } // GetMoreChannelsPage will return a page of open channels the user is not in based on // the provided offset and limit. Must be authenticated. func (c *Client) GetMoreChannelsPage(offset int, limit int) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf(c.GetTeamRoute()+"/channels/more/%v/%v", offset, limit), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelListFromJson(r.Body)}, nil } } // SearchMoreChannels will return a list of open channels the user is not in, that matches // the search criteria provided. Must be authenticated. func (c *Client) SearchMoreChannels(channelSearch ChannelSearch) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/more/search", channelSearch.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelListFromJson(r.Body)}, nil } } // AutocompleteChannels will return a list of open channels that match the provided // string. Must be authenticated. func (c *Client) AutocompleteChannels(term string) (*Result, *AppError) { url := fmt.Sprintf("%s/channels/autocomplete?term=%s", c.GetTeamRoute(), url.QueryEscape(term)) if r, err := c.DoApiGet(url, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelListFromJson(r.Body)}, nil } } func (c *Client) GetChannelCounts(etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/channels/counts", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelCountsFromJson(r.Body)}, nil } } func (c *Client) GetChannels(etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/channels/", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelListFromJson(r.Body)}, nil } } func (c *Client) GetChannelByName(channelName string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelNameRoute(channelName), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelFromJson(r.Body)}, nil } } func (c *Client) JoinChannel(id string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(id)+"/join", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } func (c *Client) JoinChannelByName(name string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelNameRoute(name)+"/join", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } func (c *Client) LeaveChannel(id string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(id)+"/leave", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } func (c *Client) DeleteChannel(id string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(id)+"/delete", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } func (c *Client) AddChannelMember(id, user_id string) (*Result, *AppError) { data := make(map[string]string) data["user_id"] = user_id if r, err := c.DoApiPost(c.GetChannelRoute(id)+"/add", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } func (c *Client) RemoveChannelMember(id, user_id string) (*Result, *AppError) { data := make(map[string]string) data["user_id"] = user_id if r, err := c.DoApiPost(c.GetChannelRoute(id)+"/remove", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } // UpdateLastViewedAt will mark a channel as read. // The channelId indicates the channel to mark as read. If active is true, push notifications // will be cleared if there are unread messages. The default for active is true. // SCHEDULED FOR DEPRECATION IN 3.8 - use ViewChannel instead func (c *Client) UpdateLastViewedAt(channelId string, active bool) (*Result, *AppError) { data := make(map[string]interface{}) data["active"] = active if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+"/update_last_viewed_at", StringInterfaceToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } // ViewChannel performs all the actions related to viewing a channel. This includes marking // the channel and the previous one as read, and marking the channel as being actively viewed. // ChannelId is required but may be blank to indicate no channel is being viewed. // PrevChannelId is optional, populate to indicate a channel switch occurred. func (c *Client) ViewChannel(params ChannelView) (bool, *ResponseMetadata) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/channels/view", params.ToJson()); err != nil { return false, &ResponseMetadata{StatusCode: r.StatusCode, Error: err} } else { return c.CheckStatusOK(r), &ResponseMetadata{ StatusCode: r.StatusCode, RequestId: r.Header.Get(HEADER_REQUEST_ID), Etag: r.Header.Get(HEADER_ETAG_SERVER), } } } func (c *Client) GetChannelStats(id string, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(id)+"/stats", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelStatsFromJson(r.Body)}, nil } } func (c *Client) GetChannelMember(channelId string, userId string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+"/members/"+userId, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelMemberFromJson(r.Body)}, nil } } // GetChannelMembersByIds will return channel member objects as an array based on the // channel id and a list of user ids provided. Must be authenticated. func (c *Client) GetChannelMembersByIds(channelId string, userIds []string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+"/members/ids", ArrayToJson(userIds)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), ChannelMembersFromJson(r.Body)}, nil } } func (c *Client) CreatePost(post *Post) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(post.ChannelId)+"/posts/create", post.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostFromJson(r.Body)}, nil } } func (c *Client) UpdatePost(post *Post) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(post.ChannelId)+"/posts/update", post.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostFromJson(r.Body)}, nil } } func (c *Client) GetPosts(channelId string, offset int, limit int, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/page/%v/%v", offset, limit), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } func (c *Client) GetPostsSince(channelId string, time int64) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/since/%v", time), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } func (c *Client) GetPostsBefore(channelId string, postid string, offset int, limit int, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/before/%v/%v", postid, offset, limit), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } func (c *Client) GetPostsAfter(channelId string, postid string, offset int, limit int, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf(c.GetChannelRoute(channelId)+"/posts/%v/after/%v/%v", postid, offset, limit), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } func (c *Client) GetPost(channelId string, postId string, etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/get", postId), "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } // GetPostById returns a post and any posts in the same thread by post id func (c *Client) GetPostById(postId string, etag string) (*PostList, *ResponseMetadata) { if r, err := c.DoApiGet(c.GetTeamRoute()+fmt.Sprintf("/posts/%v", postId), "", etag); err != nil { return nil, &ResponseMetadata{StatusCode: r.StatusCode, Error: err} } else { defer closeBody(r) return PostListFromJson(r.Body), &ResponseMetadata{ StatusCode: r.StatusCode, RequestId: r.Header.Get(HEADER_REQUEST_ID), Etag: r.Header.Get(HEADER_ETAG_SERVER), } } } // GetPermalink returns a post list, based on the provided channel and post ID. func (c *Client) GetPermalink(channelId string, postId string, etag string) (*PostList, *ResponseMetadata) { if r, err := c.DoApiGet(c.GetTeamRoute()+fmt.Sprintf("/pltmp/%v", postId), "", etag); err != nil { return nil, &ResponseMetadata{StatusCode: r.StatusCode, Error: err} } else { defer closeBody(r) return PostListFromJson(r.Body), &ResponseMetadata{ StatusCode: r.StatusCode, RequestId: r.Header.Get(HEADER_REQUEST_ID), Etag: r.Header.Get(HEADER_ETAG_SERVER), } } } func (c *Client) DeletePost(channelId string, postId string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/delete", postId), ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) SearchPosts(terms string, isOrSearch bool) (*Result, *AppError) { data := map[string]interface{}{} data["terms"] = terms data["is_or_search"] = isOrSearch if r, err := c.DoApiPost(c.GetTeamRoute()+"/posts/search", StringInterfaceToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } // GetFlaggedPosts will return a post list of posts that have been flagged by the user. // The page is set by the integer parameters offset and limit. func (c *Client) GetFlaggedPosts(offset int, limit int) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+fmt.Sprintf("/posts/flagged/%v/%v", offset, limit), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } func (c *Client) GetPinnedPosts(channelId string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+"/pinned", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostListFromJson(r.Body)}, nil } } func (c *Client) UploadProfileFile(data []byte, contentType string) (*Result, *AppError) { return c.uploadFile(c.ApiUrl+"/users/newimage", data, contentType) } func (c *Client) UploadPostAttachment(data []byte, channelId string, filename string) (*FileUploadResponse, *AppError) { c.clearExtraProperties() body := &bytes.Buffer{} writer := multipart.NewWriter(body) if part, err := writer.CreateFormFile("files", filename); err != nil { return nil, NewLocAppError("UploadPostAttachment", "model.client.upload_post_attachment.file.app_error", nil, err.Error()) } else if _, err = io.Copy(part, bytes.NewBuffer(data)); err != nil { return nil, NewLocAppError("UploadPostAttachment", "model.client.upload_post_attachment.file.app_error", nil, err.Error()) } if part, err := writer.CreateFormField("channel_id"); err != nil { return nil, NewLocAppError("UploadPostAttachment", "model.client.upload_post_attachment.channel_id.app_error", nil, err.Error()) } else if _, err = io.Copy(part, strings.NewReader(channelId)); err != nil { return nil, NewLocAppError("UploadPostAttachment", "model.client.upload_post_attachment.channel_id.app_error", nil, err.Error()) } if err := writer.Close(); err != nil { return nil, NewLocAppError("UploadPostAttachment", "model.client.upload_post_attachment.writer.app_error", nil, err.Error()) } if result, err := c.uploadFile(c.ApiUrl+c.GetTeamRoute()+"/files/upload", body.Bytes(), writer.FormDataContentType()); err != nil { return nil, err } else { return result.Data.(*FileUploadResponse), nil } } func (c *Client) uploadFile(url string, data []byte, contentType string) (*Result, *AppError) { rq, _ := http.NewRequest("POST", url, bytes.NewReader(data)) rq.Header.Set("Content-Type", contentType) rq.Close = true if len(c.AuthToken) > 0 { rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken) } if rp, err := c.HttpClient.Do(rq); err != nil { return nil, NewLocAppError(url, "model.client.connecting.app_error", nil, err.Error()) } else if rp.StatusCode >= 300 { return nil, AppErrorFromJson(rp.Body) } else { defer closeBody(rp) return &Result{rp.Header.Get(HEADER_REQUEST_ID), rp.Header.Get(HEADER_ETAG_SERVER), FileUploadResponseFromJson(rp.Body)}, nil } } func (c *Client) GetFile(fileId string) (io.ReadCloser, *AppError) { if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/get", "", ""); err != nil { return nil, err } else { c.fillInExtraProperties(r) return r.Body, nil } } func (c *Client) GetFileThumbnail(fileId string) (io.ReadCloser, *AppError) { if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/get_thumbnail", "", ""); err != nil { return nil, err } else { c.fillInExtraProperties(r) return r.Body, nil } } func (c *Client) GetFilePreview(fileId string) (io.ReadCloser, *AppError) { if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/get_preview", "", ""); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return r.Body, nil } } func (c *Client) GetFileInfo(fileId string) (*FileInfo, *AppError) { if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/get_info", "", ""); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return FileInfoFromJson(r.Body), nil } } func (c *Client) GetPublicLink(fileId string) (string, *AppError) { if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/get_public_link", "", ""); err != nil { return "", err } else { defer closeBody(r) c.fillInExtraProperties(r) return StringFromJson(r.Body), nil } } func (c *Client) UpdateUser(user *User) (*Result, *AppError) { if r, err := c.DoApiPost("/users/update", user.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } func (c *Client) UpdateUserRoles(userId string, roles string) (*Result, *AppError) { data := make(map[string]string) data["new_roles"] = roles if r, err := c.DoApiPost(c.GetUserRequiredRoute(userId)+"/update_roles", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) UpdateTeamRoles(userId string, roles string) (*Result, *AppError) { data := make(map[string]string) data["new_roles"] = roles data["user_id"] = userId if r, err := c.DoApiPost(c.GetTeamRoute()+"/update_member_roles", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) AttachDeviceId(deviceId string) (*Result, *AppError) { data := make(map[string]string) data["device_id"] = deviceId if r, err := c.DoApiPost("/users/attach_device", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } func (c *Client) UpdateActive(userId string, active bool) (*Result, *AppError) { data := make(map[string]string) data["user_id"] = userId data["active"] = strconv.FormatBool(active) if r, err := c.DoApiPost("/users/update_active", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } func (c *Client) UpdateUserNotify(data map[string]string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/update_notify", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), UserFromJson(r.Body)}, nil } } func (c *Client) UpdateUserPassword(userId, currentPassword, newPassword string) (*Result, *AppError) { data := make(map[string]string) data["current_password"] = currentPassword data["new_password"] = newPassword data["user_id"] = userId if r, err := c.DoApiPost("/users/newpassword", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) SendPasswordReset(email string) (*Result, *AppError) { data := map[string]string{} data["email"] = email if r, err := c.DoApiPost("/users/send_password_reset", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) ResetPassword(code, newPassword string) (*Result, *AppError) { data := map[string]string{} data["code"] = code data["new_password"] = newPassword if r, err := c.DoApiPost("/users/reset_password", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) AdminResetPassword(userId, newPassword string) (*Result, *AppError) { data := map[string]string{} data["user_id"] = userId data["new_password"] = newPassword if r, err := c.DoApiPost("/admin/reset_password", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // GetStatuses returns a map of string statuses using user id as the key func (c *Client) GetStatuses() (*Result, *AppError) { if r, err := c.DoApiGet("/users/status", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // GetStatusesByIds returns a map of string statuses using user id as the key, // based on the provided user ids func (c *Client) GetStatusesByIds(userIds []string) (*Result, *AppError) { if r, err := c.DoApiPost("/users/status/ids", ArrayToJson(userIds)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // SetActiveChannel sets the the channel id the user is currently viewing. // The channelId key is required but the value can be blank. Returns standard // response. // SCHEDULED FOR DEPRECATION IN 3.8 - use ViewChannel instead func (c *Client) SetActiveChannel(channelId string) (*Result, *AppError) { data := map[string]string{} data["channel_id"] = channelId if r, err := c.DoApiPost("/users/status/set_active_channel", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) GetMyTeam(etag string) (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/me", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamFromJson(r.Body)}, nil } } // GetTeamMembers will return a page of team member objects as an array paged based on the // team id, offset and limit provided. Must be authenticated. func (c *Client) GetTeamMembers(teamId string, offset int, limit int) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf("/teams/%v/members/%v/%v", teamId, offset, limit), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamMembersFromJson(r.Body)}, nil } } // GetMyTeamMembers will return an array with team member objects that the current user // is a member of. Must be authenticated. func (c *Client) GetMyTeamMembers() (*Result, *AppError) { if r, err := c.DoApiGet("/teams/members", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamMembersFromJson(r.Body)}, nil } } // GetMyTeamsUnread will return an array with TeamUnread objects that contain the amount of // unread messages and mentions the current user has for the teams it belongs to. // An optional team ID can be set to exclude that team from the results. Must be authenticated. func (c *Client) GetMyTeamsUnread(teamId string) (*Result, *AppError) { endpoint := "/teams/unread" if teamId != "" { endpoint += fmt.Sprintf("?id=%s", url.QueryEscape(teamId)) } if r, err := c.DoApiGet(endpoint, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamsUnreadFromJson(r.Body)}, nil } } // GetTeamMember will return a team member object based on the team id and user id provided. // Must be authenticated. func (c *Client) GetTeamMember(teamId string, userId string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf("/teams/%v/members/%v", teamId, userId), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamMemberFromJson(r.Body)}, nil } } // GetTeamStats will return a team stats object containing the number of users on the team // based on the team id provided. Must be authenticated. func (c *Client) GetTeamStats(teamId string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf("/teams/%v/stats", teamId), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamStatsFromJson(r.Body)}, nil } } // GetTeamStats will return a team stats object containing the number of users on the team // based on the team id provided. Must be authenticated. func (c *Client) GetTeamByName(teamName string) (*Result, *AppError) { if r, err := c.DoApiGet(fmt.Sprintf("/teams/name/%v", teamName), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamStatsFromJson(r.Body)}, nil } } // GetTeamMembersByIds will return team member objects as an array based on the // team id and a list of user ids provided. Must be authenticated. func (c *Client) GetTeamMembersByIds(teamId string, userIds []string) (*Result, *AppError) { if r, err := c.DoApiPost(fmt.Sprintf("/teams/%v/members/ids", teamId), ArrayToJson(userIds)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), TeamMembersFromJson(r.Body)}, nil } } // RegisterApp creates a new OAuth2 app to be used with the OAuth2 Provider. On success // it returns the created app. Must be authenticated as a user. func (c *Client) RegisterApp(app *OAuthApp) (*Result, *AppError) { if r, err := c.DoApiPost("/oauth/register", app.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OAuthAppFromJson(r.Body)}, nil } } // AllowOAuth allows a new session by an OAuth2 App. On success // it returns the url to be redirected back to the app which initiated the oauth2 flow. // Must be authenticated as a user. func (c *Client) AllowOAuth(rspType, clientId, redirect, scope, state string) (*Result, *AppError) { if r, err := c.DoApiGet("/oauth/allow?response_type="+rspType+"&client_id="+clientId+"&redirect_uri="+url.QueryEscape(redirect)+"&scope="+scope+"&state="+url.QueryEscape(state), "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // GetOAuthAppsByUser returns the OAuth2 Apps registered by the user. On success // it returns a list of OAuth2 Apps from the same user or all the registered apps if the user // is a System Administrator. Must be authenticated as a user. func (c *Client) GetOAuthAppsByUser() (*Result, *AppError) { if r, err := c.DoApiGet("/oauth/list", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OAuthAppListFromJson(r.Body)}, nil } } // GetOAuthAppInfo lookup an OAuth2 App using the client_id. On success // it returns a Sanitized OAuth2 App. Must be authenticated as a user. func (c *Client) GetOAuthAppInfo(clientId string) (*Result, *AppError) { if r, err := c.DoApiGet("/oauth/app/"+clientId, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OAuthAppFromJson(r.Body)}, nil } } // DeleteOAuthApp deletes an OAuth2 app, the app must be deleted by the same user who created it or // a System Administrator. On success returs Status OK. Must be authenticated as a user. func (c *Client) DeleteOAuthApp(id string) (*Result, *AppError) { data := make(map[string]string) data["id"] = id if r, err := c.DoApiPost("/oauth/delete", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } // GetOAuthAuthorizedApps returns the OAuth2 Apps authorized by the user. On success // it returns a list of sanitized OAuth2 Authorized Apps by the user. func (c *Client) GetOAuthAuthorizedApps() (*Result, *AppError) { if r, err := c.DoApiGet("/oauth/authorized", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OAuthAppListFromJson(r.Body)}, nil } } // OAuthDeauthorizeApp deauthorize a user an OAuth 2.0 app. On success // it returns status OK or an AppError on fail. func (c *Client) OAuthDeauthorizeApp(clientId string) *AppError { if r, err := c.DoApiPost("/oauth/"+clientId+"/deauthorize", ""); err != nil { return err } else { defer closeBody(r) return nil } } // RegenerateOAuthAppSecret generates a new OAuth App Client Secret. On success // it returns an OAuth2 App. Must be authenticated as a user and the same user who // registered the app or a System Admin. func (c *Client) RegenerateOAuthAppSecret(clientId string) (*Result, *AppError) { if r, err := c.DoApiPost("/oauth/"+clientId+"/regen_secret", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OAuthAppFromJson(r.Body)}, nil } } func (c *Client) GetAccessToken(data url.Values) (*Result, *AppError) { if r, err := c.DoPost("/oauth/access_token", data.Encode(), "application/x-www-form-urlencoded"); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), AccessResponseFromJson(r.Body)}, nil } } func (c *Client) CreateIncomingWebhook(hook *IncomingWebhook) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/incoming/create", hook.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), IncomingWebhookFromJson(r.Body)}, nil } } func (c *Client) UpdateIncomingWebhook(hook *IncomingWebhook) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/incoming/update", hook.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), IncomingWebhookFromJson(r.Body)}, nil } } func (c *Client) PostToWebhook(id, payload string) (*Result, *AppError) { if r, err := c.DoPost("/hooks/"+id, payload, "application/x-www-form-urlencoded"); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), nil}, nil } } func (c *Client) DeleteIncomingWebhook(id string) (*Result, *AppError) { data := make(map[string]string) data["id"] = id if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/incoming/delete", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) ListIncomingWebhooks() (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/hooks/incoming/list", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), IncomingWebhookListFromJson(r.Body)}, nil } } func (c *Client) GetAllPreferences() (*Result, *AppError) { if r, err := c.DoApiGet("/preferences/", "", ""); err != nil { return nil, err } else { defer closeBody(r) preferences, _ := PreferencesFromJson(r.Body) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), preferences}, nil } } func (c *Client) SetPreferences(preferences *Preferences) (*Result, *AppError) { if r, err := c.DoApiPost("/preferences/save", preferences.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), preferences}, nil } } func (c *Client) GetPreference(category string, name string) (*Result, *AppError) { if r, err := c.DoApiGet("/preferences/"+category+"/"+name, "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PreferenceFromJson(r.Body)}, nil } } func (c *Client) GetPreferenceCategory(category string) (*Result, *AppError) { if r, err := c.DoApiGet("/preferences/"+category, "", ""); err != nil { return nil, err } else { defer closeBody(r) preferences, _ := PreferencesFromJson(r.Body) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), preferences}, nil } } // DeletePreferences deletes a list of preferences owned by the current user. If successful, // it will return status=ok. Otherwise, an error will be returned. func (c *Client) DeletePreferences(preferences *Preferences) (bool, *AppError) { if r, err := c.DoApiPost("/preferences/delete", preferences.ToJson()); err != nil { return false, err } else { return c.CheckStatusOK(r), nil } } func (c *Client) CreateOutgoingWebhook(hook *OutgoingWebhook) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/outgoing/create", hook.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OutgoingWebhookFromJson(r.Body)}, nil } } func (c *Client) UpdateOutgoingWebhook(hook *OutgoingWebhook) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/outgoing/update", hook.ToJson()); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OutgoingWebhookFromJson(r.Body)}, nil } } func (c *Client) DeleteOutgoingWebhook(id string) (*Result, *AppError) { data := make(map[string]string) data["id"] = id if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/outgoing/delete", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) ListOutgoingWebhooks() (*Result, *AppError) { if r, err := c.DoApiGet(c.GetTeamRoute()+"/hooks/outgoing/list", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OutgoingWebhookListFromJson(r.Body)}, nil } } func (c *Client) RegenOutgoingWebhookToken(id string) (*Result, *AppError) { data := make(map[string]string) data["id"] = id if r, err := c.DoApiPost(c.GetTeamRoute()+"/hooks/outgoing/regen_token", MapToJson(data)); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), OutgoingWebhookFromJson(r.Body)}, nil } } func (c *Client) MockSession(sessionToken string) { c.AuthToken = sessionToken c.AuthType = HEADER_BEARER } func (c *Client) GetClientLicenceConfig(etag string) (*Result, *AppError) { if r, err := c.DoApiGet("/license/client_config", "", etag); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), MapFromJson(r.Body)}, nil } } func (c *Client) GetInitialLoad() (*Result, *AppError) { if r, err := c.DoApiGet("/users/initial_load", "", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), InitialLoadFromJson(r.Body)}, nil } } // ListEmoji returns a list of all user-created emoji for the server. func (c *Client) ListEmoji() ([]*Emoji, *AppError) { if r, err := c.DoApiGet(c.GetEmojiRoute()+"/list", "", ""); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return EmojiListFromJson(r.Body), nil } } // CreateEmoji will save an emoji to the server if the current user has permission // to do so. If successful, the provided emoji will be returned with its Id field // filled in. Otherwise, an error will be returned. func (c *Client) CreateEmoji(emoji *Emoji, image []byte, filename string) (*Emoji, *AppError) { c.clearExtraProperties() body := &bytes.Buffer{} writer := multipart.NewWriter(body) if part, err := writer.CreateFormFile("image", filename); err != nil { return nil, NewLocAppError("CreateEmoji", "model.client.create_emoji.image.app_error", nil, err.Error()) } else if _, err = io.Copy(part, bytes.NewBuffer(image)); err != nil { return nil, NewLocAppError("CreateEmoji", "model.client.create_emoji.image.app_error", nil, err.Error()) } if err := writer.WriteField("emoji", emoji.ToJson()); err != nil { return nil, NewLocAppError("CreateEmoji", "model.client.create_emoji.emoji.app_error", nil, err.Error()) } if err := writer.Close(); err != nil { return nil, NewLocAppError("CreateEmoji", "model.client.create_emoji.writer.app_error", nil, err.Error()) } rq, _ := http.NewRequest("POST", c.ApiUrl+c.GetEmojiRoute()+"/create", body) rq.Header.Set("Content-Type", writer.FormDataContentType()) rq.Close = true if len(c.AuthToken) > 0 { rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken) } if r, err := c.HttpClient.Do(rq); err != nil { return nil, NewLocAppError("CreateEmoji", "model.client.connecting.app_error", nil, err.Error()) } else if r.StatusCode >= 300 { return nil, AppErrorFromJson(r.Body) } else { defer closeBody(r) c.fillInExtraProperties(r) return EmojiFromJson(r.Body), nil } } // DeleteEmoji will delete an emoji from the server if the current user has permission // to do so. If successful, it will return status=ok. Otherwise, an error will be returned. func (c *Client) DeleteEmoji(id string) (bool, *AppError) { data := map[string]string{"id": id} if r, err := c.DoApiPost(c.GetEmojiRoute()+"/delete", MapToJson(data)); err != nil { return false, err } else { defer closeBody(r) c.fillInExtraProperties(r) return c.CheckStatusOK(r), nil } } // GetCustomEmojiImageUrl returns the API route that can be used to get the image used by // the given emoji. func (c *Client) GetCustomEmojiImageUrl(id string) string { return c.GetEmojiRoute() + "/" + id } // Uploads a x509 base64 Certificate or Private Key file to be used with SAML. // data byte array is required and needs to be a Multi-Part with 'certificate' as the field name // contentType is also required. Returns nil if succesful, otherwise returns an AppError func (c *Client) UploadCertificateFile(data []byte, contentType string) *AppError { url := c.ApiUrl + "/admin/add_certificate" rq, _ := http.NewRequest("POST", url, bytes.NewReader(data)) rq.Header.Set("Content-Type", contentType) rq.Close = true if len(c.AuthToken) > 0 { rq.Header.Set(HEADER_AUTH, "BEARER "+c.AuthToken) } if rp, err := c.HttpClient.Do(rq); err != nil { return NewLocAppError(url, "model.client.connecting.app_error", nil, err.Error()) } else if rp.StatusCode >= 300 { return AppErrorFromJson(rp.Body) } else { defer closeBody(rp) c.fillInExtraProperties(rp) return nil } } // Removes a x509 base64 Certificate or Private Key file used with SAML. // filename is required. Returns nil if successful, otherwise returns an AppError func (c *Client) RemoveCertificateFile(filename string) *AppError { if r, err := c.DoApiPost("/admin/remove_certificate", MapToJson(map[string]string{"filename": filename})); err != nil { return err } else { defer closeBody(r) c.fillInExtraProperties(r) return nil } } // Checks if the x509 base64 Certificates and Private Key files used with SAML exists on the file system. // Returns a map[string]interface{} if successful, otherwise returns an AppError. Must be System Admin authenticated. func (c *Client) SamlCertificateStatus(filename string) (map[string]interface{}, *AppError) { if r, err := c.DoApiGet("/admin/remove_certificate", "", ""); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return StringInterfaceFromJson(r.Body), nil } } // GetWebrtcToken if Successful returns a map with a valid token, stun server and turn server with credentials to use with // the Mattermost WebRTC service, otherwise returns an AppError. Must be authenticated user. func (c *Client) GetWebrtcToken() (map[string]string, *AppError) { if r, err := c.DoApiPost("/webrtc/token", ""); err != nil { return nil, err } else { defer closeBody(r) return MapFromJson(r.Body), nil } } // GetFileInfosForPost returns a list of FileInfo objects for a given post id, if successful. // Otherwise, it returns an error. func (c *Client) GetFileInfosForPost(channelId string, postId string, etag string) ([]*FileInfo, *AppError) { c.clearExtraProperties() if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/get_file_infos", postId), "", etag); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return FileInfosFromJson(r.Body), nil } } // Saves an emoji reaction for a post in the given channel. Returns the saved reaction if successful, otherwise returns an AppError. func (c *Client) SaveReaction(channelId string, reaction *Reaction) (*Reaction, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/reactions/save", reaction.PostId), reaction.ToJson()); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return ReactionFromJson(r.Body), nil } } // Removes an emoji reaction for a post in the given channel. Returns nil if successful, otherwise returns an AppError. func (c *Client) DeleteReaction(channelId string, reaction *Reaction) *AppError { if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/reactions/delete", reaction.PostId), reaction.ToJson()); err != nil { return err } else { defer closeBody(r) c.fillInExtraProperties(r) return nil } } // Lists all emoji reactions made for the given post in the given channel. Returns a list of Reactions if successful, otherwise returns an AppError. func (c *Client) ListReactions(channelId string, postId string) ([]*Reaction, *AppError) { if r, err := c.DoApiGet(c.GetChannelRoute(channelId)+fmt.Sprintf("/posts/%v/reactions", postId), "", ""); err != nil { return nil, err } else { defer closeBody(r) c.fillInExtraProperties(r) return ReactionsFromJson(r.Body), nil } } // Updates the user's roles in the channel by replacing them with the roles provided. func (c *Client) UpdateChannelRoles(channelId string, userId string, roles string) (map[string]string, *ResponseMetadata) { data := make(map[string]string) data["new_roles"] = roles data["user_id"] = userId if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+"/update_member_roles", MapToJson(data)); err != nil { metadata := ResponseMetadata{Error: err} if r != nil { metadata.StatusCode = r.StatusCode } return nil, &metadata } else { defer closeBody(r) return MapFromJson(r.Body), &ResponseMetadata{ StatusCode: r.StatusCode, RequestId: r.Header.Get(HEADER_REQUEST_ID), Etag: r.Header.Get(HEADER_ETAG_SERVER), } } } func (c *Client) PinPost(channelId string, postId string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+"/posts/"+postId+"/pin", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostFromJson(r.Body)}, nil } } func (c *Client) UnpinPost(channelId string, postId string) (*Result, *AppError) { if r, err := c.DoApiPost(c.GetChannelRoute(channelId)+"/posts/"+postId+"/unpin", ""); err != nil { return nil, err } else { defer closeBody(r) return &Result{r.Header.Get(HEADER_REQUEST_ID), r.Header.Get(HEADER_ETAG_SERVER), PostFromJson(r.Body)}, nil } }
asaadmahmoodspin/platform
model/client.go
GO
agpl-3.0
84,229
require 'spec_helper' describe Queries::SignaturesExport do subject { Queries::SignaturesExport.new(petition_id: petition_id) } let(:petition_id) { '1' } it "should have generate some SQL" do subject.sql.should start_with("SELECT") end context "with objects" do let(:petition) { FactoryGirl.create(:petition) } let(:petition_id) { petition.id } let!(:signature) { FactoryGirl.create(:signature, petition: petition) } before(:each) do @result = "" subject.as_csv_stream.each do |chunk| @result << chunk end end context "when parsed" do before(:each) do @parsed = CSV.parse(@result) end describe "header" do let(:header) { @parsed[0] } specify{ header.should include("email")} end describe "first row" do let(:first_row) { @parsed[1] } specify{ first_row.should include(signature.email)} end end end end
MayOneUS/victorykit
spec/models/queries/signatures_export_spec.rb
Ruby
agpl-3.0
963
/*////////////////////////////////////////////////////////////////// //// SKIRT -- an advanced radiative transfer code //// //// © Astronomical Observatory, Ghent University //// ///////////////////////////////////////////////////////////////// */ #include "SubItemPropertyWizardPane.hpp" #include "ItemListPropertyHandler.hpp" #include "SimulationItemDiscovery.hpp" #include "SimulationItemTools.hpp" #include "SimulationItem.hpp" #include <QVBoxLayout> #include <QLabel> #include <QRadioButton> #include <QButtonGroup> #include <QVariant> using namespace SimulationItemDiscovery; //////////////////////////////////////////////////////////////////// SubItemPropertyWizardPane::SubItemPropertyWizardPane(PropertyHandlerPtr handler, QObject* target) : PropertyWizardPane(handler, target) { auto hdlr = handlerCast<ItemListPropertyHandler>(); // create the layout so that we can add stuff one by one auto layout = new QVBoxLayout; // add the question layout->addWidget(new QLabel("Select one of the following options for item #" + QString::number(selectedIndex()+1) + " in " + hdlr->title() + " list:")); // determine the current and default item types QByteArray currentType = itemType(hdlr->value()[selectedIndex()]); QByteArray defaultType = hdlr->hasDefaultValue() ? hdlr->defaultItemType() : ""; // make a button group to contain the radio buttons reflecting the possible choices auto buttonGroup = new QButtonGroup; // add the choices for (auto choiceType : SimulationItemTools::allowedDescendants(hdlr->baseType(),hdlr->target())) { auto choiceTitle = title(choiceType); if (!choiceTitle.isEmpty()) choiceTitle.replace(0, 1, choiceTitle[0].toUpper()); if (SimulationItemDiscovery::inherits(choiceType,defaultType)) choiceTitle += " [default]"; auto choiceButton = new QRadioButton(choiceTitle); choiceButton->setFocusPolicy(Qt::NoFocus); buttonGroup->addButton(choiceButton); layout->addWidget(choiceButton); // associate the item type corresponding to this button with the button object choiceButton->setProperty("choiceType", choiceType); choiceButton->setToolTip(choiceType); // if this button corresponds to the current type, select it if (choiceType==currentType) { choiceButton->setChecked(true); emit propertyValidChanged(true); } } // connect the button group to ourselves connect(buttonGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(selectTypeFor(QAbstractButton*))); // finalize the layout and assign it to ourselves layout->addStretch(); setLayout(layout); } //////////////////////////////////////////////////////////////////// int SubItemPropertyWizardPane::selectedIndex() { auto hdlr = handlerCast<ItemListPropertyHandler>(); return SimulationItemTools::retrieveSelectedRow(hdlr->target(), hdlr->name()); } //////////////////////////////////////////////////////////////////// void SubItemPropertyWizardPane::selectTypeFor(QAbstractButton* button) { auto hdlr = handlerCast<ItemListPropertyHandler>(); // update the value if needed auto newType = button->property("choiceType").toByteArray(); int index = selectedIndex(); if (itemType(hdlr->value()[index]) != newType) { hdlr->removeValueAt(index); hdlr->insertNewItemOfType(index, newType); emit propertyValueChanged(); } // signal the change emit propertyValidChanged(true); } ////////////////////////////////////////////////////////////////////
raesjo/SKIRTcorona
SkirtMakeUp/SubItemPropertyWizardPane.cpp
C++
agpl-3.0
3,696
/** * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of fiware-tidoop (FI-WARE project). * * fiware-tidoop 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. * fiware-tidoop 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 fiware-tidoop. If not, see * http://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License please contact with * francisco.romerobueno at telefonica dot com */ package com.telefonica.iot.tidoop.apiext.utils; import com.telefonica.iot.tidoop.apiext.hadoop.ckan.CKANInputFormat; import com.telefonica.iot.tidoop.apiext.hadoop.ckan.CKANOutputFormat; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; /** * * @author frb */ public final class CKANMapReduceExample extends Configured implements Tool { /** * Constructor. It is private since utility classes should not have a public or default constructor. */ private CKANMapReduceExample() { } // CKANMapReduceTest /** * Mapper class. It receives a CKAN record pair (Object key, Text ckanRecord) and returns a (Text globalKey, * IntWritable recordLength) pair about a common global key and the length of the record. */ public static class RecordSizeGetter extends Mapper<Object, Text, Text, IntWritable> { private final Text globalKey = new Text("size"); private final IntWritable recordLength = new IntWritable(); @Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException { recordLength.set(value.getLength()); context.write(globalKey, recordLength); } // map } // RecordSizeGetter /** * Reducer class. It receives a list of (Text globalKey, IntWritable length) pairs and computes the sum of all the * lengths, producing a final (Text globalKey, IntWritable totalLength). */ public static class RecordSizeAdder extends Reducer<Text, IntWritable, Text, IntWritable> { private final IntWritable totalLength = new IntWritable(); @Override public void reduce(Text globalKey, Iterable<IntWritable> recordLengths, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : recordLengths) { sum += val.get(); } // for totalLength.set(sum); context.write(globalKey, totalLength); } // reduce } // RecordSizeAdder /** * Main class. * @param args * @throws Exception */ public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new CKANMapReduceExample(), args); System.exit(res); } // main @Override public int run(String[] args) throws Exception { // check the number of arguments, show the usage if it is wrong if (args.length != 7) { showUsage(); return -1; } // if // get the arguments String ckanHost = args[0]; String ckanPort = args[1]; boolean sslEnabled = args[2].equals("true"); String ckanAPIKey = args[3]; String ckanInputs = args[4]; String ckanOutput = args[5]; String splitsLength = args[6]; // create and configure a MapReduce job Configuration conf = this.getConf(); Job job = Job.getInstance(conf, "CKAN MapReduce test"); job.setJarByClass(CKANMapReduceExample.class); job.setMapperClass(RecordSizeGetter.class); job.setCombinerClass(RecordSizeAdder.class); job.setReducerClass(RecordSizeAdder.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setInputFormatClass(CKANInputFormat.class); CKANInputFormat.setInput(job, ckanInputs); CKANInputFormat.setEnvironment(job, ckanHost, ckanPort, sslEnabled, ckanAPIKey); CKANInputFormat.setSplitsLength(job, splitsLength); job.setOutputFormatClass(CKANOutputFormat.class); CKANOutputFormat.setEnvironment(job, ckanHost, ckanPort, sslEnabled, ckanAPIKey); CKANOutputFormat.setOutputPkg(job, ckanOutput); // run the MapReduce job return job.waitForCompletion(true) ? 0 : 1; } // main private void showUsage() { System.out.println("Usage:"); System.out.println(); System.out.println("hadoop jar \\"); System.out.println(" target/ckan-protocol-0.1-jar-with-dependencies.jar \\"); System.out.println(" es.tid.fiware.fiwareconnectors.ckanprotocol.utils.CKANMapReduceTest \\"); System.out.println(" -libjars target/ckan-protocol-0.1-jar-with-dependencies.jar \\"); System.out.println(" <ckan host> \\"); System.out.println(" <ckan port> \\"); System.out.println(" <ssl enabled=true|false> \\"); System.out.println(" <ckan API key> \\"); System.out.println(" <comma-separated list of ckan inputs> \\"); System.out.println(" <ckan output package> \\"); System.out.println(" <splits length>"); } // showUsage } // CKANMapReduceTest
telefonicaid/fiware-tidoop
tidoop-hadoop-ext/src/main/java/com/telefonica/iot/tidoop/apiext/utils/CKANMapReduceExample.java
Java
agpl-3.0
6,139
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Agile Business Group sagl # (<http://www.agilebg.com>) # @author Alex Comba <alex.comba@agilebg.com> # # This program 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. # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': "Stock Invoice Picking Incoterm", 'version': '0.1', 'category': 'Warehouse Management', 'description': """ This module adds the field incoterm to invoice and picking. In this way the user can specify the incoterm directly on these documents, with no need to refer to the incoterm of the order (which could even be missing). The module extends 'stock_invoice_picking' so that the invoices created from pickings will have the same incoterm set in the picking. """, 'author': 'Agile Business Group', 'website': 'http://www.agilebg.com', 'license': 'AGPL-3', 'depends': [ 'stock_invoice_picking', ], 'data': [ 'account_invoice_view.xml', 'stock_view.xml', ], 'test': [ 'test/invoice_picking_incoterm.yml', ], 'installable': False }
jbaudoux/account-invoicing
__unported__/stock_invoice_picking_incoterm/__openerp__.py
Python
agpl-3.0
1,830
package org.yamcs.parameter; import org.yamcs.protobuf.Yamcs.Value.Type; public class FloatValue extends Value { final float v; public FloatValue(float v) { this.v = v; } @Override public Type getType() { return Type.FLOAT; } @Override public float getFloatValue() { return v; } @Override public double toDouble() { return v; } @Override public int hashCode() { return Float.hashCode(v); } public boolean equals(Object obj) { return (obj instanceof FloatValue) && (Float.floatToIntBits(((FloatValue) obj).v) == Float.floatToIntBits(v)); } @Override public String toString() { return Float.toString(v); } }
fqqb/yamcs
yamcs-core/src/main/java/org/yamcs/parameter/FloatValue.java
Java
agpl-3.0
767
from django.utils.translation import ugettext as _, ugettext_lazy as _lazy from django.core import urlresolvers from django.http import HttpResponse, HttpResponseServerError from flexi_auth.models import ObjectWithContext from rest.views.blocks.base import BlockSSDataTables, ResourceBlockAction, CREATE_CSV from consts import VIEW_CONFIDENTIAL, CONFIDENTIAL_VERBOSE_HTML, CASH from gf.base.templatetags.accounting_tags import human_readable_account_csv,human_readable_kind, signed_ledger_entry_amount from django.template.loader import render_to_string import datetime, csv import cStringIO as StringIO #from simple_accounting.models import economic_subject, AccountingDescriptor #from simple_accounting.models import account_type #from simple_accounting.exceptions import MalformedTransaction #from simple_accounting.models import AccountingProxy #from simple_accounting.utils import register_transaction, register_simple_transaction #from gf.base.accounting import PersonAccountingProxy from lib.shortcuts import render_to_xml_response, render_to_context_response #------------------------------------------------------------------------------# # # #------------------------------------------------------------------------------# #OLD: ENCODING = "iso-8859-1" class Block(BlockSSDataTables): BLOCK_NAME = "transactions" BLOCK_DESCRIPTION = _("Economic transactions") BLOCK_VALID_RESOURCE_TYPES = ["gas", "supplier", "pact"] COLUMN_INDEX_NAME_MAP = { 0: 'id', 1: 'transaction__date', 2: '', 3: '', 4: 'amount', 5: 'transaction__description', } #WAS 2: 'transaction__issuer', #WAS 3: 'transaction__source', #WAS 3: 'transaction__kind', --> FIXME: In case of translation the search does not operate correctly def __init__(self, *args, **kw): super(Block, self).__init__(*args, **kw) # Default start closed. Mainly for GAS -> Accounting tab ("Conto") self.start_open = False def _check_permission(self, request): if request.resource.gas: return request.user.has_perm( CASH, obj=ObjectWithContext(request.resource.gas) ) else: return True def _get_resource_list(self, request): #Accounting.LedgerEntry or Transactions return request.resource.economic_movements def get_response(self, request, resource_type, resource_id, args): """Check for confidential access permission and call superclass if needed""" if not self._check_permission(request): return render_to_xml_response( "blocks/table_html_message.xml", { 'msg' : CONFIDENTIAL_VERBOSE_HTML } ) if args == CREATE_CSV: return self._create_csv(request) return super(Block, self).get_response(request, resource_type, resource_id, args) #TODO: Filter grid by # Date From --> To # Kind iof transctions: can be checkbox list multiselect # Subject: Radio or multiple checkbox onto values [GAS borselino, GASMemmbers, Suppliers] # def options_response(self, request, resource_type, resource_id): # """Get options for transaction block. # WARNING: call to this method doesn't pass through get_response # so you have to reset self.request and self.resource attribute if you want # """ # self.request = request # self.resource = request.resource # fields = [] # #DATE FROM # fields.append({ # 'field_type' : 'datetime', # 'field_label' : 'from date', # 'field_name' : 'from', # 'field_values' : [{ 'value' : '22/09/2012', 'selected' : ''}] # }) # #DATE TO # fields.append({ # 'field_type' : 'datetime', # 'field_label' : 'to date', # 'field_name' : 'to', # 'field_values' : [{ 'value' : '28/09/2012', 'label' : 'labelvalue', 'selected' : 'sel'}] # }) # ctx = { # 'block_name' : self.description, # 'fields': fields, # } # #Can use html template loader # return render_to_xml_response('eco-options.xml', ctx) def _get_user_actions(self, request): user_actions = [] resource_type = request.resource.resource_type if self._check_permission(request): user_actions += [ ResourceBlockAction( block_name = self.BLOCK_NAME, resource = request.resource, name=CREATE_CSV, verbose_name=_("Create CSV"), popup_form=False, method="OPENURL", ), ] return user_actions def _create_csv(self, request): """ Create CSV of this block transactions #MATTEO TOREMOVE: lascio la prima implementazione (da levare ovviamente dall'integrazione) come monito a me stesso --> kiss, kiss e ancora kiss !! #NOTA: eliminare nell'integrazione tutte le righe commentate con #OLD: """ headers = [_(u'Id'), _(u'Data'), _(u'Account'), _(u'Kind'), _(u'Cash amount'), _(u'Description')] records = self._get_resource_list(request) csvfile = StringIO.StringIO() writer = csv.writer(csvfile, delimiter=';',quotechar='"', quoting=csv.QUOTE_MINIMAL) writer.writerow(headers) for res in self._get_resource_list(request): writer.writerow([res.pk, '{0:%a %d %b %Y %H:%M}'.format(res.date), human_readable_account_csv(res.account), human_readable_kind(res.transaction.kind), signed_ledger_entry_amount(res), res.transaction.description.encode("utf-8", "ignore") ]) csv_data = csvfile.getvalue() if not csv_data: rv = HttpResponseServerError(_('Report not generated')) else: response = HttpResponse(csv_data, content_type='text/csv') filename = "%(res)s_%(date)s.csv" % { 'res': request.resource, 'date' : '{0:%Y%m%d_%H%M}'.format(datetime.datetime.now()) } response['Content-Disposition'] = "attachment; filename=" + filename rv = response return rv
befair/gasistafelice
gasistafelice/rest/views/blocks/transactions.py
Python
agpl-3.0
6,479
require 'test_helper' class CurrenciesHelperTest < ActionView::TestCase end
BCJonesey/CDB3
test/unit/helpers/currencies_helper_test.rb
Ruby
agpl-3.0
77
<?php /** * Interface denoting an event is a deferred event that should be raised only at the end of the multirequest * * @package Core * @subpackage events */ interface IKalturaMultiDeferredEvent { /** * @param array $partnerCriteriaParams */ public function setPartnerCriteriaParams(array $partnerCriteriaParams); }
kaltura/server
alpha/apps/kaltura/lib/events/interfaces/IKalturaMultiDeferredEvent.php
PHP
agpl-3.0
330
package org.tasgoon.coherence.client; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import org.apache.commons.io.FileUtils; import org.tasgoon.coherence.common.Library; import org.tasgoon.coherence.ziputils.ZipUtility; import joptsimple.OptionParser; import joptsimple.OptionSet; public class CohereUndoer { //public final Logger logger = LogManager.getLogger("Coherence"); public String pid, ip, minecraftCmd; public boolean crashed = false; public static void main(String[] args) throws IOException, InterruptedException { OptionParser parser = new OptionParser("i:p:c::"); /*OptionSpec<String> ip = parser.accepts("ip", "The previous IP Minecraft was connected to").withRequiredArg(); OptionSpec<String> pid = parser.accepts("pid", "PID of the minecraft process").withRequiredArg(); OptionSpec<String> cmd = parser.accepts("cmd", "The minecraft command, for crash recovery").withOptionalArg();*/ new CohereUndoer(parser.parse(args)); } public CohereUndoer(OptionSet options) throws IOException, InterruptedException { System.out.println("Starting coherence undoer"); pid = (String) options.valueOf("p"); ip = (String) options.valueOf("i"); if (options.has("c")) { crashed = true; minecraftCmd = (String) options.valueOf("c"); } System.out.println("Using command: " + getCommand()); System.out.println("Starting process kill detector"); waitForProcessEnd(); undo(); } public String getCommand() { String command; String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("win") >= 0) command = System.getenv("windir") + "\\system32\\" + "tasklist.exe /FI \"PID eq %s\""; else command = "ps -p %s"; return String.format(command, pid); } public void waitForProcessEnd() throws IOException, InterruptedException { boolean detected = true; String line; while (detected) { detected = false; Process process = Runtime.getRuntime().exec(getCommand()); BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((line = input.readLine()) != null) { if (line.contains(pid)) detected = true; } } } public void undo() { System.out.println("Moving files back."); File modsDir = new File("mods"); File originalModsDir = Library.getFile("coherence", "localhost", "mods"); /*//Because the reversal script is running from a file in the mods directory, I can't just remove the file. //So, I have to iterate through the folder and remove all the files save for Coherence. for (File file : cohereModsDir.listFiles()) FileUtils.deleteQuietly(file);*/ FileUtils.deleteQuietly(modsDir); for (File file : originalModsDir.listFiles()) { try { FileUtils.moveToDirectory(file, modsDir, false); } catch (IOException e) { System.err.println("Could not move file " + file.getAbsolutePath() + " back."); e.printStackTrace(); } } File config = new File("config"); File customConfig = Library.getFile("coherence", ip, "customConfig.zip"); System.out.println("Saving current configs to " + customConfig.getAbsolutePath()); ZipUtility.compressFolder(config, customConfig); System.out.println("Deleting configs from config folder"); try { FileUtils.forceDelete(config); } catch (IOException e) { System.err.println("Could not delete synchronized config files."); e.printStackTrace(); } System.out.println("Moving old configs back to main config folder"); new File("oldConfig").renameTo(config); FileUtils.deleteQuietly(new File("coherence", "localhost")); //Contains mods that were just moved back if (crashed) startMC(); } public void startMC() { try { Runtime.getRuntime().exec(minecraftCmd); } catch (IOException e) {} } }
Kagiu/Coherence
src/main/java/org/tasgoon/coherence/client/CohereUndoer.java
Java
agpl-3.0
3,832
(function () { var ns = $.namespace('pskl.service'); ns.SelectedColorsService = function () { this.reset(); }; ns.SelectedColorsService.prototype.init = function () { $.subscribe(Events.PRIMARY_COLOR_SELECTED, this.onPrimaryColorUpdate_.bind(this)); $.subscribe(Events.SECONDARY_COLOR_SELECTED, this.onSecondaryColorUpdate_.bind(this)); }; ns.SelectedColorsService.prototype.getPrimaryColor = function () { return this.primaryColor_; }; ns.SelectedColorsService.prototype.getSecondaryColor = function () { return this.secondaryColor_; }; ns.SelectedColorsService.prototype.reset = function () { this.primaryColor_ = Constants.DEFAULT_PEN_COLOR; this.secondaryColor_ = Constants.TRANSPARENT_COLOR; }; ns.SelectedColorsService.prototype.onPrimaryColorUpdate_ = function (evt, color) { this.primaryColor_ = color; }; ns.SelectedColorsService.prototype.onSecondaryColorUpdate_ = function (evt, color) { this.secondaryColor_ = color; }; })();
RichardMarks/piskel
src/js/service/SelectedColorsService.js
JavaScript
agpl-3.0
1,011
<?php return [ 'accessories' => 'Accessories', 'activated' => 'Aktivoitu', 'accessory' => 'Accessory', 'accessory_report' => 'Accessory Report', 'action' => 'Toiminto', 'activity_report' => 'Activity Report', 'address' => 'Osoite', 'admin' => 'Ylläpitäjä', 'add_seats' => 'Added seats', 'all_assets' => 'Kaikki Laitteet', 'all' => 'Kaikki', 'archived' => 'Arkistoitu', 'asset_models' => 'Laitemallit', 'asset' => 'Laite', 'asset_report' => 'Laiteraportti', 'asset_tag' => 'Laitetunnus', 'assets_available' => 'laitetta vapaana', 'assets' => 'Laitteet', 'avatar_delete' => 'Poista käyttäjäkuva', 'avatar_upload' => 'Lähetä Käyttäjäkuva', 'back' => 'Edellinen', 'bad_data' => 'Nothing found. Maybe bad data?', 'bulk_checkout' => 'Bulk Checkout', 'cancel' => 'Peruuta', 'categories' => 'Kategoriat', 'category' => 'Kategoria', 'changeemail' => 'Muuta Email-osoite', 'changepassword' => 'Muuta Salasana', 'checkin' => 'Palauta', 'checkin_from' => 'Checkin from', 'checkout' => 'Luovuta', 'city' => 'Kaupunki', 'companies' => 'Yritykset', 'company' => 'Yritys', 'component' => 'Komponentti', 'components' => 'Komponentit', 'consumable' => 'Consumable', 'consumables' => 'Consumables', 'country' => 'Maa', 'create' => 'Luo Uusi', 'created' => 'Item Created', 'created_asset' => 'laite luotu', 'created_at' => 'Luontiaika', 'currency' => '€', // this is deprecated 'current' => 'Käytössä Olevat', 'custom_report' => 'Muokattu Laiteraportti', 'dashboard' => 'Hallintasivu', 'date' => 'Päivä', 'debug_warning' => 'Warning!', 'debug_warning_text' => 'This application is running in production mode with debugging enabled. This can expose sensitive data if your application is accessible to the outside world. Disable debug mode by setting the <code>APP_DEBUG</code> value in your <code>.env</code> file to <code>false</code>.', 'delete' => 'Poista', 'deleted' => 'Poistettu', 'delete_seats' => 'Deleted Seats', 'deployed' => 'Käyttöönotettu', 'depreciation_report' => 'Poistoraportti', 'download' => 'Lataa', 'depreciation' => 'Poistoluokka', 'editprofile' => 'Muokkaa Profiilia', 'eol' => 'Elinikä', 'email_domain' => 'Email Domain', 'email_format' => 'Email Format', 'email_domain_help' => 'This is used to generate email addresses when importing', 'filastname_format' => 'First Initial Last Name (jsmith@example.com)', 'firstname_lastname_format' => 'First Name Last Name (jane.smith@example.com)', 'first' => 'Ensimmäinen', 'first_name' => 'Etunimi', 'first_name_format' => 'First Name (jane@example.com)', 'file_name' => 'Tiedosto', 'file_uploads' => 'Tiedostolataus', 'generate' => 'Luo', 'groups' => 'Ryhmät', 'gravatar_email' => 'Gravatarin Email-osoite', 'history' => 'History', 'history_for' => 'Laitehistoria käyttäjälle', 'id' => 'Tunnus', 'image_delete' => 'Poista Kuva', 'image_upload' => 'Lähetä Kuva', 'import' => 'Tuo tiedot', 'import-history' => 'Import History', 'asset_maintenance' => 'Asset Maintenance', 'asset_maintenance_report' => 'Asset Maintenance Report', 'asset_maintenances' => 'Asset Maintenances', 'item' => 'Item', 'insufficient_permissions' => 'Insufficient permissions!', 'language' => 'Kieli', 'last' => 'Last', 'last_name' => 'Sukunimi', 'license' => 'Lisenssi', 'license_report' => 'Lisenssiraportti', 'licenses_available' => 'Vapaana olevat lisenssit', 'licenses' => 'Lisenssit', 'list_all' => 'Listaa Kaikki', 'loading' => 'Ladataan', 'lock_passwords' => 'This field cannot be edited in this installation.', 'feature_disabled' => 'This feature has been disabled for the demo installation.', 'location' => 'Sijainti', 'locations' => 'Sijainnit', 'logout' => 'Kirjaudu Ulos', 'lookup_by_tag' => 'Lookup by Asset Tag', 'manufacturer' => 'Valmistaja', 'manufacturers' => 'Valmistajat', 'markdown' => 'This field allows <a href="https://help.github.com/articles/github-flavored-markdown/">Github flavored markdown</a>.', 'min_amt' => 'Min. QTY', 'min_amt_help' => 'Minimum number of items that should be available before an alert gets triggered.', 'model_no' => 'Mallinumero', 'months' => 'Kuukautta', 'moreinfo' => 'Lisätiedot', 'name' => 'Nimi', 'next' => 'Seuraava', 'new' => 'new!', 'no_depreciation' => 'Ei poistoluokkaa', 'no_results' => 'Ei tuloksia.', 'no' => 'Ei', 'notes' => 'Muistiinpanot', 'order_number' => 'Order Number', 'page_menu' => 'Showing _MENU_ items', 'pagination_info' => 'Showing _START_ to _END_ of _TOTAL_ items', 'pending' => 'Odottaa', 'people' => 'Ihmiset', 'per_page' => 'Tuloksia Per Sivu', 'previous' => 'Edellinen', 'processing' => 'Käsitellään', 'profile' => 'Profiilisi', 'purchase_cost' => 'Purchase Cost', 'purchase_date' => 'Purchase Date', 'qty' => 'KPL', 'quantity' => 'Määrä', 'ready_to_deploy' => 'Käyttöönotettavissa', 'recent_activity' => 'Viimeisin toiminta', 'remove_company' => 'Remove Company Association', 'reports' => 'Raportit', 'requested' => 'Requested', 'request_canceled' => 'Request Canceled', 'save' => 'Tallenna', 'select' => 'Valitse', 'search' => 'Etsi', 'select_category' => 'Select a Category', 'select_depreciation' => 'Select a Depreciation Type', 'select_location' => 'Valitse sijainti', 'select_manufacturer' => 'Valitse valmistaja', 'select_model' => 'Select a Model', 'select_supplier' => 'Valitse toimittaja', 'select_user' => 'Valitse käyttäjä', 'select_date' => 'Select Date', 'select_statuslabel' => 'Select Status', 'select_company' => 'Select Company', 'select_asset' => 'Select Asset', 'settings' => 'Asetukset', 'sign_in' => 'Kirjaudu sisään', 'signature' => 'Signature', 'some_features_disabled' => 'DEMO MODE: Some features are disabled for this installation.', 'site_name' => 'Sivuston Nimi', 'state' => 'Lääni', 'status_labels' => 'Tilamerkinnät', 'status' => 'Tila', 'supplier' => 'Supplier', 'suppliers' => 'Toimittajat', 'submit' => 'Submit', 'total_assets' => 'laitteita yhteensä', 'total_licenses' => 'lisenssejä yhteensä', 'total_accessories' => 'total accessories', 'total_consumables' => 'total consumables', 'type' => 'Tyyppi', 'undeployable' => 'Ei-käyttöönotettavissa', 'unknown_admin' => 'Tuntematon Ylläpitäjä', 'username_format' => 'Username Format', 'update' => 'Päivitä', 'uploaded' => 'Ladattu', 'user' => 'Käyttäjä', 'accepted' => 'hyväksytty', 'declined' => 'hylkää', 'unaccepted_asset_report' => 'Unaccepted Assets', 'users' => 'Käyttäjät', 'viewassets' => 'Näytä Käyttöönotetut Laitteet', 'website' => 'Verkkosivu', 'welcome' => 'Tervetuloa, :name', 'years' => 'vuotta', 'yes' => 'Kyllä', 'zip' => 'Postinumero', 'noimage' => 'No image uploaded or image not found.', 'token_expired' => 'Istuntosi on vanhentunut. Ole hyvä ja kirjaudu uudelleen.', ];
Murima/asset-mgmt
resources/lang/fi/general.php
PHP
agpl-3.0
8,191
// Copyright 2016 The Mangos Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use 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. // survey implements a survey example. server is a surveyor listening // socket, and clients are dialing respondent sockets. // // To use: // // $ go build . // $ url=tcp://127.0.0.1:40899 // $ ./survey server $url server & server=$! // $ ./survey client $url client0 & client0=$! // $ ./survey client $url client1 & client1=$! // $ ./survey client $url client2 & client2=$! // $ sleep 5 // $ kill $server $client0 $client1 $client2 // package main import ( "fmt" "github.com/go-mangos/mangos" "github.com/go-mangos/mangos/protocol/respondent" "github.com/go-mangos/mangos/protocol/surveyor" "github.com/go-mangos/mangos/transport/ipc" "github.com/go-mangos/mangos/transport/tcp" "os" "time" ) func die(format string, v ...interface{}) { fmt.Fprintln(os.Stderr, fmt.Sprintf(format, v...)) os.Exit(1) } func date() string { return time.Now().Format(time.ANSIC) } func server(url string) { var sock mangos.Socket var err error var msg []byte if sock, err = surveyor.NewSocket(); err != nil { die("can't get new surveyor socket: %s", err) } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) if err = sock.Listen(url); err != nil { die("can't listen on surveyor socket: %s", err.Error()) } err = sock.SetOption(mangos.OptionSurveyTime, time.Second/2) if err != nil { die("SetOption(): %s", err.Error()) } for { time.Sleep(time.Second) fmt.Println("SERVER: SENDING DATE SURVEY REQUEST") if err = sock.Send([]byte("DATE")); err != nil { die("Failed sending survey: %s", err.Error()) } for { if msg, err = sock.Recv(); err != nil { break } fmt.Printf("SERVER: RECEIVED \"%s\" SURVEY RESPONSE\n", string(msg)) } fmt.Println("SERVER: SURVEY OVER") } } func client(url string, name string) { var sock mangos.Socket var err error var msg []byte if sock, err = respondent.NewSocket(); err != nil { die("can't get new respondent socket: %s", err.Error()) } sock.AddTransport(ipc.NewTransport()) sock.AddTransport(tcp.NewTransport()) if err = sock.Dial(url); err != nil { die("can't dial on respondent socket: %s", err.Error()) } for { if msg, err = sock.Recv(); err != nil { die("Cannot recv: %s", err.Error()) } fmt.Printf("CLIENT(%s): RECEIVED \"%s\" SURVEY REQUEST\n", name, string(msg)) d := date() fmt.Printf("CLIENT(%s): SENDING DATE SURVEY RESPONSE\n", name) if err = sock.Send([]byte(d)); err != nil { die("Cannot send: %s", err.Error()) } } } func main() { if len(os.Args) > 2 && os.Args[1] == "server" { server(os.Args[2]) os.Exit(0) } if len(os.Args) > 3 && os.Args[1] == "client" { client(os.Args[2], os.Args[3]) os.Exit(0) } fmt.Fprintf(os.Stderr, "Usage: survey server|client <URL> <ARG>\n") os.Exit(1) }
synapse-garden/sg-proto
vendor/github.com/go-mangos/mangos/examples/survey/survey.go
GO
agpl-3.0
3,364
class Admin::PetitionsController < ApplicationController before_filter :require_admin def index params[:time_span] ||= 'month' respond_to do |format| format.html {} format.json { render json: PetitionsDatatable.new(view_context, PetitionReportRepository.new) } end end end
ChrisAntaki/victorykit
app/controllers/admin/petitions_controller.rb
Ruby
agpl-3.0
304
/* * Async_MediaConnectionListener.java Version-1.4, 2002/11/22 09:26:10 -0800 (Fri) * ECTF S.410-R2 Source code distribution. * * Copyright (c) 2002, Enterprise Computer Telephony Forum (ECTF), * All Rights Reserved. * * Use and redistribution of this file is subject to a License. * For terms and conditions see: javax/telephony/media/LICENSE.HTML * * In short, you can use this source code if you keep and display * the ECTF Copyright and the License conditions. The code is supplied * "AS IS" and ECTF disclaims all warranties and liability. */ package javax.telephony.media.connection.async; import javax.telephony.media.connection.*; import javax.telephony.media.async.*; import javax.telephony.media.*; /** Transaction completion Listener for connect() and related methods. * * @author Jeff Peck * @since JTAPI-1.4 */ public interface Async_MediaConnectionListener extends MediaListener { /** * Connect complete. * <tt>event.getEventID()</tt> is one of the connection type Symbols: * <br>{<tt>ev_Bridge</tt>, <tt>ev_Join</tt>, <tt>ev_Loopback</tt>}. * <p> * <tt>event.getToken()</tt> identifies the connection: * <ul><li> * the other Group, * </li><li> * connection type, * </li><li> * dataFlow, * </li><li> * maxDataFlow. * </li></ul> * * @param event the MediaConnectionEvent that is done. */ void onConnectDone( MediaConnectionEvent event ); /** * Disconnect complete. * event.getEventID() = <tt>ev_Disconnect</tt>. * <p> * The event.getToken() identifies the connection and Group * which has been disconnected. * Token.dataFlow and Token.maxDataFlow are <tt>null</tt>. * * <p> * <tt>event.getEventID() = connType = ev_Disconnect</tt>. * * @param event the MediaConnectionEvent that is done. */ void onDisconnectDone( MediaConnectionEvent event ); /** * SetDataFlow complete. * event.getEventID() = <tt>ev_Disconnect</tt>. * <p> * The event.getToken() identifies the connection and Group * which has been disconnected. * Token.dataFlow and Token.maxDataFlow are <tt>null</tt>. * * <p> * <tt>event.getEventID() = connType = ev_Disconnect</tt>. * * @param event the MediaConnectionEvent that is done. */ void onSetDataFlowDone( MediaConnectionEvent event ); }
openss7/openss7
src/java/javax/telephony/media/connection/async/Async_MediaConnectionListener.java
Java
agpl-3.0
2,435
// Copyright 2014 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // Package miner implements Ethereum block creation and mining. package miner import ( "errors" "math/big" "sync/atomic" "github.com/ethereumproject/go-ethereum/common" "github.com/ethereumproject/go-ethereum/core" "github.com/ethereumproject/go-ethereum/core/state" "github.com/ethereumproject/go-ethereum/core/types" "github.com/ethereumproject/go-ethereum/eth/downloader" "github.com/ethereumproject/go-ethereum/event" "github.com/ethereumproject/go-ethereum/logger" "github.com/ethereumproject/go-ethereum/logger/glog" "github.com/ethereumproject/go-ethereum/pow" ) // HeaderExtra is a freeform description. var HeaderExtra []byte type Miner struct { mux *event.TypeMux worker *worker MinAcceptedGasPrice *big.Int threads int coinbase common.Address mining int32 eth core.Backend pow pow.PoW canStart int32 // can start indicates whether we can start the mining operation shouldStart int32 // should start indicates whether we should start after sync } func New(eth core.Backend, config *core.ChainConfig, mux *event.TypeMux, pow pow.PoW) *Miner { miner := &Miner{eth: eth, mux: mux, pow: pow, worker: newWorker(config, common.Address{}, eth), canStart: 1} go miner.update() return miner } // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop. // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks // and halt your mining operation for as long as the DOS continues. func (self *Miner) update() { events := self.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{}) out: for ev := range events.Chan() { switch ev.Data.(type) { case downloader.StartEvent: atomic.StoreInt32(&self.canStart, 0) if self.Mining() { self.Stop() atomic.StoreInt32(&self.shouldStart, 1) glog.V(logger.Info).Infoln("Mining operation aborted due to sync operation") } case downloader.DoneEvent, downloader.FailedEvent: shouldStart := atomic.LoadInt32(&self.shouldStart) == 1 atomic.StoreInt32(&self.canStart, 1) atomic.StoreInt32(&self.shouldStart, 0) if shouldStart { self.Start(self.coinbase, self.threads) } // unsubscribe. we're only interested in this event once events.Unsubscribe() // stop immediately and ignore all further pending events break out } } } func (m *Miner) SetGasPrice(price *big.Int) error { if price == nil { return nil } if m.MinAcceptedGasPrice != nil && price.Cmp(m.MinAcceptedGasPrice) == -1 { priceTooLowError := errors.New("Gas price lower than minimum allowed.") return priceTooLowError } m.worker.setGasPrice(price) return nil } func (self *Miner) Start(coinbase common.Address, threads int) { atomic.StoreInt32(&self.shouldStart, 1) self.threads = threads self.worker.coinbase = coinbase self.coinbase = coinbase if atomic.LoadInt32(&self.canStart) == 0 { glog.V(logger.Info).Infoln("Can not start mining operation due to network sync (starts when finished)") return } atomic.StoreInt32(&self.mining, 1) for i := 0; i < threads; i++ { self.worker.register(NewCpuAgent(i, self.pow)) } mlogMinerStart.AssignDetails( coinbase.Hex(), threads, ).Send(mlogMiner) glog.V(logger.Info).Infof("Starting mining operation (CPU=%d TOT=%d)\n", threads, len(self.worker.agents)) self.worker.start() self.worker.commitNewWork() } func (self *Miner) Stop() { self.worker.stop() atomic.StoreInt32(&self.mining, 0) atomic.StoreInt32(&self.shouldStart, 0) if logger.MlogEnabled() { mlogMinerStop.AssignDetails( self.coinbase.Hex(), self.threads, ).Send(mlogMiner) } } func (self *Miner) Register(agent Agent) { if self.Mining() { agent.Start() } self.worker.register(agent) } func (self *Miner) Unregister(agent Agent) { self.worker.unregister(agent) } func (self *Miner) Mining() bool { return atomic.LoadInt32(&self.mining) > 0 } func (self *Miner) HashRate() (tot int64) { tot += self.pow.GetHashrate() // do we care this might race? is it worth we're rewriting some // aspects of the worker/locking up agents so we can get an accurate // hashrate? for agent := range self.worker.agents { tot += agent.GetHashRate() } return } // Pending returns the currently pending block and associated state. func (self *Miner) Pending() (*types.Block, *state.StateDB) { return self.worker.pending() } func (self *Miner) SetEtherbase(addr common.Address) { self.coinbase = addr self.worker.setEtherbase(addr) }
adrianbrink/tendereum
vendor/github.com/ethereumproject/go-ethereum/miner/miner.go
GO
agpl-3.0
5,441
/** * Copyright (c) 2010-present Abixen Systems. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.abixen.platform.service.businessintelligence.multivisualisation.service; import com.abixen.platform.service.businessintelligence.multivisualisation.model.enumtype.DataValueType; import com.abixen.platform.service.businessintelligence.multivisualisation.util.*; public interface DomainBuilderService { DatabaseDataSourceBuilder newDatabaseDataSourceBuilderInstance(); FileDataSourceBuilder newFileDataSourceBuilderInstance(); DataFileBuilder newDataFileBuilderInstance(); DataSetBuilder newDataSetBuilderInstance(); DataSetSeriesBuilder newDataSetSeriesBuilderInstance(); DataSetSeriesColumnBuilder newDataSetSeriesColumnBuilderInstance(); DataSourceColumnBuilder newDataSourceColumnBuilderInstance(); DataSourceValueBuilder newDataSourceValueBuilderInstance(DataValueType dataValueType); }
cloudowski/abixen-platform
abixen-platform-business-intelligence-service/src/main/java/com/abixen/platform/service/businessintelligence/multivisualisation/service/DomainBuilderService.java
Java
lgpl-2.1
1,441
<?php /* * $Id$ * * 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. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.phpdoctrine.org>. */ /** * Doctrine_Ticket_DC187_TestCase * * @package Doctrine * @author Konsta Vesterinen <kvesteri@cc.hut.fi> * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @category Object Relational Mapping * @link www.phpdoctrine.org * @since 1.0 * @version $Revision$ */ class Doctrine_Ticket_DC187_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { $this->tables[] = 'Ticket_DC187_User'; parent::prepareTables(); } public function testTest() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); $user = new Ticket_DC187_User(); $user->username = 'jwage'; $user->email = 'jonwage@gmail.com'; $user->password = 'changeme'; $user->save(); $user->delete(); try { $user = new Ticket_DC187_User(); $user->username = 'jwage'; $user->email = 'jonwage@gmail.com'; $user->password = 'changeme'; $user->save(); $this->pass(); } catch (Exception $e) { $this->fail($e->getMessage()); } try { $user = new Ticket_DC187_User(); $user->username = 'jwage'; $user->email = 'jonwage@gmail.com'; $user->password = 'changeme'; $user->save(); $this->fail(); } catch (Exception $e) { $this->pass(); } Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } } class Ticket_DC187_User extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('username', 'string', 255); $this->hasColumn('email', 'string', 255); $this->hasColumn('password', 'string', 255); $this->unique( array('username', 'email'), array('where' => "deleted_at IS NULL"), false ); } public function setUp() { $this->actAs('SoftDelete'); } }
ascorbic/doctrine-tracker
tests/Ticket/DC187TestCase.php
PHP
lgpl-2.1
3,118
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import spack.util.url import spack.package class XorgPackage(spack.package.PackageBase): """Mixin that takes care of setting url and mirrors for x.org packages.""" #: Path of the package in a x.org mirror xorg_mirror_path = None #: List of x.org mirrors used by Spack # Note: x.org mirrors are a bit tricky, since many are out-of-sync or off. # A good package to test with is `util-macros`, which had a "recent" # release. base_mirrors = [ 'https://www.x.org/archive/individual/', 'https://mirrors.ircam.fr/pub/x.org/individual/', 'https://mirror.transip.net/xorg/individual/', 'ftp://ftp.freedesktop.org/pub/xorg/individual/', 'http://xorg.mirrors.pair.com/individual/' ] @property def urls(self): self._ensure_xorg_mirror_path_is_set_or_raise() return [ spack.util.url.join(m, self.xorg_mirror_path, resolve_href=True) for m in self.base_mirrors ] def _ensure_xorg_mirror_path_is_set_or_raise(self): if self.xorg_mirror_path is None: cls_name = type(self).__name__ msg = ('{0} must define a `xorg_mirror_path` attribute' ' [none defined]') raise AttributeError(msg.format(cls_name))
iulian787/spack
lib/spack/spack/build_systems/xorg.py
Python
lgpl-2.1
1,541
/* * Binomial.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST 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 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package beast.math; /** * Binomial coefficients * * @author Andrew Rambaut * @author Alexei Drummond * @author Korbinian Strimmer * @version $Id: Binomial.java,v 1.11 2005/05/24 20:26:00 rambaut Exp $ */ public class Binomial { // // Public stuff // public static double logChoose(final int n, final int k) { return GammaFunction.lnGamma(n + 1.0) - GammaFunction.lnGamma(k + 1.0) - GammaFunction.lnGamma(n - k + 1.0); } /** * @param n total elements * @param k chosen elements * @return Binomial coefficient n choose k */ public static double choose(double n, double k) { n = Math.floor(n + 0.5); k = Math.floor(k + 0.5); final double lchoose = GammaFunction.lnGamma(n + 1.0) - GammaFunction.lnGamma(k + 1.0) - GammaFunction.lnGamma(n - k + 1.0); return Math.floor(Math.exp(lchoose) + 0.5); } /** * @param n # elements * @return n choose 2 (number of distinct ways to choose a pair from n elements) */ public static double choose2(final int n) { // not sure how much overhead there is with try-catch blocks // i.e. would an if statement be better? try { return choose2LUT[n]; } catch (ArrayIndexOutOfBoundsException e) { if (n < 0) { return 0; } while (maxN < n) { maxN += 1000; } initialize(); return choose2LUT[n]; } } private static void initialize() { choose2LUT = new double[maxN + 1]; choose2LUT[0] = 0; choose2LUT[1] = 0; choose2LUT[2] = 1; for (int i = 3; i <= maxN; i++) { choose2LUT[i] = (i * (i - 1)) * 0.5; } } private static int maxN = 5000; private static double[] choose2LUT; static { // initialize(); } }
CompEvol/beast2
src/beast/math/Binomial.java
Java
lgpl-2.1
2,920
<?php namespace wcf\data\devtools\missing\language\item; use wcf\data\DatabaseObject; use wcf\data\language\Language; use wcf\system\language\LanguageFactory; use wcf\system\WCF; use wcf\util\JSON; /** * Represents a missing language item log entry. * * @author Matthias Schmidt * @copyright 2001-2020 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Devtools\Missing\Language\Item * @since 5.3 * * @property-read int $itemID unique id of the missing language item log entry * @property-read int $languageID id of the language the missing language item was requested for * @property-read string $languageItem name of the missing language item * @property-read int $lastTime timestamp of the last time the missing language item was requested * @property-read string $stackTrace stack trace of how the missing language item was requested for the last time */ class DevtoolsMissingLanguageItem extends DatabaseObject { /** * Returns the language the missing language item was requested for or `null` if the language * does not exist anymore. * * @return null|Language */ public function getLanguage() { if ($this->languageID === null) { return null; } return LanguageFactory::getInstance()->getLanguage($this->languageID); } /** * Returns the formatted stack trace of how the missing language item was requested for the * last time. * * @return string */ public function getStackTrace() { $stackTrace = JSON::decode($this->stackTrace); foreach ($stackTrace as &$stackEntry) { foreach ($stackEntry['args'] as &$stackEntryArg) { if (\gettype($stackEntryArg) === 'string') { $stackEntryArg = \str_replace(["\n", "\t"], ['\n', '\t'], $stackEntryArg); } } unset($stackEntryArg); } unset($stackEntry); return WCF::getTPL()->fetch('__devtoolsMissingLanguageItemStackTrace', 'wcf', [ 'stackTrace' => $stackTrace, ]); } }
SoftCreatR/WCF
wcfsetup/install/files/lib/data/devtools/missing/language/item/DevtoolsMissingLanguageItem.class.php
PHP
lgpl-2.1
2,209
package ch.unibas.cs.hpwc.patus.grammar.stencil2; import cetus.hir.BinaryExpression; import cetus.hir.BinaryOperator; import cetus.hir.DepthFirstIterator; import cetus.hir.Expression; import cetus.hir.IDExpression; import cetus.hir.IntegerLiteral; import cetus.hir.NameID; import ch.unibas.cs.hpwc.patus.representation.Stencil; import ch.unibas.cs.hpwc.patus.representation.StencilBundle; import ch.unibas.cs.hpwc.patus.representation.StencilNode; import ch.unibas.cs.hpwc.patus.symbolic.Symbolic; import ch.unibas.cs.hpwc.patus.util.CodeGeneratorUtil; import ch.unibas.cs.hpwc.patus.util.StringUtil; public class StencilSpecificationAnalyzer { /** * * @param bundle */ public static void normalizeStencilNodesForBoundariesAndIntial (StencilBundle bundle) { for (Stencil stencil : bundle) { for (StencilNode node : stencil.getAllNodes ()) { Expression[] rgIdx = node.getIndex ().getSpaceIndexEx (); Expression[] rgIdxNew = new Expression[rgIdx.length]; for (int i = 0; i < rgIdx.length; i++) { String strDimId = StencilSpecificationAnalyzer.getContainedDimensionIdentifier (rgIdx[i], i); if (strDimId != null) { // if an entry I contains the corresponding dimension identifier id, compute I-id // we expect this to be an integer value rgIdxNew[i] = Symbolic.simplify (new BinaryExpression (rgIdx[i].clone (), BinaryOperator.SUBTRACT, new NameID (strDimId))); if (!(rgIdxNew[i] instanceof IntegerLiteral)) { throw new RuntimeException (StringUtil.concat ("Illegal coordinate ", rgIdx[i].toString (), " in grid reference ", node.toString ()," in definition ", stencil.toString () )); } } else { // if the entry doesn't contain a dimension identifier, set the corresponding spatial index coordinate // to 0 (=> do something when the point becomes the center point), and add a constraint setting the // corresponding subdomain index (dimension identifier) to the expression of the index entry rgIdxNew[i] = new IntegerLiteral (0); node.addConstraint (new BinaryExpression (new NameID (CodeGeneratorUtil.getDimensionName (i)), BinaryOperator.COMPARE_EQ, rgIdx[i])); } } node.getIndex ().setSpaceIndex (rgIdxNew); } } } /** * Check that all the stencil nodes in the stencils of the bundle are legal, * i.e., that the spatial index has the form [x+dx, y+dy, ...]. Note that * the dimension identifiers (x, y, ...) have been subtracted already, so * the spatial index should be an array of integer numbers. * * @param bundle * The bundle to check */ public static void checkStencilNodesLegality (StencilBundle bundle) { for (Stencil stencil : bundle) for (StencilNode node : stencil) for (Expression exprIdx : node.getIndex ().getSpaceIndexEx ()) if (!(exprIdx instanceof IntegerLiteral)) throw new RuntimeException (StringUtil.concat ("Illegal grid reference", exprIdx.toString ())); // TODO: handle in parser } /** * Determines whether the expression <code>expr</code> contains a dimension * identifier corresponding to dimension <code>nDim</code>. * * @param expr * The expression to examine * @param nDim * The dimension whose identifier to detect * @return <code>true</code> iff <code>expr</code> contains a dimension * identifier corresponding to the dimension <code>nDim</code> */ public static String getContainedDimensionIdentifier (Expression expr, int nDim) { String strId = CodeGeneratorUtil.getDimensionName (nDim); String strIdAlt = CodeGeneratorUtil.getAltDimensionName (nDim); for (DepthFirstIterator it = new DepthFirstIterator (Symbolic.simplify (expr)); it.hasNext (); ) { Object o = it.next (); if (o instanceof IDExpression) { if (((IDExpression) o).getName ().equals (strId)) return strId; if (((IDExpression) o).getName ().equals (strIdAlt)) return strIdAlt; } } return null; } }
matthias-christen/patus
src/ch/unibas/cs/hpwc/patus/grammar/stencil2/StencilSpecificationAnalyzer.java
Java
lgpl-2.1
4,059
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #define SOFA_COMPONENT_FORCEFIELD_SURFACEPRESSUREFORCEFIELD_CPP #include <SofaBoundaryCondition/SurfacePressureForceField.inl> #include <sofa/core/ObjectFactory.h> #include <sofa/defaulttype/Vec3Types.h> namespace sofa { namespace component { namespace forcefield { using namespace sofa::defaulttype; SOFA_DECL_CLASS(SurfacePressureForceField) int SurfacePressureForceFieldClass = core::RegisterObject("SurfacePressure") #ifndef SOFA_FLOAT .add< SurfacePressureForceField<Vec3dTypes> >() .add< SurfacePressureForceField<Rigid3Types> >() #endif #ifndef SOFA_DOUBLE .add< SurfacePressureForceField<Vec3fTypes> >() .add< SurfacePressureForceField<Rigid3fTypes> >() #endif ; #ifndef SOFA_FLOAT template class SOFA_BOUNDARY_CONDITION_API SurfacePressureForceField<Vec3dTypes>; template class SOFA_BOUNDARY_CONDITION_API SurfacePressureForceField<Rigid3dTypes>; #endif #ifndef SOFA_DOUBLE template class SOFA_BOUNDARY_CONDITION_API SurfacePressureForceField<Vec3fTypes>; template class SOFA_BOUNDARY_CONDITION_API SurfacePressureForceField<Rigid3fTypes>; #endif } // namespace forcefield } // namespace component } // namespace sofa
FabienPean/sofa
modules/SofaBoundaryCondition/SurfacePressureForceField.cpp
C++
lgpl-2.1
2,847
/* * ALMA - Atacama Large Millimiter Array (c) European Southern Observatory, 2010 * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package alma.acs.alarmsystemprofiler.document.flood; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.Vector; import org.eclipse.jface.viewers.TableViewer; import cern.laser.client.data.Alarm; import alma.acs.alarmsystemprofiler.document.DocumentBase; import alma.acs.alarmsystemprofiler.engine.AlarmCategoryListener; import alma.acs.alarmsystemprofiler.save.TableData; /** * Count the number of floods and generate the statistics * * @author acaproni */ public class FloodContainer extends DocumentBase implements AlarmCategoryListener { public enum FloodItem { NUM_OF_FLOODS("Num. of floods",false,false), ACTUALLY_IN_FLOOD("Actually in flood", false,true), TOT_ALARMS("Tot. alarms in floods",false,false), HIGHEST_ALARMS("Highest num. of alarms in flood",false,false), AVG_ALARMS("Avg. alarms per flood",false,false), MEASURED_TIME("Monitoring time",true,false), FLOOD_TIME("Time of Alarm service in flood",true,false); /** * The name show in the first column */ public String description; /** * <code>true</code> if number represents a time value */ private final boolean isTime; /** * <code>true</code> if number represents a boolean value (0 means <code>false</code>, * all other values mean <code>true</code>) */ private final boolean isBoolean; /** * The value */ private Number value; /** * The formatter of the times */ private static final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss.S"); /** * Constructor * * @param name The description of the value */ private FloodItem(String name, boolean isTm, boolean isBool) { this.description=name; this.isTime=isTm; this.isBoolean=isBool; value=Integer.valueOf(0); } public void setNumber(Number newValue) { value=newValue; } /** * Getter */ public Number getValue() { return value; } @Override public String toString() { if (isBoolean) { int val = value.intValue(); if (val==0) { return "No"; } else { return "Yes"; } } if (isTime) { Date date = new Date(value.longValue()); Calendar cal = Calendar.getInstance(); cal.setTime(date); int day = cal.get(Calendar.DAY_OF_MONTH)-1; synchronized (timeFormat) { if (day>0) { return ""+day+" days, "+timeFormat.format(date); } else { return timeFormat.format(date); } } } if ((value instanceof Float) || (value instanceof Double)) { double d = value.doubleValue(); return String.format("%.2f", d); } return value.toString(); } }; /** * The singleton */ private static FloodContainer singleton=null; public static FloodContainer getInstance() { if (singleton==null) { singleton = new FloodContainer(); } return singleton; } /** * Constructor */ private FloodContainer() { super("Alarm floods statistics", new String[] { "Entry", "Value" }); actualFlood=new AlarmFlood(this); } /** * The floods registered since the system started */ private final Vector<AlarmFlood> floods = new Vector<AlarmFlood>(); /** * The start time of this container in mesec */ private final long startTime=System.currentTimeMillis(); /** * The actual counter of alarm floods */ private AlarmFlood actualFlood; /** * * @return The number of alarms registered in all the floods */ public synchronized int getTotAlarmsInFloods() { int ret=0; for (AlarmFlood af: floods) { ret+=af.getAlarmsInFlood(); } ret+=actualFlood.getAlarmsInFlood(); return ret; } /** * * @return The total time the alarm system was in flood in msec */ public synchronized long getTotTimeInFloods() { long ret=0; for (AlarmFlood af: floods) { ret+=af.lengthOfFlood(); } if (actualFlood.getStartTimeOfFlood()>0) { ret+=actualFlood.lengthOfFlood(); } return ret; } /** * * @return The average number of alarms registered in all the floods */ public synchronized float getAvgAlarmsInFloods() { if (floods.size()==0) { return 0; } float ret=0; for (AlarmFlood af: floods) { ret+=af.getAlarmsInFlood(); } return ret/(float)floods.size(); } /** * * @return The highest number of alarms registered between all the floods */ public synchronized int getHighestAlarmsCountInFloods() { int ret=0; for (AlarmFlood af: floods) { if (ret<af.getAlarmsInFlood()) { ret=af.getAlarmsInFlood(); } } return ret; } /** * @return The total number of floods */ public synchronized int getNumOfFloods() { return floods.size(); } /** * @return The values of the flood to be shown in the table */ @Override public synchronized Collection<FloodItem> getNumbers() { FloodItem.AVG_ALARMS.setNumber(Float.valueOf(getAvgAlarmsInFloods())); FloodItem.FLOOD_TIME.setNumber(Long.valueOf(getTotTimeInFloods())); FloodItem.HIGHEST_ALARMS.setNumber(Integer.valueOf(getHighestAlarmsCountInFloods())); FloodItem.MEASURED_TIME.setNumber(Long.valueOf(System.currentTimeMillis()-startTime)); FloodItem.NUM_OF_FLOODS.setNumber(Integer.valueOf(getNumOfFloods())); FloodItem.TOT_ALARMS.setNumber(Integer.valueOf(getTotAlarmsInFloods())); FloodItem.ACTUALLY_IN_FLOOD.setNumber(Integer.valueOf(actualFlood.isFloodStarted()?1:0)); Vector<FloodContainer.FloodItem> ret= new Vector<FloodContainer.FloodItem>(FloodItem.values().length); for (FloodItem fi: FloodItem.values()) { ret.add(fi); } return ret; } @Override public synchronized void shutdownContainer() { super.shutdownContainer(); actualFlood.stop(); } @Override public void setTableViewer(TableViewer table) { super.setTableViewer(table); } public synchronized void doneFlood() { floods.add(actualFlood); actualFlood=new AlarmFlood(this); System.out.println("Refreshing table"); System.out.println("doneFlood done"); } @Override public synchronized void onAlarm(Alarm alarm) { actualFlood.onAlarm(alarm); } @Override public void setTableContent(TableData tData) { Collection<FloodItem> vals=getNumbers(); for (FloodItem val: vals) { String[] row = new String[2]; row[0]=val.description; row[1]=val.toString(); tData.addRowData(row); } } }
ACS-Community/ACS
LGPL/CommonSoftware/acsGUIs/AlarmSystemProfiler/src/alma/acs/alarmsystemprofiler/document/flood/FloodContainer.java
Java
lgpl-2.1
7,180
/* * Copyright 2011 Stephen Liu * For license terms, see the file COPYING along with this library. */ #include <vector> #include <unistd.h> #include <errno.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include "spnkprefork.hpp" #include "spnklog.hpp" #include "spnkstr.hpp" #include "spnksocket.hpp" typedef struct tagSP_NKPreforkManagerImpl { SP_NKPreforkManager::Handler_t mHandler; void * mArgs; int mMaxProcs; int mCheckInterval; std::vector< pid_t > mPidList; } SP_NKPreforkManagerImpl_t; SP_NKPreforkManager :: SP_NKPreforkManager( Handler_t handler, void * args, int maxProcs, int checkInterval ) { mImpl = new SP_NKPreforkManagerImpl_t; mImpl->mHandler = handler; mImpl->mArgs = args; mImpl->mMaxProcs = maxProcs; mImpl->mCheckInterval = checkInterval; if( mImpl->mCheckInterval <= 0 ) checkInterval = 1; } SP_NKPreforkManager :: ~SP_NKPreforkManager() { delete mImpl; mImpl = NULL; } int SP_NKPreforkManager :: run() { pid_t pid = fork(); if( 0 == pid ) { runForever(); return 0; } else if( pid > 0 ) { SP_NKLog::log( LOG_DEBUG, "fork proc master %d", pid ); } else { SP_NKLog::log( LOG_ERR, "fork fail, errno %d, %s", errno, strerror( errno ) ); } return pid > 0 ? 0 : -1; } void SP_NKPreforkManager :: termHandler( int sig ) { kill( 0, SIGTERM ); exit( 0 ); } void SP_NKPreforkManager :: runForever() { signal( SIGCHLD, SIG_IGN ); signal( SIGTERM, termHandler ); for( int i = 0; i < mImpl->mMaxProcs; i++ ) { pid_t pid = fork(); if( 0 == pid ) { mImpl->mHandler( i, mImpl->mArgs ); exit( 0 ); } else if( pid > 0 ) { SP_NKLog::log( LOG_DEBUG, "fork proc#%d %d", i, pid ); mImpl->mPidList.push_back( pid ); } else { SP_NKLog::log( LOG_ERR, "fork fail, errno %d, %s", errno, strerror( errno ) ); exit( -1 ); } } for( ; ; ) { sleep( mImpl->mCheckInterval ); for( int i = 0; i < (int)mImpl->mPidList.size(); i++ ) { pid_t pid = mImpl->mPidList[i]; if( 0 != kill( pid, 0 ) ) { SP_NKLog::log( LOG_ERR, "proc#%d %d is not exists", i, pid ); pid = fork(); if( 0 == pid ) { mImpl->mHandler( i, mImpl->mArgs ); exit( 0 ); } else if( pid > 0 ) { SP_NKLog::log( LOG_DEBUG, "fork proc#%d %d to replace %d", i, pid, mImpl->mPidList[i] ); mImpl->mPidList[i] = pid; } else { SP_NKLog::log( LOG_ERR, "fork fail, errno %d, %s", errno, strerror( errno ) ); // leave pid for next check } } } } } void SP_NKPreforkManager :: shutdown() { kill( 0, SIGTERM ); } //=========================================================================== typedef struct tagSP_NKPreforkServerImpl { char mBindIP[ 64 ]; int mPort; SP_NKPreforkServer::OnRequest_t mOnRequest; void * mProcArgs; int mMaxProcs; int mCheckInterval; int mListenFD; int mMaxRequestsPerChild; SP_NKPreforkServer::BeforeChildRun_t mBeforeChildRun; SP_NKPreforkServer::AfterChildRun_t mAfterChildRun; } SP_NKPreforkServerImpl_t; SP_NKPreforkServer :: SP_NKPreforkServer( const char * bindIP, int port, OnRequest_t onRequest, void * procArgs ) { mImpl = (SP_NKPreforkServerImpl_t*)calloc( sizeof( SP_NKPreforkServerImpl_t ), 1 ); SP_NKStr::strlcpy( mImpl->mBindIP, bindIP, sizeof( mImpl->mBindIP ) ); mImpl->mPort = port; mImpl->mOnRequest = onRequest; mImpl->mProcArgs = procArgs; mImpl->mMaxProcs = 8; mImpl->mCheckInterval = 1; mImpl->mMaxRequestsPerChild = 10000; mImpl->mListenFD = -1; } SP_NKPreforkServer :: ~SP_NKPreforkServer() { if( mImpl->mListenFD >= 0 ) close( mImpl->mListenFD ); free( mImpl ); mImpl = NULL; } void SP_NKPreforkServer :: setBeforeChildRun( BeforeChildRun_t beforeChildRun ) { mImpl->mBeforeChildRun = beforeChildRun; } void SP_NKPreforkServer :: setAfterChildRun( AfterChildRun_t afterChildRun ) { mImpl->mAfterChildRun = afterChildRun; } void SP_NKPreforkServer :: setPreforkArgs( int maxProcs, int checkInterval, int maxRequestsPerChild ) { mImpl->mMaxProcs = maxProcs; mImpl->mCheckInterval = checkInterval; mImpl->mMaxRequestsPerChild = maxRequestsPerChild; } int SP_NKPreforkServer :: run() { pid_t pid = fork(); if( 0 == pid ) { runForever(); return 0; } else if( pid > 0 ) { SP_NKLog::log( LOG_DEBUG, "fork proc master %d", pid ); } else { SP_NKLog::log( LOG_ERR, "fork fail, errno %d, %s", errno, strerror( errno ) ); } return pid > 0 ? 0 : -1; } void SP_NKPreforkServer :: runForever() { #ifdef SIGPIPE /* Don't die with SIGPIPE on remote read shutdown. That's dumb. */ signal( SIGPIPE, SIG_IGN ); #endif int ret = 0; int listenFD = -1; ret = SP_NKSocket::tcpListen( mImpl->mBindIP, mImpl->mPort, &listenFD, 1 ); if( 0 == ret ) { mImpl->mListenFD = listenFD; SP_NKPreforkManager manager( serverHandler, mImpl, mImpl->mMaxProcs, mImpl->mCheckInterval ); manager.runForever(); } else { SP_NKLog::log( LOG_ERR, "list fail, errno %d, %s", errno, strerror( errno ) ); } } void SP_NKPreforkServer :: serverHandler( int index, void * args ) { SP_NKPreforkServerImpl_t * impl = (SP_NKPreforkServerImpl_t*)args; if( NULL != impl->mBeforeChildRun ) { impl->mBeforeChildRun( impl->mProcArgs ); } int factor = impl->mMaxRequestsPerChild / 10; factor = factor <= 0 ? 1 : factor; int maxRequestsPerChild = impl->mMaxRequestsPerChild + factor * index; for( int i= 0; i < maxRequestsPerChild; i++ ) { struct sockaddr_in addr; socklen_t socklen = sizeof( addr ); int fd = accept( impl->mListenFD, (struct sockaddr*)&addr, &socklen ); if( fd >= 0 ) { impl->mOnRequest( fd, impl->mProcArgs ); close( fd ); } else { SP_NKLog::log( LOG_ERR, "accept fail, errno %d, %s", errno, strerror( errno ) ); } } if( NULL != impl->mAfterChildRun ) { impl->mAfterChildRun( impl->mProcArgs ); } } void SP_NKPreforkServer :: shutdown() { kill( 0, SIGTERM ); } //=========================================================================== int SP_NKPreforkServer :: initDaemon( const char * workdir ) { pid_t pid; if ( (pid = fork()) < 0) return (-1); else if (pid) _exit(0); /* parent terminates */ /* child 1 continues... */ if (setsid() < 0) /* become session leader */ return (-1); assert( signal( SIGHUP, SIG_IGN ) != SIG_ERR ); assert( signal( SIGPIPE, SIG_IGN ) != SIG_ERR ); assert( signal( SIGALRM, SIG_IGN ) != SIG_ERR ); assert( signal( SIGCHLD, SIG_IGN ) != SIG_ERR ); if ( (pid = fork()) < 0) return (-1); else if (pid) _exit(0); /* child 1 terminates */ /* child 2 continues... */ if( NULL != workdir ) chdir( workdir ); /* change working directory */ /* close off file descriptors */ for (int i = 0; i < 64; i++) close(i); /* redirect stdin, stdout, and stderr to /dev/null */ open("/dev/null", O_RDONLY); open("/dev/null", O_RDWR); open("/dev/null", O_RDWR); return (0); /* success */ }
spsoft/spnetkit
spnetkit/spnkprefork.cpp
C++
lgpl-2.1
6,852
package org.exist.source; import java.io.*; import java.util.Map; import org.exist.security.PermissionDeniedException; import org.exist.security.Subject; import org.exist.storage.DBBroker; /** * A simple source object wrapping a single query string, but associating it with a specific * map (e.g., of namespace bindings). This prevents two textually equal queries with different * maps from getting aliased in the query pool. * * @author <a href="mailto:piotr@ideanest.com">Piotr Kaminski</a> */ public class StringSourceWithMapKey extends AbstractSource { private final Map<String, String> map; /** * Create a new source for the given content and namespace map (string to string). * The map will be taken over and modified by the source, so make a copy first if * you're passing a shared one. * * @param content the content of the query * @param map the map of prefixes to namespace URIs */ public StringSourceWithMapKey(String content, Map<String, String> map) { this.map = map; this.map.put("<query>", content); } @Override public String path() { return type(); } @Override public String type() { return "StringWithMapKey"; } public Object getKey() {return map;} public int isValid(DBBroker broker) {return Source.VALID;} public int isValid(Source other) {return Source.VALID;} public Reader getReader() throws IOException {return new StringReader(map.get("<query>"));} public InputStream getInputStream() throws IOException { // not implemented return null; } public String getContent() throws IOException {return map.get("<query>");} @Override public void validate(Subject subject, int perm) throws PermissionDeniedException { // TODO protected? } }
jensopetersen/exist
src/org/exist/source/StringSourceWithMapKey.java
Java
lgpl-2.1
1,741
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_TOPOJSON_UTILS_HPP #define MAPNIK_TOPOJSON_UTILS_HPP // mapnik #include <mapnik/box2d.hpp> #include <mapnik/json/topology.hpp> namespace mapnik { namespace topojson { struct bounding_box_visitor { bounding_box_visitor(topology const& topo) : topo_(topo), num_arcs_(topo_.arcs.size()) {} box2d<double> operator() (mapnik::topojson::point const& pt) const { double x = pt.coord.x; double y = pt.coord.y; if (topo_.tr) { x = x * (*topo_.tr).scale_x + (*topo_.tr).translate_x; y = y * (*topo_.tr).scale_y + (*topo_.tr).translate_y; } return box2d<double>(x, y, x, y); } box2d<double> operator() (mapnik::topojson::multi_point const& multi_pt) const { box2d<double> bbox; if (num_arcs_ > 0) { bool first = true; for (auto const& pt : multi_pt.points) { double x = pt.x; double y = pt.y; if (topo_.tr) { x = x * (*topo_.tr).scale_x + (*topo_.tr).translate_x; y = y * (*topo_.tr).scale_y + (*topo_.tr).translate_y; // TODO : delta encoded ? } if (first) { first = false; bbox.init(x,y,x,y); } else { bbox.expand_to_include(x,y); } } } return bbox; } box2d<double> operator() (mapnik::topojson::linestring const& line) const { box2d<double> bbox; if (num_arcs_ > 0) { index_type index = line.ring; index_type arc_index = index < 0 ? std::abs(index) - 1 : index; if (arc_index >= 0 && arc_index < static_cast<int>(num_arcs_)) { bool first = true; double px = 0, py = 0; auto const& arcs = topo_.arcs[arc_index]; for (auto pt : arcs.coordinates) { double x = pt.x; double y = pt.y; if (topo_.tr) { x = (px += x) * (*topo_.tr).scale_x + (*topo_.tr).translate_x; y = (py += y) * (*topo_.tr).scale_y + (*topo_.tr).translate_y; } if (first) { first = false; bbox.init(x, y, x, y); } else { bbox.expand_to_include(x, y); } } } } return bbox; } box2d<double> operator() (mapnik::topojson::multi_linestring const& multi_line) const { box2d<double> bbox; if (num_arcs_ > 0) { bool first = true; for (auto index : multi_line.rings) { index_type arc_index = index < 0 ? std::abs(index) - 1 : index; if (arc_index >= 0 && arc_index < static_cast<int>(num_arcs_)) { double px = 0, py = 0; auto const& arcs = topo_.arcs[arc_index]; for (auto pt : arcs.coordinates) { double x = pt.x; double y = pt.y; if (topo_.tr) { x = (px += x) * (*topo_.tr).scale_x + (*topo_.tr).translate_x; y = (py += y) * (*topo_.tr).scale_y + (*topo_.tr).translate_y; } if (first) { first = false; bbox.init(x, y, x, y); } else { bbox.expand_to_include(x, y); } } } } } return bbox; } box2d<double> operator() (mapnik::topojson::polygon const& poly) const { box2d<double> bbox; if (num_arcs_ > 0) { bool first = true; for (auto const& ring : poly.rings) { for (auto index : ring) { index_type arc_index = index < 0 ? std::abs(index) - 1 : index; if (arc_index >= 0 && arc_index < static_cast<int>(num_arcs_)) { double px = 0, py = 0; auto const& arcs = topo_.arcs[arc_index]; for (auto const& pt : arcs.coordinates) { double x = pt.x; double y = pt.y; if (topo_.tr) { x = (px += x) * (*topo_.tr).scale_x + (*topo_.tr).translate_x; y = (py += y) * (*topo_.tr).scale_y + (*topo_.tr).translate_y; } if (first) { first = false; bbox.init( x, y, x, y); } else { bbox.expand_to_include(x, y); } } } } } } return bbox; } box2d<double> operator() (mapnik::topojson::multi_polygon const& multi_poly) const { box2d<double> bbox; if (num_arcs_ > 0) { bool first = true; for (auto const& poly : multi_poly.polygons) { for (auto const& ring : poly) { for (auto index : ring) { index_type arc_index = index < 0 ? std::abs(index) - 1 : index; if (arc_index >= 0 && arc_index < static_cast<int>(num_arcs_)) { double px = 0, py = 0; auto const& arcs = topo_.arcs[arc_index]; for (auto const& pt : arcs.coordinates) { double x = pt.x; double y = pt.y; if (topo_.tr) { x = (px += x) * (*topo_.tr).scale_x + (*topo_.tr).translate_x; y = (py += y) * (*topo_.tr).scale_y + (*topo_.tr).translate_y; } if (first) { first = false; bbox.init( x, y, x, y); } else { bbox.expand_to_include(x, y); } } } } } } } return bbox; } private: topology const& topo_; std::size_t num_arcs_; }; }} #endif //MAPNIK_TOPOJSON_UTILS_HPP
stefanklug/mapnik
include/mapnik/json/topojson_utils.hpp
C++
lgpl-2.1
8,585
package railo.runtime.listener; import railo.commons.lang.types.RefBoolean; import railo.commons.lang.types.RefBooleanImpl; import railo.runtime.PageContext; import railo.runtime.PageSource; import railo.runtime.exp.PageException; public final class MixedAppListener extends ModernAppListener { @Override public void onRequest(PageContext pc, PageSource requestedPage, RequestListener rl) throws PageException { RefBoolean isCFC=new RefBooleanImpl(false); PageSource appPS=//pc.isCFCRequest()?null: AppListenerUtil.getApplicationPageSource(pc, requestedPage, mode, isCFC); if(isCFC.toBooleanValue())_onRequest(pc, requestedPage,appPS,rl); else ClassicAppListener._onRequest(pc, requestedPage,appPS,rl); } @Override public final String getType() { return "mixed"; } }
JordanReiter/railo
railo-java/railo-core/src/railo/runtime/listener/MixedAppListener.java
Java
lgpl-2.1
797
v.setCursorPosition(0,19); v.type('/'); v.type('/'); v.type('/'); v.type('/'); v.type("ok");
hlamer/kate
tests/data/indent/cppstyle/comment11/input.js
JavaScript
lgpl-2.1
93
/* This file is part of KAddressBook. Copyright (c) 2002 Mike Pilone <mpilone@slac.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "viewconfigurefilterpage.h" #include <QtGui/QBoxLayout> #include <QtGui/QButtonGroup> #include <QtGui/QHBoxLayout> #include <QtGui/QLabel> #include <QtGui/QRadioButton> #include <QtGui/QVBoxLayout> #include <kconfig.h> #include <kcombobox.h> #include <kdialog.h> #include <klocale.h> #include "filter.h" ViewConfigureFilterPage::ViewConfigureFilterPage( QWidget *parent, const char *name ) : QWidget( parent ) { setObjectName( name ); QBoxLayout *topLayout = new QVBoxLayout( this ); topLayout->setSpacing( KDialog::spacingHint() ); topLayout->setMargin( 0 ); mFilterGroup = new QButtonGroup(); connect( mFilterGroup, SIGNAL( buttonClicked( int ) ), SLOT( buttonClicked( int ) ) ); QLabel *label = new QLabel( i18n( "The default filter will be activated whenever" " this view is displayed. This feature allows you to configure views that only" " interact with certain types of information based on the filter. Once the view" " is activated, the filter can be changed at anytime." ), this ); label->setAlignment( Qt::AlignLeft | Qt::AlignTop ); label->setWordWrap( true ); topLayout->addWidget( label ); QWidget *spacer = new QWidget( this ); spacer->setMinimumHeight( 5 ); topLayout->addWidget( spacer ); QRadioButton *button = new QRadioButton( i18n( "No default filter" ), this ); mFilterGroup->addButton( button,0 ); topLayout->addWidget( button ); button = new QRadioButton( i18n( "Use last active filter" ), this ); mFilterGroup->addButton( button,1 ); topLayout->addWidget( button ); QBoxLayout *comboLayout = new QHBoxLayout(); topLayout->addLayout( comboLayout ); button = new QRadioButton( i18n( "Use filter:" ), this ); mFilterGroup->addButton( button,2 ); comboLayout->addWidget( button ); mFilterCombo = new KComboBox( this ); comboLayout->addWidget( mFilterCombo ); topLayout->addStretch( 100 ); } ViewConfigureFilterPage::~ViewConfigureFilterPage() { } void ViewConfigureFilterPage::restoreSettings( const KConfigGroup &config ) { mFilterCombo->clear(); // Load the filter combo const Filter::List list = Filter::restore( config.config(), "Filter" ); Filter::List::ConstIterator it; for ( it = list.begin(); it != list.end(); ++it ) mFilterCombo->addItem( (*it).name() ); int id = config.readEntry( "DefaultFilterType", 1 ); mFilterGroup->button ( id )->setChecked(true); buttonClicked( id ); if ( id == 2 ) // has default filter mFilterCombo->setItemText( mFilterCombo->currentIndex(), config.readEntry( "DefaultFilterName" ) ); } void ViewConfigureFilterPage::saveSettings( KConfigGroup &config ) { config.writeEntry( "DefaultFilterName", mFilterCombo->currentText() ); config.writeEntry( "DefaultFilterType", mFilterGroup->id( mFilterGroup->checkedButton() ) ); } void ViewConfigureFilterPage::buttonClicked( int id ) { mFilterCombo->setEnabled( id == 2 ); } #include "viewconfigurefilterpage.moc"
lefou/kdepim-noakonadi
kaddressbook/viewconfigurefilterpage.cpp
C++
lgpl-2.1
4,025
/* A Bison parser, made by GNU Bison 2.4.1. */ /* Skeleton implementation for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.4.1" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 1 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* Using locations. */ #define YYLSP_NEEDED 1 /* Substitute the variable and function names. */ #define yyparse jscyyparse #define yylex jscyylex #define yyerror jscyyerror #define yylval jscyylval #define yychar jscyychar #define yydebug jscyydebug #define yynerrs jscyynerrs #define yylloc jscyylloc /* Copy the first part of user declarations. */ /* Line 189 of yacc.c */ #line 3 "../../JavaScriptCore/parser/Grammar.y" /* * Copyright (C) 1999-2000 Harri Porten (porten@kde.org) * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. * Copyright (C) 2007 Eric Seidel <eric@webkit.org> * * 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 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "config.h" #include <string.h> #include <stdlib.h> #include "JSValue.h" #include "JSObject.h" #include "Nodes.h" #include "Lexer.h" #include "JSString.h" #include "JSGlobalData.h" #include "CommonIdentifiers.h" #include "NodeInfo.h" #include "Parser.h" #include <wtf/MathExtras.h> #define YYMAXDEPTH 10000 #define YYENABLE_NLS 0 /* default values for bison */ #define YYDEBUG 0 // Set to 1 to debug a parse error. #define jscyydebug 0 // Set to 1 to debug a parse error. #if !PLATFORM(DARWIN) // avoid triggering warnings in older bison #define YYERROR_VERBOSE #endif int jscyylex(void* lvalp, void* llocp, void* globalPtr); int jscyyerror(const char*); static inline bool allowAutomaticSemicolon(JSC::Lexer&, int); #define GLOBAL_DATA static_cast<JSGlobalData*>(globalPtr) #define LEXER (GLOBAL_DATA->lexer) #define AUTO_SEMICOLON do { if (!allowAutomaticSemicolon(*LEXER, yychar)) YYABORT; } while (0) #define SET_EXCEPTION_LOCATION(node, start, divot, end) node->setExceptionSourceCode((divot), (divot) - (start), (end) - (divot)) #define DBG(l, s, e) (l)->setLoc((s).first_line, (e).last_line) using namespace JSC; using namespace std; static ExpressionNode* makeAssignNode(void*, ExpressionNode* loc, Operator, ExpressionNode* expr, bool locHasAssignments, bool exprHasAssignments, int start, int divot, int end); static ExpressionNode* makePrefixNode(void*, ExpressionNode* expr, Operator, int start, int divot, int end); static ExpressionNode* makePostfixNode(void*, ExpressionNode* expr, Operator, int start, int divot, int end); static PropertyNode* makeGetterOrSetterPropertyNode(void*, const Identifier &getOrSet, const Identifier& name, ParameterNode*, FunctionBodyNode*, const SourceCode&); static ExpressionNodeInfo makeFunctionCallNode(void*, ExpressionNodeInfo func, ArgumentsNodeInfo, int start, int divot, int end); static ExpressionNode* makeTypeOfNode(void*, ExpressionNode*); static ExpressionNode* makeDeleteNode(void*, ExpressionNode*, int start, int divot, int end); static ExpressionNode* makeNegateNode(void*, ExpressionNode*); static NumberNode* makeNumberNode(void*, double); static ExpressionNode* makeBitwiseNotNode(void*, ExpressionNode*); static ExpressionNode* makeMultNode(void*, ExpressionNode*, ExpressionNode*, bool rightHasAssignments); static ExpressionNode* makeDivNode(void*, ExpressionNode*, ExpressionNode*, bool rightHasAssignments); static ExpressionNode* makeAddNode(void*, ExpressionNode*, ExpressionNode*, bool rightHasAssignments); static ExpressionNode* makeSubNode(void*, ExpressionNode*, ExpressionNode*, bool rightHasAssignments); static ExpressionNode* makeLeftShiftNode(void*, ExpressionNode*, ExpressionNode*, bool rightHasAssignments); static ExpressionNode* makeRightShiftNode(void*, ExpressionNode*, ExpressionNode*, bool rightHasAssignments); static StatementNode* makeVarStatementNode(void*, ExpressionNode*); static ExpressionNode* combineVarInitializers(void*, ExpressionNode* list, AssignResolveNode* init); #if COMPILER(MSVC) #pragma warning(disable: 4065) #pragma warning(disable: 4244) #pragma warning(disable: 4702) // At least some of the time, the declarations of malloc and free that bison // generates are causing warnings. A way to avoid this is to explicitly define // the macros so that bison doesn't try to declare malloc and free. #define YYMALLOC malloc #define YYFREE free #endif #define YYPARSE_PARAM globalPtr #define YYLEX_PARAM globalPtr template <typename T> NodeDeclarationInfo<T> createNodeDeclarationInfo(T node, ParserRefCountedData<DeclarationStacks::VarStack>* varDecls, ParserRefCountedData<DeclarationStacks::FunctionStack>* funcDecls, CodeFeatures info, int numConstants) { ASSERT((info & ~AllFeatures) == 0); NodeDeclarationInfo<T> result = {node, varDecls, funcDecls, info, numConstants}; return result; } template <typename T> NodeInfo<T> createNodeInfo(T node, CodeFeatures info, int numConstants) { ASSERT((info & ~AllFeatures) == 0); NodeInfo<T> result = {node, info, numConstants}; return result; } template <typename T> T mergeDeclarationLists(T decls1, T decls2) { // decls1 or both are null if (!decls1) return decls2; // only decls1 is non-null if (!decls2) return decls1; // Both are non-null decls1->data.append(decls2->data); // We manually release the declaration lists to avoid accumulating many many // unused heap allocated vectors decls2->ref(); decls2->deref(); return decls1; } static void appendToVarDeclarationList(void* globalPtr, ParserRefCountedData<DeclarationStacks::VarStack>*& varDecls, const Identifier& ident, unsigned attrs) { if (!varDecls) varDecls = new ParserRefCountedData<DeclarationStacks::VarStack>(GLOBAL_DATA); varDecls->data.append(make_pair(ident, attrs)); } static inline void appendToVarDeclarationList(void* globalPtr, ParserRefCountedData<DeclarationStacks::VarStack>*& varDecls, ConstDeclNode* decl) { unsigned attrs = DeclarationStacks::IsConstant; if (decl->m_init) attrs |= DeclarationStacks::HasInitializer; appendToVarDeclarationList(globalPtr, varDecls, decl->m_ident, attrs); } /* Line 189 of yacc.c */ #line 236 "Grammar.tab.c" /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* Enabling the token table. */ #ifndef YYTOKEN_TABLE # define YYTOKEN_TABLE 0 #endif /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { NULLTOKEN = 258, TRUETOKEN = 259, FALSETOKEN = 260, BREAK = 261, CASE = 262, DEFAULT = 263, FOR = 264, NEW = 265, VAR = 266, CONSTTOKEN = 267, CONTINUE = 268, FUNCTION = 269, RETURN = 270, VOIDTOKEN = 271, DELETETOKEN = 272, IF = 273, THISTOKEN = 274, DO = 275, WHILE = 276, INTOKEN = 277, INSTANCEOF = 278, TYPEOF = 279, SWITCH = 280, WITH = 281, RESERVED = 282, THROW = 283, TRY = 284, CATCH = 285, FINALLY = 286, DEBUGGER = 287, IF_WITHOUT_ELSE = 288, ELSE = 289, EQEQ = 290, NE = 291, STREQ = 292, STRNEQ = 293, LE = 294, GE = 295, OR = 296, AND = 297, PLUSPLUS = 298, MINUSMINUS = 299, LSHIFT = 300, RSHIFT = 301, URSHIFT = 302, PLUSEQUAL = 303, MINUSEQUAL = 304, MULTEQUAL = 305, DIVEQUAL = 306, LSHIFTEQUAL = 307, RSHIFTEQUAL = 308, URSHIFTEQUAL = 309, ANDEQUAL = 310, MODEQUAL = 311, XOREQUAL = 312, OREQUAL = 313, OPENBRACE = 314, CLOSEBRACE = 315, NUMBER = 316, IDENT = 317, STRING = 318, AUTOPLUSPLUS = 319, AUTOMINUSMINUS = 320 }; #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE { /* Line 214 of yacc.c */ #line 157 "../../JavaScriptCore/parser/Grammar.y" int intValue; double doubleValue; Identifier* ident; // expression subtrees ExpressionNodeInfo expressionNode; FuncDeclNodeInfo funcDeclNode; PropertyNodeInfo propertyNode; ArgumentsNodeInfo argumentsNode; ConstDeclNodeInfo constDeclNode; CaseBlockNodeInfo caseBlockNode; CaseClauseNodeInfo caseClauseNode; FuncExprNodeInfo funcExprNode; // statement nodes StatementNodeInfo statementNode; FunctionBodyNode* functionBodyNode; ProgramNode* programNode; SourceElementsInfo sourceElements; PropertyListInfo propertyList; ArgumentListInfo argumentList; VarDeclListInfo varDeclList; ConstDeclListInfo constDeclList; ClauseListInfo clauseList; ElementListInfo elementList; ParameterListInfo parameterList; Operator op; /* Line 214 of yacc.c */ #line 371 "Grammar.tab.c" } YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 #endif #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; } YYLTYPE; # define yyltype YYLTYPE /* obsolescent; will be withdrawn */ # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif /* Copy the second part of user declarations. */ /* Line 264 of yacc.c */ #line 396 "Grammar.tab.c" #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(e) ((void) (e)) #else # define YYUSE(e) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(n) (n) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int yyi) #else static int YYID (yyi) int yyi; #endif { return yyi; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined _STDLIB_H \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \ && defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; YYLTYPE yyls_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \ + 2 * YYSTACK_GAP_MAXIMUM) /* Copy COUNT objects from FROM to TO. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(To, From, Count) \ __builtin_memcpy (To, From, (Count) * sizeof (*(From))) # else # define YYCOPY(To, From, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (To)[yyi] = (From)[yyi]; \ } \ while (YYID (0)) # endif # endif /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif /* YYFINAL -- State number of the termination state. */ #define YYFINAL 206 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 2349 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 88 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 194 /* YYNRULES -- Number of rules. */ #define YYNRULES 597 /* YYNRULES -- Number of states. */ #define YYNSTATES 1082 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 320 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 77, 2, 2, 2, 79, 82, 2, 68, 69, 78, 74, 70, 75, 73, 66, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 67, 87, 80, 86, 81, 85, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 71, 2, 72, 83, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 84, 2, 76, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint16 yyprhs[] = { 0, 0, 3, 5, 7, 9, 11, 13, 15, 17, 21, 25, 29, 37, 46, 48, 52, 54, 57, 61, 66, 68, 70, 72, 74, 78, 82, 86, 92, 95, 100, 101, 103, 105, 108, 110, 112, 117, 121, 125, 127, 132, 136, 140, 142, 145, 147, 150, 153, 156, 161, 165, 168, 171, 176, 180, 183, 187, 189, 193, 195, 197, 199, 201, 203, 206, 209, 211, 214, 217, 220, 223, 226, 229, 232, 235, 238, 241, 244, 247, 250, 252, 254, 256, 258, 260, 264, 268, 272, 274, 278, 282, 286, 288, 292, 296, 298, 302, 306, 308, 312, 316, 320, 322, 326, 330, 334, 336, 340, 344, 348, 352, 356, 360, 362, 366, 370, 374, 378, 382, 384, 388, 392, 396, 400, 404, 408, 410, 414, 418, 422, 426, 428, 432, 436, 440, 444, 446, 450, 454, 458, 462, 464, 468, 470, 474, 476, 480, 482, 486, 488, 492, 494, 498, 500, 504, 506, 510, 512, 516, 518, 522, 524, 528, 530, 534, 536, 540, 542, 546, 548, 552, 554, 560, 562, 568, 570, 576, 578, 582, 584, 588, 590, 594, 596, 598, 600, 602, 604, 606, 608, 610, 612, 614, 616, 618, 620, 624, 626, 630, 632, 636, 638, 640, 642, 644, 646, 648, 650, 652, 654, 656, 658, 660, 662, 664, 666, 668, 670, 673, 677, 681, 685, 687, 690, 694, 699, 701, 704, 708, 713, 717, 721, 723, 727, 729, 732, 735, 738, 740, 743, 746, 752, 760, 768, 776, 782, 792, 803, 811, 820, 830, 831, 833, 834, 836, 839, 842, 846, 850, 853, 856, 860, 864, 867, 870, 874, 878, 884, 890, 894, 900, 901, 903, 905, 908, 912, 917, 920, 924, 928, 932, 936, 941, 949, 959, 962, 965, 973, 982, 989, 997, 1005, 1014, 1016, 1020, 1021, 1023, 1024, 1026, 1028, 1031, 1033, 1035, 1037, 1039, 1041, 1043, 1045, 1049, 1053, 1057, 1065, 1074, 1076, 1080, 1082, 1085, 1089, 1094, 1096, 1098, 1100, 1102, 1106, 1110, 1114, 1120, 1123, 1128, 1129, 1131, 1133, 1136, 1138, 1140, 1145, 1149, 1153, 1155, 1160, 1164, 1168, 1170, 1173, 1175, 1178, 1181, 1184, 1189, 1193, 1196, 1199, 1204, 1208, 1211, 1215, 1217, 1221, 1223, 1225, 1227, 1229, 1231, 1234, 1237, 1239, 1242, 1245, 1248, 1251, 1254, 1257, 1260, 1263, 1266, 1269, 1272, 1275, 1278, 1280, 1282, 1284, 1286, 1288, 1292, 1296, 1300, 1302, 1306, 1310, 1314, 1316, 1320, 1324, 1326, 1330, 1334, 1336, 1340, 1344, 1348, 1350, 1354, 1358, 1362, 1364, 1368, 1372, 1376, 1380, 1384, 1388, 1390, 1394, 1398, 1402, 1406, 1410, 1412, 1416, 1420, 1424, 1428, 1432, 1436, 1438, 1442, 1446, 1450, 1454, 1456, 1460, 1464, 1468, 1472, 1474, 1478, 1482, 1486, 1490, 1492, 1496, 1498, 1502, 1504, 1508, 1510, 1514, 1516, 1520, 1522, 1526, 1528, 1532, 1534, 1538, 1540, 1544, 1546, 1550, 1552, 1556, 1558, 1562, 1564, 1568, 1570, 1574, 1576, 1580, 1582, 1588, 1590, 1596, 1598, 1604, 1606, 1610, 1612, 1616, 1618, 1622, 1624, 1626, 1628, 1630, 1632, 1634, 1636, 1638, 1640, 1642, 1644, 1646, 1648, 1652, 1654, 1658, 1660, 1664, 1666, 1668, 1670, 1672, 1674, 1676, 1678, 1680, 1682, 1684, 1686, 1688, 1690, 1692, 1694, 1696, 1698, 1701, 1705, 1709, 1713, 1715, 1718, 1722, 1727, 1729, 1732, 1736, 1741, 1745, 1749, 1751, 1755, 1757, 1760, 1763, 1766, 1768, 1771, 1774, 1780, 1788, 1796, 1804, 1810, 1820, 1831, 1839, 1848, 1858, 1859, 1861, 1862, 1864, 1867, 1870, 1874, 1878, 1881, 1884, 1888, 1892, 1895, 1898, 1902, 1906, 1912, 1918, 1922, 1928, 1929, 1931, 1933, 1936, 1940, 1945, 1948, 1952, 1956, 1960, 1964, 1969, 1977, 1987, 1990, 1993, 2001, 2010, 2017, 2025, 2033, 2042, 2044, 2048, 2049, 2051, 2053 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int16 yyrhs[] = { 184, 0, -1, 3, -1, 4, -1, 5, -1, 61, -1, 63, -1, 66, -1, 51, -1, 62, 67, 143, -1, 63, 67, 143, -1, 61, 67, 143, -1, 62, 62, 68, 69, 59, 183, 60, -1, 62, 62, 68, 182, 69, 59, 183, 60, -1, 90, -1, 91, 70, 90, -1, 93, -1, 59, 60, -1, 59, 91, 60, -1, 59, 91, 70, 60, -1, 19, -1, 89, -1, 94, -1, 62, -1, 68, 147, 69, -1, 71, 96, 72, -1, 71, 95, 72, -1, 71, 95, 70, 96, 72, -1, 96, 143, -1, 95, 70, 96, 143, -1, -1, 97, -1, 70, -1, 97, 70, -1, 92, -1, 181, -1, 98, 71, 147, 72, -1, 98, 73, 62, -1, 10, 98, 104, -1, 93, -1, 99, 71, 147, 72, -1, 99, 73, 62, -1, 10, 98, 104, -1, 98, -1, 10, 100, -1, 99, -1, 10, 100, -1, 98, 104, -1, 102, 104, -1, 102, 71, 147, 72, -1, 102, 73, 62, -1, 99, 104, -1, 103, 104, -1, 103, 71, 147, 72, -1, 103, 73, 62, -1, 68, 69, -1, 68, 105, 69, -1, 143, -1, 105, 70, 143, -1, 100, -1, 102, -1, 101, -1, 103, -1, 106, -1, 106, 43, -1, 106, 44, -1, 107, -1, 107, 43, -1, 107, 44, -1, 17, 111, -1, 16, 111, -1, 24, 111, -1, 43, 111, -1, 64, 111, -1, 44, 111, -1, 65, 111, -1, 74, 111, -1, 75, 111, -1, 76, 111, -1, 77, 111, -1, 108, -1, 110, -1, 109, -1, 110, -1, 111, -1, 113, 78, 111, -1, 113, 66, 111, -1, 113, 79, 111, -1, 112, -1, 114, 78, 111, -1, 114, 66, 111, -1, 114, 79, 111, -1, 113, -1, 115, 74, 113, -1, 115, 75, 113, -1, 114, -1, 116, 74, 113, -1, 116, 75, 113, -1, 115, -1, 117, 45, 115, -1, 117, 46, 115, -1, 117, 47, 115, -1, 116, -1, 118, 45, 115, -1, 118, 46, 115, -1, 118, 47, 115, -1, 117, -1, 119, 80, 117, -1, 119, 81, 117, -1, 119, 39, 117, -1, 119, 40, 117, -1, 119, 23, 117, -1, 119, 22, 117, -1, 117, -1, 120, 80, 117, -1, 120, 81, 117, -1, 120, 39, 117, -1, 120, 40, 117, -1, 120, 23, 117, -1, 118, -1, 121, 80, 117, -1, 121, 81, 117, -1, 121, 39, 117, -1, 121, 40, 117, -1, 121, 23, 117, -1, 121, 22, 117, -1, 119, -1, 122, 35, 119, -1, 122, 36, 119, -1, 122, 37, 119, -1, 122, 38, 119, -1, 120, -1, 123, 35, 120, -1, 123, 36, 120, -1, 123, 37, 120, -1, 123, 38, 120, -1, 121, -1, 124, 35, 119, -1, 124, 36, 119, -1, 124, 37, 119, -1, 124, 38, 119, -1, 122, -1, 125, 82, 122, -1, 123, -1, 126, 82, 123, -1, 124, -1, 127, 82, 122, -1, 125, -1, 128, 83, 125, -1, 126, -1, 129, 83, 126, -1, 127, -1, 130, 83, 125, -1, 128, -1, 131, 84, 128, -1, 129, -1, 132, 84, 129, -1, 130, -1, 133, 84, 128, -1, 131, -1, 134, 42, 131, -1, 132, -1, 135, 42, 132, -1, 133, -1, 136, 42, 131, -1, 134, -1, 137, 41, 134, -1, 135, -1, 138, 41, 135, -1, 136, -1, 139, 41, 134, -1, 137, -1, 137, 85, 143, 67, 143, -1, 138, -1, 138, 85, 144, 67, 144, -1, 139, -1, 139, 85, 143, 67, 143, -1, 140, -1, 106, 146, 143, -1, 141, -1, 106, 146, 144, -1, 142, -1, 107, 146, 143, -1, 86, -1, 48, -1, 49, -1, 50, -1, 51, -1, 52, -1, 53, -1, 54, -1, 55, -1, 57, -1, 58, -1, 56, -1, 143, -1, 147, 70, 143, -1, 144, -1, 148, 70, 144, -1, 145, -1, 149, 70, 143, -1, 151, -1, 152, -1, 155, -1, 180, -1, 160, -1, 161, -1, 162, -1, 163, -1, 166, -1, 167, -1, 168, -1, 169, -1, 170, -1, 176, -1, 177, -1, 178, -1, 179, -1, 59, 60, -1, 59, 185, 60, -1, 11, 153, 87, -1, 11, 153, 1, -1, 62, -1, 62, 158, -1, 153, 70, 62, -1, 153, 70, 62, 158, -1, 62, -1, 62, 159, -1, 154, 70, 62, -1, 154, 70, 62, 159, -1, 12, 156, 87, -1, 12, 156, 1, -1, 157, -1, 156, 70, 157, -1, 62, -1, 62, 158, -1, 86, 143, -1, 86, 144, -1, 87, -1, 149, 87, -1, 149, 1, -1, 18, 68, 147, 69, 150, -1, 18, 68, 147, 69, 150, 34, 150, -1, 20, 150, 21, 68, 147, 69, 87, -1, 20, 150, 21, 68, 147, 69, 1, -1, 21, 68, 147, 69, 150, -1, 9, 68, 165, 87, 164, 87, 164, 69, 150, -1, 9, 68, 11, 154, 87, 164, 87, 164, 69, 150, -1, 9, 68, 106, 22, 147, 69, 150, -1, 9, 68, 11, 62, 22, 147, 69, 150, -1, 9, 68, 11, 62, 159, 22, 147, 69, 150, -1, -1, 147, -1, -1, 148, -1, 13, 87, -1, 13, 1, -1, 13, 62, 87, -1, 13, 62, 1, -1, 6, 87, -1, 6, 1, -1, 6, 62, 87, -1, 6, 62, 1, -1, 15, 87, -1, 15, 1, -1, 15, 147, 87, -1, 15, 147, 1, -1, 26, 68, 147, 69, 150, -1, 25, 68, 147, 69, 171, -1, 59, 172, 60, -1, 59, 172, 175, 172, 60, -1, -1, 173, -1, 174, -1, 173, 174, -1, 7, 147, 67, -1, 7, 147, 67, 185, -1, 8, 67, -1, 8, 67, 185, -1, 62, 67, 150, -1, 28, 147, 87, -1, 28, 147, 1, -1, 29, 151, 31, 151, -1, 29, 151, 30, 68, 62, 69, 151, -1, 29, 151, 30, 68, 62, 69, 151, 31, 151, -1, 32, 87, -1, 32, 1, -1, 14, 62, 68, 69, 59, 183, 60, -1, 14, 62, 68, 182, 69, 59, 183, 60, -1, 14, 68, 69, 59, 183, 60, -1, 14, 68, 182, 69, 59, 183, 60, -1, 14, 62, 68, 69, 59, 183, 60, -1, 14, 62, 68, 182, 69, 59, 183, 60, -1, 62, -1, 182, 70, 62, -1, -1, 281, -1, -1, 185, -1, 150, -1, 185, 150, -1, 3, -1, 4, -1, 5, -1, 61, -1, 63, -1, 66, -1, 51, -1, 62, 67, 240, -1, 63, 67, 240, -1, 61, 67, 240, -1, 62, 62, 68, 69, 59, 280, 60, -1, 62, 62, 68, 279, 69, 59, 280, 60, -1, 187, -1, 188, 70, 187, -1, 190, -1, 59, 60, -1, 59, 188, 60, -1, 59, 188, 70, 60, -1, 19, -1, 186, -1, 191, -1, 62, -1, 68, 244, 69, -1, 71, 193, 72, -1, 71, 192, 72, -1, 71, 192, 70, 193, 72, -1, 193, 240, -1, 192, 70, 193, 240, -1, -1, 194, -1, 70, -1, 194, 70, -1, 189, -1, 278, -1, 195, 71, 244, 72, -1, 195, 73, 62, -1, 10, 195, 201, -1, 190, -1, 196, 71, 244, 72, -1, 196, 73, 62, -1, 10, 195, 201, -1, 195, -1, 10, 197, -1, 196, -1, 10, 197, -1, 195, 201, -1, 199, 201, -1, 199, 71, 244, 72, -1, 199, 73, 62, -1, 196, 201, -1, 200, 201, -1, 200, 71, 244, 72, -1, 200, 73, 62, -1, 68, 69, -1, 68, 202, 69, -1, 240, -1, 202, 70, 240, -1, 197, -1, 199, -1, 198, -1, 200, -1, 203, -1, 203, 43, -1, 203, 44, -1, 204, -1, 204, 43, -1, 204, 44, -1, 17, 208, -1, 16, 208, -1, 24, 208, -1, 43, 208, -1, 64, 208, -1, 44, 208, -1, 65, 208, -1, 74, 208, -1, 75, 208, -1, 76, 208, -1, 77, 208, -1, 205, -1, 207, -1, 206, -1, 207, -1, 208, -1, 210, 78, 208, -1, 210, 66, 208, -1, 210, 79, 208, -1, 209, -1, 211, 78, 208, -1, 211, 66, 208, -1, 211, 79, 208, -1, 210, -1, 212, 74, 210, -1, 212, 75, 210, -1, 211, -1, 213, 74, 210, -1, 213, 75, 210, -1, 212, -1, 214, 45, 212, -1, 214, 46, 212, -1, 214, 47, 212, -1, 213, -1, 215, 45, 212, -1, 215, 46, 212, -1, 215, 47, 212, -1, 214, -1, 216, 80, 214, -1, 216, 81, 214, -1, 216, 39, 214, -1, 216, 40, 214, -1, 216, 23, 214, -1, 216, 22, 214, -1, 214, -1, 217, 80, 214, -1, 217, 81, 214, -1, 217, 39, 214, -1, 217, 40, 214, -1, 217, 23, 214, -1, 215, -1, 218, 80, 214, -1, 218, 81, 214, -1, 218, 39, 214, -1, 218, 40, 214, -1, 218, 23, 214, -1, 218, 22, 214, -1, 216, -1, 219, 35, 216, -1, 219, 36, 216, -1, 219, 37, 216, -1, 219, 38, 216, -1, 217, -1, 220, 35, 217, -1, 220, 36, 217, -1, 220, 37, 217, -1, 220, 38, 217, -1, 218, -1, 221, 35, 216, -1, 221, 36, 216, -1, 221, 37, 216, -1, 221, 38, 216, -1, 219, -1, 222, 82, 219, -1, 220, -1, 223, 82, 220, -1, 221, -1, 224, 82, 219, -1, 222, -1, 225, 83, 222, -1, 223, -1, 226, 83, 223, -1, 224, -1, 227, 83, 222, -1, 225, -1, 228, 84, 225, -1, 226, -1, 229, 84, 226, -1, 227, -1, 230, 84, 225, -1, 228, -1, 231, 42, 228, -1, 229, -1, 232, 42, 229, -1, 230, -1, 233, 42, 228, -1, 231, -1, 234, 41, 231, -1, 232, -1, 235, 41, 232, -1, 233, -1, 236, 41, 231, -1, 234, -1, 234, 85, 240, 67, 240, -1, 235, -1, 235, 85, 241, 67, 241, -1, 236, -1, 236, 85, 240, 67, 240, -1, 237, -1, 203, 243, 240, -1, 238, -1, 203, 243, 241, -1, 239, -1, 204, 243, 240, -1, 86, -1, 48, -1, 49, -1, 50, -1, 51, -1, 52, -1, 53, -1, 54, -1, 55, -1, 57, -1, 58, -1, 56, -1, 240, -1, 244, 70, 240, -1, 241, -1, 245, 70, 241, -1, 242, -1, 246, 70, 240, -1, 248, -1, 249, -1, 252, -1, 277, -1, 257, -1, 258, -1, 259, -1, 260, -1, 263, -1, 264, -1, 265, -1, 266, -1, 267, -1, 273, -1, 274, -1, 275, -1, 276, -1, 59, 60, -1, 59, 281, 60, -1, 11, 250, 87, -1, 11, 250, 1, -1, 62, -1, 62, 255, -1, 250, 70, 62, -1, 250, 70, 62, 255, -1, 62, -1, 62, 256, -1, 251, 70, 62, -1, 251, 70, 62, 256, -1, 12, 253, 87, -1, 12, 253, 1, -1, 254, -1, 253, 70, 254, -1, 62, -1, 62, 255, -1, 86, 240, -1, 86, 241, -1, 87, -1, 246, 87, -1, 246, 1, -1, 18, 68, 244, 69, 247, -1, 18, 68, 244, 69, 247, 34, 247, -1, 20, 247, 21, 68, 244, 69, 87, -1, 20, 247, 21, 68, 244, 69, 1, -1, 21, 68, 244, 69, 247, -1, 9, 68, 262, 87, 261, 87, 261, 69, 247, -1, 9, 68, 11, 251, 87, 261, 87, 261, 69, 247, -1, 9, 68, 203, 22, 244, 69, 247, -1, 9, 68, 11, 62, 22, 244, 69, 247, -1, 9, 68, 11, 62, 256, 22, 244, 69, 247, -1, -1, 244, -1, -1, 245, -1, 13, 87, -1, 13, 1, -1, 13, 62, 87, -1, 13, 62, 1, -1, 6, 87, -1, 6, 1, -1, 6, 62, 87, -1, 6, 62, 1, -1, 15, 87, -1, 15, 1, -1, 15, 244, 87, -1, 15, 244, 1, -1, 26, 68, 244, 69, 247, -1, 25, 68, 244, 69, 268, -1, 59, 269, 60, -1, 59, 269, 272, 269, 60, -1, -1, 270, -1, 271, -1, 270, 271, -1, 7, 244, 67, -1, 7, 244, 67, 281, -1, 8, 67, -1, 8, 67, 281, -1, 62, 67, 247, -1, 28, 244, 87, -1, 28, 244, 1, -1, 29, 248, 31, 248, -1, 29, 248, 30, 68, 62, 69, 248, -1, 29, 248, 30, 68, 62, 69, 248, 31, 248, -1, 32, 87, -1, 32, 1, -1, 14, 62, 68, 69, 59, 280, 60, -1, 14, 62, 68, 279, 69, 59, 280, 60, -1, 14, 68, 69, 59, 280, 60, -1, 14, 68, 279, 69, 59, 280, 60, -1, 14, 62, 68, 69, 59, 280, 60, -1, 14, 62, 68, 279, 69, 59, 280, 60, -1, 62, -1, 279, 70, 62, -1, -1, 281, -1, 247, -1, 281, 247, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 290, 290, 291, 292, 293, 294, 295, 304, 316, 317, 318, 319, 320, 332, 336, 343, 344, 345, 347, 351, 352, 353, 354, 355, 359, 360, 361, 365, 369, 377, 378, 382, 383, 387, 388, 389, 393, 397, 404, 405, 409, 413, 420, 421, 428, 429, 436, 437, 438, 442, 448, 449, 450, 454, 461, 462, 466, 470, 477, 478, 482, 483, 487, 488, 489, 493, 494, 495, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 512, 513, 517, 518, 522, 523, 524, 525, 529, 530, 532, 534, 539, 540, 541, 545, 546, 548, 553, 554, 555, 556, 560, 561, 562, 563, 567, 568, 569, 570, 571, 572, 575, 581, 582, 583, 584, 585, 586, 593, 594, 595, 596, 597, 598, 602, 609, 610, 611, 612, 613, 617, 618, 620, 622, 624, 629, 630, 632, 633, 635, 640, 641, 645, 646, 651, 652, 656, 657, 661, 662, 667, 668, 673, 674, 678, 679, 684, 685, 690, 691, 695, 696, 701, 702, 707, 708, 712, 713, 718, 719, 723, 724, 729, 730, 735, 736, 741, 742, 749, 750, 757, 758, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 780, 781, 785, 786, 790, 791, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 815, 817, 822, 824, 830, 837, 846, 854, 867, 874, 883, 891, 904, 906, 912, 920, 932, 933, 937, 941, 945, 949, 951, 956, 959, 968, 970, 972, 974, 980, 987, 996, 1002, 1013, 1014, 1018, 1019, 1023, 1027, 1031, 1035, 1042, 1045, 1048, 1051, 1057, 1060, 1063, 1066, 1072, 1078, 1084, 1085, 1094, 1095, 1099, 1105, 1115, 1116, 1120, 1121, 1125, 1131, 1135, 1142, 1148, 1154, 1164, 1166, 1171, 1172, 1183, 1184, 1191, 1192, 1202, 1205, 1211, 1212, 1216, 1217, 1222, 1229, 1240, 1241, 1242, 1243, 1244, 1245, 1246, 1250, 1251, 1252, 1253, 1254, 1258, 1259, 1263, 1264, 1265, 1267, 1271, 1272, 1273, 1274, 1275, 1279, 1280, 1281, 1285, 1286, 1289, 1291, 1295, 1296, 1300, 1301, 1302, 1303, 1304, 1308, 1309, 1310, 1311, 1315, 1316, 1320, 1321, 1325, 1326, 1327, 1328, 1332, 1333, 1334, 1335, 1339, 1340, 1344, 1345, 1349, 1350, 1354, 1355, 1359, 1360, 1361, 1365, 1366, 1367, 1371, 1372, 1373, 1374, 1375, 1376, 1377, 1378, 1379, 1380, 1381, 1384, 1385, 1389, 1390, 1394, 1395, 1396, 1397, 1401, 1402, 1403, 1404, 1408, 1409, 1410, 1414, 1415, 1416, 1420, 1421, 1422, 1423, 1427, 1428, 1429, 1430, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 1444, 1445, 1446, 1447, 1448, 1449, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1463, 1464, 1465, 1466, 1467, 1471, 1472, 1473, 1474, 1475, 1479, 1480, 1481, 1482, 1483, 1487, 1488, 1492, 1493, 1497, 1498, 1502, 1503, 1507, 1508, 1512, 1513, 1517, 1518, 1522, 1523, 1527, 1528, 1532, 1533, 1537, 1538, 1542, 1543, 1547, 1548, 1552, 1553, 1557, 1558, 1562, 1563, 1567, 1568, 1572, 1573, 1577, 1578, 1582, 1583, 1587, 1588, 1592, 1593, 1594, 1595, 1596, 1597, 1598, 1599, 1600, 1601, 1602, 1603, 1607, 1608, 1612, 1613, 1617, 1618, 1622, 1623, 1624, 1625, 1626, 1627, 1628, 1629, 1630, 1631, 1632, 1633, 1634, 1635, 1636, 1637, 1638, 1642, 1643, 1647, 1648, 1652, 1653, 1654, 1655, 1659, 1660, 1661, 1662, 1666, 1667, 1671, 1672, 1676, 1677, 1681, 1685, 1689, 1693, 1694, 1698, 1699, 1703, 1704, 1705, 1706, 1707, 1708, 1709, 1710, 1713, 1715, 1718, 1720, 1724, 1725, 1726, 1727, 1731, 1732, 1733, 1734, 1738, 1739, 1740, 1741, 1745, 1749, 1753, 1754, 1757, 1759, 1763, 1764, 1768, 1769, 1773, 1774, 1778, 1782, 1783, 1787, 1788, 1789, 1793, 1794, 1798, 1799, 1803, 1804, 1805, 1806, 1810, 1811, 1814, 1816, 1820, 1821 }; #endif #if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "NULLTOKEN", "TRUETOKEN", "FALSETOKEN", "BREAK", "CASE", "DEFAULT", "FOR", "NEW", "VAR", "CONSTTOKEN", "CONTINUE", "FUNCTION", "RETURN", "VOIDTOKEN", "DELETETOKEN", "IF", "THISTOKEN", "DO", "WHILE", "INTOKEN", "INSTANCEOF", "TYPEOF", "SWITCH", "WITH", "RESERVED", "THROW", "TRY", "CATCH", "FINALLY", "DEBUGGER", "IF_WITHOUT_ELSE", "ELSE", "EQEQ", "NE", "STREQ", "STRNEQ", "LE", "GE", "OR", "AND", "PLUSPLUS", "MINUSMINUS", "LSHIFT", "RSHIFT", "URSHIFT", "PLUSEQUAL", "MINUSEQUAL", "MULTEQUAL", "DIVEQUAL", "LSHIFTEQUAL", "RSHIFTEQUAL", "URSHIFTEQUAL", "ANDEQUAL", "MODEQUAL", "XOREQUAL", "OREQUAL", "OPENBRACE", "CLOSEBRACE", "NUMBER", "IDENT", "STRING", "AUTOPLUSPLUS", "AUTOMINUSMINUS", "'/'", "':'", "'('", "')'", "','", "'['", "']'", "'.'", "'+'", "'-'", "'~'", "'!'", "'*'", "'%'", "'<'", "'>'", "'&'", "'^'", "'|'", "'?'", "'='", "';'", "$accept", "Literal", "Property", "PropertyList", "PrimaryExpr", "PrimaryExprNoBrace", "ArrayLiteral", "ElementList", "ElisionOpt", "Elision", "MemberExpr", "MemberExprNoBF", "NewExpr", "NewExprNoBF", "CallExpr", "CallExprNoBF", "Arguments", "ArgumentList", "LeftHandSideExpr", "LeftHandSideExprNoBF", "PostfixExpr", "PostfixExprNoBF", "UnaryExprCommon", "UnaryExpr", "UnaryExprNoBF", "MultiplicativeExpr", "MultiplicativeExprNoBF", "AdditiveExpr", "AdditiveExprNoBF", "ShiftExpr", "ShiftExprNoBF", "RelationalExpr", "RelationalExprNoIn", "RelationalExprNoBF", "EqualityExpr", "EqualityExprNoIn", "EqualityExprNoBF", "BitwiseANDExpr", "BitwiseANDExprNoIn", "BitwiseANDExprNoBF", "BitwiseXORExpr", "BitwiseXORExprNoIn", "BitwiseXORExprNoBF", "BitwiseORExpr", "BitwiseORExprNoIn", "BitwiseORExprNoBF", "LogicalANDExpr", "LogicalANDExprNoIn", "LogicalANDExprNoBF", "LogicalORExpr", "LogicalORExprNoIn", "LogicalORExprNoBF", "ConditionalExpr", "ConditionalExprNoIn", "ConditionalExprNoBF", "AssignmentExpr", "AssignmentExprNoIn", "AssignmentExprNoBF", "AssignmentOperator", "Expr", "ExprNoIn", "ExprNoBF", "Statement", "Block", "VariableStatement", "VariableDeclarationList", "VariableDeclarationListNoIn", "ConstStatement", "ConstDeclarationList", "ConstDeclaration", "Initializer", "InitializerNoIn", "EmptyStatement", "ExprStatement", "IfStatement", "IterationStatement", "ExprOpt", "ExprNoInOpt", "ContinueStatement", "BreakStatement", "ReturnStatement", "WithStatement", "SwitchStatement", "CaseBlock", "CaseClausesOpt", "CaseClauses", "CaseClause", "DefaultClause", "LabelledStatement", "ThrowStatement", "TryStatement", "DebuggerStatement", "FunctionDeclaration", "FunctionExpr", "FormalParameterList", "FunctionBody", "Program", "SourceElements", "Literal_NoNode", "Property_NoNode", "PropertyList_NoNode", "PrimaryExpr_NoNode", "PrimaryExprNoBrace_NoNode", "ArrayLiteral_NoNode", "ElementList_NoNode", "ElisionOpt_NoNode", "Elision_NoNode", "MemberExpr_NoNode", "MemberExprNoBF_NoNode", "NewExpr_NoNode", "NewExprNoBF_NoNode", "CallExpr_NoNode", "CallExprNoBF_NoNode", "Arguments_NoNode", "ArgumentList_NoNode", "LeftHandSideExpr_NoNode", "LeftHandSideExprNoBF_NoNode", "PostfixExpr_NoNode", "PostfixExprNoBF_NoNode", "UnaryExprCommon_NoNode", "UnaryExpr_NoNode", "UnaryExprNoBF_NoNode", "MultiplicativeExpr_NoNode", "MultiplicativeExprNoBF_NoNode", "AdditiveExpr_NoNode", "AdditiveExprNoBF_NoNode", "ShiftExpr_NoNode", "ShiftExprNoBF_NoNode", "RelationalExpr_NoNode", "RelationalExprNoIn_NoNode", "RelationalExprNoBF_NoNode", "EqualityExpr_NoNode", "EqualityExprNoIn_NoNode", "EqualityExprNoBF_NoNode", "BitwiseANDExpr_NoNode", "BitwiseANDExprNoIn_NoNode", "BitwiseANDExprNoBF_NoNode", "BitwiseXORExpr_NoNode", "BitwiseXORExprNoIn_NoNode", "BitwiseXORExprNoBF_NoNode", "BitwiseORExpr_NoNode", "BitwiseORExprNoIn_NoNode", "BitwiseORExprNoBF_NoNode", "LogicalANDExpr_NoNode", "LogicalANDExprNoIn_NoNode", "LogicalANDExprNoBF_NoNode", "LogicalORExpr_NoNode", "LogicalORExprNoIn_NoNode", "LogicalORExprNoBF_NoNode", "ConditionalExpr_NoNode", "ConditionalExprNoIn_NoNode", "ConditionalExprNoBF_NoNode", "AssignmentExpr_NoNode", "AssignmentExprNoIn_NoNode", "AssignmentExprNoBF_NoNode", "AssignmentOperator_NoNode", "Expr_NoNode", "ExprNoIn_NoNode", "ExprNoBF_NoNode", "Statement_NoNode", "Block_NoNode", "VariableStatement_NoNode", "VariableDeclarationList_NoNode", "VariableDeclarationListNoIn_NoNode", "ConstStatement_NoNode", "ConstDeclarationList_NoNode", "ConstDeclaration_NoNode", "Initializer_NoNode", "InitializerNoIn_NoNode", "EmptyStatement_NoNode", "ExprStatement_NoNode", "IfStatement_NoNode", "IterationStatement_NoNode", "ExprOpt_NoNode", "ExprNoInOpt_NoNode", "ContinueStatement_NoNode", "BreakStatement_NoNode", "ReturnStatement_NoNode", "WithStatement_NoNode", "SwitchStatement_NoNode", "CaseBlock_NoNode", "CaseClausesOpt_NoNode", "CaseClauses_NoNode", "CaseClause_NoNode", "DefaultClause_NoNode", "LabelledStatement_NoNode", "ThrowStatement_NoNode", "TryStatement_NoNode", "DebuggerStatement_NoNode", "FunctionDeclaration_NoNode", "FunctionExpr_NoNode", "FormalParameterList_NoNode", "FunctionBody_NoNode", "SourceElements_NoNode", 0 }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 47, 58, 40, 41, 44, 91, 93, 46, 43, 45, 126, 33, 42, 37, 60, 62, 38, 94, 124, 63, 61, 59 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint16 yyr1[] = { 0, 88, 89, 89, 89, 89, 89, 89, 89, 90, 90, 90, 90, 90, 91, 91, 92, 92, 92, 92, 93, 93, 93, 93, 93, 94, 94, 94, 95, 95, 96, 96, 97, 97, 98, 98, 98, 98, 98, 99, 99, 99, 99, 100, 100, 101, 101, 102, 102, 102, 102, 103, 103, 103, 103, 104, 104, 105, 105, 106, 106, 107, 107, 108, 108, 108, 109, 109, 109, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 111, 111, 112, 112, 113, 113, 113, 113, 114, 114, 114, 114, 115, 115, 115, 116, 116, 116, 117, 117, 117, 117, 118, 118, 118, 118, 119, 119, 119, 119, 119, 119, 119, 120, 120, 120, 120, 120, 120, 121, 121, 121, 121, 121, 121, 121, 122, 122, 122, 122, 122, 123, 123, 123, 123, 123, 124, 124, 124, 124, 124, 125, 125, 126, 126, 127, 127, 128, 128, 129, 129, 130, 130, 131, 131, 132, 132, 133, 133, 134, 134, 135, 135, 136, 136, 137, 137, 138, 138, 139, 139, 140, 140, 141, 141, 142, 142, 143, 143, 144, 144, 145, 145, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 147, 147, 148, 148, 149, 149, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 151, 151, 152, 152, 153, 153, 153, 153, 154, 154, 154, 154, 155, 155, 156, 156, 157, 157, 158, 159, 160, 161, 161, 162, 162, 163, 163, 163, 163, 163, 163, 163, 163, 164, 164, 165, 165, 166, 166, 166, 166, 167, 167, 167, 167, 168, 168, 168, 168, 169, 170, 171, 171, 172, 172, 173, 173, 174, 174, 175, 175, 176, 177, 177, 178, 178, 178, 179, 179, 180, 180, 181, 181, 181, 181, 182, 182, 183, 183, 184, 184, 185, 185, 186, 186, 186, 186, 186, 186, 186, 187, 187, 187, 187, 187, 188, 188, 189, 189, 189, 189, 190, 190, 190, 190, 190, 191, 191, 191, 192, 192, 193, 193, 194, 194, 195, 195, 195, 195, 195, 196, 196, 196, 196, 197, 197, 198, 198, 199, 199, 199, 199, 200, 200, 200, 200, 201, 201, 202, 202, 203, 203, 204, 204, 205, 205, 205, 206, 206, 206, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 207, 208, 208, 209, 209, 210, 210, 210, 210, 211, 211, 211, 211, 212, 212, 212, 213, 213, 213, 214, 214, 214, 214, 215, 215, 215, 215, 216, 216, 216, 216, 216, 216, 216, 217, 217, 217, 217, 217, 217, 218, 218, 218, 218, 218, 218, 218, 219, 219, 219, 219, 219, 220, 220, 220, 220, 220, 221, 221, 221, 221, 221, 222, 222, 223, 223, 224, 224, 225, 225, 226, 226, 227, 227, 228, 228, 229, 229, 230, 230, 231, 231, 232, 232, 233, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238, 239, 239, 240, 240, 241, 241, 242, 242, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 247, 247, 247, 247, 247, 247, 247, 247, 247, 247, 247, 247, 247, 247, 247, 248, 248, 249, 249, 250, 250, 250, 250, 251, 251, 251, 251, 252, 252, 253, 253, 254, 254, 255, 256, 257, 258, 258, 259, 259, 260, 260, 260, 260, 260, 260, 260, 260, 261, 261, 262, 262, 263, 263, 263, 263, 264, 264, 264, 264, 265, 265, 265, 265, 266, 267, 268, 268, 269, 269, 270, 270, 271, 271, 272, 272, 273, 274, 274, 275, 275, 275, 276, 276, 277, 277, 278, 278, 278, 278, 279, 279, 280, 280, 281, 281 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 7, 8, 1, 3, 1, 2, 3, 4, 1, 1, 1, 1, 3, 3, 3, 5, 2, 4, 0, 1, 1, 2, 1, 1, 4, 3, 3, 1, 4, 3, 3, 1, 2, 1, 2, 2, 2, 4, 3, 2, 2, 4, 3, 2, 3, 1, 3, 1, 1, 1, 1, 1, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 3, 3, 3, 1, 3, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 1, 3, 3, 3, 3, 1, 3, 3, 3, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 5, 1, 5, 1, 5, 1, 3, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3, 3, 1, 2, 3, 4, 1, 2, 3, 4, 3, 3, 1, 3, 1, 2, 2, 2, 1, 2, 2, 5, 7, 7, 7, 5, 9, 10, 7, 8, 9, 0, 1, 0, 1, 2, 2, 3, 3, 2, 2, 3, 3, 2, 2, 3, 3, 5, 5, 3, 5, 0, 1, 1, 2, 3, 4, 2, 3, 3, 3, 3, 4, 7, 9, 2, 2, 7, 8, 6, 7, 7, 8, 1, 3, 0, 1, 0, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 7, 8, 1, 3, 1, 2, 3, 4, 1, 1, 1, 1, 3, 3, 3, 5, 2, 4, 0, 1, 1, 2, 1, 1, 4, 3, 3, 1, 4, 3, 3, 1, 2, 1, 2, 2, 2, 4, 3, 2, 2, 4, 3, 2, 3, 1, 3, 1, 1, 1, 1, 1, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 3, 3, 3, 1, 3, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 1, 3, 3, 3, 3, 1, 3, 3, 3, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 5, 1, 5, 1, 5, 1, 3, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3, 3, 1, 2, 3, 4, 1, 2, 3, 4, 3, 3, 1, 3, 1, 2, 2, 2, 1, 2, 2, 5, 7, 7, 7, 5, 9, 10, 7, 8, 9, 0, 1, 0, 1, 2, 2, 3, 3, 2, 2, 3, 3, 2, 2, 3, 3, 5, 5, 3, 5, 0, 1, 1, 2, 3, 4, 2, 3, 3, 3, 3, 4, 7, 9, 2, 2, 7, 8, 6, 7, 7, 8, 1, 3, 0, 1, 1, 2 }; /* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state STATE-NUM when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint16 yydefact[] = { 297, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 5, 23, 6, 0, 0, 7, 0, 30, 0, 0, 0, 0, 238, 21, 39, 22, 45, 61, 62, 66, 82, 83, 88, 95, 102, 119, 136, 145, 151, 157, 163, 169, 175, 181, 199, 0, 299, 201, 202, 203, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 204, 0, 298, 260, 0, 259, 253, 0, 0, 0, 23, 34, 16, 43, 46, 35, 222, 0, 234, 0, 232, 256, 0, 255, 0, 264, 263, 43, 59, 60, 63, 80, 81, 84, 92, 98, 106, 126, 141, 147, 153, 159, 165, 171, 177, 195, 0, 63, 70, 69, 0, 0, 0, 71, 0, 0, 0, 0, 286, 285, 72, 74, 218, 0, 0, 73, 75, 0, 32, 0, 0, 31, 76, 77, 78, 79, 0, 0, 0, 51, 0, 0, 52, 67, 68, 184, 185, 186, 187, 188, 189, 190, 191, 194, 192, 193, 183, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 0, 239, 1, 300, 262, 261, 0, 63, 113, 131, 143, 149, 155, 161, 167, 173, 179, 197, 254, 0, 43, 44, 0, 0, 17, 0, 0, 0, 14, 0, 0, 0, 42, 0, 223, 221, 0, 220, 235, 231, 0, 230, 258, 257, 0, 47, 0, 0, 48, 64, 65, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 266, 0, 265, 0, 0, 0, 0, 0, 281, 280, 0, 0, 219, 279, 24, 30, 26, 25, 28, 33, 55, 0, 57, 0, 41, 0, 54, 182, 90, 89, 91, 96, 97, 103, 104, 105, 125, 124, 122, 123, 120, 121, 137, 138, 139, 140, 146, 152, 158, 164, 170, 0, 200, 226, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 251, 38, 0, 293, 0, 0, 0, 0, 0, 0, 18, 0, 0, 37, 236, 224, 233, 0, 0, 0, 50, 178, 86, 85, 87, 93, 94, 99, 100, 101, 112, 111, 109, 110, 107, 108, 127, 128, 129, 130, 142, 148, 154, 160, 166, 0, 196, 0, 0, 0, 0, 0, 0, 282, 0, 56, 0, 40, 53, 0, 0, 0, 227, 0, 251, 0, 63, 180, 118, 116, 117, 114, 115, 132, 133, 134, 135, 144, 150, 156, 162, 168, 0, 198, 252, 0, 0, 0, 295, 0, 0, 11, 0, 9, 10, 19, 15, 36, 225, 295, 0, 49, 0, 241, 0, 245, 271, 268, 267, 0, 27, 29, 58, 176, 0, 237, 0, 228, 0, 0, 0, 251, 295, 0, 301, 302, 303, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 319, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 307, 0, 304, 322, 305, 0, 0, 306, 0, 329, 0, 0, 0, 0, 537, 0, 320, 338, 321, 344, 360, 361, 365, 381, 382, 387, 394, 401, 418, 435, 444, 450, 456, 462, 468, 474, 480, 498, 0, 596, 500, 501, 502, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 503, 296, 295, 294, 0, 0, 0, 295, 172, 0, 0, 0, 0, 272, 273, 0, 0, 0, 229, 251, 248, 174, 0, 0, 295, 559, 0, 558, 552, 0, 0, 0, 322, 333, 315, 342, 345, 334, 521, 0, 533, 0, 531, 555, 0, 554, 0, 563, 562, 342, 358, 359, 362, 379, 380, 383, 391, 397, 405, 425, 440, 446, 452, 458, 464, 470, 476, 494, 0, 362, 369, 368, 0, 0, 0, 370, 0, 0, 0, 0, 585, 584, 371, 373, 517, 0, 0, 372, 374, 0, 331, 0, 0, 330, 375, 376, 377, 378, 289, 0, 0, 0, 350, 0, 0, 351, 366, 367, 483, 484, 485, 486, 487, 488, 489, 490, 493, 491, 492, 482, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 539, 0, 538, 597, 0, 295, 0, 287, 0, 242, 244, 243, 0, 0, 269, 271, 274, 283, 249, 0, 0, 0, 291, 0, 561, 560, 0, 362, 412, 430, 442, 448, 454, 460, 466, 472, 478, 496, 553, 0, 342, 343, 0, 0, 316, 0, 0, 0, 313, 0, 0, 0, 341, 0, 522, 520, 0, 519, 534, 530, 0, 529, 557, 556, 0, 346, 0, 0, 347, 363, 364, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 565, 0, 564, 0, 0, 0, 0, 0, 580, 579, 0, 0, 518, 578, 323, 329, 325, 324, 327, 332, 354, 0, 356, 0, 340, 0, 353, 481, 389, 388, 390, 395, 396, 402, 403, 404, 424, 423, 421, 422, 419, 420, 436, 437, 438, 439, 445, 451, 457, 463, 469, 0, 499, 290, 0, 295, 288, 275, 277, 0, 0, 250, 0, 246, 292, 525, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 550, 337, 0, 592, 0, 0, 0, 0, 0, 0, 317, 0, 0, 336, 535, 523, 532, 0, 0, 0, 349, 477, 385, 384, 386, 392, 393, 398, 399, 400, 411, 410, 408, 409, 406, 407, 426, 427, 428, 429, 441, 447, 453, 459, 465, 0, 495, 0, 0, 0, 0, 0, 0, 581, 0, 355, 0, 339, 352, 0, 12, 0, 276, 278, 270, 284, 247, 0, 0, 526, 0, 550, 0, 362, 479, 417, 415, 416, 413, 414, 431, 432, 433, 434, 443, 449, 455, 461, 467, 0, 497, 551, 0, 0, 0, 594, 0, 0, 310, 0, 308, 309, 318, 314, 335, 524, 594, 0, 348, 0, 540, 0, 544, 570, 567, 566, 0, 326, 328, 357, 475, 13, 0, 536, 0, 527, 0, 0, 0, 550, 594, 0, 0, 595, 594, 593, 0, 0, 0, 594, 471, 0, 0, 0, 0, 571, 572, 0, 0, 0, 528, 550, 547, 473, 0, 0, 594, 588, 0, 594, 0, 586, 0, 541, 543, 542, 0, 0, 568, 570, 573, 582, 548, 0, 0, 0, 590, 0, 589, 0, 594, 587, 574, 576, 0, 0, 549, 0, 545, 591, 311, 0, 575, 577, 569, 583, 546, 312 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 41, 232, 233, 92, 93, 43, 150, 151, 152, 108, 44, 109, 45, 110, 46, 160, 301, 128, 47, 112, 48, 113, 114, 50, 115, 51, 116, 52, 117, 53, 118, 213, 54, 119, 214, 55, 120, 215, 56, 121, 216, 57, 122, 217, 58, 123, 218, 59, 124, 219, 60, 125, 220, 61, 126, 221, 62, 336, 437, 222, 63, 64, 65, 66, 98, 334, 67, 100, 101, 238, 415, 68, 69, 70, 71, 438, 223, 72, 73, 74, 75, 76, 460, 570, 571, 572, 718, 77, 78, 79, 80, 81, 96, 358, 517, 82, 83, 518, 751, 752, 591, 592, 520, 649, 650, 651, 607, 521, 608, 522, 609, 523, 660, 820, 627, 524, 611, 525, 612, 613, 527, 614, 528, 615, 529, 616, 530, 617, 732, 531, 618, 733, 532, 619, 734, 533, 620, 735, 534, 621, 736, 535, 622, 737, 536, 623, 738, 537, 624, 739, 538, 625, 740, 539, 867, 975, 741, 540, 541, 542, 543, 597, 865, 544, 599, 600, 757, 953, 545, 546, 547, 548, 976, 742, 549, 550, 551, 552, 553, 998, 1028, 1029, 1030, 1053, 554, 555, 556, 557, 558, 595, 889, 1016, 559 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -941 static const yytype_int16 yypact[] = { 1516, -941, -941, -941, 44, -2, 839, 26, 178, 73, 192, 954, 2114, 2114, 189, -941, 1516, 207, 2114, 245, 275, 2114, 226, 47, 2114, 2114, -941, 1200, -941, 280, -941, 2114, 2114, -941, 2114, 20, 2114, 2114, 2114, 2114, -941, -941, -941, -941, 350, -941, 361, 2201, -941, -941, -941, 6, -21, 437, 446, 264, 269, 315, 306, 364, 9, -941, -941, 69, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, 417, 1516, -941, 88, -941, 1670, 839, 25, 435, -941, -941, -941, 390, -941, -941, 338, 96, 338, 151, -941, -941, 90, -941, 365, -941, -941, 390, -941, 394, 2224, -941, -941, -941, 215, 255, 483, 509, 504, 374, 377, 380, 424, 14, -941, -941, 163, 445, -941, -941, 2114, 452, 2114, -941, 2114, 2114, 164, 486, -941, -941, -941, -941, -941, 1279, 1516, -941, -941, 495, -941, 311, 1706, 400, -941, -941, -941, -941, 1781, 2114, 418, -941, 2114, 432, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, -941, 2114, -941, -941, -941, -941, -941, 442, 737, 483, 355, 583, 428, 440, 453, 491, 17, -941, -941, 481, 469, 390, -941, 505, 187, -941, 513, -5, 521, -941, 177, 2114, 539, -941, 2114, -941, -941, 545, -941, -941, -941, 178, -941, -941, -941, 236, -941, 2114, 547, -941, -941, -941, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, -941, 2114, -941, 499, 548, 559, 582, 617, -941, -941, 556, 226, -941, -941, -941, 20, -941, -941, -941, -941, -941, 628, -941, 314, -941, 329, -941, -941, -941, -941, -941, 215, 215, 255, 255, 255, 483, 483, 483, 483, 483, 483, 509, 509, 509, 509, 504, 374, 377, 380, 424, 546, -941, 29, -11, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, 2114, -941, 256, -941, 567, 632, 2114, 563, 2114, 2114, -941, 586, 358, -941, -941, 338, -941, 574, 635, 436, -941, -941, -941, -941, -941, 215, 215, 255, 255, 255, 483, 483, 483, 483, 483, 483, 509, 509, 509, 509, 504, 374, 377, 380, 424, 571, -941, 1516, 2114, 1516, 584, 1516, 591, -941, 1817, -941, 2114, -941, -941, 2114, 2114, 2114, 656, 598, 2114, 648, 2224, -941, 483, 483, 483, 483, 483, 355, 355, 355, 355, 583, 428, 440, 453, 491, 639, -941, 614, 608, 649, 662, 1595, 651, 650, -941, 283, -941, -941, -941, -941, -941, -941, 1595, 660, -941, 2114, 681, 670, -941, 716, -941, -941, 657, -941, -941, -941, -941, 680, -941, 2114, 647, 654, 1516, 2114, 2114, 1595, 677, -941, -941, -941, 141, 688, 1122, 707, 712, 179, 717, 1087, 2150, 2150, 728, -941, 1595, 730, 2150, 732, 743, 2150, 754, 91, 2150, 2150, -941, 1358, -941, 755, -941, 2150, 2150, -941, 2150, 714, 2150, 2150, 2150, 2150, -941, 756, -941, -941, -941, 403, -941, 434, 2240, -941, -941, -941, 257, 581, 498, 619, 630, 747, 769, 753, 828, 23, -941, -941, 185, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, 1595, 1595, -941, 819, 685, 821, 1595, -941, 1516, 171, 2114, 219, 716, -941, 226, 1516, 692, -941, 2114, -941, -941, 810, 822, 1595, -941, 183, -941, 1892, 1122, 305, 609, -941, -941, -941, 441, -941, -941, 797, 195, 797, 203, -941, -941, 197, -941, 816, -941, -941, 441, -941, 447, 2263, -941, -941, -941, 262, 698, 515, 640, 638, 812, 802, 811, 845, 28, -941, -941, 208, 739, -941, -941, 2150, 868, 2150, -941, 2150, 2150, 216, 777, -941, -941, -941, -941, -941, 1437, 1595, -941, -941, 740, -941, 449, 1928, 827, -941, -941, -941, -941, -941, 2003, 2150, 837, -941, 2150, 841, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, -941, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, -941, 2150, -941, -941, 844, 1595, 847, -941, 848, -941, -941, -941, 8, 842, -941, 716, -941, 880, -941, 1516, 849, 1516, -941, 859, -941, -941, 860, 2185, 515, 357, 655, 843, 838, 840, 884, 150, -941, -941, 857, 846, 441, -941, 861, 299, -941, 863, 181, 870, -941, 284, 2150, 866, -941, 2150, -941, -941, 873, -941, -941, -941, 712, -941, -941, -941, 301, -941, 2150, 876, -941, -941, -941, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, -941, 2150, -941, 749, 871, 751, 757, 766, -941, -941, 872, 754, -941, -941, -941, 714, -941, -941, -941, -941, -941, 778, -941, 464, -941, 511, -941, -941, -941, -941, -941, 262, 262, 698, 698, 698, 515, 515, 515, 515, 515, 515, 640, 640, 640, 640, 638, 812, 802, 811, 845, 878, -941, -941, 891, 1595, -941, 1516, 1516, 894, 226, -941, 1516, -941, -941, 39, -7, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, 2150, -941, 307, -941, 897, 781, 2150, 892, 2150, 2150, -941, 683, 522, -941, -941, 797, -941, 902, 785, 525, -941, -941, -941, -941, -941, 262, 262, 698, 698, 698, 515, 515, 515, 515, 515, 515, 640, 640, 640, 640, 638, 812, 802, 811, 845, 895, -941, 1595, 2150, 1595, 904, 1595, 907, -941, 2039, -941, 2150, -941, -941, 2150, -941, 906, 1516, 1516, -941, -941, -941, 2150, 2150, 950, 912, 2150, 793, 2263, -941, 515, 515, 515, 515, 515, 357, 357, 357, 357, 655, 843, 838, 840, 884, 908, -941, 909, 889, 918, 796, 1595, 921, 919, -941, 313, -941, -941, -941, -941, -941, -941, 1595, 923, -941, 2150, 949, 798, -941, 977, -941, -941, 916, -941, -941, -941, -941, -941, 803, -941, 2150, 900, 901, 1595, 2150, 2150, 1595, 928, 935, 1595, 1595, -941, 937, 805, 939, 1595, -941, 1595, 217, 2150, 237, 977, -941, 754, 1595, 807, -941, 2150, -941, -941, 931, 941, 1595, -941, 942, 1595, 944, -941, 946, -941, -941, -941, 37, 940, -941, 977, -941, 973, -941, 1595, 943, 1595, -941, 948, -941, 951, 1595, -941, 1595, 1595, 961, 754, -941, 1595, -941, -941, -941, 963, 1595, 1595, -941, -941, -941, -941 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -941, -941, 645, -941, -941, 0, -941, -941, 715, -941, 22, -941, 186, -941, -941, -941, -29, -941, 479, -941, -941, -941, 3, 169, -941, 105, -941, 230, -941, 725, -941, 138, 423, -941, -174, 668, -941, 31, 679, -941, 40, 676, -941, 42, 678, -941, 68, 682, -941, -941, -941, -941, -941, -941, -941, -35, -305, -941, 172, 18, -941, -941, -15, -20, -941, -941, -941, -941, -941, 791, -91, 566, -941, -941, -941, -941, -407, -941, -941, -941, -941, -941, -941, -941, 319, -941, 471, -941, -941, -941, -941, -941, -941, -941, -235, -441, -941, -23, -941, 148, -941, -941, -432, -941, -941, 231, -941, -450, -941, -449, -941, -941, -941, -511, -941, 167, -941, -941, -941, -329, 263, -941, -661, -941, -460, -941, -428, -941, -480, -70, -941, -679, 170, -941, -673, 166, -941, -663, 173, -941, -660, 174, -941, -657, 165, -941, -941, -941, -941, -941, -941, -941, -601, -841, -941, -302, -473, -941, -941, -454, -493, -941, -941, -941, -941, -941, 290, -592, 46, -941, -941, -941, -941, -940, -941, -941, -941, -941, -941, -941, -941, 5, -941, 49, -941, -941, -941, -941, -941, -941, -941, -760, -652, -468 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If zero, do what YYDEFACT says. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -1 static const yytype_uint16 yytable[] = { 42, 132, 138, 49, 144, 637, 761, 902, 242, 519, 471, 564, 663, 371, 626, 1010, 42, 163, 845, 49, 519, 830, 831, 326, 636, 846, 958, 42, 94, 127, 49, 420, 593, 594, 581, 643, 847, 647, 631, 137, 848, 973, 974, 519, 849, 84, 435, 436, 139, 817, 201, 413, 148, 182, 183, 278, 821, 360, 350, 416, 519, 951, 361, 954, 701, 236, 87, 580, 207, 797, 203, 519, 179, 1038, 102, 856, 417, 826, 281, 249, 955, 252, 755, 42, 180, 181, 49, 226, 97, 208, 149, 246, 638, 227, 202, 1058, 768, 239, 771, 279, 393, 850, 351, 851, 1066, 706, 85, 800, 702, 468, 224, 1007, 526, 798, 924, 414, 298, 909, 910, 707, 440, 925, 302, 526, 711, 952, 978, 519, 519, 207, 293, 86, 926, 519, 140, 103, 927, 743, 744, 204, 928, 726, 583, 307, 42, 42, 526, 49, 49, 283, 519, 285, 243, 286, 287, 898, 205, 802, 731, 804, 104, 805, 806, 526, 280, 288, 240, 331, 579, 332, 723, 1037, 713, 905, 526, 209, 303, 247, 639, 305, 601, 129, 130, 241, 727, 822, 703, 134, 824, 706, 812, 881, 95, 141, 142, 354, 758, 929, 765, 930, 146, 147, 367, 584, 762, 153, 154, 155, 156, 799, 563, 519, 519, 841, 842, 843, 844, 807, 1048, 178, 374, 244, 678, 1021, 832, 833, 834, 716, 585, 327, 526, 526, 885, 281, 281, 882, 526, 363, 245, 328, 99, 602, 329, 891, 398, 1051, 399, 364, 892, 356, 282, 289, 365, 526, 105, 704, 357, 131, 714, 835, 836, 837, 838, 839, 840, 759, 603, 853, 372, 330, 728, 406, 705, 763, 225, 133, 519, 451, 800, 717, 896, 256, 760, 255, 766, 27, 800, 311, 312, 982, 764, 984, 985, 257, 258, 801, 903, 1052, 356, 193, 194, 195, 196, 808, 1049, 370, 394, 989, 774, 920, 921, 922, 923, 135, 526, 526, 395, 937, 356, 396, 911, 912, 913, 679, 444, 439, 446, 447, 775, 259, 260, 322, 323, 324, 325, 680, 681, 1002, 1022, 1003, 776, 777, 1004, 136, 894, 356, 397, 145, 308, 309, 310, 197, 562, 418, 895, 914, 915, 916, 917, 918, 919, 887, 1039, 887, 378, 379, 1042, 745, 888, 887, 901, 1046, 464, 746, 465, 887, 977, 466, 337, 526, 868, 295, 1020, 296, 281, 456, 410, 458, 1061, 461, 199, 1063, 1024, 956, 338, 339, 869, 870, 198, 281, 42, 411, 42, 49, 42, 49, 200, 49, 389, 390, 391, 392, 1075, 945, 313, 314, 315, 206, 157, 457, 566, 158, 519, 159, 237, 375, 376, 377, 281, 157, 450, 467, 161, 248, 162, 340, 341, 871, 872, 731, 959, 960, 961, 962, 963, 731, 731, 731, 731, 731, 731, 731, 731, 731, 731, 731, 274, 578, 157, 995, 275, 234, 157, 235, 276, 250, 277, 251, 187, 188, 299, 657, 42, 284, 658, 49, 659, 994, 1006, 996, 304, 999, 184, 185, 186, 189, 190, 575, 253, 254, 111, 380, 381, 382, 306, 228, 229, 230, 231, 519, 111, 519, 657, 519, 333, 661, 281, 662, 454, 657, 346, 1017, 753, 111, 754, 657, 290, 291, 769, 814, 770, 815, 1017, 347, 731, 526, 191, 192, 261, 262, 263, 264, 265, 349, 800, 1033, 941, 348, 1055, 270, 271, 272, 273, 684, 685, 686, 1017, 519, 266, 267, 1017, 352, 712, 720, 1050, 1017, 353, 1036, 519, 721, 780, 781, 782, 706, 294, 281, 211, 42, 400, 281, 49, 1047, 1017, 355, 42, 1017, 1079, 49, 1056, 519, 359, 800, 519, 942, 731, 519, 519, 715, 362, 268, 269, 519, 800, 519, 988, 800, 1017, 992, 1076, 1077, 519, 366, 526, 1070, 526, 1072, 526, 368, 519, 373, 111, 519, 111, 412, 111, 111, 401, 1080, 342, 343, 344, 345, 706, 706, 405, 519, 441, 519, 402, 281, 111, 445, 519, 452, 519, 519, 111, 111, 455, 519, 111, 687, 688, 459, 519, 519, 448, 229, 230, 231, 526, 403, 281, 462, 610, 682, 683, 111, 689, 690, 470, 526, 783, 784, 610, 693, 694, 695, 696, 747, 748, 749, 750, 789, 790, 791, 792, 610, 469, 785, 786, 111, 526, 111, 281, 526, 404, 281, 526, 526, 873, 874, 875, 876, 526, 474, 526, 408, 409, 691, 692, 442, 443, 526, 453, 443, 473, 860, 475, 862, 560, 526, 561, 111, 526, 567, 111, 472, 281, 565, 787, 788, 42, 569, 42, 49, 573, 49, 526, 111, 526, 476, 443, 414, 111, 526, 582, 526, 526, 568, 281, 577, 526, 986, 748, 749, 750, 526, 526, 574, 281, 628, 629, 730, 709, 443, 586, 633, 111, 335, 111, 722, 281, 640, 641, 426, 427, 428, 429, 596, 645, 646, 778, 779, 598, 652, 653, 654, 655, 604, 253, 254, 772, 773, 648, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 630, 610, 632, 610, 634, 610, 610, 964, 965, 966, 967, 809, 810, 813, 800, 635, 212, 503, 111, 419, 656, 610, 931, 800, 933, 800, 644, 177, 610, 610, 934, 800, 610, 697, 419, 419, 111, 946, 947, 935, 800, 699, 111, 949, 111, 111, 1, 2, 3, 610, 950, 939, 940, 88, 980, 981, 698, 89, 991, 981, 42, 42, 15, 49, 49, 42, 1011, 800, 49, 1015, 981, 1026, 800, 610, 700, 610, 1032, 800, 1044, 981, 1057, 800, 708, 724, 111, 710, 725, 756, 767, 794, 111, 796, 111, 803, 26, 111, 111, 419, 793, 795, 111, 818, 90, 823, 28, 91, 30, 825, 852, 33, 854, 34, 855, 857, 35, 859, 316, 317, 318, 319, 320, 321, 861, 863, 610, 878, 864, 610, 879, 877, 880, 883, 897, 886, 890, 207, 207, 884, 111, 899, 610, 893, 904, 932, 936, 610, 827, 828, 829, 943, 42, 42, 111, 49, 49, 944, 419, 111, 948, 106, 979, 1, 2, 3, 983, 990, 993, 997, 88, 610, 1005, 610, 89, 1000, 12, 13, 1008, 15, 1009, 1012, 1013, 1014, 18, 800, 1018, 1019, 1023, 1025, 1027, 1031, 952, 1040, 1035, 383, 384, 385, 386, 387, 388, 1041, 1043, 24, 25, 1045, 1059, 1060, 1062, 1064, 1069, 26, 1065, 1067, 1073, 449, 407, 1074, 1071, 90, 430, 28, 91, 30, 31, 32, 33, 1078, 34, 1081, 432, 35, 431, 433, 36, 37, 38, 39, 434, 610, 957, 369, 576, 858, 906, 907, 908, 107, 719, 987, 969, 938, 972, 968, 111, 957, 957, 610, 970, 900, 971, 1034, 111, 610, 1068, 610, 610, 212, 421, 422, 423, 424, 425, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 1054, 0, 0, 0, 0, 0, 0, 0, 0, 0, 605, 0, 477, 478, 479, 0, 0, 0, 0, 587, 0, 610, 0, 588, 0, 488, 489, 610, 491, 610, 0, 0, 610, 494, 0, 0, 0, 0, 0, 0, 610, 957, 0, 0, 610, 0, 0, 477, 478, 479, 0, 0, 500, 501, 587, 0, 0, 0, 588, 0, 502, 212, 0, 491, 0, 0, 0, 0, 589, 0, 504, 590, 506, 507, 508, 509, 0, 510, 0, 0, 511, 0, 610, 512, 513, 514, 515, 0, 0, 0, 0, 0, 0, 0, 0, 502, 606, 610, 0, 0, 0, 957, 610, 589, 0, 504, 590, 506, 0, 0, 509, 0, 510, 0, 0, 511, 610, 0, 0, 0, 212, 0, 0, 0, 610, 1, 2, 3, 4, 0, 0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 0, 0, 18, 19, 20, 0, 21, 22, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 25, 0, 0, 0, 0, 0, 0, 26, 0, 0, 0, 0, 0, 0, 0, 27, 143, 28, 29, 30, 31, 32, 33, 0, 34, 0, 0, 35, 0, 0, 36, 37, 38, 39, 0, 0, 0, 0, 1, 2, 3, 4, 0, 40, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 0, 0, 18, 19, 20, 0, 21, 22, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 25, 0, 0, 0, 0, 0, 0, 26, 0, 0, 0, 0, 0, 0, 0, 27, 292, 28, 29, 30, 31, 32, 33, 0, 34, 0, 0, 35, 0, 0, 36, 37, 38, 39, 0, 0, 0, 0, 477, 478, 479, 480, 0, 40, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 0, 0, 494, 495, 496, 0, 497, 498, 0, 0, 499, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 500, 501, 0, 0, 0, 0, 0, 0, 502, 0, 0, 0, 0, 0, 0, 0, 503, 642, 504, 505, 506, 507, 508, 509, 0, 510, 0, 0, 511, 0, 0, 512, 513, 514, 515, 0, 0, 0, 0, 477, 478, 479, 480, 0, 516, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 0, 0, 494, 495, 496, 0, 497, 498, 0, 0, 499, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 500, 501, 0, 0, 0, 0, 0, 0, 502, 0, 0, 0, 0, 0, 0, 0, 503, 811, 504, 505, 506, 507, 508, 509, 0, 510, 0, 0, 511, 0, 0, 512, 513, 514, 515, 0, 0, 0, 0, 1, 2, 3, 4, 0, 516, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 0, 0, 18, 19, 20, 0, 21, 22, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 25, 0, 0, 0, 0, 0, 0, 26, 0, 0, 0, 0, 0, 0, 0, 27, 0, 28, 29, 30, 31, 32, 33, 0, 34, 0, 0, 35, 0, 0, 36, 37, 38, 39, 0, 0, 0, 0, 477, 478, 479, 480, 0, 40, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 0, 0, 494, 495, 496, 0, 497, 498, 0, 0, 499, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 500, 501, 0, 0, 0, 0, 0, 0, 502, 0, 0, 0, 0, 0, 0, 0, 503, 0, 504, 505, 506, 507, 508, 509, 0, 510, 0, 0, 511, 0, 0, 512, 513, 514, 515, 1, 2, 3, 0, 0, 0, 0, 88, 210, 516, 0, 89, 0, 12, 13, 0, 15, 0, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 24, 25, 0, 88, 0, 0, 0, 89, 26, 12, 13, 0, 15, 0, 0, 0, 90, 18, 28, 91, 30, 31, 32, 33, 0, 34, 0, 0, 35, 0, 0, 36, 37, 38, 39, 0, 24, 25, 0, 0, 0, 0, 0, 0, 26, 0, 0, 0, 0, 0, 0, 0, 90, 0, 28, 91, 30, 31, 32, 33, 0, 34, 0, 0, 35, 297, 0, 36, 37, 38, 39, 1, 2, 3, 0, 0, 0, 0, 88, 0, 0, 0, 89, 0, 12, 13, 0, 15, 0, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 24, 25, 0, 88, 0, 0, 0, 89, 26, 12, 13, 0, 15, 0, 0, 0, 90, 18, 28, 91, 30, 31, 32, 33, 0, 34, 300, 0, 35, 0, 0, 36, 37, 38, 39, 0, 24, 25, 0, 0, 0, 0, 0, 0, 26, 0, 0, 0, 0, 0, 0, 0, 90, 0, 28, 91, 30, 31, 32, 33, 0, 34, 0, 0, 35, 463, 0, 36, 37, 38, 39, 477, 478, 479, 0, 0, 0, 0, 587, 729, 0, 0, 588, 0, 488, 489, 0, 491, 0, 0, 0, 0, 494, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 477, 478, 479, 0, 500, 501, 0, 587, 0, 0, 0, 588, 502, 488, 489, 0, 491, 0, 0, 0, 589, 494, 504, 590, 506, 507, 508, 509, 0, 510, 0, 0, 511, 0, 0, 512, 513, 514, 515, 0, 500, 501, 0, 0, 0, 0, 0, 0, 502, 0, 0, 0, 0, 0, 0, 0, 589, 0, 504, 590, 506, 507, 508, 509, 0, 510, 0, 0, 511, 816, 0, 512, 513, 514, 515, 477, 478, 479, 0, 0, 0, 0, 587, 0, 0, 0, 588, 0, 488, 489, 0, 491, 0, 0, 0, 0, 494, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 477, 478, 479, 0, 500, 501, 0, 587, 0, 0, 0, 588, 502, 488, 489, 0, 491, 0, 0, 0, 589, 494, 504, 590, 506, 507, 508, 509, 0, 510, 819, 0, 511, 0, 0, 512, 513, 514, 515, 0, 500, 501, 0, 0, 0, 0, 0, 0, 502, 0, 0, 0, 0, 0, 0, 0, 589, 0, 504, 590, 506, 507, 508, 509, 0, 510, 0, 0, 511, 1001, 0, 512, 513, 514, 515, 1, 2, 3, 0, 0, 0, 0, 88, 0, 0, 0, 89, 0, 12, 13, 0, 15, 0, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 477, 478, 479, 0, 24, 25, 0, 587, 0, 0, 0, 588, 26, 488, 489, 0, 491, 0, 0, 0, 90, 494, 28, 91, 30, 31, 32, 33, 0, 34, 0, 0, 35, 0, 0, 36, 37, 38, 39, 0, 500, 501, 0, 0, 0, 0, 0, 0, 502, 0, 0, 0, 0, 0, 866, 0, 589, 0, 504, 590, 506, 507, 508, 509, 0, 510, 0, 0, 511, 0, 0, 512, 513, 514, 515, 772, 773, 0, 0, 0, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 164, 165, 0, 0, 0, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 0, 0, 0, 0, 0, 0, 0, 253, 254, 0, 0, 677, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 664, 665, 0, 0, 177, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 0, 0, 0, 0, 0, 0, 0, 772, 773, 0, 0, 177, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 0, 0, 0, 0, 677, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 677 }; static const yytype_int16 yycheck[] = { 0, 16, 22, 0, 27, 498, 598, 767, 99, 441, 417, 452, 523, 248, 487, 955, 16, 46, 697, 16, 452, 682, 683, 197, 497, 698, 867, 27, 6, 11, 27, 336, 482, 482, 475, 503, 699, 510, 492, 21, 700, 882, 883, 475, 701, 1, 351, 352, 1, 650, 41, 22, 34, 74, 75, 41, 657, 62, 41, 70, 492, 22, 67, 70, 41, 94, 68, 474, 83, 41, 1, 503, 66, 1013, 1, 67, 87, 678, 70, 108, 87, 110, 593, 83, 78, 79, 83, 62, 62, 1, 70, 1, 1, 68, 85, 1035, 607, 1, 609, 85, 274, 702, 85, 704, 67, 559, 62, 70, 85, 414, 88, 952, 441, 85, 793, 86, 151, 778, 779, 560, 355, 794, 157, 452, 565, 86, 886, 559, 560, 144, 145, 87, 795, 565, 87, 62, 796, 587, 587, 70, 797, 582, 1, 178, 144, 145, 475, 144, 145, 131, 582, 133, 1, 135, 136, 756, 87, 630, 586, 632, 87, 634, 635, 492, 1, 1, 70, 202, 473, 204, 577, 1012, 1, 774, 503, 87, 158, 87, 87, 161, 1, 12, 13, 87, 1, 658, 1, 18, 661, 643, 644, 41, 6, 24, 25, 224, 1, 798, 1, 800, 31, 32, 237, 62, 1, 36, 37, 38, 39, 1, 445, 643, 644, 693, 694, 695, 696, 1, 1, 47, 255, 70, 524, 983, 684, 685, 686, 8, 87, 198, 559, 560, 743, 70, 70, 85, 565, 60, 87, 199, 62, 62, 200, 62, 279, 8, 281, 70, 67, 62, 87, 87, 234, 582, 62, 70, 69, 68, 87, 687, 688, 689, 690, 691, 692, 70, 87, 708, 250, 201, 87, 291, 87, 70, 88, 68, 708, 368, 70, 60, 753, 66, 87, 111, 87, 59, 70, 182, 183, 890, 87, 892, 893, 78, 79, 87, 769, 60, 62, 35, 36, 37, 38, 87, 87, 69, 275, 899, 610, 789, 790, 791, 792, 68, 643, 644, 276, 810, 62, 277, 780, 781, 782, 66, 359, 69, 361, 362, 66, 74, 75, 193, 194, 195, 196, 78, 79, 938, 990, 940, 78, 79, 943, 68, 60, 62, 278, 67, 179, 180, 181, 82, 69, 335, 70, 783, 784, 785, 786, 787, 788, 62, 1014, 62, 259, 260, 1018, 62, 69, 62, 69, 1023, 407, 68, 409, 62, 69, 412, 23, 708, 23, 70, 69, 72, 70, 400, 72, 402, 1040, 404, 84, 1043, 993, 866, 39, 40, 39, 40, 83, 70, 400, 72, 402, 400, 404, 402, 42, 404, 270, 271, 272, 273, 1064, 854, 184, 185, 186, 0, 68, 401, 455, 71, 854, 73, 86, 256, 257, 258, 70, 68, 72, 413, 71, 68, 73, 80, 81, 80, 81, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 82, 472, 68, 932, 83, 71, 68, 73, 84, 71, 42, 73, 22, 23, 70, 68, 472, 21, 71, 472, 73, 931, 951, 933, 62, 935, 45, 46, 47, 39, 40, 469, 43, 44, 11, 261, 262, 263, 62, 60, 61, 62, 63, 931, 21, 933, 68, 935, 62, 71, 70, 73, 72, 68, 82, 979, 71, 34, 73, 68, 30, 31, 71, 70, 73, 72, 990, 83, 952, 854, 80, 81, 45, 46, 47, 22, 23, 42, 70, 1008, 72, 84, 1031, 35, 36, 37, 38, 45, 46, 47, 1014, 979, 39, 40, 1018, 70, 567, 573, 1027, 1023, 87, 1011, 990, 574, 45, 46, 47, 1017, 69, 70, 87, 567, 69, 70, 567, 1025, 1040, 68, 574, 1043, 1069, 574, 1032, 1011, 67, 70, 1014, 72, 1012, 1017, 1018, 569, 67, 80, 81, 1023, 70, 1025, 72, 70, 1064, 72, 1066, 1067, 1032, 62, 931, 1057, 933, 1059, 935, 62, 1040, 62, 131, 1043, 133, 67, 135, 136, 68, 1071, 35, 36, 37, 38, 1076, 1077, 68, 1057, 59, 1059, 69, 70, 151, 68, 1064, 59, 1066, 1067, 157, 158, 67, 1071, 161, 22, 23, 59, 1076, 1077, 60, 61, 62, 63, 979, 69, 70, 62, 487, 74, 75, 178, 39, 40, 62, 990, 22, 23, 497, 35, 36, 37, 38, 60, 61, 62, 63, 35, 36, 37, 38, 510, 22, 39, 40, 202, 1011, 204, 70, 1014, 69, 70, 1017, 1018, 35, 36, 37, 38, 1023, 87, 1025, 69, 70, 80, 81, 69, 70, 1032, 69, 70, 67, 722, 59, 724, 59, 1040, 62, 234, 1043, 34, 237, 69, 70, 59, 80, 81, 722, 7, 724, 722, 69, 724, 1057, 250, 1059, 69, 70, 86, 255, 1064, 59, 1066, 1067, 69, 70, 87, 1071, 60, 61, 62, 63, 1076, 1077, 69, 70, 488, 489, 586, 69, 70, 68, 494, 279, 22, 281, 69, 70, 500, 501, 342, 343, 344, 345, 62, 507, 508, 74, 75, 62, 512, 513, 514, 515, 62, 43, 44, 43, 44, 70, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 68, 630, 68, 632, 68, 634, 635, 873, 874, 875, 876, 30, 31, 69, 70, 68, 87, 59, 335, 336, 60, 650, 69, 70, 69, 70, 67, 86, 657, 658, 69, 70, 661, 82, 351, 352, 353, 856, 857, 69, 70, 84, 359, 859, 361, 362, 3, 4, 5, 678, 861, 69, 70, 10, 69, 70, 83, 14, 69, 70, 856, 857, 19, 856, 857, 861, 69, 70, 861, 69, 70, 69, 70, 702, 42, 704, 69, 70, 69, 70, 69, 70, 59, 69, 401, 60, 60, 86, 68, 83, 407, 42, 409, 21, 51, 412, 413, 414, 82, 84, 417, 70, 59, 62, 61, 62, 63, 62, 60, 66, 59, 68, 60, 67, 71, 31, 187, 188, 189, 190, 191, 192, 69, 60, 753, 83, 62, 756, 84, 82, 42, 70, 62, 68, 67, 946, 947, 87, 455, 62, 769, 67, 62, 68, 68, 774, 679, 680, 681, 67, 946, 947, 469, 946, 947, 60, 473, 474, 60, 1, 59, 3, 4, 5, 68, 59, 67, 59, 10, 798, 60, 800, 14, 62, 16, 17, 22, 19, 62, 67, 87, 59, 24, 70, 59, 62, 59, 34, 7, 69, 86, 59, 87, 264, 265, 266, 267, 268, 269, 60, 59, 43, 44, 60, 69, 60, 60, 59, 31, 51, 60, 67, 60, 364, 295, 60, 69, 59, 346, 61, 62, 63, 64, 65, 66, 60, 68, 60, 348, 71, 347, 349, 74, 75, 76, 77, 350, 866, 867, 244, 470, 718, 775, 776, 777, 87, 571, 895, 878, 814, 881, 877, 569, 882, 883, 884, 879, 763, 880, 1009, 577, 890, 1053, 892, 893, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 1029, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 3, 4, 5, -1, -1, -1, -1, 10, -1, 932, -1, 14, -1, 16, 17, 938, 19, 940, -1, -1, 943, 24, -1, -1, -1, -1, -1, -1, 951, 952, -1, -1, 955, -1, -1, 3, 4, 5, -1, -1, 43, 44, 10, -1, -1, -1, 14, -1, 51, 414, -1, 19, -1, -1, -1, -1, 59, -1, 61, 62, 63, 64, 65, 66, -1, 68, -1, -1, 71, -1, 993, 74, 75, 76, 77, -1, -1, -1, -1, -1, -1, -1, -1, 51, 87, 1008, -1, -1, -1, 1012, 1013, 59, -1, 61, 62, 63, -1, -1, 66, -1, 68, -1, -1, 71, 1027, -1, -1, -1, 473, -1, -1, -1, 1035, 3, 4, 5, 6, -1, -1, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, -1, -1, 24, 25, 26, -1, 28, 29, -1, -1, 32, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 43, 44, -1, -1, -1, -1, -1, -1, 51, -1, -1, -1, -1, -1, -1, -1, 59, 60, 61, 62, 63, 64, 65, 66, -1, 68, -1, -1, 71, -1, -1, 74, 75, 76, 77, -1, -1, -1, -1, 3, 4, 5, 6, -1, 87, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, -1, -1, 24, 25, 26, -1, 28, 29, -1, -1, 32, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 43, 44, -1, -1, -1, -1, -1, -1, 51, -1, -1, -1, -1, -1, -1, -1, 59, 60, 61, 62, 63, 64, 65, 66, -1, 68, -1, -1, 71, -1, -1, 74, 75, 76, 77, -1, -1, -1, -1, 3, 4, 5, 6, -1, 87, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, -1, -1, 24, 25, 26, -1, 28, 29, -1, -1, 32, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 43, 44, -1, -1, -1, -1, -1, -1, 51, -1, -1, -1, -1, -1, -1, -1, 59, 60, 61, 62, 63, 64, 65, 66, -1, 68, -1, -1, 71, -1, -1, 74, 75, 76, 77, -1, -1, -1, -1, 3, 4, 5, 6, -1, 87, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, -1, -1, 24, 25, 26, -1, 28, 29, -1, -1, 32, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 43, 44, -1, -1, -1, -1, -1, -1, 51, -1, -1, -1, -1, -1, -1, -1, 59, 60, 61, 62, 63, 64, 65, 66, -1, 68, -1, -1, 71, -1, -1, 74, 75, 76, 77, -1, -1, -1, -1, 3, 4, 5, 6, -1, 87, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, -1, -1, 24, 25, 26, -1, 28, 29, -1, -1, 32, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 43, 44, -1, -1, -1, -1, -1, -1, 51, -1, -1, -1, -1, -1, -1, -1, 59, -1, 61, 62, 63, 64, 65, 66, -1, 68, -1, -1, 71, -1, -1, 74, 75, 76, 77, -1, -1, -1, -1, 3, 4, 5, 6, -1, 87, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, -1, -1, 24, 25, 26, -1, 28, 29, -1, -1, 32, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 43, 44, -1, -1, -1, -1, -1, -1, 51, -1, -1, -1, -1, -1, -1, -1, 59, -1, 61, 62, 63, 64, 65, 66, -1, 68, -1, -1, 71, -1, -1, 74, 75, 76, 77, 3, 4, 5, -1, -1, -1, -1, 10, 11, 87, -1, 14, -1, 16, 17, -1, 19, -1, -1, -1, -1, 24, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 4, 5, -1, 43, 44, -1, 10, -1, -1, -1, 14, 51, 16, 17, -1, 19, -1, -1, -1, 59, 24, 61, 62, 63, 64, 65, 66, -1, 68, -1, -1, 71, -1, -1, 74, 75, 76, 77, -1, 43, 44, -1, -1, -1, -1, -1, -1, 51, -1, -1, -1, -1, -1, -1, -1, 59, -1, 61, 62, 63, 64, 65, 66, -1, 68, -1, -1, 71, 72, -1, 74, 75, 76, 77, 3, 4, 5, -1, -1, -1, -1, 10, -1, -1, -1, 14, -1, 16, 17, -1, 19, -1, -1, -1, -1, 24, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 4, 5, -1, 43, 44, -1, 10, -1, -1, -1, 14, 51, 16, 17, -1, 19, -1, -1, -1, 59, 24, 61, 62, 63, 64, 65, 66, -1, 68, 69, -1, 71, -1, -1, 74, 75, 76, 77, -1, 43, 44, -1, -1, -1, -1, -1, -1, 51, -1, -1, -1, -1, -1, -1, -1, 59, -1, 61, 62, 63, 64, 65, 66, -1, 68, -1, -1, 71, 72, -1, 74, 75, 76, 77, 3, 4, 5, -1, -1, -1, -1, 10, 11, -1, -1, 14, -1, 16, 17, -1, 19, -1, -1, -1, -1, 24, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 4, 5, -1, 43, 44, -1, 10, -1, -1, -1, 14, 51, 16, 17, -1, 19, -1, -1, -1, 59, 24, 61, 62, 63, 64, 65, 66, -1, 68, -1, -1, 71, -1, -1, 74, 75, 76, 77, -1, 43, 44, -1, -1, -1, -1, -1, -1, 51, -1, -1, -1, -1, -1, -1, -1, 59, -1, 61, 62, 63, 64, 65, 66, -1, 68, -1, -1, 71, 72, -1, 74, 75, 76, 77, 3, 4, 5, -1, -1, -1, -1, 10, -1, -1, -1, 14, -1, 16, 17, -1, 19, -1, -1, -1, -1, 24, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 4, 5, -1, 43, 44, -1, 10, -1, -1, -1, 14, 51, 16, 17, -1, 19, -1, -1, -1, 59, 24, 61, 62, 63, 64, 65, 66, -1, 68, 69, -1, 71, -1, -1, 74, 75, 76, 77, -1, 43, 44, -1, -1, -1, -1, -1, -1, 51, -1, -1, -1, -1, -1, -1, -1, 59, -1, 61, 62, 63, 64, 65, 66, -1, 68, -1, -1, 71, 72, -1, 74, 75, 76, 77, 3, 4, 5, -1, -1, -1, -1, 10, -1, -1, -1, 14, -1, 16, 17, -1, 19, -1, -1, -1, -1, 24, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 4, 5, -1, 43, 44, -1, 10, -1, -1, -1, 14, 51, 16, 17, -1, 19, -1, -1, -1, 59, 24, 61, 62, 63, 64, 65, 66, -1, 68, -1, -1, 71, -1, -1, 74, 75, 76, 77, -1, 43, 44, -1, -1, -1, -1, -1, -1, 51, -1, -1, -1, -1, -1, 22, -1, 59, -1, 61, 62, 63, 64, 65, 66, -1, 68, -1, -1, 71, -1, -1, 74, 75, 76, 77, 43, 44, -1, -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 43, 44, -1, -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, -1, -1, -1, -1, -1, -1, -1, 43, 44, -1, -1, 86, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 43, 44, -1, -1, 86, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, -1, -1, -1, -1, -1, -1, -1, 43, 44, -1, -1, 86, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, -1, -1, -1, -1, 86, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 86 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint16 yystos[] = { 0, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 24, 25, 26, 28, 29, 32, 43, 44, 51, 59, 61, 62, 63, 64, 65, 66, 68, 71, 74, 75, 76, 77, 87, 89, 93, 94, 99, 101, 103, 107, 109, 110, 112, 114, 116, 118, 121, 124, 127, 130, 133, 136, 139, 142, 145, 149, 150, 151, 152, 155, 160, 161, 162, 163, 166, 167, 168, 169, 170, 176, 177, 178, 179, 180, 184, 185, 1, 62, 87, 68, 10, 14, 59, 62, 92, 93, 98, 100, 181, 62, 153, 62, 156, 157, 1, 62, 87, 62, 1, 87, 98, 100, 102, 106, 108, 110, 111, 113, 115, 117, 119, 122, 125, 128, 131, 134, 137, 140, 143, 147, 106, 111, 111, 68, 150, 68, 111, 68, 68, 147, 151, 1, 87, 111, 111, 60, 185, 67, 111, 111, 147, 70, 95, 96, 97, 111, 111, 111, 111, 68, 71, 73, 104, 71, 73, 104, 43, 44, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 86, 146, 66, 78, 79, 74, 75, 45, 46, 47, 22, 23, 39, 40, 80, 81, 35, 36, 37, 38, 82, 83, 84, 42, 41, 85, 1, 70, 87, 0, 150, 1, 87, 11, 106, 117, 120, 123, 126, 129, 132, 135, 138, 141, 144, 148, 165, 98, 100, 62, 68, 60, 61, 62, 63, 90, 91, 71, 73, 104, 86, 158, 1, 70, 87, 158, 1, 70, 87, 1, 87, 68, 104, 71, 73, 104, 43, 44, 146, 66, 78, 79, 74, 75, 45, 46, 47, 22, 23, 39, 40, 80, 81, 35, 36, 37, 38, 82, 83, 84, 42, 41, 85, 1, 70, 87, 147, 21, 147, 147, 147, 1, 87, 30, 31, 60, 150, 69, 70, 72, 72, 143, 70, 69, 105, 143, 147, 62, 147, 62, 143, 111, 111, 111, 113, 113, 115, 115, 115, 117, 117, 117, 117, 117, 117, 119, 119, 119, 119, 122, 125, 128, 131, 134, 143, 143, 62, 154, 22, 146, 23, 39, 40, 80, 81, 35, 36, 37, 38, 82, 83, 84, 42, 41, 85, 70, 87, 104, 68, 62, 69, 182, 67, 62, 67, 67, 60, 70, 147, 62, 143, 62, 157, 69, 182, 147, 62, 143, 111, 111, 111, 113, 113, 115, 115, 115, 117, 117, 117, 117, 117, 117, 119, 119, 119, 119, 122, 125, 128, 131, 134, 143, 143, 69, 68, 69, 69, 69, 68, 151, 96, 69, 70, 72, 72, 67, 22, 86, 159, 70, 87, 147, 106, 144, 117, 117, 117, 117, 117, 120, 120, 120, 120, 123, 126, 129, 132, 135, 144, 144, 147, 164, 69, 182, 59, 69, 70, 143, 68, 143, 143, 60, 90, 72, 158, 59, 69, 72, 67, 150, 147, 150, 59, 171, 150, 62, 72, 143, 143, 143, 147, 144, 22, 62, 164, 69, 67, 87, 59, 69, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 24, 25, 26, 28, 29, 32, 43, 44, 51, 59, 61, 62, 63, 64, 65, 66, 68, 71, 74, 75, 76, 77, 87, 183, 186, 190, 191, 196, 198, 200, 204, 206, 207, 209, 211, 213, 215, 218, 221, 224, 227, 230, 233, 236, 239, 242, 246, 247, 248, 249, 252, 257, 258, 259, 260, 263, 264, 265, 266, 267, 273, 274, 275, 276, 277, 281, 59, 62, 69, 182, 183, 59, 143, 34, 69, 7, 172, 173, 174, 69, 69, 147, 159, 87, 150, 144, 164, 183, 59, 1, 62, 87, 68, 10, 14, 59, 62, 189, 190, 195, 197, 278, 62, 250, 62, 253, 254, 1, 62, 87, 62, 1, 87, 195, 197, 199, 203, 205, 207, 208, 210, 212, 214, 216, 219, 222, 225, 228, 231, 234, 237, 240, 244, 203, 208, 208, 68, 247, 68, 208, 68, 68, 244, 248, 1, 87, 208, 208, 60, 281, 67, 208, 208, 244, 70, 192, 193, 194, 208, 208, 208, 208, 60, 68, 71, 73, 201, 71, 73, 201, 43, 44, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 86, 243, 66, 78, 79, 74, 75, 45, 46, 47, 22, 23, 39, 40, 80, 81, 35, 36, 37, 38, 82, 83, 84, 42, 41, 85, 1, 70, 87, 247, 183, 59, 69, 60, 183, 150, 1, 87, 147, 8, 60, 175, 174, 151, 150, 69, 164, 69, 60, 183, 1, 87, 11, 203, 214, 217, 220, 223, 226, 229, 232, 235, 238, 241, 245, 262, 195, 197, 62, 68, 60, 61, 62, 63, 187, 188, 71, 73, 201, 86, 255, 1, 70, 87, 255, 1, 70, 87, 1, 87, 68, 201, 71, 73, 201, 43, 44, 243, 66, 78, 79, 74, 75, 45, 46, 47, 22, 23, 39, 40, 80, 81, 35, 36, 37, 38, 82, 83, 84, 42, 41, 85, 1, 70, 87, 244, 21, 244, 244, 244, 1, 87, 30, 31, 60, 247, 69, 70, 72, 72, 240, 70, 69, 202, 240, 244, 62, 244, 62, 240, 208, 208, 208, 210, 210, 212, 212, 212, 214, 214, 214, 214, 214, 214, 216, 216, 216, 216, 219, 222, 225, 228, 231, 240, 240, 60, 183, 59, 60, 67, 67, 172, 31, 150, 69, 150, 60, 62, 251, 22, 243, 23, 39, 40, 80, 81, 35, 36, 37, 38, 82, 83, 84, 42, 41, 85, 70, 87, 201, 68, 62, 69, 279, 67, 62, 67, 67, 60, 70, 244, 62, 240, 62, 254, 69, 279, 244, 62, 240, 208, 208, 208, 210, 210, 212, 212, 212, 214, 214, 214, 214, 214, 214, 216, 216, 216, 216, 219, 222, 225, 228, 231, 240, 240, 69, 68, 69, 69, 69, 68, 248, 193, 69, 70, 72, 72, 67, 60, 183, 185, 185, 60, 151, 150, 22, 86, 256, 70, 87, 244, 203, 241, 214, 214, 214, 214, 214, 217, 217, 217, 217, 220, 223, 226, 229, 232, 241, 241, 244, 261, 69, 279, 59, 69, 70, 240, 68, 240, 240, 60, 187, 72, 255, 59, 69, 72, 67, 247, 244, 247, 59, 268, 247, 62, 72, 240, 240, 240, 60, 244, 241, 22, 62, 261, 69, 67, 87, 59, 69, 280, 281, 59, 62, 69, 279, 280, 59, 240, 34, 69, 7, 269, 270, 271, 69, 69, 244, 256, 87, 247, 241, 261, 280, 59, 60, 280, 59, 69, 60, 280, 247, 1, 87, 244, 8, 60, 272, 271, 248, 247, 69, 261, 69, 60, 280, 60, 280, 59, 60, 67, 67, 269, 31, 247, 69, 247, 60, 60, 280, 281, 281, 60, 248, 247, 60 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL goto yyerrlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { \ yychar = (Token); \ yylval = (Value); \ yytoken = YYTRANSLATE (yychar); \ YYPOPSTACK (1); \ goto yybackup; \ } \ else \ { \ yyerror (YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #define YYRHSLOC(Rhs, K) ((Rhs)[K]) #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (YYID (N)) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (YYID (0)) #endif /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if YYLTYPE_IS_TRIVIAL # define YY_LOCATION_PRINT(File, Loc) \ fprintf (File, "%d.%d-%d.%d", \ (Loc).first_line, (Loc).first_column, \ (Loc).last_line, (Loc).last_column) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (&yylval, &yylloc, YYLEX_PARAM) #else # define YYLEX yylex (&yylval, &yylloc) #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, Location); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; #endif { if (!yyvaluep) return; YYUSE (yylocationp); # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep, yylocationp) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); YY_LOCATION_PRINT (yyoutput, *yylocationp); YYFPRINTF (yyoutput, ": "); yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) #else static void yy_stack_print (yybottom, yytop) yytype_int16 *yybottom; yytype_int16 *yytop; #endif { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule) #else static void yy_reduce_print (yyvsp, yylsp, yyrule) YYSTYPE *yyvsp; YYLTYPE *yylsp; int yyrule; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) , &(yylsp[(yyi + 1) - (yynrhs)]) ); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, yylsp, Rule); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into YYRESULT an error message about the unexpected token YYCHAR while in state YYSTATE. Return the number of bytes copied, including the terminating null byte. If YYRESULT is null, do not copy anything; just return the number of bytes that would be copied. As a special case, return 0 if an ordinary "syntax error" message will do. Return YYSIZE_MAXIMUM if overflow occurs during size calculation. */ static YYSIZE_T yysyntax_error (char *yyresult, int yystate, int yychar) { int yyn = yypact[yystate]; if (! (YYPACT_NINF < yyn && yyn <= YYLAST)) return 0; else { int yytype = YYTRANSLATE (yychar); YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]); YYSIZE_T yysize = yysize0; YYSIZE_T yysize1; int yysize_overflow = 0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; int yyx; # if 0 /* This is so xgettext sees the translatable formats that are constructed on the fly. */ YY_("syntax error, unexpected %s"); YY_("syntax error, unexpected %s, expecting %s"); YY_("syntax error, unexpected %s, expecting %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"); # endif char *yyfmt; char const *yyf; static char const yyunexpected[] = "syntax error, unexpected %s"; static char const yyexpecting[] = ", expecting %s"; static char const yyor[] = " or %s"; char yyformat[sizeof yyunexpected + sizeof yyexpecting - 1 + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) * (sizeof yyor - 1))]; char const *yyprefix = yyexpecting; /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yycount = 1; yyarg[0] = yytname[yytype]; yyfmt = yystpcpy (yyformat, yyunexpected); for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; yyformat[sizeof yyunexpected - 1] = '\0'; break; } yyarg[yycount++] = yytname[yyx]; yysize1 = yysize + yytnamerr (0, yytname[yyx]); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; yyfmt = yystpcpy (yyfmt, yyprefix); yyprefix = yyor; } yyf = YY_(yyformat); yysize1 = yysize + yystrlen (yyf); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; if (yysize_overflow) return YYSIZE_MAXIMUM; if (yyresult) { /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ char *yyp = yyresult; int yyi = 0; while ((*yyp = *yyf) != '\0') { if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyf += 2; } else { yyp++; yyf++; } } } return yysize; } } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp) #else static void yydestruct (yymsg, yytype, yyvaluep, yylocationp) const char *yymsg; int yytype; YYSTYPE *yyvaluep; YYLTYPE *yylocationp; #endif { YYUSE (yyvaluep); YYUSE (yylocationp); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /* Prevent warnings from -Wmissing-prototypes. */ #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (void); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ /*-------------------------. | yyparse or yypush_parse. | `-------------------------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void) #else int yyparse () #endif #endif { /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ YYSTYPE yylval; /* Location data for the lookahead symbol. */ YYLTYPE yylloc; /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: `yyss': related to states. `yyvs': related to semantic values. `yyls': related to locations. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[2]; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yytoken = 0; yyss = yyssa; yyvs = yyvsa; yyls = yylsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; yylsp = yyls; #if YYLTYPE_IS_TRIVIAL /* Initialize the default location before parsing starts. */ yylloc.first_line = yylloc.last_line = 1; yylloc.first_column = yylloc.last_column = 1; #endif goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyls = yyls1; yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); YYSTACK_RELOCATE (yyls_alloc, yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: /* Line 1455 of yacc.c */ #line 290 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new NullNode(GLOBAL_DATA), 0, 1); ;} break; case 3: /* Line 1455 of yacc.c */ #line 291 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new BooleanNode(GLOBAL_DATA, true), 0, 1); ;} break; case 4: /* Line 1455 of yacc.c */ #line 292 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new BooleanNode(GLOBAL_DATA, false), 0, 1); ;} break; case 5: /* Line 1455 of yacc.c */ #line 293 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeNumberNode(GLOBAL_DATA, (yyvsp[(1) - (1)].doubleValue)), 0, 1); ;} break; case 6: /* Line 1455 of yacc.c */ #line 294 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new StringNode(GLOBAL_DATA, *(yyvsp[(1) - (1)].ident)), 0, 1); ;} break; case 7: /* Line 1455 of yacc.c */ #line 295 "../../JavaScriptCore/parser/Grammar.y" { Lexer& l = *LEXER; if (!l.scanRegExp()) YYABORT; RegExpNode* node = new RegExpNode(GLOBAL_DATA, l.pattern(), l.flags()); int size = l.pattern().size() + 2; // + 2 for the two /'s SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (1)]).first_column, (yylsp[(1) - (1)]).first_column + size, (yylsp[(1) - (1)]).first_column + size); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, 0, 0); ;} break; case 8: /* Line 1455 of yacc.c */ #line 304 "../../JavaScriptCore/parser/Grammar.y" { Lexer& l = *LEXER; if (!l.scanRegExp()) YYABORT; RegExpNode* node = new RegExpNode(GLOBAL_DATA, "=" + l.pattern(), l.flags()); int size = l.pattern().size() + 2; // + 2 for the two /'s SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (1)]).first_column, (yylsp[(1) - (1)]).first_column + size, (yylsp[(1) - (1)]).first_column + size); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, 0, 0); ;} break; case 9: /* Line 1455 of yacc.c */ #line 316 "../../JavaScriptCore/parser/Grammar.y" { (yyval.propertyNode) = createNodeInfo<PropertyNode*>(new PropertyNode(GLOBAL_DATA, *(yyvsp[(1) - (3)].ident), (yyvsp[(3) - (3)].expressionNode).m_node, PropertyNode::Constant), (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 10: /* Line 1455 of yacc.c */ #line 317 "../../JavaScriptCore/parser/Grammar.y" { (yyval.propertyNode) = createNodeInfo<PropertyNode*>(new PropertyNode(GLOBAL_DATA, *(yyvsp[(1) - (3)].ident), (yyvsp[(3) - (3)].expressionNode).m_node, PropertyNode::Constant), (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 11: /* Line 1455 of yacc.c */ #line 318 "../../JavaScriptCore/parser/Grammar.y" { (yyval.propertyNode) = createNodeInfo<PropertyNode*>(new PropertyNode(GLOBAL_DATA, Identifier(GLOBAL_DATA, UString::from((yyvsp[(1) - (3)].doubleValue))), (yyvsp[(3) - (3)].expressionNode).m_node, PropertyNode::Constant), (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 12: /* Line 1455 of yacc.c */ #line 319 "../../JavaScriptCore/parser/Grammar.y" { (yyval.propertyNode) = createNodeInfo<PropertyNode*>(makeGetterOrSetterPropertyNode(globalPtr, *(yyvsp[(1) - (7)].ident), *(yyvsp[(2) - (7)].ident), 0, (yyvsp[(6) - (7)].functionBodyNode), LEXER->sourceCode((yyvsp[(5) - (7)].intValue), (yyvsp[(7) - (7)].intValue), (yylsp[(5) - (7)]).first_line)), ClosureFeature, 0); DBG((yyvsp[(6) - (7)].functionBodyNode), (yylsp[(5) - (7)]), (yylsp[(7) - (7)])); if (!(yyval.propertyNode).m_node) YYABORT; ;} break; case 13: /* Line 1455 of yacc.c */ #line 321 "../../JavaScriptCore/parser/Grammar.y" { (yyval.propertyNode) = createNodeInfo<PropertyNode*>(makeGetterOrSetterPropertyNode(globalPtr, *(yyvsp[(1) - (8)].ident), *(yyvsp[(2) - (8)].ident), (yyvsp[(4) - (8)].parameterList).m_node.head, (yyvsp[(7) - (8)].functionBodyNode), LEXER->sourceCode((yyvsp[(6) - (8)].intValue), (yyvsp[(8) - (8)].intValue), (yylsp[(6) - (8)]).first_line)), (yyvsp[(4) - (8)].parameterList).m_features | ClosureFeature, 0); if ((yyvsp[(4) - (8)].parameterList).m_features & ArgumentsFeature) (yyvsp[(7) - (8)].functionBodyNode)->setUsesArguments(); DBG((yyvsp[(7) - (8)].functionBodyNode), (yylsp[(6) - (8)]), (yylsp[(8) - (8)])); if (!(yyval.propertyNode).m_node) YYABORT; ;} break; case 14: /* Line 1455 of yacc.c */ #line 332 "../../JavaScriptCore/parser/Grammar.y" { (yyval.propertyList).m_node.head = new PropertyListNode(GLOBAL_DATA, (yyvsp[(1) - (1)].propertyNode).m_node); (yyval.propertyList).m_node.tail = (yyval.propertyList).m_node.head; (yyval.propertyList).m_features = (yyvsp[(1) - (1)].propertyNode).m_features; (yyval.propertyList).m_numConstants = (yyvsp[(1) - (1)].propertyNode).m_numConstants; ;} break; case 15: /* Line 1455 of yacc.c */ #line 336 "../../JavaScriptCore/parser/Grammar.y" { (yyval.propertyList).m_node.head = (yyvsp[(1) - (3)].propertyList).m_node.head; (yyval.propertyList).m_node.tail = new PropertyListNode(GLOBAL_DATA, (yyvsp[(3) - (3)].propertyNode).m_node, (yyvsp[(1) - (3)].propertyList).m_node.tail); (yyval.propertyList).m_features = (yyvsp[(1) - (3)].propertyList).m_features | (yyvsp[(3) - (3)].propertyNode).m_features; (yyval.propertyList).m_numConstants = (yyvsp[(1) - (3)].propertyList).m_numConstants + (yyvsp[(3) - (3)].propertyNode).m_numConstants; ;} break; case 17: /* Line 1455 of yacc.c */ #line 344 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new ObjectLiteralNode(GLOBAL_DATA), 0, 0); ;} break; case 18: /* Line 1455 of yacc.c */ #line 345 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new ObjectLiteralNode(GLOBAL_DATA, (yyvsp[(2) - (3)].propertyList).m_node.head), (yyvsp[(2) - (3)].propertyList).m_features, (yyvsp[(2) - (3)].propertyList).m_numConstants); ;} break; case 19: /* Line 1455 of yacc.c */ #line 347 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new ObjectLiteralNode(GLOBAL_DATA, (yyvsp[(2) - (4)].propertyList).m_node.head), (yyvsp[(2) - (4)].propertyList).m_features, (yyvsp[(2) - (4)].propertyList).m_numConstants); ;} break; case 20: /* Line 1455 of yacc.c */ #line 351 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new ThisNode(GLOBAL_DATA), ThisFeature, 0); ;} break; case 23: /* Line 1455 of yacc.c */ #line 354 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new ResolveNode(GLOBAL_DATA, *(yyvsp[(1) - (1)].ident), (yylsp[(1) - (1)]).first_column), (*(yyvsp[(1) - (1)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0, 0); ;} break; case 24: /* Line 1455 of yacc.c */ #line 355 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = (yyvsp[(2) - (3)].expressionNode); ;} break; case 25: /* Line 1455 of yacc.c */ #line 359 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new ArrayNode(GLOBAL_DATA, (yyvsp[(2) - (3)].intValue)), 0, (yyvsp[(2) - (3)].intValue) ? 1 : 0); ;} break; case 26: /* Line 1455 of yacc.c */ #line 360 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new ArrayNode(GLOBAL_DATA, (yyvsp[(2) - (3)].elementList).m_node.head), (yyvsp[(2) - (3)].elementList).m_features, (yyvsp[(2) - (3)].elementList).m_numConstants); ;} break; case 27: /* Line 1455 of yacc.c */ #line 361 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new ArrayNode(GLOBAL_DATA, (yyvsp[(4) - (5)].intValue), (yyvsp[(2) - (5)].elementList).m_node.head), (yyvsp[(2) - (5)].elementList).m_features, (yyvsp[(4) - (5)].intValue) ? (yyvsp[(2) - (5)].elementList).m_numConstants + 1 : (yyvsp[(2) - (5)].elementList).m_numConstants); ;} break; case 28: /* Line 1455 of yacc.c */ #line 365 "../../JavaScriptCore/parser/Grammar.y" { (yyval.elementList).m_node.head = new ElementNode(GLOBAL_DATA, (yyvsp[(1) - (2)].intValue), (yyvsp[(2) - (2)].expressionNode).m_node); (yyval.elementList).m_node.tail = (yyval.elementList).m_node.head; (yyval.elementList).m_features = (yyvsp[(2) - (2)].expressionNode).m_features; (yyval.elementList).m_numConstants = (yyvsp[(2) - (2)].expressionNode).m_numConstants; ;} break; case 29: /* Line 1455 of yacc.c */ #line 370 "../../JavaScriptCore/parser/Grammar.y" { (yyval.elementList).m_node.head = (yyvsp[(1) - (4)].elementList).m_node.head; (yyval.elementList).m_node.tail = new ElementNode(GLOBAL_DATA, (yyvsp[(1) - (4)].elementList).m_node.tail, (yyvsp[(3) - (4)].intValue), (yyvsp[(4) - (4)].expressionNode).m_node); (yyval.elementList).m_features = (yyvsp[(1) - (4)].elementList).m_features | (yyvsp[(4) - (4)].expressionNode).m_features; (yyval.elementList).m_numConstants = (yyvsp[(1) - (4)].elementList).m_numConstants + (yyvsp[(4) - (4)].expressionNode).m_numConstants; ;} break; case 30: /* Line 1455 of yacc.c */ #line 377 "../../JavaScriptCore/parser/Grammar.y" { (yyval.intValue) = 0; ;} break; case 32: /* Line 1455 of yacc.c */ #line 382 "../../JavaScriptCore/parser/Grammar.y" { (yyval.intValue) = 1; ;} break; case 33: /* Line 1455 of yacc.c */ #line 383 "../../JavaScriptCore/parser/Grammar.y" { (yyval.intValue) = (yyvsp[(1) - (2)].intValue) + 1; ;} break; case 35: /* Line 1455 of yacc.c */ #line 388 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>((yyvsp[(1) - (1)].funcExprNode).m_node, (yyvsp[(1) - (1)].funcExprNode).m_features, (yyvsp[(1) - (1)].funcExprNode).m_numConstants); ;} break; case 36: /* Line 1455 of yacc.c */ #line 389 "../../JavaScriptCore/parser/Grammar.y" { BracketAccessorNode* node = new BracketAccessorNode(GLOBAL_DATA, (yyvsp[(1) - (4)].expressionNode).m_node, (yyvsp[(3) - (4)].expressionNode).m_node, (yyvsp[(3) - (4)].expressionNode).m_features & AssignFeature); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (4)]).first_column, (yylsp[(1) - (4)]).last_column, (yylsp[(4) - (4)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(1) - (4)].expressionNode).m_features | (yyvsp[(3) - (4)].expressionNode).m_features, (yyvsp[(1) - (4)].expressionNode).m_numConstants + (yyvsp[(3) - (4)].expressionNode).m_numConstants); ;} break; case 37: /* Line 1455 of yacc.c */ #line 393 "../../JavaScriptCore/parser/Grammar.y" { DotAccessorNode* node = new DotAccessorNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, *(yyvsp[(3) - (3)].ident)); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(1) - (3)]).last_column, (yylsp[(3) - (3)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(1) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants); ;} break; case 38: /* Line 1455 of yacc.c */ #line 397 "../../JavaScriptCore/parser/Grammar.y" { NewExprNode* node = new NewExprNode(GLOBAL_DATA, (yyvsp[(2) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].argumentsNode).m_node); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(2) - (3)]).last_column, (yylsp[(3) - (3)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(2) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].argumentsNode).m_features, (yyvsp[(2) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].argumentsNode).m_numConstants); ;} break; case 40: /* Line 1455 of yacc.c */ #line 405 "../../JavaScriptCore/parser/Grammar.y" { BracketAccessorNode* node = new BracketAccessorNode(GLOBAL_DATA, (yyvsp[(1) - (4)].expressionNode).m_node, (yyvsp[(3) - (4)].expressionNode).m_node, (yyvsp[(3) - (4)].expressionNode).m_features & AssignFeature); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (4)]).first_column, (yylsp[(1) - (4)]).last_column, (yylsp[(4) - (4)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(1) - (4)].expressionNode).m_features | (yyvsp[(3) - (4)].expressionNode).m_features, (yyvsp[(1) - (4)].expressionNode).m_numConstants + (yyvsp[(3) - (4)].expressionNode).m_numConstants); ;} break; case 41: /* Line 1455 of yacc.c */ #line 409 "../../JavaScriptCore/parser/Grammar.y" { DotAccessorNode* node = new DotAccessorNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, *(yyvsp[(3) - (3)].ident)); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(1) - (3)]).last_column, (yylsp[(3) - (3)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(1) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants); ;} break; case 42: /* Line 1455 of yacc.c */ #line 413 "../../JavaScriptCore/parser/Grammar.y" { NewExprNode* node = new NewExprNode(GLOBAL_DATA, (yyvsp[(2) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].argumentsNode).m_node); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(2) - (3)]).last_column, (yylsp[(3) - (3)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(2) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].argumentsNode).m_features, (yyvsp[(2) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].argumentsNode).m_numConstants); ;} break; case 44: /* Line 1455 of yacc.c */ #line 421 "../../JavaScriptCore/parser/Grammar.y" { NewExprNode* node = new NewExprNode(GLOBAL_DATA, (yyvsp[(2) - (2)].expressionNode).m_node); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (2)]).first_column, (yylsp[(2) - (2)]).last_column, (yylsp[(2) - (2)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(2) - (2)].expressionNode).m_features, (yyvsp[(2) - (2)].expressionNode).m_numConstants); ;} break; case 46: /* Line 1455 of yacc.c */ #line 429 "../../JavaScriptCore/parser/Grammar.y" { NewExprNode* node = new NewExprNode(GLOBAL_DATA, (yyvsp[(2) - (2)].expressionNode).m_node); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (2)]).first_column, (yylsp[(2) - (2)]).last_column, (yylsp[(2) - (2)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(2) - (2)].expressionNode).m_features, (yyvsp[(2) - (2)].expressionNode).m_numConstants); ;} break; case 47: /* Line 1455 of yacc.c */ #line 436 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = makeFunctionCallNode(globalPtr, (yyvsp[(1) - (2)].expressionNode), (yyvsp[(2) - (2)].argumentsNode), (yylsp[(1) - (2)]).first_column, (yylsp[(1) - (2)]).last_column, (yylsp[(2) - (2)]).last_column); ;} break; case 48: /* Line 1455 of yacc.c */ #line 437 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = makeFunctionCallNode(globalPtr, (yyvsp[(1) - (2)].expressionNode), (yyvsp[(2) - (2)].argumentsNode), (yylsp[(1) - (2)]).first_column, (yylsp[(1) - (2)]).last_column, (yylsp[(2) - (2)]).last_column); ;} break; case 49: /* Line 1455 of yacc.c */ #line 438 "../../JavaScriptCore/parser/Grammar.y" { BracketAccessorNode* node = new BracketAccessorNode(GLOBAL_DATA, (yyvsp[(1) - (4)].expressionNode).m_node, (yyvsp[(3) - (4)].expressionNode).m_node, (yyvsp[(3) - (4)].expressionNode).m_features & AssignFeature); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (4)]).first_column, (yylsp[(1) - (4)]).last_column, (yylsp[(4) - (4)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(1) - (4)].expressionNode).m_features | (yyvsp[(3) - (4)].expressionNode).m_features, (yyvsp[(1) - (4)].expressionNode).m_numConstants + (yyvsp[(3) - (4)].expressionNode).m_numConstants); ;} break; case 50: /* Line 1455 of yacc.c */ #line 442 "../../JavaScriptCore/parser/Grammar.y" { DotAccessorNode* node = new DotAccessorNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, *(yyvsp[(3) - (3)].ident)); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(1) - (3)]).last_column, (yylsp[(3) - (3)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(1) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants); ;} break; case 51: /* Line 1455 of yacc.c */ #line 448 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = makeFunctionCallNode(globalPtr, (yyvsp[(1) - (2)].expressionNode), (yyvsp[(2) - (2)].argumentsNode), (yylsp[(1) - (2)]).first_column, (yylsp[(1) - (2)]).last_column, (yylsp[(2) - (2)]).last_column); ;} break; case 52: /* Line 1455 of yacc.c */ #line 449 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = makeFunctionCallNode(globalPtr, (yyvsp[(1) - (2)].expressionNode), (yyvsp[(2) - (2)].argumentsNode), (yylsp[(1) - (2)]).first_column, (yylsp[(1) - (2)]).last_column, (yylsp[(2) - (2)]).last_column); ;} break; case 53: /* Line 1455 of yacc.c */ #line 450 "../../JavaScriptCore/parser/Grammar.y" { BracketAccessorNode* node = new BracketAccessorNode(GLOBAL_DATA, (yyvsp[(1) - (4)].expressionNode).m_node, (yyvsp[(3) - (4)].expressionNode).m_node, (yyvsp[(3) - (4)].expressionNode).m_features & AssignFeature); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (4)]).first_column, (yylsp[(1) - (4)]).last_column, (yylsp[(4) - (4)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(1) - (4)].expressionNode).m_features | (yyvsp[(3) - (4)].expressionNode).m_features, (yyvsp[(1) - (4)].expressionNode).m_numConstants + (yyvsp[(3) - (4)].expressionNode).m_numConstants); ;} break; case 54: /* Line 1455 of yacc.c */ #line 454 "../../JavaScriptCore/parser/Grammar.y" { DotAccessorNode* node = new DotAccessorNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, *(yyvsp[(3) - (3)].ident)); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(1) - (3)]).last_column, (yylsp[(3) - (3)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(1) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants); ;} break; case 55: /* Line 1455 of yacc.c */ #line 461 "../../JavaScriptCore/parser/Grammar.y" { (yyval.argumentsNode) = createNodeInfo<ArgumentsNode*>(new ArgumentsNode(GLOBAL_DATA), 0, 0); ;} break; case 56: /* Line 1455 of yacc.c */ #line 462 "../../JavaScriptCore/parser/Grammar.y" { (yyval.argumentsNode) = createNodeInfo<ArgumentsNode*>(new ArgumentsNode(GLOBAL_DATA, (yyvsp[(2) - (3)].argumentList).m_node.head), (yyvsp[(2) - (3)].argumentList).m_features, (yyvsp[(2) - (3)].argumentList).m_numConstants); ;} break; case 57: /* Line 1455 of yacc.c */ #line 466 "../../JavaScriptCore/parser/Grammar.y" { (yyval.argumentList).m_node.head = new ArgumentListNode(GLOBAL_DATA, (yyvsp[(1) - (1)].expressionNode).m_node); (yyval.argumentList).m_node.tail = (yyval.argumentList).m_node.head; (yyval.argumentList).m_features = (yyvsp[(1) - (1)].expressionNode).m_features; (yyval.argumentList).m_numConstants = (yyvsp[(1) - (1)].expressionNode).m_numConstants; ;} break; case 58: /* Line 1455 of yacc.c */ #line 470 "../../JavaScriptCore/parser/Grammar.y" { (yyval.argumentList).m_node.head = (yyvsp[(1) - (3)].argumentList).m_node.head; (yyval.argumentList).m_node.tail = new ArgumentListNode(GLOBAL_DATA, (yyvsp[(1) - (3)].argumentList).m_node.tail, (yyvsp[(3) - (3)].expressionNode).m_node); (yyval.argumentList).m_features = (yyvsp[(1) - (3)].argumentList).m_features | (yyvsp[(3) - (3)].expressionNode).m_features; (yyval.argumentList).m_numConstants = (yyvsp[(1) - (3)].argumentList).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants; ;} break; case 64: /* Line 1455 of yacc.c */ #line 488 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makePostfixNode(GLOBAL_DATA, (yyvsp[(1) - (2)].expressionNode).m_node, OpPlusPlus, (yylsp[(1) - (2)]).first_column, (yylsp[(1) - (2)]).last_column, (yylsp[(2) - (2)]).last_column), (yyvsp[(1) - (2)].expressionNode).m_features | AssignFeature, (yyvsp[(1) - (2)].expressionNode).m_numConstants); ;} break; case 65: /* Line 1455 of yacc.c */ #line 489 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makePostfixNode(GLOBAL_DATA, (yyvsp[(1) - (2)].expressionNode).m_node, OpMinusMinus, (yylsp[(1) - (2)]).first_column, (yylsp[(1) - (2)]).last_column, (yylsp[(2) - (2)]).last_column), (yyvsp[(1) - (2)].expressionNode).m_features | AssignFeature, (yyvsp[(1) - (2)].expressionNode).m_numConstants); ;} break; case 67: /* Line 1455 of yacc.c */ #line 494 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makePostfixNode(GLOBAL_DATA, (yyvsp[(1) - (2)].expressionNode).m_node, OpPlusPlus, (yylsp[(1) - (2)]).first_column, (yylsp[(1) - (2)]).last_column, (yylsp[(2) - (2)]).last_column), (yyvsp[(1) - (2)].expressionNode).m_features | AssignFeature, (yyvsp[(1) - (2)].expressionNode).m_numConstants); ;} break; case 68: /* Line 1455 of yacc.c */ #line 495 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makePostfixNode(GLOBAL_DATA, (yyvsp[(1) - (2)].expressionNode).m_node, OpMinusMinus, (yylsp[(1) - (2)]).first_column, (yylsp[(1) - (2)]).last_column, (yylsp[(2) - (2)]).last_column), (yyvsp[(1) - (2)].expressionNode).m_features | AssignFeature, (yyvsp[(1) - (2)].expressionNode).m_numConstants); ;} break; case 69: /* Line 1455 of yacc.c */ #line 499 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeDeleteNode(GLOBAL_DATA, (yyvsp[(2) - (2)].expressionNode).m_node, (yylsp[(1) - (2)]).first_column, (yylsp[(2) - (2)]).last_column, (yylsp[(2) - (2)]).last_column), (yyvsp[(2) - (2)].expressionNode).m_features, (yyvsp[(2) - (2)].expressionNode).m_numConstants); ;} break; case 70: /* Line 1455 of yacc.c */ #line 500 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new VoidNode(GLOBAL_DATA, (yyvsp[(2) - (2)].expressionNode).m_node), (yyvsp[(2) - (2)].expressionNode).m_features, (yyvsp[(2) - (2)].expressionNode).m_numConstants + 1); ;} break; case 71: /* Line 1455 of yacc.c */ #line 501 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeTypeOfNode(GLOBAL_DATA, (yyvsp[(2) - (2)].expressionNode).m_node), (yyvsp[(2) - (2)].expressionNode).m_features, (yyvsp[(2) - (2)].expressionNode).m_numConstants); ;} break; case 72: /* Line 1455 of yacc.c */ #line 502 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makePrefixNode(GLOBAL_DATA, (yyvsp[(2) - (2)].expressionNode).m_node, OpPlusPlus, (yylsp[(1) - (2)]).first_column, (yylsp[(2) - (2)]).first_column + 1, (yylsp[(2) - (2)]).last_column), (yyvsp[(2) - (2)].expressionNode).m_features | AssignFeature, (yyvsp[(2) - (2)].expressionNode).m_numConstants); ;} break; case 73: /* Line 1455 of yacc.c */ #line 503 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makePrefixNode(GLOBAL_DATA, (yyvsp[(2) - (2)].expressionNode).m_node, OpPlusPlus, (yylsp[(1) - (2)]).first_column, (yylsp[(2) - (2)]).first_column + 1, (yylsp[(2) - (2)]).last_column), (yyvsp[(2) - (2)].expressionNode).m_features | AssignFeature, (yyvsp[(2) - (2)].expressionNode).m_numConstants); ;} break; case 74: /* Line 1455 of yacc.c */ #line 504 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makePrefixNode(GLOBAL_DATA, (yyvsp[(2) - (2)].expressionNode).m_node, OpMinusMinus, (yylsp[(1) - (2)]).first_column, (yylsp[(2) - (2)]).first_column + 1, (yylsp[(2) - (2)]).last_column), (yyvsp[(2) - (2)].expressionNode).m_features | AssignFeature, (yyvsp[(2) - (2)].expressionNode).m_numConstants); ;} break; case 75: /* Line 1455 of yacc.c */ #line 505 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makePrefixNode(GLOBAL_DATA, (yyvsp[(2) - (2)].expressionNode).m_node, OpMinusMinus, (yylsp[(1) - (2)]).first_column, (yylsp[(2) - (2)]).first_column + 1, (yylsp[(2) - (2)]).last_column), (yyvsp[(2) - (2)].expressionNode).m_features | AssignFeature, (yyvsp[(2) - (2)].expressionNode).m_numConstants); ;} break; case 76: /* Line 1455 of yacc.c */ #line 506 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new UnaryPlusNode(GLOBAL_DATA, (yyvsp[(2) - (2)].expressionNode).m_node), (yyvsp[(2) - (2)].expressionNode).m_features, (yyvsp[(2) - (2)].expressionNode).m_numConstants); ;} break; case 77: /* Line 1455 of yacc.c */ #line 507 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeNegateNode(GLOBAL_DATA, (yyvsp[(2) - (2)].expressionNode).m_node), (yyvsp[(2) - (2)].expressionNode).m_features, (yyvsp[(2) - (2)].expressionNode).m_numConstants); ;} break; case 78: /* Line 1455 of yacc.c */ #line 508 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeBitwiseNotNode(GLOBAL_DATA, (yyvsp[(2) - (2)].expressionNode).m_node), (yyvsp[(2) - (2)].expressionNode).m_features, (yyvsp[(2) - (2)].expressionNode).m_numConstants); ;} break; case 79: /* Line 1455 of yacc.c */ #line 509 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new LogicalNotNode(GLOBAL_DATA, (yyvsp[(2) - (2)].expressionNode).m_node), (yyvsp[(2) - (2)].expressionNode).m_features, (yyvsp[(2) - (2)].expressionNode).m_numConstants); ;} break; case 85: /* Line 1455 of yacc.c */ #line 523 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeMultNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 86: /* Line 1455 of yacc.c */ #line 524 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeDivNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 87: /* Line 1455 of yacc.c */ #line 525 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new ModNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 89: /* Line 1455 of yacc.c */ #line 531 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeMultNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 90: /* Line 1455 of yacc.c */ #line 533 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeDivNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 91: /* Line 1455 of yacc.c */ #line 535 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new ModNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 93: /* Line 1455 of yacc.c */ #line 540 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeAddNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 94: /* Line 1455 of yacc.c */ #line 541 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeSubNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 96: /* Line 1455 of yacc.c */ #line 547 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeAddNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 97: /* Line 1455 of yacc.c */ #line 549 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeSubNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 99: /* Line 1455 of yacc.c */ #line 554 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeLeftShiftNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 100: /* Line 1455 of yacc.c */ #line 555 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeRightShiftNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 101: /* Line 1455 of yacc.c */ #line 556 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new UnsignedRightShiftNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 103: /* Line 1455 of yacc.c */ #line 561 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeLeftShiftNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 104: /* Line 1455 of yacc.c */ #line 562 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeRightShiftNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 105: /* Line 1455 of yacc.c */ #line 563 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new UnsignedRightShiftNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 107: /* Line 1455 of yacc.c */ #line 568 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new LessNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 108: /* Line 1455 of yacc.c */ #line 569 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new GreaterNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 109: /* Line 1455 of yacc.c */ #line 570 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new LessEqNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 110: /* Line 1455 of yacc.c */ #line 571 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new GreaterEqNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 111: /* Line 1455 of yacc.c */ #line 572 "../../JavaScriptCore/parser/Grammar.y" { InstanceOfNode* node = new InstanceOfNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(3) - (3)]).first_column, (yylsp[(3) - (3)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 112: /* Line 1455 of yacc.c */ #line 575 "../../JavaScriptCore/parser/Grammar.y" { InNode* node = new InNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(3) - (3)]).first_column, (yylsp[(3) - (3)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 114: /* Line 1455 of yacc.c */ #line 582 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new LessNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 115: /* Line 1455 of yacc.c */ #line 583 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new GreaterNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 116: /* Line 1455 of yacc.c */ #line 584 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new LessEqNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 117: /* Line 1455 of yacc.c */ #line 585 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new GreaterEqNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 118: /* Line 1455 of yacc.c */ #line 587 "../../JavaScriptCore/parser/Grammar.y" { InstanceOfNode* node = new InstanceOfNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(3) - (3)]).first_column, (yylsp[(3) - (3)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 120: /* Line 1455 of yacc.c */ #line 594 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new LessNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 121: /* Line 1455 of yacc.c */ #line 595 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new GreaterNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 122: /* Line 1455 of yacc.c */ #line 596 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new LessEqNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 123: /* Line 1455 of yacc.c */ #line 597 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new GreaterEqNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 124: /* Line 1455 of yacc.c */ #line 599 "../../JavaScriptCore/parser/Grammar.y" { InstanceOfNode* node = new InstanceOfNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(3) - (3)]).first_column, (yylsp[(3) - (3)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 125: /* Line 1455 of yacc.c */ #line 603 "../../JavaScriptCore/parser/Grammar.y" { InNode* node = new InNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(3) - (3)]).first_column, (yylsp[(3) - (3)]).last_column); (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(node, (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 127: /* Line 1455 of yacc.c */ #line 610 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new EqualNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 128: /* Line 1455 of yacc.c */ #line 611 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new NotEqualNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 129: /* Line 1455 of yacc.c */ #line 612 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new StrictEqualNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 130: /* Line 1455 of yacc.c */ #line 613 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new NotStrictEqualNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 132: /* Line 1455 of yacc.c */ #line 619 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new EqualNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 133: /* Line 1455 of yacc.c */ #line 621 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new NotEqualNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 134: /* Line 1455 of yacc.c */ #line 623 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new StrictEqualNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 135: /* Line 1455 of yacc.c */ #line 625 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new NotStrictEqualNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 137: /* Line 1455 of yacc.c */ #line 631 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new EqualNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 138: /* Line 1455 of yacc.c */ #line 632 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new NotEqualNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 139: /* Line 1455 of yacc.c */ #line 634 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new StrictEqualNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 140: /* Line 1455 of yacc.c */ #line 636 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new NotStrictEqualNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 142: /* Line 1455 of yacc.c */ #line 641 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new BitAndNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 144: /* Line 1455 of yacc.c */ #line 647 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new BitAndNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 146: /* Line 1455 of yacc.c */ #line 652 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new BitAndNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 148: /* Line 1455 of yacc.c */ #line 657 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new BitXOrNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 150: /* Line 1455 of yacc.c */ #line 663 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new BitXOrNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 152: /* Line 1455 of yacc.c */ #line 669 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new BitXOrNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 154: /* Line 1455 of yacc.c */ #line 674 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new BitOrNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 156: /* Line 1455 of yacc.c */ #line 680 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new BitOrNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 158: /* Line 1455 of yacc.c */ #line 686 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new BitOrNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 160: /* Line 1455 of yacc.c */ #line 691 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new LogicalOpNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, OpLogicalAnd), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 162: /* Line 1455 of yacc.c */ #line 697 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new LogicalOpNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, OpLogicalAnd), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 164: /* Line 1455 of yacc.c */ #line 703 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new LogicalOpNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, OpLogicalAnd), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 166: /* Line 1455 of yacc.c */ #line 708 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new LogicalOpNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, OpLogicalOr), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 168: /* Line 1455 of yacc.c */ #line 714 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new LogicalOpNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, OpLogicalOr), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 170: /* Line 1455 of yacc.c */ #line 719 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new LogicalOpNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node, OpLogicalOr), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 172: /* Line 1455 of yacc.c */ #line 725 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new ConditionalNode(GLOBAL_DATA, (yyvsp[(1) - (5)].expressionNode).m_node, (yyvsp[(3) - (5)].expressionNode).m_node, (yyvsp[(5) - (5)].expressionNode).m_node), (yyvsp[(1) - (5)].expressionNode).m_features | (yyvsp[(3) - (5)].expressionNode).m_features | (yyvsp[(5) - (5)].expressionNode).m_features, (yyvsp[(1) - (5)].expressionNode).m_numConstants + (yyvsp[(3) - (5)].expressionNode).m_numConstants + (yyvsp[(5) - (5)].expressionNode).m_numConstants); ;} break; case 174: /* Line 1455 of yacc.c */ #line 731 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new ConditionalNode(GLOBAL_DATA, (yyvsp[(1) - (5)].expressionNode).m_node, (yyvsp[(3) - (5)].expressionNode).m_node, (yyvsp[(5) - (5)].expressionNode).m_node), (yyvsp[(1) - (5)].expressionNode).m_features | (yyvsp[(3) - (5)].expressionNode).m_features | (yyvsp[(5) - (5)].expressionNode).m_features, (yyvsp[(1) - (5)].expressionNode).m_numConstants + (yyvsp[(3) - (5)].expressionNode).m_numConstants + (yyvsp[(5) - (5)].expressionNode).m_numConstants); ;} break; case 176: /* Line 1455 of yacc.c */ #line 737 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new ConditionalNode(GLOBAL_DATA, (yyvsp[(1) - (5)].expressionNode).m_node, (yyvsp[(3) - (5)].expressionNode).m_node, (yyvsp[(5) - (5)].expressionNode).m_node), (yyvsp[(1) - (5)].expressionNode).m_features | (yyvsp[(3) - (5)].expressionNode).m_features | (yyvsp[(5) - (5)].expressionNode).m_features, (yyvsp[(1) - (5)].expressionNode).m_numConstants + (yyvsp[(3) - (5)].expressionNode).m_numConstants + (yyvsp[(5) - (5)].expressionNode).m_numConstants); ;} break; case 178: /* Line 1455 of yacc.c */ #line 743 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeAssignNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(2) - (3)].op), (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(1) - (3)].expressionNode).m_features & AssignFeature, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature, (yylsp[(1) - (3)]).first_column, (yylsp[(2) - (3)]).first_column + 1, (yylsp[(3) - (3)]).last_column), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features | AssignFeature, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 180: /* Line 1455 of yacc.c */ #line 751 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeAssignNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(2) - (3)].op), (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(1) - (3)].expressionNode).m_features & AssignFeature, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature, (yylsp[(1) - (3)]).first_column, (yylsp[(2) - (3)]).first_column + 1, (yylsp[(3) - (3)]).last_column), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features | AssignFeature, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 182: /* Line 1455 of yacc.c */ #line 759 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(makeAssignNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(2) - (3)].op), (yyvsp[(3) - (3)].expressionNode).m_node, (yyvsp[(1) - (3)].expressionNode).m_features & AssignFeature, (yyvsp[(3) - (3)].expressionNode).m_features & AssignFeature, (yylsp[(1) - (3)]).first_column, (yylsp[(2) - (3)]).first_column + 1, (yylsp[(3) - (3)]).last_column), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features | AssignFeature, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 183: /* Line 1455 of yacc.c */ #line 765 "../../JavaScriptCore/parser/Grammar.y" { (yyval.op) = OpEqual; ;} break; case 184: /* Line 1455 of yacc.c */ #line 766 "../../JavaScriptCore/parser/Grammar.y" { (yyval.op) = OpPlusEq; ;} break; case 185: /* Line 1455 of yacc.c */ #line 767 "../../JavaScriptCore/parser/Grammar.y" { (yyval.op) = OpMinusEq; ;} break; case 186: /* Line 1455 of yacc.c */ #line 768 "../../JavaScriptCore/parser/Grammar.y" { (yyval.op) = OpMultEq; ;} break; case 187: /* Line 1455 of yacc.c */ #line 769 "../../JavaScriptCore/parser/Grammar.y" { (yyval.op) = OpDivEq; ;} break; case 188: /* Line 1455 of yacc.c */ #line 770 "../../JavaScriptCore/parser/Grammar.y" { (yyval.op) = OpLShift; ;} break; case 189: /* Line 1455 of yacc.c */ #line 771 "../../JavaScriptCore/parser/Grammar.y" { (yyval.op) = OpRShift; ;} break; case 190: /* Line 1455 of yacc.c */ #line 772 "../../JavaScriptCore/parser/Grammar.y" { (yyval.op) = OpURShift; ;} break; case 191: /* Line 1455 of yacc.c */ #line 773 "../../JavaScriptCore/parser/Grammar.y" { (yyval.op) = OpAndEq; ;} break; case 192: /* Line 1455 of yacc.c */ #line 774 "../../JavaScriptCore/parser/Grammar.y" { (yyval.op) = OpXOrEq; ;} break; case 193: /* Line 1455 of yacc.c */ #line 775 "../../JavaScriptCore/parser/Grammar.y" { (yyval.op) = OpOrEq; ;} break; case 194: /* Line 1455 of yacc.c */ #line 776 "../../JavaScriptCore/parser/Grammar.y" { (yyval.op) = OpModEq; ;} break; case 196: /* Line 1455 of yacc.c */ #line 781 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new CommaNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 198: /* Line 1455 of yacc.c */ #line 786 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new CommaNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 200: /* Line 1455 of yacc.c */ #line 791 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(new CommaNode(GLOBAL_DATA, (yyvsp[(1) - (3)].expressionNode).m_node, (yyvsp[(3) - (3)].expressionNode).m_node), (yyvsp[(1) - (3)].expressionNode).m_features | (yyvsp[(3) - (3)].expressionNode).m_features, (yyvsp[(1) - (3)].expressionNode).m_numConstants + (yyvsp[(3) - (3)].expressionNode).m_numConstants); ;} break; case 218: /* Line 1455 of yacc.c */ #line 815 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new BlockNode(GLOBAL_DATA, 0), 0, 0, 0, 0); DBG((yyval.statementNode).m_node, (yylsp[(1) - (2)]), (yylsp[(2) - (2)])); ;} break; case 219: /* Line 1455 of yacc.c */ #line 817 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new BlockNode(GLOBAL_DATA, (yyvsp[(2) - (3)].sourceElements).m_node), (yyvsp[(2) - (3)].sourceElements).m_varDeclarations, (yyvsp[(2) - (3)].sourceElements).m_funcDeclarations, (yyvsp[(2) - (3)].sourceElements).m_features, (yyvsp[(2) - (3)].sourceElements).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (3)]), (yylsp[(3) - (3)])); ;} break; case 220: /* Line 1455 of yacc.c */ #line 822 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(makeVarStatementNode(GLOBAL_DATA, (yyvsp[(2) - (3)].varDeclList).m_node), (yyvsp[(2) - (3)].varDeclList).m_varDeclarations, (yyvsp[(2) - (3)].varDeclList).m_funcDeclarations, (yyvsp[(2) - (3)].varDeclList).m_features, (yyvsp[(2) - (3)].varDeclList).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (3)]), (yylsp[(3) - (3)])); ;} break; case 221: /* Line 1455 of yacc.c */ #line 824 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(makeVarStatementNode(GLOBAL_DATA, (yyvsp[(2) - (3)].varDeclList).m_node), (yyvsp[(2) - (3)].varDeclList).m_varDeclarations, (yyvsp[(2) - (3)].varDeclList).m_funcDeclarations, (yyvsp[(2) - (3)].varDeclList).m_features, (yyvsp[(2) - (3)].varDeclList).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (3)]), (yylsp[(2) - (3)])); AUTO_SEMICOLON; ;} break; case 222: /* Line 1455 of yacc.c */ #line 830 "../../JavaScriptCore/parser/Grammar.y" { (yyval.varDeclList).m_node = 0; (yyval.varDeclList).m_varDeclarations = new ParserRefCountedData<DeclarationStacks::VarStack>(GLOBAL_DATA); appendToVarDeclarationList(GLOBAL_DATA, (yyval.varDeclList).m_varDeclarations, *(yyvsp[(1) - (1)].ident), 0); (yyval.varDeclList).m_funcDeclarations = 0; (yyval.varDeclList).m_features = (*(yyvsp[(1) - (1)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0; (yyval.varDeclList).m_numConstants = 0; ;} break; case 223: /* Line 1455 of yacc.c */ #line 837 "../../JavaScriptCore/parser/Grammar.y" { AssignResolveNode* node = new AssignResolveNode(GLOBAL_DATA, *(yyvsp[(1) - (2)].ident), (yyvsp[(2) - (2)].expressionNode).m_node, (yyvsp[(2) - (2)].expressionNode).m_features & AssignFeature); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (2)]).first_column, (yylsp[(2) - (2)]).first_column + 1, (yylsp[(2) - (2)]).last_column); (yyval.varDeclList).m_node = node; (yyval.varDeclList).m_varDeclarations = new ParserRefCountedData<DeclarationStacks::VarStack>(GLOBAL_DATA); appendToVarDeclarationList(GLOBAL_DATA, (yyval.varDeclList).m_varDeclarations, *(yyvsp[(1) - (2)].ident), DeclarationStacks::HasInitializer); (yyval.varDeclList).m_funcDeclarations = 0; (yyval.varDeclList).m_features = ((*(yyvsp[(1) - (2)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0) | (yyvsp[(2) - (2)].expressionNode).m_features; (yyval.varDeclList).m_numConstants = (yyvsp[(2) - (2)].expressionNode).m_numConstants; ;} break; case 224: /* Line 1455 of yacc.c */ #line 847 "../../JavaScriptCore/parser/Grammar.y" { (yyval.varDeclList).m_node = (yyvsp[(1) - (3)].varDeclList).m_node; (yyval.varDeclList).m_varDeclarations = (yyvsp[(1) - (3)].varDeclList).m_varDeclarations; appendToVarDeclarationList(GLOBAL_DATA, (yyval.varDeclList).m_varDeclarations, *(yyvsp[(3) - (3)].ident), 0); (yyval.varDeclList).m_funcDeclarations = 0; (yyval.varDeclList).m_features = (yyvsp[(1) - (3)].varDeclList).m_features | ((*(yyvsp[(3) - (3)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0); (yyval.varDeclList).m_numConstants = (yyvsp[(1) - (3)].varDeclList).m_numConstants; ;} break; case 225: /* Line 1455 of yacc.c */ #line 855 "../../JavaScriptCore/parser/Grammar.y" { AssignResolveNode* node = new AssignResolveNode(GLOBAL_DATA, *(yyvsp[(3) - (4)].ident), (yyvsp[(4) - (4)].expressionNode).m_node, (yyvsp[(4) - (4)].expressionNode).m_features & AssignFeature); SET_EXCEPTION_LOCATION(node, (yylsp[(3) - (4)]).first_column, (yylsp[(4) - (4)]).first_column + 1, (yylsp[(4) - (4)]).last_column); (yyval.varDeclList).m_node = combineVarInitializers(GLOBAL_DATA, (yyvsp[(1) - (4)].varDeclList).m_node, node); (yyval.varDeclList).m_varDeclarations = (yyvsp[(1) - (4)].varDeclList).m_varDeclarations; appendToVarDeclarationList(GLOBAL_DATA, (yyval.varDeclList).m_varDeclarations, *(yyvsp[(3) - (4)].ident), DeclarationStacks::HasInitializer); (yyval.varDeclList).m_funcDeclarations = 0; (yyval.varDeclList).m_features = (yyvsp[(1) - (4)].varDeclList).m_features | ((*(yyvsp[(3) - (4)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0) | (yyvsp[(4) - (4)].expressionNode).m_features; (yyval.varDeclList).m_numConstants = (yyvsp[(1) - (4)].varDeclList).m_numConstants + (yyvsp[(4) - (4)].expressionNode).m_numConstants; ;} break; case 226: /* Line 1455 of yacc.c */ #line 867 "../../JavaScriptCore/parser/Grammar.y" { (yyval.varDeclList).m_node = 0; (yyval.varDeclList).m_varDeclarations = new ParserRefCountedData<DeclarationStacks::VarStack>(GLOBAL_DATA); appendToVarDeclarationList(GLOBAL_DATA, (yyval.varDeclList).m_varDeclarations, *(yyvsp[(1) - (1)].ident), 0); (yyval.varDeclList).m_funcDeclarations = 0; (yyval.varDeclList).m_features = (*(yyvsp[(1) - (1)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0; (yyval.varDeclList).m_numConstants = 0; ;} break; case 227: /* Line 1455 of yacc.c */ #line 874 "../../JavaScriptCore/parser/Grammar.y" { AssignResolveNode* node = new AssignResolveNode(GLOBAL_DATA, *(yyvsp[(1) - (2)].ident), (yyvsp[(2) - (2)].expressionNode).m_node, (yyvsp[(2) - (2)].expressionNode).m_features & AssignFeature); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (2)]).first_column, (yylsp[(2) - (2)]).first_column + 1, (yylsp[(2) - (2)]).last_column); (yyval.varDeclList).m_node = node; (yyval.varDeclList).m_varDeclarations = new ParserRefCountedData<DeclarationStacks::VarStack>(GLOBAL_DATA); appendToVarDeclarationList(GLOBAL_DATA, (yyval.varDeclList).m_varDeclarations, *(yyvsp[(1) - (2)].ident), DeclarationStacks::HasInitializer); (yyval.varDeclList).m_funcDeclarations = 0; (yyval.varDeclList).m_features = ((*(yyvsp[(1) - (2)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0) | (yyvsp[(2) - (2)].expressionNode).m_features; (yyval.varDeclList).m_numConstants = (yyvsp[(2) - (2)].expressionNode).m_numConstants; ;} break; case 228: /* Line 1455 of yacc.c */ #line 884 "../../JavaScriptCore/parser/Grammar.y" { (yyval.varDeclList).m_node = (yyvsp[(1) - (3)].varDeclList).m_node; (yyval.varDeclList).m_varDeclarations = (yyvsp[(1) - (3)].varDeclList).m_varDeclarations; appendToVarDeclarationList(GLOBAL_DATA, (yyval.varDeclList).m_varDeclarations, *(yyvsp[(3) - (3)].ident), 0); (yyval.varDeclList).m_funcDeclarations = 0; (yyval.varDeclList).m_features = (yyvsp[(1) - (3)].varDeclList).m_features | ((*(yyvsp[(3) - (3)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0); (yyval.varDeclList).m_numConstants = (yyvsp[(1) - (3)].varDeclList).m_numConstants; ;} break; case 229: /* Line 1455 of yacc.c */ #line 892 "../../JavaScriptCore/parser/Grammar.y" { AssignResolveNode* node = new AssignResolveNode(GLOBAL_DATA, *(yyvsp[(3) - (4)].ident), (yyvsp[(4) - (4)].expressionNode).m_node, (yyvsp[(4) - (4)].expressionNode).m_features & AssignFeature); SET_EXCEPTION_LOCATION(node, (yylsp[(3) - (4)]).first_column, (yylsp[(4) - (4)]).first_column + 1, (yylsp[(4) - (4)]).last_column); (yyval.varDeclList).m_node = combineVarInitializers(GLOBAL_DATA, (yyvsp[(1) - (4)].varDeclList).m_node, node); (yyval.varDeclList).m_varDeclarations = (yyvsp[(1) - (4)].varDeclList).m_varDeclarations; appendToVarDeclarationList(GLOBAL_DATA, (yyval.varDeclList).m_varDeclarations, *(yyvsp[(3) - (4)].ident), DeclarationStacks::HasInitializer); (yyval.varDeclList).m_funcDeclarations = 0; (yyval.varDeclList).m_features = (yyvsp[(1) - (4)].varDeclList).m_features | ((*(yyvsp[(3) - (4)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0) | (yyvsp[(4) - (4)].expressionNode).m_features; (yyval.varDeclList).m_numConstants = (yyvsp[(1) - (4)].varDeclList).m_numConstants + (yyvsp[(4) - (4)].expressionNode).m_numConstants; ;} break; case 230: /* Line 1455 of yacc.c */ #line 904 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new ConstStatementNode(GLOBAL_DATA, (yyvsp[(2) - (3)].constDeclList).m_node.head), (yyvsp[(2) - (3)].constDeclList).m_varDeclarations, (yyvsp[(2) - (3)].constDeclList).m_funcDeclarations, (yyvsp[(2) - (3)].constDeclList).m_features, (yyvsp[(2) - (3)].constDeclList).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (3)]), (yylsp[(3) - (3)])); ;} break; case 231: /* Line 1455 of yacc.c */ #line 907 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new ConstStatementNode(GLOBAL_DATA, (yyvsp[(2) - (3)].constDeclList).m_node.head), (yyvsp[(2) - (3)].constDeclList).m_varDeclarations, (yyvsp[(2) - (3)].constDeclList).m_funcDeclarations, (yyvsp[(2) - (3)].constDeclList).m_features, (yyvsp[(2) - (3)].constDeclList).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (3)]), (yylsp[(2) - (3)])); AUTO_SEMICOLON; ;} break; case 232: /* Line 1455 of yacc.c */ #line 912 "../../JavaScriptCore/parser/Grammar.y" { (yyval.constDeclList).m_node.head = (yyvsp[(1) - (1)].constDeclNode).m_node; (yyval.constDeclList).m_node.tail = (yyval.constDeclList).m_node.head; (yyval.constDeclList).m_varDeclarations = new ParserRefCountedData<DeclarationStacks::VarStack>(GLOBAL_DATA); appendToVarDeclarationList(GLOBAL_DATA, (yyval.constDeclList).m_varDeclarations, (yyvsp[(1) - (1)].constDeclNode).m_node); (yyval.constDeclList).m_funcDeclarations = 0; (yyval.constDeclList).m_features = (yyvsp[(1) - (1)].constDeclNode).m_features; (yyval.constDeclList).m_numConstants = (yyvsp[(1) - (1)].constDeclNode).m_numConstants; ;} break; case 233: /* Line 1455 of yacc.c */ #line 921 "../../JavaScriptCore/parser/Grammar.y" { (yyval.constDeclList).m_node.head = (yyvsp[(1) - (3)].constDeclList).m_node.head; (yyvsp[(1) - (3)].constDeclList).m_node.tail->m_next = (yyvsp[(3) - (3)].constDeclNode).m_node; (yyval.constDeclList).m_node.tail = (yyvsp[(3) - (3)].constDeclNode).m_node; (yyval.constDeclList).m_varDeclarations = (yyvsp[(1) - (3)].constDeclList).m_varDeclarations; appendToVarDeclarationList(GLOBAL_DATA, (yyval.constDeclList).m_varDeclarations, (yyvsp[(3) - (3)].constDeclNode).m_node); (yyval.constDeclList).m_funcDeclarations = 0; (yyval.constDeclList).m_features = (yyvsp[(1) - (3)].constDeclList).m_features | (yyvsp[(3) - (3)].constDeclNode).m_features; (yyval.constDeclList).m_numConstants = (yyvsp[(1) - (3)].constDeclList).m_numConstants + (yyvsp[(3) - (3)].constDeclNode).m_numConstants; ;} break; case 234: /* Line 1455 of yacc.c */ #line 932 "../../JavaScriptCore/parser/Grammar.y" { (yyval.constDeclNode) = createNodeInfo<ConstDeclNode*>(new ConstDeclNode(GLOBAL_DATA, *(yyvsp[(1) - (1)].ident), 0), (*(yyvsp[(1) - (1)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0, 0); ;} break; case 235: /* Line 1455 of yacc.c */ #line 933 "../../JavaScriptCore/parser/Grammar.y" { (yyval.constDeclNode) = createNodeInfo<ConstDeclNode*>(new ConstDeclNode(GLOBAL_DATA, *(yyvsp[(1) - (2)].ident), (yyvsp[(2) - (2)].expressionNode).m_node), ((*(yyvsp[(1) - (2)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0) | (yyvsp[(2) - (2)].expressionNode).m_features, (yyvsp[(2) - (2)].expressionNode).m_numConstants); ;} break; case 236: /* Line 1455 of yacc.c */ #line 937 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = (yyvsp[(2) - (2)].expressionNode); ;} break; case 237: /* Line 1455 of yacc.c */ #line 941 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = (yyvsp[(2) - (2)].expressionNode); ;} break; case 238: /* Line 1455 of yacc.c */ #line 945 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new EmptyStatementNode(GLOBAL_DATA), 0, 0, 0, 0); ;} break; case 239: /* Line 1455 of yacc.c */ #line 949 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new ExprStatementNode(GLOBAL_DATA, (yyvsp[(1) - (2)].expressionNode).m_node), 0, 0, (yyvsp[(1) - (2)].expressionNode).m_features, (yyvsp[(1) - (2)].expressionNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (2)]), (yylsp[(2) - (2)])); ;} break; case 240: /* Line 1455 of yacc.c */ #line 951 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new ExprStatementNode(GLOBAL_DATA, (yyvsp[(1) - (2)].expressionNode).m_node), 0, 0, (yyvsp[(1) - (2)].expressionNode).m_features, (yyvsp[(1) - (2)].expressionNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (2)]), (yylsp[(1) - (2)])); AUTO_SEMICOLON; ;} break; case 241: /* Line 1455 of yacc.c */ #line 957 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new IfNode(GLOBAL_DATA, (yyvsp[(3) - (5)].expressionNode).m_node, (yyvsp[(5) - (5)].statementNode).m_node), (yyvsp[(5) - (5)].statementNode).m_varDeclarations, (yyvsp[(5) - (5)].statementNode).m_funcDeclarations, (yyvsp[(3) - (5)].expressionNode).m_features | (yyvsp[(5) - (5)].statementNode).m_features, (yyvsp[(3) - (5)].expressionNode).m_numConstants + (yyvsp[(5) - (5)].statementNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (5)]), (yylsp[(4) - (5)])); ;} break; case 242: /* Line 1455 of yacc.c */ #line 960 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new IfElseNode(GLOBAL_DATA, (yyvsp[(3) - (7)].expressionNode).m_node, (yyvsp[(5) - (7)].statementNode).m_node, (yyvsp[(7) - (7)].statementNode).m_node), mergeDeclarationLists((yyvsp[(5) - (7)].statementNode).m_varDeclarations, (yyvsp[(7) - (7)].statementNode).m_varDeclarations), mergeDeclarationLists((yyvsp[(5) - (7)].statementNode).m_funcDeclarations, (yyvsp[(7) - (7)].statementNode).m_funcDeclarations), (yyvsp[(3) - (7)].expressionNode).m_features | (yyvsp[(5) - (7)].statementNode).m_features | (yyvsp[(7) - (7)].statementNode).m_features, (yyvsp[(3) - (7)].expressionNode).m_numConstants + (yyvsp[(5) - (7)].statementNode).m_numConstants + (yyvsp[(7) - (7)].statementNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (7)]), (yylsp[(4) - (7)])); ;} break; case 243: /* Line 1455 of yacc.c */ #line 968 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new DoWhileNode(GLOBAL_DATA, (yyvsp[(2) - (7)].statementNode).m_node, (yyvsp[(5) - (7)].expressionNode).m_node), (yyvsp[(2) - (7)].statementNode).m_varDeclarations, (yyvsp[(2) - (7)].statementNode).m_funcDeclarations, (yyvsp[(2) - (7)].statementNode).m_features | (yyvsp[(5) - (7)].expressionNode).m_features, (yyvsp[(2) - (7)].statementNode).m_numConstants + (yyvsp[(5) - (7)].expressionNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (7)]), (yylsp[(3) - (7)])); ;} break; case 244: /* Line 1455 of yacc.c */ #line 970 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new DoWhileNode(GLOBAL_DATA, (yyvsp[(2) - (7)].statementNode).m_node, (yyvsp[(5) - (7)].expressionNode).m_node), (yyvsp[(2) - (7)].statementNode).m_varDeclarations, (yyvsp[(2) - (7)].statementNode).m_funcDeclarations, (yyvsp[(2) - (7)].statementNode).m_features | (yyvsp[(5) - (7)].expressionNode).m_features, (yyvsp[(2) - (7)].statementNode).m_numConstants + (yyvsp[(5) - (7)].expressionNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (7)]), (yylsp[(3) - (7)])); ;} break; case 245: /* Line 1455 of yacc.c */ #line 972 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new WhileNode(GLOBAL_DATA, (yyvsp[(3) - (5)].expressionNode).m_node, (yyvsp[(5) - (5)].statementNode).m_node), (yyvsp[(5) - (5)].statementNode).m_varDeclarations, (yyvsp[(5) - (5)].statementNode).m_funcDeclarations, (yyvsp[(3) - (5)].expressionNode).m_features | (yyvsp[(5) - (5)].statementNode).m_features, (yyvsp[(3) - (5)].expressionNode).m_numConstants + (yyvsp[(5) - (5)].statementNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (5)]), (yylsp[(4) - (5)])); ;} break; case 246: /* Line 1455 of yacc.c */ #line 975 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new ForNode(GLOBAL_DATA, (yyvsp[(3) - (9)].expressionNode).m_node, (yyvsp[(5) - (9)].expressionNode).m_node, (yyvsp[(7) - (9)].expressionNode).m_node, (yyvsp[(9) - (9)].statementNode).m_node, false), (yyvsp[(9) - (9)].statementNode).m_varDeclarations, (yyvsp[(9) - (9)].statementNode).m_funcDeclarations, (yyvsp[(3) - (9)].expressionNode).m_features | (yyvsp[(5) - (9)].expressionNode).m_features | (yyvsp[(7) - (9)].expressionNode).m_features | (yyvsp[(9) - (9)].statementNode).m_features, (yyvsp[(3) - (9)].expressionNode).m_numConstants + (yyvsp[(5) - (9)].expressionNode).m_numConstants + (yyvsp[(7) - (9)].expressionNode).m_numConstants + (yyvsp[(9) - (9)].statementNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (9)]), (yylsp[(8) - (9)])); ;} break; case 247: /* Line 1455 of yacc.c */ #line 981 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new ForNode(GLOBAL_DATA, (yyvsp[(4) - (10)].varDeclList).m_node, (yyvsp[(6) - (10)].expressionNode).m_node, (yyvsp[(8) - (10)].expressionNode).m_node, (yyvsp[(10) - (10)].statementNode).m_node, true), mergeDeclarationLists((yyvsp[(4) - (10)].varDeclList).m_varDeclarations, (yyvsp[(10) - (10)].statementNode).m_varDeclarations), mergeDeclarationLists((yyvsp[(4) - (10)].varDeclList).m_funcDeclarations, (yyvsp[(10) - (10)].statementNode).m_funcDeclarations), (yyvsp[(4) - (10)].varDeclList).m_features | (yyvsp[(6) - (10)].expressionNode).m_features | (yyvsp[(8) - (10)].expressionNode).m_features | (yyvsp[(10) - (10)].statementNode).m_features, (yyvsp[(4) - (10)].varDeclList).m_numConstants + (yyvsp[(6) - (10)].expressionNode).m_numConstants + (yyvsp[(8) - (10)].expressionNode).m_numConstants + (yyvsp[(10) - (10)].statementNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (10)]), (yylsp[(9) - (10)])); ;} break; case 248: /* Line 1455 of yacc.c */ #line 988 "../../JavaScriptCore/parser/Grammar.y" { ForInNode* node = new ForInNode(GLOBAL_DATA, (yyvsp[(3) - (7)].expressionNode).m_node, (yyvsp[(5) - (7)].expressionNode).m_node, (yyvsp[(7) - (7)].statementNode).m_node); SET_EXCEPTION_LOCATION(node, (yylsp[(3) - (7)]).first_column, (yylsp[(3) - (7)]).last_column, (yylsp[(5) - (7)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(node, (yyvsp[(7) - (7)].statementNode).m_varDeclarations, (yyvsp[(7) - (7)].statementNode).m_funcDeclarations, (yyvsp[(3) - (7)].expressionNode).m_features | (yyvsp[(5) - (7)].expressionNode).m_features | (yyvsp[(7) - (7)].statementNode).m_features, (yyvsp[(3) - (7)].expressionNode).m_numConstants + (yyvsp[(5) - (7)].expressionNode).m_numConstants + (yyvsp[(7) - (7)].statementNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (7)]), (yylsp[(6) - (7)])); ;} break; case 249: /* Line 1455 of yacc.c */ #line 997 "../../JavaScriptCore/parser/Grammar.y" { ForInNode *forIn = new ForInNode(GLOBAL_DATA, *(yyvsp[(4) - (8)].ident), 0, (yyvsp[(6) - (8)].expressionNode).m_node, (yyvsp[(8) - (8)].statementNode).m_node, (yylsp[(5) - (8)]).first_column, (yylsp[(5) - (8)]).first_column - (yylsp[(4) - (8)]).first_column, (yylsp[(6) - (8)]).last_column - (yylsp[(5) - (8)]).first_column); SET_EXCEPTION_LOCATION(forIn, (yylsp[(4) - (8)]).first_column, (yylsp[(5) - (8)]).first_column + 1, (yylsp[(6) - (8)]).last_column); appendToVarDeclarationList(GLOBAL_DATA, (yyvsp[(8) - (8)].statementNode).m_varDeclarations, *(yyvsp[(4) - (8)].ident), DeclarationStacks::HasInitializer); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(forIn, (yyvsp[(8) - (8)].statementNode).m_varDeclarations, (yyvsp[(8) - (8)].statementNode).m_funcDeclarations, ((*(yyvsp[(4) - (8)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0) | (yyvsp[(6) - (8)].expressionNode).m_features | (yyvsp[(8) - (8)].statementNode).m_features, (yyvsp[(6) - (8)].expressionNode).m_numConstants + (yyvsp[(8) - (8)].statementNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (8)]), (yylsp[(7) - (8)])); ;} break; case 250: /* Line 1455 of yacc.c */ #line 1003 "../../JavaScriptCore/parser/Grammar.y" { ForInNode *forIn = new ForInNode(GLOBAL_DATA, *(yyvsp[(4) - (9)].ident), (yyvsp[(5) - (9)].expressionNode).m_node, (yyvsp[(7) - (9)].expressionNode).m_node, (yyvsp[(9) - (9)].statementNode).m_node, (yylsp[(5) - (9)]).first_column, (yylsp[(5) - (9)]).first_column - (yylsp[(4) - (9)]).first_column, (yylsp[(5) - (9)]).last_column - (yylsp[(5) - (9)]).first_column); SET_EXCEPTION_LOCATION(forIn, (yylsp[(4) - (9)]).first_column, (yylsp[(6) - (9)]).first_column + 1, (yylsp[(7) - (9)]).last_column); appendToVarDeclarationList(GLOBAL_DATA, (yyvsp[(9) - (9)].statementNode).m_varDeclarations, *(yyvsp[(4) - (9)].ident), DeclarationStacks::HasInitializer); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(forIn, (yyvsp[(9) - (9)].statementNode).m_varDeclarations, (yyvsp[(9) - (9)].statementNode).m_funcDeclarations, ((*(yyvsp[(4) - (9)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0) | (yyvsp[(5) - (9)].expressionNode).m_features | (yyvsp[(7) - (9)].expressionNode).m_features | (yyvsp[(9) - (9)].statementNode).m_features, (yyvsp[(5) - (9)].expressionNode).m_numConstants + (yyvsp[(7) - (9)].expressionNode).m_numConstants + (yyvsp[(9) - (9)].statementNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (9)]), (yylsp[(8) - (9)])); ;} break; case 251: /* Line 1455 of yacc.c */ #line 1013 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(0, 0, 0); ;} break; case 253: /* Line 1455 of yacc.c */ #line 1018 "../../JavaScriptCore/parser/Grammar.y" { (yyval.expressionNode) = createNodeInfo<ExpressionNode*>(0, 0, 0); ;} break; case 255: /* Line 1455 of yacc.c */ #line 1023 "../../JavaScriptCore/parser/Grammar.y" { ContinueNode* node = new ContinueNode(GLOBAL_DATA); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (2)]).first_column, (yylsp[(1) - (2)]).last_column, (yylsp[(1) - (2)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(node, 0, 0, 0, 0); DBG((yyval.statementNode).m_node, (yylsp[(1) - (2)]), (yylsp[(2) - (2)])); ;} break; case 256: /* Line 1455 of yacc.c */ #line 1027 "../../JavaScriptCore/parser/Grammar.y" { ContinueNode* node = new ContinueNode(GLOBAL_DATA); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (2)]).first_column, (yylsp[(1) - (2)]).last_column, (yylsp[(1) - (2)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(node, 0, 0, 0, 0); DBG((yyval.statementNode).m_node, (yylsp[(1) - (2)]), (yylsp[(1) - (2)])); AUTO_SEMICOLON; ;} break; case 257: /* Line 1455 of yacc.c */ #line 1031 "../../JavaScriptCore/parser/Grammar.y" { ContinueNode* node = new ContinueNode(GLOBAL_DATA, *(yyvsp[(2) - (3)].ident)); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(2) - (3)]).last_column, (yylsp[(2) - (3)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(node, 0, 0, 0, 0); DBG((yyval.statementNode).m_node, (yylsp[(1) - (3)]), (yylsp[(3) - (3)])); ;} break; case 258: /* Line 1455 of yacc.c */ #line 1035 "../../JavaScriptCore/parser/Grammar.y" { ContinueNode* node = new ContinueNode(GLOBAL_DATA, *(yyvsp[(2) - (3)].ident)); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(2) - (3)]).last_column, (yylsp[(2) - (3)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(node, 0, 0, 0, 0); DBG((yyval.statementNode).m_node, (yylsp[(1) - (3)]), (yylsp[(2) - (3)])); AUTO_SEMICOLON; ;} break; case 259: /* Line 1455 of yacc.c */ #line 1042 "../../JavaScriptCore/parser/Grammar.y" { BreakNode* node = new BreakNode(GLOBAL_DATA); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (2)]).first_column, (yylsp[(1) - (2)]).last_column, (yylsp[(1) - (2)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(node, 0, 0, 0, 0); DBG((yyval.statementNode).m_node, (yylsp[(1) - (2)]), (yylsp[(2) - (2)])); ;} break; case 260: /* Line 1455 of yacc.c */ #line 1045 "../../JavaScriptCore/parser/Grammar.y" { BreakNode* node = new BreakNode(GLOBAL_DATA); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (2)]).first_column, (yylsp[(1) - (2)]).last_column, (yylsp[(1) - (2)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new BreakNode(GLOBAL_DATA), 0, 0, 0, 0); DBG((yyval.statementNode).m_node, (yylsp[(1) - (2)]), (yylsp[(1) - (2)])); AUTO_SEMICOLON; ;} break; case 261: /* Line 1455 of yacc.c */ #line 1048 "../../JavaScriptCore/parser/Grammar.y" { BreakNode* node = new BreakNode(GLOBAL_DATA, *(yyvsp[(2) - (3)].ident)); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(2) - (3)]).last_column, (yylsp[(2) - (3)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(node, 0, 0, 0, 0); DBG((yyval.statementNode).m_node, (yylsp[(1) - (3)]), (yylsp[(3) - (3)])); ;} break; case 262: /* Line 1455 of yacc.c */ #line 1051 "../../JavaScriptCore/parser/Grammar.y" { BreakNode* node = new BreakNode(GLOBAL_DATA, *(yyvsp[(2) - (3)].ident)); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(2) - (3)]).last_column, (yylsp[(2) - (3)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new BreakNode(GLOBAL_DATA, *(yyvsp[(2) - (3)].ident)), 0, 0, 0, 0); DBG((yyval.statementNode).m_node, (yylsp[(1) - (3)]), (yylsp[(2) - (3)])); AUTO_SEMICOLON; ;} break; case 263: /* Line 1455 of yacc.c */ #line 1057 "../../JavaScriptCore/parser/Grammar.y" { ReturnNode* node = new ReturnNode(GLOBAL_DATA, 0); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (2)]).first_column, (yylsp[(1) - (2)]).last_column, (yylsp[(1) - (2)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(node, 0, 0, 0, 0); DBG((yyval.statementNode).m_node, (yylsp[(1) - (2)]), (yylsp[(2) - (2)])); ;} break; case 264: /* Line 1455 of yacc.c */ #line 1060 "../../JavaScriptCore/parser/Grammar.y" { ReturnNode* node = new ReturnNode(GLOBAL_DATA, 0); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (2)]).first_column, (yylsp[(1) - (2)]).last_column, (yylsp[(1) - (2)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(node, 0, 0, 0, 0); DBG((yyval.statementNode).m_node, (yylsp[(1) - (2)]), (yylsp[(1) - (2)])); AUTO_SEMICOLON; ;} break; case 265: /* Line 1455 of yacc.c */ #line 1063 "../../JavaScriptCore/parser/Grammar.y" { ReturnNode* node = new ReturnNode(GLOBAL_DATA, (yyvsp[(2) - (3)].expressionNode).m_node); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(2) - (3)]).last_column, (yylsp[(2) - (3)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(node, 0, 0, (yyvsp[(2) - (3)].expressionNode).m_features, (yyvsp[(2) - (3)].expressionNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (3)]), (yylsp[(3) - (3)])); ;} break; case 266: /* Line 1455 of yacc.c */ #line 1066 "../../JavaScriptCore/parser/Grammar.y" { ReturnNode* node = new ReturnNode(GLOBAL_DATA, (yyvsp[(2) - (3)].expressionNode).m_node); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(2) - (3)]).last_column, (yylsp[(2) - (3)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(node, 0, 0, (yyvsp[(2) - (3)].expressionNode).m_features, (yyvsp[(2) - (3)].expressionNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (3)]), (yylsp[(2) - (3)])); AUTO_SEMICOLON; ;} break; case 267: /* Line 1455 of yacc.c */ #line 1072 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new WithNode(GLOBAL_DATA, (yyvsp[(3) - (5)].expressionNode).m_node, (yyvsp[(5) - (5)].statementNode).m_node, (yylsp[(3) - (5)]).last_column, (yylsp[(3) - (5)]).last_column - (yylsp[(3) - (5)]).first_column), (yyvsp[(5) - (5)].statementNode).m_varDeclarations, (yyvsp[(5) - (5)].statementNode).m_funcDeclarations, (yyvsp[(3) - (5)].expressionNode).m_features | (yyvsp[(5) - (5)].statementNode).m_features | WithFeature, (yyvsp[(3) - (5)].expressionNode).m_numConstants + (yyvsp[(5) - (5)].statementNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (5)]), (yylsp[(4) - (5)])); ;} break; case 268: /* Line 1455 of yacc.c */ #line 1078 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new SwitchNode(GLOBAL_DATA, (yyvsp[(3) - (5)].expressionNode).m_node, (yyvsp[(5) - (5)].caseBlockNode).m_node), (yyvsp[(5) - (5)].caseBlockNode).m_varDeclarations, (yyvsp[(5) - (5)].caseBlockNode).m_funcDeclarations, (yyvsp[(3) - (5)].expressionNode).m_features | (yyvsp[(5) - (5)].caseBlockNode).m_features, (yyvsp[(3) - (5)].expressionNode).m_numConstants + (yyvsp[(5) - (5)].caseBlockNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (5)]), (yylsp[(4) - (5)])); ;} break; case 269: /* Line 1455 of yacc.c */ #line 1084 "../../JavaScriptCore/parser/Grammar.y" { (yyval.caseBlockNode) = createNodeDeclarationInfo<CaseBlockNode*>(new CaseBlockNode(GLOBAL_DATA, (yyvsp[(2) - (3)].clauseList).m_node.head, 0, 0), (yyvsp[(2) - (3)].clauseList).m_varDeclarations, (yyvsp[(2) - (3)].clauseList).m_funcDeclarations, (yyvsp[(2) - (3)].clauseList).m_features, (yyvsp[(2) - (3)].clauseList).m_numConstants); ;} break; case 270: /* Line 1455 of yacc.c */ #line 1086 "../../JavaScriptCore/parser/Grammar.y" { (yyval.caseBlockNode) = createNodeDeclarationInfo<CaseBlockNode*>(new CaseBlockNode(GLOBAL_DATA, (yyvsp[(2) - (5)].clauseList).m_node.head, (yyvsp[(3) - (5)].caseClauseNode).m_node, (yyvsp[(4) - (5)].clauseList).m_node.head), mergeDeclarationLists(mergeDeclarationLists((yyvsp[(2) - (5)].clauseList).m_varDeclarations, (yyvsp[(3) - (5)].caseClauseNode).m_varDeclarations), (yyvsp[(4) - (5)].clauseList).m_varDeclarations), mergeDeclarationLists(mergeDeclarationLists((yyvsp[(2) - (5)].clauseList).m_funcDeclarations, (yyvsp[(3) - (5)].caseClauseNode).m_funcDeclarations), (yyvsp[(4) - (5)].clauseList).m_funcDeclarations), (yyvsp[(2) - (5)].clauseList).m_features | (yyvsp[(3) - (5)].caseClauseNode).m_features | (yyvsp[(4) - (5)].clauseList).m_features, (yyvsp[(2) - (5)].clauseList).m_numConstants + (yyvsp[(3) - (5)].caseClauseNode).m_numConstants + (yyvsp[(4) - (5)].clauseList).m_numConstants); ;} break; case 271: /* Line 1455 of yacc.c */ #line 1094 "../../JavaScriptCore/parser/Grammar.y" { (yyval.clauseList).m_node.head = 0; (yyval.clauseList).m_node.tail = 0; (yyval.clauseList).m_varDeclarations = 0; (yyval.clauseList).m_funcDeclarations = 0; (yyval.clauseList).m_features = 0; (yyval.clauseList).m_numConstants = 0; ;} break; case 273: /* Line 1455 of yacc.c */ #line 1099 "../../JavaScriptCore/parser/Grammar.y" { (yyval.clauseList).m_node.head = new ClauseListNode(GLOBAL_DATA, (yyvsp[(1) - (1)].caseClauseNode).m_node); (yyval.clauseList).m_node.tail = (yyval.clauseList).m_node.head; (yyval.clauseList).m_varDeclarations = (yyvsp[(1) - (1)].caseClauseNode).m_varDeclarations; (yyval.clauseList).m_funcDeclarations = (yyvsp[(1) - (1)].caseClauseNode).m_funcDeclarations; (yyval.clauseList).m_features = (yyvsp[(1) - (1)].caseClauseNode).m_features; (yyval.clauseList).m_numConstants = (yyvsp[(1) - (1)].caseClauseNode).m_numConstants; ;} break; case 274: /* Line 1455 of yacc.c */ #line 1105 "../../JavaScriptCore/parser/Grammar.y" { (yyval.clauseList).m_node.head = (yyvsp[(1) - (2)].clauseList).m_node.head; (yyval.clauseList).m_node.tail = new ClauseListNode(GLOBAL_DATA, (yyvsp[(1) - (2)].clauseList).m_node.tail, (yyvsp[(2) - (2)].caseClauseNode).m_node); (yyval.clauseList).m_varDeclarations = mergeDeclarationLists((yyvsp[(1) - (2)].clauseList).m_varDeclarations, (yyvsp[(2) - (2)].caseClauseNode).m_varDeclarations); (yyval.clauseList).m_funcDeclarations = mergeDeclarationLists((yyvsp[(1) - (2)].clauseList).m_funcDeclarations, (yyvsp[(2) - (2)].caseClauseNode).m_funcDeclarations); (yyval.clauseList).m_features = (yyvsp[(1) - (2)].clauseList).m_features | (yyvsp[(2) - (2)].caseClauseNode).m_features; (yyval.clauseList).m_numConstants = (yyvsp[(1) - (2)].clauseList).m_numConstants + (yyvsp[(2) - (2)].caseClauseNode).m_numConstants; ;} break; case 275: /* Line 1455 of yacc.c */ #line 1115 "../../JavaScriptCore/parser/Grammar.y" { (yyval.caseClauseNode) = createNodeDeclarationInfo<CaseClauseNode*>(new CaseClauseNode(GLOBAL_DATA, (yyvsp[(2) - (3)].expressionNode).m_node), 0, 0, (yyvsp[(2) - (3)].expressionNode).m_features, (yyvsp[(2) - (3)].expressionNode).m_numConstants); ;} break; case 276: /* Line 1455 of yacc.c */ #line 1116 "../../JavaScriptCore/parser/Grammar.y" { (yyval.caseClauseNode) = createNodeDeclarationInfo<CaseClauseNode*>(new CaseClauseNode(GLOBAL_DATA, (yyvsp[(2) - (4)].expressionNode).m_node, (yyvsp[(4) - (4)].sourceElements).m_node), (yyvsp[(4) - (4)].sourceElements).m_varDeclarations, (yyvsp[(4) - (4)].sourceElements).m_funcDeclarations, (yyvsp[(2) - (4)].expressionNode).m_features | (yyvsp[(4) - (4)].sourceElements).m_features, (yyvsp[(2) - (4)].expressionNode).m_numConstants + (yyvsp[(4) - (4)].sourceElements).m_numConstants); ;} break; case 277: /* Line 1455 of yacc.c */ #line 1120 "../../JavaScriptCore/parser/Grammar.y" { (yyval.caseClauseNode) = createNodeDeclarationInfo<CaseClauseNode*>(new CaseClauseNode(GLOBAL_DATA, 0), 0, 0, 0, 0); ;} break; case 278: /* Line 1455 of yacc.c */ #line 1121 "../../JavaScriptCore/parser/Grammar.y" { (yyval.caseClauseNode) = createNodeDeclarationInfo<CaseClauseNode*>(new CaseClauseNode(GLOBAL_DATA, 0, (yyvsp[(3) - (3)].sourceElements).m_node), (yyvsp[(3) - (3)].sourceElements).m_varDeclarations, (yyvsp[(3) - (3)].sourceElements).m_funcDeclarations, (yyvsp[(3) - (3)].sourceElements).m_features, (yyvsp[(3) - (3)].sourceElements).m_numConstants); ;} break; case 279: /* Line 1455 of yacc.c */ #line 1125 "../../JavaScriptCore/parser/Grammar.y" { LabelNode* node = new LabelNode(GLOBAL_DATA, *(yyvsp[(1) - (3)].ident), (yyvsp[(3) - (3)].statementNode).m_node); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(2) - (3)]).last_column, (yylsp[(2) - (3)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(node, (yyvsp[(3) - (3)].statementNode).m_varDeclarations, (yyvsp[(3) - (3)].statementNode).m_funcDeclarations, (yyvsp[(3) - (3)].statementNode).m_features, (yyvsp[(3) - (3)].statementNode).m_numConstants); ;} break; case 280: /* Line 1455 of yacc.c */ #line 1131 "../../JavaScriptCore/parser/Grammar.y" { ThrowNode* node = new ThrowNode(GLOBAL_DATA, (yyvsp[(2) - (3)].expressionNode).m_node); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(2) - (3)]).last_column, (yylsp[(2) - (3)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(node, 0, 0, (yyvsp[(2) - (3)].expressionNode).m_features, (yyvsp[(2) - (3)].expressionNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (3)]), (yylsp[(2) - (3)])); ;} break; case 281: /* Line 1455 of yacc.c */ #line 1135 "../../JavaScriptCore/parser/Grammar.y" { ThrowNode* node = new ThrowNode(GLOBAL_DATA, (yyvsp[(2) - (3)].expressionNode).m_node); SET_EXCEPTION_LOCATION(node, (yylsp[(1) - (3)]).first_column, (yylsp[(2) - (3)]).last_column, (yylsp[(2) - (3)]).last_column); (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(node, 0, 0, (yyvsp[(2) - (3)].expressionNode).m_features, (yyvsp[(2) - (3)].expressionNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (3)]), (yylsp[(2) - (3)])); AUTO_SEMICOLON; ;} break; case 282: /* Line 1455 of yacc.c */ #line 1142 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new TryNode(GLOBAL_DATA, (yyvsp[(2) - (4)].statementNode).m_node, GLOBAL_DATA->propertyNames->nullIdentifier, false, 0, (yyvsp[(4) - (4)].statementNode).m_node), mergeDeclarationLists((yyvsp[(2) - (4)].statementNode).m_varDeclarations, (yyvsp[(4) - (4)].statementNode).m_varDeclarations), mergeDeclarationLists((yyvsp[(2) - (4)].statementNode).m_funcDeclarations, (yyvsp[(4) - (4)].statementNode).m_funcDeclarations), (yyvsp[(2) - (4)].statementNode).m_features | (yyvsp[(4) - (4)].statementNode).m_features, (yyvsp[(2) - (4)].statementNode).m_numConstants + (yyvsp[(4) - (4)].statementNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (4)]), (yylsp[(2) - (4)])); ;} break; case 283: /* Line 1455 of yacc.c */ #line 1148 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new TryNode(GLOBAL_DATA, (yyvsp[(2) - (7)].statementNode).m_node, *(yyvsp[(5) - (7)].ident), ((yyvsp[(7) - (7)].statementNode).m_features & EvalFeature) != 0, (yyvsp[(7) - (7)].statementNode).m_node, 0), mergeDeclarationLists((yyvsp[(2) - (7)].statementNode).m_varDeclarations, (yyvsp[(7) - (7)].statementNode).m_varDeclarations), mergeDeclarationLists((yyvsp[(2) - (7)].statementNode).m_funcDeclarations, (yyvsp[(7) - (7)].statementNode).m_funcDeclarations), (yyvsp[(2) - (7)].statementNode).m_features | (yyvsp[(7) - (7)].statementNode).m_features | CatchFeature, (yyvsp[(2) - (7)].statementNode).m_numConstants + (yyvsp[(7) - (7)].statementNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (7)]), (yylsp[(2) - (7)])); ;} break; case 284: /* Line 1455 of yacc.c */ #line 1155 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new TryNode(GLOBAL_DATA, (yyvsp[(2) - (9)].statementNode).m_node, *(yyvsp[(5) - (9)].ident), ((yyvsp[(7) - (9)].statementNode).m_features & EvalFeature) != 0, (yyvsp[(7) - (9)].statementNode).m_node, (yyvsp[(9) - (9)].statementNode).m_node), mergeDeclarationLists(mergeDeclarationLists((yyvsp[(2) - (9)].statementNode).m_varDeclarations, (yyvsp[(7) - (9)].statementNode).m_varDeclarations), (yyvsp[(9) - (9)].statementNode).m_varDeclarations), mergeDeclarationLists(mergeDeclarationLists((yyvsp[(2) - (9)].statementNode).m_funcDeclarations, (yyvsp[(7) - (9)].statementNode).m_funcDeclarations), (yyvsp[(9) - (9)].statementNode).m_funcDeclarations), (yyvsp[(2) - (9)].statementNode).m_features | (yyvsp[(7) - (9)].statementNode).m_features | (yyvsp[(9) - (9)].statementNode).m_features | CatchFeature, (yyvsp[(2) - (9)].statementNode).m_numConstants + (yyvsp[(7) - (9)].statementNode).m_numConstants + (yyvsp[(9) - (9)].statementNode).m_numConstants); DBG((yyval.statementNode).m_node, (yylsp[(1) - (9)]), (yylsp[(2) - (9)])); ;} break; case 285: /* Line 1455 of yacc.c */ #line 1164 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new DebuggerStatementNode(GLOBAL_DATA), 0, 0, 0, 0); DBG((yyval.statementNode).m_node, (yylsp[(1) - (2)]), (yylsp[(2) - (2)])); ;} break; case 286: /* Line 1455 of yacc.c */ #line 1166 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new DebuggerStatementNode(GLOBAL_DATA), 0, 0, 0, 0); DBG((yyval.statementNode).m_node, (yylsp[(1) - (2)]), (yylsp[(1) - (2)])); AUTO_SEMICOLON; ;} break; case 287: /* Line 1455 of yacc.c */ #line 1171 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new FuncDeclNode(GLOBAL_DATA, *(yyvsp[(2) - (7)].ident), (yyvsp[(6) - (7)].functionBodyNode), LEXER->sourceCode((yyvsp[(5) - (7)].intValue), (yyvsp[(7) - (7)].intValue), (yylsp[(5) - (7)]).first_line)), 0, new ParserRefCountedData<DeclarationStacks::FunctionStack>(GLOBAL_DATA), ((*(yyvsp[(2) - (7)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0) | ClosureFeature, 0); DBG((yyvsp[(6) - (7)].functionBodyNode), (yylsp[(5) - (7)]), (yylsp[(7) - (7)])); (yyval.statementNode).m_funcDeclarations->data.append(static_cast<FuncDeclNode*>((yyval.statementNode).m_node)); ;} break; case 288: /* Line 1455 of yacc.c */ #line 1173 "../../JavaScriptCore/parser/Grammar.y" { (yyval.statementNode) = createNodeDeclarationInfo<StatementNode*>(new FuncDeclNode(GLOBAL_DATA, *(yyvsp[(2) - (8)].ident), (yyvsp[(7) - (8)].functionBodyNode), LEXER->sourceCode((yyvsp[(6) - (8)].intValue), (yyvsp[(8) - (8)].intValue), (yylsp[(6) - (8)]).first_line), (yyvsp[(4) - (8)].parameterList).m_node.head), 0, new ParserRefCountedData<DeclarationStacks::FunctionStack>(GLOBAL_DATA), ((*(yyvsp[(2) - (8)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0) | (yyvsp[(4) - (8)].parameterList).m_features | ClosureFeature, 0); if ((yyvsp[(4) - (8)].parameterList).m_features & ArgumentsFeature) (yyvsp[(7) - (8)].functionBodyNode)->setUsesArguments(); DBG((yyvsp[(7) - (8)].functionBodyNode), (yylsp[(6) - (8)]), (yylsp[(8) - (8)])); (yyval.statementNode).m_funcDeclarations->data.append(static_cast<FuncDeclNode*>((yyval.statementNode).m_node)); ;} break; case 289: /* Line 1455 of yacc.c */ #line 1183 "../../JavaScriptCore/parser/Grammar.y" { (yyval.funcExprNode) = createNodeInfo(new FuncExprNode(GLOBAL_DATA, GLOBAL_DATA->propertyNames->nullIdentifier, (yyvsp[(5) - (6)].functionBodyNode), LEXER->sourceCode((yyvsp[(4) - (6)].intValue), (yyvsp[(6) - (6)].intValue), (yylsp[(4) - (6)]).first_line)), ClosureFeature, 0); DBG((yyvsp[(5) - (6)].functionBodyNode), (yylsp[(4) - (6)]), (yylsp[(6) - (6)])); ;} break; case 290: /* Line 1455 of yacc.c */ #line 1185 "../../JavaScriptCore/parser/Grammar.y" { (yyval.funcExprNode) = createNodeInfo(new FuncExprNode(GLOBAL_DATA, GLOBAL_DATA->propertyNames->nullIdentifier, (yyvsp[(6) - (7)].functionBodyNode), LEXER->sourceCode((yyvsp[(5) - (7)].intValue), (yyvsp[(7) - (7)].intValue), (yylsp[(5) - (7)]).first_line), (yyvsp[(3) - (7)].parameterList).m_node.head), (yyvsp[(3) - (7)].parameterList).m_features | ClosureFeature, 0); if ((yyvsp[(3) - (7)].parameterList).m_features & ArgumentsFeature) (yyvsp[(6) - (7)].functionBodyNode)->setUsesArguments(); DBG((yyvsp[(6) - (7)].functionBodyNode), (yylsp[(5) - (7)]), (yylsp[(7) - (7)])); ;} break; case 291: /* Line 1455 of yacc.c */ #line 1191 "../../JavaScriptCore/parser/Grammar.y" { (yyval.funcExprNode) = createNodeInfo(new FuncExprNode(GLOBAL_DATA, *(yyvsp[(2) - (7)].ident), (yyvsp[(6) - (7)].functionBodyNode), LEXER->sourceCode((yyvsp[(5) - (7)].intValue), (yyvsp[(7) - (7)].intValue), (yylsp[(5) - (7)]).first_line)), ClosureFeature, 0); DBG((yyvsp[(6) - (7)].functionBodyNode), (yylsp[(5) - (7)]), (yylsp[(7) - (7)])); ;} break; case 292: /* Line 1455 of yacc.c */ #line 1193 "../../JavaScriptCore/parser/Grammar.y" { (yyval.funcExprNode) = createNodeInfo(new FuncExprNode(GLOBAL_DATA, *(yyvsp[(2) - (8)].ident), (yyvsp[(7) - (8)].functionBodyNode), LEXER->sourceCode((yyvsp[(6) - (8)].intValue), (yyvsp[(8) - (8)].intValue), (yylsp[(6) - (8)]).first_line), (yyvsp[(4) - (8)].parameterList).m_node.head), (yyvsp[(4) - (8)].parameterList).m_features | ClosureFeature, 0); if ((yyvsp[(4) - (8)].parameterList).m_features & ArgumentsFeature) (yyvsp[(7) - (8)].functionBodyNode)->setUsesArguments(); DBG((yyvsp[(7) - (8)].functionBodyNode), (yylsp[(6) - (8)]), (yylsp[(8) - (8)])); ;} break; case 293: /* Line 1455 of yacc.c */ #line 1202 "../../JavaScriptCore/parser/Grammar.y" { (yyval.parameterList).m_node.head = new ParameterNode(GLOBAL_DATA, *(yyvsp[(1) - (1)].ident)); (yyval.parameterList).m_features = (*(yyvsp[(1) - (1)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0; (yyval.parameterList).m_node.tail = (yyval.parameterList).m_node.head; ;} break; case 294: /* Line 1455 of yacc.c */ #line 1205 "../../JavaScriptCore/parser/Grammar.y" { (yyval.parameterList).m_node.head = (yyvsp[(1) - (3)].parameterList).m_node.head; (yyval.parameterList).m_features = (yyvsp[(1) - (3)].parameterList).m_features | ((*(yyvsp[(3) - (3)].ident) == GLOBAL_DATA->propertyNames->arguments) ? ArgumentsFeature : 0); (yyval.parameterList).m_node.tail = new ParameterNode(GLOBAL_DATA, (yyvsp[(1) - (3)].parameterList).m_node.tail, *(yyvsp[(3) - (3)].ident)); ;} break; case 295: /* Line 1455 of yacc.c */ #line 1211 "../../JavaScriptCore/parser/Grammar.y" { (yyval.functionBodyNode) = FunctionBodyNode::create(GLOBAL_DATA); ;} break; case 296: /* Line 1455 of yacc.c */ #line 1212 "../../JavaScriptCore/parser/Grammar.y" { (yyval.functionBodyNode) = FunctionBodyNode::create(GLOBAL_DATA); ;} break; case 297: /* Line 1455 of yacc.c */ #line 1216 "../../JavaScriptCore/parser/Grammar.y" { GLOBAL_DATA->parser->didFinishParsing(new SourceElements(GLOBAL_DATA), 0, 0, NoFeatures, (yylsp[(0) - (0)]).last_line, 0); ;} break; case 298: /* Line 1455 of yacc.c */ #line 1217 "../../JavaScriptCore/parser/Grammar.y" { GLOBAL_DATA->parser->didFinishParsing((yyvsp[(1) - (1)].sourceElements).m_node, (yyvsp[(1) - (1)].sourceElements).m_varDeclarations, (yyvsp[(1) - (1)].sourceElements).m_funcDeclarations, (yyvsp[(1) - (1)].sourceElements).m_features, (yylsp[(1) - (1)]).last_line, (yyvsp[(1) - (1)].sourceElements).m_numConstants); ;} break; case 299: /* Line 1455 of yacc.c */ #line 1222 "../../JavaScriptCore/parser/Grammar.y" { (yyval.sourceElements).m_node = new SourceElements(GLOBAL_DATA); (yyval.sourceElements).m_node->append((yyvsp[(1) - (1)].statementNode).m_node); (yyval.sourceElements).m_varDeclarations = (yyvsp[(1) - (1)].statementNode).m_varDeclarations; (yyval.sourceElements).m_funcDeclarations = (yyvsp[(1) - (1)].statementNode).m_funcDeclarations; (yyval.sourceElements).m_features = (yyvsp[(1) - (1)].statementNode).m_features; (yyval.sourceElements).m_numConstants = (yyvsp[(1) - (1)].statementNode).m_numConstants; ;} break; case 300: /* Line 1455 of yacc.c */ #line 1229 "../../JavaScriptCore/parser/Grammar.y" { (yyval.sourceElements).m_node->append((yyvsp[(2) - (2)].statementNode).m_node); (yyval.sourceElements).m_varDeclarations = mergeDeclarationLists((yyvsp[(1) - (2)].sourceElements).m_varDeclarations, (yyvsp[(2) - (2)].statementNode).m_varDeclarations); (yyval.sourceElements).m_funcDeclarations = mergeDeclarationLists((yyvsp[(1) - (2)].sourceElements).m_funcDeclarations, (yyvsp[(2) - (2)].statementNode).m_funcDeclarations); (yyval.sourceElements).m_features = (yyvsp[(1) - (2)].sourceElements).m_features | (yyvsp[(2) - (2)].statementNode).m_features; (yyval.sourceElements).m_numConstants = (yyvsp[(1) - (2)].sourceElements).m_numConstants + (yyvsp[(2) - (2)].statementNode).m_numConstants; ;} break; case 304: /* Line 1455 of yacc.c */ #line 1243 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 305: /* Line 1455 of yacc.c */ #line 1244 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 306: /* Line 1455 of yacc.c */ #line 1245 "../../JavaScriptCore/parser/Grammar.y" { Lexer& l = *LEXER; if (!l.scanRegExp()) YYABORT; ;} break; case 307: /* Line 1455 of yacc.c */ #line 1246 "../../JavaScriptCore/parser/Grammar.y" { Lexer& l = *LEXER; if (!l.scanRegExp()) YYABORT; ;} break; case 308: /* Line 1455 of yacc.c */ #line 1250 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 309: /* Line 1455 of yacc.c */ #line 1251 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 310: /* Line 1455 of yacc.c */ #line 1252 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 311: /* Line 1455 of yacc.c */ #line 1253 "../../JavaScriptCore/parser/Grammar.y" { if (*(yyvsp[(1) - (7)].ident) != "get" && *(yyvsp[(1) - (7)].ident) != "set") YYABORT; ;} break; case 312: /* Line 1455 of yacc.c */ #line 1254 "../../JavaScriptCore/parser/Grammar.y" { if (*(yyvsp[(1) - (8)].ident) != "get" && *(yyvsp[(1) - (8)].ident) != "set") YYABORT; ;} break; case 316: /* Line 1455 of yacc.c */ #line 1264 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 317: /* Line 1455 of yacc.c */ #line 1265 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 318: /* Line 1455 of yacc.c */ #line 1267 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 322: /* Line 1455 of yacc.c */ #line 1274 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 517: /* Line 1455 of yacc.c */ #line 1642 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 518: /* Line 1455 of yacc.c */ #line 1643 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 520: /* Line 1455 of yacc.c */ #line 1648 "../../JavaScriptCore/parser/Grammar.y" { AUTO_SEMICOLON; ;} break; case 521: /* Line 1455 of yacc.c */ #line 1652 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 522: /* Line 1455 of yacc.c */ #line 1653 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 525: /* Line 1455 of yacc.c */ #line 1659 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 526: /* Line 1455 of yacc.c */ #line 1660 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 530: /* Line 1455 of yacc.c */ #line 1667 "../../JavaScriptCore/parser/Grammar.y" { AUTO_SEMICOLON; ;} break; case 533: /* Line 1455 of yacc.c */ #line 1676 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 534: /* Line 1455 of yacc.c */ #line 1677 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 539: /* Line 1455 of yacc.c */ #line 1694 "../../JavaScriptCore/parser/Grammar.y" { AUTO_SEMICOLON; ;} break; case 555: /* Line 1455 of yacc.c */ #line 1725 "../../JavaScriptCore/parser/Grammar.y" { AUTO_SEMICOLON; ;} break; case 557: /* Line 1455 of yacc.c */ #line 1727 "../../JavaScriptCore/parser/Grammar.y" { AUTO_SEMICOLON; ;} break; case 559: /* Line 1455 of yacc.c */ #line 1732 "../../JavaScriptCore/parser/Grammar.y" { AUTO_SEMICOLON; ;} break; case 561: /* Line 1455 of yacc.c */ #line 1734 "../../JavaScriptCore/parser/Grammar.y" { AUTO_SEMICOLON; ;} break; case 563: /* Line 1455 of yacc.c */ #line 1739 "../../JavaScriptCore/parser/Grammar.y" { AUTO_SEMICOLON; ;} break; case 565: /* Line 1455 of yacc.c */ #line 1741 "../../JavaScriptCore/parser/Grammar.y" { AUTO_SEMICOLON; ;} break; case 568: /* Line 1455 of yacc.c */ #line 1753 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 569: /* Line 1455 of yacc.c */ #line 1754 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 578: /* Line 1455 of yacc.c */ #line 1778 "../../JavaScriptCore/parser/Grammar.y" { ;} break; case 580: /* Line 1455 of yacc.c */ #line 1783 "../../JavaScriptCore/parser/Grammar.y" { AUTO_SEMICOLON; ;} break; case 585: /* Line 1455 of yacc.c */ #line 1794 "../../JavaScriptCore/parser/Grammar.y" { AUTO_SEMICOLON; ;} break; case 592: /* Line 1455 of yacc.c */ #line 1810 "../../JavaScriptCore/parser/Grammar.y" { ;} break; /* Line 1455 of yacc.c */ #line 5110 "Grammar.tab.c" default: break; } YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (YY_("syntax error")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (yymsg); } else { yyerror (YY_("syntax error")); if (yysize != 0) goto yyexhaustedlab; } } #endif } yyerror_range[0] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; yyerror_range[0] = yylsp[1-yylen]; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[0] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } *++yyvsp = yylval; yyerror_range[1] = yylloc; /* Using YYLLOC is tempting, but would change the location of the lookahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, (yyerror_range - 1), 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined(yyoverflow) || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc); /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } /* Line 1675 of yacc.c */ #line 1826 "../../JavaScriptCore/parser/Grammar.y" static ExpressionNode* makeAssignNode(void* globalPtr, ExpressionNode* loc, Operator op, ExpressionNode* expr, bool locHasAssignments, bool exprHasAssignments, int start, int divot, int end) { if (!loc->isLocation()) return new AssignErrorNode(GLOBAL_DATA, loc, op, expr, divot, divot - start, end - divot); if (loc->isResolveNode()) { ResolveNode* resolve = static_cast<ResolveNode*>(loc); if (op == OpEqual) { AssignResolveNode* node = new AssignResolveNode(GLOBAL_DATA, resolve->identifier(), expr, exprHasAssignments); SET_EXCEPTION_LOCATION(node, start, divot, end); return node; } else return new ReadModifyResolveNode(GLOBAL_DATA, resolve->identifier(), op, expr, exprHasAssignments, divot, divot - start, end - divot); } if (loc->isBracketAccessorNode()) { BracketAccessorNode* bracket = static_cast<BracketAccessorNode*>(loc); if (op == OpEqual) return new AssignBracketNode(GLOBAL_DATA, bracket->base(), bracket->subscript(), expr, locHasAssignments, exprHasAssignments, bracket->divot(), bracket->divot() - start, end - bracket->divot()); else { ReadModifyBracketNode* node = new ReadModifyBracketNode(GLOBAL_DATA, bracket->base(), bracket->subscript(), op, expr, locHasAssignments, exprHasAssignments, divot, divot - start, end - divot); node->setSubexpressionInfo(bracket->divot(), bracket->endOffset()); return node; } } ASSERT(loc->isDotAccessorNode()); DotAccessorNode* dot = static_cast<DotAccessorNode*>(loc); if (op == OpEqual) return new AssignDotNode(GLOBAL_DATA, dot->base(), dot->identifier(), expr, exprHasAssignments, dot->divot(), dot->divot() - start, end - dot->divot()); ReadModifyDotNode* node = new ReadModifyDotNode(GLOBAL_DATA, dot->base(), dot->identifier(), op, expr, exprHasAssignments, divot, divot - start, end - divot); node->setSubexpressionInfo(dot->divot(), dot->endOffset()); return node; } static ExpressionNode* makePrefixNode(void* globalPtr, ExpressionNode* expr, Operator op, int start, int divot, int end) { if (!expr->isLocation()) return new PrefixErrorNode(GLOBAL_DATA, expr, op, divot, divot - start, end - divot); if (expr->isResolveNode()) { ResolveNode* resolve = static_cast<ResolveNode*>(expr); return new PrefixResolveNode(GLOBAL_DATA, resolve->identifier(), op, divot, divot - start, end - divot); } if (expr->isBracketAccessorNode()) { BracketAccessorNode* bracket = static_cast<BracketAccessorNode*>(expr); PrefixBracketNode* node = new PrefixBracketNode(GLOBAL_DATA, bracket->base(), bracket->subscript(), op, divot, divot - start, end - divot); node->setSubexpressionInfo(bracket->divot(), bracket->startOffset()); return node; } ASSERT(expr->isDotAccessorNode()); DotAccessorNode* dot = static_cast<DotAccessorNode*>(expr); PrefixDotNode* node = new PrefixDotNode(GLOBAL_DATA, dot->base(), dot->identifier(), op, divot, divot - start, end - divot); node->setSubexpressionInfo(dot->divot(), dot->startOffset()); return node; } static ExpressionNode* makePostfixNode(void* globalPtr, ExpressionNode* expr, Operator op, int start, int divot, int end) { if (!expr->isLocation()) return new PostfixErrorNode(GLOBAL_DATA, expr, op, divot, divot - start, end - divot); if (expr->isResolveNode()) { ResolveNode* resolve = static_cast<ResolveNode*>(expr); return new PostfixResolveNode(GLOBAL_DATA, resolve->identifier(), op, divot, divot - start, end - divot); } if (expr->isBracketAccessorNode()) { BracketAccessorNode* bracket = static_cast<BracketAccessorNode*>(expr); PostfixBracketNode* node = new PostfixBracketNode(GLOBAL_DATA, bracket->base(), bracket->subscript(), op, divot, divot - start, end - divot); node->setSubexpressionInfo(bracket->divot(), bracket->endOffset()); return node; } ASSERT(expr->isDotAccessorNode()); DotAccessorNode* dot = static_cast<DotAccessorNode*>(expr); PostfixDotNode* node = new PostfixDotNode(GLOBAL_DATA, dot->base(), dot->identifier(), op, divot, divot - start, end - divot); node->setSubexpressionInfo(dot->divot(), dot->endOffset()); return node; } static ExpressionNodeInfo makeFunctionCallNode(void* globalPtr, ExpressionNodeInfo func, ArgumentsNodeInfo args, int start, int divot, int end) { CodeFeatures features = func.m_features | args.m_features; int numConstants = func.m_numConstants + args.m_numConstants; if (!func.m_node->isLocation()) return createNodeInfo<ExpressionNode*>(new FunctionCallValueNode(GLOBAL_DATA, func.m_node, args.m_node, divot, divot - start, end - divot), features, numConstants); if (func.m_node->isResolveNode()) { ResolveNode* resolve = static_cast<ResolveNode*>(func.m_node); const Identifier& identifier = resolve->identifier(); if (identifier == GLOBAL_DATA->propertyNames->eval) return createNodeInfo<ExpressionNode*>(new EvalFunctionCallNode(GLOBAL_DATA, args.m_node, divot, divot - start, end - divot), EvalFeature | features, numConstants); return createNodeInfo<ExpressionNode*>(new FunctionCallResolveNode(GLOBAL_DATA, identifier, args.m_node, divot, divot - start, end - divot), features, numConstants); } if (func.m_node->isBracketAccessorNode()) { BracketAccessorNode* bracket = static_cast<BracketAccessorNode*>(func.m_node); FunctionCallBracketNode* node = new FunctionCallBracketNode(GLOBAL_DATA, bracket->base(), bracket->subscript(), args.m_node, divot, divot - start, end - divot); node->setSubexpressionInfo(bracket->divot(), bracket->endOffset()); return createNodeInfo<ExpressionNode*>(node, features, numConstants); } ASSERT(func.m_node->isDotAccessorNode()); DotAccessorNode* dot = static_cast<DotAccessorNode*>(func.m_node); FunctionCallDotNode* node = new FunctionCallDotNode(GLOBAL_DATA, dot->base(), dot->identifier(), args.m_node, divot, divot - start, end - divot); node->setSubexpressionInfo(dot->divot(), dot->endOffset()); return createNodeInfo<ExpressionNode*>(node, features, numConstants); } static ExpressionNode* makeTypeOfNode(void* globalPtr, ExpressionNode* expr) { if (expr->isResolveNode()) { ResolveNode* resolve = static_cast<ResolveNode*>(expr); return new TypeOfResolveNode(GLOBAL_DATA, resolve->identifier()); } return new TypeOfValueNode(GLOBAL_DATA, expr); } static ExpressionNode* makeDeleteNode(void* globalPtr, ExpressionNode* expr, int start, int divot, int end) { if (!expr->isLocation()) return new DeleteValueNode(GLOBAL_DATA, expr); if (expr->isResolveNode()) { ResolveNode* resolve = static_cast<ResolveNode*>(expr); return new DeleteResolveNode(GLOBAL_DATA, resolve->identifier(), divot, divot - start, end - divot); } if (expr->isBracketAccessorNode()) { BracketAccessorNode* bracket = static_cast<BracketAccessorNode*>(expr); return new DeleteBracketNode(GLOBAL_DATA, bracket->base(), bracket->subscript(), divot, divot - start, end - divot); } ASSERT(expr->isDotAccessorNode()); DotAccessorNode* dot = static_cast<DotAccessorNode*>(expr); return new DeleteDotNode(GLOBAL_DATA, dot->base(), dot->identifier(), divot, divot - start, end - divot); } static PropertyNode* makeGetterOrSetterPropertyNode(void* globalPtr, const Identifier& getOrSet, const Identifier& name, ParameterNode* params, FunctionBodyNode* body, const SourceCode& source) { PropertyNode::Type type; if (getOrSet == "get") type = PropertyNode::Getter; else if (getOrSet == "set") type = PropertyNode::Setter; else return 0; return new PropertyNode(GLOBAL_DATA, name, new FuncExprNode(GLOBAL_DATA, GLOBAL_DATA->propertyNames->nullIdentifier, body, source, params), type); } static ExpressionNode* makeNegateNode(void* globalPtr, ExpressionNode* n) { if (n->isNumber()) { NumberNode* number = static_cast<NumberNode*>(n); if (number->value() > 0.0) { number->setValue(-number->value()); return number; } } return new NegateNode(GLOBAL_DATA, n); } static NumberNode* makeNumberNode(void* globalPtr, double d) { return new NumberNode(GLOBAL_DATA, d); } static ExpressionNode* makeBitwiseNotNode(void* globalPtr, ExpressionNode* expr) { if (expr->isNumber()) return makeNumberNode(globalPtr, ~toInt32(static_cast<NumberNode*>(expr)->value())); return new BitwiseNotNode(GLOBAL_DATA, expr); } static ExpressionNode* makeMultNode(void* globalPtr, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments) { expr1 = expr1->stripUnaryPlus(); expr2 = expr2->stripUnaryPlus(); if (expr1->isNumber() && expr2->isNumber()) return makeNumberNode(globalPtr, static_cast<NumberNode*>(expr1)->value() * static_cast<NumberNode*>(expr2)->value()); if (expr1->isNumber() && static_cast<NumberNode*>(expr1)->value() == 1) return new UnaryPlusNode(GLOBAL_DATA, expr2); if (expr2->isNumber() && static_cast<NumberNode*>(expr2)->value() == 1) return new UnaryPlusNode(GLOBAL_DATA, expr1); return new MultNode(GLOBAL_DATA, expr1, expr2, rightHasAssignments); } static ExpressionNode* makeDivNode(void* globalPtr, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments) { expr1 = expr1->stripUnaryPlus(); expr2 = expr2->stripUnaryPlus(); if (expr1->isNumber() && expr2->isNumber()) return makeNumberNode(globalPtr, static_cast<NumberNode*>(expr1)->value() / static_cast<NumberNode*>(expr2)->value()); return new DivNode(GLOBAL_DATA, expr1, expr2, rightHasAssignments); } static ExpressionNode* makeAddNode(void* globalPtr, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments) { if (expr1->isNumber() && expr2->isNumber()) return makeNumberNode(globalPtr, static_cast<NumberNode*>(expr1)->value() + static_cast<NumberNode*>(expr2)->value()); return new AddNode(GLOBAL_DATA, expr1, expr2, rightHasAssignments); } static ExpressionNode* makeSubNode(void* globalPtr, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments) { expr1 = expr1->stripUnaryPlus(); expr2 = expr2->stripUnaryPlus(); if (expr1->isNumber() && expr2->isNumber()) return makeNumberNode(globalPtr, static_cast<NumberNode*>(expr1)->value() - static_cast<NumberNode*>(expr2)->value()); return new SubNode(GLOBAL_DATA, expr1, expr2, rightHasAssignments); } static ExpressionNode* makeLeftShiftNode(void* globalPtr, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments) { if (expr1->isNumber() && expr2->isNumber()) return makeNumberNode(globalPtr, toInt32(static_cast<NumberNode*>(expr1)->value()) << (toUInt32(static_cast<NumberNode*>(expr2)->value()) & 0x1f)); return new LeftShiftNode(GLOBAL_DATA, expr1, expr2, rightHasAssignments); } static ExpressionNode* makeRightShiftNode(void* globalPtr, ExpressionNode* expr1, ExpressionNode* expr2, bool rightHasAssignments) { if (expr1->isNumber() && expr2->isNumber()) return makeNumberNode(globalPtr, toInt32(static_cast<NumberNode*>(expr1)->value()) >> (toUInt32(static_cast<NumberNode*>(expr2)->value()) & 0x1f)); return new RightShiftNode(GLOBAL_DATA, expr1, expr2, rightHasAssignments); } /* called by yyparse on error */ int yyerror(const char *) { return 1; } /* may we automatically insert a semicolon ? */ static bool allowAutomaticSemicolon(Lexer& lexer, int yychar) { return yychar == CLOSEBRACE || yychar == 0 || lexer.prevTerminator(); } static ExpressionNode* combineVarInitializers(void* globalPtr, ExpressionNode* list, AssignResolveNode* init) { if (!list) return init; return new VarDeclCommaNode(GLOBAL_DATA, list, init); } // We turn variable declarations into either assignments or empty // statements (which later get stripped out), because the actual // declaration work is hoisted up to the start of the function body static StatementNode* makeVarStatementNode(void* globalPtr, ExpressionNode* expr) { if (!expr) return new EmptyStatementNode(GLOBAL_DATA); return new VarStatementNode(GLOBAL_DATA, expr); } #undef GLOBAL_DATA
RLovelett/qt
src/3rdparty/webkit/WebCore/generated/Grammar.cpp
C++
lgpl-2.1
296,109
object = {__bases__: [], __name__: 'object'} object.__mro__ = [object] type = {__bases__: [object], __mro__: [object], __name__: 'type'} object.__metaclass__ = type __ARGUMENTS_PADDING__ = {ARGUMENTS_PADDING: "YES IT IS!"} def __is__(me, other): return (me is other) __is__.is_method = True object.__is__ = __is__ def __isnot__(me, other): return not (me is other) __isnot__.is_method = True object.__isnot__ = __isnot__ def mro(me): if me is object: raw = me.__mro__ elif me.__class__: raw = me.__class__.__mro__ else: raw = me.__mro__ l = pythonium_call(tuple) l.jsobject = raw.slice() return l mro.is_method = True object.mro = mro def __hash__(me): uid = lookup(me, 'uid') if not uid: uid = object._uid object._uid += 1 me.__uid__ = uid return pythonium_call(str, '{' + uid) __hash__.is_method = True object._uid = 1 object.__hash__ = __hash__ def __rcontains__(me, other): contains = lookup(other, '__contains__') return contains(me) __rcontains__.is_method = True object.__rcontains__ = __rcontains__ def issubclass(klass, other): if klass is other: return __TRUE if not klass.__bases__: return __FALSE for base in klass.__bases__: if issubclass(base, other) is __TRUE: return __TRUE return __FALSE def pythonium_is_true(v): if v is False: return False if v is True: return True if v is None: return False if v is __NONE: return False if v is __FALSE: return False if isinstance(v, int) or isinstance(v, float): if v.jsobject == 0: return False length = lookup(v, '__len__') if length and length().jsobject == 0: return False return True def isinstance(obj, klass): if obj.__class__: return issubclass(obj.__class__, klass) return __FALSE def pythonium_obj_to_js_exception(obj): def exception(): this.exception = obj return exception def pythonium_is_exception(obj, exc): if obj is exc: return True return isinstance(obj, exc) def pythonium_call(obj): args = Array.prototype.slice.call(arguments, 1) if obj.__metaclass__: instance = {__class__: obj} init = lookup(instance, '__init__') if init: init.apply(instance, args) return instance else: return obj.apply(None, args) def pythonium_create_empty_dict(): instance = {__class__: dict} instance._keys = pythonium_call(list) instance.jsobject = JSObject() return instance def pythonium_mro(bases): """Calculate the Method Resolution Order of bases using the C3 algorithm. Suppose you intended creating a class K with the given base classes. This function returns the MRO which K would have, *excluding* K itself (since it doesn't yet exist), as if you had actually created the class. Another way of looking at this, if you pass a single class K, this will return the linearization of K (the MRO of K, *including* itself). """ # based on http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/ seqs = [C.__mro__.slice() for C in bases] seqs.push(bases.slice()) def cdr(l): l = l.slice() l = l.splice(1) return l def contains(l, c): for i in l: if i is c: return True return False res = [] while True: non_empty = [] for seq in seqs: out = [] for item in seq: if item: out.push(item) if out.length != 0: non_empty.push(out) if non_empty.length == 0: # Nothing left to process, we're done. return res for seq in non_empty: # Find merge candidates among seq heads. candidate = seq[0] not_head = [] for s in non_empty: if contains(cdr(s), candidate): not_head.push(s) if not_head.length != 0: candidate = None else: break if not candidate: raise TypeError("Inconsistent hierarchy, no C3 MRO is possible") res.push(candidate) for seq in non_empty: # Remove candidate. if seq[0] is candidate: seq[0] = None seqs = non_empty def pythonium_create_class(name, bases, attrs): attrs.__name__ = name attrs.__metaclass__ = type attrs.__bases__ = bases mro = pythonium_mro(bases) mro.splice(0, 0, attrs) attrs.__mro__ = mro return attrs def lookup(obj, attr): obj_attr = obj[attr] if obj_attr != None: if obj_attr and {}.toString.call(obj_attr) == '[object Function]' and obj_attr.is_method and not obj_attr.bound: def method_wrapper(): args = Array.prototype.slice.call(arguments) args.splice(0, 0, obj) return obj_attr.apply(None, args) method_wrapper.bound = True return method_wrapper return obj_attr else: if obj.__class__: __mro__ = obj.__class__.__mro__ elif obj.__metaclass__: __mro__ = obj.__metaclass__.__mro__ else: # it's a function return None for base in __mro__: class_attr = base[attr] if class_attr != None: if {}.toString.call(class_attr) == '[object Function]' and class_attr.is_method and not class_attr.bound: def method_wrapper(): args = Array.prototype.slice.call(arguments) args.splice(0, 0, obj) return class_attr.apply(None, args) method_wrapper.bound = True return method_wrapper return class_attr def pythonium_object_get_attribute(obj, attr): r = lookup(obj, attr) if r != None: return r else: getattr = lookup(obj, '__getattr__') if getattr: return getattr(attr) else: console.trace('AttributeError', attr, obj) raise AttributeError pythonium_object_get_attribute.is_method = True object.__getattribute__ = pythonium_object_get_attribute def pythonium_get_attribute(obj, attr): if obj.__class__ or obj.__metaclass__: getattribute = lookup(obj, '__getattribute__') r = getattribute(attr) return r attr = obj[attr] if attr: if {}.toString.call(attr) == '[object Function]': def method_wrapper(): return attr.apply(obj, arguments) return method_wrapper else: return attr def pythonium_set_attribute(obj, attr, value): obj[attr] = value def ASSERT(condition, message): if not condition: raise message or pythonium_call(str, 'Assertion failed')
skariel/pythonium
pythonium/compliant/runtime.py
Python
lgpl-2.1
7,045
// 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. // // Copyright (c) 2007, 2008 Novell, Inc. // // Authors: // Andreia Gaita (avidigal@novell.com) // using System; using System.Text; using System.Runtime.InteropServices; using System.Collections; using System.Collections.Specialized; using Mono.WebBrowser.DOM; namespace Mono.WebBrowser { public interface IWebBrowser { /// <summary> /// Initialize a browser instance. /// </summary> /// <param name="handle"> /// A <see cref="IntPtr"/> to the native window handle of the widget /// where the browser engine will draw /// </param> /// <param name="width"> /// A <see cref="System.Int32"/>. Initial width /// </param> /// <param name="height"> /// A <see cref="System.Int32"/>. Initial height /// </param> /// <returns> /// A <see cref="System.Boolean"/> /// </returns> bool Load (IntPtr handle, int width, int height); void Shutdown (); void FocusIn (FocusOption focus); void FocusOut (); void Activate (); void Deactivate (); void Resize (int width, int height); void Render (byte[] data); void Render (string html); void Render (string html, string uri, string contentType); void ExecuteScript (string script); bool Initialized { get; } IWindow Window { get; } IDocument Document { get; } bool Offline {get; set;} /// <value> /// Object exposing navigation methods like Go, Back, etc. /// </value> INavigation Navigation { get; } event NodeEventHandler KeyDown; event NodeEventHandler KeyPress; event NodeEventHandler KeyUp; event NodeEventHandler MouseClick; event NodeEventHandler MouseDoubleClick; event NodeEventHandler MouseDown; event NodeEventHandler MouseEnter; event NodeEventHandler MouseLeave; event NodeEventHandler MouseMove; event NodeEventHandler MouseUp; event EventHandler Focus; event CreateNewWindowEventHandler CreateNewWindow; event AlertEventHandler Alert; event LoadStartedEventHandler LoadStarted; event LoadCommitedEventHandler LoadCommited; event ProgressChangedEventHandler ProgressChanged; event LoadFinishedEventHandler LoadFinished; event StatusChangedEventHandler StatusChanged; event SecurityChangedEventHandler SecurityChanged; event ContextMenuEventHandler ContextMenuShown; event NavigationRequestedEventHandler NavigationRequested; } public enum ReloadOption : uint { None = 0, Proxy = 1, Full = 2 } public enum FocusOption { None = 0, FocusFirstElement = 1, FocusLastElement = 2 } [Flags] public enum DialogButtonFlags { BUTTON_POS_0 = 1, BUTTON_POS_1 = 256, BUTTON_POS_2 = 65536, BUTTON_TITLE_OK = 1, BUTTON_TITLE_CANCEL = 2, BUTTON_TITLE_YES = 3, BUTTON_TITLE_NO = 4, BUTTON_TITLE_SAVE = 5, BUTTON_TITLE_DONT_SAVE = 6, BUTTON_TITLE_REVERT = 7, BUTTON_TITLE_IS_STRING = 127, BUTTON_POS_0_DEFAULT = 0, BUTTON_POS_1_DEFAULT = 16777216, BUTTON_POS_2_DEFAULT = 33554432, BUTTON_DELAY_ENABLE = 67108864, STD_OK_CANCEL_BUTTONS = 513 } public enum DialogType { Alert = 1, AlertCheck = 2, Confirm = 3, ConfirmEx = 4, ConfirmCheck = 5, Prompt = 6, PromptUsernamePassword = 7, PromptPassword = 8, Select = 9 } public enum Platform { Unknown = 0, Winforms = 1, Gtk = 2 } public enum SecurityLevel { Insecure= 1, Mixed = 2, Secure = 3 } #region Window Events public delegate bool CreateNewWindowEventHandler (object sender, CreateNewWindowEventArgs e); public class CreateNewWindowEventArgs : EventArgs { private bool isModal; #region Public Constructors public CreateNewWindowEventArgs (bool isModal) : base () { this.isModal = isModal; } #endregion // Public Constructors #region Public Instance Properties public bool IsModal { get { return this.isModal; } } #endregion // Public Instance Properties } #endregion #region Script events public delegate void AlertEventHandler (object sender, AlertEventArgs e); public class AlertEventArgs : EventArgs { private DialogType type; private string title; private string text; private string text2; private string username; private string password; private string checkMsg; private bool checkState; private DialogButtonFlags dialogButtons; private StringCollection buttons; private StringCollection options; private object returnValue; #region Public Constructors /// <summary> /// void (STDCALL *OnAlert) (const PRUnichar * title, const PRUnichar * text); /// </summary> /// <param name="title"></param> /// <param name="text"></param> public AlertEventArgs () : base () { } #endregion // Public Constructors #region Public Instance Properties public DialogType Type { get { return this.type; } set { this.type = value; } } public string Title { get { return this.title; } set { this.title = value; } } public string Text { get { return this.text; } set { this.text = value; } } public string Text2 { get { return this.text2; } set { this.text2 = value; } } public string CheckMessage { get { return this.checkMsg; } set { this.checkMsg = value; } } public bool CheckState { get { return this.checkState; } set { this.checkState = value; } } public DialogButtonFlags DialogButtons { get { return this.dialogButtons; } set { this.dialogButtons = value; } } public StringCollection Buttons { get { return buttons; } set { buttons = value; } } public StringCollection Options { get { return options; } set { options = value; } } public string Username { get { return username; } set { username = value; } } public string Password { get { return password; } set { password = value; } } public bool BoolReturn { get { if (returnValue is bool) return (bool) returnValue; return false; } set { returnValue = value; } } public int IntReturn { get { if (returnValue is int) return (int) returnValue; return -1; } set { returnValue = value; } } public string StringReturn { get { if (returnValue is string) return (string) returnValue; return String.Empty; } set { returnValue = value; } } #endregion } #endregion #region Loading events public delegate void StatusChangedEventHandler (object sender, StatusChangedEventArgs e); public class StatusChangedEventArgs : EventArgs { private string message; public string Message { get { return message; } set { message = value; } } private int status; public int Status { get { return status; } set { status = value; } } public StatusChangedEventArgs (string message, int status) { this.message = message; this.status = status; } } public delegate void ProgressChangedEventHandler (object sender, ProgressChangedEventArgs e); public class ProgressChangedEventArgs : EventArgs { private int progress; public int Progress { get { return progress; } } private int maxProgress; public int MaxProgress { get { return maxProgress; } } public ProgressChangedEventArgs (int progress, int maxProgress) { this.progress = progress; this.maxProgress = maxProgress; } } public delegate void LoadStartedEventHandler (object sender, LoadStartedEventArgs e); public class LoadStartedEventArgs : System.ComponentModel.CancelEventArgs { private string uri; public string Uri { get {return uri;} } private string frameName; public string FrameName { get {return frameName;} } public LoadStartedEventArgs (string uri, string frameName) { this.uri = uri; this.frameName = frameName; } } public delegate void LoadCommitedEventHandler (object sender, LoadCommitedEventArgs e); public class LoadCommitedEventArgs : EventArgs { private string uri; public string Uri { get {return uri;} } public LoadCommitedEventArgs (string uri) { this.uri = uri; } } public delegate void LoadFinishedEventHandler (object sender, LoadFinishedEventArgs e); public class LoadFinishedEventArgs : EventArgs { private string uri; public string Uri { get {return uri;} } public LoadFinishedEventArgs (string uri) { this.uri = uri; } } public delegate void SecurityChangedEventHandler (object sender, SecurityChangedEventArgs e); public class SecurityChangedEventArgs : EventArgs { private SecurityLevel state; public SecurityLevel State { get { return state; } set { state = value; } } public SecurityChangedEventArgs (SecurityLevel state) { this.state = state; } } public delegate void ContextMenuEventHandler (object sender, ContextMenuEventArgs e); public class ContextMenuEventArgs : EventArgs { private int x; private int y; public int X { get { return x; } } public int Y { get { return y; } } public ContextMenuEventArgs (int x, int y) { this.x = x; this.y = y; } } public delegate void NavigationRequestedEventHandler (object sender, NavigationRequestedEventArgs e); public class NavigationRequestedEventArgs : System.ComponentModel.CancelEventArgs { private string uri; public string Uri { get {return uri;} } public NavigationRequestedEventArgs (string uri) { this.uri = uri; } } #endregion }
edwinspire/VSharp
class/Mono.WebBrowser/Mono.WebBrowser/IWebBrowser.cs
C#
lgpl-3.0
10,333
/* * @BEGIN LICENSE * * Psi4: an open-source quantum chemistry software package * * Copyright (c) 2007-2019 The Psi4 Developers. * * The copyrights for code used from other parties are included in * the corresponding files. * * This file is part of Psi4. * * Psi4 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, version 3. * * Psi4 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 Psi4; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * @END LICENSE */ #include "slater_determinant.h" namespace psi { // SlaterDeterminant::SlaterDeterminant() //{ // startup(); //} // SlaterDeterminant::SlaterDeterminant(SlaterDeterminant& det) //{ // alfa_sym = det.alfa_sym; // beta_sym = det.beta_sym; // alfa_string = det.alfa_string; // beta_string = det.beta_string; // alfa_bits = det.alfa_bits; // beta_bits = det.beta_bits; // startup(); //} SlaterDeterminant::SlaterDeterminant(int alfa_sym_, int beta_sym_, std::vector<bool> alfa_bits_, std::vector<bool> beta_bits_) : alfa_sym(alfa_sym_), beta_sym(beta_sym_), alfa_string(-1), beta_string(-1), alfa_bits(alfa_bits_), beta_bits(beta_bits_) { startup(); } SlaterDeterminant::~SlaterDeterminant() { cleanup(); } void SlaterDeterminant::startup() {} void SlaterDeterminant::cleanup() {} bool SlaterDeterminant::is_closed_shell() { return (alfa_bits == beta_bits); } std::string SlaterDeterminant::get_label() { std::string label; label = "|"; int max_i = alfa_bits.size(); for (int i = 0; i < max_i; ++i) label += get_occupation_symbol(i); label += ">"; return label; } char SlaterDeterminant::get_occupation_symbol(int i) { char symbol; if (alfa_bits[i] && beta_bits[i]) symbol = '2'; if (alfa_bits[i] && !beta_bits[i]) symbol = '+'; if (!alfa_bits[i] && beta_bits[i]) symbol = '-'; if (!alfa_bits[i] && !beta_bits[i]) symbol = '0'; return (symbol); } } // namespace psi
CDSherrill/psi4
psi4/src/psi4/libmoinfo/slater_determinant.cc
C++
lgpl-3.0
2,456
<?php $lang['install']['flag'] = 'en'; //en $lang['install']['i001'] = 'KimsQ Rb Installation'; //KimsQ Rb 설치 $lang['install']['i002'] = 'Select the version'; //설치할 패키지를 선택해주세요. *** 사이트 패키지와 용어 혼동 $lang['install']['i003'] = 'Do not refresh this page. It will automatically move on to the next step after the downloading. The time of downloading depends on your network environment.';//다운로드 완료 후 자동으로 다음단계로 이동되니 새로고침 하지 마세요.네트웍 상태에 따라 다운로드에 수초가 소요될수 있습니다. $lang['install']['i004'] = 'Start Installation';//설치하기 *** 실제 설치는 모든 정보를 입력 후 이루어짐. 마지막 Next 버튼이 Install Now가 되어야 함. $lang['install']['i005'] = 'You can also install KimsQ Rb by uploading its files directly.'; //또는 패키지 파일을 업로드해 주세요. $lang['install']['i006'] = 'Browse a (zip) file'; //파일 찾기 *** zip 파일만 허용하는 경우 괄호 해제 $lang['install']['i007'] = 'KimsQ Installer'; //킴스큐 인스톨러 $lang['install']['i008'] = 'Agreement'; //사용조건 동의 $lang['install']['i009'] = 'Set Database'; //데이터베이스 $lang['install']['i010'] = 'Create Admin'; //사용자 등록 *** 사실상 일반 사용자가 아닌 관리자 계정이므로. Regist는 없는 단어. $lang['install']['i011'] = 'Create Site'; //사이트 생성 $lang['install']['i012'] = 'License Agreement'; //사용조건 동의 $lang['install']['i013'] = 'Open Source Software License'; //오픈소스 소프트웨어 라이선스 $lang['install']['i014'] = 'I agree to the license above.'; //위의 라이선스 정책에 동의 합니다. $lang['install']['i015'] = 'Database Information'; //'Database settings'; //데이터베이스 설정 *** DB를 설정하는 게 아님, 설정된 DB의 정보를 입력하는 것 $lang['install']['i016'] = 'Basic Info'; //기본정보 $lang['install']['i017'] = 'Advanced Options'; //고급옵션 $lang['install']['i018'] = 'DBMS'; //'DB kind'; //DB종류 (type) $lang['install']['i019'] = 'DB name'; //DB명 (name) $lang['install']['i020'] = 'Username'; //유저 (username) $lang['install']['i021'] = 'Password'; //암호 (password) $lang['install']['i022'] = 'Type your database information. Installation will be finished successfully only with the correct information.'; //데이터베이스(MySQL) 정보를 정확히 입력해 주십시오. 입력된 정보가 정확해야만 정상적으로 설치가 진행됩니다. *** 입력을 아무렇게나 해도 사실 next step으로는 갈 수 있음. 마지막에 설치가 안 될 뿐. 키보드로 입력하라고 할 때는 input은 어색, type이 자연스러움. $lang['install']['i023'] = 'DB Host'; //호스트 (Host) $lang['install']['i024'] = 'Change this if your DB is running on the remote server'; //데이터베이스가 다른 서버에 있다면 이 설정을 바꾸십시오. $lang['install']['i025'] = 'DB Port'; //포트 (Port) $lang['install']['i026'] = 'Change this if the port of your DB server is different'; //DB서버의 포트가 기본 포트가 아닐 경우 변경하십시오. $lang['install']['i027'] = 'Table Prefix'; //접두어 (Prefix) $lang['install']['i028'] = 'Change this if you want to install more than one KimsQ Rb on your server'; //단일 DB에 킴스큐 복수설치를 원하시면 변경해 주십시오. $lang['install']['i029'] = 'DB Engine'; //형식 (Engine) $lang['install']['i030'] = 'MyISAM is the basic engine'; //기본엔진은 MyISAM 입니다. $lang['install']['i031'] = 'These options are needed only for the specific cases. Do not change if you do not know what to do, or ask your hosting provider'; //이 선택사항은 일부 경우에만 필요합니다.무엇을 입력해야할지 모를경우 그대로 두거나 호스팅 제공자에게 문의하십시오. $lang['install']['i032'] = 'User Registration'; //사용자 등록 $lang['install']['i033'] = 'Basic Info'; //기본정보 $lang['install']['i034'] = 'Extra Info'; //추가정보 $lang['install']['i035'] = 'Name'; //이름 $lang['install']['i036'] = 'Email'; //이메일 $lang['install']['i037'] = 'ID (Username)'; //아이디 $lang['install']['i038'] = '4 to 12 lowercase letters or numbers'; //영문소문자+숫자 4~12자 이내 $lang['install']['i039'] = 'Password'; //패스워드 $lang['install']['i040'] = 'Retype'; //패스워드 확인 $lang['install']['i041'] = 'Nickname'; //닉네임 $lang['install']['i042'] = 'Sex'; //성별 $lang['install']['i043'] = 'Male'; //남성 $lang['install']['i044'] = 'Female'; //여성 *** 워드로 열어서 맞춤법 검사 정도는... $lang['install']['i045'] = 'Birthday'; //생년월일 $lang['install']['i046'] = 'Lunar'; //음력생일 $lang['install']['i047'] = 'Phone'; //연락처 $lang['install']['i048'] = 'Create an administrator account. You can add more detail in the profile page after installation.'; //입력된 정보로 신규 회원등록이 이루어지며 최고관리자 권한이 부여됩니다. 관리자 부가정보는 설치 후 프로필페이지 추가로 등록할 수 있습니다. $lang['install']['i049'] = 'Create a site'; //사이트 생성 $lang['install']['i050'] = 'Site Name'; //사이트명 $lang['install']['i051'] = 'Type the name of your first site'; //이 사이트의 명칭을 입력해 주세요. $lang['install']['i052'] = 'Site Code'; //사이트 코드 $lang['install']['i053'] = 'Site Code makes the site recognizable among multiple sites.'; //이 사이트를 구분하기 위한 코드입니다. *** 설치 후 사이트는 하나인데 others라고 하기엔 어색함. $lang['install']['i054'] = 'sitecode'; //사이트코드 $lang['install']['i055'] = 'Using Permalink'; //고유주소(Permalink) 사용 $lang['install']['i056'] = 'Check if you want to have shortened URLs. (PHP rewrite_mod necessarily loaded)'; //주소를 짧게 줄일 수 있습니다.(서버에서 rewrite_mod 허용시) $lang['install']['i057'] = 'This is the last step. After installation, you can create a navigation bar and pages, or apply a site package to build your own website at once.'; //사이트명 입력 후 다음버튼을 클릭하면 킴스큐 설치가 진행됩니다.설치가 완료된 후에는 메뉴와 페이지를 만들거나 사이트 패키지를 이용하세요. $lang['install']['i058'] = 'Previous'; //이전 $lang['install']['i059'] = 'Next'; //다음 *** 마지막 Next 버튼은 Install Now가 되어야 함. $lang['install']['i060'] = 'Install this version?'; //정말로 선택하신 버젼을 설치하시겠습니까? $lang['install']['i061'] = 'Connecting to KimsQ Rb server...'; //KimsQ Rb 다운로드중.. *** 실제 다운로드 메시지는 i062 $lang['install']['i062'] = 'Now downloading from the server...'; //서버에서 다운로드 받고 있습니다... $lang['install']['i063'] = 'We are sorry. The selected version is not available now.'; //죄송합니다. 선택하신 버젼은 아직 다운로드 받으실 수 없습니다. $lang['install']['i064'] = 'We are sorry. The selected file is not KimsQ Rb.'; //죄송합니다. 킴스큐 패키지가 아닙니다. $lang['install']['i065'] = 'You do not have proper permissions for the destination folder.\nTry again after changing the permission to 707'; //설치폴더의 쓰기권한이 없습니다.\n퍼미션을 707로 변경 후 다시 시도해 주세요. $lang['install']['i066'] = 'Uploading KimsQ Rb...'; //KimsQ Rb 업로드중.. *** 말줄임표 $lang['install']['i067'] = 'Unzipping installation file on the server...'; //서버에서 패키지 압축을 풀고 있습니다... *** 사이트 패키지와 혼동 $lang['install']['i068'] = 'DB Host is required.'; //DB호스트를 입력해 주세요. $lang['install']['i069'] = 'DB Name is required.'; //DB명을 입력해 주세요. $lang['install']['i070'] = 'DB Username is required.'; //DB사용자를 입력해 주세요. $lang['install']['i071'] = 'DB Password is required.'; //DB 패스워드를 입력해 주세요. $lang['install']['i072'] = 'DB Port number is required'; //DB 포트번호를 입력해 주세요. $lang['install']['i073'] = 'Table Prefix is required and cannot be empty'; //DB 접두어를 정확히 입력해 주세요. $lang['install']['i074'] = 'Administrator account`s name is required.'; //이름을 입력해 주세요. $lang['install']['i075'] = 'Administrator`s email address is required.'; //이메일주소를 정확히 입력해 주세요. $lang['install']['i076'] = 'Administrator`s id is required.'; //아이디를 정확히 입력해 주세요. $lang['install']['i077'] = 'Administrator`s password is required.'; //패스워드를 입력해 주세요. $lang['install']['i078'] = 'Fill the both of two blanks for Administrator`s password.'; //패스워드를 다시한번 입력해 주세요. *** 두번째 패스워드 칸이 비었을 경우, 그냥 다시 입력하라는 설명은 너무 모호함 $lang['install']['i079'] = 'The both passwords are not identical.'; //패스워드가 일치하지 않습니다. $lang['install']['i080'] = 'Installing KimsQ Rb now. Please wait a second.'; //설치중입니다. 잠시만 기다려 주세요. $lang['install']['i081'] = 'Type Site Name, please.'; //사이트명을 입력해 주세요. $lang['install']['i082'] = 'Type Site Code, please.'; //사이트 코드를 정확히 입력해 주세요. $lang['install']['i083'] = 'Start the installation with the typed information?'; //정말로 설치하시겠습니까? ?>
kieregh/rb
_install/language/english/lang.install.php
PHP
lgpl-3.0
9,586
/* * Copyright (C) 2014-2015 Vote Rewarding System * * This file is part of Vote Rewarding System. * * Vote Rewarding System 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. * * Vote Rewarding System is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.github.unafraid.votingreward.interfaceprovider.model; /** * @author UnAfraid */ public class RewardItemHolder { private final int _id; private final long _count; public RewardItemHolder(int id, long count) { _id = id; _count = count; } /** * @return the ID of the item contained in this object */ public int getId() { return _id; } /** * @return the count of items contained in this object */ public long getCount() { return _count; } }
UnAfraid/topzone
VotingRewardInterfaceProvider/src/main/java/com/github/unafraid/votingreward/interfaceprovider/model/RewardItemHolder.java
Java
lgpl-3.0
1,261
{ 'name': 'Control access to Apps', 'version': '1.0.0', 'author': 'IT-Projects LLC, Ivan Yelizariev', 'category': 'Tools', 'website': 'https://twitter.com/yelizariev', 'price': 10.00, 'currency': 'EUR', 'depends': [ 'access_restricted' ], 'data': [ 'security/access_apps_security.xml', 'security/ir.model.access.csv', ], 'installable': True }
ufaks/addons-yelizariev
access_apps/__openerp__.py
Python
lgpl-3.0
415
""" Classes for interacting with the tor control socket. Controllers are a wrapper around a ControlSocket, retaining many of its methods (connect, close, is_alive, etc) in addition to providing its own for interacting at a higher level. **Module Overview:** :: from_port - Provides a Controller based on a port connection. from_socket_file - Provides a Controller based on a socket file connection. Controller - General controller class intended for direct use. +- get_info - issues a GETINFO query BaseController - Base controller class asynchronous message handling. |- msg - communicates with the tor process |- is_alive - reports if our connection to tor is open or closed |- connect - connects or reconnects to tor |- close - shuts down our connection to the tor process |- get_socket - provides the socket used for control communication |- add_status_listener - notifies a callback of changes in our status |- remove_status_listener - prevents further notification of status changes +- __enter__ / __exit__ - manages socket connection """ import time import Queue import threading import stem.response import stem.socket import stem.util.log as log # state changes a control socket can have # INIT - new control connection # RESET - received a reset/sighup signal # CLOSED - control connection closed State = stem.util.enum.Enum("INIT", "RESET", "CLOSED") # Constant to indicate an undefined argument default. Usually we'd use None for # this, but users will commonly provide None as the argument so need something # else fairly unique... UNDEFINED = "<Undefined_ >" class BaseController: """ Controller for the tor process. This is a minimal base class for other controllers, providing basic process communication and event listing. Don't use this directly - subclasses like the Controller provide higher level functionality. Do not continue to directly interacte with the ControlSocket we're constructed from - use our wrapper methods instead. """ def __init__(self, control_socket): self._socket = control_socket self._msg_lock = threading.RLock() self._status_listeners = [] # tuples of the form (callback, spawn_thread) self._status_listeners_lock = threading.RLock() # queues where incoming messages are directed self._reply_queue = Queue.Queue() self._event_queue = Queue.Queue() # thread to continually pull from the control socket self._reader_thread = None # thread to pull from the _event_queue and call handle_event self._event_notice = threading.Event() self._event_thread = None # saves our socket's prior _connect() and _close() methods so they can be # called along with ours self._socket_connect = self._socket._connect self._socket_close = self._socket._close self._socket._connect = self._connect self._socket._close = self._close if self._socket.is_alive(): self._launch_threads() def msg(self, message): """ Sends a message to our control socket and provides back its reply. :param str message: message to be formatted and sent to tor :returns: :class:`stem.response.ControlMessage` with the response :raises: * :class:`stem.socket.ProtocolError` the content from the socket is malformed * :class:`stem.socket.SocketError` if a problem arises in using the socket * :class:`stem.socket.SocketClosed` if the socket is shut down """ with self._msg_lock: # If our _reply_queue isn't empty then one of a few things happened... # # - Our connection was closed and probably re-restablished. This was # in reply to pulling for an asynchronous event and getting this is # expected - ignore it. # # - Pulling for asynchronous events produced an error. If this was a # ProtocolError then it's a tor bug, and if a non-closure SocketError # then it was probably a socket glitch. Deserves an INFO level log # message. # # - This is a leftover response for a msg() call. We can't tell who an # exception was airmarked for, so we only know that this was the case # if it's a ControlMessage. This should not be possable and indicates # a stem bug. This deserves a NOTICE level log message since it # indicates that one of our callers didn't get their reply. while not self._reply_queue.empty(): try: response = self._reply_queue.get_nowait() if isinstance(response, stem.socket.SocketClosed): pass # this is fine elif isinstance(response, stem.socket.ProtocolError): log.info("Tor provided a malformed message (%s)" % response) elif isinstance(response, stem.socket.ControllerError): log.info("Socket experienced a problem (%s)" % response) elif isinstance(response, stem.response.ControlMessage): log.notice("BUG: the msg() function failed to deliver a response: %s" % response) except Queue.Empty: # the empty() method is documented to not be fully reliable so this # isn't entirely surprising break try: self._socket.send(message) response = self._reply_queue.get() # If the message we received back had an exception then re-raise it to the # caller. Otherwise return the response. if isinstance(response, stem.socket.ControllerError): raise response else: return response except stem.socket.SocketClosed, exc: # If the recv() thread caused the SocketClosed then we could still be # in the process of closing. Calling close() here so that we can # provide an assurance to the caller that when we raise a SocketClosed # exception we are shut down afterward for realz. self.close() raise exc def is_alive(self): """ Checks if our socket is currently connected. This is a passthrough for our socket's is_alive() method. :returns: bool that's True if we're shut down and False otherwise """ return self._socket.is_alive() def connect(self): """ Reconnects our control socket. This is a passthrough for our socket's connect() method. :raises: :class:`stem.socket.SocketError` if unable to make a socket """ self._socket.connect() def close(self): """ Closes our socket connection. This is a passthrough for our socket's :func:`stem.socket.ControlSocket.close` method. """ self._socket.close() def get_socket(self): """ Provides the socket used to speak with the tor process. Communicating with the socket directly isn't advised since it may confuse the controller. :returns: :class:`stem.socket.ControlSocket` we're communicating with """ return self._socket def add_status_listener(self, callback, spawn = True): """ Notifies a given function when the state of our socket changes. Functions are expected to be of the form... :: my_function(controller, state, timestamp) The state is a value from stem.socket.State, functions **must** allow for new values in this field. The timestamp is a float for the unix time when the change occured. This class only provides ``State.INIT`` and ``State.CLOSED`` notifications. Subclasses may provide others. If spawn is True then the callback is notified via a new daemon thread. If false then the notice is under our locks, within the thread where the change occured. In general this isn't advised, especially if your callback could block for a while. :param function callback: function to be notified when our state changes :param bool spawn: calls function via a new thread if True, otherwise it's part of the connect/close method call """ with self._status_listeners_lock: self._status_listeners.append((callback, spawn)) def remove_status_listener(self, callback): """ Stops listener from being notified of further events. :param function callback: function to be removed from our listeners :returns: bool that's True if we removed one or more occurances of the callback, False otherwise """ with self._status_listeners_lock: new_listeners, is_changed = [], False for listener, spawn in self._status_listeners: if listener != callback: new_listeners.append((listener, spawn)) else: is_changed = True self._status_listeners = new_listeners return is_changed def __enter__(self): return self def __exit__(self, exit_type, value, traceback): self.close() def _handle_event(self, event_message): """ Callback to be overwritten by subclasses for event listening. This is notified whenever we receive an event from the control socket. :param stem.response.ControlMessage event_message: message received from the control socket """ pass def _connect(self): self._launch_threads() self._notify_status_listeners(State.INIT, True) self._socket_connect() def _close(self): # Our is_alive() state is now false. Our reader thread should already be # awake from recv() raising a closure exception. Wake up the event thread # too so it can end. self._event_notice.set() # joins on our threads if it's safe to do so for t in (self._reader_thread, self._event_thread): if t and t.is_alive() and threading.current_thread() != t: t.join() self._notify_status_listeners(State.CLOSED, False) self._socket_close() def _notify_status_listeners(self, state, expect_alive = None): """ Informs our status listeners that a state change occured. States imply that our socket is either alive or not, which may not hold true when multiple events occure in quick succession. For instance, a sighup could cause two events (``State.RESET`` for the sighup and ``State.CLOSE`` if it causes tor to crash). However, there's no guarentee of the order in which they occure, and it would be bad if listeners got the ``State.RESET`` last, implying that we were alive. If set, the expect_alive flag will discard our event if it conflicts with our current :func:`stem.control.BaseController.is_alive` state. :param stem.socket.State state: state change that has occured :param bool expect_alive: discard event if it conflicts with our :func:`stem.control.BaseController.is_alive` state """ # Any changes to our is_alive() state happen under the send lock, so we # need to have it to ensure it doesn't change beneath us. with self._socket._get_send_lock(), self._status_listeners_lock: change_timestamp = time.time() if expect_alive != None and expect_alive != self.is_alive(): return for listener, spawn in self._status_listeners: if spawn: name = "%s notification" % state args = (self, state, change_timestamp) notice_thread = threading.Thread(target = listener, args = args, name = name) notice_thread.setDaemon(True) notice_thread.start() else: listener(self, state, change_timestamp) def _launch_threads(self): """ Initializes daemon threads. Threads can't be reused so we need to recreate them if we're restarted. """ # In theory concurrent calls could result in multple start() calls on a # single thread, which would cause an unexpeceted exception. Best be safe. with self._socket._get_send_lock(): if not self._reader_thread or not self._reader_thread.is_alive(): self._reader_thread = threading.Thread(target = self._reader_loop, name = "Tor Listener") self._reader_thread.setDaemon(True) self._reader_thread.start() if not self._event_thread or not self._event_thread.is_alive(): self._event_thread = threading.Thread(target = self._event_loop, name = "Event Notifier") self._event_thread.setDaemon(True) self._event_thread.start() def _reader_loop(self): """ Continually pulls from the control socket, directing the messages into queues based on their type. Controller messages come in two varieties... * Responses to messages we've sent (GETINFO, SETCONF, etc). * Asynchronous events, identified by a status code of 650. """ while self.is_alive(): try: control_message = self._socket.recv() if control_message.content()[-1][0] == "650": # asynchronous message, adds to the event queue and wakes up its handler self._event_queue.put(control_message) self._event_notice.set() else: # response to a msg() call self._reply_queue.put(control_message) except stem.socket.ControllerError, exc: # Assume that all exceptions belong to the reader. This isn't always # true, but the msg() call can do a better job of sorting it out. # # Be aware that the msg() method relies on this to unblock callers. self._reply_queue.put(exc) def _event_loop(self): """ Continually pulls messages from the _event_queue and sends them to our handle_event callback. This is done via its own thread so subclasses with a lengthy handle_event implementation don't block further reading from the socket. """ while True: try: event_message = self._event_queue.get_nowait() self._handle_event(event_message) except Queue.Empty: if not self.is_alive(): break self._event_notice.wait() self._event_notice.clear() class Controller(BaseController): """ Communicates with a control socket. This is built on top of the BaseController and provides a more user friendly API for library users. """ def from_port(control_addr = "127.0.0.1", control_port = 9051): """ Constructs a ControlPort based Controller. :param str control_addr: ip address of the controller :param int control_port: port number of the controller :returns: :class:`stem.control.Controller` attached to the given port :raises: :class:`stem.socket.SocketError` if we're unable to establish a connection """ control_port = stem.socket.ControlPort(control_addr, control_port) return Controller(control_port) def from_socket_file(socket_path = "/var/run/tor/control"): """ Constructs a ControlSocketFile based Controller. :param str socket_path: path where the control socket is located :returns: :class:`stem.control.Controller` attached to the given socket file :raises: :class:`stem.socket.SocketError` if we're unable to establish a connection """ control_socket = stem.socket.ControlSocketFile(socket_path) return Controller(control_socket) from_port = staticmethod(from_port) from_socket_file = staticmethod(from_socket_file) def get_info(self, param, default = UNDEFINED): """ Queries the control socket for the given GETINFO option. If provided a default then that's returned if the GETINFO option is undefined or the call fails for any reason (error response, control port closed, initiated, etc). :param str,list param: GETINFO option or options to be queried :param object default: response if the query fails :returns: Response depends upon how we were called as follows... * str with the response if our param was a str * dict with the param => response mapping if our param was a list * default if one was provided and our call failed :raises: :class:`stem.socket.ControllerError` if the call fails, and we weren't provided a default response """ # TODO: add caching? # TODO: special geoip handling? # TODO: add logging, including call runtime if isinstance(param, str): is_multiple = False param = [param] else: is_multiple = True try: response = self.msg("GETINFO %s" % " ".join(param)) stem.response.convert("GETINFO", response) # error if we got back different parameters than we requested requested_params = set(param) reply_params = set(response.entries.keys()) if requested_params != reply_params: requested_label = ", ".join(requested_params) reply_label = ", ".join(reply_params) raise stem.socket.ProtocolError("GETINFO reply doesn't match the parameters that we requested. Queried '%s' but got '%s'." % (requested_label, reply_label)) if is_multiple: return response.entries else: return response.entries[param[0]] except stem.socket.ControllerError, exc: if default == UNDEFINED: raise exc else: return default
meganchang/Stem
stem/control.py
Python
lgpl-3.0
17,273
/* ========================================================================= * This file is part of xml.lite-c++ * ========================================================================= * * (C) Copyright 2004 - 2014, MDA Information Systems LLC * (C) Copyright 2022, Maxar Technologies, Inc. * * xml.lite-c++ is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; If not, * see <http://www.gnu.org/licenses/>. * */ #include <xml/lite/ValidatorInterface.h> #include <algorithm> #include <iterator> #include <std/filesystem> #include <std/memory> #include <sys/OS.h> #include <io/StringStream.h> #include <mem/ScopedArray.h> #include <str/EncodedStringView.h> namespace fs = std::filesystem; #include <xml/lite/xml_lite_config.h> template<typename TStringStream> bool vallidate_(const xml::lite::ValidatorInterface& validator, io::InputStream& xml, TStringStream&& oss, const std::string& xmlID, std::vector<xml::lite::ValidationInfo>& errors) { xml.streamTo(oss); return validator.validate(oss.stream().str(), xmlID, errors); } bool xml::lite::ValidatorInterface::validate( io::InputStream& xml, StringEncoding encoding, const std::string& xmlID, std::vector<ValidationInfo>& errors) const { // convert to the correcrt std::basic_string<T> based on "encoding" if (encoding == StringEncoding::Utf8) { return vallidate_(*this, xml, io::U8StringStream(), xmlID, errors); } if (encoding == StringEncoding::Windows1252) { return vallidate_(*this, xml, io::W1252StringStream(), xmlID, errors); } // this really shouldn't happen return validate(xml, xmlID, errors); }
mdaus/coda-oss
modules/c++/xml.lite/source/ValidatorInterface.cpp
C++
lgpl-3.0
2,255
// System.Net.Sockets.SocketAsyncEventArgs.cs // // Authors: // Marek Habersack (mhabersack@novell.com) // // Copyright (c) 2008 Novell, Inc. (http://www.novell.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace System.Net.Sockets { public class SendPacketsElement { public byte[] Buffer { get; private set; } public int Count { get; private set; } public bool EndOfPacket { get; private set; } public string FilePath { get; private set; } public int Offset { get; private set; } public SendPacketsElement (byte[] buffer) : this (buffer, 0, buffer != null ? buffer.Length : 0) { } public SendPacketsElement (byte[] buffer, int offset, int count) : this (buffer, offset, count, false) { } public SendPacketsElement (byte[] buffer, int offset, int count, bool endOfPacket) { if (buffer == null) throw new ArgumentNullException ("buffer"); int buflen = buffer.Length; if (offset < 0 || offset >= buflen) throw new ArgumentOutOfRangeException ("offset"); if (count < 0 || offset + count >= buflen) throw new ArgumentOutOfRangeException ("count"); Buffer = buffer; Offset = offset; Count = count; EndOfPacket = endOfPacket; FilePath = null; } public SendPacketsElement (string filepath) : this (filepath, 0, 0, false) { } public SendPacketsElement (string filepath, int offset, int count) : this (filepath, offset, count, false) { } // LAME SPEC: only ArgumentNullException for filepath is thrown public SendPacketsElement (string filepath, int offset, int count, bool endOfPacket) { if (filepath == null) throw new ArgumentNullException ("filepath"); Buffer = null; Offset = offset; Count = count; EndOfPacket = endOfPacket; FilePath = filepath; } } }
edwinspire/VSharp
class/System/System.Net.Sockets/SendPacketsElement.cs
C#
lgpl-3.0
2,838
// Authors: // Francis Fisher (frankie@terrorise.me.uk) // // (C) Francis Fisher 2013 // // 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. namespace System.Windows.Forms.DataVisualization.Charting { public class CustomizeLegendEventArgs : EventArgs { public LegendItemsCollection LegendItems { get; private set; } public string LegendName { get; private set; } } }
edwinspire/VSharp
class/System.Windows.Forms.DataVisualization/System.Windows.Forms.DataVisualization.Charting/CustomizeLegendEventArgs.cs
C#
lgpl-3.0
1,400
function main() { // Widget instantiation metadata... var widget = { id: "UploaderPlusAdmin", name: "SoftwareLoop.UploaderPlusAdmin", }; model.widgets = [widget]; } main();
sprouvez/uploader-plus
surf/src/main/amp/config/alfresco/web-extension/site-webscripts/uploader-plus/uploader-plus-admin.get.js
JavaScript
lgpl-3.0
204
# encoding: utf-8 """ Utilities for working with strings and text. """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import __main__ import os import re import shutil import sys import textwrap from string import Formatter from IPython.external.path import path from IPython.testing.skipdoctest import skip_doctest_py3, skip_doctest from IPython.utils import py3compat from IPython.utils.io import nlprint from IPython.utils.data import flatten #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- def unquote_ends(istr): """Remove a single pair of quotes from the endpoints of a string.""" if not istr: return istr if (istr[0]=="'" and istr[-1]=="'") or \ (istr[0]=='"' and istr[-1]=='"'): return istr[1:-1] else: return istr class LSString(str): """String derivative with a special access attributes. These are normal strings, but with the special attributes: .l (or .list) : value as list (split on newlines). .n (or .nlstr): original value (the string itself). .s (or .spstr): value as whitespace-separated string. .p (or .paths): list of path objects Any values which require transformations are computed only once and cached. Such strings are very useful to efficiently interact with the shell, which typically only understands whitespace-separated options for commands.""" def get_list(self): try: return self.__list except AttributeError: self.__list = self.split('\n') return self.__list l = list = property(get_list) def get_spstr(self): try: return self.__spstr except AttributeError: self.__spstr = self.replace('\n',' ') return self.__spstr s = spstr = property(get_spstr) def get_nlstr(self): return self n = nlstr = property(get_nlstr) def get_paths(self): try: return self.__paths except AttributeError: self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] return self.__paths p = paths = property(get_paths) # FIXME: We need to reimplement type specific displayhook and then add this # back as a custom printer. This should also be moved outside utils into the # core. # def print_lsstring(arg): # """ Prettier (non-repr-like) and more informative printer for LSString """ # print "LSString (.p, .n, .l, .s available). Value:" # print arg # # # print_lsstring = result_display.when_type(LSString)(print_lsstring) class SList(list): """List derivative with a special access attributes. These are normal lists, but with the special attributes: .l (or .list) : value as list (the list itself). .n (or .nlstr): value as a string, joined on newlines. .s (or .spstr): value as a string, joined on spaces. .p (or .paths): list of path objects Any values which require transformations are computed only once and cached.""" def get_list(self): return self l = list = property(get_list) def get_spstr(self): try: return self.__spstr except AttributeError: self.__spstr = ' '.join(self) return self.__spstr s = spstr = property(get_spstr) def get_nlstr(self): try: return self.__nlstr except AttributeError: self.__nlstr = '\n'.join(self) return self.__nlstr n = nlstr = property(get_nlstr) def get_paths(self): try: return self.__paths except AttributeError: self.__paths = [path(p) for p in self if os.path.exists(p)] return self.__paths p = paths = property(get_paths) def grep(self, pattern, prune = False, field = None): """ Return all strings matching 'pattern' (a regex or callable) This is case-insensitive. If prune is true, return all items NOT matching the pattern. If field is specified, the match must occur in the specified whitespace-separated field. Examples:: a.grep( lambda x: x.startswith('C') ) a.grep('Cha.*log', prune=1) a.grep('chm', field=-1) """ def match_target(s): if field is None: return s parts = s.split() try: tgt = parts[field] return tgt except IndexError: return "" if isinstance(pattern, basestring): pred = lambda x : re.search(pattern, x, re.IGNORECASE) else: pred = pattern if not prune: return SList([el for el in self if pred(match_target(el))]) else: return SList([el for el in self if not pred(match_target(el))]) def fields(self, *fields): """ Collect whitespace-separated fields from string list Allows quick awk-like usage of string lists. Example data (in var a, created by 'a = !ls -l'):: -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] (note the joining by space). a.fields(-1) is ['ChangeLog', 'IPython'] IndexErrors are ignored. Without args, fields() just split()'s the strings. """ if len(fields) == 0: return [el.split() for el in self] res = SList() for el in [f.split() for f in self]: lineparts = [] for fd in fields: try: lineparts.append(el[fd]) except IndexError: pass if lineparts: res.append(" ".join(lineparts)) return res def sort(self,field= None, nums = False): """ sort by specified fields (see fields()) Example:: a.sort(1, nums = True) Sorts a by second field, in numerical order (so that 21 > 3) """ #decorate, sort, undecorate if field is not None: dsu = [[SList([line]).fields(field), line] for line in self] else: dsu = [[line, line] for line in self] if nums: for i in range(len(dsu)): numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()]) try: n = int(numstr) except ValueError: n = 0; dsu[i][0] = n dsu.sort() return SList([t[1] for t in dsu]) # FIXME: We need to reimplement type specific displayhook and then add this # back as a custom printer. This should also be moved outside utils into the # core. # def print_slist(arg): # """ Prettier (non-repr-like) and more informative printer for SList """ # print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):" # if hasattr(arg, 'hideonce') and arg.hideonce: # arg.hideonce = False # return # # nlprint(arg) # # print_slist = result_display.when_type(SList)(print_slist) def esc_quotes(strng): """Return the input string with single and double quotes escaped out""" return strng.replace('"','\\"').replace("'","\\'") def qw(words,flat=0,sep=None,maxsplit=-1): """Similar to Perl's qw() operator, but with some more options. qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) words can also be a list itself, and with flat=1, the output will be recursively flattened. Examples: >>> qw('1 2') ['1', '2'] >>> qw(['a b','1 2',['m n','p q']]) [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] >>> qw(['a b','1 2',['m n','p q']],flat=1) ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ if isinstance(words, basestring): return [word.strip() for word in words.split(sep,maxsplit) if word and not word.isspace() ] if flat: return flatten(map(qw,words,[1]*len(words))) return map(qw,words) def qwflat(words,sep=None,maxsplit=-1): """Calls qw(words) in flat mode. It's just a convenient shorthand.""" return qw(words,1,sep,maxsplit) def qw_lol(indata): """qw_lol('a b') -> [['a','b']], otherwise it's just a call to qw(). We need this to make sure the modules_some keys *always* end up as a list of lists.""" if isinstance(indata, basestring): return [qw(indata)] else: return qw(indata) def grep(pat,list,case=1): """Simple minded grep-like function. grep(pat,list) returns occurrences of pat in list, None on failure. It only does simple string matching, with no support for regexps. Use the option case=0 for case-insensitive matching.""" # This is pretty crude. At least it should implement copying only references # to the original data in case it's big. Now it copies the data for output. out=[] if case: for term in list: if term.find(pat)>-1: out.append(term) else: lpat=pat.lower() for term in list: if term.lower().find(lpat)>-1: out.append(term) if len(out): return out else: return None def dgrep(pat,*opts): """Return grep() on dir()+dir(__builtins__). A very common use of grep() when working interactively.""" return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) def idgrep(pat): """Case-insensitive dgrep()""" return dgrep(pat,0) def igrep(pat,list): """Synonym for case-insensitive grep.""" return grep(pat,list,case=0) def indent(instr,nspaces=4, ntabs=0, flatten=False): """Indent a string a given number of spaces or tabstops. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. Parameters ---------- instr : basestring The string to be indented. nspaces : int (default: 4) The number of spaces to be indented. ntabs : int (default: 0) The number of tabs to be indented. flatten : bool (default: False) Whether to scrub existing indentation. If True, all lines will be aligned to the same indentation. If False, existing indentation will be strictly increased. Returns ------- str|unicode : string indented by ntabs and nspaces. """ if instr is None: return ind = '\t'*ntabs+' '*nspaces if flatten: pat = re.compile(r'^\s*', re.MULTILINE) else: pat = re.compile(r'^', re.MULTILINE) outstr = re.sub(pat, ind, instr) if outstr.endswith(os.linesep+ind): return outstr[:-len(ind)] else: return outstr def native_line_ends(filename,backup=1): """Convert (in-place) a file to line-ends native to the current OS. If the optional backup argument is given as false, no backup of the original file is left. """ backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} bak_filename = filename + backup_suffixes[os.name] original = open(filename).read() shutil.copy2(filename,bak_filename) try: new = open(filename,'wb') new.write(os.linesep.join(original.splitlines())) new.write(os.linesep) # ALWAYS put an eol at the end of the file new.close() except: os.rename(bak_filename,filename) if not backup: try: os.remove(bak_filename) except: pass def list_strings(arg): """Always return a list of strings, given a string or list of strings as input. :Examples: In [7]: list_strings('A single string') Out[7]: ['A single string'] In [8]: list_strings(['A single string in a list']) Out[8]: ['A single string in a list'] In [9]: list_strings(['A','list','of','strings']) Out[9]: ['A', 'list', 'of', 'strings'] """ if isinstance(arg,basestring): return [arg] else: return arg def marquee(txt='',width=78,mark='*'): """Return the input string centered in a 'marquee'. :Examples: In [16]: marquee('A test',40) Out[16]: '**************** A test ****************' In [17]: marquee('A test',40,'-') Out[17]: '---------------- A test ----------------' In [18]: marquee('A test',40,' ') Out[18]: ' A test ' """ if not txt: return (mark*width)[:width] nmark = (width-len(txt)-2)//len(mark)//2 if nmark < 0: nmark =0 marks = mark*nmark return '%s %s %s' % (marks,txt,marks) ini_spaces_re = re.compile(r'^(\s+)') def num_ini_spaces(strng): """Return the number of initial spaces in a string""" ini_spaces = ini_spaces_re.match(strng) if ini_spaces: return ini_spaces.end() else: return 0 def format_screen(strng): """Format a string for screen printing. This removes some latex-type format codes.""" # Paragraph continue par_re = re.compile(r'\\$',re.MULTILINE) strng = par_re.sub('',strng) return strng def dedent(text): """Equivalent of textwrap.dedent that ignores unindented first line. This means it will still dedent strings like: '''foo is a bar ''' For use in wrap_paragraphs. """ if text.startswith('\n'): # text starts with blank line, don't ignore the first line return textwrap.dedent(text) # split first line splits = text.split('\n',1) if len(splits) == 1: # only one line return textwrap.dedent(text) first, rest = splits # dedent everything but the first line rest = textwrap.dedent(rest) return '\n'.join([first, rest]) def wrap_paragraphs(text, ncols=80): """Wrap multiple paragraphs to fit a specified width. This is equivalent to textwrap.wrap, but with support for multiple paragraphs, as separated by empty lines. Returns ------- list of complete paragraphs, wrapped to fill `ncols` columns. """ paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE) text = dedent(text).strip() paragraphs = paragraph_re.split(text)[::2] # every other entry is space out_ps = [] indent_re = re.compile(r'\n\s+', re.MULTILINE) for p in paragraphs: # presume indentation that survives dedent is meaningful formatting, # so don't fill unless text is flush. if indent_re.search(p) is None: # wrap paragraph p = textwrap.fill(p, ncols) out_ps.append(p) return out_ps def long_substr(data): """Return the longest common substring in a list of strings. Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python """ substr = '' if len(data) > 1 and len(data[0]) > 0: for i in range(len(data[0])): for j in range(len(data[0])-i+1): if j > len(substr) and all(data[0][i:i+j] in x for x in data): substr = data[0][i:i+j] elif len(data) == 1: substr = data[0] return substr def strip_email_quotes(text): """Strip leading email quotation characters ('>'). Removes any combination of leading '>' interspersed with whitespace that appears *identically* in all lines of the input text. Parameters ---------- text : str Examples -------- Simple uses:: In [2]: strip_email_quotes('> > text') Out[2]: 'text' In [3]: strip_email_quotes('> > text\\n> > more') Out[3]: 'text\\nmore' Note how only the common prefix that appears in all lines is stripped:: In [4]: strip_email_quotes('> > text\\n> > more\\n> more...') Out[4]: '> text\\n> more\\nmore...' So if any line has no quote marks ('>') , then none are stripped from any of them :: In [5]: strip_email_quotes('> > text\\n> > more\\nlast different') Out[5]: '> > text\\n> > more\\nlast different' """ lines = text.splitlines() matches = set() for line in lines: prefix = re.match(r'^(\s*>[ >]*)', line) if prefix: matches.add(prefix.group(1)) else: break else: prefix = long_substr(list(matches)) if prefix: strip = len(prefix) text = '\n'.join([ ln[strip:] for ln in lines]) return text class EvalFormatter(Formatter): """A String Formatter that allows evaluation of simple expressions. Note that this version interprets a : as specifying a format string (as per standard string formatting), so if slicing is required, you must explicitly create a slice. This is to be used in templating cases, such as the parallel batch script templates, where simple arithmetic on arguments is useful. Examples -------- In [1]: f = EvalFormatter() In [2]: f.format('{n//4}', n=8) Out [2]: '2' In [3]: f.format("{greeting[slice(2,4)]}", greeting="Hello") Out [3]: 'll' """ def get_field(self, name, args, kwargs): v = eval(name, kwargs) return v, name @skip_doctest_py3 class FullEvalFormatter(Formatter): """A String Formatter that allows evaluation of simple expressions. Any time a format key is not found in the kwargs, it will be tried as an expression in the kwargs namespace. Note that this version allows slicing using [1:2], so you cannot specify a format string. Use :class:`EvalFormatter` to permit format strings. Examples -------- In [1]: f = FullEvalFormatter() In [2]: f.format('{n//4}', n=8) Out[2]: u'2' In [3]: f.format('{list(range(5))[2:4]}') Out[3]: u'[2, 3]' In [4]: f.format('{3*2}') Out[4]: u'6' """ # copied from Formatter._vformat with minor changes to allow eval # and replace the format_spec code with slicing def _vformat(self, format_string, args, kwargs, used_args, recursion_depth): if recursion_depth < 0: raise ValueError('Max string recursion exceeded') result = [] for literal_text, field_name, format_spec, conversion in \ self.parse(format_string): # output the literal text if literal_text: result.append(literal_text) # if there's a field, output it if field_name is not None: # this is some markup, find the object and do # the formatting if format_spec: # override format spec, to allow slicing: field_name = ':'.join([field_name, format_spec]) # eval the contents of the field for the object # to be formatted obj = eval(field_name, kwargs) # do any conversion on the resulting object obj = self.convert_field(obj, conversion) # format the object and append to the result result.append(self.format_field(obj, '')) return u''.join(py3compat.cast_unicode(s) for s in result) @skip_doctest_py3 class DollarFormatter(FullEvalFormatter): """Formatter allowing Itpl style $foo replacement, for names and attribute access only. Standard {foo} replacement also works, and allows full evaluation of its arguments. Examples -------- In [1]: f = DollarFormatter() In [2]: f.format('{n//4}', n=8) Out[2]: u'2' In [3]: f.format('23 * 76 is $result', result=23*76) Out[3]: u'23 * 76 is 1748' In [4]: f.format('$a or {b}', a=1, b=2) Out[4]: u'1 or 2' """ _dollar_pattern = re.compile("(.*?)\$(\$?[\w\.]+)") def parse(self, fmt_string): for literal_txt, field_name, format_spec, conversion \ in Formatter.parse(self, fmt_string): # Find $foo patterns in the literal text. continue_from = 0 txt = "" for m in self._dollar_pattern.finditer(literal_txt): new_txt, new_field = m.group(1,2) # $$foo --> $foo if new_field.startswith("$"): txt += new_txt + new_field else: yield (txt + new_txt, new_field, "", None) txt = "" continue_from = m.end() # Re-yield the {foo} style pattern yield (txt + literal_txt[continue_from:], field_name, format_spec, conversion) #----------------------------------------------------------------------------- # Utils to columnize a list of string #----------------------------------------------------------------------------- def _chunks(l, n): """Yield successive n-sized chunks from l.""" for i in xrange(0, len(l), n): yield l[i:i+n] def _find_optimal(rlist , separator_size=2 , displaywidth=80): """Calculate optimal info to columnize a list of string""" for nrow in range(1, len(rlist)+1) : chk = map(max,_chunks(rlist, nrow)) sumlength = sum(chk) ncols = len(chk) if sumlength+separator_size*(ncols-1) <= displaywidth : break; return {'columns_numbers' : ncols, 'optimal_separator_width':(displaywidth - sumlength)/(ncols-1) if (ncols -1) else 0, 'rows_numbers' : nrow, 'columns_width' : chk } def _get_or_default(mylist, i, default=None): """return list item number, or default if don't exist""" if i >= len(mylist): return default else : return mylist[i] @skip_doctest def compute_item_matrix(items, empty=None, *args, **kwargs) : """Returns a nested list, and info to columnize items Parameters : ------------ items : list of strings to columize empty : (default None) default value to fill list if needed separator_size : int (default=2) How much caracters will be used as a separation between each columns. displaywidth : int (default=80) The width of the area onto wich the columns should enter Returns : --------- Returns a tuple of (strings_matrix, dict_info) strings_matrix : nested list of string, the outer most list contains as many list as rows, the innermost lists have each as many element as colums. If the total number of elements in `items` does not equal the product of rows*columns, the last element of some lists are filled with `None`. dict_info : some info to make columnize easier: columns_numbers : number of columns rows_numbers : number of rows columns_width : list of with of each columns optimal_separator_width : best separator width between columns Exemple : --------- In [1]: l = ['aaa','b','cc','d','eeeee','f','g','h','i','j','k','l'] ...: compute_item_matrix(l,displaywidth=12) Out[1]: ([['aaa', 'f', 'k'], ['b', 'g', 'l'], ['cc', 'h', None], ['d', 'i', None], ['eeeee', 'j', None]], {'columns_numbers': 3, 'columns_width': [5, 1, 1], 'optimal_separator_width': 2, 'rows_numbers': 5}) """ info = _find_optimal(map(len, items), *args, **kwargs) nrow, ncol = info['rows_numbers'], info['columns_numbers'] return ([[ _get_or_default(items, c*nrow+i, default=empty) for c in range(ncol) ] for i in range(nrow) ], info) def columnize(items, separator=' ', displaywidth=80): """ Transform a list of strings into a single string with columns. Parameters ---------- items : sequence of strings The strings to process. separator : str, optional [default is two spaces] The string that separates columns. displaywidth : int, optional [default is 80] Width of the display in number of characters. Returns ------- The formatted string. """ if not items : return '\n' matrix, info = compute_item_matrix(items, separator_size=len(separator), displaywidth=displaywidth) fmatrix = [filter(None, x) for x in matrix] sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['columns_width'])]) return '\n'.join(map(sjoin, fmatrix))+'\n'
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/utils/text.py
Python
lgpl-3.0
25,044
using UnityEngine; using System.Collections; public class InputBehaviour : MonoBehaviour { // Cuando se llama, notifica a todos los métodos que hacen referencia al delegate (DownHandler). public delegate void DownHandler( int button ); // evento que se activa cuando aparece el DownHandler public event DownHandler onDown; // Funcion que se llama desde InputManger, activa el evento onDown de éste y otras clases public void triggerDown(int button){ if( onDown != null ) onDown(button); } }
ddacoak/Fallen-Instinct
Assets/Scripts/OtrosScripts/Input/InputBehaviour.cs
C#
unlicense
514
package org.myrobotlab.logging; import org.myrobotlab.framework.Platform; import org.slf4j.Logger; public class LoggerFactory { public static Logger getLogger(Class<?> clazz) { return getLogger(clazz.toString()); } public static Logger getLogger(String name) { Platform platform = Platform.getLocalInstance(); if (platform.isDalvik()) { String android = name.substring(name.lastIndexOf(".") + 1); if (android.length() > 23) android = android.substring(0, 23); // http://slf4j.42922.n3.nabble.com/ // Bug-173-New-slf4j-android-Android-throws-an-IllegalArgumentException-when-Log-Tag-length-exceeds-23-s-td443886.html return org.slf4j.LoggerFactory.getLogger(android); } else { return org.slf4j.LoggerFactory.getLogger(name); } } }
lanchun/myrobotlab
src/org/myrobotlab/logging/LoggerFactory.java
Java
apache-2.0
771
from __future__ import division, absolute_import from __future__ import print_function, unicode_literals import numpy as np import theano import theano.tensor as T import treeano import treeano.nodes as tn fX = theano.config.floatX # ################################## config ################################## N_TRAIN = 5000 LAG = 20 LENGTH = 50 HIDDEN_STATE_SIZE = 10 # ############################### prepare data ############################### def binary_toy_data(lag=1, length=20): inputs = np.random.randint(0, 2, length).astype(fX) outputs = np.array(lag * [0] + list(inputs), dtype=fX)[:length] return inputs, outputs # ############################## prepare model ############################## model = tn.HyperparameterNode( "model", tn.SequentialNode( "seq", [tn.InputNode("x", shape=(None, 1)), tn.recurrent.SimpleRecurrentNode( "srn", tn.TanhNode("nonlin"), batch_size=None, num_units=HIDDEN_STATE_SIZE), tn.scan.ScanNode( "scan", tn.DenseNode("fc", num_units=1)), tn.SigmoidNode("pred"), ]), inits=[treeano.inits.NormalWeightInit(0.01)], batch_axis=None, scan_axis=0 ) with_updates = tn.HyperparameterNode( "with_updates", tn.SGDNode( "adam", {"subtree": model, "cost": tn.TotalCostNode("cost", { "pred": tn.ReferenceNode("pred_ref", reference="model"), "target": tn.InputNode("y", shape=(None, 1))}, )}), learning_rate=0.1, cost_function=treeano.utils.squared_error, ) network = with_updates.network() train_fn = network.function(["x", "y"], ["cost"], include_updates=True) valid_fn = network.function(["x"], ["model"]) # ################################# training ################################# print("Starting training...") import time st = time.time() for i in range(N_TRAIN): inputs, outputs = binary_toy_data(lag=LAG, length=LENGTH) loss = train_fn(inputs.reshape(-1, 1), outputs.reshape(-1, 1))[0] if (i % (N_TRAIN // 100)) == 0: print(loss) print("total_time: %s" % (time.time() - st)) inputs, outputs = binary_toy_data(lag=LAG, length=LENGTH) pred = valid_fn(inputs.reshape(-1, 1))[0].flatten() print(np.round(pred) == outputs)
diogo149/treeano
examples/simple_rnn_comparison/with_treeano.py
Python
apache-2.0
2,330
/** * Copyright 2016 LinkedIn Corp. 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. */ package com.github.ambry.store; import java.io.DataInputStream; import java.io.IOException; /** * Factory to create an index key */ public interface StoreKeyFactory { /** * The store key created using the stream provided * @param stream The stream used to create the store key * @return The store key created from the stream */ StoreKey getStoreKey(DataInputStream stream) throws IOException; }
nsivabalan/ambry
ambry-api/src/main/java/com.github.ambry/store/StoreKeyFactory.java
Java
apache-2.0
929
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/route53/model/ListTrafficPoliciesRequest.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <aws/core/http/URI.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Route53::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils; using namespace Aws::Http; ListTrafficPoliciesRequest::ListTrafficPoliciesRequest() : m_trafficPolicyIdMarkerHasBeenSet(false), m_maxItemsHasBeenSet(false) { } Aws::String ListTrafficPoliciesRequest::SerializePayload() const { return ""; } void ListTrafficPoliciesRequest::AddQueryStringParameters(URI& uri) const { Aws::StringStream ss; if(m_trafficPolicyIdMarkerHasBeenSet) { ss << m_trafficPolicyIdMarker; uri.AddQueryStringParameter("trafficpolicyid", ss.str()); ss.str(""); } if(m_maxItemsHasBeenSet) { ss << m_maxItems; uri.AddQueryStringParameter("maxitems", ss.str()); ss.str(""); } }
JoyIfBam5/aws-sdk-cpp
aws-cpp-sdk-route53/source/model/ListTrafficPoliciesRequest.cpp
C++
apache-2.0
1,614
/* Copyright 2015 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 cmd import ( "fmt" "io" "github.com/renstrom/dedent" "k8s.io/kubernetes/pkg/kubectl" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "k8s.io/kubernetes/pkg/kubectl/resource" utilerrors "k8s.io/kubernetes/pkg/util/errors" "github.com/spf13/cobra" ) var ( autoscaleLong = dedent.Dedent(` Creates an autoscaler that automatically chooses and sets the number of pods that run in a kubernetes cluster. Looks up a Deployment, ReplicaSet, or ReplicationController by name and creates an autoscaler that uses the given resource as a reference. An autoscaler can automatically increase or decrease number of pods deployed within the system as needed.`) autoscaleExample = dedent.Dedent(` # Auto scale a deployment "foo", with the number of pods between 2 and 10, target CPU utilization specified so a default autoscaling policy will be used: kubectl autoscale deployment foo --min=2 --max=10 # Auto scale a replication controller "foo", with the number of pods between 1 and 5, target CPU utilization at 80%: kubectl autoscale rc foo --max=5 --cpu-percent=80`) ) func NewCmdAutoscale(f cmdutil.Factory, out io.Writer) *cobra.Command { options := &resource.FilenameOptions{} validArgs := []string{"deployment", "replicaset", "replicationcontroller"} argAliases := kubectl.ResourceAliases(validArgs) cmd := &cobra.Command{ Use: "autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags]", Short: "Auto-scale a Deployment, ReplicaSet, or ReplicationController", Long: autoscaleLong, Example: autoscaleExample, Run: func(cmd *cobra.Command, args []string) { err := RunAutoscale(f, out, cmd, args, options) cmdutil.CheckErr(err) }, ValidArgs: validArgs, ArgAliases: argAliases, } cmdutil.AddPrinterFlags(cmd) cmd.Flags().String("generator", "horizontalpodautoscaler/v1", "The name of the API generator to use. Currently there is only 1 generator.") cmd.Flags().Int("min", -1, "The lower limit for the number of pods that can be set by the autoscaler. If it's not specified or negative, the server will apply a default value.") cmd.Flags().Int("max", -1, "The upper limit for the number of pods that can be set by the autoscaler. Required.") cmd.MarkFlagRequired("max") cmd.Flags().Int("cpu-percent", -1, fmt.Sprintf("The target average CPU utilization (represented as a percent of requested CPU) over all the pods. If it's not specified or negative, a default autoscaling policy will be used.")) cmd.Flags().String("name", "", "The name for the newly created object. If not specified, the name of the input resource will be used.") cmdutil.AddDryRunFlag(cmd) usage := "identifying the resource to autoscale." cmdutil.AddFilenameOptionFlags(cmd, options, usage) cmdutil.AddApplyAnnotationFlags(cmd) cmdutil.AddRecordFlag(cmd) cmdutil.AddInclude3rdPartyFlags(cmd) return cmd } func RunAutoscale(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *resource.FilenameOptions) error { namespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } // validate flags if err := validateFlags(cmd); err != nil { return err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). ContinueOnError(). NamespaceParam(namespace).DefaultNamespace(). FilenameParam(enforceNamespace, options). ResourceTypeOrNameArgs(false, args...). Flatten(). Do() err = r.Err() if err != nil { return err } // Get the generator, setup and validate all required parameters generatorName := cmdutil.GetFlagString(cmd, "generator") generators := f.Generators("autoscale") generator, found := generators[generatorName] if !found { return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName)) } names := generator.ParamNames() count := 0 err = r.Visit(func(info *resource.Info, err error) error { if err != nil { return err } mapping := info.ResourceMapping() if err := f.CanBeAutoscaled(mapping.GroupVersionKind.GroupKind()); err != nil { return err } name := info.Name params := kubectl.MakeParams(cmd, names) params["default-name"] = name params["scaleRef-kind"] = mapping.GroupVersionKind.Kind params["scaleRef-name"] = name params["scaleRef-apiVersion"] = mapping.GroupVersionKind.GroupVersion().String() if err = kubectl.ValidateParams(names, params); err != nil { return err } // Check for invalid flags used against the present generator. if err := kubectl.EnsureFlagsValid(cmd, generators, generatorName); err != nil { return err } // Generate new object object, err := generator.Generate(params) if err != nil { return err } resourceMapper := &resource.Mapper{ ObjectTyper: typer, RESTMapper: mapper, ClientMapper: resource.ClientMapperFunc(f.ClientForMapping), Decoder: f.Decoder(true), } hpa, err := resourceMapper.InfoForObject(object, nil) if err != nil { return err } if cmdutil.ShouldRecord(cmd, hpa) { if err := cmdutil.RecordChangeCause(hpa.Object, f.Command()); err != nil { return err } object = hpa.Object } if cmdutil.GetDryRunFlag(cmd) { return f.PrintObject(cmd, mapper, object, out) } if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), hpa, f.JSONEncoder()); err != nil { return err } object, err = resource.NewHelper(hpa.Client, hpa.Mapping).Create(namespace, false, object) if err != nil { return err } count++ if len(cmdutil.GetFlagString(cmd, "output")) > 0 { return f.PrintObject(cmd, mapper, object, out) } cmdutil.PrintSuccess(mapper, false, out, info.Mapping.Resource, info.Name, cmdutil.GetDryRunFlag(cmd), "autoscaled") return nil }) if err != nil { return err } if count == 0 { return fmt.Errorf("no objects passed to autoscale") } return nil } func validateFlags(cmd *cobra.Command) error { errs := []error{} max, min := cmdutil.GetFlagInt(cmd, "max"), cmdutil.GetFlagInt(cmd, "min") if max < 1 { errs = append(errs, fmt.Errorf("--max=MAXPODS is required and must be at least 1, max: %d", max)) } if max < min { errs = append(errs, fmt.Errorf("--max=MAXPODS must be larger or equal to --min=MINPODS, max: %d, min: %d", max, min)) } return utilerrors.NewAggregate(errs) }
gluke77/kubernetes
pkg/kubectl/cmd/autoscale.go
GO
apache-2.0
6,991
/* * 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.activemq.artemis.utils.network; import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.artemis.core.server.NetworkHealthCheck; import org.apache.activemq.artemis.utils.ExecuteUtil; import org.junit.Assert; import org.junit.Assume; import org.junit.Test; /** * This utility class will use sudo commands to start "fake" network cards on a given address. * It's used on tests that need to emmulate network outages and split brains. * * If you write a new test using this class, please make special care on undoing the config, * especially in case of failures. * * Usually the class {@link NetUtilResource} is pretty accurate on undoing this, but you also need to *test your test* well. * * You need special sudo authorizations on your system to let this class work: * * Add the following at the end of your /etc/sudoers (use the sudo visudo command)"); * # ------------------------------------------------------- "); * yourUserName ALL = NOPASSWD: /sbin/ifconfig"); * # ------------------------------------------------------- "); * */ public class NetUtil extends ExecuteUtil { public static boolean checkIP(String ip) throws Exception { InetAddress ipAddress = null; try { ipAddress = InetAddress.getByName(ip); } catch (Exception e) { e.printStackTrace(); // not supposed to happen return false; } NetworkHealthCheck healthCheck = new NetworkHealthCheck(null, 100, 100); return healthCheck.check(ipAddress); } public static AtomicInteger nextDevice = new AtomicInteger(0); // IP / device (device being only valid on linux) public static Map<String, String> networks = new ConcurrentHashMap<>(); private enum OS { MAC, LINUX, NON_SUPORTED; } static final OS osUsed; static final String user = System.getProperty("user.name"); static { OS osTmp; String propOS = System.getProperty("os.name").toUpperCase(); if (propOS.contains("MAC")) { osTmp = OS.MAC; } else if (propOS.contains("LINUX")) { osTmp = OS.LINUX; } else { osTmp = OS.NON_SUPORTED; } osUsed = osTmp; } public static void failIfNotSudo() { Assume.assumeTrue("non supported OS", osUsed != OS.NON_SUPORTED); if (!canSudo()) { StringWriter writer = new StringWriter(); PrintWriter out = new PrintWriter(writer); out.println("Add the following at the end of your /etc/sudoers (use the visudo command)"); out.println("# ------------------------------------------------------- "); out.println(user + " ALL = NOPASSWD: /sbin/ifconfig"); out.println("# ------------------------------------------------------- "); Assert.fail(writer.toString()); } } public static void cleanup() { nextDevice.set(0); Set entrySet = networks.entrySet(); Iterator iter = entrySet.iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next(); try { netDown(entry.getKey(), entry.getValue(), true); } catch (Exception e) { e.printStackTrace(); } } } public static void netUp(String ip) throws Exception { String deviceID = "lo:" + nextDevice.incrementAndGet(); netUp(ip, deviceID); } public static void netUp(String ip, String deviceID) throws Exception { if (osUsed == OS.MAC) { if (runCommand(false, "sudo", "-n", "ifconfig", "lo0", "alias", ip) != 0) { Assert.fail("Cannot sudo ifconfig for ip " + ip); } networks.put(ip, "lo0"); } else if (osUsed == OS.LINUX) { if (runCommand(false, "sudo", "-n", "ifconfig", deviceID, ip, "netmask", "255.0.0.0") != 0) { Assert.fail("Cannot sudo ifconfig for ip " + ip); } networks.put(ip, deviceID); } else { Assert.fail("OS not supported"); } } public static void netDown(String ip) throws Exception { netDown(ip, false); } public static void netDown(String ip, boolean force) throws Exception { String device = networks.remove(ip); if (!force) { // in case the netDown is coming from a different VM (spawned tests) Assert.assertNotNull("ip " + ip + "wasn't set up before", device); } netDown(ip, device, force); } public static void netDown(String ip, String device, boolean force) throws Exception { networks.remove(ip); if (osUsed == OS.MAC) { if (runCommand(false, "sudo", "-n", "ifconfig", "lo0", "-alias", ip) != 0) { if (!force) { Assert.fail("Cannot sudo ifconfig for ip " + ip); } } } else if (osUsed == OS.LINUX) { if (runCommand(false, "sudo", "-n", "ifconfig", device, "down") != 0) { if (!force) { Assert.fail("Cannot sudo ifconfig for ip " + ip); } } } else { Assert.fail("OS not supported"); } } public static boolean canSudo() { try { return runCommand(false, "sudo", "-n", "ifconfig") == 0; } catch (Exception e) { e.printStackTrace(); return false; } } @Test public void testCanSudo() throws Exception { Assert.assertTrue(canSudo()); } }
kjniemi/activemq-artemis
artemis-commons/src/test/java/org/apache/activemq/artemis/utils/network/NetUtil.java
Java
apache-2.0
6,434
/* Copyright 2017 IBM Corporation * * 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 main import "fmt" func main() { fmt.Println("Hello, World") }
denilsonm/advance-toolchain
fvtr/gccgo/test.go
GO
apache-2.0
669
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution; public class IllegalEnvVarException extends ExecutionException { public IllegalEnvVarException(String message) { super(message); } }
mdanielwork/intellij-community
platform/platform-api/src/com/intellij/execution/IllegalEnvVarException.java
Java
apache-2.0
314
<?php // Start of AMQPExchangeException from php-amqp v.1.4.0beta2 /** * stub class representing AMQPExchangeException from pecl-amqp * @jms-builtin */ class AMQPExchangeException extends AMQPException { } // End of AMQPExchangeException from php-amqp v.1.4.0beta2 ?>
walkeralencar/ci-php-analyzer
res/php-5.4-core-api/AMQPExchangeException.php
PHP
apache-2.0
273
<?php # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/gaming/v1/game_server_deployments.proto namespace Google\Cloud\Gaming\V1; use Google\Protobuf\Internal\GPBType; use Google\Protobuf\Internal\RepeatedField; use Google\Protobuf\Internal\GPBUtil; /** * Request message for GameServerDeploymentsService.GetGameServerDeployment. * * Generated from protobuf message <code>google.cloud.gaming.v1.GetGameServerDeploymentRequest</code> */ class GetGameServerDeploymentRequest extends \Google\Protobuf\Internal\Message { /** * Required. The name of the game server delpoyment to retrieve, in the following form: * `projects/{project}/locations/{location}/gameServerDeployments/{deployment}`. * * Generated from protobuf field <code>string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {</code> */ private $name = ''; /** * Constructor. * * @param array $data { * Optional. Data for populating the Message object. * * @type string $name * Required. The name of the game server delpoyment to retrieve, in the following form: * `projects/{project}/locations/{location}/gameServerDeployments/{deployment}`. * } */ public function __construct($data = NULL) { \GPBMetadata\Google\Cloud\Gaming\V1\GameServerDeployments::initOnce(); parent::__construct($data); } /** * Required. The name of the game server delpoyment to retrieve, in the following form: * `projects/{project}/locations/{location}/gameServerDeployments/{deployment}`. * * Generated from protobuf field <code>string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {</code> * @return string */ public function getName() { return $this->name; } /** * Required. The name of the game server delpoyment to retrieve, in the following form: * `projects/{project}/locations/{location}/gameServerDeployments/{deployment}`. * * Generated from protobuf field <code>string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {</code> * @param string $var * @return $this */ public function setName($var) { GPBUtil::checkString($var, True); $this->name = $var; return $this; } }
googleapis/google-cloud-php-game-servers
src/V1/GetGameServerDeploymentRequest.php
PHP
apache-2.0
2,444
// Copyright 2020 Google Inc. 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. package pbtesting import ( "fmt" "github.com/golang/mock/gomock" "github.com/golang/protobuf/proto" "github.com/google/go-cmp/cmp" "google.golang.org/protobuf/testing/protocmp" ) type protoMatcher struct { expected proto.Message } func (m protoMatcher) Got(got interface{}) string { message, ok := got.(proto.Message) if !ok { return fmt.Sprintf("%v", ok) } return proto.MarshalTextString(message) } func (m protoMatcher) Matches(actual interface{}) bool { return cmp.Diff(m.expected, actual, protocmp.Transform()) == "" } func (m protoMatcher) String() string { return proto.MarshalTextString(m.expected) } func ProtoEquals(expected proto.Message) gomock.Matcher { return protoMatcher{expected} }
adjackura/compute-image-tools
proto/go/pbtesting/gomock_matcher.go
GO
apache-2.0
1,340