repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
markogresak/DefinitelyTyped | types/carbon__icons-react/lib/reply--all/32.d.ts | 59 | import { ReplyAll32 } from "../../";
export = ReplyAll32;
| mit |
brunolauze/openpegasus-providers-old | src/Providers/UNIXProviders/SwitchService/UNIX_SwitchService_VMS.hpp | 12290 | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
UNIX_SwitchService::UNIX_SwitchService(void)
{
}
UNIX_SwitchService::~UNIX_SwitchService(void)
{
}
Boolean UNIX_SwitchService::getInstanceID(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INSTANCE_ID, getInstanceID());
return true;
}
String UNIX_SwitchService::getInstanceID() const
{
return String ("");
}
Boolean UNIX_SwitchService::getCaption(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_CAPTION, getCaption());
return true;
}
String UNIX_SwitchService::getCaption() const
{
return String ("");
}
Boolean UNIX_SwitchService::getDescription(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_DESCRIPTION, getDescription());
return true;
}
String UNIX_SwitchService::getDescription() const
{
return String ("");
}
Boolean UNIX_SwitchService::getElementName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ELEMENT_NAME, getElementName());
return true;
}
String UNIX_SwitchService::getElementName() const
{
return String("SwitchService");
}
Boolean UNIX_SwitchService::getInstallDate(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_INSTALL_DATE, getInstallDate());
return true;
}
CIMDateTime UNIX_SwitchService::getInstallDate() const
{
struct tm* clock; // create a time structure
time_t val = time(NULL);
clock = gmtime(&(val)); // Get the last modified time and put it into the time structure
return CIMDateTime(
clock->tm_year + 1900,
clock->tm_mon + 1,
clock->tm_mday,
clock->tm_hour,
clock->tm_min,
clock->tm_sec,
0,0,
clock->tm_gmtoff);
}
Boolean UNIX_SwitchService::getName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_NAME, getName());
return true;
}
String UNIX_SwitchService::getName() const
{
return String ("");
}
Boolean UNIX_SwitchService::getOperationalStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_OPERATIONAL_STATUS, getOperationalStatus());
return true;
}
Array<Uint16> UNIX_SwitchService::getOperationalStatus() const
{
Array<Uint16> as;
return as;
}
Boolean UNIX_SwitchService::getStatusDescriptions(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_STATUS_DESCRIPTIONS, getStatusDescriptions());
return true;
}
Array<String> UNIX_SwitchService::getStatusDescriptions() const
{
Array<String> as;
return as;
}
Boolean UNIX_SwitchService::getStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_STATUS, getStatus());
return true;
}
String UNIX_SwitchService::getStatus() const
{
return String(DEFAULT_STATUS);
}
Boolean UNIX_SwitchService::getHealthState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_HEALTH_STATE, getHealthState());
return true;
}
Uint16 UNIX_SwitchService::getHealthState() const
{
return Uint16(DEFAULT_HEALTH_STATE);
}
Boolean UNIX_SwitchService::getCommunicationStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_COMMUNICATION_STATUS, getCommunicationStatus());
return true;
}
Uint16 UNIX_SwitchService::getCommunicationStatus() const
{
return Uint16(0);
}
Boolean UNIX_SwitchService::getDetailedStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_DETAILED_STATUS, getDetailedStatus());
return true;
}
Uint16 UNIX_SwitchService::getDetailedStatus() const
{
return Uint16(0);
}
Boolean UNIX_SwitchService::getOperatingStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_OPERATING_STATUS, getOperatingStatus());
return true;
}
Uint16 UNIX_SwitchService::getOperatingStatus() const
{
return Uint16(DEFAULT_OPERATING_STATUS);
}
Boolean UNIX_SwitchService::getPrimaryStatus(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_PRIMARY_STATUS, getPrimaryStatus());
return true;
}
Uint16 UNIX_SwitchService::getPrimaryStatus() const
{
return Uint16(DEFAULT_PRIMARY_STATUS);
}
Boolean UNIX_SwitchService::getEnabledState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ENABLED_STATE, getEnabledState());
return true;
}
Uint16 UNIX_SwitchService::getEnabledState() const
{
return Uint16(DEFAULT_ENABLED_STATE);
}
Boolean UNIX_SwitchService::getOtherEnabledState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_OTHER_ENABLED_STATE, getOtherEnabledState());
return true;
}
String UNIX_SwitchService::getOtherEnabledState() const
{
return String ("");
}
Boolean UNIX_SwitchService::getRequestedState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_REQUESTED_STATE, getRequestedState());
return true;
}
Uint16 UNIX_SwitchService::getRequestedState() const
{
return Uint16(0);
}
Boolean UNIX_SwitchService::getEnabledDefault(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_ENABLED_DEFAULT, getEnabledDefault());
return true;
}
Uint16 UNIX_SwitchService::getEnabledDefault() const
{
return Uint16(0);
}
Boolean UNIX_SwitchService::getTimeOfLastStateChange(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_TIME_OF_LAST_STATE_CHANGE, getTimeOfLastStateChange());
return true;
}
CIMDateTime UNIX_SwitchService::getTimeOfLastStateChange() const
{
struct tm* clock; // create a time structure
time_t val = time(NULL);
clock = gmtime(&(val)); // Get the last modified time and put it into the time structure
return CIMDateTime(
clock->tm_year + 1900,
clock->tm_mon + 1,
clock->tm_mday,
clock->tm_hour,
clock->tm_min,
clock->tm_sec,
0,0,
clock->tm_gmtoff);
}
Boolean UNIX_SwitchService::getAvailableRequestedStates(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_AVAILABLE_REQUESTED_STATES, getAvailableRequestedStates());
return true;
}
Array<Uint16> UNIX_SwitchService::getAvailableRequestedStates() const
{
Array<Uint16> as;
return as;
}
Boolean UNIX_SwitchService::getTransitioningToState(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_TRANSITIONING_TO_STATE, getTransitioningToState());
return true;
}
Uint16 UNIX_SwitchService::getTransitioningToState() const
{
return Uint16(0);
}
Boolean UNIX_SwitchService::getSystemCreationClassName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_SYSTEM_CREATION_CLASS_NAME, getSystemCreationClassName());
return true;
}
String UNIX_SwitchService::getSystemCreationClassName() const
{
return String("UNIX_ComputerSystem");
}
Boolean UNIX_SwitchService::getSystemName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_SYSTEM_NAME, getSystemName());
return true;
}
String UNIX_SwitchService::getSystemName() const
{
return CIMHelper::HostName;
}
Boolean UNIX_SwitchService::getCreationClassName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_CREATION_CLASS_NAME, getCreationClassName());
return true;
}
String UNIX_SwitchService::getCreationClassName() const
{
return String("UNIX_SwitchService");
}
Boolean UNIX_SwitchService::getPrimaryOwnerName(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_PRIMARY_OWNER_NAME, getPrimaryOwnerName());
return true;
}
String UNIX_SwitchService::getPrimaryOwnerName() const
{
return String ("");
}
Boolean UNIX_SwitchService::getPrimaryOwnerContact(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_PRIMARY_OWNER_CONTACT, getPrimaryOwnerContact());
return true;
}
String UNIX_SwitchService::getPrimaryOwnerContact() const
{
return String ("");
}
Boolean UNIX_SwitchService::getStartMode(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_START_MODE, getStartMode());
return true;
}
String UNIX_SwitchService::getStartMode() const
{
return String ("");
}
Boolean UNIX_SwitchService::getStarted(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_STARTED, getStarted());
return true;
}
Boolean UNIX_SwitchService::getStarted() const
{
return Boolean(false);
}
Boolean UNIX_SwitchService::getKeywords(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_KEYWORDS, getKeywords());
return true;
}
Array<String> UNIX_SwitchService::getKeywords() const
{
Array<String> as;
return as;
}
Boolean UNIX_SwitchService::getServiceURL(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_SERVICE_U_R_L, getServiceURL());
return true;
}
String UNIX_SwitchService::getServiceURL() const
{
return String ("");
}
Boolean UNIX_SwitchService::getStartupConditions(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_STARTUP_CONDITIONS, getStartupConditions());
return true;
}
Array<String> UNIX_SwitchService::getStartupConditions() const
{
Array<String> as;
return as;
}
Boolean UNIX_SwitchService::getStartupParameters(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_STARTUP_PARAMETERS, getStartupParameters());
return true;
}
Array<String> UNIX_SwitchService::getStartupParameters() const
{
Array<String> as;
return as;
}
Boolean UNIX_SwitchService::getProtocolType(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_PROTOCOL_TYPE, getProtocolType());
return true;
}
Uint16 UNIX_SwitchService::getProtocolType() const
{
return Uint16(0);
}
Boolean UNIX_SwitchService::getOtherProtocolType(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_OTHER_PROTOCOL_TYPE, getOtherProtocolType());
return true;
}
String UNIX_SwitchService::getOtherProtocolType() const
{
return String ("");
}
Boolean UNIX_SwitchService::getBridgeAddress(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_BRIDGE_ADDRESS, getBridgeAddress());
return true;
}
String UNIX_SwitchService::getBridgeAddress() const
{
return String ("");
}
Boolean UNIX_SwitchService::getNumPorts(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_NUM_PORTS, getNumPorts());
return true;
}
Uint16 UNIX_SwitchService::getNumPorts() const
{
return Uint16(0);
}
Boolean UNIX_SwitchService::getBridgeType(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_BRIDGE_TYPE, getBridgeType());
return true;
}
Uint8 UNIX_SwitchService::getBridgeType() const
{
return Uint8(0);
}
Boolean UNIX_SwitchService::getBridgeAddressType(CIMProperty &p) const
{
p = CIMProperty(PROPERTY_BRIDGE_ADDRESS_TYPE, getBridgeAddressType());
return true;
}
Uint16 UNIX_SwitchService::getBridgeAddressType() const
{
return Uint16(0);
}
Boolean UNIX_SwitchService::initialize()
{
return false;
}
Boolean UNIX_SwitchService::load(int &pIndex)
{
return false;
}
Boolean UNIX_SwitchService::finalize()
{
return false;
}
Boolean UNIX_SwitchService::find(Array<CIMKeyBinding> &kbArray)
{
CIMKeyBinding kb;
String systemCreationClassNameKey;
String systemNameKey;
String creationClassNameKey;
String nameKey;
for(Uint32 i = 0; i < kbArray.size(); i++)
{
kb = kbArray[i];
CIMName keyName = kb.getName();
if (keyName.equal(PROPERTY_SYSTEM_CREATION_CLASS_NAME)) systemCreationClassNameKey = kb.getValue();
else if (keyName.equal(PROPERTY_SYSTEM_NAME)) systemNameKey = kb.getValue();
else if (keyName.equal(PROPERTY_CREATION_CLASS_NAME)) creationClassNameKey = kb.getValue();
else if (keyName.equal(PROPERTY_NAME)) nameKey = kb.getValue();
}
/* EXecute find with extracted keys */
return false;
}
| mit |
VelocityRa/scummvm | backends/platform/iphone/osys_events.cpp | 13276 | /* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
// Disable symbol overrides so that we can use system headers.
#define FORBIDDEN_SYMBOL_ALLOW_ALL
#include "gui/message.h"
#include "common/translation.h"
#include "backends/platform/iphone/osys_main.h"
static const int kQueuedInputEventDelay = 50;
bool OSystem_IPHONE::pollEvent(Common::Event &event) {
//printf("pollEvent()\n");
long curTime = getMillis();
if (_timerCallback && (curTime >= _timerCallbackNext)) {
_timerCallback(_timerCallbackTimer);
_timerCallbackNext = curTime + _timerCallbackTimer;
}
if (_queuedInputEvent.type != Common::EVENT_INVALID && curTime >= _queuedEventTime) {
event = _queuedInputEvent;
_queuedInputEvent.type = Common::EVENT_INVALID;
return true;
}
InternalEvent internalEvent;
if (iPhone_fetchEvent(&internalEvent)) {
switch (internalEvent.type) {
case kInputMouseDown:
if (!handleEvent_mouseDown(event, internalEvent.value1, internalEvent.value2))
return false;
break;
case kInputMouseUp:
if (!handleEvent_mouseUp(event, internalEvent.value1, internalEvent.value2))
return false;
break;
case kInputMouseDragged:
if (!handleEvent_mouseDragged(event, internalEvent.value1, internalEvent.value2))
return false;
break;
case kInputMouseSecondDragged:
if (!handleEvent_mouseSecondDragged(event, internalEvent.value1, internalEvent.value2))
return false;
break;
case kInputMouseSecondDown:
_secondaryTapped = true;
if (!handleEvent_secondMouseDown(event, internalEvent.value1, internalEvent.value2))
return false;
break;
case kInputMouseSecondUp:
_secondaryTapped = false;
if (!handleEvent_secondMouseUp(event, internalEvent.value1, internalEvent.value2))
return false;
break;
case kInputOrientationChanged:
handleEvent_orientationChanged(internalEvent.value1);
return false;
break;
case kInputApplicationSuspended:
suspendLoop();
return false;
break;
case kInputKeyPressed:
handleEvent_keyPressed(event, internalEvent.value1);
break;
case kInputSwipe:
if (!handleEvent_swipe(event, internalEvent.value1))
return false;
break;
default:
break;
}
return true;
}
return false;
}
bool OSystem_IPHONE::handleEvent_mouseDown(Common::Event &event, int x, int y) {
//printf("Mouse down at (%u, %u)\n", x, y);
// Workaround: kInputMouseSecondToggled isn't always sent when the
// secondary finger is lifted. Need to make sure we get out of that mode.
_secondaryTapped = false;
if (_touchpadModeEnabled) {
_lastPadX = x;
_lastPadY = y;
} else
warpMouse(x, y);
if (_mouseClickAndDragEnabled) {
event.type = Common::EVENT_LBUTTONDOWN;
event.mouse.x = _videoContext->mouseX;
event.mouse.y = _videoContext->mouseY;
return true;
} else {
_lastMouseDown = getMillis();
}
return false;
}
bool OSystem_IPHONE::handleEvent_mouseUp(Common::Event &event, int x, int y) {
//printf("Mouse up at (%u, %u)\n", x, y);
if (_secondaryTapped) {
_secondaryTapped = false;
if (!handleEvent_secondMouseUp(event, x, y))
return false;
} else if (_mouseClickAndDragEnabled) {
event.type = Common::EVENT_LBUTTONUP;
event.mouse.x = _videoContext->mouseX;
event.mouse.y = _videoContext->mouseY;
} else {
if (getMillis() - _lastMouseDown < 250) {
event.type = Common::EVENT_LBUTTONDOWN;
event.mouse.x = _videoContext->mouseX;
event.mouse.y = _videoContext->mouseY;
_queuedInputEvent.type = Common::EVENT_LBUTTONUP;
_queuedInputEvent.mouse.x = _videoContext->mouseX;
_queuedInputEvent.mouse.y = _videoContext->mouseY;
_lastMouseTap = getMillis();
_queuedEventTime = _lastMouseTap + kQueuedInputEventDelay;
} else
return false;
}
return true;
}
bool OSystem_IPHONE::handleEvent_secondMouseDown(Common::Event &event, int x, int y) {
_lastSecondaryDown = getMillis();
_gestureStartX = x;
_gestureStartY = y;
if (_mouseClickAndDragEnabled) {
event.type = Common::EVENT_LBUTTONUP;
event.mouse.x = _videoContext->mouseX;
event.mouse.y = _videoContext->mouseY;
_queuedInputEvent.type = Common::EVENT_RBUTTONDOWN;
_queuedInputEvent.mouse.x = _videoContext->mouseX;
_queuedInputEvent.mouse.y = _videoContext->mouseY;
} else
return false;
return true;
}
bool OSystem_IPHONE::handleEvent_secondMouseUp(Common::Event &event, int x, int y) {
int curTime = getMillis();
if (curTime - _lastSecondaryDown < 400) {
//printf("Right tap!\n");
if (curTime - _lastSecondaryTap < 400 && !_videoContext->overlayVisible) {
//printf("Right escape!\n");
event.type = Common::EVENT_KEYDOWN;
_queuedInputEvent.type = Common::EVENT_KEYUP;
event.kbd.flags = _queuedInputEvent.kbd.flags = 0;
event.kbd.keycode = _queuedInputEvent.kbd.keycode = Common::KEYCODE_ESCAPE;
event.kbd.ascii = _queuedInputEvent.kbd.ascii = Common::ASCII_ESCAPE;
_queuedEventTime = curTime + kQueuedInputEventDelay;
_lastSecondaryTap = 0;
} else if (!_mouseClickAndDragEnabled) {
//printf("Rightclick!\n");
event.type = Common::EVENT_RBUTTONDOWN;
event.mouse.x = _videoContext->mouseX;
event.mouse.y = _videoContext->mouseY;
_queuedInputEvent.type = Common::EVENT_RBUTTONUP;
_queuedInputEvent.mouse.x = _videoContext->mouseX;
_queuedInputEvent.mouse.y = _videoContext->mouseY;
_lastSecondaryTap = curTime;
_queuedEventTime = curTime + kQueuedInputEventDelay;
} else {
//printf("Right nothing!\n");
return false;
}
}
if (_mouseClickAndDragEnabled) {
event.type = Common::EVENT_RBUTTONUP;
event.mouse.x = _videoContext->mouseX;
event.mouse.y = _videoContext->mouseY;
}
return true;
}
bool OSystem_IPHONE::handleEvent_mouseDragged(Common::Event &event, int x, int y) {
if (_lastDragPosX == x && _lastDragPosY == y)
return false;
_lastDragPosX = x;
_lastDragPosY = y;
//printf("Mouse dragged at (%u, %u)\n", x, y);
int mouseNewPosX;
int mouseNewPosY;
if (_touchpadModeEnabled) {
int deltaX = _lastPadX - x;
int deltaY = _lastPadY - y;
_lastPadX = x;
_lastPadY = y;
mouseNewPosX = (int)(_videoContext->mouseX - deltaX / 0.5f);
mouseNewPosY = (int)(_videoContext->mouseY - deltaY / 0.5f);
int widthCap = _videoContext->overlayVisible ? _videoContext->overlayWidth : _videoContext->screenWidth;
int heightCap = _videoContext->overlayVisible ? _videoContext->overlayHeight : _videoContext->screenHeight;
if (mouseNewPosX < 0)
mouseNewPosX = 0;
else if (mouseNewPosX > widthCap)
mouseNewPosX = widthCap;
if (mouseNewPosY < 0)
mouseNewPosY = 0;
else if (mouseNewPosY > heightCap)
mouseNewPosY = heightCap;
} else {
mouseNewPosX = x;
mouseNewPosY = y;
}
event.type = Common::EVENT_MOUSEMOVE;
event.mouse.x = mouseNewPosX;
event.mouse.y = mouseNewPosY;
warpMouse(mouseNewPosX, mouseNewPosY);
return true;
}
bool OSystem_IPHONE::handleEvent_mouseSecondDragged(Common::Event &event, int x, int y) {
if (_gestureStartX == -1 || _gestureStartY == -1) {
return false;
}
static const int kNeededLength = 100;
static const int kMaxDeviation = 20;
int vecX = (x - _gestureStartX);
int vecY = (y - _gestureStartY);
int absX = abs(vecX);
int absY = abs(vecY);
//printf("(%d, %d)\n", vecX, vecY);
if (absX >= kNeededLength || absY >= kNeededLength) { // Long enough gesture to react upon.
_gestureStartX = -1;
_gestureStartY = -1;
if (absX < kMaxDeviation && vecY >= kNeededLength) {
// Swipe down
event.type = Common::EVENT_MAINMENU;
_queuedInputEvent.type = Common::EVENT_INVALID;
_queuedEventTime = getMillis() + kQueuedInputEventDelay;
return true;
}
if (absX < kMaxDeviation && -vecY >= kNeededLength) {
// Swipe up
_mouseClickAndDragEnabled = !_mouseClickAndDragEnabled;
const char *dialogMsg;
if (_mouseClickAndDragEnabled) {
_touchpadModeEnabled = false;
dialogMsg = _("Mouse-click-and-drag mode enabled.");
} else
dialogMsg = _("Mouse-click-and-drag mode disabled.");
GUI::TimedMessageDialog dialog(dialogMsg, 1500);
dialog.runModal();
return false;
}
if (absY < kMaxDeviation && vecX >= kNeededLength) {
// Swipe right
_touchpadModeEnabled = !_touchpadModeEnabled;
const char *dialogMsg;
if (_touchpadModeEnabled)
dialogMsg = _("Touchpad mode enabled.");
else
dialogMsg = _("Touchpad mode disabled.");
GUI::TimedMessageDialog dialog(dialogMsg, 1500);
dialog.runModal();
return false;
}
if (absY < kMaxDeviation && -vecX >= kNeededLength) {
// Swipe left
return false;
}
}
return false;
}
void OSystem_IPHONE::handleEvent_orientationChanged(int orientation) {
//printf("Orientation: %i\n", orientation);
ScreenOrientation newOrientation;
switch (orientation) {
case 1:
newOrientation = kScreenOrientationPortrait;
break;
case 3:
newOrientation = kScreenOrientationLandscape;
break;
case 4:
newOrientation = kScreenOrientationFlippedLandscape;
break;
default:
return;
}
if (_screenOrientation != newOrientation) {
_screenOrientation = newOrientation;
updateOutputSurface();
dirtyFullScreen();
if (_videoContext->overlayVisible)
dirtyFullOverlayScreen();
updateScreen();
}
}
void OSystem_IPHONE::handleEvent_keyPressed(Common::Event &event, int keyPressed) {
int ascii = keyPressed;
//printf("key: %i\n", keyPressed);
// We remap some of the iPhone keyboard keys.
// The first ten here are the row of symbols below the numeric keys.
switch (keyPressed) {
case 45:
keyPressed = Common::KEYCODE_F1;
ascii = Common::ASCII_F1;
break;
case 47:
keyPressed = Common::KEYCODE_F2;
ascii = Common::ASCII_F2;
break;
case 58:
keyPressed = Common::KEYCODE_F3;
ascii = Common::ASCII_F3;
break;
case 59:
keyPressed = Common::KEYCODE_F4;
ascii = Common::ASCII_F4;
break;
case 40:
keyPressed = Common::KEYCODE_F5;
ascii = Common::ASCII_F5;
break;
case 41:
keyPressed = Common::KEYCODE_F6;
ascii = Common::ASCII_F6;
break;
case 36:
keyPressed = Common::KEYCODE_F7;
ascii = Common::ASCII_F7;
break;
case 38:
keyPressed = Common::KEYCODE_F8;
ascii = Common::ASCII_F8;
break;
case 64:
keyPressed = Common::KEYCODE_F9;
ascii = Common::ASCII_F9;
break;
case 34:
keyPressed = Common::KEYCODE_F10;
ascii = Common::ASCII_F10;
break;
case 10:
keyPressed = Common::KEYCODE_RETURN;
ascii = Common::ASCII_RETURN;
break;
}
event.type = Common::EVENT_KEYDOWN;
_queuedInputEvent.type = Common::EVENT_KEYUP;
event.kbd.flags = _queuedInputEvent.kbd.flags = 0;
event.kbd.keycode = _queuedInputEvent.kbd.keycode = (Common::KeyCode)keyPressed;
event.kbd.ascii = _queuedInputEvent.kbd.ascii = ascii;
_queuedEventTime = getMillis() + kQueuedInputEventDelay;
}
bool OSystem_IPHONE::handleEvent_swipe(Common::Event &event, int direction) {
Common::KeyCode keycode = Common::KEYCODE_INVALID;
switch (_screenOrientation) {
case kScreenOrientationPortrait:
switch ((UIViewSwipeDirection)direction) {
case kUIViewSwipeUp:
keycode = Common::KEYCODE_UP;
break;
case kUIViewSwipeDown:
keycode = Common::KEYCODE_DOWN;
break;
case kUIViewSwipeLeft:
keycode = Common::KEYCODE_LEFT;
break;
case kUIViewSwipeRight:
keycode = Common::KEYCODE_RIGHT;
break;
default:
return false;
}
break;
case kScreenOrientationLandscape:
switch ((UIViewSwipeDirection)direction) {
case kUIViewSwipeUp:
keycode = Common::KEYCODE_LEFT;
break;
case kUIViewSwipeDown:
keycode = Common::KEYCODE_RIGHT;
break;
case kUIViewSwipeLeft:
keycode = Common::KEYCODE_DOWN;
break;
case kUIViewSwipeRight:
keycode = Common::KEYCODE_UP;
break;
default:
return false;
}
break;
case kScreenOrientationFlippedLandscape:
switch ((UIViewSwipeDirection)direction) {
case kUIViewSwipeUp:
keycode = Common::KEYCODE_RIGHT;
break;
case kUIViewSwipeDown:
keycode = Common::KEYCODE_LEFT;
break;
case kUIViewSwipeLeft:
keycode = Common::KEYCODE_UP;
break;
case kUIViewSwipeRight:
keycode = Common::KEYCODE_DOWN;
break;
default:
return false;
}
break;
}
event.kbd.keycode = _queuedInputEvent.kbd.keycode = keycode;
event.kbd.ascii = _queuedInputEvent.kbd.ascii = 0;
event.type = Common::EVENT_KEYDOWN;
_queuedInputEvent.type = Common::EVENT_KEYUP;
event.kbd.flags = _queuedInputEvent.kbd.flags = 0;
_queuedEventTime = getMillis() + kQueuedInputEventDelay;
return true;
}
| gpl-2.0 |
htakeo/drupal8 | modules/contrib/rules/src/Plugin/Condition/UserHasEntityFieldAccess.php | 3408 | <?php
namespace Drupal\rules\Plugin\Condition;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\rules\Core\RulesConditionBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a 'User has entity field access' condition.
*
* @Condition(
* id = "rules_entity_field_access",
* label = @Translation("User has entity field access"),
* category = @Translation("User"),
* context = {
* "entity" = @ContextDefinition("entity",
* label = @Translation("Entity")
* ),
* "field" = @ContextDefinition("string",
* label = @Translation("Field")
* ),
* "operation" = @ContextDefinition("string",
* label = @Translation("Operation")
* ),
* "user" = @ContextDefinition("entity:user",
* label = @Translation("User")
* )
* }
* )
*
* @todo: Add access callback information from Drupal 7.
*/
class UserHasEntityFieldAccess extends RulesConditionBase implements ContainerFactoryPluginInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a UserHasEntityFieldAccess object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin ID for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager')
);
}
/**
* Evaluate if the user has access to the field of an entity.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity to check access on.
* @param string $field
* The name of the field to check access on.
* @param string $operation
* The operation access should be checked for. Usually one of "view" or
* "edit".
* @param \Drupal\Core\Session\AccountInterface $user
* The user account to test access against.
*
* @return bool
* TRUE if the user has access to the field on the entity, FALSE otherwise.
*/
protected function doEvaluate(ContentEntityInterface $entity, $field, $operation, AccountInterface $user) {
if (!$entity->hasField($field)) {
return FALSE;
}
$access = $this->entityTypeManager->getAccessControlHandler($entity->getEntityTypeId());
if (!$access->access($entity, $operation, $user)) {
return FALSE;
}
$definition = $entity->getFieldDefinition($field);
$items = $entity->get($field);
return $access->fieldAccess($operation, $definition, $user, $items);
}
}
| gpl-2.0 |
joshuaspence/ThesisCode | MATLAB/Lib/matlab_bgl-4.0.1/libmbgl/boost1.36/include/boost/iostreams/checked_operations.hpp | 4469 | // (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
// (C) Copyright 2005-2007 Jonathan Turkanis
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
// See http://www.boost.org/libs/iostreams for documentation.
// Contains implementations of get, read, put, write and seek which
// check a device's mode at runtime instead of compile time.
#ifndef BOOST_IOSTREAMS_DETAIL_CHECKED_OPERATIONS_HPP_INCLUDED
#define BOOST_IOSTREAMS_DETAIL_CHECKED_OPERATIONS_HPP_INCLUDED
#include <boost/iostreams/categories.hpp>
#include <boost/iostreams/detail/dispatch.hpp>
#include <boost/iostreams/detail/error.hpp>
#include <boost/iostreams/get.hpp>
#include <boost/iostreams/put.hpp>
#include <boost/iostreams/read.hpp>
#include <boost/iostreams/seek.hpp>
#include <boost/iostreams/traits.hpp>
#include <boost/iostreams/write.hpp>
// Must come last.
#include <boost/iostreams/detail/config/disable_warnings.hpp> // MSVC.
namespace boost { namespace iostreams {
namespace detail {
template<typename T>
struct read_write_if_impl;
template<typename T>
struct seek_if_impl;
} // End namespace detail.
template<typename T>
typename int_type_of<T>::type get_if(T& t)
{
typedef typename detail::dispatch<T, input, output>::type tag;
return detail::read_write_if_impl<tag>::get(t);
}
template<typename T>
inline std::streamsize
read_if(T& t, typename char_type_of<T>::type* s, std::streamsize n)
{
typedef typename detail::dispatch<T, input, output>::type tag;
return detail::read_write_if_impl<tag>::read(t, s, n);
}
template<typename T>
bool put_if(T& t, typename char_type_of<T>::type c)
{
typedef typename detail::dispatch<T, output, input>::type tag;
return detail::read_write_if_impl<tag>::put(t, c);
}
template<typename T>
inline std::streamsize write_if
(T& t, const typename char_type_of<T>::type* s, std::streamsize n)
{
typedef typename detail::dispatch<T, output, input>::type tag;
return detail::read_write_if_impl<tag>::write(t, s, n);
}
template<typename T>
inline std::streampos
seek_if( T& t, stream_offset off, BOOST_IOS::seekdir way,
BOOST_IOS::openmode which = BOOST_IOS::in | BOOST_IOS::out )
{
using namespace detail;
typedef typename dispatch<T, random_access, any_tag>::type tag;
return seek_if_impl<tag>::seek(t, off, way, which);
}
namespace detail {
//------------------Specializations of read_write_if_impl---------------------//
template<>
struct read_write_if_impl<input> {
template<typename T>
static typename int_type_of<T>::type get(T& t)
{ return iostreams::get(t); }
template<typename T>
static std::streamsize
read(T& t, typename char_type_of<T>::type* s, std::streamsize n)
{ return iostreams::read(t, s, n); }
template<typename T>
static bool put(T&, typename char_type_of<T>::type)
{ throw cant_write(); }
template<typename T>
static std::streamsize
write(T&, const typename char_type_of<T>::type*, std::streamsize)
{ throw cant_write(); }
};
template<>
struct read_write_if_impl<output> {
template<typename T>
static typename int_type_of<T>::type get(T&)
{ throw cant_read(); }
template<typename T>
static std::streamsize
read(T&, typename char_type_of<T>::type*, std::streamsize)
{ throw cant_read(); }
template<typename T>
static bool put(T& t, typename char_type_of<T>::type c)
{ return iostreams::put(t, c); }
template<typename T>
static std::streamsize
write( T& t, const typename char_type_of<T>::type* s,
std::streamsize n )
{ return iostreams::write(t, s, n); }
};
//------------------Specializations of seek_if_impl---------------------------//
template<>
struct seek_if_impl<random_access> {
template<typename T>
static std::streampos
seek( T& t, stream_offset off, BOOST_IOS::seekdir way,
BOOST_IOS::openmode which )
{ return iostreams::seek(t, off, way, which); }
};
template<>
struct seek_if_impl<any_tag> {
template<typename T>
static std::streampos
seek(T&, stream_offset, BOOST_IOS::seekdir, BOOST_IOS::openmode)
{ throw cant_seek(); }
};
} // End namespace detail.
} } // End namespaces iostreams, boost.
#include <boost/iostreams/detail/config/enable_warnings.hpp> // MSVC.
#endif // #ifndef BOOST_IOSTREAMS_DETAIL_CHECKED_OPERATIONS_HPP_INCLUDED
| gpl-3.0 |
palerdot/calibre | src/calibre/gui2/store/stores/pragmatic_bookshelf_plugin.py | 940 | # -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, absolute_import, print_function)
store_version = 1 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.opensearch_store import OpenSearchOPDSStore
from calibre.gui2.store.search_result import SearchResult
class PragmaticBookshelfStore(BasicStoreConfig, OpenSearchOPDSStore):
open_search_url = 'http://pragprog.com/catalog/search-description'
web_url = 'http://pragprog.com/'
# http://pragprog.com/catalog.opds
def search(self, query, max_results=10, timeout=60):
for s in OpenSearchOPDSStore.search(self, query, max_results, timeout):
s.drm = SearchResult.DRM_UNLOCKED
s.formats = 'EPUB, PDF, MOBI'
yield s
| gpl-3.0 |
SSNico/XLParser | lib/Irony/Irony.GrammarExplorer/fmSelectGrammars.cs | 3205 | #region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using Irony.Parsing;
using System.IO;
namespace Irony.GrammarExplorer {
public partial class fmSelectGrammars : Form {
public fmSelectGrammars() {
InitializeComponent();
}
public static GrammarItemList SelectGrammars(string assemblyPath, GrammarItemList loadedGrammars) {
var fromGrammars = LoadGrammars(assemblyPath);
if (fromGrammars == null)
return null;
//fill the listbox and show the form
fmSelectGrammars form = new fmSelectGrammars();
var listbox = form.lstGrammars;
listbox.Sorted = false;
foreach(GrammarItem item in fromGrammars) {
listbox.Items.Add(item);
if (!ContainsGrammar(loadedGrammars, item))
listbox.SetItemChecked(listbox.Items.Count - 1, true);
}
listbox.Sorted = true;
if (form.ShowDialog() != DialogResult.OK) return null;
GrammarItemList result = new GrammarItemList();
for (int i = 0; i < listbox.Items.Count; i++) {
if (listbox.GetItemChecked(i)) {
var item = listbox.Items[i] as GrammarItem;
item._loading = false;
result.Add(item);
}
}
return result;
}
private static GrammarItemList LoadGrammars(string assemblyPath) {
Assembly asm = null;
try {
asm = GrammarLoader.LoadAssembly(assemblyPath);
} catch (Exception ex) {
MessageBox.Show("Failed to load assembly: " + ex.Message);
return null;
}
var types = asm.GetTypes();
var grammars = new GrammarItemList();
foreach (Type t in types) {
if (t.IsAbstract) continue;
if (!t.IsSubclassOf(typeof(Grammar))) continue;
grammars.Add(new GrammarItem(t, assemblyPath));
}
if (grammars.Count == 0) {
MessageBox.Show("No classes derived from Irony.Grammar were found in the assembly.");
return null;
}
return grammars;
}
private static bool ContainsGrammar(GrammarItemList items, GrammarItem item) {
foreach (var listItem in items)
if (listItem.TypeName == item.TypeName && listItem.Location == item.Location)
return true;
return false;
}
private void btnCheckUncheck_Click(object sender, EventArgs e) {
bool check = sender == btnCheckAll;
for (int i = 0; i < lstGrammars.Items.Count; i++)
lstGrammars.SetItemChecked(i, check);
}
}//class
}
| mpl-2.0 |
ErikSchierboom/roslyn | src/Compilers/CSharp/Portable/FlowAnalysis/RegionAnalysisContext.cs | 2335 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Represents region analysis context attributes such as compilation, region, etc...
/// </summary>
internal struct RegionAnalysisContext
{
/// <summary> Compilation to use </summary>
public readonly CSharpCompilation Compilation;
/// <summary> Containing symbol if available, null otherwise </summary>
public readonly Symbol Member;
/// <summary> Bound node, not null </summary>
public readonly BoundNode BoundNode;
/// <summary> Region to be used </summary>
public readonly BoundNode FirstInRegion, LastInRegion;
/// <summary> True if the input was bad, such as no first and last nodes </summary>
public readonly bool Failed;
/// <summary>
/// Construct context
/// </summary>
public RegionAnalysisContext(CSharpCompilation compilation, Symbol member, BoundNode boundNode, BoundNode firstInRegion, BoundNode lastInRegion)
{
this.Compilation = compilation;
this.Member = member;
this.BoundNode = boundNode;
this.FirstInRegion = firstInRegion;
this.LastInRegion = lastInRegion;
this.Failed =
boundNode == null ||
firstInRegion == null ||
lastInRegion == null ||
firstInRegion.Syntax.SpanStart > lastInRegion.Syntax.Span.End;
if (!this.Failed && ReferenceEquals(firstInRegion, lastInRegion))
{
switch (firstInRegion.Kind)
{
case BoundKind.NamespaceExpression:
case BoundKind.TypeExpression:
// Some bound nodes are still considered to be invalid for flow analysis
this.Failed = true;
break;
}
}
}
}
}
| apache-2.0 |
johan/closure-library | closure/goog/structs/prioritypool.js | 4645 | // Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Datastructure: Priority Pool.
*
*
* An extending of Pool that handles queueing and prioritization.
*/
goog.provide('goog.structs.PriorityPool');
goog.require('goog.structs.Pool');
goog.require('goog.structs.PriorityQueue');
/**
* A generic pool class. If max is greater than min, an error is thrown.
* @param {number=} opt_minCount Min. number of objects (Default: 1).
* @param {number=} opt_maxCount Max. number of objects (Default: 10).
* @constructor
* @extends {goog.structs.Pool}
*/
goog.structs.PriorityPool = function(opt_minCount, opt_maxCount) {
/**
* Queue of requests for pool objects.
* @type {goog.structs.PriorityQueue}
* @private
*/
this.requestQueue_ = new goog.structs.PriorityQueue();
// Must break convention of putting the super-class's constructor first. This
// is because the super-class constructor calls adjustForMinMax, which this
// class overrides. In this class's implementation, it assumes that there
// is a requestQueue_, and will error if not present.
goog.structs.Pool.call(this, opt_minCount, opt_maxCount);
};
goog.inherits(goog.structs.PriorityPool, goog.structs.Pool);
/**
* Default priority for pool objects requests.
* @type {number}
* @private
*/
goog.structs.PriorityPool.DEFAULT_PRIORITY_ = 100;
/**
* Get a new object from the the pool, if there is one available, otherwise
* return undefined.
* @param {Function=} opt_callback The function to callback when an object is
* available. This could be immediately. If this is not present, then an
* object is immediately returned if available, or undefined if not.
* @param {*=} opt_priority The priority of the request.
* @return {Object|undefined} The new object from the pool if there is one
* available and a callback is not given. Otherwise, undefined.
*/
goog.structs.PriorityPool.prototype.getObject = function(opt_callback,
opt_priority) {
if (!opt_callback) {
return goog.structs.PriorityPool.superClass_.getObject.call(this);
}
var priority = opt_priority || goog.structs.PriorityPool.DEFAULT_PRIORITY_;
this.requestQueue_.enqueue(priority, opt_callback);
// Handle all requests.
this.handleQueueRequests_();
return undefined;
};
/**
* Handles the request queue. Tries to fires off as many queued requests as
* possible.
* @private
*/
goog.structs.PriorityPool.prototype.handleQueueRequests_ = function() {
var requestQueue = this.requestQueue_;
while (requestQueue.getCount() > 0) {
var obj = this.getObject();
if (!obj) {
return;
} else {
var requestCallback = requestQueue.dequeue();
requestCallback.apply(this, [obj]);
}
}
};
/**
* Adds an object to the collection of objects that are free. If the object can
* not be added, then it is disposed.
*
* NOTE: This method does not remove the object from the in use collection.
*
* @param {Object} obj The object to add to the collection of free objects.
*/
goog.structs.PriorityPool.prototype.addFreeObject = function(obj) {
goog.structs.PriorityPool.superClass_.addFreeObject.call(this, obj);
// Handle all requests.
this.handleQueueRequests_();
};
/**
* Adjusts the objects held in the pool to be within the min/max constraints.
*
* NOTE: It is possible that the number of objects in the pool will still be
* greater than the maximum count of objects allowed. This will be the case
* if no more free objects can be disposed of to get below the minimum count
* (i.e., all objects are in use).
*/
goog.structs.PriorityPool.prototype.adjustForMinMax = function() {
goog.structs.PriorityPool.superClass_.adjustForMinMax.call(this);
// Handle all requests.
this.handleQueueRequests_();
};
/**
* Disposes of the pool.
*/
goog.structs.PriorityPool.prototype.disposeInternal = function() {
goog.structs.PriorityPool.superClass_.disposeInternal.call(this);
this.requestQueue_.clear();
this.requestQueue_ = null;
};
| apache-2.0 |
kdwink/intellij-community | java/java-tests/testSrc/com/intellij/ide/fileTemplates/EmbeddedLiveTemplatesTest.java | 2666 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.fileTemplates;
import com.intellij.codeInsight.template.impl.TemplateManagerImpl;
import com.intellij.ide.fileTemplates.actions.CreateFromTemplateActionBase;
import com.intellij.ide.fileTemplates.impl.CustomFileTemplate;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileTypes.PlainTextFileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
/**
* @author Dmitry Avdeev
*/
public class EmbeddedLiveTemplatesTest extends LightPlatformCodeInsightFixtureTestCase {
public void testCreateFromTemplateAction() throws Exception {
doTest("Put caret here: #[[$END$]]# end of template",
"Put caret here: <caret> end of template");
}
public void testSupportVariables() throws Exception {
doTest("First: #[[$Var$]]# Second: #[[$Var$]]#",
"First: Var Second: Var");
}
protected void doTest(String text, String result) {
CustomFileTemplate template = new CustomFileTemplate("foo", "txt");
template.setText(text);
template.setLiveTemplateEnabled(true);
myFixture.testAction(new TestAction(template));
VirtualFile[] files = FileEditorManager.getInstance(getProject()).getSelectedFiles();
myFixture.openFileInEditor(files[0]);
myFixture.checkResult(result);
}
@Override
public void setUp() throws Exception {
super.setUp();
myFixture.configureByText(PlainTextFileType.INSTANCE, ""); // enable editor action context
TemplateManagerImpl.setTemplateTesting(getProject(), getTestRootDisposable());
}
private static class TestAction extends CreateFromTemplateActionBase {
private final FileTemplate myTemplate;
public TestAction(FileTemplate template) {
super("", "", null);
myTemplate = template;
}
@Override
protected FileTemplate getTemplate(Project project, PsiDirectory dir) {
return myTemplate;
}
}
}
| apache-2.0 |
stevesloka/kubernetes | cmd/kubeadm/app/componentconfigs/fakeconfig_test.go | 23187 | /*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package componentconfigs
import (
"crypto/sha256"
"fmt"
"reflect"
"strings"
"testing"
"time"
"github.com/lithammer/dedent"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
clientset "k8s.io/client-go/kubernetes"
clientsetfake "k8s.io/client-go/kubernetes/fake"
kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
kubeadmscheme "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/scheme"
kubeadmapiv1 "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta2"
outputapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/output"
"k8s.io/kubernetes/cmd/kubeadm/app/constants"
kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
)
// All tests in this file use an alternative set of `known` component configs.
// In this case it's just one known config and it's kubeadm's very own ClusterConfiguration.
// ClusterConfiguration is normally not managed by this package. It's only used, because of the following:
// - It's a versioned API that is under the control of kubeadm maintainers. This enables us to test
// the componentconfigs package more thoroughly without having to have full and always up to date
// knowledge about the config of another component.
// - Other components often introduce new fields in their configs without bumping up the config version.
// This, often times, requires that the PR that introduces such new fields to touch kubeadm test code.
// Doing so, requires more work on the part of developers and reviewers. When kubeadm moves out of k/k
// this would allow for more sporadic breaks in kubeadm tests as PRs that merge in k/k and introduce
// new fields won't be able to fix the tests in kubeadm.
// - If we implement tests for all common functionality using the config of another component and it gets
// deprecated and/or we stop supporting it in production, we'll have to focus on a massive test refactoring
// or just continue importing this config just for test use.
//
// Thus, to reduce maintenance costs without sacrificing test coverage, we introduce this mini-framework
// and set of tests here which replace the normal component configs with a single one (ClusterConfiguration)
// and test the component config independent logic of this package.
// clusterConfigHandler is the handler instance for the latest supported ClusterConfiguration to be used in tests
var clusterConfigHandler = handler{
GroupVersion: kubeadmapiv1.SchemeGroupVersion,
AddToScheme: kubeadmapiv1.AddToScheme,
CreateEmpty: func() kubeadmapi.ComponentConfig {
return &clusterConfig{
configBase: configBase{
GroupVersion: kubeadmapiv1.SchemeGroupVersion,
},
}
},
fromCluster: clusterConfigFromCluster,
}
func clusterConfigFromCluster(h *handler, clientset clientset.Interface, _ *kubeadmapi.ClusterConfiguration) (kubeadmapi.ComponentConfig, error) {
return h.fromConfigMap(clientset, constants.KubeadmConfigConfigMap, constants.ClusterConfigurationConfigMapKey, true)
}
type clusterConfig struct {
configBase
config kubeadmapiv1.ClusterConfiguration
}
func (cc *clusterConfig) DeepCopy() kubeadmapi.ComponentConfig {
result := &clusterConfig{}
cc.configBase.DeepCopyInto(&result.configBase)
cc.config.DeepCopyInto(&result.config)
return result
}
func (cc *clusterConfig) Marshal() ([]byte, error) {
return cc.configBase.Marshal(&cc.config)
}
func (cc *clusterConfig) Unmarshal(docmap kubeadmapi.DocumentMap) error {
return cc.configBase.Unmarshal(docmap, &cc.config)
}
func (cc *clusterConfig) Default(_ *kubeadmapi.ClusterConfiguration, _ *kubeadmapi.APIEndpoint, _ *kubeadmapi.NodeRegistrationOptions) {
cc.config.ClusterName = "foo"
cc.config.KubernetesVersion = "bar"
}
// fakeKnown replaces temporarily during the execution of each test here known (in configset.go)
var fakeKnown = []*handler{
&clusterConfigHandler,
}
// fakeKnownContext is the func that houses the fake component config context.
// NOTE: It does not support concurrent test execution!
func fakeKnownContext(f func()) {
// Save the real values
realKnown := known
realScheme := Scheme
realCodecs := Codecs
// Replace the context with the fake context
known = fakeKnown
Scheme = kubeadmscheme.Scheme
Codecs = kubeadmscheme.Codecs
// Upon function exit, restore the real values
defer func() {
known = realKnown
Scheme = realScheme
Codecs = realCodecs
}()
// Call f in the fake context
f()
}
// testClusterConfigMap is a short hand for creating and possibly signing a test config map.
// This produces config maps that can be loaded by clusterConfigFromCluster
func testClusterConfigMap(yaml string, signIt bool) *v1.ConfigMap {
cm := &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: constants.KubeadmConfigConfigMap,
Namespace: metav1.NamespaceSystem,
},
Data: map[string]string{
constants.ClusterConfigurationConfigMapKey: dedent.Dedent(yaml),
},
}
if signIt {
SignConfigMap(cm)
}
return cm
}
// oldClusterConfigVersion is used as an old unsupported version in tests throughout this file
const oldClusterConfigVersion = "v1alpha1"
var (
// currentClusterConfigVersion represents the current actively supported version of ClusterConfiguration
currentClusterConfigVersion = kubeadmapiv1.SchemeGroupVersion.Version
// currentFooClusterConfig is a minimal currently supported ClusterConfiguration
// with a well known value of clusterName (in this case `foo`)
currentFooClusterConfig = fmt.Sprintf(`
apiVersion: %s
kind: ClusterConfiguration
clusterName: foo
`, kubeadmapiv1.SchemeGroupVersion)
// oldFooClusterConfig is a minimal unsupported ClusterConfiguration
// with a well known value of clusterName (in this case `foo`)
oldFooClusterConfig = fmt.Sprintf(`
apiVersion: %s/%s
kind: ClusterConfiguration
clusterName: foo
`, kubeadmapiv1.GroupName, oldClusterConfigVersion)
// currentBarClusterConfig is a minimal currently supported ClusterConfiguration
// with a well known value of clusterName (in this case `bar`)
currentBarClusterConfig = fmt.Sprintf(`
apiVersion: %s
kind: ClusterConfiguration
clusterName: bar
`, kubeadmapiv1.SchemeGroupVersion)
// oldBarClusterConfig is a minimal unsupported ClusterConfiguration
// with a well known value of clusterName (in this case `bar`)
oldBarClusterConfig = fmt.Sprintf(`
apiVersion: %s/%s
kind: ClusterConfiguration
clusterName: bar
`, kubeadmapiv1.GroupName, oldClusterConfigVersion)
// This is the "minimal" valid config that can be unmarshalled to and from YAML.
// Due to same static defaulting it's not exactly small in size.
validUnmarshallableClusterConfig = struct {
yaml string
obj kubeadmapiv1.ClusterConfiguration
}{
yaml: dedent.Dedent(`
apiServer:
timeoutForControlPlane: 4m
apiVersion: kubeadm.k8s.io/v1beta2
certificatesDir: /etc/kubernetes/pki
clusterName: LeCluster
controllerManager: {}
dns:
type: CoreDNS
etcd:
local:
dataDir: /var/lib/etcd
imageRepository: k8s.gcr.io
kind: ClusterConfiguration
kubernetesVersion: 1.2.3
networking:
dnsDomain: cluster.local
serviceSubnet: 10.96.0.0/12
scheduler: {}
`),
obj: kubeadmapiv1.ClusterConfiguration{
TypeMeta: metav1.TypeMeta{
APIVersion: kubeadmapiv1.SchemeGroupVersion.String(),
Kind: "ClusterConfiguration",
},
ClusterName: "LeCluster",
KubernetesVersion: "1.2.3",
CertificatesDir: "/etc/kubernetes/pki",
ImageRepository: "k8s.gcr.io",
Networking: kubeadmapiv1.Networking{
DNSDomain: "cluster.local",
ServiceSubnet: "10.96.0.0/12",
},
DNS: kubeadmapiv1.DNS{
Type: kubeadmapiv1.CoreDNS,
},
Etcd: kubeadmapiv1.Etcd{
Local: &kubeadmapiv1.LocalEtcd{
DataDir: "/var/lib/etcd",
},
},
APIServer: kubeadmapiv1.APIServer{
TimeoutForControlPlane: &metav1.Duration{
Duration: 4 * time.Minute,
},
},
},
}
)
func TestConfigBaseMarshal(t *testing.T) {
fakeKnownContext(func() {
cfg := &clusterConfig{
configBase: configBase{
GroupVersion: kubeadmapiv1.SchemeGroupVersion,
},
config: kubeadmapiv1.ClusterConfiguration{
TypeMeta: metav1.TypeMeta{
APIVersion: kubeadmapiv1.SchemeGroupVersion.String(),
Kind: "ClusterConfiguration",
},
ClusterName: "LeCluster",
KubernetesVersion: "1.2.3",
},
}
b, err := cfg.Marshal()
if err != nil {
t.Fatalf("Marshal failed: %v", err)
}
got := strings.TrimSpace(string(b))
expected := strings.TrimSpace(dedent.Dedent(`
apiServer: {}
apiVersion: kubeadm.k8s.io/v1beta2
clusterName: LeCluster
controllerManager: {}
dns:
type: ""
etcd: {}
kind: ClusterConfiguration
kubernetesVersion: 1.2.3
networking: {}
scheduler: {}
`))
if expected != got {
t.Fatalf("Missmatch between expected and got:\nExpected:\n%s\n---\nGot:\n%s", expected, got)
}
})
}
func TestConfigBaseUnmarshal(t *testing.T) {
fakeKnownContext(func() {
expected := &clusterConfig{
configBase: configBase{
GroupVersion: kubeadmapiv1.SchemeGroupVersion,
},
config: validUnmarshallableClusterConfig.obj,
}
gvkmap, err := kubeadmutil.SplitYAMLDocuments([]byte(validUnmarshallableClusterConfig.yaml))
if err != nil {
t.Fatalf("unexpected failure of SplitYAMLDocuments: %v", err)
}
got := &clusterConfig{
configBase: configBase{
GroupVersion: kubeadmapiv1.SchemeGroupVersion,
},
}
if err = got.Unmarshal(gvkmap); err != nil {
t.Fatalf("unexpected failure of Unmarshal: %v", err)
}
if !reflect.DeepEqual(got, expected) {
t.Fatalf("Missmatch between expected and got:\nExpected:\n%v\n---\nGot:\n%v", expected, got)
}
})
}
func TestGeneratedConfigFromCluster(t *testing.T) {
fakeKnownContext(func() {
testYAML := dedent.Dedent(`
apiVersion: kubeadm.k8s.io/v1beta2
kind: ClusterConfiguration
`)
testYAMLHash := fmt.Sprintf("sha256:%x", sha256.Sum256([]byte(testYAML)))
// The SHA256 sum of "The quick brown fox jumps over the lazy dog"
const mismatchHash = "sha256:d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"
tests := []struct {
name string
hash string
userSupplied bool
}{
{
name: "Matching hash means generated config",
hash: testYAMLHash,
},
{
name: "Missmatching hash means user supplied config",
hash: mismatchHash,
userSupplied: true,
},
{
name: "No hash means user supplied config",
userSupplied: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
configMap := testClusterConfigMap(testYAML, false)
if test.hash != "" {
configMap.Annotations = map[string]string{
constants.ComponentConfigHashAnnotationKey: test.hash,
}
}
client := clientsetfake.NewSimpleClientset(configMap)
cfg, err := clusterConfigHandler.FromCluster(client, testClusterCfg())
if err != nil {
t.Fatalf("unexpected failure of FromCluster: %v", err)
}
got := cfg.IsUserSupplied()
if got != test.userSupplied {
t.Fatalf("mismatch between expected and got:\n\tExpected: %t\n\tGot: %t", test.userSupplied, got)
}
})
}
})
}
// runClusterConfigFromTest holds common test case data and evaluation code for handler.From* functions
func runClusterConfigFromTest(t *testing.T, perform func(t *testing.T, in string) (kubeadmapi.ComponentConfig, error)) {
fakeKnownContext(func() {
tests := []struct {
name string
in string
out *clusterConfig
expectErr bool
}{
{
name: "Empty document map should return nothing successfully",
},
{
name: "Non-empty document map without the proper API group returns nothing successfully",
in: dedent.Dedent(`
apiVersion: api.example.com/v1
kind: Configuration
`),
},
{
name: "Old config version returns an error",
in: dedent.Dedent(`
apiVersion: kubeadm.k8s.io/v1alpha1
kind: ClusterConfiguration
`),
expectErr: true,
},
{
name: "Unknown kind returns an error",
in: dedent.Dedent(`
apiVersion: kubeadm.k8s.io/v1beta2
kind: Configuration
`),
expectErr: true,
},
{
name: "Valid config gets loaded",
in: validUnmarshallableClusterConfig.yaml,
out: &clusterConfig{
configBase: configBase{
GroupVersion: clusterConfigHandler.GroupVersion,
userSupplied: true,
},
config: validUnmarshallableClusterConfig.obj,
},
},
{
name: "Valid config gets loaded even if coupled with an extra document",
in: "apiVersion: api.example.com/v1\nkind: Configuration\n---\n" + validUnmarshallableClusterConfig.yaml,
out: &clusterConfig{
configBase: configBase{
GroupVersion: clusterConfigHandler.GroupVersion,
userSupplied: true,
},
config: validUnmarshallableClusterConfig.obj,
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
componentCfg, err := perform(t, test.in)
if err != nil {
if !test.expectErr {
t.Errorf("unexpected failure: %v", err)
}
} else {
if test.expectErr {
t.Error("unexpected success")
} else {
if componentCfg == nil {
if test.out != nil {
t.Error("unexpected nil result")
}
} else {
if got, ok := componentCfg.(*clusterConfig); !ok {
t.Error("different result type")
} else {
if test.out == nil {
t.Errorf("unexpected result: %v", got)
} else {
if !reflect.DeepEqual(test.out, got) {
t.Errorf("missmatch between expected and got:\nExpected:\n%v\n---\nGot:\n%v", test.out, got)
}
}
}
}
}
}
})
}
})
}
func TestLoadingFromDocumentMap(t *testing.T) {
runClusterConfigFromTest(t, func(t *testing.T, in string) (kubeadmapi.ComponentConfig, error) {
gvkmap, err := kubeadmutil.SplitYAMLDocuments([]byte(in))
if err != nil {
t.Fatalf("unexpected failure of SplitYAMLDocuments: %v", err)
}
return clusterConfigHandler.FromDocumentMap(gvkmap)
})
}
func TestLoadingFromCluster(t *testing.T) {
runClusterConfigFromTest(t, func(t *testing.T, in string) (kubeadmapi.ComponentConfig, error) {
client := clientsetfake.NewSimpleClientset(
testClusterConfigMap(in, false),
)
return clusterConfigHandler.FromCluster(client, testClusterCfg())
})
}
func TestFetchFromClusterWithLocalOverwrites(t *testing.T) {
fakeKnownContext(func() {
cases := []struct {
desc string
obj runtime.Object
config string
expectedValue string
isNotLoaded bool
expectedErr bool
}{
{
desc: "appropriate cluster object without overwrite is used",
obj: testClusterConfigMap(currentFooClusterConfig, false),
expectedValue: "foo",
},
{
desc: "appropriate cluster object with appropriate overwrite is overwritten",
obj: testClusterConfigMap(currentFooClusterConfig, false),
config: dedent.Dedent(currentBarClusterConfig),
expectedValue: "bar",
},
{
desc: "appropriate cluster object with old overwrite returns an error",
obj: testClusterConfigMap(currentFooClusterConfig, false),
config: dedent.Dedent(oldBarClusterConfig),
expectedErr: true,
},
{
desc: "old config without overwrite returns an error",
obj: testClusterConfigMap(oldFooClusterConfig, false),
expectedErr: true,
},
{
desc: "old config with appropriate overwrite returns the substitute",
obj: testClusterConfigMap(oldFooClusterConfig, false),
config: dedent.Dedent(currentBarClusterConfig),
expectedValue: "bar",
},
{
desc: "old config with old overwrite returns an error",
obj: testClusterConfigMap(oldFooClusterConfig, false),
config: dedent.Dedent(oldBarClusterConfig),
expectedErr: true,
},
{
desc: "appropriate signed cluster object without overwrite is used",
obj: testClusterConfigMap(currentFooClusterConfig, true),
expectedValue: "foo",
},
{
desc: "appropriate signed cluster object with appropriate overwrite is overwritten",
obj: testClusterConfigMap(currentFooClusterConfig, true),
config: dedent.Dedent(currentBarClusterConfig),
expectedValue: "bar",
},
{
desc: "appropriate signed cluster object with old overwrite returns an error",
obj: testClusterConfigMap(currentFooClusterConfig, true),
config: dedent.Dedent(oldBarClusterConfig),
expectedErr: true,
},
{
desc: "old signed config without an overwrite is not loaded",
obj: testClusterConfigMap(oldFooClusterConfig, true),
isNotLoaded: true,
},
{
desc: "old signed config with appropriate overwrite returns the substitute",
obj: testClusterConfigMap(oldFooClusterConfig, true),
config: dedent.Dedent(currentBarClusterConfig),
expectedValue: "bar",
},
{
desc: "old signed config with old overwrite returns an error",
obj: testClusterConfigMap(oldFooClusterConfig, true),
config: dedent.Dedent(oldBarClusterConfig),
expectedErr: true,
},
}
for _, test := range cases {
t.Run(test.desc, func(t *testing.T) {
client := clientsetfake.NewSimpleClientset(test.obj)
docmap, err := kubeadmutil.SplitYAMLDocuments([]byte(test.config))
if err != nil {
t.Fatalf("unexpected failure of SplitYAMLDocuments: %v", err)
}
clusterCfg := testClusterCfg()
err = FetchFromClusterWithLocalOverwrites(clusterCfg, client, docmap)
if err != nil {
if !test.expectedErr {
t.Errorf("unexpected failure: %v", err)
}
} else {
if test.expectedErr {
t.Error("unexpected success")
} else {
clusterCfg, ok := clusterCfg.ComponentConfigs[kubeadmapiv1.GroupName]
if !ok {
if !test.isNotLoaded {
t.Error("no config was loaded when it should have been")
}
} else {
actualConfig, ok := clusterCfg.(*clusterConfig)
if !ok {
t.Error("the config is not of the expected type")
} else if actualConfig.config.ClusterName != test.expectedValue {
t.Errorf("unexpected value:\n\tgot: %q\n\texpected: %q", actualConfig.config.ClusterName, test.expectedValue)
}
}
}
}
})
}
})
}
func TestGetVersionStates(t *testing.T) {
fakeKnownContext(func() {
versionStateCurrent := outputapi.ComponentConfigVersionState{
Group: kubeadmapiv1.GroupName,
CurrentVersion: currentClusterConfigVersion,
PreferredVersion: currentClusterConfigVersion,
}
versionStateOld := outputapi.ComponentConfigVersionState{
Group: kubeadmapiv1.GroupName,
CurrentVersion: oldClusterConfigVersion,
PreferredVersion: currentClusterConfigVersion,
ManualUpgradeRequired: true,
}
cases := []struct {
desc string
obj runtime.Object
config string
expected outputapi.ComponentConfigVersionState
}{
{
desc: "appropriate cluster object without overwrite",
obj: testClusterConfigMap(currentFooClusterConfig, false),
expected: versionStateCurrent,
},
{
desc: "appropriate cluster object with appropriate overwrite",
obj: testClusterConfigMap(currentFooClusterConfig, false),
config: dedent.Dedent(currentBarClusterConfig),
expected: versionStateCurrent,
},
{
desc: "appropriate cluster object with old overwrite",
obj: testClusterConfigMap(currentFooClusterConfig, false),
config: dedent.Dedent(oldBarClusterConfig),
expected: versionStateOld,
},
{
desc: "old config without overwrite returns an error",
obj: testClusterConfigMap(oldFooClusterConfig, false),
expected: versionStateOld,
},
{
desc: "old config with appropriate overwrite",
obj: testClusterConfigMap(oldFooClusterConfig, false),
config: dedent.Dedent(currentBarClusterConfig),
expected: versionStateCurrent,
},
{
desc: "old config with old overwrite",
obj: testClusterConfigMap(oldFooClusterConfig, false),
config: dedent.Dedent(oldBarClusterConfig),
expected: versionStateOld,
},
{
desc: "appropriate signed cluster object without overwrite",
obj: testClusterConfigMap(currentFooClusterConfig, true),
expected: versionStateCurrent,
},
{
desc: "appropriate signed cluster object with appropriate overwrite",
obj: testClusterConfigMap(currentFooClusterConfig, true),
config: dedent.Dedent(currentBarClusterConfig),
expected: versionStateCurrent,
},
{
desc: "appropriate signed cluster object with old overwrit",
obj: testClusterConfigMap(currentFooClusterConfig, true),
config: dedent.Dedent(oldBarClusterConfig),
expected: versionStateOld,
},
{
desc: "old signed config without an overwrite",
obj: testClusterConfigMap(oldFooClusterConfig, true),
expected: outputapi.ComponentConfigVersionState{
Group: kubeadmapiv1.GroupName,
CurrentVersion: "", // The config is treated as if it's missing
PreferredVersion: currentClusterConfigVersion,
},
},
{
desc: "old signed config with appropriate overwrite",
obj: testClusterConfigMap(oldFooClusterConfig, true),
config: dedent.Dedent(currentBarClusterConfig),
expected: versionStateCurrent,
},
{
desc: "old signed config with old overwrite",
obj: testClusterConfigMap(oldFooClusterConfig, true),
config: dedent.Dedent(oldBarClusterConfig),
expected: versionStateOld,
},
}
for _, test := range cases {
t.Run(test.desc, func(t *testing.T) {
client := clientsetfake.NewSimpleClientset(test.obj)
docmap, err := kubeadmutil.SplitYAMLDocuments([]byte(test.config))
if err != nil {
t.Fatalf("unexpected failure of SplitYAMLDocuments: %v", err)
}
clusterCfg := testClusterCfg()
got, err := GetVersionStates(clusterCfg, client, docmap)
if err != nil {
t.Errorf("unexpected error: %v", err)
} else if len(got) != 1 {
t.Errorf("got %d, but expected only a single result: %v", len(got), got)
} else if got[0] != test.expected {
t.Errorf("unexpected result:\n\texpected: %v\n\tgot: %v", test.expected, got[0])
}
})
}
})
}
| apache-2.0 |
Yuriy-Leonov/nova | nova/db/sqlalchemy/migrate_repo/versions/161_fix_system_metadata_none_strings.py | 1505 | # Copyright 2013 IBM Corp.
#
# 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.
from sqlalchemy import MetaData, Table
from nova.openstack.common import timeutils
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
sys_meta = Table('instance_system_metadata', meta, autoload=True)
sys_meta.update().\
values(value=None).\
where(sys_meta.c.key != 'instance_type_name').\
where(sys_meta.c.key != 'instance_type_flavorid').\
where(sys_meta.c.key.like('instance_type_%')).\
where(sys_meta.c.value == 'None').\
execute()
now = timeutils.utcnow()
sys_meta.update().\
values(created_at=now).\
where(sys_meta.c.created_at == None).\
where(sys_meta.c.key.like('instance_type_%')).\
execute()
def downgrade(migration_engine):
# This migration only touches data, and only metadata at that. No need
# to go through and delete old metadata items.
pass
| apache-2.0 |
dev-ab/marketplace | vendor/zf-commons/zfc-user/src/ZfcUser/Factory/Controller/Plugin/ZfcUserAuthenticationFactory.php | 1103 | <?php
namespace ZfcUser\Factory\Controller\Plugin;
use Zend\Authentication\AuthenticationService;
use Zend\Mvc\Controller\PluginManager;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZfcUser\Authentication\Adapter;
use ZfcUser\Controller\Plugin\ZfcUserAuthentication;
class ZfcUserAuthenticationFactory implements FactoryInterface
{
/**
* {@inheritDoc}
*/
public function createService(ServiceLocatorInterface $pluginManager)
{
/* @var $pluginManager PluginManager */
$serviceManager = $pluginManager->getServiceLocator();
/* @var $authService AuthenticationService */
$authService = $serviceManager->get('zfcuser_auth_service');
/* @var $authAdapter Adapter\AdapterChain */
$authAdapter = $serviceManager->get('ZfcUser\Authentication\Adapter\AdapterChain');
$controllerPlugin = new ZfcUserAuthentication;
$controllerPlugin
->setAuthService($authService)
->setAuthAdapter($authAdapter)
;
return $controllerPlugin;
}
}
| bsd-3-clause |
markogresak/DefinitelyTyped | types/carbon__pictograms-react/lib/document--security/index.d.ts | 71 | import { DocumentSecurity } from "../../";
export = DocumentSecurity;
| mit |
mravinale/micro-cms | node_modules/sails/node_modules/i18n/i18n.js | 12712 | /**
* @author Created by Marcus Spiegel <marcus.spiegel@gmail.com> on 2011-03-25.
* @link https://github.com/mashpie/i18n-node
* @license http://opensource.org/licenses/MIT
*
* @version 0.4.1
*/
// dependencies and "private" vars
var vsprintf = require('sprintf').vsprintf,
fs = require('fs'),
url = require('url'),
path = require('path'),
debug = require('debug')('i18n:debug'),
warn = require('debug')('i18n:warn'),
error = require('debug')('i18n:error'),
locales = {},
api = ['__', '__n', 'getLocale', 'setLocale', 'getCatalog'],
pathsep = path.sep || '/', // ---> means win support will be available in node 0.8.x and above
defaultLocale, updateFiles, cookiename, extension, directory, indent;
// public exports
var i18n = exports;
i18n.version = '0.4.1';
i18n.configure = function i18nConfigure(opt) {
// you may register helpers in global scope, up to you
if (typeof opt.register === 'object') {
applyAPItoObject(opt.register);
}
// sets a custom cookie name to parse locale settings from
cookiename = (typeof opt.cookie === 'string') ? opt.cookie : null;
// where to store json files
directory = (typeof opt.directory === 'string') ? opt.directory : __dirname + pathsep + 'locales';
// write new locale information to disk
updateFiles = (typeof opt.updateFiles === 'boolean') ? opt.updateFiles : true;
// what to use as the indentation unit (ex: "\t", " ")
indent = (typeof opt.indent === 'string') ? opt.indent : "\t";
// where to store json files
extension = (typeof opt.extension === 'string') ? opt.extension : '.json';
// setting defaultLocale
defaultLocale = (typeof opt.defaultLocale === 'string') ? opt.defaultLocale : 'en';
// implicitly read all locales
if (typeof opt.locales === 'object') {
opt.locales.forEach(function (l) {
read(l);
});
}
};
i18n.init = function i18nInit(request, response, next) {
if (typeof request === 'object') {
guessLanguage(request);
if (typeof response === 'object') {
applyAPItoObject(request, response);
// register locale to res.locals so hbs helpers know this.locale
if (!response.locale) response.locale = request.locale;
if (response.locals) {
applyAPItoObject(request, response.locals);
// register locale to res.locals so hbs helpers know this.locale
if (!response.locals.locale) response.locals.locale = request.locale;
}
}
}
if (typeof next === 'function') {
next();
}
};
i18n.__ = function i18nTranslate(phrase) {
var msg;
// called like __({phrase: "Hello", locale: "en"})
if (typeof phrase === 'object') {
if (typeof phrase.locale === 'string' && typeof phrase.phrase === 'string') {
msg = translate(phrase.locale, phrase.phrase);
}
}
// called like __("Hello")
else {
// get translated message with locale from scope (deprecated) or object
msg = translate(getLocaleFromObject(this), phrase);
}
// if we have extra arguments with strings to get replaced,
// an additional substition injects those strings afterwards
if (arguments.length > 1) {
msg = vsprintf(msg, Array.prototype.slice.call(arguments, 1));
}
return msg;
};
i18n.__n = function i18nTranslatePlural(singular, plural, count) {
var msg;
// called like __n({singular: "%s cat", plural: "%s cats", locale: "en"}, 3)
if (typeof singular === 'object') {
if (typeof singular.locale === 'string' && typeof singular.singular === 'string' && typeof singular.plural === 'string') {
msg = translate(singular.locale, singular.singular, singular.plural);
}
if(typeof plural === 'number'){
count = plural;
}
// called like __n({singular: "%s cat", plural: "%s cats", locale: "en", count: 3})
if(typeof singular.count === 'number' || typeof singular.count === 'string'){
count = singular.count;
}
}
// called like __n('%s cat', '%s cats', 3)
else {
// get translated message with locale from scope (deprecated) or object
msg = translate(getLocaleFromObject(this), singular, plural);
}
// parse translation and replace all digets '%d' by `count`
// this also replaces extra strings '%%s' to parseble '%s' for next step
// simplest 2 form implementation of plural, like https://developer.mozilla.org/en/docs/Localization_and_Plurals#Plural_rule_.231_.282_forms.29
if (parseInt(count, 10) > 1) {
msg = vsprintf(msg.other, [count]);
} else {
msg = vsprintf(msg.one, [count]);
}
// if we have extra arguments with strings to get replaced,
// an additional substition injects those strings afterwards
if (arguments.length > 3) {
msg = vsprintf(msg, Array.prototype.slice.call(arguments, 3));
}
return msg;
};
i18n.setLocale = function i18nSetLocale(locale_or_request, locale) {
var target_locale = locale_or_request,
request;
// called like setLocale(req, 'en')
if (locale_or_request && typeof locale === 'string' && locales[locale]) {
request = locale_or_request;
target_locale = locale;
}
// called like req.setLocale('en')
if (locale === undefined && typeof this.locale === 'string' && typeof locale_or_request === 'string') {
request = this;
target_locale = locale_or_request;
}
if (locales[target_locale]) {
// called like setLocale('en')
if (request === undefined) {
defaultLocale = target_locale;
}
else {
request.locale = target_locale;
}
}
return i18n.getLocale(request);
};
i18n.getLocale = function i18nGetLocale(request) {
// called like getLocale(req)
if (request && request.locale) {
return request.locale;
}
// called like req.getLocale()
if (request === undefined && typeof this.locale === 'string') {
return this.locale;
}
// called like getLocale()
return defaultLocale;
};
i18n.getCatalog = function i18nGetCatalog(locale_or_request, locale) {
var target_locale = locale_or_request;
// called like getCatalog(req)
if (typeof locale_or_request === 'object' && typeof locale_or_request.locale === 'string') {
target_locale = locale_or_request.locale;
}
// called like getCatalog(req, 'en')
if (typeof locale_or_request === 'object' && typeof locale === 'string') {
target_locale = locale;
}
// called like req.getCatalog()
if (locale === undefined && typeof this.locale === 'string') {
target_locale = this.locale;
}
// called like req.getCatalog('en')
if (locale === undefined && typeof locale_or_request === 'string') {
target_locale = locale_or_request;
}
// called like getCatalog()
if (target_locale === undefined || target_locale === '') {
return locales;
}
if (locales[target_locale]) {
return locales[target_locale];
} else {
logWarn('No catalog found for "' + target_locale + '"');
return false;
}
};
i18n.overrideLocaleFromQuery = function (req) {
if (req === null) {
return;
}
var urlObj = url.parse(req.url, true);
if (urlObj.query.locale) {
logDebug("Overriding locale from query: " + urlObj.query.locale);
i18n.setLocale(req, urlObj.query.locale.toLowerCase());
}
};
// ===================
// = private methods =
// ===================
/**
* registers all public API methods to a given response object when not already declared
*/
function applyAPItoObject(request, response) {
// attach to itself if not provided
var object = response || request;
api.forEach(function (method) {
// be kind rewind, or better not touch anything already exiting
if (!object[method]) {
object[method] = function () {
return i18n[method].apply(request, arguments);
};
}
});
}
/**
* guess language setting based on http headers
*/
function guessLanguage(request) {
if (typeof request === 'object') {
var language_header = request.headers['accept-language'],
languages = [],
regions = [];
request.languages = [defaultLocale];
request.regions = [defaultLocale];
request.language = defaultLocale;
request.region = defaultLocale;
if (language_header) {
language_header.split(',').forEach(function (l) {
var header = l.split(';', 1)[0],
lr = header.split('-', 2);
if (lr[0]) {
languages.push(lr[0].toLowerCase());
}
if (lr[1]) {
regions.push(lr[1].toLowerCase());
}
});
if (languages.length > 0) {
request.languages = languages;
request.language = languages[0];
}
if (regions.length > 0) {
request.regions = regions;
request.region = regions[0];
}
}
// setting the language by cookie
if (cookiename && request.cookies && request.cookies[cookiename]) {
request.language = request.cookies[cookiename];
}
i18n.setLocale(request, request.language);
}
}
/**
* searches for locale in given object
*/
function getLocaleFromObject(obj) {
var locale;
if (obj && obj.scope) {
locale = obj.scope.locale;
}
if (obj && obj.locale) {
locale = obj.locale;
}
return locale;
}
/**
* read locale file, translate a msg and write to fs if new
*/
function translate(locale, singular, plural) {
if (locale === undefined) {
logWarn("WARN: No locale found - check the context of the call to __(). Using " + defaultLocale + " as current locale");
locale = defaultLocale;
}
// attempt to read when defined as valid locale
if (!locales[locale]) {
read(locale);
}
// fallback to default when missed
if (!locales[locale]) {
logWarn("WARN: Locale " + locale + " couldn't be read - check the context of the call to $__. Using " + defaultLocale + " (default) as current locale");
locale = defaultLocale;
read(locale);
}
if (plural) {
if (!locales[locale][singular]) {
locales[locale][singular] = {
'one': singular,
'other': plural
};
write(locale);
}
}
if (!locales[locale][singular]) {
locales[locale][singular] = singular;
write(locale);
}
return locales[locale][singular];
}
/**
* try reading a file
*/
function read(locale) {
var localeFile = {},
file = getStorageFilePath(locale);
try {
logDebug('read ' + file + ' for locale: ' + locale);
localeFile = fs.readFileSync(file);
try {
// parsing filecontents to locales[locale]
locales[locale] = JSON.parse(localeFile);
} catch (parseError) {
logError('unable to parse locales from file (maybe ' + file + ' is empty or invalid json?): ', e);
}
} catch (readError) {
// unable to read, so intialize that file
// locales[locale] are already set in memory, so no extra read required
// or locales[locale] are empty, which initializes an empty locale.json file
logDebug('initializing ' + file);
write(locale);
}
}
/**
* try writing a file in a created directory
*/
function write(locale) {
var stats, target, tmp;
// don't write new locale information to disk if updateFiles isn't true
if (!updateFiles) {
return;
}
// creating directory if necessary
try {
stats = fs.lstatSync(directory);
} catch (e) {
logDebug('creating locales dir in: ' + directory);
fs.mkdirSync(directory, parseInt('755', 8));
}
// first time init has an empty file
if (!locales[locale]) {
locales[locale] = {};
}
// writing to tmp and rename on success
try {
target = getStorageFilePath(locale);
tmp = target + ".tmp";
fs.writeFileSync(tmp, JSON.stringify(locales[locale], null, indent), "utf8");
stats = fs.statSync(tmp);
if (stats.isFile()) {
fs.renameSync(tmp, target);
} else {
logError('unable to write locales to file (either ' + tmp + ' or ' + target + ' are not writeable?): ', e);
}
} catch (e) {
logError('unexpected error writing files (either ' + tmp + ' or ' + target + ' are not writeable?): ', e);
}
}
/**
* basic normalization of filepath
*/
function getStorageFilePath(locale) {
// changed API to use .json as default, #16
var ext = extension || '.json',
filepath = path.normalize(directory + pathsep + locale + ext),
filepathJS = path.normalize(directory + pathsep + locale + '.js');
// use .js as fallback if already existing
try {
if (fs.statSync(filepathJS)) {
logDebug('using existing file ' + filepathJS);
extension = '.js';
return filepathJS;
}
} catch (e) {
logDebug('will write to ' + filepath);
}
return filepath;
}
/**
* Logging proxies
*/
function logDebug(msg) {
debug(msg);
}
function logWarn(msg) {
warn(msg);
}
function logError(msg) {
error(msg);
}
| mit |
Android-leak/android-vts | app/src/main/java/android/framework/org/apache/harmony/security_custom/asn1/BerOutputStream.java | 6083 | /*
* 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.
*/
/**
* @author Vladimir N. Molotkov, Stepan M. Mishura
* @version $Revision$
*/
package android.framework.org.apache.harmony.security_custom.asn1;
/**
* Encodes ASN.1 types with BER (X.690)
*
* @see <a href="http://asn1.elibel.tm.fr/en/standards/index.htm">ASN.1</a>
*/
public class BerOutputStream {
/** Encoded byte array */
public byte[] encoded;
/** current offset */
protected int offset;
/** Current encoded length */
public int length;
/** Current encoded content */
public Object content;
public final void encodeTag(int tag) {
encoded[offset++] = (byte) tag; //FIXME long form?
if (length > 127) { //long form
int eLen = length >> 8;
byte numOctets = 1;
for (; eLen > 0; eLen = eLen >> 8) {
numOctets++;
}
encoded[offset] = (byte) (numOctets | 0x80);
offset++;
eLen = length;
int numOffset = offset + numOctets - 1;
for (int i = 0; i < numOctets; i++, eLen = eLen >> 8) {
encoded[numOffset - i] = (byte) eLen; //FIXME long value?
}
offset += numOctets;
} else { //short form
encoded[offset++] = (byte) length;
}
}
public void encodeANY() {
System.arraycopy(content, 0, encoded, offset, length);
offset += length;
}
public void encodeBitString() {
//FIXME check encoding
BitString bStr = (BitString) content;
encoded[offset] = (byte) bStr.unusedBits;
System.arraycopy(bStr.bytes, 0, encoded, offset + 1, length - 1);
offset += length;
}
public void encodeBoolean() {
if ((Boolean) content) {
encoded[offset] = (byte) 0xFF;
} else {
encoded[offset] = 0x00;
}
offset++;
}
public void encodeChoice(ASN1Choice choice) {
throw new RuntimeException("Is not implemented yet"); //FIXME
}
public void encodeExplicit(ASN1Explicit explicit) {
throw new RuntimeException("Is not implemented yet"); //FIXME
}
public void encodeGeneralizedTime() {
System.arraycopy(content, 0, encoded, offset, length);
offset += length;
}
public void encodeUTCTime() {
System.arraycopy(content, 0, encoded, offset, length);
offset += length;
}
public void encodeInteger() {
System.arraycopy(content, 0, encoded, offset, length);
offset += length;
}
public void encodeOctetString() {
System.arraycopy(content, 0, encoded, offset, length);
offset += length;
}
public void encodeOID() {
int[] oid = (int[]) content;
int oidLen = length;
// all subidentifiers except first
int elem;
for (int i = oid.length - 1; i > 1; i--, oidLen--) {
elem = oid[i];
if (elem > 127) {
encoded[offset + oidLen - 1] = (byte) (elem & 0x7F);
elem = elem >> 7;
for (; elem > 0;) {
oidLen--;
encoded[offset + oidLen - 1] = (byte) (elem | 0x80);
elem = elem >> 7;
}
} else {
encoded[offset + oidLen - 1] = (byte) elem;
}
}
// first subidentifier
elem = oid[0] * 40 + oid[1];
if (elem > 127) {
encoded[offset + oidLen - 1] = (byte) (elem & 0x7F);
elem = elem >> 7;
for (; elem > 0;) {
oidLen--;
encoded[offset + oidLen - 1] = (byte) (elem | 0x80);
elem = elem >> 7;
}
} else {
encoded[offset + oidLen - 1] = (byte) elem;
}
offset += length;
}
public void encodeSequence(ASN1Sequence sequence) {
throw new RuntimeException("Is not implemented yet"); //FIXME
}
public void encodeSequenceOf(ASN1SequenceOf sequenceOf) {
throw new RuntimeException("Is not implemented yet"); //FIXME
}
public void encodeSet(ASN1Set set) {
throw new RuntimeException("Is not implemented yet"); //FIXME
}
public void encodeSetOf(ASN1SetOf setOf) {
throw new RuntimeException("Is not implemented yet"); //FIXME
}
public void encodeString() {
System.arraycopy(content, 0, encoded, offset, length);
offset += length;
}
public void getChoiceLength(ASN1Choice choice) {
throw new RuntimeException("Is not implemented yet"); //FIXME
}
public void getExplicitLength(ASN1Explicit sequence) {
throw new RuntimeException("Is not implemented yet"); //FIXME
}
public void getSequenceLength(ASN1Sequence sequence) {
throw new RuntimeException("Is not implemented yet"); //FIXME
}
public void getSequenceOfLength(ASN1SequenceOf sequence) {
throw new RuntimeException("Is not implemented yet"); //FIXME
}
public void getSetLength(ASN1Set set) {
throw new RuntimeException("Is not implemented yet"); //FIXME
}
public void getSetOfLength(ASN1SetOf setOf) {
throw new RuntimeException("Is not implemented yet"); //FIXME
}
}
| mit |
darkdukey/sdkbox-facebook-sample-v2 | external/emscripten/tests/poppler/utils/pdfimages.cc | 4895 | //========================================================================
//
// pdfimages.cc
//
// Copyright 1998-2003 Glyph & Cog, LLC
//
// Modified for Debian by Hamish Moffatt, 22 May 2002.
//
//========================================================================
//========================================================================
//
// Modified under the Poppler project - http://poppler.freedesktop.org
//
// All changes made under the Poppler project to this file are licensed
// under GPL version 2 or later
//
// Copyright (C) 2007-2008, 2010 Albert Astals Cid <aacid@kde.org>
// Copyright (C) 2010 Hib Eris <hib@hiberis.nl>
// Copyright (C) 2010 Jakob Voss <jakob.voss@gbv.de>
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================
#include "config.h"
#include <poppler-config.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include "parseargs.h"
#include "goo/GooString.h"
#include "goo/gmem.h"
#include "GlobalParams.h"
#include "Object.h"
#include "Stream.h"
#include "Array.h"
#include "Dict.h"
#include "XRef.h"
#include "Catalog.h"
#include "Page.h"
#include "PDFDoc.h"
#include "PDFDocFactory.h"
#include "ImageOutputDev.h"
#include "Error.h"
static int firstPage = 1;
static int lastPage = 0;
static GBool dumpJPEG = gFalse;
static GBool pageNames = gFalse;
static char ownerPassword[33] = "\001";
static char userPassword[33] = "\001";
static GBool quiet = gFalse;
static GBool printVersion = gFalse;
static GBool printHelp = gFalse;
static const ArgDesc argDesc[] = {
{"-f", argInt, &firstPage, 0,
"first page to convert"},
{"-l", argInt, &lastPage, 0,
"last page to convert"},
{"-j", argFlag, &dumpJPEG, 0,
"write JPEG images as JPEG files"},
{"-opw", argString, ownerPassword, sizeof(ownerPassword),
"owner password (for encrypted files)"},
{"-upw", argString, userPassword, sizeof(userPassword),
"user password (for encrypted files)"},
{"-p", argFlag, &pageNames, 0,
"include page numbers in output file names"},
{"-q", argFlag, &quiet, 0,
"don't print any messages or errors"},
{"-v", argFlag, &printVersion, 0,
"print copyright and version info"},
{"-h", argFlag, &printHelp, 0,
"print usage information"},
{"-help", argFlag, &printHelp, 0,
"print usage information"},
{"--help", argFlag, &printHelp, 0,
"print usage information"},
{"-?", argFlag, &printHelp, 0,
"print usage information"},
{NULL}
};
int main(int argc, char *argv[]) {
PDFDoc *doc;
GooString *fileName;
char *imgRoot;
GooString *ownerPW, *userPW;
ImageOutputDev *imgOut;
GBool ok;
int exitCode;
exitCode = 99;
// parse args
ok = parseArgs(argDesc, &argc, argv);
if (!ok || argc != 3 || printVersion || printHelp) {
fprintf(stderr, "pdfimages version %s\n", PACKAGE_VERSION);
fprintf(stderr, "%s\n", popplerCopyright);
fprintf(stderr, "%s\n", xpdfCopyright);
if (!printVersion) {
printUsage("pdfimages", "<PDF-file> <image-root>", argDesc);
}
if (printVersion || printHelp)
exitCode = 0;
goto err0;
}
fileName = new GooString(argv[1]);
imgRoot = argv[2];
// read config file
globalParams = new GlobalParams();
if (quiet) {
globalParams->setErrQuiet(quiet);
}
// open PDF file
if (ownerPassword[0] != '\001') {
ownerPW = new GooString(ownerPassword);
} else {
ownerPW = NULL;
}
if (userPassword[0] != '\001') {
userPW = new GooString(userPassword);
} else {
userPW = NULL;
}
if (fileName->cmp("-") == 0) {
delete fileName;
fileName = new GooString("fd://0");
}
doc = PDFDocFactory().createPDFDoc(*fileName, ownerPW, userPW);
delete fileName;
if (userPW) {
delete userPW;
}
if (ownerPW) {
delete ownerPW;
}
if (!doc->isOk()) {
exitCode = 1;
goto err1;
}
// check for copy permission
#ifdef ENFORCE_PERMISSIONS
if (!doc->okToCopy()) {
error(-1, "Copying of images from this document is not allowed.");
exitCode = 3;
goto err1;
}
#endif
// get page range
if (firstPage < 1)
firstPage = 1;
if (lastPage < 1 || lastPage > doc->getNumPages())
lastPage = doc->getNumPages();
// write image files
imgOut = new ImageOutputDev(imgRoot, pageNames, dumpJPEG);
if (imgOut->isOk()) {
doc->displayPages(imgOut, firstPage, lastPage, 72, 72, 0,
gTrue, gFalse, gFalse);
}
delete imgOut;
exitCode = 0;
// clean up
err1:
delete doc;
delete globalParams;
err0:
// check for memory leaks
Object::memCheck(stderr);
gMemReport(stderr);
return exitCode;
}
| mit |
aurimas-darguzis/react-intro | node_modules/lodash-es/_updateWrapDetails.js | 1218 | import arrayEach from './_arrayEach.js';
import arrayIncludes from './_arrayIncludes.js';
/** Used to compose bitmasks for function metadata. */
var BIND_FLAG = 1,
BIND_KEY_FLAG = 2,
CURRY_FLAG = 8,
CURRY_RIGHT_FLAG = 16,
PARTIAL_FLAG = 32,
PARTIAL_RIGHT_FLAG = 64,
ARY_FLAG = 128,
REARG_FLAG = 256,
FLIP_FLAG = 512;
/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
['ary', ARY_FLAG],
['bind', BIND_FLAG],
['bindKey', BIND_KEY_FLAG],
['curry', CURRY_FLAG],
['curryRight', CURRY_RIGHT_FLAG],
['flip', FLIP_FLAG],
['partial', PARTIAL_FLAG],
['partialRight', PARTIAL_RIGHT_FLAG],
['rearg', REARG_FLAG]
];
/**
* Updates wrapper `details` based on `bitmask` flags.
*
* @private
* @returns {Array} details The details to modify.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Array} Returns `details`.
*/
function updateWrapDetails(details, bitmask) {
arrayEach(wrapFlags, function(pair) {
var value = '_.' + pair[0];
if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
details.push(value);
}
});
return details.sort();
}
export default updateWrapDetails;
| mit |
him2him2/cdnjs | ajax/libs/elfinder/2.1.25/js/extras/editors.default.js | 30912 | (function(editors, elFinder) {
if (typeof define === 'function' && define.amd) {
define(['elfinder'], editors);
} else if (elFinder) {
var optEditors = elFinder.prototype._options.commandsOptions.edit.editors;
elFinder.prototype._options.commandsOptions.edit.editors = optEditors.concat(editors(elFinder));
}
}(function(elFinder) {
var // get query of getfile
getfile = window.location.search.match(/getfile=([a-z]+)/),
// cdns location
cdns = {
ace : '//cdnjs.cloudflare.com/ajax/libs/ace/1.2.6',
codemirror : '//cdnjs.cloudflare.com/ajax/libs/codemirror/5.26.0',
ckeditor : '//cdnjs.cloudflare.com/ajax/libs/ckeditor/4.7.0',
tinymce : '//cdnjs.cloudflare.com/ajax/libs/tinymce/4.6.3',
simplemde : '//cdnjs.cloudflare.com/ajax/libs/simplemde/1.11.2'
},
useRequire = (typeof define === 'function' && define.amd),
hasFlash = (function() {
var hasFlash;
try {
hasFlash = !!(new ActiveXObject('ShockwaveFlash.ShockwaveFlash'));
} catch (e) {
hasFlash = !!(navigator && navigator.mimeTypes["application/x-shockwave-flash"]);
}
return hasFlash;
})(),
initImgTag = function(id, file, content, fm) {
var node = $(this).children('img:first'),
spnr = $('<div/>')
.css({
position: 'absolute',
top: '50%',
textAlign: 'center',
width: '100%',
fontSize: '16pt'
})
.html(fm.i18n('ntfloadimg'))
.hide()
.appendTo(this);
node.attr('id', id+'-img')
.attr('src', content)
.css({'height':'', 'max-width':'100%', 'max-height':'100%', 'cursor':'pointer'})
.data('loading', function(done) {
var btns = node.closest('.elfinder-dialog').find('button,.elfinder-titlebar-button');
btns.prop('disabled', !done)[done? 'removeClass' : 'addClass']('ui-state-disabled');
node.css('opacity', done? '' : '0.3');
spnr[done? 'hide' : 'show']();
return node;
});
},
imgBase64 = function(node, mime) {
var style = node.attr('style'),
img, canvas, ctx, data;
try {
// reset css for getting image size
node.attr('style', '');
// img node
img = node.get(0);
// New Canvas
canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
// restore css
node.attr('style', style);
// Draw Image
canvas.getContext('2d').drawImage(img, 0, 0);
// To Base64
data = canvas.toDataURL(mime);
} catch(e) {
data = node.attr('src');
}
return data;
},
pixlrCallBack = function() {
if (!hasFlash || window.parent === window) {
return;
}
var pixlr = window.location.search.match(/[?&]pixlr=([^&]+)/),
image = window.location.search.match(/[?&]image=([^&]+)/),
p, ifm, url, node;
if (pixlr) {
// case of redirected from pixlr.com
p = window.parent
ifm = p.$('#'+pixlr[1]+'iframe').hide();
node = p.$('#'+pixlr[1]).data('resizeoff')();
if (image[1].substr(0, 4) === 'http') {
url = image[1];
if (window.location.protocol === 'https:') {
url = url.replace(/^http:/, 'https:');
}
node.on('load error', function() {
node.data('loading')(true);
})
.attr('src', url)
.data('loading')();
} else {
node.data('loading')(true);
}
ifm.remove();
}
};
pixlrSetup = function(opts, fm) {
if (!hasFlash) {
this.disabled = true;
}
},
pixlrLoad = function(mode, base) {
var fm = this.fm,
node = $(base).children('img:first')
.data('loading')()
.data('resizeoff', function() {
$(window).off('resize.'+node.attr('id'));
return node;
})
.on('click', function() {
launch();
}),
elfNode = fm.getUI(),
container = $('<iframe class="ui-front" allowtransparency="true">'),
file = this.file,
src = 'https://pixlr.com/'+mode+'/?s=c',
myurl = window.location.href.toString().replace(/#.*$/, ''),
error = function() {
container.remove();
node.data('loading')(true);
fm.error('Can not launch Pixlr.');
},
launch = function() {
errtm = setTimeout(error, 10000);
myurl += (myurl.indexOf('?') === -1? '?' : '&') + 'pixlr='+node.attr('id');
src += '&referrer=elFinder&locktitle=true&locktype=true';
src += '&exit='+encodeURIComponent(myurl+'&image=0');
src += '&target='+encodeURIComponent(myurl);
src += '&title='+encodeURIComponent(file.name);
src += '&image='+encodeURIComponent(node.attr('src'));
container
.attr('id', node.attr('id')+'iframe')
.attr('src', src)
.css({
width: '100%',
height: $(window).height()+'px',
position: 'fixed',
display: 'block',
backgroundColor: 'transparent',
border: 'none',
top: 0,
right: 0
})
.on('load', function() {
errtm && clearTimeout(errtm);
})
.on('error', error)
.appendTo(elfNode.hasClass('elfinder-fullscreen')? elfNode : 'body');
// fit to window size
$(window).on('resize.'+node.attr('id'), function() {
container.css('height', $(window).height());
});
},
errtm;
launch();
};
// check callback from pixlr
pixlrCallBack();
// check getfile callback function
if (getfile) {
getfile = getfile[1];
if (getfile === 'ckeditor') {
elFinder.prototype._options.getFileCallback = function(file, fm) {
window.opener.CKEDITOR.tools.callFunction((function() {
var reParam = new RegExp('(?:[\?&]|&)CKEditorFuncNum=([^&]+)', 'i'),
match = window.location.search.match(reParam);
return (match && match.length > 1) ? match[1] : '';
})(), fm.convAbsUrl(file.url));
fm.destroy();
window.close();
};
} else if (getfile === 'tinymce') {
elFinder.prototype._options.getFileCallback = function(file, fm) {
// pass selected file data to TinyMCE
parent.tinymce.activeEditor.windowManager.getParams().oninsert(file, fm);
// close popup window
parent.tinymce.activeEditor.windowManager.close();
};
}
}
// return editors Array
return [
{
// Pixlr Editor
info : {
name : 'Pixlr Editor',
iconImg : 'img/edit_pixlreditor.png',
urlAsContent: true,
schemeContent: true,
single: true
},
// MIME types to accept
mimes : ['image/jpeg', 'image/png'],
// HTML of this editor
html : '<div style="width:100%;height:300px;text-align:center;"><img/></div>',
// called on initialization of elFinder cmd edit (this: this editor's config object)
setup : function(opts, fm) {
pixlrSetup.call(this, opts, fm);
},
// Initialization of editing node (this: this editors HTML node)
init : function(id, file, url, fm) {
//initImgTag.call(this, id, file, fm.convAbsUrl(fm.openUrl(file.hash, true)), fm);
initImgTag.call(this, id, file, fm.convAbsUrl(url), fm);
},
// Get data uri scheme (this: this editors HTML node)
getContent : function() {
return $(this).children('img:first').attr('src');
},
load : function(base) {
pixlrLoad.call(this, 'editor', base);
},
save : function(base) {},
// unbind resize event function
close : function(base) {
//$(window).off('resize.'+$(base).children('img:first').attr('id'));
}
},
{
// Pixlr Express
info : {
name : 'Pixlr Express',
iconImg : 'img/edit_pixlrexpress.png',
urlAsContent: true,
schemeContent: true,
single: true
},
// MIME types to accept
mimes : ['image/jpeg', 'image/png'],
// HTML of this editor
html : '<div style="width:100%;height:300px;text-align:center;"><img/></div>',
// called on initialization of elFinder cmd edit (this: this editor's config object)
setup : function(opts, fm) {
pixlrSetup.call(this, opts, fm);
},
// Initialization of editing node (this: this editors HTML node)
init : function(id, file, url, fm) {
initImgTag.call(this, id, file, fm.convAbsUrl(url), fm);
},
// Get data uri scheme (this: this editors HTML node)
getContent : function() {
return $(this).children('img:first').attr('src');
},
load : function(base) {
pixlrLoad.call(this, 'express', base);
},
save : function(base) {},
// unbind resize event function
close : function(base) {
//$(window).off('resize.'+$(base).children('img:first').attr('id'));
}
},
{
// Adobe Creative SDK Creative Tools Image Editor UI
// MIME types to accept
info : {
name : 'Creative Cloud',
iconImg : 'img/edit_creativecloud.png',
schemeContent: true,
single: true
},
mimes : ['image/jpeg', 'image/png'],
// HTML of this editor
html : '<div style="width:100%;height:300px;text-align:center;"><img/></div>',
// called on initialization of elFinder cmd edit (this: this editor's config object)
setup : function(opts, fm) {
if (fm.UA.ltIE8 || !opts.extraOptions || !opts.extraOptions.creativeCloudApiKey) {
this.disabled = true;
} else {
this.apiKey = opts.extraOptions.creativeCloudApiKey;
}
},
// Initialization of editing node (this: this editors HTML node)
init : function(id, file, content, fm) {
initImgTag.call(this, id, file, content, fm);
},
// Get data uri scheme (this: this editors HTML node)
getContent : function() {
return $(this).children('img:first').attr('src');
},
// Launch Aviary Feather editor when dialog open
load : function(base) {
var self = this,
fm = this.fm,
node = $(base).children('img:first'),
elfNode = fm.getUI(),
dfrd = $.Deferred(),
container = $('#elfinder-aviary-container'),
init = function(onload) {
var getLang = function() {
var langMap = {
'jp' : 'ja',
'zh_TW' : 'zh_HANT',
'zh_CN' : 'zh_HANS'
};
return langMap[fm.lang]? langMap[fm.lang] : fm.lang;
};
if (!container.length) {
container = $('<div id="elfinder-aviary-container" class="ui-front"/>').css({
position: 'fixed',
top: 0,
right: 0,
width: '100%',
height: $(window).height(),
overflow: 'auto'
}).hide().appendTo(elfNode.hasClass('elfinder-fullscreen')? elfNode : 'body');
// fit to window size
$(window).on('resize.'+fm.namespace, function() {
container.css('height', $(window).height());
});
// bind switch fullscreen event
elfNode.on('resize.'+fm.namespace, function(e, data) {
data && data.fullscreen && container.appendTo(data.fullscreen === 'on'? elfNode : 'body');
});
fm.bind('destroy', function() {
container.remove();
});
} else {
// always moves to last
container.appendTo(container.parent());
}
node.on('click', launch).data('loading')();
featherEditor = new Aviary.Feather({
apiKey: self.confObj.apiKey,
onSave: function(imageID, newURL) {
featherEditor.showWaitIndicator();
node.on('load error', function() {
node.data('loading')(true);
})
.attr('crossorigin', 'anonymous')
.attr('src', newURL)
.data('loading')();
featherEditor.close();
},
onLoad: onload || function(){},
onClose: function() { $(container).hide(); },
appendTo: container.get(0),
maxSize: 2048,
language: getLang()
});
// return editor instance
dfrd.resolve(featherEditor);
},
launch = function() {
$(container).show();
featherEditor.launch({
image: node.attr('id'),
url: node.attr('src')
});
node.data('loading')(true);
},
featherEditor, extraOpts;
// load script then init
if (typeof Aviary === 'undefined') {
fm.loadScript(['https://dme0ih8comzn4.cloudfront.net/imaging/v3/editor.js'], function() {
init(launch);
});
} else {
init();
launch();
}
return dfrd;
},
// Convert content url to data uri scheme to save content
save : function(base) {
var node = $(base).children('img:first');
if (node.attr('src').substr(0, 5) !== 'data:') {
node.attr('src', imgBase64(node, this.file.mime));
}
}
},
{
// ACE Editor
// `mimes` is not set for support everything kind of text file
info : {
name : 'ACE Editor',
iconImg : 'img/edit_aceeditor.png'
},
load : function(textarea) {
var self = this,
dfrd = $.Deferred(),
cdn = cdns.ace,
start = function() {
var editor, editorBase, mode,
ta = $(textarea),
taBase = ta.parent(),
dialog = taBase.parent(),
id = textarea.id + '_ace',
ext = self.file.name.replace(/^.+\.([^.]+)|(.+)$/, '$1$2').toLowerCase(),
// MIME/mode map
mimeMode = {
'text/x-php' : 'php',
'application/x-php' : 'php',
'text/html' : 'html',
'application/xhtml+xml' : 'html',
'text/javascript' : 'javascript',
'application/javascript' : 'javascript',
'text/css' : 'css',
'text/x-c' : 'c_cpp',
'text/x-csrc' : 'c_cpp',
'text/x-chdr' : 'c_cpp',
'text/x-c++' : 'c_cpp',
'text/x-c++src' : 'c_cpp',
'text/x-c++hdr' : 'c_cpp',
'text/x-shellscript' : 'sh',
'application/x-csh' : 'sh',
'text/x-python' : 'python',
'text/x-java' : 'java',
'text/x-java-source' : 'java',
'text/x-ruby' : 'ruby',
'text/x-perl' : 'perl',
'application/x-perl' : 'perl',
'text/x-sql' : 'sql',
'text/xml' : 'xml',
'application/docbook+xml' : 'xml',
'application/xml' : 'xml'
};
// set base height
taBase.height(taBase.height());
// set basePath of ace
ace.config.set('basePath', cdn);
// Base node of Ace editor
editorBase = $('<div id="'+id+'" style="width:100%; height:100%;"/>').text(ta.val()).insertBefore(ta.hide());
// Editor flag
ta.data('ace', true);
// Aceeditor instance
editor = ace.edit(id);
// Ace editor configure
editor.$blockScrolling = Infinity;
editor.setOptions({
theme: 'ace/theme/monokai',
fontSize: '14px',
wrap: true,
});
ace.config.loadModule('ace/ext/modelist', function() {
// detect mode
mode = ace.require('ace/ext/modelist').getModeForPath('/' + self.file.name).name;
if (mode === 'text') {
if (mimeMode[self.file.mime]) {
mode = mimeMode[self.file.mime];
}
}
// show MIME:mode in title bar
taBase.prev().children('.elfinder-dialog-title').append(' (' + self.file.mime + ' : ' + mode.split(/[\/\\]/).pop() + ')');
editor.setOptions({
mode: 'ace/mode/' + mode
});
});
ace.config.loadModule('ace/ext/language_tools', function() {
ace.require('ace/ext/language_tools');
editor.setOptions({
enableBasicAutocompletion: true,
enableSnippets: true,
enableLiveAutocompletion: false
});
});
ace.config.loadModule('ace/ext/settings_menu', function() {
ace.require('ace/ext/settings_menu').init(editor);
});
// Short cuts
editor.commands.addCommand({
name : "saveFile",
bindKey: {
win : 'Ctrl-s',
mac : 'Command-s'
},
exec: function(editor) {
self.doSave();
}
});
editor.commands.addCommand({
name : "closeEditor",
bindKey: {
win : 'Ctrl-w|Ctrl-q',
mac : 'Command-w|Command-q'
},
exec: function(editor) {
self.doCancel();
}
});
editor.resize();
// TextArea button and Setting button
$('<div class="ui-dialog-buttonset"/>').css('float', 'left')
.append(
$('<button/>').html(self.fm.i18n('TextArea'))
.button()
.on('click', function(){
if (ta.data('ace')) {
ta.removeData('ace');
editorBase.hide();
ta.val(editor.session.getValue()).show().focus();
$(this).text('AceEditor');
} else {
ta.data('ace', true);
editorBase.show();
editor.setValue(ta.hide().val(), -1);
editor.focus();
$(this).html(self.fm.i18n('TextArea'));
}
})
)
.append(
$('<button>Ace editor setting</button>')
.button({
icons: {
primary: 'ui-icon-gear',
secondary: 'ui-icon-triangle-1-e'
},
text: false
})
.on('click', function(){
editor.showSettingsMenu();
$('#ace_settingsmenu')
.css('font-size', '80%')
.find('div[contains="setOptions"]').hide().end()
.parent().parent().appendTo($('#elfinder'));
})
)
.prependTo(taBase.next());
dfrd.resolve(editor);
};
// check ace & start
if (!self.confObj.loader) {
self.confObj.loader = $.Deferred();
self.fm.loadScript([ cdn+'/ace.js' ], function() {
self.confObj.loader.resolve();
}, void 0, {obj: window, name: 'ace'});
}
self.confObj.loader.done(start);
return dfrd;
},
close : function(textarea, instance) {
instance && instance.destroy();
},
save : function(textarea, instance) {
instance && $(textarea).data('ace') && (textarea.value = instance.session.getValue());
},
focus : function(textarea, instance) {
instance && $(textarea).data('ace') && instance.focus();
},
resize : function(textarea, instance, e, data) {
instance && instance.resize();
}
},
{
// CodeMirror
// `mimes` is not set for support everything kind of text file
info : {
name : 'CodeMirror',
iconImg : 'img/edit_codemirror.png'
},
load : function(textarea) {
var cmUrl = cdns.codemirror,
dfrd = $.Deferred(),
self = this,
start = function(CodeMirror) {
var ta = $(textarea),
base = ta.parent(),
editor, editorBase;
// set base height
base.height(base.height());
// CodeMirror configure
editor = CodeMirror.fromTextArea(textarea, {
lineNumbers: true,
lineWrapping: true,
extraKeys : {
'Ctrl-S': function() { self.doSave(); },
'Ctrl-Q': function() { self.doCancel(); },
'Ctrl-W': function() { self.doCancel(); }
}
});
// return editor instance
dfrd.resolve(editor);
// Auto mode set
var info, m, mode, spec;
if (! info) {
info = CodeMirror.findModeByMIME(self.file.mime);
}
if (! info && (m = self.file.name.match(/.+\.([^.]+)$/))) {
info = CodeMirror.findModeByExtension(m[1]);
}
if (info) {
CodeMirror.modeURL = useRequire? 'codemirror/mode/%N/%N.min' : cmUrl + '/mode/%N/%N.min.js';
mode = info.mode;
spec = info.mime;
editor.setOption('mode', spec);
CodeMirror.autoLoadMode(editor, mode);
// show MIME:mode in title bar
base.prev().children('.elfinder-dialog-title').append(' (' + spec + ' : ' + mode + ')');
}
// editor base node
editorBase = $(editor.getWrapperElement()).css({
// fix CSS conflict to SimpleMDE
padding: 0,
border: 'none'
});
ta.data('cm', true);
// fit height to base
editorBase.height('100%');
// TextArea button and Setting button
$('<div class="ui-dialog-buttonset"/>').css('float', 'left')
.append(
$('<button/>').html(self.fm.i18n('TextArea'))
.button()
.on('click', function(){
if (ta.data('cm')) {
ta.removeData('cm');
editorBase.hide();
ta.val(editor.getValue()).show().focus();
$(this).text('CodeMirror');
} else {
ta.data('cm', true);
editorBase.show();
editor.setValue(ta.hide().val());
editor.refresh();
editor.focus();
$(this).html(self.fm.i18n('TextArea'));
}
})
)
.prependTo(base.next());
};
// load script then start
if (!self.confObj.loader) {
self.confObj.loader = $.Deferred();
if (useRequire) {
require.config({
packages: [{
name: 'codemirror',
location: cmUrl,
main: 'codemirror.min'
}],
map: {
'codemirror': {
'codemirror/lib/codemirror': 'codemirror'
}
}
});
require([
'codemirror',
'codemirror/addon/mode/loadmode.min',
'codemirror/mode/meta.min'
], function(CodeMirror) {
self.confObj.loader.resolve(CodeMirror);
});
} else {
self.fm.loadScript([
cmUrl + '/codemirror.min.js',
cmUrl + '/addon/mode/loadmode.min.js',
cmUrl + '/mode/meta.min.js'
], function() {
self.confObj.loader.resolve(CodeMirror);
}, void 0, {obj: window, name: 'CodeMirror'});
}
self.fm.loadCss(cmUrl + '/codemirror.css');
}
self.confObj.loader.done(start);
return dfrd;
},
close : function(textarea, instance) {
instance && instance.toTextArea();
},
save : function(textarea, instance) {
instance && $(textarea).data('cm') && (textarea.value = instance.getValue());
},
focus : function(textarea, instance) {
instance && $(textarea).data('cm') && instance.focus();
},
resize : function(textarea, instance, e, data) {
instance && instance.refresh();
}
},
{
// SimpleMDE
info : {
name : 'SimpleMDE',
iconImg : 'img/edit_simplemde.png'
},
exts : ['md'],
load : function(textarea) {
var self = this,
base = $(textarea).parent(),
dfrd = $.Deferred(),
start = function(SimpleMDE) {
var h = base.height(),
delta = base.outerHeight(true) - h + 14,
editor, editorBase;
// fit height function
textarea._setHeight = function(h) {
var h = h || base.height(),
ctrH = 0,
areaH;
base.children('.editor-toolbar,.editor-statusbar').each(function() {
ctrH += $(this).outerHeight(true);
});
areaH = h - ctrH - delta;
editorBase.height(areaH);
editor.codemirror.refresh();
return areaH;
};
// set base height
base.height(h);
// make editor
editor = new SimpleMDE({
element: textarea,
autofocus: true
});
dfrd.resolve(editor);
// editor base node
editorBase = $(editor.codemirror.getWrapperElement());
// fit height to base
editorBase.css('min-height', '50px')
.children('.CodeMirror-scroll').css('min-height', '50px');
textarea._setHeight(h);
};
// check SimpleMDE & start
if (!self.confObj.loader) {
self.confObj.loader = $.Deferred();
self.fm.loadCss(cdns.simplemde+'/simplemde.min.css');
if (useRequire) {
require([
cdns.simplemde+'/simplemde.min.js'
], function(SimpleMDE) {
self.confObj.loader.resolve(SimpleMDE);
});
} else {
self.fm.loadScript([cdns.simplemde+'/simplemde.min.js'], function() {
self.confObj.loader.resolve(SimpleMDE);
}, void 0, {obj: window, name: 'SimpleMDE'});
}
}
self.confObj.loader.done(start);
return dfrd;
},
close : function(textarea, instance) {
instance && instance.toTextArea();
instance = null;
},
save : function(textarea, instance) {
instance && (textarea.value = instance.value());
},
focus : function(textarea, instance) {
instance && instance.codemirror.focus();
},
resize : function(textarea, instance, e, data) {
instance && textarea._setHeight();
}
},
{
// CKEditor for html file
info : {
name : 'CKEditor',
iconImg : 'img/edit_ckeditor.png'
},
exts : ['htm', 'html', 'xhtml'],
setup : function(opts, fm) {
if (opts.extraOptions && opts.extraOptions.managerUrl) {
this.managerUrl = opts.extraOptions.managerUrl;
}
},
load : function(textarea) {
var self = this,
fm = this.fm,
dfrd = $.Deferred(),
init = function() {
var base = $(textarea).parent(),
dlg = base.closest('.elfinder-dialog'),
h = base.height(),
reg = /([&?]getfile=)[^&]+/,
loc = self.confObj.managerUrl || window.location.href.replace(/#.*$/, ''),
name = 'ckeditor';
// make manager location
if (reg.test(loc)) {
loc = loc.replace(reg, '$1' + name);
} else {
loc += '?getfile=' + name;
}
// set base height
base.height(h);
// CKEditor configure
CKEDITOR.replace(textarea.id, {
startupFocus : true,
fullPage: true,
allowedContent: true,
filebrowserBrowseUrl : loc,
removePlugins: 'resize',
on: {
'instanceReady' : function(e) {
var editor = e.editor;
editor.resize('100%', h);
// re-build on dom move
dlg.one('beforedommove.'+fm.namespace, function() {
editor.destroy();
}).one('dommove.'+fm.namespace, function() {
self.load(textarea).done(function(editor) {
self.instance = editor;
});
});
// return editor instance
dfrd.resolve(e.editor);
}
}
});
CKEDITOR.on('dialogDefinition', function(e) {
var dlg = e.data.definition.dialog;
dlg.on('show', function(e) {
fm.getUI().append($('.cke_dialog_background_cover')).append(this.getElement().$)
});
dlg.on('hide', function(e) {
$('body:first').append($('.cke_dialog_background_cover')).append(this.getElement().$)
});
});
};
if (!self.confObj.loader) {
self.confObj.loader = $.Deferred();
$.getScript(cdns.ckeditor + '/ckeditor.js', function() {
self.confObj.loader.resolve();
});
}
self.confObj.loader.done(init);
return dfrd;
},
close : function(textarea, instance) {
instance && instance.destroy();
},
save : function(textarea, instance) {
instance && (textarea.value = instance.getData());
},
focus : function(textarea, instance) {
instance && instance.focus();
},
resize : function(textarea, instance, e, data) {
var self;
if (instance) {
if (instance.status === 'ready') {
instance.resize('100%', $(textarea).parent().height());
}
}
}
},
{
// TinyMCE for html file
info : {
name : 'TinyMCE',
iconImg : 'img/edit_tinymce.png'
},
exts : ['htm', 'html', 'xhtml'],
setup : function(opts, fm) {
if (opts.extraOptions && opts.extraOptions.managerUrl) {
this.managerUrl = opts.extraOptions.managerUrl;
}
},
load : function(textarea) {
var self = this,
fm = this.fm,
dfrd = $.Deferred(),
init = function() {
var base = $(textarea).parent(),
dlg = base.closest('.elfinder-dialog'),
h = base.height(),
delta = base.outerHeight(true) - h;
// set base height
base.height(h);
// fit height function
textarea._setHeight = function(h) {
var base = $(this).parent(),
h = h || base.height(),
ctrH = 0,
areaH;
base.find('.mce-container-body:first').children('.mce-toolbar,.mce-toolbar-grp,.mce-statusbar').each(function() {
ctrH += $(this).outerHeight(true);
});
areaH = h - ctrH - delta;
base.find('.mce-edit-area iframe:first').height(areaH);
return areaH;
};
// TinyMCE configure
tinymce.init({
selector: '#' + textarea.id,
resize: false,
plugins: [
'fullpage', // require for getting full HTML
'image', 'link', 'media',
'code', 'fullscreen'
],
init_instance_callback : function(editor) {
// fit height on init
textarea._setHeight(h);
// re-build on dom move
dlg.one('beforedommove.'+fm.namespace, function() {
tinymce.execCommand('mceRemoveEditor', false, textarea.id);
}).one('dommove.'+fm.namespace, function() {
self.load(textarea).done(function(editor) {
self.instance = editor;
});
});
// return editor instance
dfrd.resolve(editor);
},
file_picker_callback : function (callback, value, meta) {
var reg = /([&?]getfile=)[^&]+/,
loc = self.confObj.managerUrl || window.location.href.replace(/#.*$/, ''),
name = 'tinymce';
// make manager location
if (reg.test(loc)) {
loc = loc.replace(reg, '$1' + name);
} else {
loc += '?getfile=' + name;
}
// launch TinyMCE
tinymce.activeEditor.windowManager.open({
file: loc,
title: 'elFinder',
width: 900,
height: 450,
resizable: 'yes'
}, {
oninsert: function (file, elf) {
var url, reg, info;
// URL normalization
url = elf.convAbsUrl(file.url);
// Make file info
info = file.name + ' (' + elf.formatSize(file.size) + ')';
// Provide file and text for the link dialog
if (meta.filetype == 'file') {
callback(url, {text: info, title: info});
}
// Provide image and alt text for the image dialog
if (meta.filetype == 'image') {
callback(url, {alt: info});
}
// Provide alternative source and posted for the media dialog
if (meta.filetype == 'media') {
callback(url);
}
}
});
return false;
}
});
};
// impossible launch TineMCE in native fullscreen mode
fm.getUI().hasClass('elfinder-fullscreen-native') && fm.exec('fullscreen');
if (!self.confObj.loader) {
self.confObj.loader = $.Deferred();
$.getScript(cdns.tinymce + '/tinymce.min.js', function() {
setTimeout(function() {
self.confObj.loader.resolve();
}, 0);
});
}
self.confObj.loader.done(init);
return dfrd;
},
close : function(textarea, instance) {
instance && tinymce.execCommand('mceRemoveEditor', false, textarea.id);
},
save : function(textarea, instance) {
instance && instance.save();
},
focus : function(textarea, instance) {
instance && instance.focus();
},
resize : function(textarea, instance, e, data) {
// fit height to base node on dialog resize
textarea._setHeight();
}
},
{
// Simple Text (basic textarea editor)
info : {
name : 'TextArea',
useTextAreaEvent : true
},
load : function(){},
save : function(){}
}
];
}, window.elFinder));
| mit |
DaneTheory/SuperMarioRedux | node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/createlink-base/createlink-base-min.js | 874 | YUI.add("createlink-base",function(e,t){var n={};n.STRINGS={PROMPT:"Please enter the URL for the link to point to:",DEFAULT:"http://"},e.namespace("Plugin"),e.Plugin.CreateLinkBase=n,e.mix(e.Plugin.ExecCommand.COMMANDS,{createlink:function(t){var r=this.get("host").getInstance(),i,s,o,u,a=prompt(n.STRINGS.PROMPT,n.STRINGS.DEFAULT);return a&&(u=r.config.doc.createElement("div"),a=a.replace(/"/g,"").replace(/'/g,""),a=r.config.doc.createTextNode(a),u.appendChild(a),a=u.innerHTML,this.get("host")._execCommand(t,a),o=new r.EditorSelection,i=o.getSelected(),!o.isCollapsed&&i.size()?(s=i.item(0).one("a"),s&&i.item(0).replace(s),e.UA.gecko&&s.get("parentNode").test("span")&&s.get("parentNode").one("br.yui-cursor")&&s.get("parentNode").insert(s,"before")):this.get("host").execCommand("inserthtml",'<a href="'+a+'">'+a+"</a>")),s}})},"3.14.1",{requires:["editor-base"]});
| mit |
yangdd1205/spring-boot | spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/web/reactive/server/package-info.java | 832 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
/**
* Spring Boot support for testing Spring WebFlux server endpoints via
* {@link org.springframework.test.web.reactive.server.WebTestClient}.
*/
package org.springframework.boot.test.web.reactive.server;
| mit |
parameshbabu/samples | ExternalProcessLauncher/CS/ProcessLauncherSample/Properties/AssemblyInfo.cs | 1062 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ProcessLauncherSample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ProcessLauncherSample")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | mit |
falcontersama/chatbot | node_modules/caniuse-lite/data/features/flac.js | 805 | module.exports={A:{A:{"2":"J C G E B A TB"},B:{"2":"D X g H L"},C:{"1":"0 2 4 v z t s","2":"1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x PB OB"},D:{"1":"4 8 s DB AB SB BB","2":"F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m","16":"n o p","388":"0 2 q r w x v z t"},E:{"2":"7 F I J C G E B A CB EB FB GB HB IB JB"},F:{"1":"l m n o p q r","2":"5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k KB LB MB NB QB y"},G:{"2":"3 7 9 G A UB VB WB XB YB ZB aB bB"},H:{"2":"cB"},I:{"1":"s","2":"dB eB fB","16":"1 3 F gB hB iB"},J:{"1":"B","2":"C"},K:{"1":"y","16":"5 6 B A D","129":"K"},L:{"1":"8"},M:{"2":"t"},N:{"2":"B A"},O:{"1":"jB"},P:{"1":"I","129":"F"},Q:{"2":"kB"},R:{"1":"lB"}},B:6,C:"FLAC audio format"};
| mit |
yangdd1205/spring-boot | spring-boot-project/spring-boot/src/main/java/org/springframework/boot/env/OriginTrackedMapPropertySource.java | 2508 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.env;
import java.util.Map;
import org.springframework.boot.origin.Origin;
import org.springframework.boot.origin.OriginLookup;
import org.springframework.boot.origin.OriginTrackedValue;
import org.springframework.core.env.MapPropertySource;
/**
* {@link OriginLookup} backed by a {@link Map} containing {@link OriginTrackedValue
* OriginTrackedValues}.
*
* @author Madhura Bhave
* @author Phillip Webb
* @since 2.0.0
* @see OriginTrackedValue
*/
public final class OriginTrackedMapPropertySource extends MapPropertySource implements OriginLookup<String> {
private final boolean immutable;
/**
* Create a new {@link OriginTrackedMapPropertySource} instance.
* @param name the property source name
* @param source the underlying map source
*/
@SuppressWarnings("rawtypes")
public OriginTrackedMapPropertySource(String name, Map source) {
this(name, source, false);
}
/**
* Create a new {@link OriginTrackedMapPropertySource} instance.
* @param name the property source name
* @param source the underlying map source
* @param immutable if the underlying source is immutable and guaranteed not to change
* @since 2.2.0
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public OriginTrackedMapPropertySource(String name, Map source, boolean immutable) {
super(name, source);
this.immutable = immutable;
}
@Override
public Object getProperty(String name) {
Object value = super.getProperty(name);
if (value instanceof OriginTrackedValue) {
return ((OriginTrackedValue) value).getValue();
}
return value;
}
@Override
public Origin getOrigin(String name) {
Object value = super.getProperty(name);
if (value instanceof OriginTrackedValue) {
return ((OriginTrackedValue) value).getOrigin();
}
return null;
}
@Override
public boolean isImmutable() {
return this.immutable;
}
}
| mit |
mjsolidarios/openhab | bundles/binding/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/RFXComValueSelector.java | 4083 | /**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.rfxcom;
import java.io.InvalidClassException;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.ContactItem;
import org.openhab.core.library.items.DimmerItem;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
import org.openhab.core.library.items.SwitchItem;
import org.openhab.core.library.items.RollershutterItem;
/**
* Represents all valid value selectors which could be processed by this
* binding.
*
* @author Pauli Anttila, Evert van Es, Neil Renaud
* @since 1.2.0
*/
public enum RFXComValueSelector {
RAW_DATA ("RawData", StringItem.class),
SHUTTER ("Shutter", RollershutterItem.class),
COMMAND ("Command", SwitchItem.class),
MOOD ("Mood", NumberItem.class),
SIGNAL_LEVEL ("SignalLevel", NumberItem.class),
DIMMING_LEVEL ("DimmingLevel", DimmerItem.class),
TEMPERATURE ("Temperature", NumberItem.class),
HUMIDITY ("Humidity", NumberItem.class),
HUMIDITY_STATUS ("HumidityStatus", StringItem.class),
BATTERY_LEVEL ("BatteryLevel", NumberItem.class),
PRESSURE("Pressure", NumberItem.class),
FORECAST("Forecast", NumberItem.class),
RAIN_RATE("RainRate", NumberItem.class),
RAIN_TOTAL("RainTotal", NumberItem.class),
WIND_DIRECTION("WindDirection", NumberItem.class),
WIND_SPEED("WindSpeed", NumberItem.class),
GUST("Gust", NumberItem.class),
CHILL_FACTOR("ChillFactor", NumberItem.class),
INSTANT_POWER("InstantPower", NumberItem.class),
TOTAL_USAGE("TotalUsage", NumberItem.class),
INSTANT_AMPS("InstantAmps", NumberItem.class),
TOTAL_AMP_HOURS("TotalAmpHours", NumberItem.class),
CHANNEL1_AMPS("Channel1Amps", NumberItem.class),
CHANNEL2_AMPS("Channel2Amps", NumberItem.class),
CHANNEL3_AMPS("Channel3Amps", NumberItem.class),
STATUS("Status", StringItem.class),
MOTION("Motion", SwitchItem.class),
CONTACT("Contact", ContactItem.class),
VOLTAGE("Voltage", NumberItem.class),
SET_POINT("SetPoint", NumberItem.class)
;
private final String text;
private Class<? extends Item> itemClass;
private RFXComValueSelector(final String text, Class<? extends Item> itemClass) {
this.text = text;
this.itemClass = itemClass;
}
@Override
public String toString() {
return text;
}
public Class<? extends Item> getItemClass() {
return itemClass;
}
/**
* Procedure to validate selector string.
*
* @param valueSelector
* selector string e.g. RawData, Command, Temperature
* @return true if item is valid.
* @throws IllegalArgumentException
* Not valid value selector.
* @throws InvalidClassException
* Not valid class for value selector.
*/
public static boolean validateBinding(String valueSelector,
Class<? extends Item> itemClass) throws IllegalArgumentException,
InvalidClassException {
for (RFXComValueSelector c : RFXComValueSelector.values()) {
if (c.text.equals(valueSelector)) {
if (c.getItemClass().equals(itemClass))
return true;
else
throw new InvalidClassException(
"Not valid class for value selector");
}
}
throw new IllegalArgumentException("Not valid value selector");
}
/**
* Procedure to convert selector string to value selector class.
*
* @param valueSelectorText
* selector string e.g. RawData, Command, Temperature
* @return corresponding selector value.
* @throws InvalidClassException
* Not valid class for value selector.
*/
public static RFXComValueSelector getValueSelector(String valueSelectorText)
throws IllegalArgumentException {
for (RFXComValueSelector c : RFXComValueSelector.values()) {
if (c.text.equals(valueSelectorText)) {
return c;
}
}
throw new IllegalArgumentException("Not valid value selector");
}
}
| epl-1.0 |
pspanja/ezpublish-kernel | eZ/Publish/Core/Persistence/Doctrine/Tests/SelectDoctrineQueryTest.php | 3017 | <?php
namespace eZ\Publish\Core\Persistence\Doctrine\Tests;
class SelectDoctrineQueryTest extends TestCase
{
public function testSimpleSelect()
{
$query = $this->handler->createSelectQuery();
$query->select(
'val1',
'val2'
)->from(
'query_test'
);
$this->assertEquals('SELECT val1, val2 FROM query_test', $query->getQuery());
}
public function testSelectWithWhereClause()
{
$query = $this->handler->createSelectQuery();
$query->select(
'val1',
'val2'
)->from(
'query_test'
)->where(
'foo = bar',
'bar = baz'
);
$this->assertEquals(
'SELECT val1, val2 FROM query_test WHERE foo = bar AND bar = baz',
$query->getQuery()
);
}
public function testSelectWithMultipleFromsAndJoins()
{
$query = $this->handler->createSelectQuery();
$query->select(
'*'
)->from(
'query_test'
)->innerJoin(
'query_inner',
'qtid',
'qiid'
)->from(
'second_from'
)->leftJoin(
'second_inner',
'sfid',
'siid'
);
$this->assertEquals(
'SELECT * FROM query_test INNER JOIN query_inner ON qtid = qiid, second_from LEFT JOIN second_inner ON sfid = siid',
$query->getQuery()
);
}
public function testSelectDistinct()
{
$query = $this->handler->createSelectQuery();
$query->selectDistinct('val1', 'val2')->from('query_test');
$this->assertEquals('SELECT DISTINCT val1, val2 FROM query_test', $query->getQuery());
}
public function testSelectGroupByHaving()
{
$query = $this->handler->createSelectQuery();
$query->select(
'*'
)->from(
'query_test'
)->groupBy(
'id'
)->having(
'foo = bar'
);
$this->assertEquals('SELECT * FROM query_test GROUP BY id HAVING foo = bar', $query->getQuery());
}
public function testLimitGeneration()
{
$query = $this->handler->createSelectQuery();
$query->select(
'*'
)->from(
'query_test'
);
$sql = (string)$query;
$query->limit(10, 10);
$limitSql = $this->connection->getDatabasePlatform()->modifyLimitQuery($sql, 10, 10);
$this->assertEquals($limitSql, (string)$query);
}
public function testSubselect()
{
$query = $this->handler->createSelectQuery();
$subselect = $query->subSelect();
$subselect->select(
'*'
)->from(
'query_test'
);
$query->select(
'*'
)->from(
$subselect
);
$this->assertEquals('SELECT * FROM ( SELECT * FROM query_test )', (string)$query);
}
}
| gpl-2.0 |
CTSATLAS/wordpress | wp-content/plugins/constant-contact-api/vendor/giggsey/libphonenumber-for-php/src/libphonenumber/geocoding/data/fr/32.php | 412 | <?php
/**
* This file is automatically @generated by {@link GeneratePhonePrefixData}.
* Please don't modify it directly.
*/
return array (
3212 => 'Tongres',
3215 => 'Malines',
3216 => 'Louvain',
322 => 'Bruxelles',
323 => 'Anvers',
3251 => 'Roulers',
3252 => 'Termonde',
3253 => 'Alost',
3255 => 'Renaix',
3256 => 'Courtrai',
3258 => 'Furnes',
3259 => 'Ostende',
329 => 'Gand',
);
| gpl-2.0 |
clembells/nerdyNummies | wp-content/plugins/advanced-custom-fields-pro/fields/google-map.php | 5822 | <?php
/*
* ACF Google Map Field Class
*
* All the logic for this field type
*
* @class acf_field_google_map
* @extends acf_field
* @package ACF
* @subpackage Fields
*/
if( ! class_exists('acf_field_google_map') ) :
class acf_field_google_map extends acf_field {
/*
* __construct
*
* This function will setup the field type data
*
* @type function
* @date 5/03/2014
* @since 5.0.0
*
* @param n/a
* @return n/a
*/
function __construct() {
// vars
$this->name = 'google_map';
$this->label = __("Google Map",'acf');
$this->category = 'jquery';
$this->defaults = array(
'height' => '',
'center_lat' => '',
'center_lng' => '',
'zoom' => ''
);
$this->default_values = array(
'height' => '400',
'center_lat' => '-37.81411',
'center_lng' => '144.96328',
'zoom' => '14'
);
$this->l10n = array(
'locating' => __("Locating",'acf'),
'browser_support' => __("Sorry, this browser does not support geolocation",'acf'),
);
// do not delete!
parent::__construct();
}
/*
* render_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function render_field( $field ) {
// validate value
if( empty($field['value']) ) {
$field['value'] = array();
}
// value
$field['value'] = acf_parse_args($field['value'], array(
'address' => '',
'lat' => '',
'lng' => ''
));
// default options
foreach( $this->default_values as $k => $v ) {
if( empty($field[ $k ]) ) {
$field[ $k ] = $v;
}
}
// vars
$atts = array(
'id' => $field['id'],
'class' => "acf-google-map {$field['class']}",
'data-id' => $field['id'] . '-' . uniqid(),
'data-lat' => $field['center_lat'],
'data-lng' => $field['center_lng'],
'data-zoom' => $field['zoom'],
);
// has value
if( $field['value']['address'] ) {
$atts['class'] .= ' -value';
}
?>
<div <?php acf_esc_attr_e($atts); ?>>
<div class="acf-hidden">
<?php foreach( $field['value'] as $k => $v ): ?>
<input type="hidden" class="input-<?php echo $k; ?>" name="<?php echo esc_attr($field['name']); ?>[<?php echo $k; ?>]" value="<?php echo esc_attr( $v ); ?>" />
<?php endforeach; ?>
</div>
<div class="title acf-soh">
<div class="actions acf-soh-target">
<a href="#" data-name="search" class="acf-icon acf-icon-search grey" title="<?php _e("Search", 'acf'); ?>"></a>
<a href="#" data-name="clear" class="acf-icon acf-icon-cancel grey" title="<?php _e("Clear location", 'acf'); ?>"></a>
<a href="#" data-name="locate" class="acf-icon acf-icon-location grey" title="<?php _e("Find current location", 'acf'); ?>"></a>
</div>
<input class="search" type="text" placeholder="<?php _e("Search for address...",'acf'); ?>" value="<?php echo $field['value']['address']; ?>" />
<i class="acf-loading"></i>
</div>
<div class="canvas" style="height: <?php echo $field['height']; ?>px"></div>
</div>
<?php
}
/*
* render_field_settings()
*
* Create extra options for your field. This is rendered when editing a field.
* The value of $field['name'] can be used (like bellow) to save extra data to the $field
*
* @type action
* @since 3.6
* @date 23/01/13
*
* @param $field - an array holding all the field's data
*/
function render_field_settings( $field ) {
// center_lat
acf_render_field_setting( $field, array(
'label' => __('Center','acf'),
'instructions' => __('Center the initial map','acf'),
'type' => 'text',
'name' => 'center_lat',
'prepend' => 'lat',
'placeholder' => $this->default_values['center_lat']
));
// center_lng
acf_render_field_setting( $field, array(
'label' => __('Center','acf'),
'instructions' => __('Center the initial map','acf'),
'type' => 'text',
'name' => 'center_lng',
'prepend' => 'lng',
'placeholder' => $this->default_values['center_lng'],
'wrapper' => array(
'data-append' => 'center_lat'
)
));
// zoom
acf_render_field_setting( $field, array(
'label' => __('Zoom','acf'),
'instructions' => __('Set the initial zoom level','acf'),
'type' => 'text',
'name' => 'zoom',
'placeholder' => $this->default_values['zoom']
));
// allow_null
acf_render_field_setting( $field, array(
'label' => __('Height','acf'),
'instructions' => __('Customise the map height','acf'),
'type' => 'text',
'name' => 'height',
'append' => 'px',
'placeholder' => $this->default_values['height']
));
}
/*
* validate_value
*
* description
*
* @type function
* @date 11/02/2014
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function validate_value( $valid, $value, $field, $input ){
// bail early if not required
if( ! $field['required'] ) {
return $valid;
}
if( empty($value) || empty($value['lat']) || empty($value['lng']) ) {
return false;
}
// return
return $valid;
}
/*
* update_value()
*
* This filter is appied to the $value before it is updated in the db
*
* @type filter
* @since 3.6
* @date 23/01/13
*
* @param $value - the value which will be saved in the database
* @param $post_id - the $post_id of which the value will be saved
* @param $field - the field array holding all the field options
*
* @return $value - the modified value
*/
function update_value( $value, $post_id, $field ) {
if( empty($value) || empty($value['lat']) || empty($value['lng']) ) {
return false;
}
// return
return $value;
}
}
new acf_field_google_map();
endif;
?>
| gpl-2.0 |
dmlloyd/openjdk-modules | langtools/test/tools/javac/limits/ArrayDims5.java | 1961 | /*
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4741759
* @summary javac fails to diagnose too many array dimensions
* @author gafter
*
* @compile/fail/ref=ArrayDims5.out -XDrawDiagnostics ArrayDims5.java
*/
public abstract class ArrayDims5 {
abstract int
[][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][]
f()
[][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][]
[][][][][][][][][][][][][][][][];
}
| gpl-2.0 |
kvar/ansible | lib/ansible/modules/cloud/azure/azure_rm_networkinterface.py | 39110 | #!/usr/bin/python
#
# Copyright (c) 2016 Matt Davis, <mdavis@ansible.com>
# Chris Houseknecht, <house@redhat.com>
# Yuwei ZHou, <yuwzho@microsoft.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: azure_rm_networkinterface
version_added: '2.1'
short_description: Manage Azure network interfaces
description:
- Create, update or delete a network interface.
- When creating a network interface you must provide the name of an existing virtual network, the name of an existing subnet within the virtual network.
- A default security group and public IP address will be created automatically.
- Or you can provide the name of an existing security group and public IP address.
- See the examples below for more details.
options:
resource_group:
description:
- Name of a resource group where the network interface exists or will be created.
required: true
name:
description:
- Name of the network interface.
required: true
state:
description:
- Assert the state of the network interface. Use C(present) to create or update an interface and
C(absent) to delete an interface.
default: present
choices:
- absent
- present
location:
description:
- Valid Azure location. Defaults to location of the resource group.
virtual_network:
description:
- An existing virtual network with which the network interface will be associated. Required when creating a network interface.
- It can be the virtual network's name.
- Make sure your virtual network is in the same resource group as NIC when you give only the name.
- It can be the virtual network's resource id.
- It can be a dict which contains I(name) and I(resource_group) of the virtual network.
aliases:
- virtual_network_name
required: true
subnet_name:
description:
- Name of an existing subnet within the specified virtual network. Required when creating a network interface.
- Use the C(virtual_network)'s resource group.
aliases:
- subnet
required: true
os_type:
description:
- Determines any rules to be added to a default security group.
- When creating a network interface, if no security group name is provided, a default security group will be created.
- If the I(os_type=Windows), a rule allowing RDP access will be added.
- If the I(os_type=Linux), a rule allowing SSH access will be added.
choices:
- Windows
- Linux
default: Linux
private_ip_address:
description:
- (Deprecate) Valid IPv4 address that falls within the specified subnet.
- This option will be deprecated in 2.9, use I(ip_configurations) instead.
private_ip_allocation_method:
description:
- (Deprecate) Whether or not the assigned IP address is permanent.
- When creating a network interface, if you specify I(private_ip_address=Static), you must provide a value for I(private_ip_address).
- You can update the allocation method to C(Static) after a dynamic private IP address has been assigned.
- This option will be deprecated in 2.9, use I(ip_configurations) instead.
default: Dynamic
choices:
- Dynamic
- Static
public_ip:
description:
- (Deprecate) When creating a network interface, if no public IP address name is provided a default public IP address will be created.
- Set to C(false) if you do not want a public IP address automatically created.
- This option will be deprecated in 2.9, use I(ip_configurations) instead.
type: bool
default: 'yes'
public_ip_address_name:
description:
- (Deprecate) Name of an existing public IP address object to associate with the security group.
- This option will be deprecated in 2.9, use I(ip_configurations) instead.
aliases:
- public_ip_address
- public_ip_name
public_ip_allocation_method:
description:
- (Deprecate) If a I(public_ip_address_name) is not provided, a default public IP address will be created.
- The allocation method determines whether or not the public IP address assigned to the network interface is permanent.
- This option will be deprecated in 2.9, use I(ip_configurations) instead.
choices:
- Dynamic
- Static
default: Dynamic
ip_configurations:
description:
- List of IP configurations. Each configuration object should include
field I(private_ip_address), I(private_ip_allocation_method), I(public_ip_address_name), I(public_ip), I(public_ip_allocation_method), I(name).
suboptions:
name:
description:
- Name of the IP configuration.
required: true
private_ip_address:
description:
- Private IP address for the IP configuration.
private_ip_allocation_method:
description:
- Private IP allocation method.
choices:
- Dynamic
- Static
default: Dynamic
public_ip_address_name:
description:
- Name of the public IP address. None for disable IP address.
aliases:
- public_ip_address
- public_ip_name
public_ip_allocation_method:
description:
- Public IP allocation method.
choices:
- Dynamic
- Static
default: Dynamic
load_balancer_backend_address_pools:
description:
- List of existing load-balancer backend address pools to associate with the network interface.
- Can be written as a resource ID.
- Also can be a dict of I(name) and I(load_balancer).
version_added: '2.6'
primary:
description:
- Whether the IP configuration is the primary one in the list.
type: bool
default: 'no'
application_security_groups:
description:
- List of application security groups in which the IP configuration is included.
- Element of the list could be a resource id of application security group, or dict of I(resource_group) and I(name).
version_added: '2.8'
version_added: '2.5'
enable_accelerated_networking:
description:
- Whether the network interface should be created with the accelerated networking feature or not.
type: bool
version_added: '2.7'
default: False
create_with_security_group:
description:
- Whether a security group should be be created with the NIC.
- If this flag set to C(True) and no I(security_group) set, a default security group will be created.
type: bool
version_added: '2.6'
default: True
security_group:
description:
- An existing security group with which to associate the network interface.
- If not provided, a default security group will be created when I(create_with_security_group=true).
- It can be the name of security group.
- Make sure the security group is in the same resource group when you only give its name.
- It can be the resource id.
- It can be a dict contains security_group's I(name) and I(resource_group).
aliases:
- security_group_name
open_ports:
description:
- When a default security group is created for a Linux host a rule will be added allowing inbound TCP
connections to the default SSH port C(22), and for a Windows host rules will be added allowing inbound
access to RDP ports C(3389) and C(5986). Override the default ports by providing a list of open ports.
enable_ip_forwarding:
description:
- Whether to enable IP forwarding.
aliases:
- ip_forwarding
type: bool
default: False
version_added: '2.7'
dns_servers:
description:
- Which DNS servers should the NIC lookup.
- List of IP addresses.
type: list
version_added: '2.7'
extends_documentation_fragment:
- azure
- azure_tags
author:
- Chris Houseknecht (@chouseknecht)
- Matt Davis (@nitzmahone)
- Yuwei Zhou (@yuwzho)
'''
EXAMPLES = '''
- name: Create a network interface with minimal parameters
azure_rm_networkinterface:
name: nic001
resource_group: myResourceGroup
virtual_network: vnet001
subnet_name: subnet001
ip_configurations:
- name: ipconfig1
public_ip_address_name: publicip001
primary: True
- name: Create a network interface with private IP address only (no Public IP)
azure_rm_networkinterface:
name: nic001
resource_group: myResourceGroup
virtual_network: vnet001
subnet_name: subnet001
create_with_security_group: False
ip_configurations:
- name: ipconfig1
primary: True
- name: Create a network interface for use in a Windows host (opens RDP port) with custom RDP port
azure_rm_networkinterface:
name: nic002
resource_group: myResourceGroup
virtual_network: vnet001
subnet_name: subnet001
os_type: Windows
rdp_port: 3399
security_group: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkSecurit
yGroups/nsg001"
ip_configurations:
- name: ipconfig1
public_ip_address_name: publicip001
primary: True
- name: Create a network interface using existing security group and public IP
azure_rm_networkinterface:
name: nic003
resource_group: myResourceGroup
virtual_network: vnet001
subnet_name: subnet001
security_group: secgroup001
ip_configurations:
- name: ipconfig1
public_ip_address_name: publicip001
primary: True
- name: Create a network with multiple ip configurations
azure_rm_networkinterface:
name: nic004
resource_group: myResourceGroup
subnet_name: subnet001
virtual_network: vnet001
security_group:
name: testnic002
resource_group: Testing1
ip_configurations:
- name: ipconfig1
public_ip_address_name: publicip001
primary: True
- name: ipconfig2
load_balancer_backend_address_pools:
- "{{ loadbalancer001.state.backend_address_pools[0].id }}"
- name: backendaddrpool1
load_balancer: loadbalancer001
- name: Create a network interface in accelerated networking mode
azure_rm_networkinterface:
name: nic005
resource_group: myResourceGroup
virtual_network_name: vnet001
subnet_name: subnet001
enable_accelerated_networking: True
- name: Create a network interface with IP forwarding
azure_rm_networkinterface:
name: nic001
resource_group: myResourceGroup
virtual_network: vnet001
subnet_name: subnet001
ip_forwarding: True
ip_configurations:
- name: ipconfig1
public_ip_address_name: publicip001
primary: True
- name: Create a network interface with dns servers
azure_rm_networkinterface:
name: nic009
resource_group: myResourceGroup
virtual_network: vnet001
subnet_name: subnet001
dns_servers:
- 8.8.8.8
- name: Delete network interface
azure_rm_networkinterface:
resource_group: myResourceGroup
name: nic003
state: absent
'''
RETURN = '''
state:
description:
- The current state of the network interface.
returned: always
type: complex
contains:
dns_server:
description:
- Which DNS servers should the NIC lookup.
- List of IP addresses.
type: list
sample: ['8.9.10.11', '7.8.9.10']
dns_setting:
description:
- The DNS settings in network interface.
type: dict
sample: {
"applied_dns_servers": [],
"dns_servers": [
"8.9.10.11",
"7.8.9.10"
],
"internal_dns_name_label": null,
"internal_fqdn": null
}
enable_ip_forwarding:
description:
Whether to enable IP forwarding.
type: bool
sample: true
etag:
description:
- A unique read-only string that changes whenever the resource is updated.
type: str
sample: 'W/"be115a43-2148-4545-a324-f33ad444c926"'
id:
description:
- Id of the network interface.
type: str
sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/networkInterfaces/nic003"
enable_accelerated_networking:
description:
- Whether the network interface should be created with the accelerated networking feature or not.
type: bool
sample: true
ip_configurations:
description:
- List of IP configurations.
type: complex
contains:
name:
description:
- Name of the IP configuration.
type: str
sample: default
load_balancer_backend_address_pools:
description:
- List of existing load-balancer backend address pools to associate with the network interface.
type: list
private_ip_address:
description:
- Private IP address for the IP configuration.
type: str
sample: "10.1.0.10"
private_ip_allocation_method:
description:
- Private IP allocation method.
type: str
sample: "Static"
public_ip_address:
description:
- Name of the public IP address. None for disable IP address.
type: dict
sample: {
"id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/myResourceGroup/providers/Microsoft.Network/publicIPAddresse
s/publicip001",
"name": "publicip001"
}
subnet:
description:
- The reference of the subnet resource.
type: dict
sample: {
"id": "/subscriptions/xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/
myresourcegroup/providers/Microsoft.Network/virtualNetworks/tnb57dc95318/subnets/tnb57dc95318",
"name": "tnb57dc95318",
"resource_group": "myresourcegroup",
"virtual_network_name": "tnb57dc95318"
}
location:
description:
- The network interface resource location.
type: str
sample: eastus
mac_address:
description:
- The MAC address of the network interface.
type: str
name:
description:
- Name of the network interface.
type: str
sample: nic003
network_security_group:
description:
- The reference of the network security group resource.
type: dict
sample: {
"id": "/subscriptions//xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroup/
myResourceGroup/providers/Microsoft.Network/networkSecurityGroups/nsg001",
"name": "nsg001"
}
primary:
description:
- Get whether this is a primary network interface on virtual machine.
type: bool
sample: true
provisioning_state:
description:
- The provisioning state of the public IP resource.
type: str
sample: Succeeded
tags:
description:
-Tags of the network interface.
type: dict
sample: { 'key': 'value' }
type:
description:
- Type of the resource.
type: str
sample: "Microsoft.Network/networkInterfaces"
'''
try:
from msrestazure.tools import parse_resource_id, resource_id, is_valid_resource_id
from msrestazure.azure_exceptions import CloudError
except ImportError:
# This is handled in azure_rm_common
pass
from ansible.module_utils.azure_rm_common import AzureRMModuleBase, azure_id_to_dict, normalize_location_name, format_resource_id
from ansible.module_utils._text import to_native
def subnet_to_dict(subnet):
dic = azure_id_to_dict(subnet.id)
return dict(
id=subnet.id,
virtual_network_name=dic.get('virtualNetworks'),
resource_group=dic.get('resourceGroups'),
name=dic.get('subnets')
)
def nic_to_dict(nic):
ip_configurations = [
dict(
name=config.name,
private_ip_address=config.private_ip_address,
private_ip_allocation_method=config.private_ip_allocation_method,
subnet=subnet_to_dict(config.subnet),
primary=config.primary,
load_balancer_backend_address_pools=([item.id for item in config.load_balancer_backend_address_pools]
if config.load_balancer_backend_address_pools else None),
public_ip_address=dict(
id=config.public_ip_address.id,
name=azure_id_to_dict(config.public_ip_address.id).get('publicIPAddresses'),
public_ip_allocation_method=config.public_ip_address.public_ip_allocation_method
) if config.public_ip_address else None,
application_security_groups=([asg.id for asg in config.application_security_groups]
if config.application_security_groups else None)
) for config in nic.ip_configurations
]
return dict(
id=nic.id,
name=nic.name,
type=nic.type,
location=nic.location,
tags=nic.tags,
network_security_group=dict(
id=nic.network_security_group.id,
name=azure_id_to_dict(nic.network_security_group.id).get('networkSecurityGroups')
) if nic.network_security_group else None,
dns_settings=dict(
dns_servers=nic.dns_settings.dns_servers,
applied_dns_servers=nic.dns_settings.applied_dns_servers,
internal_dns_name_label=nic.dns_settings.internal_dns_name_label,
internal_fqdn=nic.dns_settings.internal_fqdn
),
ip_configurations=ip_configurations,
ip_configuration=ip_configurations[0] if len(ip_configurations) == 1 else None, # for compatible issue, keep this field
mac_address=nic.mac_address,
enable_ip_forwarding=nic.enable_ip_forwarding,
provisioning_state=nic.provisioning_state,
etag=nic.etag,
enable_accelerated_networking=nic.enable_accelerated_networking,
dns_servers=nic.dns_settings.dns_servers,
)
ip_configuration_spec = dict(
name=dict(type='str', required=True),
private_ip_address=dict(type='str'),
private_ip_allocation_method=dict(type='str', choices=['Dynamic', 'Static'], default='Dynamic'),
public_ip_address_name=dict(type='str', aliases=['public_ip_address', 'public_ip_name']),
public_ip_allocation_method=dict(type='str', choices=['Dynamic', 'Static'], default='Dynamic'),
load_balancer_backend_address_pools=dict(type='list'),
primary=dict(type='bool', default=False),
application_security_groups=dict(type='list', elements='raw')
)
class AzureRMNetworkInterface(AzureRMModuleBase):
def __init__(self):
self.module_arg_spec = dict(
resource_group=dict(type='str', required=True),
name=dict(type='str', required=True),
location=dict(type='str'),
enable_accelerated_networking=dict(type='bool', default=False),
create_with_security_group=dict(type='bool', default=True),
security_group=dict(type='raw', aliases=['security_group_name']),
state=dict(default='present', choices=['present', 'absent']),
private_ip_address=dict(type='str'),
private_ip_allocation_method=dict(type='str', choices=['Dynamic', 'Static'], default='Dynamic'),
public_ip_address_name=dict(type='str', aliases=['public_ip_address', 'public_ip_name']),
public_ip=dict(type='bool', default=True),
subnet_name=dict(type='str', aliases=['subnet']),
virtual_network=dict(type='raw', aliases=['virtual_network_name']),
public_ip_allocation_method=dict(type='str', choices=['Dynamic', 'Static'], default='Dynamic'),
ip_configurations=dict(type='list', default=None, elements='dict', options=ip_configuration_spec),
os_type=dict(type='str', choices=['Windows', 'Linux'], default='Linux'),
open_ports=dict(type='list'),
enable_ip_forwarding=dict(type='bool', aliases=['ip_forwarding'], default=False),
dns_servers=dict(type='list'),
)
required_if = [
('state', 'present', ['subnet_name', 'virtual_network'])
]
self.resource_group = None
self.name = None
self.location = None
self.create_with_security_group = None
self.enable_accelerated_networking = None
self.security_group = None
self.private_ip_address = None
self.private_ip_allocation_method = None
self.public_ip_address_name = None
self.public_ip = None
self.subnet_name = None
self.virtual_network = None
self.public_ip_allocation_method = None
self.state = None
self.tags = None
self.os_type = None
self.open_ports = None
self.enable_ip_forwarding = None
self.ip_configurations = None
self.dns_servers = None
self.results = dict(
changed=False,
state=dict(),
)
super(AzureRMNetworkInterface, self).__init__(derived_arg_spec=self.module_arg_spec,
supports_check_mode=True,
required_if=required_if)
def exec_module(self, **kwargs):
for key in list(self.module_arg_spec.keys()) + ['tags']:
setattr(self, key, kwargs[key])
results = None
changed = False
nic = None
nsg = None
resource_group = self.get_resource_group(self.resource_group)
if not self.location:
# Set default location
self.location = resource_group.location
self.location = normalize_location_name(self.location)
# parse the virtual network resource group and name
self.virtual_network = self.parse_resource_to_dict(self.virtual_network)
# if not set the security group name, use nic name for default
self.security_group = self.parse_resource_to_dict(self.security_group or self.name)
# if application security groups set, convert to resource id format
if self.ip_configurations:
for config in self.ip_configurations:
if config.get('application_security_groups'):
asgs = []
for asg in config['application_security_groups']:
asg_resource_id = asg
if isinstance(asg, str) and (not is_valid_resource_id(asg)):
asg = self.parse_resource_to_dict(asg)
if isinstance(asg, dict):
asg_resource_id = format_resource_id(val=asg['name'],
subscription_id=self.subscription_id,
namespace='Microsoft.Network',
types='applicationSecurityGroups',
resource_group=asg['resource_group'])
asgs.append(asg_resource_id)
if len(asgs) > 0:
config['application_security_groups'] = asgs
if self.state == 'present' and not self.ip_configurations:
# construct the ip_configurations array for compatible
self.deprecate('Setting ip_configuration flatten is deprecated and will be removed.'
' Using ip_configurations list to define the ip configuration', version='2.9')
self.ip_configurations = [
dict(
private_ip_address=self.private_ip_address,
private_ip_allocation_method=self.private_ip_allocation_method,
public_ip_address_name=self.public_ip_address_name if self.public_ip else None,
public_ip_allocation_method=self.public_ip_allocation_method,
name='default',
primary=True
)
]
try:
self.log('Fetching network interface {0}'.format(self.name))
nic = self.network_client.network_interfaces.get(self.resource_group, self.name)
self.log('Network interface {0} exists'.format(self.name))
self.check_provisioning_state(nic, self.state)
results = nic_to_dict(nic)
self.log(results, pretty_print=True)
nsg = None
if self.state == 'present':
# check for update
update_tags, results['tags'] = self.update_tags(results['tags'])
if update_tags:
changed = True
if self.create_with_security_group != bool(results.get('network_security_group')):
self.log("CHANGED: add or remove network interface {0} network security group".format(self.name))
changed = True
if self.enable_accelerated_networking != bool(results.get('enable_accelerated_networking')):
self.log("CHANGED: Accelerated Networking set to {0} (previously {1})".format(
self.enable_accelerated_networking,
results.get('enable_accelerated_networking')))
changed = True
if self.enable_ip_forwarding != bool(results.get('enable_ip_forwarding')):
self.log("CHANGED: IP forwarding set to {0} (previously {1})".format(
self.enable_ip_forwarding,
results.get('enable_ip_forwarding')))
changed = True
# We need to ensure that dns_servers are list like
dns_servers_res = results.get('dns_settings').get('dns_servers')
_dns_servers_set = sorted(self.dns_servers) if isinstance(self.dns_servers, list) else list()
_dns_servers_res = sorted(dns_servers_res) if isinstance(self.dns_servers, list) else list()
if _dns_servers_set != _dns_servers_res:
self.log("CHANGED: DNS servers set to {0} (previously {1})".format(
", ".join(_dns_servers_set),
", ".join(_dns_servers_res)))
changed = True
if not changed:
nsg = self.get_security_group(self.security_group['resource_group'], self.security_group['name'])
if nsg and results.get('network_security_group') and results['network_security_group'].get('id') != nsg.id:
self.log("CHANGED: network interface {0} network security group".format(self.name))
changed = True
if results['ip_configurations'][0]['subnet']['virtual_network_name'] != self.virtual_network['name']:
self.log("CHANGED: network interface {0} virtual network name".format(self.name))
changed = True
if results['ip_configurations'][0]['subnet']['resource_group'] != self.virtual_network['resource_group']:
self.log("CHANGED: network interface {0} virtual network resource group".format(self.name))
changed = True
if results['ip_configurations'][0]['subnet']['name'] != self.subnet_name:
self.log("CHANGED: network interface {0} subnet name".format(self.name))
changed = True
# check the ip_configuration is changed
# construct two set with the same structure and then compare
# the list should contains:
# name, private_ip_address, public_ip_address_name, private_ip_allocation_method, subnet_name
ip_configuration_result = self.construct_ip_configuration_set(results['ip_configurations'])
ip_configuration_request = self.construct_ip_configuration_set(self.ip_configurations)
if ip_configuration_result != ip_configuration_request:
self.log("CHANGED: network interface {0} ip configurations".format(self.name))
changed = True
elif self.state == 'absent':
self.log("CHANGED: network interface {0} exists but requested state is 'absent'".format(self.name))
changed = True
except CloudError:
self.log('Network interface {0} does not exist'.format(self.name))
if self.state == 'present':
self.log("CHANGED: network interface {0} does not exist but requested state is 'present'".format(self.name))
changed = True
self.results['changed'] = changed
self.results['state'] = results
if self.check_mode:
return self.results
if changed:
if self.state == 'present':
subnet = self.network_models.SubResource(
id='/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/virtualNetworks/{2}/subnets/{3}'.format(
self.virtual_network['subscription_id'],
self.virtual_network['resource_group'],
self.virtual_network['name'],
self.subnet_name))
nic_ip_configurations = [
self.network_models.NetworkInterfaceIPConfiguration(
private_ip_allocation_method=ip_config.get('private_ip_allocation_method'),
private_ip_address=ip_config.get('private_ip_address'),
name=ip_config.get('name'),
subnet=subnet,
public_ip_address=self.get_or_create_public_ip_address(ip_config),
load_balancer_backend_address_pools=([self.network_models.BackendAddressPool(id=self.backend_addr_pool_id(bap_id))
for bap_id in ip_config.get('load_balancer_backend_address_pools')]
if ip_config.get('load_balancer_backend_address_pools') else None),
primary=ip_config.get('primary'),
application_security_groups=([self.network_models.ApplicationSecurityGroup(id=asg_id)
for asg_id in ip_config.get('application_security_groups')]
if ip_config.get('application_security_groups') else None)
) for ip_config in self.ip_configurations
]
nsg = self.create_default_securitygroup(self.security_group['resource_group'],
self.location,
self.security_group['name'],
self.os_type,
self.open_ports) if self.create_with_security_group else None
self.log('Creating or updating network interface {0}'.format(self.name))
nic = self.network_models.NetworkInterface(
id=results['id'] if results else None,
location=self.location,
tags=self.tags,
ip_configurations=nic_ip_configurations,
enable_accelerated_networking=self.enable_accelerated_networking,
enable_ip_forwarding=self.enable_ip_forwarding,
network_security_group=nsg
)
if self.dns_servers:
dns_settings = self.network_models.NetworkInterfaceDnsSettings(
dns_servers=self.dns_servers)
nic.dns_settings = dns_settings
self.results['state'] = self.create_or_update_nic(nic)
elif self.state == 'absent':
self.log('Deleting network interface {0}'.format(self.name))
self.delete_nic()
# Delete doesn't return anything. If we get this far, assume success
self.results['state']['status'] = 'Deleted'
return self.results
def get_or_create_public_ip_address(self, ip_config):
name = ip_config.get('public_ip_address_name')
if not (self.public_ip and name):
return None
pip = self.get_public_ip_address(name)
if not pip:
params = self.network_models.PublicIPAddress(
location=self.location,
public_ip_allocation_method=ip_config.get('public_ip_allocation_method'),
)
try:
poller = self.network_client.public_ip_addresses.create_or_update(self.resource_group, name, params)
pip = self.get_poller_result(poller)
except CloudError as exc:
self.fail("Error creating {0} - {1}".format(name, str(exc)))
return pip
def create_or_update_nic(self, nic):
try:
poller = self.network_client.network_interfaces.create_or_update(self.resource_group, self.name, nic)
new_nic = self.get_poller_result(poller)
return nic_to_dict(new_nic)
except Exception as exc:
self.fail("Error creating or updating network interface {0} - {1}".format(self.name, str(exc)))
def delete_nic(self):
try:
poller = self.network_client.network_interfaces.delete(self.resource_group, self.name)
self.get_poller_result(poller)
except Exception as exc:
self.fail("Error deleting network interface {0} - {1}".format(self.name, str(exc)))
return True
def get_public_ip_address(self, name):
self.log("Fetching public ip address {0}".format(name))
try:
return self.network_client.public_ip_addresses.get(self.resource_group, name)
except Exception as exc:
return None
def get_security_group(self, resource_group, name):
self.log("Fetching security group {0}".format(name))
try:
return self.network_client.network_security_groups.get(resource_group, name)
except Exception as exc:
return None
def backend_addr_pool_id(self, val):
if isinstance(val, dict):
lb = val.get('load_balancer', None)
name = val.get('name', None)
if lb and name:
return resource_id(subscription=self.subscription_id,
resource_group=self.resource_group,
namespace='Microsoft.Network',
type='loadBalancers',
name=lb,
child_type_1='backendAddressPools',
child_name_1=name)
return val
def construct_ip_configuration_set(self, raw):
configurations = [str(dict(
private_ip_allocation_method=to_native(item.get('private_ip_allocation_method')),
public_ip_address_name=(to_native(item.get('public_ip_address').get('name'))
if item.get('public_ip_address') else to_native(item.get('public_ip_address_name'))),
primary=item.get('primary'),
load_balancer_backend_address_pools=(set([to_native(self.backend_addr_pool_id(id))
for id in item.get('load_balancer_backend_address_pools')])
if item.get('load_balancer_backend_address_pools') else None),
application_security_groups=(set([to_native(asg_id) for asg_id in item.get('application_security_groups')])
if item.get('application_security_groups') else None),
name=to_native(item.get('name'))
)) for item in raw]
return set(configurations)
def main():
AzureRMNetworkInterface()
if __name__ == '__main__':
main()
| gpl-3.0 |
jumbucks/go-jumbucksee | Godeps/_workspace/src/github.com/gizak/termui/linechart_others.go | 264 | // Copyright 2016 Zack Guo <gizak@icloud.com>. All rights reserved.
// Use of this source code is governed by a MIT license that can
// be found in the LICENSE file.
// +build !windows
package termui
const VDASH = '┊'
const HDASH = '┈'
const ORIGIN = '└'
| gpl-3.0 |
shakuzen/spring-boot | spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-ldap/src/test/java/smoketest/data/ldap/SampleLdapApplicationTests.java | 1275 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package smoketest.data.ldap;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SampleLdapApplication}.
*
* @author Phillip Webb
*/
@ExtendWith(OutputCaptureExtension.class)
@SpringBootTest
class SampleLdapApplicationTests {
@Test
void testDefaultSettings(CapturedOutput output) {
assertThat(output).contains("cn=Alice Smith");
}
}
| apache-2.0 |
nibin/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/util/io/StringStreamSource.java | 1020 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.impl.util.io;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* @author Tom Baeyens
*/
public class StringStreamSource implements StreamSource {
String string;
public StringStreamSource(String string) {
this.string = string;
}
public InputStream getInputStream() {
return new ByteArrayInputStream(string.getBytes());
}
public String toString() {
return "String";
}
}
| apache-2.0 |
raehalme/keycloak | model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCache.java | 2256 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.models.cache.infinispan;
import org.keycloak.models.cache.infinispan.entities.CachedClient;
import org.keycloak.models.cache.infinispan.entities.CachedClientTemplate;
import org.keycloak.models.cache.infinispan.entities.CachedGroup;
import org.keycloak.models.cache.infinispan.entities.CachedRealm;
import org.keycloak.models.cache.infinispan.entities.CachedRole;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface RealmCache {
void clear();
CachedRealm getRealm(String id);
void invalidateRealm(CachedRealm realm);
void addRealm(CachedRealm realm);
CachedRealm getRealmByName(String name);
void invalidateRealmById(String id);
CachedClient getClient(String id);
void invalidateClient(CachedClient app);
void evictClientById(String id);
void addClient(CachedClient app);
void invalidateClientById(String id);
CachedRole getRole(String id);
void invalidateRole(CachedRole role);
void evictRoleById(String id);
void addRole(CachedRole role);
void invalidateRoleById(String id);
CachedGroup getGroup(String id);
void invalidateGroup(CachedGroup role);
void addGroup(CachedGroup role);
void invalidateGroupById(String id);
CachedClientTemplate getClientTemplate(String id);
void invalidateClientTemplate(CachedClientTemplate app);
void evictClientTemplateById(String id);
void addClientTemplate(CachedClientTemplate app);
void invalidateClientTemplateById(String id);
}
| apache-2.0 |
liangpengfei/UltimateAndroid | UltimateAndroidNormal/UltimateAndroid/src/com/marshalchen/common/usefulModule/standuptimer/dao/CannotUpdateMeetingException.java | 321 | /*
* Copyright (c) 2014. Marshal Chen.
*/
package com.marshalchen.common.usefulModule.standuptimer.dao;
public class CannotUpdateMeetingException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CannotUpdateMeetingException(String message) {
super(message);
}
}
| apache-2.0 |
headwirecom/sling | bundles/extensions/discovery/base/src/test/java/org/apache/sling/discovery/base/connectors/announcement/AnnouncementRegistryImplTest.java | 18905 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.discovery.base.connectors.announcement;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.List;
import java.util.UUID;
import javax.jcr.Session;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.commons.testing.jcr.RepositoryProvider;
import org.apache.sling.commons.testing.junit.categories.Slow;
import org.apache.sling.discovery.ClusterView;
import org.apache.sling.discovery.InstanceDescription;
import org.apache.sling.discovery.base.connectors.BaseConfig;
import org.apache.sling.discovery.base.its.setup.TopologyHelper;
import org.apache.sling.discovery.base.its.setup.VirtualInstanceHelper;
import org.apache.sling.discovery.base.its.setup.mock.MockFactory;
import org.apache.sling.discovery.base.its.setup.mock.SimpleConnectorConfig;
import org.apache.sling.discovery.commons.providers.DefaultClusterView;
import org.apache.sling.discovery.commons.providers.DefaultInstanceDescription;
import org.apache.sling.discovery.commons.providers.spi.base.DummySlingSettingsService;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
public class AnnouncementRegistryImplTest {
private AnnouncementRegistryImpl registry;
private String slingId;
private ResourceResolverFactory resourceResolverFactory;
private BaseConfig config;
@Before
public void setup() throws Exception {
resourceResolverFactory = MockFactory
.mockResourceResolverFactory();
config = new SimpleConnectorConfig() {
public long getConnectorPingTimeout() {
// 10s for tests that also run on apache jenkins
return 10;
};
};
slingId = UUID.randomUUID().toString();
Session l = RepositoryProvider.instance().getRepository()
.loginAdministrative(null);
try {
l.removeItem("/var");
l.save();
l.logout();
} catch (Exception e) {
l.refresh(false);
l.logout();
}
registry = AnnouncementRegistryImpl.testConstructorAndActivate(
resourceResolverFactory, new DummySlingSettingsService(slingId), config);
}
@Test
public void testRegisterUnregister() throws Exception {
doTestRegisterUnregister(false);
}
@Category(Slow.class)
@Test
public void testRegisterUnregister_Slow() throws Exception {
doTestRegisterUnregister(true);
}
private void doTestRegisterUnregister(boolean includeFinalExpiryCheck) throws Exception {
try{
registry.registerAnnouncement(null);
fail("should complain");
} catch(IllegalArgumentException iae) {
// ok
}
try{
registry.unregisterAnnouncement(null);
fail("should complain");
} catch(IllegalArgumentException iae) {
// ok
}
try{
registry.unregisterAnnouncement("");
fail("should complain");
} catch(IllegalArgumentException iae) {
// ok
}
try{
new Announcement(null);
fail("should complain");
} catch(IllegalArgumentException iae) {
// ok
}
try{
new Announcement("");
fail("should complain");
} catch(IllegalArgumentException iae) {
// ok
}
Announcement ann = new Announcement(slingId);
assertFalse(ann.isValid());
assertFalse(registry.registerAnnouncement(ann)!=-1);
DefaultClusterView localCluster = new DefaultClusterView(UUID.randomUUID().toString());
ann.setLocalCluster(localCluster);
assertFalse(ann.isValid());
assertFalse(registry.registerAnnouncement(ann)!=-1);
try{
registry.listInstances(localCluster);
fail("doing getInstances() on an empty cluster should throw an illegalstateexception");
} catch(IllegalStateException ise) {
// ok
}
DefaultInstanceDescription instance = TopologyHelper.createInstanceDescription(ann.getOwnerId(), true, localCluster);
assertEquals(instance.getSlingId(), ann.getOwnerId());
assertTrue(ann.isValid());
assertTrue(registry.registerAnnouncement(ann)!=-1);
assertEquals(1, registry.listInstances(localCluster).size());
registry.checkExpiredAnnouncements();
assertEquals(1, registry.listInstances(localCluster).size());
registry.unregisterAnnouncement(ann.getOwnerId());
assertEquals(0, registry.listInstances(localCluster).size());
assertTrue(ann.isValid());
assertTrue(registry.registerAnnouncement(ann)!=-1);
assertEquals(1, registry.listInstances(localCluster).size());
if (includeFinalExpiryCheck) {
Thread.sleep(10500);
assertEquals(0, registry.listInstances(localCluster).size());
}
}
@Test
public void testLists() throws Exception {
try{
registry.listAnnouncementsInSameCluster(null);
fail("should complain");
} catch(IllegalArgumentException iae) {
// ok
}
try{
registry.listAnnouncementsInSameCluster(null);
fail("should complain");
} catch(IllegalArgumentException iae) {
// ok
}
assertEquals(0, registry.listLocalAnnouncements().size());
assertEquals(0, registry.listLocalIncomingAnnouncements().size());
DefaultClusterView localCluster = new DefaultClusterView(UUID.randomUUID().toString());
DefaultInstanceDescription instance = TopologyHelper.createInstanceDescription(slingId, true, localCluster);
assertEquals(0, registry.listAnnouncementsInSameCluster(localCluster).size());
assertEquals(0, registry.listLocalAnnouncements().size());
assertEquals(0, registry.listLocalIncomingAnnouncements().size());
Announcement ann = new Announcement(slingId);
ann.setLocalCluster(localCluster);
ann.setInherited(true);
registry.registerAnnouncement(ann);
assertEquals(1, registry.listAnnouncementsInSameCluster(localCluster).size());
assertEquals(1, registry.listLocalAnnouncements().size());
assertEquals(0, registry.listLocalIncomingAnnouncements().size());
ann.setInherited(true);
assertEquals(0, registry.listLocalIncomingAnnouncements().size());
assertTrue(registry.hasActiveAnnouncement(slingId));
assertFalse(registry.hasActiveAnnouncement(UUID.randomUUID().toString()));
registry.unregisterAnnouncement(slingId);
assertEquals(0, registry.listAnnouncementsInSameCluster(localCluster).size());
assertEquals(0, registry.listLocalAnnouncements().size());
assertEquals(0, registry.listLocalIncomingAnnouncements().size());
assertFalse(registry.hasActiveAnnouncement(slingId));
assertFalse(registry.hasActiveAnnouncement(UUID.randomUUID().toString()));
ann.setInherited(false);
registry.registerAnnouncement(ann);
assertEquals(1, registry.listAnnouncementsInSameCluster(localCluster).size());
assertEquals(1, registry.listLocalAnnouncements().size());
assertEquals(1, registry.listLocalIncomingAnnouncements().size());
assertTrue(registry.hasActiveAnnouncement(slingId));
assertFalse(registry.hasActiveAnnouncement(UUID.randomUUID().toString()));
registry.unregisterAnnouncement(slingId);
assertEquals(0, registry.listAnnouncementsInSameCluster(localCluster).size());
assertEquals(0, registry.listLocalAnnouncements().size());
assertEquals(0, registry.listLocalIncomingAnnouncements().size());
assertFalse(registry.hasActiveAnnouncement(slingId));
assertFalse(registry.hasActiveAnnouncement(UUID.randomUUID().toString()));
assertEquals(1, ann.listInstances().size());
registry.addAllExcept(ann, localCluster, new AnnouncementFilter() {
public boolean accept(String receivingSlingId, Announcement announcement) {
assertNotNull(receivingSlingId);
assertNotNull(announcement);
return true;
}
});
assertEquals(1, ann.listInstances().size());
registry.registerAnnouncement(createAnnouncement(createCluster(3), 1, false));
assertEquals(1, registry.listAnnouncementsInSameCluster(localCluster).size());
assertEquals(3, registry.listInstances(localCluster).size());
registry.addAllExcept(ann, localCluster, new AnnouncementFilter() {
public boolean accept(String receivingSlingId, Announcement announcement) {
assertNotNull(receivingSlingId);
assertNotNull(announcement);
return true;
}
});
assertEquals(4, ann.listInstances().size());
registry.registerAnnouncement(ann);
assertEquals(2, registry.listAnnouncementsInSameCluster(localCluster).size());
}
private ClusterView createCluster(int numInstances) {
DefaultClusterView localCluster = new DefaultClusterView(UUID.randomUUID().toString());
for (int i = 0; i < numInstances; i++) {
DefaultInstanceDescription instance = TopologyHelper.createInstanceDescription(UUID.randomUUID().toString(), (i==0 ? true : false), localCluster);
}
return localCluster;
}
private ClusterView createCluster(String... instanceIds) {
DefaultClusterView localCluster = new DefaultClusterView(UUID.randomUUID().toString());
for (int i = 0; i < instanceIds.length; i++) {
DefaultInstanceDescription instance = TopologyHelper.createInstanceDescription(instanceIds[i], (i==0 ? true : false), localCluster);
}
return localCluster;
}
private Announcement createAnnouncement(ClusterView remoteCluster, int ownerIndex, boolean inherited) {
List<InstanceDescription> instances = remoteCluster.getInstances();
Announcement ann = new Announcement(instances.get(ownerIndex).getSlingId());
ann.setInherited(inherited);
ann.setLocalCluster(remoteCluster);
return ann;
}
@Test
public void testExpiry() throws InterruptedException, NoSuchFieldException {
ClusterView cluster1 = createCluster(4);
ClusterView cluster2 = createCluster(3);
ClusterView cluster3 = createCluster(5);
ClusterView myCluster = createCluster(slingId);
Announcement ann1 = createAnnouncement(cluster1, 0, true);
Announcement ann2 = createAnnouncement(cluster2, 1, true);
Announcement ann3 = createAnnouncement(cluster3, 1, false);
assertTrue(registry.registerAnnouncement(ann1)!=-1);
assertTrue(registry.registerAnnouncement(ann2)!=-1);
assertTrue(registry.registerAnnouncement(ann3)!=-1);
assertTrue(registry.hasActiveAnnouncement(cluster1.getInstances().get(0).getSlingId()));
assertTrue(registry.hasActiveAnnouncement(cluster2.getInstances().get(1).getSlingId()));
assertTrue(registry.hasActiveAnnouncement(cluster3.getInstances().get(1).getSlingId()));
assertEquals(3, registry.listAnnouncementsInSameCluster(myCluster).size());
assertEquals(3, registry.listLocalAnnouncements().size());
assertEquals(1, registry.listLocalIncomingAnnouncements().size());
{
Announcement testAnn = createAnnouncement(myCluster, 0, false);
assertEquals(1, testAnn.listInstances().size());
registry.addAllExcept(testAnn, myCluster, null);
assertEquals(13, testAnn.listInstances().size());
}
Thread.sleep(10500);
{
Announcement testAnn = createAnnouncement(myCluster, 0, false);
assertEquals(1, testAnn.listInstances().size());
registry.addAllExcept(testAnn, myCluster, null);
assertEquals(13, testAnn.listInstances().size());
}
assertTrue(registry.registerAnnouncement(ann3)!=-1);
{
Announcement testAnn = createAnnouncement(myCluster, 0, false);
assertEquals(1, testAnn.listInstances().size());
registry.addAllExcept(testAnn, myCluster, null);
assertEquals(13, testAnn.listInstances().size());
}
registry.checkExpiredAnnouncements();
assertEquals(1, registry.listAnnouncementsInSameCluster(myCluster).size());
assertEquals(1, registry.listLocalAnnouncements().size());
assertEquals(1, registry.listLocalIncomingAnnouncements().size());
assertFalse(registry.hasActiveAnnouncement(cluster1.getInstances().get(0).getSlingId()));
assertFalse(registry.hasActiveAnnouncement(cluster2.getInstances().get(1).getSlingId()));
assertTrue(registry.hasActiveAnnouncement(cluster3.getInstances().get(1).getSlingId()));
{
Announcement testAnn = createAnnouncement(myCluster, 0, false);
assertEquals(1, testAnn.listInstances().size());
registry.addAllExcept(testAnn, myCluster, null);
assertEquals(6, testAnn.listInstances().size());
}
}
@Test
public void testCluster() throws Exception {
doTestCluster(false);
}
@Category(Slow.class)
@Test
public void testCluster_Slow() throws Exception {
doTestCluster(true);
}
private void doTestCluster(boolean includeFinalExpiryCheck) throws Exception {
ClusterView cluster1 = createCluster(2);
ClusterView cluster2 = createCluster(4);
ClusterView cluster3 = createCluster(7);
Announcement ann1 = createAnnouncement(cluster1, 1, true);
Announcement ann2 = createAnnouncement(cluster2, 2, true);
Announcement ann3 = createAnnouncement(cluster3, 3, false);
final String instance1 = UUID.randomUUID().toString();
final String instance2 = UUID.randomUUID().toString();
final String instance3 = UUID.randomUUID().toString();
ClusterView myCluster = createCluster(instance1, instance2, instance3);
AnnouncementRegistryImpl registry1 = AnnouncementRegistryImpl.testConstructorAndActivate(
resourceResolverFactory, new DummySlingSettingsService(instance1), config);
AnnouncementRegistryImpl registry2 = AnnouncementRegistryImpl.testConstructorAndActivate(
resourceResolverFactory, new DummySlingSettingsService(instance2), config);
AnnouncementRegistryImpl registry3 = AnnouncementRegistryImpl.testConstructorAndActivate(
resourceResolverFactory, new DummySlingSettingsService(instance3), config);
assertTrue(registry1.registerAnnouncement(ann1)!=-1);
assertTrue(registry2.registerAnnouncement(ann2)!=-1);
assertTrue(registry3.registerAnnouncement(ann3)!=-1);
assertTrue(registry1.hasActiveAnnouncement(cluster1.getInstances().get(1).getSlingId()));
assertTrue(registry2.hasActiveAnnouncement(cluster2.getInstances().get(2).getSlingId()));
assertTrue(registry3.hasActiveAnnouncement(cluster3.getInstances().get(3).getSlingId()));
assertEquals(3, registry1.listAnnouncementsInSameCluster(myCluster).size());
assertEquals(1, registry1.listLocalAnnouncements().size());
assertEquals(0, registry1.listLocalIncomingAnnouncements().size());
assertAnnouncements(registry1, myCluster, 4, 16);
assertEquals(3, registry2.listAnnouncementsInSameCluster(myCluster).size());
assertEquals(1, registry2.listLocalAnnouncements().size());
assertEquals(0, registry2.listLocalIncomingAnnouncements().size());
assertAnnouncements(registry2, myCluster, 4, 16);
assertEquals(3, registry3.listAnnouncementsInSameCluster(myCluster).size());
assertEquals(1, registry3.listLocalAnnouncements().size());
assertEquals(1, registry3.listLocalIncomingAnnouncements().size());
assertAnnouncements(registry3, myCluster, 4, 16);
myCluster = createCluster(instance1, instance2);
VirtualInstanceHelper.dumpRepo(resourceResolverFactory);
assertEquals(2, registry1.listAnnouncementsInSameCluster(myCluster).size());
assertEquals(1, registry1.listLocalAnnouncements().size());
assertEquals(0, registry1.listLocalIncomingAnnouncements().size());
assertAnnouncements(registry1, myCluster, 3, 8);
assertEquals(2, registry2.listAnnouncementsInSameCluster(myCluster).size());
assertEquals(1, registry2.listLocalAnnouncements().size());
assertEquals(0, registry2.listLocalIncomingAnnouncements().size());
assertAnnouncements(registry2, myCluster, 3, 8);
if (includeFinalExpiryCheck) {
Thread.sleep(10500);
assertAnnouncements(registry1, myCluster, 3, 8);
assertAnnouncements(registry2, myCluster, 3, 8);
registry1.checkExpiredAnnouncements();
registry2.checkExpiredAnnouncements();
assertAnnouncements(registry1, myCluster, 1, 2);
assertAnnouncements(registry2, myCluster, 1, 2);
}
}
private void assertAnnouncements(AnnouncementRegistryImpl registry,
ClusterView myCluster, int expectedNumAnnouncements, int expectedNumInstances) {
Announcement ann = createAnnouncement(myCluster, 0, false);
registry.addAllExcept(ann, myCluster, null);
assertEquals(expectedNumInstances, ann.listInstances().size());
}
}
| apache-2.0 |
rainkinste/memdb | test/app/database.js | 4354 | // Copyright 2015 The MemDB 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. See the AUTHORS file
// for names of contributors.
'use strict';
var P = require('bluebird');
var _ = require('lodash');
var should = require('should');
var env = require('../env');
var Database = require('../../app/database');
var logger = require('memdb-logger').getLogger('test', __filename);
describe('database test', function(){
beforeEach(env.flushdb);
// it('find/update/insert/remove/commit/rollback', function(cb){
// //tested in ../lib/connection
// });
// it('index test', function(cb){
// //tested in ../lib/connection
// });
it('persistent / idle timeout', function(cb){
var config = env.shardConfig('s1');
config.persistentDelay = 50;
config.idleTimeout = 500;
var db = new Database(config);
var conn = null;
var collName = 'player', doc = {_id : '1', name : 'rain'};
return P.try(function(){
return db.start();
})
.then(function(){
conn = db.getConnection(db.connect().connId);
return conn.insert(collName, doc);
})
.then(function(){
return conn.commit();
})
.delay(300) // doc persistented
.then(function(){
// read from backend
return db.shard.backend.get(collName, doc._id)
.then(function(ret){
ret.should.eql(doc);
});
})
.delay(500) // doc idle timed out
.then(function(){
db.shard._isLoaded(collName + '$' + doc._id).should.eql(false);
})
.then(function(){
return conn.remove(collName, doc._id);
})
.then(function(){
return conn.commit();
})
.then(function(){
return db.stop();
})
.nodeify(cb);
});
it('restore from slave', function(cb){
var db1 = null, db2 = null;
var conn = null;
var player1 = {_id : 'p1', name : 'rain', age: 30};
var player2 = {_id : 'p2', name : 'snow', age: 25};
return P.try(function(){
var config = env.shardConfig('s1');
config.heartbeatInterval = -1; // disable heartbeat
config.gcInterval = 3600 * 1000; // disable gc
db1 = new Database(config);
return db1.start();
})
.then(function(){
conn = db1.getConnection(db1.connect().connId);
})
.then(function(){
return conn.insert('player', player1);
})
.then(function(){
return conn.insert('player', player2);
})
.then(function(){
return conn.commit();
})
.then(function(){
db1.shard.state = 4; // Db is suddenly stopped
})
.then(function(){
//restart db
db2 = new Database(env.shardConfig('s1'));
return db2.start();
})
.then(function(){
conn = db2.getConnection(db2.connect().connId);
})
.then(function(){
return P.try(function(){
return conn.find('player', player1._id);
})
.then(function(ret){
ret.should.eql(player1);
});
})
.then(function(){
return P.try(function(){
return conn.find('player', player2._id);
})
.then(function(ret){
ret.should.eql(player2);
});
})
.then(function(){
conn.close();
return db2.stop();
})
.finally(function(){
// clean up
db1.shard.state = 2;
return db1.stop(true);
})
.nodeify(cb);
});
});
| apache-2.0 |
uschindler/elasticsearch | libs/x-content/src/main/java/org/elasticsearch/common/xcontent/cbor/CborXContent.java | 4614 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.common.xcontent.cbor;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import org.elasticsearch.common.xcontent.DeprecationHandler;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentGenerator;
import org.elasticsearch.common.xcontent.XContentParseException;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.Set;
/**
* A CBOR based content implementation using Jackson.
*/
public class CborXContent implements XContent {
public static XContentBuilder contentBuilder() throws IOException {
return XContentBuilder.builder(cborXContent);
}
static final CBORFactory cborFactory;
public static final CborXContent cborXContent;
static {
cborFactory = new CBORFactory();
cborFactory.configure(CBORFactory.Feature.FAIL_ON_SYMBOL_HASH_OVERFLOW, false); // this trips on many mappings now...
// Do not automatically close unclosed objects/arrays in com.fasterxml.jackson.dataformat.cbor.CBORGenerator#close() method
cborFactory.configure(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT, false);
cborFactory.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true);
cborXContent = new CborXContent();
}
private CborXContent() {
}
@Override
public XContentType type() {
return XContentType.CBOR;
}
@Override
public byte streamSeparator() {
throw new XContentParseException("cbor does not support stream parsing...");
}
@Override
public XContentGenerator createGenerator(OutputStream os, Set<String> includes, Set<String> excludes) throws IOException {
return new CborXContentGenerator(cborFactory.createGenerator(os, JsonEncoding.UTF8), os, includes, excludes);
}
@Override
public XContentParser createParser(NamedXContentRegistry xContentRegistry,
DeprecationHandler deprecationHandler, String content) throws IOException {
return new CborXContentParser(xContentRegistry, deprecationHandler, cborFactory.createParser(new StringReader(content)));
}
@Override
public XContentParser createParser(NamedXContentRegistry xContentRegistry,
DeprecationHandler deprecationHandler, InputStream is) throws IOException {
return new CborXContentParser(xContentRegistry, deprecationHandler, cborFactory.createParser(is));
}
@Override
public XContentParser createParser(NamedXContentRegistry xContentRegistry,
DeprecationHandler deprecationHandler, byte[] data) throws IOException {
return new CborXContentParser(xContentRegistry, deprecationHandler, cborFactory.createParser(data));
}
@Override
public XContentParser createParser(NamedXContentRegistry xContentRegistry,
DeprecationHandler deprecationHandler, byte[] data, int offset, int length) throws IOException {
return new CborXContentParser(xContentRegistry, deprecationHandler, cborFactory.createParser(data, offset, length));
}
@Override
public XContentParser createParser(NamedXContentRegistry xContentRegistry,
DeprecationHandler deprecationHandler, Reader reader) throws IOException {
return new CborXContentParser(xContentRegistry, deprecationHandler, cborFactory.createParser(reader));
}
}
| apache-2.0 |
pasitive/zapad | protected/extensions/tinymce/assets/tiny_mce/plugins/advhr/langs/tw_dlg.js | 104 | tinyMCE.addI18n('tw.advhr_dlg',{size:"\u9ad8\u5ea6",noshade:"\u7121\u9670\u5f71",width:"\u5bec\u5ea6"}); | bsd-3-clause |
honix/godot | thirdparty/graphite/src/gr_slot.cpp | 4519 | /* GRAPHITE2 LICENSING
Copyright 2010, SIL International
All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should also have received a copy of the GNU Lesser General Public
License along with this library in the file named "LICENSE".
If not, write to the Free Software Foundation, 51 Franklin Street,
Suite 500, Boston, MA 02110-1335, USA or visit their web page on the
internet at http://www.fsf.org/licenses/lgpl.html.
Alternatively, the contents of this file may be used under the terms of the
Mozilla Public License (http://mozilla.org/MPL) or the GNU General Public
License, as published by the Free Software Foundation, either version 2
of the License or (at your option) any later version.
*/
#include "graphite2/Segment.h"
#include "inc/Segment.h"
#include "inc/Slot.h"
#include "inc/Font.h"
extern "C" {
const gr_slot* gr_slot_next_in_segment(const gr_slot* p/*not NULL*/)
{
assert(p);
return static_cast<const gr_slot*>(p->next());
}
const gr_slot* gr_slot_prev_in_segment(const gr_slot* p/*not NULL*/)
{
assert(p);
return static_cast<const gr_slot*>(p->prev());
}
const gr_slot* gr_slot_attached_to(const gr_slot* p/*not NULL*/) //returns NULL iff base. If called repeatedly on result, will get to a base
{
assert(p);
return static_cast<const gr_slot*>(p->attachedTo());
}
const gr_slot* gr_slot_first_attachment(const gr_slot* p/*not NULL*/) //returns NULL iff no attachments.
{ //if slot_first_attachment(p) is not NULL, then slot_attached_to(slot_first_attachment(p))==p.
assert(p);
return static_cast<const gr_slot*>(p->firstChild());
}
const gr_slot* gr_slot_next_sibling_attachment(const gr_slot* p/*not NULL*/) //returns NULL iff no more attachments.
{ //if slot_next_sibling_attachment(p) is not NULL, then slot_attached_to(slot_next_sibling_attachment(p))==slot_attached_to(p).
assert(p);
return static_cast<const gr_slot*>(p->nextSibling());
}
unsigned short gr_slot_gid(const gr_slot* p/*not NULL*/)
{
assert(p);
return p->glyph();
}
float gr_slot_origin_X(const gr_slot* p/*not NULL*/)
{
assert(p);
return p->origin().x;
}
float gr_slot_origin_Y(const gr_slot* p/*not NULL*/)
{
assert(p);
return p->origin().y;
}
float gr_slot_advance_X(const gr_slot* p/*not NULL*/, const gr_face *face, const gr_font *font)
{
assert(p);
float scale = 1.0;
float res = p->advance();
if (font)
{
scale = font->scale();
int gid = p->glyph();
if (face && font->isHinted() && gid < face->glyphs().numGlyphs())
res = (res - face->glyphs().glyph(gid)->theAdvance().x) * scale + font->advance(gid);
else
res = res * scale;
}
return res;
}
float gr_slot_advance_Y(const gr_slot *p/*not NULL*/, GR_MAYBE_UNUSED const gr_face *face, const gr_font *font)
{
assert(p);
float res = p->advancePos().y;
if (font)
return res * font->scale();
else
return res;
}
int gr_slot_before(const gr_slot* p/*not NULL*/)
{
assert(p);
return p->before();
}
int gr_slot_after(const gr_slot* p/*not NULL*/)
{
assert(p);
return p->after();
}
unsigned int gr_slot_index(const gr_slot *p/*not NULL*/)
{
assert(p);
return p->index();
}
int gr_slot_attr(const gr_slot* p/*not NULL*/, const gr_segment* pSeg/*not NULL*/, gr_attrCode index, gr_uint8 subindex)
{
assert(p);
return p->getAttr(pSeg, index, subindex);
}
int gr_slot_can_insert_before(const gr_slot* p/*not NULL*/)
{
assert(p);
return (p->isInsertBefore())? 1 : 0;
}
int gr_slot_original(const gr_slot* p/*not NULL*/)
{
assert(p);
return p->original();
}
void gr_slot_linebreak_before(gr_slot* p/*not NULL*/)
{
assert(p);
gr_slot *prev = (gr_slot *)p->prev();
prev->sibling(NULL);
prev->next(NULL);
p->prev(NULL);
}
#if 0 //what should this be
size_t id(const gr_slot* p/*not NULL*/)
{
return (size_t)p->id();
}
#endif
} // extern "C"
| mit |
dylanh724/tol-node-public | tol2-test/node_modules/forever/lib/forever.js | 28771 | /*
* forever.js: Top level include for the forever module
*
* (C) 2010 Charlie Robbins & the Contributors
* MIT LICENCE
*
*/
var fs = require('fs'),
path = require('path'),
events = require('events'),
exec = require('child_process').exec,
spawn = require('child_process').spawn,
cliff = require('cliff'),
nconf = require('nconf'),
nssocket = require('nssocket'),
timespan = require('timespan'),
utile = require('utile'),
winston = require('winston'),
mkdirp = utile.mkdirp,
async = utile.async;
var forever = exports;
//
// Setup `forever.log` to be a custom `winston` logger.
//
forever.log = new (winston.Logger)({
transports: [
new (winston.transports.Console)()
]
});
forever.log.cli();
//
// Setup `forever out` for logEvents with `winston` custom logger.
//
forever.out = new (winston.Logger)({
transports: [
new (winston.transports.Console)()
]
});
//
// ### Export Components / Settings
// Export `version` and important Prototypes from `lib/forever/*`
//
forever.initialized = false;
forever.kill = require('forever-monitor').kill;
forever.checkProcess = require('forever-monitor').checkProcess;
forever.root = process.env.FOREVER_ROOT || path.join(process.env.HOME || process.env.USERPROFILE || '/root', '.forever');
forever.config = new nconf.File({ file: path.join(forever.root, 'config.json') });
forever.Forever = forever.Monitor = require('forever-monitor').Monitor;
forever.Worker = require('./forever/worker').Worker;
forever.cli = require('./forever/cli');
//
// Expose version through `pkginfo`
//
exports.version = require('../package').version;
//
// ### function getSockets (sockPath, callback)
// #### @sockPath {string} Path in which to look for UNIX domain sockets
// #### @callback {function} Continuation to pass control to when complete
// Attempts to read the files from `sockPath` if the directory does not exist,
// then it is created using `mkdirp`.
//
function getSockets(sockPath, callback) {
var sockets;
try {
sockets = fs.readdirSync(sockPath);
}
catch (ex) {
if (ex.code !== 'ENOENT') {
return callback(ex);
}
return mkdirp(sockPath, '0755', function (err) {
return err ? callback(err) : callback(null, []);
});
}
callback(null, sockets);
}
//
// ### function getAllProcess (callback)
// #### @callback {function} Continuation to respond to when complete.
// Returns all data for processes managed by forever.
//
function getAllProcesses(callback) {
var sockPath = forever.config.get('sockPath');
function getProcess(name, next) {
var fullPath = path.join(sockPath, name),
socket = new nssocket.NsSocket();
if (process.platform === 'win32') {
// it needs the prefix
fullPath = '\\\\.\\pipe\\' + fullPath;
}
socket.connect(fullPath, function (err) {
if (err) {
next(err);
}
socket.dataOnce(['data'], function (data) {
data.socket = fullPath;
next(null, data);
socket.end();
});
socket.send(['data']);
});
socket.on('error', function (err) {
if (err.code === 'ECONNREFUSED') {
fs.unlink(fullPath, function () {
next();
});
}
else {
next();
}
});
}
getSockets(sockPath, function (err, sockets) {
if (err || (sockets && sockets.length === 0)) {
return callback(err);
}
async.map(sockets, getProcess, function (err, processes) {
callback(err, processes.filter(Boolean));
});
});
}
//
// ### function getAllPids ()
// Returns the set of all pids managed by forever.
// e.x. [{ pid: 12345, foreverPid: 12346 }, ...]
//
function getAllPids(processes) {
return !processes ? null : processes.map(function (proc) {
return {
pid: proc.pid,
foreverPid: proc.foreverPid
};
});
}
//
// ### function stopOrRestart (action, event, format, target)
// #### @action {string} Action that is to be sent to target(s).
// #### @event {string} Event that will be emitted on success.
// #### @format {boolean} Indicated if we should CLI format the returned output.
// #### @target {string} Index or script name to stop. Optional.
// #### If not provided -> action will be sent to all targets.
// Returns emitter that you can use to handle events on failure or success (i.e 'error' or <event>)
//
function stopOrRestart(action, event, format, target) {
var emitter = new events.EventEmitter();
function sendAction(proc, next) {
var socket = new nssocket.NsSocket();
function onMessage(data) {
//
// Cleanup the socket.
//
socket.undata([action, 'ok'], onMessage);
socket.undata([action, 'error'], onMessage);
socket.end();
//
// Messages are only sent back from error cases. The event
// calling context is available from `nssocket`.
//
var message = data && data.message,
type = this.event.slice().pop();
//
// Remark (Tjatse): This message comes from `forever-monitor`, the process is marked
// as `STOPPED`: message: Cannot stop process that is not running.
//
// Remark (indexzero): We should probably warn instead of emitting an error in `forever-monitor`,
// OR handle that error in `bin/worker` for better RPC.
//
return type === 'error' && /is not running/.test(message)
? next(new Error(message))
: next(null, data);
}
socket.connect(proc.socket, function (err) {
if (err) {
next(err);
}
socket.dataOnce([action, 'ok'], onMessage);
socket.dataOnce([action, 'error'], onMessage);
socket.send([action]);
});
//
// Remark (indexzero): This is a race condition, but unlikely to ever hit since
// if the socket errors we will never get any data in the first place...
//
socket.on('error', function (err) {
next(err);
});
}
getAllProcesses(function (err, processes) {
if (err) {
return process.nextTick(function () {
emitter.emit('error', err);
});
}
var procs;
if (target !== undefined && target !== null) {
if (isNaN(target)) {
procs = forever.findByScript(target, processes);
}
procs = procs
|| forever.findById(target, processes)
|| forever.findByIndex(target, processes)
|| forever.findByUid(target, processes)
|| forever.findByPid(target, processes);
}
else {
procs = processes;
}
if (procs && procs.length > 0) {
async.map(procs, sendAction, function (err, results) {
if (err) {
emitter.emit('error', err);
}
//
// Remark (indexzero): we should do something with the results.
//
emitter.emit(event, forever.format(format, procs));
});
}
else {
process.nextTick(function () {
emitter.emit('error', new Error('Cannot find forever process: ' + target));
});
}
});
return emitter;
}
//
// ### function load (options, [callback])
// #### @options {Object} Options to load into the forever module
// Initializes configuration for forever module
//
forever.load = function (options) {
// memorize current options.
this._loadedOptions = options;
//
// Setup the incoming options with default options.
//
options = options || {};
options.loglength = options.loglength || 100;
options.logstream = options.logstream || false;
options.root = options.root || forever.root;
options.pidPath = options.pidPath || path.join(options.root, 'pids');
options.sockPath = options.sockPath || path.join(options.root, 'sock');
//
// If forever is initalized and the config directories are identical
// simply return without creating directories
//
if (forever.initialized && forever.config.get('root') === options.root &&
forever.config.get('pidPath') === options.pidPath) {
return;
}
forever.config = new nconf.File({ file: path.join(options.root, 'config.json') });
//
// Try to load the forever `config.json` from
// the specified location.
//
try {
forever.config.loadSync();
}
catch (ex) { }
//
// Setup the columns for `forever list`.
//
options.columns = options.columns || forever.config.get('columns');
if (!options.columns) {
options.columns = [
'uid', 'command', 'script', 'forever', 'pid', 'id', 'logfile', 'uptime'
];
}
forever.config.set('root', options.root);
forever.config.set('pidPath', options.pidPath);
forever.config.set('sockPath', options.sockPath);
forever.config.set('loglength', options.loglength);
forever.config.set('logstream', options.logstream);
forever.config.set('columns', options.columns);
//
// Setup timestamp to event logger
//
forever.out.transports.console.timestamp = forever.config.get('timestamp') === 'true';
//
// Attempt to see if `forever` has been configured to
// run in debug mode.
//
options.debug = options.debug || forever.config.get('debug') || false;
if (options.debug) {
//
// If we have been indicated to debug this forever process
// then setup `forever._debug` to be an instance of `winston.Logger`.
//
forever._debug();
}
//
// Syncronously create the `root` directory
// and the `pid` directory for forever. Although there is
// an additional overhead here of the sync action. It simplifies
// the setup of forever dramatically.
//
function tryCreate(dir) {
try {
fs.mkdirSync(dir, '0755');
}
catch (ex) { }
}
tryCreate(forever.config.get('root'));
tryCreate(forever.config.get('pidPath'));
tryCreate(forever.config.get('sockPath'));
//
// Attempt to save the new `config.json` for forever
//
try {
forever.config.saveSync();
}
catch (ex) { }
forever.initialized = true;
};
//
// ### @private function _debug ()
// Sets up debugging for this forever process
//
forever._debug = function () {
var debug = forever.config.get('debug');
if (!debug) {
forever.config.set('debug', true);
forever.log.add(winston.transports.File, {
level: 'silly',
filename: path.join(forever.config.get('root'), 'forever.debug.log')
});
}
};
//
// Ensure forever will always be loaded the first time it is required.
//
forever.load();
//
// ### function stat (logFile, script, callback)
// #### @logFile {string} Path to the log file for this script
// #### @logAppend {boolean} Optional. True Prevent failure if the log file exists.
// #### @script {string} Path to the target script.
// #### @callback {function} Continuation to pass control back to
// Ensures that the logFile doesn't exist and that
// the target script does exist before executing callback.
//
forever.stat = function (logFile, script, callback) {
var logAppend;
if (arguments.length === 4) {
logAppend = callback;
callback = arguments[3];
}
fs.stat(script, function (err, stats) {
if (err) {
return callback(new Error('script ' + script + ' does not exist.'));
}
return logAppend ? callback(null) : fs.stat(logFile, function (err, stats) {
return !err
? callback(new Error('log file ' + logFile + ' exists. Use the -a or --append option to append log.'))
: callback(null);
});
});
};
//
// ### function start (script, options)
// #### @script {string} Location of the script to run.
// #### @options {Object} Configuration for forever instance.
// Starts a script with forever
//
forever.start = function (script, options) {
if (!options.uid) {
options.uid = utile.randomString(4).replace(/^\-/, '_');
}
if (!options.logFile) {
options.logFile = forever.logFilePath(options.uid + '.log');
}
//
// Create the monitor, log events, and start.
//
var monitor = new forever.Monitor(script, options);
forever.logEvents(monitor);
return monitor.start();
};
//
// ### function startDaemon (script, options)
// #### @script {string} Location of the script to run.
// #### @options {Object} Configuration for forever instance.
// Starts a script with forever as a daemon
//
forever.startDaemon = function (script, options) {
options = options || {};
options.uid = options.uid || utile.randomString(4).replace(/^\-/, '_');
options.logFile = forever.logFilePath(options.logFile || forever.config.get('logFile') || options.uid + '.log');
options.pidFile = forever.pidFilePath(options.pidFile || forever.config.get('pidFile') || options.uid + '.pid');
var monitor, outFD, errFD, monitorPath;
//
// This log file is forever's log file - the user's outFile and errFile
// options are not taken into account here. This will be an aggregate of all
// the app's output, as well as messages from the monitor process, where
// applicable.
//
outFD = fs.openSync(options.logFile, 'a');
errFD = fs.openSync(options.logFile, 'a');
monitorPath = path.resolve(__dirname, '..', 'bin', 'monitor');
monitor = spawn(process.execPath, [monitorPath, script], {
stdio: ['ipc', outFD, errFD],
detached: true
});
monitor.on('exit', function (code) {
console.error('Monitor died unexpectedly with exit code %d', code);
});
// transmit options to daemonic(child) process, keep configuration lineage.
options._loadedOptions = this._loadedOptions;
monitor.send(JSON.stringify(options));
// close the ipc communication channel with the monitor
// otherwise the corresponding events listeners will prevent
// the exit of the current process (observed with node 0.11.9)
monitor.disconnect();
// make sure the monitor is unref() and does not prevent the
// exit of the current process
monitor.unref();
return monitor;
};
//
// ### function startServer ()
// #### @arguments {forever.Monitor...} A list of forever.Monitor instances
// Starts the `forever` HTTP server for communication with the forever CLI.
// **NOTE:** This will change your `process.title`.
//
forever.startServer = function () {
var args = Array.prototype.slice.call(arguments),
monitors = [],
callback;
args.forEach(function (a) {
if (Array.isArray(a)) {
monitors = monitors.concat(a.filter(function (m) {
return m instanceof forever.Monitor;
}));
}
else if (a instanceof forever.Monitor) {
monitors.push(a);
}
else if (typeof a === 'function') {
callback = a;
}
});
async.map(monitors, function (monitor, next) {
var worker = new forever.Worker({
monitor: monitor,
sockPath: forever.config.get('sockPath'),
exitOnStop: true
});
worker.start(function (err) {
return err ? next(err) : next(null, worker);
});
}, callback || function () {});
};
//
// ### function stop (target, [format])
// #### @target {string} Index or script name to stop
// #### @format {boolean} Indicated if we should CLI format the returned output.
// Stops the process(es) with the specified index or script name
// in the list of all processes
//
forever.stop = function (target, format) {
return stopOrRestart('stop', 'stop', format, target);
};
//
// ### function restart (target, format)
// #### @target {string} Index or script name to restart
// #### @format {boolean} Indicated if we should CLI format the returned output.
// Restarts the process(es) with the specified index or script name
// in the list of all processes
//
forever.restart = function (target, format) {
return stopOrRestart('restart', 'restart', format, target);
};
//
// ### function stopbypid (target, format)
// #### @pid {string} Pid of process to stop.
// #### @format {boolean} Indicated if we should CLI format the returned output.
// Stops the process with specified pid
//
forever.stopbypid = function (pid, format) {
// stopByPid only capable of stopping, but can't restart
return stopOrRestart('stop', 'stopByPid', format, pid);
};
//
// ### function restartAll (format)
// #### @format {boolean} Value indicating if we should format output
// Restarts all processes managed by forever.
//
forever.restartAll = function (format) {
return stopOrRestart('restart', 'restartAll', format);
};
//
// ### function stopAll (format)
// #### @format {boolean} Value indicating if we should format output
// Stops all processes managed by forever.
//
forever.stopAll = function (format) {
return stopOrRestart('stop', 'stopAll', format);
};
//
// ### function list (format, procs, callback)
// #### @format {boolean} If set, will return a formatted string of data
// #### @callback {function} Continuation to respond to when complete.
// Returns the list of all process data managed by forever.
//
forever.list = function (format, callback) {
getAllProcesses(function (err, processes) {
callback(err, forever.format(format, processes));
});
};
//
// ### function tail (target, length, callback)
// #### @target {string} Target script to list logs for
// #### @options {length|stream} **Optional** Length of the logs to tail, boolean stream
// #### @callback {function} Continuation to respond to when complete.
// Responds with the latest `length` logs for the specified `target` process
// managed by forever. If no `length` is supplied then `forever.config.get('loglength`)`
// is used.
//
forever.tail = function (target, options, callback) {
if (!callback && typeof options === 'function') {
callback = options;
options.length = 0;
options.stream = false;
}
var that = this,
length = options.length || forever.config.get('loglength'),
stream = options.stream || forever.config.get('logstream'),
blanks = function (e, i, a) { return e !== ''; },
title = function (e, i, a) { return e.match(/^==>/); },
args = ['-n', length],
logs;
if (stream) { args.unshift('-f'); }
function tailProcess(procs, next) {
var count = 0,
map = {},
tail;
procs.forEach(function (proc) {
args.push(proc.logFile);
map[proc.logFile] = { pid: proc.pid, file: proc.file };
count++;
});
tail = spawn('tail', args, {
stdio: [null, 'pipe', 'pipe'],
});
tail.stdio[1].setEncoding('utf8');
tail.stdio[2].setEncoding('utf8');
tail.stdio[1].on('data', function (data) {
var chunk = data.split('\n\n');
chunk.forEach(function (logs) {
var logs = logs.split('\n').filter(blanks),
file = logs.filter(title),
lines,
proc;
proc = file.length
? map[file[0].split(' ')[1]]
: map[procs[0].logFile];
lines = count !== 1
? logs.slice(1)
: logs;
lines.forEach(function (line) {
callback(null, { file: proc.file, pid: proc.pid, line: line });
});
});
});
tail.stdio[2].on('data', function (err) {
return callback(err);
});
}
getAllProcesses(function (err, processes) {
if (err) {
return callback(err);
}
else if (!processes) {
return callback(new Error('Cannot find forever process: ' + target));
}
var procs = forever.findByIndex(target, processes)
|| forever.findByScript(target, processes);
if (!procs) {
return callback(new Error('No logs available for process: ' + target));
}
tailProcess(procs, callback);
});
};
//
// ### function findById (id, processes)
// #### @id {string} id of the process to find.
// #### @processes {Array} Set of processes to find in.
// Finds the process with the specified index.
//
forever.findById = function (id, processes) {
if (!processes) { return null; }
var procs = processes.filter(function (p) {
return p.id === id;
});
if (procs.length === 0) { procs = null; }
return procs;
};
//
// ### function findByIndex (index, processes)
// #### @index {string} Index of the process to find.
// #### @processes {Array} Set of processes to find in.
// Finds the process with the specified index.
//
forever.findByIndex = function (index, processes) {
var indexAsNum = parseInt(index, 10),
proc;
if (indexAsNum == index) {
proc = processes && processes[indexAsNum];
}
return proc ? [proc] : null;
};
//
// ### function findByScript (script, processes)
// #### @script {string} The name of the script to find.
// #### @processes {Array} Set of processes to find in.
// Finds the process with the specified script name.
//
forever.findByScript = function (script, processes) {
if (!processes) { return null; }
// make script absolute.
if (script.indexOf('/') != 0) {
script = path.resolve(process.cwd(), script);
}
var procs = processes.filter(function (p) {
return p.file === script || path.join(p.spawnWith.cwd, p.file) === script;
});
if (procs.length === 0) { procs = null; }
return procs;
};
//
// ### function findByUid (uid, processes)
// #### @uid {string} The uid of the process to find.
// #### @processes {Array} Set of processes to find in.
// Finds the process with the specified uid.
//
forever.findByUid = function (script, processes) {
var procs = !processes
? null
: processes.filter(function (p) {
return p.uid === script;
});
if (procs && procs.length === 0) { procs = null; }
return procs;
};
//
// ### function findByPid (pid, processes)
// #### @pid {string} The pid of the process to find.
// #### @processes {Array} Set of processes to find in.
// Finds the process with the specified pid.
//
forever.findByPid = function (pid, processes) {
pid = typeof pid === 'string'
? parseInt(pid, 10)
: pid;
var procs = processes && processes.filter(function (p) {
return p.pid === pid;
});
if (procs && procs.length === 0) { procs = null; }
return procs || null;
};
//
// ### function format (format, procs)
// #### @format {Boolean} Value indicating if processes should be formatted
// #### @procs {Array} Processes to format
// Returns a formatted version of the `procs` supplied based on the column
// configuration in `forever.config`.
//
forever.format = function (format, procs) {
if (!procs || procs.length === 0) {
return null;
}
var index = 0,
columns = forever.config.get('columns'),
rows = [[' '].concat(columns)],
formatted;
function mapColumns(prefix, mapFn) {
return [prefix].concat(columns.map(mapFn));
}
if (format) {
//
// Iterate over the procs to see which has the
// longest options string
//
procs.forEach(function (proc) {
rows.push(mapColumns('[' + index + ']', function (column) {
return forever.columns[column]
? forever.columns[column].get(proc)
: 'MISSING';
}));
index++;
});
formatted = cliff.stringifyRows(rows, mapColumns('white', function (column) {
return forever.columns[column]
? forever.columns[column].color
: 'white';
}));
}
return format ? formatted : procs;
};
//
// ### function cleanUp ()
// Utility function for removing excess pid and
// config, and log files used by forever.
//
forever.cleanUp = function (cleanLogs, allowManager) {
var emitter = new events.EventEmitter(),
pidPath = forever.config.get('pidPath');
getAllProcesses(function (err, processes) {
if (err) {
return process.nextTick(function () {
emitter.emit('error', err);
});
}
else if (cleanLogs) {
forever.cleanLogsSync(processes);
}
function unlinkProcess(proc, done) {
fs.unlink(path.join(pidPath, proc.uid + '.pid'), function () {
//
// Ignore errors (in case the file doesnt exist).
//
if (cleanLogs && proc.logFile) {
//
// If we are cleaning logs then do so if the process
// has a logfile.
//
return fs.unlink(proc.logFile, function () {
done();
});
}
done();
});
}
function cleanProcess(proc, done) {
if (proc.child && proc.manager) {
return done();
}
else if (!proc.child && !proc.manager
|| (!proc.child && proc.manager && allowManager)
|| proc.dead) {
return unlinkProcess(proc, done);
}
//
// If we have a manager but no child, wait a moment
// in-case the child is currently restarting, but **only**
// if we have not already waited for this process
//
if (!proc.waited) {
proc.waited = true;
return setTimeout(function () {
checkProcess(proc, done);
}, 500);
}
done();
}
function checkProcess(proc, next) {
proc.child = forever.checkProcess(proc.pid);
proc.manager = forever.checkProcess(proc.foreverPid);
cleanProcess(proc, next);
}
if (processes && processes.length > 0) {
(function cleanBatch(batch) {
async.forEach(batch, checkProcess, function () {
return processes.length > 0
? cleanBatch(processes.splice(0, 10))
: emitter.emit('cleanUp');
});
})(processes.splice(0, 10));
}
else {
process.nextTick(function () {
emitter.emit('cleanUp');
});
}
});
return emitter;
};
//
// ### function cleanLogsSync (processes)
// #### @processes {Array} The set of all forever processes
// Removes all log files from the root forever directory
// that do not belong to current running forever processes.
//
forever.cleanLogsSync = function (processes) {
var root = forever.config.get('root'),
files = fs.readdirSync(root),
running,
runningLogs;
running = processes && processes.filter(function (p) {
return p && p.logFile;
});
runningLogs = running && running.map(function (p) {
return p.logFile.split('/').pop();
});
files.forEach(function (file) {
if (/\.log$/.test(file) && (!runningLogs || runningLogs.indexOf(file) === -1)) {
fs.unlinkSync(path.join(root, file));
}
});
};
//
// ### function logFilePath (logFile)
// #### @logFile {string} Log file path
// Determines the full logfile path name
//
forever.logFilePath = function (logFile, uid) {
return logFile && (logFile[0] === '/' || logFile[1] === ':')
? logFile
: path.join(forever.config.get('root'), logFile || (uid || 'forever') + '.log');
};
//
// ### function pidFilePath (pidFile)
// #### @logFile {string} Pid file path
// Determines the full pid file path name
//
forever.pidFilePath = function (pidFile) {
return pidFile && (pidFile[0] === '/' || pidFile[1] === ':')
? pidFile
: path.join(forever.config.get('pidPath'), pidFile);
};
//
// ### @function logEvents (monitor)
// #### @monitor {forever.Monitor} Monitor to log events for
// Logs important restart and error events to `console.error`
//
forever.logEvents = function (monitor) {
monitor.on('watch:error', function (info) {
forever.out.error(info.message);
forever.out.error(info.error);
});
monitor.on('watch:restart', function (info) {
forever.out.error('restarting script because ' + info.file + ' changed');
});
monitor.on('restart', function () {
forever.out.error('Script restart attempt #' + monitor.times);
});
monitor.on('exit:code', function (code, signal) {
forever.out.error((code !== null && code !== undefined)
? 'Forever detected script exited with code: ' + code
: 'Forever detected script was killed by signal: ' + signal);
});
};
//
// ### @columns {Object}
// Property descriptors for accessing forever column information
// through `forever list` and `forever.list()`
//
forever.columns = {
uid: {
color: 'white',
get: function (proc) {
return proc.uid;
}
},
id: {
color: 'white',
get: function (proc) {
return proc.id ? proc.id : '';
}
},
command: {
color: 'grey',
get: function (proc) {
return (proc.command || 'node').grey;
}
},
script: {
color: 'grey',
get: function (proc) {
return [proc.file].concat(proc.args).join(' ').grey;
}
},
forever: {
color: 'white',
get: function (proc) {
return proc.foreverPid;
}
},
pid: {
color: 'white',
get: function (proc) {
return proc.pid;
}
},
logfile: {
color: 'magenta',
get: function (proc) {
return proc.logFile ? proc.logFile.magenta : '';
}
},
dir: {
color: 'grey',
get: function (proc) {
return proc.sourceDir.grey;
}
},
uptime: {
color: 'yellow',
get: function (proc) {
return proc.running ? timespan.fromDates(new Date(proc.ctime), new Date()).toString().yellow : "STOPPED".red;
}
}
};
| mit |
ssmiech/fastlane | screengrab/example/src/androidTest/java/tools/fastlane/localetester/JUnit3StyleTests.java | 1475 | package tools.fastlane.localetester;
import android.test.ActivityInstrumentationTestCase2;
import tools.fastlane.screengrab.Screengrab;
import tools.fastlane.screengrab.locale.LocaleUtil;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
public class JUnit3StyleTests extends ActivityInstrumentationTestCase2<MainActivity> {
public JUnit3StyleTests() {
super(MainActivity.class);
}
public void setUp() {
getActivity();
LocaleUtil.changeDeviceLocaleTo(LocaleUtil.getTestLocale());
}
public void tearDown() {
LocaleUtil.changeDeviceLocaleTo(LocaleUtil.getEndingLocale());
}
public void testTakeScreenshot() {
Screengrab.screenshot("beforeFabClick");
onView(withId(tools.fastlane.localetester.R.id.fab)).perform(click());
Screengrab.screenshot("afterFabClick");
}
public void testTakeMoreScreenshots() {
Screengrab.screenshot("mainActivity");
onView(withId(tools.fastlane.localetester.R.id.nav_button)).perform(click());
Screengrab.screenshot("anotherActivity");
onView(withId(R.id.hello)).check(matches(isDisplayed()));
}
}
| mit |
cemalkilic/che | plugins/plugin-java/che-plugin-java-ext-lang-server/src/test/resources/RenameNonPrivateField/test4/in/A.java | 103 | package p;
class A{
protected int f;
void m(){
f++;
}
}
class B extends A{
void m(){
f= 0;
}
} | epl-1.0 |
cmuartfab/statuevision | Unity/StatueVisionTestProject/Assets/Standard Assets/Scripts/Hands/DebugHand.cs | 1395 | /******************************************************************************\
* Copyright (C) Leap Motion, Inc. 2011-2014. *
* Leap Motion proprietary. Licensed under Apache 2.0 *
* Available at http://www.apache.org/licenses/LICENSE-2.0.html *
\******************************************************************************/
using UnityEngine;
using System.Collections;
using Leap;
// A debugging hand that draws debug lines connecting important positions.
public class DebugHand : HandModel {
public override void InitHand() {
for (int f = 0; f < fingers.Length; ++f) {
if (fingers[f] != null)
fingers[f].InitFinger();
}
DrawDebugLines();
}
public override void UpdateHand() {
for (int f = 0; f < fingers.Length; ++f) {
if (fingers[f] != null)
fingers[f].UpdateFinger();
}
DrawDebugLines();
}
protected void DrawDebugLines() {
HandModel hand = GetComponent<HandModel>();
Debug.DrawLine(hand.GetElbowPosition(), hand.GetWristPosition(), Color.red);
Debug.DrawLine(hand.GetWristPosition(), hand.GetPalmPosition(), Color.white);
Debug.DrawLine(hand.GetPalmPosition(),
hand.GetPalmPosition() + hand.GetPalmNormal(), Color.black);
Debug.Log(Vector3.Dot(hand.GetPalmDirection(), hand.GetPalmNormal()));
}
}
| gpl-2.0 |
samdunne/terraform | vendor/github.com/xanzy/go-gitlab/tags.go | 4326 | //
// Copyright 2015, Sander van Harmelen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package gitlab
import (
"fmt"
"net/url"
)
// TagsService handles communication with the tags related methods
// of the GitLab API.
//
// GitLab API docs:
// https://gitlab.com/gitlab-org/gitlab-ce/blob/8-16-stable/doc/api/tags.md
type TagsService struct {
client *Client
}
// Tag represents a GitLab tag.
//
// GitLab API docs:
// https://gitlab.com/gitlab-org/gitlab-ce/blob/8-16-stable/doc/api/tags.md
type Tag struct {
Commit *Commit `json:"commit"`
Name string `json:"name"`
Message string `json:"message"`
}
func (r Tag) String() string {
return Stringify(r)
}
// ListTags gets a list of tags from a project, sorted by name in reverse
// alphabetical order.
//
// GitLab API docs:
// https://gitlab.com/gitlab-org/gitlab-ce/blob/8-16-stable/doc/api/tags.md#list-project-repository-tags
func (s *TagsService) ListTags(pid interface{}, options ...OptionFunc) ([]*Tag, *Response, error) {
project, err := parseID(pid)
if err != nil {
return nil, nil, err
}
u := fmt.Sprintf("projects/%s/repository/tags", url.QueryEscape(project))
req, err := s.client.NewRequest("GET", u, nil, options)
if err != nil {
return nil, nil, err
}
var t []*Tag
resp, err := s.client.Do(req, &t)
if err != nil {
return nil, resp, err
}
return t, resp, err
}
// GetTag a specific repository tag determined by its name. It returns 200 together
// with the tag information if the tag exists. It returns 404 if the tag does not exist.
//
// GitLab API docs:
// https://gitlab.com/gitlab-org/gitlab-ce/blob/8-16-stable/doc/api/tags.md#get-a-single-repository-tag
func (s *TagsService) GetTag(pid interface{}, tag string, options ...OptionFunc) (*Tag, *Response, error) {
project, err := parseID(pid)
if err != nil {
return nil, nil, err
}
u := fmt.Sprintf("projects/%s/repository/tags/%s", url.QueryEscape(project), tag)
req, err := s.client.NewRequest("GET", u, nil, options)
if err != nil {
return nil, nil, err
}
var t *Tag
resp, err := s.client.Do(req, &t)
if err != nil {
return nil, resp, err
}
return t, resp, err
}
// CreateTagOptions represents the available CreateTag() options.
//
// GitLab API docs:
// https://gitlab.com/gitlab-org/gitlab-ce/blob/8-16-stable/doc/api/tags.md#create-a-new-tag
type CreateTagOptions struct {
TagName *string `url:"tag_name,omitempty" json:"tag_name,omitempty"`
Ref *string `url:"ref,omitempty" json:"ref,omitempty"`
Message *string `url:"message,omitempty" json:"message,omitempty"`
}
// CreateTag creates a new tag in the repository that points to the supplied ref.
//
// GitLab API docs:
// https://gitlab.com/gitlab-org/gitlab-ce/blob/8-16-stable/doc/api/tags.md#create-a-new-tag
func (s *TagsService) CreateTag(pid interface{}, opt *CreateTagOptions, options ...OptionFunc) (*Tag, *Response, error) {
project, err := parseID(pid)
if err != nil {
return nil, nil, err
}
u := fmt.Sprintf("projects/%s/repository/tags", url.QueryEscape(project))
req, err := s.client.NewRequest("POST", u, opt, options)
if err != nil {
return nil, nil, err
}
t := new(Tag)
resp, err := s.client.Do(req, t)
if err != nil {
return nil, resp, err
}
return t, resp, err
}
// DeleteTag deletes a tag of a repository with given name.
//
// GitLab API docs:
// https://gitlab.com/gitlab-org/gitlab-ce/blob/8-16-stable/doc/api/tags.md#delete-a-tag
func (s *TagsService) DeleteTag(pid interface{}, tag string, options ...OptionFunc) (*Response, error) {
project, err := parseID(pid)
if err != nil {
return nil, err
}
u := fmt.Sprintf("projects/%s/repository/tags/%s", url.QueryEscape(project), tag)
req, err := s.client.NewRequest("DELETE", u, nil, options)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
| mpl-2.0 |
finetjul/CTK | Applications/ctkSimplePythonShell/Testing/Python/wrappedQPropertyTest.py | 226 |
import qt
if (_testWrappedQPropertyInstance.value != 0):
qt.QApplication.exit(1)
_testWrappedQPropertyInstance.value = 74
if (_testWrappedQPropertyInstance.value != 74):
qt.QApplication.exit(1)
qt.QApplication.exit(0)
| apache-2.0 |
aospx-kitkat/platform_external_chromium_org | chrome/renderer/translate/translate_helper_browsertest.cc | 20156 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/time/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/translate/translate_helper.h"
#include "chrome/test/base/chrome_render_view_test.h"
#include "content/public/renderer/render_view.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/public/web/WebHistoryItem.h"
using testing::AtLeast;
using testing::Return;
using testing::_;
class TestTranslateHelper : public TranslateHelper {
public:
explicit TestTranslateHelper(content::RenderView* render_view)
: TranslateHelper(render_view) {
}
virtual base::TimeDelta AdjustDelay(int delayInMs) OVERRIDE {
// Just returns base::TimeDelta() which has initial value 0.
// Tasks doesn't need to be delayed in tests.
return base::TimeDelta();
}
void TranslatePage(int page_id,
const std::string& source_lang,
const std::string& target_lang,
const std::string& translate_script) {
OnTranslatePage(page_id, translate_script, source_lang, target_lang);
}
MOCK_METHOD0(IsTranslateLibAvailable, bool());
MOCK_METHOD0(IsTranslateLibReady, bool());
MOCK_METHOD0(HasTranslationFinished, bool());
MOCK_METHOD0(HasTranslationFailed, bool());
MOCK_METHOD0(GetOriginalPageLanguage, std::string());
MOCK_METHOD0(StartTranslation, bool());
MOCK_METHOD1(ExecuteScript, void(const std::string&));
MOCK_METHOD2(ExecuteScriptAndGetBoolResult, bool(const std::string&, bool));
MOCK_METHOD1(ExecuteScriptAndGetStringResult,
std::string(const std::string&));
MOCK_METHOD1(ExecuteScriptAndGetDoubleResult, double(const std::string&));
private:
DISALLOW_COPY_AND_ASSIGN(TestTranslateHelper);
};
class TranslateHelperBrowserTest : public ChromeRenderViewTest {
public:
TranslateHelperBrowserTest() : translate_helper_(NULL) {}
protected:
virtual void SetUp() OVERRIDE {
ChromeRenderViewTest::SetUp();
translate_helper_ = new TestTranslateHelper(view_);
}
virtual void TearDown() OVERRIDE {
delete translate_helper_;
ChromeRenderViewTest::TearDown();
}
bool GetPageTranslatedMessage(int* page_id,
std::string* original_lang,
std::string* target_lang,
TranslateErrors::Type* error) {
const IPC::Message* message = render_thread_->sink().
GetUniqueMessageMatching(ChromeViewHostMsg_PageTranslated::ID);
if (!message)
return false;
Tuple4<int, std::string, std::string, TranslateErrors::Type>
translate_param;
ChromeViewHostMsg_PageTranslated::Read(message, &translate_param);
if (page_id)
*page_id = translate_param.a;
if (original_lang)
*original_lang = translate_param.b;
if (target_lang)
*target_lang = translate_param.c;
if (error)
*error = translate_param.d;
return true;
}
TestTranslateHelper* translate_helper_;
private:
DISALLOW_COPY_AND_ASSIGN(TranslateHelperBrowserTest);
};
// Tests that the browser gets notified of the translation failure if the
// translate library fails/times-out during initialization.
TEST_F(TranslateHelperBrowserTest, TranslateLibNeverReady) {
// We make IsTranslateLibAvailable true so we don't attempt to inject the
// library.
EXPECT_CALL(*translate_helper_, IsTranslateLibAvailable())
.Times(AtLeast(1))
.WillRepeatedly(Return(true));
EXPECT_CALL(*translate_helper_, IsTranslateLibReady())
.Times(AtLeast(5)) // See kMaxTranslateInitCheckAttempts in
// translate_helper.cc
.WillRepeatedly(Return(false));
translate_helper_->TranslatePage(
view_->GetPageId(), "en", "fr", std::string());
base::MessageLoop::current()->RunUntilIdle();
int page_id;
TranslateErrors::Type error;
ASSERT_TRUE(GetPageTranslatedMessage(&page_id, NULL, NULL, &error));
EXPECT_EQ(view_->GetPageId(), page_id);
EXPECT_EQ(TranslateErrors::INITIALIZATION_ERROR, error);
}
// Tests that the browser gets notified of the translation success when the
// translation succeeds.
TEST_F(TranslateHelperBrowserTest, TranslateSuccess) {
// We make IsTranslateLibAvailable true so we don't attempt to inject the
// library.
EXPECT_CALL(*translate_helper_, IsTranslateLibAvailable())
.Times(AtLeast(1))
.WillRepeatedly(Return(true));
EXPECT_CALL(*translate_helper_, IsTranslateLibReady())
.WillOnce(Return(false))
.WillOnce(Return(true));
EXPECT_CALL(*translate_helper_, StartTranslation()).WillOnce(Return(true));
// Succeed after few checks.
EXPECT_CALL(*translate_helper_, HasTranslationFailed())
.WillRepeatedly(Return(false));
EXPECT_CALL(*translate_helper_, HasTranslationFinished())
.WillOnce(Return(false))
.WillOnce(Return(false))
.WillOnce(Return(true));
// V8 call for performance monitoring should be ignored.
EXPECT_CALL(*translate_helper_,
ExecuteScriptAndGetDoubleResult(_)).Times(3);
std::string original_lang("en");
std::string target_lang("fr");
translate_helper_->TranslatePage(
view_->GetPageId(), original_lang, target_lang, std::string());
base::MessageLoop::current()->RunUntilIdle();
int page_id;
std::string received_original_lang;
std::string received_target_lang;
TranslateErrors::Type error;
ASSERT_TRUE(GetPageTranslatedMessage(&page_id,
&received_original_lang,
&received_target_lang,
&error));
EXPECT_EQ(view_->GetPageId(), page_id);
EXPECT_EQ(original_lang, received_original_lang);
EXPECT_EQ(target_lang, received_target_lang);
EXPECT_EQ(TranslateErrors::NONE, error);
}
// Tests that the browser gets notified of the translation failure when the
// translation fails.
TEST_F(TranslateHelperBrowserTest, TranslateFailure) {
// We make IsTranslateLibAvailable true so we don't attempt to inject the
// library.
EXPECT_CALL(*translate_helper_, IsTranslateLibAvailable())
.Times(AtLeast(1))
.WillRepeatedly(Return(true));
EXPECT_CALL(*translate_helper_, IsTranslateLibReady())
.WillOnce(Return(true));
EXPECT_CALL(*translate_helper_, StartTranslation()).WillOnce(Return(true));
// Fail after few checks.
EXPECT_CALL(*translate_helper_, HasTranslationFailed())
.WillOnce(Return(false))
.WillOnce(Return(false))
.WillOnce(Return(false))
.WillOnce(Return(true));
EXPECT_CALL(*translate_helper_, HasTranslationFinished())
.Times(AtLeast(1))
.WillRepeatedly(Return(false));
// V8 call for performance monitoring should be ignored.
EXPECT_CALL(*translate_helper_,
ExecuteScriptAndGetDoubleResult(_)).Times(2);
translate_helper_->TranslatePage(
view_->GetPageId(), "en", "fr", std::string());
base::MessageLoop::current()->RunUntilIdle();
int page_id;
TranslateErrors::Type error;
ASSERT_TRUE(GetPageTranslatedMessage(&page_id, NULL, NULL, &error));
EXPECT_EQ(view_->GetPageId(), page_id);
EXPECT_EQ(TranslateErrors::TRANSLATION_ERROR, error);
}
// Tests that when the browser translate a page for which the language is
// undefined we query the translate element to get the language.
TEST_F(TranslateHelperBrowserTest, UndefinedSourceLang) {
// We make IsTranslateLibAvailable true so we don't attempt to inject the
// library.
EXPECT_CALL(*translate_helper_, IsTranslateLibAvailable())
.Times(AtLeast(1))
.WillRepeatedly(Return(true));
EXPECT_CALL(*translate_helper_, IsTranslateLibReady())
.WillOnce(Return(true));
EXPECT_CALL(*translate_helper_, GetOriginalPageLanguage())
.WillOnce(Return("de"));
EXPECT_CALL(*translate_helper_, StartTranslation()).WillOnce(Return(true));
EXPECT_CALL(*translate_helper_, HasTranslationFailed())
.WillOnce(Return(false));
EXPECT_CALL(*translate_helper_, HasTranslationFinished())
.Times(AtLeast(1))
.WillRepeatedly(Return(true));
// V8 call for performance monitoring should be ignored.
EXPECT_CALL(*translate_helper_,
ExecuteScriptAndGetDoubleResult(_)).Times(3);
translate_helper_->TranslatePage(view_->GetPageId(),
chrome::kUnknownLanguageCode, "fr",
std::string());
base::MessageLoop::current()->RunUntilIdle();
int page_id;
TranslateErrors::Type error;
std::string original_lang;
std::string target_lang;
ASSERT_TRUE(GetPageTranslatedMessage(&page_id, &original_lang, &target_lang,
&error));
EXPECT_EQ(view_->GetPageId(), page_id);
EXPECT_EQ("de", original_lang);
EXPECT_EQ("fr", target_lang);
EXPECT_EQ(TranslateErrors::NONE, error);
}
// Tests that starting a translation while a similar one is pending does not
// break anything.
TEST_F(TranslateHelperBrowserTest, MultipleSimilarTranslations) {
// We make IsTranslateLibAvailable true so we don't attempt to inject the
// library.
EXPECT_CALL(*translate_helper_, IsTranslateLibAvailable())
.Times(AtLeast(1))
.WillRepeatedly(Return(true));
EXPECT_CALL(*translate_helper_, IsTranslateLibReady())
.WillRepeatedly(Return(true));
EXPECT_CALL(*translate_helper_, StartTranslation())
.WillRepeatedly(Return(true));
EXPECT_CALL(*translate_helper_, HasTranslationFailed())
.WillRepeatedly(Return(false));
EXPECT_CALL(*translate_helper_, HasTranslationFinished())
.WillOnce(Return(true));
// V8 call for performance monitoring should be ignored.
EXPECT_CALL(*translate_helper_,
ExecuteScriptAndGetDoubleResult(_)).Times(3);
std::string original_lang("en");
std::string target_lang("fr");
translate_helper_->TranslatePage(
view_->GetPageId(), original_lang, target_lang, std::string());
// While this is running call again TranslatePage to make sure noting bad
// happens.
translate_helper_->TranslatePage(
view_->GetPageId(), original_lang, target_lang, std::string());
base::MessageLoop::current()->RunUntilIdle();
int page_id;
std::string received_original_lang;
std::string received_target_lang;
TranslateErrors::Type error;
ASSERT_TRUE(GetPageTranslatedMessage(&page_id,
&received_original_lang,
&received_target_lang,
&error));
EXPECT_EQ(view_->GetPageId(), page_id);
EXPECT_EQ(original_lang, received_original_lang);
EXPECT_EQ(target_lang, received_target_lang);
EXPECT_EQ(TranslateErrors::NONE, error);
}
// Tests that starting a translation while a different one is pending works.
TEST_F(TranslateHelperBrowserTest, MultipleDifferentTranslations) {
EXPECT_CALL(*translate_helper_, IsTranslateLibAvailable())
.Times(AtLeast(1))
.WillRepeatedly(Return(true));
EXPECT_CALL(*translate_helper_, IsTranslateLibReady())
.WillRepeatedly(Return(true));
EXPECT_CALL(*translate_helper_, StartTranslation())
.WillRepeatedly(Return(true));
EXPECT_CALL(*translate_helper_, HasTranslationFailed())
.WillRepeatedly(Return(false));
EXPECT_CALL(*translate_helper_, HasTranslationFinished())
.WillOnce(Return(true));
// V8 call for performance monitoring should be ignored.
EXPECT_CALL(*translate_helper_,
ExecuteScriptAndGetDoubleResult(_)).Times(5);
std::string original_lang("en");
std::string target_lang("fr");
translate_helper_->TranslatePage(
view_->GetPageId(), original_lang, target_lang, std::string());
// While this is running call again TranslatePage with a new target lang.
std::string new_target_lang("de");
translate_helper_->TranslatePage(
view_->GetPageId(), original_lang, new_target_lang, std::string());
base::MessageLoop::current()->RunUntilIdle();
int page_id;
std::string received_original_lang;
std::string received_target_lang;
TranslateErrors::Type error;
ASSERT_TRUE(GetPageTranslatedMessage(&page_id,
&received_original_lang,
&received_target_lang,
&error));
EXPECT_EQ(view_->GetPageId(), page_id);
EXPECT_EQ(original_lang, received_original_lang);
EXPECT_EQ(new_target_lang, received_target_lang);
EXPECT_EQ(TranslateErrors::NONE, error);
}
// Tests that we send the right translate language message for a page and that
// we respect the "no translate" meta-tag.
TEST_F(ChromeRenderViewTest, TranslatablePage) {
// Suppress the normal delay that occurs when the page is loaded before which
// the renderer sends the page contents to the browser.
SendContentStateImmediately();
LoadHTML("<html><body>A random page with random content.</body></html>");
const IPC::Message* message = render_thread_->sink().GetUniqueMessageMatching(
ChromeViewHostMsg_TranslateLanguageDetermined::ID);
ASSERT_NE(static_cast<IPC::Message*>(NULL), message);
ChromeViewHostMsg_TranslateLanguageDetermined::Param params;
ChromeViewHostMsg_TranslateLanguageDetermined::Read(message, ¶ms);
EXPECT_TRUE(params.b) << "Page should be translatable.";
render_thread_->sink().ClearMessages();
// Now the page specifies the META tag to prevent translation.
LoadHTML("<html><head><meta name=\"google\" value=\"notranslate\"></head>"
"<body>A random page with random content.</body></html>");
message = render_thread_->sink().GetUniqueMessageMatching(
ChromeViewHostMsg_TranslateLanguageDetermined::ID);
ASSERT_NE(static_cast<IPC::Message*>(NULL), message);
ChromeViewHostMsg_TranslateLanguageDetermined::Read(message, ¶ms);
EXPECT_FALSE(params.b) << "Page should not be translatable.";
render_thread_->sink().ClearMessages();
// Try the alternate version of the META tag (content instead of value).
LoadHTML("<html><head><meta name=\"google\" content=\"notranslate\"></head>"
"<body>A random page with random content.</body></html>");
message = render_thread_->sink().GetUniqueMessageMatching(
ChromeViewHostMsg_TranslateLanguageDetermined::ID);
ASSERT_NE(static_cast<IPC::Message*>(NULL), message);
ChromeViewHostMsg_TranslateLanguageDetermined::Read(message, ¶ms);
EXPECT_FALSE(params.b) << "Page should not be translatable.";
}
// Tests that the language meta tag takes precedence over the CLD when reporting
// the page's language.
TEST_F(ChromeRenderViewTest, LanguageMetaTag) {
// Suppress the normal delay that occurs when the page is loaded before which
// the renderer sends the page contents to the browser.
SendContentStateImmediately();
LoadHTML("<html><head><meta http-equiv=\"content-language\" content=\"es\">"
"</head><body>A random page with random content.</body></html>");
const IPC::Message* message = render_thread_->sink().GetUniqueMessageMatching(
ChromeViewHostMsg_TranslateLanguageDetermined::ID);
ASSERT_NE(static_cast<IPC::Message*>(NULL), message);
ChromeViewHostMsg_TranslateLanguageDetermined::Param params;
ChromeViewHostMsg_TranslateLanguageDetermined::Read(message, ¶ms);
EXPECT_EQ("es", params.a.adopted_language);
render_thread_->sink().ClearMessages();
// Makes sure we support multiple languages specified.
LoadHTML("<html><head><meta http-equiv=\"content-language\" "
"content=\" fr , es,en \">"
"</head><body>A random page with random content.</body></html>");
message = render_thread_->sink().GetUniqueMessageMatching(
ChromeViewHostMsg_TranslateLanguageDetermined::ID);
ASSERT_NE(static_cast<IPC::Message*>(NULL), message);
ChromeViewHostMsg_TranslateLanguageDetermined::Read(message, ¶ms);
EXPECT_EQ("fr", params.a.adopted_language);
}
// Tests that the language meta tag works even with non-all-lower-case.
// http://code.google.com/p/chromium/issues/detail?id=145689
TEST_F(ChromeRenderViewTest, LanguageMetaTagCase) {
// Suppress the normal delay that occurs when the page is loaded before which
// the renderer sends the page contents to the browser.
SendContentStateImmediately();
LoadHTML("<html><head><meta http-equiv=\"Content-Language\" content=\"es\">"
"</head><body>A random page with random content.</body></html>");
const IPC::Message* message = render_thread_->sink().GetUniqueMessageMatching(
ChromeViewHostMsg_TranslateLanguageDetermined::ID);
ASSERT_NE(static_cast<IPC::Message*>(NULL), message);
ChromeViewHostMsg_TranslateLanguageDetermined::Param params;
ChromeViewHostMsg_TranslateLanguageDetermined::Read(message, ¶ms);
EXPECT_EQ("es", params.a.adopted_language);
render_thread_->sink().ClearMessages();
// Makes sure we support multiple languages specified.
LoadHTML("<html><head><meta http-equiv=\"Content-Language\" "
"content=\" fr , es,en \">"
"</head><body>A random page with random content.</body></html>");
message = render_thread_->sink().GetUniqueMessageMatching(
ChromeViewHostMsg_TranslateLanguageDetermined::ID);
ASSERT_NE(static_cast<IPC::Message*>(NULL), message);
ChromeViewHostMsg_TranslateLanguageDetermined::Read(message, ¶ms);
EXPECT_EQ("fr", params.a.adopted_language);
}
// Tests that the language meta tag is converted to Chrome standard of dashes
// instead of underscores and proper capitalization.
// http://code.google.com/p/chromium/issues/detail?id=159487
TEST_F(ChromeRenderViewTest, LanguageCommonMistakesAreCorrected) {
// Suppress the normal delay that occurs when the page is loaded before which
// the renderer sends the page contents to the browser.
SendContentStateImmediately();
LoadHTML("<html><head><meta http-equiv='Content-Language' content='EN_us'>"
"</head><body>A random page with random content.</body></html>");
const IPC::Message* message = render_thread_->sink().GetUniqueMessageMatching(
ChromeViewHostMsg_TranslateLanguageDetermined::ID);
ASSERT_NE(static_cast<IPC::Message*>(NULL), message);
ChromeViewHostMsg_TranslateLanguageDetermined::Param params;
ChromeViewHostMsg_TranslateLanguageDetermined::Read(message, ¶ms);
EXPECT_EQ("en-US", params.a.adopted_language);
render_thread_->sink().ClearMessages();
}
// Tests that a back navigation gets a translate language message.
TEST_F(ChromeRenderViewTest, BackToTranslatablePage) {
SendContentStateImmediately();
LoadHTML("<html><head><meta http-equiv=\"content-language\" content=\"zh\">"
"</head><body>This page is in Chinese.</body></html>");
const IPC::Message* message = render_thread_->sink().GetUniqueMessageMatching(
ChromeViewHostMsg_TranslateLanguageDetermined::ID);
ASSERT_NE(static_cast<IPC::Message*>(NULL), message);
ChromeViewHostMsg_TranslateLanguageDetermined::Param params;
ChromeViewHostMsg_TranslateLanguageDetermined::Read(message, ¶ms);
EXPECT_EQ("zh", params.a.adopted_language);
render_thread_->sink().ClearMessages();
LoadHTML("<html><head><meta http-equiv=\"content-language\" content=\"fr\">"
"</head><body>This page is in French.</body></html>");
message = render_thread_->sink().GetUniqueMessageMatching(
ChromeViewHostMsg_TranslateLanguageDetermined::ID);
ASSERT_NE(static_cast<IPC::Message*>(NULL), message);
ChromeViewHostMsg_TranslateLanguageDetermined::Read(message, ¶ms);
EXPECT_EQ("fr", params.a.adopted_language);
render_thread_->sink().ClearMessages();
GoBack(GetMainFrame()->previousHistoryItem());
message = render_thread_->sink().GetUniqueMessageMatching(
ChromeViewHostMsg_TranslateLanguageDetermined::ID);
ASSERT_NE(static_cast<IPC::Message*>(NULL), message);
ChromeViewHostMsg_TranslateLanguageDetermined::Read(message, ¶ms);
EXPECT_EQ("zh", params.a.adopted_language);
render_thread_->sink().ClearMessages();
}
| bsd-3-clause |
allquixotic/opensim-autobackup | OpenSim/Region/OptionalModules/Scripting/Minimodule/Test/TestModule.cs | 3535 | /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 OpenSimulator 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 DEVELOPERS ``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 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.
*/
using System.Collections;
using System.Collections.Generic;
using OpenSim.Region.OptionalModules.Scripting.Minimodule;
namespace OpenSim
{
class MiniModule : MRMBase
{
// private microthreaded Function(params...)
private IEnumerable TestMicrothread(string param)
{
Host.Console.Info("Microthreaded " + param);
// relax;
yield return null;
Host.Console.Info("Microthreaded 2" + param);
yield return null;
int c = 100;
while (c-- < 0)
{
Host.Console.Info("Microthreaded Looped " + c + " " + param);
yield return null;
}
}
public void Microthread(IEnumerable thread)
{
}
public void RunMicrothread()
{
List<IEnumerator> threads = new List<IEnumerator>();
threads.Add(TestMicrothread("A").GetEnumerator());
threads.Add(TestMicrothread("B").GetEnumerator());
threads.Add(TestMicrothread("C").GetEnumerator());
Microthread(TestMicrothread("Ohai"));
int i = 0;
while (threads.Count > 0)
{
i++;
bool running = threads[i%threads.Count].MoveNext();
if (!running)
threads.Remove(threads[i%threads.Count]);
}
}
public override void Start()
{
// Say Hello
Host.Object.Say("Hello, Avatar!");
// Register ourselves to listen
// for touch events.
Host.Object.OnTouch += OnTouched;
}
// This is our touch event handler
void OnTouched(IObject sender, TouchEventArgs e)
{
Host.Object.Say("Touched.");
}
public override void Stop()
{
}
}
}
| bsd-3-clause |
4ad/go | test/fixedbugs/bug328.go | 252 | // cmpout
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import "unsafe"
func main() {
var p unsafe.Pointer
println(p)
}
| bsd-3-clause |
ltilve/ChromiumGStreamerBackend | device/hid/hid_device_info_linux.cc | 869 | // 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 "hid_device_info_linux.h"
namespace device {
HidDeviceInfoLinux::HidDeviceInfoLinux(
const HidDeviceId& device_id,
const std::string& device_node,
uint16_t vendor_id,
uint16_t product_id,
const std::string& product_name,
const std::string& serial_number,
HidBusType bus_type,
const std::vector<uint8> report_descriptor)
: HidDeviceInfo(device_id,
vendor_id,
product_id,
product_name,
serial_number,
bus_type,
report_descriptor),
device_node_(device_node) {
}
HidDeviceInfoLinux::~HidDeviceInfoLinux() {
}
} // namespace device
| bsd-3-clause |
cuboxi/android_external_chromium_org | chrome/android/java/src/org/chromium/chrome/browser/contextmenu/EmptyChromeContextMenuItemDelegate.java | 1293 | // Copyright 2013 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.
package org.chromium.chrome.browser.contextmenu;
/**
* An empty implementation of {@link ChromeContextMenuItemDelegate} to make overriding subsets of
* the delegate methods easier.
*/
public class EmptyChromeContextMenuItemDelegate implements ChromeContextMenuItemDelegate {
@Override
public boolean isIncognito() {
return false;
}
@Override
public boolean isIncognitoSupported() {
return false;
}
@Override
public boolean canLoadOriginalImage() {
return false;
}
@Override
public boolean startDownload(boolean isLink) {
return false;
}
@Override
public void onOpenInNewTab(String url) {
}
@Override
public void onOpenInNewIncognitoTab(String url) {
}
@Override
public void onOpenImageUrl(String url) {
}
@Override
public void onOpenImageInNewTab(String url) {
}
@Override
public void onSaveToClipboard(String text, boolean isUrl) {
}
@Override
public void onSaveImageToClipboard(String url) {
}
@Override
public void onSearchByImageInNewTab() {
}
} | bsd-3-clause |
deek87/concrete5 | concrete/src/Service/Configuration/StorageInterface.php | 748 | <?php
namespace Concrete\Core\Service\Configuration;
use Exception;
interface StorageInterface
{
/**
* Determine whether the configuration can be read.
*
* @return bool
*/
public function canRead();
/**
* Read the configuration.
*
* @return string
*
* @throws Exception Throws an exception in case of errors.
*/
public function read();
/**
* Determine whether this configuration can be written.
*
* @return bool
*/
public function canWrite();
/**
* Read the configuration.
*
* @param string $configuration
*
* @throws Exception Throws an exception in case of errors.
*/
public function write($configuration);
}
| mit |
codydaig/hub | Godeps/_workspace/src/github.com/octokit/go-octokit/octokit/releases_test.go | 3712 | package octokit
import (
"net/http"
"testing"
"github.com/github/hub/Godeps/_workspace/src/github.com/bmizerany/assert"
)
func TestReleasesService_All(t *testing.T) {
setup()
defer tearDown()
mux.HandleFunc("/repos/jingweno/gh/releases", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "GET")
respondWithJSON(w, loadFixture("releases.json"))
})
url, err := ReleasesURL.Expand(M{"owner": "jingweno", "repo": "gh"})
assert.Equal(t, nil, err)
releases, result := client.Releases(url).All()
assert.T(t, !result.HasError())
assert.Equal(t, 1, len(releases))
firstRelease := releases[0]
assert.Equal(t, 50013, firstRelease.ID)
assert.Equal(t, "v0.23.0", firstRelease.TagName)
assert.Equal(t, "master", firstRelease.TargetCommitish)
assert.Equal(t, "v0.23.0", firstRelease.Name)
assert.T(t, !firstRelease.Draft)
assert.T(t, !firstRelease.Prerelease)
assert.Equal(t, "* Windows works!: https://github.com/jingweno/gh/commit/6cb80cb09fd9f624a64d85438157955751a9ac70", firstRelease.Body)
assert.Equal(t, "https://api.github.com/repos/jingweno/gh/releases/50013", firstRelease.URL)
assert.Equal(t, "https://api.github.com/repos/jingweno/gh/releases/50013/assets", firstRelease.AssetsURL)
assert.Equal(t, "https://uploads.github.com/repos/jingweno/gh/releases/50013/assets{?name}", string(firstRelease.UploadURL))
assert.Equal(t, "https://github.com/jingweno/gh/releases/v0.23.0", firstRelease.HTMLURL)
assert.Equal(t, "2013-09-23 00:59:10 +0000 UTC", firstRelease.CreatedAt.String())
assert.Equal(t, "2013-09-23 01:07:56 +0000 UTC", firstRelease.PublishedAt.String())
firstReleaseAssets := firstRelease.Assets
assert.Equal(t, 8, len(firstReleaseAssets))
firstAsset := firstReleaseAssets[0]
assert.Equal(t, 20428, firstAsset.ID)
assert.Equal(t, "gh_0.23.0-snapshot_amd64.deb", firstAsset.Name)
assert.Equal(t, "gh_0.23.0-snapshot_amd64.deb", firstAsset.Label)
assert.Equal(t, "application/x-deb", firstAsset.ContentType)
assert.Equal(t, "uploaded", firstAsset.State)
assert.Equal(t, 1562984, firstAsset.Size)
assert.Equal(t, 0, firstAsset.DownloadCount)
assert.Equal(t, "https://api.github.com/repos/jingweno/gh/releases/assets/20428", firstAsset.URL)
assert.Equal(t, "2013-09-23 01:05:20 +0000 UTC", firstAsset.CreatedAt.String())
assert.Equal(t, "2013-09-23 01:07:56 +0000 UTC", firstAsset.UpdatedAt.String())
}
func TestCreateRelease(t *testing.T) {
setup()
defer tearDown()
mux.HandleFunc("/repos/octokit/Hello-World/releases", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "POST")
testBody(t, r, "{\"tag_name\":\"v1.0.0\",\"target_commitish\":\"master\"}\n")
respondWithJSON(w, loadFixture("create_release.json"))
})
url, err := ReleasesURL.Expand(M{"owner": "octokit", "repo": "Hello-World"})
assert.Equal(t, nil, err)
params := Release{
TagName: "v1.0.0",
TargetCommitish: "master",
}
release, result := client.Releases(url).Create(params)
assert.T(t, !result.HasError())
assert.Equal(t, "v1.0.0", release.TagName)
}
func TestUpdateRelease(t *testing.T) {
setup()
defer tearDown()
mux.HandleFunc("/repos/octokit/Hello-World/releases/123", func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, "PATCH")
testBody(t, r, "{\"tag_name\":\"v1.0.0\",\"target_commitish\":\"master\"}\n")
respondWithJSON(w, loadFixture("create_release.json"))
})
url, err := ReleasesURL.Expand(M{"owner": "octokit", "repo": "Hello-World", "id": "123"})
assert.Equal(t, nil, err)
params := Release{
TagName: "v1.0.0",
TargetCommitish: "master",
}
release, result := client.Releases(url).Update(params)
assert.T(t, !result.HasError())
assert.Equal(t, "v1.0.0", release.TagName)
}
| mit |
ShionRyuu/sproto | testall.lua | 741 | local sproto = require "sproto"
local print_r = require "print_r"
local sp = sproto.parse [[
.foobar {
.nest {
a 1 : string
b 3 : boolean
c 5 : integer
}
a 0 : string
b 1 : integer
c 2 : boolean
d 3 : *nest(a)
e 4 : *string
f 5 : *integer
g 6 : *boolean
h 7 : *foobar
}
]]
local obj = {
a = "hello",
b = 1000000,
c = true,
d = {
{
a = "one",
-- skip b
c = -1,
},
{
a = "two",
b = true,
},
{
a = "",
b = false,
c = 1,
},
},
e = { "ABC", "", "def" },
f = { -3, -2, -1, 0 , 1, 2},
g = { true, false, true },
h = {
{ b = 100 },
{},
{ b = -100, c= false },
{ b = 0, e = { "test" } },
},
}
local code = sp:encode("foobar", obj)
obj = sp:decode("foobar", code)
print_r(obj)
| mit |
fonea/connections | core/modules/block_content/src/Tests/BlockContentTranslationUITest.php | 5678 | <?php
/**
* @file
* Contains \Drupal\block_content\Tests\BlockContentTranslationUITest.
*/
namespace Drupal\block_content\Tests;
use Drupal\Component\Utility\Unicode;
use Drupal\content_translation\Tests\ContentTranslationUITestBase;
/**
* Tests the block content translation UI.
*
* @group block_content
*/
class BlockContentTranslationUITest extends ContentTranslationUITestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array(
'language',
'content_translation',
'block',
'field_ui',
'block_content'
);
/**
* Overrides \Drupal\simpletest\WebTestBase::setUp().
*/
protected function setUp() {
$this->entityTypeId = 'block_content';
$this->bundle = 'basic';
$this->testLanguageSelector = FALSE;
parent::setUp();
}
/**
* {@inheritdoc}
*/
protected function setupBundle() {
// Create the basic bundle since it is provided by standard.
$bundle = entity_create('block_content_type', array(
'id' => $this->bundle,
'label' => $this->bundle,
'revision' => FALSE
));
$bundle->save();
}
/**
* Overrides \Drupal\content_translation\Tests\ContentTranslationUITestBase::getTranslatorPermission().
*/
public function getTranslatorPermissions() {
return array_merge(parent::getTranslatorPermissions(), array(
'translate any entity',
'access administration pages',
'administer blocks',
'administer block_content fields'
));
}
/**
* Creates a custom block.
*
* @param string $title
* (optional) Title of block. When no value is given uses a random name.
* Defaults to FALSE.
* @param string $bundle
* (optional) Bundle name. When no value is given, defaults to
* $this->bundle. Defaults to FALSE.
*
* @return \Drupal\block_content\Entity\BlockContent
* Created custom block.
*/
protected function createBlockContent($title = FALSE, $bundle = FALSE) {
$title = ($title ? : $this->randomMachineName());
$bundle = ($bundle ? : $this->bundle);
$block_content = entity_create('block_content', array(
'info' => $title,
'type' => $bundle,
'langcode' => 'en'
));
$block_content->save();
return $block_content;
}
/**
* Overrides \Drupal\content_translation\Tests\ContentTranslationUITestBase::getNewEntityValues().
*/
protected function getNewEntityValues($langcode) {
return array('info' => Unicode::strtolower($this->randomMachineName())) + parent::getNewEntityValues($langcode);
}
/**
* Returns an edit array containing the values to be posted.
*/
protected function getEditValues($values, $langcode, $new = FALSE) {
$edit = parent::getEditValues($values, $langcode, $new);
foreach ($edit as $property => $value) {
if ($property == 'info') {
$edit['info[0][value]'] = $value;
unset($edit[$property]);
}
}
return $edit;
}
/**
* {@inheritdoc}
*/
protected function doTestBasicTranslation() {
parent::doTestBasicTranslation();
// Ensure that a block translation can be created using the same description
// as in the original language.
$default_langcode = $this->langcodes[0];
$values = $this->getNewEntityValues($default_langcode);
$storage = \Drupal::entityManager()->getStorage($this->entityTypeId);
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $storage->create(array('type' => 'basic') + $values);
$entity->save();
$entity->addTranslation('it', $values);
try {
$message = 'Blocks can have translations with the same "info" value.';
$entity->save();
$this->pass($message);
}
catch (\Exception $e) {
$this->fail($message);
}
// Check that the translate operation link is shown.
$this->drupalGet('admin/structure/block/block-content');
$this->assertLinkByHref('block/' . $entity->id() . '/translations');
}
/**
* Test that no metadata is stored for a disabled bundle.
*/
public function testDisabledBundle() {
// Create a bundle that does not have translation enabled.
$disabled_bundle = $this->randomMachineName();
$bundle = entity_create('block_content_type', array(
'id' => $disabled_bundle,
'label' => $disabled_bundle,
'revision' => FALSE
));
$bundle->save();
// Create a block content for each bundle.
$enabled_block_content = $this->createBlockContent();
$disabled_block_content = $this->createBlockContent(FALSE, $bundle->id());
// Make sure that only a single row was inserted into the block table.
$rows = db_query('SELECT * FROM {block_content_field_data} WHERE id = :id', array(':id' => $enabled_block_content->id()))->fetchAll();
$this->assertEqual(1, count($rows));
}
/**
* {@inheritdoc}
*/
protected function doTestTranslationEdit() {
$entity = entity_load($this->entityTypeId, $this->entityId, TRUE);
$languages = $this->container->get('language_manager')->getLanguages();
foreach ($this->langcodes as $langcode) {
// We only want to test the title for non-english translations.
if ($langcode != 'en') {
$options = array('language' => $languages[$langcode]);
$url = $entity->urlInfo('edit-form', $options);
$this->drupalGet($url);
$title = t('<em>Edit @type</em> @title [%language translation]', array(
'@type' => $entity->bundle(),
'@title' => $entity->getTranslation($langcode)->label(),
'%language' => $languages[$langcode]->getName(),
));
$this->assertRaw($title);
}
}
}
}
| gpl-2.0 |
louishust/mysql5.6.14_tokudb | storage/tokudb/ft-index/src/tests/hotindexer-bw.cc | 18672 | /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
/*
COPYING CONDITIONS NOTICE:
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation, and provided that the
following conditions are met:
* Redistributions of source code must retain this COPYING
CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
PATENT MARKING NOTICE (below), and the PATENT RIGHTS
GRANT (below).
* Redistributions in binary form must reproduce this COPYING
CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
PATENT MARKING NOTICE (below), and the PATENT RIGHTS
GRANT (below) in the documentation and/or other materials
provided with the distribution.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
COPYRIGHT NOTICE:
TokuFT, Tokutek Fractal Tree Indexing Library.
Copyright (C) 2007-2013 Tokutek, Inc.
DISCLAIMER:
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.
UNIVERSITY PATENT NOTICE:
The technology is licensed by the Massachusetts Institute of
Technology, Rutgers State University of New Jersey, and the Research
Foundation of State University of New York at Stony Brook under
United States of America Serial No. 11/760379 and to the patents
and/or patent applications resulting from it.
PATENT MARKING NOTICE:
This software is covered by US Patent No. 8,185,551.
This software is covered by US Patent No. 8,489,638.
PATENT RIGHTS GRANT:
"THIS IMPLEMENTATION" means the copyrightable works distributed by
Tokutek as part of the Fractal Tree project.
"PATENT CLAIMS" means the claims of patents that are owned or
licensable by Tokutek, both currently or in the future; and that in
the absence of this license would be infringed by THIS
IMPLEMENTATION or by using or running THIS IMPLEMENTATION.
"PATENT CHALLENGE" shall mean a challenge to the validity,
patentability, enforceability and/or non-infringement of any of the
PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS.
Tokutek hereby grants to you, for the term and geographical scope of
the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to
make, have made, use, offer to sell, sell, import, transfer, and
otherwise run, modify, and propagate the contents of THIS
IMPLEMENTATION, where such license applies only to the PATENT
CLAIMS. This grant does not include claims that would be infringed
only as a consequence of further modifications of THIS
IMPLEMENTATION. If you or your agent or licensee institute or order
or agree to the institution of patent litigation against any entity
(including a cross-claim or counterclaim in a lawsuit) alleging that
THIS IMPLEMENTATION constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any rights
granted to you under this License shall terminate as of the date
such litigation is filed. If you or your agent or exclusive
licensee institute or order or agree to the institution of a PATENT
CHALLENGE, then Tokutek may terminate any rights granted to you
under this License.
*/
#ident "Copyright (c) 2010-2013 Tokutek Inc. All rights reserved."
#ident "$Id$"
#include "test.h"
#include "toku_pthread.h"
#include <db.h>
#include <sys/stat.h>
#include "key-val.h"
toku_mutex_t put_lock;
enum {NUM_INDEXER_INDEXES=1};
static const int NUM_DBS = NUM_INDEXER_INDEXES + 1; // 1 for source DB
static const int NUM_ROWS = 100000;
static int num_rows;
static const int FORWARD = 0;
static const int BACKWARD = 1;
typedef int Direction;
static const int TXN_CREATE = 1;
static const int TXN_END = 2;
typedef int TxnWork;
DB_ENV *env;
/*
* client() is a routine intended to be run in a separate thread from index creation
* - it takes a client spec which describes work to be done
* - direction : move to ever increasing or decreasing rows
* - txnwork : whether a transaction should be created or closed within the client
* (allows client transaction to start before or during index creation,
* and to close during or after index creation)
*/
typedef struct {
uint32_t num; // number of rows to write
uint32_t start; // approximate start row
int offset; // offset from stride (= MAX_CLIENTS)
Direction dir;
TxnWork txnwork;
DB_TXN *txn;
DB **dbs;
int client_number;
uint32_t *flags;
} client_spec_t, *client_spec;
int client_count = 0;
static void * client(void *arg)
{
client_spec CAST_FROM_VOIDP(cs, arg);
client_count++;
if ( verbose ) printf("client[%d]\n", cs->client_number);
assert(cs->client_number < MAX_CLIENTS);
assert(cs->dir == FORWARD || cs->dir == BACKWARD);
int r;
if ( cs->txnwork & TXN_CREATE ) { r = env->txn_begin(env, NULL, &cs->txn, 0); CKERR(r); }
DBT key, val;
DBT dest_keys[NUM_DBS];
DBT dest_vals[NUM_DBS];
uint32_t k, v;
int n = cs->start;
for(int which=0;which<NUM_DBS;which++) {
dbt_init(&dest_keys[which], NULL, 0);
dest_keys[which].flags = DB_DBT_REALLOC;
dbt_init(&dest_vals[which], NULL, 0);
dest_vals[which].flags = DB_DBT_REALLOC;
}
int rr = 0;
int retry = 0;
for (uint32_t i = 0; i < cs->num; i++ ) {
DB_TXN *txn;
env->txn_begin(env, cs->txn, &txn, 0);
k = key_to_put(n, cs->offset);
v = generate_val(k, 0);
dbt_init(&key, &k, sizeof(k));
dbt_init(&val, &v, sizeof(v));
while ( retry++ < 10 ) {
toku_mutex_lock(&put_lock);
rr = env_put_multiple_test_no_array(env,
cs->dbs[0],
txn,
&key,
&val,
NUM_DBS,
cs->dbs, // dest dbs
dest_keys,
dest_vals,
cs->flags);
toku_mutex_unlock(&put_lock);
if ( rr == 0 ) break;
sleep(0);
}
if ( rr != 0 ) {
if ( verbose ) printf("client[%u] : put_multiple returns %d, i=%u, n=%u, key=%u\n", cs->client_number, rr, i, n, k);
r = txn->abort(txn); CKERR(r);
break;
}
r = txn->commit(txn, 0); CKERR(r);
n = ( cs->dir == FORWARD ) ? n + 1 : n - 1;
retry = 0;
}
if ( cs->txnwork & TXN_END ) { r = cs->txn->commit(cs->txn, DB_TXN_SYNC); CKERR(r); }
if (verbose) printf("client[%d] done\n", cs->client_number);
for (int which=0; which<NUM_DBS; which++) {
toku_free(dest_keys[which].data);
toku_free(dest_vals[which].data);
}
return 0;
}
toku_pthread_t *client_threads;
client_spec_t *client_specs;
static void clients_init(DB **dbs, uint32_t *flags)
{
XMALLOC_N(MAX_CLIENTS, client_threads);
XMALLOC_N(MAX_CLIENTS, client_specs);
client_specs[0].client_number = 0;
// client_specs[0].start = 0;
client_specs[0].start = num_rows - 1;
client_specs[0].num = num_rows;
client_specs[0].offset = -1;
// client_specs[0].dir = FORWARD;
client_specs[0].dir = BACKWARD;
client_specs[0].txnwork = TXN_CREATE | TXN_END;
client_specs[0].txn = NULL;
client_specs[0].dbs = dbs;
client_specs[0].flags = flags;
client_specs[1].client_number = 1;
client_specs[1].start = 0;
client_specs[1].num = num_rows;
client_specs[1].offset = 1;
client_specs[1].dir = FORWARD;
client_specs[1].txnwork = TXN_CREATE | TXN_END;
client_specs[1].txn = NULL;
client_specs[1].dbs = dbs;
client_specs[1].flags = flags;
}
static void clients_cleanup(void)
{
toku_free(client_threads); client_threads = NULL;
toku_free(client_specs); client_specs = NULL;
}
// verify results
// - read the keys in the primary table, then calculate what keys should exist
// in the other DB. Read the other table to verify.
static void check_results(DB *src, DB *db)
{
int r;
int pass = 1;
int clients = client_count;
int max_rows = ( clients + 1 ) * num_rows;
unsigned int *db_keys = (unsigned int *) toku_malloc(max_rows * sizeof (unsigned int));
DBT key, val;
unsigned int k=0, v=0;
dbt_init(&key, &k, sizeof(unsigned int));
dbt_init(&val, &v, sizeof(unsigned int));
DB_TXN *txn;
r = env->txn_begin(env, NULL, &txn, 0); CKERR(r);
DBC *cursor;
r = src->cursor(src, txn, &cursor, 0); CKERR(r);
int which = *(uint32_t*)db->app_private;
// scan the primary table,
// calculate the expected keys in 'db'
int row = 0;
while ( r != DB_NOTFOUND ) {
r = cursor->c_get(cursor, &key, &val, DB_NEXT);
if ( r != DB_NOTFOUND ) {
k = *((uint32_t *)(key.data));
db_keys[row] = twiddle32(k, which);
row++;
}
}
if ( verbose ) printf("primary table scanned, contains %d rows\n", row);
int primary_rows = row;
r = cursor->c_close(cursor); CKERR(r);
// sort the expected keys
qsort(db_keys, primary_rows, sizeof (unsigned int), uint_cmp);
if ( verbose > 1 ) {
for(int i=0;i<primary_rows;i++) {
printf("primary table[%u] = %u\n", i, db_keys[i]);
}
}
// scan the indexer-created DB, comparing keys with expected keys
// - there should be exactly 'primary_rows' in the new index
r = db->cursor(db, txn, &cursor, 0); CKERR(r);
for (int i=0;i<primary_rows;i++) {
r = cursor->c_get(cursor, &key, &val, DB_NEXT);
if ( r == DB_NOTFOUND ) {
printf("scan of index finds last row is %d\n", i);
}
CKERR(r);
k = *((uint32_t *)(key.data));
if ( db_keys[i] != k ) {
if ( verbose ) printf("ERROR expecting key %10u for row %d, found key = %10u\n", db_keys[i],i,k);
pass = 0;
i++;
// goto check_results_error;
}
}
// next cursor op should return DB_NOTFOUND
r = cursor->c_get(cursor, &key, &val, DB_NEXT);
assert(r == DB_NOTFOUND);
// we're done - cleanup and close
//check_results_error:
r = cursor->c_close(cursor); CKERR(r);
toku_free(db_keys);
r = txn->commit(txn, 0); CKERR(r);
if ( verbose ) {
if ( pass ) printf("check_results : pass\n");
else printf("check_results : fail\n");
}
assert(pass);
return;
}
static void test_indexer(DB *src, DB **dbs)
{
int r;
DB_TXN *txn;
DB_INDEXER *indexer;
uint32_t db_flags[NUM_DBS];
if ( verbose ) printf("test_indexer\n");
for(int i=0;i<NUM_DBS;i++) {
db_flags[i] = 0;
}
clients_init(dbs, db_flags);
// create and initialize indexer
r = env->txn_begin(env, NULL, &txn, 0);
CKERR(r);
if ( verbose ) printf("test_indexer create_indexer\n");
toku_mutex_lock(&put_lock);
r = env->create_indexer(env, txn, &indexer, src, NUM_DBS-1, &dbs[1], db_flags, 0);
CKERR(r);
r = indexer->set_error_callback(indexer, NULL, NULL);
CKERR(r);
r = indexer->set_poll_function(indexer, poll_print, NULL);
CKERR(r);
toku_mutex_unlock(&put_lock);
// start threads doing additional inserts - no lock issues since indexer already created
r = toku_pthread_create(&client_threads[0], 0, client, (void *)&client_specs[0]); CKERR(r);
// r = toku_pthread_create(&client_threads[1], 0, client, (void *)&client_specs[1]); CKERR(r);
struct timeval start, now;
if ( verbose ) {
printf("test_indexer build\n");
gettimeofday(&start,0);
}
r = indexer->build(indexer);
CKERR(r);
if ( verbose ) {
gettimeofday(&now,0);
int duration = (int)(now.tv_sec - start.tv_sec);
if ( duration > 0 )
printf("test_indexer build : sec = %d\n", duration);
}
if ( verbose ) printf("test_indexer close\n");
toku_mutex_lock(&put_lock);
r = indexer->close(indexer);
CKERR(r);
toku_mutex_unlock(&put_lock);
r = txn->commit(txn, DB_TXN_SYNC);
CKERR(r);
void *t0;
r = toku_pthread_join(client_threads[0], &t0); CKERR(r);
// void *t1;
// r = toku_pthread_join(client_threads[1], &t1); CKERR(r);
clients_cleanup();
if ( verbose ) printf("check_results\n");
check_results(src, dbs[1]);
if ( verbose ) printf("PASS\n");
if ( verbose ) printf("test_indexer done\n");
}
static void run_test(void)
{
int r;
toku_mutex_init(&put_lock, NULL);
toku_os_recursive_delete(TOKU_TEST_FILENAME);
r = toku_os_mkdir(TOKU_TEST_FILENAME, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r);
char logname[TOKU_PATH_MAX+1];
r = toku_os_mkdir(toku_path_join(logname, 2, TOKU_TEST_FILENAME, "log"), S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r);
r = db_env_create(&env, 0); CKERR(r);
r = env->set_redzone(env, 0); CKERR(r);
r = env->set_lg_dir(env, "log"); CKERR(r);
r = env->set_default_bt_compare(env, uint_dbt_cmp); CKERR(r);
generate_permute_tables();
r = env->set_generate_row_callback_for_put(env, put_multiple_generate); CKERR(r);
int envflags = DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN | DB_CREATE | DB_PRIVATE | DB_INIT_LOG;
r = env->open(env, TOKU_TEST_FILENAME, envflags, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r);
env->set_errfile(env, stderr);
r = env->checkpointing_set_period(env, 0); CKERR(r);
DBT desc;
dbt_init(&desc, "foo", sizeof("foo"));
int ids[MAX_DBS];
DB *dbs[MAX_DBS];
for (int i = 0; i < NUM_DBS; i++) {
ids[i] = i;
r = db_create(&dbs[i], env, 0); CKERR(r);
dbs[i]->app_private = &ids[i];
char key_name[32];
sprintf(key_name, "key%d", i);
r = dbs[i]->open(dbs[i], NULL, key_name, NULL, DB_BTREE, DB_AUTO_COMMIT|DB_CREATE, 0666); CKERR(r);
IN_TXN_COMMIT(env, NULL, txn_desc, 0, {
{ int chk_r = dbs[i]->change_descriptor(dbs[i], txn_desc, &desc, 0); CKERR(chk_r); }
});
}
// generate the src DB (do not use put_multiple)
DB_TXN *txn;
r = env->txn_begin(env, NULL, &txn, 0); CKERR(r);
r = generate_initial_table(dbs[0], txn, num_rows); CKERR(r);
r = txn->commit(txn, DB_TXN_SYNC); CKERR(r);
// -------------------------- //
if (1) test_indexer(dbs[0], dbs);
// -------------------------- //
for(int i=0;i<NUM_DBS;i++) {
r = dbs[i]->close(dbs[i], 0); CKERR(r);
}
toku_mutex_destroy(&put_lock);
r = env->close(env, 0); CKERR(r);
}
// ------------ infrastructure ----------
static inline void
do_args (int argc, char * const argv[]) {
const char *progname=argv[0];
num_rows = NUM_ROWS;
argc--; argv++;
while (argc>0) {
if (strcmp(argv[0],"-v")==0) {
verbose++;
} else if (strcmp(argv[0],"-q")==0) {
verbose=0;
} else if (strcmp(argv[0],"-r")==0) {
argc--; argv++;
num_rows = atoi(argv[0]);
} else {
fprintf(stderr, "Usage:\n %s [-v] [-q] [-r rows]\n", progname);
exit(1);
}
argc--; argv++;
}
}
int test_main(int argc, char * const *argv) {
do_args(argc, argv);
run_test();
return 0;
}
/*
* Please ignore this code - I don't think I'm going to use it, but I don't want to lose it
* I will delete this later - Dave
if ( rr != 0 ) { // possible lock deadlock
if (verbose > 1) {
printf("client[%u] : put_multiple returns %d, i=%u, n=%u, key=%u\n", cs->client_number, rr, i, n, k);
if ( verbose > 2 ) print_engine_status(env);
}
// abort the transaction, freeing up locks associated with previous put_multiples
if ( verbose > 1 ) printf("start txn abort\n");
r = txn->abort(txn); CKERR(r);
if ( verbose > 1 ) printf(" txn aborted\n");
sleep(2 + cs->client_number);
// now retry, waiting until the deadlock resolves itself
r = env->txn_begin(env, cs->txn, &txn, 0); CKERR(r);
if ( verbose > 1 ) printf("txn begin\n");
while ( rr != 0 ) {
rr = env->put_multiple(env,
cs->dbs[0],
txn,
&key,
&val,
NUM_DBS,
cs->dbs, // dest dbs
dest_keys,
dest_vals,
cs->flags,
NULL);
if ( rr != 0 ) {
if ( verbose ) printf("client[%u] : put_multiple returns %d, i=%u, n=%u, key=%u\n", cs->client_number, rr, i, n, k);
if ( verbose ) printf("start txn abort\n");
r = txn->abort(txn); CKERR(r);
if ( verbose ) printf(" txn aborted\n");
sleep(2 + cs->client_number);
r = env->txn_begin(env, cs->txn, &txn, 0); CKERR(r);
if ( verbose ) printf("txn begin\n");
}
}
*/
| gpl-2.0 |
jagnoha/website | libraries/jquery.intl-tel-input/examples/js/hiddenInput.js | 242 | $("#phone").intlTelInput({
utilsScript: "../../build/js/utils.js" // just for formatting/placeholders etc
});
// update the hidden input on submit
$("form").submit(function() {
$("#hidden").val($("#phone").intlTelInput("getNumber"));
}); | gpl-2.0 |
MikeThomsen/nifi | nifi-toolkit/nifi-toolkit-cli/src/test/java/org/apache/nifi/toolkit/cli/impl/command/CommandA.java | 2237 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.toolkit.cli.impl.command;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.nifi.toolkit.cli.api.Command;
import org.apache.nifi.toolkit.cli.api.CommandException;
import org.apache.nifi.toolkit.cli.api.Context;
import java.util.List;
public class CommandA implements Command<CommandAResult> {
private final List<String> results;
private CommandLine cli;
public CommandA(final List<String> results) {
this.results = results;
}
@Override
public void initialize(Context context) {
}
@Override
public String getName() {
return "command-a";
}
@Override
public String getDescription() {
return "command-a";
}
@Override
public Options getOptions() {
Options options = new Options();
options.addOption(CommandOption.BUCKET_ID.createOption());
options.addOption(CommandOption.FLOW_ID.createOption());
return options;
}
@Override
public void printUsage(String errorMessage) {
}
@Override
public CommandAResult execute(CommandLine cli) throws CommandException {
this.cli = cli;
return new CommandAResult(results);
}
@Override
public Class<CommandAResult> getResultImplType() {
return CommandAResult.class;
}
public CommandLine getCli() {
return this.cli;
}
}
| apache-2.0 |
liwangdong/UltimateAndroid | UltimateAndroidNormal/UltimateAndroidUi/src/com/marshalchen/common/uimodule/tileView/layouts/FixedLayout.java | 2211 | package com.marshalchen.common.uimodule.tileView.layouts;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
public class FixedLayout extends ViewGroup {
public FixedLayout(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
measureChildren(widthMeasureSpec, heightMeasureSpec);
int w = 0;
int h = 0;
int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
LayoutParams lp = (LayoutParams) child.getLayoutParams();
int right = lp.x + child.getMeasuredWidth();
int bottom = lp.y + child.getMeasuredHeight();
w = Math.max(w, right);
h = Math.max(h, bottom);
}
}
h = Math.max(h, getSuggestedMinimumHeight());
w = Math.max(w, getSuggestedMinimumWidth());
w = resolveSize(w, widthMeasureSpec);
h = resolveSize(h, heightMeasureSpec);
setMeasuredDimension(w, h);
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
LayoutParams lp = (LayoutParams) child.getLayoutParams();
child.layout(lp.x, lp.y, lp.x + child.getMeasuredWidth(), lp.y + child.getMeasuredHeight());
}
}
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams;
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}
public static class LayoutParams extends ViewGroup.LayoutParams {
public int x = 0;
public int y = 0;
public LayoutParams(int width, int height, int left, int top) {
super(width, height);
x = left;
y = top;
}
public LayoutParams(int width, int height){
super(width, height);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
}
}
| apache-2.0 |
pchico83/i2kit | cli/vendor/github.com/aws/aws-sdk-go/service/alexaforbusiness/errors.go | 1521 | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package alexaforbusiness
const (
// ErrCodeAlreadyExistsException for service response error code
// "AlreadyExistsException".
//
// The resource being created already exists. HTTP Status Code: 400
ErrCodeAlreadyExistsException = "AlreadyExistsException"
// ErrCodeInvalidUserStatusException for service response error code
// "InvalidUserStatusException".
//
// The attempt to update a user is invalid due to the user's current status.
// HTTP Status Code: 400
ErrCodeInvalidUserStatusException = "InvalidUserStatusException"
// ErrCodeLimitExceededException for service response error code
// "LimitExceededException".
//
// You are performing an action that would put you beyond your account's limits.
// HTTP Status Code: 400
ErrCodeLimitExceededException = "LimitExceededException"
// ErrCodeNameInUseException for service response error code
// "NameInUseException".
//
// The name sent in the request is already in use. HTTP Status Code: 400
ErrCodeNameInUseException = "NameInUseException"
// ErrCodeNotFoundException for service response error code
// "NotFoundException".
//
// The resource is not found. HTTP Status Code: 400
ErrCodeNotFoundException = "NotFoundException"
// ErrCodeResourceInUseException for service response error code
// "ResourceInUseException".
//
// The resource in the request is already in use. HTTP Status Code: 400
ErrCodeResourceInUseException = "ResourceInUseException"
)
| apache-2.0 |
sethpollack/kubernetes | vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs2/io.go | 2929 | // +build linux
package fs2
import (
"bufio"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/opencontainers/runc/libcontainer/cgroups"
"github.com/opencontainers/runc/libcontainer/cgroups/fscommon"
"github.com/opencontainers/runc/libcontainer/configs"
)
func setIo(dirPath string, cgroup *configs.Cgroup) error {
if cgroup.Resources.BlkioWeight != 0 {
filename := "io.bfq.weight"
if err := fscommon.WriteFile(dirPath, filename, strconv.FormatUint(uint64(cgroup.Resources.BlkioWeight), 10)); err != nil {
return err
}
}
for _, td := range cgroup.Resources.BlkioThrottleReadBpsDevice {
if err := fscommon.WriteFile(dirPath, "io.max", td.StringName("rbps")); err != nil {
return err
}
}
for _, td := range cgroup.Resources.BlkioThrottleWriteBpsDevice {
if err := fscommon.WriteFile(dirPath, "io.max", td.StringName("wbps")); err != nil {
return err
}
}
for _, td := range cgroup.Resources.BlkioThrottleReadIOPSDevice {
if err := fscommon.WriteFile(dirPath, "io.max", td.StringName("riops")); err != nil {
return err
}
}
for _, td := range cgroup.Resources.BlkioThrottleWriteIOPSDevice {
if err := fscommon.WriteFile(dirPath, "io.max", td.StringName("wiops")); err != nil {
return err
}
}
return nil
}
func readCgroup2MapFile(dirPath string, name string) (map[string][]string, error) {
ret := map[string][]string{}
p := filepath.Join(dirPath, name)
f, err := os.Open(p)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
parts := strings.Fields(line)
if len(parts) < 2 {
continue
}
ret[parts[0]] = parts[1:]
}
if err := scanner.Err(); err != nil {
return nil, err
}
return ret, nil
}
func statIo(dirPath string, stats *cgroups.Stats) error {
// more details on the io.stat file format: https://www.kernel.org/doc/Documentation/cgroup-v2.txt
var ioServiceBytesRecursive []cgroups.BlkioStatEntry
values, err := readCgroup2MapFile(dirPath, "io.stat")
if err != nil {
return err
}
for k, v := range values {
d := strings.Split(k, ":")
if len(d) != 2 {
continue
}
minor, err := strconv.ParseUint(d[0], 10, 0)
if err != nil {
return err
}
major, err := strconv.ParseUint(d[1], 10, 0)
if err != nil {
return err
}
for _, item := range v {
d := strings.Split(item, "=")
if len(d) != 2 {
continue
}
op := d[0]
// Accommodate the cgroup v1 naming
switch op {
case "rbytes":
op = "read"
case "wbytes":
op = "write"
}
value, err := strconv.ParseUint(d[1], 10, 0)
if err != nil {
return err
}
entry := cgroups.BlkioStatEntry{
Op: op,
Major: major,
Minor: minor,
Value: value,
}
ioServiceBytesRecursive = append(ioServiceBytesRecursive, entry)
}
}
stats.BlkioStats = cgroups.BlkioStats{IoServiceBytesRecursive: ioServiceBytesRecursive}
return nil
}
| apache-2.0 |
Plantain/sms-mailinglist | lib/google/apputils/setup_command.py | 5191 | #!/usr/bin/env python
# Copyright 2010 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.
"""Setuptools extension for running Google-style Python tests.
Google-style Python tests differ from normal Python tests in that each test
module is intended to be executed as an independent script. In particular, the
test fixture code in basetest.main() that executes module-wide setUp() and
tearDown() depends on __main__ being the module under test. This conflicts with
the usual setuptools test style, which uses a single TestSuite to run all of a
package's tests.
This package provides a new setuptools command, google_test, that runs all of
the google-style tests found in a specified directory.
NOTE: This works by overriding sys.modules['__main__'] with the module under
test, but still runs tests in the same process. Thus it will *not* work if your
tests depend on any of the following:
- Per-process (as opposed to per-module) initialization.
- Any entry point that is not basetest.main().
To use the google_test command in your project, do something like the following:
In setup.py:
setup(
name = "mypackage",
...
setup_requires = ["google-apputils>=0.2"],
google_test_dir = "tests",
)
Run:
$ python setup.py google_test
"""
from distutils import errors
import imp
import os
import re
import shlex
import sys
import traceback
from setuptools.command import test
def ValidateGoogleTestDir(unused_dist, unused_attr, value):
"""Validate that the test directory is a directory."""
if not os.path.isdir(value):
raise errors.DistutilsSetupError('%s is not a directory' % value)
class GoogleTest(test.test):
"""Command to run Google-style tests after in-place build."""
description = 'run Google-style tests after in-place build'
_DEFAULT_PATTERN = r'_(?:unit|reg)?test\.py$'
user_options = [
('test-dir=', 'd', 'Look for test modules in specified directory.'),
('test-module-pattern=', 'p',
('Pattern for matching test modules. Defaults to %r. '
'Only source files (*.py) will be considered, even if more files match '
'this pattern.' % _DEFAULT_PATTERN)),
('test-args=', 'a',
('Arguments to pass to basetest.main(). May only make sense if '
'test_module_pattern matches exactly one test.')),
]
def initialize_options(self):
self.test_dir = None
self.test_module_pattern = self._DEFAULT_PATTERN
self.test_args = ''
# Set to a dummy value, since we don't call the superclass methods for
# options parsing.
self.test_suite = True
def finalize_options(self):
if self.test_dir is None:
if self.distribution.google_test_dir:
self.test_dir = self.distribution.google_test_dir
else:
raise errors.DistutilsOptionError('No test directory specified')
self.test_module_pattern = re.compile(self.test_module_pattern)
self.test_args = shlex.split(self.test_args)
def _RunTestModule(self, module_path):
"""Run a module as a test module given its path.
Args:
module_path: The path to the module to test; must end in '.py'.
Returns:
True if the tests in this module pass, False if not or if an error occurs.
"""
path, filename = os.path.split(module_path)
old_argv = sys.argv[:]
old_path = sys.path[:]
old_modules = sys.modules.copy()
# Make relative imports in test modules work with our mangled sys.path.
sys.path.insert(0, path)
module_name = filename.replace('.py', '')
import_tuple = imp.find_module(module_name, [path])
module = imp.load_module(module_name, *import_tuple)
sys.modules['__main__'] = module
sys.argv = [module.__file__] + self.test_args
# Late import since this must be run with the project's sys.path.
import basetest
try:
try:
sys.stderr.write('Testing %s\n' % module_name)
basetest.main()
# basetest.main() should always call sys.exit, so this is very bad.
return False
except SystemExit, e:
returncode, = e.args
return not returncode
except:
traceback.print_exc()
return False
finally:
sys.argv[:] = old_argv
sys.path[:] = old_path
sys.modules.clear()
sys.modules.update(old_modules)
def run_tests(self):
ok = True
for path, _, filenames in os.walk(self.test_dir):
for filename in filenames:
if not filename.endswith('.py'):
continue
file_path = os.path.join(path, filename)
if self.test_module_pattern.search(file_path):
ok &= self._RunTestModule(file_path)
sys.exit(int(not ok))
| apache-2.0 |
maropu/spark | sql/catalyst/src/main/java/org/apache/spark/sql/connector/write/streaming/StreamingWrite.java | 4291 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.connector.write.streaming;
import org.apache.spark.annotation.Evolving;
import org.apache.spark.sql.connector.write.DataWriter;
import org.apache.spark.sql.connector.write.PhysicalWriteInfo;
import org.apache.spark.sql.connector.write.WriterCommitMessage;
/**
* An interface that defines how to write the data to data source in streaming queries.
*
* The writing procedure is:
* <ol>
* <li>Create a writer factory by {@link #createStreamingWriterFactory(PhysicalWriteInfo)},
* serialize and send it to all the partitions of the input data(RDD).</li>
* <li>For each epoch in each partition, create the data writer, and write the data of the
* epoch in the partition with this writer. If all the data are written successfully, call
* {@link DataWriter#commit()}. If exception happens during the writing, call
* {@link DataWriter#abort()}.</li>
* <li>If writers in all partitions of one epoch are successfully committed, call
* {@link #commit(long, WriterCommitMessage[])}. If some writers are aborted, or the job failed
* with an unknown reason, call {@link #abort(long, WriterCommitMessage[])}.</li>
* </ol>
* <p>
* While Spark will retry failed writing tasks, Spark won't retry failed writing jobs. Users should
* do it manually in their Spark applications if they want to retry.
* <p>
* Please refer to the documentation of commit/abort methods for detailed specifications.
*
* @since 3.0.0
*/
@Evolving
public interface StreamingWrite {
/**
* Creates a writer factory which will be serialized and sent to executors.
* <p>
* If this method fails (by throwing an exception), the action will fail and no Spark job will be
* submitted.
*
* @param info Information about the RDD that will be written to this data writer
*/
StreamingDataWriterFactory createStreamingWriterFactory(PhysicalWriteInfo info);
/**
* Commits this writing job for the specified epoch with a list of commit messages. The commit
* messages are collected from successful data writers and are produced by
* {@link DataWriter#commit()}.
* <p>
* If this method fails (by throwing an exception), this writing job is considered to have been
* failed, and the execution engine will attempt to call
* {@link #abort(long, WriterCommitMessage[])}.
* <p>
* The execution engine may call {@code commit} multiple times for the same epoch in some
* circumstances. To support exactly-once data semantics, implementations must ensure that
* multiple commits for the same epoch are idempotent.
*/
void commit(long epochId, WriterCommitMessage[] messages);
/**
* Aborts this writing job because some data writers are failed and keep failing when retried, or
* the Spark job fails with some unknown reasons, or {@link #commit(long, WriterCommitMessage[])}
* fails.
* <p>
* If this method fails (by throwing an exception), the underlying data source may require manual
* cleanup.
* <p>
* Unless the abort is triggered by the failure of commit, the given messages will have some
* null slots, as there may be only a few data writers that were committed before the abort
* happens, or some data writers were committed but their commit messages haven't reached the
* driver when the abort is triggered. So this is just a "best effort" for data sources to
* clean up the data left by data writers.
*/
void abort(long epochId, WriterCommitMessage[] messages);
}
| apache-2.0 |
tmckayus/oshinko-cli | vendor/github.com/openshift/origin/pkg/oc/bootstrap/docker/dockermachine/errors.go | 714 | package dockermachine
import (
"errors"
starterrors "github.com/openshift/origin/pkg/oc/bootstrap/docker/errors"
)
var (
// ErrDockerMachineExists is returned if a Docker machine you are trying to create already exists
ErrDockerMachineExists = errors.New("Docker machine exists")
// ErrDockerMachineNotAvailable is returned if the docker-machine command is not available in the PATH
ErrDockerMachineNotAvailable = errors.New("docker-machine not available")
)
// ErrDockerMachineExec is an error that occurred while executing the docker-machine command
func ErrDockerMachineExec(cmd string, cause error) error {
return starterrors.NewError("failed to execute docker-machine %s", cmd).WithCause(cause)
}
| apache-2.0 |
phpwutz/homebrew-cask | Casks/massreplaceit.rb | 279 | cask 'massreplaceit' do
version '2.9.1'
sha256 '1ab3482f7568953899474397fa401342daec56d4efe4a856de8e387294f7c667'
url 'http://www.hexmonkeysoftware.com/files/mri.dmg.zip'
name 'MassReplaceIt'
homepage 'http://www.hexmonkeysoftware.com/'
app 'MassReplaceIt.app'
end
| bsd-2-clause |
jrwesolo/homebrew-cask | Casks/cloudytabs.rb | 385 | cask :v1 => 'cloudytabs' do
version '1.4'
sha256 '7ba67b0f7415fe2d2cb545866eb0e9c7c2bea8980445921a9da5d2bf55711d76'
url "https://github.com/josh-/CloudyTabs/releases/download/v#{version}/CloudyTabs.zip"
appcast 'https://github.com/josh-/CloudyTabs/releases.atom'
name 'CloudyTabs'
homepage 'https://github.com/josh-/CloudyTabs/'
license :mit
app 'CloudyTabs.app'
end
| bsd-2-clause |
android-ia/platform_external_chromium_org | content/browser/renderer_host/render_message_filter.cc | 49233 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/render_message_filter.h"
#include <map>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/debug/alias.h"
#include "base/numerics/safe_math.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread.h"
#include "base/threading/worker_pool.h"
#include "content/browser/browser_main_loop.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
#include "content/browser/dom_storage/session_storage_namespace_impl.h"
#include "content/browser/download/download_stats.h"
#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "content/browser/media/media_internals.h"
#include "content/browser/plugin_process_host.h"
#include "content/browser/renderer_host/pepper/pepper_security_helper.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host_delegate.h"
#include "content/browser/renderer_host/render_widget_helper.h"
#include "content/browser/renderer_host/render_widget_resize_helper.h"
#include "content/browser/transition_request_manager.h"
#include "content/common/child_process_host_impl.h"
#include "content/common/child_process_messages.h"
#include "content/common/content_constants_internal.h"
#include "content/common/cookie_data.h"
#include "content/common/desktop_notification_messages.h"
#include "content/common/frame_messages.h"
#include "content/common/gpu/client/gpu_memory_buffer_impl.h"
#include "content/common/host_shared_bitmap_manager.h"
#include "content/common/media/media_param_traits.h"
#include "content/common/view_messages.h"
#include "content/public/browser/browser_child_process_host.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/download_save_info.h"
#include "content/public/browser/plugin_service_filter.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/context_menu_params.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/webplugininfo.h"
#include "ipc/ipc_channel_handle.h"
#include "ipc/ipc_platform_file.h"
#include "media/audio/audio_manager.h"
#include "media/audio/audio_manager_base.h"
#include "media/audio/audio_parameters.h"
#include "media/base/media_log_event.h"
#include "net/base/io_buffer.h"
#include "net/base/keygen_handler.h"
#include "net/base/mime_util.h"
#include "net/base/request_priority.h"
#include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_store.h"
#include "net/http/http_cache.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "ppapi/shared_impl/file_type_conversion.h"
#include "third_party/WebKit/public/web/WebNotificationPresenter.h"
#include "ui/gfx/color_profile.h"
#if defined(OS_MACOSX)
#include "content/common/mac/font_descriptor.h"
#else
#include "gpu/GLES2/gl2extchromium.h"
#include "third_party/khronos/GLES2/gl2.h"
#include "third_party/khronos/GLES2/gl2ext.h"
#endif
#if defined(OS_POSIX)
#include "base/file_descriptor_posix.h"
#endif
#if defined(OS_WIN)
#include "content/common/font_cache_dispatcher_win.h"
#include "content/common/sandbox_win.h"
#endif
#if defined(OS_ANDROID)
#include "content/browser/renderer_host/compositor_impl_android.h"
#include "content/common/gpu/client/gpu_memory_buffer_impl_surface_texture.h"
#include "media/base/android/webaudio_media_codec_bridge.h"
#endif
#if defined(ENABLE_PLUGINS)
#include "content/browser/plugin_service_impl.h"
#include "content/browser/ppapi_plugin_process_host.h"
#endif
using net::CookieStore;
namespace content {
namespace {
#if defined(ENABLE_PLUGINS)
const int kPluginsRefreshThresholdInSeconds = 3;
#endif
const uint32 kFilteredMessageClasses[] = {
ChildProcessMsgStart,
DesktopNotificationMsgStart,
FrameMsgStart,
ViewMsgStart,
};
#if defined(OS_WIN)
// On Windows, |g_color_profile| can run on an arbitrary background thread.
// We avoid races by using LazyInstance's constructor lock to initialize the
// object.
base::LazyInstance<gfx::ColorProfile>::Leaky g_color_profile =
LAZY_INSTANCE_INITIALIZER;
#endif
// Common functionality for converting a sync renderer message to a callback
// function in the browser. Derive from this, create it on the heap when
// issuing your callback. When done, write your reply parameters into
// reply_msg(), and then call SendReplyAndDeleteThis().
class RenderMessageCompletionCallback {
public:
RenderMessageCompletionCallback(RenderMessageFilter* filter,
IPC::Message* reply_msg)
: filter_(filter),
reply_msg_(reply_msg) {
}
virtual ~RenderMessageCompletionCallback() {
}
RenderMessageFilter* filter() { return filter_.get(); }
IPC::Message* reply_msg() { return reply_msg_; }
void SendReplyAndDeleteThis() {
filter_->Send(reply_msg_);
delete this;
}
private:
scoped_refptr<RenderMessageFilter> filter_;
IPC::Message* reply_msg_;
};
#if defined(ENABLE_PLUGINS)
class OpenChannelToPpapiPluginCallback
: public RenderMessageCompletionCallback,
public PpapiPluginProcessHost::PluginClient {
public:
OpenChannelToPpapiPluginCallback(RenderMessageFilter* filter,
ResourceContext* context,
IPC::Message* reply_msg)
: RenderMessageCompletionCallback(filter, reply_msg),
context_(context) {
}
virtual void GetPpapiChannelInfo(base::ProcessHandle* renderer_handle,
int* renderer_id) OVERRIDE {
*renderer_handle = filter()->PeerHandle();
*renderer_id = filter()->render_process_id();
}
virtual void OnPpapiChannelOpened(const IPC::ChannelHandle& channel_handle,
base::ProcessId plugin_pid,
int plugin_child_id) OVERRIDE {
ViewHostMsg_OpenChannelToPepperPlugin::WriteReplyParams(
reply_msg(), channel_handle, plugin_pid, plugin_child_id);
SendReplyAndDeleteThis();
}
virtual bool OffTheRecord() OVERRIDE {
return filter()->OffTheRecord();
}
virtual ResourceContext* GetResourceContext() OVERRIDE {
return context_;
}
private:
ResourceContext* context_;
};
class OpenChannelToPpapiBrokerCallback
: public PpapiPluginProcessHost::BrokerClient {
public:
OpenChannelToPpapiBrokerCallback(RenderMessageFilter* filter,
int routing_id)
: filter_(filter),
routing_id_(routing_id) {
}
virtual ~OpenChannelToPpapiBrokerCallback() {}
virtual void GetPpapiChannelInfo(base::ProcessHandle* renderer_handle,
int* renderer_id) OVERRIDE {
*renderer_handle = filter_->PeerHandle();
*renderer_id = filter_->render_process_id();
}
virtual void OnPpapiChannelOpened(const IPC::ChannelHandle& channel_handle,
base::ProcessId plugin_pid,
int /* plugin_child_id */) OVERRIDE {
filter_->Send(new ViewMsg_PpapiBrokerChannelCreated(routing_id_,
plugin_pid,
channel_handle));
delete this;
}
virtual bool OffTheRecord() OVERRIDE {
return filter_->OffTheRecord();
}
private:
scoped_refptr<RenderMessageFilter> filter_;
int routing_id_;
};
#endif // defined(ENABLE_PLUGINS)
} // namespace
class RenderMessageFilter::OpenChannelToNpapiPluginCallback
: public RenderMessageCompletionCallback,
public PluginProcessHost::Client {
public:
OpenChannelToNpapiPluginCallback(RenderMessageFilter* filter,
ResourceContext* context,
IPC::Message* reply_msg)
: RenderMessageCompletionCallback(filter, reply_msg),
context_(context),
host_(NULL),
sent_plugin_channel_request_(false) {
}
virtual int ID() OVERRIDE {
return filter()->render_process_id();
}
virtual ResourceContext* GetResourceContext() OVERRIDE {
return context_;
}
virtual bool OffTheRecord() OVERRIDE {
if (filter()->OffTheRecord())
return true;
if (GetContentClient()->browser()->AllowSaveLocalState(context_))
return false;
// For now, only disallow storing data for Flash <http://crbug.com/97319>.
for (size_t i = 0; i < info_.mime_types.size(); ++i) {
if (info_.mime_types[i].mime_type == kFlashPluginSwfMimeType)
return true;
}
return false;
}
virtual void SetPluginInfo(const WebPluginInfo& info) OVERRIDE {
info_ = info;
}
virtual void OnFoundPluginProcessHost(PluginProcessHost* host) OVERRIDE {
DCHECK(host);
host_ = host;
}
virtual void OnSentPluginChannelRequest() OVERRIDE {
sent_plugin_channel_request_ = true;
}
virtual void OnChannelOpened(const IPC::ChannelHandle& handle) OVERRIDE {
WriteReplyAndDeleteThis(handle);
}
virtual void OnError() OVERRIDE {
WriteReplyAndDeleteThis(IPC::ChannelHandle());
}
PluginProcessHost* host() const {
return host_;
}
bool sent_plugin_channel_request() const {
return sent_plugin_channel_request_;
}
void Cancel() {
delete this;
}
private:
void WriteReplyAndDeleteThis(const IPC::ChannelHandle& handle) {
FrameHostMsg_OpenChannelToPlugin::WriteReplyParams(reply_msg(),
handle, info_);
filter()->OnCompletedOpenChannelToNpapiPlugin(this);
SendReplyAndDeleteThis();
}
ResourceContext* context_;
WebPluginInfo info_;
PluginProcessHost* host_;
bool sent_plugin_channel_request_;
};
RenderMessageFilter::RenderMessageFilter(
int render_process_id,
PluginServiceImpl* plugin_service,
BrowserContext* browser_context,
net::URLRequestContextGetter* request_context,
RenderWidgetHelper* render_widget_helper,
media::AudioManager* audio_manager,
MediaInternals* media_internals,
DOMStorageContextWrapper* dom_storage_context)
: BrowserMessageFilter(
kFilteredMessageClasses, arraysize(kFilteredMessageClasses)),
resource_dispatcher_host_(ResourceDispatcherHostImpl::Get()),
plugin_service_(plugin_service),
profile_data_directory_(browser_context->GetPath()),
request_context_(request_context),
resource_context_(browser_context->GetResourceContext()),
render_widget_helper_(render_widget_helper),
incognito_(browser_context->IsOffTheRecord()),
dom_storage_context_(dom_storage_context),
render_process_id_(render_process_id),
audio_manager_(audio_manager),
media_internals_(media_internals) {
DCHECK(request_context_.get());
if (render_widget_helper)
render_widget_helper_->Init(render_process_id_, resource_dispatcher_host_);
}
RenderMessageFilter::~RenderMessageFilter() {
// This function should be called on the IO thread.
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(plugin_host_clients_.empty());
HostSharedBitmapManager::current()->ProcessRemoved(PeerHandle());
}
void RenderMessageFilter::OnChannelClosing() {
#if defined(ENABLE_PLUGINS)
for (std::set<OpenChannelToNpapiPluginCallback*>::iterator it =
plugin_host_clients_.begin(); it != plugin_host_clients_.end(); ++it) {
OpenChannelToNpapiPluginCallback* client = *it;
if (client->host()) {
if (client->sent_plugin_channel_request()) {
client->host()->CancelSentRequest(client);
} else {
client->host()->CancelPendingRequest(client);
}
} else {
plugin_service_->CancelOpenChannelToNpapiPlugin(client);
}
client->Cancel();
}
#endif // defined(ENABLE_PLUGINS)
plugin_host_clients_.clear();
#if defined(OS_ANDROID)
CompositorImpl::DestroyAllSurfaceTextures(render_process_id_);
#endif
}
bool RenderMessageFilter::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderMessageFilter, message)
#if defined(OS_WIN)
IPC_MESSAGE_HANDLER(ViewHostMsg_PreCacheFontCharacters,
OnPreCacheFontCharacters)
#endif
IPC_MESSAGE_HANDLER(ViewHostMsg_GetProcessMemorySizes,
OnGetProcessMemorySizes)
IPC_MESSAGE_HANDLER(ViewHostMsg_GenerateRoutingID, OnGenerateRoutingID)
IPC_MESSAGE_HANDLER(ViewHostMsg_CreateWindow, OnCreateWindow)
IPC_MESSAGE_HANDLER(ViewHostMsg_CreateWidget, OnCreateWidget)
IPC_MESSAGE_HANDLER(ViewHostMsg_CreateFullscreenWidget,
OnCreateFullscreenWidget)
IPC_MESSAGE_HANDLER(ViewHostMsg_SetCookie, OnSetCookie)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_GetCookies, OnGetCookies)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_GetRawCookies, OnGetRawCookies)
IPC_MESSAGE_HANDLER(ViewHostMsg_DeleteCookie, OnDeleteCookie)
IPC_MESSAGE_HANDLER(ViewHostMsg_CookiesEnabled, OnCookiesEnabled)
#if defined(OS_MACOSX)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_LoadFont, OnLoadFont)
#endif
IPC_MESSAGE_HANDLER(ViewHostMsg_DownloadUrl, OnDownloadUrl)
IPC_MESSAGE_HANDLER(ViewHostMsg_SaveImageFromDataURL,
OnSaveImageFromDataURL)
#if defined(ENABLE_PLUGINS)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_GetPlugins, OnGetPlugins)
IPC_MESSAGE_HANDLER(FrameHostMsg_GetPluginInfo, OnGetPluginInfo)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_OpenChannelToPlugin,
OnOpenChannelToPlugin)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_OpenChannelToPepperPlugin,
OnOpenChannelToPepperPlugin)
IPC_MESSAGE_HANDLER(ViewHostMsg_DidCreateOutOfProcessPepperInstance,
OnDidCreateOutOfProcessPepperInstance)
IPC_MESSAGE_HANDLER(ViewHostMsg_DidDeleteOutOfProcessPepperInstance,
OnDidDeleteOutOfProcessPepperInstance)
IPC_MESSAGE_HANDLER(ViewHostMsg_OpenChannelToPpapiBroker,
OnOpenChannelToPpapiBroker)
#endif
#if defined(OS_MACOSX)
IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame,
RenderWidgetResizeHelper::Get()->PostRendererProcessMsg(
render_process_id_, message))
IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_UpdateRect,
RenderWidgetResizeHelper::Get()->PostRendererProcessMsg(
render_process_id_, message))
#endif
IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_CheckPermission,
OnCheckNotificationPermission)
IPC_MESSAGE_HANDLER(ChildProcessHostMsg_SyncAllocateSharedMemory,
OnAllocateSharedMemory)
IPC_MESSAGE_HANDLER_DELAY_REPLY(
ChildProcessHostMsg_SyncAllocateSharedBitmap, OnAllocateSharedBitmap)
IPC_MESSAGE_HANDLER_DELAY_REPLY(
ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer,
OnAllocateGpuMemoryBuffer)
IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DeletedGpuMemoryBuffer,
OnDeletedGpuMemoryBuffer)
IPC_MESSAGE_HANDLER(ChildProcessHostMsg_AllocatedSharedBitmap,
OnAllocatedSharedBitmap)
IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DeletedSharedBitmap,
OnDeletedSharedBitmap)
#if defined(OS_POSIX) && !defined(OS_ANDROID)
IPC_MESSAGE_HANDLER(ViewHostMsg_AllocTransportDIB, OnAllocTransportDIB)
IPC_MESSAGE_HANDLER(ViewHostMsg_FreeTransportDIB, OnFreeTransportDIB)
#endif
IPC_MESSAGE_HANDLER(ViewHostMsg_DidGenerateCacheableMetadata,
OnCacheableMetadataAvailable)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_Keygen, OnKeygen)
IPC_MESSAGE_HANDLER(ViewHostMsg_GetAudioHardwareConfig,
OnGetAudioHardwareConfig)
#if defined(OS_WIN)
IPC_MESSAGE_HANDLER(ViewHostMsg_GetMonitorColorProfile,
OnGetMonitorColorProfile)
#endif
IPC_MESSAGE_HANDLER(ViewHostMsg_MediaLogEvents, OnMediaLogEvents)
IPC_MESSAGE_HANDLER(ViewHostMsg_Are3DAPIsBlocked, OnAre3DAPIsBlocked)
IPC_MESSAGE_HANDLER(ViewHostMsg_DidLose3DContext, OnDidLose3DContext)
#if defined(OS_ANDROID)
IPC_MESSAGE_HANDLER(ViewHostMsg_RunWebAudioMediaCodec, OnWebAudioMediaCodec)
#endif
IPC_MESSAGE_HANDLER(FrameHostMsg_AddNavigationTransitionData,
OnAddNavigationTransitionData)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void RenderMessageFilter::OnDestruct() const {
BrowserThread::DeleteOnIOThread::Destruct(this);
}
base::TaskRunner* RenderMessageFilter::OverrideTaskRunnerForMessage(
const IPC::Message& message) {
#if defined(OS_WIN)
// Windows monitor profile must be read from a file.
if (message.type() == ViewHostMsg_GetMonitorColorProfile::ID)
return BrowserThread::GetBlockingPool();
#endif
// Always query audio device parameters on the audio thread.
if (message.type() == ViewHostMsg_GetAudioHardwareConfig::ID)
return audio_manager_->GetTaskRunner().get();
return NULL;
}
bool RenderMessageFilter::OffTheRecord() const {
return incognito_;
}
void RenderMessageFilter::OnCreateWindow(
const ViewHostMsg_CreateWindow_Params& params,
int* route_id,
int* main_frame_route_id,
int* surface_id,
int64* cloned_session_storage_namespace_id) {
bool no_javascript_access;
// Merge the additional features into the WebWindowFeatures struct before we
// pass it on.
blink::WebVector<blink::WebString> additional_features(
params.additional_features.size());
for (size_t i = 0; i < params.additional_features.size(); ++i)
additional_features[i] = blink::WebString(params.additional_features[i]);
blink::WebWindowFeatures features = params.features;
features.additionalFeatures.swap(additional_features);
bool can_create_window =
GetContentClient()->browser()->CanCreateWindow(
params.opener_url,
params.opener_top_level_frame_url,
params.opener_security_origin,
params.window_container_type,
params.target_url,
params.referrer,
params.disposition,
features,
params.user_gesture,
params.opener_suppressed,
resource_context_,
render_process_id_,
params.opener_id,
&no_javascript_access);
if (!can_create_window) {
*route_id = MSG_ROUTING_NONE;
*main_frame_route_id = MSG_ROUTING_NONE;
*surface_id = 0;
*cloned_session_storage_namespace_id = 0;
return;
}
// This will clone the sessionStorage for namespace_id_to_clone.
scoped_refptr<SessionStorageNamespaceImpl> cloned_namespace =
new SessionStorageNamespaceImpl(dom_storage_context_.get(),
params.session_storage_namespace_id);
*cloned_session_storage_namespace_id = cloned_namespace->id();
render_widget_helper_->CreateNewWindow(params,
no_javascript_access,
PeerHandle(),
route_id,
main_frame_route_id,
surface_id,
cloned_namespace.get());
}
void RenderMessageFilter::OnCreateWidget(int opener_id,
blink::WebPopupType popup_type,
int* route_id,
int* surface_id) {
render_widget_helper_->CreateNewWidget(
opener_id, popup_type, route_id, surface_id);
}
void RenderMessageFilter::OnCreateFullscreenWidget(int opener_id,
int* route_id,
int* surface_id) {
render_widget_helper_->CreateNewFullscreenWidget(
opener_id, route_id, surface_id);
}
void RenderMessageFilter::OnGetProcessMemorySizes(size_t* private_bytes,
size_t* shared_bytes) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
using base::ProcessMetrics;
#if !defined(OS_MACOSX) || defined(OS_IOS)
scoped_ptr<ProcessMetrics> metrics(ProcessMetrics::CreateProcessMetrics(
PeerHandle()));
#else
scoped_ptr<ProcessMetrics> metrics(ProcessMetrics::CreateProcessMetrics(
PeerHandle(), BrowserChildProcessHost::GetPortProvider()));
#endif
if (!metrics->GetMemoryBytes(private_bytes, shared_bytes)) {
*private_bytes = 0;
*shared_bytes = 0;
}
}
void RenderMessageFilter::OnSetCookie(int render_frame_id,
const GURL& url,
const GURL& first_party_for_cookies,
const std::string& cookie) {
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
if (!policy->CanAccessCookiesForOrigin(render_process_id_, url))
return;
net::CookieOptions options;
if (GetContentClient()->browser()->AllowSetCookie(
url, first_party_for_cookies, cookie, resource_context_,
render_process_id_, render_frame_id, &options)) {
net::CookieStore* cookie_store = GetCookieStoreForURL(url);
// Pass a null callback since we don't care about when the 'set' completes.
cookie_store->SetCookieWithOptionsAsync(
url, cookie, options, net::CookieStore::SetCookiesCallback());
}
}
void RenderMessageFilter::OnGetCookies(int render_frame_id,
const GURL& url,
const GURL& first_party_for_cookies,
IPC::Message* reply_msg) {
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
if (!policy->CanAccessCookiesForOrigin(render_process_id_, url)) {
SendGetCookiesResponse(reply_msg, std::string());
return;
}
// If we crash here, figure out what URL the renderer was requesting.
// http://crbug.com/99242
char url_buf[128];
base::strlcpy(url_buf, url.spec().c_str(), arraysize(url_buf));
base::debug::Alias(url_buf);
net::CookieStore* cookie_store = GetCookieStoreForURL(url);
cookie_store->GetAllCookiesForURLAsync(
url, base::Bind(&RenderMessageFilter::CheckPolicyForCookies, this,
render_frame_id, url, first_party_for_cookies,
reply_msg));
}
void RenderMessageFilter::OnGetRawCookies(
const GURL& url,
const GURL& first_party_for_cookies,
IPC::Message* reply_msg) {
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
// Only return raw cookies to trusted renderers or if this request is
// not targeted to an an external host like ChromeFrame.
// TODO(ananta) We need to support retreiving raw cookies from external
// hosts.
if (!policy->CanReadRawCookies(render_process_id_) ||
!policy->CanAccessCookiesForOrigin(render_process_id_, url)) {
SendGetRawCookiesResponse(reply_msg, net::CookieList());
return;
}
// We check policy here to avoid sending back cookies that would not normally
// be applied to outbound requests for the given URL. Since this cookie info
// is visible in the developer tools, it is helpful to make it match reality.
net::CookieStore* cookie_store = GetCookieStoreForURL(url);
cookie_store->GetAllCookiesForURLAsync(
url, base::Bind(&RenderMessageFilter::SendGetRawCookiesResponse,
this, reply_msg));
}
void RenderMessageFilter::OnDeleteCookie(const GURL& url,
const std::string& cookie_name) {
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
if (!policy->CanAccessCookiesForOrigin(render_process_id_, url))
return;
net::CookieStore* cookie_store = GetCookieStoreForURL(url);
cookie_store->DeleteCookieAsync(url, cookie_name, base::Closure());
}
void RenderMessageFilter::OnCookiesEnabled(
int render_frame_id,
const GURL& url,
const GURL& first_party_for_cookies,
bool* cookies_enabled) {
// TODO(ananta): If this render view is associated with an automation channel,
// aka ChromeFrame then we need to retrieve cookie settings from the external
// host.
*cookies_enabled = GetContentClient()->browser()->AllowGetCookie(
url, first_party_for_cookies, net::CookieList(), resource_context_,
render_process_id_, render_frame_id);
}
#if defined(OS_MACOSX)
void RenderMessageFilter::OnLoadFont(const FontDescriptor& font,
IPC::Message* reply_msg) {
FontLoader::Result* result = new FontLoader::Result;
BrowserThread::PostTaskAndReply(
BrowserThread::FILE, FROM_HERE,
base::Bind(&FontLoader::LoadFont, font, result),
base::Bind(&RenderMessageFilter::SendLoadFontReply, this, reply_msg,
base::Owned(result)));
}
void RenderMessageFilter::SendLoadFontReply(IPC::Message* reply,
FontLoader::Result* result) {
base::SharedMemoryHandle handle;
if (result->font_data_size == 0 || result->font_id == 0) {
result->font_data_size = 0;
result->font_id = 0;
handle = base::SharedMemory::NULLHandle();
} else {
result->font_data.GiveToProcess(base::GetCurrentProcessHandle(), &handle);
}
ViewHostMsg_LoadFont::WriteReplyParams(
reply, result->font_data_size, handle, result->font_id);
Send(reply);
}
#endif // OS_MACOSX
#if defined(ENABLE_PLUGINS)
void RenderMessageFilter::OnGetPlugins(
bool refresh,
IPC::Message* reply_msg) {
// Don't refresh if the specified threshold has not been passed. Note that
// this check is performed before off-loading to the file thread. The reason
// we do this is that some pages tend to request that the list of plugins be
// refreshed at an excessive rate. This instigates disk scanning, as the list
// is accumulated by doing multiple reads from disk. This effect is
// multiplied when we have several pages requesting this operation.
if (refresh) {
const base::TimeDelta threshold = base::TimeDelta::FromSeconds(
kPluginsRefreshThresholdInSeconds);
const base::TimeTicks now = base::TimeTicks::Now();
if (now - last_plugin_refresh_time_ >= threshold) {
// Only refresh if the threshold hasn't been exceeded yet.
PluginServiceImpl::GetInstance()->RefreshPlugins();
last_plugin_refresh_time_ = now;
}
}
PluginServiceImpl::GetInstance()->GetPlugins(
base::Bind(&RenderMessageFilter::GetPluginsCallback, this, reply_msg));
}
void RenderMessageFilter::GetPluginsCallback(
IPC::Message* reply_msg,
const std::vector<WebPluginInfo>& all_plugins) {
// Filter the plugin list.
PluginServiceFilter* filter = PluginServiceImpl::GetInstance()->GetFilter();
std::vector<WebPluginInfo> plugins;
int child_process_id = -1;
int routing_id = MSG_ROUTING_NONE;
for (size_t i = 0; i < all_plugins.size(); ++i) {
// Copy because the filter can mutate.
WebPluginInfo plugin(all_plugins[i]);
if (!filter || filter->IsPluginAvailable(child_process_id,
routing_id,
resource_context_,
GURL(),
GURL(),
&plugin)) {
plugins.push_back(plugin);
}
}
ViewHostMsg_GetPlugins::WriteReplyParams(reply_msg, plugins);
Send(reply_msg);
}
void RenderMessageFilter::OnGetPluginInfo(
int render_frame_id,
const GURL& url,
const GURL& page_url,
const std::string& mime_type,
bool* found,
WebPluginInfo* info,
std::string* actual_mime_type) {
bool allow_wildcard = true;
*found = plugin_service_->GetPluginInfo(
render_process_id_, render_frame_id, resource_context_,
url, page_url, mime_type, allow_wildcard,
NULL, info, actual_mime_type);
}
void RenderMessageFilter::OnOpenChannelToPlugin(int render_frame_id,
const GURL& url,
const GURL& policy_url,
const std::string& mime_type,
IPC::Message* reply_msg) {
OpenChannelToNpapiPluginCallback* client =
new OpenChannelToNpapiPluginCallback(this, resource_context_, reply_msg);
DCHECK(!ContainsKey(plugin_host_clients_, client));
plugin_host_clients_.insert(client);
plugin_service_->OpenChannelToNpapiPlugin(
render_process_id_, render_frame_id,
url, policy_url, mime_type, client);
}
void RenderMessageFilter::OnOpenChannelToPepperPlugin(
const base::FilePath& path,
IPC::Message* reply_msg) {
plugin_service_->OpenChannelToPpapiPlugin(
render_process_id_,
path,
profile_data_directory_,
new OpenChannelToPpapiPluginCallback(this, resource_context_, reply_msg));
}
void RenderMessageFilter::OnDidCreateOutOfProcessPepperInstance(
int plugin_child_id,
int32 pp_instance,
PepperRendererInstanceData instance_data,
bool is_external) {
// It's important that we supply the render process ID ourselves based on the
// channel the message arrived on. We use the
// PP_Instance -> (process id, view id)
// mapping to decide how to handle messages received from the (untrusted)
// plugin, so an exploited renderer must not be able to insert fake mappings
// that may allow it access to other render processes.
DCHECK_EQ(0, instance_data.render_process_id);
instance_data.render_process_id = render_process_id_;
if (is_external) {
// We provide the BrowserPpapiHost to the embedder, so it's safe to cast.
BrowserPpapiHostImpl* host = static_cast<BrowserPpapiHostImpl*>(
GetContentClient()->browser()->GetExternalBrowserPpapiHost(
plugin_child_id));
if (host)
host->AddInstance(pp_instance, instance_data);
} else {
PpapiPluginProcessHost::DidCreateOutOfProcessInstance(
plugin_child_id, pp_instance, instance_data);
}
}
void RenderMessageFilter::OnDidDeleteOutOfProcessPepperInstance(
int plugin_child_id,
int32 pp_instance,
bool is_external) {
if (is_external) {
// We provide the BrowserPpapiHost to the embedder, so it's safe to cast.
BrowserPpapiHostImpl* host = static_cast<BrowserPpapiHostImpl*>(
GetContentClient()->browser()->GetExternalBrowserPpapiHost(
plugin_child_id));
if (host)
host->DeleteInstance(pp_instance);
} else {
PpapiPluginProcessHost::DidDeleteOutOfProcessInstance(
plugin_child_id, pp_instance);
}
}
void RenderMessageFilter::OnOpenChannelToPpapiBroker(
int routing_id,
const base::FilePath& path) {
plugin_service_->OpenChannelToPpapiBroker(
render_process_id_,
path,
new OpenChannelToPpapiBrokerCallback(this, routing_id));
}
#endif // defined(ENABLE_PLUGINS)
void RenderMessageFilter::OnGenerateRoutingID(int* route_id) {
*route_id = render_widget_helper_->GetNextRoutingID();
}
void RenderMessageFilter::OnGetAudioHardwareConfig(
media::AudioParameters* input_params,
media::AudioParameters* output_params) {
DCHECK(input_params);
DCHECK(output_params);
*output_params = audio_manager_->GetDefaultOutputStreamParameters();
// TODO(henrika): add support for all available input devices.
*input_params = audio_manager_->GetInputStreamParameters(
media::AudioManagerBase::kDefaultDeviceId);
}
#if defined(OS_WIN)
void RenderMessageFilter::OnGetMonitorColorProfile(std::vector<char>* profile) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
*profile = g_color_profile.Get().profile();
}
#endif
void RenderMessageFilter::DownloadUrl(int render_view_id,
const GURL& url,
const Referrer& referrer,
const base::string16& suggested_name,
const bool use_prompt) const {
scoped_ptr<DownloadSaveInfo> save_info(new DownloadSaveInfo());
save_info->suggested_name = suggested_name;
save_info->prompt_for_save_location = use_prompt;
// There may be a special cookie store that we could use for this download,
// rather than the default one. Since this feature is generally only used for
// proper render views, and not downloads, we do not need to retrieve the
// special cookie store here, but just initialize the request to use the
// default cookie store.
// TODO(tburkard): retrieve the appropriate special cookie store, if this
// is ever to be used for downloads as well.
scoped_ptr<net::URLRequest> request(
resource_context_->GetRequestContext()->CreateRequest(
url, net::DEFAULT_PRIORITY, NULL, NULL));
RecordDownloadSource(INITIATED_BY_RENDERER);
resource_dispatcher_host_->BeginDownload(
request.Pass(),
referrer,
true, // is_content_initiated
resource_context_,
render_process_id_,
render_view_id,
false,
save_info.Pass(),
DownloadItem::kInvalidId,
ResourceDispatcherHostImpl::DownloadStartedCallback());
}
void RenderMessageFilter::OnDownloadUrl(int render_view_id,
const GURL& url,
const Referrer& referrer,
const base::string16& suggested_name) {
DownloadUrl(render_view_id, url, referrer, suggested_name, false);
}
void RenderMessageFilter::OnSaveImageFromDataURL(int render_view_id,
const std::string& url_str) {
// Please refer to RenderViewImpl::saveImageFromDataURL().
if (url_str.length() >= kMaxLengthOfDataURLString)
return;
GURL data_url(url_str);
if (!data_url.SchemeIs(url::kDataScheme))
return;
DownloadUrl(render_view_id, data_url, Referrer(), base::string16(), true);
}
void RenderMessageFilter::OnCheckNotificationPermission(
const GURL& source_origin, int* result) {
#if defined(ENABLE_NOTIFICATIONS)
*result = GetContentClient()->browser()->
CheckDesktopNotificationPermission(source_origin, resource_context_,
render_process_id_);
#else
*result = blink::WebNotificationPresenter::PermissionAllowed;
#endif
}
void RenderMessageFilter::OnAllocateSharedMemory(
uint32 buffer_size,
base::SharedMemoryHandle* handle) {
ChildProcessHostImpl::AllocateSharedMemory(
buffer_size, PeerHandle(), handle);
}
void RenderMessageFilter::AllocateSharedBitmapOnFileThread(
uint32 buffer_size,
const cc::SharedBitmapId& id,
IPC::Message* reply_msg) {
base::SharedMemoryHandle handle;
HostSharedBitmapManager::current()->AllocateSharedBitmapForChild(
PeerHandle(), buffer_size, id, &handle);
ChildProcessHostMsg_SyncAllocateSharedBitmap::WriteReplyParams(reply_msg,
handle);
Send(reply_msg);
}
void RenderMessageFilter::OnAllocateSharedBitmap(uint32 buffer_size,
const cc::SharedBitmapId& id,
IPC::Message* reply_msg) {
BrowserThread::PostTask(
BrowserThread::FILE_USER_BLOCKING,
FROM_HERE,
base::Bind(&RenderMessageFilter::AllocateSharedBitmapOnFileThread,
this,
buffer_size,
id,
reply_msg));
}
void RenderMessageFilter::OnAllocatedSharedBitmap(
size_t buffer_size,
const base::SharedMemoryHandle& handle,
const cc::SharedBitmapId& id) {
HostSharedBitmapManager::current()->ChildAllocatedSharedBitmap(
buffer_size, handle, PeerHandle(), id);
}
void RenderMessageFilter::OnDeletedSharedBitmap(const cc::SharedBitmapId& id) {
HostSharedBitmapManager::current()->ChildDeletedSharedBitmap(id);
}
net::CookieStore* RenderMessageFilter::GetCookieStoreForURL(
const GURL& url) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
net::URLRequestContext* context =
GetContentClient()->browser()->OverrideRequestContextForURL(
url, resource_context_);
// If we should use a special URLRequestContext rather than the default one,
// return the cookie store of that special URLRequestContext.
if (context)
return context->cookie_store();
// Otherwise, if there is a special cookie store to be used for this process,
// return that cookie store.
net::CookieStore* cookie_store =
GetContentClient()->browser()->OverrideCookieStoreForRenderProcess(
render_process_id_);
if (cookie_store)
return cookie_store;
// Otherwise, return the cookie store of the default request context used
// for this renderer.
return request_context_->GetURLRequestContext()->cookie_store();
}
#if defined(OS_POSIX) && !defined(OS_ANDROID)
void RenderMessageFilter::OnAllocTransportDIB(
uint32 size, bool cache_in_browser, TransportDIB::Handle* handle) {
render_widget_helper_->AllocTransportDIB(size, cache_in_browser, handle);
}
void RenderMessageFilter::OnFreeTransportDIB(
TransportDIB::Id dib_id) {
render_widget_helper_->FreeTransportDIB(dib_id);
}
#endif
void RenderMessageFilter::OnCacheableMetadataAvailable(
const GURL& url,
double expected_response_time,
const std::vector<char>& data) {
net::HttpCache* cache = request_context_->GetURLRequestContext()->
http_transaction_factory()->GetCache();
DCHECK(cache);
// Use the same priority for the metadata write as for script
// resources (see defaultPriorityForResourceType() in WebKit's
// CachedResource.cpp). Note that WebURLRequest::PriorityMedium
// corresponds to net::LOW (see ConvertWebKitPriorityToNetPriority()
// in weburlloader_impl.cc).
const net::RequestPriority kPriority = net::LOW;
scoped_refptr<net::IOBuffer> buf(new net::IOBuffer(data.size()));
memcpy(buf->data(), &data.front(), data.size());
cache->WriteMetadata(url,
kPriority,
base::Time::FromDoubleT(expected_response_time),
buf.get(),
data.size());
}
void RenderMessageFilter::OnKeygen(uint32 key_size_index,
const std::string& challenge_string,
const GURL& url,
IPC::Message* reply_msg) {
// Map displayed strings indicating level of keysecurity in the <keygen>
// menu to the key size in bits. (See SSLKeyGeneratorChromium.cpp in WebCore.)
int key_size_in_bits;
switch (key_size_index) {
case 0:
key_size_in_bits = 2048;
break;
case 1:
key_size_in_bits = 1024;
break;
default:
DCHECK(false) << "Illegal key_size_index " << key_size_index;
ViewHostMsg_Keygen::WriteReplyParams(reply_msg, std::string());
Send(reply_msg);
return;
}
resource_context_->CreateKeygenHandler(
key_size_in_bits,
challenge_string,
url,
base::Bind(
&RenderMessageFilter::PostKeygenToWorkerThread, this, reply_msg));
}
void RenderMessageFilter::PostKeygenToWorkerThread(
IPC::Message* reply_msg,
scoped_ptr<net::KeygenHandler> keygen_handler) {
VLOG(1) << "Dispatching keygen task to worker pool.";
// Dispatch to worker pool, so we do not block the IO thread.
if (!base::WorkerPool::PostTask(
FROM_HERE,
base::Bind(&RenderMessageFilter::OnKeygenOnWorkerThread,
this,
base::Passed(&keygen_handler),
reply_msg),
true)) {
NOTREACHED() << "Failed to dispatch keygen task to worker pool";
ViewHostMsg_Keygen::WriteReplyParams(reply_msg, std::string());
Send(reply_msg);
}
}
void RenderMessageFilter::OnKeygenOnWorkerThread(
scoped_ptr<net::KeygenHandler> keygen_handler,
IPC::Message* reply_msg) {
DCHECK(reply_msg);
// Generate a signed public key and challenge, then send it back.
ViewHostMsg_Keygen::WriteReplyParams(
reply_msg,
keygen_handler->GenKeyAndSignChallenge());
Send(reply_msg);
}
void RenderMessageFilter::OnMediaLogEvents(
const std::vector<media::MediaLogEvent>& events) {
if (media_internals_)
media_internals_->OnMediaEvents(render_process_id_, events);
}
void RenderMessageFilter::CheckPolicyForCookies(
int render_frame_id,
const GURL& url,
const GURL& first_party_for_cookies,
IPC::Message* reply_msg,
const net::CookieList& cookie_list) {
net::CookieStore* cookie_store = GetCookieStoreForURL(url);
// Check the policy for get cookies, and pass cookie_list to the
// TabSpecificContentSetting for logging purpose.
if (GetContentClient()->browser()->AllowGetCookie(
url, first_party_for_cookies, cookie_list, resource_context_,
render_process_id_, render_frame_id)) {
// Gets the cookies from cookie store if allowed.
cookie_store->GetCookiesWithOptionsAsync(
url, net::CookieOptions(),
base::Bind(&RenderMessageFilter::SendGetCookiesResponse,
this, reply_msg));
} else {
SendGetCookiesResponse(reply_msg, std::string());
}
}
void RenderMessageFilter::SendGetCookiesResponse(IPC::Message* reply_msg,
const std::string& cookies) {
ViewHostMsg_GetCookies::WriteReplyParams(reply_msg, cookies);
Send(reply_msg);
}
void RenderMessageFilter::SendGetRawCookiesResponse(
IPC::Message* reply_msg,
const net::CookieList& cookie_list) {
std::vector<CookieData> cookies;
for (size_t i = 0; i < cookie_list.size(); ++i)
cookies.push_back(CookieData(cookie_list[i]));
ViewHostMsg_GetRawCookies::WriteReplyParams(reply_msg, cookies);
Send(reply_msg);
}
void RenderMessageFilter::OnCompletedOpenChannelToNpapiPlugin(
OpenChannelToNpapiPluginCallback* client) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(ContainsKey(plugin_host_clients_, client));
plugin_host_clients_.erase(client);
}
void RenderMessageFilter::OnAre3DAPIsBlocked(int render_view_id,
const GURL& top_origin_url,
ThreeDAPIType requester,
bool* blocked) {
*blocked = GpuDataManagerImpl::GetInstance()->Are3DAPIsBlocked(
top_origin_url, render_process_id_, render_view_id, requester);
}
void RenderMessageFilter::OnDidLose3DContext(
const GURL& top_origin_url,
ThreeDAPIType /* unused */,
int arb_robustness_status_code) {
#if defined(OS_MACOSX)
// TODO(kbr): this file indirectly includes npapi.h, which on Mac
// OS pulls in the system OpenGL headers. For some
// not-yet-investigated reason this breaks the build with the 10.6
// SDK but not 10.7. For now work around this in a way compatible
// with the Khronos headers.
#ifndef GL_GUILTY_CONTEXT_RESET_ARB
#define GL_GUILTY_CONTEXT_RESET_ARB 0x8253
#endif
#ifndef GL_INNOCENT_CONTEXT_RESET_ARB
#define GL_INNOCENT_CONTEXT_RESET_ARB 0x8254
#endif
#ifndef GL_UNKNOWN_CONTEXT_RESET_ARB
#define GL_UNKNOWN_CONTEXT_RESET_ARB 0x8255
#endif
#endif
GpuDataManagerImpl::DomainGuilt guilt;
switch (arb_robustness_status_code) {
case GL_GUILTY_CONTEXT_RESET_ARB:
guilt = GpuDataManagerImpl::DOMAIN_GUILT_KNOWN;
break;
case GL_UNKNOWN_CONTEXT_RESET_ARB:
guilt = GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN;
break;
default:
// Ignore lost contexts known to be innocent.
return;
}
GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(
top_origin_url, guilt);
}
#if defined(OS_WIN)
void RenderMessageFilter::OnPreCacheFontCharacters(const LOGFONT& font,
const base::string16& str) {
// TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
// GDI fonts (http://crbug.com/383227), even when using DirectWrite.
// Eventually this shouldn't be added and should be moved to
// FontCacheDispatcher too. http://crbug.com/356346.
// First, comments from FontCacheDispatcher::OnPreCacheFont do apply here too.
// Except that for True Type fonts,
// GetTextMetrics will not load the font in memory.
// The only way windows seem to load properly, it is to create a similar
// device (like the one in which we print), then do an ExtTextOut,
// as we do in the printing thread, which is sandboxed.
HDC hdc = CreateEnhMetaFile(NULL, NULL, NULL, NULL);
HFONT font_handle = CreateFontIndirect(&font);
DCHECK(NULL != font_handle);
HGDIOBJ old_font = SelectObject(hdc, font_handle);
DCHECK(NULL != old_font);
ExtTextOut(hdc, 0, 0, ETO_GLYPH_INDEX, 0, str.c_str(), str.length(), NULL);
SelectObject(hdc, old_font);
DeleteObject(font_handle);
HENHMETAFILE metafile = CloseEnhMetaFile(hdc);
if (metafile) {
DeleteEnhMetaFile(metafile);
}
}
#endif
#if defined(OS_ANDROID)
void RenderMessageFilter::OnWebAudioMediaCodec(
base::SharedMemoryHandle encoded_data_handle,
base::FileDescriptor pcm_output,
uint32_t data_size) {
// Let a WorkerPool handle this request since the WebAudio
// MediaCodec bridge is slow and can block while sending the data to
// the renderer.
base::WorkerPool::PostTask(
FROM_HERE,
base::Bind(&media::WebAudioMediaCodecBridge::RunWebAudioMediaCodec,
encoded_data_handle, pcm_output, data_size),
true);
}
#endif
void RenderMessageFilter::OnAddNavigationTransitionData(
int render_frame_id,
const std::string& allowed_destination_host_pattern,
const std::string& selector,
const std::string& markup) {
TransitionRequestManager::GetInstance()->AddPendingTransitionRequestData(
render_process_id_, render_frame_id, allowed_destination_host_pattern,
selector, markup);
}
void RenderMessageFilter::OnAllocateGpuMemoryBuffer(uint32 width,
uint32 height,
uint32 internalformat,
uint32 usage,
IPC::Message* reply) {
if (!GpuMemoryBufferImpl::IsFormatValid(internalformat) ||
!GpuMemoryBufferImpl::IsUsageValid(usage)) {
GpuMemoryBufferAllocated(reply, gfx::GpuMemoryBufferHandle());
return;
}
base::CheckedNumeric<int> size = width;
size *= height;
if (!size.IsValid()) {
GpuMemoryBufferAllocated(reply, gfx::GpuMemoryBufferHandle());
return;
}
#if defined(OS_ANDROID)
// TODO(reveman): This should be moved to
// GpuMemoryBufferImpl::AllocateForChildProcess and
// GpuMemoryBufferImplSurfaceTexture when adding support for out-of-process
// GPU service. crbug.com/368716
if (GpuMemoryBufferImplSurfaceTexture::IsConfigurationSupported(
internalformat, usage)) {
// Each surface texture is associated with a render process id. This allows
// the GPU service and Java Binder IPC to verify that a renderer is not
// trying to use a surface texture it doesn't own.
int surface_texture_id =
CompositorImpl::CreateSurfaceTexture(render_process_id_);
if (surface_texture_id != -1) {
gfx::GpuMemoryBufferHandle handle;
handle.type = gfx::SURFACE_TEXTURE_BUFFER;
handle.surface_texture_id =
gfx::SurfaceTextureId(surface_texture_id, render_process_id_);
GpuMemoryBufferAllocated(reply, handle);
return;
}
}
#endif
GpuMemoryBufferImpl::AllocateForChildProcess(
gfx::Size(width, height),
internalformat,
usage,
PeerHandle(),
render_process_id_,
base::Bind(&RenderMessageFilter::GpuMemoryBufferAllocated, this, reply));
}
void RenderMessageFilter::GpuMemoryBufferAllocated(
IPC::Message* reply,
const gfx::GpuMemoryBufferHandle& handle) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer::WriteReplyParams(reply,
handle);
Send(reply);
}
void RenderMessageFilter::OnDeletedGpuMemoryBuffer(
gfx::GpuMemoryBufferType type,
const gfx::GpuMemoryBufferId& id) {
GpuMemoryBufferImpl::DeletedByChildProcess(type, id, PeerHandle());
}
} // namespace content
| bsd-3-clause |
joone/chromium-crosswalk | ui/webui/resources/js/parse_html_subset.js | 3331 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* Parse a very small subset of HTML. This ensures that insecure HTML /
* javascript cannot be injected into the new tab page.
* @param {string} s The string to parse.
* @param {Array<string>=} opt_extraTags Optional extra allowed tags.
* @param {Object<function(Node, string):boolean>=} opt_extraAttrs
* Optional extra allowed attributes (all tags are run through these).
* @throws {Error} In case of non supported markup.
* @return {DocumentFragment} A document fragment containing the DOM tree.
*/
var parseHtmlSubset = (function() {
'use strict';
var allowedAttributes = {
'href': function(node, value) {
// Only allow a[href] starting with chrome:// and https://
return node.tagName == 'A' && (value.indexOf('chrome://') == 0 ||
value.indexOf('https://') == 0);
},
'target': function(node, value) {
// Allow a[target] but reset the value to "".
if (node.tagName != 'A')
return false;
node.setAttribute('target', '');
return true;
}
};
/**
* Whitelist of tag names allowed in parseHtmlSubset.
* @type {!Array<string>}
* @const
*/
var allowedTags = ['A', 'B', 'STRONG'];
/** @param {...Object} var_args Objects to merge. */
function merge(var_args) {
var clone = {};
for (var i = 0; i < arguments.length; ++i) {
if (typeof arguments[i] == 'object') {
for (var key in arguments[i]) {
if (arguments[i].hasOwnProperty(key))
clone[key] = arguments[i][key];
}
}
}
return clone;
}
function walk(n, f) {
f(n);
for (var i = 0; i < n.childNodes.length; i++) {
walk(n.childNodes[i], f);
}
}
function assertElement(tags, node) {
if (tags.indexOf(node.tagName) == -1)
throw Error(node.tagName + ' is not supported');
}
function assertAttribute(attrs, attrNode, node) {
var n = attrNode.nodeName;
var v = attrNode.nodeValue;
if (!attrs.hasOwnProperty(n) || !attrs[n](node, v))
throw Error(node.tagName + '[' + n + '="' + v + '"] is not supported');
}
return function(s, opt_extraTags, opt_extraAttrs) {
var extraTags =
(opt_extraTags || []).map(function(str) { return str.toUpperCase(); });
var tags = allowedTags.concat(extraTags);
var attrs = merge(allowedAttributes, opt_extraAttrs || {});
var doc = document.implementation.createHTMLDocument('');
var r = doc.createRange();
r.selectNode(doc.body);
// This does not execute any scripts because the document has no view.
var df = r.createContextualFragment(s);
walk(df, function(node) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
assertElement(tags, node);
var nodeAttrs = node.attributes;
for (var i = 0; i < nodeAttrs.length; ++i) {
assertAttribute(attrs, nodeAttrs[i], node);
}
break;
case Node.COMMENT_NODE:
case Node.DOCUMENT_FRAGMENT_NODE:
case Node.TEXT_NODE:
break;
default:
throw Error('Node type ' + node.nodeType + ' is not supported');
}
});
return df;
};
})();
| bsd-3-clause |
bauhouse/Bugaroo | symphony/lib/toolkit/class.alert.php | 2922 | <?php
/**
* @package toolkit
*/
/**
* The Alert class drives the standard Symphony notices that
* appear at the top of the backend pages to alert the user of
* something. Their are three default alert styles, notice, error
* and success.
*/
Class Alert{
/**
* Represents a notice, usually used for non blocking alerts,
* just to inform that user that something has happened and
* they need to aware of it
* @var string
*/
const NOTICE = 'notice';
/**
* Represents an error, used when something has gone wrong during
* the previous action. It is blocking, in that the action has
* not completed successfully.
* @var string
*/
const ERROR = 'error';
/**
* Represents success, used when an action has completed successfully
* with no errors
* @var string
*/
const SUCCESS = 'success';
/**
* The message for this Alert, this text will be displayed to the user
* @var string
*/
private $_message;
/**
* The Alert constant to represent the style that this alert should
* take on. Defaults to `Alert::NOTICE`.
* @var string
*/
private $_type;
/**
* Constructor for the Alert class initialises some default
* variables
*
* @param string $message
* This text will be displayed to the user
* @param string $type
* The type of alert this is. Defaults to NOTICE, available
* values are `Alert::NOTICE`, `Alert::ERROR`, `Alert::SUCCESS`
*/
public function __construct($message, $type = self::NOTICE){
$this->message = $message;
$this->type = $type;
}
/**
* Magic accessor function to get the private variables from
* an Alert instance
*
* @param string $name
* The name of the variable, message or type are the valid
* values
* @return string
*/
public function __get($name){
return $this->{"_$name"};
}
/**
* Magic setter function to set the private variables of
* an Alert instance
*
* @param string $name
* The name of the variable, message or type are the valid values
* @param string $value
* The value of the variable that is being set
*/
public function __set($name, $value){
$this->{"_$name"} = $value;
}
/**
* Magic isset function to check if a variable is set by ensuring
* it's not null
*
* @param string $name
* The name of the variable to check, message or type are the valid
* values
* @return boolean
* True when set, false when not set.
*/
public function __isset($name){
return (isset($this->{"_$name"}) && !is_null($this->{"_$name"}));
}
/**
* Generates as XMLElement representation of this Alert
*
* @return XMLElement
*/
public function asXML(){
$p = new XMLElement('p', $this->message);
$p->setAttribute('id', 'notice');
if($this->type != self::NOTICE){
$p->setAttribute('class', $this->type);
}
return $p;
}
}
| mit |
rafaelcastelani/novomaq | lib/Zend/Gdata/Media/Extension/MediaKeywords.php | 1466 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Gdata
* @subpackage Media
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Gdata_App_Extension
*/
#require_once 'Zend/Gdata/App/Extension.php';
/**
* Represents the media:keywords element
*
* @category Zend
* @package Zend_Gdata
* @subpackage Media
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_Media_Extension_MediaKeywords extends Zend_Gdata_Extension
{
protected $_rootElement = 'keywords';
protected $_rootNamespace = 'media';
/**
* Constructs a new MediaKeywords element
*/
public function __construct()
{
$this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
parent::__construct();
}
}
| mit |
drupal-ukraine/csua_d8 | drupal/core/modules/system/src/Tests/Block/SystemMenuBlockTest.php | 10669 | <?php
/**
* Contains \Drupal\system\Tests\Block\SystemMenuBlockTest
*/
namespace Drupal\system\Tests\Block;
use Drupal\Core\Render\Element;
use Drupal\simpletest\KernelTestBase;
use Drupal\system\Tests\Routing\MockRouteProvider;
use Drupal\Tests\Core\Menu\MenuLinkMock;
use Drupal\user\Entity\User;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* Tests \Drupal\system\Plugin\Block\SystemMenuBlock.
*
* @group Block
* @todo Expand test coverage to all SystemMenuBlock functionality, including
* block_menu_delete().
*
* @see \Drupal\system\Plugin\Derivative\SystemMenuBlock
* @see \Drupal\system\Plugin\Block\SystemMenuBlock
*/
class SystemMenuBlockTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array(
'system',
'block',
'menu_test',
'menu_link_content',
'field',
'user',
);
/**
* The block under test.
*
* @var \Drupal\system\Plugin\Block\SystemMenuBlock
*/
protected $block;
/**
* The menu for testing.
*
* @var \Drupal\system\MenuInterface
*/
protected $menu;
/**
* The menu link tree service.
*
* @var \Drupal\Core\Menu\MenuLinkTree
*/
protected $linkTree;
/**
* The menu link plugin manager service.
*
* @var \Drupal\Core\Menu\MenuLinkManagerInterface $menuLinkManager
*/
protected $menuLinkManager;
/**
* The block manager service.
*
* @var \Drupal\Core\block\BlockManagerInterface
*/
protected $blockManager;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installSchema('system', 'sequences');
$this->installEntitySchema('user');
$this->installSchema('system', array('router'));
$this->installEntitySchema('menu_link_content');
$account = User::create([
'name' => $this->randomMachineName(),
'status' => 1,
]);
$account->save();
$this->container->get('current_user')->setAccount($account);
$this->menuLinkManager = $this->container->get('plugin.manager.menu.link');
$this->linkTree = $this->container->get('menu.link_tree');
$this->blockManager = $this->container->get('plugin.manager.block');
$routes = new RouteCollection();
$requirements = array('_access' => 'TRUE');
$options = array('_access_checks' => array('access_check.default'));
$routes->add('example1', new Route('/example1', array(), $requirements, $options));
$routes->add('example2', new Route('/example2', array(), $requirements, $options));
$routes->add('example3', new Route('/example3', array(), $requirements, $options));
$routes->add('example4', new Route('/example4', array(), $requirements, $options));
$routes->add('example5', new Route('/example5', array(), $requirements, $options));
$routes->add('example6', new Route('/example6', array(), $requirements, $options));
$routes->add('example7', new Route('/example7', array(), $requirements, $options));
$routes->add('example8', new Route('/example8', array(), $requirements, $options));
$mock_route_provider = new MockRouteProvider($routes);
$this->container->set('router.route_provider', $mock_route_provider);
// Add a new custom menu.
$menu_name = 'mock';
$label = $this->randomMachineName(16);
$this->menu = entity_create('menu', array(
'id' => $menu_name,
'label' => $label,
'description' => 'Description text',
));
$this->menu->save();
// This creates a tree with the following structure:
// - 1
// - 2
// - 3
// - 4
// - 5
// - 7
// - 6
// - 8
// With link 6 being the only external link.
$links = array(
1 => MenuLinkMock::create(array('id' => 'test.example1', 'route_name' => 'example1', 'title' => 'foo', 'parent' => '', 'weight' => 0)),
2 => MenuLinkMock::create(array('id' => 'test.example2', 'route_name' => 'example2', 'title' => 'bar', 'parent' => '', 'route_parameters' => array('foo' => 'bar'), 'weight' => 1)),
3 => MenuLinkMock::create(array('id' => 'test.example3', 'route_name' => 'example3', 'title' => 'baz', 'parent' => 'test.example2', 'weight' => 2)),
4 => MenuLinkMock::create(array('id' => 'test.example4', 'route_name' => 'example4', 'title' => 'qux', 'parent' => 'test.example3', 'weight' => 3)),
5 => MenuLinkMock::create(array('id' => 'test.example5', 'route_name' => 'example5', 'title' => 'foofoo', 'parent' => '', 'expanded' => TRUE, 'weight' => 4)),
6 => MenuLinkMock::create(array('id' => 'test.example6', 'route_name' => '', 'url' => 'https://drupal.org/', 'title' => 'barbar', 'parent' => '', 'weight' => 5)),
7 => MenuLinkMock::create(array('id' => 'test.example7', 'route_name' => 'example7', 'title' => 'bazbaz', 'parent' => 'test.example5', 'weight' => 6)),
8 => MenuLinkMock::create(array('id' => 'test.example8', 'route_name' => 'example8', 'title' => 'quxqux', 'parent' => '', 'weight' => 7)),
);
foreach ($links as $instance) {
$this->menuLinkManager->addDefinition($instance->getPluginId(), $instance->getPluginDefinition());
}
}
/**
* Tests calculation of a system menu block's configuration dependencies.
*/
public function testSystemMenuBlockConfigDependencies() {
$block = entity_create('block', array(
'plugin' => 'system_menu_block:' . $this->menu->id(),
'region' => 'footer',
'id' => 'machinename',
'theme' => 'stark',
));
$dependencies = $block->calculateDependencies();
$expected = array(
'config' => array(
'system.menu.' . $this->menu->id()
),
'module' => array(
'system'
),
'theme' => array(
'stark'
),
);
$this->assertIdentical($expected, $dependencies);
}
/**
* Tests the config start level and depth.
*/
public function testConfigLevelDepth() {
// Helper function to generate a configured block instance.
$place_block = function ($level, $depth) {
return $this->blockManager->createInstance('system_menu_block:' . $this->menu->id(), array(
'region' => 'footer',
'id' => 'machinename',
'theme' => 'stark',
'level' => $level,
'depth' => $depth,
));
};
// All the different block instances we're going to test.
$blocks = [
'all' => $place_block(1, 0),
'level_1_only' => $place_block(1, 1),
'level_2_only' => $place_block(2, 1),
'level_3_only' => $place_block(3, 1),
'level_1_and_beyond' => $place_block(1, 0),
'level_2_and_beyond' => $place_block(2, 0),
'level_3_and_beyond' => $place_block(3, 0),
];
// Scenario 1: test all block instances when there's no active trail.
$no_active_trail_expectations = [];
$no_active_trail_expectations['all'] = [
'test.example1' => [],
'test.example2' => [],
'test.example5' => [
'test.example7' => [],
],
'test.example6' => [],
'test.example8' => [],
];
$no_active_trail_expectations['level_1_only'] = [
'test.example1' => [],
'test.example2' => [],
'test.example5' => [],
'test.example6' => [],
'test.example8' => [],
];
$no_active_trail_expectations['level_2_only'] = [
'test.example7' => [],
];
$no_active_trail_expectations['level_3_only'] = [];
$no_active_trail_expectations['level_1_and_beyond'] = $no_active_trail_expectations['all'];
$no_active_trail_expectations['level_2_and_beyond'] = $no_active_trail_expectations['level_2_only'];
$no_active_trail_expectations['level_3_and_beyond'] = [];
foreach ($blocks as $id => $block) {
$block_build = $block->build();
$items = isset($block_build['#items']) ? $block_build['#items'] : [];
$this->assertIdentical($no_active_trail_expectations[$id], $this->convertBuiltMenuToIdTree($items), format_string('Menu block %id with no active trail renders the expected tree.', ['%id' => $id]));
}
// Scenario 2: test all block instances when there's an active trail.
$route = $this->container->get('router.route_provider')->getRouteByName('example3');
$request = new Request();
$request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'example3');
$request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, $route);
$this->container->get('request_stack')->push($request);
$active_trail_expectations = [];
$active_trail_expectations['all'] = [
'test.example1' => [],
'test.example2' => [
'test.example3' => [
'test.example4' => [],
]
],
'test.example5' => [
'test.example7' => [],
],
'test.example6' => [],
'test.example8' => [],
];
$active_trail_expectations['level_1_only'] = [
'test.example1' => [],
'test.example2' => [],
'test.example5' => [],
'test.example6' => [],
'test.example8' => [],
];
$active_trail_expectations['level_2_only'] = [
'test.example3' => [],
'test.example7' => [],
];
$active_trail_expectations['level_3_only'] = [
'test.example4' => [],
];
$active_trail_expectations['level_1_and_beyond'] = $active_trail_expectations['all'];
$active_trail_expectations['level_2_and_beyond'] = [
'test.example3' => [
'test.example4' => [],
],
'test.example7' => [],
];
$active_trail_expectations['level_3_and_beyond'] = $active_trail_expectations['level_3_only'];
foreach ($blocks as $id => $block) {
$block_build = $block->build();
$items = isset($block_build['#items']) ? $block_build['#items'] : [];
$this->assertIdentical($active_trail_expectations[$id], $this->convertBuiltMenuToIdTree($items), format_string('Menu block %id with an active trail renders the expected tree.', ['%id' => $id]));
}
}
/**
* Helper method to allow for easy menu link tree structure assertions.
*
* Converts the result of MenuLinkTree::build() in a "menu link ID tree".
*
* @param array $build
* The return value of of MenuLinkTree::build()
*
* @return array
* The "menu link ID tree" representation of the given render array.
*/
protected function convertBuiltMenuToIdTree(array $build) {
$level = [];
foreach (Element::children($build) as $id) {
$level[$id] = [];
if (isset($build[$id]['below'])) {
$level[$id] = $this->convertBuiltMenuToIdTree($build[$id]['below']);
}
}
return $level;
}
}
| gpl-2.0 |
phproberto/joomla-cms | libraries/src/Cache/Storage/MemcacheStorage.php | 9325 | <?php
/**
* Joomla! Content Management System
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\CMS\Cache\Storage;
defined('JPATH_PLATFORM') or die;
use Joomla\CMS\Cache\Cache;
use Joomla\CMS\Cache\CacheStorage;
use Joomla\CMS\Cache\Exception\CacheConnectingException;
/**
* Memcache cache storage handler
*
* @link https://www.php.net/manual/en/book.memcache.php
* @since 1.7.0
* @deprecated 4.0 Use the Memcached handler instead
*/
class MemcacheStorage extends CacheStorage
{
/**
* Memcache connection object
*
* @var \Memcache
* @since 1.7.0
*/
protected static $_db = null;
/**
* Payload compression level
*
* @var integer
* @since 1.7.0
*/
protected $_compress = 0;
/**
* Constructor
*
* @param array $options Optional parameters.
*
* @since 1.7.0
*/
public function __construct($options = array())
{
parent::__construct($options);
$this->_compress = \JFactory::getConfig()->get('memcache_compress', false) ? MEMCACHE_COMPRESSED : 0;
if (static::$_db === null)
{
$this->getConnection();
}
}
/**
* Create the Memcache connection
*
* @return void
*
* @since 1.7.0
* @throws \RuntimeException
*/
protected function getConnection()
{
if (!static::isSupported())
{
throw new \RuntimeException('Memcache Extension is not available');
}
$config = \JFactory::getConfig();
$host = $config->get('memcache_server_host', 'localhost');
$port = $config->get('memcache_server_port', 11211);
// Create the memcache connection
static::$_db = new \Memcache;
if ($config->get('memcache_persist', true))
{
$result = @static::$_db->pconnect($host, $port);
}
else
{
$result = @static::$_db->connect($host, $port);
}
if (!$result)
{
// Null out the connection to inform the constructor it will need to attempt to connect if this class is instantiated again
static::$_db = null;
throw new CacheConnectingException('Could not connect to memcache server');
}
}
/**
* Get a cache_id string from an id/group pair
*
* @param string $id The cache data id
* @param string $group The cache data group
*
* @return string The cache_id string
*
* @since 1.7.0
*/
protected function _getCacheId($id, $group)
{
$prefix = Cache::getPlatformPrefix();
$length = strlen($prefix);
$cache_id = parent::_getCacheId($id, $group);
if ($length)
{
// Memcache use suffix instead of prefix
$cache_id = substr($cache_id, $length) . strrev($prefix);
}
return $cache_id;
}
/**
* Check if the cache contains data stored by ID and group
*
* @param string $id The cache data ID
* @param string $group The cache data group
*
* @return boolean
*
* @since 3.7.0
*/
public function contains($id, $group)
{
return $this->get($id, $group) !== false;
}
/**
* Get cached data by ID and group
*
* @param string $id The cache data ID
* @param string $group The cache data group
* @param boolean $checkTime True to verify cache time expiration threshold
*
* @return mixed Boolean false on failure or a cached data object
*
* @since 1.7.0
*/
public function get($id, $group, $checkTime = true)
{
return static::$_db->get($this->_getCacheId($id, $group));
}
/**
* Get all cached data
*
* @return mixed Boolean false on failure or a cached data object
*
* @since 1.7.0
*/
public function getAll()
{
$keys = static::$_db->get($this->_hash . '-index');
$secret = $this->_hash;
$data = array();
if (is_array($keys))
{
foreach ($keys as $key)
{
if (empty($key))
{
continue;
}
$namearr = explode('-', $key->name);
if ($namearr !== false && $namearr[0] == $secret && $namearr[1] == 'cache')
{
$group = $namearr[2];
if (!isset($data[$group]))
{
$item = new CacheStorageHelper($group);
}
else
{
$item = $data[$group];
}
$item->updateSize($key->size);
$data[$group] = $item;
}
}
}
return $data;
}
/**
* Store the data to cache by ID and group
*
* @param string $id The cache data ID
* @param string $group The cache data group
* @param string $data The data to store in cache
*
* @return boolean
*
* @since 1.7.0
*/
public function store($id, $group, $data)
{
$cache_id = $this->_getCacheId($id, $group);
if (!$this->lockindex())
{
return false;
}
$index = static::$_db->get($this->_hash . '-index');
if (!is_array($index))
{
$index = array();
}
$tmparr = new \stdClass;
$tmparr->name = $cache_id;
$tmparr->size = strlen($data);
$index[] = $tmparr;
static::$_db->set($this->_hash . '-index', $index, 0, 0);
$this->unlockindex();
static::$_db->set($cache_id, $data, $this->_compress, $this->_lifetime);
return true;
}
/**
* Remove a cached data entry by ID and group
*
* @param string $id The cache data ID
* @param string $group The cache data group
*
* @return boolean
*
* @since 1.7.0
*/
public function remove($id, $group)
{
$cache_id = $this->_getCacheId($id, $group);
if (!$this->lockindex())
{
return false;
}
$index = static::$_db->get($this->_hash . '-index');
if (is_array($index))
{
foreach ($index as $key => $value)
{
if ($value->name == $cache_id)
{
unset($index[$key]);
static::$_db->set($this->_hash . '-index', $index, 0, 0);
break;
}
}
}
$this->unlockindex();
return static::$_db->delete($cache_id);
}
/**
* Clean cache for a group given a mode.
*
* group mode : cleans all cache in the group
* notgroup mode : cleans all cache not in the group
*
* @param string $group The cache data group
* @param string $mode The mode for cleaning cache [group|notgroup]
*
* @return boolean
*
* @since 1.7.0
*/
public function clean($group, $mode = null)
{
if (!$this->lockindex())
{
return false;
}
$index = static::$_db->get($this->_hash . '-index');
if (is_array($index))
{
$prefix = $this->_hash . '-cache-' . $group . '-';
foreach ($index as $key => $value)
{
if (strpos($value->name, $prefix) === 0 xor $mode != 'group')
{
static::$_db->delete($value->name);
unset($index[$key]);
}
}
static::$_db->set($this->_hash . '-index', $index, 0, 0);
}
$this->unlockindex();
return true;
}
/**
* Flush all existing items in storage.
*
* @return boolean
*
* @since 3.6.3
*/
public function flush()
{
if (!$this->lockindex())
{
return false;
}
return static::$_db->flush();
}
/**
* Test to see if the storage handler is available.
*
* @return boolean
*
* @since 3.0.0
*/
public static function isSupported()
{
return extension_loaded('memcache') && class_exists('\\Memcache');
}
/**
* Lock cached item
*
* @param string $id The cache data ID
* @param string $group The cache data group
* @param integer $locktime Cached item max lock time
*
* @return mixed Boolean false if locking failed or an object containing properties lock and locklooped
*
* @since 1.7.0
*/
public function lock($id, $group, $locktime)
{
$returning = new \stdClass;
$returning->locklooped = false;
$looptime = $locktime * 10;
$cache_id = $this->_getCacheId($id, $group);
$data_lock = static::$_db->add($cache_id . '_lock', 1, 0, $locktime);
if ($data_lock === false)
{
$lock_counter = 0;
// Loop until you find that the lock has been released.
// That implies that data get from other thread has finished.
while ($data_lock === false)
{
if ($lock_counter > $looptime)
{
break;
}
usleep(100);
$data_lock = static::$_db->add($cache_id . '_lock', 1, 0, $locktime);
$lock_counter++;
}
$returning->locklooped = true;
}
$returning->locked = $data_lock;
return $returning;
}
/**
* Unlock cached item
*
* @param string $id The cache data ID
* @param string $group The cache data group
*
* @return boolean
*
* @since 1.7.0
*/
public function unlock($id, $group = null)
{
$cache_id = $this->_getCacheId($id, $group) . '_lock';
return static::$_db->delete($cache_id);
}
/**
* Lock cache index
*
* @return boolean
*
* @since 1.7.0
*/
protected function lockindex()
{
$looptime = 300;
$data_lock = static::$_db->add($this->_hash . '-index_lock', 1, 0, 30);
if ($data_lock === false)
{
$lock_counter = 0;
// Loop until you find that the lock has been released. that implies that data get from other thread has finished
while ($data_lock === false)
{
if ($lock_counter > $looptime)
{
return false;
}
usleep(100);
$data_lock = static::$_db->add($this->_hash . '-index_lock', 1, 0, 30);
$lock_counter++;
}
}
return true;
}
/**
* Unlock cache index
*
* @return boolean
*
* @since 1.7.0
*/
protected function unlockindex()
{
return static::$_db->delete($this->_hash . '-index_lock');
}
}
| gpl-2.0 |
pavel-else/komplect-ug | jssource/src_files/modules/Project/Project.js | 4019 | /*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
* SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
* Copyright (C) 2011 - 2014 Salesagility Ltd.
*
* 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 with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* 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
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
********************************************************************************/
function prep_edit(the_form)
{
the_form.return_module.value='Project';
the_form.return_action.value='DetailView';
the_form.return_id.value='{id}';
the_form.action.value='EditView';
the_form.sugar_body_only.value='0';
}
function prep_edit_project_tasks(the_form)
{
the_form.return_module.value='Project';
the_form.return_action.value='DetailView';
the_form.return_id.value='{id}';
the_form.action.value='EditGridView';
the_form.sugar_body_only.value='0';
}
function prep_duplicate(the_form)
{
the_form.return_module.value='Project';
the_form.return_action.value='index';
the_form.isDuplicate.value=true;
the_form.action.value='EditView';
the_form.sugar_body_only.value='0';
}
function prep_delete(the_form)
{
the_form.return_module.value='Project';
the_form.return_action.value='ListView';
the_form.action.value='Delete';
the_form.sugar_body_only.value='0';
}
function prep_save_as_template(the_form)
{
the_form.return_module.value='Project';
the_form.return_action.value='DetailView';
the_form.return_id.value='{id}';
the_form.action.value='Convert';
the_form.sugar_body_only.value='0';
}
function prep_save_as_project(the_form)
{
the_form.return_module.value='Project';
the_form.return_action.value='ProjectTemplatesDetailView';
the_form.return_id.value='{id}';
the_form.action.value='Convert';
}
function prep_export_to_project(the_form)
{
the_form.return_module.value='Project';
the_form.return_action.value='DetailView';
the_form.return_id.value='{id}';
the_form.action.value='Export';
the_form.sugar_body_only.value='1';
}
//html = '<a id="create_link" onclick="' + $("#view_gantt").attr('onclick') + '" class="utilsLink">' + $("#view_gantt").attr('value') + '</a> ' + $(".moduleTitle .utils").html();
//$(".moduleTitle .utils").html(html);
| agpl-3.0 |
thahemp/osg-android | src/osgWrappers/serializers/osg/Depth.cpp | 818 | #include <osg/Depth>
#include <osgDB/ObjectWrapper>
#include <osgDB/InputStream>
#include <osgDB/OutputStream>
REGISTER_OBJECT_WRAPPER( Depth,
new osg::Depth,
osg::Depth,
"osg::Object osg::StateAttribute osg::Depth" )
{
BEGIN_ENUM_SERIALIZER( Function, LESS );
ADD_ENUM_VALUE( NEVER );
ADD_ENUM_VALUE( LESS );
ADD_ENUM_VALUE( EQUAL );
ADD_ENUM_VALUE( LEQUAL );
ADD_ENUM_VALUE( GREATER );
ADD_ENUM_VALUE( NOTEQUAL );
ADD_ENUM_VALUE( GEQUAL );
ADD_ENUM_VALUE( ALWAYS );
END_ENUM_SERIALIZER(); // _func
ADD_DOUBLE_SERIALIZER( ZNear, 0.0 ); // _zNear
ADD_DOUBLE_SERIALIZER( ZFar, 1.0 ); // _zFar
ADD_BOOL_SERIALIZER( WriteMask, true ); // _depthWriteMask
}
| lgpl-2.1 |
thahemp/osg-android | src/osgWrappers/serializers/osgSim/DOFTransform.cpp | 2676 | #include <osgSim/DOFTransform>
#include <osgDB/ObjectWrapper>
#include <osgDB/InputStream>
#include <osgDB/OutputStream>
static bool checkPutMatrix( const osgSim::DOFTransform& dof )
{ return !dof.getPutMatrix().isIdentity(); }
static bool readPutMatrix( osgDB::InputStream& is, osgSim::DOFTransform& dof )
{
osg::Matrixf put; is >> put;
dof.setPutMatrix( put );
dof.setInversePutMatrix( osg::Matrix::inverse(put) );
return true;
}
static bool writePutMatrix( osgDB::OutputStream& os, const osgSim::DOFTransform& dof )
{
osg::Matrixf put = dof.getPutMatrix();
os << put << std::endl;
return true;
}
static bool checkLimitationFlags( const osgSim::DOFTransform& dof )
{ return dof.getLimitationFlags()>0; }
static bool readLimitationFlags( osgDB::InputStream& is, osgSim::DOFTransform& dof )
{
unsigned long flags; is >> flags;
dof.setLimitationFlags( flags );;
return true;
}
static bool writeLimitationFlags( osgDB::OutputStream& os, const osgSim::DOFTransform& dof )
{
os << dof.getLimitationFlags() << std::endl;
return true;
}
REGISTER_OBJECT_WRAPPER( osgSim_DOFTransform,
new osgSim::DOFTransform,
osgSim::DOFTransform,
"osg::Object osg::Node osg::Group osg::Transform osgSim::DOFTransform" )
{
ADD_VEC3_SERIALIZER( MinHPR, osg::Vec3() ); // _minHPR
ADD_VEC3_SERIALIZER( MaxHPR, osg::Vec3() ); // _maxHPR
ADD_VEC3_SERIALIZER( CurrentHPR, osg::Vec3() ); // _currentHPR
ADD_VEC3_SERIALIZER( IncrementHPR, osg::Vec3() ); // _incrementHPR
ADD_VEC3_SERIALIZER( MinTranslate, osg::Vec3() ); // _minTranslate
ADD_VEC3_SERIALIZER( MaxTranslate, osg::Vec3() ); // _maxTranslate
ADD_VEC3_SERIALIZER( CurrentTranslate, osg::Vec3() ); // _currentTranslate
ADD_VEC3_SERIALIZER( IncrementTranslate, osg::Vec3() ); // _incrementTranslate
ADD_VEC3_SERIALIZER( MinScale, osg::Vec3() ); // _minScale
ADD_VEC3_SERIALIZER( MaxScale, osg::Vec3() ); // _maxScale
ADD_VEC3_SERIALIZER( CurrentScale, osg::Vec3() ); // _currentScale
ADD_VEC3_SERIALIZER( IncrementScale, osg::Vec3() ); // _incrementScale
ADD_USER_SERIALIZER( PutMatrix ); // _Put, _inversePut
ADD_USER_SERIALIZER( LimitationFlags ); // _limitationFlags
ADD_BOOL_SERIALIZER( AnimationOn, false ); // _animationOn
BEGIN_ENUM_SERIALIZER2( HPRMultOrder, osgSim::DOFTransform::MultOrder, PRH );
ADD_ENUM_VALUE( PRH );
ADD_ENUM_VALUE( PHR );
ADD_ENUM_VALUE( HPR );
ADD_ENUM_VALUE( HRP );
ADD_ENUM_VALUE( RPH );
ADD_ENUM_VALUE( RHP );
END_ENUM_SERIALIZER(); // _multOrder
}
| lgpl-2.1 |
RossLieberman/NEST | src/Nest/Cat/ICatRecord.cs | 53 | namespace Nest
{
public interface ICatRecord {}
} | apache-2.0 |
GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/ci-info/index.js | 1739 | 'use strict'
var vendors = require('./vendors.json')
var env = process.env
// Used for testing only
Object.defineProperty(exports, '_vendors', {
value: vendors.map(function (v) { return v.constant })
})
exports.name = null
exports.isPR = null
vendors.forEach(function (vendor) {
var envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env]
var isCI = envs.every(function (obj) {
return checkEnv(obj)
})
exports[vendor.constant] = isCI
if (isCI) {
exports.name = vendor.name
switch (typeof vendor.pr) {
case 'string':
// "pr": "CIRRUS_PR"
exports.isPR = !!env[vendor.pr]
break
case 'object':
if ('env' in vendor.pr) {
// "pr": { "env": "BUILDKITE_PULL_REQUEST", "ne": "false" }
exports.isPR = vendor.pr.env in env && env[vendor.pr.env] !== vendor.pr.ne
} else if ('any' in vendor.pr) {
// "pr": { "any": ["ghprbPullId", "CHANGE_ID"] }
exports.isPR = vendor.pr.any.some(function (key) {
return !!env[key]
})
} else {
// "pr": { "DRONE_BUILD_EVENT": "pull_request" }
exports.isPR = checkEnv(vendor.pr)
}
break
default:
// PR detection not supported for this vendor
exports.isPR = null
}
}
})
exports.isCI = !!(
env.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari
env.CONTINUOUS_INTEGRATION || // Travis CI, Cirrus CI
env.BUILD_NUMBER || // Jenkins, TeamCity
env.RUN_ID || // TaskCluster, dsari
exports.name ||
false
)
function checkEnv (obj) {
if (typeof obj === 'string') return !!env[obj]
return Object.keys(obj).every(function (k) {
return env[k] === obj[k]
})
}
| apache-2.0 |
atpham256/azure-powershell | src/ResourceManager/Dns/Commands.Dns/Models/DnsRecordSet.cs | 19103 | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Management.Dns.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Microsoft.Azure.Commands.Dns
{
/// <summary>
/// Represents a set of records with the same name, with the same type and in the same zone.
/// </summary>
public class DnsRecordSet : ICloneable
{
/// <summary>
/// Gets or sets the name of this record set, relative to the name of the zone to which it belongs and WITHOUT a terminating '.' (dot) character.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the name of the zone to which this recordset belongs.
/// </summary>
public string ZoneName { get; set; }
/// <summary>
/// Gets or sets the name of the resource group to which this record set belongs.
/// </summary>
public string ResourceGroupName { get; set; }
/// <summary>
/// Gets or sets the TTL of all the records in this record set.
/// </summary>
public uint Ttl { get; set; }
/// <summary>
/// Gets or sets the Etag of this record set.
/// </summary>
public string Etag { get; set; }
/// <summary>
/// Gets or sets the type of DNS records in this record set. Only records of this type may be added to this record set.
/// </summary>
public RecordType RecordType { get; set; }
/// <summary>
/// Gets or sets the list of records in this record set.
/// </summary>
public List<DnsRecordBase> Records { get; set; }
/// <summary>
/// Gets or sets the tags of this record set.
/// </summary>
public Hashtable Metadata { get; set; }
/// <summary>
/// Returns a deep copy of this record set
/// </summary>
/// <returns></returns>
public object Clone()
{
var clone = new DnsRecordSet();
clone.Name = this.Name;
clone.ZoneName = this.ZoneName;
clone.ResourceGroupName = this.ResourceGroupName;
clone.Ttl = this.Ttl;
clone.Etag = this.Etag;
clone.RecordType = this.RecordType;
if (this.Records != null)
{
clone.Records = this.Records.Select(record => record.Clone()).Cast<DnsRecordBase>().ToList();
}
if (this.Metadata != null)
{
clone.Metadata = (Hashtable)this.Metadata.Clone();
}
return clone;
}
}
/// <summary>
/// Represents a DNS record that is part of a <see cref="DnsRecordSet"/>.
/// </summary>
public abstract class DnsRecordBase : ICloneable
{
public abstract object Clone();
public const int TxtRecordMaxLength = 1024;
public const int TxtRecordMinLength = 0;
public const int TxtRecordChunkSize = 255;
internal abstract object ToMamlRecord();
internal static DnsRecordBase FromMamlRecord(object record)
{
if (record is Management.Dns.Models.ARecord)
{
var mamlRecord = (Management.Dns.Models.ARecord)record;
return new ARecord
{
Ipv4Address = mamlRecord.Ipv4Address
};
}
else if (record is Management.Dns.Models.AaaaRecord)
{
var mamlRecord = (Management.Dns.Models.AaaaRecord)record;
return new AaaaRecord
{
Ipv6Address = mamlRecord.Ipv6Address
};
}
else if (record is Management.Dns.Models.CnameRecord)
{
var mamlRecord = (Management.Dns.Models.CnameRecord)record;
return new CnameRecord
{
Cname = mamlRecord.Cname
};
}
else if (record is Management.Dns.Models.NsRecord)
{
var mamlRecord = (Management.Dns.Models.NsRecord)record;
return new NsRecord
{
Nsdname = mamlRecord.Nsdname
};
}
else if (record is Management.Dns.Models.MxRecord)
{
var mamlRecord = (Management.Dns.Models.MxRecord)record;
return new MxRecord
{
Exchange = mamlRecord.Exchange,
Preference = (ushort) mamlRecord.Preference,
};
}
else if (record is Management.Dns.Models.SrvRecord)
{
var mamlRecord = (Management.Dns.Models.SrvRecord)record;
return new SrvRecord
{
Port = (ushort) mamlRecord.Port,
Priority = (ushort) mamlRecord.Priority,
Target = mamlRecord.Target,
Weight = (ushort) mamlRecord.Weight,
};
}
else if (record is Management.Dns.Models.SoaRecord)
{
var mamlRecord = (Management.Dns.Models.SoaRecord)record;
return new SoaRecord
{
Email = mamlRecord.Email,
ExpireTime = (uint) mamlRecord.ExpireTime.GetValueOrDefault(),
Host = mamlRecord.Host,
MinimumTtl = (uint) mamlRecord.MinimumTtl.GetValueOrDefault(),
RefreshTime = (uint) mamlRecord.RefreshTime.GetValueOrDefault(),
RetryTime = (uint) mamlRecord.RetryTime.GetValueOrDefault(),
SerialNumber = (uint) mamlRecord.SerialNumber.GetValueOrDefault(),
};
}
else if (record is Management.Dns.Models.TxtRecord)
{
var mamlRecord = (Management.Dns.Models.TxtRecord)record;
return new TxtRecord
{
Value = ToPowerShellTxtValue(mamlRecord.Value),
};
}
else if (record is Management.Dns.Models.PtrRecord)
{
var mamlRecord = (Management.Dns.Models.PtrRecord)record;
return new PtrRecord
{
Ptrdname = mamlRecord.Ptrdname,
};
}
return null;
}
private static string ToPowerShellTxtValue(ICollection<string> value)
{
if (value == null || value.Count == 0)
{
return null;
}
var sb = new StringBuilder();
foreach (var s in value)
{
sb.Append(s);
}
return sb.ToString();
}
}
/// <summary>
/// Represents a DNS record of type A that is part of a <see cref="DnsRecordSet"/>.
/// </summary>
public class ARecord : DnsRecordBase
{
/// <summary>
/// Gets or sets the IPv4 address of this A record in string notation
/// </summary>
public string Ipv4Address { get; set; }
public override string ToString()
{
return this.Ipv4Address;
}
internal override object ToMamlRecord()
{
return new Management.Dns.Models.ARecord
{
Ipv4Address = this.Ipv4Address,
};
}
/// <summary>
/// Cerates a deep copy of this object
/// </summary>
/// <returns>A clone of this object</returns>
public override object Clone()
{
return new ARecord { Ipv4Address = this.Ipv4Address };
}
}
/// <summary>
/// Represents a DNS record of type AAAA that is part of a <see cref="DnsRecordSet"/>.
/// </summary>
public class AaaaRecord : DnsRecordBase
{
/// <summary>
/// Gets or sets the IPv6 address of this AAAA record in string notation.
/// </summary>
public string Ipv6Address { get; set; }
public override string ToString()
{
return this.Ipv6Address;
}
internal override object ToMamlRecord()
{
return new Management.Dns.Models.AaaaRecord
{
Ipv6Address = this.Ipv6Address,
};
}
/// <summary>
/// Cerates a deep copy of this object
/// </summary>
/// <returns>A clone of this object</returns>
public override object Clone()
{
return new AaaaRecord { Ipv6Address = this.Ipv6Address };
}
}
/// <summary>
/// Represents a DNS record of type CNAME that is part of a <see cref="DnsRecordSet"/>.
/// </summary>
public class CnameRecord : DnsRecordBase
{
/// <summary>
/// Gets or sets the canonical name for this CNAME record without a terminating dot.
/// </summary>
public string Cname { get; set; }
public override string ToString()
{
return this.Cname;
}
internal override object ToMamlRecord()
{
return new Management.Dns.Models.CnameRecord
{
Cname = this.Cname,
};
}
/// <summary>
/// Cerates a deep copy of this object
/// </summary>
/// <returns>A clone of this object</returns>
public override object Clone()
{
return new CnameRecord { Cname = this.Cname };
}
}
/// <summary>
/// Represents a DNS record of type NS that is part of a <see cref="DnsRecordSet"/>.
/// </summary>
public class NsRecord : DnsRecordBase
{
/// <summary>
/// Gets or sets the name server name for this NS record, without a terminating dot.
/// </summary>
public string Nsdname { get; set; }
public override string ToString()
{
return this.Nsdname;
}
internal override object ToMamlRecord()
{
return new Management.Dns.Models.NsRecord
{
Nsdname = this.Nsdname,
};
}
/// <summary>
/// Cerates a deep copy of this object
/// </summary>
/// <returns>A clone of this object</returns>
public override object Clone()
{
return new NsRecord { Nsdname = this.Nsdname };
}
}
/// <summary>
/// Represents a DNS record of type TXT that is part of a <see cref="DnsRecordSet"/>.
/// </summary>
public class TxtRecord : DnsRecordBase
{
/// <summary>
/// Gets or sets the text value of this TXT record.
/// </summary>
public string Value { get; set; }
public override string ToString()
{
return this.Value;
}
internal override object ToMamlRecord()
{
char[] letters = this.Value.ToCharArray();
var splitValues = new List<string>();
int remaining = letters.Length;
int begin = 0;
while (remaining > 0)
{
if (remaining < TxtRecordChunkSize)
{
splitValues.Add(new string(letters, begin, remaining));
remaining = 0;
}
else
{
splitValues.Add(new string(letters, begin, TxtRecordChunkSize));
begin += TxtRecordChunkSize;
remaining -= TxtRecordChunkSize;
}
}
return new Management.Dns.Models.TxtRecord
{
Value = splitValues,
};
}
/// <summary>
/// Cerates a deep copy of this object
/// </summary>
/// <returns>A clone of this object</returns>
public override object Clone()
{
return new TxtRecord { Value = this.Value };
}
}
/// <summary>
/// Represents a DNS record of type MX that is part of a <see cref="DnsRecordSet"/>.
/// </summary>
public class MxRecord : DnsRecordBase
{
/// <summary>
/// Gets or sets the preference metric for this MX record.
/// </summary>
public ushort Preference { get; set; }
/// <summary>
/// Gets or sets the domain name of the mail host, without a terminating dot
/// </summary>
public string Exchange { get; set; }
public override string ToString()
{
return string.Format("[{0},{1}]", Preference, Exchange);
}
internal override object ToMamlRecord()
{
return new Management.Dns.Models.MxRecord
{
Exchange = this.Exchange,
Preference = this.Preference,
};
}
/// <summary>
/// Cerates a deep copy of this object
/// </summary>
/// <returns>A clone of this object</returns>
public override object Clone()
{
return new MxRecord { Exchange = this.Exchange, Preference = this.Preference };
}
}
/// <summary>
/// Represents a DNS record of type SRV that is part of a <see cref="DnsRecordSet"/>.
/// </summary>
public class SrvRecord : DnsRecordBase
{
/// <summary>
/// Gets or sets the domain name of the target for this SRV record, without a terminating dot.
/// </summary>
public string Target { get; set; }
/// <summary>
/// Gets or sets the weight metric for this SRV record.
/// </summary>
public ushort Weight { get; set; }
/// <summary>
/// Gets or sets the port for this SRV record
/// </summary>
public ushort Port { get; set; }
/// <summary>
/// Gets or sets the priority metric for this SRV record.
/// </summary>
public ushort Priority { get; set; }
public override string ToString()
{
return string.Format("[{0},{1},{2},{3}]", Priority, Weight, Port, Target);
}
internal override object ToMamlRecord()
{
return new Management.Dns.Models.SrvRecord
{
Priority = this.Priority,
Target = this.Target,
Weight = this.Weight,
Port = this.Port,
};
}
/// <summary>
/// Cerates a deep copy of this object
/// </summary>
/// <returns>A clone of this object</returns>
public override object Clone()
{
return new SrvRecord
{
Priority = this.Priority,
Target = this.Target,
Weight = this.Weight,
Port = this.Port
};
}
}
/// <summary>
/// Represents a DNS record of type SOA that is part of a <see cref="DnsRecordSet"/>.
/// </summary>
public class SoaRecord : DnsRecordBase
{
/// <summary>
/// Gets or sets the domain name of the authoritative name server for this SOA record, without a temrinating dot.
/// </summary>
public string Host { get; set; }
/// <summary>
/// Gets or sets the email for this SOA record.
/// </summary>
public string Email { get; set; }
/// <summary>
/// Gets or sets the serial number of this SOA record.
/// </summary>
public uint SerialNumber { get; set; }
/// <summary>
/// Gets or sets the refresh value for this SOA record.
/// </summary>
public uint RefreshTime { get; set; }
/// <summary>
/// Gets or sets the retry time for SOA record.
/// </summary>
public uint RetryTime { get; set; }
/// <summary>
/// Gets or sets the expire time for this SOA record.
/// </summary>
public uint ExpireTime { get; set; }
/// <summary>
/// Gets or sets the minimum TTL for this SOA record.
/// </summary>
public uint MinimumTtl { get; set; }
public override string ToString()
{
return string.Format("[{0},{1},{2},{3},{4},{5}]", Host, Email, RefreshTime, RetryTime, ExpireTime, MinimumTtl);
}
internal override object ToMamlRecord()
{
return new Management.Dns.Models.SoaRecord
{
Host = this.Host,
Email = this.Email,
SerialNumber = this.SerialNumber,
RefreshTime = this.RefreshTime,
RetryTime = this.RetryTime,
ExpireTime = this.ExpireTime,
MinimumTtl = this.MinimumTtl,
};
}
/// <summary>
/// Cerates a deep copy of this object
/// </summary>
/// <returns>A clone of this object</returns>
public override object Clone()
{
return new SoaRecord
{
Host = this.Host,
Email = this.Email,
SerialNumber = this.SerialNumber,
RefreshTime = this.RefreshTime,
RetryTime = this.RetryTime,
ExpireTime = this.ExpireTime,
MinimumTtl = this.MinimumTtl,
};
}
}
/// <summary>
/// Represents a DNS record of type NS that is part of a <see cref="DnsRecordSet"/>.
/// </summary>
public class PtrRecord : DnsRecordBase
{
/// <summary>
/// Gets or sets the ptr for this record.
/// </summary>
public string Ptrdname { get; set; }
public override string ToString()
{
return this.Ptrdname;
}
public override object Clone()
{
return new PtrRecord()
{
Ptrdname = this.Ptrdname,
};
}
internal override object ToMamlRecord()
{
return new Management.Dns.Models.PtrRecord
{
Ptrdname = this.Ptrdname,
};
}
}
}
| apache-2.0 |
GBGamer/rust | src/test/rustdoc/issue-29584.rs | 635 | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:issue-29584.rs
// ignore-cross-compile
extern crate issue_29584;
// @has issue_29584/struct.Foo.html
// @!has - 'impl Bar for'
pub use issue_29584::Foo;
| apache-2.0 |
ibinti/intellij-community | python/ipnb/src/org/jetbrains/plugins/ipnb/format/cells/output/IpnbStreamOutputCell.java | 605 | package org.jetbrains.plugins.ipnb.format.cells.output;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Map;
public class IpnbStreamOutputCell extends IpnbOutputCell {
@NotNull private final String myStream;
public IpnbStreamOutputCell(@NotNull final String stream, List<String> text, @Nullable final Integer prompt,
@Nullable Map<String, Object> metadata) {
super(text, prompt, metadata);
myStream = stream;
}
@NotNull
public String getStream() {
return myStream;
}
}
| apache-2.0 |
GBGamer/rust | src/test/ui/issues/issue-6801.rs | 905 | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Creating a stack closure which references a box and then
// transferring ownership of the box before invoking the stack
// closure results in a crash.
#![feature(box_syntax)]
fn twice(x: Box<usize>) -> usize {
*x * 2
}
fn invoke<F>(f: F) where F: FnOnce() -> usize {
f();
}
fn main() {
let x : Box<usize> = box 9;
let sq = || { *x * *x };
twice(x); //~ ERROR: cannot move out of
invoke(sq);
}
| apache-2.0 |
basho-labs/riak-cxx-client | deps/boost-1.47.0/libs/test/test/prg_exec_fail1.cpp | 1601 | // (C) Copyright Gennadiy Rozental 2001-2008.
// (C) Copyright Beman Dawes 2001.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision: 49313 $
//
// Description : tests an ability of Program Execution Monitor to catch
// uncatched exceptions. Should fail during run.
// ***************************************************************************
#ifdef __MWERKS__
// Metrowerks doesn't build knowledge of what runtime libraries to link with
// into their compiler. Instead they depend on pragmas in their standard
// library headers. That creates the odd situation that certain programs
// won't link unless at least one standard header is included. Note that
// this problem is highly dependent on enviroment variables and command
// line options, so just because the problem doesn't show up on one
// system doesn't mean it has been fixed. Remove this workaround only
// when told by Metrowerks that it is safe to do so.
#include <cstddef> //Metrowerks linker needs at least one standard library
#endif
#include <boost/test/included/prg_exec_monitor.hpp>
int
cpp_main( int argc, char *[] ) // note the name
{
if( argc > 0 ) // to prevent the unreachable return warning
throw "Test error by throwing C-style string exception";
return 0;
}
//____________________________________________________________________________//
// EOF
| apache-2.0 |
epiqc/ScaffCC | clang/lib/StaticAnalyzer/Checkers/ObjCPropertyChecker.cpp | 3098 | //==- ObjCPropertyChecker.cpp - Check ObjC properties ------------*- C++ -*-==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This checker finds issues with Objective-C properties.
// Currently finds only one kind of issue:
// - Find synthesized properties with copy attribute of mutable NS collection
// types. Calling -copy on such collections produces an immutable copy,
// which contradicts the type of the property.
//
//===----------------------------------------------------------------------===//
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
using namespace clang;
using namespace ento;
namespace {
class ObjCPropertyChecker
: public Checker<check::ASTDecl<ObjCPropertyDecl>> {
void checkCopyMutable(const ObjCPropertyDecl *D, BugReporter &BR) const;
public:
void checkASTDecl(const ObjCPropertyDecl *D, AnalysisManager &Mgr,
BugReporter &BR) const;
};
} // end anonymous namespace.
void ObjCPropertyChecker::checkASTDecl(const ObjCPropertyDecl *D,
AnalysisManager &Mgr,
BugReporter &BR) const {
checkCopyMutable(D, BR);
}
void ObjCPropertyChecker::checkCopyMutable(const ObjCPropertyDecl *D,
BugReporter &BR) const {
if (D->isReadOnly() || D->getSetterKind() != ObjCPropertyDecl::Copy)
return;
QualType T = D->getType();
if (!T->isObjCObjectPointerType())
return;
const std::string &PropTypeName(T->getPointeeType().getCanonicalType()
.getUnqualifiedType()
.getAsString());
if (!StringRef(PropTypeName).startswith("NSMutable"))
return;
const ObjCImplDecl *ImplD = nullptr;
if (const ObjCInterfaceDecl *IntD =
dyn_cast<ObjCInterfaceDecl>(D->getDeclContext())) {
ImplD = IntD->getImplementation();
} else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(D->getDeclContext())) {
ImplD = CatD->getClassInterface()->getImplementation();
}
if (!ImplD || ImplD->HasUserDeclaredSetterMethod(D))
return;
SmallString<128> Str;
llvm::raw_svector_ostream OS(Str);
OS << "Property of mutable type '" << PropTypeName
<< "' has 'copy' attribute; an immutable object will be stored instead";
BR.EmitBasicReport(
D, this, "Objective-C property misuse", "Logic error", OS.str(),
PathDiagnosticLocation::createBegin(D, BR.getSourceManager()),
D->getSourceRange());
}
void ento::registerObjCPropertyChecker(CheckerManager &Mgr) {
Mgr.registerChecker<ObjCPropertyChecker>();
}
bool ento::shouldRegisterObjCPropertyChecker(const LangOptions &LO) {
return true;
}
| bsd-2-clause |
Slaffka/moodel | mod/glossary/tests/generator/lib.php | 5271 | <?php
// 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 <http://www.gnu.org/licenses/>.
/**
* mod_glossary data generator.
*
* @package mod_glossary
* @category test
* @copyright 2013 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* mod_glossary data generator class.
*
* @package mod_glossary
* @category test
* @copyright 2013 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class mod_glossary_generator extends testing_module_generator {
/**
* @var int keep track of how many entries have been created.
*/
protected $entrycount = 0;
/**
* @var int keep track of how many entries have been created.
*/
protected $categorycount = 0;
/**
* To be called from data reset code only,
* do not use in tests.
* @return void
*/
public function reset() {
$this->entrycount = 0;
$this->categorycount = 0;
parent::reset();
}
public function create_instance($record = null, array $options = null) {
global $CFG;
// Add default values for glossary.
$record = (array)$record + array(
'globalglossary' => 0,
'mainglossary' => 0,
'defaultapproval' => $CFG->glossary_defaultapproval,
'allowduplicatedentries' => $CFG->glossary_dupentries,
'allowcomments' => $CFG->glossary_allowcomments,
'usedynalink' => $CFG->glossary_linkbydefault,
'displayformat' => 'dictionary',
'approvaldisplayformat' => 'default',
'entbypage' => !empty($CFG->glossary_entbypage) ? $CFG->glossary_entbypage : 10,
'showalphabet' => 1,
'showall' => 1,
'showspecial' => 1,
'allowprintview' => 1,
'rsstype' => 0,
'rssarticles' => 0,
'grade' => 100,
'assessed' => 0,
);
return parent::create_instance($record, (array)$options);
}
public function create_category($glossary, $record = array(), $entries = array()) {
global $CFG, $DB;
$this->categorycount++;
$record = (array)$record + array(
'name' => 'Glossary category '.$this->categorycount,
'usedynalink' => $CFG->glossary_linkbydefault,
);
$record['glossaryid'] = $glossary->id;
$id = $DB->insert_record('glossary_categories', $record);
if ($entries) {
foreach ($entries as $entry) {
$ce = new stdClass();
$ce->categoryid = $id;
$ce->entryid = $entry->id;
$DB->insert_record('glossary_entries_categories', $ce);
}
}
return $DB->get_record('glossary_categories', array('id' => $id), '*', MUST_EXIST);
}
public function create_content($glossary, $record = array(), $aliases = array()) {
global $DB, $USER, $CFG;
$this->entrycount++;
$now = time();
$record = (array)$record + array(
'glossaryid' => $glossary->id,
'timecreated' => $now,
'timemodified' => $now,
'userid' => $USER->id,
'concept' => 'Glossary entry '.$this->entrycount,
'definition' => 'Definition of glossary entry '.$this->entrycount,
'definitionformat' => FORMAT_MOODLE,
'definitiontrust' => 0,
'usedynalink' => $CFG->glossary_linkentries,
'casesensitive' => $CFG->glossary_casesensitive,
'fullmatch' => $CFG->glossary_fullmatch
);
if (!isset($record['teacherentry']) || !isset($record['approved'])) {
$context = context_module::instance($glossary->cmid);
if (!isset($record['teacherentry'])) {
$record['teacherentry'] = has_capability('mod/glossary:manageentries', $context, $record['userid']);
}
if (!isset($record['approved'])) {
$defaultapproval = $glossary->defaultapproval;
$record['approved'] = ($defaultapproval || has_capability('mod/glossary:approve', $context));
}
}
$id = $DB->insert_record('glossary_entries', $record);
if ($aliases) {
foreach ($aliases as $alias) {
$ar = new stdClass();
$ar->entryid = $id;
$ar->alias = $alias;
$DB->insert_record('glossary_alias', $ar);
}
}
return $DB->get_record('glossary_entries', array('id' => $id), '*', MUST_EXIST);
}
}
| gpl-3.0 |
quyse/inanity | deps/icu/repo/source/common/utypes.cpp | 7211 | // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
******************************************************************************
*
* Copyright (C) 1997-2015, International Business Machines
* Corporation and others. All Rights Reserved.
*
******************************************************************************
*
* FILE NAME : utypes.c (previously putil.c)
*
* Date Name Description
* 10/07/2004 grhoten split from putil.c
******************************************************************************
*/
#include "unicode/utypes.h"
/* u_errorName() ------------------------------------------------------------ */
static const char * const
_uErrorInfoName[U_ERROR_WARNING_LIMIT-U_ERROR_WARNING_START]={
"U_USING_FALLBACK_WARNING",
"U_USING_DEFAULT_WARNING",
"U_SAFECLONE_ALLOCATED_WARNING",
"U_STATE_OLD_WARNING",
"U_STRING_NOT_TERMINATED_WARNING",
"U_SORT_KEY_TOO_SHORT_WARNING",
"U_AMBIGUOUS_ALIAS_WARNING",
"U_DIFFERENT_UCA_VERSION",
"U_PLUGIN_CHANGED_LEVEL_WARNING",
};
static const char * const
_uTransErrorName[U_PARSE_ERROR_LIMIT - U_PARSE_ERROR_START]={
"U_BAD_VARIABLE_DEFINITION",
"U_MALFORMED_RULE",
"U_MALFORMED_SET",
"U_MALFORMED_SYMBOL_REFERENCE",
"U_MALFORMED_UNICODE_ESCAPE",
"U_MALFORMED_VARIABLE_DEFINITION",
"U_MALFORMED_VARIABLE_REFERENCE",
"U_MISMATCHED_SEGMENT_DELIMITERS",
"U_MISPLACED_ANCHOR_START",
"U_MISPLACED_CURSOR_OFFSET",
"U_MISPLACED_QUANTIFIER",
"U_MISSING_OPERATOR",
"U_MISSING_SEGMENT_CLOSE",
"U_MULTIPLE_ANTE_CONTEXTS",
"U_MULTIPLE_CURSORS",
"U_MULTIPLE_POST_CONTEXTS",
"U_TRAILING_BACKSLASH",
"U_UNDEFINED_SEGMENT_REFERENCE",
"U_UNDEFINED_VARIABLE",
"U_UNQUOTED_SPECIAL",
"U_UNTERMINATED_QUOTE",
"U_RULE_MASK_ERROR",
"U_MISPLACED_COMPOUND_FILTER",
"U_MULTIPLE_COMPOUND_FILTERS",
"U_INVALID_RBT_SYNTAX",
"U_INVALID_PROPERTY_PATTERN",
"U_MALFORMED_PRAGMA",
"U_UNCLOSED_SEGMENT",
"U_ILLEGAL_CHAR_IN_SEGMENT",
"U_VARIABLE_RANGE_EXHAUSTED",
"U_VARIABLE_RANGE_OVERLAP",
"U_ILLEGAL_CHARACTER",
"U_INTERNAL_TRANSLITERATOR_ERROR",
"U_INVALID_ID",
"U_INVALID_FUNCTION"
};
static const char * const
_uErrorName[U_STANDARD_ERROR_LIMIT]={
"U_ZERO_ERROR",
"U_ILLEGAL_ARGUMENT_ERROR",
"U_MISSING_RESOURCE_ERROR",
"U_INVALID_FORMAT_ERROR",
"U_FILE_ACCESS_ERROR",
"U_INTERNAL_PROGRAM_ERROR",
"U_MESSAGE_PARSE_ERROR",
"U_MEMORY_ALLOCATION_ERROR",
"U_INDEX_OUTOFBOUNDS_ERROR",
"U_PARSE_ERROR",
"U_INVALID_CHAR_FOUND",
"U_TRUNCATED_CHAR_FOUND",
"U_ILLEGAL_CHAR_FOUND",
"U_INVALID_TABLE_FORMAT",
"U_INVALID_TABLE_FILE",
"U_BUFFER_OVERFLOW_ERROR",
"U_UNSUPPORTED_ERROR",
"U_RESOURCE_TYPE_MISMATCH",
"U_ILLEGAL_ESCAPE_SEQUENCE",
"U_UNSUPPORTED_ESCAPE_SEQUENCE",
"U_NO_SPACE_AVAILABLE",
"U_CE_NOT_FOUND_ERROR",
"U_PRIMARY_TOO_LONG_ERROR",
"U_STATE_TOO_OLD_ERROR",
"U_TOO_MANY_ALIASES_ERROR",
"U_ENUM_OUT_OF_SYNC_ERROR",
"U_INVARIANT_CONVERSION_ERROR",
"U_INVALID_STATE_ERROR",
"U_COLLATOR_VERSION_MISMATCH",
"U_USELESS_COLLATOR_ERROR",
"U_NO_WRITE_PERMISSION",
"U_INPUT_TOO_LONG_ERROR"
};
static const char * const
_uFmtErrorName[U_FMT_PARSE_ERROR_LIMIT - U_FMT_PARSE_ERROR_START] = {
"U_UNEXPECTED_TOKEN",
"U_MULTIPLE_DECIMAL_SEPARATORS",
"U_MULTIPLE_EXPONENTIAL_SYMBOLS",
"U_MALFORMED_EXPONENTIAL_PATTERN",
"U_MULTIPLE_PERCENT_SYMBOLS",
"U_MULTIPLE_PERMILL_SYMBOLS",
"U_MULTIPLE_PAD_SPECIFIERS",
"U_PATTERN_SYNTAX_ERROR",
"U_ILLEGAL_PAD_POSITION",
"U_UNMATCHED_BRACES",
"U_UNSUPPORTED_PROPERTY",
"U_UNSUPPORTED_ATTRIBUTE",
"U_ARGUMENT_TYPE_MISMATCH",
"U_DUPLICATE_KEYWORD",
"U_UNDEFINED_KEYWORD",
"U_DEFAULT_KEYWORD_MISSING",
"U_DECIMAL_NUMBER_SYNTAX_ERROR",
"U_FORMAT_INEXACT_ERROR",
"U_NUMBER_ARG_OUTOFBOUNDS_ERROR",
"U_NUMBER_SKELETON_SYNTAX_ERROR",
};
static const char * const
_uBrkErrorName[U_BRK_ERROR_LIMIT - U_BRK_ERROR_START] = {
"U_BRK_INTERNAL_ERROR",
"U_BRK_HEX_DIGITS_EXPECTED",
"U_BRK_SEMICOLON_EXPECTED",
"U_BRK_RULE_SYNTAX",
"U_BRK_UNCLOSED_SET",
"U_BRK_ASSIGN_ERROR",
"U_BRK_VARIABLE_REDFINITION",
"U_BRK_MISMATCHED_PAREN",
"U_BRK_NEW_LINE_IN_QUOTED_STRING",
"U_BRK_UNDEFINED_VARIABLE",
"U_BRK_INIT_ERROR",
"U_BRK_RULE_EMPTY_SET",
"U_BRK_UNRECOGNIZED_OPTION",
"U_BRK_MALFORMED_RULE_TAG"
};
static const char * const
_uRegexErrorName[U_REGEX_ERROR_LIMIT - U_REGEX_ERROR_START] = {
"U_REGEX_INTERNAL_ERROR",
"U_REGEX_RULE_SYNTAX",
"U_REGEX_INVALID_STATE",
"U_REGEX_BAD_ESCAPE_SEQUENCE",
"U_REGEX_PROPERTY_SYNTAX",
"U_REGEX_UNIMPLEMENTED",
"U_REGEX_MISMATCHED_PAREN",
"U_REGEX_NUMBER_TOO_BIG",
"U_REGEX_BAD_INTERVAL",
"U_REGEX_MAX_LT_MIN",
"U_REGEX_INVALID_BACK_REF",
"U_REGEX_INVALID_FLAG",
"U_REGEX_LOOK_BEHIND_LIMIT",
"U_REGEX_SET_CONTAINS_STRING",
"U_REGEX_OCTAL_TOO_BIG",
"U_REGEX_MISSING_CLOSE_BRACKET",
"U_REGEX_INVALID_RANGE",
"U_REGEX_STACK_OVERFLOW",
"U_REGEX_TIME_OUT",
"U_REGEX_STOPPED_BY_CALLER",
"U_REGEX_PATTERN_TOO_BIG",
"U_REGEX_INVALID_CAPTURE_GROUP_NAME"
};
static const char * const
_uIDNAErrorName[U_IDNA_ERROR_LIMIT - U_IDNA_ERROR_START] = {
"U_STRINGPREP_PROHIBITED_ERROR",
"U_STRINGPREP_UNASSIGNED_ERROR",
"U_STRINGPREP_CHECK_BIDI_ERROR",
"U_IDNA_STD3_ASCII_RULES_ERROR",
"U_IDNA_ACE_PREFIX_ERROR",
"U_IDNA_VERIFICATION_ERROR",
"U_IDNA_LABEL_TOO_LONG_ERROR",
"U_IDNA_ZERO_LENGTH_LABEL_ERROR",
"U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR"
};
static const char * const
_uPluginErrorName[U_PLUGIN_ERROR_LIMIT - U_PLUGIN_ERROR_START] = {
"U_PLUGIN_TOO_HIGH",
"U_PLUGIN_DIDNT_SET_LEVEL",
};
U_CAPI const char * U_EXPORT2
u_errorName(UErrorCode code) {
if(U_ZERO_ERROR <= code && code < U_STANDARD_ERROR_LIMIT) {
return _uErrorName[code];
} else if(U_ERROR_WARNING_START <= code && code < U_ERROR_WARNING_LIMIT) {
return _uErrorInfoName[code - U_ERROR_WARNING_START];
} else if(U_PARSE_ERROR_START <= code && code < U_PARSE_ERROR_LIMIT){
return _uTransErrorName[code - U_PARSE_ERROR_START];
} else if(U_FMT_PARSE_ERROR_START <= code && code < U_FMT_PARSE_ERROR_LIMIT){
return _uFmtErrorName[code - U_FMT_PARSE_ERROR_START];
} else if (U_BRK_ERROR_START <= code && code < U_BRK_ERROR_LIMIT){
return _uBrkErrorName[code - U_BRK_ERROR_START];
} else if (U_REGEX_ERROR_START <= code && code < U_REGEX_ERROR_LIMIT) {
return _uRegexErrorName[code - U_REGEX_ERROR_START];
} else if(U_IDNA_ERROR_START <= code && code < U_IDNA_ERROR_LIMIT) {
return _uIDNAErrorName[code - U_IDNA_ERROR_START];
} else if(U_PLUGIN_ERROR_START <= code && code < U_PLUGIN_ERROR_LIMIT) {
return _uPluginErrorName[code - U_PLUGIN_ERROR_START];
} else {
return "[BOGUS UErrorCode]";
}
}
/*
* Hey, Emacs, please set the following:
*
* Local Variables:
* indent-tabs-mode: nil
* End:
*
*/
| mit |
imrandomizer/Algorithm-Implementations | Sieve_of_Eratosthenes/Ruby/mitogh/sieve.rb | 293 | def sieve(n)
primes = Array.new(n, true)
limit = Math.sqrt(n).floor
primes[0], primes[1] = nil, nil
for i in 2..limit
if primes[i]
j, k = 0, 0
while( j <= n ) do
j = i ** 2 + (k * i)
k += 1
primes[j] = nil
end
end
end
primes
end
| mit |
iamjasonp/corefx | src/System.Threading/tests/InterlockedTests.cs | 1308 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
public class InterlockedTests
{
[Fact]
public void IncrementDecrement_int()
{
List<Task> threads = new List<Task>();
int count = 0;
for (int i = 0; i < 10000; i++)
{
threads.Add(Task.Run(() => Interlocked.Increment(ref count)));
threads.Add(Task.Run(() => Interlocked.Decrement(ref count)));
}
Task.WaitAll(threads.ToArray());
Assert.Equal(0, count);
}
[Fact]
public void IncrementDecrement_long()
{
List<Task> threads = new List<Task>();
long count = 0;
for (int i = 0; i < 10000; i++)
{
threads.Add(Task.Run(() => Interlocked.Increment(ref count)));
threads.Add(Task.Run(() => Interlocked.Decrement(ref count)));
}
Task.WaitAll(threads.ToArray());
Assert.Equal(0, count);
}
}
} | mit |
bbernardoni/dolphin | Source/Core/Core/PowerPC/JitArm64/JitArm64_LoadStorePaired.cpp | 4927 | // Copyright 2015 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include "Common/Arm64Emitter.h"
#include "Common/Common.h"
#include "Common/StringUtil.h"
#include "Core/Core.h"
#include "Core/CoreTiming.h"
#include "Core/PowerPC/PowerPC.h"
#include "Core/PowerPC/PPCTables.h"
#include "Core/PowerPC/JitArm64/Jit.h"
#include "Core/PowerPC/JitArm64/JitArm64_RegCache.h"
#include "Core/PowerPC/JitArm64/JitAsm.h"
using namespace Arm64Gen;
void JitArm64::psq_l(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITLoadStorePairedOff);
FALLBACK_IF(jo.memcheck || !jo.fastmem);
// X30 is LR
// X0 contains the scale
// X1 is the address
// X2 is a temporary
// Q0 is the return register
// Q1 is a temporary
bool update = inst.OPCD == 57;
s32 offset = inst.SIMM_12;
gpr.Lock(W0, W1, W2, W30);
fpr.Lock(Q0, Q1);
ARM64Reg arm_addr = gpr.R(inst.RA);
ARM64Reg scale_reg = W0;
ARM64Reg addr_reg = W1;
ARM64Reg type_reg = W2;
ARM64Reg VS;
if (inst.RA || update) // Always uses the register on update
{
if (offset >= 0)
ADD(addr_reg, gpr.R(inst.RA), offset);
else
SUB(addr_reg, gpr.R(inst.RA), std::abs(offset));
}
else
{
MOVI2R(addr_reg, (u32)offset);
}
if (update)
{
gpr.BindToRegister(inst.RA, REG_REG);
MOV(arm_addr, addr_reg);
}
if (js.assumeNoPairedQuantize)
{
VS = fpr.RW(inst.RS, REG_REG);
if (!inst.W)
{
ADD(EncodeRegTo64(addr_reg), EncodeRegTo64(addr_reg), X28);
m_float_emit.LD1(32, 1, EncodeRegToDouble(VS), EncodeRegTo64(addr_reg));
m_float_emit.REV32(8, VS, VS);
m_float_emit.FCVTL(64, VS, VS);
}
else
{
m_float_emit.LDR(32, VS, EncodeRegTo64(addr_reg), X28);
m_float_emit.REV32(8, VS, VS);
m_float_emit.FCVT(64, 32, EncodeRegToDouble(VS), EncodeRegToDouble(VS));
}
}
else
{
LDR(INDEX_UNSIGNED, scale_reg, X29, PPCSTATE_OFF(spr[SPR_GQR0 + inst.I]));
UBFM(type_reg, scale_reg, 16, 18); // Type
UBFM(scale_reg, scale_reg, 24, 29); // Scale
MOVI2R(X30, (u64)&asm_routines.pairedLoadQuantized[inst.W * 8]);
LDR(X30, X30, ArithOption(EncodeRegTo64(type_reg), true));
BLR(X30);
VS = fpr.RW(inst.RS, REG_REG);
if (!inst.W)
m_float_emit.FCVTL(64, VS, D0);
else
m_float_emit.FCVT(64, 32, EncodeRegToDouble(VS), D0);
}
if (inst.W)
{
m_float_emit.FMOV(D0, 0x70); // 1.0 as a Double
m_float_emit.INS(64, VS, 1, Q0, 0);
}
gpr.Unlock(W0, W1, W2, W30);
fpr.Unlock(Q0, Q1);
}
void JitArm64::psq_st(UGeckoInstruction inst)
{
INSTRUCTION_START
JITDISABLE(bJITLoadStorePairedOff);
FALLBACK_IF(jo.memcheck || !jo.fastmem);
// X30 is LR
// X0 contains the scale
// X1 is the address
// Q0 is the store register
bool update = inst.OPCD == 61;
s32 offset = inst.SIMM_12;
gpr.Lock(W0, W1, W2, W30);
fpr.Lock(Q0, Q1);
ARM64Reg arm_addr = gpr.R(inst.RA);
ARM64Reg VS = fpr.R(inst.RS, REG_REG);
ARM64Reg scale_reg = W0;
ARM64Reg addr_reg = W1;
ARM64Reg type_reg = W2;
BitSet32 gprs_in_use = gpr.GetCallerSavedUsed();
BitSet32 fprs_in_use = fpr.GetCallerSavedUsed();
// Wipe the registers we are using as temporaries
gprs_in_use &= BitSet32(~7);
fprs_in_use &= BitSet32(~3);
if (inst.RA || update) // Always uses the register on update
{
if (offset >= 0)
ADD(addr_reg, gpr.R(inst.RA), offset);
else
SUB(addr_reg, gpr.R(inst.RA), std::abs(offset));
}
else
{
MOVI2R(addr_reg, (u32)offset);
}
if (update)
{
gpr.BindToRegister(inst.RA, REG_REG);
MOV(arm_addr, addr_reg);
}
if (js.assumeNoPairedQuantize)
{
u32 flags = BackPatchInfo::FLAG_STORE;
flags |= (inst.W ? BackPatchInfo::FLAG_SIZE_F32 : BackPatchInfo::FLAG_SIZE_F32X2);
EmitBackpatchRoutine(flags,
jo.fastmem,
jo.fastmem,
VS, EncodeRegTo64(addr_reg),
gprs_in_use,
fprs_in_use);
}
else
{
if (inst.W)
m_float_emit.FCVT(32, 64, D0, VS);
else
m_float_emit.FCVTN(32, D0, VS);
LDR(INDEX_UNSIGNED, scale_reg, X29, PPCSTATE_OFF(spr[SPR_GQR0 + inst.I]));
UBFM(type_reg, scale_reg, 0, 2); // Type
UBFM(scale_reg, scale_reg, 8, 13); // Scale
// Inline address check
TST(addr_reg, 6, 1);
FixupBranch pass = B(CC_EQ);
FixupBranch fail = B();
SwitchToFarCode();
SetJumpTarget(fail);
// Slow
MOVI2R(X30, (u64)&asm_routines.pairedStoreQuantized[16 + inst.W * 8]);
LDR(EncodeRegTo64(type_reg), X30, ArithOption(EncodeRegTo64(type_reg), true));
ABI_PushRegisters(gprs_in_use);
m_float_emit.ABI_PushRegisters(fprs_in_use, X30);
BLR(EncodeRegTo64(type_reg));
m_float_emit.ABI_PopRegisters(fprs_in_use, X30);
ABI_PopRegisters(gprs_in_use);
FixupBranch continue1 = B();
SwitchToNearCode();
SetJumpTarget(pass);
// Fast
MOVI2R(X30, (u64)&asm_routines.pairedStoreQuantized[inst.W * 8]);
LDR(EncodeRegTo64(type_reg), X30, ArithOption(EncodeRegTo64(type_reg), true));
BLR(EncodeRegTo64(type_reg));
SetJumpTarget(continue1);
}
gpr.Unlock(W0, W1, W2, W30);
fpr.Unlock(Q0, Q1);
}
| gpl-2.0 |
asridharan/stitch-click | tools/lib/eclasst.cc | 9455 | // -*- c-basic-offset: 4 -*-
/*
* eclasst.{cc,hh} -- tool definition of element classes
* Eddie Kohler
*
* Copyright (c) 1999-2000 Massachusetts Institute of Technology
* Copyright (c) 2000 Mazu Networks, Inc.
* Copyright (c) 2001-2003 International Computer Science Institute
*
* 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, subject to the conditions
* listed in the Click LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Click LICENSE file; the license in that file is
* legally binding.
*/
#include <click/config.h>
#include "eclasst.hh"
#include "routert.hh"
#include "elementmap.hh"
#include "processingt.hh"
#include <click/straccum.hh>
#include <click/confparse.hh>
#include <click/variableenv.hh>
#include <stdlib.h>
static HashTable<String, int> base_type_map(-1);
static Vector<ElementClassT *> base_types;
typedef ElementTraits Traits;
namespace {
class TraitsElementClassT : public ElementClassT { public:
TraitsElementClassT(const String &, int component, ...);
bool primitive() const { return false; }
const ElementTraits *find_traits(ElementMap *emap) const;
private:
ElementTraits _the_traits;
};
TraitsElementClassT::TraitsElementClassT(const String &name, int component, ...)
: ElementClassT(name)
{
*(_the_traits.component(Traits::D_CLASS)) = name;
va_list val;
va_start(val, component);
while (component > Traits::D_NONE) {
const char *x = va_arg(val, const char *);
if (String *val = _the_traits.component(component))
*val = x;
component = va_arg(val, int);
}
va_end(val);
use(); // make sure we hold onto this forever
}
const ElementTraits *
TraitsElementClassT::find_traits(ElementMap *) const
{
return &_the_traits;
}
}
ElementClassT *ElementClassT::the_tunnel_type = new TraitsElementClassT("<tunnel>", Traits::D_PROCESSING, "a/a", Traits::D_FLOW_CODE, "x/y", 0);
ElementClassT::ElementClassT(const String &name)
: _name(name),
_printable_name(name ? name : String::make_stable("<anonymous>")),
_use_count(0), _traits_version(-1)
{
//fprintf(stderr, "%p: %s\n", this, printable_name_c_str());
}
ElementClassT::~ElementClassT()
{
//fprintf(stderr, "%p: ~%s\n", this, printable_name_c_str());
}
static ElementClassT *default_base_type_factory(const String &name)
{
return new ElementClassT(name);
}
static ElementClassT *(*base_type_factory)(const String &) = default_base_type_factory;
void ElementClassT::set_base_type_factory(ElementClassT *(*f)(const String &))
{
base_type_factory = f;
}
ElementClassT *
ElementClassT::base_type(const String &name)
{
if (!name)
return 0;
int &i = base_type_map[name];
if (i < 0) {
i = base_types.size();
ElementClassT *t = base_type_factory(name);
assert(t && t->name() == name);
t->use();
base_types.push_back(t);
}
return base_types[i];
}
ElementTraits &
ElementClassT::force_traits(ElementMap *emap) const
{
ElementTraits &traits = emap->force_traits(_name);
_traits = &traits;
_traits_version = emap->version();
return traits;
}
const ElementTraits *
ElementClassT::find_traits(ElementMap *emap) const
{
return &emap->traits(_name);
}
const String &
ElementClassT::package() const
{
return ElementMap::default_map()->package(traits());
}
String
ElementClassT::documentation_url() const
{
return ElementMap::default_map()->documentation_url(traits());
}
bool
ElementClassT::need_resolve() const
{
return false;
}
ElementClassT *
ElementClassT::resolve(int, int, Vector<String> &, ErrorHandler *, const LandmarkT &)
{
return this;
}
void
ElementClassT::create_scope(const Vector<String> &, const VariableEnvironment &, VariableEnvironment &)
{
}
ElementT *
ElementClassT::direct_expand_element(
ElementT *e, RouterT *tor, const String &prefix,
const VariableEnvironment &env, ErrorHandler *errh)
{
assert(!prefix || prefix.back() == '/');
RouterT *fromr = e->router();
String new_name = prefix + e->name();
String new_configuration = cp_expand(e->configuration(), env);
// check for tunnel
if (e->tunnel()) {
assert(this == ElementClassT::tunnel_type());
// common case -- expanding router into itself
if (fromr == tor && !prefix)
return e;
// make the tunnel or tunnel pair
if (e->tunnel_output()) {
tor->add_tunnel(new_name,
prefix + e->tunnel_output()->name(),
e->landmarkt(), errh);
return tor->element(new_name);
} else
return tor->get_element
(new_name, e->type(), new_configuration, e->landmarkt());
}
// otherwise, not tunnel
// check for common case -- expanding router into itself
if (fromr == tor && !prefix) {
e->set_configuration(new_configuration);
e->set_type(this);
return e;
}
// check for old element
if (ElementT *new_e = tor->element(new_name))
ElementT::redeclaration_error(errh, "element", new_name, e->landmark(), new_e->landmark());
// add element
return tor->get_element(new_name, this, new_configuration, e->landmarkt());
}
ElementT *
ElementClassT::expand_element(
ElementT *e, RouterT *tor, const String &prefix,
const VariableEnvironment &env, ErrorHandler *errh)
{
ElementClassT *c = e->type();
if (c->primitive())
return c->direct_expand_element(e, tor, prefix, env, errh);
// if not direct expansion, do some more work
int inputs_used = e->ninputs();
int outputs_used = e->noutputs();
RouterT *fromr = e->router();
Vector<String> args;
String new_configuration = cp_expand(e->configuration(), env);
cp_argvec(new_configuration, args);
ElementClassT *found_c = c->resolve(inputs_used, outputs_used, args, errh, e->landmarkt());
if (!found_c) { // destroy element
if (fromr == tor)
e->kill();
return 0;
}
return found_c->complex_expand_element(e, args, tor, prefix, env, errh);
}
ElementT *
ElementClassT::complex_expand_element(
ElementT *e, const Vector<String> &,
RouterT *tor, const String &prefix,
const VariableEnvironment &env, ErrorHandler *errh)
{
return direct_expand_element(e, tor, prefix, env, errh);
}
String
ElementClassT::unparse_signature(const String &name, const Vector<String> *formal_types, int nargs, int ninputs, int noutputs)
{
StringAccum sa;
sa << (name ? name : String("<anonymous>"));
if (formal_types && formal_types->size()) {
sa << '(';
for (int i = 0; i < formal_types->size(); i++) {
if (i)
sa << ", ";
if ((*formal_types)[i] == "")
sa << "<arg>";
else if ((*formal_types)[i] == "__REST__")
sa << "...";
else
sa << (*formal_types)[i];
}
sa << ')';
}
const char *pl_args = (nargs == 1 ? " argument, " : " arguments, ");
const char *pl_ins = (ninputs == 1 ? " input, " : " inputs, ");
const char *pl_outs = (noutputs == 1 ? " output" : " outputs");
sa << '[';
if (!formal_types && nargs > 0)
sa << nargs << pl_args;
sa << ninputs << pl_ins << noutputs << pl_outs;
sa << ']';
return sa.take_string();
}
SynonymElementClassT::SynonymElementClassT(const String &name, ElementClassT *eclass, RouterT *declaration_scope)
: ElementClassT(name), _eclass(eclass), _declaration_scope(declaration_scope)
{
assert(eclass);
}
bool
SynonymElementClassT::need_resolve() const
{
return true;
}
ElementClassT *
SynonymElementClassT::resolve(int ninputs, int noutputs, Vector<String> &args, ErrorHandler *errh, const LandmarkT &landmark)
{
return _eclass->resolve(ninputs, noutputs, args, errh, landmark);
}
void
SynonymElementClassT::create_scope(const Vector<String> &, const VariableEnvironment &, VariableEnvironment &)
{
assert(0);
}
ElementT *
SynonymElementClassT::complex_expand_element(
ElementT *, const Vector<String> &,
RouterT *, const String &, const VariableEnvironment &, ErrorHandler *)
{
assert(0);
return 0;
}
const ElementTraits *
SynonymElementClassT::find_traits(ElementMap *emap) const
{
return _eclass->find_traits(emap);
}
RouterT *
SynonymElementClassT::cast_router()
{
return _eclass->cast_router();
}
RouterT *
ElementClassT::declaration_scope() const
{
return 0;
}
RouterT *
SynonymElementClassT::declaration_scope() const
{
return _declaration_scope;
}
ElementClassT *
ElementClassT::overload_type() const
{
return 0;
}
String
ElementClassT::unparse_signature() const
{
return name() + "[...]";
}
void
ElementClassT::collect_types(HashTable<ElementClassT *, int> &m) const
{
m.set(const_cast<ElementClassT *>(this), 1);
}
void
SynonymElementClassT::collect_types(HashTable<ElementClassT *, int> &m) const
{
HashTable<ElementClassT *, int>::iterator it = m.find_insert(const_cast<SynonymElementClassT *>(this), 0);
if (it != m.end() && it.value() == 0) {
it.value() = 1;
_eclass->collect_types(m);
}
}
void
ElementClassT::collect_overloads(Vector<ElementClassT *> &v) const
{
v.push_back(const_cast<ElementClassT *>(this));
}
void
SynonymElementClassT::collect_overloads(Vector<ElementClassT *> &v) const
{
_eclass->collect_overloads(v);
}
| gpl-2.0 |
benwa/librenms | vendor/amenadiel/jpgraph/Examples/examples_theme/softy_example.php | 1793 | <?php
require_once 'jpgraph/jpgraph.php';
require_once 'jpgraph/jpgraph_bar.php';
require_once 'jpgraph/jpgraph_line.php';
$theme = isset($_GET['theme']) ? $_GET['theme'] : null;
$data = array(
0 => array(0 => 79, 1 => -25, 2 => -7, 3 => 85, 4 => -26, 5 => -32),
1 => array(0 => 76, 1 => 51, 2 => 86, 3 => 12, 4 => -7, 5 => 94),
2 => array(0 => 49, 1 => 38, 2 => 7, 3 => -40, 4 => 9, 5 => -7),
3 => array(0 => 69, 1 => 96, 2 => 49, 3 => 7, 4 => 92, 5 => -38),
4 => array(0 => 68, 1 => 16, 2 => 82, 3 => -49, 4 => 50, 5 => 7),
5 => array(0 => -37, 1 => 28, 2 => 32, 3 => 6, 4 => 13, 5 => 57),
6 => array(0 => 24, 1 => -11, 2 => 7, 3 => 10, 4 => 51, 5 => 51),
7 => array(0 => 3, 1 => -1, 2 => -12, 3 => 61, 4 => 10, 5 => 47),
8 => array(0 => -47, 1 => -21, 2 => 43, 3 => 53, 4 => 36, 5 => 34),
);
// Create the graph. These two calls are always required
$graph = new Graph\Graph(400, 300);
$graph->SetScale("textlin");
if ($theme) {
$graph->SetTheme(new $theme());
}
$theme_class = new SoftyTheme;
$graph->SetTheme($theme_class);
$plot = array();
// Create the bar plots
for ($i = 0; $i < 4; $i++) {
$plot[$i] = new Plot\BarPlot($data[$i]);
$plot[$i]->SetLegend('plot' . ($i + 1));
}
//$acc1 = new Plot\AccBarPlot(array($plot[0], $plot[1]));
//$acc1->value->Show();
$gbplot = new Plot\GroupBarPlot(array($plot[2], $plot[1]));
for ($i = 4; $i < 8; $i++) {
$plot[$i] = new Plot\LinePlot($data[$i]);
$plot[$i]->SetLegend('plot' . $i);
$plot[$i]->value->Show();
}
$graph->Add($gbplot);
$graph->Add($plot[4]);
$title = "SoftyTheme Example";
$title = mb_convert_encoding($title, 'UTF-8');
$graph->title->Set($title);
$graph->xaxis->title->Set("X-title");
$graph->yaxis->title->Set("Y-title");
// Display the graph
$graph->Stroke();
| gpl-3.0 |
together-web-pj/together-web-pj | node_modules/faker/lib/locales/tr/phone_number/formats.js | 70 | module["exports"] = [
"+90-###-###-##-##",
"+90-###-###-#-###"
];
| gpl-3.0 |
lopezloo/mtasa-blue | vendor/google-breakpad/src/common/solaris/guid_creator.cc | 2965 | // Copyright (c) 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * 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.
// Author: Alfred Peng
#include <cassert>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "common/solaris/guid_creator.h"
//
// GUIDGenerator
//
// This class is used to generate random GUID.
// Currently use random number to generate a GUID. This should be OK since
// we don't expect crash to happen very offen.
//
class GUIDGenerator {
public:
GUIDGenerator() {
srandom(time(NULL));
}
bool CreateGUID(GUID *guid) const {
guid->data1 = random();
guid->data2 = (uint16_t)(random());
guid->data3 = (uint16_t)(random());
*reinterpret_cast<uint32_t*>(&guid->data4[0]) = random();
*reinterpret_cast<uint32_t*>(&guid->data4[4]) = random();
return true;
}
};
// Guid generator.
const GUIDGenerator kGuidGenerator;
bool CreateGUID(GUID *guid) {
return kGuidGenerator.CreateGUID(guid);
}
// Parse guid to string.
bool GUIDToString(const GUID *guid, char *buf, int buf_len) {
// Should allow more space the the max length of GUID.
assert(buf_len > kGUIDStringLength);
int num = snprintf(buf, buf_len, kGUIDFormatString,
guid->data1, guid->data2, guid->data3,
*reinterpret_cast<const uint32_t *>(&(guid->data4[0])),
*reinterpret_cast<const uint32_t *>(&(guid->data4[4])));
if (num != kGUIDStringLength)
return false;
buf[num] = '\0';
return true;
}
| gpl-3.0 |
PangZhi/flink | flink-libraries/flink-gelly/src/main/java/org/apache/flink/graph/pregel/ComputeFunction.java | 8797 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.graph.pregel;
import org.apache.flink.api.common.aggregators.Aggregator;
import org.apache.flink.api.common.functions.IterationRuntimeContext;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.graph.Edge;
import org.apache.flink.graph.Vertex;
import org.apache.flink.types.Either;
import org.apache.flink.types.Value;
import org.apache.flink.util.Collector;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
/**
* The base class for the message-passing functions between vertices as a part of a {@link VertexCentricIteration}.
*
* @param <K> The type of the vertex key (the vertex identifier).
* @param <VV> The type of the vertex value (the state of the vertex).
* @param <EV> The type of the values that are associated with the edges.
* @param <Message> The type of the message sent between vertices along the edges.
*/
public abstract class ComputeFunction<K, VV, EV, Message> implements Serializable {
private static final long serialVersionUID = 1L;
// --------------------------------------------------------------------------------------------
// Public API Methods
// --------------------------------------------------------------------------------------------
/**
* This method is invoked once per superstep, for each active vertex.
* A vertex is active during a superstep, if at least one message was produced for it,
* in the previous superstep. During the first superstep, all vertices are active.
*
* <p>This method can iterate over all received messages, set the new vertex value, and
* send messages to other vertices (which will be delivered in the next superstep).
*
* @param vertex The vertex executing this function
* @param messages The messages that were sent to this vertex in the previous superstep
* @throws Exception
*/
public abstract void compute(Vertex<K, VV> vertex, MessageIterator<Message> messages) throws Exception;
/**
* This method is executed once per superstep before the vertex update function is invoked for each vertex.
*
* @throws Exception Exceptions in the pre-superstep phase cause the superstep to fail.
*/
public void preSuperstep() throws Exception {}
/**
* This method is executed once per superstep after the vertex update function has been invoked for each vertex.
*
* @throws Exception Exceptions in the post-superstep phase cause the superstep to fail.
*/
public void postSuperstep() throws Exception {}
/**
* Gets an {@link java.lang.Iterable} with all out-going edges. This method is mutually exclusive with
* {@link #sendMessageToAllNeighbors(Object)} and may be called only once.
*
* @return An iterator with all edges.
*/
public final Iterable<Edge<K, EV>> getEdges() {
verifyEdgeUsage();
this.edgeIterator.set(edges);
return this.edgeIterator;
}
/**
* Sends the given message to all vertices that adjacent to the changed vertex.
* This method is mutually exclusive to the method {@link #getEdges()} and may be called only once.
*
* @param m The message to send.
*/
public final void sendMessageToAllNeighbors(Message m) {
verifyEdgeUsage();
outMsg.f1 = m;
while (edges.hasNext()) {
Tuple next = edges.next();
outMsg.f0 = next.getField(1);
out.collect(Either.Right(outMsg));
}
}
/**
* Sends the given message to the vertex identified by the given key. If the target vertex does not exist,
* the next superstep will cause an exception due to a non-deliverable message.
*
* @param target The key (id) of the target vertex to message.
* @param m The message.
*/
public final void sendMessageTo(K target, Message m) {
outMsg.f0 = target;
outMsg.f1 = m;
out.collect(Either.Right(outMsg));
}
/**
* Sets the new value of this vertex.
*
* <p>This should be called at most once per ComputeFunction.
*
* @param newValue The new vertex value.
*/
public final void setNewVertexValue(VV newValue) {
if (setNewVertexValueCalled) {
throw new IllegalStateException("setNewVertexValue should only be called at most once per updateVertex");
}
setNewVertexValueCalled = true;
outVertex.f1 = newValue;
out.collect(Either.Left(outVertex));
}
// --------------------------------------------------------------------------------------------
/**
* Gets the number of the superstep, starting at <tt>1</tt>.
*
* @return The number of the current superstep.
*/
public final int getSuperstepNumber() {
return this.runtimeContext.getSuperstepNumber();
}
/**
* Gets the iteration aggregator registered under the given name. The iteration aggregator combines
* all aggregates globally once per superstep and makes them available in the next superstep.
*
* @param name The name of the aggregator.
* @return The aggregator registered under this name, or {@code null}, if no aggregator was registered.
*/
public final <T extends Aggregator<?>> T getIterationAggregator(String name) {
return this.runtimeContext.getIterationAggregator(name);
}
/**
* Get the aggregated value that an aggregator computed in the previous iteration.
*
* @param name The name of the aggregator.
* @return The aggregated value of the previous iteration.
*/
public final <T extends Value> T getPreviousIterationAggregate(String name) {
return this.runtimeContext.getPreviousIterationAggregate(name);
}
/**
* Gets the broadcast data set registered under the given name. Broadcast data sets
* are available on all parallel instances of a function. They can be registered via
* {@link org.apache.flink.graph.pregel.VertexCentricConfiguration#addBroadcastSet(String, DataSet)}.
*
* @param name The name under which the broadcast set is registered.
* @return The broadcast data set.
*/
public final <T> Collection<T> getBroadcastSet(String name) {
return this.runtimeContext.getBroadcastVariable(name);
}
// --------------------------------------------------------------------------------------------
// internal methods and state
// --------------------------------------------------------------------------------------------
private Vertex<K, VV> outVertex;
private Tuple2<K, Message> outMsg;
private IterationRuntimeContext runtimeContext;
private Iterator<Edge<K, EV>> edges;
private Collector<Either<?, ?>> out;
private EdgesIterator<K, EV> edgeIterator;
private boolean edgesUsed;
private boolean setNewVertexValueCalled;
void init(IterationRuntimeContext context) {
this.runtimeContext = context;
this.outVertex = new Vertex<>();
this.outMsg = new Tuple2<>();
this.edgeIterator = new EdgesIterator<>();
}
@SuppressWarnings("unchecked")
void set(K vertexId, Iterator<Edge<K, EV>> edges,
Collector<Either<Vertex<K, VV>, Tuple2<K, Message>>> out) {
this.outVertex.f0 = vertexId;
this.edges = edges;
this.out = (Collector<Either<?, ?>>) (Collector<?>) out;
this.edgesUsed = false;
setNewVertexValueCalled = false;
}
private void verifyEdgeUsage() throws IllegalStateException {
if (edgesUsed) {
throw new IllegalStateException(
"Can use either 'getEdges()' or 'sendMessageToAllNeighbors()' exactly once.");
}
edgesUsed = true;
}
private static final class EdgesIterator<K, EV>
implements Iterator<Edge<K, EV>>, Iterable<Edge<K, EV>> {
private Iterator<Edge<K, EV>> input;
private Edge<K, EV> edge = new Edge<>();
void set(Iterator<Edge<K, EV>> input) {
this.input = input;
}
@Override
public boolean hasNext() {
return input.hasNext();
}
@Override
public Edge<K, EV> next() {
Edge<K, EV> next = input.next();
edge.setSource(next.f0);
edge.setTarget(next.f1);
edge.setValue(next.f2);
return edge;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Iterator<Edge<K, EV>> iterator() {
return this;
}
}
}
| apache-2.0 |
mive93/Smemorata | JLayer1.0.1/src/javazoom/jl/converter/RiffFile.java | 12752 | /*
* 11/19/04 1.0 moved to LGPL.
* 02/23/99 JavaConversion by E.B
* Don Cross, April 1993.
* RIFF file format classes.
* See Chapter 8 of "Multimedia Programmer's Reference" in
* the Microsoft Windows SDK.
*
*-----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*----------------------------------------------------------------------
*/
package javazoom.jl.converter;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* Class to manage RIFF files
*/
public class RiffFile
{
class RiffChunkHeader
{
public int ckID = 0; // Four-character chunk ID
public int ckSize = 0; // Length of data in chunk
public RiffChunkHeader()
{}
}
// DDCRET
public static final int DDC_SUCCESS = 0; // The operation succeded
public static final int DDC_FAILURE = 1; // The operation failed for unspecified reasons
public static final int DDC_OUT_OF_MEMORY = 2; // Operation failed due to running out of memory
public static final int DDC_FILE_ERROR = 3; // Operation encountered file I/O error
public static final int DDC_INVALID_CALL = 4; // Operation was called with invalid parameters
public static final int DDC_USER_ABORT = 5; // Operation was aborted by the user
public static final int DDC_INVALID_FILE = 6; // File format does not match
// RiffFileMode
public static final int RFM_UNKNOWN = 0; // undefined type (can use to mean "N/A" or "not open")
public static final int RFM_WRITE = 1; // open for write
public static final int RFM_READ = 2; // open for read
private RiffChunkHeader riff_header; // header for whole file
protected int fmode; // current file I/O mode
protected RandomAccessFile file; // I/O stream to use
/**
* Dummy Constructor
*/
public RiffFile()
{
file = null;
fmode = RFM_UNKNOWN;
riff_header = new RiffChunkHeader();
riff_header.ckID = FourCC("RIFF");
riff_header.ckSize = 0;
}
/**
* Return File Mode.
*/
public int CurrentFileMode()
{return fmode;}
/**
* Open a RIFF file.
*/
public int Open(String Filename, int NewMode)
{
int retcode = DDC_SUCCESS;
if ( fmode != RFM_UNKNOWN )
{
retcode = Close();
}
if ( retcode == DDC_SUCCESS )
{
switch ( NewMode )
{
case RFM_WRITE:
try
{
file = new RandomAccessFile(Filename,"rw");
try
{
// Write the RIFF header...
// We will have to come back later and patch it!
byte[] br = new byte[8];
br[0] = (byte) ((riff_header.ckID >>> 24) & 0x000000FF);
br[1] = (byte) ((riff_header.ckID >>> 16) & 0x000000FF);
br[2] = (byte) ((riff_header.ckID >>> 8) & 0x000000FF);
br[3] = (byte) (riff_header.ckID & 0x000000FF);
byte br4 = (byte) ((riff_header.ckSize >>> 24)& 0x000000FF);
byte br5 = (byte) ((riff_header.ckSize >>> 16)& 0x000000FF);
byte br6 = (byte) ((riff_header.ckSize >>> 8)& 0x000000FF);
byte br7 = (byte) (riff_header.ckSize & 0x000000FF);
br[4] = br7;
br[5] = br6;
br[6] = br5;
br[7] = br4;
file.write(br,0,8);
fmode = RFM_WRITE;
} catch (IOException ioe)
{
file.close();
fmode = RFM_UNKNOWN;
}
} catch (IOException ioe)
{
fmode = RFM_UNKNOWN;
retcode = DDC_FILE_ERROR;
}
break;
case RFM_READ:
try
{
file = new RandomAccessFile(Filename,"r");
try
{
// Try to read the RIFF header...
byte[] br = new byte[8];
file.read(br,0,8);
fmode = RFM_READ;
riff_header.ckID = ((br[0]<<24)& 0xFF000000) | ((br[1]<<16)&0x00FF0000) | ((br[2]<<8)&0x0000FF00) | (br[3]&0x000000FF);
riff_header.ckSize = ((br[4]<<24)& 0xFF000000) | ((br[5]<<16)&0x00FF0000) | ((br[6]<<8)&0x0000FF00) | (br[7]&0x000000FF);
} catch (IOException ioe)
{
file.close();
fmode = RFM_UNKNOWN;
}
} catch (IOException ioe)
{
fmode = RFM_UNKNOWN;
retcode = DDC_FILE_ERROR;
}
break;
default:
retcode = DDC_INVALID_CALL;
}
}
return retcode;
}
/**
* Write NumBytes data.
*/
public int Write(byte[] Data, int NumBytes )
{
if ( fmode != RFM_WRITE )
{
return DDC_INVALID_CALL;
}
try
{
file.write(Data,0,NumBytes);
fmode = RFM_WRITE;
}
catch (IOException ioe)
{
return DDC_FILE_ERROR;
}
riff_header.ckSize += NumBytes;
return DDC_SUCCESS;
}
/**
* Write NumBytes data.
*/
public int Write(short[] Data, int NumBytes )
{
byte[] theData = new byte[NumBytes];
int yc = 0;
for (int y = 0;y<NumBytes;y=y+2)
{
theData[y] = (byte) (Data[yc] & 0x00FF);
theData[y+1] =(byte) ((Data[yc++] >>> 8) & 0x00FF);
}
if ( fmode != RFM_WRITE )
{
return DDC_INVALID_CALL;
}
try
{
file.write(theData,0,NumBytes);
fmode = RFM_WRITE;
}
catch (IOException ioe)
{
return DDC_FILE_ERROR;
}
riff_header.ckSize += NumBytes;
return DDC_SUCCESS;
}
/**
* Write NumBytes data.
*/
public int Write(RiffChunkHeader Triff_header, int NumBytes )
{
byte[] br = new byte[8];
br[0] = (byte) ((Triff_header.ckID >>> 24) & 0x000000FF);
br[1] = (byte) ((Triff_header.ckID >>> 16) & 0x000000FF);
br[2] = (byte) ((Triff_header.ckID >>> 8) & 0x000000FF);
br[3] = (byte) (Triff_header.ckID & 0x000000FF);
byte br4 = (byte) ((Triff_header.ckSize >>> 24)& 0x000000FF);
byte br5 = (byte) ((Triff_header.ckSize >>> 16)& 0x000000FF);
byte br6 = (byte) ((Triff_header.ckSize >>> 8)& 0x000000FF);
byte br7 = (byte) (Triff_header.ckSize & 0x000000FF);
br[4] = br7;
br[5] = br6;
br[6] = br5;
br[7] = br4;
if ( fmode != RFM_WRITE )
{
return DDC_INVALID_CALL;
}
try
{
file.write(br,0,NumBytes);
fmode = RFM_WRITE;
} catch (IOException ioe)
{
return DDC_FILE_ERROR;
}
riff_header.ckSize += NumBytes;
return DDC_SUCCESS;
}
/**
* Write NumBytes data.
*/
public int Write(short Data, int NumBytes )
{
short theData = (short) ( ((Data>>>8)&0x00FF) | ((Data<<8)&0xFF00) );
if ( fmode != RFM_WRITE )
{
return DDC_INVALID_CALL;
}
try
{
file.writeShort(theData);
fmode = RFM_WRITE;
} catch (IOException ioe)
{
return DDC_FILE_ERROR;
}
riff_header.ckSize += NumBytes;
return DDC_SUCCESS;
}
/**
* Write NumBytes data.
*/
public int Write(int Data, int NumBytes )
{
short theDataL = (short) ((Data>>>16)&0x0000FFFF);
short theDataR = (short) (Data&0x0000FFFF);
short theDataLI = (short) ( ((theDataL>>>8)&0x00FF) | ((theDataL<<8)&0xFF00) );
short theDataRI = (short) ( ((theDataR>>>8)&0x00FF) | ((theDataR<<8)&0xFF00) );
int theData = ((theDataRI<<16)&0xFFFF0000) | (theDataLI&0x0000FFFF);
if ( fmode != RFM_WRITE )
{
return DDC_INVALID_CALL;
}
try
{
file.writeInt(theData);
fmode = RFM_WRITE;
} catch (IOException ioe)
{
return DDC_FILE_ERROR;
}
riff_header.ckSize += NumBytes;
return DDC_SUCCESS;
}
/**
* Read NumBytes data.
*/
public int Read (byte[] Data, int NumBytes)
{
int retcode = DDC_SUCCESS;
try
{
file.read(Data,0,NumBytes);
} catch (IOException ioe)
{
retcode = DDC_FILE_ERROR;
}
return retcode;
}
/**
* Expect NumBytes data.
*/
public int Expect(String Data, int NumBytes )
{
byte target = 0;
int cnt = 0;
try
{
while ((NumBytes--) != 0)
{
target = file.readByte();
if (target != Data.charAt(cnt++)) return DDC_FILE_ERROR;
}
} catch (IOException ioe)
{
return DDC_FILE_ERROR;
}
return DDC_SUCCESS;
}
/**
* Close Riff File.
* Length is written too.
*/
public int Close()
{
int retcode = DDC_SUCCESS;
switch ( fmode )
{
case RFM_WRITE:
try
{
file.seek(0);
try
{
byte[] br = new byte[8];
br[0] = (byte) ((riff_header.ckID >>> 24) & 0x000000FF);
br[1] = (byte) ((riff_header.ckID >>> 16) & 0x000000FF);
br[2] = (byte) ((riff_header.ckID >>> 8) & 0x000000FF);
br[3] = (byte) (riff_header.ckID & 0x000000FF);
br[7] = (byte) ((riff_header.ckSize >>> 24)& 0x000000FF);
br[6] = (byte) ((riff_header.ckSize >>> 16)& 0x000000FF);
br[5] = (byte) ((riff_header.ckSize >>> 8)& 0x000000FF);
br[4] = (byte) (riff_header.ckSize & 0x000000FF);
file.write(br,0,8);
file.close();
} catch (IOException ioe)
{
retcode = DDC_FILE_ERROR;
}
} catch (IOException ioe)
{
retcode = DDC_FILE_ERROR;
}
break;
case RFM_READ:
try
{
file.close();
} catch (IOException ioe)
{
retcode = DDC_FILE_ERROR;
}
break;
}
file = null;
fmode = RFM_UNKNOWN;
return retcode;
}
/**
* Return File Position.
*/
public long CurrentFilePosition()
{
long position;
try
{
position = file.getFilePointer();
} catch (IOException ioe)
{
position = -1;
}
return position;
}
/**
* Write Data to specified offset.
*/
public int Backpatch (long FileOffset, RiffChunkHeader Data, int NumBytes )
{
if (file == null)
{
return DDC_INVALID_CALL;
}
try
{
file.seek(FileOffset);
} catch (IOException ioe)
{
return DDC_FILE_ERROR;
}
return Write ( Data, NumBytes );
}
public int Backpatch (long FileOffset, byte[] Data, int NumBytes )
{
if (file == null)
{
return DDC_INVALID_CALL;
}
try
{
file.seek(FileOffset);
} catch (IOException ioe)
{
return DDC_FILE_ERROR;
}
return Write ( Data, NumBytes );
}
/**
* Seek in the File.
*/
protected int Seek(long offset)
{
int rc;
try
{
file.seek(offset);
rc = DDC_SUCCESS;
} catch (IOException ioe)
{
rc = DDC_FILE_ERROR;
}
return rc;
}
/**
* Error Messages.
*/
private String DDCRET_String(int retcode)
{
switch ( retcode )
{
case DDC_SUCCESS: return "DDC_SUCCESS";
case DDC_FAILURE: return "DDC_FAILURE";
case DDC_OUT_OF_MEMORY: return "DDC_OUT_OF_MEMORY";
case DDC_FILE_ERROR: return "DDC_FILE_ERROR";
case DDC_INVALID_CALL: return "DDC_INVALID_CALL";
case DDC_USER_ABORT: return "DDC_USER_ABORT";
case DDC_INVALID_FILE: return "DDC_INVALID_FILE";
}
return "Unknown Error";
}
/**
* Fill the header.
*/
public static int FourCC(String ChunkName)
{
byte[] p = {0x20,0x20,0x20,0x20};
ChunkName.getBytes(0,4,p,0);
int ret = (((p[0] << 24)& 0xFF000000) | ((p[1] << 16)&0x00FF0000) | ((p[2] << 8)&0x0000FF00) | (p[3]&0x000000FF));
return ret;
}
}
| apache-2.0 |
bemosior/CaptiveResponse | lib/Cake/Test/Case/Model/ModelTestBase.php | 3500 | <?php
/**
* ModelTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Model
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Model', 'Model');
App::uses('AppModel', 'Model');
require_once dirname(__FILE__) . DS . 'models.php';
/**
* ModelBaseTest
*
* @package Cake.Test.Case.Model
*/
abstract class BaseModelTest extends CakeTestCase {
/**
* autoFixtures property
*
* @var boolean
*/
public $autoFixtures = false;
/**
* Whether backup global state for each test method or not
*
* @var boolean
*/
public $backupGlobals = false;
/**
* fixtures property
*
* @var array
*/
public $fixtures = array(
'core.category', 'core.category_thread', 'core.user', 'core.my_category', 'core.my_product',
'core.my_user', 'core.my_categories_my_users', 'core.my_categories_my_products',
'core.article', 'core.featured', 'core.article_featureds_tags', 'core.article_featured',
'core.numeric_article', 'core.tag', 'core.articles_tag', 'core.comment',
'core.attachment', 'core.apple', 'core.sample', 'core.another_article', 'core.item',
'core.advertisement', 'core.home', 'core.post', 'core.author', 'core.bid', 'core.portfolio',
'core.product', 'core.project', 'core.thread', 'core.message', 'core.items_portfolio',
'core.syfile', 'core.image', 'core.device_type', 'core.device_type_category',
'core.feature_set', 'core.exterior_type_category', 'core.document', 'core.device',
'core.document_directory', 'core.primary_model', 'core.secondary_model', 'core.something',
'core.something_else', 'core.join_thing', 'core.join_a', 'core.join_b', 'core.join_c',
'core.join_a_b', 'core.join_a_c', 'core.uuid', 'core.data_test', 'core.posts_tag',
'core.the_paper_monkies', 'core.person', 'core.underscore_field', 'core.node',
'core.dependency', 'core.story', 'core.stories_tag', 'core.cd', 'core.book', 'core.basket',
'core.overall_favorite', 'core.account', 'core.content', 'core.content_account',
'core.film_file', 'core.test_plugin_article', 'core.test_plugin_comment', 'core.uuiditem',
'core.counter_cache_user', 'core.counter_cache_post',
'core.counter_cache_user_nonstandard_primary_key',
'core.counter_cache_post_nonstandard_primary_key', 'core.uuidportfolio',
'core.uuiditems_uuidportfolio', 'core.uuiditems_uuidportfolio_numericid', 'core.fruit',
'core.fruits_uuid_tag', 'core.uuid_tag', 'core.product_update_all', 'core.group_update_all',
'core.player', 'core.guild', 'core.guilds_player', 'core.armor', 'core.armors_player',
'core.bidding', 'core.bidding_message', 'core.site', 'core.domain', 'core.domains_site',
);
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->debug = Configure::read('debug');
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
Configure::write('debug', $this->debug);
ClassRegistry::flush();
}
}
| apache-2.0 |
ASMlover/study | 3rdparty/boost/include/boost/math/special_functions/detail/lgamma_small.hpp | 23234 | // (C) Copyright John Maddock 2006.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_MATH_SPECIAL_FUNCTIONS_DETAIL_LGAMMA_SMALL
#define BOOST_MATH_SPECIAL_FUNCTIONS_DETAIL_LGAMMA_SMALL
#ifdef _MSC_VER
#pragma once
#endif
#include <boost/math/tools/big_constant.hpp>
#if defined(__GNUC__) && defined(BOOST_MATH_USE_FLOAT128)
//
// This is the only way we can avoid
// warning: non-standard suffix on floating constant [-Wpedantic]
// when building with -Wall -pedantic. Neither __extension__
// nor #pragma dianostic ignored work :(
//
#pragma GCC system_header
#endif
namespace boost{ namespace math{ namespace detail{
//
// These need forward declaring to keep GCC happy:
//
template <class T, class Policy, class Lanczos>
T gamma_imp(T z, const Policy& pol, const Lanczos& l);
template <class T, class Policy>
T gamma_imp(T z, const Policy& pol, const lanczos::undefined_lanczos& l);
//
// lgamma for small arguments:
//
template <class T, class Policy, class Lanczos>
T lgamma_small_imp(T z, T zm1, T zm2, const mpl::int_<64>&, const Policy& /* l */, const Lanczos&)
{
// This version uses rational approximations for small
// values of z accurate enough for 64-bit mantissas
// (80-bit long doubles), works well for 53-bit doubles as well.
// Lanczos is only used to select the Lanczos function.
BOOST_MATH_STD_USING // for ADL of std names
T result = 0;
if(z < tools::epsilon<T>())
{
result = -log(z);
}
else if((zm1 == 0) || (zm2 == 0))
{
// nothing to do, result is zero....
}
else if(z > 2)
{
//
// Begin by performing argument reduction until
// z is in [2,3):
//
if(z >= 3)
{
do
{
z -= 1;
zm2 -= 1;
result += log(z);
}while(z >= 3);
// Update zm2, we need it below:
zm2 = z - 2;
}
//
// Use the following form:
//
// lgamma(z) = (z-2)(z+1)(Y + R(z-2))
//
// where R(z-2) is a rational approximation optimised for
// low absolute error - as long as it's absolute error
// is small compared to the constant Y - then any rounding
// error in it's computation will get wiped out.
//
// R(z-2) has the following properties:
//
// At double: Max error found: 4.231e-18
// At long double: Max error found: 1.987e-21
// Maximum Deviation Found (approximation error): 5.900e-24
//
static const T P[] = {
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.180355685678449379109e-1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.25126649619989678683e-1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.494103151567532234274e-1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.172491608709613993966e-1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.259453563205438108893e-3)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.541009869215204396339e-3)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.324588649825948492091e-4))
};
static const T Q[] = {
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.1e1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.196202987197795200688e1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.148019669424231326694e1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.541391432071720958364e0)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.988504251128010129477e-1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.82130967464889339326e-2)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.224936291922115757597e-3)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.223352763208617092964e-6))
};
static const float Y = 0.158963680267333984375e0f;
T r = zm2 * (z + 1);
T R = tools::evaluate_polynomial(P, zm2);
R /= tools::evaluate_polynomial(Q, zm2);
result += r * Y + r * R;
}
else
{
//
// If z is less than 1 use recurrance to shift to
// z in the interval [1,2]:
//
if(z < 1)
{
result += -log(z);
zm2 = zm1;
zm1 = z;
z += 1;
}
//
// Two approximations, on for z in [1,1.5] and
// one for z in [1.5,2]:
//
if(z <= 1.5)
{
//
// Use the following form:
//
// lgamma(z) = (z-1)(z-2)(Y + R(z-1))
//
// where R(z-1) is a rational approximation optimised for
// low absolute error - as long as it's absolute error
// is small compared to the constant Y - then any rounding
// error in it's computation will get wiped out.
//
// R(z-1) has the following properties:
//
// At double precision: Max error found: 1.230011e-17
// At 80-bit long double precision: Max error found: 5.631355e-21
// Maximum Deviation Found: 3.139e-021
// Expected Error Term: 3.139e-021
//
static const float Y = 0.52815341949462890625f;
static const T P[] = {
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.490622454069039543534e-1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.969117530159521214579e-1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.414983358359495381969e0)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.406567124211938417342e0)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.158413586390692192217e0)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.240149820648571559892e-1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.100346687696279557415e-2))
};
static const T Q[] = {
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.1e1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.302349829846463038743e1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.348739585360723852576e1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.191415588274426679201e1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.507137738614363510846e0)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.577039722690451849648e-1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.195768102601107189171e-2))
};
T r = tools::evaluate_polynomial(P, zm1) / tools::evaluate_polynomial(Q, zm1);
T prefix = zm1 * zm2;
result += prefix * Y + prefix * r;
}
else
{
//
// Use the following form:
//
// lgamma(z) = (2-z)(1-z)(Y + R(2-z))
//
// where R(2-z) is a rational approximation optimised for
// low absolute error - as long as it's absolute error
// is small compared to the constant Y - then any rounding
// error in it's computation will get wiped out.
//
// R(2-z) has the following properties:
//
// At double precision, max error found: 1.797565e-17
// At 80-bit long double precision, max error found: 9.306419e-21
// Maximum Deviation Found: 2.151e-021
// Expected Error Term: 2.150e-021
//
static const float Y = 0.452017307281494140625f;
static const T P[] = {
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.292329721830270012337e-1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.144216267757192309184e0)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.142440390738631274135e0)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.542809694055053558157e-1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.850535976868336437746e-2)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.431171342679297331241e-3))
};
static const T Q[] = {
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.1e1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.150169356054485044494e1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.846973248876495016101e0)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.220095151814995745555e0)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, 0.25582797155975869989e-1)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.100666795539143372762e-2)),
static_cast<T>(BOOST_MATH_BIG_CONSTANT(T, 64, -0.827193521891290553639e-6))
};
T r = zm2 * zm1;
T R = tools::evaluate_polynomial(P, T(-zm2)) / tools::evaluate_polynomial(Q, T(-zm2));
result += r * Y + r * R;
}
}
return result;
}
template <class T, class Policy, class Lanczos>
T lgamma_small_imp(T z, T zm1, T zm2, const mpl::int_<113>&, const Policy& /* l */, const Lanczos&)
{
//
// This version uses rational approximations for small
// values of z accurate enough for 113-bit mantissas
// (128-bit long doubles).
//
BOOST_MATH_STD_USING // for ADL of std names
T result = 0;
if(z < tools::epsilon<T>())
{
result = -log(z);
BOOST_MATH_INSTRUMENT_CODE(result);
}
else if((zm1 == 0) || (zm2 == 0))
{
// nothing to do, result is zero....
}
else if(z > 2)
{
//
// Begin by performing argument reduction until
// z is in [2,3):
//
if(z >= 3)
{
do
{
z -= 1;
result += log(z);
}while(z >= 3);
zm2 = z - 2;
}
BOOST_MATH_INSTRUMENT_CODE(zm2);
BOOST_MATH_INSTRUMENT_CODE(z);
BOOST_MATH_INSTRUMENT_CODE(result);
//
// Use the following form:
//
// lgamma(z) = (z-2)(z+1)(Y + R(z-2))
//
// where R(z-2) is a rational approximation optimised for
// low absolute error - as long as it's absolute error
// is small compared to the constant Y - then any rounding
// error in it's computation will get wiped out.
//
// Maximum Deviation Found (approximation error) 3.73e-37
static const T P[] = {
BOOST_MATH_BIG_CONSTANT(T, 113, -0.018035568567844937910504030027467476655),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.013841458273109517271750705401202404195),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.062031842739486600078866923383017722399),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.052518418329052161202007865149435256093),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.01881718142472784129191838493267755758),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.0025104830367021839316463675028524702846),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.00021043176101831873281848891452678568311),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.00010249622350908722793327719494037981166),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.11381479670982006841716879074288176994e-4),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.49999811718089980992888533630523892389e-6),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.70529798686542184668416911331718963364e-8)
};
static const T Q[] = {
BOOST_MATH_BIG_CONSTANT(T, 113, 1.0),
BOOST_MATH_BIG_CONSTANT(T, 113, 2.5877485070422317542808137697939233685),
BOOST_MATH_BIG_CONSTANT(T, 113, 2.8797959228352591788629602533153837126),
BOOST_MATH_BIG_CONSTANT(T, 113, 1.8030885955284082026405495275461180977),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.69774331297747390169238306148355428436),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.17261566063277623942044077039756583802),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.02729301254544230229429621192443000121),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.0026776425891195270663133581960016620433),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.00015244249160486584591370355730402168106),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.43997034032479866020546814475414346627e-5),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.46295080708455613044541885534408170934e-7),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.93326638207459533682980757982834180952e-11),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.42316456553164995177177407325292867513e-13)
};
T R = tools::evaluate_polynomial(P, zm2);
R /= tools::evaluate_polynomial(Q, zm2);
static const float Y = 0.158963680267333984375F;
T r = zm2 * (z + 1);
result += r * Y + r * R;
BOOST_MATH_INSTRUMENT_CODE(result);
}
else
{
//
// If z is less than 1 use recurrance to shift to
// z in the interval [1,2]:
//
if(z < 1)
{
result += -log(z);
zm2 = zm1;
zm1 = z;
z += 1;
}
BOOST_MATH_INSTRUMENT_CODE(result);
BOOST_MATH_INSTRUMENT_CODE(z);
BOOST_MATH_INSTRUMENT_CODE(zm2);
//
// Three approximations, on for z in [1,1.35], [1.35,1.625] and [1.625,1]
//
if(z <= 1.35)
{
//
// Use the following form:
//
// lgamma(z) = (z-1)(z-2)(Y + R(z-1))
//
// where R(z-1) is a rational approximation optimised for
// low absolute error - as long as it's absolute error
// is small compared to the constant Y - then any rounding
// error in it's computation will get wiped out.
//
// R(z-1) has the following properties:
//
// Maximum Deviation Found (approximation error) 1.659e-36
// Expected Error Term (theoretical error) 1.343e-36
// Max error found at 128-bit long double precision 1.007e-35
//
static const float Y = 0.54076099395751953125f;
static const T P[] = {
BOOST_MATH_BIG_CONSTANT(T, 113, 0.036454670944013329356512090082402429697),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.066235835556476033710068679907798799959),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.67492399795577182387312206593595565371),
BOOST_MATH_BIG_CONSTANT(T, 113, -1.4345555263962411429855341651960000166),
BOOST_MATH_BIG_CONSTANT(T, 113, -1.4894319559821365820516771951249649563),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.87210277668067964629483299712322411566),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.29602090537771744401524080430529369136),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.0561832587517836908929331992218879676),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.0053236785487328044334381502530383140443),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.00018629360291358130461736386077971890789),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.10164985672213178500790406939467614498e-6),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.13680157145361387405588201461036338274e-8)
};
static const T Q[] = {
BOOST_MATH_BIG_CONSTANT(T, 113, 1.0),
BOOST_MATH_BIG_CONSTANT(T, 113, 4.9106336261005990534095838574132225599),
BOOST_MATH_BIG_CONSTANT(T, 113, 10.258804800866438510889341082793078432),
BOOST_MATH_BIG_CONSTANT(T, 113, 11.88588976846826108836629960537466889),
BOOST_MATH_BIG_CONSTANT(T, 113, 8.3455000546999704314454891036700998428),
BOOST_MATH_BIG_CONSTANT(T, 113, 3.6428823682421746343233362007194282703),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.97465989807254572142266753052776132252),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.15121052897097822172763084966793352524),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.012017363555383555123769849654484594893),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.0003583032812720649835431669893011257277)
};
T r = tools::evaluate_polynomial(P, zm1) / tools::evaluate_polynomial(Q, zm1);
T prefix = zm1 * zm2;
result += prefix * Y + prefix * r;
BOOST_MATH_INSTRUMENT_CODE(result);
}
else if(z <= 1.625)
{
//
// Use the following form:
//
// lgamma(z) = (2-z)(1-z)(Y + R(2-z))
//
// where R(2-z) is a rational approximation optimised for
// low absolute error - as long as it's absolute error
// is small compared to the constant Y - then any rounding
// error in it's computation will get wiped out.
//
// R(2-z) has the following properties:
//
// Max error found at 128-bit long double precision 9.634e-36
// Maximum Deviation Found (approximation error) 1.538e-37
// Expected Error Term (theoretical error) 2.350e-38
//
static const float Y = 0.483787059783935546875f;
static const T P[] = {
BOOST_MATH_BIG_CONSTANT(T, 113, -0.017977422421608624353488126610933005432),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.18484528905298309555089509029244135703),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.40401251514859546989565001431430884082),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.40277179799147356461954182877921388182),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.21993421441282936476709677700477598816),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.069595742223850248095697771331107571011),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.012681481427699686635516772923547347328),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.0012489322866834830413292771335113136034),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.57058739515423112045108068834668269608e-4),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.8207548771933585614380644961342925976e-6)
};
static const T Q[] = {
BOOST_MATH_BIG_CONSTANT(T, 113, 1.0),
BOOST_MATH_BIG_CONSTANT(T, 113, -2.9629552288944259229543137757200262073),
BOOST_MATH_BIG_CONSTANT(T, 113, 3.7118380799042118987185957298964772755),
BOOST_MATH_BIG_CONSTANT(T, 113, -2.5569815272165399297600586376727357187),
BOOST_MATH_BIG_CONSTANT(T, 113, 1.0546764918220835097855665680632153367),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.26574021300894401276478730940980810831),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.03996289731752081380552901986471233462),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.0033398680924544836817826046380586480873),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.00013288854760548251757651556792598235735),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.17194794958274081373243161848194745111e-5)
};
T r = zm2 * zm1;
T R = tools::evaluate_polynomial(P, T(0.625 - zm1)) / tools::evaluate_polynomial(Q, T(0.625 - zm1));
result += r * Y + r * R;
BOOST_MATH_INSTRUMENT_CODE(result);
}
else
{
//
// Same form as above.
//
// Max error found (at 128-bit long double precision) 1.831e-35
// Maximum Deviation Found (approximation error) 8.588e-36
// Expected Error Term (theoretical error) 1.458e-36
//
static const float Y = 0.443811893463134765625f;
static const T P[] = {
BOOST_MATH_BIG_CONSTANT(T, 113, -0.021027558364667626231512090082402429494),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.15128811104498736604523586803722368377),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.26249631480066246699388544451126410278),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.21148748610533489823742352180628489742),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.093964130697489071999873506148104370633),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.024292059227009051652542804957550866827),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.0036284453226534839926304745756906117066),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.0002939230129315195346843036254392485984),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.11088589183158123733132268042570710338e-4),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.13240510580220763969511741896361984162e-6)
};
static const T Q[] = {
BOOST_MATH_BIG_CONSTANT(T, 113, 1.0),
BOOST_MATH_BIG_CONSTANT(T, 113, -2.4240003754444040525462170802796471996),
BOOST_MATH_BIG_CONSTANT(T, 113, 2.4868383476933178722203278602342786002),
BOOST_MATH_BIG_CONSTANT(T, 113, -1.4047068395206343375520721509193698547),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.47583809087867443858344765659065773369),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.09865724264554556400463655444270700132),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.012238223514176587501074150988445109735),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.00084625068418239194670614419707491797097),
BOOST_MATH_BIG_CONSTANT(T, 113, 0.2796574430456237061420839429225710602e-4),
BOOST_MATH_BIG_CONSTANT(T, 113, -0.30202973883316730694433702165188835331e-6)
};
// (2 - x) * (1 - x) * (c + R(2 - x))
T r = zm2 * zm1;
T R = tools::evaluate_polynomial(P, T(-zm2)) / tools::evaluate_polynomial(Q, T(-zm2));
result += r * Y + r * R;
BOOST_MATH_INSTRUMENT_CODE(result);
}
}
BOOST_MATH_INSTRUMENT_CODE(result);
return result;
}
template <class T, class Policy, class Lanczos>
T lgamma_small_imp(T z, T zm1, T zm2, const mpl::int_<0>&, const Policy& pol, const Lanczos&)
{
//
// No rational approximations are available because either
// T has no numeric_limits support (so we can't tell how
// many digits it has), or T has more digits than we know
// what to do with.... we do have a Lanczos approximation
// though, and that can be used to keep errors under control.
//
BOOST_MATH_STD_USING // for ADL of std names
T result = 0;
if(z < tools::epsilon<T>())
{
result = -log(z);
}
else if(z < 0.5)
{
// taking the log of tgamma reduces the error, no danger of overflow here:
result = log(gamma_imp(z, pol, Lanczos()));
}
else if(z >= 3)
{
// taking the log of tgamma reduces the error, no danger of overflow here:
result = log(gamma_imp(z, pol, Lanczos()));
}
else if(z >= 1.5)
{
// special case near 2:
T dz = zm2;
result = dz * log((z + Lanczos::g() - T(0.5)) / boost::math::constants::e<T>());
result += boost::math::log1p(dz / (Lanczos::g() + T(1.5)), pol) * T(1.5);
result += boost::math::log1p(Lanczos::lanczos_sum_near_2(dz), pol);
}
else
{
// special case near 1:
T dz = zm1;
result = dz * log((z + Lanczos::g() - T(0.5)) / boost::math::constants::e<T>());
result += boost::math::log1p(dz / (Lanczos::g() + T(0.5)), pol) / 2;
result += boost::math::log1p(Lanczos::lanczos_sum_near_1(dz), pol);
}
return result;
}
}}} // namespaces
#endif // BOOST_MATH_SPECIAL_FUNCTIONS_DETAIL_LGAMMA_SMALL
| bsd-2-clause |
jgcaaprom/android_external_chromium_org | tools/chrome_proxy/integration_tests/chrome_proxy_pagesets/bypass.py | 807 | # Copyright 2014 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.
from telemetry.page import page as page_module
from telemetry.page import page_set as page_set_module
class BypassPage(page_module.Page):
def __init__(self, url, page_set):
super(BypassPage, self).__init__(url=url, page_set=page_set)
self.archive_data_file = '../data/chrome_proxy_bypass.json'
class BypassPageSet(page_set_module.PageSet):
""" Chrome proxy test sites """
def __init__(self):
super(BypassPageSet, self).__init__(
archive_data_file='../data/chrome_proxy_bypass.json')
urls_list = [
'http://aws1.mdw.la/bypass/',
]
for url in urls_list:
self.AddPage(BypassPage(url, self))
| bsd-3-clause |
Jonekee/chromium.src | chrome/browser/extensions/api/vpn_provider/vpn_service_factory.cc | 2169 | // Copyright 2014 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 "extensions/browser/api/vpn_provider/vpn_service_factory.h"
#include "base/memory/singleton.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/network/network_handler.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "extensions/browser/api/vpn_provider/vpn_service.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_registry.h"
namespace chromeos {
// static
VpnService* VpnServiceFactory::GetForBrowserContext(
content::BrowserContext* context) {
return static_cast<VpnService*>(
GetInstance()->GetServiceForBrowserContext(context, true));
}
// static
VpnServiceFactory* VpnServiceFactory::GetInstance() {
return Singleton<VpnServiceFactory>::get();
}
VpnServiceFactory::VpnServiceFactory()
: BrowserContextKeyedServiceFactory(
"VpnService",
BrowserContextDependencyManager::GetInstance()) {
}
VpnServiceFactory::~VpnServiceFactory() {
}
bool VpnServiceFactory::ServiceIsCreatedWithBrowserContext() const {
return true;
}
bool VpnServiceFactory::ServiceIsNULLWhileTesting() const {
return true;
}
KeyedService* VpnServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
if (!chromeos::ProfileHelper::IsPrimaryProfile(
Profile::FromBrowserContext(context))) {
return nullptr;
}
return new VpnService(
context,
chromeos::ProfileHelper::GetUserIdHashFromProfile(
Profile::FromBrowserContext(context)),
extensions::ExtensionRegistry::Get(context),
extensions::EventRouter::Get(context),
DBusThreadManager::Get()->GetShillThirdPartyVpnDriverClient(),
NetworkHandler::Get()->network_configuration_handler(),
NetworkHandler::Get()->network_profile_handler(),
NetworkHandler::Get()->network_state_handler());
}
} // namespace chromeos
| bsd-3-clause |
mohitbhatia1994/cdnjs | ajax/libs/angularSubkit/1.0.2/angularsubkit.js | 101154 | // - 1.0.2
// https://github.com/subkit
// Copyright 2012 - 2015 http://subkit.io
// MIT License
!function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.Subkit=e():"undefined"!=typeof global?global.Subkit=e():"undefined"!=typeof self&&(self.Subkit=e())}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports = function(subkit, subscriptions, poll){
'use strict';
return function(){
return {
list: function(callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/events/streams';
subkit.httpRequest.get(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
log: function(stream, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/events/log/' + stream;
subkit.httpRequest.get(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
remove: function(stream, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/events/log/' + stream;
subkit.httpRequest.del(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status!==202 && status!==204) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
emit: function(stream, payload, persistent, metadata, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/events/emit/' + stream;
var msg = JSON.parse(JSON.stringify(subkit.options));
msg.data = payload;
if(persistent) msg.headers['X-Subkit-Event-Persistent'] = true;
if(metadata) msg.headers['X-Subkit-Event-Metadata'] = JSON.stringify(metadata);
subkit.httpRequest.post(url, msg, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 201 && status !== 202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
on: function(stream, callback) {
stream = stream.replace('/', '_');
subscriptions[stream] = poll(stream, callback);
return {
off: function(){
delete subscriptions[stream];
if(subscriptions[stream]) subscriptions[stream]().abort();
},
emit: function(value, callback){
subkit.events.emit(stream, value, callback);
}
};
},
off: function(stream){
if(subscriptions[stream]) subscriptions[stream]().abort();
delete subscriptions[stream];
return false;
}
};
};
};
},{}],2:[function(require,module,exports){
module.exports = function(subkit){
'use strict';
return function(){
return {
login: function(callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/login';
subkit.httpRequest.authBasic(subkit.options.username, subkit.options.password);
subkit.httpRequest.post(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else {
subkit.options.apiKey = result.json().api.apiKey;
deferred.resolve({
apiKey: subkit.options.apiKey,
username: subkit.options.username,
password: subkit.options.password,
baseUrl: subkit.baseUrl
});
}
});
return deferred.promise.nodeify(callback);
},
import: function(file, callback){
var deferred = subkit.$q.defer();
var msg = JSON.parse(JSON.stringify(subkit.options));
msg.headers = {
'Content-Type': 'application/octed-stream'
};
msg.data = file;
var url = subkit.baseUrl + '/manage/import';
subkit.httpRequest.post(url, msg, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 201) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
export: function(callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/export';
subkit.httpRequest.get(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve('data:application/octet-stream,' + result.text());
});
return deferred.promise.nodeify(callback);
},
backup: function(callback){
if(callback) callback();
},
restore: function(name, callback){
if(callback) callback();
},
password: {
set: function(oldPassword, newPassword, verifyPassword, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/password/action/reset';
var msg = JSON.parse(JSON.stringify(subkit.options));
msg.data = {
password: oldPassword,
newPassword: newPassword,
newPasswordValidation: verifyPassword
};
subkit.httpRequest.put(url, msg, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
}
},
user: {
set: function(username, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/user';
var msg = JSON.parse(JSON.stringify(subkit.options));
msg.data = {
username: username
};
subkit.httpRequest.put(url, msg, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
}
},
apikey: {
reset: function(callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/apikey/action/reset';
subkit.httpRequest.put(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
}
},
certificate:{
get: function(callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/certificate';
subkit.httpRequest.get(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
set: function(certificate, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/certificate/action/change';
var msg = JSON.parse(JSON.stringify(subkit.options));
msg.data = certificate;
subkit.httpRequest.put(url, msg, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 201 && status !== 202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
}
},
status: {
get: function(callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/os';
subkit.httpRequest.get(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
kill: function(callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/kill';
subkit.httpRequest.put(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status!==202 && status!==204) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
}
},
plugins: {
list: function(callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/plugins';
subkit.httpRequest.get(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
install: function(name,callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/plugins/' + name;
subkit.httpRequest.post(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 201 && status !== 202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
update: function(name,callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/plugins/' + name;
subkit.httpRequest.put(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status!==202 && status!==204) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
uninstall: function(name,callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/plugins/' + name;
subkit.httpRequest.del(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status!==202 && status!==204) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
}
},
permissions:{
roles: function(callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/permissions/identities';
subkit.httpRequest.get(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
list: function(identity, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/permissions/' + identity;
subkit.httpRequest.get(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
set: function(key, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key);
subkit.httpRequest.post(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 201 && status !== 202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
remove: function(key, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key);
subkit.httpRequest.del(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status!==202 && status!==204) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
grantInsert: function(key, identity, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/grantinsert/' + identity;
subkit.httpRequest.put(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
grantUpdate: function(key, identity, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/grantupdate/' + identity;
subkit.httpRequest.put(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
grantDelete: function(key, identity, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/grantdelete/' + identity;
subkit.httpRequest.put(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
grantRead: function(key, identity, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/grantread/' + identity;
subkit.httpRequest.put(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
revokeInsert: function(key, identity, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/revokeinsert/' + identity;
subkit.httpRequest.put(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
revokeUpdate: function(key, identity, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/revokeupdate/' + identity;
subkit.httpRequest.put(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
revokeDelete: function(key, identity, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/revokedelete/' + identity;
subkit.httpRequest.put(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
revokeRead: function(key, identity, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/permissions/' + encodeURIComponent(key) + '/action/revokeread/' + identity;
subkit.httpRequest.put(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
}
}
};
};
};
},{}],3:[function(require,module,exports){
module.exports = function(subkit, subscriptions, poll){
'use strict';
return function(store){
var _prepareUrl = function(key){
if(store && !key) return subkit.baseUrl + '/stores/' + store;
if(store && key) return subkit.baseUrl + '/stores/' + store + '/' + key;
if(!store && key && key.indexOf('!') !== -1) {
key = key.replace(/^[a-zA-z0-9]\/\//, '!');
return subkit.baseUrl + '/stores/' + key;
}
if(!store && key) return subkit.baseUrl + '/stores/' + key;
return subkit.baseUrl + '/stores';
};
var _prepareParams = function(url, params){
var queryString = '';
for(var key in params){
if(key === 'where') {
var jsonFilter = JSON.stringify(params[key]);
queryString += '&where=' + jsonFilter;
} else {
queryString += '&' + key + '=' + params[key];
}
}
queryString = queryString.substring(1, queryString.length);
return url + '?' + queryString;
};
var ref = {
key: function(){
return Subkit.UUID();
},
import: function(file, callback){
var deferred = subkit.$q.defer();
var msg = JSON.parse(JSON.stringify(subkit.options));
msg.headers = {
'Content-Type': 'application/octed-stream',
apiKey: config.apiKey
};
msg.data = file;
var url = subkit.baseUrl + '/manage/import/' + store;
subkit.httpRequest.post(url, msg, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status!==201 && status!==202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
export: function(callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/manage/export/' + store;
subkit.httpRequest.get(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve('data:application/octet-stream,' + result.text());
});
return deferred.promise.nodeify(callback);
},
add: function(key, value, callback){
var deferred = subkit.$q.defer();
key = arguments[0];
value = arguments[1];
if(arguments.length === 1 && key instanceof Object){
value = key;
key = Subkit.UUID();
}
var url = _prepareUrl(key);
var msg = JSON.parse(JSON.stringify(subkit.options));
msg.data = value;
subkit.httpRequest.post(url, msg, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status!==201) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
set: function(key, value, version, callback){
if(typeof version === 'function') {
callback = version;
version = undefined;
}
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/stores/' + store + '/' + key;
var msg = JSON.parse(JSON.stringify(subkit.options));
msg.data = value;
if(version) msg.headers['If-Match'] = version;
subkit.httpRequest.put(url, msg, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status!==202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
get: function(key, callback){
var deferred = subkit.$q.defer();
subkit.httpRequest.get(_prepareUrl(key), subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
find: function(query, callback){
var url = _prepareUrl(query.key);
url = _prepareParams(url, query);
var deferred = subkit.$q.defer();
subkit.httpRequest.get(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
remove: function(key, version, callback){
if(typeof version === 'function') {
callback = version;
version = undefined;
}
var deferred = subkit.$q.defer();
var msg = JSON.parse(JSON.stringify(subkit.options));
if(version) msg.headers['If-Match'] = version;
subkit.httpRequest.del(_prepareUrl(key), msg, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status!==202 && status!==204) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
log: function(callback){
var deferred = subkit.$q.defer();
subkit.httpRequest.get('', subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
on: function(callback){
if(subscriptions[store]) subscriptions[store]().abort();
subscriptions[store] = poll(store, callback);
return true;
},
off: function(){
if(subscriptions[store]) subscriptions[store]().abort();
delete subscriptions[store];
return false;
}
};
return ref;
};
};
},{}],4:[function(require,module,exports){
module.exports = function(subkit){
'use strict';
return function(){
return {
set: function(task, callback){
var deferred = subkit.$q.defer();
var msg = JSON.parse(JSON.stringify(subkit.options));
msg.data = task;
var url = subkit.baseUrl + '/tasks/' + task.name;
subkit.httpRequest.put(url, msg, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status !== 201 && status!==202) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
get: function(taskName, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/tasks/' + taskName;
subkit.httpRequest.get(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
remove: function(taskName, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/tasks/' + taskName;
subkit.httpRequest.del(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200 && status!==202 && status!==204) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
list: function(callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/tasks';
subkit.httpRequest.get(url, subkit.options, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
},
runDebug: function(taskName, value, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/tasks/api/' + taskName;
var msg = JSON.parse(JSON.stringify(subkit.options));
msg.data = value;
subkit.httpRequest.get(url, msg, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve({
result: result.json(),
raw: result.text(),
headers: result.headers(),
log: result.log()
});
});
return deferred.promise.nodeify(callback);
},
run: function(taskName, value, callback){
var deferred = subkit.$q.defer();
var url = subkit.baseUrl + '/tasks/action/run/' + taskName;
var msg = JSON.parse(JSON.stringify(subkit.options));
msg.data = value;
subkit.httpRequest.get(url, msg, function(status, result){
if (status === 0) deferred.reject(new Error('No network connection.'));
else if (status !== 200) deferred.reject(new Error(result.json().message));
else deferred.resolve(result.json());
});
return deferred.promise.nodeify(callback);
}
};
};
};
},{}],5:[function(require,module,exports){
/** @module Subkit */
/**
* Subkit
* @param {object} config - A Subkit configuration
*/
var Subkit = function (config){
'use strict';
var self = this;
var subscriptions = {};
self.clientId = config.clientId || initClientId();
self.baseUrl = config.baseUrl || ((window.location.origin.indexOf('http') !== -1) ? window.location.origin : 'https://localhost:8080');
self.options = {
apiKey: config.apiKey || '',
username: config.username || '',
password: config.password || '',
headers : {
'Content-Type': 'application/json'
}
};
self.httpRequest = {
authBasic: function (username, password) {
self.httpRequest.headers({});
ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
},
connect: function (url, options, callback) {
return ajax('CONNECT', url, options, callback);
},
del: function (url, options, callback) {
return ajax('DELETE', url, options, callback);
},
get: function (url, options, callback) {
return ajax('GET', url, options, callback);
},
head: function (url, options, callback) {
return ajax('HEAD', url, options, callback);
},
headers: function (headers) {
ajax.headers = headers || {};
},
isAllowed: function (url, verb, callback) {
this.options(url, function (status, data) {
callback(data.text().indexOf(verb) !== -1);
});
},
options: function (url, options, callback) {
return ajax('OPTIONS', url, options, callback);
},
patch: function (url, options, callback) {
return ajax('PATCH', url, options, callback);
},
post: function (url, options, callback) {
return ajax('POST', url, options, callback);
},
put: function (url, options, callback) {
return ajax('PUT', url, options, callback);
},
trace: function (url, options, callback) {
return ajax('TRACE', url, options, callback);
}
};
self.$q = require('q');
self.manage = require('./lib/manage')(self);
self.tasks = require('./lib/tasks')(self);
self.stores = require('./lib/stores')(self, subscriptions, poll);
self.events = require('./lib/events')(self, subscriptions, poll);
function getXhr(callback) {
if (window.XMLHttpRequest) {
return callback(null, new XMLHttpRequest());
} else if (window.ActiveXObject) {
try {
return callback(null, new ActiveXObject('Msxml2.XMLHTTP'));
} catch (e) {
return callback(null, new ActiveXObject('Microsoft.XMLHTTP'));
}
}
return callback(new Error());
}
function encodeUsingUrlEncoding(data) {
if(typeof data === 'string') {
return data;
}
var result = [];
for(var dataItem in data) {
if(data.hasOwnProperty(dataItem)) {
result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
}
}
return result.join('&');
}
function utf8(text) {
text = text.replace(/\r\n/g, '\n');
var result = '';
for(var i = 0; i < text.length; i++) {
var c = text.charCodeAt(i);
if(c < 128) {
result += String.fromCharCode(c);
} else if((c > 127) && (c < 2048)) {
result += String.fromCharCode((c >> 6) | 192);
result += String.fromCharCode((c & 63) | 128);
} else {
result += String.fromCharCode((c >> 12) | 224);
result += String.fromCharCode(((c >> 6) & 63) | 128);
result += String.fromCharCode((c & 63) | 128);
}
}
return result;
}
function base64(text) {
var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
text = utf8(text);
var result = '',
chr1, chr2, chr3,
enc1, enc2, enc3, enc4,
i = 0;
do {
chr1 = text.charCodeAt(i++);
chr2 = text.charCodeAt(i++);
chr3 = text.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if(isNaN(chr2)) {
enc3 = enc4 = 64;
} else if(isNaN(chr3)) {
enc4 = 64;
}
result +=
keyStr.charAt(enc1) +
keyStr.charAt(enc2) +
keyStr.charAt(enc3) +
keyStr.charAt(enc4);
chr1 = chr2 = chr3 = '';
enc1 = enc2 = enc3 = enc4 = '';
} while(i < text.length);
return result;
}
function mergeHeaders() {
var result = arguments[0];
for(var i = 1; i < arguments.length; i++) {
var currentHeaders = arguments[i];
for(var header in currentHeaders) {
if(currentHeaders.hasOwnProperty(header)) {
result[header] = currentHeaders[header];
}
}
}
return result;
}
function ajax(method, url, options, callback) {
if(typeof options === 'function') {
callback = options;
options = {};
}
options.cache = options.cache || true;
options.headers = options.headers || {};
options.jsonp = options.jsonp || false;
var headers = mergeHeaders({
'Accept': '*/*',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'X-Auth-Token': options.apiKey
}, ajax.headers, options.headers);
var payload;
if(options.data) {
if ((method === 'GET') && (headers['Content-Type'] === 'application/json')) {
payload = encodeUsingUrlEncoding(options.data);
}
else if (headers['Content-Type'] === 'application/json') {
payload = JSON.stringify(options.data);
}
else if(headers['Content-Type'].indexOf('application/octed-stream') !== -1){
payload = options.data;
}
else {
payload = encodeUsingUrlEncoding(options.data);
}
}
if(method === 'GET') {
var queryString = [];
if(payload) {
queryString.push(payload);
payload = null;
}
if(!options.cache) {
queryString.push('_=' + (new Date()).getTime());
}
if(options.jsonp) {
queryString.push('callback=' + options.jsonp);
queryString.push('jsonp=' + options.jsonp);
}
queryString = '?' + queryString.join('&');
url += queryString !== '?' ? queryString : '';
if(options.jsonp) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
head.appendChild(script);
return;
}
}
var xhrRef = null;
getXhr(function (err, xhr) {
xhrRef = xhr;
if(err) return callback(err);
xhr.open(method, url, options.async || true);
for(var header in headers) {
if(headers.hasOwnProperty(header)) {
xhr.setRequestHeader(header, headers[header]);
}
}
xhr.timeout = 240000;
xhr.ontimeout = function (){
callback(0, {
text: function () {
return 'Connection timeout';
},
json: function(){
return {message: 'Connection timeout'}
}
});
}
xhr.onerror = function(){
callback(xhr.status, {
text: function () {
return xhr.statusText;
},
json: function(){
return {message: xhr.statusText}
}
});
};
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status !== 0) {
if(!callback) return;
var data = xhr.responseText || '';
callback(xhr.status, {
text: function () {
return data;
},
json: function () {
if(data) return JSON.parse(data);
return {};
},
headers: function(){
return xhr.getAllResponseHeaders();
},
log: function(){
return xhr.getResponseHeader('subkit-log');
}
});
}
};
xhr.send(payload);
});
return xhrRef;
}
function initClientId(){
var clientId = window.sessionStorage.getItem('clientId');
if(!clientId) {
clientId = Subkit.UUID();
window.sessionStorage.setItem('clientId', clientId);
}
return clientId;
}
function poll(stream, callback) {
var subscribeUrl = self.baseUrl + '/events/bind/' + stream;
var request = null;
var count = 1;
(function _pollRef(){
request = self.httpRequest.get(subscribeUrl, self.options, function(status, result){
if(status !== 200) {
if(subscriptions[stream]){
callback({message: 'subscription error - retry'});
setTimeout(function(){_pollRef(stream, callback);},300*count++);
}
}else{
count = 1;
result.json().forEach(function(item){
callback(null, item);
});
if(subscriptions[stream]) _pollRef(stream, callback);
}
});
})();
return function(){
return request;
};
}
};
Subkit.UUID = function () {
// http://www.ietf.org/rfc/rfc4122.txt
var s = [];
var hexDigits = '0123456789abcdef';
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = '-';
var uuid = s.join('');
return uuid;
};
module.exports = Subkit
},{"./lib/events":1,"./lib/manage":2,"./lib/stores":3,"./lib/tasks":4,"q":7}],6:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.binding = function (name) {
throw new Error('process.binding is not supported');
}
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],7:[function(require,module,exports){
var process=require("__browserify_process");// vim:ts=4:sts=4:sw=4:
/*!
*
* Copyright 2009-2012 Kris Kowal under the terms of the MIT
* license found at http://github.com/kriskowal/q/raw/master/LICENSE
*
* With parts by Tyler Close
* Copyright 2007-2009 Tyler Close under the terms of the MIT X license found
* at http://www.opensource.org/licenses/mit-license.html
* Forked at ref_send.js version: 2009-05-11
*
* With parts by Mark Miller
* Copyright (C) 2011 Google 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 (definition) {
"use strict";
// This file will function properly as a <script> tag, or a module
// using CommonJS and NodeJS or RequireJS module formats. In
// Common/Node/RequireJS, the module exports the Q API and when
// executed as a simple <script>, it creates a Q global instead.
// Montage Require
if (typeof bootstrap === "function") {
bootstrap("promise", definition);
// CommonJS
} else if (typeof exports === "object" && typeof module === "object") {
module.exports = definition();
// RequireJS
} else if (typeof define === "function" && define.amd) {
define(definition);
// SES (Secure EcmaScript)
} else if (typeof ses !== "undefined") {
if (!ses.ok()) {
return;
} else {
ses.makeQ = definition;
}
// <script>
} else if (typeof self !== "undefined") {
self.Q = definition();
} else {
throw new Error("This environment was not anticipated by Q. Please file a bug.");
}
})(function () {
"use strict";
var hasStacks = false;
try {
throw new Error();
} catch (e) {
hasStacks = !!e.stack;
}
// All code after this point will be filtered from stack traces reported
// by Q.
var qStartingLine = captureLine();
var qFileName;
// shims
// used for fallback in "allResolved"
var noop = function () {};
// Use the fastest possible means to execute a task in a future turn
// of the event loop.
var nextTick =(function () {
// linked list of tasks (single, with head node)
var head = {task: void 0, next: null};
var tail = head;
var flushing = false;
var requestTick = void 0;
var isNodeJS = false;
function flush() {
/* jshint loopfunc: true */
while (head.next) {
head = head.next;
var task = head.task;
head.task = void 0;
var domain = head.domain;
if (domain) {
head.domain = void 0;
domain.enter();
}
try {
task();
} catch (e) {
if (isNodeJS) {
// In node, uncaught exceptions are considered fatal errors.
// Re-throw them synchronously to interrupt flushing!
// Ensure continuation if the uncaught exception is suppressed
// listening "uncaughtException" events (as domains does).
// Continue in next event to avoid tick recursion.
if (domain) {
domain.exit();
}
setTimeout(flush, 0);
if (domain) {
domain.enter();
}
throw e;
} else {
// In browsers, uncaught exceptions are not fatal.
// Re-throw them asynchronously to avoid slow-downs.
setTimeout(function() {
throw e;
}, 0);
}
}
if (domain) {
domain.exit();
}
}
flushing = false;
}
nextTick = function (task) {
tail = tail.next = {
task: task,
domain: isNodeJS && process.domain,
next: null
};
if (!flushing) {
flushing = true;
requestTick();
}
};
if (typeof process !== "undefined" && process.nextTick) {
// Node.js before 0.9. Note that some fake-Node environments, like the
// Mocha test runner, introduce a `process` global without a `nextTick`.
isNodeJS = true;
requestTick = function () {
process.nextTick(flush);
};
} else if (typeof setImmediate === "function") {
// In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate
if (typeof window !== "undefined") {
requestTick = setImmediate.bind(window, flush);
} else {
requestTick = function () {
setImmediate(flush);
};
}
} else if (typeof MessageChannel !== "undefined") {
// modern browsers
// http://www.nonblocking.io/2011/06/windownexttick.html
var channel = new MessageChannel();
// At least Safari Version 6.0.5 (8536.30.1) intermittently cannot create
// working message ports the first time a page loads.
channel.port1.onmessage = function () {
requestTick = requestPortTick;
channel.port1.onmessage = flush;
flush();
};
var requestPortTick = function () {
// Opera requires us to provide a message payload, regardless of
// whether we use it.
channel.port2.postMessage(0);
};
requestTick = function () {
setTimeout(flush, 0);
requestPortTick();
};
} else {
// old browsers
requestTick = function () {
setTimeout(flush, 0);
};
}
return nextTick;
})();
// Attempt to make generics safe in the face of downstream
// modifications.
// There is no situation where this is necessary.
// If you need a security guarantee, these primordials need to be
// deeply frozen anyway, and if you don’t need a security guarantee,
// this is just plain paranoid.
// However, this **might** have the nice side-effect of reducing the size of
// the minified code by reducing x.call() to merely x()
// See Mark Miller’s explanation of what this does.
// http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming
var call = Function.call;
function uncurryThis(f) {
return function () {
return call.apply(f, arguments);
};
}
// This is equivalent, but slower:
// uncurryThis = Function_bind.bind(Function_bind.call);
// http://jsperf.com/uncurrythis
var array_slice = uncurryThis(Array.prototype.slice);
var array_reduce = uncurryThis(
Array.prototype.reduce || function (callback, basis) {
var index = 0,
length = this.length;
// concerning the initial value, if one is not provided
if (arguments.length === 1) {
// seek to the first value in the array, accounting
// for the possibility that is is a sparse array
do {
if (index in this) {
basis = this[index++];
break;
}
if (++index >= length) {
throw new TypeError();
}
} while (1);
}
// reduce
for (; index < length; index++) {
// account for the possibility that the array is sparse
if (index in this) {
basis = callback(basis, this[index], index);
}
}
return basis;
}
);
var array_indexOf = uncurryThis(
Array.prototype.indexOf || function (value) {
// not a very good shim, but good enough for our one use of it
for (var i = 0; i < this.length; i++) {
if (this[i] === value) {
return i;
}
}
return -1;
}
);
var array_map = uncurryThis(
Array.prototype.map || function (callback, thisp) {
var self = this;
var collect = [];
array_reduce(self, function (undefined, value, index) {
collect.push(callback.call(thisp, value, index, self));
}, void 0);
return collect;
}
);
var object_create = Object.create || function (prototype) {
function Type() { }
Type.prototype = prototype;
return new Type();
};
var object_hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty);
var object_keys = Object.keys || function (object) {
var keys = [];
for (var key in object) {
if (object_hasOwnProperty(object, key)) {
keys.push(key);
}
}
return keys;
};
var object_toString = uncurryThis(Object.prototype.toString);
function isObject(value) {
return value === Object(value);
}
// generator related shims
// FIXME: Remove this function once ES6 generators are in SpiderMonkey.
function isStopIteration(exception) {
return (
object_toString(exception) === "[object StopIteration]" ||
exception instanceof QReturnValue
);
}
// FIXME: Remove this helper and Q.return once ES6 generators are in
// SpiderMonkey.
var QReturnValue;
if (typeof ReturnValue !== "undefined") {
QReturnValue = ReturnValue;
} else {
QReturnValue = function (value) {
this.value = value;
};
}
// long stack traces
var STACK_JUMP_SEPARATOR = "From previous event:";
function makeStackTraceLong(error, promise) {
// If possible, transform the error stack trace by removing Node and Q
// cruft, then concatenating with the stack trace of `promise`. See #57.
if (hasStacks &&
promise.stack &&
typeof error === "object" &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var p = promise; !!p; p = p.source) {
if (p.stack) {
stacks.unshift(p.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split("\n");
var desiredLines = [];
for (var i = 0; i < lines.length; ++i) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join("\n");
}
function isNodeFrame(stackLine) {
return stackLine.indexOf("(module.js:") !== -1 ||
stackLine.indexOf("(node.js:") !== -1;
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: "at functionName (filename:lineNumber:columnNumber)"
// In IE10 function name can have spaces ("Anonymous function") O_o
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) {
return [attempt1[1], Number(attempt1[2])];
}
// Anonymous functions: "at filename:lineNumber:columnNumber"
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) {
return [attempt2[1], Number(attempt2[2])];
}
// Firefox style: "function@filename:lineNumber or @filename:lineNumber"
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) {
return [attempt3[1], Number(attempt3[2])];
}
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0];
var lineNumber = fileNameAndLineNumber[1];
return fileName === qFileName &&
lineNumber >= qStartingLine &&
lineNumber <= qEndingLine;
}
// discover own file name and line number range for filtering stack
// traces
function captureLine() {
if (!hasStacks) {
return;
}
try {
throw new Error();
} catch (e) {
var lines = e.stack.split("\n");
var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) {
return;
}
qFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function deprecate(callback, name, alternative) {
return function () {
if (typeof console !== "undefined" &&
typeof console.warn === "function") {
console.warn(name + " is deprecated, use " + alternative +
" instead.", new Error("").stack);
}
return callback.apply(callback, arguments);
};
}
// end of shims
// beginning of real work
/**
* Constructs a promise for an immediate reference, passes promises through, or
* coerces promises from different systems.
* @param value immediate reference or promise
*/
function Q(value) {
// If the object is already a Promise, return it directly. This enables
// the resolve function to both be used to created references from objects,
// but to tolerably coerce non-promises to promises.
if (value instanceof Promise) {
return value;
}
// assimilate thenables
if (isPromiseAlike(value)) {
return coerce(value);
} else {
return fulfill(value);
}
}
Q.resolve = Q;
/**
* Performs a task in a future turn of the event loop.
* @param {Function} task
*/
Q.nextTick = nextTick;
/**
* Controls whether or not long stack traces will be on
*/
Q.longStackSupport = false;
// enable long stacks if Q_DEBUG is set
if (typeof process === "object" && process && process.env && process.env.Q_DEBUG) {
Q.longStackSupport = true;
}
/**
* Constructs a {promise, resolve, reject} object.
*
* `resolve` is a callback to invoke with a more resolved value for the
* promise. To fulfill the promise, invoke `resolve` with any value that is
* not a thenable. To reject the promise, invoke `resolve` with a rejected
* thenable, or invoke `reject` with the reason directly. To resolve the
* promise to another thenable, thus putting it in the same state, invoke
* `resolve` with that other thenable.
*/
Q.defer = defer;
function defer() {
// if "messages" is an "Array", that indicates that the promise has not yet
// been resolved. If it is "undefined", it has been resolved. Each
// element of the messages array is itself an array of complete arguments to
// forward to the resolved promise. We coerce the resolution value to a
// promise using the `resolve` function because it handles both fully
// non-thenable values and other thenables gracefully.
var messages = [], progressListeners = [], resolvedPromise;
var deferred = object_create(defer.prototype);
var promise = object_create(Promise.prototype);
promise.promiseDispatch = function (resolve, op, operands) {
var args = array_slice(arguments);
if (messages) {
messages.push(args);
if (op === "when" && operands[1]) { // progress operand
progressListeners.push(operands[1]);
}
} else {
Q.nextTick(function () {
resolvedPromise.promiseDispatch.apply(resolvedPromise, args);
});
}
};
// XXX deprecated
promise.valueOf = function () {
if (messages) {
return promise;
}
var nearerValue = nearer(resolvedPromise);
if (isPromise(nearerValue)) {
resolvedPromise = nearerValue; // shorten chain
}
return nearerValue;
};
promise.inspect = function () {
if (!resolvedPromise) {
return { state: "pending" };
}
return resolvedPromise.inspect();
};
if (Q.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
// NOTE: don't try to use `Error.captureStackTrace` or transfer the
// accessor around; that causes memory leaks as per GH-111. Just
// reify the stack trace as a string ASAP.
//
// At the same time, cut off the first line; it's always just
// "[object Promise]\n", as per the `toString`.
promise.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
}
// NOTE: we do the checks for `resolvedPromise` in each method, instead of
// consolidating them into `become`, since otherwise we'd create new
// promises with the lines `become(whatever(value))`. See e.g. GH-252.
function become(newPromise) {
resolvedPromise = newPromise;
promise.source = newPromise;
array_reduce(messages, function (undefined, message) {
Q.nextTick(function () {
newPromise.promiseDispatch.apply(newPromise, message);
});
}, void 0);
messages = void 0;
progressListeners = void 0;
}
deferred.promise = promise;
deferred.resolve = function (value) {
if (resolvedPromise) {
return;
}
become(Q(value));
};
deferred.fulfill = function (value) {
if (resolvedPromise) {
return;
}
become(fulfill(value));
};
deferred.reject = function (reason) {
if (resolvedPromise) {
return;
}
become(reject(reason));
};
deferred.notify = function (progress) {
if (resolvedPromise) {
return;
}
array_reduce(progressListeners, function (undefined, progressListener) {
Q.nextTick(function () {
progressListener(progress);
});
}, void 0);
};
return deferred;
}
/**
* Creates a Node-style callback that will resolve or reject the deferred
* promise.
* @returns a nodeback
*/
defer.prototype.makeNodeResolver = function () {
var self = this;
return function (error, value) {
if (error) {
self.reject(error);
} else if (arguments.length > 2) {
self.resolve(array_slice(arguments, 1));
} else {
self.resolve(value);
}
};
};
/**
* @param resolver {Function} a function that returns nothing and accepts
* the resolve, reject, and notify functions for a deferred.
* @returns a promise that may be resolved with the given resolve and reject
* functions, or rejected by a thrown exception in resolver
*/
Q.Promise = promise; // ES6
Q.promise = promise;
function promise(resolver) {
if (typeof resolver !== "function") {
throw new TypeError("resolver must be a function.");
}
var deferred = defer();
try {
resolver(deferred.resolve, deferred.reject, deferred.notify);
} catch (reason) {
deferred.reject(reason);
}
return deferred.promise;
}
promise.race = race; // ES6
promise.all = all; // ES6
promise.reject = reject; // ES6
promise.resolve = Q; // ES6
// XXX experimental. This method is a way to denote that a local value is
// serializable and should be immediately dispatched to a remote upon request,
// instead of passing a reference.
Q.passByCopy = function (object) {
//freeze(object);
//passByCopies.set(object, true);
return object;
};
Promise.prototype.passByCopy = function () {
//freeze(object);
//passByCopies.set(object, true);
return this;
};
/**
* If two promises eventually fulfill to the same value, promises that value,
* but otherwise rejects.
* @param x {Any*}
* @param y {Any*}
* @returns {Any*} a promise for x and y if they are the same, but a rejection
* otherwise.
*
*/
Q.join = function (x, y) {
return Q(x).join(y);
};
Promise.prototype.join = function (that) {
return Q([this, that]).spread(function (x, y) {
if (x === y) {
// TODO: "===" should be Object.is or equiv
return x;
} else {
throw new Error("Can't join: not the same: " + x + " " + y);
}
});
};
/**
* Returns a promise for the first of an array of promises to become settled.
* @param answers {Array[Any*]} promises to race
* @returns {Any*} the first promise to be settled
*/
Q.race = race;
function race(answerPs) {
return promise(function(resolve, reject) {
// Switch to this once we can assume at least ES5
// answerPs.forEach(function(answerP) {
// Q(answerP).then(resolve, reject);
// });
// Use this in the meantime
for (var i = 0, len = answerPs.length; i < len; i++) {
Q(answerPs[i]).then(resolve, reject);
}
});
}
Promise.prototype.race = function () {
return this.then(Q.race);
};
/**
* Constructs a Promise with a promise descriptor object and optional fallback
* function. The descriptor contains methods like when(rejected), get(name),
* set(name, value), post(name, args), and delete(name), which all
* return either a value, a promise for a value, or a rejection. The fallback
* accepts the operation name, a resolver, and any further arguments that would
* have been forwarded to the appropriate method above had a method been
* provided with the proper name. The API makes no guarantees about the nature
* of the returned object, apart from that it is usable whereever promises are
* bought and sold.
*/
Q.makePromise = Promise;
function Promise(descriptor, fallback, inspect) {
if (fallback === void 0) {
fallback = function (op) {
return reject(new Error(
"Promise does not support operation: " + op
));
};
}
if (inspect === void 0) {
inspect = function () {
return {state: "unknown"};
};
}
var promise = object_create(Promise.prototype);
promise.promiseDispatch = function (resolve, op, args) {
var result;
try {
if (descriptor[op]) {
result = descriptor[op].apply(promise, args);
} else {
result = fallback.call(promise, op, args);
}
} catch (exception) {
result = reject(exception);
}
if (resolve) {
resolve(result);
}
};
promise.inspect = inspect;
// XXX deprecated `valueOf` and `exception` support
if (inspect) {
var inspected = inspect();
if (inspected.state === "rejected") {
promise.exception = inspected.reason;
}
promise.valueOf = function () {
var inspected = inspect();
if (inspected.state === "pending" ||
inspected.state === "rejected") {
return promise;
}
return inspected.value;
};
}
return promise;
}
Promise.prototype.toString = function () {
return "[object Promise]";
};
Promise.prototype.then = function (fulfilled, rejected, progressed) {
var self = this;
var deferred = defer();
var done = false; // ensure the untrusted promise makes at most a
// single call to one of the callbacks
function _fulfilled(value) {
try {
return typeof fulfilled === "function" ? fulfilled(value) : value;
} catch (exception) {
return reject(exception);
}
}
function _rejected(exception) {
if (typeof rejected === "function") {
makeStackTraceLong(exception, self);
try {
return rejected(exception);
} catch (newException) {
return reject(newException);
}
}
return reject(exception);
}
function _progressed(value) {
return typeof progressed === "function" ? progressed(value) : value;
}
Q.nextTick(function () {
self.promiseDispatch(function (value) {
if (done) {
return;
}
done = true;
deferred.resolve(_fulfilled(value));
}, "when", [function (exception) {
if (done) {
return;
}
done = true;
deferred.resolve(_rejected(exception));
}]);
});
// Progress propagator need to be attached in the current tick.
self.promiseDispatch(void 0, "when", [void 0, function (value) {
var newValue;
var threw = false;
try {
newValue = _progressed(value);
} catch (e) {
threw = true;
if (Q.onerror) {
Q.onerror(e);
} else {
throw e;
}
}
if (!threw) {
deferred.notify(newValue);
}
}]);
return deferred.promise;
};
Q.tap = function (promise, callback) {
return Q(promise).tap(callback);
};
/**
* Works almost like "finally", but not called for rejections.
* Original resolution value is passed through callback unaffected.
* Callback may return a promise that will be awaited for.
* @param {Function} callback
* @returns {Q.Promise}
* @example
* doSomething()
* .then(...)
* .tap(console.log)
* .then(...);
*/
Promise.prototype.tap = function (callback) {
callback = Q(callback);
return this.then(function (value) {
return callback.fcall(value).thenResolve(value);
});
};
/**
* Registers an observer on a promise.
*
* Guarantees:
*
* 1. that fulfilled and rejected will be called only once.
* 2. that either the fulfilled callback or the rejected callback will be
* called, but not both.
* 3. that fulfilled and rejected will not be called in this turn.
*
* @param value promise or immediate reference to observe
* @param fulfilled function to be called with the fulfilled value
* @param rejected function to be called with the rejection exception
* @param progressed function to be called on any progress notifications
* @return promise for the return value from the invoked callback
*/
Q.when = when;
function when(value, fulfilled, rejected, progressed) {
return Q(value).then(fulfilled, rejected, progressed);
}
Promise.prototype.thenResolve = function (value) {
return this.then(function () { return value; });
};
Q.thenResolve = function (promise, value) {
return Q(promise).thenResolve(value);
};
Promise.prototype.thenReject = function (reason) {
return this.then(function () { throw reason; });
};
Q.thenReject = function (promise, reason) {
return Q(promise).thenReject(reason);
};
/**
* If an object is not a promise, it is as "near" as possible.
* If a promise is rejected, it is as "near" as possible too.
* If it’s a fulfilled promise, the fulfillment value is nearer.
* If it’s a deferred promise and the deferred has been resolved, the
* resolution is "nearer".
* @param object
* @returns most resolved (nearest) form of the object
*/
// XXX should we re-do this?
Q.nearer = nearer;
function nearer(value) {
if (isPromise(value)) {
var inspected = value.inspect();
if (inspected.state === "fulfilled") {
return inspected.value;
}
}
return value;
}
/**
* @returns whether the given object is a promise.
* Otherwise it is a fulfilled value.
*/
Q.isPromise = isPromise;
function isPromise(object) {
return object instanceof Promise;
}
Q.isPromiseAlike = isPromiseAlike;
function isPromiseAlike(object) {
return isObject(object) && typeof object.then === "function";
}
/**
* @returns whether the given object is a pending promise, meaning not
* fulfilled or rejected.
*/
Q.isPending = isPending;
function isPending(object) {
return isPromise(object) && object.inspect().state === "pending";
}
Promise.prototype.isPending = function () {
return this.inspect().state === "pending";
};
/**
* @returns whether the given object is a value or fulfilled
* promise.
*/
Q.isFulfilled = isFulfilled;
function isFulfilled(object) {
return !isPromise(object) || object.inspect().state === "fulfilled";
}
Promise.prototype.isFulfilled = function () {
return this.inspect().state === "fulfilled";
};
/**
* @returns whether the given object is a rejected promise.
*/
Q.isRejected = isRejected;
function isRejected(object) {
return isPromise(object) && object.inspect().state === "rejected";
}
Promise.prototype.isRejected = function () {
return this.inspect().state === "rejected";
};
//// BEGIN UNHANDLED REJECTION TRACKING
// This promise library consumes exceptions thrown in handlers so they can be
// handled by a subsequent promise. The exceptions get added to this array when
// they are created, and removed when they are handled. Note that in ES6 or
// shimmed environments, this would naturally be a `Set`.
var unhandledReasons = [];
var unhandledRejections = [];
var trackUnhandledRejections = true;
function resetUnhandledRejections() {
unhandledReasons.length = 0;
unhandledRejections.length = 0;
if (!trackUnhandledRejections) {
trackUnhandledRejections = true;
}
}
function trackRejection(promise, reason) {
if (!trackUnhandledRejections) {
return;
}
unhandledRejections.push(promise);
if (reason && typeof reason.stack !== "undefined") {
unhandledReasons.push(reason.stack);
} else {
unhandledReasons.push("(no stack) " + reason);
}
}
function untrackRejection(promise) {
if (!trackUnhandledRejections) {
return;
}
var at = array_indexOf(unhandledRejections, promise);
if (at !== -1) {
unhandledRejections.splice(at, 1);
unhandledReasons.splice(at, 1);
}
}
Q.resetUnhandledRejections = resetUnhandledRejections;
Q.getUnhandledReasons = function () {
// Make a copy so that consumers can't interfere with our internal state.
return unhandledReasons.slice();
};
Q.stopUnhandledRejectionTracking = function () {
resetUnhandledRejections();
trackUnhandledRejections = false;
};
resetUnhandledRejections();
//// END UNHANDLED REJECTION TRACKING
/**
* Constructs a rejected promise.
* @param reason value describing the failure
*/
Q.reject = reject;
function reject(reason) {
var rejection = Promise({
"when": function (rejected) {
// note that the error has been handled
if (rejected) {
untrackRejection(this);
}
return rejected ? rejected(reason) : this;
}
}, function fallback() {
return this;
}, function inspect() {
return { state: "rejected", reason: reason };
});
// Note that the reason has not been handled.
trackRejection(rejection, reason);
return rejection;
}
/**
* Constructs a fulfilled promise for an immediate reference.
* @param value immediate reference
*/
Q.fulfill = fulfill;
function fulfill(value) {
return Promise({
"when": function () {
return value;
},
"get": function (name) {
return value[name];
},
"set": function (name, rhs) {
value[name] = rhs;
},
"delete": function (name) {
delete value[name];
},
"post": function (name, args) {
// Mark Miller proposes that post with no name should apply a
// promised function.
if (name === null || name === void 0) {
return value.apply(void 0, args);
} else {
return value[name].apply(value, args);
}
},
"apply": function (thisp, args) {
return value.apply(thisp, args);
},
"keys": function () {
return object_keys(value);
}
}, void 0, function inspect() {
return { state: "fulfilled", value: value };
});
}
/**
* Converts thenables to Q promises.
* @param promise thenable promise
* @returns a Q promise
*/
function coerce(promise) {
var deferred = defer();
Q.nextTick(function () {
try {
promise.then(deferred.resolve, deferred.reject, deferred.notify);
} catch (exception) {
deferred.reject(exception);
}
});
return deferred.promise;
}
/**
* Annotates an object such that it will never be
* transferred away from this process over any promise
* communication channel.
* @param object
* @returns promise a wrapping of that object that
* additionally responds to the "isDef" message
* without a rejection.
*/
Q.master = master;
function master(object) {
return Promise({
"isDef": function () {}
}, function fallback(op, args) {
return dispatch(object, op, args);
}, function () {
return Q(object).inspect();
});
}
/**
* Spreads the values of a promised array of arguments into the
* fulfillment callback.
* @param fulfilled callback that receives variadic arguments from the
* promised array
* @param rejected callback that receives the exception if the promise
* is rejected.
* @returns a promise for the return value or thrown exception of
* either callback.
*/
Q.spread = spread;
function spread(value, fulfilled, rejected) {
return Q(value).spread(fulfilled, rejected);
}
Promise.prototype.spread = function (fulfilled, rejected) {
return this.all().then(function (array) {
return fulfilled.apply(void 0, array);
}, rejected);
};
/**
* The async function is a decorator for generator functions, turning
* them into asynchronous generators. Although generators are only part
* of the newest ECMAScript 6 drafts, this code does not cause syntax
* errors in older engines. This code should continue to work and will
* in fact improve over time as the language improves.
*
* ES6 generators are currently part of V8 version 3.19 with the
* --harmony-generators runtime flag enabled. SpiderMonkey has had them
* for longer, but under an older Python-inspired form. This function
* works on both kinds of generators.
*
* Decorates a generator function such that:
* - it may yield promises
* - execution will continue when that promise is fulfilled
* - the value of the yield expression will be the fulfilled value
* - it returns a promise for the return value (when the generator
* stops iterating)
* - the decorated function returns a promise for the return value
* of the generator or the first rejected promise among those
* yielded.
* - if an error is thrown in the generator, it propagates through
* every following yield until it is caught, or until it escapes
* the generator function altogether, and is translated into a
* rejection for the promise returned by the decorated generator.
*/
Q.async = async;
function async(makeGenerator) {
return function () {
// when verb is "send", arg is a value
// when verb is "throw", arg is an exception
function continuer(verb, arg) {
var result;
// Until V8 3.19 / Chromium 29 is released, SpiderMonkey is the only
// engine that has a deployed base of browsers that support generators.
// However, SM's generators use the Python-inspired semantics of
// outdated ES6 drafts. We would like to support ES6, but we'd also
// like to make it possible to use generators in deployed browsers, so
// we also support Python-style generators. At some point we can remove
// this block.
if (typeof StopIteration === "undefined") {
// ES6 Generators
try {
result = generator[verb](arg);
} catch (exception) {
return reject(exception);
}
if (result.done) {
return Q(result.value);
} else {
return when(result.value, callback, errback);
}
} else {
// SpiderMonkey Generators
// FIXME: Remove this case when SM does ES6 generators.
try {
result = generator[verb](arg);
} catch (exception) {
if (isStopIteration(exception)) {
return Q(exception.value);
} else {
return reject(exception);
}
}
return when(result, callback, errback);
}
}
var generator = makeGenerator.apply(this, arguments);
var callback = continuer.bind(continuer, "next");
var errback = continuer.bind(continuer, "throw");
return callback();
};
}
/**
* The spawn function is a small wrapper around async that immediately
* calls the generator and also ends the promise chain, so that any
* unhandled errors are thrown instead of forwarded to the error
* handler. This is useful because it's extremely common to run
* generators at the top-level to work with libraries.
*/
Q.spawn = spawn;
function spawn(makeGenerator) {
Q.done(Q.async(makeGenerator)());
}
// FIXME: Remove this interface once ES6 generators are in SpiderMonkey.
/**
* Throws a ReturnValue exception to stop an asynchronous generator.
*
* This interface is a stop-gap measure to support generator return
* values in older Firefox/SpiderMonkey. In browsers that support ES6
* generators like Chromium 29, just use "return" in your generator
* functions.
*
* @param value the return value for the surrounding generator
* @throws ReturnValue exception with the value.
* @example
* // ES6 style
* Q.async(function* () {
* var foo = yield getFooPromise();
* var bar = yield getBarPromise();
* return foo + bar;
* })
* // Older SpiderMonkey style
* Q.async(function () {
* var foo = yield getFooPromise();
* var bar = yield getBarPromise();
* Q.return(foo + bar);
* })
*/
Q["return"] = _return;
function _return(value) {
throw new QReturnValue(value);
}
/**
* The promised function decorator ensures that any promise arguments
* are settled and passed as values (`this` is also settled and passed
* as a value). It will also ensure that the result of a function is
* always a promise.
*
* @example
* var add = Q.promised(function (a, b) {
* return a + b;
* });
* add(Q(a), Q(B));
*
* @param {function} callback The function to decorate
* @returns {function} a function that has been decorated.
*/
Q.promised = promised;
function promised(callback) {
return function () {
return spread([this, all(arguments)], function (self, args) {
return callback.apply(self, args);
});
};
}
/**
* sends a message to a value in a future turn
* @param object* the recipient
* @param op the name of the message operation, e.g., "when",
* @param args further arguments to be forwarded to the operation
* @returns result {Promise} a promise for the result of the operation
*/
Q.dispatch = dispatch;
function dispatch(object, op, args) {
return Q(object).dispatch(op, args);
}
Promise.prototype.dispatch = function (op, args) {
var self = this;
var deferred = defer();
Q.nextTick(function () {
self.promiseDispatch(deferred.resolve, op, args);
});
return deferred.promise;
};
/**
* Gets the value of a property in a future turn.
* @param object promise or immediate reference for target object
* @param name name of property to get
* @return promise for the property value
*/
Q.get = function (object, key) {
return Q(object).dispatch("get", [key]);
};
Promise.prototype.get = function (key) {
return this.dispatch("get", [key]);
};
/**
* Sets the value of a property in a future turn.
* @param object promise or immediate reference for object object
* @param name name of property to set
* @param value new value of property
* @return promise for the return value
*/
Q.set = function (object, key, value) {
return Q(object).dispatch("set", [key, value]);
};
Promise.prototype.set = function (key, value) {
return this.dispatch("set", [key, value]);
};
/**
* Deletes a property in a future turn.
* @param object promise or immediate reference for target object
* @param name name of property to delete
* @return promise for the return value
*/
Q.del = // XXX legacy
Q["delete"] = function (object, key) {
return Q(object).dispatch("delete", [key]);
};
Promise.prototype.del = // XXX legacy
Promise.prototype["delete"] = function (key) {
return this.dispatch("delete", [key]);
};
/**
* Invokes a method in a future turn.
* @param object promise or immediate reference for target object
* @param name name of method to invoke
* @param value a value to post, typically an array of
* invocation arguments for promises that
* are ultimately backed with `resolve` values,
* as opposed to those backed with URLs
* wherein the posted value can be any
* JSON serializable object.
* @return promise for the return value
*/
// bound locally because it is used by other methods
Q.mapply = // XXX As proposed by "Redsandro"
Q.post = function (object, name, args) {
return Q(object).dispatch("post", [name, args]);
};
Promise.prototype.mapply = // XXX As proposed by "Redsandro"
Promise.prototype.post = function (name, args) {
return this.dispatch("post", [name, args]);
};
/**
* Invokes a method in a future turn.
* @param object promise or immediate reference for target object
* @param name name of method to invoke
* @param ...args array of invocation arguments
* @return promise for the return value
*/
Q.send = // XXX Mark Miller's proposed parlance
Q.mcall = // XXX As proposed by "Redsandro"
Q.invoke = function (object, name /*...args*/) {
return Q(object).dispatch("post", [name, array_slice(arguments, 2)]);
};
Promise.prototype.send = // XXX Mark Miller's proposed parlance
Promise.prototype.mcall = // XXX As proposed by "Redsandro"
Promise.prototype.invoke = function (name /*...args*/) {
return this.dispatch("post", [name, array_slice(arguments, 1)]);
};
/**
* Applies the promised function in a future turn.
* @param object promise or immediate reference for target function
* @param args array of application arguments
*/
Q.fapply = function (object, args) {
return Q(object).dispatch("apply", [void 0, args]);
};
Promise.prototype.fapply = function (args) {
return this.dispatch("apply", [void 0, args]);
};
/**
* Calls the promised function in a future turn.
* @param object promise or immediate reference for target function
* @param ...args array of application arguments
*/
Q["try"] =
Q.fcall = function (object /* ...args*/) {
return Q(object).dispatch("apply", [void 0, array_slice(arguments, 1)]);
};
Promise.prototype.fcall = function (/*...args*/) {
return this.dispatch("apply", [void 0, array_slice(arguments)]);
};
/**
* Binds the promised function, transforming return values into a fulfilled
* promise and thrown errors into a rejected one.
* @param object promise or immediate reference for target function
* @param ...args array of application arguments
*/
Q.fbind = function (object /*...args*/) {
var promise = Q(object);
var args = array_slice(arguments, 1);
return function fbound() {
return promise.dispatch("apply", [
this,
args.concat(array_slice(arguments))
]);
};
};
Promise.prototype.fbind = function (/*...args*/) {
var promise = this;
var args = array_slice(arguments);
return function fbound() {
return promise.dispatch("apply", [
this,
args.concat(array_slice(arguments))
]);
};
};
/**
* Requests the names of the owned properties of a promised
* object in a future turn.
* @param object promise or immediate reference for target object
* @return promise for the keys of the eventually settled object
*/
Q.keys = function (object) {
return Q(object).dispatch("keys", []);
};
Promise.prototype.keys = function () {
return this.dispatch("keys", []);
};
/**
* Turns an array of promises into a promise for an array. If any of
* the promises gets rejected, the whole array is rejected immediately.
* @param {Array*} an array (or promise for an array) of values (or
* promises for values)
* @returns a promise for an array of the corresponding values
*/
// By Mark Miller
// http://wiki.ecmascript.org/doku.php?id=strawman:concurrency&rev=1308776521#allfulfilled
Q.all = all;
function all(promises) {
return when(promises, function (promises) {
var pendingCount = 0;
var deferred = defer();
array_reduce(promises, function (undefined, promise, index) {
var snapshot;
if (
isPromise(promise) &&
(snapshot = promise.inspect()).state === "fulfilled"
) {
promises[index] = snapshot.value;
} else {
++pendingCount;
when(
promise,
function (value) {
promises[index] = value;
if (--pendingCount === 0) {
deferred.resolve(promises);
}
},
deferred.reject,
function (progress) {
deferred.notify({ index: index, value: progress });
}
);
}
}, void 0);
if (pendingCount === 0) {
deferred.resolve(promises);
}
return deferred.promise;
});
}
Promise.prototype.all = function () {
return all(this);
};
/**
* Returns the first resolved promise of an array. Prior rejected promises are
* ignored. Rejects only if all promises are rejected.
* @param {Array*} an array containing values or promises for values
* @returns a promise fulfilled with the value of the first resolved promise,
* or a rejected promise if all promises are rejected.
*/
Q.any = any;
function any(promises) {
if (promises.length === 0) {
return Q.resolve();
}
var deferred = Q.defer();
var pendingCount = 0;
array_reduce(promises, function(prev, current, index) {
var promise = promises[index];
pendingCount++;
when(promise, onFulfilled, onRejected, onProgress);
function onFulfilled(result) {
deferred.resolve(result);
}
function onRejected() {
pendingCount--;
if (pendingCount === 0) {
deferred.reject(new Error(
"Can't get fulfillment value from any promise, all " +
"promises were rejected."
));
}
}
function onProgress(progress) {
deferred.notify({
index: index,
value: progress
});
}
}, undefined);
return deferred.promise;
}
Promise.prototype.any = function() {
return any(this);
};
/**
* Waits for all promises to be settled, either fulfilled or
* rejected. This is distinct from `all` since that would stop
* waiting at the first rejection. The promise returned by
* `allResolved` will never be rejected.
* @param promises a promise for an array (or an array) of promises
* (or values)
* @return a promise for an array of promises
*/
Q.allResolved = deprecate(allResolved, "allResolved", "allSettled");
function allResolved(promises) {
return when(promises, function (promises) {
promises = array_map(promises, Q);
return when(all(array_map(promises, function (promise) {
return when(promise, noop, noop);
})), function () {
return promises;
});
});
}
Promise.prototype.allResolved = function () {
return allResolved(this);
};
/**
* @see Promise#allSettled
*/
Q.allSettled = allSettled;
function allSettled(promises) {
return Q(promises).allSettled();
}
/**
* Turns an array of promises into a promise for an array of their states (as
* returned by `inspect`) when they have all settled.
* @param {Array[Any*]} values an array (or promise for an array) of values (or
* promises for values)
* @returns {Array[State]} an array of states for the respective values.
*/
Promise.prototype.allSettled = function () {
return this.then(function (promises) {
return all(array_map(promises, function (promise) {
promise = Q(promise);
function regardless() {
return promise.inspect();
}
return promise.then(regardless, regardless);
}));
});
};
/**
* Captures the failure of a promise, giving an oportunity to recover
* with a callback. If the given promise is fulfilled, the returned
* promise is fulfilled.
* @param {Any*} promise for something
* @param {Function} callback to fulfill the returned promise if the
* given promise is rejected
* @returns a promise for the return value of the callback
*/
Q.fail = // XXX legacy
Q["catch"] = function (object, rejected) {
return Q(object).then(void 0, rejected);
};
Promise.prototype.fail = // XXX legacy
Promise.prototype["catch"] = function (rejected) {
return this.then(void 0, rejected);
};
/**
* Attaches a listener that can respond to progress notifications from a
* promise's originating deferred. This listener receives the exact arguments
* passed to ``deferred.notify``.
* @param {Any*} promise for something
* @param {Function} callback to receive any progress notifications
* @returns the given promise, unchanged
*/
Q.progress = progress;
function progress(object, progressed) {
return Q(object).then(void 0, void 0, progressed);
}
Promise.prototype.progress = function (progressed) {
return this.then(void 0, void 0, progressed);
};
/**
* Provides an opportunity to observe the settling of a promise,
* regardless of whether the promise is fulfilled or rejected. Forwards
* the resolution to the returned promise when the callback is done.
* The callback can return a promise to defer completion.
* @param {Any*} promise
* @param {Function} callback to observe the resolution of the given
* promise, takes no arguments.
* @returns a promise for the resolution of the given promise when
* ``fin`` is done.
*/
Q.fin = // XXX legacy
Q["finally"] = function (object, callback) {
return Q(object)["finally"](callback);
};
Promise.prototype.fin = // XXX legacy
Promise.prototype["finally"] = function (callback) {
callback = Q(callback);
return this.then(function (value) {
return callback.fcall().then(function () {
return value;
});
}, function (reason) {
// TODO attempt to recycle the rejection with "this".
return callback.fcall().then(function () {
throw reason;
});
});
};
/**
* Terminates a chain of promises, forcing rejections to be
* thrown as exceptions.
* @param {Any*} promise at the end of a chain of promises
* @returns nothing
*/
Q.done = function (object, fulfilled, rejected, progress) {
return Q(object).done(fulfilled, rejected, progress);
};
Promise.prototype.done = function (fulfilled, rejected, progress) {
var onUnhandledError = function (error) {
// forward to a future turn so that ``when``
// does not catch it and turn it into a rejection.
Q.nextTick(function () {
makeStackTraceLong(error, promise);
if (Q.onerror) {
Q.onerror(error);
} else {
throw error;
}
});
};
// Avoid unnecessary `nextTick`ing via an unnecessary `when`.
var promise = fulfilled || rejected || progress ?
this.then(fulfilled, rejected, progress) :
this;
if (typeof process === "object" && process && process.domain) {
onUnhandledError = process.domain.bind(onUnhandledError);
}
promise.then(void 0, onUnhandledError);
};
/**
* Causes a promise to be rejected if it does not get fulfilled before
* some milliseconds time out.
* @param {Any*} promise
* @param {Number} milliseconds timeout
* @param {Any*} custom error message or Error object (optional)
* @returns a promise for the resolution of the given promise if it is
* fulfilled before the timeout, otherwise rejected.
*/
Q.timeout = function (object, ms, error) {
return Q(object).timeout(ms, error);
};
Promise.prototype.timeout = function (ms, error) {
var deferred = defer();
var timeoutId = setTimeout(function () {
if (!error || "string" === typeof error) {
error = new Error(error || "Timed out after " + ms + " ms");
error.code = "ETIMEDOUT";
}
deferred.reject(error);
}, ms);
this.then(function (value) {
clearTimeout(timeoutId);
deferred.resolve(value);
}, function (exception) {
clearTimeout(timeoutId);
deferred.reject(exception);
}, deferred.notify);
return deferred.promise;
};
/**
* Returns a promise for the given value (or promised value), some
* milliseconds after it resolved. Passes rejections immediately.
* @param {Any*} promise
* @param {Number} milliseconds
* @returns a promise for the resolution of the given promise after milliseconds
* time has elapsed since the resolution of the given promise.
* If the given promise rejects, that is passed immediately.
*/
Q.delay = function (object, timeout) {
if (timeout === void 0) {
timeout = object;
object = void 0;
}
return Q(object).delay(timeout);
};
Promise.prototype.delay = function (timeout) {
return this.then(function (value) {
var deferred = defer();
setTimeout(function () {
deferred.resolve(value);
}, timeout);
return deferred.promise;
});
};
/**
* Passes a continuation to a Node function, which is called with the given
* arguments provided as an array, and returns a promise.
*
* Q.nfapply(FS.readFile, [__filename])
* .then(function (content) {
* })
*
*/
Q.nfapply = function (callback, args) {
return Q(callback).nfapply(args);
};
Promise.prototype.nfapply = function (args) {
var deferred = defer();
var nodeArgs = array_slice(args);
nodeArgs.push(deferred.makeNodeResolver());
this.fapply(nodeArgs).fail(deferred.reject);
return deferred.promise;
};
/**
* Passes a continuation to a Node function, which is called with the given
* arguments provided individually, and returns a promise.
* @example
* Q.nfcall(FS.readFile, __filename)
* .then(function (content) {
* })
*
*/
Q.nfcall = function (callback /*...args*/) {
var args = array_slice(arguments, 1);
return Q(callback).nfapply(args);
};
Promise.prototype.nfcall = function (/*...args*/) {
var nodeArgs = array_slice(arguments);
var deferred = defer();
nodeArgs.push(deferred.makeNodeResolver());
this.fapply(nodeArgs).fail(deferred.reject);
return deferred.promise;
};
/**
* Wraps a NodeJS continuation passing function and returns an equivalent
* version that returns a promise.
* @example
* Q.nfbind(FS.readFile, __filename)("utf-8")
* .then(console.log)
* .done()
*/
Q.nfbind =
Q.denodeify = function (callback /*...args*/) {
var baseArgs = array_slice(arguments, 1);
return function () {
var nodeArgs = baseArgs.concat(array_slice(arguments));
var deferred = defer();
nodeArgs.push(deferred.makeNodeResolver());
Q(callback).fapply(nodeArgs).fail(deferred.reject);
return deferred.promise;
};
};
Promise.prototype.nfbind =
Promise.prototype.denodeify = function (/*...args*/) {
var args = array_slice(arguments);
args.unshift(this);
return Q.denodeify.apply(void 0, args);
};
Q.nbind = function (callback, thisp /*...args*/) {
var baseArgs = array_slice(arguments, 2);
return function () {
var nodeArgs = baseArgs.concat(array_slice(arguments));
var deferred = defer();
nodeArgs.push(deferred.makeNodeResolver());
function bound() {
return callback.apply(thisp, arguments);
}
Q(bound).fapply(nodeArgs).fail(deferred.reject);
return deferred.promise;
};
};
Promise.prototype.nbind = function (/*thisp, ...args*/) {
var args = array_slice(arguments, 0);
args.unshift(this);
return Q.nbind.apply(void 0, args);
};
/**
* Calls a method of a Node-style object that accepts a Node-style
* callback with a given array of arguments, plus a provided callback.
* @param object an object that has the named method
* @param {String} name name of the method of object
* @param {Array} args arguments to pass to the method; the callback
* will be provided by Q and appended to these arguments.
* @returns a promise for the value or error
*/
Q.nmapply = // XXX As proposed by "Redsandro"
Q.npost = function (object, name, args) {
return Q(object).npost(name, args);
};
Promise.prototype.nmapply = // XXX As proposed by "Redsandro"
Promise.prototype.npost = function (name, args) {
var nodeArgs = array_slice(args || []);
var deferred = defer();
nodeArgs.push(deferred.makeNodeResolver());
this.dispatch("post", [name, nodeArgs]).fail(deferred.reject);
return deferred.promise;
};
/**
* Calls a method of a Node-style object that accepts a Node-style
* callback, forwarding the given variadic arguments, plus a provided
* callback argument.
* @param object an object that has the named method
* @param {String} name name of the method of object
* @param ...args arguments to pass to the method; the callback will
* be provided by Q and appended to these arguments.
* @returns a promise for the value or error
*/
Q.nsend = // XXX Based on Mark Miller's proposed "send"
Q.nmcall = // XXX Based on "Redsandro's" proposal
Q.ninvoke = function (object, name /*...args*/) {
var nodeArgs = array_slice(arguments, 2);
var deferred = defer();
nodeArgs.push(deferred.makeNodeResolver());
Q(object).dispatch("post", [name, nodeArgs]).fail(deferred.reject);
return deferred.promise;
};
Promise.prototype.nsend = // XXX Based on Mark Miller's proposed "send"
Promise.prototype.nmcall = // XXX Based on "Redsandro's" proposal
Promise.prototype.ninvoke = function (name /*...args*/) {
var nodeArgs = array_slice(arguments, 1);
var deferred = defer();
nodeArgs.push(deferred.makeNodeResolver());
this.dispatch("post", [name, nodeArgs]).fail(deferred.reject);
return deferred.promise;
};
/**
* If a function would like to support both Node continuation-passing-style and
* promise-returning-style, it can end its internal promise chain with
* `nodeify(nodeback)`, forwarding the optional nodeback argument. If the user
* elects to use a nodeback, the result will be sent there. If they do not
* pass a nodeback, they will receive the result promise.
* @param object a result (or a promise for a result)
* @param {Function} nodeback a Node.js-style callback
* @returns either the promise or nothing
*/
Q.nodeify = nodeify;
function nodeify(object, nodeback) {
return Q(object).nodeify(nodeback);
}
Promise.prototype.nodeify = function (nodeback) {
if (nodeback) {
this.then(function (value) {
Q.nextTick(function () {
nodeback(null, value);
});
}, function (error) {
Q.nextTick(function () {
nodeback(error);
});
});
} else {
return this;
}
};
// All code before this point will be filtered from stack traces.
var qEndingLine = captureLine();
return Q;
});
},{"__browserify_process":6}],8:[function(require,module,exports){
'use strict';
var Subkit = require('Subkit');
module.exports = Subkit;
angular
.module('subkit', [])
.value('Subkit', Subkit);
angular
.module('subkit')
.factory('angularSubkit', function($rootScope) {
return function(ref, name, initial) {
var ask = new AngularSubkit(ref);
return ask.associate($rootScope, name, initial);
};
});
var AngularSubkit = function(ref) {
if (typeof ref == 'string') throw new Error('Please provide a Subkit reference instead of a URL, eg: new Subkit(url)');
this._fRef = ref;
};
AngularSubkit.prototype = {
associate: function($rootScope, name, initial) {
var self = this;
if(!$rootScope[name]) $rootScope[name] = initial;
var storeRef = this._fRef.stores(name);
storeRef
.get()
.done(function(data){
$rootScope[name] = data.results;
$rootScope.$apply();
});
storeRef.on(function(error, data) {
if(error) return console.log(error);
if(initial instanceof Array){
if(data.$metadata.type === 'put') {
var map = $rootScope[name].map(function(itm){ return itm.$key; });
var itmIdx = map.indexOf(data.$metadata.key);
if(itmIdx!==-1) {
$rootScope[name][itmIdx].$metadata = data.$metadata;
$rootScope[name][itmIdx].$payload = data.$payload;
}
else $rootScope[name].unshift(data);
}
if(data.$metadata.type === 'del') {
var map = $rootScope[name].map(function(itm){ return itm.$key; });
var itmIdx = map.indexOf(data.$metadata.key);
if(itmIdx !== -1) $rootScope[name].splice(itmIdx, 1);
}
} else if(initial instanceof Object){
$rootScope[name] = data;
}
$rootScope.$apply();
});
return storeRef;
},
disassociate: function(name) {
var self = this;
this._fRef.off(name);
},
_log: function(msg) {
if (console && console.log) {
console.log(msg);
}
}
};
},{"Subkit":5}]},{},[8])
(8)
});
; | mit |
Tsingbo-Kooboo/Kooboo.CMS.Toolkit | Web/Areas/Sites/Scripts/inlineEdit/inline/htmlBlock.js | 713 | /*
* htmlBlock edit
* author: ronglin
* create date: 2011.04.02
*/
(function (ctx, $) {
var htmlBlockClass = function (config) {
htmlBlockClass.superclass.constructor.call(this, config);
};
ctx.extend(htmlBlockClass, ctx.htmlClass, {
createMenu: function () {
htmlBlockClass.superclass.createMenu.call(this);
this.menu.setTitle(this.params.blockName);
},
getParams: function () {
return {
dataType: this.startNode.attr('dataType'),
blockName: this.startNode.attr('blockName')
};
}
});
// register
ctx.htmlBlockClass = htmlBlockClass;
})(yardi, jQuery);
| mit |