diff --git a/pool/shard002/C++/0034609_web_apps.cc b/pool/shard002/C++/0034609_web_apps.cc new file mode 100644 index 0000000000000000000000000000000000000000..375adf8125383e9929e5fa463a6dcb29547ac9ca --- /dev/null +++ b/pool/shard002/C++/0034609_web_apps.cc @@ -0,0 +1,57 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/apps/app_service/web_apps.h" + +#include "base/bind_helpers.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/web_applications/web_app_dialog_manager.h" +#include "chrome/browser/ui/web_applications/web_app_ui_manager_impl.h" +#include "chrome/browser/web_applications/system_web_app_manager.h" +#include "chrome/browser/web_applications/web_app_provider.h" + +namespace apps { + +WebApps::WebApps(const mojo::Remote& app_service, + Profile* profile) + : WebAppsBase(app_service, profile) {} + +WebApps::~WebApps() = default; + +// static +void WebApps::UninstallImpl(Profile* profile, + const std::string& app_id, + gfx::NativeWindow parent_window) { + web_app::WebAppUiManagerImpl* web_app_ui_manager = + web_app::WebAppUiManagerImpl::Get(profile); + if (!web_app_ui_manager) { + return; + } + + web_app::WebAppDialogManager& web_app_dialog_manager = + web_app_ui_manager->dialog_manager(); + if (web_app_dialog_manager.CanUninstallWebApp(app_id)) { + web_app_dialog_manager.UninstallWebApp( + app_id, web_app::WebAppDialogManager::UninstallSource::kAppMenu, + parent_window, base::DoNothing()); + } +} + +apps::mojom::AppPtr WebApps::Convert(const web_app::WebApp* web_app, + apps::mojom::Readiness readiness) { + apps::mojom::AppPtr app = ConvertImpl(web_app, readiness); + + app->icon_key = icon_key_factory().MakeIconKey(GetIconEffects(web_app)); + + app->has_badge = apps::mojom::OptionalBool::kFalse; + app->paused = apps::mojom::OptionalBool::kFalse; + + return app; +} + +bool WebApps::Accepts(const std::string& app_id) { + return true; +} + +} // namespace apps diff --git a/pool/shard002/C++/0034610_ServicePortCollection.cpp b/pool/shard002/C++/0034610_ServicePortCollection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a5836d61d8356f677fbba867fbc82f195fb0296c --- /dev/null +++ b/pool/shard002/C++/0034610_ServicePortCollection.cpp @@ -0,0 +1,176 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "config.h" +#include "modules/navigatorconnect/ServicePortCollection.h" + +#include "bindings/core/v8/ScriptPromiseResolver.h" +#include "bindings/core/v8/SerializedScriptValueFactory.h" +#include "core/dom/DOMException.h" +#include "core/dom/ExceptionCode.h" +#include "core/dom/MessagePort.h" +#include "core/events/MessageEvent.h" +#include "modules/EventTargetModules.h" +#include "modules/navigatorconnect/AcceptConnectionObserver.h" +#include "modules/navigatorconnect/ServicePort.h" +#include "modules/navigatorconnect/ServicePortConnectEvent.h" +#include "modules/navigatorconnect/ServicePortConnectEventInit.h" +#include "modules/navigatorconnect/ServicePortConnectOptions.h" +#include "public/platform/Platform.h" +#include "public/platform/modules/navigator_services/WebServicePortProvider.h" + +namespace blink { + +namespace { + +class ConnectCallbacks : public WebServicePortConnectCallbacks { +public: + ConnectCallbacks(ScriptPromiseResolver* resolver, ServicePortCollection* collection, const KURL& targetUrl, const String& portName, const String& serializedPortData) + : m_resolver(resolver), m_collection(collection), m_targetUrl(targetUrl), m_portName(portName), m_serializedPortData(serializedPortData) + { + ASSERT(m_resolver); + } + + ~ConnectCallbacks() override { } + + void onSuccess(WebServicePortID* portIdRaw) override + { + OwnPtr webPortId = adoptPtr(portIdRaw); + if (!m_resolver->executionContext() || m_resolver->executionContext()->activeDOMObjectsAreStopped()) { + return; + } + WebServicePort webPort; + webPort.id = *webPortId; + webPort.targetUrl = m_targetUrl; + webPort.name = m_portName; + webPort.data = m_serializedPortData; + ServicePort* port = ServicePort::create(m_collection, webPort); + m_collection->addPort(port); + m_resolver->resolve(port); + } + + void onError() override + { + // TODO(mek): Pass actual error code back. + if (!m_resolver->executionContext() || m_resolver->executionContext()->activeDOMObjectsAreStopped()) { + return; + } + m_resolver->reject(DOMException::create(AbortError)); + } + +private: + Persistent m_resolver; + Persistent m_collection; + KURL m_targetUrl; + String m_portName; + String m_serializedPortData; + + WTF_MAKE_NONCOPYABLE(ConnectCallbacks); +}; + +} // namespace + +ServicePortCollection* ServicePortCollection::create(ExecutionContext* context) +{ + return new ServicePortCollection(context); +} + +ServicePortCollection::~ServicePortCollection() +{ +} + +void ServicePortCollection::addPort(ServicePort* port) +{ + m_ports.append(port); +} + +void ServicePortCollection::closePort(ServicePort* port) +{ + m_ports.remove(m_ports.find(port)); + if (m_provider) + m_provider->closePort(port->id()); +} + +ScriptPromise ServicePortCollection::connect(ScriptState* scriptState, const String& url, const ServicePortConnectOptions& options, ExceptionState& exceptionState) +{ + if (!m_provider) + return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(NotSupportedError)); + + RefPtr portData; + if (options.hasData()) { + portData = SerializedScriptValueFactory::instance().create(options.data().isolate(), options.data(), nullptr, exceptionState); + if (exceptionState.hadException()) + return exceptionState.reject(scriptState); + } + ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); + ScriptPromise promise = resolver->promise(); + KURL targetUrl = scriptState->executionContext()->completeURL(url); + m_provider->connect( + targetUrl, + scriptState->executionContext()->securityOrigin()->toString(), + new ConnectCallbacks(resolver, this, targetUrl, options.name(), portData ? portData->toWireString() : String())); + return promise; +} + +ScriptPromise ServicePortCollection::match(ScriptState* scriptState, const ServicePortMatchOptions& options) +{ + return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(NotSupportedError)); +} + +ScriptPromise ServicePortCollection::matchAll(ScriptState* scriptState, const ServicePortMatchOptions& options) +{ + return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(NotSupportedError)); +} + +const AtomicString& ServicePortCollection::interfaceName() const +{ + return EventTargetNames::ServicePortCollection; +} + +ExecutionContext* ServicePortCollection::executionContext() const +{ + return ContextLifecycleObserver::executionContext(); +} + +void ServicePortCollection::postMessage(WebServicePortID portId, const WebString& messageString, const WebMessagePortChannelArray& webChannels) +{ + OwnPtr channels; + if (webChannels.size()) { + channels = adoptPtr(new MessagePortChannelArray(webChannels.size())); + for (size_t i = 0; i < webChannels.size(); ++i) + (*channels)[i] = adoptPtr(webChannels[i]); + } + RefPtr message = SerializedScriptValueFactory::instance().createFromWire(messageString); + + MessagePortArray* ports = MessagePort::entanglePorts(*executionContext(), channels.release()); + RefPtrWillBeRawPtr evt = MessageEvent::create(ports, message.release()); + // TODO(mek): Lookup ServicePort and set events source attribute. + dispatchEvent(evt.release()); +} + +void ServicePortCollection::dispatchConnectEvent(PassOwnPtr callbacks, const WebURL& targetURL, const WebString& origin, WebServicePortID portID) +{ + AcceptConnectionObserver* observer = AcceptConnectionObserver::create(this, callbacks, portID, targetURL); + ServicePortConnectEventInit init; + init.setTargetURL(targetURL.string()); + init.setOrigin(origin); + RefPtrWillBeRawPtr event = ServicePortConnectEvent::create(EventTypeNames::connect, init, observer); + dispatchEvent(event.release()); + observer->didDispatchEvent(); +} + +DEFINE_TRACE(ServicePortCollection) +{ + visitor->trace(m_ports); + RefCountedGarbageCollectedEventTargetWithInlineData::trace(visitor); + ContextLifecycleObserver::trace(visitor); +} + +ServicePortCollection::ServicePortCollection(ExecutionContext* context) + : ContextLifecycleObserver(context) + , m_provider(adoptPtr(Platform::current()->createServicePortProvider(this))) +{ +} + +} // namespace blink diff --git a/pool/shard002/C++/0034611_qxtpushbutton.cpp b/pool/shard002/C++/0034611_qxtpushbutton.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9cc69db2dc6e46daaf6c5259217db751d0157af3 --- /dev/null +++ b/pool/shard002/C++/0034611_qxtpushbutton.cpp @@ -0,0 +1,323 @@ +#include "qxtpushbutton.h" +/**************************************************************************** +** Copyright (c) 2006 - 2011, the LibQxt project. +** See the Qxt AUTHORS file for a list of authors and copyright holders. +** All rights reserved. +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in the +** documentation and/or other materials provided with the distribution. +** * Neither the name of the LibQxt project 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 BE LIABLE FOR ANY +** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +** +** +*****************************************************************************/ + +#include +#include +#include +#include +#include +#include + +static const int Vertical_Mask = 0x02; + +class QxtPushButtonPrivate : public QxtPrivate +{ +public: + QXT_DECLARE_PUBLIC(QxtPushButton) + QxtPushButtonPrivate(); + + bool isRichText() const; + QStyleOptionButton getStyleOption() const; + + QString text; + Qxt::Rotation rot; + Qt::TextFormat format; + mutable QTextDocument* doc; +}; + +QxtPushButtonPrivate::QxtPushButtonPrivate() : + rot(Qxt::NoRotation), format(Qt::PlainText), doc(0) +{ +} + +bool QxtPushButtonPrivate::isRichText() const +{ + bool rich = (format == Qt::RichText) || (format == Qt::AutoText && Qt::mightBeRichText(qxt_p().text())); + if (rich && !doc) + { + doc = new QTextDocument(const_cast(&qxt_p())); + doc->setUndoRedoEnabled(false); + } + return rich; +} + +QStyleOptionButton QxtPushButtonPrivate::getStyleOption() const +{ + QStyleOptionButton option; + option.initFrom(&qxt_p()); + if (rot & Vertical_Mask) + { + QSize size = option.rect.size(); + size.transpose(); + option.rect.setSize(size); + } + option.features = QStyleOptionButton::None; + if (qxt_p().isFlat()) + option.features |= QStyleOptionButton::Flat; + if (qxt_p().menu()) + option.features |= QStyleOptionButton::HasMenu; + if (qxt_p().autoDefault() || qxt_p().isDefault()) + option.features |= QStyleOptionButton::AutoDefaultButton; + if (qxt_p().isDefault()) + option.features |= QStyleOptionButton::DefaultButton; + if (qxt_p().isDown() || (qxt_p().menu() && qxt_p().menu()->isVisible())) + option.state |= QStyle::State_Sunken; + if (qxt_p().isChecked()) + option.state |= QStyle::State_On; + if (!qxt_p().isFlat() && !qxt_p().isDown()) + option.state |= QStyle::State_Raised; + if (!isRichText()) + { + option.text = qxt_p().text(); + option.icon = qxt_p().icon(); + option.iconSize = qxt_p().iconSize(); + } + return option; +} + +/*! + \class QxtPushButton + \inmodule QxtWidgets + \brief The QxtPushButton widget is an extended QPushButton with rotation and rich text support. + + QxtPushButton is a QPushButton which can be rotated. In addition, QxtPushButton + provides rich text support. + + \image qxtpushbutton.png "QxtPushButton in action." + */ + +/*! + Constructs a new QxtPushButton with \a parent. + */ +QxtPushButton::QxtPushButton(QWidget* parent) : QPushButton(parent) +{ + QXT_INIT_PRIVATE(QxtPushButton); +} + +/*! + Constructs a new QxtPushButton with \a text and \a parent. + */ +QxtPushButton::QxtPushButton(const QString& text, QWidget* parent) : QPushButton(text, parent) +{ + QXT_INIT_PRIVATE(QxtPushButton); +} + +/*! + Constructs a new QxtPushButton with \a icon, \a text and \a parent. + + \bold {Note:} An icon is not rendered when using rich text. + */ +QxtPushButton::QxtPushButton(const QIcon& icon, const QString& text, QWidget* parent) : QPushButton(icon, text, parent) +{ + QXT_INIT_PRIVATE(QxtPushButton); +} + +/*! + Constructs a new QxtPushButton with \a rotation, \a text and \a parent. + */ +QxtPushButton::QxtPushButton(Qxt::Rotation rotation, const QString& text, QWidget* parent) : QPushButton(text, parent) +{ + QXT_INIT_PRIVATE(QxtPushButton); + setRotation(rotation); +} + +/*! + Destructs the button. + */ +QxtPushButton::~QxtPushButton() +{} + +/*! + \property QxtPushButton::rotation + \brief the rotation of the button + + The button is rotated according to this property. + The default value is Qxt::NoRotation. + + \sa Qxt::Rotation + */ +Qxt::Rotation QxtPushButton::rotation() const +{ + return qxt_d().rot; +} + +void QxtPushButton::setRotation(Qxt::Rotation rotation) +{ + if (qxt_d().rot != rotation) + { + qxt_d().rot = rotation; + switch (rotation) + { + case Qxt::NoRotation: + case Qxt::UpsideDown: + setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); + break; + + case Qxt::Clockwise: + case Qxt::CounterClockwise: + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum); + break; + + default: + // nothing to do + break; + } + updateGeometry(); + update(); + } +} + +/*! + \property QxtPushButton::textFormat + \brief the text format of the button + + Supported formats are Qt::PlainText, Qt::RichText and Qt::AutoText. + + The default format is Qt::PlainText. + + \sa Qt::TextFormat + */ +Qt::TextFormat QxtPushButton::textFormat() const +{ + return qxt_d().format; +} + +void QxtPushButton::setTextFormat(Qt::TextFormat format) +{ + if (qxt_d().format != format) + { + qxt_d().format = format; + if (!qxt_d().isRichText()) + { + delete qxt_d().doc; + qxt_d().doc = 0; + } + qxt_d().text.clear(); + update(); + updateGeometry(); + } +} + +/*! + \reimp + */ +QSize QxtPushButton::sizeHint() const +{ + QSize size; + if (qxt_d().isRichText()) + size = qxt_d().doc->documentLayout()->documentSize().toSize(); + else + size = QPushButton::sizeHint(); + + if (qxt_d().rot & Vertical_Mask) + size.transpose(); + return size; +} + +/*! + \reimp + */ +QSize QxtPushButton::minimumSizeHint() const +{ + return sizeHint(); +} + +/*! + \reimp + */ +void QxtPushButton::paintEvent(QPaintEvent* event) +{ + Q_UNUSED(event); + + // the only reliable way to detect text changes + if (text() != qxt_d().text) + { + qxt_d().text = text(); + if (qxt_d().isRichText()) + qxt_d().doc->setHtml(qxt_d().text); + updateGeometry(); + } + + QStylePainter painter(this); + painter.rotate(qxt_d().rot); + switch (qxt_d().rot) + { + case Qxt::UpsideDown: + painter.translate(-width(), -height()); + break; + + case Qxt::Clockwise: + painter.translate(0, -width()); + break; + + case Qxt::CounterClockwise: + painter.translate(-height(), 0); + break; + + default: + // nothing to do + break; + } + + const QStyleOptionButton option = qxt_d().getStyleOption(); + painter.drawControl(QStyle::CE_PushButton, option); + + if (qxt_d().isRichText()) + { + int dx = 0; + int dy = 0; + if (option.state & (QStyle::State_On | QStyle::State_Sunken)) + { + dx += style()->pixelMetric(QStyle::PM_ButtonShiftHorizontal, &option, this); + dy += style()->pixelMetric(QStyle::PM_ButtonShiftVertical, &option, this); + } + + QRect area = rect(); + const QSizeF docSize = qxt_d().doc->documentLayout()->documentSize(); + if (qxt_d().rot & Vertical_Mask) + { + dx += static_cast((height() - docSize.width()) / 2); + dy += static_cast((width() - docSize.height()) / 2); + painter.translate(dx, dy); + + QSize size = area.size(); + size.transpose(); + area.setSize(size); + } + else + { + dx += static_cast((width() - docSize.width()) / 2); + dy += static_cast((height() - docSize.height()) / 2); + painter.translate(dx, dy); + } + qxt_d().doc->drawContents(&painter, area); + } +} diff --git a/pool/shard002/C++/0034619_http_client.cpp b/pool/shard002/C++/0034619_http_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..79af43b58578fadd06d6c2b3575094fe106a6dfe --- /dev/null +++ b/pool/shard002/C++/0034619_http_client.cpp @@ -0,0 +1,216 @@ +#include "platform/http_client.hpp" + +#include "coding/base64.hpp" + +#include "base/string_utils.hpp" + +#include + +using namespace std; + +namespace platform +{ +HttpClient::HttpClient(string const & url) : m_urlRequested(url) +{ +// Http client for linux supports only "deflate" encoding, but osrm server cannot +// correctly process "Accept-Encoding: deflate" header, so do not encode data on linux. +#if !defined(OMIM_OS_LINUX) + m_headers.emplace("Accept-Encoding", "gzip, deflate"); +#endif +} + +bool HttpClient::RunHttpRequest(string & response, SuccessChecker checker /* = nullptr */) +{ + static auto const simpleChecker = [](HttpClient const & request) + { + return request.ErrorCode() == 200; + }; + + if (checker == nullptr) + checker = simpleChecker; + + if (RunHttpRequest() && checker(*this)) + { + response = ServerResponse(); + return true; + } + + return false; +} + +HttpClient & HttpClient::SetUrlRequested(string const & url) +{ + m_urlRequested = url; + return *this; +} + +HttpClient & HttpClient::SetHttpMethod(string const & method) +{ + m_httpMethod = method; + return *this; +} + +HttpClient & HttpClient::SetBodyFile(string const & body_file, string const & content_type, + string const & http_method /* = "POST" */, + string const & content_encoding /* = "" */) +{ + m_inputFile = body_file; + m_bodyData.clear(); + m_headers.emplace("Content-Type", content_type); + m_httpMethod = http_method; + m_headers.emplace("Content-Encoding", content_encoding); + return *this; +} + +HttpClient & HttpClient::SetReceivedFile(string const & received_file) +{ + m_outputFile = received_file; + return *this; +} + +HttpClient & HttpClient::SetUserAndPassword(string const & user, string const & password) +{ + m_headers.emplace("Authorization", "Basic " + base64::Encode(user + ":" + password)); + return *this; +} + +HttpClient & HttpClient::SetCookies(string const & cookies) +{ + m_cookies = cookies; + return *this; +} + +HttpClient & HttpClient::SetHandleRedirects(bool handle_redirects) +{ + m_handleRedirects = handle_redirects; + return *this; +} + +HttpClient & HttpClient::SetRawHeader(string const & key, string const & value) +{ + m_headers.emplace(key, value); + return *this; +} + +HttpClient & HttpClient::SetRawHeaders(Headers const & headers) +{ + m_headers.insert(headers.begin(), headers.end()); + return *this; +} + +void HttpClient::SetTimeout(double timeoutSec) +{ + m_timeoutSec = timeoutSec; +} + +string const & HttpClient::UrlRequested() const +{ + return m_urlRequested; +} + +string const & HttpClient::UrlReceived() const +{ + return m_urlReceived; +} + +bool HttpClient::WasRedirected() const +{ + return m_urlRequested != m_urlReceived; +} + +int HttpClient::ErrorCode() const +{ + return m_errorCode; +} + +string const & HttpClient::ServerResponse() const +{ + return m_serverResponse; +} + +string const & HttpClient::HttpMethod() const +{ + return m_httpMethod; +} + +string HttpClient::CombinedCookies() const +{ + string serverCookies; + auto const it = m_headers.find("Set-Cookie"); + if (it != m_headers.end()) + serverCookies = it->second; + + if (serverCookies.empty()) + return m_cookies; + + if (m_cookies.empty()) + return serverCookies; + + return serverCookies + "; " + m_cookies; +} + +string HttpClient::CookieByName(string name) const +{ + string const str = CombinedCookies(); + name += "="; + auto const cookie = str.find(name); + auto const eq = cookie + name.size(); + if (cookie != string::npos && str.size() > eq) + return str.substr(eq, str.find(';', eq) - eq); + + return {}; +} + +void HttpClient::LoadHeaders(bool loadHeaders) +{ + m_loadHeaders = loadHeaders; +} + +HttpClient::Headers const & HttpClient::GetHeaders() const +{ + return m_headers; +} + +// static +string HttpClient::NormalizeServerCookies(string && cookies) +{ + istringstream is(cookies); + string str, result; + + // Split by ", ". Can have invalid tokens here, expires= can also contain a comma. + while (getline(is, str, ',')) + { + size_t const leading = str.find_first_not_of(" "); + if (leading != string::npos) + str.substr(leading).swap(str); + + // In the good case, we have '=' and it goes before any ' '. + auto const eq = str.find('='); + if (eq == string::npos) + continue; // It's not a cookie: no valid key value pair. + + auto const sp = str.find(' '); + if (sp != string::npos && eq > sp) + continue; // It's not a cookie: comma in expires date. + + // Insert delimiter. + if (!result.empty()) + result.append("; "); + + // Read cookie itself. + result.append(str, 0, str.find(";")); + } + return result; +} + +string DebugPrint(HttpClient const & request) +{ + ostringstream ostr; + ostr << "HTTP " << request.ErrorCode() << " url [" << request.UrlRequested() << "]"; + if (request.WasRedirected()) + ostr << " was redirected to [" << request.UrlReceived() << "]"; + if (!request.ServerResponse().empty()) + ostr << " response: " << request.ServerResponse(); + return ostr.str(); +} +} // namespace platform diff --git a/pool/shard002/C++/0034623_PGLoader.cpp b/pool/shard002/C++/0034623_PGLoader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b3ef8d2be2cd94e042e81a922275c7c3ca0b8037 --- /dev/null +++ b/pool/shard002/C++/0034623_PGLoader.cpp @@ -0,0 +1,198 @@ +/* + * Copyright (C) 2011-2021 FlylinkDC++ Team http://flylinkdc.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include "stdinc.h" + +#include "PGLoader.h" +#include "ResourceManager.h" +#include "File.h" +#include "IpGuard.h" +#include "SettingsManager.h" +#include "../windows/resource.h" + +#ifdef FLYLINKDC_USE_IPFILTER + +FastCriticalSection PGLoader::g_cs; +IPList PGLoader::g_ipTrustListAllow; +IPList PGLoader::g_ipTrustListBlock; + +void PGLoader::load(const string& p_data /*= BaseUtil::emptyString*/) +{ + string l_data; + const string l_url = SETTING(URL_IPTRUST); + bool l_is_download = false; + CFlyLog l_IPTrust_log("[IPTrust]"); + if (p_data.empty()) + { + if (!l_url.empty()) + { + try + { + const string l_log_message = STRING(DOWNLOAD) + ": " + l_url; + if (Util::getDataFromInet(true, l_url, l_data, 0) == 0) + { + l_IPTrust_log.step(l_log_message + " [" + STRING(ERROR_STRING) + ']'); + } + else + { + l_IPTrust_log.step(l_log_message + " [OK]"); + // "ðàñïàðñèì" îòâåò (TODO - ïåðåéòè íà regexp) + { + string::size_type linestart = 0; + string::size_type lineend = 0; + for (;;) + { + lineend = l_data.find('\n', linestart); + if (lineend == string::npos) + break; + const string line = l_data.substr(linestart, lineend - linestart - 1); + int u1, u2, u3, u4, u5, u6, u7, u8; + int iItems = sscanf_s(line.c_str(), "%u.%u.%u.%u - %u.%u.%u.%u", &u1, &u2, &u3, &u4, &u5, &u6, &u7, &u8); + if (iItems == 8 || iItems == 4) + { + l_is_download = true; + break; + } + iItems = sscanf_s(line.c_str(), "#%u.%u.%u.%u - %u.%u.%u.%u", &u1, &u2, &u3, &u4, &u5, &u6, &u7, &u8); + if (iItems == 8 || iItems == 4) + { + l_is_download = true; + break; + } + linestart = lineend + 1; + } + } + if (l_is_download) + { + const auto l_IPTrust_ini = getConfigFileName(); + File(l_IPTrust_ini, File::WRITE, File::CREATE | File::TRUNCATE).write(l_data); + l_IPTrust_log.step(l_IPTrust_ini + " [" + STRING(SAVE) + ']'); + } + } + } + catch (const FileException& e) + { + l_IPTrust_log.step("Can't write IPTrust.ini file: " + e.getError()); + dcdebug("IPTrust::save: %s\n", e.getError().c_str()); + } + } + if (l_data.empty()) + { + const string l_IPTrust_ini = getConfigFileName(); + if (File::isExist(l_IPTrust_ini)) + { + try + { + l_data = File(l_IPTrust_ini, File::READ, File::OPEN).read(); + } + catch (const FileException& e) + { + l_IPTrust_log.step("Can't read IPTrust.ini file: " + e.getError()); + dcdebug("IPTrust::load: %s\n", e.getError().c_str()); + } + } + else + { + Util::WriteTextResourceToFile(IDR_IPTRUST_EXAMPLE, Text::toT(l_IPTrust_ini)); + l_IPTrust_log.step("IPTrust.ini restored from internal resources"); + } + } + } + else + { + l_data = p_data; + } + + CFlyFastLock(g_cs); + l_IPTrust_log.step("parse IPTrust.ini"); + g_ipTrustListAllow.clear(); + g_ipTrustListBlock.clear(); + + if (!l_data.empty()) + { + string::size_type linestart = 0; + string::size_type lineend = 0; + for (;;) + { + lineend = l_data.find('\n', linestart); + if (lineend == string::npos) + { + string l_line = l_data.substr(linestart); + addLine(l_line, l_IPTrust_log); + break; + } + else + { + string l_line = l_data.substr(linestart, lineend - linestart - 1); + addLine(l_line, l_IPTrust_log); + linestart = lineend + 1; + } + } + } + l_IPTrust_log.step("parse IPTrust.ini done"); +} + +bool PGLoader::check(uint32_t p_ip4) +{ + if (BOOLSETTING(ENABLE_IPTRUST)) + { + CFlyFastLock(g_cs); + if (!g_ipTrustListBlock.empty()) + { + if (g_ipTrustListBlock.checkIp(p_ip4)) + { + return true; + } + } + if (!g_ipTrustListAllow.empty()) + { + const auto l_ipguard = g_ipTrustListAllow.checkIp(p_ip4); + return !l_ipguard; + } + else + { + return false; + } + } + else + { + return false; + } +} + +void PGLoader::addLine(string& p_Line, CFlyLog& p_log) +{ + Text::replace_all(p_Line, " ", ""); + if (p_Line.empty()) + return; + + if (p_Line[0] == '#') + return; + + if (p_Line[0] == '-') + { + p_Line.erase(0, 1); + g_ipTrustListBlock.addLine(p_Line, p_log); + } + else + { + g_ipTrustListAllow.addLine(p_Line, p_log); + } +} + +#endif // FLYLINKDC_USE_IPFILTER diff --git a/pool/shard002/C++/0034625_boss_cyanigosa.cpp b/pool/shard002/C++/0034625_boss_cyanigosa.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a3f2691145ef022c13633c9eb51497f66e863190 --- /dev/null +++ b/pool/shard002/C++/0034625_boss_cyanigosa.cpp @@ -0,0 +1,188 @@ +/* + * Copyright (C) 2008-2011 WCloudCore + * + * 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 . + */ + +#include "ScriptPCH.h" +#include "violet_hold.h" + +enum Spells +{ + SPELL_ARCANE_VACUUM = 58694, + SPELL_BLIZZARD = 58693, + H_SPELL_BLIZZARD = 59369, + SPELL_MANA_DESTRUCTION = 59374, + SPELL_TAIL_SWEEP = 58690, + H_SPELL_TAIL_SWEEP = 59283, + SPELL_UNCONTROLLABLE_ENERGY = 58688, + H_SPELL_UNCONTROLLABLE_ENERGY = 59281, + SPELL_TRANSFORM = 58668 +}; + +enum Yells +{ + SAY_AGGRO = -1608000, + SAY_SLAY_1 = -1608001, + SAY_SLAY_2 = -1608002, + SAY_SLAY_3 = -1608003, + SAY_DEATH = -1608004, + SAY_SPAWN = -1608005, + SAY_DISRUPTION = -1608006, + SAY_BREATH_ATTACK = -1608007, + SAY_SPECIAL_ATTACK_1 = -1608008, + SAY_SPECIAL_ATTACK_2 = -1608009 +}; + +class boss_cyanigosa : public CreatureScript +{ +public: + boss_cyanigosa() : CreatureScript("boss_cyanigosa") { } + + CreatureAI* GetAI(Creature* creature) const + { + return new boss_cyanigosaAI (creature); + } + + struct boss_cyanigosaAI : public ScriptedAI + { + boss_cyanigosaAI(Creature* c) : ScriptedAI(c) + { + instance = c->GetInstanceScript(); + } + + uint32 uiArcaneVacuumTimer; + uint32 uiBlizzardTimer; + uint32 uiManaDestructionTimer; + uint32 uiTailSweepTimer; + uint32 uiUncontrollableEnergyTimer; + + InstanceScript* instance; + + void Reset() + { + uiArcaneVacuumTimer = 10000; + uiBlizzardTimer = 15000; + uiManaDestructionTimer = 30000; + uiTailSweepTimer = 20000; + uiUncontrollableEnergyTimer = 25000; + if (instance) + instance->SetData(DATA_CYANIGOSA_EVENT, NOT_STARTED); + } + + void EnterCombat(Unit* /*who*/) + { + DoScriptText(SAY_AGGRO, me); + + if (instance) + instance->SetData(DATA_CYANIGOSA_EVENT, IN_PROGRESS); + } + + void MoveInLineOfSight(Unit* /*who*/) {} + + void UpdateAI(const uint32 diff) + { + if (instance && instance->GetData(DATA_REMOVE_NPC) == 1) + { + me->DespawnOrUnsummon(); + instance->SetData(DATA_REMOVE_NPC, 0); + } + + //Return since we have no target + if (!UpdateVictim()) + return; + + if (uiArcaneVacuumTimer <= diff) + { + DoCast(SPELL_ARCANE_VACUUM); + uiArcaneVacuumTimer = 10000; + } else uiArcaneVacuumTimer -= diff; + + if (uiBlizzardTimer <= diff) + { + if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) + DoCast(target, SPELL_BLIZZARD); + uiBlizzardTimer = 15000; + } else uiBlizzardTimer -= diff; + + if (uiTailSweepTimer <= diff) + { + DoCast(SPELL_TAIL_SWEEP); + uiTailSweepTimer = 20000; + } else uiTailSweepTimer -= diff; + + if (uiUncontrollableEnergyTimer <= diff) + { + DoCastVictim(SPELL_UNCONTROLLABLE_ENERGY); + uiUncontrollableEnergyTimer = 25000; + } else uiUncontrollableEnergyTimer -= diff; + + if (IsHeroic()) + { + if (uiManaDestructionTimer <= diff) + { + if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true)) + DoCast(target, SPELL_MANA_DESTRUCTION); + uiManaDestructionTimer = 30000; + } else uiManaDestructionTimer -= diff; + } + + DoMeleeAttackIfReady(); + } + + void JustDied(Unit* /*killer*/) + { + DoScriptText(SAY_DEATH, me); + + if (instance) + instance->SetData(DATA_CYANIGOSA_EVENT, DONE); + } + + void KilledUnit(Unit* victim) + { + if (victim == me) + return; + DoScriptText(RAND(SAY_SLAY_1, SAY_SLAY_2, SAY_SLAY_3), me); + } + }; +}; + +class achievement_defenseless : public AchievementCriteriaScript +{ + public: + achievement_defenseless() : AchievementCriteriaScript("achievement_defenseless") + { + } + + bool OnCheck(Player* /*player*/, Unit* target) + { + if(!target) + return false; + + InstanceScript* instance = target->GetInstanceScript(); + if (!instance) + return false; + + if (!instance->GetData(DATA_DEFENSELESS)) + return false; + + return true; + } +}; + +void AddSC_boss_cyanigosa() +{ + new boss_cyanigosa(); + new achievement_defenseless(); +} \ No newline at end of file diff --git a/pool/shard002/C++/0034631_encoder_containers.cpp b/pool/shard002/C++/0034631_encoder_containers.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a5ca3c43dd625a7c41dc36526db6a4fa11e51ee0 --- /dev/null +++ b/pool/shard002/C++/0034631_encoder_containers.cpp @@ -0,0 +1,84 @@ +/*----------------------------------------------------------------------------- +cboreli - CBOR library + +encoder_containers.cpp + +The MIT License (MIT) + +Copyright (c) 2016 Elisha Kendagor kendagor@live.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. +-----------------------------------------------------------------------------*/ + +#include "encoder.h" +#include "random_number.h" + +using namespace std; +using namespace cboreli; + +codec_res_ptr encoder::add_byte_array(const_str key, vector& value, + item_ptr container){ + item_ptr p = make_shared(); + p->value_type = t_byte_string; + new(&(p->p_byte_string)) arr_uint8_ptr(); + p->p_byte_string = make_shared(value); + return make_result(codec_result::status::ok, codec_result::res_comment_ok, + key, p, container); +} + +codec_res_ptr encoder::add_byte_array(const_str key, arr_uint8& value, + item_ptr container){ + item_ptr p = make_shared(); + p->value_type = t_byte_string; + new(&(p->p_byte_string)) arr_uint8_ptr(); + p->p_byte_string = make_shared(value); + return make_result(codec_result::status::ok, codec_result::res_comment_ok, + key, p, container); +} + +codec_res_ptr encoder::add_byte_array(const_str key, arr_uint8&& value, + item_ptr container){ + item_ptr p = make_shared(); + p->value_type = t_byte_string; + new(&(p->p_byte_string)) arr_uint8_ptr(); + p->p_byte_string = make_shared(value); + return make_result(codec_result::status::ok, codec_result::res_comment_ok, + key, p, container); +} + +codec_res_ptr encoder::add_items_array(const_str key, vector_items& value, + item_ptr container){ + item_ptr p = make_shared(); + p->value_type = t_array; + new(&(p->p_array_items)) vector_items_ptr(); + p->p_array_items = make_shared(value); + return make_result(codec_result::status::ok, codec_result::res_comment_ok, + key, p, container); +} + +codec_res_ptr encoder::add_items_map(const_str key, map_items& value, + item_ptr container){ + item_ptr p = make_shared(); + p->value_type = t_map; + new(&(p->p_map_items)) map_items_ptr(); + p->p_map_items = make_shared(value); + return make_result(codec_result::status::ok, codec_result::res_comment_ok, + key, p, container); +} + diff --git a/pool/shard002/C++/0034634_AppDefaultIconElement.cpp b/pool/shard002/C++/0034634_AppDefaultIconElement.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e814af56b602499da468417fcb24cc064d17b034 --- /dev/null +++ b/pool/shard002/C++/0034634_AppDefaultIconElement.cpp @@ -0,0 +1,93 @@ +/* UOL Messenger + * Copyright (c) 2005 Universo Online S/A + * + * Direitos Autorais Reservados + * All rights reserved + * + * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo + * sob os termos da Licença Pública Geral GNU conforme publicada pela Free + * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) + * qualquer versão posterior. + * Este programa é distribuído na expectativa de que seja útil, porém, + * SEM NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE + * OU ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral + * do GNU para mais detalhes. + * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto + * com este programa; se não, escreva para a Free Software Foundation, Inc., + * no endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * Universo Online S/A - A/C: UOL Messenger 5o. Andar + * Avenida Brigadeiro Faria Lima, 1.384 - Jardim Paulistano + * São Paulo SP - CEP 01452-002 - BRASIL */ + + +#include "stdafx.h" +#include "AppDefaultIconElement.h" + + +CAppDefaultIconElement::CAppDefaultIconElement() +{ +} + + +CAppDefaultIconElement::~CAppDefaultIconElement() +{ +} + + +CString CAppDefaultIconElement::GetName() const +{ + return _T("__AppDefaultIconInstance"); +} + + +void CAppDefaultIconElement::SetParameters(CString2StringMapPtr& pMapParams, IElementTable* pElementTable) +{ + try + { + CString strIconSmall; + GetParameterValue(strIconSmall, pMapParams, "smallicon"); + + m_pIconSmall = ap_dynamic_cast(pElementTable->GetElement(strIconSmall)); + } + catch (const CSkinException&) + { + m_pIconSmall = CIconElementPtr(); + } + + try + { + CString strIconLarge; + GetParameterValue(strIconLarge, pMapParams, "largeicon"); + + m_pIconLarge = ap_dynamic_cast(pElementTable->GetElement(strIconLarge)); + } + catch (const CSkinException&) + { + m_pIconLarge = CIconElementPtr(); + } +} + + +CIconElementPtr CAppDefaultIconElement::GetSmallIcon() const +{ + return m_pIconSmall; +} + + +CIconElementPtr CAppDefaultIconElement::GetLargeIcon() const +{ + return m_pIconLarge; +} \ No newline at end of file diff --git a/pool/shard002/C++/0034638_standalone_example_docs1.cpp b/pool/shard002/C++/0034638_standalone_example_docs1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f88f9883dea0703d86746f887e0a2741fd0d2ed --- /dev/null +++ b/pool/shard002/C++/0034638_standalone_example_docs1.cpp @@ -0,0 +1,87 @@ +/* +Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +. + +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; version 2 of the License. + +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 St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + +/* Standard C++ includes */ +#include +#include + +/* + Include directly the different + headers from cppconn/ and mysql_driver.h + mysql_util.h + (and mysql_connection.h). This will reduce your build time! +*/ +#include "mysql_connection.h" + +#include +#include +#include +#include + +using namespace std; + +int main(void) +{ +cout << endl; +cout << "Running 'SELECT 'Hello World!' AS _message'..." << endl; + +try { + sql::Driver *driver; + sql::Connection *con; + sql::Statement *stmt; + sql::ResultSet *res; + + /* Create a connection */ + driver = sql::mysql::get_driver_instance(); + con = driver->connect("tcp://127.0.0.1:3306", "root", "root"); + /* Connect to the MySQL test database */ + con->setSchema("test"); + + stmt = con->createStatement(); + res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); + while (res->next()) { + cout << "\t... MySQL replies: "; + /* Access column data by alias or column name */ + cout << res->getString("_message") << endl; + cout << "\t... MySQL says it again: "; + /* Access column fata by numeric offset, 1 is the first column */ + cout << res->getString(1) << endl; + } + delete res; + delete stmt; + delete con; + +} catch (sql::SQLException &e) { + cout << "# ERR: SQLException in " << __FILE__; + cout << "(" << EXAMPLE_FUNCTION << ") on line " << __LINE__ << endl; + cout << "# ERR: " << e.what(); + cout << " (MySQL error code: " << e.getErrorCode(); + cout << ", SQLState: " << e.getSQLState() << " )" << endl; +} + +cout << endl; + +return EXIT_SUCCESS; +} diff --git a/pool/shard002/C++/0034641_main.cc b/pool/shard002/C++/0034641_main.cc new file mode 100644 index 0000000000000000000000000000000000000000..0f99a501fe4cb3dd5984ccfe9596dabad16815ec --- /dev/null +++ b/pool/shard002/C++/0034641_main.cc @@ -0,0 +1,83 @@ +#include +#include +#include + +#include "find.h" +#include "parse.h" +#include "argpc.h" +#include "build.h" +#include "plotter.h" +#include "debug.h" +#include "dependencies.h" +#include "argpcoption.h" + +using namespace std; + +bool makefile_specified = false; +string plotfile = ""; +std::string makefile; +extern std::string depfile; + +void set_makefile( std::string file ) +{ + makefile_specified = true; + makefile = file; +} + +void set_depfile( std::string file ) +{ + depfile = file; +} + +void plot( std::string file ) +{ + plotfile = file; +} + +int main(int argc, char *argv[]) +{ + Plotter p; + int ret; + + try { + Argpc *options = Argpc::getInstance( ); + + // Set up the standard argument options + options->addHelp( ); + options->addUsage( ); + options->addVersion( ); + options->setVersion( "0.1" ); + options->setBugAddress( "Aaron Small " ); + options->setDoc( "Yet another make clone" ); + options->setArgumentDescription( "..." ); + options->addOption( ArgpcOption( "file", 'f', "file", "Read FILE as a makefile.", set_makefile ) ); + options->addOption( ArgpcOption( "depfile", 'b', "depfile", "Use specified file as dependency database.", set_depfile ) ); + options->addOption( ArgpcOption( "plot", 'p', "graphfile", "Draw the cached dependency information", plot ) ); + + debug_init( ); + + options->parse( &argc, argv ); + + dependencies_init(); + + if( !makefile_specified ) { + makefile = find_makefile( ); + } + parse_makefile( makefile ); + for( int i = 1; i < argc; i ++ ) { + set_target( argv[i] ); + } + set_default_target(); + if( plotfile != "" ) { + p.open( plotfile ); + set_plotter( &p ); + } + ret = build_targets(); + } catch ( const std::exception &e ) { + cerr << "make: " << e.what() << endl; + dependencies_deinit(); + return 1; + } + dependencies_deinit(); + return ret; +} diff --git a/pool/shard002/C++/0034642_ColourUtils.cpp b/pool/shard002/C++/0034642_ColourUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1bb6fa9563ee3ffff15897308d93ca1592b545d --- /dev/null +++ b/pool/shard002/C++/0034642_ColourUtils.cpp @@ -0,0 +1,76 @@ +// +// ColourUtils.cpp +// Chilli Source +// Created by Scott Downie on 03/04/2014. +// +// The MIT License (MIT) +// +// Copyright (c) 2014 Tag Games Limited +// +// 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 + +#include + +namespace ChilliSource +{ + namespace Core + { + namespace ColourUtils + { + //----------------------------------------------------------- + //----------------------------------------------------------- + ByteColour ColourToByteColour(const Colour& in_colour) + { + return ColourToByteColour(in_colour.r, in_colour.g, in_colour.b, in_colour.a); + } + //----------------------------------------------------------- + //----------------------------------------------------------- + ByteColour ColourToByteColour(f32 in_red, f32 in_green, f32 in_blue, f32 in_alpha) + { + CS_ASSERT(in_red >= 0.0f && in_red <= 1.0f, "Colour must be in range 0.0 - 1.0"); + CS_ASSERT(in_green >= 0.0f && in_green <= 1.0f, "Colour must be in range 0.0 - 1.0"); + CS_ASSERT(in_blue >= 0.0f && in_blue <= 1.0f, "Colour must be in range 0.0 - 1.0"); + CS_ASSERT(in_alpha >= 0.0f && in_alpha <= 1.0f, "Colour must be in range 0.0 - 1.0"); + + ByteColour result; + + result.r = (u8)MathUtils::Round(in_red * 255.0f); + result.g = (u8)MathUtils::Round(in_green * 255.0f); + result.b = (u8)MathUtils::Round(in_blue * 255.0f); + result.a = (u8)MathUtils::Round(in_alpha * 255.0f); + + return result; + } + //----------------------------------------------------------- + //----------------------------------------------------------- + Colour PackedRGBAToColour(u32 in_rgba) + { + u8 byteR = (in_rgba >> 24) & 255; + u8 byteG = (in_rgba >> 16) & 255; + u8 byteB = (in_rgba >> 8) & 255; + u8 byteA = (in_rgba) & 255; + + return Colour((f32)byteR/255.0f, (f32)byteG/255.0f, (f32)byteB/255.0f, (f32)byteA/255.0f); + } + } + } +} diff --git a/pool/shard002/C++/0034643_BigNumber.cpp b/pool/shard002/C++/0034643_BigNumber.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5292f1364b4847176c692f14cb4ab30da8ff2c01 --- /dev/null +++ b/pool/shard002/C++/0034643_BigNumber.cpp @@ -0,0 +1,206 @@ +/* + * + * Copyright (C) 2011-2013 ArkCORE + * + * Copyright (C) 2008-2013 TrinityCore + * + * Copyright (C) 2005-2009 MaNGOS + * + * 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 . + */ + +#include + +#include "Cryptography/BigNumber.h" +#include +#include +#include + +BigNumber::BigNumber() + : _bn(BN_new()), _array(NULL) +{ } + +BigNumber::BigNumber(BigNumber const& bn) + : _bn(BN_dup(bn._bn)), _array(NULL) +{ } + +BigNumber::BigNumber(uint32 val) + : _bn(BN_new()), _array(NULL) +{ + BN_set_word(_bn, val); +} + +BigNumber::~BigNumber() +{ + BN_free(_bn); + delete[] _array; +} + +void BigNumber::SetDword(uint32 val) +{ + BN_set_word(_bn, val); +} + +void BigNumber::SetQword(uint64 val) +{ + BN_add_word(_bn, (uint32)(val >> 32)); + BN_lshift(_bn, _bn, 32); + BN_add_word(_bn, (uint32)(val & 0xFFFFFFFF)); +} + +void BigNumber::SetBinary(uint8 const* bytes, int32 len) +{ + uint8 t[1000]; + for (int i = 0; i < len; i++) t[i] = bytes[len - 1 - i]; + BN_bin2bn(t, len, _bn); +} + +void BigNumber::SetHexStr(char const* str) +{ + BN_hex2bn(&_bn, str); +} + +void BigNumber::SetRand(int32 numbits) +{ + BN_rand(_bn, numbits, 0, 1); +} + +BigNumber& BigNumber::operator=(BigNumber const& bn) +{ + if (this == &bn) + return *this; + + BN_copy(_bn, bn._bn); + return *this; +} + +BigNumber BigNumber::operator+=(BigNumber const& bn) +{ + BN_add(_bn, _bn, bn._bn); + return *this; +} + +BigNumber BigNumber::operator-=(BigNumber const& bn) +{ + BN_sub(_bn, _bn, bn._bn); + return *this; +} + +BigNumber BigNumber::operator*=(BigNumber const& bn) +{ + BN_CTX *bnctx; + + bnctx = BN_CTX_new(); + BN_mul(_bn, _bn, bn._bn, bnctx); + BN_CTX_free(bnctx); + + return *this; +} + +BigNumber BigNumber::operator/=(BigNumber const& bn) +{ + BN_CTX *bnctx; + + bnctx = BN_CTX_new(); + BN_div(_bn, NULL, _bn, bn._bn, bnctx); + BN_CTX_free(bnctx); + + return *this; +} + +BigNumber BigNumber::operator%=(BigNumber const& bn) +{ + BN_CTX *bnctx; + + bnctx = BN_CTX_new(); + BN_mod(_bn, _bn, bn._bn, bnctx); + BN_CTX_free(bnctx); + + return *this; +} + +BigNumber BigNumber::Exp(BigNumber const& bn) +{ + BigNumber ret; + BN_CTX *bnctx; + + bnctx = BN_CTX_new(); + BN_exp(ret._bn, _bn, bn._bn, bnctx); + BN_CTX_free(bnctx); + + return ret; +} + +BigNumber BigNumber::ModExp(BigNumber const& bn1, BigNumber const& bn2) +{ + BigNumber ret; + BN_CTX *bnctx; + + bnctx = BN_CTX_new(); + BN_mod_exp(ret._bn, _bn, bn1._bn, bn2._bn, bnctx); + BN_CTX_free(bnctx); + + return ret; +} + +int32 BigNumber::GetNumBytes(void) +{ + return BN_num_bytes(_bn); +} + +uint32 BigNumber::AsDword() +{ + return (uint32)BN_get_word(_bn); +} + +bool BigNumber::isZero() const +{ + return BN_is_zero(_bn); +} + +uint8* BigNumber::AsByteArray(int32 minSize, bool reverse) +{ + int length = (minSize >= GetNumBytes()) ? minSize : GetNumBytes(); + + ACE_GUARD_RETURN(ACE_Mutex, g, _lock, 0); + + if (_array) + { + delete[] _array; + _array = NULL; + } + _array = new uint8[length]; + + // If we need more bytes than length of BigNumber set the rest to 0 + if (length > GetNumBytes()) + memset((void*)_array, 0, length); + + BN_bn2bin(_bn, (unsigned char *)_array); + + if (reverse) + std::reverse(_array, _array + length); + + return _array; +} + +char * BigNumber::AsHexStr() const +{ + return BN_bn2hex(_bn); +} + +char * BigNumber::AsDecStr() const +{ + return BN_bn2dec(_bn); +} + diff --git a/pool/shard002/C++/0034649_Process_test.cpp b/pool/shard002/C++/0034649_Process_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f351fbc1089316393067c8924ab882a14fac0aee --- /dev/null +++ b/pool/shard002/C++/0034649_Process_test.cpp @@ -0,0 +1,141 @@ + +/* + * Copyright (C) 2017 Anoop Chandran + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * or see +*/ + +#include"Process_test.h" + +Process_test::Process_test() +{} + + +Process_test::~Process_test() +{} + + +void Process_test::run_sleep() +{ + char* args[] = {"/bin/sleep", "2", NULL}; + process.create("/bin/sleep",args,NULL); + process.requester.Connect(this,&Process_test::process_exit); + process.run(); +} + +void Process_test::run_ls() +{ + char* args[] = {"/bin/ls", "-ls", NULL}; + process.create("/bin/ls",args,NULL); + process.requester.Connect(this,&Process_test::process_exit); + process.run(); +} + + +void Process_test::run_a_disable_test() +{ + char* args[] = {"/home/neo/build/OSAL/Process/unit_test/process_test","--gtest_filter=Process_test.print_test",NULL}; + process.create("/home/neo/build/OSAL/Process/unit_test/process_test",args,NULL); + process.requester.Connect(this,&Process_test::process_exit); + process.run(); +} + + +void Process_test::process_exit(uint64_t exit_code, uint32_t exit_signal) +{ + printf("Process_test::process_exit exit_code = %d exit_signal = %d\n", exit_code, exit_signal); +} + + +void Process_test::SetUp() +{ + osal_test_base::SetUp(); +} + + +void Process_test::TearDown() +{ + osal_test_base::TearDown(); +} + + +TEST_F(Process_test, run_sleep ) +{ + printf("start test"); + run_sleep(); + run(); +} + + +TEST_F(Process_test, run_ls ) +{ + printf("start test"); + run_ls(); + run(); +} + + +TEST_F(Process_test, run_a_disable_test ) +{ + printf("start test"); + run_a_disable_test(); + run(); +} + + +TEST_F(Process_test, DISABLED_run_ls ) +{ + printf("start ls test"); +} + +TEST_F(Process_test, print_test ) +{ + fprintf(stderr,"start ls test"); +} + + +#if 0 + +void on_exit(uv_process_t *req, int exit_status, int term_signal) { + fprintf(stderr, "Process exited with status %d, signal %d\n", exit_status, term_signal); + uv_close((uv_handle_t*)req, NULL); +} + +uv_process_options_t options; +TEST_F(Process_test, run_ls_test) +{ + uv_loop_t *loop; + loop = uv_default_loop(); +uv_process_t child_req; + + char *args[] = { "/bin/sleep", "2", NULL }; + + options.exit_cb = NULL; + options.file = "/bin/sleep"; + options.args = args; + options.flags = UV_PROCESS_DETACHED; + fprintf(stderr,"loop %d\n",loop); + int error = uv_spawn(loop, &child_req, &options); + if (error) { + fprintf(stderr, "Error = %s!\n",uv_err_name(error)); + } + fprintf(stderr, "Launched sleep with PID %d\n", child_req.pid); +// uv_unref((uv_handle_t*) &child_req); + + uv_run(loop, UV_RUN_DEFAULT); +} + +#endif diff --git a/pool/shard002/C++/0034658_PhyloTree.cpp b/pool/shard002/C++/0034658_PhyloTree.cpp new file mode 100644 index 0000000000000000000000000000000000000000..300632d59c98963cbf592c6bc8a7f76fc383439a --- /dev/null +++ b/pool/shard002/C++/0034658_PhyloTree.cpp @@ -0,0 +1,326 @@ +/* Copyright (C) 2014 University of Southern California and + * Andrew D. Smith + * + * Authors: Andrew D. Smith and Jenny Qu + * + * 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 . + */ + + +/* + + ABOUT NEWICK FORMAT + ------------------- + + The following should all be legal, according to wikipedia. + + (,,(,)); no nodes are named + (A,B,(C,D)); leaf nodes are named + (A,B,(C,D)E)F; all nodes are named + (:0.1,:0.2,(:0.3,:0.4):0.5); all but root node have a distance to parent + (:0.1,:0.2,(:0.3,:0.4):0.5):0.0; all have a distance to parent + (A:0.1,B:0.2,(C:0.3,D:0.4):0.5); distances and leaf names (popular) + (A:0.1,B:0.2,(C:0.3,D:0.4)E:0.5)F; distances and all names + ((B:0.2,(C:0.3,D:0.4)E:0.5)F:0.1)A; a tree rooted on a leaf node (rare) + + ======================================================================== + + (1) It seems like a tree always ends in a semicolon + (2) Trees need not be binary, but usually are *** + (3) Since the code needs to have uniform nodes, we will always have + a distance, even for the root, but this will be 0.0 + (4) The parsing will look for commas, but not within parentheses + (5) No whitespace will be allowed. It will be removed initially + (6) There is a question of whether to allow commas or colons inside + names, for example by using quotes around the names or trying to + parse intelligently +*/ + + +#include "PhyloTree.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include // for isspace + +#include "smithlab_utils.hpp" + +using std::string; +using std::vector; +using std::endl; +using std::cerr; +using std::cout; +using std::unordered_set; + + +static bool +check_balanced_parentheses(const string &s) { + int count = 0; + for (size_t i = 0; i < s.length(); ++i) { + if (s[i] == '(') ++count; + if (s[i] == ')') --count; + } + return count == 0; +} + + +// static bool +// check_unique_names(const string &s) { +// /// ADS: this function is really poorly coded +// bool is_unique=true; +// string s_copy =s; +// unordered_set names; +// size_t f1, f2; +// while (!s_copy.empty()) { +// f1 = s_copy.find_first_not_of("()0123456789:,;"); +// s_copy.erase(0,f1); +// if (s_copy.empty()) break; +// f2 = s_copy.find_first_of("()0123456789:,;"); +// string name=s_copy.substr(0,f2); +// if (names.find(name)== names.end()){ +// names.insert(name); +// } +// else { +// is_unique=false; +// break; +// } +// } +// return is_unique; +// } + + +void +PhyloTree::PTNode::swap(PTNode &other) { + std::swap(child, other.child); + std::swap(name, other.name); + std::swap(branch_length, other.branch_length); +} + +size_t +PhyloTree::PTNode::get_size() const { + size_t sz = 1; + for (size_t i = 0; i < child.size(); ++i) + sz += child[i].get_size(); + return sz; +} + + +string +PhyloTree::PTNode::tostring(const size_t depth) const { + std::ostringstream oss; + oss << string(depth, '\t') << branch_length << ':' << name; + for (size_t i = 0; i < child.size(); ++i) + oss << endl << child[i].tostring(depth + 1); + return oss.str(); +} + + +string +PhyloTree::PTNode::Newick_format() const { + std::ostringstream oss; + if (!child.empty()) { + oss << '('; + oss << child.front().Newick_format(); + for (size_t i = 1; i < child.size(); ++i) + oss << ',' << child[i].Newick_format(); + oss << ')'; + } + oss << name << ':' << branch_length; + return oss.str(); +} + + +static bool +represents_leaf(const string &tree_rep) { + return (tree_rep.find_first_of(',') == string::npos); +} + + +static string +extract_name(const string &tree_rep) { + const size_t final_parenthesis = tree_rep.find_last_of(")"); + const size_t possible_name_start = + (final_parenthesis == string::npos) ? 0 : final_parenthesis + 1; + const size_t branch_len_start = + std::min(tree_rep.find_first_of(":", possible_name_start), + tree_rep.length()); + return string(tree_rep.begin() + possible_name_start, + tree_rep.begin() + branch_len_start); +} + + +static double +extract_branch_length(const string &tree_rep) { + const size_t final_parenthesis = tree_rep.find_last_of(")"); + const size_t colon_pos = tree_rep.find_first_of(":", final_parenthesis + 1); + if (colon_pos == string::npos) + return 0.0; + const size_t non_numeric = + tree_rep.find_first_not_of("0123456789.", colon_pos + 1); + if (non_numeric == 0) + return 0.0; + return atof(tree_rep.substr(colon_pos + 1).c_str()); +} + + +static bool +root_has_name(const string &tree_rep) { + const size_t final_parenthesis = tree_rep.find_last_of(")"); + const size_t possible_name_start = + (final_parenthesis == string::npos) ? 0 : final_parenthesis; + return (tree_rep[possible_name_start] != ':'); +} + + +static void +extract_subtrees(const string &tree_rep, + vector &subtree_reps) { + const size_t offset = (tree_rep[0] == '(') ? 1 : 0; + const string tmp(tree_rep.begin() + offset, + tree_rep.begin() + tree_rep.find_last_of(")")); + vector split_points; + size_t p_count = 0; + for (size_t i = 0; i < tmp.length(); ++i) { + if (p_count == 0 && tmp[i] == ',') + split_points.push_back(i); + if (tmp[i] == '(') ++p_count; + if (tmp[i] == ')') --p_count; + } + split_points.push_back(tmp.length()); + subtree_reps.push_back(tmp.substr(0, split_points[0])); + for (size_t i = 0; i < split_points.size() - 1; ++i) + subtree_reps.push_back(string(tmp.begin() + split_points[i] + 1, + tmp.begin() + split_points[i + 1])); +} + + +PhyloTree::PTNode::PTNode(const string &tree_rep) { + // This function needs to test the various ways that a string can be + // passed in to represent a subtree at the current node + + branch_length = extract_branch_length(tree_rep); + if (root_has_name(tree_rep)) + name = extract_name(tree_rep); + + if (!represents_leaf(tree_rep)) { + vector subtree_reps; + extract_subtrees(tree_rep, subtree_reps); + for (size_t i = 0; i < subtree_reps.size(); ++i) + child.push_back(PTNode(subtree_reps[i])); + } +} + +void +PhyloTree::PTNode::copy_subtree_with_species(const PTNode &t, + const + unordered_set &species, + PTNode &u) { + if (t.is_leaf()) { + if (species.find(t.name) != species.end()) { + u.name = t.name; + u.branch_length = t.branch_length; + } + } + else { + + vector children; + for (size_t i = 0; i < t.child.size(); ++i) { + PTNode v; + copy_subtree_with_species(t.child[i], species, v); + if (v.has_children() || !v.name.empty()) { + children.push_back(PTNode()); + children.back().swap(v); + } + } + + if (children.size() > 0) { + if (children.size() == 1) { + u.swap(children.front()); + u.branch_length += t.branch_length; + } + else { + u.name = t.name; + u.branch_length = t.branch_length; + u.child.swap(children); + } + } + } +} + + + +//////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////// +//// PHYLO TREE CLASS BELOW HERE //// +//////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////// + + +PhyloTree::PhyloTree(string tree_rep) { + if (!check_balanced_parentheses(tree_rep)) + throw SMITHLABException("Unbalanced parentheses in Newick format: " + + tree_rep); + // remove whitespace + string::iterator w = + std::remove_copy_if(tree_rep.begin(), tree_rep.end(), + tree_rep.begin(), &isspace); + assert(w != tree_rep.begin()); + if (*(w - 1) == ';') + tree_rep.erase(--w, tree_rep.end()); // The "--w" is for the ";" + + /* ADS: requirement for unique names should only apply to leafs + */ + // if (!check_unique_names(tree_rep)) + // throw SMITHLABException("duplicate names in: " + tree_rep); + + root = PTNode(tree_rep); +} + + +void +PhyloTree::copy_subtree_with_species(const PhyloTree &t, + const unordered_set &species, + PhyloTree &u) { + PTNode::copy_subtree_with_species(t.root, species, u.root); +} + + +std::istream& +operator>>(std::istream &in, PhyloTree &t) { + /* doing it this way to just get one tree at a time */ + string r; + char c; + bool found_end = false; + while (!found_end && in >> c) { + r += c; + if (c == ';') + found_end = true; + } + if (!found_end) + throw SMITHLABException("bad tree format"); + t = PhyloTree(r); + return in; +} + + +std::ostream& +operator<<(std::ostream &out, const PhyloTree &t) { + return out << t.Newick_format(); +} diff --git a/pool/shard002/C++/0034662_BitmapWindow.cpp b/pool/shard002/C++/0034662_BitmapWindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4949e63158ac89cf5dcb2c8e46c8ca123b1f8f88 --- /dev/null +++ b/pool/shard002/C++/0034662_BitmapWindow.cpp @@ -0,0 +1,60 @@ +///////////////////////////////////////////////////////////////////////////// +// The GaugeWorks project is released under the GNU Lesser Public License +// with modifications. See the License.txt file for the full text +// Copyright (c) 2007 Brent Picasso http://picasso.org +// Name: BitmapWindow +// Purpose: wxLed implementation +///////////////////////////////////////////////////////////////////////////// +#include "BitmapWindow.h" + +BEGIN_EVENT_TABLE(BitmapWindow,wxWindow) + EVT_PAINT(BitmapWindow::OnPaint) + EVT_SIZE(BitmapWindow::OnSize) + +END_EVENT_TABLE() + +//BitmapWindow::BitmapWindow() : _imageXpm(NULL){} + +BitmapWindow::BitmapWindow( wxWindow *parent, + wxWindowID id, + const char ** xpm_bitmap, + const wxPoint &pos, + const wxSize &size ) +: wxWindow(parent, id, pos, size, 0) +{ + _imageXpm = new wxBitmap(xpm_bitmap); +} + +BitmapWindow::~BitmapWindow(){ + delete (_imageXpm); +} + +void BitmapWindow::SetBitmap(const char ** newXpm){ + if (_imageXpm) delete (_imageXpm); + _imageXpm = new wxBitmap(newXpm); + Refresh(); +} + + +void BitmapWindow::OnSize(wxSizeEvent &event){ + Refresh(); +} + +wxSize BitmapWindow::GetMinSize() const{ + return wxSize(_imageXpm->GetWidth(), _imageXpm->GetHeight()); +} + +void BitmapWindow::OnPaint(wxPaintEvent &event){ + + + int w,h ; + GetClientSize(&w,&h); + + wxPaintDC dc( this ); + PrepareDC( dc ); + dc.SetBackground(*wxTheBrushList->FindOrCreateBrush(GetBackgroundColour(),wxSOLID)); + dc.SetBrush(*wxTheBrushList->FindOrCreateBrush(GetBackgroundColour(),wxSOLID)); + dc.Clear(); + + dc.DrawBitmap(*_imageXpm, w -_imageXpm->GetWidth(),0,true); +} diff --git a/pool/shard002/C++/0034663_task_scheduler_impl_unittest.cc b/pool/shard002/C++/0034663_task_scheduler_impl_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..21a18b0dba8753e14cf37c0b64a1e3a734f31d70 --- /dev/null +++ b/pool/shard002/C++/0034663_task_scheduler_impl_unittest.cc @@ -0,0 +1,263 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/task_scheduler/task_scheduler_impl.h" + +#include + +#include +#include +#include + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/callback.h" +#include "base/macros.h" +#include "base/memory/ptr_util.h" +#include "base/synchronization/lock.h" +#include "base/synchronization/waitable_event.h" +#include "base/task_scheduler/scheduler_worker_pool_params.h" +#include "base/task_scheduler/task_traits.h" +#include "base/task_scheduler/test_task_factory.h" +#include "base/threading/platform_thread.h" +#include "base/threading/simple_thread.h" +#include "base/threading/thread.h" +#include "base/threading/thread_restrictions.h" +#include "base/time/time.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace base { +namespace internal { + +namespace { + +struct TraitsExecutionModePair { + TraitsExecutionModePair(const TaskTraits& traits, + ExecutionMode execution_mode) + : traits(traits), execution_mode(execution_mode) {} + + TaskTraits traits; + ExecutionMode execution_mode; +}; + +#if DCHECK_IS_ON() +// Returns whether I/O calls are allowed on the current thread. +bool GetIOAllowed() { + const bool previous_value = ThreadRestrictions::SetIOAllowed(true); + ThreadRestrictions::SetIOAllowed(previous_value); + return previous_value; +} +#endif + +// Verify that the current thread priority and I/O restrictions are appropriate +// to run a Task with |traits|. +// Note: ExecutionMode is verified inside TestTaskFactory. +void VerifyTaskEnvironement(const TaskTraits& traits) { + const bool supports_background_priority = + Lock::HandlesMultipleThreadPriorities() && + PlatformThread::CanIncreaseCurrentThreadPriority(); + + EXPECT_EQ(supports_background_priority && + traits.priority() == TaskPriority::BACKGROUND + ? ThreadPriority::BACKGROUND + : ThreadPriority::NORMAL, + PlatformThread::GetCurrentThreadPriority()); + +#if DCHECK_IS_ON() + // The #if above is required because GetIOAllowed() always returns true when + // !DCHECK_IS_ON(), even when |traits| don't allow file I/O. + EXPECT_EQ(traits.with_file_io(), GetIOAllowed()); +#endif + + // Verify that the thread the task is running on is named as expected. + const std::string current_thread_name(PlatformThread::GetName()); + EXPECT_NE(std::string::npos, current_thread_name.find("TaskScheduler")); + EXPECT_NE(std::string::npos, + current_thread_name.find( + traits.priority() == TaskPriority::BACKGROUND ? "Background" + : "Foreground")); + EXPECT_EQ(traits.with_file_io(), + current_thread_name.find("FileIO") != std::string::npos); +} + +void VerifyTaskEnvironementAndSignalEvent(const TaskTraits& traits, + WaitableEvent* event) { + DCHECK(event); + VerifyTaskEnvironement(traits); + event->Signal(); +} + +class ThreadPostingTasks : public SimpleThread { + public: + // Creates a thread that posts Tasks to |scheduler| with |traits| and + // |execution_mode|. + ThreadPostingTasks(TaskSchedulerImpl* scheduler, + const TaskTraits& traits, + ExecutionMode execution_mode) + : SimpleThread("ThreadPostingTasks"), + traits_(traits), + factory_(scheduler->CreateTaskRunnerWithTraits(traits, execution_mode), + execution_mode) {} + + void WaitForAllTasksToRun() { factory_.WaitForAllTasksToRun(); } + + private: + void Run() override { + EXPECT_FALSE(factory_.task_runner()->RunsTasksOnCurrentThread()); + + const size_t kNumTasksPerThread = 150; + for (size_t i = 0; i < kNumTasksPerThread; ++i) { + factory_.PostTask(test::TestTaskFactory::PostNestedTask::NO, + Bind(&VerifyTaskEnvironement, traits_)); + } + } + + const TaskTraits traits_; + test::TestTaskFactory factory_; + + DISALLOW_COPY_AND_ASSIGN(ThreadPostingTasks); +}; + +// Returns a vector with a TraitsExecutionModePair for each valid +// combination of {ExecutionMode, TaskPriority, WithFileIO()}. +std::vector GetTraitsExecutionModePairs() { + std::vector params; + + const ExecutionMode execution_modes[] = {ExecutionMode::PARALLEL, + ExecutionMode::SEQUENCED, + ExecutionMode::SINGLE_THREADED}; + + for (ExecutionMode execution_mode : execution_modes) { + for (size_t priority_index = static_cast(TaskPriority::LOWEST); + priority_index <= static_cast(TaskPriority::HIGHEST); + ++priority_index) { + const TaskPriority priority = static_cast(priority_index); + params.push_back(TraitsExecutionModePair( + TaskTraits().WithPriority(priority), execution_mode)); + params.push_back(TraitsExecutionModePair( + TaskTraits().WithPriority(priority).WithFileIO(), execution_mode)); + } + } + + return params; +} + +enum WorkerPoolType { + BACKGROUND_WORKER_POOL = 0, + BACKGROUND_FILE_IO_WORKER_POOL, + FOREGROUND_WORKER_POOL, + FOREGROUND_FILE_IO_WORKER_POOL, +}; + +size_t GetThreadPoolIndexForTraits(const TaskTraits& traits) { + if (traits.with_file_io()) { + return traits.priority() == TaskPriority::BACKGROUND + ? BACKGROUND_FILE_IO_WORKER_POOL + : FOREGROUND_FILE_IO_WORKER_POOL; + } + return traits.priority() == TaskPriority::BACKGROUND ? BACKGROUND_WORKER_POOL + : FOREGROUND_WORKER_POOL; +} + +class TaskSchedulerImplTest + : public testing::TestWithParam { + protected: + TaskSchedulerImplTest() = default; + + void SetUp() override { + using IORestriction = SchedulerWorkerPoolParams::IORestriction; + + std::vector params_vector; + + ASSERT_EQ(BACKGROUND_WORKER_POOL, params_vector.size()); + params_vector.emplace_back("Background", ThreadPriority::BACKGROUND, + IORestriction::DISALLOWED, 1U, TimeDelta::Max()); + + ASSERT_EQ(BACKGROUND_FILE_IO_WORKER_POOL, params_vector.size()); + params_vector.emplace_back("BackgroundFileIO", ThreadPriority::BACKGROUND, + IORestriction::ALLOWED, 3U, TimeDelta::Max()); + + ASSERT_EQ(FOREGROUND_WORKER_POOL, params_vector.size()); + params_vector.emplace_back("Foreground", ThreadPriority::NORMAL, + IORestriction::DISALLOWED, 4U, TimeDelta::Max()); + + ASSERT_EQ(FOREGROUND_FILE_IO_WORKER_POOL, params_vector.size()); + params_vector.emplace_back("ForegroundFileIO", ThreadPriority::NORMAL, + IORestriction::ALLOWED, 12U, TimeDelta::Max()); + + scheduler_ = TaskSchedulerImpl::Create(params_vector, + Bind(&GetThreadPoolIndexForTraits)); + ASSERT_TRUE(scheduler_); + } + + void TearDown() override { scheduler_->JoinForTesting(); } + + std::unique_ptr scheduler_; + + private: + DISALLOW_COPY_AND_ASSIGN(TaskSchedulerImplTest); +}; + +} // namespace + +// Verifies that a Task posted via PostTaskWithTraits with parameterized +// TaskTraits runs on a thread with the expected priority and I/O restrictions. +// The ExecutionMode parameter is ignored by this test. +TEST_P(TaskSchedulerImplTest, PostTaskWithTraits) { + WaitableEvent task_ran(WaitableEvent::ResetPolicy::MANUAL, + WaitableEvent::InitialState::NOT_SIGNALED); + scheduler_->PostTaskWithTraits( + FROM_HERE, GetParam().traits, + Bind(&VerifyTaskEnvironementAndSignalEvent, GetParam().traits, + Unretained(&task_ran))); + task_ran.Wait(); +} + +// Verifies that Tasks posted via a TaskRunner with parameterized TaskTraits and +// ExecutionMode run on a thread with the expected priority and I/O restrictions +// and respect the characteristics of their ExecutionMode. +TEST_P(TaskSchedulerImplTest, PostTasksViaTaskRunner) { + test::TestTaskFactory factory( + scheduler_->CreateTaskRunnerWithTraits(GetParam().traits, + GetParam().execution_mode), + GetParam().execution_mode); + EXPECT_FALSE(factory.task_runner()->RunsTasksOnCurrentThread()); + + const size_t kNumTasksPerTest = 150; + for (size_t i = 0; i < kNumTasksPerTest; ++i) { + factory.PostTask(test::TestTaskFactory::PostNestedTask::NO, + Bind(&VerifyTaskEnvironement, GetParam().traits)); + } + + factory.WaitForAllTasksToRun(); +} + +INSTANTIATE_TEST_CASE_P(OneTraitsExecutionModePair, + TaskSchedulerImplTest, + ::testing::ValuesIn(GetTraitsExecutionModePairs())); + +// Spawns threads that simultaneously post Tasks to TaskRunners with various +// TaskTraits and ExecutionModes. Verifies that each Task runs on a thread with +// the expected priority and I/O restrictions and respects the characteristics +// of its ExecutionMode. +TEST_F(TaskSchedulerImplTest, MultipleTraitsExecutionModePairs) { + std::vector> threads_posting_tasks; + for (const auto& traits_execution_mode_pair : GetTraitsExecutionModePairs()) { + threads_posting_tasks.push_back(WrapUnique(new ThreadPostingTasks( + scheduler_.get(), traits_execution_mode_pair.traits, + traits_execution_mode_pair.execution_mode))); + threads_posting_tasks.back()->Start(); + } + + for (const auto& thread : threads_posting_tasks) { + thread->WaitForAllTasksToRun(); + thread->Join(); + } +} + +// TODO(fdoray): Add tests with Sequences that move around worker pools once +// child TaskRunners are supported. + +} // namespace internal +} // namespace base diff --git a/pool/shard002/C++/0034682_updategeomatchsetresponse.cpp b/pool/shard002/C++/0034682_updategeomatchsetresponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9adedba52468edaddf8b25cbb2f16dce11a6828a --- /dev/null +++ b/pool/shard002/C++/0034682_updategeomatchsetresponse.cpp @@ -0,0 +1,121 @@ +/* + Copyright 2013-2021 Paul Colby + + This file is part of QtAws. + + QtAws 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. + + QtAws 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 QtAws. If not, see . +*/ + +#include "updategeomatchsetresponse.h" +#include "updategeomatchsetresponse_p.h" + +#include +#include +#include + +namespace QtAws { +namespace WAF { + +/*! + * \class QtAws::WAF::UpdateGeoMatchSetResponse + * \brief The UpdateGeoMatchSetResponse class provides an interace for WAF UpdateGeoMatchSet responses. + * + * \inmodule QtAwsWAF + * + * + * + * This is AWS WAF Classic documentation. For more information, see AWS WAF Classic in the + * developer + * + * guide> + * + * For the latest version of AWS WAF, use the AWS WAFV2 API and see the AWS WAF Developer Guide. With the + * latest version, AWS WAF has a single set of endpoints for regional and global use. + * + *

+ * + * This is the AWS WAF Classic API Reference for using AWS WAF Classic with Amazon CloudFront. The AWS WAF Classic + * actions and data types listed in the reference are available for protecting Amazon CloudFront distributions. You can use + * these actions and data types via the endpoint waf.amazonaws.com. This guide is for developers who need detailed + * information about the AWS WAF Classic API actions, data types, and errors. For detailed information about AWS WAF + * Classic features and an overview of how to use the AWS WAF Classic API, see the AWS WAF Classic in the + * developer + * + * \sa WafClient::updateGeoMatchSet + */ + +/*! + * Constructs a UpdateGeoMatchSetResponse object for \a reply to \a request, with parent \a parent. + */ +UpdateGeoMatchSetResponse::UpdateGeoMatchSetResponse( + const UpdateGeoMatchSetRequest &request, + QNetworkReply * const reply, + QObject * const parent) + : WafResponse(new UpdateGeoMatchSetResponsePrivate(this), parent) +{ + setRequest(new UpdateGeoMatchSetRequest(request)); + setReply(reply); +} + +/*! + * \reimp + */ +const UpdateGeoMatchSetRequest * UpdateGeoMatchSetResponse::request() const +{ + Q_D(const UpdateGeoMatchSetResponse); + return static_cast(d->request); +} + +/*! + * \reimp + * Parses a successful WAF UpdateGeoMatchSet \a response. + */ +void UpdateGeoMatchSetResponse::parseSuccess(QIODevice &response) +{ + //Q_D(UpdateGeoMatchSetResponse); + QXmlStreamReader xml(&response); + /// @todo +} + +/*! + * \class QtAws::WAF::UpdateGeoMatchSetResponsePrivate + * \brief The UpdateGeoMatchSetResponsePrivate class provides private implementation for UpdateGeoMatchSetResponse. + * \internal + * + * \inmodule QtAwsWAF + */ + +/*! + * Constructs a UpdateGeoMatchSetResponsePrivate object with public implementation \a q. + */ +UpdateGeoMatchSetResponsePrivate::UpdateGeoMatchSetResponsePrivate( + UpdateGeoMatchSetResponse * const q) : WafResponsePrivate(q) +{ + +} + +/*! + * Parses a WAF UpdateGeoMatchSet response element from \a xml. + */ +void UpdateGeoMatchSetResponsePrivate::parseUpdateGeoMatchSetResponse(QXmlStreamReader &xml) +{ + Q_ASSERT(xml.name() == QLatin1String("UpdateGeoMatchSetResponse")); + Q_UNUSED(xml) ///< @todo +} + +} // namespace WAF +} // namespace QtAws diff --git a/pool/shard002/C++/0034688_output_m001u006.cpp b/pool/shard002/C++/0034688_output_m001u006.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba0eb77b171d5ab4ff16dda5bd2f9bfcf4e14921 --- /dev/null +++ b/pool/shard002/C++/0034688_output_m001u006.cpp @@ -0,0 +1,29 @@ +#include +#include "gtest/gtest.h" +#include "test_miranda.hpp" + +namespace { + +class OM001U006 : public TestIOBase { +protected: + OM001U006() { + IFNAME1 = (char *) "mir_001.fasta"; + IFNAME2 = (char *) "utr3_006.fasta"; + O1FNAME1 = (char *) "test_output1_site_6.txt"; + O1FNAME2 = (char *) "test_output1_mrna_6.txt"; + O2FNAME1 = (char *) "test_output2_site_6.txt"; + O2FNAME2 = (char *) "test_output2_mrna_6.txt"; + OMPATH = (char *) "mk_miranda/"; + } +}; + +TEST_F(OM001U006, comp_site) { + (void) mikan::MKCoreMain(argc, (const char **) argv); + gtest_compare_two_files(o1file1, o2file1); +} + +TEST_F(OM001U006, comp_mrna) { + (void) mikan::MKCoreMain(argc, (const char **) argv); + gtest_compare_two_files(o1file2, o2file2); +} +} \ No newline at end of file diff --git a/pool/shard002/C++/0034689_emi2.cpp b/pool/shard002/C++/0034689_emi2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b5126f91edcd0a22d1da9f1ef898696506636cc8 --- /dev/null +++ b/pool/shard002/C++/0034689_emi2.cpp @@ -0,0 +1,140 @@ +/* + EIBD eib bus access and management daemon + Copyright (C) 2005-2011 Martin Koegler + + 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. +*/ + +#include "emi2.h" + +#include "emi.h" + +EMI2Driver::EMI2Driver (LowLevelIface* c, IniSectionPtr& s, LowLevelDriver *i) : EMI_Common(c,s,i) +{ + t->setAuxName("EMI2"); + sendLocal_done.set(this); +} + +void +EMI2Driver::sendLocal_done_cb(bool success) +{ + if (!success || sendLocal_done_next == N_bad) + { + errored(); + LowLevelFilter::stopped(); + } + else if (sendLocal_done_next == N_down) + LowLevelFilter::stop(); + else if (sendLocal_done_next == N_up) + LowLevelFilter::started(); + else if (sendLocal_done_next == N_open) + { + sendLocal_done_next = N_up; + const uint8_t t2[] = { 0xa9, 0x00, 0x18, 0x34, 0x56, 0x78, 0x0a }; + send_Local (CArray (t2, sizeof (t2)),1); + } + else if (sendLocal_done_next == N_enter) + { + sendLocal_done_next = N_up; + const uint8_t t2[] = { 0xa9, 0x90, 0x18, 0x34, 0x45, 0x67, 0x8a }; + send_Local (CArray (t2, sizeof (t2)),1); + } + +} + +void +EMI2Driver::cmdEnterMonitor () +{ + sendLocal_done_next = N_enter; + const uint8_t t1[] = { 0xa9, 0x1E, 0x12, 0x34, 0x56, 0x78, 0x9a }; + send_Local (CArray (t1, sizeof (t1)),1); +} + +void +EMI2Driver::cmdLeaveMonitor () +{ + if (wait_confirm_low) + { + sendLocal_done_next = N_want_leave; + return; + } + sendLocal_done_next = N_down; + uint8_t t[] = { 0xa9, 0x1E, 0x12, 0x34, 0x56, 0x78, 0x9a }; + send_Local (CArray (t, sizeof (t)),1); +} + +void +EMI2Driver::cmdOpen () +{ + sendLocal_done_next = N_open; + const uint8_t t1[] = { 0xa9, 0x1E, 0x12, 0x34, 0x56, 0x78, 0x9a }; + send_Local (CArray (t1, sizeof (t1)),1); +} + +void +EMI2Driver::cmdClose () +{ + if (wait_confirm_low) + { + sendLocal_done_next = N_want_close; + return; + } + sendLocal_done_next = N_down; + uint8_t t[] = { 0xa9, 0x1E, 0x12, 0x34, 0x56, 0x78, 0x9a }; + send_Local (CArray (t, sizeof (t)),1); +} + +void EMI2Driver::started() +{ + reset_ack_wait = true; + reset_timer.start(0.5, 0); + sendReset(); +} + +void EMI2Driver::reset_timer_cb(ev::timer&, int) +{ + ERRORPRINTF(t, E_ERROR | 57, "reset timed out"); + errored(); +} + +void EMI2Driver::do_send_Next() +{ + if (reset_ack_wait) + { + reset_ack_wait = false; + reset_timer.stop(); + EMI_Common::started(); + } + else if (sendLocal_done_next == N_want_close) + { + wait_confirm_low = false; + cmdClose(); + } + else if (sendLocal_done_next == N_want_leave) + { + wait_confirm_low = false; + cmdLeaveMonitor(); + } + else + EMI_Common::do_send_Next(); +} + +const uint8_t * +EMI2Driver::getIndTypes() const +{ + static const uint8_t indTypes[] = { 0x2E, 0x29, 0x2B }; + return indTypes; +} + diff --git a/pool/shard002/C++/0034691_memoryagent.cpp b/pool/shard002/C++/0034691_memoryagent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ecb8b44ad2a68e8750debf150ea67305563b7a66 --- /dev/null +++ b/pool/shard002/C++/0034691_memoryagent.cpp @@ -0,0 +1,317 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +****************************************************************************/ + +#include "memoryagent.h" +#include "memoryview.h" + +#include "breakhandler.h" +#include "debuggerengine.h" +#include "debuggerstartparameters.h" +#include "debuggercore.h" +#include "debuggerinternalconstants.h" + +#include +#include +#include + +#include +#include +#include + +#include + +#include + +using namespace Core; + +namespace Debugger { +namespace Internal { + +/////////////////////////////////////////////////////////////////////// +// +// MemoryAgent +// +/////////////////////////////////////////////////////////////////////// + +/*! + \class Debugger::Internal::MemoryAgent + + Objects form this class are created in response to user actions in + the Gui for showing raw memory from the inferior. After creation + it handles communication between the engine and the bineditor. + + Memory can be shown as + \list + \li Editor: Create an IEditor using the normal editor factory + interface (m_editors) + \li View: Separate top-level view consisting of a Bin Editor widget + (m_view). + \endlist + + Views are updated on the DebuggerEngine::stackFrameCompleted signal. + An exception are views of class Debugger::RegisterMemoryView tracking the + content pointed to by a register (eg stack pointer, instruction pointer). + They are connected to the set/changed signals of + the engine's register handler. + + \sa Debugger::MemoryView, Debugger::RegisterMemoryView +*/ + +MemoryAgent::MemoryAgent(DebuggerEngine *engine) + : QObject(engine), m_engine(engine) +{ + QTC_CHECK(engine); + connect(engine, SIGNAL(stateChanged(Debugger::DebuggerState)), + this, SLOT(engineStateChanged(Debugger::DebuggerState))); + connect(engine, SIGNAL(stackFrameCompleted()), this, + SLOT(updateContents())); +} + +MemoryAgent::~MemoryAgent() +{ + closeEditors(); + closeViews(); +} + +void MemoryAgent::closeEditors() +{ + if (m_editors.isEmpty()) + return; + + QSet documents; + foreach (QPointer editor, m_editors) + if (editor) + documents.insert(editor->document()); + EditorManager::closeDocuments(documents.toList()); + m_editors.clear(); +} + +void MemoryAgent::closeViews() +{ + foreach (const QPointer &w, m_views) + if (w) + w->close(); + m_views.clear(); +} + +void MemoryAgent::updateMemoryView(quint64 address, quint64 length) +{ + m_engine->fetchMemory(this, sender(), address, length); +} + +void MemoryAgent::connectBinEditorWidget(QWidget *w) +{ + connect(w, SIGNAL(dataRequested(quint64)), SLOT(fetchLazyData(quint64))); + connect(w, SIGNAL(newWindowRequested(quint64)), SLOT(createBinEditor(quint64))); + connect(w, SIGNAL(newRangeRequested(quint64)), SLOT(provideNewRange(quint64))); + connect(w, SIGNAL(dataChanged(quint64,QByteArray)), SLOT(handleDataChanged(quint64,QByteArray))); + connect(w, SIGNAL(dataChanged(quint64,QByteArray)), SLOT(handleDataChanged(quint64,QByteArray))); + connect(w, SIGNAL(addWatchpointRequested(quint64,uint)), SLOT(handleWatchpointRequest(quint64,uint))); +} + +bool MemoryAgent::doCreateBinEditor(quint64 addr, unsigned flags, + const QList &ml, const QPoint &pos, + QString title, QWidget *parent) +{ + const bool readOnly = (flags & DebuggerEngine::MemoryReadOnly) != 0; + if (title.isEmpty()) + title = tr("Memory at 0x%1").arg(addr, 0, 16); + // Separate view? + if (flags & DebuggerEngine::MemoryView) { + // Ask BIN editor plugin for factory service and have it create a bin editor widget. + QWidget *binEditor = 0; + if (QObject *factory = ExtensionSystem::PluginManager::getObjectByClassName(QLatin1String("BinEditor::BinEditorWidgetFactory"))) + binEditor = ExtensionSystem::invoke(factory, "createWidget", (QWidget *)0); + if (!binEditor) + return false; + connectBinEditorWidget(binEditor); + MemoryView::setBinEditorReadOnly(binEditor, readOnly); + MemoryView::setBinEditorNewWindowRequestAllowed(binEditor, true); + MemoryView *topLevel = 0; + // Memory view tracking register value, providing its own updating mechanism. + if (flags & DebuggerEngine::MemoryTrackRegister) { + RegisterMemoryView *rmv = new RegisterMemoryView(binEditor, parent); + rmv->init(m_engine->registerHandler(), int(addr)); + topLevel = rmv; + } else { + // Ordinary memory view + MemoryView::setBinEditorMarkup(binEditor, ml); + MemoryView::setBinEditorRange(binEditor, addr, MemoryAgent::DataRange, MemoryAgent::BinBlockSize); + topLevel = new MemoryView(binEditor, parent); + topLevel->setWindowTitle(title); + } + m_views << topLevel; + topLevel->move(pos); + topLevel->show(); + return true; + } + // Editor: Register tracking not supported. + QTC_ASSERT(!(flags & DebuggerEngine::MemoryTrackRegister), return false); + if (!title.endsWith(QLatin1Char('$'))) + title.append(QLatin1String(" $")); + IEditor *editor = EditorManager::openEditorWithContents( + Core::Constants::K_DEFAULT_BINARY_EDITOR_ID, &title); + if (!editor) + return false; + editor->document()->setProperty(Constants::OPENED_BY_DEBUGGER, QVariant(true)); + editor->document()->setTemporary(true); + QWidget *editorBinEditor = editor->widget(); + connectBinEditorWidget(editorBinEditor); + MemoryView::setBinEditorReadOnly(editorBinEditor, readOnly); + MemoryView::setBinEditorNewWindowRequestAllowed(editorBinEditor, true); + MemoryView::setBinEditorRange(editorBinEditor, addr, MemoryAgent::DataRange, MemoryAgent::BinBlockSize); + MemoryView::setBinEditorMarkup(editorBinEditor, ml); + m_editors << editor; + return true; +} + +void MemoryAgent::createBinEditor(quint64 addr, unsigned flags, + const QList &ml, const QPoint &pos, + const QString &title, QWidget *parent) +{ + if (!doCreateBinEditor(addr, flags, ml, pos, title, parent)) + showMessageBox(QMessageBox::Warning, + tr("No Memory Viewer Available"), + tr("The memory contents cannot be shown as no viewer plugin " + "for binary data has been loaded.")); +} + +void MemoryAgent::createBinEditor(quint64 addr) +{ + createBinEditor(addr, 0, QList(), QPoint(), QString(), 0); +} + +void MemoryAgent::fetchLazyData(quint64 block) +{ + m_engine->fetchMemory(this, sender(), BinBlockSize * block, BinBlockSize); +} + +void MemoryAgent::addLazyData(QObject *editorToken, quint64 addr, + const QByteArray &ba) +{ + QWidget *w = qobject_cast(editorToken); + QTC_ASSERT(w, return); + MemoryView::binEditorAddData(w, addr, ba); +} + +void MemoryAgent::provideNewRange(quint64 address) +{ + QWidget *w = qobject_cast(sender()); + QTC_ASSERT(w, return); + MemoryView::setBinEditorRange(w, address, DataRange, BinBlockSize); +} + +void MemoryAgent::handleDataChanged(quint64 addr, const QByteArray &data) +{ + m_engine->changeMemory(this, sender(), addr, data); +} + +void MemoryAgent::handleWatchpointRequest(quint64 address, uint size) +{ + m_engine->breakHandler()->setWatchpointAtAddress(address, size); +} + +void MemoryAgent::updateContents() +{ + foreach (const QPointer &e, m_editors) + if (e) + MemoryView::binEditorUpdateContents(e->widget()); + // Update all views except register views, which trigger on + // register value set/changed. + foreach (const QPointer &w, m_views) + if (w && !qobject_cast(w.data())) + w->updateContents(); +} + +bool MemoryAgent::hasVisibleEditor() const +{ + QList visible = EditorManager::visibleEditors(); + foreach (QPointer editor, m_editors) + if (visible.contains(editor.data())) + return true; + return false; +} + +void MemoryAgent::engineStateChanged(Debugger::DebuggerState s) +{ + switch (s) { + case DebuggerFinished: + closeViews(); + foreach (const QPointer &editor, m_editors) + if (editor) { // Prevent triggering updates, etc. + MemoryView::setBinEditorReadOnly(editor->widget(), true); + editor->widget()->disconnect(this); + } + break; + default: + break; + } +} + +bool MemoryAgent::isBigEndian(const ProjectExplorer::Abi &a) +{ + switch (a.architecture()) { + case ProjectExplorer::Abi::UnknownArchitecture: + case ProjectExplorer::Abi::X86Architecture: + case ProjectExplorer::Abi::ItaniumArchitecture: // Configureable + case ProjectExplorer::Abi::ArmArchitecture: // Configureable + case ProjectExplorer::Abi::ShArchitecture: // Configureable + break; + case ProjectExplorer::Abi::MipsArchitecture: // Configureable + case ProjectExplorer::Abi::PowerPCArchitecture: // Configureable + return true; + } + return false; +} + +// Read a POD variable from a memory location. Swap bytes if endianness differs +template POD readPod(const unsigned char *data, bool swapByteOrder) +{ + POD pod = 0; + if (swapByteOrder) { + unsigned char *target = reinterpret_cast(&pod) + sizeof(POD) - 1; + for (size_t i = 0; i < sizeof(POD); i++) + *target-- = data[i]; + } else { + std::memcpy(&pod, data, sizeof(POD)); + } + return pod; +} + +// Read memory from debuggee +quint64 MemoryAgent::readInferiorPointerValue(const unsigned char *data, const ProjectExplorer::Abi &a) +{ + const bool swapByteOrder = isBigEndian(a) != isBigEndian(ProjectExplorer::Abi::hostAbi()); + return a.wordWidth() == 32 ? readPod(data, swapByteOrder) : + readPod(data, swapByteOrder); +} + +} // namespace Internal +} // namespace Debugger +; diff --git a/pool/shard002/C++/0034694_ProcessStartInfoUnitTests.cpp b/pool/shard002/C++/0034694_ProcessStartInfoUnitTests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bd22b3adee8cd2479f20bb35dc281721711b0500 --- /dev/null +++ b/pool/shard002/C++/0034694_ProcessStartInfoUnitTests.cpp @@ -0,0 +1,82 @@ +#include +#include +#include + +using namespace System; +using namespace System::Diagnostics; + +namespace UnitTests { + TEST(ProcessStartInfoUnitTest, Constructor) { + ProcessStartInfo psi; + ASSERT_EQ(string::Empty, psi.Arguments); + ASSERT_FALSE(psi.CreateNoWindow); + ASSERT_EQ(string::Empty, psi.Domain); + ASSERT_EQ(0, psi.EnvironmentVariables().Count); + ASSERT_FALSE(psi.ErrorDialog); + ASSERT_EQ(0, psi.ErrorDialogParamHandle()); + ASSERT_EQ(string::Empty, psi.FileName); + ASSERT_FALSE(psi.LoadUserProfile); + ASSERT_EQ(string::Empty, psi.PasswordInClearText); + ASSERT_FALSE(psi.RedirectStandardError); + ASSERT_FALSE(psi.RedirectStandardInput); + ASSERT_FALSE(psi.RedirectStandardOutput); + } + + TEST(ProcessStartInfoUnitTest, ConstructorWithFileName) { + ProcessStartInfo psi("FileName"); + ASSERT_EQ(string::Empty, psi.Arguments); + ASSERT_FALSE(psi.CreateNoWindow); + ASSERT_EQ(string::Empty, psi.Domain); + ASSERT_EQ(0, psi.EnvironmentVariables().Count); + ASSERT_FALSE(psi.ErrorDialog); + ASSERT_EQ(0, psi.ErrorDialogParamHandle()); + ASSERT_EQ("FileName", psi.FileName); + ASSERT_FALSE(psi.LoadUserProfile); + ASSERT_EQ(string::Empty, psi.PasswordInClearText); + ASSERT_FALSE(psi.RedirectStandardError); + ASSERT_FALSE(psi.RedirectStandardInput); + ASSERT_FALSE(psi.RedirectStandardOutput); + } + + TEST(ProcessStartInfoUnitTest, ConstructorWithFileNameAndArgument) { + ProcessStartInfo psi("FileName", "Arguments"); + ASSERT_EQ("Arguments", psi.Arguments); + ASSERT_FALSE(psi.CreateNoWindow); + ASSERT_EQ(string::Empty, psi.Domain); + ASSERT_EQ(0, psi.EnvironmentVariables().Count); + ASSERT_FALSE(psi.ErrorDialog); + ASSERT_EQ(0, psi.ErrorDialogParamHandle()); + ASSERT_EQ("FileName", psi.FileName); + ASSERT_FALSE(psi.LoadUserProfile); + ASSERT_EQ(string::Empty, psi.PasswordInClearText); + ASSERT_FALSE(psi.RedirectStandardError); + ASSERT_FALSE(psi.RedirectStandardInput); + ASSERT_FALSE(psi.RedirectStandardOutput); + } + + TEST(ProcessStartInfoUnitTest, ConstructorByCopy) { + ProcessStartInfo psiOriginal("FileName", "Arguments"); + ProcessStartInfo psi = psiOriginal; + ASSERT_EQ(psiOriginal.Arguments, psi.Arguments); + ASSERT_EQ(psiOriginal.CreateNoWindow, psi.CreateNoWindow); + ASSERT_EQ(psiOriginal.Domain, psi.Domain); + ASSERT_EQ(psiOriginal.EnvironmentVariables, psi.EnvironmentVariables); + ASSERT_EQ(psiOriginal.ErrorDialog, psi.ErrorDialog); + ASSERT_EQ(psiOriginal.ErrorDialogParamHandle, psi.ErrorDialogParamHandle); + ASSERT_EQ(psiOriginal.FileName, psi.FileName); + } + + TEST(ProcessStartInfoUnitTest, SetPasswordThenCheckPasswordInClearText) { + ProcessStartInfo psi; + char32 password[] = {'M', 'y', ' ', 'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; + psi.Pasword = System::Security::SecureString(password, 11); + ASSERT_EQ("My password", psi.PasswordInClearText); + } + + TEST(ProcessStartInfoUnitTest, SetPasswordInClearTextThenCheckPasswordInClearText) { + ProcessStartInfo psi; + psi.PasswordInClearText = "My password"; + ASSERT_EQ("My password", psi.PasswordInClearText); + } +} + diff --git a/pool/shard002/C++/0034699_ioutil_test.cpp b/pool/shard002/C++/0034699_ioutil_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b15f5701e1e68f38bd079c86aa8bdd223fdb6d8 --- /dev/null +++ b/pool/shard002/C++/0034699_ioutil_test.cpp @@ -0,0 +1,20 @@ +#include "libreactor/ioutil.h" +#include "libreactor/misc.h" +#include + +int main() { + Reactor reactor; + + std::vector fds = fd_pair(reactor); + + ioutil::write(fds[0], ByteString::copy_from("hello")).wait(reactor); + ioutil::read(fds[1], 4).then([&](ByteString ret) { + std::cerr << ret << std::endl; + return ioutil::read(fds[1], 1); + }).then([](ByteString ret) { + std::cerr << ret << std::endl; + return unit(); + }).wait(reactor); + + exit(0); +} diff --git a/pool/shard002/C++/0034704_coincontroltreewidget.cpp b/pool/shard002/C++/0034704_coincontroltreewidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4e250600f56c16b7fdb9bcdd88add82871295947 --- /dev/null +++ b/pool/shard002/C++/0034704_coincontroltreewidget.cpp @@ -0,0 +1,33 @@ +// Copyright (c) 2011-2015 The Oakcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "coincontroltreewidget.h" +#include "coincontroldialog.h" + +CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) : + QTreeWidget(parent) +{ + +} + +void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event) +{ + if (event->key() == Qt::Key_Space) // press spacebar -> select checkbox + { + event->ignore(); + int COLUMN_CHECKBOX = 0; + if(this->currentItem()) + this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked)); + } + else if (event->key() == Qt::Key_Escape) // press esc -> close dialog + { + event->ignore(); + CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget(); + coinControlDialog->done(QDialog::Accepted); + } + else + { + this->QTreeWidget::keyPressEvent(event); + } +} diff --git a/pool/shard002/C++/0034707_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memmove_65b.cpp b/pool/shard002/C++/0034707_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memmove_65b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4de24f7dcb8f4080e8410511ea13256c9e39a427 --- /dev/null +++ b/pool/shard002/C++/0034707_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memmove_65b.cpp @@ -0,0 +1,62 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memmove_65b.cpp +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193.label.xml +Template File: sources-sink-65b.tmpl.cpp +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate memory for a string, but do not allocate space for NULL terminator + * GoodSource: Allocate enough memory for a string and the NULL terminator + * Sinks: memmove + * BadSink : Copy string to data using memmove() + * Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer + * + * */ + +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +/* MAINTENANCE NOTE: The length of this string should equal the 10 */ +#define SRC_STRING "AAAAAAAAAA" + +namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memmove_65 +{ + +#ifndef OMITBAD + +void badSink(char * data) +{ + { + char source[10+1] = SRC_STRING; + /* Copy length + 1 to include NUL terminator from source */ + /* POTENTIAL FLAW: data may not have enough space to hold source */ + memmove(data, source, (strlen(source) + 1) * sizeof(char)); + printLine(data); + delete [] data; + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(char * data) +{ + { + char source[10+1] = SRC_STRING; + /* Copy length + 1 to include NUL terminator from source */ + /* POTENTIAL FLAW: data may not have enough space to hold source */ + memmove(data, source, (strlen(source) + 1) * sizeof(char)); + printLine(data); + delete [] data; + } +} + +#endif /* OMITGOOD */ + +} /* close namespace */ diff --git a/pool/shard002/C++/0034708_QxSqlLimit.cpp b/pool/shard002/C++/0034708_QxSqlLimit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..38e39348d4e257ce33df0e3f479e46c991e5d6dd --- /dev/null +++ b/pool/shard002/C++/0034708_QxSqlLimit.cpp @@ -0,0 +1,110 @@ +/**************************************************************************** +** +** http://www.qxorm.com/ +** http://sourceforge.net/projects/qxorm/ +** Original file by Lionel Marty +** +** This file is part of the QxOrm library +** +** This software is provided 'as-is', without any express or implied +** warranty. In no event will the authors be held liable for any +** damages arising from the use of this software. +** +** GNU Lesser General Public License Usage +** This file must be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file 'license.lgpl.txt' included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** If you have questions regarding the use of this file, please contact : +** contact@qxorm.com +** +****************************************************************************/ + +#include + +#include + +#include + +#include + +namespace qx { +namespace dao { +namespace detail { + +QxSqlLimit::QxSqlLimit(int index) : IxSqlElement(index) { ; } + +QxSqlLimit::~QxSqlLimit() { ; } + +QString QxSqlLimit::toString() const +{ + if (! m_pSqlGenerator) { qAssert(false); return ""; } + return m_pSqlGenerator->getLimit(this); +} + +void QxSqlLimit::resolve(QSqlQuery & query) const +{ + if (! m_pSqlGenerator) { qAssert(false); return; } + m_pSqlGenerator->resolveLimit(query, this); +} + +void QxSqlLimit::postProcess(QString & sql) const +{ + if (! m_pSqlGenerator) { qAssert(false); return; } + m_pSqlGenerator->postProcess(sql, this); +} + +int QxSqlLimit::getStartRow() const +{ + qAssert(m_lstValues.count() == 2); + return ((m_lstValues.count() > 0) ? m_lstValues.at(0).toInt() : 0); +} + +int QxSqlLimit::getRowsCount() const +{ + qAssert(m_lstValues.count() == 2); + return ((m_lstValues.count() > 1) ? m_lstValues.at(1).toInt() : 0); +} + +int QxSqlLimit::getMaxRow() const +{ + qAssert(m_lstValues.count() == 2); + return ((m_lstValues.count() > 1) ? (m_lstValues.at(0).toInt() + m_lstValues.at(1).toInt()) : 0); +} + +QString QxSqlLimit::getStartRow_ParamKey() const +{ + QString sStartRow("offset_start_row"); + sStartRow += "_" + QString::number(m_iIndex) + "_0"; + if (qx::QxSqlDatabase::getSingleton()->getSqlPlaceHolderStyle() == qx::QxSqlDatabase::ph_style_question_mark) { sStartRow = "?"; } + else if (qx::QxSqlDatabase::getSingleton()->getSqlPlaceHolderStyle() == qx::QxSqlDatabase::ph_style_at_name) { sStartRow = "@" + sStartRow; } + else { sStartRow = ":" + sStartRow; } + return sStartRow; +} + +QString QxSqlLimit::getRowsCount_ParamKey() const +{ + QString sRowsCount("limit_rows_count"); + sRowsCount += "_" + QString::number(m_iIndex) + "_0"; + if (qx::QxSqlDatabase::getSingleton()->getSqlPlaceHolderStyle() == qx::QxSqlDatabase::ph_style_question_mark) { sRowsCount = "?"; } + else if (qx::QxSqlDatabase::getSingleton()->getSqlPlaceHolderStyle() == qx::QxSqlDatabase::ph_style_at_name) { sRowsCount = "@" + sRowsCount; } + else { sRowsCount = ":" + sRowsCount; } + return sRowsCount; +} + +QString QxSqlLimit::getMaxRow_ParamKey() const +{ + QString sMaxRow("offset_max_row"); + sMaxRow += "_" + QString::number(m_iIndex) + "_0"; + if (qx::QxSqlDatabase::getSingleton()->getSqlPlaceHolderStyle() == qx::QxSqlDatabase::ph_style_question_mark) { sMaxRow = "?"; } + else if (qx::QxSqlDatabase::getSingleton()->getSqlPlaceHolderStyle() == qx::QxSqlDatabase::ph_style_at_name) { sMaxRow = "@" + sMaxRow; } + else { sMaxRow = ":" + sMaxRow; } + return sMaxRow; +} + +} // namespace detail +} // namespace dao +} // namespace qx diff --git a/pool/shard002/C++/0034717_ThirdPartyUtil.cpp b/pool/shard002/C++/0034717_ThirdPartyUtil.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2b2718ab42a02542b348ec7088d764fc2bb9592c --- /dev/null +++ b/pool/shard002/C++/0034717_ThirdPartyUtil.cpp @@ -0,0 +1,288 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "ThirdPartyUtil.h" +#include "nsNetUtil.h" +#include "nsIServiceManager.h" +#include "nsIHttpChannelInternal.h" +#include "nsIDOMWindow.h" +#include "nsILoadContext.h" +#include "nsIPrincipal.h" +#include "nsIScriptObjectPrincipal.h" +#include "nsThreadUtils.h" + +NS_IMPL_ISUPPORTS1(ThirdPartyUtil, mozIThirdPartyUtil) + +nsresult +ThirdPartyUtil::Init() +{ + NS_ENSURE_TRUE(NS_IsMainThread(), NS_ERROR_NOT_AVAILABLE); + + nsresult rv; + mTLDService = do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID, &rv); + return rv; +} + +// Determine if aFirstDomain is a different base domain to aSecondURI; or, if +// the concept of base domain does not apply, determine if the two hosts are not +// string-identical. +nsresult +ThirdPartyUtil::IsThirdPartyInternal(const nsCString& aFirstDomain, + nsIURI* aSecondURI, + bool* aResult) +{ + NS_ASSERTION(aSecondURI, "null URI!"); + + // Get the base domain for aSecondURI. + nsCString secondDomain; + nsresult rv = GetBaseDomain(aSecondURI, secondDomain); + if (NS_FAILED(rv)) + return rv; + + // Check strict equality. + *aResult = aFirstDomain != secondDomain; + return NS_OK; +} + +// Get the URI associated with a window. +already_AddRefed +ThirdPartyUtil::GetURIFromWindow(nsIDOMWindow* aWin) +{ + nsCOMPtr scriptObjPrin = do_QueryInterface(aWin); + NS_ENSURE_TRUE(scriptObjPrin, NULL); + + nsIPrincipal* prin = scriptObjPrin->GetPrincipal(); + NS_ENSURE_TRUE(prin, NULL); + + nsCOMPtr result; + prin->GetURI(getter_AddRefs(result)); + return result.forget(); +} + +// Determine if aFirstURI is third party with respect to aSecondURI. See docs +// for mozIThirdPartyUtil. +NS_IMETHODIMP +ThirdPartyUtil::IsThirdPartyURI(nsIURI* aFirstURI, + nsIURI* aSecondURI, + bool* aResult) +{ + NS_ENSURE_ARG(aFirstURI); + NS_ENSURE_ARG(aSecondURI); + NS_ASSERTION(aResult, "null outparam pointer"); + + nsCString firstHost; + nsresult rv = GetBaseDomain(aFirstURI, firstHost); + if (NS_FAILED(rv)) + return rv; + + return IsThirdPartyInternal(firstHost, aSecondURI, aResult); +} + +// Determine if any URI of the window hierarchy of aWindow is foreign with +// respect to aSecondURI. See docs for mozIThirdPartyUtil. +NS_IMETHODIMP +ThirdPartyUtil::IsThirdPartyWindow(nsIDOMWindow* aWindow, + nsIURI* aURI, + bool* aResult) +{ + NS_ENSURE_ARG(aWindow); + NS_ASSERTION(aResult, "null outparam pointer"); + + bool result; + + // Get the URI of the window, and its base domain. + nsCOMPtr currentURI = GetURIFromWindow(aWindow); + NS_ENSURE_TRUE(currentURI, NS_ERROR_INVALID_ARG); + + nsCString bottomDomain; + nsresult rv = GetBaseDomain(currentURI, bottomDomain); + if (NS_FAILED(rv)) + return rv; + + if (aURI) { + // Determine whether aURI is foreign with respect to currentURI. + rv = IsThirdPartyInternal(bottomDomain, aURI, &result); + if (NS_FAILED(rv)) + return rv; + + if (result) { + *aResult = true; + return NS_OK; + } + } + + nsCOMPtr current = aWindow, parent; + nsCOMPtr parentURI; + do { + // We use GetScriptableParent rather than GetParent because we consider + // ', + itemId: 'widgetIframe', + + initComponent : function() { + + var results = /id\s*=\s*"([^"]*)"/.exec(this.iframeProperties); + if (results != null) { + this.id = results[1]; + } + + results = /name\s*=\s*"([^"]*)"/.exec(this.iframeProperties); + if (results != null) { + this.name = results[1]; + } + + this.autoEl = { + tag: 'iframe', + //src is required + src: /src\s*=\s*"([^"]*)"/.exec(this.iframeProperties)[1], + frameBorder: 0 /* Improve appearance a bit */ + }; + if (this.name) { + this.autoEl.name = this.name; + } + + this.callParent(arguments); + + this.on('afterrender', function(cmp) { + Ozone.KeyMap.bindWidgetEvents(cmp); + }); + }, + + clearSrc: function() { + this.getEl().dom.src = 'about:blank'; + }, + + isSrcCleared: function() { + var el = this.getEl(); + if(!el) { + return true; + } + return el.dom.src === 'about:blank'; + } +}); diff --git a/pool/shard002/JavaScript/0013872_base.js b/pool/shard002/JavaScript/0013872_base.js new file mode 100644 index 0000000000000000000000000000000000000000..0d8ea1eaf0e0d0db35c495a1b7dc7bb16bc5ac5a --- /dev/null +++ b/pool/shard002/JavaScript/0013872_base.js @@ -0,0 +1,65 @@ +'use strict'; + +var Raven = require('raven-js'); +var URI = require('URIjs'); +var oop = require('js/oop'); +var $ = require('jquery'); + +var DOMAIN = ''; + +var BaseClient = oop.defclass({ + PREFIX: '/api', + DEFAULT_AJAX_OPTIONS: { + contentType: 'application/json', + dataType: 'json' + }, + constructor: function() {}, + /** + * Make an API request. + * NOTE: Assumes request bodies are JSON. + * + * @param {object} params + * {string} method + * {string} url + * {object} query + * {object} data: Request body (will be JSONified) + * {object} options: Additional options to pass to $.ajax + */ + _request: function(params) { + var baseUrl = DOMAIN + this.PREFIX + params.url; + var uri = URI(baseUrl) + .query(params.query || {}).toString(); + var jsonData = JSON.stringify(params.data || {}); + console.log(uri); + var opts = $.extend( + {}, + {url: uri, data: jsonData, type: params.method || 'GET'}, this.DEFAULT_AJAX_OPTIONS, + params.options + ); + return $.ajax(opts); + } +}); + +/** + * Return a generic error handler for requests. + * Log to Sentry with the given message. + * + * Usage: + * client.makeRequest() + * .fail(captureError('Failed to make request')); + */ +var DEFAULT_ERROR_MESSAGE = 'Request failed.'; +function captureError(message, callback) { + return function(xhr, status, error) { + Raven.captureMessage(message || DEFAULT_ERROR_MESSAGE, { + extra: { xhr: xhr, status: status, error: error } + }); + // Additional error-handling + callback && callback(xhr, status, error); + }; +} + +module.exports = { + BaseClient: BaseClient, + captureError: captureError +}; diff --git a/pool/shard002/JavaScript/0013876_server.js b/pool/shard002/JavaScript/0013876_server.js new file mode 100644 index 0000000000000000000000000000000000000000..a2a2baeea831d216e959bbd8e5ef0e376a457ac4 --- /dev/null +++ b/pool/shard002/JavaScript/0013876_server.js @@ -0,0 +1,49 @@ +#!/usr/bin/env node + +'use strict'; + +const st = require('st'); +const http = require('http'); +const path = require('path'); +const dir = path.join(__dirname, '..'); +const chokidar = require('chokidar'); +const build = require('./build'); +function start() { + const mount = st({ + path: path.join(dir, 'dist'), + cache: false, + index: 'index.html' + }); + http.createServer(function (req, res) { + mount(req, res); + }).listen(8080, function () { + let url = 'http://localhost:8080'; + console.log(`Serving static site at: ${url}`); + // Open browser url after 1.5s (it waits for everything to be built) + setTimeout(function() { + require("openurl").open(url) + }, 1500); + }); + + /** File Watches for Re-Builds **/ + const opts = { + persistent: true, + ignoreInitial: true, + followSymlinks: true, + usePolling: true, + alwaysStat: false, + depth: undefined, + interval: 100, + ignorePermissionErrors: false, + atomic: true + }; + + + ['layouts', 'static', 'content'].forEach(function(folder) { + chokidar.watch(path.join(dir, folder), opts).on('change', function() { + console.log('files changed in', folder, 'building...'); + build(); + }) + }); +} +start(); diff --git a/pool/shard002/JavaScript/0013877_Recorder.js b/pool/shard002/JavaScript/0013877_Recorder.js new file mode 100644 index 0000000000000000000000000000000000000000..82995da42e33b088ea2904cf1b7e88b6422c2a4e --- /dev/null +++ b/pool/shard002/JavaScript/0013877_Recorder.js @@ -0,0 +1,75 @@ +/* + * Copyright 2012-2013 eBay Software Foundation and ios-driver committers + * + * 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. + */ + +function Recorder(inspector) { + this.log = new Logger(this); + this.inspector = inspector; + this.log.lvl = 4; + this.index = 0; + this.urlBase = document.URL.split("/session/")[0].replace("inspector", "wd/hub"); + var secondPart = document.URL.split("/session/")[1]; + this.session = secondPart.split("/")[0]; + this.log.info(this.session); + this.on = document.URL.indexOf("mode=record") !== -1; +} + +Recorder.prototype.active = function (state) { + this.on = state; +} +Recorder.prototype.recordClick = function (locator) { + this.index++; + var el = "WebElement element" + this.index + " = driver.findElement(By.xpath('" + locator + + "');" + + var base = $("#java").html(); + if (base !== "") { + base += "\n"; + } + var content = base + el; + content += "\nelement" + this.index + ".click();"; + this.log.debug(content); + $("#java").html(content); + if (prettyPrint) { + prettyPrint(); + } + console.log("click : " + el); +} + +Recorder.prototype.forwardClick = function (x, y) { + var url = this.urlBase + "/session/" + this.session + "/tap/2"; + var payload = {"x": x, "y": y}; + this.POST(url, payload); +} + +Recorder.prototype.POST = function (url, payload) { + var me = this; + this.log.debug(url + ", payload=" + JSON.stringify(payload)); + $.ajax({ + url: url, + async: false, + type: "POST", + contentType: 'application/json;charset=UTF-8', + data: JSON.stringify(payload) + + }) + .done(function () { + me.log.info("success"); + }) + .fail(function () { + me.log.info("error"); + }); + + this.log.debug("Reloading now."); + this.inspector.reloadData(); +} \ No newline at end of file diff --git a/pool/shard002/JavaScript/0013879_checkButton.js b/pool/shard002/JavaScript/0013879_checkButton.js new file mode 100644 index 0000000000000000000000000000000000000000..140994d0fd01cb64e4ee9e09051b3ac8e83cf16f --- /dev/null +++ b/pool/shard002/JavaScript/0013879_checkButton.js @@ -0,0 +1,59 @@ +strapout.CheckButton = (function() { + + function CheckButton() { + this.element = null; + this.selected = ko.observableArray(); + } + + CheckButton.prototype.init = function (element, valueAccessor) { + var self = this, + params, + $element; + + params = valueAccessor(); + if (params instanceof CheckButton) { + } + else { + setObservableProperty('selected', params, this); + } + + this.element = element; + $element = $(element); + + if (!$element.attr('data-toggle')) { + $element.attr('data-toggle', 'buttons'); + } + + $element.find('input[type="checkbox"]').each(function () { + var input = this; + ko.applyBindingsToNode(input, { + /** bootstrap doesn't play nice with knockout and checked binding. + * bootstrap stops event propagation before click would be called. + * TODO: make a binding to use for this */ + 'event': { + 'change': function () { + var checked = $(input).filter(':checkbox').prop('checked'); + if (checked) { + self.selected.push($(input).val()); + } + else { + self.selected.remove($(input).val()); + } + } + } + }); + }); + + $element.button(); + + return { + controlsDescendantBindings: false + }; + }; + + ko.bindingHandlers['checkButton'] = { + init: initBindingHandler(CheckButton) + }; + + return CheckButton; +})(); \ No newline at end of file diff --git a/pool/shard002/JavaScript/0013880_gallery-event-binder.js b/pool/shard002/JavaScript/0013880_gallery-event-binder.js new file mode 100644 index 0000000000000000000000000000000000000000..0400ea582ac86342e0df58f5dc13a27a2497cc18 --- /dev/null +++ b/pool/shard002/JavaScript/0013880_gallery-event-binder.js @@ -0,0 +1,149 @@ +YUI.add('gallery-event-binder', function(Y) { + +/** +*

The Event Binder satisfies a very specific need. Binding user actions until a +* particular YUI instance become ready, and the listeners defined before flushing those +* events through a queue. This will help to catch some early user interactions due +* the ondemand nature of YUI 3. +* +*

To use the Event Binder Module, you have to leverage YUI_config object first. More information +* about this object visit this page: http://developer.yahoo.com/yui/3/api/config.html

+*

There is a member of this global object that you have to set up, the member is called: "eventbinder". To get +* more information about this object, visit this page: http://yuilibrary.com/gallery/show/event-binder

+* +*

+* +* <script type="text/javascript">
+*
+* // Call the "use" method, passing in "gallery-event-binder". Then you can
+* // call Y.EventBinder.flush('click'); to flush all the events that might had happened
+* // before your listeners were defined.
+*
+* YUI().use("gallery-event-binder", "event", function(Y) {
+*
+* Y.on('click', function(e) {
+* // do your stuff here...
+* }, '#demo');
+*
+* Y.EventBinder.flush('click');
+*
+* });
+*});
+*
+*
+* </script>
+*
+*

+* +*

The Event Binder has a single method called "flush". This method accept one argument to +* identify what type of event should be flushed. The argument can be:

+*
    +*
  • click
  • +*
  • dblclick
  • +*
  • mouseover
  • +*
  • mouseout
  • +*
  • mousedown
  • +*
  • mouseup
  • +*
  • mousemove
  • +*
  • keydown
  • +*
  • keyup
  • +*
  • keypress
  • +*
  • ...etc...
  • +*
+*

Keep in mind that before flushing any of these events, you have to add them to the +* monitoring system through the configuration object (YUI_config.eventbinder), otherwise +* YUI will be unable to listen for any early user interaction.

+*

+* +* @module gallery-event-binder +*/ + +function _modulesReady (e, modules, handler) { + var args = Y.Array(modules); + + // stopping the module inmidiately + e.halt(); + + // adding the loading class + e.target.addClass('yui3-waiting'); + + args.push(function() { + // once the modules gets ready, let's remove the original binder + handler.detach(); + // removing the loading class + e.target.removeClass('yui3-waiting'); + // let's simulate the new event based on the original facade + Y.Event.simulate(e.target._node, e.type, e); + }); + + Y.use.apply (Y, args); + +} + +Y.EventBinder = { + /* + * Filter all the events in the queue by type, and simulate those that match. + * @method flush + * @param type {string} The type of event to flush + */ + flush: function (type) { + var config = Y.config.eventbinder || {}; + + config.q = config.q || []; + type = type || 'click'; + + if (config.fn) { + // once you call flush, the original listener should be removed + YUI.Env.remove(Y.config.doc, type, config.fn); + } + // filtering all the events in the queue by type + Y.each(config.q, function(o) { + + if (type == o.type) { + // removing the loading class + Y.get(o.target).removeClass('yui3-waiting'); + // let's simulate the new event based on the backup object described by "e" in the configuration + Y.Event.simulate(o.target, type, o); + } + + }); + }, + /* + * Adds an event listener. This method is an wrap for Y.on, and instead of supporting + * a regular callback, it loads a set of modules and simulate the same event once those + * modules become available. + * @method on + * @param type {string} The type of event to append + * @param modules {string|array} a module or a list of modules that should be loaded when this event happens + * @param el {String|HTMLElement|Array|NodeList} An id, an element reference, or a collection of ids and/or elements to assign the listener to. + * @return {EventHandle} the detach handle + */ + on: function (type, modules, el) { + // setting the event listener + var handler = Y.on (type, function(e) { + return _modulesReady(e, modules, handler); + }, el); + return handler; + }, + /* + * Adds an event listener. This method is an wrap for Y.on, and instead of supporting + * a regular callback, it loads a set of modules and simulate the same event once those + * modules become available. + * @method delegate + * @param type {string} the event type to delegate + * @param modules {string|array} a module or a list of modules that should be loaded when this event happens + * @param el {String|HTMLElement|Array|NodeList} An id, an element reference, or a collection of ids and/or elements representing the delegation container. + * @param spec {string} a selector that must match the target of the event. + * @return {EventHandle} the detach handle + */ + delegate: function (type, modules, el, spec) { + // setting the delegate listener + var handler = Y.delegate (type, function(e) { + return _modulesReady(e, modules, handler); + }, el, spec); + return handler; + } +}; + + +}, 'gallery-2010.06.30-19-54' ,{requires:['event-simulate','event-base','event-delegate']}); diff --git a/pool/shard002/JavaScript/0013883_controller.js b/pool/shard002/JavaScript/0013883_controller.js new file mode 100644 index 0000000000000000000000000000000000000000..67b506b76291f659bb5da9b140616fcc6305624c --- /dev/null +++ b/pool/shard002/JavaScript/0013883_controller.js @@ -0,0 +1,58 @@ +import { alias } from '@ember/object/computed'; +import { get } from '@ember/object'; +import { inject as service } from '@ember/service'; +import Controller, { inject as controller } from '@ember/controller'; +import { computed } from '@ember/object'; + +export default Controller.extend({ + prefs: service(), + scope: service(), + + projectController: controller('authenticated.project'), + queryParams: ['sortBy'], + sortBy: 'name', + headers: [ + { + name: 'state', + sort: ['sortState', 'name', 'id'], + type: 'string', + searchField: 'displayState', + translationKey: 'generic.state', + width: 125, + }, + { + name: 'name', + sort: ['name', 'id'], + translationKey: 'generic.name', + }, + { + name: 'namespace', + translationKey: 'generic.namespace', + searchField: 'namespace.displayName', + sort: ['namespace.displayName', 'name', 'id'], + }, + { + name: 'registry', + translationKey: 'cruRegistry.address.label', + searchField: ['displayAddress', 'searchAddresses'], + sort: ['displayAddress', 'name', 'id'], + }, + { + name: 'username', + translationKey: 'cruRegistry.username.label', + searchField: ['firstUsername', 'searchUsernames'], + sort: ['firstUsername', 'name', 'id'], + }, + ], + + group: alias('projectController.group'), + groupTableBy: alias('projectController.groupTableBy'), + + rows: computed('model.projectDockerCredentials.[]', 'model.namespacedDockerCredentials.[]', function() { + const proj = get(this, 'model.projectDockerCredentials').slice(); + const ns = get(this, 'model.namespacedDockerCredentials').slice(); + const out = proj.concat(ns); + + return out; + }), +}); diff --git a/pool/shard002/JavaScript/0013885_grouppage.js b/pool/shard002/JavaScript/0013885_grouppage.js new file mode 100644 index 0000000000000000000000000000000000000000..948e5d61923db8cb7b84602ff75a2211c6c997bd --- /dev/null +++ b/pool/shard002/JavaScript/0013885_grouppage.js @@ -0,0 +1,126 @@ +/* +* eyeos - The Open Source Cloud's Web Desktop +* Version 2.0 +* Copyright (C) 2007 - 2010 eyeos Team +* +* This program is free software; you can redistribute it and/or modify it under +* the terms of the GNU Affero 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 Affero General Public License for more +* details. +* +* You should have received a copy of the GNU Affero General Public License +* version 3 along with this program in the file "LICENSE". If not, see +* . +* +* See www.eyeos.org for more details. All requests should be sent to licensing@eyeos.org +* +* The interactive user interfaces in modified source and object code versions +* of this program must display Appropriate Legal Notices, as required under +* Section 5 of the GNU Affero General Public License version 3. +* +* In accordance with Section 7(b) of the GNU Affero General Public License version 3, +* these Appropriate Legal Notices must retain the display of the "Powered by +* eyeos" logo and retain the original copyright notice. If the display of the +* logo is not reasonably feasible for technical reasons, the Appropriate Legal Notices +* must display the words "Powered by eyeos" and retain the original copyright notice. +* */ +qx.Class.define('eyeos.application.usermanagement.grouppage', { + extend: qx.ui.tabview.Page, + + properties: { + + }, + + construct: function (label, icon, checknum) { + this.base(arguments, label); + this._checknum = checknum; + + this._buildGui(); + this._addMyListeners(); + }, + + members: { + _checknum: null, //checknum of application + + _firstColumn: null, //Gui Element + _seconColumn: null, //Gui Element + + _addMyListeners: function () { + this._groupList.addListener('groupSelect', function (e) { + if (e.getData()) { + this._groupTabView.updateGui(e.getData()); + } + }, this); + + + this._groupList.addListener('unselectGroup', function (e) { + this._groupTabView._refreshGui(); + }, this); + }, + + _buildGui: function () { + this.set({ + layout: new qx.ui.layout.HBox(), + decorator: null, + allowGrowY: true + }); + + // + // First Column + // + this._firstColumn = new qx.ui.container.Composite().set({ + layout: new qx.ui.layout.VBox() + }); + this.add(this._firstColumn); + + this._groupList = new eyeos.application.usermanagement.groupList(this._checknum); + this._firstColumn.add(this._groupList, {flex: 1}); + + var commandBox = new qx.ui.container.Composite(new qx.ui.layout.HBox()); + this._firstColumn.add(commandBox); + + commandBox.add(new qx.ui.core.Spacer(), {flex: 1}); + + var deleteButton = new qx.ui.form.Button(tr('Delete'), 'index.php?extern=images/16x16/actions/edit-delete.png'); + deleteButton.addListener('execute', function () { + var selectedGroup = this._groupList.getSelectedGroup(); + if (selectedGroup != null) { + var op = new eyeos.dialogs.OptionPane( + tr('Are you sure you want to delete this group?'), + eyeos.dialogs.OptionPane.QUESTION_MESSAGE, + eyeos.dialogs.OptionPane.YES_NO_OPTION); + op.createDialog(null, tr('Are you sure you want to delete this group?'), function (answer) { + if (answer == eyeos.dialogs.OptionPane.YES_OPTION) { + eyeos.callMessage(this._checknum, '__Workgroups_deleteWorkgroup', {workgroupId: selectedGroup['id']}, function() { + this._refreshGui(); + }, this); + } + }, this, true).open(); + } + }, this); + commandBox.add(deleteButton); + + // + // Second Column + // + this._secondColumn = new qx.ui.container.Composite().set({ + layout: new qx.ui.layout.VBox(), + marginLeft: 20 + }); + this.add(this._secondColumn, {flex: 1}); + + this._groupTabView = new eyeos.application.usermanagement.groupTabView(this._checknum); + this._secondColumn.add(this._groupTabView, {flex: 1}); + + }, + + _refreshGui: function () { + this._groupList.updategroupList(); + this._groupTabView._refreshGui(); + } + } +}); diff --git a/pool/shard002/JavaScript/0013886_guacScroll.js b/pool/shard002/JavaScript/0013886_guacScroll.js new file mode 100644 index 0000000000000000000000000000000000000000..630897d238068affc94a0f55b54367414c4efc76 --- /dev/null +++ b/pool/shard002/JavaScript/0013886_guacScroll.js @@ -0,0 +1,82 @@ +/* + * 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. + */ + +/** + * A directive which allows elements to be manually scrolled, and for their + * scroll state to be observed. + */ +angular.module('element').directive('guacScroll', [function guacScroll() { + + return { + restrict: 'A', + + link: function linkGuacScroll($scope, $element, $attrs) { + + /** + * The current scroll state of the element. + * + * @type ScrollState + */ + var guacScroll = $scope.$eval($attrs.guacScroll); + + /** + * The element which is being scrolled, or monitored for changes + * in scroll. + * + * @type Element + */ + var element = $element[0]; + + /** + * Returns the current left edge of the scrolling rectangle. + * + * @returns {Number} + * The current left edge of the scrolling rectangle. + */ + var getScrollLeft = function getScrollLeft() { + return guacScroll.left; + }; + + /** + * Returns the current top edge of the scrolling rectangle. + * + * @returns {Number} + * The current top edge of the scrolling rectangle. + */ + var getScrollTop = function getScrollTop() { + return guacScroll.top; + }; + + // Update underlying scrollLeft property when left changes + $scope.$watch(getScrollLeft, function scrollLeftChanged(left) { + element.scrollLeft = left; + guacScroll.left = element.scrollLeft; + }); + + // Update underlying scrollTop property when top changes + $scope.$watch(getScrollTop, function scrollTopChanged(top) { + element.scrollTop = top; + guacScroll.top = element.scrollTop; + }); + + } // end guacScroll link function + + }; + +}]); diff --git a/pool/shard002/JavaScript/0013887_print.js b/pool/shard002/JavaScript/0013887_print.js new file mode 100644 index 0000000000000000000000000000000000000000..a800bdd6cf343d85e520650ce7bf8e7f1c79baac --- /dev/null +++ b/pool/shard002/JavaScript/0013887_print.js @@ -0,0 +1,40 @@ +define("utils/print", ["require", "exports", "module", "configs/settings", "utils/timeformat", "utils/browser"], function(e, t) { + var i = e("configs/settings"), + n = (e("utils/timeformat"), e("utils/browser")), + s = { + debug: !1, + importCSS: !0, + importStyle: !0, + printContainer: !0, + loadCSS: "", + pageTitle: "", + removeInline: !1, + printDelay: n.isFirefox ? 1e3 : 0, + header: null, + formValues: !0 + }, + a = (new Date).getTime(), + r = { + detail: i.cdn + "/static/build/app/core/print-detail.css?v=" + a, + list: i.cdn + "/static/build/app/core/print-list.css?v=" + a + }; + i.is_product_mode || (r.detail = "/static/styles/dist/print-detail.css", r.list = "/static/styles/dist/print-list.css"), t.printTaskDetail = function() { + s.loadCSS = r.detail, $("#task-detail-view").printThis(s) + }, t.printTasks = function() { + s.loadCSS = r.list, $("#task-list-view").printThis(s) + }, t.preloadcss = function() { + var e = document.createElement("iframe"); + if (e.name = "preloadIframe", e.style.display = "none", e.id = "preloadIframe", window.location.hostname !== document.domain && navigator.userAgent.match(/msie/i)) { + var t = 'javascript:document.write("")'; + e.src = t + } + document.body.appendChild(e), setTimeout(function() { + _.each(r, function(t) { + var i = document.createElement("link"); + i.type = "text/css", i.rel = "stylesheet", i.href = t; + var n = e.contentDocument || e.contentWindow.document; + n.getElementsByTagName("head")[0].appendChild(i) + }) + }, 333) + } + }) diff --git a/pool/shard002/JavaScript/0013889_validation.js b/pool/shard002/JavaScript/0013889_validation.js new file mode 100644 index 0000000000000000000000000000000000000000..e0551a33904d3165b9bd9826287cdac794dfe42f --- /dev/null +++ b/pool/shard002/JavaScript/0013889_validation.js @@ -0,0 +1,232 @@ +// Copyright 2015-2017 Parity Technologies (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +import BigNumber from 'bignumber.js'; + +import apiutil from '~/api/util'; + +import { NULL_ADDRESS } from './constants'; + +// TODO: Convert to FormattedMessages as soon as comfortable with the impact, i.e. errors +// not being concatted into strings in components, all supporting a non-string format +export const ERRORS = { + invalidAddress: 'address is an invalid network address', + invalidAmount: 'the supplied amount should be a valid positive number', + invalidAmountDecimals: 'the supplied amount exceeds the allowed decimals', + duplicateAddress: 'the address is already in your address book', + invalidChecksum: 'address has failed the checksum formatting', + invalidName: 'name should not be blank and longer than 2', + invalidAbi: 'abi should be a valid JSON array', + invalidCode: 'code should be the compiled hex string', + invalidNumber: 'invalid number format', + negativeNumber: 'input number should be positive', + decimalNumber: 'input number should not contain decimals', + gasException: 'the transaction will throw an exception with the current values', + gasBlockLimit: 'the transaction execution will exceed the block gas limit' +}; + +export function validateAbi (abi) { + let abiError = null; + let abiParsed = null; + + try { + abiParsed = JSON.parse(abi); + + if (!apiutil.isArray(abiParsed)) { + abiError = ERRORS.invalidAbi; + + return { + error: abiError, + abi, + abiError, + abiParsed + }; + } + + // Validate each elements of the Array + const invalidIndex = abiParsed + .map((o) => isValidAbiEvent(o) || isValidAbiFunction(o) || isAbiFallback(o)) + .findIndex((valid) => !valid); + + if (invalidIndex !== -1) { + const invalid = abiParsed[invalidIndex]; + + // TODO: Needs seperate error when using FormattedMessage (no concats) + abiError = `${ERRORS.invalidAbi} (#${invalidIndex}: ${invalid.name || invalid.type})`; + + return { + error: abiError, + abi, + abiError, + abiParsed + }; + } + + abi = JSON.stringify(abiParsed); + } catch (error) { + abiError = ERRORS.invalidAbi; + } + + return { + error: abiError, + abi, + abiError, + abiParsed + }; +} + +function isValidAbiFunction (object) { + if (!object) { + return false; + } + + return ((object.type === 'function' && object.name) || object.type === 'constructor') && + (object.inputs && apiutil.isArray(object.inputs)); +} + +function isAbiFallback (object) { + if (!object) { + return false; + } + + return object.type === 'fallback'; +} + +function isValidAbiEvent (object) { + if (!object) { + return false; + } + + return (object.type === 'event') && + (object.name) && + (object.inputs && apiutil.isArray(object.inputs)); +} + +export function validateAddress (address) { + let addressError = null; + + if (!address) { + addressError = ERRORS.invalidAddress; + } else if (!apiutil.isAddressValid(address)) { + addressError = ERRORS.invalidAddress; + } else { + address = apiutil.toChecksumAddress(address); + } + + return { + error: addressError, + address, + addressError + }; +} + +export function validateCode (code) { + let codeError = null; + + if (!code || !code.length) { + codeError = ERRORS.invalidCode; + } else if (!apiutil.isHex(code)) { + codeError = ERRORS.invalidCode; + } + + return { + error: codeError, + code, + codeError + }; +} + +export function validateName (name) { + const nameError = !name || name.trim().length < 2 + ? ERRORS.invalidName + : null; + + return { + error: nameError, + name, + nameError + }; +} + +export function validatePositiveNumber (number) { + let numberError = null; + + try { + const v = new BigNumber(number); + + if (v.lt(0)) { + numberError = ERRORS.invalidAmount; + } + } catch (e) { + numberError = ERRORS.invalidAmount; + } + + return { + error: numberError, + number, + numberError + }; +} + +export function validateDecimalsNumber (number, base = 1) { + let numberError = null; + + try { + const s = new BigNumber(number).mul(base).toFixed(); + + if (s.indexOf('.') !== -1) { + numberError = ERRORS.invalidAmountDecimals; + } + } catch (e) { + numberError = ERRORS.invalidAmount; + } + + return { + error: numberError, + number, + numberError + }; +} + +export function validateUint (value) { + let valueError = null; + + try { + const bn = new BigNumber(value); + + if (bn.lt(0)) { + valueError = ERRORS.negativeNumber; + } else if (!bn.isInteger()) { + valueError = ERRORS.decimalNumber; + } + } catch (e) { + valueError = ERRORS.invalidNumber; + } + + return { + error: valueError, + value, + valueError + }; +} + +export function isNullAddress (address) { + if (address && address.substr(0, 2) === '0x') { + return isNullAddress(address.substr(2)); + } + + return address === NULL_ADDRESS; +} diff --git a/pool/shard002/JavaScript/0013894_batch_write_collation_estsize.js b/pool/shard002/JavaScript/0013894_batch_write_collation_estsize.js new file mode 100644 index 0000000000000000000000000000000000000000..944b20946968f64b9bf1dc33b050ec18d43e1f84 --- /dev/null +++ b/pool/shard002/JavaScript/0013894_batch_write_collation_estsize.js @@ -0,0 +1,187 @@ +// Tests that the update and delete batch write operations account for the size of the collation +// specification in the write operation document. + +(function() { + "use strict"; + + // Setup the test collection. + db.batch_write_collation_estsize.drop(); + assert.writeOK(db.batch_write_collation_estsize.insert({str: "FOO"})); + + if (db.getMongo().writeMode() !== "commands") { + // Cannot use the bulk API to set a collation when using legacy write ops. + let bulk; + + // Test updateOne unordered bulk write operation with collation specification. + bulk = db.batch_write_collation_estsize.initializeUnorderedBulkOp(); + assert.throws(() => { + bulk.find({str: "FOO"}).collation({locale: "en_US", strength: 2}).updateOne({ + str: "BAR" + }); + }); + + // Test update unordered bulk write operation with collation specification. + bulk = db.batch_write_collation_estsize.initializeUnorderedBulkOp(); + assert.throws(() => { + bulk.find({str: "FOO"}).collation({locale: "en_US", strength: 2}).update({str: "BAR"}); + }); + + // Test replaceOne unordered bulk write operation with collation specification. + bulk = db.batch_write_collation_estsize.initializeUnorderedBulkOp(); + assert.throws(() => { + bulk.find({str: "FOO"}).collation({locale: "en_US", strength: 2}).replaceOne({ + str: "BAR" + }); + }); + + // Test removeOne unordered bulk write operation with collation specification. + bulk = db.batch_write_collation_estsize.initializeUnorderedBulkOp(); + assert.throws(() => { + bulk.find({str: "FOO"}).collation({locale: "en_US", strength: 2}).removeOne(); + }); + + // Test remove unordered bulk write operation with collation specification. + bulk = db.batch_write_collation_estsize.initializeUnorderedBulkOp(); + assert.throws(() => { + bulk.find({str: "FOO"}).collation({locale: "en_US", strength: 2}).remove(); + }); + + // Test updateOne ordered bulk write operation with collation specification. + bulk = db.batch_write_collation_estsize.initializeOrderedBulkOp(); + assert.throws(() => { + bulk.find({str: "FOO"}).collation({locale: "en_US", strength: 2}).updateOne({ + str: "BAR" + }); + }); + + // Test update ordered bulk write operation with collation specification. + bulk = db.batch_write_collation_estsize.initializeOrderedBulkOp(); + assert.throws(() => { + bulk.find({str: "FOO"}).collation({locale: "en_US", strength: 2}).update({str: "BAR"}); + }); + + // Test replaceOne ordered bulk write operation with collation specification. + bulk = db.batch_write_collation_estsize.initializeOrderedBulkOp(); + assert.throws(() => { + bulk.find({str: "FOO"}).collation({locale: "en_US", strength: 2}).replaceOne({ + str: "BAR" + }); + }); + + // Test removeOne ordered bulk write operation with collation specification. + bulk = db.batch_write_collation_estsize.initializeOrderedBulkOp(); + assert.throws(() => { + bulk.find({str: "FOO"}).collation({locale: "en_US", strength: 2}).removeOne(); + }); + + // Test remove ordered bulk write operation with collation specification. + bulk = db.batch_write_collation_estsize.initializeOrderedBulkOp(); + assert.throws(() => { + bulk.find({str: "FOO"}).collation({locale: "en_US", strength: 2}).remove(); + }); + } else { + // Setup the bulk write response variable. + let res; + + // Test updateOne bulk write operation with collation specification. + res = db.batch_write_collation_estsize.bulkWrite([{ + updateOne: { + filter: {str: "FOO"}, + update: {$set: {str: "BAR"}}, + collation: { + locale: "en_US", + caseLevel: false, + caseFirst: "off", + strength: 3, + numericOrdering: false, + alternate: "non-ignorable", + maxVariable: "punct", + normalization: false, + backwards: false + } + } + }]); + assert.eq(1, res.matchedCount); + + // Test updateMany bulk write operation with collation specification. + res = db.batch_write_collation_estsize.bulkWrite([{ + updateMany: { + filter: {str: "BAR"}, + update: {$set: {str: "FOO"}}, + collation: { + locale: "en_US", + caseLevel: false, + caseFirst: "off", + strength: 3, + numericOrdering: false, + alternate: "non-ignorable", + maxVariable: "punct", + normalization: false, + backwards: false + } + } + }]); + assert.eq(1, res.matchedCount); + + // Test replaceOne bulk write operation with collation specification. + res = db.batch_write_collation_estsize.bulkWrite([{ + replaceOne: { + filter: {str: "FOO"}, + replacement: {str: "BAR"}, + collation: { + locale: "en_US", + caseLevel: false, + caseFirst: "off", + strength: 3, + numericOrdering: false, + alternate: "non-ignorable", + maxVariable: "punct", + normalization: false, + backwards: false + } + } + }]); + assert.eq(1, res.matchedCount); + + // Test deleteMany bulk write operation with collation specification. + res = db.batch_write_collation_estsize.bulkWrite([{ + deleteOne: { + filter: {str: "BAR"}, + collation: { + locale: "en_US", + caseLevel: false, + caseFirst: "off", + strength: 3, + numericOrdering: false, + alternate: "non-ignorable", + maxVariable: "punct", + normalization: false, + backwards: false + } + } + }]); + assert.eq(1, res.deletedCount); + + // Reinsert a document to test deleteMany bulk write operation. + assert.writeOK(db.batch_write_collation_estsize.insert({str: "FOO"})); + + // Test deleteMany bulk write operation with collation specification. + res = db.batch_write_collation_estsize.bulkWrite([{ + deleteMany: { + filter: {str: "FOO"}, + collation: { + locale: "en_US", + caseLevel: false, + caseFirst: "off", + strength: 3, + numericOrdering: false, + alternate: "non-ignorable", + maxVariable: "punct", + normalization: false, + backwards: false + } + } + }]); + assert.eq(1, res.deletedCount); + } +})(); diff --git a/pool/shard002/JavaScript/0013896_ApplicationsCtrl.js b/pool/shard002/JavaScript/0013896_ApplicationsCtrl.js new file mode 100644 index 0000000000000000000000000000000000000000..5a1e6fca870e1e96573c4ce872147eed1edd0975 --- /dev/null +++ b/pool/shard002/JavaScript/0013896_ApplicationsCtrl.js @@ -0,0 +1,95 @@ +/*jshint devel:true */ + +'use strict'; + +angular.module('wasabi.controllers'). + controller('ApplicationsCtrl', ['$scope', '$filter', '$http', 'ApplicationsFactory', 'AuthzFactory', '$uibModal', 'UtilitiesFactory', '$rootScope', 'StateFactory', 'DialogsFactory', 'AUTH_EVENTS', + function ($scope, $filter, $http, ApplicationsFactory, AuthzFactory, $uibModal, UtilitiesFactory, $rootScope, StateFactory, DialogsFactory, AUTH_EVENTS) { + + // The data object is where values are stored that need to be data bound to the fields in the form. + // I believe there was a scope problem and I found this solution on the Googles. Basically, by + // using the "data.xx" notation, you do a cleaner job of setting scope for the things that will be + // bound from the form. For the fields they are bound to, look at ExperimentTable.html . + $scope.data = { + query: '' + }; + + // sorting + $scope.orderByField = 'label'; + $scope.reverseSort = false; + + $scope.applications = []; + + // load applications from server + $scope.loadApplications = function () { + $scope.applications = UtilitiesFactory.getAdministeredApplications(); + + if ($scope.applications.length === 1) { + // Special handling when the user only has admin rights over one application. Need + // to set up the stuff used by the EditApplicationModal template. + $scope.application = $scope.applications[0]; + $scope.administeredApplications = $scope.applications; + } + }; + + UtilitiesFactory.hideHeading(false); + UtilitiesFactory.selectTopLevelTab('Applications'); + + $scope.capitalizeFirstLetter = function(string) { + return UtilitiesFactory.capitalizeFirstLetter(string); + }; + + // change sorting order if 2nd argument undefined + $scope.sortBy = function (orderByField, reverseSort) { + if ($scope.orderByField === orderByField) { + $scope.reverseSort = !$scope.reverseSort; + } + if (reverseSort) { + $scope.reverseSort = reverseSort; + } + + $scope.orderByField = orderByField; + + // take care of the sorting order + if ($scope.orderByField !== '') { + $scope.applications = $filter('orderBy')($scope.applications, $scope.orderByField, $scope.reverseSort); + } + }; + + // init controller + $scope.loadApplications(); + + $scope.openApplicationModal = function (application) { + var modalInstance = $uibModal.open({ + templateUrl: 'views/EditApplicationModal.html', + controller: 'EditApplicationModalCtrl', + windowClass: 'xx-dialog', + backdrop: 'static', + resolve: { + application: function () { + if (application) { + // get application by ID from server (to update application) + //return ApplicationsFactory.show({id: id}); + return application; + } + }, + applications: function () { + return $scope.applications; + } + } + }); + + // This will cause the dialog to be closed and we get redirected to the Sign In page if + // the login token has expired. + UtilitiesFactory.failIfTokenExpired(modalInstance); + + // This handles closing the dialog if one of the child dialogs has encountered an expired token. + $scope.$on(AUTH_EVENTS.notAuthenticated, function(/*event*/) { + modalInstance.close(); + }); + + modalInstance.result.then(function () { + // Nothing to do. + }); + }; + }]); diff --git a/pool/shard002/JavaScript/0013898_categories.js b/pool/shard002/JavaScript/0013898_categories.js new file mode 100644 index 0000000000000000000000000000000000000000..cbec80330cfb2d4d40d4773400868db8ba6cfa02 --- /dev/null +++ b/pool/shard002/JavaScript/0013898_categories.js @@ -0,0 +1,25 @@ +'use strict' + +const db = require('APP/db') +const Category = db.model('categories') + +const {mustBeLoggedIn, forbidden} = require('./auth.filters') + +module.exports = require('express').Router() + .get('/', + (req, res, next) => + Category.findAll() + .then(categories => res.json(categories)) + .catch(next)) + .post('/', + (req, res, next) => + Category.create(req.body) + .then(category => res.status(201).json(category)) + .catch(next)) + .get('/:id', + //mustBeLoggedIn, + (req, res, next) => + Category.findById(req.params.id) + .then(category => res.json(category)) + .catch(next)) + \ No newline at end of file diff --git a/pool/shard002/JavaScript/0013900_authService.js b/pool/shard002/JavaScript/0013900_authService.js new file mode 100644 index 0000000000000000000000000000000000000000..234e22ea415087b0988f93b2168e8552fb8b95c6 --- /dev/null +++ b/pool/shard002/JavaScript/0013900_authService.js @@ -0,0 +1,26 @@ +var module = require('./_module_init.js'); +module.factory('$QJAuth', ['$QJLogger', "$rootScope", "$http", '$QJLocalSession', + function($QJLogger, $rootScope, $http, $QJLocalSession) { + return { + updateSessionCustom: function(token, _group_id) { + $rootScope.session.token = token; + $rootScope.session._group_id = _group_id; + $rootScope.config._group_id = _group_id; + $QJLocalSession.save(); + $rootScope.$emit('session.change'); + $QJLogger.log('QJAuth -> updateSessionCustom -> token ->' + token); + }, + updateSessionFromLogin: function(res) { + $rootScope.session.loginname = res.loginname; + $rootScope.session.token = res.token; + $rootScope.session.tokenReq = res.tokenReq; + $rootScope.session.tokenExp = res.tokenExp; + $rootScope.session._group_id = $rootScope.config._group_id; + $QJLocalSession.save(); + $rootScope.$emit('session.change'); + $QJLogger.log('QJAuth -> updateSessionFromLogin -> token ->' + res.token); + + } + } + } +]); \ No newline at end of file diff --git a/pool/shard002/JavaScript/0013901_ComputerTable.js b/pool/shard002/JavaScript/0013901_ComputerTable.js new file mode 100644 index 0000000000000000000000000000000000000000..e3e02f0e2247ff4e1d3dc08fe63c1f57c40ec1d9 --- /dev/null +++ b/pool/shard002/JavaScript/0013901_ComputerTable.js @@ -0,0 +1,33 @@ +const ComputerSearchSection = require('./ComputerSearchForm'); +const computerSearch = new ComputerSearchSection($('#actions form')); +const BaseFragment = require('protractor-element-extend').BaseFragment; +const Helpers = require('./../../utils/helpers'); + +class ComputerTable extends BaseFragment { + constructor(rootElement) { + super(rootElement); + this.tableHeaderColumns = element.all(by.tagName('th')); + this.computerNamesInTheTable = element.all(by.css('.computers.zebra-striped>tbody>tr>td>a')); + this.computerIntroducedDateInTheTable = $('.computers.zebra-striped>tbody>tr>td:nth-child(2)'); + this.computerDiscontinuedDateInTheTable = $('.computers.zebra-striped>tbody>tr>td:nth-child(3)'); + this.computerCompanyNameInTheTable = $('.computers.zebra-striped>tbody>tr>td:nth-child(4)'); + } + + async getTableColumnsAmount() { + return await this.tableHeaderColumns.count(); + } + + isComputerInfoInTheTableEqualsExpected(initialComputerData) { + computerSearch.findComputerInTheTable(initialComputerData[0]); + + const actualComputerInfo = []; + return protractor.promise.all([ + this.computerNamesInTheTable.get(0).getText().then(text => actualComputerInfo.push(text)), + this.computerIntroducedDateInTheTable.getText().then(text => actualComputerInfo.push(text)), + this.computerDiscontinuedDateInTheTable.getText().then(text => actualComputerInfo.push(text)), + this.computerCompanyNameInTheTable.getText().then(text => actualComputerInfo.push(text)), + ]).then(() => Helpers.arraysEqual(initialComputerData, actualComputerInfo)); + } +} + +module.exports = ComputerTable; diff --git a/pool/shard002/JavaScript/0013902_eddard.js b/pool/shard002/JavaScript/0013902_eddard.js new file mode 100644 index 0000000000000000000000000000000000000000..d9aa1b340fed5c3c8f438baf6036aadd4df18be4 --- /dev/null +++ b/pool/shard002/JavaScript/0013902_eddard.js @@ -0,0 +1,14 @@ +var GotBot = require('./got-bot') +var Eddard = new GotBot() + +Eddard.params.username = 'Eddard Stark' +Eddard.params.icon_url = 'https://raw.githubusercontent.com/davekinkead/bots-of-thrones/master/media/eddard.jpg' + +Eddard.trigger = function(data) { + // ... coming .... + if (data.text && data.text.match(/\scoming\s/)) { + return this.quip = 'Winter. Winter is coming.' + } +} + +module.exports = Eddard \ No newline at end of file diff --git a/pool/shard002/JavaScript/0013903_main.js b/pool/shard002/JavaScript/0013903_main.js new file mode 100644 index 0000000000000000000000000000000000000000..3f5e51a8ebb031cfbaf06bfa6bbfd54451594539 --- /dev/null +++ b/pool/shard002/JavaScript/0013903_main.js @@ -0,0 +1,145 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib 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. +*/ + +'use strict'; + +// MODULES // + +var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); +var iteratorSymbol = require( '@stdlib/symbol/iterator' ); +var factorial = require( '@stdlib/math/base/special/factorial' ); +var validate = require( './validate.js' ); + + +// VARIABLES // + +var MAX_ITER = 1e308; + + +// MAIN // + +/** +* Returns an iterator which generates a sequence of factorials. +* +* ## Notes +* +* - If an environment supports `Symbol.iterator`, the returned iterator is iterable. +* +* @param {Options} [options] - function options +* @param {NonNegativeInteger} [options.iter=1e308] - number of iterations +* @throws {TypeError} options argument must be an object +* @throws {TypeError} must provide valid options +* @returns {Iterator} iterator +* +* @example +* var iter = iterFactorialsSeq(); +* +* var v = iter.next().value; +* // returns 1 +* +* v = iter.next().value; +* // returns 1 +* +* v = iter.next().value; +* // returns 2 +* +* // ... +*/ +function iterFactorialsSeq( options ) { + var opts; + var iter; + var FLG; + var err; + var i; + + opts = { + 'iter': MAX_ITER + }; + if ( arguments.length ) { + err = validate( opts, options ); + if ( err ) { + throw err; + } + } + i = -1; + + // Create an iterator protocol-compliant object: + iter = {}; + setReadOnly( iter, 'next', next ); + setReadOnly( iter, 'return', end ); + + // If an environment supports `Symbol.iterator`, make the iterator iterable: + if ( iteratorSymbol ) { + setReadOnly( iter, iteratorSymbol, factory ); + } + return iter; + + /** + * Returns an iterator protocol-compliant object containing the next iterated value. + * + * @private + * @returns {Object} iterator protocol-compliant object + */ + function next() { + i += 1; + if ( FLG || i >= opts.iter ) { + return { + 'done': true + }; + } + return { + 'value': factorial( i ), + 'done': false + }; + } + + /** + * Finishes an iterator. + * + * @private + * @param {*} [value] - value to return + * @returns {Object} iterator protocol-compliant object + */ + function end( value ) { + FLG = true; + if ( arguments.length ) { + return { + 'value': value, + 'done': true + }; + } + return { + 'done': true + }; + } + + /** + * Returns a new iterator. + * + * @private + * @returns {Iterator} iterator + */ + function factory() { + return iterFactorialsSeq( opts ); + } +} + + +// EXPORTS // + +module.exports = iterFactorialsSeq; diff --git a/pool/shard002/JavaScript/0013906_radar.js b/pool/shard002/JavaScript/0013906_radar.js new file mode 100644 index 0000000000000000000000000000000000000000..e98819362664348e89e5dc7554ebfbc7e09f8ec0 --- /dev/null +++ b/pool/shard002/JavaScript/0013906_radar.js @@ -0,0 +1,167 @@ +Radar = (function (){ + function draw(element, svg_path, json_path){ + d3.xml(svg_path, 'image/svg+xml', function (xml) { + element.appendChild(xml.documentElement); + + var svg = d3.select('#radar'); + + _doRadar(svg); + _defineBlips(svg); + _drawBlips(svg, json_path); + }); + } + + function zoomIn(quadrantName) { + var quadrant = d3.select("g#" + quadrantName).select(".largest-arc"); + + quadrant.on("click").call(quadrant[0][0]); + } + + function zoomOut() { + d3.select("g#radar").transition() + .attr('transform', ''); + + d3.selectAll('text').transition() + .duration(800) + .style('opacity', '0') + .style('display', 'none'); + } + + function _doRadar(svg) { + var quadrants = svg.selectAll('g.quadrant') + + quadrants.select('.largest-arc') + .on('click', function () { + var d3_element = d3.select(this), + id = d3_element.attr('id'), + size = 800, + offX = 0, + offY = 0; + + switch (id) { + case 'techniques-arc': + break; + case 'tools-arc': + offX = -size; + break; + case 'languages-arc': + offX = -size; + offY = -size; + break; + case 'platforms-arc': + offY = -size; + break; + } + + d3.selectAll('g#radar').transition() + .attr('transform', 'translate(' + offX + ',' + offY + ') scale(2)'); + + d3.selectAll('text').style('display', 'block') + .transition() + .duration(800) + .style('opacity', '1') + }) + } + + function _defineBlips(svg) { + var definitions = svg.append('defs'); + + definitions.append('circle') + .attr('r', 4) + .attr('class', 'unchanged blip') + .attr('id', 'circular-blip'); + + definitions.append('polygon') + .attr('points', '-2,-2 8,-2 3,-10') + .attr('class', 'changed blip') + .attr('id', 'triangular-blip'); + + return svg; + } + + function _drawBlips(svg, json_path) { + d3.json(json_path, function (blipData) { + _drawBlipsUpon(svg, blipData); + }); + } + + function _drawBlipsUpon(svg, blipData) { + var center = _centerOf(svg), + blips = svg.selectAll('.blip-container') + .data(blipData); + blip = blips.enter() + .append('g') + .attr('class', 'blip-container') + .on('click', _showBlipDescription); + + blip.append('use') + .attr('xlink:href', function (blip) { + return blip.movement == 'c' ? '#circular-blip' : '#triangular-blip'; + }) + .attr('x', function (blip){ + return center.x + _toRect(blip.pc).x; + }) + .attr('y', function (blip){ + return center.y + _toRect(blip.pc).y; + }) + .attr('title', function (blip) { return blip.name }); + + blip.append('text') + .text(function (blip) { return blip.name; }) + .style('opacity', '0') + .style('display', 'none') + .attr('class', 'label') + .attr('transform', function (blip) { + var blipCenter = _toRect(blip.pc); + return 'translate(' + (center.x+blipCenter.x+5) + ', ' + (center.y+blipCenter.y-2) + ')'; + }); + + return svg; + } + + function _showBlipDescription(blip) { + d3.selectAll('.blip-container').attr('class', 'blip-container'); + d3.select(this).attr('class', 'blip-container active'); + + _zoomInBlip(blip); + + $('#blip-name').text(blip.name); + $('#blip-description').text(blip.description); + }; + + function _zoomInBlip(blip) { + var theta = blip.pc.t % 360, + quadrants = ['languages', 'platforms', 'techniques', 'tools'], + quadrant = quadrants[Math.floor(theta / 90)]; + + zoomIn(quadrant); + } + + function _centerOf(d3_element) { + var element = document.getElementById(d3_element.attr('id')), + bbox = element.getBBox(); + + return _point(bbox.width / 2, bbox.height / 2); + } + + function _point(x, y) { + return { + 'x': x, + 'y': y + }; + } + + function _toRect(polarCoords) { + var angleInRadians = (polarCoords.t * Math.PI) / 180; + function xProjection(r,a) { return r * Math.cos(a); } + function yProjection(r,a) { return r * Math.sin(a); } + return _point(xProjection(polarCoords.r, angleInRadians), yProjection(polarCoords.r, angleInRadians)); + } + + return { + draw: draw, + zoomIn: zoomIn, + zoomOut: zoomOut + }; +})(); + diff --git a/pool/shard002/JavaScript/0013908_popover.js b/pool/shard002/JavaScript/0013908_popover.js new file mode 100644 index 0000000000000000000000000000000000000000..482985b639dbf86b1f6d3f35123eb192b764de1f --- /dev/null +++ b/pool/shard002/JavaScript/0013908_popover.js @@ -0,0 +1,113 @@ +/* ======================================================================== + * Bootstrap: popover.js v3.0.0 + * http://twitter.github.com/bootstrap/javascript.html#popovers + * ======================================================================== + * Copyright 2012 Twitter, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ======================================================================== */ + + ++function ($) { "use strict"; + + // POPOVER PUBLIC CLASS DEFINITION + // =============================== + + var Popover = function (element, options) { + this.init('popover', element, options) + } + + Popover.DEFAULTS = $.extend({} , $.fn.tooltip.Constructor.DEFAULTS, { + placement: 'right' + , trigger: 'click' + , content: '' + , template: '

' + }) + + + // NOTE: POPOVER EXTENDS tooltip.js + // ================================ + + Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) + + Popover.prototype.constructor = Popover + + Popover.prototype.getDefaults = function () { + return Popover.DEFAULTS + } + + Popover.prototype.setContent = function () { + var $tip = this.tip() + var title = this.getTitle() + var content = this.getContent() + + $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) + $tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content) + + $tip.removeClass('fade top bottom left right in') + + $tip.find('.popover-title:empty').hide() + } + + Popover.prototype.hasContent = function () { + return this.getTitle() || this.getContent() + } + + Popover.prototype.getContent = function () { + var $e = this.$element + var o = this.options + + return $e.attr('data-content') + || (typeof o.content == 'function' ? + o.content.call($e[0]) : + o.content) + } + + Popover.prototype.tip = function () { + if (!this.$tip) this.$tip = $(this.options.template) + return this.$tip + } + + Popover.prototype.destroy = function () { + this.hide().$element.off('.' + this.type).removeData(this.type) + } + + + // POPOVER PLUGIN DEFINITION + // ========================= + + var old = $.fn.popover + + $.fn.popover = function (option) { + return this.each(function () { + var $this = $(this) + var data = $this.data('bs.popover') + var options = typeof option == 'object' && option + + if (!data) $this.data('bs.popover', (data = new Popover(this, options))) + if (typeof option == 'string') data[option]() + }) + } + + $.fn.popover.Constructor = Popover + + + // POPOVER NO CONFLICT + // =================== + + $.fn.popover.noConflict = function () { + $.fn.popover = old + return this + } + +}(window.jQuery); diff --git a/pool/shard002/JavaScript/0013910_moodle-question-preview.js b/pool/shard002/JavaScript/0013910_moodle-question-preview.js new file mode 100644 index 0000000000000000000000000000000000000000..bb1772cb3281998c299042785d2fb2b329c01eaa --- /dev/null +++ b/pool/shard002/JavaScript/0013910_moodle-question-preview.js @@ -0,0 +1,55 @@ +YUI.add('moodle-question-preview', function (Y, NAME) { + +// This file is part of Moodle - http://moodle.org/ +// +// Moodle is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Moodle is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Moodle. If not, see . + +/* + * @copyright 2014 The Open University + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +/** + * JavaScript required by the question preview pop-up. + * + * @deprecated since Moodle 4.0 + * @todo Final deprecation on Moodle 4.4 MDL-72438 + * @module moodle-question-preview + */ + + +M.question = M.question || {}; +M.question.preview = M.question.preview || {}; + +/* + * Initialise JavaScript-specific parts of the question preview popup. + */ +M.question.preview.init = function() { + M.core_question_engine.init_form(Y, '#responseform'); + + // Add a close button to the window. + var closebutton = Y.Node.create('') + .set('value', M.util.get_string('closepreview', 'question')); + + closebutton.on('click', function() { + window.close(); + }); + Y.one('#previewcontrols').append(closebutton); + + // Stop a question form being submitted more than once. + Y.on('submit', M.core_question_engine.prevent_repeat_submission, '#mform1', null, Y); +}; + + +}, '@VERSION@', {"requires": ["base", "dom", "event-delegate", "event-key", "core_question_engine"]}); diff --git a/pool/shard002/JavaScript/0013911_app.js b/pool/shard002/JavaScript/0013911_app.js new file mode 100644 index 0000000000000000000000000000000000000000..dd4b2f4ba3f954bba61eedb9b5437d721383d3fc --- /dev/null +++ b/pool/shard002/JavaScript/0013911_app.js @@ -0,0 +1,45 @@ + +/** + * Module dependencies. + */ + +var express = require('express'); +var routes = require('./routes'); +var user = require('./routes/user'); +var http = require('http'); +var path = require('path'); + +var app = express(); + +// all environments +app.set('port', process.env.PORT || 3000); +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'jade'); +app.use(express.favicon()); +app.use(express.logger('dev')); +app.use(express.json()); +app.use(express.urlencoded()); +app.use(express.methodOverride()); +app.use(app.router); +app.use(express.static(path.join(__dirname, 'public'))); + + +// development only +if ('development' == app.get('env')) { + app.use(express.errorHandler()); +} + +app.get('/', routes.index); + + +app.use(function(req, res, next){ + // the status option, or res.statusCode = 404 + // are equivalent, however with the option we + // get the "status" local available as well + res.render('404', { status: 404, url: req.url }); +}); + + +http.createServer(app).listen(app.get('port'), function(){ + console.log('Express server listening on port ' + app.get('port')); +}); diff --git a/pool/shard002/JavaScript/0013914_fibers.js b/pool/shard002/JavaScript/0013914_fibers.js new file mode 100644 index 0000000000000000000000000000000000000000..74ee924a8c3306379141720fb6d15a32a0ec2b6b --- /dev/null +++ b/pool/shard002/JavaScript/0013914_fibers.js @@ -0,0 +1,106 @@ + +var CALL_TIMEOUT = 30000 + +var __assert = require('assert') +var util = require('util') + +var streamingMethod = require('./streaming_method') + +var mp = require('msgpack') + +var slice = Array.prototype.slice + +var trace = 0 + +module.exports = function(Fiber){ + + function Session(id, fiber){ + __assert(typeof id === 'number', 'no id passed to session') + __assert(fiber, 'no fiber passed to session') + this.fiber = fiber + this._id = id + this._owner = null + this._methodId = undefined + this._args = null + this._done = false + this._chunk = undefined + this._callTimer = 0 + this._unpacker = null + var _this = this + this._timeoutHandler = function(){ + __assert(!_this._done,'!_this._done') + _this._done = true + var err = new Error('call timeout') + _this.fiber.throwInto(err) + } + this._resetTimeout() + } + + Session.prototype = { + _resetTimeout: function(){ + clearTimeout(this._callTimer) + this._callTimer = setTimeout(this._timeoutHandler, CALL_TIMEOUT) + }, + + pushChunk: function(chunk){ + __assert(this._chunk === undefined, 'this._chunk === undefined') + this._chunk = chunk + var unpacker = this._unpacker || mp.unpack + this._result = unpacker(chunk) + }, + pushChoke: function(){ + __assert(!this._done, '!this._done') + this._done = true + this._owner = null + clearTimeout(this._callTimer) + this.fiber.run(this._result) + }, + pushError: function(code, message) { + __assert(!this._done, '!this._done') + this._done = true + var owner = this._owner + this._owner = null + clearTimeout(this._callTimer) + var err = new Error(util.format('%s\n in service %s method %s\n args: %s\n', message, owner._name, this._methodId, util.inspect(this._args))) + err.code = code + this.fiber.thowInto(err) + } + } + + return { + unpackWith: function(unpacker){ + return function(mid){ + return function(){ + var args = slice.call(arguments) + var sid = this.__sid++ + var S = new Session(sid, Fiber.current) + S._unpacker = unpacker + S._owner = this + S._methodId = mid + S._args = args + this._sessions[S._id] = S + this._send([mid, S._id, args]) + return Fiber.yield() + } + } + }, + unpacking: function(mid){ + return function(){ + var args = slice.call(arguments) + var sid = this.__sid++ + var S = new Session(sid, Fiber.current) + S._owner = this + S._methodId = mid + S._args = args + this._sessions[S._id] = S + this._send([mid, S._id, args]) + return Fiber.yield() + } + }, + streaming: streamingMethod + } +} + + + + diff --git a/pool/shard002/JavaScript/0013917_lang.en.js b/pool/shard002/JavaScript/0013917_lang.en.js new file mode 100644 index 0000000000000000000000000000000000000000..d903016c096189b4560c2aa12f6aa255c15901b3 --- /dev/null +++ b/pool/shard002/JavaScript/0013917_lang.en.js @@ -0,0 +1,180 @@ +define('lang.en', ['lang', 'grammar', 'util'], function(Lang, Grammar, _) { + + var {Translation, Language, ActionTranslation, ObjectTranslation} = Lang; + var {Word} = Grammar; + + class ActionTranslationEn extends ActionTranslation { + + constructor(opts) { + opts.defaultForm = opts.root; + super(opts); + this.dependentActionConnector = _.isDefined(this.opts.dependentActionConnector) ? + this.opts.dependentActionConnector : 'to'; + super.conjugate(); + } + + getPresentForms() { + return _.extend(this.forAllPersons(this.defaultForm), { + he: this.defaultForm + 's', + she: this.defaultForm + 's', + it: this.defaultForm + 's' + }); + } + + getFutureForms() { + return this.forAllPersons(`will ${this.defaultForm}`); + } + + getPastForms() { + return this.forAllPersons(`${this.defaultForm}ed`); + } + + asPrimaryTimeActorForm(time, actor) { + return `${this.timeActorForm(time, actor)} ${this.dependentActionConnector}`.trim(); + } + } + + var translations = { + sun: new ObjectTranslation({ + defaultForm: 'sun', + asActor: Word.it + }), + sing: new ActionTranslationEn({ + root: 'sing', + conjugations: { + past: 'sang' + } + }), + do: new ActionTranslationEn({ + root: 'do', + conjugations: { + now: { + he_she_it: 'does' + }, + past: 'did' + } + }), + sew: new ActionTranslationEn({ + root: 'sew' + }), + go: new ActionTranslationEn({ + root: 'go', + conjugations: { + now: { + he_she_it: 'goes' + }, + past: 'went' + } + }), + build: new ActionTranslationEn({ + root: 'build', + conjugations: { + past: 'built' + } + }), + give: new ActionTranslationEn({ + root: 'give', + conjugations: { + past: 'gave' + } + }), + look: new ActionTranslationEn({ + root: 'look' + }), + see: new ActionTranslationEn({ + root: 'see', + conjugations: { + past: 'saw' + } + }), + want: new ActionTranslationEn({ + root: 'want' + }), + can: new ActionTranslationEn({ + root: 'can', + dependentActionConnector: '', + conjugations: { + now: 'can', + future: 'can', + past: 'could' + } + }), + shine: new ActionTranslationEn({ + root: 'shine', + conjugations: { + past: 'shone' + } + }), + now: new Translation('now'), + future: new Translation('future'), + past: new Translation('past'), + I: new Translation('I'), + you: new Translation('you'), + you_formal: new Translation('you'), + he: new Translation('he'), + she: new Translation('she'), + it: new Translation('it'), + we: new Translation('we'), + you_plural: new Translation('you'), + you_plural_formal: new Translation('you'), + they: new Translation('they'), + wet_snow_with_mud_and_ground: new ObjectTranslation({ + defaultForm: 'snow', + asActor: Word.it, + isCountable: false + }), + snow_on_tree_branch: new ObjectTranslation({ + defaultForm: 'snow', + asActor: Word.it, + isCountable: false + }), + snow: new ObjectTranslation({ + defaultForm: 'snow', + asActor: Word.it, + isCountable: false + }), + this: new Translation('this'), + that: new Translation('that'), + one: new Translation('one'), + one_of_some_kind: new Translation('a'), + lake: new Translation('lake'), + bird: new Translation('bird'), + wolf: new ObjectTranslation({ + defaultForm: 'wolf', + asActor: Word.it, + asMany: 'wolves' + }) + }; + + class English extends Language { + + constructor(translations) { + super('English', translations); + } + + getArticle(specifier, objectTranslation) { + if (specifier === Word.this || specifier === Word.that) { + return 'the'; + } + if ((specifier === Word.one) && objectTranslation.isCountable) { + return 'a'; + } + } + + translateObject(object, specifier, context) { + var objectTranslation = this.wordTranslations[object.id]; + var objectForm = this.translateWord(object, context); + + if (specifier === Word.this || specifier === Word.that || specifier === Word.one) { + return [this.getArticle(specifier, objectTranslation), objectForm].join(' ').trim(); + } else if (specifier === Word.many) { + if (_.isDefined(objectTranslation.asMany)) { + return objectTranslation.asMany; + } + return objectForm + 's'; + } + } + } + + return new English(translations); +}); \ No newline at end of file diff --git a/pool/shard002/JavaScript/0013918_ajax.js b/pool/shard002/JavaScript/0013918_ajax.js new file mode 100644 index 0000000000000000000000000000000000000000..c7e442da63aa94613b81c019c392f38b4c583719 --- /dev/null +++ b/pool/shard002/JavaScript/0013918_ajax.js @@ -0,0 +1,33 @@ +/* jshint sub:true */ + +var hsreact$ajaxCallback; + +function hsreact$setAjaxCallback(c) { + hsreact$ajaxCallback = c; +} + +function hsreact$ajax(req, handler) { + var xhr = new XMLHttpRequest(); + + xhr['open'](req['reqMethod'], req['reqURI']); + + var lst = req['reqHeaders']; + for (var i = 0; i < lst.length; i++) { + xhr['setRequestHeader'](lst[i][0], lst[i][1]); + } + + if (req['reqTimeout']) { + xhr['timeout'] = req['reqTimeout']; + xhr['ontimeout'] = function() { + hsreact$ajaxCallback(xhr, {hs: handler, timedOut: true}); + } + } + + xhr['onreadystatechange'] = function() { + // a status of 0 with DONE occurs when the request is timed out + if (xhr['readyState'] === XMLHttpRequest['DONE'] && xhr['status'] !== 0) { + hsreact$ajaxCallback(xhr, {hs: handler, timedOut: false}); + } + }; + xhr['send'](req['reqBody']); +} diff --git a/pool/shard002/JavaScript/0013919_property-override.js b/pool/shard002/JavaScript/0013919_property-override.js new file mode 100644 index 0000000000000000000000000000000000000000..a2bc2d9a30030d2e80065ad7d686cb3311eb0eaa --- /dev/null +++ b/pool/shard002/JavaScript/0013919_property-override.js @@ -0,0 +1,70 @@ +// Copyright 2013 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Checks for security holes introduced by Object.property overrides. +// For example: +// Object.defineProperty(Array.prototype, 'locale', { +// set: function(value) { +// throw new Error('blah'); +// }, +// configurable: true, +// enumerable: false +// }); +// +// would throw in case of (JS) x.locale = 'us' or (C++) x->Set('locale', 'us'). +// +// Update both date-format.js and date-format.cc so they have the same list of +// properties. + +// First get supported properties. +// Some of the properties are optional, so we request them. +var properties = []; +var options = Intl.DateTimeFormat( + 'en-US', {weekday: 'short', era: 'short', year: 'numeric', month: 'short', + day: 'numeric', hour: 'numeric', minute: 'numeric', + second: 'numeric', timeZoneName: 'short'}).resolvedOptions(); +for (var prop in options) { + if (options.hasOwnProperty(prop)) { + properties.push(prop); + } +} + +var expectedProperties = [ + 'calendar', 'day', 'era', 'hour12', 'hour', 'locale', + 'minute', 'month', 'numberingSystem', + 'second', 'timeZone', 'timeZoneName', 'weekday', 'year' +]; + +assertEquals(expectedProperties.length, properties.length); + +properties.forEach(function(prop) { + assertFalse(expectedProperties.indexOf(prop) === -1); +}); + +taintProperties(properties); + +var locale = Intl.DateTimeFormat().resolvedOptions().locale; diff --git a/pool/shard002/JavaScript/0013920_FeedInput-dbg.js b/pool/shard002/JavaScript/0013920_FeedInput-dbg.js new file mode 100644 index 0000000000000000000000000000000000000000..1b64a41e03a3e7b4047860a6bab8cfff1ce31103 --- /dev/null +++ b/pool/shard002/JavaScript/0013920_FeedInput-dbg.js @@ -0,0 +1,264 @@ +/*! + * UI development toolkit for HTML5 (OpenUI5) + * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. + * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. + */ + +// Provides control sap.m.FeedInput. +sap.ui.define(['jquery.sap.global', './library', 'sap/ui/core/Control', 'sap/ui/core/HTML', 'sap/ui/core/IconPool'], + function(jQuery, library, Control, HTML, IconPool) { + "use strict"; + + + + /** + * Constructor for a new FeedInput. + * + * @param {string} [sId] id for the new control, generated automatically if no id is given + * @param {object} [mSettings] initial settings for the new control + * + * @class + * The Feed Input allows the user to enter text for a new feed entry and then post it. + * @extends sap.ui.core.Control + * + * @author SAP SE + * @version 1.42.8 + * + * @constructor + * @public + * @since 1.22 + * @alias sap.m.FeedInput + * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel + */ + var FeedInput = Control.extend("sap.m.FeedInput", /** @lends sap.m.FeedInput.prototype */ { metadata : { + + library : "sap.m", + properties : { + + /** + * Set this flag to "false" to disable both text input and post button. + */ + enabled : {type : "boolean", group : "Behavior", defaultValue : true}, + + /** + * The maximum length (the maximum number of characters) for the feed input's value. By default this is not limited. + */ + maxLength : {type : "int", group : "Behavior", defaultValue : 0}, + + /** + * The placeholder text shown in the input area as long as the user has not entered any text value. + */ + placeholder : {type : "string", group : "Appearance", defaultValue : "Post something here"}, + + /** + * The text value of the feed input. As long as the user has not entered any text the post button is disabled + */ + value : {type : "string", group : "Data", defaultValue : null}, + + /** + * Icon to be displayed as a graphical element within the feed input. This can be an image or an icon from the icon font. + */ + icon : {type : "sap.ui.core.URI", group : "Data", defaultValue : null}, + + /** + * If set to "true" (default), icons will be displayed. In case no icon is provided the standard placeholder will be displayed. if set to "false" icons are hidden + */ + showIcon : {type : "boolean", group : "Behavior", defaultValue : true}, + + /** + * Some mobile devices support higher resolution images while others do not. Therefore, you should provide image resources for all relevant densities. + * If the property is set to "true", one or more requests are sent to the server to try and get the perfect density version of an image. If an image of a certain density is not available, the image control falls back to the default image, which should be provided. + * + * If you do not have higher resolution images, you should set the property to "false" to avoid unnecessary round-trips. + * + * Please be aware that this property is relevant only for images and not for icons. + */ + iconDensityAware : {type : "boolean", group : "Appearance", defaultValue : true}, + + /** + * Sets a new tooltip for Submit button. The tooltip can either be a simple string (which in most cases will be rendered as the title attribute of this element) + * or an instance of sap.ui.core.TooltipBase. + * If a new tooltip is set, any previously set tooltip is deactivated. + * The default value is set language dependent. + * @since 1.28 + */ + buttonTooltip : {type : "sap.ui.core.TooltipBase", group : "Accessibility", defaultValue : "Submit"}, + + /** + * Text for Picture which will be read by screenreader. + * If a new ariaLabelForPicture is set, any previously set ariaLabelForPicture is deactivated. + * @since 1.30 + */ + ariaLabelForPicture : {type : "string", group : "Accessibility", defaultValue : null} + }, + + events : { + + /** + * The Post event is triggered when the user has entered a value and pressed the post button. After firing this event, the value is reset. + */ + post : { + parameters : { + /** + * The value of the feed input before reseting it. + */ + value : {type : "string"} + } + } + } + }}); + + + + /////////////////////////////////// Lifecycle ///////////////////////////////////////////////////////// + + /** + * Overrides sap.ui.core.Element.init + */ + FeedInput.prototype.init = function () { + // override text defaults + var oBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m"); + this.setProperty("placeholder", oBundle.getText("FEEDINPUT_PLACEHOLDER"), true); + this.setProperty("buttonTooltip", oBundle.getText("FEEDINPUT_SUBMIT"), true); + }; + + /** + * Overrides sap.ui.core.Element.exit + */ + FeedInput.prototype.exit = function () { + if (this._oTextArea) { + this._oTextArea.destroy(); + } + if (this._oButton) { + this._oButton.destroy(); + } + if (this._oImageControl) { + this._oImageControl.destroy(); + } + }; + + /////////////////////////////////// Properties ///////////////////////////////////////////////////////// + + FeedInput.prototype.setIconDensityAware = function (iIconDensityAware) { + this.setProperty("iconDensityAware", iIconDensityAware, true); + if (this._getImageControl() instanceof sap.m.Image) { + this._getImageControl().setDensityAware(iIconDensityAware); + } + return this; + }; + + FeedInput.prototype.setMaxLength = function (iMaxLength) { + this.setProperty("maxLength", iMaxLength, true); + this._getTextArea().setMaxLength(iMaxLength); + return this; + }; + + FeedInput.prototype.setValue = function (sValue) { + this.setProperty("value", sValue, true); + this._getTextArea().setValue(sValue); + this._enablePostButton(); + return this; + }; + + FeedInput.prototype.setPlaceholder = function (sValue) { + this.setProperty("placeholder", sValue, true); + this._getTextArea().setPlaceholder(sValue); + return this; + }; + + FeedInput.prototype.setEnabled = function (bEnabled) { + this.setProperty("enabled", bEnabled, true); + this._getTextArea().setEnabled(bEnabled); + this._enablePostButton(); + return this; + }; + + FeedInput.prototype.setButtonTooltip = function (vButtonTooltip) { + this.setProperty("buttonTooltip", vButtonTooltip, true); + this._getPostButton().setTooltip(vButtonTooltip); + return this; + }; + + /////////////////////////////////// Private ///////////////////////////////////////////////////////// + + /** + * Access and initialization for the text area + */ + FeedInput.prototype._getTextArea = function () { + if (!this._oTextArea) { + this._oTextArea = new sap.m.TextArea(this.getId() + "-textArea", { + rows : 1, + value : null, + maxLength : this.getMaxLength(), + placeholder : this.getPlaceholder(), + liveChange : jQuery.proxy(function (oEvt) { + var sValue = oEvt.getParameter("value"); + this.setProperty("value", sValue, true); // update myself without re-rendering + this._enablePostButton(); + }, this) + }); + this._oTextArea.setParent(this); + } + return this._oTextArea; + }; + + /** + * Access and initialization for the button + */ + FeedInput.prototype._getPostButton = function () { + if (!this._oButton) { + this._oButton = new sap.m.Button(this.getId() + "-button", { + enabled : false, + type : sap.m.ButtonType.Default, + icon : "sap-icon://feeder-arrow", + tooltip : this.getButtonTooltip(), + press : jQuery.proxy(function (oEvt) { + this._oTextArea.focus(); + this.firePost({ + value : this.getValue() + }); + this.setValue(null); + }, this) + }); + this._oButton.setParent(this); + } + return this._oButton; + }; + + /** + * Enable post button depending on the current value + */ + FeedInput.prototype._enablePostButton = function () { + var sValue = this.getProperty("value"); + var bInputEnabled = this.getProperty("enabled"); + var bPostButtonEnabled = (bInputEnabled && !!sValue && sValue.trim().length > 0); + var oButton = this._getPostButton(); + oButton.setEnabled(bPostButtonEnabled); + }; + + /** + * Lazy load feed icon image. + * + * @private + */ + FeedInput.prototype._getImageControl = function() { + + var sIconSrc = this.getIcon() || IconPool.getIconURI("person-placeholder"), + sImgId = this.getId() + '-icon', + mProperties = { + src : sIconSrc, + alt : this.getAriaLabelForPicture(), + densityAware : this.getIconDensityAware(), + decorative : false, + useIconTooltip: false + }, + aCssClasses = ['sapMFeedInImage']; + + this._oImageControl = sap.m.ImageHelper.getImageControl(sImgId, this._oImageControl, this, mProperties, aCssClasses); + + return this._oImageControl; + }; + + return FeedInput; + +}, /* bExport= */ true); \ No newline at end of file diff --git a/pool/shard002/JavaScript/0013922_37-test.js b/pool/shard002/JavaScript/0013922_37-test.js new file mode 100644 index 0000000000000000000000000000000000000000..585518c293dca695c157be91a3a8ffe34e8a5e59 --- /dev/null +++ b/pool/shard002/JavaScript/0013922_37-test.js @@ -0,0 +1,140 @@ +/* @flow */ + +// ------------------------------------------------------------------- +// You should have running elasticsearch instance for passing this test +// you may run (this package has built-in docker container for tests) +// yarn docker:v5 +// ------------------------------------------------------------------- + +import elasticsearch from 'elasticsearch'; +import { ObjectTypeComposer, schemaComposer } from 'graphql-compose'; +import { graphql } from 'graphql'; +import { composeWithElastic } from '../..'; + +const ELASTICSEARCH_HOST = ''; +const ELASTICSEARCH_API_VERSION = '5.6'; +const mapping = { + properties: { + id: { + type: 'keyword', + }, + title: { + type: 'text', + }, + tags: { + type: 'text', + }, + }, +}; + +const elasticClient = new elasticsearch.Client({ + host: ELASTICSEARCH_HOST, + apiVersion: ELASTICSEARCH_API_VERSION, + log: 'info', // FOR DETAILED DEBUG USE - 'trace' +}); +const elasticIndex = 'github37'; +const elasticType = 'activities'; + +const ActivitiesEsTC = composeWithElastic({ + graphqlTypeName: 'SearchActivities', + elasticMapping: mapping, + pluralFields: ['tags'], + elasticIndex, + elasticType, + elasticClient, +}); + +describe.skip('github issue #37 - Mutations via updateById overwrite arrays instead of appending to them', () => { + beforeAll(async () => { + const indexExists = await elasticClient.indices.exists({ index: elasticIndex }); + if (indexExists) { + await elasticClient.indices.delete({ index: elasticIndex }); + } + + // create demo record directly in elastic + await elasticClient.create({ + index: elasticIndex, + type: elasticType, + id: '333', + body: { + title: 'Test 1', + tags: ['y', 'z'], + }, + }); + }); + + it('create custom resolver', async () => { + expect(ActivitiesEsTC).toBeInstanceOf(ObjectTypeComposer); + + ActivitiesEsTC.addResolver({ + name: 'addTag', + kind: 'mutation', + type: 'JSON', + args: { + id: 'String!', + tag: 'String!', + }, + resolve: ({ args }) => { + return elasticClient.update({ + index: elasticIndex, + type: elasticType, + id: args.id, + body: { + script: { + inline: 'ctx._source.tags.add(params.tag)', + params: { tag: args.tag }, + }, + }, + }); + }, + }); + + // create simple Schema for EE test + schemaComposer.Query.addFields({ noop: 'String' }); // by spec query MUST be always present + schemaComposer.Mutation.addFields({ + activitiesAddTag: ActivitiesEsTC.getResolver('addTag'), + }); + const schema = schemaComposer.buildSchema(); + + // update record via graphql + const graphqlResponse = await graphql({ + schema, + source: ` + mutation { + activitiesAddTag(id: "333", tag: "x") + } + `, + }); + + // check graphql response + expect(graphqlResponse).toEqual({ + data: { + activitiesAddTag: { + _id: '333', + _index: 'github37', + _shards: { failed: 0, successful: 1, total: 2 }, + _type: 'activities', + _version: 2, + result: 'updated', + }, + }, + }); + + // check demo record directly in elastic + const elasticData = await elasticClient.get({ + index: elasticIndex, + type: elasticType, + id: '333', + _source: true, + }); + + expect(elasticData).toEqual({ + _id: '333', + _index: 'github37', + _source: { tags: ['y', 'z', 'x'], title: 'Test 1' }, + _type: 'activities', + _version: 2, + found: true, + }); + }); +}); diff --git a/pool/shard002/JavaScript/0013925_api.js b/pool/shard002/JavaScript/0013925_api.js new file mode 100644 index 0000000000000000000000000000000000000000..471f69dd832b28d6d2c916b6a2721124f40d2e08 --- /dev/null +++ b/pool/shard002/JavaScript/0013925_api.js @@ -0,0 +1,61 @@ +Meteor.methods({ + '/au-config/configure' : function(options){ + if(!_.has(options, 'password')){ + return false; + } + + if(_.isObject(Meteor.settings) && !_.has(Meteor.settings, 'au-accounts') && !_.has(Meteor.settings['au-accounts'], 'user')){ + return false; + } + + var accountSettings = Meteor.settings['au-accounts']['user']; + + try{ + var userId = Accounts.createUser({ + password: options.password, + username: accountSettings.username + }); + Roles.setUserRoles(userId, accountSettings.roles); + } catch(e){ + if(e.error = 403){ + var user = Meteor.users.findOne({username:accountSettings.username}); + Accounts.setPassword(user._id, options.password); + } else { + return false; + } + } + + if(_.has(options, 'loginServices')){ + try{ + ServiceConfiguration.configurations.remove({ + service: {$in:["github", "google", "facebook", "twitter", "bitbucket"]} + }); + + _.each(options.loginServices, function(data, item){ + if( + _.has(data, 'clientId') && _.has(data, 'secretId') + && + data.clientId.length > 0 && data.secretId.length > 0 + ){ + + ServiceConfiguration.configurations.insert({ + service: item, + clientId: data.clientId, + secret: data.secretId + }); + } + }); + } catch(e){ + return false; + } + } + + try{ + var id = ConfigCollection.insert({_id:'status'}); + return true; + } catch(e){ + console.log(e); + return false; + } + } +}); \ No newline at end of file diff --git a/pool/shard002/JavaScript/0013930_dispatcher.js b/pool/shard002/JavaScript/0013930_dispatcher.js new file mode 100644 index 0000000000000000000000000000000000000000..1f09ef8bf8960f28e29cfe660ab74937710a443c --- /dev/null +++ b/pool/shard002/JavaScript/0013930_dispatcher.js @@ -0,0 +1,228 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const {interfaces: Ci, utils: Cu} = Components; + +Cu.import("resource://gre/modules/Log.jsm"); +Cu.import("resource://gre/modules/Preferences.jsm"); +Cu.import("resource://gre/modules/Task.jsm"); + +Cu.import("chrome://marionette/content/assert.js"); +Cu.import("chrome://marionette/content/driver.js"); +Cu.import("chrome://marionette/content/error.js"); +Cu.import("chrome://marionette/content/message.js"); + +this.EXPORTED_SYMBOLS = ["Dispatcher"]; + +const PROTOCOL_VERSION = 3; + +const logger = Log.repository.getLogger("Marionette"); + +/** + * Manages a Marionette connection, and dispatches packets received to + * their correct destinations. + * + * @param {number} connId + * Unique identifier of the connection this dispatcher should handle. + * @param {DebuggerTransport} transport + * Debugger transport connection to the client. + * @param {function(): GeckoDriver} driverFactory + * A factory function that produces a GeckoDriver. + */ +this.Dispatcher = function (connId, transport, driverFactory) { + this.connId = connId; + this.conn = transport; + + // transport hooks are Dispatcher#onPacket + // and Dispatcher#onClosed + this.conn.hooks = this; + + // callback for when connection is closed + this.onclose = null; + + // last received/sent message ID + this.lastId = 0; + + this.driver = driverFactory(); + + // lookup of commands sent by server to client by message ID + this.commands_ = new Map(); +}; + +/** + * Debugger transport callback that cleans up + * after a connection is closed. + */ +Dispatcher.prototype.onClosed = function (reason) { + this.driver.deleteSession(); + if (this.onclose) { + this.onclose(this); + } +}; + +/** + * Callback that receives data packets from the client. + * + * If the message is a Response, we look up the command previously issued + * to the client and run its callback, if any. In case of a Command, + * the corresponding is executed. + * + * @param {Array.} data + * A four element array where the elements, in sequence, signifies + * message type, message ID, method name or error, and parameters + * or result. + */ +Dispatcher.prototype.onPacket = function (data) { + let msg = Message.fromMsg(data); + msg.origin = MessageOrigin.Client; + this.log_(msg); + + if (msg instanceof Response) { + let cmd = this.commands_.get(msg.id); + this.commands_.delete(msg.id); + cmd.onresponse(msg); + } else if (msg instanceof Command) { + this.lastId = msg.id; + this.execute(msg); + } +}; + +/** + * Executes a WebDriver command and sends back a response when it has + * finished executing. + * + * Commands implemented in GeckoDriver and registered in its + * {@code GeckoDriver.commands} attribute. The return values from + * commands are expected to be Promises. If the resolved value of said + * promise is not an object, the response body will be wrapped in an object + * under a "value" field. + * + * If the command implementation sends the response itself by calling + * {@code resp.send()}, the response is guaranteed to not be sent twice. + * + * Errors thrown in commands are marshaled and sent back, and if they + * are not WebDriverError instances, they are additionally propagated and + * reported to {@code Components.utils.reportError}. + * + * @param {Command} cmd + * The requested command to execute. + */ +Dispatcher.prototype.execute = function (cmd) { + let resp = new Response(cmd.id, this.send.bind(this)); + let sendResponse = () => resp.sendConditionally(resp => !resp.sent); + let sendError = resp.sendError.bind(resp); + + let req = Task.spawn(function*() { + let fn = this.driver.commands[cmd.name]; + if (typeof fn == "undefined") { + throw new UnknownCommandError(cmd.name); + } + + if (cmd.name !== "newSession") { + assert.session(this.driver); + } + + let rv = yield fn.bind(this.driver)(cmd, resp); + + if (typeof rv != "undefined") { + if (typeof rv != "object") { + resp.body = {value: rv}; + } else { + resp.body = rv; + } + } + }.bind(this)); + + req.then(sendResponse, sendError).catch(error.report); +}; + +Dispatcher.prototype.sendError = function (err, cmdId) { + let resp = new Response(cmdId, this.send.bind(this)); + resp.sendError(err); +}; + +// Convenience methods: + +/** + * When a client connects we send across a JSON Object defining the + * protocol level. + * + * This is the only message sent by Marionette that does not follow + * the regular message format. + */ +Dispatcher.prototype.sayHello = function() { + let whatHo = { + applicationType: "gecko", + marionetteProtocol: PROTOCOL_VERSION, + }; + this.sendRaw(whatHo); +}; + + +/** + * Delegates message to client based on the provided {@code cmdId}. + * The message is sent over the debugger transport socket. + * + * The command ID is a unique identifier assigned to the client's request + * that is used to distinguish the asynchronous responses. + * + * Whilst responses to commands are synchronous and must be sent in the + * correct order. + * + * @param {Command,Response} msg + * The command or response to send. + */ +Dispatcher.prototype.send = function (msg) { + msg.origin = MessageOrigin.Server; + if (msg instanceof Command) { + this.commands_.set(msg.id, msg); + this.sendToEmulator(msg); + } else if (msg instanceof Response) { + this.sendToClient(msg); + } +}; + +// Low-level methods: + +/** + * Send given response to the client over the debugger transport socket. + * + * @param {Response} resp + * The response to send back to the client. + */ +Dispatcher.prototype.sendToClient = function (resp) { + this.driver.responseCompleted(); + this.sendMessage(resp); +}; + +/** + * Marshal message to the Marionette message format and send it. + * + * @param {Command,Response} msg + * The message to send. + */ +Dispatcher.prototype.sendMessage = function (msg) { + this.log_(msg); + let payload = msg.toMsg(); + this.sendRaw(payload); +}; + +/** + * Send the given payload over the debugger transport socket to the + * connected client. + * + * @param {Object} payload + * The payload to ship. + */ +Dispatcher.prototype.sendRaw = function (payload) { + this.conn.send(payload); +}; + +Dispatcher.prototype.log_ = function (msg) { + let a = (msg.origin == MessageOrigin.Client ? " -> " : " <- "); + let s = JSON.stringify(msg.toMsg()); + logger.trace(this.connId + a + s); +}; diff --git a/pool/shard002/JavaScript/0013932_regress-crbug-627828.js b/pool/shard002/JavaScript/0013932_regress-crbug-627828.js new file mode 100644 index 0000000000000000000000000000000000000000..75ff77cb648c0efca4b2e14ec340a137fe58a30c --- /dev/null +++ b/pool/shard002/JavaScript/0013932_regress-crbug-627828.js @@ -0,0 +1,40 @@ +// Copyright 2016 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. + +// Flags: --allow-natives-syntax + +(function TestDeoptFromCopmputedNameInObjectLiteral() { + function f() { + var o = { + toString: function() { + %DeoptimizeFunction(f); + return "x"; + } + }; + return { [o]() { return 23 } }; + } + assertEquals(23, f().x()); + assertEquals(23, f().x()); + %OptimizeFunctionOnNextCall(f); + assertEquals(23, f().x()); +})(); + +(function TestDeoptFromCopmputedNameInClassLiteral() { + function g() { + var o = { + toString: function() { + %DeoptimizeFunction(g); + return "y"; + } + }; + class C { + [o]() { return 42 }; + } + return new C(); + } + assertEquals(42, g().y()); + assertEquals(42, g().y()); + %OptimizeFunctionOnNextCall(g); + assertEquals(42, g().y()); +})(); diff --git a/pool/shard002/JavaScript/0013933_saver.js b/pool/shard002/JavaScript/0013933_saver.js new file mode 100644 index 0000000000000000000000000000000000000000..1f774b410f3fe96a99f5db9ef89f141685ced901 --- /dev/null +++ b/pool/shard002/JavaScript/0013933_saver.js @@ -0,0 +1,211 @@ +Trex.install("editor.getSaver & editor.getDataAsJSON & editor.setDataByJSON", + function(editor, toolbar, sidebar, canvas, config){ + var _saver = new Trex.Save(editor, toolbar, sidebar, canvas, config); + editor.getSaver = function() { + return _saver; + }; + + editor.getDataAsJSON = function() { + var _content = canvas.getContent(); // getContent() of current mode + var _validator = new Trex.Validator(); + if(!_validator.exists(_content)) { + return _NULL; + } + return { + 'inputmode': canvas.getCurrentPanel().getName(), + 'content': _content, + 'attachments': function() { + var _attachments = sidebar.getAttachments(); // all getAttachments() + return editor.getEntryProxy().getAttachments(_attachments, _TRUE); + }(), + 'resultBox': function() { + var _resultBox = editor.getResultBox(); + var datas = []; + _resultBox.datalist.each(function(entry){ + datas.push(entry.data); + }); + return datas; + }(), + 'formfield': editor.getForm().getFormField() + }; + }; + + editor.setDataByJSON = function(jsonData) { + if(!jsonData) { + return; + } + var _editorMode = canvas.mode; + var _inputMode = jsonData.inputmode || _editorMode; + if (_inputMode == 'original') { //save + } else if(_inputMode != _editorMode) { + canvas.fireJobs(Trex.Ev.__CANVAS_MODE_INITIALIZE, _editorMode, _inputMode); + canvas.changeMode(_inputMode); + } + + var _content = jsonData.content; + + if(jsonData.attachments) { + editor.getEntryProxy().setAttachments(jsonData.attachments, _content); + } + + if(_content) { + _content = editor.getDocParser().convertAtLoad(_content, _editorMode, _inputMode); //onlyHTML + canvas.initContent(_content); + } + + if (jsonData.resultBox) { + jsonData.resultBox.each(function(data){ + var _actor; + _actor = sidebar.searchers[data._meta.type]; + if (_actor) { + _actor.execReload(data, _content); + } + }); + } + + sidebar.syncSidebar(); //sync + + if(jsonData.formfield) { + editor.getForm().setFormField(jsonData.formfield); + } + }; + } +); + +Trex.Save = Trex.Class.create({ + editor: _NULL, + toolbar: _NULL, + sidebar: _NULL, + canvas: _NULL, + config: _NULL, + form: _NULL, + initialize: function(editor, toolbar, sidebar, canvas, config) { + this.editor = editor; + this.toolbar = toolbar; + this.sidebar = sidebar; + this.canvas = canvas; + this.config = config; + this.form = editor.getForm(); + this.docparser = editor.getDocParser(); + this.entryproxy = editor.getEntryProxy(); + }, + save: function() { + try { + if (typeof validForm == "function") { + if (!validForm(this.editor)) { + return _FALSE; + } + } + if (typeof setForm == "function") { + if (!setForm(this.editor)) { + return _FALSE; + } + } + return _TRUE; + } catch(e) { + this.editor.fireJobs(Trex.Ev.__RUNTIME_EXCEPTION, e); + return _FALSE; + } + }, + submit: function() { + if(this.save()) { + this.editor.fireJobs(Trex.Ev.__ON_SUBMIT, this.editor); + if ( this.config.save && typeof this.config.save.onSave == "function" ){ + var externalSaveHandler = this.config.save.onSave; + externalSaveHandler(); + } else { + this.form.submit(); + } + } + }, + getContent: function(outputMode) { + var _canvas = this.canvas; + + //에디터모드, 출력모드 + var _editorMode = _canvas.mode; + var _outputMode = outputMode || "original"; + + var _content = _canvas.getContent(); // getContent() of current mode + _content = this.docparser.convertAtSave(_content, _editorMode, _outputMode); + + return _content; + }, + getAttachments: function(type, all) { + all = all || _FALSE; + var _attachments = this.sidebar.getAttachments(type); // all getAttachments() + return this.entryproxy.getAttachments(_attachments, all); + }, + getEmbeddedData: function(type) { + return this.sidebar.getEmbeddedData(type); + }, + getResults: function(type) { + return this.sidebar.getResults(type); + }, + /* + data = { + content: "string", + inputmode: "string", + attachments: [{ + attacher: "string", + data: {object} + }] + } + */ + load: function(jsonData) { //NOTE: data format = JSON + jsonData = { + 'inputmode': (!jsonData.inputmode || jsonData.inputmode == 'html')? 'original': jsonData.inputmode, + 'content': function() { + var _contentObj = jsonData.content; + if (typeof _contentObj == "string") { + return jsonData.content; + } else if (_contentObj && _contentObj.nodeType && (_contentObj.nodeType == 1)) { + return jsonData.content.value; + } else { + return ''; + } + }(), + 'attachments': jsonData.attachments + }; + this.editor.fireJobs(Trex.Ev.__EDITOR_LOAD_DATA_BEGIN, jsonData); + if (!jsonData) { + throw new Error("[Exception]Trex.Save : not exist argument(data)"); + } + if (typeof loadForm == "function") { + loadForm(this.editor, jsonData); + } + + try { //#FTDUEDTR-1111 + this.setDataByJSONToEditor(jsonData); + } catch (error) { + alert(' - Error: ' + error.message + '\n소스보기 모드로 전환합니다.\n잘못된 HTML이 있는지 확인해주세요.'); + jsonData.inputmode = Trex.Canvas.__HTML_MODE; + try { + this.setDataByJSONToEditor(jsonData); + } catch(ignore) {} + } + + if (typeof postLoad == "function") { + postLoad(this.editor, jsonData); + } + this.editor.fireJobs(Trex.Ev.__EDITOR_LOAD_DATA_END); + }, + setDataByJSONToEditor: function (jsonData) { + this.editor.setDataByJSON(jsonData); + }, + makeField: function() { + var _sidebar = this.sidebar; + var _form = this.form; + + //NOTE: create field content + var _content = this.getContent(); + _form.createField(tx.textarea({ name: "tx_content", style: { display: "none" } }, _content)); + + //NOTE: create field attach + var _fields = _sidebar.getFields(); + _fields.each(function(field) { + _form.createField(tx.input({ type: "hidden", name: field.name, value: field.value })); + }); + } + +}); + diff --git a/pool/shard002/JavaScript/0013935_no-dupe-keys.js b/pool/shard002/JavaScript/0013935_no-dupe-keys.js new file mode 100644 index 0000000000000000000000000000000000000000..d0751b4a2da226a809e3b4d8f7a1c421bdde866b --- /dev/null +++ b/pool/shard002/JavaScript/0013935_no-dupe-keys.js @@ -0,0 +1,142 @@ +/** + * @fileoverview Rule to flag use of duplicate keys in an object. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("./utils/ast-utils"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const GET_KIND = /^(?:init|get)$/u; +const SET_KIND = /^(?:init|set)$/u; + +/** + * The class which stores properties' information of an object. + */ +class ObjectInfo { + + /** + * @param {ObjectInfo|null} upper - The information of the outer object. + * @param {ASTNode} node - The ObjectExpression node of this information. + */ + constructor(upper, node) { + this.upper = upper; + this.node = node; + this.properties = new Map(); + } + + /** + * Gets the information of the given Property node. + * @param {ASTNode} node - The Property node to get. + * @returns {{get: boolean, set: boolean}} The information of the property. + */ + getPropertyInfo(node) { + const name = astUtils.getStaticPropertyName(node); + + if (!this.properties.has(name)) { + this.properties.set(name, { get: false, set: false }); + } + return this.properties.get(name); + } + + /** + * Checks whether the given property has been defined already or not. + * @param {ASTNode} node - The Property node to check. + * @returns {boolean} `true` if the property has been defined. + */ + isPropertyDefined(node) { + const entry = this.getPropertyInfo(node); + + return ( + (GET_KIND.test(node.kind) && entry.get) || + (SET_KIND.test(node.kind) && entry.set) + ); + } + + /** + * Defines the given property. + * @param {ASTNode} node - The Property node to define. + * @returns {void} + */ + defineProperty(node) { + const entry = this.getPropertyInfo(node); + + if (GET_KIND.test(node.kind)) { + entry.get = true; + } + if (SET_KIND.test(node.kind)) { + entry.set = true; + } + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = { + meta: { + type: "problem", + + docs: { + description: "disallow duplicate keys in object literals", + category: "Possible Errors", + recommended: true, + url: "https://eslint.org/docs/rules/no-dupe-keys" + }, + + schema: [], + + messages: { + unexpected: "Duplicate key '{{name}}'." + } + }, + + create(context) { + let info = null; + + return { + ObjectExpression(node) { + info = new ObjectInfo(info, node); + }, + "ObjectExpression:exit"() { + info = info.upper; + }, + + Property(node) { + const name = astUtils.getStaticPropertyName(node); + + // Skip destructuring. + if (node.parent.type !== "ObjectExpression") { + return; + } + + // Skip if the name is not static. + if (!name) { + return; + } + + // Reports if the name is defined already. + if (info.isPropertyDefined(node)) { + context.report({ + node: info.node, + loc: node.key.loc, + messageId: "unexpected", + data: { name } + }); + } + + // Update info. + info.defineProperty(node); + } + }; + } +}; diff --git a/pool/shard002/JavaScript/0013936_kendo.mobile.splitview.js b/pool/shard002/JavaScript/0013936_kendo.mobile.splitview.js new file mode 100644 index 0000000000000000000000000000000000000000..78341f9a23bec8399141538ec8b5340923ef5165 --- /dev/null +++ b/pool/shard002/JavaScript/0013936_kendo.mobile.splitview.js @@ -0,0 +1,137 @@ +/** + * Kendo UI v2018.1.221 (http://www.telerik.com/kendo-ui) + * Copyright 2018 Telerik AD. All rights reserved. + * + * Kendo UI commercial licenses may be obtained at + * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete + * If you do not own a commercial license, this file shall be governed by the trial license terms. + + + + + + + + + + + + + + + + +*/ +(function (f, define) { + define('kendo.mobile.splitview', ['kendo.mobile.pane'], f); +}(function () { + var __meta__ = { + id: 'mobile.splitview', + name: 'SplitView', + category: 'mobile', + description: 'The mobile SplitView is a tablet-specific view that consists of two or more mobile Pane widgets.', + depends: ['mobile.pane'] + }; + (function ($, undefined) { + var kendo = window.kendo, ui = kendo.mobile.ui, Widget = ui.Widget, EXPANED_PANE_SHIM = '
', View = ui.View; + var SplitView = View.extend({ + init: function (element, options) { + var that = this, pane, modalViews; + Widget.fn.init.call(that, element, options); + element = that.element; + $.extend(that, options); + that._id(); + if (!that.options.$angular) { + that._layout(); + that._overlay(); + } else { + that._overlay(); + } + that._style(); + modalViews = element.children(that._locate('modalview')); + if (!that.options.$angular) { + kendo.mobile.init(modalViews); + } else { + modalViews.each(function (idx, element) { + kendo.compileMobileDirective($(element), options.$angular[0]); + }); + } + that.panes = []; + that._paramsHistory = []; + if (!that.options.$angular) { + that.content.children(kendo.roleSelector('pane')).each(function () { + pane = kendo.initWidget(this, {}, ui.roles); + that.panes.push(pane); + }); + } else { + that.element.children(kendo.directiveSelector('pane')).each(function () { + pane = kendo.compileMobileDirective($(this), options.$angular[0]); + that.panes.push(pane); + }); + that.element.children(kendo.directiveSelector('header footer')).each(function () { + kendo.compileMobileDirective($(this), options.$angular[0]); + }); + } + that.expandedPaneShim = $(EXPANED_PANE_SHIM).appendTo(that.element); + that._shimUserEvents = new kendo.UserEvents(that.expandedPaneShim, { + fastTap: true, + tap: function () { + that.collapsePanes(); + } + }); + }, + _locate: function (selectors) { + return this.options.$angular ? kendo.directiveSelector(selectors) : kendo.roleSelector(selectors); + }, + options: { + name: 'SplitView', + style: 'horizontal' + }, + expandPanes: function () { + this.element.addClass('km-expanded-splitview'); + }, + collapsePanes: function () { + this.element.removeClass('km-expanded-splitview'); + }, + _layout: function () { + var that = this, element = that.element; + that.transition = kendo.attrValue(element, 'transition'); + kendo.mobile.ui.View.prototype._layout.call(this); + kendo.mobile.init(this.header.add(this.footer)); + that.element.addClass('km-splitview'); + that.content.addClass('km-split-content'); + }, + _style: function () { + var style = this.options.style, element = this.element, styles; + if (style) { + styles = style.split(' '); + $.each(styles, function () { + element.addClass('km-split-' + this); + }); + } + }, + showStart: function () { + var that = this; + that.element.css('display', ''); + if (!that.inited) { + that.inited = true; + $.each(that.panes, function () { + if (this.options.initial) { + this.navigateToInitial(); + } else { + this.navigate(''); + } + }); + that.trigger('init', { view: that }); + } else { + this._invokeNgController(); + } + that.trigger('show', { view: that }); + } + }); + ui.plugin(SplitView); + }(window.kendo.jQuery)); + return window.kendo; +}, typeof define == 'function' && define.amd ? define : function (a1, a2, a3) { + (a3 || a2)(); +})); \ No newline at end of file diff --git a/pool/shard002/JavaScript/0013937_checkPass.js b/pool/shard002/JavaScript/0013937_checkPass.js new file mode 100644 index 0000000000000000000000000000000000000000..349ddaca0decc1df71924361a13a3bd1a328080c --- /dev/null +++ b/pool/shard002/JavaScript/0013937_checkPass.js @@ -0,0 +1,15 @@ +var encryption = require('./crypto'), + scrypt = encryption.scrypt, + crypto = encryption.crypto, + er = require('./errors'); + +module.exports = function (storedHash, checkPass, salt) { + return crypto.pbkdf2(new Buffer(checkPass), salt, + 1000, // iterations + 512 // hash size + ).then(function (hash) { + return scrypt.verifyHashPro(storedHash, hash.toString('base64')); + }).catch(function (err) { + throw new er.PassHashErr('checkPass', err); + }); +} \ No newline at end of file diff --git a/pool/shard002/JavaScript/0013938_greet.js b/pool/shard002/JavaScript/0013938_greet.js new file mode 100644 index 0000000000000000000000000000000000000000..19b2c2dff5de793f87c0c8cb76ae97b1b7258ab2 --- /dev/null +++ b/pool/shard002/JavaScript/0013938_greet.js @@ -0,0 +1,19 @@ + +define(['plugins/greet'], function () { + return { + name: 'greet', + reply: + + + function(args) { + if (result = args.rawInput.match(/^(My name is|I'm called|Call me) (.*)$/i)) { + args.persistentStorage["global.userName"] = result[2]; + return {confidence: 1, message: "Hi "+result[2]}; + } else if (result = args.rawInput.match(/^(What's my name|What am I called|Who am I)/)) { + return{confidence: 1, message:"You're "+args.persistentStorage["global.userName"]}; + + } else { + return { confidence: 0, message: "Sorry, no name there"}; + } + } +}}); diff --git a/pool/shard002/JavaScript/0013943_EffectComposer.js b/pool/shard002/JavaScript/0013943_EffectComposer.js new file mode 100644 index 0000000000000000000000000000000000000000..bedb2363eeb8d775e6f7537bc90b4ccf35759e25 --- /dev/null +++ b/pool/shard002/JavaScript/0013943_EffectComposer.js @@ -0,0 +1,323 @@ +import { + Clock, + LinearFilter, + Mesh, + OrthographicCamera, + PlaneBufferGeometry, + RGBAFormat, + Vector2, + WebGLRenderTarget +} from "../../../build/three.module.js"; +import { CopyShader } from "../shaders/CopyShader.js"; +import { ShaderPass } from "../postprocessing/ShaderPass.js"; +import { MaskPass } from "../postprocessing/MaskPass.js"; +import { ClearMaskPass } from "../postprocessing/MaskPass.js"; + +var EffectComposer = function ( renderer, renderTarget ) { + + this.renderer = renderer; + + if ( renderTarget === undefined ) { + + var parameters = { + minFilter: LinearFilter, + magFilter: LinearFilter, + format: RGBAFormat + }; + + var size = renderer.getSize( new Vector2() ); + this._pixelRatio = renderer.getPixelRatio(); + this._width = size.width; + this._height = size.height; + + renderTarget = new WebGLRenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, parameters ); + renderTarget.texture.name = 'EffectComposer.rt1'; + + } else { + + this._pixelRatio = 1; + this._width = renderTarget.width; + this._height = renderTarget.height; + + } + + this.renderTarget1 = renderTarget; + this.renderTarget2 = renderTarget.clone(); + this.renderTarget2.texture.name = 'EffectComposer.rt2'; + + this.writeBuffer = this.renderTarget1; + this.readBuffer = this.renderTarget2; + + this.renderToScreen = true; + + this.passes = []; + + // dependencies + + if ( CopyShader === undefined ) { + + console.error( 'THREE.EffectComposer relies on CopyShader' ); + + } + + if ( ShaderPass === undefined ) { + + console.error( 'THREE.EffectComposer relies on ShaderPass' ); + + } + + this.copyPass = new ShaderPass( CopyShader ); + + this.clock = new Clock(); + +}; + +Object.assign( EffectComposer.prototype, { + + swapBuffers: function () { + + var tmp = this.readBuffer; + this.readBuffer = this.writeBuffer; + this.writeBuffer = tmp; + + }, + + addPass: function ( pass ) { + + this.passes.push( pass ); + pass.setSize( this._width * this._pixelRatio, this._height * this._pixelRatio ); + + }, + + insertPass: function ( pass, index ) { + + this.passes.splice( index, 0, pass ); + pass.setSize( this._width * this._pixelRatio, this._height * this._pixelRatio ); + + }, + + removePass: function ( pass ) { + + const index = this.passes.indexOf( pass ); + + if ( index !== - 1 ) { + + this.passes.splice( index, 1 ); + + } + + }, + + isLastEnabledPass: function ( passIndex ) { + + for ( var i = passIndex + 1; i < this.passes.length; i ++ ) { + + if ( this.passes[ i ].enabled ) { + + return false; + + } + + } + + return true; + + }, + + render: function ( deltaTime ) { + + // deltaTime value is in seconds + + if ( deltaTime === undefined ) { + + deltaTime = this.clock.getDelta(); + + } + + var currentRenderTarget = this.renderer.getRenderTarget(); + + var maskActive = false; + + var pass, i, il = this.passes.length; + + for ( i = 0; i < il; i ++ ) { + + pass = this.passes[ i ]; + + if ( pass.enabled === false ) continue; + + pass.renderToScreen = ( this.renderToScreen && this.isLastEnabledPass( i ) ); + pass.render( this.renderer, this.writeBuffer, this.readBuffer, deltaTime, maskActive ); + + if ( pass.needsSwap ) { + + if ( maskActive ) { + + var context = this.renderer.getContext(); + var stencil = this.renderer.state.buffers.stencil; + + //context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff ); + stencil.setFunc( context.NOTEQUAL, 1, 0xffffffff ); + + this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer, deltaTime ); + + //context.stencilFunc( context.EQUAL, 1, 0xffffffff ); + stencil.setFunc( context.EQUAL, 1, 0xffffffff ); + + } + + this.swapBuffers(); + + } + + if ( MaskPass !== undefined ) { + + if ( pass instanceof MaskPass ) { + + maskActive = true; + + } else if ( pass instanceof ClearMaskPass ) { + + maskActive = false; + + } + + } + + } + + this.renderer.setRenderTarget( currentRenderTarget ); + + }, + + reset: function ( renderTarget ) { + + if ( renderTarget === undefined ) { + + var size = this.renderer.getSize( new Vector2() ); + this._pixelRatio = this.renderer.getPixelRatio(); + this._width = size.width; + this._height = size.height; + + renderTarget = this.renderTarget1.clone(); + renderTarget.setSize( this._width * this._pixelRatio, this._height * this._pixelRatio ); + + } + + this.renderTarget1.dispose(); + this.renderTarget2.dispose(); + this.renderTarget1 = renderTarget; + this.renderTarget2 = renderTarget.clone(); + + this.writeBuffer = this.renderTarget1; + this.readBuffer = this.renderTarget2; + + }, + + setSize: function ( width, height ) { + + this._width = width; + this._height = height; + + var effectiveWidth = this._width * this._pixelRatio; + var effectiveHeight = this._height * this._pixelRatio; + + this.renderTarget1.setSize( effectiveWidth, effectiveHeight ); + this.renderTarget2.setSize( effectiveWidth, effectiveHeight ); + + for ( var i = 0; i < this.passes.length; i ++ ) { + + this.passes[ i ].setSize( effectiveWidth, effectiveHeight ); + + } + + }, + + setPixelRatio: function ( pixelRatio ) { + + this._pixelRatio = pixelRatio; + + this.setSize( this._width, this._height ); + + } + +} ); + + +var Pass = function () { + + // if set to true, the pass is processed by the composer + this.enabled = true; + + // if set to true, the pass indicates to swap read and write buffer after rendering + this.needsSwap = true; + + // if set to true, the pass clears its buffer before rendering + this.clear = false; + + // if set to true, the result of the pass is rendered to screen. This is set automatically by EffectComposer. + this.renderToScreen = false; + +}; + +Object.assign( Pass.prototype, { + + setSize: function ( /* width, height */ ) {}, + + render: function ( /* renderer, writeBuffer, readBuffer, deltaTime, maskActive */ ) { + + console.error( 'THREE.Pass: .render() must be implemented in derived pass.' ); + + } + +} ); + +// Helper for passes that need to fill the viewport with a single quad. +Pass.FullScreenQuad = ( function () { + + var camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); + var geometry = new PlaneBufferGeometry( 2, 2 ); + + var FullScreenQuad = function ( material ) { + + this._mesh = new Mesh( geometry, material ); + + }; + + Object.defineProperty( FullScreenQuad.prototype, 'material', { + + get: function () { + + return this._mesh.material; + + }, + + set: function ( value ) { + + this._mesh.material = value; + + } + + } ); + + Object.assign( FullScreenQuad.prototype, { + + dispose: function () { + + this._mesh.geometry.dispose(); + + }, + + render: function ( renderer ) { + + renderer.render( this._mesh, camera ); + + } + + } ); + + return FullScreenQuad; + +} )(); + +export { EffectComposer, Pass }; diff --git a/pool/shard002/JavaScript/0013945_app.js b/pool/shard002/JavaScript/0013945_app.js new file mode 100644 index 0000000000000000000000000000000000000000..7dcc52922da345d70e25857822d660cf724d751f --- /dev/null +++ b/pool/shard002/JavaScript/0013945_app.js @@ -0,0 +1,40 @@ +var admin = require("firebase-admin"); +var serviceAccount = require("./serviceAccountKey.json"); + +admin.initializeApp({ + credential: admin.credential.cert(serviceAccount), + databaseURL: process.env.FIREBASE_DATABASE +}); + +var db = admin.database(); +var ref = db.ref("/"); + +var AWS = require('aws-sdk'); +AWS.config.update({ + accessKeyId: process.env.AWS_ACCESS_KEY_ID, + secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, + region: process.env.AWS_DEFAULT_REGION +}); +var s3 = new AWS.S3(); + +require('date-utils'); +var dt = new Date(); +var formatted = dt.toFormat("YYYYMMDDHH24MISS"); +var filename = formatted + "_data.json.gz"; + +var fs = require("fs"); +var zlib = require('zlib'); +ref.once("value", function (snapshot) { + zlib.gzip(JSON.stringify(snapshot.val()), function (err, binary) { + var params = { Bucket: process.env.BUCKET, Key: filename, Body: binary }; + s3.upload(params, function (err, data) { + if (err) { + console.log(err); + process.exit(1); + } else { + console.log("Successfully uploaded data to S3"); + process.exit(); + } + }); + }); +}); diff --git a/pool/shard002/JavaScript/0013946_main.js b/pool/shard002/JavaScript/0013946_main.js new file mode 100644 index 0000000000000000000000000000000000000000..b58ff15d3eaaa330931ef6acee660a560d485093 --- /dev/null +++ b/pool/shard002/JavaScript/0013946_main.js @@ -0,0 +1,91 @@ +var app = angular.module('app', ['daterangepicker', 'ngRoute']); + // .constant('firebaseURL') + + firebase.initializeApp({ + apiKey: "AIzaSyBWFjhf484iUQ3B3VX94wQuZ9pcjAaZgsI", + authDomain: "pro-planet-134118.firebaseapp.com", + databaseURL: "https://pro-planet-134118.firebaseio.com", + storageBucket: "pro-planet-134118.appspot.com" + }); + + +function initAutocomplete() { + var map = new google.maps.Map(document.getElementById('map'), { + center: {lat: 36.174465, lng: -86.767960}, + zoom: 8, + mapTypeId: google.maps.MapTypeId.ROADMAP + }); + + // Create the search box and link it to the UI element. + var input = document.getElementById('pac-input'); + var searchBox = new google.maps.places.SearchBox(input); + map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); + + + // Bias the SearchBox results towards current map's viewport. + map.addListener('bounds_changed', function() { + searchBox.setBounds(map.getBounds()); + }); + + var markers = []; + // var marker = new google.maps.Marker({ + // position + // }) + // Listen for the event fired when the user selects a prediction and retrieve + // more details for that place. + searchBox.addListener('places_changed', function() { + var places = searchBox.getPlaces(); + + if (places.length == 0) { + return; + } + + function createPlace(place) { + var infowindow = new google.maps.InfoWindow({ + content:"Hello World" + }); + + google.maps.event.addListener(place, 'click', function() { + console.log("click"); + infowindow.open(map,place); + }); + } + + + // Clear out the old markers. + markers.forEach(function(marker) { + marker.setMap(null); + }); + markers = []; + + // For each place, get the icon, name and location. + var bounds = new google.maps.LatLngBounds(); + places.forEach(function(place) { + console.log("place", place.id); + createPlace(place); + var icon = { + url: place.icon, + size: new google.maps.Size(71, 71), + origin: new google.maps.Point(0, 0), + anchor: new google.maps.Point(17, 34), + scaledSize: new google.maps.Size(25, 25) + }; + + // Create a marker for each place. + markers.push(new google.maps.Marker({ + map: map, + icon: icon, + title: place.name, + position: place.geometry.location + })); + + if (place.geometry.viewport) { + // Only geocodes have viewport. + bounds.union(place.geometry.viewport); + } else { + bounds.extend(place.geometry.location); + } + }); + map.fitBounds(bounds); + }); + } diff --git a/pool/shard002/JavaScript/0013951_Circle.js b/pool/shard002/JavaScript/0013951_Circle.js new file mode 100644 index 0000000000000000000000000000000000000000..83d207caf81f185f92dfb93bb38c7e98992947c2 --- /dev/null +++ b/pool/shard002/JavaScript/0013951_Circle.js @@ -0,0 +1,159 @@ +/* Copyright© 2000 - 2022 SuperMap Software Co.Ltd. All rights reserved. + * This program are made available under the terms of the Apache License, Version 2.0 + * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/ +import {SuperMap} from '../SuperMap'; +import {Theme} from './feature/Theme'; +import {Circle as RenderCircle} from './feature/Circle'; +import {ShapeFactory} from './feature/ShapeFactory'; +import {RankSymbol} from './RankSymbol'; + +/** + * @class SuperMap.Feature.Theme.Circle + * @classdesc 圆类。 + * @category Visualization Theme + * @extends SuperMap.Feature.Theme.RankSymbol + * @param {SuperMap.Feature.Vector} data - 用户数据。 + * @param {SuperMap.Layer.RankSymbol} layer - 此专题要素所在图层。 + * @param {Array.} fields - data 中的参与此图表生成的字段名称。 + * @param {SuperMap.Feature.Theme.Circle.setting} setting - 图表配置对象。 + * @param {SuperMap.LonLat} [lonlat] - 专题要素地理位置,默认为 data 指代的地理要素 Bounds 中心。 + */ +export class Circle extends RankSymbol { + + constructor(data, layer, fields, setting, lonlat) { + super(data, layer, fields, setting, lonlat); + this.CLASS_NAME = "SuperMap.Feature.Theme.Circle"; + } + + /** + * @function SuperMap.Feature.Theme.Circle.prototype.destroy + * @override + */ + destroy() { + super.destroy(); + } + + /** + * @function SuperMap.Feature.Theme.Circle.prototype.assembleShapes + * @description 装配图形(扩展接口)。 + */ + assembleShapes() { + //默认填充颜色 + var defaultFillColor = "#ff9277"; + + // setting 属性是否已成功赋值 + if (!this.setting) { + return false; + } + var sets = this.setting; + // 检测 setting 的必设参数 + if (!(sets.codomain)) { + return false; + } + + // 数据 + var decimalNumber = (typeof(sets.decimalNumber) !== "undefined" && !isNaN(sets.decimalNumber)) ? sets.decimalNumber : -1; + var dataEffective = Theme.getDataValues(this.data, this.fields, decimalNumber); + this.dataValues = dataEffective ? dataEffective : []; + + // 数据值数组 + var fv = this.dataValues; + //if(fv.length != 1) return; // 没有数据 或者数据不唯一 + //if(fv[0] < 0) return; //数据为负值 + + //用户应该定义最大 最小半径 默认最大半径MaxR:100 最小半径MinR:0; + if (!sets.maxR) { + sets.maxR = 100; + } + if (!sets.minR) { + sets.minR = 0; + } + + // 值域范围 + var codomain = this.DVBCodomain; + + // 重要步骤:定义Circle数据视图框中单位值的含义,单位值:1所代表的长度 + // 用户定义了值域范围 + if (codomain && codomain[1] - codomain[0] > 0) { + this.DVBUnitValue = sets.maxR / (codomain[1] - codomain[0]); + } else { + //this.DVBUnitValue = sets.maxR / maxValue; + this.DVBUnitValue = sets.maxR; + } + + var uv = this.DVBUnitValue; + //圆半径 + var r = fv[0] * uv + sets.minR; + this.width = 2 * r; + this.height = 2 * r; + + // 重要步骤:初始化参数 + if (!this.initBaseParameter()) { + return; + } + + //假如用户设置了值域范围 没有在值域范围直接返回 + if (codomain) { + if (fv[0] < codomain[0] || fv[0] > codomain[1]) { + return; + } + } + + var dvbCenter = this.DVBCenterPoint; // 数据视图框中心作为圆心 + + //圆形对象参数 + var circleSP = new RenderCircle(dvbCenter[0], dvbCenter[1], r); + + //circleSP.sytle 初始化 + circleSP.style = ShapeFactory.ShapeStyleTool(null, sets.circleStyle, null, null, 0); + //图形的填充颜色 + if (typeof (sets.fillColor) !== "undefined") { + //用户自定义 + circleSP.style.fillColor = sets.fillColor; + } else { + //当前默认 + circleSP.style.fillColor = defaultFillColor; + } + //圆形 Hover样式 + circleSP.highlightStyle = ShapeFactory.ShapeStyleTool(null, sets.circleHoverStyle); + //圆形 Hover 与 click 设置 + if (typeof(sets.circleHoverAble) !== "undefined") { + circleSP.hoverable = sets.circleHoverAble; + } + if (typeof(sets.circleClickAble) !== "undefined") { + circleSP.clickable = sets.circleClickAble; + } + + //图形携带的数据信息 + circleSP.refDataID = this.data.id; + circleSP.dataInfo = { + field: this.fields[0], + r: r, + value: fv[0] + }; + + // 创建扇形并把此扇形添加到图表图形数组 + this.shapes.push(this.shapeFactory.createShape(circleSP)); + + // 重要步骤:将图形转为由相对坐标表示的图形,以便在地图平移缩放过程中快速重绘图形 + // (统计专题图模块从结构上要求使用相对坐标,assembleShapes() 函数必须在图形装配完成后调用 shapesConvertToRelativeCoordinate() 函数) + this.shapesConvertToRelativeCoordinate(); + } + +} + +/** + * @typedef {Object} SuperMap.Feature.Theme.Circle.setting + * @property {Array.} codomain - 图表允许展示的数据值域,长度为 2 的一维数组,第一个元素表示值域下限,第二个元素表示值域上限。 + * @property {number} [maxR] - 圆形的最大半径。 + * @property {number} [minR] - 圆形的最小半径。 + * @property {string} [fillColor] - 圆形的填充色,如:fillColor: "#FFB980"。 + * @property {Object} [circleStyle] - 圆形的基础 style,此参数控制圆形基础样式,优先级低于 circleStyleByFields 和 circleStyleByCodomain。 + * @property {number} [decimalNumber] - 数据值数组 dataValues 元素值小数位数,数据的小数位处理参数,取值范围:[0, 16]。如果不设置此参数,在取数据值时不对数据做小数位处理。 + * @property {Object} [circleHoverStyle] - 圆形 hover 状态时的样式,circleHoverAble 为 true 时有效。 + * @property {boolean} [circleHoverAble=true] - 是否允许圆形使用 hover 状态。同时设置 circleHoverAble 和 circleClickAble 为 false,可以直接屏蔽图形对专题图层事件的响应。 + * @property {boolean} [circleClickAble=true] - 是否允许圆形被点击。同时设置 circleHoverAble 和 circleClickAble 为 false,可以直接屏蔽图形对专题图层事件的响应。 + * + */ + +SuperMap.Feature.Theme.Circle = Circle; \ No newline at end of file diff --git a/pool/shard002/JavaScript/0013954_states.spec.js b/pool/shard002/JavaScript/0013954_states.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..d35241e51ca2cdb1674805e1019081131e160827 --- /dev/null +++ b/pool/shard002/JavaScript/0013954_states.spec.js @@ -0,0 +1,60 @@ +(function () { + "use strict"; + + describe("Test rating states", function () { + var testAuthed, testUnAuthed; + + beforeEach(function () { + module("mfl.rating"); + module("mflAppConfig"); + module("templates-app"); + module("mfl.auth.service"); + + inject(["$rootScope", "$state", "api.auth", + function ($rootScope, $state, auth) { + testAuthed = function (name) { + spyOn(auth, "getToken").andReturn({access_token: "DSA"}); + spyOn(auth, "fetchToken"); + $state.go(name); + $rootScope.$digest(); + expect($state.current.name).toEqual(name); + expect(auth.fetchToken).not.toHaveBeenCalled(); + }; + testUnAuthed = function (name) { + spyOn(auth, "getToken").andReturn(null); + spyOn(auth, "fetchToken"); + $state.go(name); + $rootScope.$digest(); + expect($state.current.name).toEqual(name); + expect(auth.fetchToken).toHaveBeenCalled(); + }; + }] + ); + }); + + it("should load rating state (authed)", function () { + testAuthed("rating"); + }); + + it("should load rating state (unauthed)", function () { + testUnAuthed("rating"); + }); + + it("should load rating services state (authed)", function () { + testAuthed("rating.services"); + }); + + it("should load rating services state (unauthed)", function () { + testUnAuthed("rating.services"); + }); + + it("should load rating units state (authed)", function () { + testAuthed("rating.units"); + }); + + it("should load rating units state (unauthed)", function () { + testUnAuthed("rating.units"); + }); + }); + +})(); diff --git a/pool/shard002/JavaScript/0013962_index.spec.js b/pool/shard002/JavaScript/0013962_index.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..95e0e9d8215305c9bc960cc25886491859920cbe --- /dev/null +++ b/pool/shard002/JavaScript/0013962_index.spec.js @@ -0,0 +1,28 @@ +/** Created by hhj on 1/4/16. */ +/* eslint-disable no-unused-expressions, no-unused-vars, import/no-extraneous-dependencies */ +import { expect } from 'chai' +import React from 'react' +import sd from 'skin-deep' +import createStore from '../../../app/createStore' +import Connected from '../index' + +describe('umistovani connected Container component (wrapper)', () => { + let tree + const store = createStore() + + beforeEach(() => { + tree = sd.shallowRender(React.createElement(Connected, { store })) + }) + + it('should connect props to redux', () => { + expect(tree.props.store).to.deep.equal(store) + }) + + it('should connect proper sub state to props', () => { + expect(typeof tree.props.zarizeniResource).to.equal('object') + expect(typeof tree.props.umisteniResource).to.equal('object') + expect(typeof tree.props.akrloksResource).to.equal('object') + }) + +}) + diff --git a/pool/shard002/JavaScript/0013963_test-tls-npn-server-client.js b/pool/shard002/JavaScript/0013963_test-tls-npn-server-client.js new file mode 100644 index 0000000000000000000000000000000000000000..86e10bedc6a5b77f8fc845cbe17cab220b69b84d --- /dev/null +++ b/pool/shard002/JavaScript/0013963_test-tls-npn-server-client.js @@ -0,0 +1,105 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +if (!process.features.tls_npn) { + console.error('Skipping because node compiled without OpenSSL or ' + + 'with old OpenSSL version.'); + process.exit(0); +} + +var common = require('../common'), + assert = require('assert'), + fs = require('fs'), + tls = require('tls'); + +function filenamePEM(n) { + return require('path').join(common.fixturesDir, 'keys', n + '.pem'); +} + +function loadPEM(n) { + return fs.readFileSync(filenamePEM(n)); +} + +var serverOptions = { + key: loadPEM('agent2-key'), + cert: loadPEM('agent2-cert'), + crl: loadPEM('ca2-crl'), + NPNProtocols: ['a', 'b', 'c'] +}; + +var serverPort = common.PORT; + +var clientsOptions = [{ + port: serverPort, + key: serverOptions.key, + cert: serverOptions.cert, + crl: serverOptions.crl, + NPNProtocols: ['a', 'b', 'c'], + rejectUnauthorized: false +},{ + port: serverPort, + key: serverOptions.key, + cert: serverOptions.cert, + crl: serverOptions.crl, + NPNProtocols: ['c', 'b', 'e'], + rejectUnauthorized: false +},{ + port: serverPort, + key: serverOptions.key, + cert: serverOptions.cert, + crl: serverOptions.crl, + NPNProtocols: ['first-priority-unsupported', 'x', 'y'], + rejectUnauthorized: false +}]; + +var serverResults = [], + clientsResults = []; + +var server = tls.createServer(serverOptions, function(c) { + serverResults.push(c.npnProtocol); +}); +server.listen(serverPort, startTest); + +function startTest() { + function connectClient(options, callback) { + var client = tls.connect(options, function() { + clientsResults.push(client.npnProtocol); + client.destroy(); + + callback(); + }); + }; + + connectClient(clientsOptions[0], function() { + connectClient(clientsOptions[1], function() { + connectClient(clientsOptions[2], function() { + server.close(); + }); + }); + }); +} + +process.on('exit', function() { + assert.equal(serverResults[0], clientsResults[0]); + assert.equal(serverResults[1], clientsResults[1]); + assert.equal(serverResults[2], 'first-priority-unsupported'); + assert.equal(clientsResults[2], false); +}); diff --git a/pool/shard002/JavaScript/0013964_media-link.js b/pool/shard002/JavaScript/0013964_media-link.js new file mode 100644 index 0000000000000000000000000000000000000000..b5ef07705a8426c014e7117789f04788daf06316 --- /dev/null +++ b/pool/shard002/JavaScript/0013964_media-link.js @@ -0,0 +1,80 @@ +window.customElements.define('d-media-link', class extends HTMLAnchorElement { + static get observedAttributes() { + return ['active']; + } + + get isYoutube() { + return this.href.indexOf('youtu.be') > -1 + } + + get isCoub() { + return this.href.indexOf('coub.com') > -1 + } + + get YoutubeId() { + return this.href.match(/^https?:\/\/youtu\.be\/([0-9a-zA-Z_\-]+)$/)[1]; + } + + get iframe() { + return this.querySelector('iframe'); + } + + get contentSrc() { + let src = this.href; + [ + [/^https?:\/\/vimeo\.com\/([0-9a-zA-Z_\-]+)$/, '//player.vimeo.com/video/$1?autoplay=1'], + [/^https?:\/\/coub\.com\/view\/([0-9a-zA-Z_\-]+)$/, '//coub.com/embed/$1?autostart=false'], + [/^https?:\/\/rutube\.ru\/video\/([0-9a-zA-Z_\-]+)\/?$/, '//rutube.ru/play/embed/$1?autoStart=true'], + ].forEach(i => src = src.replace(...i)); + + return src; + } + + + activeObserver(newValue) { + if (newValue) { + if (this.isYoutube) { + App.YT((YT) => this.initYoutube(YT)) + } + else { + this.innerHTML = ``; + } + if (this.isCoub) { + this.initCoub() + } + } + else { + this.innerHTML = `` + } + } + + attributeChangedCallback(name, oldValue, newValue) { + if (name === 'active') { + this.activeObserver(newValue); + } + } + + connectedCallback() { + this.addEventListener('click', e => { + e.preventDefault(); + this.setAttribute('active', 'active') + }); + this.activeObserver(); + } + + initYoutube(YT) { + this.innerHTML = '
'; + new YT.Player(this.querySelector('div'), { + videoId: this.YoutubeId, + playerVars: {autoplay: 1} + }); + } + + initCoub() { + setTimeout(() => { + this.iframe.contentWindow.postMessage('play#runner', '*'); + }, 3000) + + } +}, {extends: 'a'}); + diff --git a/pool/shard002/JavaScript/0013966_get-srt-text.js b/pool/shard002/JavaScript/0013966_get-srt-text.js new file mode 100644 index 0000000000000000000000000000000000000000..280ce4911810ec2e9e22f8b4f800461626a59d91 --- /dev/null +++ b/pool/shard002/JavaScript/0013966_get-srt-text.js @@ -0,0 +1,14 @@ +const fs = require('fs') +const parser = require('subtitles-parser') + +const input = process.argv[2] +const output = input.replace('.srt', '.txt') +const srt = fs.readFileSync(input, 'utf8') + +const data = parser.fromSrt(srt) + +const string = data.map(i => i.text).join(' ').replace(/\n/g, ' ').replace(/ {2,}/g, ' ') + +fs.writeFileSync(output, string, 'utf8') + +console.log('written to %s', output) // eslint-disable-line no-console diff --git a/pool/shard002/JavaScript/0013968_agGridNg1.js b/pool/shard002/JavaScript/0013968_agGridNg1.js new file mode 100644 index 0000000000000000000000000000000000000000..d78a72e06dc84f57c0140cde24a07deeadaa340e --- /dev/null +++ b/pool/shard002/JavaScript/0013968_agGridNg1.js @@ -0,0 +1,41 @@ +/** + * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components + * @version v14.1.1 + * @link http://www.ag-grid.com/ + * @license MIT + */ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var grid_1 = require("../grid"); +function initialiseAgGridWithAngular1(angular) { + var angularModule = angular.module("agGrid", []); + angularModule.directive("agGrid", function () { + return { + restrict: "A", + controller: ['$element', '$scope', '$compile', '$attrs', AngularDirectiveController], + scope: true + }; + }); +} +exports.initialiseAgGridWithAngular1 = initialiseAgGridWithAngular1; +function AngularDirectiveController($element, $scope, $compile, $attrs) { + var gridOptions; + var quickFilterOnScope; + var keyOfGridInScope = $attrs.agGrid; + quickFilterOnScope = keyOfGridInScope + '.quickFilterText'; + gridOptions = $scope.$eval(keyOfGridInScope); + if (!gridOptions) { + console.warn("WARNING - grid options for ag-Grid not found. Please ensure the attribute ag-grid points to a valid object on the scope"); + return; + } + var eGridDiv = $element[0]; + var gridParams = { + $scope: $scope, + $compile: $compile, + quickFilterOnScope: quickFilterOnScope + }; + var grid = new grid_1.Grid(eGridDiv, gridOptions, gridParams); + $scope.$on("$destroy", function () { + grid.destroy(); + }); +} diff --git a/pool/shard002/JavaScript/0013969_view_instrumentation_test.js b/pool/shard002/JavaScript/0013969_view_instrumentation_test.js new file mode 100644 index 0000000000000000000000000000000000000000..ba3cd866c5a469b96d434a72b11092521b89badd --- /dev/null +++ b/pool/shard002/JavaScript/0013969_view_instrumentation_test.js @@ -0,0 +1,69 @@ +import { + run, + instrumentationSubscribe as subscribe, + instrumentationReset as reset +} from 'ember-metal'; +import { jQuery as $ } from 'ember-views'; +import { Application } from 'ember-application'; +import { compile } from 'ember-template-compiler'; +import { setTemplates, setTemplate } from 'ember-glimmer'; + +let App, $fixture; + +function setupExample() { + // setup templates + setTemplate('application', compile('{{outlet}}')); + setTemplate('index', compile('

Index

')); + setTemplate('posts', compile('

Posts

')); + + App.Router.map(function() { + this.route('posts'); + }); +} + +function handleURL(path) { + let router = App.__container__.lookup('router:main'); + return run(router, 'handleURL', path); +} + +QUnit.module('View Instrumentation', { + setup() { + run(() => { + App = Application.create({ + rootElement: '#qunit-fixture' + }); + App.deferReadiness(); + + App.Router.reopen({ + location: 'none' + }); + }); + + $fixture = $('#qunit-fixture'); + setupExample(); + }, + + teardown() { + reset(); + run(App, 'destroy'); + App = null; + setTemplates({}); + } +}); + +QUnit.test('Nodes without view instances are instrumented', function(assert) { + let called = false; + subscribe('render', { + before() { + called = true; + }, + after() {} + }); + run(App, 'advanceReadiness'); + assert.equal($fixture.text(), 'Index', 'It rendered the right template'); + assert.ok(called, 'Instrumentation called on first render'); + called = false; + handleURL('/posts'); + assert.equal($fixture.text(), 'Posts', 'It rendered the right template'); + assert.ok(called, 'instrumentation called on transition to non-view backed route'); +}); diff --git a/pool/shard002/JavaScript/0013970_multi-select.js b/pool/shard002/JavaScript/0013970_multi-select.js new file mode 100644 index 0000000000000000000000000000000000000000..9d8906dd5acadcd3643a52487bb85544ac925c82 --- /dev/null +++ b/pool/shard002/JavaScript/0013970_multi-select.js @@ -0,0 +1,30 @@ +"use strict" +import React from "react" + +export default class InstantSearch extends React.Component { + constructor(props) { + super(props) + this.handleSearchOnKeyUp = this.handleSearchOnKeyUp.bind(this) + this.searchTimer = null + } + + handleSearchOnKeyUp(event){ + let selectedValue = event.target.value.trim() + + } + + render (){ + return
+ + + + + + + + + + +
+ } +} diff --git a/pool/shard002/JavaScript/0013979_monitor.js b/pool/shard002/JavaScript/0013979_monitor.js new file mode 100644 index 0000000000000000000000000000000000000000..70cd64bf5c6cc73fe8d8f7c6eb0e6685f83ec0eb --- /dev/null +++ b/pool/shard002/JavaScript/0013979_monitor.js @@ -0,0 +1,21 @@ +import { Meteor } from 'meteor/meteor'; +import { InstanceStatus } from 'meteor/konecty:multiple-instances-status'; + +import { SAUMonitorClass } from '../lib/SAUMonitor'; +import { settings } from '../../../settings/server'; + +const SAUMonitor = new SAUMonitorClass(); + +Meteor.startup(() => { + let TroubleshootDisableSessionsMonitor; + settings.get('Troubleshoot_Disable_Sessions_Monitor', (key, value) => { + if (TroubleshootDisableSessionsMonitor === value) { return; } + TroubleshootDisableSessionsMonitor = value; + + if (value) { + return SAUMonitor.stop(); + } + + SAUMonitor.start(InstanceStatus.id()); + }); +}); diff --git a/pool/shard002/JavaScript/0013982_response.js b/pool/shard002/JavaScript/0013982_response.js new file mode 100644 index 0000000000000000000000000000000000000000..b05471dcfd6b8814deafd467681f09a8447a80d0 --- /dev/null +++ b/pool/shard002/JavaScript/0013982_response.js @@ -0,0 +1,57 @@ +import Render from './render.js'; +import Axa from 'axa'; + +function Response (data) { + this.query = data.query; + this.route = data.route; +} + +Response.prototype.send = function (content, callback) { + var self = this; + + Render({ + type: 'html', + query: self.query, + title: self.route.title, + content: content + }); + + if (callback) return callback(); +}; + +Response.prototype.file = function (path, callback) { + var self = this; + + Axa.request({ + action: path, + responseType: 'html', + success: function (xhr) { + Render({ + type: 'html', + query: self.query, + title: self.route.title, + content: xhr.response + }); + + if (callback) return callback(); + }, + error: function (xhr) { + Render({ + type: 'text', + query: self.query, + title: self.route.title, + content: xhr.response + }); + + if (callback) return callback(); + } + }); +}; + +Response.prototype.redirect = function (path) { + window.location = path; +}; + +export default function (data) { + return new Response(data); +} diff --git a/pool/shard002/JavaScript/0013983_server.js b/pool/shard002/JavaScript/0013983_server.js new file mode 100644 index 0000000000000000000000000000000000000000..e9579bf98a8ce5368cf39e705221ef5798b06f05 --- /dev/null +++ b/pool/shard002/JavaScript/0013983_server.js @@ -0,0 +1,93 @@ +// REQUIRES +var express = require('express'); +var app = express(); +var bodyParser = require("body-parser"); +var fs = require('fs'); +var path = require('path'); +var passport = require('passport'); + +// OWN REQUIRES +var Auth = require('./helpers/auth'); + +// USE +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded()); +app.use('/public', express.static(path.join(__dirname, 'public'))) + +app.all('/*', function(req, res, next) { + // CORS headers + res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain + res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); + // Set custom headers for CORS + res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key'); + if (req.method == 'OPTIONS') { + res.status(200).end(); + } else { + next(); + } +}); + +// MONGOOSE SETUP +var mongoose = require('mongoose'); +mongoose.Promise = global.Promise; +mongoose.connect("mongodb://pushakib:pushakib@ds029197.mlab.com:29197/sendat"); +mongoose.connection.once("open", function() { + console.log('Mongoose Connected!'); +}) + +// PASSPORT SETUP +var cookieparser = require('cookie-parser')(); +var bodyparser = require('body-parser').urlencoded({ extended: true }); +var expresssession = require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }); +app.use(expresssession); // has to be above passport.intialize() and passport.session() +app.use(passport.initialize()); +app.use(passport.session()); +require('./config/passport')(passport); // pass passport for configuration + +// Authentication Required +// app.all('/api/*', Auth.isAuthenticated); // TODO: UNCOMMENT + +// ROUTING +app.use('/api', require('./routes')); +app.use('/courses', require('./routes/courses')); + +// BASE ROUTES +app.get('/' , Auth.isLoggedIn, function(req , res){ + // Going to index.html in public directory + console.log(req.user); + fs.readFile('./views/index.html', function(err, html){ + if (err){ + throw err; + } + res.writeHead(200, {'Content-Type' : 'text/html'}); + res.end(html); + }); +}); +app.get('/login', Auth.isNotLoggedIn, function(req , res){ + // Going to index.html in public directory + fs.readFile('./views/login.html', function(err, html){ + if (err){ + throw err; + } + res.writeHead(200, {'Content-Type' : 'text/html'}); + res.end(html); + }); +}); +app.get('/logout', function(req, res) { + req.logout(); + res.redirect('/'); +}); + +// FACEBOOK ROUTES +app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' })); +app.get('/auth/facebook/callback', + passport.authenticate('facebook', { + successRedirect : '/', + failureRedirect : '/login' +})); + +// SERVER SETUP +var PORT = 3000 +app.listen(PORT, function(){ + console.log("Server listening on: http://localhost:%s", PORT); +}); diff --git a/pool/shard002/JavaScript/0013985_auto-destroy.js b/pool/shard002/JavaScript/0013985_auto-destroy.js new file mode 100644 index 0000000000000000000000000000000000000000..7a904f332e888b818c7de2bfb5900ace6ef77d7d --- /dev/null +++ b/pool/shard002/JavaScript/0013985_auto-destroy.js @@ -0,0 +1,26 @@ +/* */ +var test = require("tape"); +var through = require("../index"); +test('end before close', function(assert) { + var ts = through(); + ts.autoDestroy = false; + var ended = false, + closed = false; + ts.on('end', function() { + assert.ok(!closed); + ended = true; + }); + ts.on('close', function() { + assert.ok(ended); + closed = true; + }); + ts.write(1); + ts.write(2); + ts.write(3); + ts.end(); + assert.ok(ended); + assert.notOk(closed); + ts.destroy(); + assert.ok(closed); + assert.end(); +}); diff --git a/pool/shard002/JavaScript/0013987_EnterLeaveEventPlugin.js b/pool/shard002/JavaScript/0013987_EnterLeaveEventPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..dcc9bd68e04a5cedb8e72a30dfced855e8ab2453 --- /dev/null +++ b/pool/shard002/JavaScript/0013987_EnterLeaveEventPlugin.js @@ -0,0 +1,138 @@ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @providesModule EnterLeaveEventPlugin + * @typechecks static-only + */ + +'use strict'; + +var EventConstants = require('EventConstants'); +var EventPropagators = require('EventPropagators'); +var SyntheticMouseEvent = require('SyntheticMouseEvent'); + +var ReactMount = require('ReactMount'); +var keyOf = require('keyOf'); + +var topLevelTypes = EventConstants.topLevelTypes; +var getFirstReactDOM = ReactMount.getFirstReactDOM; + +var eventTypes = { + mouseEnter: { + registrationName: keyOf({onMouseEnter: null}), + dependencies: [ + topLevelTypes.topMouseOut, + topLevelTypes.topMouseOver, + ], + }, + mouseLeave: { + registrationName: keyOf({onMouseLeave: null}), + dependencies: [ + topLevelTypes.topMouseOut, + topLevelTypes.topMouseOver, + ], + }, +}; + +var extractedEvents = [null, null]; + +var EnterLeaveEventPlugin = { + + eventTypes: eventTypes, + + /** + * For almost every interaction we care about, there will be both a top-level + * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that + * we do not extract duplicate events. However, moving the mouse into the + * browser from outside will not fire a `mouseout` event. In this case, we use + * the `mouseover` top-level event. + * + * @param {string} topLevelType Record from `EventConstants`. + * @param {DOMEventTarget} topLevelTarget The listening component root node. + * @param {string} topLevelTargetID ID of `topLevelTarget`. + * @param {object} nativeEvent Native browser event. + * @return {*} An accumulation of synthetic events. + * @see {EventPluginHub.extractEvents} + */ + extractEvents: function( + topLevelType, + topLevelTarget, + topLevelTargetID, + nativeEvent) { + if (topLevelType === topLevelTypes.topMouseOver && + (nativeEvent.relatedTarget || nativeEvent.fromElement)) { + return null; + } + if (topLevelType !== topLevelTypes.topMouseOut && + topLevelType !== topLevelTypes.topMouseOver) { + // Must not be a mouse in or mouse out - ignoring. + return null; + } + + var win; + if (topLevelTarget.window === topLevelTarget) { + // `topLevelTarget` is probably a window object. + win = topLevelTarget; + } else { + // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. + var doc = topLevelTarget.ownerDocument; + if (doc) { + win = doc.defaultView || doc.parentWindow; + } else { + win = window; + } + } + + var from, to; + if (topLevelType === topLevelTypes.topMouseOut) { + from = topLevelTarget; + to = + getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement) || + win; + } else { + from = win; + to = topLevelTarget; + } + + if (from === to) { + // Nothing pertains to our managed components. + return null; + } + + var fromID = from ? ReactMount.getID(from) : ''; + var toID = to ? ReactMount.getID(to) : ''; + + var leave = SyntheticMouseEvent.getPooled( + eventTypes.mouseLeave, + fromID, + nativeEvent + ); + leave.type = 'mouseleave'; + leave.target = from; + leave.relatedTarget = to; + + var enter = SyntheticMouseEvent.getPooled( + eventTypes.mouseEnter, + toID, + nativeEvent + ); + enter.type = 'mouseenter'; + enter.target = to; + enter.relatedTarget = from; + + EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID); + + extractedEvents[0] = leave; + extractedEvents[1] = enter; + + return extractedEvents; + }, + +}; + +module.exports = EnterLeaveEventPlugin; diff --git a/pool/shard002/JavaScript/0013990_Proclass.js b/pool/shard002/JavaScript/0013990_Proclass.js new file mode 100644 index 0000000000000000000000000000000000000000..c3740b1313024642ffacc653e912b25162dbd1f5 --- /dev/null +++ b/pool/shard002/JavaScript/0013990_Proclass.js @@ -0,0 +1,167 @@ +"use strict"; + +// Empty constructor (overwritten in `extend()`) +var Proclass = function() { }; + +// Make it possible to extend the class +// Save function (as `Extend`) to inject protected variables later +Proclass.extend = function Extend(_self, _parent) { + + // If `_parent` doesn't exist, define it (to avoid errors later) + if (typeof _parent === "undefined") { + _parent = {}; + } + + // Create base prototype for new class + var prototype = function() {}; + + // Helper function to bind a function to a particular scope + // Optionally bind parent functions to `this._parent()` + var attach = function(scope, fnc, providedParents) { + return function() { + + // Transfer all but last item from `providedParents` to `parents` + // Must duplicate the array manually in order to keep the scope for + // multiple calls to this._parent() + var parents = []; + if (providedParents) { + providedParents.forEach(function(value) { + parents.push(value); + }); + } + + // Create temp object to store previous values for protected variables + var temp = {}; + + // If parent function exists, bind temporarily + if (parents && parents.length) { + var parent = parents.pop(); + temp._parent = scope._parent; + scope._parent = attach(scope, parent, parents); + } + + // Bind actual function with the newly created scope + var appliedFunction = fnc.apply(scope, arguments); + + // Set `scope._parent` to saved `temp._parent` + if (parent) { + scope._parent = temp._parent; + } + + // Return applied function + return appliedFunction; + }; + }; + + // Loop through `_parent` and add to saved prototype + for (var name in _parent) { + if (name === "_parents") { + continue; + } + prototype[name] = _parent[name]; + } + + // Add each parent to the prototype manually to avoid scope issues + prototype._parents = {}; + if (_parent._parents) { + for (var name in _parent._parents) { + _parent._parents[name].forEach(function(value) { + if (!prototype._parents[name]) { + prototype._parents[name] = []; + } + prototype._parents[name].push(value); + }); + } + } + + // Loop through `_self` and add to saved prototype + for (var name in _self) { + + // If overwriting a function with a function, add parent function to + // prototype._parents array + if (typeof _self[name] === "function" && typeof _parent[name] === "function") { + if (!prototype._parents[name]) { + prototype._parents[name] = []; + } + prototype._parents[name].push(_parent[name]); + } + + // Add function to prototype + prototype[name] = _self[name]; + } + + // Create constructor + function Proclass() { + + // Store protected variables + var internalScope = {}; + + // Copy prototype onto `this` + for (var name in prototype) { + + // Skip `_parents` + if (name === "_parents") { + continue; + } + + // If variable begins with `_`, consider it protected + var isProtected = false; + if (/^_/.test(name)) { + isProtected = true; + } + + // If a function, attach to internalScope (with parents, if any) + // If an object or array, clone it + // Else, simply use the value + if (typeof prototype[name] === "function") { + var parents = []; + if (name !== "constructor") { + parents = prototype._parents[name]; + } + var toCall = attach(internalScope, prototype[name], parents); + } else if (prototype[name] === Object(prototype[name])) { + var toCall = JSON.parse(JSON.stringify(prototype[name])); + } else { + var toCall = prototype[name]; + } + + // If protected, set to `undefined` + // Else, add to `this` (public scope) + if (isProtected) { + this[name] = undefined; + } else { + this[name] = toCall; + } + + // Always add to internalScope + internalScope[name] = toCall; + + } + + // Run constructor function (`_init()`) + if (internalScope._init) { + internalScope._init.apply(this, arguments); + } + + // Prevent new properties from being added + Object.preventExtensions(this); + } + + // Make sure the correct prototype gets passed to children + Proclass.extend = (function(fnc, prototype){ + return function() { + return fnc.call(this, arguments[0], prototype); + }; + })(Extend, prototype); + + // Save prototype + Proclass.prototype = prototype; + + // Save constructor + Proclass.prototype.constructor = Proclass; + + return Proclass; +}; + +// Export Proclass +module.exports = Proclass; diff --git a/pool/shard002/JavaScript/0013991_tsv.js b/pool/shard002/JavaScript/0013991_tsv.js new file mode 100644 index 0000000000000000000000000000000000000000..a8ad1009757be23d750d8c65eb9704a1d46fa8be --- /dev/null +++ b/pool/shard002/JavaScript/0013991_tsv.js @@ -0,0 +1,61 @@ +var addMedia = require("../media").addMedia; +var Result = require("../result"); + + +function getProperties(items){ + var props = {}; + items.forEach(function(item){ + Object.keys(item).forEach(function(prop){ + props[prop]=true; + }); + }); + return Object.keys(props).sort(); +} + +var toColumn = function(obj){ + var out; + if (typeof obj == "undefined") { + out = ""; + }else if (obj instanceof Array){ + out = obj.map(toColumn).join(","); + }else if (typeof obj == "object") { + out = JSON.stringify(obj); + }else{ + out = obj; + } + return out; +} + +addMedia({ + "content-type": "application/tsv", + serialize: function(results,options){ + if (results instanceof Result){ + results = results.getData(); + } + + if (!results){ + results="" + } + + if (results instanceof Array){ + var out = []; + var props = getProperties(results); + out.push(props.join("\t")); + results.forEach(function(item){ + var row = [] + props.forEach(function(prop){ + row.push(toColumn(item[prop])); + }); + out.push(row.join("\t")); + }); + + return out.join("\n"); + }else{ + throw Error("Serialization to TSV must be an array"); + } + + + } +}) + + diff --git a/pool/shard002/JavaScript/0013992_15.4.4.22-9-c-ii-7.js b/pool/shard002/JavaScript/0013992_15.4.4.22-9-c-ii-7.js new file mode 100644 index 0000000000000000000000000000000000000000..f4d88297edcdb73e731bd30c301a55ee97aeaa07 --- /dev/null +++ b/pool/shard002/JavaScript/0013992_15.4.4.22-9-c-ii-7.js @@ -0,0 +1,28 @@ +// Copyright (c) 2012 Ecma International. All rights reserved. +// This code is governed by the BSD license found in the LICENSE file. + +/*--- +es5id: 15.4.4.22-9-c-ii-7 +description: > + Array.prototype.reduceRight - unhandled exceptions happened in + callbackfn terminate iteration +---*/ + + var accessed = false; + + function callbackfn(prevVal, curVal, idx, obj) { + if (idx < 10) { + accessed = true; + } + if (idx === 10) { + throw new Test262Error("Exception occurred in callbackfn"); + } + } + + var obj = { 0: 11, 4: 10, 10: 8, length: 20 }; + +assert.throws(Test262Error, function() { + Array.prototype.reduceRight.call(obj, callbackfn, 1); +}); + +assert.sameValue(accessed, false, 'accessed'); diff --git a/pool/shard002/JavaScript/0013993_jquery.glob.mk.js b/pool/shard002/JavaScript/0013993_jquery.glob.mk.js new file mode 100644 index 0000000000000000000000000000000000000000..4511cbd954af88abddd3a35bf3325383dee8b5e5 --- /dev/null +++ b/pool/shard002/JavaScript/0013993_jquery.glob.mk.js @@ -0,0 +1,53 @@ +(function($) { + var cultures = $.global.cultures, + en = cultures.en, + standard = en.calendars.standard, + culture = cultures["mk"] = $.extend(true, {}, en, { + name: "mk", + englishName: "Macedonian (FYROM)", + nativeName: "македонски јазик", + language: "mk", + numberFormat: { + ',': ".", + '.': ",", + percent: { + ',': ".", + '.': "," + }, + currency: { + pattern: ["-n $","n $"], + ',': ".", + '.': ",", + symbol: "ден." + } + }, + calendars: { + standard: $.extend(true, {}, standard, { + '/': ".", + firstDay: 1, + days: { + names: ["недела","понеделник","вторник","среда","четврток","петок","сабота"], + namesAbbr: ["нед","пон","втр","срд","чет","пет","саб"], + namesShort: ["не","по","вт","ср","че","пе","са"] + }, + months: { + names: ["јануари","февруари","март","април","мај","јуни","јули","август","септември","октомври","ноември","декември",""], + namesAbbr: ["јан","фев","мар","апр","мај","јун","јул","авг","сеп","окт","ное","дек",""] + }, + AM: null, + PM: null, + patterns: { + d: "dd.MM.yyyy", + D: "dddd, dd MMMM yyyy", + t: "HH:mm", + T: "HH:mm:ss", + f: "dddd, dd MMMM yyyy HH:mm", + F: "dddd, dd MMMM yyyy HH:mm:ss", + M: "dd MMMM", + Y: "MMMM yyyy" + } + }) + } + }, cultures["mk"]); + culture.calendar = culture.calendars.standard; +})(jQuery); \ No newline at end of file diff --git a/pool/shard002/JavaScript/0013996_touchevent.js b/pool/shard002/JavaScript/0013996_touchevent.js new file mode 100644 index 0000000000000000000000000000000000000000..d825389a3c1b4c29961b4d01ca1f78e1e6f425f0 --- /dev/null +++ b/pool/shard002/JavaScript/0013996_touchevent.js @@ -0,0 +1,15 @@ +// Copyright (c) 2012 Turbulenz Limited +var WebGLTouchEvent = (function () { + function WebGLTouchEvent() { + } + WebGLTouchEvent.create = function (params) { + var touchEvent = new WebGLTouchEvent(); + + touchEvent.changedTouches = params.changedTouches; + touchEvent.gameTouches = params.gameTouches; + touchEvent.touches = params.touches; + + return touchEvent; + }; + return WebGLTouchEvent; +})(); diff --git a/pool/shard002/JavaScript/0013997_life.js b/pool/shard002/JavaScript/0013997_life.js new file mode 100644 index 0000000000000000000000000000000000000000..5391930a571c5250a9c4b0a43fb52f104aa206fb --- /dev/null +++ b/pool/shard002/JavaScript/0013997_life.js @@ -0,0 +1,43 @@ +import config from '../config' +import { instanceMap } from './map' + +export function init (cfg) { + config.Document = cfg.Document + config.Element = cfg.Element + config.Comment = cfg.Comment + config.sendTasks = cfg.sendTasks + config.Listener = cfg.Listener +} + +/** + * refresh a Weex instance + * + * @param {string} instanceId + * @param {object} data + */ +export function refreshInstance (instanceId, data) { + const instance = instanceMap[instanceId] + let result + if (instance) { + result = instance.refreshData(data) + } + else { + result = new Error(`invalid instance id "${instanceId}"`) + } + return result +} + +/** + * destroy a Weex instance + * @param {string} instanceId + */ +export function destroyInstance (instanceId) { + const instance = instanceMap[instanceId] + if (!instance) { + return new Error(`invalid instance id "${instanceId}"`) + } + + instance.destroy() + delete instanceMap[instanceId] + return instanceMap +} diff --git a/pool/shard002/JavaScript/0014001_securitygroup.js b/pool/shard002/JavaScript/0014001_securitygroup.js new file mode 100644 index 0000000000000000000000000000000000000000..6d40ac86398e425c5422ec8342259082b6194c7d --- /dev/null +++ b/pool/shard002/JavaScript/0014001_securitygroup.js @@ -0,0 +1,66 @@ +/* -------------------------------------------------------------------------- */ +/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems */ +/* */ +/* 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. */ +/* -------------------------------------------------------------------------- */ + +define(function(require) { + var OpenNebulaAction = require('./action'); + + var RESOURCE = "SECURITY_GROUP"; + + var SecurityGroup = { + "resource" : "SECURITY_GROUP", + + "create" : function(params) { + OpenNebulaAction.create(params, RESOURCE); + }, + "del" : function(params) { + OpenNebulaAction.del(params, RESOURCE); + }, + "list" : function(params) { + OpenNebulaAction.list(params, RESOURCE); + }, + "show" : function(params) { + OpenNebulaAction.show(params, RESOURCE); + }, + "chown" : function(params) { + OpenNebulaAction.chown(params, RESOURCE); + }, + "chgrp" : function(params) { + OpenNebulaAction.chgrp(params, RESOURCE); + }, + "chmod" : function(params) { + var action_obj = params.data.extra_param; + OpenNebulaAction.simple_action(params, RESOURCE, "chmod", action_obj); + }, + "update": function(params) { + var action_obj = {"template_raw" : params.data.extra_param}; + OpenNebulaAction.simple_action(params, RESOURCE, "update", action_obj); + }, + "clone" : function(params) { + var name = params.data.extra_param ? params.data.extra_param : ""; + var action_obj = {"name" : name}; + OpenNebulaAction.simple_action(params, RESOURCE, "clone", action_obj); + }, + "rename" : function(params) { + var action_obj = params.data.extra_param; + OpenNebulaAction.simple_action(params, RESOURCE, "rename", action_obj); + }, + "getName": function(id){ + return OpenNebulaAction.getName(id, RESOURCE); + } + } + + return SecurityGroup; +}) diff --git a/pool/shard002/JavaScript/0014005_collections.js b/pool/shard002/JavaScript/0014005_collections.js new file mode 100644 index 0000000000000000000000000000000000000000..b22d74a7dcd49f0a7e690516defa1e45f270cf18 --- /dev/null +++ b/pool/shard002/JavaScript/0014005_collections.js @@ -0,0 +1,32 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _pure = require('recompose/pure'); + +var _pure2 = _interopRequireDefault(_pure); + +var _SvgIcon = require('../../SvgIcon'); + +var _SvgIcon2 = _interopRequireDefault(_SvgIcon); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ImageCollections = function ImageCollections(props) { + return _react2.default.createElement( + _SvgIcon2.default, + props, + _react2.default.createElement('path', { d: 'M22 16V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2zm-11-4l2.03 2.71L16 11l4 5H8l3-4zM2 6v14c0 1.1.9 2 2 2h14v-2H4V6H2z' }) + ); +}; +ImageCollections = (0, _pure2.default)(ImageCollections); +ImageCollections.displayName = 'ImageCollections'; +ImageCollections.muiName = 'SvgIcon'; + +exports.default = ImageCollections; \ No newline at end of file diff --git a/pool/shard002/JavaScript/0014015_app.js b/pool/shard002/JavaScript/0014015_app.js new file mode 100644 index 0000000000000000000000000000000000000000..2617358027f4e6c6105593c6ac831765c9816e2b --- /dev/null +++ b/pool/shard002/JavaScript/0014015_app.js @@ -0,0 +1,80 @@ +var express = require('express'); +var http = require('http'); +var socketio = require('socket.io'); +var path = require('path'); +var favicon = require('serve-favicon'); +var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var bodyParser = require('body-parser'); + +var mongoose = require('mongoose'); +mongoose.connect('mongodb://localhost/scrumboard', function(err) { + if(err) { + console.log('connection error', err); + } else { + console.log('connection successful'); + } +}); + +var routes = require('./routes/index'); +var database = require('./routes/data'); + +var app = express(); + +var node_modules = require('express-node_modules'); +app.use(node_modules('/lib', require)); + +var server = http.createServer(app); +var io = socketio.listen(server); +app.set('socketio', io); +app.set('server', server); +app.get('server').listen(3001); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'ejs'); + +// uncomment after placing your favicon in /public +//app.use(favicon(__dirname + '/public/favicon.ico')); +app.use(logger('dev')); +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ extended: false })); +app.use(cookieParser()); +app.use(express.static(path.join(__dirname, 'public'))); + +app.use('/', routes); +app.use('/data', database); + +// catch 404 and forward to error handler +app.use(function(req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); +}); + +// error handlers + +// development error handler +// will print stacktrace +if (app.get('env') === 'development') { + app.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: err + }); + }); +} + +// production error handler +// no stacktraces leaked to user +app.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: {} + }); +}); + + +module.exports = app; diff --git a/pool/shard002/JavaScript/0014018_setup.js b/pool/shard002/JavaScript/0014018_setup.js new file mode 100644 index 0000000000000000000000000000000000000000..f6898af06153ced0ea77c62fdf984d9a60789537 --- /dev/null +++ b/pool/shard002/JavaScript/0014018_setup.js @@ -0,0 +1,104 @@ +module.exports = function(app, security) { + var async = require('async') + , Role = require('../models/role') + , User = require('../models/user') + , Device = require('../models/device') + , userTransformer = require('../transformers/user'); + + var passwordLength = null; + Object.keys(security.authentication.strategies).forEach(function(name) { + if (security.authentication.strategies[name].passwordMinLength) { + passwordLength = security.authentication.strategies[name].passwordMinLength; + } + }); + + function authorizeSetup(req, res, next) { + User.count(function(err, count) { + if (err) next(err); + + if (count > 0) { + return res.sendStatus(404); + } + + next(); + }); + } + + function validateSetup(req, res, next) { + var username = req.param('username'); + if (!username) { + return res.status(400).send('username is required'); + } + + var password = req.param('password'); + if (!password) { + return res.status(400).send('password is required'); + } + + var passwordconfirm = req.param('passwordconfirm'); + if (!passwordconfirm) { + return res.status(400).send('passwordconfirm is required'); + } + + if (password !== passwordconfirm) { + return res.status(400).send('passwords do not match'); + } + + if (password.length < passwordLength) { + return res.status(400).send('password does not meet minimum length requirment of ' + passwordLength + ' characters'); + } + + var uid = req.param('uid'); + if (!uid) { + return res.send(400).send('passwordconfirm is required'); + } + + req.user = { + username: username, + displayName: username, + active: true, + authentication: { + type: 'local', + password: password + } + }; + + req.device = { + uid: uid, + registered: true + }; + + next(); + } + + app.post( + '/api/setup', + authorizeSetup, + validateSetup, + function (req, res, next) { + async.waterfall([ + function(done) { + Role.getRole('ADMIN_ROLE', function(err, role) { + done(err, role); + }); + }, + function(role, done) { + req.user.roleId = role._id; + User.createUser(req.user, function(err, user) { + done(err, user); + }); + }, + function(user, done) { + Device.createDevice(req.device, function(err, device) { + done(err, user, device); + }); + } + ], function(err, user, device) { + if (err) return next(err); + + res.json({user: userTransformer.transform(user, {path: req.getRoot()}), device: device}); + }); + } + ); + +}; diff --git a/pool/shard002/JavaScript/0014019_set.setCache.spec.js b/pool/shard002/JavaScript/0014019_set.setCache.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..3da1208afb2448618bc3361b9071a2650fd771fd --- /dev/null +++ b/pool/shard002/JavaScript/0014019_set.setCache.spec.js @@ -0,0 +1,143 @@ +var falcor = require("./../../../lib/"); +var Model = falcor.Model; +var Rx = require('rx'); +var Cache = require('../../data/Cache'); +var LocalDataSource = require('../../data/LocalDataSource'); +var clean = require('../../cleanData').stripDerefAndVersionKeys; +var $ref = Model.ref; + +describe('Set Cache', function() { + it("should be fine when you set an empty cache", function(done) { + var model = new Model({source: new LocalDataSource({ + a: { b: $ref("a"), + c: "foo" } + })}); + model.setCache({}); + model.get("a.b.c").subscribe(function(x) { + expect(clean(x)).toEqual({ + json: { a: { b: { c: "foo" } }} + }); + }, done, done); + }); + it("should be fine when you set an undefined cache", function(done) { + var model = new Model({source: new LocalDataSource({ + a: { b: $ref("a"), + c: "foo" } + })}); + model.setCache(undefined); + model.get("a.b.c").subscribe(function(x) { + expect(clean(x)).toEqual({ + json: { a: { b: { c: "foo" } }} + }); + }, done, done); + }); + it("should be fine when you set an empty cache with a pre-existing cache", function(done) { + var model = new Model({ + cache: { a: { + b: $ref("a"), + c: "foo" } }, + source: new LocalDataSource({ + a: { b: $ref("a"), + c: "foo" } + })}); + model.setCache({}); + model.get("a.b.c").subscribe(function(x) { + expect(clean(x)).toEqual({ + json: { a: { b: { c: "foo" } }} + }); + }, done, done); + }); + it("should be fine when you set an undefined cache with a pre-existing cache", function(done) { + var model = new Model({ + cache: { a: { + b: $ref("a"), + c: "foo" } }, + source: new LocalDataSource({ + a: { b: $ref("a"), + c: "foo" } + })}); + model.setCache(undefined); + model.get("a.b.c").subscribe(function(x) { + expect(clean(x)).toEqual({ + json: { a: { b: { c: "foo" } }} + }); + }, done, done); + }); + it("should be fine when you set a new cache", function(done) { + var model = new Model({ + cache: { a: { + b: $ref("a"), + c: "foo" } }, + source: new LocalDataSource({ + a: { b: $ref("d") }, + d: { c: "foo" } + })}); + model.setCache({ + a: { b: $ref("d") }, + d: { c: "foo" } + }); + model.get("a.b.c").subscribe(function(x) { + expect(clean(x)).toEqual({ + json: { a: { b: { c: "foo" } }} + }); + }, done, done); + }); + it("should be fine when you hydrate from an existing cache", function(done) { + var model = new Model({ + cache: { + a: { + b: $ref("a"), + c: "foo" + } + }, + source: new LocalDataSource({ + a: { + b: $ref("d") + }, + d: { + c: "foo" + } + })}); + + var cache = model.getCache(); + model.setCache({}); + + model.get("a.b.c").subscribe(function(x) { + expect(clean(x)).toEqual({ + json: { a: { b: { c: "foo" } }} + }); + }); + + model.setCache(cache); + model.get("a.b.c").subscribe(function(x) { + expect(clean(x)).toEqual({ + json: { a: { b: { c: "foo" } }} + }); + }, done, done); + }); + + it("should re-establish atoms and references when you hydrate from an existing cache into a completely new model instance", function(done) { + var modelOrig = new Model({ + cache: { + a: { + b: $ref("d") + }, + d: { + c: "foo" + } + } + }); + + var cache = modelOrig.getCache(); + var modelNew = new Model(); + + modelNew.setCache(cache); + modelNew.get("a.b.c").subscribe(function(x) { + + expect(clean(x)).toEqual({ + json: { a: { b: { c: "foo" } }} + }); + }, done, done); + + }); +}); diff --git a/pool/shard002/JavaScript/0014023_password-reset-test.js b/pool/shard002/JavaScript/0014023_password-reset-test.js new file mode 100644 index 0000000000000000000000000000000000000000..f3a17e9964c08f49f533a6d60f75bab3a9d16e66 --- /dev/null +++ b/pool/shard002/JavaScript/0014023_password-reset-test.js @@ -0,0 +1,21 @@ +import { expect } from 'chai'; +import { describe, it } from 'mocha'; +import { setupTest } from 'ember-mocha'; + +describe('Unit | Route | password reset', function() { + setupTest('route:password-reset-demand', { + // Specify the other units that are required for this test. + needs: ['service:current-routed-modal'] + }); + + let route; + + beforeEach(function() { + route = this.subject(); + }); + + it('exists', function() { + expect(route).to.be.ok; + }); + +}); diff --git a/pool/shard002/JavaScript/0014024_test.js b/pool/shard002/JavaScript/0014024_test.js new file mode 100644 index 0000000000000000000000000000000000000000..e0eacd61f815a7eba5e8b31451a8c3f1a0673d31 --- /dev/null +++ b/pool/shard002/JavaScript/0014024_test.js @@ -0,0 +1,19 @@ +// For authoring Nightwatch tests, see +// http://nightwatchjs.org/guide#usage + +module.exports = { + 'default e2e tests': function (browser) { + // automatically uses dev Server port from /config.index.js + // default: http://localhost:8080 + // see nightwatch.conf.js + const devServer = browser.globals.devServerURL + + browser + .url(devServer) + .waitForElementVisible('#app', 5000) + .assert.elementPresent('.greeting') + .assert.elementCount('input', 2) + .assert.containsText('h1', 'Hello') + .end() + } +} diff --git a/pool/shard002/JavaScript/0014027_index.js b/pool/shard002/JavaScript/0014027_index.js new file mode 100644 index 0000000000000000000000000000000000000000..e5e1a0c9d7709ad5505f20af02b5f458ad2712aa --- /dev/null +++ b/pool/shard002/JavaScript/0014027_index.js @@ -0,0 +1,32 @@ +import React, { PropTypes } from 'react'; + +import Wrapper from './Wrapper'; + +class ImageThumbnail extends React.PureComponent { + + constructor(props) { + super(props); + this.activateImage = this.activateImage.bind(this); + } + + activateImage() { + this.props.showImage(this.props.position); + } + + render() { + return ( + +
+
+ ); + } +} + +ImageThumbnail.propTypes = { + showImage: PropTypes.func.isRequired, + image: PropTypes.object.isRequired, + selected: PropTypes.bool.isRequired, + position: PropTypes.number.isRequired, +}; + +export default ImageThumbnail; diff --git a/pool/shard002/JavaScript/0014029_issues.js b/pool/shard002/JavaScript/0014029_issues.js new file mode 100644 index 0000000000000000000000000000000000000000..058e1ba130292ebf04515295132d1f3a6fb011ea --- /dev/null +++ b/pool/shard002/JavaScript/0014029_issues.js @@ -0,0 +1,76 @@ +/** + * Copyright 2013-2022 the original author or authors from the JHipster project. + * + * This file is part of the JHipster project, see https://www.jhipster.tech/ + * for more information. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Issues { + constructor() { + this.entityIssues = []; + this.fieldIssues = []; + this.enumIssues = []; + this.relationshipIssues = []; + } + + addEntityIssues(issues = []) { + this.entityIssues = this.entityIssues.concat(issues); + } + + addFieldIssues(issues = []) { + this.fieldIssues = this.fieldIssues.concat(issues); + } + + addEnumIssues(issues = []) { + this.enumIssues = this.enumIssues.concat(issues); + } + + addRelationshipIssues(issues = []) { + this.relationshipIssues = this.relationshipIssues.concat(issues); + } + + getNumberOfIssues() { + return ( + this.getNumberOfEntityIssues() + this.getNumberOfFieldIssues() + this.getNumberOfEnumIssues() + this.getNumberOfRelationshipIssues() + ); + } + + getNumberOfEntityIssues() { + return this.entityIssues.length; + } + + getNumberOfFieldIssues() { + return this.fieldIssues.length; + } + + getNumberOfEnumIssues() { + return this.enumIssues.length; + } + + getNumberOfRelationshipIssues() { + return this.relationshipIssues.length; + } + + getIssues() { + return { + entities: this.entityIssues, + enums: this.enumIssues, + fields: this.fieldIssues, + relationships: this.relationshipIssues, + }; + } +} + +module.exports = Issues; diff --git a/pool/shard002/JavaScript/0014030_client.js b/pool/shard002/JavaScript/0014030_client.js new file mode 100644 index 0000000000000000000000000000000000000000..83d9a899fce268bb5ca178c4e89a0ea6da8926ef --- /dev/null +++ b/pool/shard002/JavaScript/0014030_client.js @@ -0,0 +1,65 @@ +'use strict'; + +var _ash = require('ash'); + +var _ash2 = _interopRequireDefault(_ash); + +var _Router = require('ash/Router'); + +var _Router2 = _interopRequireDefault(_Router); + +var _I18n = require('ash/I18n'); + +var _I18n2 = _interopRequireDefault(_I18n); + +var _jquery = require('jquery'); + +var _jquery2 = _interopRequireDefault(_jquery); + +var _App = require('./components/App'); + +var _App2 = _interopRequireDefault(_App); + +var _i18nStrings = require('./config/i18nStrings'); + +var _i18nStrings2 = _interopRequireDefault(_i18nStrings); + +var _constants = require('./internals/constants'); + +var _constants2 = _interopRequireDefault(_constants); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +global.ash = _ash2.default; +global.$ = _jquery2.default; + +const EN = _constants2.default.EN; +const G_KEY_CODE = 71; + +// grid toggle +(0, _jquery2.default)(global.document).on('keydown', event => { + let tagName = event.target.tagName.toLowerCase(); + + if (event.keyCode === G_KEY_CODE && event.target && tagName !== 'textarea' && tagName !== 'input') { + (0, _jquery2.default)('body').toggleClass('hasGrid'); + } +}); + +// init i18n +let i18n = new _I18n2.default(); + +i18n.use({ + strings: _i18nStrings2.default, + locale: EN, + currency: '$' +}); + +// init routing +let router = new _Router2.default(); + +router.start(); + +// init renderering +let viewStream = global.viewStream = new _ash2.default.ViewStream(_ash2.default.createElement(_App2.default, null)); + +_ash2.default.renderViewStream(viewStream, global.document.querySelector('.page')); \ No newline at end of file diff --git a/pool/shard002/JavaScript/0014033_index.js b/pool/shard002/JavaScript/0014033_index.js new file mode 100644 index 0000000000000000000000000000000000000000..8b532ef238ef158cf80d3f28a33183a5ebe58736 --- /dev/null +++ b/pool/shard002/JavaScript/0014033_index.js @@ -0,0 +1,47 @@ +// Code generated by generate-maintenance-handler. DO NOT EDIT. +/* eslint-disable */ +import assert from 'assert' +import sinon from 'sinon' +import { handle } from 'api/getMaintenance' +import MaintenancesStore from 'db/maintenances' +import MaintenanceUpdatesStore from 'db/maintenanceUpdates' +import { Maintenance, MaintenanceUpdate } from 'model/maintenances' +import { NotFoundError } from 'utils/errors' + +describe('getMaintenance', () => { + afterEach(() => { + MaintenancesStore.prototype.get.restore() + MaintenanceUpdatesStore.prototype.query.restore() + }) + + it('should return an maintenance', async () => { + const maintenance = new Maintenance({maintenanceID: '1'}) + sinon.stub(MaintenancesStore.prototype, 'get').returns(maintenance) + const maintenanceUpdates = [new MaintenanceUpdate({maintenanceID: '1', maintenanceUpdateID: '1'})] + sinon.stub(MaintenanceUpdatesStore.prototype, 'query').returns(maintenanceUpdates) + + return await handle({ params: { maintenanceid: '1' } }, null, (error, result) => { + assert(error === null) + assert(result.maintenanceID === '1') + assert(result.maintenanceUpdates.length === 1) + assert(result.maintenanceUpdates[0].maintenanceID === '1') + assert(result.maintenanceUpdates[0].maintenanceUpdateID === '1') + }) + }) + + it('should handle not found error', async () => { + sinon.stub(MaintenancesStore.prototype, 'get').throws(new NotFoundError()) + sinon.stub(MaintenanceUpdatesStore.prototype, 'query').throws() + return await handle({ params: { maintenanceid: '1' } }, null, (error, result) => { + assert(error.match(/not found/)) + }) + }) + + it('should return error on exception thrown', async () => { + sinon.stub(MaintenancesStore.prototype, 'get').throws() + sinon.stub(MaintenanceUpdatesStore.prototype, 'query').throws() + return await handle({ params: { maintenanceid: '1' } }, null, (error, result) => { + assert(error.match(/Error/)) + }) + }) +}) diff --git a/pool/shard002/JavaScript/0014036_formatterTerminal.js b/pool/shard002/JavaScript/0014036_formatterTerminal.js new file mode 100644 index 0000000000000000000000000000000000000000..7d0a34a9b86755fb76f7b6c4bfebaf4f06daf21f --- /dev/null +++ b/pool/shard002/JavaScript/0014036_formatterTerminal.js @@ -0,0 +1,88 @@ +const {set, prop} = require('partial.lenses') +const {bold, green, red, yellow, grey} = require('chalk') +const {task} = require('folktale/concurrency/task') +const {inspect} = require('util') + +const spaceEm = value => { + const inspection = inspect( + value, + {sorted: true, depth: 5, colors: true, breakLength: 120} + ).split('\n') + + return inspection.length > 1 + ? inspection.map((line, index) => index === 0 ? line : ` ${line}`).join('\n') + : inspection +} + + +const setMessage = example => set( + prop('message'), + (() => { + switch (example.result.type) { + case 'failure': { + if (example.result.original === undefined || example.result.original.shouldEqual === undefined) { + return `${red(example.description)} +${bold(red(example.result.message))} +${grey(example.result.stack.map(line => ` ${line}`).join('\n'))} +` + } else { + return `${red(example.description)} + ${grey('expect:')} ${spaceEm(example.result.original.shouldEqual)} + ${grey('result:')} ${spaceEm(example.result.original.result)} +` + } + } + + case 'pending': + return yellow(`${example.description}`) + + case 'success': + return green(`${example.description}`) + } + })(), + example +) + +module.exports = logger => suiteResult => + task(({resolve}) => { + const exampleMessages = suiteResult + .map(setMessage) + .map(({message}) => message) + + const totals = suiteResult + .reduce( + ({success, failure, pending}, {result: {type}}) => { + switch (type) { + case 'failure': + return {success, failure: failure + 1, pending} + + case 'pending': + return {success, failure, pending: pending + 1} + + case 'success': + return {success: success + 1, failure, pending} + } + }, + {success: 0, failure: 0, pending: 0} + ) + + const totalsToPrint = [ + [totals.success, green(`${totals.success} successful`)], + [totals.pending, yellow(`${totals.pending} pending`)], + [totals.failure, red(`${totals.failure} failing`)] + ] + + logger( + exampleMessages + .concat([ + '', + totalsToPrint + .filter(([total]) => total > 0) + .map(([_, message]) => message) + .join(grey(' • ')) + ]) + .join('\n') + ) + + resolve(suiteResult) + }) diff --git a/pool/shard002/JavaScript/0014040_MDAO.js b/pool/shard002/JavaScript/0014040_MDAO.js new file mode 100644 index 0000000000000000000000000000000000000000..699bb767ba5a4220683d4249dd82924a95bb95b7 --- /dev/null +++ b/pool/shard002/JavaScript/0014040_MDAO.js @@ -0,0 +1,268 @@ +/** + * @license + * Copyright 2012 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. + */ + +foam.CLASS({ + package: 'foam.dao', + name: 'MDAO', + label: 'Indexed DAO', + extends: 'foam.dao.AbstractDAO', + + documentation: 'Indexed in-Memory DAO.', + + requires: [ + 'foam.dao.ArraySink', + 'foam.dao.ExternalException', + 'foam.dao.InternalException', + 'foam.dao.InvalidArgumentException', + 'foam.dao.ObjectNotFoundException', + 'foam.dao.index.AltIndex', + 'foam.dao.index.AutoIndex', + 'foam.dao.index.SetIndex', + 'foam.dao.index.TreeIndex', + 'foam.dao.index.ValueIndex', + 'foam.mlang.predicate.Eq', + 'foam.mlang.predicate.True', + 'foam.mlang.predicate.Or', + 'foam.mlang.sink.Explain', + 'foam.dao.index.MergePlan' + ], + + properties: [ + { + class: 'Class', + name: 'of', + required: true, + postSet: function() { + foam.assert(this.of.ID, "MDAO.of must be assigned a FOAM Class " + + "with an 'id' Property or 'ids' array specified. Missing id in " + + "class: " + ( this.of && this.of.id )); + } + }, + { + class: 'Boolean', + name: 'autoIndex' + }, + { + name: 'idIndex', + transient: true + }, + { + /** The root IndexNode of our index. */ + name: 'index', + transient: true + } + ], + + methods: [ + function init() { + // adds the primary key(s) as an index, and stores it for fast find(). + this.addPropertyIndex(); + this.idIndex = this.index; + + if ( this.autoIndex ) { + this.addIndex(this.AutoIndex.create({ idIndex: this.idIndex.index })); + } + }, + + /** + * Add a non-unique index + * args: one or more properties + **/ + function addPropertyIndex() { + var props = Array.from(arguments); + + // Add ID to make each sure the object is uniquely identified + props.push(this.of.ID); + + return this.addUniqueIndex_.apply(this, props); + }, + + /** + * Add a unique index + * args: one or more properties + * @private + **/ + function addUniqueIndex_() { + var index = this.ValueIndex.create(); + + for ( var i = arguments.length-1 ; i >= 0 ; i-- ) { + var prop = arguments[i]; + + // Pass previous index as the sub-index of the next level up. + // (we are working from leaf-most index up to root index in the list) + index = prop.toIndex(index); + } + + return this.addIndex(index); + }, + + function addIndex(index) { + if ( ! this.index ) { + this.index = index.createNode(); + return this; + } + + // Upgrade single Index to an AltIndex if required. + if ( ! this.AltIndex.isInstance(this.index.index) ) { + this.index = this.AltIndex.create({ + delegates: [ this.index.index ] // create factory + }).createNode({ + delegates: [ this.index ] // create an instance + }); + } + + this.index.addIndex(index, this.index); + + return this; + }, + + /** + * Bulk load data from another DAO. + * Any data already loaded into this DAO will be lost. + * @param sink (optional) eof is called when loading is complete. + **/ + function bulkLoad(dao) { + var self = this; + var sink = self.ArraySink.create(); + return dao.select(sink).then(function() { + var a = sink.array; + self.index.bulkLoad(a); + for ( var i = 0; i < a.length; ++i ) { + var obj = a[i]; + } + }); + }, + + function put_(x, obj) { + var oldValue = this.findSync_(obj.id); + if ( oldValue ) { + this.index.remove(oldValue); + } + this.index.put(obj); + this.pub('on', 'put', obj); + return Promise.resolve(obj); + }, + + function find_(x, objOrKey) { + if ( objOrKey === undefined ) { + return Promise.reject(this.InvalidArgumentException.create({ + message: '"key" cannot be undefined/null' + })); + } + + return Promise.resolve(this.findSync_( + this.of.isInstance(objOrKey) ? objOrKey.id : objOrKey)); + }, + + /** internal, synchronous version of find, does not throw */ + function findSync_(key) { + var index = this.idIndex; + index = index.get(key); + + if ( index && index.get() ) return index.get(); + + return null; + }, + + function remove_(x, obj) { + if ( ! obj || obj.id === undefined ) { + return Promise.reject(this.ExternalException.create({ id: 'no_id' })); // TODO: err + } + + var id = obj.id; + var self = this; + + var found = this.findSync_(id); + if ( found ) { + self.index.remove(found); + self.pub('on', 'remove', found); + } + + return Promise.resolve(); + }, + + function removeAll_(x, skip, limit, order, predicate) { + if ( ! predicate ) predicate = this.True.create(); + var self = this; + return self.where(predicate).select(self.ArraySink.create()).then( + function(sink) { + var a = sink.array; + for ( var i = 0 ; i < a.length ; i++ ) { + self.index.remove(a[i]); + self.pub('on', 'remove', a[i]); + } + return Promise.resolve(); + } + ); + }, + + function select_(x, sink, skip, limit, order, predicate) { + sink = sink || this.ArraySink.create(); + var plan; +//console.log("----select"); + if ( this.Explain.isInstance(sink) ) { + plan = this.index.plan(sink.arg1, skip, limit, order, predicate, this.index); + sink.plan = 'cost: ' + plan.cost + ', ' + plan.toString(); + sink && sink.eof && sink.eof(); + return Promise.resolve(sink); + } + + predicate = predicate && predicate.toDisjunctiveNormalForm(); + if ( ! predicate || ! this.Or.isInstance(predicate) ) { + plan = this.index.plan(sink, skip, limit, order, predicate, this.index); + } else { + plan = this.planForOr(sink, skip, limit, order, predicate); + } + + var promise = [Promise.resolve()]; + plan.execute(promise, sink, skip, limit, order, predicate); + return promise[0].then( + function() { + sink && sink.eof && sink.eof(); + return Promise.resolve(sink); + }, + function(err) { + return Promise.reject(err); + } + ); + }, + + function planForOr(sink, skip, limit, order, predicate) { + // if there's a limit, add skip to make sure we get enough results + // from each subquery. Our sink will throw out the extra results + // after sorting. + var subLimit = ( limit ? limit + ( skip ? skip : 0 ) : undefined ); + + // This is an instance of OR, break up into separate queries + var args = predicate.args; + var plans = []; + for ( var i = 0; i < args.length; i++ ) { + // NOTE: we pass sink here, but it's not going to be the one eventually + // used. + plans.push( + this.index.plan(sink, undefined, subLimit, order, args[i], this.index) + ); + } + + return this.MergePlan.create({ of: this.of, subPlans: plans, predicates: args }); + }, + + function toString() { + return 'MDAO(' + this.cls_.name + ',' + this.index + ')'; + } + ] +}); diff --git a/pool/shard002/JavaScript/0014051_index.js b/pool/shard002/JavaScript/0014051_index.js new file mode 100644 index 0000000000000000000000000000000000000000..5e4311f8a4e22c74a6ecb03bc5e5f31c5a6f3309 --- /dev/null +++ b/pool/shard002/JavaScript/0014051_index.js @@ -0,0 +1,97 @@ +/** + * Express Writer + * Authors: Richard Torruellas and Jacob Heun + * Allows developers to develop like they would in Express, but output rendered html as static files. + */ + +var fs = require('fs'), + mkdirp = require('mkdirp'), + DIST_BASE_DIR = "./dist"; + +/** + * Writes the given content to the desired destination + * @param destination The destination of the file to be written + * @param body The content to be written to the file + */ +var writeHtml = function(destination, body, callback){ + var msg; + fs.writeFile(destination, body, function(err){ + /*@todo: Better handling here*/ + if (err){ + throw new Error("Writer:: Issue writing to destination '" + destination + "'"); + }else { + msg = 'Wrote to >' + destination; + callback(msg); + } + }); + +}; + +/** + * Writes the given body to the directory equivalent to the requests original url + * @param req The Express wrapped request made to the server. + * @param body The html body to be rendered. + */ +var scribe = function(req, body, callback) { + + var directory = DIST_BASE_DIR + req.originalUrl, + destination = DIST_BASE_DIR; + + // Determine the correct destination + if (req.originalUrl !== '/'){ + destination += req.originalUrl + '/index.html'; + }else { + destination += req.originalUrl + 'index.html'; + } + + // Make the necessary folder and write the html + mkdirp(directory, function(err) { + if (err){ + throw new Error("Writer:: Issue creating directory '" + destination + "'"); + }else { + writeHtml(destination, body, callback); + } + }); + +}; + +/** + * Highjacks the res.send method in order to get a hold of the content to be rendered + * @param req The Express wrapped request object + * @param res The Express wrapped response object + * @param next Used to trigger the next middleware + */ +var watch = function(req, res, next) { + + // Copy a reference to the proper res.send method + var _send = res.send; + + // Replace the existing send method with out temp method + res.send = function() { + + // Call the original send to finish the request + _send.apply(res, arguments); + + //Write out the content + //callback is for testing purposes + scribe(req, arguments[0], function(msg){ + console.log(msg); + }); + + }; + + next(); + +}; + +var setWriteDirectory = function(newDirectory) { + DIST_BASE_DIR = newDirectory; +}; + +exports = module.exports = { + + scribe : scribe, + setWriteDirectory: setWriteDirectory, + watch : watch + +}; \ No newline at end of file diff --git a/pool/shard002/JavaScript/0014052_sweetalert.js b/pool/shard002/JavaScript/0014052_sweetalert.js new file mode 100644 index 0000000000000000000000000000000000000000..ec039aa109d3d0c5a8f5787e1466972e03e6b14b --- /dev/null +++ b/pool/shard002/JavaScript/0014052_sweetalert.js @@ -0,0 +1,51 @@ +/** + * Proudly created by ohad on 22/12/2016. + */ +let _ = require('../../../common/util/wrapper'), + $ = require('../../../common/util/dom'), + Logger = require('../../../common/log/logger'), + Level = require('../../../common/log/logger').Level, + BaseError = require('../../../common/log/base.error'), + Master = require('../master'); +exports.name = 'sweetalert'; +Master.register(exports); +/** + * Creates a modal using sweet alerts 2, the modal is triggered by an external event. + * https://limonte.github.io/sweetalert2/ + * @param {Object} options + * @property {function} swalFn - runs sweetalert2 code + */ +exports.execute = function (options) { + require.ensure(['sweetalert2', 'sweetalert2/dist/sweetalert2.css'], function (require) { + if (!_styleLoaded) $.load(require('sweetalert2/dist/sweetalert2.css')); + _styleLoaded = true; + options.swalFn(require('sweetalert2')); + if (options.toLog) { + setTimeout(() => { + const suffix = _.isNil(options.id) ? '' : ` (id = ${options.id}`; + if ($.isVisible($('div.swal2-modal.swal2-show'))) { + Logger.log(Level.INFO, 'Fired sweetalert2' + suffix); + } else { + Logger.log(Level.WARNING, 'Sweetalert2 was not fired' + suffix); + } + }, 20) + } + }); +}; + +/** + * @param {Object} options + * @returns {boolean} whether the executor has a valid input. + */ +exports.preconditions = function (options) { + if (!_.isFunction(options.swalFn)) { + throw new BaseError('SweetalertExecutor: swalFn must be a function.'); + } +}; + +/** + * Indicates whether the style was loaded to the DOM. + * @type {boolean} + * @private + */ +let _styleLoaded = false; diff --git a/pool/shard002/JavaScript/0014053_persistentvolumeclaimlist_controller_test.js b/pool/shard002/JavaScript/0014053_persistentvolumeclaimlist_controller_test.js new file mode 100644 index 0000000000000000000000000000000000000000..efd24b9967b7784cbd2fbd1896f2e3d5532d768d --- /dev/null +++ b/pool/shard002/JavaScript/0014053_persistentvolumeclaimlist_controller_test.js @@ -0,0 +1,53 @@ +// Copyright 2015 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. + +import {PersistentVolumeClaimListController} from 'persistentvolumeclaimlist/persistentvolumeclaimlist_controller'; +import persistentVolumeClaimListModule from 'persistentvolumeclaimlist/persistentvolumeclaimlist_module'; + +describe('Persistent Volume list controller', () => { + /** @type + * {!persistentvolumeclaimlist/persistentvolumeclaimlist_controller.PersistentVolumeClaimListController} + */ + let ctrl; + + beforeEach(() => { + angular.mock.module(persistentVolumeClaimListModule.name); + + angular.mock.inject(($controller) => { + ctrl = $controller( + PersistentVolumeClaimListController, {persistentVolumeClaimList: {items: []}}); + }); + }); + + it('should initialize persistent volume claim controller', angular.mock.inject(($controller) => { + let ctrls = {}; + /** @type {!PersistentVolumeClaimListController} */ + let ctrl = $controller( + PersistentVolumeClaimListController, {persistentVolumeClaimList: {items: ctrls}}); + + expect(ctrl.persistentVolumeClaimList.items).toBe(ctrls); + })); + + it('should show zero state', () => { + expect(ctrl.shouldShowZeroState()).toBe(true); + }); + + it('should hide zero state', () => { + // given + ctrl.persistentVolumeClaimList = {items: ['mock']}; + + // then + expect(ctrl.shouldShowZeroState()).toBe(false); + }); +}); diff --git a/pool/shard002/JavaScript/0014055_app.js b/pool/shard002/JavaScript/0014055_app.js new file mode 100644 index 0000000000000000000000000000000000000000..6e10eb9d34ef67144ca226c67db1dafeca3128c1 --- /dev/null +++ b/pool/shard002/JavaScript/0014055_app.js @@ -0,0 +1,32 @@ +'use strict'; + +var angular = require('angular'), + ui_router = require('angular-ui-router'), + app_home = require('./home/home'), + app_about = require('./about/about'), + ui_bootstrap_collapse = require('ui.bootstrap.collapse'); + +module.exports = angular.module( 'ngBoilerplate', [ + app_home.name, + app_about.name, + ui_router, + ui_bootstrap_collapse +]) + +.config( function myAppConfig ( $stateProvider, $urlRouterProvider ) { + $urlRouterProvider.otherwise( '/home' ); +}) + +.run( function run () { +}) + +.controller( 'AppCtrl', function AppCtrl ( $scope, $location ) { + $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){ + if ( angular.isDefined( toState.data.pageTitle ) ) { + $scope.pageTitle = toState.data.pageTitle + ' | ngBoilerplate' ; + } + }); +}) + +; + diff --git a/pool/shard002/JavaScript/0014058_d3-timer.js b/pool/shard002/JavaScript/0014058_d3-timer.js new file mode 100644 index 0000000000000000000000000000000000000000..11d4bee8d04c5092c1737b30ffa796d2960dea4a --- /dev/null +++ b/pool/shard002/JavaScript/0014058_d3-timer.js @@ -0,0 +1,129 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.d3_timer = {}))); +}(this, function (exports) { 'use strict'; + + var frame = 0; + var timeout = 0; + var interval = 0; + var maxDelay = 5000; + var taskHead; + var taskTail; + var clockLast = 0; + var clockNow = 0; + var clock = typeof performance === "object" ? performance : Date; + var setFrame = typeof requestAnimationFrame === "function" ? requestAnimationFrame : function(callback) { return setTimeout(callback, 17); }; + function now() { + return clockNow || (setFrame(clearNow), clockNow = clock.now()); + } + + function clearNow() { + clockNow = 0; + } + + function Timer() { + this._call = + this._time = + this._next = null; + } + + Timer.prototype = timer.prototype = { + restart: function(callback, delay, time) { + if (typeof callback !== "function") throw new TypeError("callback is not a function"); + time = (time == null ? now() : +time) + (delay == null ? 0 : +delay); + if (!this._call) { + if (taskTail) taskTail._next = this; + else taskHead = this; + taskTail = this; + } + this._call = callback; + this._time = time; + sleep(); + }, + stop: function() { + if (this._call) { + this._call = null; + this._time = Infinity; + sleep(); + } + } + }; + + function timer(callback, delay, time) { + var t = new Timer; + t.restart(callback, delay, time); + return t; + } + + function timerOnce(callback, delay, time) { + var t = new Timer; + t.restart(function(elapsed) { t.stop(); callback(elapsed); }, delay, time); + return t; + } + + function timerFlush() { + now(); // Get the current time, if not already set. + ++frame; // Pretend we’ve set an alarm, if we haven’t already. + var t = taskHead, e; + while (t) { + if ((e = clockNow - t._time) >= 0) t._call.call(null, e); + t = t._next; + } + --frame; + } + + function wake(time) { + clockLast = clockNow = time || clock.now(); + frame = timeout = 0; + try { + timerFlush(); + } finally { + frame = 0; + nap(); + clockNow = 0; + } + } + + function poke() { + if (clock.now() - clockLast > maxDelay) { + wake(); + } + } + + function nap() { + var t0, t1 = taskHead, time = Infinity; + while (t1) { + if (t1._call) { + if (time > t1._time) time = t1._time; + t1 = (t0 = t1)._next; + } else { + t1 = t0 ? t0._next = t1._next : taskHead = t1._next; + } + } + taskTail = t0; + sleep(time); + } + + function sleep(time) { + if (frame) return; // Soonest alarm already set, or will be. + if (timeout) timeout = clearTimeout(timeout); + var delay = time - clockNow; + if (delay > 24) { + if (time < Infinity) timeout = setTimeout(wake, delay); + else if (interval) interval = clearInterval(interval); + } else { + if (!interval) interval = setInterval(poke, maxDelay); + frame = 1, setFrame(wake); + } + } + + var version = "0.3.1"; + + exports.version = version; + exports.now = now; + exports.timer = timer; + exports.timerOnce = timerOnce; + exports.timerFlush = timerFlush; + +})); \ No newline at end of file diff --git a/pool/shard002/JavaScript/0014060_Service.js b/pool/shard002/JavaScript/0014060_Service.js new file mode 100644 index 0000000000000000000000000000000000000000..570dcaeaa8caf8297cb093acafcd35b333e7c49c --- /dev/null +++ b/pool/shard002/JavaScript/0014060_Service.js @@ -0,0 +1,128 @@ +import L from 'leaflet'; +import {cors} from '../Support.js'; +import {cleanUrl} from '../Util.js'; +import Request from '../Request.js'; + +export var Service = L.Evented.extend({ + + options: { + proxy: false, + useCors: cors + }, + + initialize: function (options) { + options = options || {}; + this._requestQueue = []; + this._authenticating = false; + L.Util.setOptions(this, options); + this.options.url = cleanUrl(this.options.url); + }, + + get: function (path, params, callback, context) { + return this._request('get', path, params, callback, context); + }, + + post: function (path, params, callback, context) { + return this._request('post', path, params, callback, context); + }, + + request: function (path, params, callback, context) { + return this._request('request', path, params, callback, context); + }, + + metadata: function (callback, context) { + return this._request('get', '', {}, callback, context); + }, + + authenticate: function (token) { + this._authenticating = false; + this.options.token = token; + this._runQueue(); + return this; + }, + + _request: function (method, path, params, callback, context) { + this.fire('requeststart', { + url: this.options.url + path, + params: params, + method: method + }, true); + + var wrappedCallback = this._createServiceCallback(method, path, params, callback, context); + + if (this.options.token) { + params.token = this.options.token; + } + + if (this._authenticating) { + this._requestQueue.push([method, path, params, callback, context]); + return; + } else { + var url = (this.options.proxy) ? this.options.proxy + '?' + this.options.url + path : this.options.url + path; + + if ((method === 'get' || method === 'request') && !this.options.useCors) { + return Request.get.JSONP(url, params, wrappedCallback); + } else { + return Request[method](url, params, wrappedCallback); + } + } + }, + + _createServiceCallback: function (method, path, params, callback, context) { + return L.Util.bind(function (error, response) { + if (error && (error.code === 499 || error.code === 498)) { + this._authenticating = true; + + this._requestQueue.push([method, path, params, callback, context]); + + // fire an event for users to handle and re-authenticate + this.fire('authenticationrequired', { + authenticate: L.Util.bind(this.authenticate, this) + }, true); + + // if the user has access to a callback they can handle the auth error + error.authenticate = L.Util.bind(this.authenticate, this); + } + + callback.call(context, error, response); + + if (error) { + this.fire('requesterror', { + url: this.options.url + path, + params: params, + message: error.message, + code: error.code, + method: method + }, true); + } else { + this.fire('requestsuccess', { + url: this.options.url + path, + params: params, + response: response, + method: method + }, true); + } + + this.fire('requestend', { + url: this.options.url + path, + params: params, + method: method + }, true); + }, this); + }, + + _runQueue: function () { + for (var i = this._requestQueue.length - 1; i >= 0; i--) { + var request = this._requestQueue[i]; + var method = request.shift(); + this[method].apply(this, request); + } + this._requestQueue = []; + } +}); + +export function service (options) { + return new Service(options); +} + +export default service; diff --git a/pool/shard002/JavaScript/0014061_index.test.js b/pool/shard002/JavaScript/0014061_index.test.js new file mode 100644 index 0000000000000000000000000000000000000000..15c85ba1c5d83f6b0710e71f0da9bed113431794 --- /dev/null +++ b/pool/shard002/JavaScript/0014061_index.test.js @@ -0,0 +1,21 @@ +import {expect} from 'chai'; +import jsdom from 'jsdom'; +import fs from 'fs'; + +describe('Our first test', () => { + it('should pass', () => { + expect(true).to.equal(true); + }); +}); + +describe('index.html', () => { + it('should have h1 that says Users', (done) => { + const index = fs.readFileSync('./src/index.html', 'utf-8'); + jsdom.env(index, function (err, window) { + const h1 = window.document.getElementsByTagName('h1')[0]; + expect(h1.innerHTML).to.equal("Users"); + done(); + window.close(); + }); + }); +}); diff --git a/pool/shard002/JavaScript/0014063_index.js b/pool/shard002/JavaScript/0014063_index.js new file mode 100644 index 0000000000000000000000000000000000000000..fb3c875716b457727d6d4c1b3472a153bddb5776 --- /dev/null +++ b/pool/shard002/JavaScript/0014063_index.js @@ -0,0 +1,44 @@ +// boilerplate to import all models in the folder +// taken from sequelize website + +// make sure to have a method named "associate" in the class Methods +// this is used to build the association between various tables +"use strict"; + +var fs = require("fs"); +var path = require("path"); +var Sequelize = require("sequelize"); +var sequelize = new Sequelize('my_database', 'db_user', 'db_password', { + dialect: "postgres", + port: 5432, +}); + +// backend model reference object, used to expose everything in it +// for everyone to use +var db = {}; + +// read all files present in the folder except index.js +// ., .. and hidden files +// import each module into the db object +fs + .readdirSync(__dirname) + .filter(function(file) { + return (file.indexOf(".") !== 0) && (file !== "index.js"); + }) + .forEach(function(file) { + var model = sequelize["import"](path.join(__dirname, file)); + db[model.name] = model; + }); + +// Make associations if we have an association with the table +Object.keys(db).forEach(function(modelName) { + if ("associate" in db[modelName]) { + db[modelName].associate(db); + } +}); + +// export stuff +db.sequelize = sequelize; +db.Sequelize = Sequelize; + +module.exports = db; diff --git a/pool/shard002/JavaScript/0014064_enabledElements.js b/pool/shard002/JavaScript/0014064_enabledElements.js new file mode 100644 index 0000000000000000000000000000000000000000..0080a531e2f795c719ea2b7eeeb2a673af740b90 --- /dev/null +++ b/pool/shard002/JavaScript/0014064_enabledElements.js @@ -0,0 +1,162 @@ +const enabledElements = []; + +/** + * A two-dimensional vector + * + * @typedef {Object} vec2 + * @param {Number} x - The x distance + * @param {Number} y - The y distance + */ + +/** + * VOI + * + * @typedef {Object} VOI + * @param {Number} windowWidth - Window Width for display + * @param {Number} windowCenter - Window Center for display + */ + +/** + * Lookup Table Array + * + * @typedef {Object} LUT + * @property {Number} firstValueMapped + * @property {Number} numBitsPerEntry + * @property {Array} lut + */ + +/** + * Image Statistics Object + * + * @typedef {Object} ImageStats + * + * @property {Number} [lastGetPixelDataTime] The time in ms taken to retrieve stored pixels required to draw the image + * @property {Number} [lastStoredPixelDataToCanvasImageDataTime] The time in ms taken to map from stored pixel array to canvas pixel array + * @property {Number} [lastPutImageDataTime] The time in ms taken for putImageData to put the canvas pixel data into the canvas context + * @property {Number} [lastRenderTime] The total time in ms taken for the entire rendering function to run + * @property {Number} [lastLutGenerateTime] The time in ms taken to generate the lookup table for the image + */ + +/** + * An Image Object in Cornerstone + * + * @typedef {Object} Image + * + * @property {string} imageId - The imageId associated with this image object + * @property {Number} minPixelValue - the minimum stored pixel value in the image + * @property {Number} maxPixelValue - the maximum stored pixel value in the image + * @property {Number} slope - the rescale slope to convert stored pixel values to modality pixel values or 1 if not specified + * @property {Number} intercept - the rescale intercept used to convert stored pixel values to modality values or 0 if not specified + * @property {Number} windowCenter - the default windowCenter to apply to the image + * @property {Number} windowWidth - the default windowWidth to apply to the image + * @property {function} getPixelData - a function that returns the underlying pixel data. An array of integers for grayscale and an array of RGBA for color + * @property {function} getImageData - a function that returns a canvas imageData object for the image. This is only needed for color images + * @property {function} getCanvas - a function that returns a canvas element with the image loaded into it. This is only needed for color images. + * @property {function} getImage - a function that returns a JavaScript Image object with the image data. This is optional and typically used for images encoded in standard web JPEG and PNG formats + * @property {Number} rows - number of rows in the image. This is the same as height but duplicated for convenience + * @property {Number} columns - number of columns in the image. This is the same as width but duplicated for convenience + * @property {Number} height - the height of the image. This is the same as rows but duplicated for convenience + * @property {Number} width - the width of the image. This is the same as columns but duplicated for convenience + * @property {Boolean} color - true if pixel data is RGB, false if grayscale + * @property {Object} lut - The Lookup Table + * @property {Boolean} rgba - Is the color pixel data stored in RGBA? + * @property {Number} columnPixelSpacing - horizontal distance between the middle of each pixel (or width of each pixel) in mm or undefined if not known + * @property {Number} rowPixelSpacing - vertical distance between the middle of each pixel (or heigh of each pixel) in mm or undefined if not known + * @property {Boolean} invert - true if the the image should initially be displayed be inverted, false if not. This is here mainly to support DICOM images with a photometric interpretation of MONOCHROME1 + * @property {Number} sizeInBytes - the number of bytes used to store the pixels for this image. + * @property {Boolean} [falseColor=false] - Whether or not the image has undergone false color mapping + * @property {Array} [origPixelData] - Original pixel data for an image after it has undergone false color mapping + * @property {ImageStats} [stats] - Statistics for the last redraw of the image + * @property {Object} cachedLut - Cached Lookup Table for this image. + */ + +/** + * A Viewport Settings Object Cornerstone + * + * @typedef {Object} Viewport + * + * @property {Number} [scale=1.0] - The scale applied to the image. A scale of 1.0 will display no zoom (one image pixel takes up one screen pixel). A scale of 2.0 will be double zoom and a scale of .5 will be zoomed out by 2x + * @param {vec2} [translation] - An object with properties x and y which describe the translation to apply in the pixel coordinate system. Note that the image is initially displayed centered in the enabled element with a x and y translation of 0 and 0 respectively. + * @param {VOI} [voi] - an object with properties windowWidth and windowCenter. + * @property {boolean} [invert=false] - Whether or not the image is inverted. + * @property {boolean} [pixelReplication=false] - true if the image smooth / interpolation should be used when zoomed in on the image or false if pixel replication should be used. + * @property {boolean} [hflip=false] - true if the image is flipped horizontally. Default is false + * @property {boolean} [vflip=false] - true if the image is flipped vertically. Default is false + * @property {Number} [rotation=0] - the rotation of the image (90 degree increments). Default is 0 + * @property {LUT} [modalityLUT] - the modality LUT to apply or undefined if none + * @property {LUT} [voiLUT] - the modality LUT to apply or undefined if none + */ + +/** + * An Enabled Element in Cornerstone + * + * @typedef {Object} EnabledElement + * + * @property {HTMLElement} element - The DOM element which has been enabled for use by Cornerstone + * @property {Image} [image] - The image currently displayed in the enabledElement + * @property {Viewport} [viewport] - The current viewport settings of the enabledElement + * @property {Boolean} invalid - Whether or not the image pixel data underlying the enabledElement has been changed, necessitating a redraw + * @property {Boolean} needsRedraw - A flag for triggering a redraw of the canvas without re-retrieving the pixel data, since it remains valid + */ + + +/** + * Retrieves a Cornerstone Enabled Element object + * + * @param {HTMLElement} element An HTML Element enabled for Cornerstone + * + * @returns {EnabledElement} A Cornerstone Enabled Element + */ +export function getEnabledElement (element) { + if (element === undefined) { + throw new Error('getEnabledElement: parameter element must not be undefined'); + } + for (let i = 0; i < enabledElements.length; i++) { + if (enabledElements[i].element === element) { + return enabledElements[i]; + } + } + + throw new Error('element not enabled'); +} + +/** + * Adds a Cornerstone Enabled Element object to the central store of enabledElements + * + * @param {EnabledElement} enabledElement A Cornerstone enabledElement Object + * @returns {void} + */ +export function addEnabledElement (enabledElement) { + if (enabledElement === undefined) { + throw new Error('getEnabledElement: enabledElement element must not be undefined'); + } + + enabledElements.push(enabledElement); +} + +/** + * Adds a Cornerstone Enabled Element object to the central store of enabledElements + * + * @param {string} imageId A Cornerstone Image ID + * @returns {EnabledElement[]} An Array of Cornerstone enabledElement Objects + */ +export function getEnabledElementsByImageId (imageId) { + const ees = []; + + enabledElements.forEach(function (enabledElement) { + if (enabledElement.image && enabledElement.image.imageId === imageId) { + ees.push(enabledElement); + } + }); + + return ees; +} + +/** + * Retrieve all of the currently enabled Cornerstone elements + * + * @return {EnabledElement[]} An Array of Cornerstone enabledElement Objects + */ +export function getEnabledElements () { + return enabledElements; +} diff --git a/pool/shard002/JavaScript/0014065_gulpfile.js b/pool/shard002/JavaScript/0014065_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..aa9404be1a35754ccb9aa932ca738bb7c04987b0 --- /dev/null +++ b/pool/shard002/JavaScript/0014065_gulpfile.js @@ -0,0 +1,168 @@ +var gulp = require('gulp'), + rename = require('gulp-rename'), + uglify = require('gulp-uglify'), + header = require('gulp-header'), + concat = require('gulp-concat'), + highland = require('highland'), + fs = require('fs'), + path = require('path'), + File = require('vinyl'), + del = require('del'), + yargs = require('yargs'), + npm = require('npm'), + + runningPackagingTask = yargs.argv._.indexOf('createPackages') > -1, + version = yargs.argv.version, + + paths = { + components: ['components/**/*.js', '!components/**/*.min.js'], + main: [ + 'components/prism-core.js', + 'components/prism-markup.js', + 'components/prism-css.js', + 'components/prism-clike.js', + 'components/prism-javascript.js', + 'plugins/file-highlight/prism-file-highlight.js' + ], + plugins: ['plugins/**/*.js', '!plugins/**/*.min.js'] + }; + +gulp.task('components', function() { + return gulp.src(paths.components) + .pipe(uglify()) + .pipe(rename({ suffix: '.min' })) + .pipe(gulp.dest('components')); +}); + +gulp.task('build', function() { + return gulp.src(paths.main) + .pipe(header('\n/* **********************************************\n' + + ' Begin <%= file.relative %>\n' + + '********************************************** */\n\n')) + .pipe(concat('prism.js')) + .pipe(gulp.dest('./')); +}); + +gulp.task('plugins', function() { + return gulp.src(paths.plugins) + .pipe(uglify()) + .pipe(rename({ suffix: '.min' })) + .pipe(gulp.dest('plugins')); +}); + +gulp.task('watch', function() { + gulp.watch(paths.components, ['components', 'build']); + gulp.watch(paths.plugins, ['plugins', 'build']); +}); + +gulp.task('default', ['components', 'plugins', 'build']); + + + +/* tasks for creating and publishing npm packages */ + +function readme(themeName) { + return [ + '# Prism ' + themeName.charAt(0).toUpperCase() + themeName.substring(1) + ' Theme', + 'Prism is a lightweight, robust, elegant syntax highlighting library.', + 'Learn more at [http://prismjs.com/](http://prismjs.com/).' + ].join('\n\n'); +} + +function packagejson(themeName) { + return JSON.stringify({ + name: 'prism-' + themeName + '-theme', + version: version, + description: 'A CSS theme for PrismJS', + repository: { + type: 'git', + url: 'https://github.com/PrismJS/prism.git' + }, + keywords: [ + 'prism', + 'highlight', + 'theme' + ], + author: 'Lea Verou', + license: 'MIT', + style: 'prism-' + themeName + '.css' + }, null, 2); +} + +function license(themeName) { + return fs.readFileSync('LICENSE'); +} + +var contentStrategy = { + 'package.json': packagejson, + 'README.md': readme, + 'LICENSE': license +}; + +gulp.task('clean-dist', function(done) { + del('dist', done); +}); + +gulp.task('copy-css', ['build', 'clean-dist'], function() { + return highland(gulp.src('themes/*.css')) + .map(function(file) { + var name = path.basename(file.path) === 'prism.css' ? 'prism-default' : path.basename(file.path, '.css'); + file.path = path.join(path.dirname(file.path), name, name + '.css'); + return file; + }) + .pipe(gulp.dest('dist')); +}); + +gulp.task('copy-files', ['copy-css'], function() { + return highland(gulp.src('dist/*')) + .flatMap(function(dir) { + var themeName = /prism-(\w+)/.exec(path.basename(dir.path))[1]; + return ['package.json', 'README.md', 'LICENSE'] + .map(function(fileName) { + return new File({ + base: path.dirname(dir.path), + path: path.join(dir.path, fileName), + contents: new Buffer(contentStrategy[fileName](themeName)) + }); + }); + }) + .pipe(gulp.dest('dist')); +}); + +gulp.task('update-version', function() { + return highland(gulp.src('package.json')) + .map(function(file) { + var packageInfo = JSON.parse(file.contents); + packageInfo.version = version; + file.contents = new Buffer(JSON.stringify(packageInfo, null, 2)); + return file; + }) + .pipe(gulp.dest('.')); +}); + +if (runningPackagingTask && !version) { + console.error('Please specify a version number for the release, for example: gulp createPackages --version 1.0.42'); + process.exit(1); +} + +gulp.task('createPackages', ['copy-css', 'copy-files', 'update-version']); + +gulp.task('publishPackages', function(done) { + var packages = fs.readdirSync('dist') + .map(function(packageName) { + return path.join('dist', packageName); + }) + .concat('.'); + + npm.load({}, function() { + function next() { + if (packages.length > 0) { + npm.commands.publish([packages.pop()], next); + } else { + done(); + } + } + next(); + }); +}); + diff --git a/pool/shard002/JavaScript/0014066_update.js b/pool/shard002/JavaScript/0014066_update.js new file mode 100644 index 0000000000000000000000000000000000000000..b72f273fcf408ea84cf7c7b56d9dd5f2c45ff5d8 --- /dev/null +++ b/pool/shard002/JavaScript/0014066_update.js @@ -0,0 +1,85 @@ +module.exports = require('./delete').extend(function() { + /* Require + -------------------------------*/ + /* Constants + -------------------------------*/ + /* Public.Properties + -------------------------------*/ + /* Protected Properties + -------------------------------*/ + this._set = {}; + + /* Private Properties + -------------------------------*/ + /* Magic + -------------------------------*/ + /* Public.Methods + -------------------------------*/ + /** + * Returns the string version of the query + * + * @param bool + * @return string + * @notes returns the query based on the registry + */ + this.getQuery = function() { + var set = []; + + for(var key in this._set) { + if(this._set.hasOwnProperty(key)) { + set.push(key + ' = ' + this._set[key]); + } + } + + return 'UPDATE "{TABLE}" SET {SET} WHERE {WHERE};' + .replace('{TABLE}' , this._table) + .replace('{SET}' , set.join(', ')) + .replace('{WHERE}' , this._where.join(' AND ')); + }; + + /** + * Set clause that assigns a given field name to a given value. + * + * @param string + * @param string + * @return this + * @notes loads a set into registry + */ + this.set = function(key, value) { + //argument test + this.argument() + .test(1, 'string', 'object') //Argument 1 must be a string + .test(2, 'numeric', 'string', 'bool', 'null', 'undef'); //Argument 2 must be scalar or null + + if(typeof key === 'object') { + for(var i in key) { + if(key.hasOwnProperty(i)) { + this.set(i, key[i]); + } + } + + return this; + } + + key = '"' + key + '"'; + + if(value === null) { + value = 'NULL'; + } else if(typeof value === 'boolean') { + value = value ? 1 : 0; + } else if(typeof value === 'string' + && value !== '?' + && value.indexOf('$') !== 0) { + value = "'" + value + "'"; + } + + this._set[key] = value; + + return this; + }; + + /* Protected Methods + -------------------------------*/ + /* Private Methods + -------------------------------*/ +}).register('eden/mysql/update'); \ No newline at end of file diff --git a/pool/shard002/JavaScript/0014067_includes.js b/pool/shard002/JavaScript/0014067_includes.js new file mode 100644 index 0000000000000000000000000000000000000000..82a48eac66c9037aeb44b163d373dd5126792a8f --- /dev/null +++ b/pool/shard002/JavaScript/0014067_includes.js @@ -0,0 +1,20 @@ +//src: includes.tag +// free indent +riot.tag2('includes', '

', '', '', function(opts) { + this.myObj = { + foo: 'bar', + baz: 'foo' + } + this.click = function(e) { + alert('Hello!') + }.bind(this) + + this.click = function(e) + {foo ({})}.bind(this) + + this.handle = function( e ) + { + bar( {} ) + } + .bind (this) +}, '{ }'); diff --git a/pool/shard002/JavaScript/0014068_control_button_src.js b/pool/shard002/JavaScript/0014068_control_button_src.js new file mode 100644 index 0000000000000000000000000000000000000000..3d18331a4fe915459220475edafde99c6ecb4b49 --- /dev/null +++ b/pool/shard002/JavaScript/0014068_control_button_src.js @@ -0,0 +1,85 @@ +/** + * $Id: control_button_src.js,v 1.1.1.1 2009/01/07 20:08:57 lukas Exp $ + * + * @author Lukas Zurschmiede + * @copyright Copyright (c) 2001-2011, delight software gmbh. All rights reserved. + */ + +tinyMCEPopup.requireLangPack(); + +var DelightButtonFieldDialog = { + init : function() { + var t = this; + tinyMCEPopup.resizeToInnerSize(); + + if (t.__isValidSelection()) { + t.__loadValues(); + } else { + selectOption('cb_type', 'submit'); + } + }, + + close : function() { + tinyMCEPopup.close(); + }, + + insert : function() { + var t = this, ed = tinyMCEPopup.editor, f = document.forms[0]; + // Insert the contents from the input into the document + o = { + replace : t.__isValidSelection(), + type : f.cb_type.value, + value : f.ed_value.value + }; + + if (o.name == 'btn_') { + tinyMCEPopup.editor.windowManager.alert('delightform.namemandatory'); + return false; + } + + if (o.replace) { + t.__replaceElement(o); + } else { + t.__insertElement(o); + } + + // Close the Editor + tinyMCEPopup.close(); + }, + + getElem : function(id) { + return document.getElementById(id); + }, + + + /// Private functions + __isValidSelection : function() { + var n = tinyMCEPopup.editor.selection.getNode(); + return (n.nodeName && (n.nodeName == 'BUTTON')); + }, + + __loadValues : function() { + var t = this, ed = tinyMCEPopup.editor, dom = ed.dom, n = ed.selection.getNode(); + var f = document.forms[0]; + + // Set value and type + selectOption('cb_type', n.getAttribute('type')); + t.getElem('ed_value').value = n.innerHTML; + }, + + __replaceElement : function(o) { + var t = this, ed = tinyMCEPopup.editor, e = ed.selection.getNode(); + e.innerHTML = o.value; + e.setAttribute('type', o.type); + e.className = 'button_'+o.type; + }, + + __insertElement : function(o) { + var t = this, ed = tinyMCEPopup.editor, html; + + html = ''; + ed.execCommand('mceInsertContent', false, html); + } +}; + +tinyMCEPopup.onInit.add(DelightButtonFieldDialog.init, DelightButtonFieldDialog); diff --git a/pool/shard002/JavaScript/0014069_pane-changer.js b/pool/shard002/JavaScript/0014069_pane-changer.js new file mode 100644 index 0000000000000000000000000000000000000000..c5b039cbec307672a3ff5b6ff3585e17da32164b --- /dev/null +++ b/pool/shard002/JavaScript/0014069_pane-changer.js @@ -0,0 +1,35 @@ +const findNextGaps = require('../services/find-next-gaps') + +module.exports = function paneChanger (state) { + return ({ + maxAllPanes: function maxAllPanes (opts = {}) { + state.panes + .filter(p => p.id !== opts.exclude) + .forEach(p => { + const directions = ['left', 'right', 'up', 'down'] + directions.forEach(d => p.maxSize(d)) + }) + }, + findGaps: function findGaps () { + return findNextGaps(state, {x: 0, y: 0}) + }, + switchPanes: function switchPanes (firstId, secondId) { + const firstPane = state.getPane(firstId) + const secondPane = state.getPane(secondId) + const firstLocation = { + x: firstPane.x, + y: firstPane.y, + height: firstPane.height, + width: firstPane.width + } + const secondLocation = { + x: secondPane.x, + y: secondPane.y, + height: secondPane.height, + width: secondPane.width + } + firstPane.overrideLocation(secondLocation) + secondPane.overrideLocation(firstLocation) + } + }) +} diff --git a/pool/shard002/JavaScript/0014076_Gruntfile.js b/pool/shard002/JavaScript/0014076_Gruntfile.js new file mode 100644 index 0000000000000000000000000000000000000000..7081cd07c421e435ce23a622d17748e463876262 --- /dev/null +++ b/pool/shard002/JavaScript/0014076_Gruntfile.js @@ -0,0 +1,78 @@ +module.exports = function(grunt) { + + // Project configuration. + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + go: { + options: { + GOPATH: [process.env.GOPATH] + }, + release: { + output: "ct", + run_files: ["main.go"], + }, + debug: { + output: "ct", + run_files: ["main.go"], + build_flags: ["-race"] + } + + }, + jshint: { + // define the files to lint + files: ['web/**/*.js', 'web/**/*.html'], + // configure JSHint (documented at http://www.jshint.com/docs/) + options: { + curly: true, + eqeqeq: true, + eqnull: true, + bitwise: true, + immed: true, + latedef: true, + noarg: true, + nonbsp: true, + quotmark: 'single', + undef: true, + unused: false, + maxparams: 5, + browser: true, + globals: { + ct: true, + Polymer: true, + }, + extract: 'auto', + ignores: ['web/lib/**', 'web/app/**', 'web/e2e-tests/**'] + } + } + }); + + // Load the plugins + grunt.loadNpmTasks('grunt-go'); + grunt.loadNpmTasks('grunt-contrib-jshint'); + + // Default task(s). + grunt.registerTask('default', 'run', function() { + var target = 'debug'; + var opt = grunt.option('target'); + if(opt === 'release') { + target = opt; + } + grunt.task.run('run' + target); + }); + + grunt.registerTask('test', 'test', function() { + var target = 'debug'; + var opt = grunt.option('target'); + if(opt === 'release') { + target = opt; + } + grunt.task.run('test' + target); + }); + + grunt.registerTask('rundebug', ['jshint', 'go:run:debug']); + grunt.registerTask('runrelease', ['jshint', 'go:run:release']); + + grunt.registerTask('testdebug', ['jshint', 'go:test:debug']); + grunt.registerTask('testrelease', ['jshint', 'go:test:release']); + +}; \ No newline at end of file diff --git a/pool/shard002/JavaScript/0014079_navigation-animation.js b/pool/shard002/JavaScript/0014079_navigation-animation.js new file mode 100644 index 0000000000000000000000000000000000000000..b4beca62f9b3b84a56bbb81137329015a93855b8 --- /dev/null +++ b/pool/shard002/JavaScript/0014079_navigation-animation.js @@ -0,0 +1,40 @@ +(function(){ + var app = angular.module('gdgApp.navigation'); + + app.animation('.hideMenu', function () { + var parent = null; + return { + addClass: function (element) { + if (!parent) parent = angular.element(element.parent()); + parent.addClass('modalView'); + TweenMax.to(element, 1, {x: "400%", z: "-1500px", rotationY: -45}); + }, + removeClass: function (element) { + if (!parent) parent = angular.element(element.parent()); + var callback = function () { + parent.removeClass('modalView'); + }; + TweenMax.to(element, 1, {x: 0, z: 0, rotationY: 0, onComplete: callback}); + } + } + }); + + app.animation('.menuShow', function () { + var children = null; + var timeline; + return { + addClass: function (element) { + if (!children) children = element.children(); + timeline = new TimelineLite(); + for (var i = 0; i < children.length; i++) { + timeline.fromTo(angular.element(children[i]), 0.1, {x: -50, opacity: 0}, {x: 0, opacity: 1}) + } + timeline.play() + }, + removeClass: function () { + timeline.restart(); + timeline.pause(); + } + } + }); +})(); diff --git a/pool/shard002/JavaScript/0014083_set-get.js b/pool/shard002/JavaScript/0014083_set-get.js new file mode 100644 index 0000000000000000000000000000000000000000..48e2f161b0db819a563d93de95576d1594b0ac5b --- /dev/null +++ b/pool/shard002/JavaScript/0014083_set-get.js @@ -0,0 +1,61 @@ +'use strict'; + +const api = require('../src/boot'), + request = require('supertest'), + Set = require('../src/model/set'), + describe = require('mocha').describe, + it = require('mocha').it, + before = require('mocha').before; + +describe('GET /set/:code', () => { + let agent; + + before(() => { + return api.boot() + .then(api => { + // silence expected errors during test + api.log.level('FATAL'); + agent = request(api); + }) + .then(() => Set.remove({ })) + .then(() => { + Set.create([ + { + name: '52 Card Pickup', + code: '52C', + cards: [ + { + name: 'somecard', + colors: [ 'Red' ] + } + ] + } + ]); + }); + }); + + it('should return JSON', done => { + agent.get('/set/52C') + .expect('Content-Type', 'application/json') + .expect(200, done); + }); + + it('should 404 when set cannot be found', done => { + agent.get('/set/fail') + .expect(404, done); + }); + + it('should include set data', done => { + agent.get('/set/52C') + .expect({ + name: '52 Card Pickup', + code: '52C', + cards: [ + { + name: 'somecard', + colors: 'r' + } + ] + }, done); + }); +}); diff --git a/pool/shard002/JavaScript/0014084_VRScenePhoto.js b/pool/shard002/JavaScript/0014084_VRScenePhoto.js new file mode 100644 index 0000000000000000000000000000000000000000..7f594bf974465a7cc510a4e505e501e25006a43f --- /dev/null +++ b/pool/shard002/JavaScript/0014084_VRScenePhoto.js @@ -0,0 +1,78 @@ +/** + Copyright 2015 Bhautik J Joshi + + 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. +**/ + +var VRTextureDescription = require('./VRTextureDescription.js'); + +VRScenePhoto = function() { + this.scenePhoto = null; + this.textureDescription = null; + + this.init = function(scenePhoto) { + this.scenePhoto = scenePhoto; + this.textureDescription = new VRTextureDescription(); + this.textureDescription.init(scenePhoto); + }; + + this.initDict = function(dict) { + this.textureDescription = new VRTextureDescription(); + this.textureDescription.initDict(dict.textureDescription); + } + + this.populateElementCommon = function(elm) { + this.textureDescription.setElement(elm); + } + + this.isStereo = function() { + return this.textureDescription.isStereo; + } + + this.getPhotoElement = function() { + var elm = document.createElement('photo'); + this.populateElementCommon(elm); + return elm; + } + + this.getSinglePhotoVrEmbedElement = function() { + var elm = document.createElement('a'); + elm.setAttribute('class', 'vrEmbedPhoto'); + this.populateElementCommon(elm); + return elm; + } + + this.getSinglePhotoURLParams= function() { + var outstr = "?"; + outstr += "src=" + this.textureDescription.getAbsoluteTexturePath(); + outstr += "&sphereParams=" + this.textureDescription.getSphereParamsString(); + if (this.isStereo() == false) { + outstr += "&isStereo=false"; + } else { + outstr += "&isStereo=true"; + outstr += "&texParams="+this.textureDescription.getTexParamsString(); + } + + if(this.textureDescription.plane == false) { + outstr += "&plane=false"; + } else { + outstr += "&plane=true"; + outstr += "&planeOffset="+this.textureDescription.getPlaneOffsetParamsString(); + } + return outstr; + } + +}; + + +module.exports = VRScenePhoto; diff --git a/pool/shard002/JavaScript/0014086_gulpfile.js b/pool/shard002/JavaScript/0014086_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..c305ac34a09ac70f3b766f91ca08256ffb1d32fd --- /dev/null +++ b/pool/shard002/JavaScript/0014086_gulpfile.js @@ -0,0 +1,176 @@ +// Define gulp before we start +var gulp = require('gulp'); + +// Define Sass and the autoprefixer +var sass = require('gulp-sass'); +var prefix = require('gulp-autoprefixer'); + +// This is an object which defines paths for the styles. +// Can add paths for javascript or images for example +// The folder, files to look for and destination are all required for sass +var paths = { + styles: { + src: './assets/sass', + files: './assets/sass/**/*.scss', + dest: './public/stylesheets' + }, + images: { + src: './assets/images', + files: './assets/images/**/*.png', + dest: './public/images' + }, + svg: { + src: './assets/images', + files: './assets/images/**/*.svg', + dest: './public/images' + }, + javascript: { + src: './assets/javascript', + files: './assets/javascript/**/*.js', + dest: './public/javascript' + } +} + +var options = {}; +options.sass = { + outputStyle: 'compressed', + errLogToConsole: true, + // sourceMap: 'sass', + // sourceComments: 'map', + precision: 10, + imagePath: paths.images.src, + includePaths: [paths.styles.src] +}; +options.autoprefixer = { + // map: true, + from: 'asset', + to: 'style.css' +}; + +// A display error function, to format and make custom errors more uniform +// Could be combined with gulp-util or npm colors for nicer output +var displayError = function(error) { + + // Initial building up of the error + var errorString = '[' + error.plugin + ']'; + errorString += ' ' + error.message.replace("\n",''); // Removes new line at the end + + // If the error contains the filename or line number add it to the string + if(error.fileName) + errorString += ' in ' + error.fileName; + + if(error.lineNumber) + errorString += ' on line ' + error.lineNumber; + + // This will output an error like the following: + // [gulp-sass] error message in file_name on line 1 + console.error(errorString); +} + +// Setting up the sass task +gulp.task('sass', function (){ + // Taking the path from the above object + gulp.src(paths.styles.files) + // Sass options - make the output compressed and add the source map + // Also pull the include path from the paths object + .pipe(sass(options.sass)) + // Pass the compiled sass through the prefixer with defined + .pipe(prefix( + 'last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4', + options.autoprefixer + )) + // If there is an error, don't stop compiling but use the custom displayError function + .on('error', function(err){ + displayError(err); + }) + // Funally put the compiled sass into a css file + .pipe(gulp.dest(paths.styles.dest)) +}); + +// -------------------------------------------- + +var imagemin = require('gulp-imagemin'); + +gulp.task('images', function(){ + return gulp.src(paths.images.files) + .pipe(imagemin()) + .pipe(gulp.dest(paths.images.dest)); +}); + +// --------------------------------------------- + +var svgmin = require('gulp-svgmin'); + +gulp.task('svg', function() { + return gulp.src(paths.svg.files) + .pipe(svgmin()) + .pipe(gulp.dest(paths.svg.dest)); +}); + +// --------------------------------------------- + +var browserify = require('browserify'); +var source = require('vinyl-source-stream'); + +gulp.task('browserify', function() { + // gulp.src(paths.javascript.src + '/app.js') + // .pipe(browserify({ + // shim: { + // jQuery: { + // path: paths.javascript.src + '/../bower_components/jquery/dist/jquery.min.js', + // exports: '$' + // } + // } + // }).bundle()) + // //Pass desired output filename to vinyl-source-stream + // .pipe(source('bundle.js')) + // // Start piping stream to tasks! + // .pipe(gulp.dest(paths.javascript.dest)); + return browserify(paths.javascript.src + '/app.js') + .bundle() + //Pass desired output filename to vinyl-source-stream + .pipe(source('bundle.js')) + // Start piping stream to tasks! + .pipe(gulp.dest(paths.javascript.dest)); +}); + +// --------------------------------------------- + +// This is the default task - which is run when `gulp` is run +// The tasks passed in as an array are run before the tasks within the function +gulp.task('default', ['sass', 'images', 'browserify', 'svg'], function() { + // Watch the files in the paths object, and when there is a change, fun the functions in the array + gulp.watch(paths.styles.files, ['sass']) + // Also when there is a change, display what file was changed, only showing the path after the 'sass folder' + .on('change', function(evt) { + console.log( + '[watcher] File ' + evt.path.replace(/.*(?=sass)/,'') + ' was ' + evt.type + ', compiling...' + ); + }); + + gulp.watch(paths.svg.files, ['svg']) + // Also when there is a change, display what file was changed, only showing the path after the 'sass folder' + .on('change', function(evt) { + console.log( + '[watcher] File ' + evt.path.replace(/.*(?=svg)/,'') + ' was ' + evt.type + ', compiling...' + ); + }); + + gulp.watch(paths.images.files, ['images']) + // Also when there is a change, display what file was changed, only showing the path after the 'sass folder' + .on('change', function(evt) { + console.log( + '[watcher] File ' + evt.path.replace(/.*(?=png)/,'') + ' was ' + evt.type + ', compiling...' + ); + }); + + gulp.watch(paths.javascript.files, ['browserify']) + // Also when there is a change, display what file was changed, only showing the path after the 'sass folder' + .on('change', function(evt) { + console.log( + '[watcher] File ' + evt.path.replace(/.*(?=js)/,'') + ' was ' + evt.type + ', compiling...' + ); + }); +}); + +gulp.task('build', ['sass', 'images', 'browserify', 'svg']); diff --git a/pool/shard002/JavaScript/0014087_Timeline.js b/pool/shard002/JavaScript/0014087_Timeline.js new file mode 100644 index 0000000000000000000000000000000000000000..92bd7748439ad46b90359076ee5e546cddc9ac9e --- /dev/null +++ b/pool/shard002/JavaScript/0014087_Timeline.js @@ -0,0 +1,170 @@ +/* + This file is part of Rekall. + Copyright (C) 2013-2015 + + Project Manager: Clarisse Bardiot + Development & interactive design: Guillaume Jacquemin & Guillaume Marais (http://www.buzzinglight.com) + + This file was written by Guillaume Jacquemin & Guillaume Marais. + + Rekall is a free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +function Timeline() { + this.timeStart = moment(); + this.state = 0; + this.timeCurrentOffset = 0; + this.timeCurrent = 0; + + var thiss = this; + /*$(document).keyup(function(e) { + if(e.keyCode == 32) + thiss.toggle(); + if(e.keyCode == 70) + thiss.rewind(); + if(e.keyCode == 83) + thiss.rewind(120); + if(e.keyCode == 68) + thiss.play(60); + }); */ +} + +Timeline.prototype.play = function(timeCurrentOffset) { + if(timeCurrentOffset == undefined) + timeCurrentOffset = this.timeCurrent; + this.timeCurrentOffset = timeCurrentOffset; + this.timeStart = moment(); + this.state = 1; + rekall.captationVideoPlayers.play(timeCurrentOffset); +//HideFlattenTimeline rekall.updateFlattenTimeline(); + $("#timeline-play").hide(); + $("#timeline-pause").show(); +} +Timeline.prototype.stop = function() { + this.state = 0; + rekall.captationVideoPlayers.pause(); +//HideFlattenTimeline rekall.updateFlattenTimeline(); + $("#timeline-play").show(); + $("#timeline-pause").hide(); +} +Timeline.prototype.rewind = function(timeCurrentOffset) { + if(timeCurrentOffset == undefined) + timeCurrentOffset = 0; + this.timeCurrent = timeCurrentOffset; + this.timeCurrentOffset = timeCurrentOffset; + this.state = 2; + rekall.captationVideoPlayers.rewind(timeCurrentOffset); +//HideFlattenTimeline rekall.updateFlattenTimeline(); + $("#timeline-play").show(); + $("#timeline-pause").hide(); +} + +Timeline.prototype.toggle = function() { + if(this.state) + this.stop(); + else + this.play(); +} + +Timeline.prototype.update = function() { + if(rekall.sortings["horizontal"].metadataKey == "Time") { + if(!rekall.timeline.barLayer.group.visible()) { + //$("#timeline-transport").css("opacity","1"); + $("#timeline-transport").show(); + rekall.timeline.barLayer.group.setVisible(true); + } + var timeBarPoints = this.line.points(); + if((this.state) || (isNaN(timeBarPoints[0]))) { + if(isNaN(timeBarPoints[0])) + this.timeStart = moment(); + if(this.state == 2) this.state = 0; + else this.timeCurrent = this.timeCurrentOffset + moment().diff(this.timeStart) / 1000; + timeBarPoints[0] = timeBarPoints[2] = Sorting.positionForTime(this.timeCurrent) * Sorting.size; + this.line.setPoints(timeBarPoints); + this.text.setText((this.timeCurrent+"").toHHMMSSmmm()); + this.text.setX(timeBarPoints[0] + 3); + +//HideFlattenTimeline rekall.updateFlattenTimeline(); + return true; + } + } + else if(rekall.timeline.barLayer.group.visible()) { + rekall.timeline.barLayer.group.setVisible(false); + //$("#timeline-transport").css("opacity",".2"); + $("#timeline-transport").hide(); + return true; + } + return false; +} + +Timeline.prototype.updateFlattenTimeline = function() { +//HideFlattenTimeline +/* + var categories = rekall.sortings["horizontal"].categories; + if(rekall.sortings["horizontal"].metadataKey == "Time") + categories = {time: {tags: Tags.flattenTimelineTags}}; + + for (var key in categories) { + for (var index in categories[key].tags) { + var tag = categories[key].tags[index]; + if(tag.flattenTimelineDom != undefined) { + var progress = 0; + var timeEndExtended = tag.timeStart + max(2, tag.timeEnd - tag.timeStart); + + if(rekall.sortings["horizontal"].metadataKey == "Time") { + if(this.timeCurrent <= tag.timeStart) + progress = this.timeCurrent - tag.timeStart; + else if((tag.timeStart < this.timeCurrent) && (this.timeCurrent < timeEndExtended)) + progress = (this.timeCurrent - tag.timeStart) / (timeEndExtended - tag.timeStart); + else + progress = undefined; + } + else + timeEndExtended = tag.timeEnd; + + var dom = tag.flattenTimelineDom; + if(progress == undefined) { + dom.slideUp(); + dom.find(".flattentimeline_counter").hide(); + } + else { + if(timeEndExtended == tag.timeEnd) + dom.find(".flattentimeline_opacifiant").css("width", constrain(progress, 0, 1)*100 + "%"); + else + dom.find(".flattentimeline_opacifiant").css("width", "100%"); + + var tagCounter = tag.flattenTimelineDom.find(".flattentimeline_counter"); + if((0 <= progress) && (progress < 1)) { + dom.css("opacity", 1.0).slideDown(); + tagCounter.hide(); + } + else if((-5 <= progress) && (progress <= 0)) { + dom.css("opacity", 0.5).slideDown(); + tagCounter.text(ceil(-progress)); + tagCounter.show(); + } + else if(-9999999 < progress) { + dom.css("opacity", 0.1).slideDown(); + tagCounter.hide(); + } + else { + dom.css("opacity", 0.1).hide(); + tagCounter.hide(); + } + } + } + } + } */ +} + diff --git a/pool/shard002/JavaScript/0014089_GuidesController.js b/pool/shard002/JavaScript/0014089_GuidesController.js new file mode 100644 index 0000000000000000000000000000000000000000..c5c94b824d9959889e123c4b37b9c88b82b38242 --- /dev/null +++ b/pool/shard002/JavaScript/0014089_GuidesController.js @@ -0,0 +1,27 @@ +angular + .module('smartris') + .controller('GuidesController', GuidesController); + +GuidesController.$inject = ['$scope', 'GuideService', 'localStorageService']; + +function GuidesController($scope, GuideService, localStorageService) { + var vm = this; + + vm.alertSuccess = false; + + $scope.save = function() { + var newGuide = new GuideService({ + patient: localStorageService.get('patient'), + procedures: localStorageService.get('procedures'), + provider: 1 + }); + + GuideService.save(newGuide, function(data){ + if (data.success) { + vm.alertSuccess = true; + localStorageService.remove('patient'); + localStorageService.remove('procedures'); + } + }); + }; +} \ No newline at end of file diff --git a/pool/shard002/JavaScript/0014091_custom.js b/pool/shard002/JavaScript/0014091_custom.js new file mode 100644 index 0000000000000000000000000000000000000000..a43672bf6c8baa4aa7e764e654b63d8f5f059ca1 --- /dev/null +++ b/pool/shard002/JavaScript/0014091_custom.js @@ -0,0 +1,100 @@ + + +$.fn.exists = function () { + return this.length > 0 ? this : false; +} + +$(document).ready(function(){ + + /*++++++++++++++++++++++++++++++++++++ + tooltips + ++++++++++++++++++++++++++++++++++++++*/ + $(".tooltips").tooltip(); + + + /*++++++++++++++++++++++++++++++++++++++++++++++ + custom scrolls with perfectScroll plugin + ++++++++++++++++++++++++++++++++++++++++++++++++*/ + $("#main-nav").perfectScrollbar({ + wheelPropagation:true, + wheelSpeed:80 + }); + + + /*++++++++++++++++++++++++++++++++++++ + click event on ul.timeline titles + ++++++++++++++++++++++++++++++++++++++*/ + $("ul.timeline").children().eq(0) + .find(".text").slideDown() + .addClass("open"); + + $("ul.timeline").on("click","li", function(){ + $this = $(this); + $this.find(".text").slideDown(); + $this.addClass("open"); + $this.siblings('li.open').find(".text").slideUp(); + $this.siblings('li').removeClass("open"); + }).on('mouseenter','li',function(){ + $this = $(this); + var anim = new TweenLite($(this).find(".subject"),0.4,{'padding-left':20, paused:true}); + ($this.hasClass('open')) || anim.play(); + }).on('mouseleave','li',function(){ + var anim = new TweenLite($(this).find(".subject"),0.2,{'padding-left':0}); + }); + + + /*++++++++++++++++++++++++++++++++++++ + ul-withdetails details show/hide + ++++++++++++++++++++++++++++++++++++++*/ + $("ul.ul-withdetails li").find(".row").on('click',function(){ + // $this = $(this); + $(this).closest("li").find(".details") + .stop(true, true) + .animate({ + height:"toggle", + opacity:"toggle" + },300); + }).on('mouseenter',function(){ + $this = $(this); + var anim = new TweenLite($(this).closest("li").find(".imageoverlay"),0.4,{left:0}); + }).on('mouseleave', function(){ + var anim = new TweenLite($(this).closest("li").find(".imageoverlay"),0.2,{left:"-102%"}); + }); + + + + /*++++++++++++++++++++++++++++++++++++ + Publications page categorization + ++++++++++++++++++++++++++++++++++++++*/ + + + $('div#pub-grid').mixitup({ + layoutMode: 'list', + easing : 'snap', + showOnLoad: 'all', + transitionSpeed :600, + onMixEnd: function(){ + $(".tooltips").tooltip(); + } + }).on('click','div.pubmain',function(){ + var $this = $(this), + $item = $this.closest(".item"); + + $item.find('div.pubdetails').slideToggle(function(){ + $this.children("i").toggleClass('icon-collapse-alt icon-expand-alt'); + },function(){ + $this.children("i").toggleClass('icon-expand-alt icon-collapse-alt'); + }); + }); + + $( '#cd-dropdown' ).dropdownit( { + gutter : 0 + } ); + + $("[name=cd-dropdown]").on("change",function(){ + var item = this.value; + $('div#pub-grid').mixitup('filter',item); + }); + +}); +