code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php // vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: /** * Toc rule end renderer for Xhtml * * PHP versions 4 and 5 * * @category Text * @package Text_Wiki * @author Paul M. Jones <pmjones@php.net> * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 * @version CVS: $Id: Toc.php,v 1.9 2005/07/30 08:03:29 toggg Exp $ * @link http://pear.php.net/package/Text_Wiki */ /** * This class inserts a table of content in XHTML. * * @category Text * @package Text_Wiki * @author Paul M. Jones <pmjones@php.net> * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 * @version Release: @package_version@ * @link http://pear.php.net/package/Text_Wiki */ class Text_Wiki_Render_Xhtml_Toc extends Text_Wiki_Render { var $conf = array( 'css_list' => null, 'css_item' => null, 'title' => '<strong>Table of Contents</strong>', 'div_id' => 'toc', 'collapse' => true ); var $min = 2; /** * * Renders a token into text matching the requested format. * * @access public * * @param array $options The "options" portion of the token (second * element). * * @return string The text rendered from the token options. * */ function token($options) { // type, id, level, count, attr extract($options); switch ($type) { case 'list_start': $css = $this->getConf('css_list'); $html = ''; // collapse div within a table? if ($this->getConf('collapse')) { $html .= '<table border="0" cellspacing="0" cellpadding="0">'; $html .= "<tr><td>\n"; } // add the div, class, and id $html .= '<div'; if ($css) { $html .= " class=\"$css\""; } $div_id = $this->getConf('div_id'); if ($div_id) { $html .= " id=\"$div_id\""; } // add the title, and done $html .= '>'; $html .= $this->getConf('title'); return $html; break; case 'list_end': if ($this->getConf('collapse')) { return "\n</div>\n</td></tr></table>\n\n"; } else { return "\n</div>\n\n"; } break; case 'item_start': $html = "\n\t<div"; $css = $this->getConf('css_item'); if ($css) { $html .= " class=\"$css\""; } $pad = ($level - $this->min); $html .= " style=\"margin-left: {$pad}em;\">"; $html .= "<a href=\"#$id\">"; return $html; break; case 'item_end': return "</a></div>"; break; } } } ?>
idoxlr8/HVAC
xataface/lib/Text/Wiki/Render/Xhtml/Toc.php
PHP
gpl-2.0
2,899
module Rails module VERSION #:nodoc: MAJOR = 2 MINOR = 1 TINY = 0 STRING = [MAJOR, MINOR, TINY].join('.') end end
YSATools/The-Ward-Menu
vendor/railties/lib/rails/version.rb
Ruby
gpl-2.0
136
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.org * * 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, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "Control.h" #include "LanguageHook.h" #include "AddonUtils.h" #include "guilib/GUILabel.h" #include "guilib/GUIFontManager.h" #include "guilib/GUILabelControl.h" #include "guilib/GUIFadeLabelControl.h" #include "guilib/GUITextBox.h" #include "guilib/GUIButtonControl.h" #include "guilib/GUICheckMarkControl.h" #include "guilib/GUIImage.h" #include "guilib/GUIListContainer.h" #include "guilib/GUIProgressControl.h" #include "guilib/GUISliderControl.h" #include "guilib/GUIRadioButtonControl.h" #include "GUIInfoManager.h" #include "guilib/GUIWindowManager.h" #include "guilib/GUIEditControl.h" #include "guilib/GUIControlFactory.h" #include "listproviders/StaticProvider.h" #include "utils/XBMCTinyXML.h" #include "utils/StringUtils.h" namespace XBMCAddon { namespace xbmcgui { // ============================================================ // ============================================================ // ============================================================ ControlFadeLabel::ControlFadeLabel(long x, long y, long width, long height, const char* font, const char* _textColor, long _alignment) : strFont("font13"), textColor(0xffffffff), align(_alignment) { dwPosX = x; dwPosY = y; dwWidth = width; dwHeight = height; if (font) strFont = font; if (_textColor) sscanf(_textColor, "%x", &textColor); pGUIControl = NULL; } void ControlFadeLabel::addLabel(const String& label) throw (UnimplementedException) { CGUIMessage msg(GUI_MSG_LABEL_ADD, iParentId, iControlId); msg.SetLabel(label); g_windowManager.SendThreadMessage(msg, iParentId); } void ControlFadeLabel::reset() throw (UnimplementedException) { CGUIMessage msg(GUI_MSG_LABEL_RESET, iParentId, iControlId); vecLabels.clear(); g_windowManager.SendThreadMessage(msg, iParentId); } CGUIControl* ControlFadeLabel::Create() throw (WindowException) { CLabelInfo label; label.font = g_fontManager.GetFont(strFont); label.textColor = label.focusedColor = textColor; label.align = align; pGUIControl = new CGUIFadeLabelControl( iParentId, iControlId, (float)dwPosX, (float)dwPosY, (float)dwWidth, (float)dwHeight, label, true, 0, true); CGUIMessage msg(GUI_MSG_LABEL_RESET, iParentId, iControlId); pGUIControl->OnMessage(msg); return pGUIControl; } // ============================================================ // ============================================================ // ============================================================ ControlTextBox::ControlTextBox(long x, long y, long width, long height, const char* font, const char* _textColor) : strFont("font13"), textColor(0xffffffff) { dwPosX = x; dwPosY = y; dwWidth = width; dwHeight = height; if (font) strFont = font; if (_textColor) sscanf(_textColor, "%x", &textColor); } void ControlTextBox::setText(const String& text) throw(UnimplementedException) { // create message CGUIMessage msg(GUI_MSG_LABEL_SET, iParentId, iControlId); msg.SetLabel(text); // send message g_windowManager.SendThreadMessage(msg, iParentId); } String ControlTextBox::getText() throw (UnimplementedException) { if (!pGUIControl) return NULL; LOCKGUI; return ((CGUITextBox*) pGUIControl)->GetDescription(); } void ControlTextBox::reset() throw(UnimplementedException) { // create message CGUIMessage msg(GUI_MSG_LABEL_RESET, iParentId, iControlId); g_windowManager.SendThreadMessage(msg, iParentId); } void ControlTextBox::scroll(long position) throw(UnimplementedException) { static_cast<CGUITextBox*>(pGUIControl)->Scroll((int)position); } CGUIControl* ControlTextBox::Create() throw (WindowException) { // create textbox CLabelInfo label; label.font = g_fontManager.GetFont(strFont); label.textColor = label.focusedColor = textColor; pGUIControl = new CGUITextBox(iParentId, iControlId, (float)dwPosX, (float)dwPosY, (float)dwWidth, (float)dwHeight, label); // reset textbox CGUIMessage msg(GUI_MSG_LABEL_RESET, iParentId, iControlId); pGUIControl->OnMessage(msg); return pGUIControl; } // ============================================================ // ============================================================ // ============================================================ ControlButton::ControlButton(long x, long y, long width, long height, const String& label, const char* focusTexture, const char* noFocusTexture, long _textOffsetX, long _textOffsetY, long alignment, const char* font, const char* _textColor, const char* _disabledColor, long angle, const char* _shadowColor, const char* _focusedColor) : textOffsetX(_textOffsetX), textOffsetY(_textOffsetY), align(alignment), strFont("font13"), textColor(0xffffffff), disabledColor(0x60ffffff), iAngle(angle), shadowColor(0), focusedColor(0xffffffff) { dwPosX = x; dwPosY = y; dwWidth = width; dwHeight = height; strText = label; // if texture is supplied use it, else get default ones strTextureFocus = focusTexture ? focusTexture : XBMCAddonUtils::getDefaultImage((char*)"button", (char*)"texturefocus", (char*)"button-focus.png"); strTextureNoFocus = noFocusTexture ? noFocusTexture : XBMCAddonUtils::getDefaultImage((char*)"button", (char*)"texturenofocus", (char*)"button-nofocus.jpg"); if (font) strFont = font; if (_textColor) sscanf( _textColor, "%x", &textColor ); if (_disabledColor) sscanf( _disabledColor, "%x", &disabledColor ); if (_shadowColor) sscanf( _shadowColor, "%x", &shadowColor ); if (_focusedColor) sscanf( _focusedColor, "%x", &focusedColor ); } void ControlButton::setLabel(const String& label, const char* font, const char* _textColor, const char* _disabledColor, const char* _shadowColor, const char* _focusedColor, const String& label2) throw (UnimplementedException) { if (!label.empty()) strText = label; if (!label2.empty()) strText2 = label2; if (font) strFont = font; if (_textColor) sscanf(_textColor, "%x", &textColor); if (_disabledColor) sscanf( _disabledColor, "%x", &disabledColor ); if (_shadowColor) sscanf(_shadowColor, "%x", &shadowColor); if (_focusedColor) sscanf(_focusedColor, "%x", &focusedColor); if (pGUIControl) { LOCKGUI; ((CGUIButtonControl*)pGUIControl)->PythonSetLabel(strFont, strText, textColor, shadowColor, focusedColor); ((CGUIButtonControl*)pGUIControl)->SetLabel2(strText2); ((CGUIButtonControl*)pGUIControl)->PythonSetDisabledColor(disabledColor); } } void ControlButton::setDisabledColor(const char* color) throw (UnimplementedException) { if (color) sscanf(color, "%x", &disabledColor); if (pGUIControl) { LOCKGUI; ((CGUIButtonControl*)pGUIControl)->PythonSetDisabledColor(disabledColor); } } String ControlButton::getLabel() throw (UnimplementedException) { if (!pGUIControl) return NULL; LOCKGUI; return ((CGUIButtonControl*) pGUIControl)->GetLabel(); } String ControlButton::getLabel2() throw (UnimplementedException) { if (!pGUIControl) return NULL; LOCKGUI; return ((CGUIButtonControl*) pGUIControl)->GetLabel2(); } CGUIControl* ControlButton::Create() throw (WindowException) { CLabelInfo label; label.font = g_fontManager.GetFont(strFont); label.textColor = textColor; label.disabledColor = disabledColor; label.shadowColor = shadowColor; label.focusedColor = focusedColor; label.align = align; label.offsetX = (float)textOffsetX; label.offsetY = (float)textOffsetY; label.angle = (float)-iAngle; pGUIControl = new CGUIButtonControl( iParentId, iControlId, (float)dwPosX, (float)dwPosY, (float)dwWidth, (float)dwHeight, CTextureInfo(strTextureFocus), CTextureInfo(strTextureNoFocus), label); CGUIButtonControl* pGuiButtonControl = (CGUIButtonControl*)pGUIControl; pGuiButtonControl->SetLabel(strText); pGuiButtonControl->SetLabel2(strText2); return pGUIControl; } // ============================================================ // ============================================================ // ============================================================ ControlCheckMark::ControlCheckMark(long x, long y, long width, long height, const String& label, const char* focusTexture, const char* noFocusTexture, long _checkWidth, long _checkHeight, long _alignment, const char* font, const char* _textColor, const char* _disabledColor) : strFont("font13"), checkWidth(_checkWidth), checkHeight(_checkHeight), align(_alignment), textColor(0xffffffff), disabledColor(0x60ffffff) { dwPosX = x; dwPosY = y; dwWidth = width; dwHeight = height; strText = label; if (font) strFont = font; if (_textColor) sscanf(_textColor, "%x", &textColor); if (_disabledColor) sscanf( _disabledColor, "%x", &disabledColor ); strTextureFocus = focusTexture ? focusTexture : XBMCAddonUtils::getDefaultImage((char*)"checkmark", (char*)"texturefocus", (char*)"check-box.png"); strTextureNoFocus = noFocusTexture ? noFocusTexture : XBMCAddonUtils::getDefaultImage((char*)"checkmark", (char*)"texturenofocus", (char*)"check-boxNF.png"); } bool ControlCheckMark::getSelected() throw (UnimplementedException) { bool isSelected = false; if (pGUIControl) { LOCKGUI; isSelected = ((CGUICheckMarkControl*)pGUIControl)->GetSelected(); } return isSelected; } void ControlCheckMark::setSelected(bool selected) throw (UnimplementedException) { if (pGUIControl) { LOCKGUI; ((CGUICheckMarkControl*)pGUIControl)->SetSelected(selected); } } void ControlCheckMark::setLabel(const String& label, const char* font, const char* _textColor, const char* _disabledColor, const char* _shadowColor, const char* _focusedColor, const String& label2) throw (UnimplementedException) { if (font) strFont = font; if (_textColor) sscanf(_textColor, "%x", &textColor); if (_disabledColor) sscanf(_disabledColor, "%x", &disabledColor); if (pGUIControl) { LOCKGUI; ((CGUICheckMarkControl*)pGUIControl)->PythonSetLabel(strFont,strText,textColor); ((CGUICheckMarkControl*)pGUIControl)->PythonSetDisabledColor(disabledColor); } } void ControlCheckMark::setDisabledColor(const char* color) throw (UnimplementedException) { if (color) sscanf(color, "%x", &disabledColor); if (pGUIControl) { LOCKGUI; ((CGUICheckMarkControl*)pGUIControl)->PythonSetDisabledColor( disabledColor ); } } CGUIControl* ControlCheckMark::Create() throw (WindowException) { CLabelInfo label; label.disabledColor = disabledColor; label.textColor = label.focusedColor = textColor; label.font = g_fontManager.GetFont(strFont); label.align = align; CTextureInfo imageFocus(strTextureFocus); CTextureInfo imageNoFocus(strTextureNoFocus); pGUIControl = new CGUICheckMarkControl( iParentId, iControlId, (float)dwPosX, (float)dwPosY, (float)dwWidth, (float)dwHeight, imageFocus, imageNoFocus, (float)checkWidth, (float)checkHeight, label ); CGUICheckMarkControl* pGuiCheckMarkControl = (CGUICheckMarkControl*)pGUIControl; pGuiCheckMarkControl->SetLabel(strText); return pGUIControl; } // ============================================================ // ============================================================ // ============================================================ ControlImage::ControlImage(long x, long y, long width, long height, const char* filename, long aRatio, const char* _colorDiffuse): aspectRatio(aRatio), colorDiffuse(0) { dwPosX = x; dwPosY = y; dwWidth = width; dwHeight = height; // check if filename exists strFileName = filename; if (_colorDiffuse) sscanf(_colorDiffuse, "%x", &colorDiffuse); } void ControlImage::setImage(const char* imageFilename, const bool useCache) throw (UnimplementedException) { strFileName = imageFilename; LOCKGUI; if (pGUIControl) ((CGUIImage*)pGUIControl)->SetFileName(strFileName, false, useCache); } void ControlImage::setColorDiffuse(const char* cColorDiffuse) throw (UnimplementedException) { if (cColorDiffuse) sscanf(cColorDiffuse, "%x", &colorDiffuse); else colorDiffuse = 0; LOCKGUI; if (pGUIControl) ((CGUIImage *)pGUIControl)->SetColorDiffuse(colorDiffuse); } CGUIControl* ControlImage::Create() throw (WindowException) { pGUIControl = new CGUIImage(iParentId, iControlId, (float)dwPosX, (float)dwPosY, (float)dwWidth, (float)dwHeight, CTextureInfo(strFileName)); if (pGUIControl && aspectRatio <= CAspectRatio::AR_KEEP) ((CGUIImage *)pGUIControl)->SetAspectRatio((CAspectRatio::ASPECT_RATIO)aspectRatio); if (pGUIControl && colorDiffuse) ((CGUIImage *)pGUIControl)->SetColorDiffuse(colorDiffuse); return pGUIControl; } // ============================================================ // ============================================================ // ============================================================ ControlProgress::ControlProgress(long x, long y, long width, long height, const char* texturebg, const char* textureleft, const char* texturemid, const char* textureright, const char* textureoverlay) { dwPosX = x; dwPosY = y; dwWidth = width; dwHeight = height; // if texture is supplied use it, else get default ones strTextureBg = texturebg ? texturebg : XBMCAddonUtils::getDefaultImage((char*)"progress", (char*)"texturebg", (char*)"progress_back.png"); strTextureLeft = textureleft ? textureleft : XBMCAddonUtils::getDefaultImage((char*)"progress", (char*)"lefttexture", (char*)"progress_left.png"); strTextureMid = texturemid ? texturemid : XBMCAddonUtils::getDefaultImage((char*)"progress", (char*)"midtexture", (char*)"progress_mid.png"); strTextureRight = textureright ? textureright : XBMCAddonUtils::getDefaultImage((char*)"progress", (char*)"righttexture", (char*)"progress_right.png"); strTextureOverlay = textureoverlay ? textureoverlay : XBMCAddonUtils::getDefaultImage((char*)"progress", (char*)"overlaytexture", (char*)"progress_over.png"); } void ControlProgress::setPercent(float pct) throw (UnimplementedException) { if (pGUIControl) ((CGUIProgressControl*)pGUIControl)->SetPercentage(pct); } float ControlProgress::getPercent() throw (UnimplementedException) { return (pGUIControl) ? ((CGUIProgressControl*)pGUIControl)->GetPercentage() : 0.0f; } CGUIControl* ControlProgress::Create() throw (WindowException) { pGUIControl = new CGUIProgressControl(iParentId, iControlId, (float)dwPosX, (float)dwPosY, (float)dwWidth,(float)dwHeight, CTextureInfo(strTextureBg), CTextureInfo(strTextureLeft), CTextureInfo(strTextureMid), CTextureInfo(strTextureRight), CTextureInfo(strTextureOverlay)); if (pGUIControl && colorDiffuse) ((CGUIProgressControl *)pGUIControl)->SetColorDiffuse(colorDiffuse); return pGUIControl; } // ============================================================ // ============================================================ // ============================================================ ControlSlider::ControlSlider(long x, long y, long width, long height, const char* textureback, const char* texture, const char* texturefocus) { dwPosX = x; dwPosY = y; dwWidth = width; dwHeight = height; // if texture is supplied use it, else get default ones strTextureBack = textureback ? textureback : XBMCAddonUtils::getDefaultImage((char*)"slider", (char*)"texturesliderbar", (char*)"osd_slider_bg_2.png"); strTexture = texture ? texture : XBMCAddonUtils::getDefaultImage((char*)"slider", (char*)"textureslidernib", (char*)"osd_slider_nibNF.png"); strTextureFoc = texturefocus ? texturefocus : XBMCAddonUtils::getDefaultImage((char*)"slider", (char*)"textureslidernibfocus", (char*)"osd_slider_nib.png"); } float ControlSlider::getPercent() throw (UnimplementedException) { return (pGUIControl) ? ((CGUISliderControl*)pGUIControl)->GetPercentage() : 0.0f; } void ControlSlider::setPercent(float pct) throw (UnimplementedException) { if (pGUIControl) ((CGUISliderControl*)pGUIControl)->SetPercentage(pct); } CGUIControl* ControlSlider::Create () throw (WindowException) { pGUIControl = new CGUISliderControl(iParentId, iControlId,(float)dwPosX, (float)dwPosY, (float)dwWidth,(float)dwHeight, CTextureInfo(strTextureBack),CTextureInfo(strTexture), CTextureInfo(strTextureFoc),0); return pGUIControl; } // ============================================================ // ============================================================ // ============================================================ ControlGroup::ControlGroup(long x, long y, long width, long height) { dwPosX = x; dwPosY = y; dwWidth = width; dwHeight = height; } CGUIControl* ControlGroup::Create() throw (WindowException) { pGUIControl = new CGUIControlGroup(iParentId, iControlId, (float) dwPosX, (float) dwPosY, (float) dwWidth, (float) dwHeight); return pGUIControl; } // ============================================================ // ============================================================ // ============================================================ ControlRadioButton::ControlRadioButton(long x, long y, long width, long height, const String& label, const char* focusOnTexture, const char* noFocusOnTexture, const char* focusOffTexture, const char* noFocusOffTexture, const char* focusTexture, const char* noFocusTexture, long _textOffsetX, long _textOffsetY, long alignment, const char* font, const char* _textColor, const char* _disabledColor, long angle, const char* _shadowColor, const char* _focusedColor) : strFont("font13"), textColor(0xffffffff), disabledColor(0x60ffffff), textOffsetX(_textOffsetX), textOffsetY(_textOffsetY), align(alignment), iAngle(angle), shadowColor(0), focusedColor(0xffffffff) { dwPosX = x; dwPosY = y; dwWidth = width; dwHeight = height; strText = label; // if texture is supplied use it, else get default ones strTextureFocus = focusTexture ? focusTexture : XBMCAddonUtils::getDefaultImage((char*)"button", (char*)"texturefocus", (char*)"button-focus.png"); strTextureNoFocus = noFocusTexture ? noFocusTexture : XBMCAddonUtils::getDefaultImage((char*)"button", (char*)"texturenofocus", (char*)"button-nofocus.jpg"); if (focusOnTexture && noFocusOnTexture) { strTextureRadioOnFocus = focusOnTexture; strTextureRadioOnNoFocus = noFocusOnTexture; } else { strTextureRadioOnFocus = strTextureRadioOnNoFocus = focusTexture ? focusTexture : XBMCAddonUtils::getDefaultImage((char*)"radiobutton", (char*)"textureradiofocus", (char*)"radiobutton-focus.png"); } if (focusOffTexture && noFocusOffTexture) { strTextureRadioOffFocus = focusOffTexture; strTextureRadioOffNoFocus = noFocusOffTexture; } else { strTextureRadioOffFocus = strTextureRadioOffNoFocus = noFocusTexture ? noFocusTexture : XBMCAddonUtils::getDefaultImage((char*)"radiobutton", (char*)"textureradiofocus", (char*)"radiobutton-focus.png"); } if (font) strFont = font; if (_textColor) sscanf( _textColor, "%x", &textColor ); if (_disabledColor) sscanf( _disabledColor, "%x", &disabledColor ); if (_shadowColor) sscanf( _shadowColor, "%x", &shadowColor ); if (_focusedColor) sscanf( _focusedColor, "%x", &focusedColor ); } void ControlRadioButton::setSelected(bool selected) throw (UnimplementedException) { if (pGUIControl) { LOCKGUI; ((CGUIRadioButtonControl*)pGUIControl)->SetSelected(selected); } } bool ControlRadioButton::isSelected() throw (UnimplementedException) { bool isSelected = false; if (pGUIControl) { LOCKGUI; isSelected = ((CGUIRadioButtonControl*)pGUIControl)->IsSelected(); } return isSelected; } void ControlRadioButton::setLabel(const String& label, const char* font, const char* _textColor, const char* _disabledColor, const char* _shadowColor, const char* _focusedColor, const String& label2) throw (UnimplementedException) { if (!label.empty()) strText = label; if (font) strFont = font; if (_textColor) sscanf(_textColor, "%x", &textColor); if (_disabledColor) sscanf( _disabledColor, "%x", &disabledColor ); if (_shadowColor) sscanf(_shadowColor, "%x", &shadowColor); if (_focusedColor) sscanf(_focusedColor, "%x", &focusedColor); if (pGUIControl) { LOCKGUI; ((CGUIRadioButtonControl*)pGUIControl)->PythonSetLabel(strFont, strText, textColor, shadowColor, focusedColor); ((CGUIRadioButtonControl*)pGUIControl)->PythonSetDisabledColor(disabledColor); } } void ControlRadioButton::setRadioDimension(long x, long y, long width, long height) throw (UnimplementedException) { dwPosX = x; dwPosY = y; dwWidth = width; dwHeight = height; if (pGUIControl) { LOCKGUI; ((CGUIRadioButtonControl*)pGUIControl)->SetRadioDimensions((float)dwPosX, (float)dwPosY, (float)dwWidth, (float)dwHeight); } } CGUIControl* ControlRadioButton::Create() throw (WindowException) { CLabelInfo label; label.font = g_fontManager.GetFont(strFont); label.textColor = textColor; label.disabledColor = disabledColor; label.shadowColor = shadowColor; label.focusedColor = focusedColor; label.align = align; label.offsetX = (float)textOffsetX; label.offsetY = (float)textOffsetY; label.angle = (float)-iAngle; pGUIControl = new CGUIRadioButtonControl( iParentId, iControlId, (float)dwPosX, (float)dwPosY, (float)dwWidth, (float)dwHeight, CTextureInfo(strTextureFocus), CTextureInfo(strTextureNoFocus), label, CTextureInfo(strTextureRadioOnFocus), CTextureInfo(strTextureRadioOnNoFocus), CTextureInfo(strTextureRadioOffFocus), CTextureInfo(strTextureRadioOffNoFocus)); CGUIRadioButtonControl* pGuiButtonControl = (CGUIRadioButtonControl*)pGUIControl; pGuiButtonControl->SetLabel(strText); return pGUIControl; } // ============================================================ // ============================================================ // ============================================================ Control::~Control() { deallocating(); } CGUIControl* Control::Create() throw (WindowException) { throw WindowException("Object is a Control, but can't be added to a window"); } std::vector<int> Control::getPosition() { std::vector<int> ret(2); ret[0] = dwPosX; ret[1] = dwPosY; return ret; } void Control::setEnabled(bool enabled) { DelayedCallGuard dcguard(languageHook); LOCKGUI; if (pGUIControl) pGUIControl->SetEnabled(enabled); } void Control::setVisible(bool visible) { DelayedCallGuard dcguard(languageHook); LOCKGUI; if (pGUIControl) pGUIControl->SetVisible(visible); } void Control::setVisibleCondition(const char* visible, bool allowHiddenFocus) { DelayedCallGuard dcguard(languageHook); LOCKGUI; if (pGUIControl) pGUIControl->SetVisibleCondition(visible, allowHiddenFocus ? "true" : "false"); } void Control::setEnableCondition(const char* enable) { DelayedCallGuard dcguard(languageHook); LOCKGUI; if (pGUIControl) pGUIControl->SetEnableCondition(enable); } void Control::setAnimations(const std::vector< Tuple<String,String> >& eventAttr) throw (WindowException) { CXBMCTinyXML xmlDoc; TiXmlElement xmlRootElement("control"); TiXmlNode *pRoot = xmlDoc.InsertEndChild(xmlRootElement); if (!pRoot) throw WindowException("TiXmlNode creation error"); std::vector<CAnimation> animations; for (unsigned int anim = 0; anim < eventAttr.size(); anim++) { const Tuple<String,String>& pTuple = eventAttr[anim]; if (pTuple.GetNumValuesSet() != 2) throw WindowException("Error unpacking tuple found in list"); const String& cEvent = pTuple.first(); const String& cAttr = pTuple.second(); TiXmlElement pNode("animation"); std::vector<std::string> attrs = StringUtils::Split(cAttr, " "); for (std::vector<std::string>::const_iterator i = attrs.begin(); i != attrs.end(); ++i) { std::vector<std::string> attrs2 = StringUtils::Split(*i, "="); if (attrs2.size() == 2) pNode.SetAttribute(attrs2[0], attrs2[1]); } TiXmlText value(cEvent.c_str()); pNode.InsertEndChild(value); pRoot->InsertEndChild(pNode); } const CRect animRect((float)dwPosX, (float)dwPosY, (float)dwPosX + dwWidth, (float)dwPosY + dwHeight); LOCKGUI; if (pGUIControl) { CGUIControlFactory::GetAnimations(pRoot, animRect, iParentId, animations); pGUIControl->SetAnimations(animations); } } void Control::setPosition(long x, long y) { DelayedCallGuard dcguard(languageHook); LOCKGUI; dwPosX = x; dwPosY = y; if (pGUIControl) pGUIControl->SetPosition((float)dwPosX, (float)dwPosY); } void Control::setWidth(long width) { DelayedCallGuard dcguard(languageHook); LOCKGUI; dwWidth = width; if (pGUIControl) pGUIControl->SetWidth((float)dwWidth); } void Control::setHeight(long height) { DelayedCallGuard dcguard(languageHook); LOCKGUI; dwHeight = height; if (pGUIControl) pGUIControl->SetHeight((float)dwHeight); } void Control::setNavigation(const Control* up, const Control* down, const Control* left, const Control* right) throw (WindowException) { if(iControlId == 0) throw WindowException("Control has to be added to a window first"); { LOCKGUI; if (pGUIControl) { pGUIControl->SetNavigationAction(ACTION_MOVE_UP, up->iControlId); pGUIControl->SetNavigationAction(ACTION_MOVE_DOWN, down->iControlId); pGUIControl->SetNavigationAction(ACTION_MOVE_LEFT, left->iControlId); pGUIControl->SetNavigationAction(ACTION_MOVE_RIGHT, right->iControlId); } } } void Control::controlUp(const Control* control) throw (WindowException) { if(iControlId == 0) throw WindowException("Control has to be added to a window first"); { LOCKGUI; if (pGUIControl) pGUIControl->SetNavigationAction(ACTION_MOVE_UP, control->iControlId); } } void Control::controlDown(const Control* control) throw (WindowException) { if(iControlId == 0) throw WindowException("Control has to be added to a window first"); { LOCKGUI; if (pGUIControl) pGUIControl->SetNavigationAction(ACTION_MOVE_DOWN, control->iControlId); } } void Control::controlLeft(const Control* control) throw (WindowException) { if(iControlId == 0) throw WindowException("Control has to be added to a window first"); { LOCKGUI; if (pGUIControl) pGUIControl->SetNavigationAction(ACTION_MOVE_LEFT, control->iControlId); } } void Control::controlRight(const Control* control) throw (WindowException) { if(iControlId == 0) throw WindowException("Control has to be added to a window first"); { LOCKGUI; if (pGUIControl) pGUIControl->SetNavigationAction(ACTION_MOVE_RIGHT, control->iControlId); } } // ============================================================ // ControlSpin // ============================================================ ControlSpin::ControlSpin() { // default values for spin control color = 0xffffffff; dwPosX = 0; dwPosY = 0; dwWidth = 16; dwHeight = 16; // get default images strTextureUp = XBMCAddonUtils::getDefaultImage((char*)"listcontrol", (char*)"textureup", (char*)"scroll-up.png"); strTextureDown = XBMCAddonUtils::getDefaultImage((char*)"listcontrol", (char*)"texturedown", (char*)"scroll-down.png"); strTextureUpFocus = XBMCAddonUtils::getDefaultImage((char*)"listcontrol", (char*)"textureupfocus", (char*)"scroll-up-focus.png"); strTextureDownFocus = XBMCAddonUtils::getDefaultImage((char*)"listcontrol", (char*)"texturedownfocus", (char*)"scroll-down-focus.png"); } void ControlSpin::setTextures(const char* up, const char* down, const char* upFocus, const char* downFocus) throw(UnimplementedException) { strTextureUp = up; strTextureDown = down; strTextureUpFocus = upFocus; strTextureDownFocus = downFocus; /* PyXBMCGUILock(); if (self->pGUIControl) { CGUISpinControl* pControl = (CGUISpinControl*)self->pGUIControl; pControl->se PyXBMCGUIUnlock(); */ } ControlSpin::~ControlSpin() {} // ============================================================ // ============================================================ // ControlLabel // ============================================================ ControlLabel::ControlLabel(long x, long y, long width, long height, const String& label, const char* font, const char* p_textColor, const char* p_disabledColor, long p_alignment, bool hasPath, long angle) : strFont("font13"), textColor(0xffffffff), disabledColor(0x60ffffff), align(p_alignment), bHasPath(hasPath), iAngle(angle) { dwPosX = x; dwPosY = y; dwWidth = width; dwHeight = height; strText = label; if (font) strFont = font; if (p_textColor) sscanf(p_textColor, "%x", &textColor); if (p_disabledColor) sscanf( p_disabledColor, "%x", &disabledColor ); } ControlLabel::~ControlLabel() {} CGUIControl* ControlLabel::Create() throw (WindowException) { CLabelInfo label; label.font = g_fontManager.GetFont(strFont); label.textColor = label.focusedColor = textColor; label.disabledColor = disabledColor; label.align = align; label.angle = (float)-iAngle; pGUIControl = new CGUILabelControl( iParentId, iControlId, (float)dwPosX, (float)dwPosY, (float)dwWidth, (float)dwHeight, label, false, bHasPath); ((CGUILabelControl *)pGUIControl)->SetLabel(strText); return pGUIControl; } void ControlLabel::setLabel(const String& label, const char* font, const char* textColor, const char* disabledColor, const char* shadowColor, const char* focusedColor, const String& label2) throw(UnimplementedException) { strText = label; CGUIMessage msg(GUI_MSG_LABEL_SET, iParentId, iControlId); msg.SetLabel(strText); g_windowManager.SendThreadMessage(msg, iParentId); } String ControlLabel::getLabel() throw(UnimplementedException) { if (!pGUIControl) return NULL; return strText; } // ============================================================ // ============================================================ // ControlEdit // ============================================================ ControlEdit::ControlEdit(long x, long y, long width, long height, const String& label, const char* font, const char* _textColor, const char* _disabledColor, long _alignment, const char* focusTexture, const char* noFocusTexture, bool isPassword) : strFont("font13"), textColor(0xffffffff), disabledColor(0x60ffffff), align(_alignment), bIsPassword(isPassword) { strTextureFocus = focusTexture ? focusTexture : XBMCAddonUtils::getDefaultImage((char*)"edit", (char*)"texturefocus", (char*)"button-focus.png"); strTextureNoFocus = noFocusTexture ? noFocusTexture : XBMCAddonUtils::getDefaultImage((char*)"edit", (char*)"texturenofocus", (char*)"button-focus.png"); if (font) strFont = font; if (_textColor) sscanf( _textColor, "%x", &textColor ); if (_disabledColor) sscanf( _disabledColor, "%x", &disabledColor ); } CGUIControl* ControlEdit::Create() throw (WindowException) { CLabelInfo label; label.font = g_fontManager.GetFont(strFont); label.textColor = label.focusedColor = textColor; label.disabledColor = disabledColor; label.align = align; pGUIControl = new CGUIEditControl( iParentId, iControlId, (float)dwPosX, (float)dwPosY, (float)dwWidth, (float)dwHeight, CTextureInfo(strTextureFocus), CTextureInfo(strTextureNoFocus), label, strText); if (bIsPassword) ((CGUIEditControl *) pGUIControl)->SetInputType(CGUIEditControl::INPUT_TYPE_PASSWORD, 0); return pGUIControl; } void ControlEdit::setLabel(const String& label, const char* font, const char* textColor, const char* disabledColor, const char* shadowColor, const char* focusedColor, const String& label2) throw(UnimplementedException) { strText = label; CGUIMessage msg(GUI_MSG_LABEL_SET, iParentId, iControlId); msg.SetLabel(strText); g_windowManager.SendThreadMessage(msg, iParentId); } String ControlEdit::getLabel() throw(UnimplementedException) { if (!pGUIControl) return NULL; return strText; } void ControlEdit::setText(const String& text) throw(UnimplementedException) { // create message CGUIMessage msg(GUI_MSG_LABEL2_SET, iParentId, iControlId); msg.SetLabel(text); // send message g_windowManager.SendThreadMessage(msg, iParentId); } String ControlEdit::getText() throw(UnimplementedException) { CGUIMessage msg(GUI_MSG_ITEM_SELECTED, iParentId, iControlId); g_windowManager.SendMessage(msg, iParentId); return msg.GetLabel(); } // ============================================================ // ControlList // ============================================================ ControlList::ControlList(long x, long y, long width, long height, const char* font, const char* ctextColor, const char* cbuttonTexture, const char* cbuttonFocusTexture, const char* cselectedColor, long _imageWidth, long _imageHeight, long _itemTextXOffset, long _itemTextYOffset, long _itemHeight, long _space, long _alignmentY) : strFont("font13"), textColor(0xe0f0f0f0), selectedColor(0xffffffff), imageHeight(_imageHeight), imageWidth(_imageWidth), itemHeight(_itemHeight), space(_space), itemTextOffsetX(_itemTextXOffset),itemTextOffsetY(_itemTextYOffset), alignmentY(_alignmentY) { dwPosX = x; dwPosY = y; dwWidth = width; dwHeight = height; // create a python spin control pControlSpin = new ControlSpin(); // initialize default values if (font) strFont = font; if (ctextColor) sscanf( ctextColor, "%x", &textColor ); if (cselectedColor) sscanf( cselectedColor, "%x", &selectedColor ); strTextureButton = cbuttonTexture ? cbuttonTexture : XBMCAddonUtils::getDefaultImage((char*)"listcontrol", (char*)"texturenofocus", (char*)"list-nofocus.png"); strTextureButtonFocus = cbuttonFocusTexture ? cbuttonFocusTexture : XBMCAddonUtils::getDefaultImage((char*)"listcontrol", (char*)"texturefocus", (char*)"list-focus.png"); // default values for spin control pControlSpin->dwPosX = dwWidth - 35; pControlSpin->dwPosY = dwHeight - 15; } ControlList::~ControlList() { } CGUIControl* ControlList::Create() throw (WindowException) { CLabelInfo label; label.align = alignmentY; label.font = g_fontManager.GetFont(strFont); label.textColor = label.focusedColor = textColor; //label.shadowColor = shadowColor; label.selectedColor = selectedColor; label.offsetX = (float)itemTextOffsetX; label.offsetY = (float)itemTextOffsetY; // Second label should have the same font, alignment, and colours as the first, but // the offsets should be 0. CLabelInfo label2 = label; label2.offsetX = label2.offsetY = 0; label2.align |= XBFONT_RIGHT; pGUIControl = new CGUIListContainer( iParentId, iControlId, (float)dwPosX, (float)dwPosY, (float)dwWidth, (float)dwHeight - pControlSpin->dwHeight - 5, label, label2, CTextureInfo(strTextureButton), CTextureInfo(strTextureButtonFocus), (float)itemHeight, (float)imageWidth, (float)imageHeight, (float)space); return pGUIControl; } void ControlList::addItem(const Alternative<String, const XBMCAddon::xbmcgui::ListItem* > & item, bool sendMessage) { XBMC_TRACE; if (item.which() == first) internAddListItem(ListItem::fromString(item.former()),sendMessage); else internAddListItem(item.later(),sendMessage); } void ControlList::addItems(const std::vector<Alternative<String, const XBMCAddon::xbmcgui::ListItem* > > & items) { XBMC_TRACE; for (std::vector<Alternative<String, const XBMCAddon::xbmcgui::ListItem* > >::const_iterator iter = items.begin(); iter != items.end(); ++iter) addItem(*iter,false); sendLabelBind(items.size()); } void ControlList::internAddListItem(AddonClass::Ref<ListItem> pListItem, bool sendMessage) throw (WindowException) { if (pListItem.isNull()) throw WindowException("NULL ListItem passed to ControlList::addListItem"); // add item to objects vector vecItems.push_back(pListItem); // send all of the items ... this is what it did before. if (sendMessage) sendLabelBind(vecItems.size()); } void ControlList::sendLabelBind(int tail) { // construct a CFileItemList to pass 'em on to the list CGUIListItemPtr items(new CFileItemList()); for (unsigned int i = vecItems.size() - tail; i < vecItems.size(); i++) ((CFileItemList*)items.get())->Add(vecItems[i]->item); CGUIMessage msg(GUI_MSG_LABEL_BIND, iParentId, iControlId, 0, 0, items); msg.SetPointer(items.get()); g_windowManager.SendThreadMessage(msg, iParentId); } void ControlList::selectItem(long item) throw(UnimplementedException) { // create message CGUIMessage msg(GUI_MSG_ITEM_SELECT, iParentId, iControlId, item); // send message g_windowManager.SendThreadMessage(msg, iParentId); } void ControlList::removeItem(int index) throw(UnimplementedException,WindowException) { if (index < 0 || index >= (int)vecItems.size()) throw WindowException("Index out of range"); vecItems.erase(vecItems.begin() + index); sendLabelBind(vecItems.size()); } void ControlList::reset() throw(UnimplementedException) { CGUIMessage msg(GUI_MSG_LABEL_RESET, iParentId, iControlId); g_windowManager.SendThreadMessage(msg, iParentId); // delete all items from vector // delete all ListItem from vector vecItems.clear(); // this should delete all of the objects } Control* ControlList::getSpinControl() throw (UnimplementedException) { return pControlSpin; } long ControlList::getSelectedPosition() throw(UnimplementedException) { DelayedCallGuard dcguard(languageHook); LOCKGUI; // create message CGUIMessage msg(GUI_MSG_ITEM_SELECTED, iParentId, iControlId); long pos = -1; // send message if ((vecItems.size() > 0) && pGUIControl) { pGUIControl->OnMessage(msg); pos = msg.GetParam1(); } return pos; } XBMCAddon::xbmcgui::ListItem* ControlList::getSelectedItem() throw (UnimplementedException) { DelayedCallGuard dcguard(languageHook); LOCKGUI; // create message CGUIMessage msg(GUI_MSG_ITEM_SELECTED, iParentId, iControlId); AddonClass::Ref<ListItem> pListItem = NULL; // send message if ((vecItems.size() > 0) && pGUIControl) { pGUIControl->OnMessage(msg); if (msg.GetParam1() >= 0 && (size_t)msg.GetParam1() < vecItems.size()) pListItem = vecItems[msg.GetParam1()]; } return pListItem.get(); } void ControlList::setImageDimensions(long imageWidth,long imageHeight) throw (UnimplementedException) { CLog::Log(LOGWARNING,"ControlList::setImageDimensions was called but ... it currently isn't defined to do anything."); /* PyXBMCGUILock(); if (self->pGUIControl) { CGUIListControl* pListControl = (CGUIListControl*) self->pGUIControl; pListControl->SetImageDimensions((float)self->dwImageWidth, (float)self->dwImageHeight ); } PyXBMCGUIUnlock(); */ } void ControlList::setItemHeight(long height) throw (UnimplementedException) { CLog::Log(LOGWARNING,"ControlList::setItemHeight was called but ... it currently isn't defined to do anything."); /* PyXBMCGUILock(); if (self->pGUIControl) { CGUIListControl* pListControl = (CGUIListControl*) self->pGUIControl; pListControl->SetItemHeight((float)self->dwItemHeight); } PyXBMCGUIUnlock(); */ } void ControlList::setSpace(int space) throw (UnimplementedException) { CLog::Log(LOGWARNING,"ControlList::setSpace was called but ... it currently isn't defined to do anything."); /* PyXBMCGUILock(); if (self->pGUIControl) { CGUIListControl* pListControl = (CGUIListControl*) self->pGUIControl; pListControl->SetSpaceBetweenItems((float)self->dwSpace); } PyXBMCGUIUnlock(); */ } void ControlList::setPageControlVisible(bool visible) throw (UnimplementedException) { CLog::Log(LOGWARNING,"ControlList::setPageControlVisible was called but ... it currently isn't defined to do anything."); // char isOn = true; /* PyXBMCGUILock(); if (self->pGUIControl) { ((CGUIListControl*)self->pGUIControl)->SetPageControlVisible((bool)isOn ); } PyXBMCGUIUnlock(); */ } long ControlList::size() throw (UnimplementedException) { return (long)vecItems.size(); } long ControlList::getItemHeight() throw(UnimplementedException) { return (long)itemHeight; } long ControlList::getSpace() throw (UnimplementedException) { return (long)space; } XBMCAddon::xbmcgui::ListItem* ControlList::getListItem(int index) throw (UnimplementedException,WindowException) { if (index < 0 || index >= (int)vecItems.size()) throw WindowException("Index out of range"); AddonClass::Ref<ListItem> pListItem = vecItems[index]; return pListItem.get(); } void ControlList::setStaticContent(const ListItemList* pitems) throw (UnimplementedException) { const ListItemList& vecItems = *pitems; std::vector<CGUIStaticItemPtr> items; for (unsigned int item = 0; item < vecItems.size(); item++) { ListItem* pItem = vecItems[item]; // NOTE: This code has likely not worked fully correctly for some time // In particular, the click behaviour won't be working. CGUIStaticItemPtr newItem(new CGUIStaticItem(*pItem->item)); items.push_back(newItem); } // set static list IListProvider *provider = new CStaticListProvider(items); ((CGUIBaseContainer *)pGUIControl)->SetListProvider(provider); } // ============================================================ } }
onetechgenius/XBMCast2TV
xbmc/interfaces/legacy/Control.cpp
C++
gpl-2.0
49,424
namespace WikiFunctions.Profiles { partial class AWBLogUploadProfilesForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.lvAccounts = new WikiFunctions.Controls.NoFlickerExtendedListView(true, true); this.colID = new System.Windows.Forms.ColumnHeader(); this.colAccountName = new System.Windows.Forms.ColumnHeader(); this.colPasswordSaved = new System.Windows.Forms.ColumnHeader(); this.colProfileSettings = new System.Windows.Forms.ColumnHeader(); this.colUsedForUpload = new System.Windows.Forms.ColumnHeader(); this.colNotes = new System.Windows.Forms.ColumnHeader(); this.mnuAccounts = new System.Windows.Forms.ContextMenuStrip(this.components); this.loginAsThisAccountToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editThisAccountToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.changePasswordToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.addNewAccountToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.deleteThisAccountToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.btnAdd = new System.Windows.Forms.Button(); this.btnDelete = new System.Windows.Forms.Button(); this.btnClose = new System.Windows.Forms.Button(); this.btnLogin = new System.Windows.Forms.Button(); this.BtnEdit = new System.Windows.Forms.Button(); this.mnuAccounts.SuspendLayout(); this.SuspendLayout(); // // lvAccounts // this.lvAccounts.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lvAccounts.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.colID, this.colAccountName, this.colPasswordSaved, this.colProfileSettings, this.colUsedForUpload, this.colNotes}); this.lvAccounts.ContextMenuStrip = this.mnuAccounts; this.lvAccounts.FullRowSelect = true; this.lvAccounts.Location = new System.Drawing.Point(12, 12); this.lvAccounts.Name = "lvAccounts"; this.lvAccounts.Size = new System.Drawing.Size(494, 175); this.lvAccounts.TabIndex = 0; this.lvAccounts.UseCompatibleStateImageBehavior = false; this.lvAccounts.View = System.Windows.Forms.View.Details; this.lvAccounts.SelectedIndexChanged += new System.EventHandler(this.lvAccounts_SelectedIndexChanged); this.lvAccounts.DoubleClick += new System.EventHandler(this.lvAccounts_DoubleClick); // // colID // this.colID.Text = "ID"; this.colID.Width = 32; // // colAccountName // this.colAccountName.Text = "Username"; this.colAccountName.Width = 89; // // colPasswordSaved // this.colPasswordSaved.Text = "Password saved?"; this.colPasswordSaved.Width = 107; // // colProfileSettings // this.colProfileSettings.Text = "Profile default settings"; this.colProfileSettings.Width = 175; // // colUsedForUpload // this.colUsedForUpload.Text = "Used for Upload?"; this.colUsedForUpload.Width = 98; // // colNotes // this.colNotes.Text = "Notes"; this.colNotes.Width = 63; // // mnuAccounts // this.mnuAccounts.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.loginAsThisAccountToolStripMenuItem, this.editThisAccountToolStripMenuItem, this.changePasswordToolStripMenuItem, this.toolStripSeparator1, this.addNewAccountToolStripMenuItem, this.toolStripSeparator2, this.deleteThisAccountToolStripMenuItem}); this.mnuAccounts.Name = "mnuAccounts"; this.mnuAccounts.Size = new System.Drawing.Size(192, 126); // // loginAsThisAccountToolStripMenuItem // this.loginAsThisAccountToolStripMenuItem.Name = "loginAsThisAccountToolStripMenuItem"; this.loginAsThisAccountToolStripMenuItem.Size = new System.Drawing.Size(191, 22); this.loginAsThisAccountToolStripMenuItem.Text = "Log-in as this account"; this.loginAsThisAccountToolStripMenuItem.Visible = false; // // editThisAccountToolStripMenuItem // this.editThisAccountToolStripMenuItem.Name = "editThisAccountToolStripMenuItem"; this.editThisAccountToolStripMenuItem.Size = new System.Drawing.Size(191, 22); this.editThisAccountToolStripMenuItem.Text = "Edit this account"; this.editThisAccountToolStripMenuItem.Click += new System.EventHandler(this.editThisAccountToolStripMenuItem_Click); // // changePasswordToolStripMenuItem // this.changePasswordToolStripMenuItem.Name = "changePasswordToolStripMenuItem"; this.changePasswordToolStripMenuItem.Size = new System.Drawing.Size(191, 22); this.changePasswordToolStripMenuItem.Text = "Change password"; this.changePasswordToolStripMenuItem.Click += new System.EventHandler(this.changePasswordToolStripMenuItem_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(188, 6); // // addNewAccountToolStripMenuItem // this.addNewAccountToolStripMenuItem.Name = "addNewAccountToolStripMenuItem"; this.addNewAccountToolStripMenuItem.Size = new System.Drawing.Size(191, 22); this.addNewAccountToolStripMenuItem.Text = "Add new account"; this.addNewAccountToolStripMenuItem.Click += new System.EventHandler(this.addNewAccountToolStripMenuItem_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(188, 6); // // deleteThisAccountToolStripMenuItem // this.deleteThisAccountToolStripMenuItem.Name = "deleteThisAccountToolStripMenuItem"; this.deleteThisAccountToolStripMenuItem.Size = new System.Drawing.Size(191, 22); this.deleteThisAccountToolStripMenuItem.Text = "Delete this account"; this.deleteThisAccountToolStripMenuItem.Click += new System.EventHandler(this.deleteThisSavedAccountToolStripMenuItem_Click); // // btnAdd // this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnAdd.Location = new System.Drawing.Point(93, 193); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(75, 23); this.btnAdd.TabIndex = 2; this.btnAdd.Text = "Add"; this.btnAdd.UseVisualStyleBackColor = true; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // btnDelete // this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnDelete.Enabled = false; this.btnDelete.Location = new System.Drawing.Point(255, 193); this.btnDelete.Name = "btnDelete"; this.btnDelete.Size = new System.Drawing.Size(75, 23); this.btnDelete.TabIndex = 4; this.btnDelete.Text = "Delete"; this.btnDelete.UseVisualStyleBackColor = true; this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // btnClose // this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnClose.Location = new System.Drawing.Point(431, 193); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(75, 23); this.btnClose.TabIndex = 5; this.btnClose.Text = "Close"; this.btnClose.UseVisualStyleBackColor = true; this.btnClose.Click += new System.EventHandler(this.btnExit_Click); // // btnLogin // this.btnLogin.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnLogin.Enabled = false; this.btnLogin.Location = new System.Drawing.Point(12, 193); this.btnLogin.Name = "btnLogin"; this.btnLogin.Size = new System.Drawing.Size(75, 23); this.btnLogin.TabIndex = 1; this.btnLogin.Text = "Login"; this.btnLogin.UseVisualStyleBackColor = true; this.btnLogin.Visible = false; // // BtnEdit // this.BtnEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.BtnEdit.Location = new System.Drawing.Point(174, 193); this.BtnEdit.Name = "BtnEdit"; this.BtnEdit.Size = new System.Drawing.Size(75, 23); this.BtnEdit.TabIndex = 3; this.BtnEdit.Text = "Edit"; this.BtnEdit.UseVisualStyleBackColor = true; this.BtnEdit.Click += new System.EventHandler(this.BtnEdit_Click); // // AWBLogUploadProfilesForm // this.AcceptButton = this.btnLogin; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.btnClose; this.ClientSize = new System.Drawing.Size(518, 223); this.Controls.Add(this.BtnEdit); this.Controls.Add(this.lvAccounts); this.Controls.Add(this.btnDelete); this.Controls.Add(this.btnClose); this.Controls.Add(this.btnAdd); this.Controls.Add(this.btnLogin); this.Name = "AWBLogUploadProfilesForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Profiles"; this.Load += new System.EventHandler(this.AWBProfiles_Load); this.mnuAccounts.ResumeLayout(false); this.ResumeLayout(false); } #endregion protected WikiFunctions.Controls.NoFlickerExtendedListView lvAccounts; protected System.Windows.Forms.ColumnHeader colAccountName; protected System.Windows.Forms.ColumnHeader colPasswordSaved; protected System.Windows.Forms.ColumnHeader colProfileSettings; protected System.Windows.Forms.ColumnHeader colNotes; protected System.Windows.Forms.ContextMenuStrip mnuAccounts; protected System.Windows.Forms.ToolStripSeparator toolStripSeparator1; protected System.Windows.Forms.ToolStripMenuItem addNewAccountToolStripMenuItem; protected System.Windows.Forms.ToolStripSeparator toolStripSeparator2; protected System.Windows.Forms.ToolStripMenuItem deleteThisAccountToolStripMenuItem; protected System.Windows.Forms.Button btnAdd; protected System.Windows.Forms.Button btnDelete; protected System.Windows.Forms.ToolStripMenuItem changePasswordToolStripMenuItem; protected System.Windows.Forms.ColumnHeader colID; protected System.Windows.Forms.ToolStripMenuItem editThisAccountToolStripMenuItem; protected System.Windows.Forms.Button btnClose; protected System.Windows.Forms.ColumnHeader colUsedForUpload; protected System.Windows.Forms.ToolStripMenuItem loginAsThisAccountToolStripMenuItem; protected System.Windows.Forms.Button btnLogin; protected System.Windows.Forms.Button BtnEdit; } }
svn2github/autowikibrowser
tags/ServerPlugin/WikiFunctions/Profiles/AWBLogUploadProfilesForm.designer.cs
C#
gpl-2.0
14,307
/* *------------------------------------------------------------------------------ * Copyright (C) 2006-2014 University of Dundee & Open Microscopy Environment. * All rights reserved. * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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. * *------------------------------------------------------------------------------ */ package omero.gateway.util; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.URL; import java.net.UnknownHostException; import java.util.Enumeration; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import omero.log.Logger; /** * Checks if the network is still up. * * @author Jean-Marie Burel &nbsp;&nbsp;&nbsp;&nbsp; <a * href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a> * @since 4.4 */ public class NetworkChecker { private final AtomicLong lastCheck = new AtomicLong( System.currentTimeMillis()); private final AtomicBoolean lastValue = new AtomicBoolean(true); /** * The IP Address of the server the client is connected to or * <code>null</code>. */ private InetAddress ipAddress; /** The address of the server to reach. */ private final String address; /** Reference to the logger. */ private Logger logger; /** The list of interfaces when the network checker is initialized. */ private long interfacesCount; /** * Creates a new instance. * * @param address * The address of the server the client is connected to or * <code>null</code>. * @param logger Reference to the logger. */ public NetworkChecker(String address, Logger logger) { this.address = address; this.logger = logger; if (ipAddress != null) { try { this.ipAddress = InetAddress.getByName(address); } catch (UnknownHostException e) { // Ignored } } interfacesCount = 0; try { Enumeration<NetworkInterface> interfaces = NetworkInterface .getNetworkInterfaces(); if (interfaces != null) { NetworkInterface ni; while (interfaces.hasMoreElements()) { ni = interfaces.nextElement(); if (ni.isLoopback() || !ni.isUp()) continue; interfacesCount++; } } } catch (Exception e) { // Ignored } } /** * Returns <code>true</code> if the network is still up, otherwise throws an * <code>UnknownHostException</code>. This tests if the adapter is ready. * * @param useCachedValue Pass <code>true</code> if we use the cached value, * <code>false</code> otherwise. * @return See above. * @throws Exception * Thrown if the network is down. */ public boolean isNetworkup(boolean useCachedValue) throws Exception { if (useCachedValue) { long elapsed = System.currentTimeMillis() - lastCheck.get(); if (elapsed <= 5000) { return lastValue.get(); } } boolean newValue = _isNetworkup(); long stop = System.currentTimeMillis(); lastValue.set(newValue); lastCheck.set(stop); return newValue; } /** * Checks the network is available or not. * * @return See above. * @throws Exception * Thrown if an error occurred if we cannot reach. */ public boolean isAvailable() throws Exception { if (ipAddress != null && ipAddress.isLoopbackAddress()) { return true; } if (address != null) { try { URL url = new URL("http://" + address); HttpURLConnection urlConnect = (HttpURLConnection) url .openConnection(); urlConnect.setConnectTimeout(1000); urlConnect.getContent(); } catch (Exception e) { log("Not available %s", e); return false; } } return true; } /** * Returns <code>true</code> if the network is still up, otherwise throws an * <code>UnknownHostException</code>. * * @return See above. * @throws Exception * Thrown if the network is down. */ private boolean _isNetworkup() throws Exception { if (ipAddress != null && ipAddress.isLoopbackAddress()) { return true; } boolean networkup = false; Enumeration<NetworkInterface> interfaces = NetworkInterface .getNetworkInterfaces(); long count = 0; if (interfaces != null && !networkup) { NetworkInterface ni; while (interfaces.hasMoreElements()) { ni = interfaces.nextElement(); if (ni.isLoopback() || !ni.isUp()) continue; count++; } } if (count >= interfacesCount) { networkup = true; } else { networkup = isAvailable(); if (networkup) { // one interface was dropped e.g. wireless interfacesCount = count; } } if (!networkup) { throw new UnknownHostException("Network is down."); } return networkup; } /** * Logs the error. * * @param msg * The message to log * @param objs * The objects to add to the message. */ void log(String msg, Object... objs) { if (logger != null) { logger.debug(this, String.format(msg, objs)); } } }
simleo/openmicroscopy
components/blitz/src/omero/gateway/util/NetworkChecker.java
Java
gpl-2.0
6,574
/* Delegate.java -- Copyright (C) 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package org.omg.CORBA.portable; import gnu.java.lang.CPStringBuilder; import org.omg.CORBA.BAD_PARAM; import org.omg.CORBA.Context; import org.omg.CORBA.ContextList; import org.omg.CORBA.DomainManager; import org.omg.CORBA.ExceptionList; import org.omg.CORBA.NO_IMPLEMENT; import org.omg.CORBA.NVList; import org.omg.CORBA.NamedValue; import org.omg.CORBA.ORB; import org.omg.CORBA.Policy; import org.omg.CORBA.Request; import org.omg.CORBA.SetOverrideType; /** * Specifies a vendor specific implementation of the * {@link org.omg.CORBA.Object} methods. The calls to these * methods are forwarded to the object delegate that can be * replaced, if needed. The first parameter is the actual * CORBA object to that the operation must be applied. * * Some methods in this class are not abstract, but no implemented, * thowing the {@link NO_IMPLEMENT}. This, however, does not mean that * they are not implemented in the derived classes as well. * * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) */ public abstract class Delegate { /** * Explains the reason of throwing the NO_IMPLEMENT. */ private static final String WHY = "Following 1.4 API, this Delegate method must not be implemented. Override."; /** * Create a request to invoke the method of this object. * * @param target the CORBA object, to that this operation must be applied. * @param context a list of additional properties. * @param operation the name of method to be invoked. * @param parameters the method parameters. * @param returns the container for tge method returned value. * * @return the created reaquest. */ public abstract Request create_request(org.omg.CORBA.Object target, Context context, String operation, NVList parameters, NamedValue returns ); /** * Create a request to invoke the method of this object, specifying * context list and the list of the expected exception. * * @param target the CORBA object, to that this operation must be applied. * @param context a list of additional properties. * @param operation the name of method to be invoked. * @param parameters the method parameters. * @param returns the container for tge method returned value. * @param exceptions the list of the possible exceptions that the method * can throw. * @param ctx_list the list of the context strings that need to be * resolved and send as a context instance. * * @return the created reaquest. */ public abstract Request create_request(org.omg.CORBA.Object target, Context context, String operation, NVList parameters, NamedValue returns, ExceptionList exceptions, ContextList ctx_list ); /** * Duplicate the object reference. This does not make much sense for * java platform and is just included for the sake of compliance with * CORBA APIs. * * @param target the CORBA object, to that this operation must be applied. * * The method may return the object reference itself. * * @return as a rule, <code>this</code>. */ public abstract org.omg.CORBA.Object duplicate(org.omg.CORBA.Object target); /** * Retrieve the domain managers for this object. * * @param target the CORBA object, to that this operation must be applied. * * @return the domain managers. * * @throws NO_IMPLEMENT, always (following the 1.4 specification). */ public DomainManager[] get_domain_managers(org.omg.CORBA.Object target) { throw new NO_IMPLEMENT(WHY); } /** * * @param target the CORBA object, to that this operation must be applied. * * Get the <code>InterfaceDef</code> for this Object. */ public abstract org.omg.CORBA.Object get_interface_def(org.omg.CORBA.Object target); /** * Returns the {@link Policy}, applying to this object. * * @param target the CORBA object, to that this operation must be applied. * @param a_policy_type a type of policy to be obtained. * @return a corresponding Policy object. * * @throws NO_IMPLEMENT, always (following the 1.4 specification). */ public Policy get_policy(org.omg.CORBA.Object target, int a_policy_type) throws BAD_PARAM { throw new NO_IMPLEMENT(WHY); } /** * Get the hashcode this object reference. The same hashcode still * does not means that the references are the same. From the other * side, two different references may still refer to the same CORBA * object. The returned value must not change during the object * lifetime. * * @param target the CORBA object, to that this operation must be applied. * @param maximum the maximal value to return. * * @return the hashcode. */ public abstract int hash(org.omg.CORBA.Object target, int maximum); /** * Check if this object can be referenced by the given repository id. * * @param target the CORBA object, to that this operation must be applied. * @param repositoryIdentifer the repository id. * * @return true if the passed parameter is a repository id of this * CORBA object. */ public abstract boolean is_a(org.omg.CORBA.Object target, String repositoryIdentifer ); /** * Return true if the other object references are equivalent, so far as * it is possible to determine this easily. * * @param target the CORBA object, to that this operation must be applied. * @param other the other object reference. * * @return true if both references refer the same object, false * if they probably can refer different objects. * */ public abstract boolean is_equivalent(org.omg.CORBA.Object target, org.omg.CORBA.Object other ); /** * Returns true if the object is local. * * @param self the object to check. * * @return false, always (following 1.4 specs). Override to get * functionality. */ public boolean is_local(org.omg.CORBA.Object self) { return false; } /** * Determines if the server object for this reference has already * been destroyed. * * @param target the CORBA object, to that this operation must be applied. * * @return true if the object has been destroyed, false otherwise. */ public abstract boolean non_existent(org.omg.CORBA.Object target); /** * Compares two objects for equality. The default implementations * delegated call to {@link java.lang.Object#equals(java.lang.Object)}. * * @param self this CORBA object. * @param other the other CORBA object. * * @return true if the objects are equal. */ public boolean equals(org.omg.CORBA.Object self, java.lang.Object other) { return self==other; } /** * Return the hashcode for this CORBA object. The default implementation * delegates call to {@link #hash(org.omg.CORBA.Object, int)}, passing Integer.MAX_VALUE as an * argument. * * @param target the object, for that the hash code must be computed. * * @return the hashcode. */ public int hashCode(org.omg.CORBA.Object target) { return hash(target, Integer.MAX_VALUE); } /** * Invoke the operation. * * @param target the invocation target. * @param output the stream, containing the written arguments. * * @return the stream, from where the input parameters could be read. * * @throws ApplicationException if the application throws an exception, * defined as a part of its remote method definition. * * @throws RemarshalException if reading(remarshalling) fails. * * @throws NO_IMPLEMENT, always (following the 1.4 specification). */ public InputStream invoke(org.omg.CORBA.Object target, org.omg.CORBA.portable.OutputStream output ) throws ApplicationException, RemarshalException { throw new NO_IMPLEMENT(WHY); } /** * Provides the reference to ORB. * * @param target the object reference. * * @return the associated ORB. * * @throws NO_IMPLEMENT, always (following the 1.4 specification). */ public ORB orb(org.omg.CORBA.Object target) { throw new NO_IMPLEMENT(WHY); } /** * Free resoureces, occupied by this reference. The object implementation * is not notified, and the other references to the same object are not * affected. * * @param target the CORBA object, to that this operation must be applied. */ public abstract void release(org.omg.CORBA.Object target); /** * Release the reply stream back to ORB after finishing reading the data * from it. * * @param target the CORBA object, to that this operation must be applied. * @param input the stream, normally returned by {@link #invoke} or * {@link ApplicationException#getInputStream()}, can be null. * * The default method returns without action. */ public void releaseReply(org.omg.CORBA.Object target, org.omg.CORBA.portable.InputStream input ) { } /** * Create a request to invoke the method of this CORBA object. * * @param target the CORBA object, to that this operation must be applied. * @param operation the name of the method to invoke. * * @return the request. */ public abstract Request request(org.omg.CORBA.Object target, String operation); /** * Create a request to invoke the method of this CORBA object. * * @param target the CORBA object, to that this operation must be applied. * @param operation the name of the method to invoke. * @param response_expected specifies if this is one way message or the * response to the message is expected. * * @return the stream where the method arguments should be written. */ public org.omg.CORBA.portable.OutputStream request(org.omg.CORBA.Object target, String operation, boolean response_expected ) { throw new NO_IMPLEMENT(WHY); } /** * This method is always called after invoking the operation on the * local servant. * * The default method returns without action. * * @param self the object. * @param servant the servant. */ public void servant_postinvoke(org.omg.CORBA.Object self, ServantObject servant ) { } /** * Returns a servant that should be used for this request. * The servant can also be casted to the expected type, calling the * required method directly. * * @param self the object * @param operation the operation * @param expectedType the expected type of the servant. * * This implementation always returns null; override for different * behavior. * * @return the servant or null if the servant is not an expected type * of the method is not supported, for example, due security reasons. */ public ServantObject servant_preinvoke(org.omg.CORBA.Object self, String operation, Class expectedType ) { return null; } /** * Returns a new object with the new policies either replacing or * extending the current policies, depending on the second parameter. * * @param target the CORBA object, to that this operation must be applied. * @param policies the policy additions or replacements. * @param how either {@link SetOverrideType#SET_OVERRIDE} to override the * current policies of {@link SetOverrideType#ADD_OVERRIDE} to replace * them. * * @throws NO_IMPLEMENT, always (following the 1.4 specification). * * @return the new reference with the changed policies. */ public org.omg.CORBA.Object set_policy_override(org.omg.CORBA.Object target, Policy[] policies, SetOverrideType how ) { throw new NO_IMPLEMENT(WHY); } /** * Return a string representation of the passed object. * * @param self the CORBA object, to that the string representation must be * returned. By default, the call is delegated to * {@link java.lang.Object#toString()}. * * @return the string representation. */ public String toString(org.omg.CORBA.Object self) { if (self instanceof ObjectImpl) { ObjectImpl x = (ObjectImpl) self; CPStringBuilder b = new CPStringBuilder(x.getClass().getName()); b.append(": ["); for (int i = 0; i < x._ids().length; i++) { b.append(x._ids() [ i ]); b.append(" "); } b.append("]"); return b.toString(); } else return self.getClass().getName(); } }
taciano-perez/JamVM-PH
src/classpath/org/omg/CORBA/portable/Delegate.java
Java
gpl-2.0
15,054
/* * Copyright (C) 2005-2012 Team XBMC * http://www.xbmc.org * * 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, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "MusicInfoTagLoaderMidi.h" #include "utils/URIUtils.h" #include "MusicInfoTag.h" using namespace XFILE; using namespace MUSIC_INFO; CMusicInfoTagLoaderMidi::CMusicInfoTagLoaderMidi() : IMusicInfoTagLoader() { } CMusicInfoTagLoaderMidi::~CMusicInfoTagLoaderMidi() { } // There is no reliable tag information in MIDI files. There is a 'title' field (@T), but it looks // like everyone puts there song title, artist name, the name of the person who created the lyrics and // greetings to their friends and family. Therefore we return the song title as file name, and the // song artist as parent directory. // A good intention of creating a pattern-based artist/song recognition engine failed greatly. Simple formats // like %A-%T fail greatly with artists like A-HA and songs like "Ob-la-Di ob-la-Da.mid". So if anyone has // a good idea which would include cases from above, I'd be happy to hear about it. bool CMusicInfoTagLoaderMidi::Load(const CStdString & strFileName, CMusicInfoTag & tag, EmbeddedArt *art) { tag.SetURL(strFileName); CStdString path, title; URIUtils::Split( strFileName, path, title); URIUtils::RemoveExtension( title ); tag.SetTitle( title ); URIUtils::RemoveSlashAtEnd(path ); if ( !path.IsEmpty() ) { CStdString artist = URIUtils::GetFileName( path ); if ( !artist.IsEmpty() ) tag.SetArtist( artist ); } tag.SetLoaded(true); return true; }
koying/xbmc-pivos
xbmc/music/tags/MusicInfoTagLoaderMidi.cpp
C++
gpl-2.0
2,164
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * 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@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Varien * @package Varien_Image * @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Image handler library * * @category Varien * @package Varien_Image * @author Magento Core Team <core@magentocommerce.com> */ class Varien_Image { protected $_adapter; protected $_fileName; /** * Constructor * * @param Varien_Image_Adapter $adapter. Default value is GD2 * @param string $fileName * @return void */ function __construct($fileName=null, $adapter=Varien_Image_Adapter::ADAPTER_GD2) { $this->_getAdapter($adapter); $this->_fileName = $fileName; if( isset($fileName) ) { $this->open(); } } /** * Opens an image and creates image handle * * @access public * @return void */ public function open() { $this->_getAdapter()->checkDependencies(); if( !file_exists($this->_fileName) ) { throw new Exception("File '{$this->_fileName}' does not exists."); } $this->_getAdapter()->open($this->_fileName); } /** * Display handled image in your browser * * @access public * @return void */ public function display() { $this->_getAdapter()->display(); } /** * Save handled image into file * * @param string $destination. Default value is NULL * @param string $newFileName. Default value is NULL * @access public * @return void */ public function save($destination=null, $newFileName=null) { $this->_getAdapter()->save($destination, $newFileName); } /** * Rotate an image. * * @param int $angle * @access public * @return void */ public function rotate($angle) { $this->_getAdapter()->rotate($angle); } /** * Crop an image. * * @param int $top. Default value is 0 * @param int $left. Default value is 0 * @param int $right. Default value is 0 * @param int $bottom. Default value is 0 * @access public * @return void */ public function crop($top=0, $left=0, $right=0, $bottom=0) { $this->_getAdapter()->crop($top, $left, $right, $bottom); } /** * Resize an image * * @param int $width * @param int $height * @access public * @return void */ public function resize($width, $height = null) { $this->_getAdapter()->resize($width, $height); } public function keepAspectRatio($value) { return $this->_getAdapter()->keepAspectRatio($value); } public function keepFrame($value) { return $this->_getAdapter()->keepFrame($value); } public function keepTransparency($value) { return $this->_getAdapter()->keepTransparency($value); } public function constrainOnly($value) { return $this->_getAdapter()->constrainOnly($value); } public function backgroundColor($value) { return $this->_getAdapter()->backgroundColor($value); } /** * Get/set quality, values in percentage from 0 to 100 * * @param int $value * @return int */ public function quality($value) { return $this->_getAdapter()->quality($value); } /** * Adds watermark to our image. * * @param string $watermarkImage. Absolute path to watermark image. * @param int $positionX. Watermark X position. * @param int $positionY. Watermark Y position. * @param int $watermarkImageOpacity. Watermark image opacity. * @param bool $repeat. Enable or disable watermark brick. * @access public * @return void */ public function watermark($watermarkImage, $positionX=0, $positionY=0, $watermarkImageOpacity=30, $repeat=false) { if( !file_exists($watermarkImage) ) { throw new Exception("Required file '{$watermarkImage}' does not exists."); } $this->_getAdapter()->watermark($watermarkImage, $positionX, $positionY, $watermarkImageOpacity, $repeat); } /** * Get mime type of handled image * * @access public * @return string */ public function getMimeType() { return $this->_getAdapter()->getMimeType(); } /** * process * * @access public * @return void */ public function process() { } /** * instruction * * @access public * @return void */ public function instruction() { } /** * Set image background color * * @param int $color * @access public * @return void */ public function setImageBackgroundColor($color) { $this->_getAdapter()->imageBackgroundColor = intval($color); } /** * Set watermark position * * @param string $position * @return Varien_Image */ public function setWatermarkPosition($position) { $this->_getAdapter()->setWatermarkPosition($position); return $this; } /** * Set watermark image opacity * * @param int $imageOpacity * @return Varien_Image */ public function setWatermarkImageOpacity($imageOpacity) { $this->_getAdapter()->setWatermarkImageOpacity($imageOpacity); return $this; } /** * Set watermark width * * @param int $width * @return Varien_Image */ public function setWatermarkWidth($width) { $this->_getAdapter()->setWatermarkWidth($width); return $this; } /** * Set watermark heigth * * @param int $heigth * @return Varien_Image */ public function setWatermarkHeigth($heigth) { $this->_getAdapter()->setWatermarkHeigth($heigth); return $this; } /** * Retrieve image adapter object * * @param string $adapter * @return Varien_Image_Adapter_Abstract */ protected function _getAdapter($adapter=null) { if( !isset($this->_adapter) ) { $this->_adapter = Varien_Image_Adapter::factory( $adapter ); } return $this->_adapter; } /** * Retrieve original image width * * @return int|null */ public function getOriginalWidth() { return $this->_getAdapter()->getOriginalWidth(); } /** * Retrieve original image height * * @return int|null */ public function getOriginalHeight() { return $this->_getAdapter()->getOriginalHeight(); } }
dvh11er/mage-cheatcode
magento/lib/Varien/Image.php
PHP
gpl-2.0
7,490
/* * Copyright (c) 1998, 2010, 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. * */ #ifndef SHARE_VM_UTILITIES_HISTOGRAM_HPP #define SHARE_VM_UTILITIES_HISTOGRAM_HPP #include "memory/allocation.hpp" #include "runtime/os.hpp" #include "utilities/growableArray.hpp" #ifdef TARGET_OS_FAMILY_linux # include "os_linux.inline.hpp" #endif #ifdef TARGET_OS_FAMILY_solaris # include "os_solaris.inline.hpp" #endif #ifdef TARGET_OS_FAMILY_windows # include "os_windows.inline.hpp" #endif #ifdef TARGET_OS_FAMILY_bsd # include "os_bsd.inline.hpp" #endif // This class provides a framework for collecting various statistics. // The current implementation is oriented towards counting invocations // of various types, but that can be easily changed. // // To use it, you need to declare a Histogram*, and a subtype of // HistogramElement: // // HistogramElement* MyHistogram; // // class MyHistogramElement : public HistogramElement { // public: // MyHistogramElement(char* name); // }; // // MyHistogramElement::MyHistogramElement(char* elementName) { // _name = elementName; // // if(MyHistogram == NULL) // MyHistogram = new Histogram("My Call Counts",100); // // MyHistogram->add_element(this); // } // // #define MyCountWrapper(arg) static MyHistogramElement* e = new MyHistogramElement(arg); e->increment_count() // // This gives you a simple way to count invocations of specfic functions: // // void a_function_that_is_being_counted() { // MyCountWrapper("FunctionName"); // ... // } // // To print the results, invoke print() on your Histogram*. #ifdef ASSERT class HistogramElement : public CHeapObj<mtInternal> { protected: jint _count; const char* _name; public: HistogramElement(); virtual int count(); virtual const char* name(); virtual void increment_count(); void print_on(outputStream* st) const; virtual int compare(HistogramElement* e1,HistogramElement* e2); }; class Histogram : public CHeapObj<mtInternal> { protected: GrowableArray<HistogramElement*>* _elements; GrowableArray<HistogramElement*>* elements() { return _elements; } const char* _title; const char* title() { return _title; } static int sort_helper(HistogramElement** e1,HistogramElement** e2); virtual void print_header(outputStream* st); virtual void print_elements(outputStream* st); public: Histogram(const char* title,int estimatedSize); virtual void add_element(HistogramElement* element); void print_on(outputStream* st) const; }; #endif #endif // SHARE_VM_UTILITIES_HISTOGRAM_HPP
BobZhao/HotSpotResearch
src/share/vm/utilities/histogram.hpp
C++
gpl-2.0
3,519
/** * Authentication controller. * * Here we just bind together the Docs.Auth and AuthForm component. */ Ext.define('Docs.controller.Auth', { extend: 'Ext.app.Controller', requires: [ 'Docs.Auth', 'Docs.Comments' ], refs: [ { ref: "authHeaderForm", selector: "authHeaderForm" } ], init: function() { this.control({ 'authHeaderForm, authForm': { login: this.login, logout: this.logout } }); // HACK: // Because the initialization of comments involves adding an // additional tab, we need to ensure that we do this addition // after Tabs controller has been launched. var tabs = this.getController("Tabs"); tabs.onLaunch = Ext.Function.createSequence(tabs.onLaunch, this.afterTabsLaunch, this); }, afterTabsLaunch: function() { if (Docs.Comments.isEnabled()) { if (Docs.Auth.isLoggedIn()) { this.setLoggedIn(); } else { this.setLoggedOut(); } } }, login: function(form, username, password, remember) { Docs.Auth.login({ username: username, password: password, remember: remember, success: this.setLoggedIn, failure: function(reason) { form.showMessage(reason); }, scope: this }); }, logout: function(form) { Docs.Auth.logout(this.setLoggedOut, this); }, setLoggedIn: function() { Docs.Comments.loadSubscriptions(function() { this.getAuthHeaderForm().showLoggedIn(Docs.Auth.getUser()); this.eachCmp("commentsListWithForm", function(list) { list.showCommentingForm(); }); this.eachCmp("commentsList", function(list) { list.refresh(); }); this.getController("Tabs").showCommentsTab(); }, this); }, setLoggedOut: function() { Docs.Comments.clearSubscriptions(); this.getAuthHeaderForm().showLoggedOut(); this.eachCmp("commentsListWithForm", function(list) { list.showAuthForm(); }); this.eachCmp("commentsList", function(list) { list.refresh(); }); this.getController("Tabs").hideCommentsTab(); }, eachCmp: function(selector, callback, scope) { Ext.Array.forEach(Ext.ComponentQuery.query(selector), callback, scope); } });
ckeditor/jsduck
template/app/controller/Auth.js
JavaScript
gpl-3.0
2,613
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Session Class * * @package CodeIgniter * @subpackage Libraries * @category Sessions * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/sessions.html */ class CI_Session { var $sess_encrypt_cookie = FALSE; var $sess_use_database = FALSE; var $sess_table_name = ''; var $sess_expiration = 7200; var $sess_expire_on_close = FALSE; var $sess_match_ip = FALSE; var $sess_match_useragent = TRUE; var $sess_cookie_name = 'ci_session'; var $cookie_prefix = ''; var $cookie_path = ''; var $cookie_domain = ''; var $cookie_secure = FALSE; var $sess_time_to_update = 300; var $encryption_key = ''; var $flashdata_key = 'flash'; var $time_reference = 'time'; var $gc_probability = 5; var $userdata = array(); var $CI; var $now; /** * Session Constructor * * The constructor runs the session routines automatically * whenever the class is instantiated. */ public function __construct($params = array()) { log_message('debug', "Session Class Initialized"); // Set the super object to a local variable for use throughout the class $this->CI =& get_instance(); // Set all the session preferences, which can either be set // manually via the $params array above or via the config file foreach (array('sess_encrypt_cookie', 'sess_use_database', 'sess_table_name', 'sess_expiration', 'sess_expire_on_close', 'sess_match_ip', 'sess_match_useragent', 'sess_cookie_name', 'cookie_path', 'cookie_domain', 'cookie_secure', 'sess_time_to_update', 'time_reference', 'cookie_prefix', 'encryption_key') as $key) { $this->$key = (isset($params[$key])) ? $params[$key] : $this->CI->config->item($key); } if ($this->encryption_key == '') { show_error('In order to use the Session class you are required to set an encryption key in your config file.'); } // Load the string helper so we can use the strip_slashes() function $this->CI->load->helper('string'); // Do we need encryption? If so, load the encryption class if ($this->sess_encrypt_cookie == TRUE) { $this->CI->load->library('encrypt'); } // Are we using a database? If so, load it if ($this->sess_use_database === TRUE AND $this->sess_table_name != '') { $this->CI->load->database(); } // Set the "now" time. Can either be GMT or server time, based on the // config prefs. We use this to set the "last activity" time $this->now = $this->_get_time(); // Set the session length. If the session expiration is // set to zero we'll set the expiration two years from now. if ($this->sess_expiration == 0) { $this->sess_expiration = (60*60*24*365*2); } // Set the cookie name $this->sess_cookie_name = $this->cookie_prefix.$this->sess_cookie_name; // Run the Session routine. If a session doesn't exist we'll // create a new one. If it does, we'll update it. if ( ! $this->sess_read()) { $this->sess_create(); } else { $this->sess_update(); } // Delete 'old' flashdata (from last request) $this->_flashdata_sweep(); // Mark all new flashdata as old (data will be deleted before next request) $this->_flashdata_mark(); // Delete expired sessions if necessary $this->_sess_gc(); log_message('debug', "Session routines successfully run"); } // -------------------------------------------------------------------- /** * Fetch the current session data if it exists * * @access public * @return bool */ function sess_read() { // Fetch the cookie $session = $this->CI->input->cookie($this->sess_cookie_name); // No cookie? Goodbye cruel world!... if ($session === FALSE) { log_message('debug', 'A session cookie was not found.'); return FALSE; } // HMAC authentication $len = strlen($session) - 40; if ($len <= 0) { log_message('error', 'Session: The session cookie was not signed.'); return FALSE; } // Check cookie authentication $hmac = substr($session, $len); $session = substr($session, 0, $len); // Time-attack-safe comparison $hmac_check = hash_hmac('sha1', $session, $this->encryption_key); $diff = 0; for ($i = 0; $i < 40; $i++) { $xor = ord($hmac[$i]) ^ ord($hmac_check[$i]); $diff |= $xor; } if ($diff !== 0) { log_message('error', 'Session: HMAC mismatch. The session cookie data did not match what was expected.'); $this->sess_destroy(); return FALSE; } // Decrypt the cookie data if ($this->sess_encrypt_cookie == TRUE) { $session = $this->CI->encrypt->decode($session); } // Unserialize the session array $session = $this->_unserialize($session); // Is the session data we unserialized an array with the correct format? if ( ! is_array($session) OR ! isset($session['session_id']) OR ! isset($session['ip_address']) OR ! isset($session['user_agent']) OR ! isset($session['last_activity'])) { $this->sess_destroy(); return FALSE; } // Is the session current? if (($session['last_activity'] + $this->sess_expiration) < $this->now) { $this->sess_destroy(); return FALSE; } // Does the IP Match? if ($this->sess_match_ip == TRUE AND $session['ip_address'] != $this->CI->input->ip_address()) { $this->sess_destroy(); return FALSE; } // Does the User Agent Match? if ($this->sess_match_useragent == TRUE AND trim($session['user_agent']) != trim(substr($this->CI->input->user_agent(), 0, 120))) { $this->sess_destroy(); return FALSE; } // Is there a corresponding session in the DB? if ($this->sess_use_database === TRUE) { $this->CI->db->where('session_id', $session['session_id']); if ($this->sess_match_ip == TRUE) { $this->CI->db->where('ip_address', $session['ip_address']); } if ($this->sess_match_useragent == TRUE) { $this->CI->db->where('user_agent', $session['user_agent']); } $query = $this->CI->db->get($this->sess_table_name); // No result? Kill it! if ($query->num_rows() == 0) { $this->sess_destroy(); return FALSE; } // Is there custom data? If so, add it to the main session array $row = $query->row(); if (isset($row->user_data) AND $row->user_data != '') { $custom_data = $this->_unserialize($row->user_data); if (is_array($custom_data)) { foreach ($custom_data as $key => $val) { $session[$key] = $val; } } } } // Session is valid! $this->userdata = $session; unset($session); return TRUE; } // -------------------------------------------------------------------- /** * Write the session data * * @access public * @return void */ function sess_write() { // Are we saving custom data to the DB? If not, all we do is update the cookie if ($this->sess_use_database === FALSE) { $this->_set_cookie(); return; } // set the custom userdata, the session data we will set in a second $custom_userdata = $this->userdata; $cookie_userdata = array(); // Before continuing, we need to determine if there is any custom data to deal with. // Let's determine this by removing the default indexes to see if there's anything left in the array // and set the session data while we're at it foreach (array('session_id','ip_address','user_agent','last_activity') as $val) { unset($custom_userdata[$val]); $cookie_userdata[$val] = $this->userdata[$val]; } // Did we find any custom data? If not, we turn the empty array into a string // since there's no reason to serialize and store an empty array in the DB if (count($custom_userdata) === 0) { $custom_userdata = ''; } else { // Serialize the custom data array so we can store it $custom_userdata = $this->_serialize($custom_userdata); } // Run the update query $this->CI->db->where('session_id', $this->userdata['session_id']); $this->CI->db->update($this->sess_table_name, array('last_activity' => $this->userdata['last_activity'], 'user_data' => $custom_userdata)); // Write the cookie. Notice that we manually pass the cookie data array to the // _set_cookie() function. Normally that function will store $this->userdata, but // in this case that array contains custom data, which we do not want in the cookie. $this->_set_cookie($cookie_userdata); } // -------------------------------------------------------------------- /** * Create a new session * * @access public * @return void */ function sess_create() { $sessid = ''; while (strlen($sessid) < 32) { $sessid .= mt_rand(0, mt_getrandmax()); } // To make the session ID even more secure we'll combine it with the user's IP $sessid .= $this->CI->input->ip_address(); $this->userdata = array( 'session_id' => md5(uniqid($sessid, TRUE)), 'ip_address' => $this->CI->input->ip_address(), 'user_agent' => substr($this->CI->input->user_agent(), 0, 120), 'last_activity' => $this->now, 'user_data' => '' ); // Save the data to the DB if needed if ($this->sess_use_database === TRUE) { $this->CI->db->query($this->CI->db->insert_string($this->sess_table_name, $this->userdata)); } // Write the cookie $this->_set_cookie(); } // -------------------------------------------------------------------- /** * Update an existing session * * @access public * @return void */ function sess_update() { // We only update the session every five minutes by default if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now) { return; } // Save the old session id so we know which record to // update in the database if we need it $old_sessid = $this->userdata['session_id']; $new_sessid = ''; while (strlen($new_sessid) < 32) { $new_sessid .= mt_rand(0, mt_getrandmax()); } // To make the session ID even more secure we'll combine it with the user's IP $new_sessid .= $this->CI->input->ip_address(); // Turn it into a hash $new_sessid = md5(uniqid($new_sessid, TRUE)); // Update the session data in the session data array $this->userdata['session_id'] = $new_sessid; $this->userdata['last_activity'] = $this->now; // _set_cookie() will handle this for us if we aren't using database sessions // by pushing all userdata to the cookie. $cookie_data = NULL; // Update the session ID and last_activity field in the DB if needed if ($this->sess_use_database === TRUE) { // set cookie explicitly to only have our session data $cookie_data = array(); foreach (array('session_id','ip_address','user_agent','last_activity') as $val) { $cookie_data[$val] = $this->userdata[$val]; } $this->CI->db->query($this->CI->db->update_string($this->sess_table_name, array('last_activity' => $this->now, 'session_id' => $new_sessid), array('session_id' => $old_sessid))); } // Write the cookie $this->_set_cookie($cookie_data); } // -------------------------------------------------------------------- /** * Destroy the current session * * @access public * @return void */ function sess_destroy() { // Kill the session DB row if ($this->sess_use_database === TRUE && isset($this->userdata['session_id'])) { $this->CI->db->where('session_id', $this->userdata['session_id']); $this->CI->db->delete($this->sess_table_name); } // Kill the cookie setcookie( $this->sess_cookie_name, addslashes(serialize(array())), ($this->now - 31500000), $this->cookie_path, $this->cookie_domain, 0 ); // Kill session data $this->userdata = array(); } // -------------------------------------------------------------------- /** * Fetch a specific item from the session array * * @access public * @param string * @return string */ function userdata($item) { return ( ! isset($this->userdata[$item])) ? FALSE : $this->userdata[$item]; } // -------------------------------------------------------------------- /** * Fetch all session data * * @access public * @return array */ function all_userdata() { return $this->userdata; } // -------------------------------------------------------------------- /** * Add or change data in the "userdata" array * * @access public * @param mixed * @param string * @return void */ function set_userdata($newdata = array(), $newval = '') { if (is_string($newdata)) { $newdata = array($newdata => $newval); } if (count($newdata) > 0) { foreach ($newdata as $key => $val) { $this->userdata[$key] = $val; } } $this->sess_write(); } // -------------------------------------------------------------------- /** * Delete a session variable from the "userdata" array * * @access array * @return void */ function unset_userdata($newdata = array()) { if (is_string($newdata)) { $newdata = array($newdata => ''); } if (count($newdata) > 0) { foreach ($newdata as $key => $val) { unset($this->userdata[$key]); } } $this->sess_write(); } // ------------------------------------------------------------------------ /** * Add or change flashdata, only available * until the next request * * @access public * @param mixed * @param string * @return void */ function set_flashdata($newdata = array(), $newval = '') { if (is_string($newdata)) { $newdata = array($newdata => $newval); } if (count($newdata) > 0) { foreach ($newdata as $key => $val) { $flashdata_key = $this->flashdata_key.':new:'.$key; $this->set_userdata($flashdata_key, $val); } } } // ------------------------------------------------------------------------ /** * Keeps existing flashdata available to next request. * * @access public * @param string * @return void */ function keep_flashdata($key) { // 'old' flashdata gets removed. Here we mark all // flashdata as 'new' to preserve it from _flashdata_sweep() // Note the function will return FALSE if the $key // provided cannot be found $old_flashdata_key = $this->flashdata_key.':old:'.$key; $value = $this->userdata($old_flashdata_key); $new_flashdata_key = $this->flashdata_key.':new:'.$key; $this->set_userdata($new_flashdata_key, $value); } // ------------------------------------------------------------------------ /** * Fetch a specific flashdata item from the session array * * @access public * @param string * @return string */ function flashdata($key) { $flashdata_key = $this->flashdata_key.':old:'.$key; return $this->userdata($flashdata_key); } // ------------------------------------------------------------------------ /** * Identifies flashdata as 'old' for removal * when _flashdata_sweep() runs. * * @access private * @return void */ function _flashdata_mark() { $userdata = $this->all_userdata(); foreach ($userdata as $name => $value) { $parts = explode(':new:', $name); if (is_array($parts) && count($parts) === 2) { $new_name = $this->flashdata_key.':old:'.$parts[1]; $this->set_userdata($new_name, $value); $this->unset_userdata($name); } } } // ------------------------------------------------------------------------ /** * Removes all flashdata marked as 'old' * * @access private * @return void */ function _flashdata_sweep() { $userdata = $this->all_userdata(); foreach ($userdata as $key => $value) { if (strpos($key, ':old:')) { $this->unset_userdata($key); } } } // -------------------------------------------------------------------- /** * Get the "now" time * * @access private * @return string */ function _get_time() { if (strtolower($this->time_reference) == 'gmt') { $now = time(); $time = mktime(gmdate("H", $now), gmdate("i", $now), gmdate("s", $now), gmdate("m", $now), gmdate("d", $now), gmdate("Y", $now)); } else { $time = time(); } return $time; } // -------------------------------------------------------------------- /** * Write the session cookie * * @access public * @return void */ function _set_cookie($cookie_data = NULL) { if (is_null($cookie_data)) { $cookie_data = $this->userdata; } // Serialize the userdata for the cookie $cookie_data = $this->_serialize($cookie_data); if ($this->sess_encrypt_cookie == TRUE) { $cookie_data = $this->CI->encrypt->encode($cookie_data); } else { // if encryption is not used, we provide an md5 hash to prevent userside tampering $cookie_data .= hash_hmac('sha1', $cookie_data, $this->encryption_key); } $expire = ($this->sess_expire_on_close === TRUE) ? 0 : $this->sess_expiration + time(); // Set the cookie setcookie( $this->sess_cookie_name, $cookie_data, $expire, $this->cookie_path, $this->cookie_domain, $this->cookie_secure ); } // -------------------------------------------------------------------- /** * Serialize an array * * This function first converts any slashes found in the array to a temporary * marker, so when it gets unserialized the slashes will be preserved * * @access private * @param array * @return string */ function _serialize($data) { if (is_array($data)) { foreach ($data as $key => $val) { if (is_string($val)) { $data[$key] = str_replace('\\', '{{slash}}', $val); } } } else { if (is_string($data)) { $data = str_replace('\\', '{{slash}}', $data); } } return serialize($data); } // -------------------------------------------------------------------- /** * Unserialize * * This function unserializes a data string, then converts any * temporary slash markers back to actual slashes * * @access private * @param array * @return string */ function _unserialize($data) { $data = @unserialize(strip_slashes($data)); if (is_array($data)) { foreach ($data as $key => $val) { if (is_string($val)) { $data[$key] = str_replace('{{slash}}', '\\', $val); } } return $data; } return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data; } // -------------------------------------------------------------------- /** * Garbage collection * * This deletes expired session rows from database * if the probability percentage is met * * @access public * @return void */ function _sess_gc() { if ($this->sess_use_database != TRUE) { return; } srand(time()); if ((rand() % 100) < $this->gc_probability) { $expire = $this->now - $this->sess_expiration; $this->CI->db->where("last_activity < {$expire}"); $this->CI->db->delete($this->sess_table_name); log_message('debug', 'Session garbage collection performed.'); } } } // END Session Class /* End of file Session.php */ /* Location: ./system/libraries/Session.php */
Karplyak/avtomag.url.ph
system/libraries/Session.php
PHP
gpl-3.0
19,399
package dockerimport import ( "fmt" "github.com/mitchellh/packer/builder/docker" "github.com/mitchellh/packer/common" "github.com/mitchellh/packer/packer" ) const BuilderId = "packer.post-processor.docker-import" type Config struct { common.PackerConfig `mapstructure:",squash"` Repository string `mapstructure:"repository"` Tag string `mapstructure:"tag"` tpl *packer.ConfigTemplate } type PostProcessor struct { config Config } func (p *PostProcessor) Configure(raws ...interface{}) error { _, err := common.DecodeConfig(&p.config, raws...) if err != nil { return err } p.config.tpl, err = packer.NewConfigTemplate() if err != nil { return err } p.config.tpl.UserVars = p.config.PackerUserVars // Accumulate any errors errs := new(packer.MultiError) templates := map[string]*string{ "repository": &p.config.Repository, "tag": &p.config.Tag, } for key, ptr := range templates { if *ptr == "" { errs = packer.MultiErrorAppend( errs, fmt.Errorf("%s must be set", key)) } *ptr, err = p.config.tpl.Process(*ptr, nil) if err != nil { errs = packer.MultiErrorAppend( errs, fmt.Errorf("Error processing %s: %s", key, err)) } } if len(errs.Errors) > 0 { return errs } return nil } func (p *PostProcessor) PostProcess(ui packer.Ui, artifact packer.Artifact) (packer.Artifact, bool, error) { if artifact.BuilderId() != docker.BuilderId { err := fmt.Errorf( "Unknown artifact type: %s\nCan only import from Docker builder artifacts.", artifact.BuilderId()) return nil, false, err } importRepo := p.config.Repository if p.config.Tag != "" { importRepo += ":" + p.config.Tag } driver := &docker.DockerDriver{Tpl: p.config.tpl, Ui: ui} ui.Message("Importing image: " + artifact.Id()) ui.Message("Repository: " + importRepo) id, err := driver.Import(artifact.Files()[0], importRepo) if err != nil { return nil, false, err } ui.Message("Imported ID: " + id) // Build the artifact artifact = &docker.ImportArtifact{ BuilderIdValue: BuilderId, Driver: driver, IdValue: importRepo, } return artifact, false, nil }
uber/packer
post-processor/docker-import/post-processor.go
GO
mpl-2.0
2,142
// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved. // See License.txt for license information. package model import ( "strings" "testing" ) func TestInitialLoadJson(t *testing.T) { u := &User{Id: NewId()} o := InitialLoad{User: u} json := o.ToJson() ro := InitialLoadFromJson(strings.NewReader(json)) if o.User.Id != ro.User.Id { t.Fatal("Ids do not match") } }
rahulltkr/platform
model/initial_load_test.go
GO
agpl-3.0
385
/* * eXist Open Source Native XML Database * Copyright (C) 2007 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * $Id: AllIndexTests.java 11737 2010-05-02 21:25:21Z ixitar $ * * @author Pierrick Brihaye <pierrick.brihaye@free.fr> */ package org.exist.indexing.spatial; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ GMLIndexTest.class }) public class AllSpatialTests { }
shabanovd/exist
extensions/indexes/spatial/test/src/org/exist/indexing/spatial/AllSpatialTests.java
Java
lgpl-2.1
1,202
/*************************************************************************** * Copyright (c) 2009 Jürgen Riegel <juergen.riegel@web.de> * * * * This file is part of the FreeCAD CAx development system. * * * * This library 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 library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <QMessageBox> #endif #include "TaskDialog.h" using namespace Gui::TaskView; //************************************************************************** //************************************************************************** // TaskDialog //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskDialog::TaskDialog() : QObject(nullptr), pos(North) , escapeButton(true) , autoCloseTransaction(false) { } TaskDialog::~TaskDialog() { for (std::vector<QWidget*>::iterator it=Content.begin();it!=Content.end();++it) { delete *it; *it = 0; } } //==== Slots =============================================================== const std::vector<QWidget*> &TaskDialog::getDialogContent(void) const { return Content; } bool TaskDialog::canClose() const { QMessageBox msgBox; msgBox.setText(tr("A dialog is already open in the task panel")); msgBox.setInformativeText(QObject::tr("Do you want to close this dialog?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); if (ret == QMessageBox::Yes) return true; else return false; } //==== calls from the TaskView =============================================================== void TaskDialog::open() { } void TaskDialog::closed() { } void TaskDialog::autoClosedOnTransactionChange() { } void TaskDialog::clicked(int) { } bool TaskDialog::accept() { return true; } bool TaskDialog::reject() { return true; } void TaskDialog::helpRequested() { } #include "moc_TaskDialog.cpp"
sanguinariojoe/FreeCAD
src/Gui/TaskView/TaskDialog.cpp
C++
lgpl-2.1
3,435
// Copyright 2012 Cloudera 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. #include "util/metrics.h" #include <sstream> #include <boost/algorithm/string/join.hpp> #include <boost/bind.hpp> #include <boost/mem_fn.hpp> #include <boost/math/special_functions/fpclassify.hpp> #include <gutil/strings/substitute.h> #include <rapidjson/stringbuffer.h> #include <rapidjson/prettywriter.h> #include "common/logging.h" #include "util/impalad-metrics.h" #include "common/names.h" using namespace impala; using namespace rapidjson; using namespace strings; namespace impala { template <> void ToJsonValue<string>(const string& value, const TUnit::type unit, Document* document, Value* out_val) { Value val(value.c_str(), document->GetAllocator()); *out_val = val; } } void Metric::AddStandardFields(Document* document, Value* val) { Value name(key_.c_str(), document->GetAllocator()); val->AddMember("name", name, document->GetAllocator()); Value desc(description_.c_str(), document->GetAllocator()); val->AddMember("description", desc, document->GetAllocator()); Value metric_value(ToHumanReadable().c_str(), document->GetAllocator()); val->AddMember("human_readable", metric_value, document->GetAllocator()); } MetricDefs* MetricDefs::GetInstance() { // Note that this is not thread-safe in C++03 (but will be in C++11 see // http://stackoverflow.com/a/19907903/132034). We don't bother with the double-check // locking pattern because it introduces complexity whereas a race is very unlikely // and it doesn't matter if we construct two instances since MetricDefsConstants is // just a constant map. static MetricDefs instance; return &instance; } TMetricDef MetricDefs::Get(const string& key, const string& arg) { MetricDefs* inst = GetInstance(); map<string, TMetricDef>::iterator it = inst->metric_defs_.TMetricDefs.find(key); if (it == inst->metric_defs_.TMetricDefs.end()) { DCHECK(false) << "Could not find metric definition for key=" << key << " arg=" << arg; return TMetricDef(); } TMetricDef md = it->second; md.__set_key(Substitute(md.key, arg)); md.__set_description(Substitute(md.description, arg)); return md; } MetricGroup::MetricGroup(const string& name) : obj_pool_(new ObjectPool()), name_(name) { } Status MetricGroup::Init(Webserver* webserver) { if (webserver != NULL) { Webserver::UrlCallback default_callback = bind<void>(mem_fn(&MetricGroup::CMCompatibleCallback), this, _1, _2); webserver->RegisterUrlCallback("/jsonmetrics", "legacy-metrics.tmpl", default_callback, false); Webserver::UrlCallback json_callback = bind<void>(mem_fn(&MetricGroup::TemplateCallback), this, _1, _2); webserver->RegisterUrlCallback("/metrics", "metrics.tmpl", json_callback); } return Status::OK(); } void MetricGroup::CMCompatibleCallback(const Webserver::ArgumentMap& args, Document* document) { // If the request has a 'metric' argument, search all top-level metrics for that metric // only. Otherwise, return document with list of all metrics at the top level. Webserver::ArgumentMap::const_iterator metric_name = args.find("metric"); lock_guard<SpinLock> l(lock_); if (metric_name != args.end()) { MetricMap::const_iterator metric = metric_map_.find(metric_name->second); if (metric != metric_map_.end()) { metric->second->ToLegacyJson(document); } return; } stack<MetricGroup*> groups; groups.push(this); do { // Depth-first traversal of children to flatten all metrics, which is what was // expected by CM before we introduced metric groups. MetricGroup* group = groups.top(); groups.pop(); BOOST_FOREACH(const ChildGroupMap::value_type& child, group->children_) { groups.push(child.second); } BOOST_FOREACH(const MetricMap::value_type& m, group->metric_map_) { m.second->ToLegacyJson(document); } } while (!groups.empty()); } void MetricGroup::TemplateCallback(const Webserver::ArgumentMap& args, Document* document) { Webserver::ArgumentMap::const_iterator metric_group = args.find("metric_group"); lock_guard<SpinLock> l(lock_); // If no particular metric group is requested, render this metric group (and all its // children). if (metric_group == args.end()) { Value container; ToJson(true, document, &container); document->AddMember("metric_group", container, document->GetAllocator()); return; } // Search all metric groups to find the one we're looking for. In the future, we'll // change this to support path-based resolution of metric groups. MetricGroup* found_group = NULL; stack<MetricGroup*> groups; groups.push(this); while (!groups.empty() && found_group == NULL) { // Depth-first traversal of children to flatten all metrics, which is what was // expected by CM before we introduced metric groups. MetricGroup* group = groups.top(); groups.pop(); BOOST_FOREACH(const ChildGroupMap::value_type& child, group->children_) { if (child.first == metric_group->second) { found_group = child.second; break; } groups.push(child.second); } } if (found_group != NULL) { Value container; found_group->ToJson(false, document, &container); document->AddMember("metric_group", container, document->GetAllocator()); } else { Value error(Substitute("Metric group $0 not found", metric_group->second).c_str(), document->GetAllocator()); document->AddMember("error", error, document->GetAllocator()); } } void MetricGroup::ToJson(bool include_children, Document* document, Value* out_val) { Value metric_list(kArrayType); BOOST_FOREACH(const MetricMap::value_type& m, metric_map_) { Value metric_value; m.second->ToJson(document, &metric_value); metric_list.PushBack(metric_value, document->GetAllocator()); } Value container(kObjectType); container.AddMember("metrics", metric_list, document->GetAllocator()); container.AddMember("name", name_.c_str(), document->GetAllocator()); if (include_children) { Value child_groups(kArrayType); BOOST_FOREACH(const ChildGroupMap::value_type& child, children_) { Value child_value; child.second->ToJson(true, document, &child_value); child_groups.PushBack(child_value, document->GetAllocator()); } container.AddMember("child_groups", child_groups, document->GetAllocator()); } *out_val = container; } MetricGroup* MetricGroup::GetChildGroup(const string& name) { lock_guard<SpinLock> l(lock_); ChildGroupMap::iterator it = children_.find(name); if (it != children_.end()) return it->second; MetricGroup* group = obj_pool_->Add(new MetricGroup(name)); children_[name] = group; return group; } string MetricGroup::DebugString() { Webserver::ArgumentMap empty_map; Document document; document.SetObject(); TemplateCallback(empty_map, &document); StringBuffer strbuf; PrettyWriter<StringBuffer> writer(strbuf); document.Accept(writer); return strbuf.GetString(); }
brightchen/Impala
be/src/util/metrics.cc
C++
apache-2.0
7,566
/* * Copyright 2000-2014 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.openapi.application; import org.jetbrains.annotations.NotNull; import java.awt.*; /** * Represents the stack of active modal dialogs. */ public abstract class ModalityState { @NotNull public static final ModalityState NON_MODAL; static { try { @SuppressWarnings("unchecked") final Class<? extends ModalityState> ex = (Class<? extends ModalityState>)Class.forName("com.intellij.openapi.application.impl.ModalityStateEx"); NON_MODAL = ex.newInstance(); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } catch (InstantiationException e) { throw new IllegalStateException(e); } } @NotNull public static ModalityState current() { return ApplicationManager.getApplication().getCurrentModalityState(); } @NotNull public static ModalityState any() { return ApplicationManager.getApplication().getAnyModalityState(); } @NotNull public static ModalityState stateForComponent(@NotNull Component component){ return ApplicationManager.getApplication().getModalityStateForComponent(component); } @NotNull public static ModalityState defaultModalityState() { return ApplicationManager.getApplication().getDefaultModalityState(); } public abstract boolean dominates(@NotNull ModalityState anotherState); @Override public abstract String toString(); }
diorcety/intellij-community
platform/core-api/src/com/intellij/openapi/application/ModalityState.java
Java
apache-2.0
2,089
/* * 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.launcher; import java.io.Closeable; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import static org.apache.spark.launcher.LauncherProtocol.*; /** * A server that listens locally for connections from client launched by the library. Each client * has a secret that it needs to send to the server to identify itself and establish the session. * * I/O is currently blocking (one thread per client). Clients have a limited time to connect back * to the server, otherwise the server will ignore the connection. * * === Architecture Overview === * * The launcher server is used when Spark apps are launched as separate processes than the calling * app. It looks more or less like the following: * * ----------------------- ----------------------- * | User App | spark-submit | Spark App | * | | -------------------> | | * | ------------| |------------- | * | | | hello | | | * | | L. Server |<----------------------| L. Backend | | * | | | | | | * | ------------- ----------------------- * | | | ^ * | v | | * | -------------| | * | | | <per-app channel> | * | | App Handle |<------------------------------ * | | | * ----------------------- * * The server is started on demand and remains active while there are active or outstanding clients, * to avoid opening too many ports when multiple clients are launched. Each client is given a unique * secret, and have a limited amount of time to connect back * ({@link SparkLauncher#CHILD_CONNECTION_TIMEOUT}), at which point the server will throw away * that client's state. A client is only allowed to connect back to the server once. * * The launcher server listens on the localhost only, so it doesn't need access controls (aside from * the per-app secret) nor encryption. It thus requires that the launched app has a local process * that communicates with the server. In cluster mode, this means that the client that launches the * application must remain alive for the duration of the application (or until the app handle is * disconnected). */ class LauncherServer implements Closeable { private static final Logger LOG = Logger.getLogger(LauncherServer.class.getName()); private static final String THREAD_NAME_FMT = "LauncherServer-%d"; private static final long DEFAULT_CONNECT_TIMEOUT = 10000L; /** For creating secrets used for communication with child processes. */ private static final SecureRandom RND = new SecureRandom(); private static volatile LauncherServer serverInstance; /** * Creates a handle for an app to be launched. This method will start a server if one hasn't been * started yet. The server is shared for multiple handles, and once all handles are disposed of, * the server is shut down. */ static synchronized ChildProcAppHandle newAppHandle() throws IOException { LauncherServer server = serverInstance != null ? serverInstance : new LauncherServer(); server.ref(); serverInstance = server; String secret = server.createSecret(); while (server.pending.containsKey(secret)) { secret = server.createSecret(); } return server.newAppHandle(secret); } static LauncherServer getServerInstance() { return serverInstance; } private final AtomicLong refCount; private final AtomicLong threadIds; private final ConcurrentMap<String, ChildProcAppHandle> pending; private final List<ServerConnection> clients; private final ServerSocket server; private final Thread serverThread; private final ThreadFactory factory; private final Timer timeoutTimer; private volatile boolean running; private LauncherServer() throws IOException { this.refCount = new AtomicLong(0); ServerSocket server = new ServerSocket(); try { server.setReuseAddress(true); server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0)); this.clients = new ArrayList<>(); this.threadIds = new AtomicLong(); this.factory = new NamedThreadFactory(THREAD_NAME_FMT); this.pending = new ConcurrentHashMap<>(); this.timeoutTimer = new Timer("LauncherServer-TimeoutTimer", true); this.server = server; this.running = true; this.serverThread = factory.newThread(new Runnable() { @Override public void run() { acceptConnections(); } }); serverThread.start(); } catch (IOException ioe) { close(); throw ioe; } catch (Exception e) { close(); throw new IOException(e); } } /** * Creates a new app handle. The handle will wait for an incoming connection for a configurable * amount of time, and if one doesn't arrive, it will transition to an error state. */ ChildProcAppHandle newAppHandle(String secret) { ChildProcAppHandle handle = new ChildProcAppHandle(secret, this); ChildProcAppHandle existing = pending.putIfAbsent(secret, handle); CommandBuilderUtils.checkState(existing == null, "Multiple handles with the same secret."); return handle; } @Override public void close() throws IOException { synchronized (this) { if (running) { running = false; timeoutTimer.cancel(); server.close(); synchronized (clients) { List<ServerConnection> copy = new ArrayList<>(clients); clients.clear(); for (ServerConnection client : copy) { client.close(); } } } } if (serverThread != null) { try { serverThread.join(); } catch (InterruptedException ie) { // no-op } } } void ref() { refCount.incrementAndGet(); } void unref() { synchronized(LauncherServer.class) { if (refCount.decrementAndGet() == 0) { try { close(); } catch (IOException ioe) { // no-op. } finally { serverInstance = null; } } } } int getPort() { return server.getLocalPort(); } /** * Removes the client handle from the pending list (in case it's still there), and unrefs * the server. */ void unregister(ChildProcAppHandle handle) { pending.remove(handle.getSecret()); unref(); } private void acceptConnections() { try { while (running) { final Socket client = server.accept(); TimerTask timeout = new TimerTask() { @Override public void run() { LOG.warning("Timed out waiting for hello message from client."); try { client.close(); } catch (IOException ioe) { // no-op. } } }; ServerConnection clientConnection = new ServerConnection(client, timeout); Thread clientThread = factory.newThread(clientConnection); synchronized (timeout) { clientThread.start(); synchronized (clients) { clients.add(clientConnection); } long timeoutMs = getConnectionTimeout(); // 0 is used for testing to avoid issues with clock resolution / thread scheduling, // and force an immediate timeout. if (timeoutMs > 0) { timeoutTimer.schedule(timeout, getConnectionTimeout()); } else { timeout.run(); } } } } catch (IOException ioe) { if (running) { LOG.log(Level.SEVERE, "Error in accept loop.", ioe); } } } private long getConnectionTimeout() { String value = SparkLauncher.launcherConfig.get(SparkLauncher.CHILD_CONNECTION_TIMEOUT); return (value != null) ? Long.parseLong(value) : DEFAULT_CONNECT_TIMEOUT; } private String createSecret() { byte[] secret = new byte[128]; RND.nextBytes(secret); StringBuilder sb = new StringBuilder(); for (byte b : secret) { int ival = b >= 0 ? b : Byte.MAX_VALUE - b; if (ival < 0x10) { sb.append("0"); } sb.append(Integer.toHexString(ival)); } return sb.toString(); } private class ServerConnection extends LauncherConnection { private TimerTask timeout; private ChildProcAppHandle handle; ServerConnection(Socket socket, TimerTask timeout) throws IOException { super(socket); this.timeout = timeout; } @Override protected void handle(Message msg) throws IOException { try { if (msg instanceof Hello) { timeout.cancel(); timeout = null; Hello hello = (Hello) msg; ChildProcAppHandle handle = pending.remove(hello.secret); if (handle != null) { handle.setConnection(this); handle.setState(SparkAppHandle.State.CONNECTED); this.handle = handle; } else { throw new IllegalArgumentException("Received Hello for unknown client."); } } else { if (handle == null) { throw new IllegalArgumentException("Expected hello, got: " + msg != null ? msg.getClass().getName() : null); } if (msg instanceof SetAppId) { SetAppId set = (SetAppId) msg; handle.setAppId(set.appId); } else if (msg instanceof SetState) { handle.setState(((SetState)msg).state); } else { throw new IllegalArgumentException("Invalid message: " + msg != null ? msg.getClass().getName() : null); } } } catch (Exception e) { LOG.log(Level.INFO, "Error handling message from client.", e); if (timeout != null) { timeout.cancel(); } close(); } finally { timeoutTimer.purge(); } } @Override public void close() throws IOException { synchronized (clients) { clients.remove(this); } super.close(); if (handle != null) { if (!handle.getState().isFinal()) { LOG.log(Level.WARNING, "Lost connection to spark application."); handle.setState(SparkAppHandle.State.LOST); } handle.disconnect(); } } } }
u2009cf/spark-radar
launcher/src/main/java/org/apache/spark/launcher/LauncherServer.java
Java
apache-2.0
11,989
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('estraverse')) : typeof define === 'function' && define.amd ? define(['estraverse'], factory) : (global = global || self, global.esquery = factory(global.estraverse)); }(this, (function (estraverse) { 'use strict'; estraverse = estraverse && Object.prototype.hasOwnProperty.call(estraverse, 'default') ? estraverse['default'] : estraverse; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function () {}; return { s: F, n: function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function (e) { throw e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function () { it = o[Symbol.iterator](); }, n: function () { var step = it.next(); normalCompletion = step.done; return step; }, e: function (e) { didErr = true; err = e; }, f: function () { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var parser = createCommonjsModule(function (module) { /* * Generated by PEG.js 0.10.0. * * http://pegjs.org/ */ (function (root, factory) { if ( module.exports) { module.exports = factory(); } })(commonjsGlobal, function () { function peg$subclass(child, parent) { function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); } function peg$SyntaxError(message, expected, found, location) { this.message = message; this.expected = expected; this.found = found; this.location = location; this.name = "SyntaxError"; if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, peg$SyntaxError); } } peg$subclass(peg$SyntaxError, Error); peg$SyntaxError.buildMessage = function (expected, found) { var DESCRIBE_EXPECTATION_FNS = { literal: function literal(expectation) { return "\"" + literalEscape(expectation.text) + "\""; }, "class": function _class(expectation) { var escapedParts = "", i; for (i = 0; i < expectation.parts.length; i++) { escapedParts += expectation.parts[i] instanceof Array ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) : classEscape(expectation.parts[i]); } return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; }, any: function any(expectation) { return "any character"; }, end: function end(expectation) { return "end of input"; }, other: function other(expectation) { return expectation.description; } }; function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } function literalEscape(s) { return s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) { return '\\x0' + hex(ch); }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return '\\x' + hex(ch); }); } function classEscape(s) { return s.replace(/\\/g, '\\\\').replace(/\]/g, '\\]').replace(/\^/g, '\\^').replace(/-/g, '\\-').replace(/\0/g, '\\0').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/[\x00-\x0F]/g, function (ch) { return '\\x0' + hex(ch); }).replace(/[\x10-\x1F\x7F-\x9F]/g, function (ch) { return '\\x' + hex(ch); }); } function describeExpectation(expectation) { return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); } function describeExpected(expected) { var descriptions = new Array(expected.length), i, j; for (i = 0; i < expected.length; i++) { descriptions[i] = describeExpectation(expected[i]); } descriptions.sort(); if (descriptions.length > 0) { for (i = 1, j = 1; i < descriptions.length; i++) { if (descriptions[i - 1] !== descriptions[i]) { descriptions[j] = descriptions[i]; j++; } } descriptions.length = j; } switch (descriptions.length) { case 1: return descriptions[0]; case 2: return descriptions[0] + " or " + descriptions[1]; default: return descriptions.slice(0, -1).join(", ") + ", or " + descriptions[descriptions.length - 1]; } } function describeFound(found) { return found ? "\"" + literalEscape(found) + "\"" : "end of input"; } return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; }; function peg$parse(input, options) { options = options !== void 0 ? options : {}; var peg$FAILED = {}, peg$startRuleFunctions = { start: peg$parsestart }, peg$startRuleFunction = peg$parsestart, peg$c0 = function peg$c0(ss) { return ss.length === 1 ? ss[0] : { type: 'matches', selectors: ss }; }, peg$c1 = function peg$c1() { return void 0; }, peg$c2 = " ", peg$c3 = peg$literalExpectation(" ", false), peg$c4 = /^[^ [\],():#!=><~+.]/, peg$c5 = peg$classExpectation([" ", "[", "]", ",", "(", ")", ":", "#", "!", "=", ">", "<", "~", "+", "."], true, false), peg$c6 = function peg$c6(i) { return i.join(''); }, peg$c7 = ">", peg$c8 = peg$literalExpectation(">", false), peg$c9 = function peg$c9() { return 'child'; }, peg$c10 = "~", peg$c11 = peg$literalExpectation("~", false), peg$c12 = function peg$c12() { return 'sibling'; }, peg$c13 = "+", peg$c14 = peg$literalExpectation("+", false), peg$c15 = function peg$c15() { return 'adjacent'; }, peg$c16 = function peg$c16() { return 'descendant'; }, peg$c17 = ",", peg$c18 = peg$literalExpectation(",", false), peg$c19 = function peg$c19(s, ss) { return [s].concat(ss.map(function (s) { return s[3]; })); }, peg$c20 = function peg$c20(a, ops) { return ops.reduce(function (memo, rhs) { return { type: rhs[0], left: memo, right: rhs[1] }; }, a); }, peg$c21 = "!", peg$c22 = peg$literalExpectation("!", false), peg$c23 = function peg$c23(subject, as) { var b = as.length === 1 ? as[0] : { type: 'compound', selectors: as }; if (subject) b.subject = true; return b; }, peg$c24 = "*", peg$c25 = peg$literalExpectation("*", false), peg$c26 = function peg$c26(a) { return { type: 'wildcard', value: a }; }, peg$c27 = "#", peg$c28 = peg$literalExpectation("#", false), peg$c29 = function peg$c29(i) { return { type: 'identifier', value: i }; }, peg$c30 = "[", peg$c31 = peg$literalExpectation("[", false), peg$c32 = "]", peg$c33 = peg$literalExpectation("]", false), peg$c34 = function peg$c34(v) { return v; }, peg$c35 = /^[><!]/, peg$c36 = peg$classExpectation([">", "<", "!"], false, false), peg$c37 = "=", peg$c38 = peg$literalExpectation("=", false), peg$c39 = function peg$c39(a) { return (a || '') + '='; }, peg$c40 = /^[><]/, peg$c41 = peg$classExpectation([">", "<"], false, false), peg$c42 = ".", peg$c43 = peg$literalExpectation(".", false), peg$c44 = function peg$c44(a, as) { return [].concat.apply([a], as).join(''); }, peg$c45 = function peg$c45(name, op, value) { return { type: 'attribute', name: name, operator: op, value: value }; }, peg$c46 = function peg$c46(name) { return { type: 'attribute', name: name }; }, peg$c47 = "\"", peg$c48 = peg$literalExpectation("\"", false), peg$c49 = /^[^\\"]/, peg$c50 = peg$classExpectation(["\\", "\""], true, false), peg$c51 = "\\", peg$c52 = peg$literalExpectation("\\", false), peg$c53 = peg$anyExpectation(), peg$c54 = function peg$c54(a, b) { return a + b; }, peg$c55 = function peg$c55(d) { return { type: 'literal', value: strUnescape(d.join('')) }; }, peg$c56 = "'", peg$c57 = peg$literalExpectation("'", false), peg$c58 = /^[^\\']/, peg$c59 = peg$classExpectation(["\\", "'"], true, false), peg$c60 = /^[0-9]/, peg$c61 = peg$classExpectation([["0", "9"]], false, false), peg$c62 = function peg$c62(a, b) { // Can use `a.flat().join('')` once supported var leadingDecimals = a ? [].concat.apply([], a).join('') : ''; return { type: 'literal', value: parseFloat(leadingDecimals + b.join('')) }; }, peg$c63 = function peg$c63(i) { return { type: 'literal', value: i }; }, peg$c64 = "type(", peg$c65 = peg$literalExpectation("type(", false), peg$c66 = /^[^ )]/, peg$c67 = peg$classExpectation([" ", ")"], true, false), peg$c68 = ")", peg$c69 = peg$literalExpectation(")", false), peg$c70 = function peg$c70(t) { return { type: 'type', value: t.join('') }; }, peg$c71 = /^[imsu]/, peg$c72 = peg$classExpectation(["i", "m", "s", "u"], false, false), peg$c73 = "/", peg$c74 = peg$literalExpectation("/", false), peg$c75 = /^[^\/]/, peg$c76 = peg$classExpectation(["/"], true, false), peg$c77 = function peg$c77(d, flgs) { return { type: 'regexp', value: new RegExp(d.join(''), flgs ? flgs.join('') : '') }; }, peg$c78 = function peg$c78(i, is) { return { type: 'field', name: is.reduce(function (memo, p) { return memo + p[0] + p[1]; }, i) }; }, peg$c79 = ":not(", peg$c80 = peg$literalExpectation(":not(", false), peg$c81 = function peg$c81(ss) { return { type: 'not', selectors: ss }; }, peg$c82 = ":matches(", peg$c83 = peg$literalExpectation(":matches(", false), peg$c84 = function peg$c84(ss) { return { type: 'matches', selectors: ss }; }, peg$c85 = ":has(", peg$c86 = peg$literalExpectation(":has(", false), peg$c87 = function peg$c87(ss) { return { type: 'has', selectors: ss }; }, peg$c88 = ":first-child", peg$c89 = peg$literalExpectation(":first-child", false), peg$c90 = function peg$c90() { return nth(1); }, peg$c91 = ":last-child", peg$c92 = peg$literalExpectation(":last-child", false), peg$c93 = function peg$c93() { return nthLast(1); }, peg$c94 = ":nth-child(", peg$c95 = peg$literalExpectation(":nth-child(", false), peg$c96 = function peg$c96(n) { return nth(parseInt(n.join(''), 10)); }, peg$c97 = ":nth-last-child(", peg$c98 = peg$literalExpectation(":nth-last-child(", false), peg$c99 = function peg$c99(n) { return nthLast(parseInt(n.join(''), 10)); }, peg$c100 = ":", peg$c101 = peg$literalExpectation(":", false), peg$c102 = "statement", peg$c103 = peg$literalExpectation("statement", true), peg$c104 = "expression", peg$c105 = peg$literalExpectation("expression", true), peg$c106 = "declaration", peg$c107 = peg$literalExpectation("declaration", true), peg$c108 = "function", peg$c109 = peg$literalExpectation("function", true), peg$c110 = "pattern", peg$c111 = peg$literalExpectation("pattern", true), peg$c112 = function peg$c112(c) { return { type: 'class', name: c }; }, peg$currPos = 0, peg$posDetailsCache = [{ line: 1, column: 1 }], peg$maxFailPos = 0, peg$maxFailExpected = [], peg$resultsCache = {}, peg$result; if ("startRule" in options) { if (!(options.startRule in peg$startRuleFunctions)) { throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; } function peg$literalExpectation(text, ignoreCase) { return { type: "literal", text: text, ignoreCase: ignoreCase }; } function peg$classExpectation(parts, inverted, ignoreCase) { return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; } function peg$anyExpectation() { return { type: "any" }; } function peg$endExpectation() { return { type: "end" }; } function peg$computePosDetails(pos) { var details = peg$posDetailsCache[pos], p; if (details) { return details; } else { p = pos - 1; while (!peg$posDetailsCache[p]) { p--; } details = peg$posDetailsCache[p]; details = { line: details.line, column: details.column }; while (p < pos) { if (input.charCodeAt(p) === 10) { details.line++; details.column = 1; } else { details.column++; } p++; } peg$posDetailsCache[pos] = details; return details; } } function peg$computeLocation(startPos, endPos) { var startPosDetails = peg$computePosDetails(startPos), endPosDetails = peg$computePosDetails(endPos); return { start: { offset: startPos, line: startPosDetails.line, column: startPosDetails.column }, end: { offset: endPos, line: endPosDetails.line, column: endPosDetails.column } }; } function peg$fail(expected) { if (peg$currPos < peg$maxFailPos) { return; } if (peg$currPos > peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected); } function peg$buildStructuredError(expected, found, location) { return new peg$SyntaxError(peg$SyntaxError.buildMessage(expected, found), expected, found, location); } function peg$parsestart() { var s0, s1, s2, s3; var key = peg$currPos * 30 + 0, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; s1 = peg$parse_(); if (s1 !== peg$FAILED) { s2 = peg$parseselectors(); if (s2 !== peg$FAILED) { s3 = peg$parse_(); if (s3 !== peg$FAILED) { s1 = peg$c0(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parse_(); if (s1 !== peg$FAILED) { s1 = peg$c1(); } s0 = s1; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parse_() { var s0, s1; var key = peg$currPos * 30 + 1, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = []; if (input.charCodeAt(peg$currPos) === 32) { s1 = peg$c2; peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c3); } } while (s1 !== peg$FAILED) { s0.push(s1); if (input.charCodeAt(peg$currPos) === 32) { s1 = peg$c2; peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c3); } } } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parseidentifierName() { var s0, s1, s2; var key = peg$currPos * 30 + 2, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; s1 = []; if (peg$c4.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; { peg$fail(peg$c5); } } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); if (peg$c4.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; { peg$fail(peg$c5); } } } } else { s1 = peg$FAILED; } if (s1 !== peg$FAILED) { s1 = peg$c6(s1); } s0 = s1; peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parsebinaryOp() { var s0, s1, s2, s3; var key = peg$currPos * 30 + 3, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; s1 = peg$parse_(); if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 62) { s2 = peg$c7; peg$currPos++; } else { s2 = peg$FAILED; { peg$fail(peg$c8); } } if (s2 !== peg$FAILED) { s3 = peg$parse_(); if (s3 !== peg$FAILED) { s1 = peg$c9(); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parse_(); if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 126) { s2 = peg$c10; peg$currPos++; } else { s2 = peg$FAILED; { peg$fail(peg$c11); } } if (s2 !== peg$FAILED) { s3 = peg$parse_(); if (s3 !== peg$FAILED) { s1 = peg$c12(); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parse_(); if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 43) { s2 = peg$c13; peg$currPos++; } else { s2 = peg$FAILED; { peg$fail(peg$c14); } } if (s2 !== peg$FAILED) { s3 = peg$parse_(); if (s3 !== peg$FAILED) { s1 = peg$c15(); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 32) { s1 = peg$c2; peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c3); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s1 = peg$c16(); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } } } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parseselectors() { var s0, s1, s2, s3, s4, s5, s6, s7; var key = peg$currPos * 30 + 4, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; s1 = peg$parseselector(); if (s1 !== peg$FAILED) { s2 = []; s3 = peg$currPos; s4 = peg$parse_(); if (s4 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 44) { s5 = peg$c17; peg$currPos++; } else { s5 = peg$FAILED; { peg$fail(peg$c18); } } if (s5 !== peg$FAILED) { s6 = peg$parse_(); if (s6 !== peg$FAILED) { s7 = peg$parseselector(); if (s7 !== peg$FAILED) { s4 = [s4, s5, s6, s7]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$currPos; s4 = peg$parse_(); if (s4 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 44) { s5 = peg$c17; peg$currPos++; } else { s5 = peg$FAILED; { peg$fail(peg$c18); } } if (s5 !== peg$FAILED) { s6 = peg$parse_(); if (s6 !== peg$FAILED) { s7 = peg$parseselector(); if (s7 !== peg$FAILED) { s4 = [s4, s5, s6, s7]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } if (s2 !== peg$FAILED) { s1 = peg$c19(s1, s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parseselector() { var s0, s1, s2, s3, s4, s5; var key = peg$currPos * 30 + 5, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; s1 = peg$parsesequence(); if (s1 !== peg$FAILED) { s2 = []; s3 = peg$currPos; s4 = peg$parsebinaryOp(); if (s4 !== peg$FAILED) { s5 = peg$parsesequence(); if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$currPos; s4 = peg$parsebinaryOp(); if (s4 !== peg$FAILED) { s5 = peg$parsesequence(); if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } if (s2 !== peg$FAILED) { s1 = peg$c20(s1, s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parsesequence() { var s0, s1, s2, s3; var key = peg$currPos * 30 + 6, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 33) { s1 = peg$c21; peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c22); } } if (s1 === peg$FAILED) { s1 = null; } if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parseatom(); if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parseatom(); } } else { s2 = peg$FAILED; } if (s2 !== peg$FAILED) { s1 = peg$c23(s1, s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parseatom() { var s0; var key = peg$currPos * 30 + 7, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$parsewildcard(); if (s0 === peg$FAILED) { s0 = peg$parseidentifier(); if (s0 === peg$FAILED) { s0 = peg$parseattr(); if (s0 === peg$FAILED) { s0 = peg$parsefield(); if (s0 === peg$FAILED) { s0 = peg$parsenegation(); if (s0 === peg$FAILED) { s0 = peg$parsematches(); if (s0 === peg$FAILED) { s0 = peg$parsehas(); if (s0 === peg$FAILED) { s0 = peg$parsefirstChild(); if (s0 === peg$FAILED) { s0 = peg$parselastChild(); if (s0 === peg$FAILED) { s0 = peg$parsenthChild(); if (s0 === peg$FAILED) { s0 = peg$parsenthLastChild(); if (s0 === peg$FAILED) { s0 = peg$parseclass(); } } } } } } } } } } } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parsewildcard() { var s0, s1; var key = peg$currPos * 30 + 8, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 42) { s1 = peg$c24; peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c25); } } if (s1 !== peg$FAILED) { s1 = peg$c26(s1); } s0 = s1; peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parseidentifier() { var s0, s1, s2; var key = peg$currPos * 30 + 9, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 35) { s1 = peg$c27; peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c28); } } if (s1 === peg$FAILED) { s1 = null; } if (s1 !== peg$FAILED) { s2 = peg$parseidentifierName(); if (s2 !== peg$FAILED) { s1 = peg$c29(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parseattr() { var s0, s1, s2, s3, s4, s5; var key = peg$currPos * 30 + 10, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 91) { s1 = peg$c30; peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c31); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = peg$parseattrValue(); if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 93) { s5 = peg$c32; peg$currPos++; } else { s5 = peg$FAILED; { peg$fail(peg$c33); } } if (s5 !== peg$FAILED) { s1 = peg$c34(s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parseattrOps() { var s0, s1, s2; var key = peg$currPos * 30 + 11, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (peg$c35.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c36); } } if (s1 === peg$FAILED) { s1 = null; } if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 61) { s2 = peg$c37; peg$currPos++; } else { s2 = peg$FAILED; { peg$fail(peg$c38); } } if (s2 !== peg$FAILED) { s1 = peg$c39(s1); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { if (peg$c40.test(input.charAt(peg$currPos))) { s0 = input.charAt(peg$currPos); peg$currPos++; } else { s0 = peg$FAILED; { peg$fail(peg$c41); } } } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parseattrEqOps() { var s0, s1, s2; var key = peg$currPos * 30 + 12, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 33) { s1 = peg$c21; peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c22); } } if (s1 === peg$FAILED) { s1 = null; } if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 61) { s2 = peg$c37; peg$currPos++; } else { s2 = peg$FAILED; { peg$fail(peg$c38); } } if (s2 !== peg$FAILED) { s1 = peg$c39(s1); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parseattrName() { var s0, s1, s2, s3, s4, s5; var key = peg$currPos * 30 + 13, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; s1 = peg$parseidentifierName(); if (s1 !== peg$FAILED) { s2 = []; s3 = peg$currPos; if (input.charCodeAt(peg$currPos) === 46) { s4 = peg$c42; peg$currPos++; } else { s4 = peg$FAILED; { peg$fail(peg$c43); } } if (s4 !== peg$FAILED) { s5 = peg$parseidentifierName(); if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$currPos; if (input.charCodeAt(peg$currPos) === 46) { s4 = peg$c42; peg$currPos++; } else { s4 = peg$FAILED; { peg$fail(peg$c43); } } if (s4 !== peg$FAILED) { s5 = peg$parseidentifierName(); if (s5 !== peg$FAILED) { s4 = [s4, s5]; s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } if (s2 !== peg$FAILED) { s1 = peg$c44(s1, s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parseattrValue() { var s0, s1, s2, s3, s4, s5; var key = peg$currPos * 30 + 14, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; s1 = peg$parseattrName(); if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = peg$parseattrEqOps(); if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { s5 = peg$parsetype(); if (s5 === peg$FAILED) { s5 = peg$parseregex(); } if (s5 !== peg$FAILED) { s1 = peg$c45(s1, s3, s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseattrName(); if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = peg$parseattrOps(); if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { s5 = peg$parsestring(); if (s5 === peg$FAILED) { s5 = peg$parsenumber(); if (s5 === peg$FAILED) { s5 = peg$parsepath(); } } if (s5 !== peg$FAILED) { s1 = peg$c45(s1, s3, s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseattrName(); if (s1 !== peg$FAILED) { s1 = peg$c46(s1); } s0 = s1; } } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parsestring() { var s0, s1, s2, s3, s4, s5; var key = peg$currPos * 30 + 15, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 34) { s1 = peg$c47; peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c48); } } if (s1 !== peg$FAILED) { s2 = []; if (peg$c49.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; { peg$fail(peg$c50); } } if (s3 === peg$FAILED) { s3 = peg$currPos; if (input.charCodeAt(peg$currPos) === 92) { s4 = peg$c51; peg$currPos++; } else { s4 = peg$FAILED; { peg$fail(peg$c52); } } if (s4 !== peg$FAILED) { if (input.length > peg$currPos) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; { peg$fail(peg$c53); } } if (s5 !== peg$FAILED) { s4 = peg$c54(s4, s5); s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } while (s3 !== peg$FAILED) { s2.push(s3); if (peg$c49.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; { peg$fail(peg$c50); } } if (s3 === peg$FAILED) { s3 = peg$currPos; if (input.charCodeAt(peg$currPos) === 92) { s4 = peg$c51; peg$currPos++; } else { s4 = peg$FAILED; { peg$fail(peg$c52); } } if (s4 !== peg$FAILED) { if (input.length > peg$currPos) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; { peg$fail(peg$c53); } } if (s5 !== peg$FAILED) { s4 = peg$c54(s4, s5); s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } } if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 34) { s3 = peg$c47; peg$currPos++; } else { s3 = peg$FAILED; { peg$fail(peg$c48); } } if (s3 !== peg$FAILED) { s1 = peg$c55(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 39) { s1 = peg$c56; peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c57); } } if (s1 !== peg$FAILED) { s2 = []; if (peg$c58.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; { peg$fail(peg$c59); } } if (s3 === peg$FAILED) { s3 = peg$currPos; if (input.charCodeAt(peg$currPos) === 92) { s4 = peg$c51; peg$currPos++; } else { s4 = peg$FAILED; { peg$fail(peg$c52); } } if (s4 !== peg$FAILED) { if (input.length > peg$currPos) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; { peg$fail(peg$c53); } } if (s5 !== peg$FAILED) { s4 = peg$c54(s4, s5); s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } while (s3 !== peg$FAILED) { s2.push(s3); if (peg$c58.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; { peg$fail(peg$c59); } } if (s3 === peg$FAILED) { s3 = peg$currPos; if (input.charCodeAt(peg$currPos) === 92) { s4 = peg$c51; peg$currPos++; } else { s4 = peg$FAILED; { peg$fail(peg$c52); } } if (s4 !== peg$FAILED) { if (input.length > peg$currPos) { s5 = input.charAt(peg$currPos); peg$currPos++; } else { s5 = peg$FAILED; { peg$fail(peg$c53); } } if (s5 !== peg$FAILED) { s4 = peg$c54(s4, s5); s3 = s4; } else { peg$currPos = s3; s3 = peg$FAILED; } } else { peg$currPos = s3; s3 = peg$FAILED; } } } if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 39) { s3 = peg$c56; peg$currPos++; } else { s3 = peg$FAILED; { peg$fail(peg$c57); } } if (s3 !== peg$FAILED) { s1 = peg$c55(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parsenumber() { var s0, s1, s2, s3; var key = peg$currPos * 30 + 16, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; s1 = peg$currPos; s2 = []; if (peg$c60.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; { peg$fail(peg$c61); } } while (s3 !== peg$FAILED) { s2.push(s3); if (peg$c60.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; { peg$fail(peg$c61); } } } if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 46) { s3 = peg$c42; peg$currPos++; } else { s3 = peg$FAILED; { peg$fail(peg$c43); } } if (s3 !== peg$FAILED) { s2 = [s2, s3]; s1 = s2; } else { peg$currPos = s1; s1 = peg$FAILED; } } else { peg$currPos = s1; s1 = peg$FAILED; } if (s1 === peg$FAILED) { s1 = null; } if (s1 !== peg$FAILED) { s2 = []; if (peg$c60.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; { peg$fail(peg$c61); } } if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); if (peg$c60.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; { peg$fail(peg$c61); } } } } else { s2 = peg$FAILED; } if (s2 !== peg$FAILED) { s1 = peg$c62(s1, s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parsepath() { var s0, s1; var key = peg$currPos * 30 + 17, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; s1 = peg$parseidentifierName(); if (s1 !== peg$FAILED) { s1 = peg$c63(s1); } s0 = s1; peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parsetype() { var s0, s1, s2, s3, s4, s5; var key = peg$currPos * 30 + 18, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.substr(peg$currPos, 5) === peg$c64) { s1 = peg$c64; peg$currPos += 5; } else { s1 = peg$FAILED; { peg$fail(peg$c65); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = []; if (peg$c66.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; { peg$fail(peg$c67); } } if (s4 !== peg$FAILED) { while (s4 !== peg$FAILED) { s3.push(s4); if (peg$c66.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; { peg$fail(peg$c67); } } } } else { s3 = peg$FAILED; } if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 41) { s5 = peg$c68; peg$currPos++; } else { s5 = peg$FAILED; { peg$fail(peg$c69); } } if (s5 !== peg$FAILED) { s1 = peg$c70(s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parseflags() { var s0, s1; var key = peg$currPos * 30 + 19, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = []; if (peg$c71.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c72); } } if (s1 !== peg$FAILED) { while (s1 !== peg$FAILED) { s0.push(s1); if (peg$c71.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c72); } } } } else { s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parseregex() { var s0, s1, s2, s3, s4; var key = peg$currPos * 30 + 20, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 47) { s1 = peg$c73; peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c74); } } if (s1 !== peg$FAILED) { s2 = []; if (peg$c75.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; { peg$fail(peg$c76); } } if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); if (peg$c75.test(input.charAt(peg$currPos))) { s3 = input.charAt(peg$currPos); peg$currPos++; } else { s3 = peg$FAILED; { peg$fail(peg$c76); } } } } else { s2 = peg$FAILED; } if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 47) { s3 = peg$c73; peg$currPos++; } else { s3 = peg$FAILED; { peg$fail(peg$c74); } } if (s3 !== peg$FAILED) { s4 = peg$parseflags(); if (s4 === peg$FAILED) { s4 = null; } if (s4 !== peg$FAILED) { s1 = peg$c77(s2, s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parsefield() { var s0, s1, s2, s3, s4, s5, s6; var key = peg$currPos * 30 + 21, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 46) { s1 = peg$c42; peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c43); } } if (s1 !== peg$FAILED) { s2 = peg$parseidentifierName(); if (s2 !== peg$FAILED) { s3 = []; s4 = peg$currPos; if (input.charCodeAt(peg$currPos) === 46) { s5 = peg$c42; peg$currPos++; } else { s5 = peg$FAILED; { peg$fail(peg$c43); } } if (s5 !== peg$FAILED) { s6 = peg$parseidentifierName(); if (s6 !== peg$FAILED) { s5 = [s5, s6]; s4 = s5; } else { peg$currPos = s4; s4 = peg$FAILED; } } else { peg$currPos = s4; s4 = peg$FAILED; } while (s4 !== peg$FAILED) { s3.push(s4); s4 = peg$currPos; if (input.charCodeAt(peg$currPos) === 46) { s5 = peg$c42; peg$currPos++; } else { s5 = peg$FAILED; { peg$fail(peg$c43); } } if (s5 !== peg$FAILED) { s6 = peg$parseidentifierName(); if (s6 !== peg$FAILED) { s5 = [s5, s6]; s4 = s5; } else { peg$currPos = s4; s4 = peg$FAILED; } } else { peg$currPos = s4; s4 = peg$FAILED; } } if (s3 !== peg$FAILED) { s1 = peg$c78(s2, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parsenegation() { var s0, s1, s2, s3, s4, s5; var key = peg$currPos * 30 + 22, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.substr(peg$currPos, 5) === peg$c79) { s1 = peg$c79; peg$currPos += 5; } else { s1 = peg$FAILED; { peg$fail(peg$c80); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = peg$parseselectors(); if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 41) { s5 = peg$c68; peg$currPos++; } else { s5 = peg$FAILED; { peg$fail(peg$c69); } } if (s5 !== peg$FAILED) { s1 = peg$c81(s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parsematches() { var s0, s1, s2, s3, s4, s5; var key = peg$currPos * 30 + 23, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.substr(peg$currPos, 9) === peg$c82) { s1 = peg$c82; peg$currPos += 9; } else { s1 = peg$FAILED; { peg$fail(peg$c83); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = peg$parseselectors(); if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 41) { s5 = peg$c68; peg$currPos++; } else { s5 = peg$FAILED; { peg$fail(peg$c69); } } if (s5 !== peg$FAILED) { s1 = peg$c84(s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parsehas() { var s0, s1, s2, s3, s4, s5; var key = peg$currPos * 30 + 24, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.substr(peg$currPos, 5) === peg$c85) { s1 = peg$c85; peg$currPos += 5; } else { s1 = peg$FAILED; { peg$fail(peg$c86); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = peg$parseselectors(); if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 41) { s5 = peg$c68; peg$currPos++; } else { s5 = peg$FAILED; { peg$fail(peg$c69); } } if (s5 !== peg$FAILED) { s1 = peg$c87(s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parsefirstChild() { var s0, s1; var key = peg$currPos * 30 + 25, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.substr(peg$currPos, 12) === peg$c88) { s1 = peg$c88; peg$currPos += 12; } else { s1 = peg$FAILED; { peg$fail(peg$c89); } } if (s1 !== peg$FAILED) { s1 = peg$c90(); } s0 = s1; peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parselastChild() { var s0, s1; var key = peg$currPos * 30 + 26, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.substr(peg$currPos, 11) === peg$c91) { s1 = peg$c91; peg$currPos += 11; } else { s1 = peg$FAILED; { peg$fail(peg$c92); } } if (s1 !== peg$FAILED) { s1 = peg$c93(); } s0 = s1; peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parsenthChild() { var s0, s1, s2, s3, s4, s5; var key = peg$currPos * 30 + 27, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.substr(peg$currPos, 11) === peg$c94) { s1 = peg$c94; peg$currPos += 11; } else { s1 = peg$FAILED; { peg$fail(peg$c95); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = []; if (peg$c60.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; { peg$fail(peg$c61); } } if (s4 !== peg$FAILED) { while (s4 !== peg$FAILED) { s3.push(s4); if (peg$c60.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; { peg$fail(peg$c61); } } } } else { s3 = peg$FAILED; } if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 41) { s5 = peg$c68; peg$currPos++; } else { s5 = peg$FAILED; { peg$fail(peg$c69); } } if (s5 !== peg$FAILED) { s1 = peg$c96(s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parsenthLastChild() { var s0, s1, s2, s3, s4, s5; var key = peg$currPos * 30 + 28, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.substr(peg$currPos, 16) === peg$c97) { s1 = peg$c97; peg$currPos += 16; } else { s1 = peg$FAILED; { peg$fail(peg$c98); } } if (s1 !== peg$FAILED) { s2 = peg$parse_(); if (s2 !== peg$FAILED) { s3 = []; if (peg$c60.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; { peg$fail(peg$c61); } } if (s4 !== peg$FAILED) { while (s4 !== peg$FAILED) { s3.push(s4); if (peg$c60.test(input.charAt(peg$currPos))) { s4 = input.charAt(peg$currPos); peg$currPos++; } else { s4 = peg$FAILED; { peg$fail(peg$c61); } } } } else { s3 = peg$FAILED; } if (s3 !== peg$FAILED) { s4 = peg$parse_(); if (s4 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 41) { s5 = peg$c68; peg$currPos++; } else { s5 = peg$FAILED; { peg$fail(peg$c69); } } if (s5 !== peg$FAILED) { s1 = peg$c99(s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function peg$parseclass() { var s0, s1, s2; var key = peg$currPos * 30 + 29, cached = peg$resultsCache[key]; if (cached) { peg$currPos = cached.nextPos; return cached.result; } s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 58) { s1 = peg$c100; peg$currPos++; } else { s1 = peg$FAILED; { peg$fail(peg$c101); } } if (s1 !== peg$FAILED) { if (input.substr(peg$currPos, 9).toLowerCase() === peg$c102) { s2 = input.substr(peg$currPos, 9); peg$currPos += 9; } else { s2 = peg$FAILED; { peg$fail(peg$c103); } } if (s2 === peg$FAILED) { if (input.substr(peg$currPos, 10).toLowerCase() === peg$c104) { s2 = input.substr(peg$currPos, 10); peg$currPos += 10; } else { s2 = peg$FAILED; { peg$fail(peg$c105); } } if (s2 === peg$FAILED) { if (input.substr(peg$currPos, 11).toLowerCase() === peg$c106) { s2 = input.substr(peg$currPos, 11); peg$currPos += 11; } else { s2 = peg$FAILED; { peg$fail(peg$c107); } } if (s2 === peg$FAILED) { if (input.substr(peg$currPos, 8).toLowerCase() === peg$c108) { s2 = input.substr(peg$currPos, 8); peg$currPos += 8; } else { s2 = peg$FAILED; { peg$fail(peg$c109); } } if (s2 === peg$FAILED) { if (input.substr(peg$currPos, 7).toLowerCase() === peg$c110) { s2 = input.substr(peg$currPos, 7); peg$currPos += 7; } else { s2 = peg$FAILED; { peg$fail(peg$c111); } } } } } } if (s2 !== peg$FAILED) { s1 = peg$c112(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$FAILED; } } else { peg$currPos = s0; s0 = peg$FAILED; } peg$resultsCache[key] = { nextPos: peg$currPos, result: s0 }; return s0; } function nth(n) { return { type: 'nth-child', index: { type: 'literal', value: n } }; } function nthLast(n) { return { type: 'nth-last-child', index: { type: 'literal', value: n } }; } function strUnescape(s) { return s.replace(/\\(.)/g, function (match, ch) { switch (ch) { case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; default: return ch; } }); } peg$result = peg$startRuleFunction(); if (peg$result !== peg$FAILED && peg$currPos === input.length) { return peg$result; } else { if (peg$result !== peg$FAILED && peg$currPos < input.length) { peg$fail(peg$endExpectation()); } throw peg$buildStructuredError(peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)); } } return { SyntaxError: peg$SyntaxError, parse: peg$parse }; }); }); function _objectEntries(obj) { var entries = []; var keys = Object.keys(obj); for (var k = 0; k < keys.length; k++) entries.push([keys[k], obj[keys[k]]]); return entries; } /** * @typedef {"LEFT_SIDE"|"RIGHT_SIDE"} Side */ var LEFT_SIDE = 'LEFT_SIDE'; var RIGHT_SIDE = 'RIGHT_SIDE'; /** * @external AST * @see https://esprima.readthedocs.io/en/latest/syntax-tree-format.html */ /** * One of the rules of `grammar.pegjs` * @typedef {PlainObject} SelectorAST * @see grammar.pegjs */ /** * The `sequence` production of `grammar.pegjs` * @typedef {PlainObject} SelectorSequenceAST */ /** * Get the value of a property which may be multiple levels down * in the object. * @param {?PlainObject} obj * @param {string} key * @returns {undefined|boolean|string|number|external:AST} */ function getPath(obj, key) { var keys = key.split('.'); var _iterator = _createForOfIteratorHelper(keys), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _key = _step.value; if (obj == null) { return obj; } obj = obj[_key]; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return obj; } /** * Determine whether `node` can be reached by following `path`, * starting at `ancestor`. * @param {?external:AST} node * @param {?external:AST} ancestor * @param {string[]} path * @returns {boolean} */ function inPath(node, ancestor, path) { if (path.length === 0) { return node === ancestor; } if (ancestor == null) { return false; } var field = ancestor[path[0]]; var remainingPath = path.slice(1); if (Array.isArray(field)) { var _iterator2 = _createForOfIteratorHelper(field), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var component = _step2.value; if (inPath(node, component, remainingPath)) { return true; } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return false; } else { return inPath(node, field, remainingPath); } } /** * @callback TraverseOptionFallback * @param {external:AST} node The given node. * @returns {string[]} An array of visitor keys for the given node. */ /** * @typedef {object} ESQueryOptions * @property { { [nodeType: string]: string[] } } [visitorKeys] By passing `visitorKeys` mapping, we can extend the properties of the nodes that traverse the node. * @property {TraverseOptionFallback} [fallback] By passing `fallback` option, we can control the properties of traversing nodes when encountering unknown nodes. */ /** * Given a `node` and its ancestors, determine if `node` is matched * by `selector`. * @param {?external:AST} node * @param {?SelectorAST} selector * @param {external:AST[]} [ancestry=[]] * @param {ESQueryOptions} [options] * @throws {Error} Unknowns (operator, class name, selector type, or * selector value type) * @returns {boolean} */ function matches(node, selector, ancestry, options) { if (!selector) { return true; } if (!node) { return false; } if (!ancestry) { ancestry = []; } switch (selector.type) { case 'wildcard': return true; case 'identifier': return selector.value.toLowerCase() === node.type.toLowerCase(); case 'field': { var path = selector.name.split('.'); var ancestor = ancestry[path.length - 1]; return inPath(node, ancestor, path); } case 'matches': var _iterator3 = _createForOfIteratorHelper(selector.selectors), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var sel = _step3.value; if (matches(node, sel, ancestry, options)) { return true; } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return false; case 'compound': var _iterator4 = _createForOfIteratorHelper(selector.selectors), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var _sel = _step4.value; if (!matches(node, _sel, ancestry, options)) { return false; } } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } return true; case 'not': var _iterator5 = _createForOfIteratorHelper(selector.selectors), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var _sel2 = _step5.value; if (matches(node, _sel2, ancestry, options)) { return false; } } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } return true; case 'has': { var _ret = function () { var collector = []; var _iterator6 = _createForOfIteratorHelper(selector.selectors), _step6; try { var _loop = function _loop() { var sel = _step6.value; var a = []; estraverse.traverse(node, { enter: function enter(node, parent) { if (parent != null) { a.unshift(parent); } if (matches(node, sel, a, options)) { collector.push(node); } }, leave: function leave() { a.shift(); }, keys: options && options.visitorKeys, fallback: options && options.fallback || 'iteration' }); }; for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { _loop(); } } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } return { v: collector.length !== 0 }; }(); if (_typeof(_ret) === "object") return _ret.v; } case 'child': if (matches(node, selector.right, ancestry, options)) { return matches(ancestry[0], selector.left, ancestry.slice(1), options); } return false; case 'descendant': if (matches(node, selector.right, ancestry, options)) { for (var i = 0, l = ancestry.length; i < l; ++i) { if (matches(ancestry[i], selector.left, ancestry.slice(i + 1), options)) { return true; } } } return false; case 'attribute': { var p = getPath(node, selector.name); switch (selector.operator) { case void 0: return p != null; case '=': switch (selector.value.type) { case 'regexp': return typeof p === 'string' && selector.value.value.test(p); case 'literal': return "".concat(selector.value.value) === "".concat(p); case 'type': return selector.value.value === _typeof(p); } throw new Error("Unknown selector value type: ".concat(selector.value.type)); case '!=': switch (selector.value.type) { case 'regexp': return !selector.value.value.test(p); case 'literal': return "".concat(selector.value.value) !== "".concat(p); case 'type': return selector.value.value !== _typeof(p); } throw new Error("Unknown selector value type: ".concat(selector.value.type)); case '<=': return p <= selector.value.value; case '<': return p < selector.value.value; case '>': return p > selector.value.value; case '>=': return p >= selector.value.value; } throw new Error("Unknown operator: ".concat(selector.operator)); } case 'sibling': return matches(node, selector.right, ancestry, options) && sibling(node, selector.left, ancestry, LEFT_SIDE, options) || selector.left.subject && matches(node, selector.left, ancestry, options) && sibling(node, selector.right, ancestry, RIGHT_SIDE, options); case 'adjacent': return matches(node, selector.right, ancestry, options) && adjacent(node, selector.left, ancestry, LEFT_SIDE, options) || selector.right.subject && matches(node, selector.left, ancestry, options) && adjacent(node, selector.right, ancestry, RIGHT_SIDE, options); case 'nth-child': return matches(node, selector.right, ancestry, options) && nthChild(node, ancestry, function () { return selector.index.value - 1; }, options); case 'nth-last-child': return matches(node, selector.right, ancestry, options) && nthChild(node, ancestry, function (length) { return length - selector.index.value; }, options); case 'class': switch (selector.name.toLowerCase()) { case 'statement': if (node.type.slice(-9) === 'Statement') return true; // fallthrough: interface Declaration <: Statement { } case 'declaration': return node.type.slice(-11) === 'Declaration'; case 'pattern': if (node.type.slice(-7) === 'Pattern') return true; // fallthrough: interface Expression <: Node, Pattern { } case 'expression': return node.type.slice(-10) === 'Expression' || node.type.slice(-7) === 'Literal' || node.type === 'Identifier' && (ancestry.length === 0 || ancestry[0].type !== 'MetaProperty') || node.type === 'MetaProperty'; case 'function': return node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression'; } throw new Error("Unknown class name: ".concat(selector.name)); } throw new Error("Unknown selector type: ".concat(selector.type)); } /** * Get visitor keys of a given node. * @param {external:AST} node The AST node to get keys. * @param {ESQueryOptions|undefined} options * @returns {string[]} Visitor keys of the node. */ function getVisitorKeys(node, options) { var nodeType = node.type; if (options && options.visitorKeys && options.visitorKeys[nodeType]) { return options.visitorKeys[nodeType]; } if (estraverse.VisitorKeys[nodeType]) { return estraverse.VisitorKeys[nodeType]; } if (options && typeof options.fallback === 'function') { return options.fallback(node); } // 'iteration' fallback return Object.keys(node).filter(function (key) { return key !== 'type'; }); } /** * Check whether the given value is an ASTNode or not. * @param {any} node The value to check. * @returns {boolean} `true` if the value is an ASTNode. */ function isNode(node) { return node !== null && _typeof(node) === 'object' && typeof node.type === 'string'; } /** * Determines if the given node has a sibling that matches the * given selector. * @param {external:AST} node * @param {SelectorSequenceAST} selector * @param {external:AST[]} ancestry * @param {Side} side * @param {ESQueryOptions|undefined} options * @returns {boolean} */ function sibling(node, selector, ancestry, side, options) { var _ancestry = _slicedToArray(ancestry, 1), parent = _ancestry[0]; if (!parent) { return false; } var keys = getVisitorKeys(parent, options); var _iterator7 = _createForOfIteratorHelper(keys), _step7; try { for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) { var key = _step7.value; var listProp = parent[key]; if (Array.isArray(listProp)) { var startIndex = listProp.indexOf(node); if (startIndex < 0) { continue; } var lowerBound = void 0, upperBound = void 0; if (side === LEFT_SIDE) { lowerBound = 0; upperBound = startIndex; } else { lowerBound = startIndex + 1; upperBound = listProp.length; } for (var k = lowerBound; k < upperBound; ++k) { if (isNode(listProp[k]) && matches(listProp[k], selector, ancestry, options)) { return true; } } } } } catch (err) { _iterator7.e(err); } finally { _iterator7.f(); } return false; } /** * Determines if the given node has an adjacent sibling that matches * the given selector. * @param {external:AST} node * @param {SelectorSequenceAST} selector * @param {external:AST[]} ancestry * @param {Side} side * @param {ESQueryOptions|undefined} options * @returns {boolean} */ function adjacent(node, selector, ancestry, side, options) { var _ancestry2 = _slicedToArray(ancestry, 1), parent = _ancestry2[0]; if (!parent) { return false; } var keys = getVisitorKeys(parent, options); var _iterator8 = _createForOfIteratorHelper(keys), _step8; try { for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) { var key = _step8.value; var listProp = parent[key]; if (Array.isArray(listProp)) { var idx = listProp.indexOf(node); if (idx < 0) { continue; } if (side === LEFT_SIDE && idx > 0 && isNode(listProp[idx - 1]) && matches(listProp[idx - 1], selector, ancestry, options)) { return true; } if (side === RIGHT_SIDE && idx < listProp.length - 1 && isNode(listProp[idx + 1]) && matches(listProp[idx + 1], selector, ancestry, options)) { return true; } } } } catch (err) { _iterator8.e(err); } finally { _iterator8.f(); } return false; } /** * @callback IndexFunction * @param {Integer} len Containing list's length * @returns {Integer} */ /** * Determines if the given node is the nth child, determined by * `idxFn`, which is given the containing list's length. * @param {external:AST} node * @param {external:AST[]} ancestry * @param {IndexFunction} idxFn * @param {ESQueryOptions|undefined} options * @returns {boolean} */ function nthChild(node, ancestry, idxFn, options) { var _ancestry3 = _slicedToArray(ancestry, 1), parent = _ancestry3[0]; if (!parent) { return false; } var keys = getVisitorKeys(parent, options); var _iterator9 = _createForOfIteratorHelper(keys), _step9; try { for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) { var key = _step9.value; var listProp = parent[key]; if (Array.isArray(listProp)) { var idx = listProp.indexOf(node); if (idx >= 0 && idx === idxFn(listProp.length)) { return true; } } } } catch (err) { _iterator9.e(err); } finally { _iterator9.f(); } return false; } /** * For each selector node marked as a subject, find the portion of the * selector that the subject must match. * @param {SelectorAST} selector * @param {SelectorAST} [ancestor] Defaults to `selector` * @returns {SelectorAST[]} */ function subjects(selector, ancestor) { if (selector == null || _typeof(selector) != 'object') { return []; } if (ancestor == null) { ancestor = selector; } var results = selector.subject ? [ancestor] : []; for (var _i = 0, _Object$entries = _objectEntries(selector); _i < _Object$entries.length; _i++) { var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), p = _Object$entries$_i[0], sel = _Object$entries$_i[1]; results.push.apply(results, _toConsumableArray(subjects(sel, p === 'left' ? sel : ancestor))); } return results; } /** * @callback TraverseVisitor * @param {?external:AST} node * @param {?external:AST} parent * @param {external:AST[]} ancestry */ /** * From a JS AST and a selector AST, collect all JS AST nodes that * match the selector. * @param {external:AST} ast * @param {?SelectorAST} selector * @param {TraverseVisitor} visitor * @param {ESQueryOptions} [options] * @returns {external:AST[]} */ function traverse(ast, selector, visitor, options) { if (!selector) { return; } var ancestry = []; var altSubjects = subjects(selector); estraverse.traverse(ast, { enter: function enter(node, parent) { if (parent != null) { ancestry.unshift(parent); } if (matches(node, selector, ancestry, options)) { if (altSubjects.length) { for (var i = 0, l = altSubjects.length; i < l; ++i) { if (matches(node, altSubjects[i], ancestry, options)) { visitor(node, parent, ancestry); } for (var k = 0, m = ancestry.length; k < m; ++k) { var succeedingAncestry = ancestry.slice(k + 1); if (matches(ancestry[k], altSubjects[i], succeedingAncestry, options)) { visitor(ancestry[k], parent, succeedingAncestry); } } } } else { visitor(node, parent, ancestry); } } }, leave: function leave() { ancestry.shift(); }, keys: options && options.visitorKeys, fallback: options && options.fallback || 'iteration' }); } /** * From a JS AST and a selector AST, collect all JS AST nodes that * match the selector. * @param {external:AST} ast * @param {?SelectorAST} selector * @param {ESQueryOptions} [options] * @returns {external:AST[]} */ function match(ast, selector, options) { var results = []; traverse(ast, selector, function (node) { results.push(node); }, options); return results; } /** * Parse a selector string and return its AST. * @param {string} selector * @returns {SelectorAST} */ function parse(selector) { return parser.parse(selector); } /** * Query the code AST using the selector string. * @param {external:AST} ast * @param {string} selector * @param {ESQueryOptions} [options] * @returns {external:AST[]} */ function query(ast, selector, options) { return match(ast, parse(selector), options); } query.parse = parse; query.match = match; query.traverse = traverse; query.matches = matches; query.query = query; return query; })));
GoogleCloudPlatform/prometheus-engine
third_party/prometheus_ui/base/web/ui/react-app/node_modules/esquery/dist/esquery.lite.js
JavaScript
apache-2.0
105,133
/* * 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.cassandra.service; import java.net.InetAddress; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import com.google.common.collect.Sets; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.concurrent.Stage; import org.apache.cassandra.concurrent.StageManager; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.db.IMutation; import org.apache.cassandra.db.Keyspace; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.gms.Gossiper; import org.apache.cassandra.locator.AbstractReplicationStrategy; import org.apache.cassandra.locator.TokenMetadata; import org.apache.cassandra.net.MessagingService; import org.apache.cassandra.repair.RepairJobDesc; import org.apache.cassandra.utils.FBUtilities; import static org.junit.Assert.assertEquals; public abstract class AntiEntropyServiceTestAbstract extends SchemaLoader { // keyspace and column family to test against public ActiveRepairService aes; public String keyspaceName; public String cfname; public RepairJobDesc desc; public ColumnFamilyStore store; public InetAddress LOCAL, REMOTE; public Range<Token> local_range; private boolean initialized; public abstract void init(); public abstract List<IMutation> getWriteData(); @Before public void prepare() throws Exception { if (!initialized) { initialized = true; init(); LOCAL = FBUtilities.getBroadcastAddress(); // generate a fake endpoint for which we can spoof receiving/sending trees REMOTE = InetAddress.getByName("127.0.0.2"); store = null; for (ColumnFamilyStore cfs : Keyspace.open(keyspaceName).getColumnFamilyStores()) { if (cfs.name.equals(cfname)) { store = cfs; break; } } assert store != null : "CF not found: " + cfname; } aes = ActiveRepairService.instance; TokenMetadata tmd = StorageService.instance.getTokenMetadata(); tmd.clearUnsafe(); StorageService.instance.setTokens(Collections.singleton(StorageService.getPartitioner().getRandomToken())); tmd.updateNormalToken(StorageService.getPartitioner().getMinimumToken(), REMOTE); assert tmd.isMember(REMOTE); MessagingService.instance().setVersion(REMOTE, MessagingService.current_version); Gossiper.instance.initializeNodeUnsafe(REMOTE, UUID.randomUUID(), 1); local_range = StorageService.instance.getPrimaryRangesForEndpoint(keyspaceName, LOCAL).iterator().next(); desc = new RepairJobDesc(UUID.randomUUID(), UUID.randomUUID(), keyspaceName, cfname, local_range); // Set a fake session corresponding to this fake request ActiveRepairService.instance.submitArtificialRepairSession(desc); } @After public void teardown() throws Exception { flushAES(); } @Test public void testGetNeighborsPlusOne() throws Throwable { // generate rf+1 nodes, and ensure that all nodes are returned Set<InetAddress> expected = addTokens(1 + Keyspace.open(keyspaceName).getReplicationStrategy().getReplicationFactor()); expected.remove(FBUtilities.getBroadcastAddress()); Collection<Range<Token>> ranges = StorageService.instance.getLocalRanges(keyspaceName); Set<InetAddress> neighbors = new HashSet<InetAddress>(); for (Range<Token> range : ranges) { neighbors.addAll(ActiveRepairService.getNeighbors(keyspaceName, range, null, null)); } assertEquals(expected, neighbors); } @Test public void testGetNeighborsTimesTwo() throws Throwable { TokenMetadata tmd = StorageService.instance.getTokenMetadata(); // generate rf*2 nodes, and ensure that only neighbors specified by the ARS are returned addTokens(2 * Keyspace.open(keyspaceName).getReplicationStrategy().getReplicationFactor()); AbstractReplicationStrategy ars = Keyspace.open(keyspaceName).getReplicationStrategy(); Set<InetAddress> expected = new HashSet<InetAddress>(); for (Range<Token> replicaRange : ars.getAddressRanges().get(FBUtilities.getBroadcastAddress())) { expected.addAll(ars.getRangeAddresses(tmd.cloneOnlyTokenMap()).get(replicaRange)); } expected.remove(FBUtilities.getBroadcastAddress()); Collection<Range<Token>> ranges = StorageService.instance.getLocalRanges(keyspaceName); Set<InetAddress> neighbors = new HashSet<InetAddress>(); for (Range<Token> range : ranges) { neighbors.addAll(ActiveRepairService.getNeighbors(keyspaceName, range, null, null)); } assertEquals(expected, neighbors); } @Test public void testGetNeighborsPlusOneInLocalDC() throws Throwable { TokenMetadata tmd = StorageService.instance.getTokenMetadata(); // generate rf+1 nodes, and ensure that all nodes are returned Set<InetAddress> expected = addTokens(1 + Keyspace.open(keyspaceName).getReplicationStrategy().getReplicationFactor()); expected.remove(FBUtilities.getBroadcastAddress()); // remove remote endpoints TokenMetadata.Topology topology = tmd.cloneOnlyTokenMap().getTopology(); HashSet<InetAddress> localEndpoints = Sets.newHashSet(topology.getDatacenterEndpoints().get(DatabaseDescriptor.getLocalDataCenter())); expected = Sets.intersection(expected, localEndpoints); Collection<Range<Token>> ranges = StorageService.instance.getLocalRanges(keyspaceName); Set<InetAddress> neighbors = new HashSet<InetAddress>(); for (Range<Token> range : ranges) { neighbors.addAll(ActiveRepairService.getNeighbors(keyspaceName, range, Arrays.asList(DatabaseDescriptor.getLocalDataCenter()), null)); } assertEquals(expected, neighbors); } @Test public void testGetNeighborsTimesTwoInLocalDC() throws Throwable { TokenMetadata tmd = StorageService.instance.getTokenMetadata(); // generate rf*2 nodes, and ensure that only neighbors specified by the ARS are returned addTokens(2 * Keyspace.open(keyspaceName).getReplicationStrategy().getReplicationFactor()); AbstractReplicationStrategy ars = Keyspace.open(keyspaceName).getReplicationStrategy(); Set<InetAddress> expected = new HashSet<InetAddress>(); for (Range<Token> replicaRange : ars.getAddressRanges().get(FBUtilities.getBroadcastAddress())) { expected.addAll(ars.getRangeAddresses(tmd.cloneOnlyTokenMap()).get(replicaRange)); } expected.remove(FBUtilities.getBroadcastAddress()); // remove remote endpoints TokenMetadata.Topology topology = tmd.cloneOnlyTokenMap().getTopology(); HashSet<InetAddress> localEndpoints = Sets.newHashSet(topology.getDatacenterEndpoints().get(DatabaseDescriptor.getLocalDataCenter())); expected = Sets.intersection(expected, localEndpoints); Collection<Range<Token>> ranges = StorageService.instance.getLocalRanges(keyspaceName); Set<InetAddress> neighbors = new HashSet<InetAddress>(); for (Range<Token> range : ranges) { neighbors.addAll(ActiveRepairService.getNeighbors(keyspaceName, range, Arrays.asList(DatabaseDescriptor.getLocalDataCenter()), null)); } assertEquals(expected, neighbors); } @Test public void testGetNeighborsTimesTwoInSpecifiedHosts() throws Throwable { TokenMetadata tmd = StorageService.instance.getTokenMetadata(); // generate rf*2 nodes, and ensure that only neighbors specified by the hosts are returned addTokens(2 * Keyspace.open(keyspaceName).getReplicationStrategy().getReplicationFactor()); AbstractReplicationStrategy ars = Keyspace.open(keyspaceName).getReplicationStrategy(); List<InetAddress> expected = new ArrayList<>(); for (Range<Token> replicaRange : ars.getAddressRanges().get(FBUtilities.getBroadcastAddress())) { expected.addAll(ars.getRangeAddresses(tmd.cloneOnlyTokenMap()).get(replicaRange)); } expected.remove(FBUtilities.getBroadcastAddress()); Collection<String> hosts = Arrays.asList(FBUtilities.getBroadcastAddress().getCanonicalHostName(),expected.get(0).getCanonicalHostName()); assertEquals(expected.get(0), ActiveRepairService.getNeighbors(keyspaceName, StorageService.instance.getLocalRanges(keyspaceName).iterator().next(), null, hosts).iterator().next()); } @Test(expected = IllegalArgumentException.class) public void testGetNeighborsSpecifiedHostsWithNoLocalHost() throws Throwable { addTokens(2 * Keyspace.open(keyspaceName).getReplicationStrategy().getReplicationFactor()); //Dont give local endpoint Collection<String> hosts = Arrays.asList("127.0.0.3"); ActiveRepairService.getNeighbors(keyspaceName, StorageService.instance.getLocalRanges(keyspaceName).iterator().next(), null, hosts); } Set<InetAddress> addTokens(int max) throws Throwable { TokenMetadata tmd = StorageService.instance.getTokenMetadata(); Set<InetAddress> endpoints = new HashSet<InetAddress>(); for (int i = 1; i <= max; i++) { InetAddress endpoint = InetAddress.getByName("127.0.0." + i); tmd.updateNormalToken(StorageService.getPartitioner().getRandomToken(), endpoint); endpoints.add(endpoint); } return endpoints; } void flushAES() throws Exception { final ExecutorService stage = StageManager.getStage(Stage.ANTI_ENTROPY); final Callable noop = new Callable<Object>() { public Boolean call() { return true; } }; // send two tasks through the stage: one to follow existing tasks and a second to follow tasks created by // those existing tasks: tasks won't recursively create more tasks stage.submit(noop).get(5000, TimeUnit.MILLISECONDS); stage.submit(noop).get(5000, TimeUnit.MILLISECONDS); } }
PaytmLabs/cassandra
test/unit/org/apache/cassandra/service/AntiEntropyServiceTestAbstract.java
Java
apache-2.0
11,389
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * The production x ^= y is the same as x = x ^ y * * @path ch11/11.13/11.13.2/S11.13.2_A4.10_T2.2.js * @description Type(x) is different from Type(y) and both types vary between Number (primitive or object) and String (primitive and object) */ //CHECK#1 x = "1"; x ^= 1; if (x !== 0) { $ERROR('#1: x = "1"; x ^= 1; x === 0. Actual: ' + (x)); } //CHECK#2 x = 1; x ^= "1"; if (x !== 0) { $ERROR('#2: x = 1; x ^= "1"; x === 0. Actual: ' + (x)); } //CHECK#3 x = new String("1"); x ^= 1; if (x !== 0) { $ERROR('#3: x = new String("1"); x ^= 1; x === 0. Actual: ' + (x)); } //CHECK#4 x = 1; x ^= new String("1"); if (x !== 0) { $ERROR('#4: x = 1; x ^= new String("1"); x === 0. Actual: ' + (x)); } //CHECK#5 x = "1"; x ^= new Number(1); if (x !== 0) { $ERROR('#5: x = "1"; x ^= new Number(1); x === 0. Actual: ' + (x)); } //CHECK#6 x = new Number(1); x ^= "1"; if (x !== 0) { $ERROR('#6: x = new Number(1); x ^= "1"; x === 0. Actual: ' + (x)); } //CHECK#7 x = new String("1"); x ^= new Number(1); if (x !== 0) { $ERROR('#7: x = new String("1"); x ^= new Number(1); x === 0. Actual: ' + (x)); } //CHECK#8 x = new Number(1); x ^= new String("1"); if (x !== 0) { $ERROR('#8: x = new Number(1); x ^= new String("1"); x === 0. Actual: ' + (x)); } //CHECK#9 x = "x"; x ^= 1; if (x !== 1) { $ERROR('#9: x = "x"; x ^= 1; x === 1. Actual: ' + (x)); } //CHECK#10 x = 1; x ^= "x"; if (x !== 1) { $ERROR('#10: x = 1; x ^= "x"; x === 1. Actual: ' + (x)); }
hippich/typescript
tests/Fidelity/test262/suite/ch11/11.13/11.13.2/S11.13.2_A4.10_T2.2.js
JavaScript
apache-2.0
1,611
/** * Copyright 2011, Big Switch Networks, Inc. * Originally created by David Erickson, Stanford University * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. **/ package net.floodlightcontroller.topology.web; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.floodlightcontroller.core.internal.IOFSwitchService; import net.floodlightcontroller.topology.ITopologyService; import org.projectfloodlight.openflow.types.DatapathId; import org.restlet.data.Form; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; /** * Returns a JSON map of <ClusterId, List<SwitchDpids>> */ public class SwitchClustersResource extends ServerResource { @Get("json") public Map<String, List<String>> retrieve() { IOFSwitchService switchService = (IOFSwitchService) getContext().getAttributes(). get(IOFSwitchService.class.getCanonicalName()); ITopologyService topologyService = (ITopologyService) getContext().getAttributes(). get(ITopologyService.class.getCanonicalName()); Form form = getQuery(); String queryType = form.getFirstValue("type", true); boolean openflowDomain = true; if (queryType != null && "l2".equals(queryType)) { openflowDomain = false; } Map<String, List<String>> switchClusterMap = new HashMap<String, List<String>>(); for (DatapathId dpid: switchService.getAllSwitchDpids()) { DatapathId clusterDpid = (openflowDomain ? topologyService.getOpenflowDomainId(dpid) :topologyService.getOpenflowDomainId(dpid)); List<String> switchesInCluster = switchClusterMap.get(clusterDpid.toString()); if (switchesInCluster != null) { switchesInCluster.add(dpid.toString()); } else { List<String> l = new ArrayList<String>(); l.add(dpid.toString()); switchClusterMap.put(clusterDpid.toString(), l); } } return switchClusterMap; } }
alberthitanaya/floodlight-dnscollector
src/main/java/net/floodlightcontroller/topology/web/SwitchClustersResource.java
Java
apache-2.0
2,712
/* * 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.tinkerpop.gremlin.process.traversal.step.sideEffect; import org.apache.tinkerpop.gremlin.LoadGraphWith; import org.apache.tinkerpop.gremlin.process.AbstractGremlinProcessTest; import org.apache.tinkerpop.gremlin.process.GremlinProcessRunner; import org.apache.tinkerpop.gremlin.process.IgnoreEngine; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.TraversalEngine; import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategy; import org.apache.tinkerpop.gremlin.process.traversal.step.map.EdgeVertexStep; import org.apache.tinkerpop.gremlin.process.traversal.strategy.optimization.IdentityRemovalStrategy; import org.apache.tinkerpop.gremlin.process.traversal.strategy.optimization.IncidentToAdjacentStrategy; import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalExplanation; import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper; import org.javatuples.Pair; import org.junit.Test; import org.junit.runner.RunWith; import static org.apache.tinkerpop.gremlin.LoadGraphWith.GraphData.MODERN; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ @RunWith(GremlinProcessRunner.class) public abstract class ExplainTest extends AbstractGremlinProcessTest { public abstract TraversalExplanation get_g_V_outE_identity_inV_explain(); @Test @LoadGraphWith(MODERN) @IgnoreEngine(TraversalEngine.Type.COMPUTER) public void g_V_outE_identity_inV_explain() { final TraversalExplanation explanation = get_g_V_outE_identity_inV_explain(); if (explanation.getStrategyTraversals().stream().map(Pair::getValue0).filter(s -> s instanceof IdentityRemovalStrategy || s instanceof IncidentToAdjacentStrategy).count() == 2) { printTraversalForm(explanation.getOriginalTraversal()); boolean beforeIncident = true; boolean beforeIdentity = true; for (final Pair<TraversalStrategy, Traversal.Admin<?, ?>> pair : explanation.getStrategyTraversals()) { if (pair.getValue0().getClass().equals(IncidentToAdjacentStrategy.class)) beforeIncident = false; if (pair.getValue0().getClass().equals(IdentityRemovalStrategy.class)) beforeIdentity = false; if (beforeIdentity) assertEquals(1, TraversalHelper.getStepsOfClass(IdentityStep.class, pair.getValue1()).size()); if (beforeIncident) assertEquals(1, TraversalHelper.getStepsOfClass(EdgeVertexStep.class, pair.getValue1()).size()); if (!beforeIdentity) assertEquals(0, TraversalHelper.getStepsOfClass(IdentityStep.class, pair.getValue1()).size()); if (!beforeIncident) assertEquals(0, TraversalHelper.getStepsOfClass(EdgeVertexStep.class, pair.getValue1()).size()); } assertFalse(beforeIncident); } } public static class Traversals extends ExplainTest { public TraversalExplanation get_g_V_outE_identity_inV_explain() { return g.V().outE().identity().inV().explain(); } } }
artem-aliev/tinkerpop
gremlin-test/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/ExplainTest.java
Java
apache-2.0
4,122
class Minitube < Cask version 'latest' sha256 :no_check url 'http://flavio.tordini.org/files/minitube/minitube.dmg' appcast 'http://flavio.tordini.org/minitube-ws/appcast.xml' homepage 'http://flavio.tordini.org/minitube' link 'Minitube.app' end
NorthIsUp/homebrew-cask
Casks/minitube.rb
Ruby
bsd-2-clause
260
cask "lynx" do version "7.5.2.0" sha256 :no_check url "https://download.saharasupport.com/lynx#{version.major}/production/macx/Lynx#{version.major}-install.dmg", verified: "download.saharasupport.com" name "LYNX Whiteboard by Clevertouch" desc "Cross platform presentation and productivity app" homepage "https://www.lynxcloud.app/" livecheck do url "https://downloads.saharasupport.com/lynx#{version.major}/production/macx/version.txt" regex(/(\d+(?:[._-]\d+)+)/) end auto_updates true pkg "Lynx#{version.major}.pkg" uninstall pkgutil: [ "com.clevertouch.lynx", "uk.co.cleverproducts.lynx", ] end
nrlquaker/homebrew-cask
Casks/lynx.rb
Ruby
bsd-2-clause
649
// 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. #include "chromeos/network/onc/onc_certificate_importer_impl.h" #include <cert.h> #include <certdb.h> #include <keyhi.h> #include <pk11pub.h> #include <string> #include "base/bind.h" #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/values.h" #include "chromeos/network/onc/onc_test_utils.h" #include "components/onc/onc_constants.h" #include "crypto/nss_util.h" #include "crypto/nss_util_internal.h" #include "net/base/crypto_module.h" #include "net/cert/cert_type.h" #include "net/cert/nss_cert_database_chromeos.h" #include "net/cert/x509_certificate.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { namespace onc { namespace { #if defined(USE_NSS) // In NSS 3.13, CERTDB_VALID_PEER was renamed CERTDB_TERMINAL_RECORD. So we use // the new name of the macro. #if !defined(CERTDB_TERMINAL_RECORD) #define CERTDB_TERMINAL_RECORD CERTDB_VALID_PEER #endif net::CertType GetCertType(net::X509Certificate::OSCertHandle cert) { CERTCertTrust trust = {0}; CERT_GetCertTrust(cert, &trust); unsigned all_flags = trust.sslFlags | trust.emailFlags | trust.objectSigningFlags; if (cert->nickname && (all_flags & CERTDB_USER)) return net::USER_CERT; if ((all_flags & CERTDB_VALID_CA) || CERT_IsCACert(cert, NULL)) return net::CA_CERT; // TODO(mattm): http://crbug.com/128633. if (trust.sslFlags & CERTDB_TERMINAL_RECORD) return net::SERVER_CERT; return net::OTHER_CERT; } #else net::CertType GetCertType(net::X509Certificate::OSCertHandle cert) { NOTIMPLEMENTED(); return net::OTHER_CERT; } #endif // USE_NSS } // namespace class ONCCertificateImporterImplTest : public testing::Test { public: ONCCertificateImporterImplTest() : user_("username_hash"), private_user_("private_user_hash") {} virtual void SetUp() { ASSERT_TRUE(user_.constructed_successfully()); ASSERT_TRUE(private_user_.constructed_successfully()); // By default test user will have the same public and private slot. // Unfortunatelly, ONC importer should care about which slot certificates // get imported to. To work around this, we create another NSS user whose // public slot will act as the private slot. // TODO(tbarzic): See if there's a better way to achieve this. test_nssdb_.reset(new net::NSSCertDatabaseChromeOS( crypto::GetPublicSlotForChromeOSUser(user_.username_hash()), crypto::GetPublicSlotForChromeOSUser(private_user_.username_hash()))); // Test db should be empty at start of test. EXPECT_TRUE(ListCertsInPublicSlot().empty()); EXPECT_TRUE(ListCertsInPrivateSlot().empty()); } virtual ~ONCCertificateImporterImplTest() {} protected: void AddCertificatesFromFile(std::string filename, bool expected_success) { scoped_ptr<base::DictionaryValue> onc = test_utils::ReadTestDictionary(filename); scoped_ptr<base::Value> certificates_value; base::ListValue* certificates = NULL; onc->RemoveWithoutPathExpansion(::onc::toplevel_config::kCertificates, &certificates_value); certificates_value.release()->GetAsList(&certificates); onc_certificates_.reset(certificates); web_trust_certificates_.clear(); imported_server_and_ca_certs_.clear(); CertificateImporterImpl importer(test_nssdb_.get()); EXPECT_EQ( expected_success, importer.ParseAndStoreCertificates(true, // allow web trust *certificates, &web_trust_certificates_, &imported_server_and_ca_certs_)); public_list_ = ListCertsInPublicSlot(); private_list_ = ListCertsInPrivateSlot(); } void AddCertificateFromFile(std::string filename, net::CertType expected_type, std::string* guid) { std::string guid_temporary; if (!guid) guid = &guid_temporary; AddCertificatesFromFile(filename, true); ASSERT_EQ(1ul, public_list_.size() + private_list_.size()); if (!public_list_.empty()) EXPECT_EQ(expected_type, GetCertType(public_list_[0]->os_cert_handle())); if (!private_list_.empty()) EXPECT_EQ(expected_type, GetCertType(private_list_[0]->os_cert_handle())); base::DictionaryValue* certificate = NULL; onc_certificates_->GetDictionary(0, &certificate); certificate->GetStringWithoutPathExpansion(::onc::certificate::kGUID, guid); if (expected_type == net::SERVER_CERT || expected_type == net::CA_CERT) { EXPECT_EQ(1u, imported_server_and_ca_certs_.size()); EXPECT_TRUE(imported_server_and_ca_certs_[*guid]->Equals( public_list_[0])); } else { // net::USER_CERT EXPECT_TRUE(imported_server_and_ca_certs_.empty()); } } scoped_ptr<net::NSSCertDatabaseChromeOS> test_nssdb_; scoped_ptr<base::ListValue> onc_certificates_; // List of certs in the nssdb's public slot. net::CertificateList public_list_; // List of certs in the nssdb's "private" slot. net::CertificateList private_list_; net::CertificateList web_trust_certificates_; CertificateImporterImpl::CertsByGUID imported_server_and_ca_certs_; private: net::CertificateList ListCertsInPublicSlot() { return ListCertsInSlot(test_nssdb_->GetPublicSlot().get()); } net::CertificateList ListCertsInPrivateSlot() { return ListCertsInSlot(test_nssdb_->GetPrivateSlot().get()); } net::CertificateList ListCertsInSlot(PK11SlotInfo* slot) { net::CertificateList result; CERTCertList* cert_list = PK11_ListCertsInSlot(slot); for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list); !CERT_LIST_END(node, cert_list); node = CERT_LIST_NEXT(node)) { result.push_back(net::X509Certificate::CreateFromHandle( node->cert, net::X509Certificate::OSCertHandles())); } CERT_DestroyCertList(cert_list); // Sort the result so that test comparisons can be deterministic. std::sort(result.begin(), result.end(), net::X509Certificate::LessThan()); return result; } crypto::ScopedTestNSSChromeOSUser user_; crypto::ScopedTestNSSChromeOSUser private_user_; }; TEST_F(ONCCertificateImporterImplTest, MultipleCertificates) { AddCertificatesFromFile("managed_toplevel2.onc", true); EXPECT_EQ(onc_certificates_->GetSize(), public_list_.size()); EXPECT_TRUE(private_list_.empty()); EXPECT_EQ(2ul, imported_server_and_ca_certs_.size()); } TEST_F(ONCCertificateImporterImplTest, MultipleCertificatesWithFailures) { AddCertificatesFromFile("toplevel_partially_invalid.onc", false); EXPECT_EQ(3ul, onc_certificates_->GetSize()); EXPECT_EQ(1ul, private_list_.size()); EXPECT_TRUE(public_list_.empty()); EXPECT_TRUE(imported_server_and_ca_certs_.empty()); } TEST_F(ONCCertificateImporterImplTest, AddClientCertificate) { std::string guid; AddCertificateFromFile("certificate-client.onc", net::USER_CERT, &guid); EXPECT_TRUE(web_trust_certificates_.empty()); EXPECT_EQ(1ul, private_list_.size()); EXPECT_TRUE(public_list_.empty()); SECKEYPrivateKeyList* privkey_list = PK11_ListPrivKeysInSlot(test_nssdb_->GetPrivateSlot().get(), NULL, NULL); EXPECT_TRUE(privkey_list); if (privkey_list) { SECKEYPrivateKeyListNode* node = PRIVKEY_LIST_HEAD(privkey_list); int count = 0; while (!PRIVKEY_LIST_END(node, privkey_list)) { char* name = PK11_GetPrivateKeyNickname(node->key); EXPECT_STREQ(guid.c_str(), name); PORT_Free(name); count++; node = PRIVKEY_LIST_NEXT(node); } EXPECT_EQ(1, count); SECKEY_DestroyPrivateKeyList(privkey_list); } SECKEYPublicKeyList* pubkey_list = PK11_ListPublicKeysInSlot(test_nssdb_->GetPrivateSlot().get(), NULL); EXPECT_TRUE(pubkey_list); if (pubkey_list) { SECKEYPublicKeyListNode* node = PUBKEY_LIST_HEAD(pubkey_list); int count = 0; while (!PUBKEY_LIST_END(node, pubkey_list)) { count++; node = PUBKEY_LIST_NEXT(node); } EXPECT_EQ(1, count); SECKEY_DestroyPublicKeyList(pubkey_list); } } TEST_F(ONCCertificateImporterImplTest, AddServerCertificateWithWebTrust) { AddCertificateFromFile("certificate-server.onc", net::SERVER_CERT, NULL); SECKEYPrivateKeyList* privkey_list = PK11_ListPrivKeysInSlot(test_nssdb_->GetPrivateSlot().get(), NULL, NULL); EXPECT_FALSE(privkey_list); SECKEYPublicKeyList* pubkey_list = PK11_ListPublicKeysInSlot(test_nssdb_->GetPrivateSlot().get(), NULL); EXPECT_FALSE(pubkey_list); ASSERT_EQ(1u, web_trust_certificates_.size()); ASSERT_EQ(1u, public_list_.size()); EXPECT_TRUE(private_list_.empty()); EXPECT_TRUE(CERT_CompareCerts(public_list_[0]->os_cert_handle(), web_trust_certificates_[0]->os_cert_handle())); } TEST_F(ONCCertificateImporterImplTest, AddWebAuthorityCertificateWithWebTrust) { AddCertificateFromFile("certificate-web-authority.onc", net::CA_CERT, NULL); SECKEYPrivateKeyList* privkey_list = PK11_ListPrivKeysInSlot(test_nssdb_->GetPrivateSlot().get(), NULL, NULL); EXPECT_FALSE(privkey_list); SECKEYPublicKeyList* pubkey_list = PK11_ListPublicKeysInSlot(test_nssdb_->GetPrivateSlot().get(), NULL); EXPECT_FALSE(pubkey_list); ASSERT_EQ(1u, web_trust_certificates_.size()); ASSERT_EQ(1u, public_list_.size()); EXPECT_TRUE(private_list_.empty()); EXPECT_TRUE(CERT_CompareCerts(public_list_[0]->os_cert_handle(), web_trust_certificates_[0]->os_cert_handle())); } TEST_F(ONCCertificateImporterImplTest, AddAuthorityCertificateWithoutWebTrust) { AddCertificateFromFile("certificate-authority.onc", net::CA_CERT, NULL); EXPECT_TRUE(web_trust_certificates_.empty()); SECKEYPrivateKeyList* privkey_list = PK11_ListPrivKeysInSlot(test_nssdb_->GetPrivateSlot().get(), NULL, NULL); EXPECT_FALSE(privkey_list); SECKEYPublicKeyList* pubkey_list = PK11_ListPublicKeysInSlot(test_nssdb_->GetPrivateSlot().get(), NULL); EXPECT_FALSE(pubkey_list); } struct CertParam { CertParam(net::CertType certificate_type, const char* original_filename, const char* update_filename) : cert_type(certificate_type), original_file(original_filename), update_file(update_filename) {} net::CertType cert_type; const char* original_file; const char* update_file; }; class ONCCertificateImporterImplTestWithParam : public ONCCertificateImporterImplTest, public testing::WithParamInterface<CertParam> { }; TEST_P(ONCCertificateImporterImplTestWithParam, UpdateCertificate) { // First we import a certificate. { SCOPED_TRACE("Import original certificate"); AddCertificateFromFile(GetParam().original_file, GetParam().cert_type, NULL); } // Now we import the same certificate with a different GUID. In case of a // client cert, the cert should be retrievable via the new GUID. { SCOPED_TRACE("Import updated certificate"); AddCertificateFromFile(GetParam().update_file, GetParam().cert_type, NULL); } } TEST_P(ONCCertificateImporterImplTestWithParam, ReimportCertificate) { // Verify that reimporting a client certificate works. for (int i = 0; i < 2; ++i) { SCOPED_TRACE("Import certificate, iteration " + base::IntToString(i)); AddCertificateFromFile(GetParam().original_file, GetParam().cert_type, NULL); } } INSTANTIATE_TEST_CASE_P( ONCCertificateImporterImplTestWithParam, ONCCertificateImporterImplTestWithParam, ::testing::Values( CertParam(net::USER_CERT, "certificate-client.onc", "certificate-client-update.onc"), CertParam(net::SERVER_CERT, "certificate-server.onc", "certificate-server-update.onc"), CertParam(net::CA_CERT, "certificate-web-authority.onc", "certificate-web-authority-update.onc"))); } // namespace onc } // namespace chromeos
boundarydevices/android_external_chromium_org
chromeos/network/onc/onc_certificate_importer_impl_unittest.cc
C++
bsd-3-clause
12,260
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.modules.i18nmanager; import android.content.Context; import android.content.SharedPreferences; import androidx.core.text.TextUtilsCompat; import androidx.core.view.ViewCompat; import java.util.Locale; public class I18nUtil { private static I18nUtil sharedI18nUtilInstance = null; private static final String SHARED_PREFS_NAME = "com.facebook.react.modules.i18nmanager.I18nUtil"; private static final String KEY_FOR_PREFS_ALLOWRTL = "RCTI18nUtil_allowRTL"; private static final String KEY_FOR_PREFS_FORCERTL = "RCTI18nUtil_forceRTL"; private static final String KEY_FOR_PERFS_MAKE_RTL_FLIP_LEFT_AND_RIGHT_STYLES = "RCTI18nUtil_makeRTLFlipLeftAndRightStyles"; private I18nUtil() { // Exists only to defeat instantiation. } public static I18nUtil getInstance() { if (sharedI18nUtilInstance == null) { sharedI18nUtilInstance = new I18nUtil(); } return sharedI18nUtilInstance; } /** * Check if the device is currently running on an RTL locale. This only happens when the app: * * <ul> * <li>is forcing RTL layout, regardless of the active language (for development purpose) * <li>allows RTL layout when using RTL locale * </ul> */ public boolean isRTL(Context context) { if (isRTLForced(context)) { return true; } return isRTLAllowed(context) && isDevicePreferredLanguageRTL(); } /** * Should be used very early during app start up Before the bridge is initialized * * @return whether the app allows RTL layout, default is true */ private boolean isRTLAllowed(Context context) { return isPrefSet(context, KEY_FOR_PREFS_ALLOWRTL, true); } public void allowRTL(Context context, boolean allowRTL) { setPref(context, KEY_FOR_PREFS_ALLOWRTL, allowRTL); } public boolean doLeftAndRightSwapInRTL(Context context) { return isPrefSet(context, KEY_FOR_PERFS_MAKE_RTL_FLIP_LEFT_AND_RIGHT_STYLES, true); } public void swapLeftAndRightInRTL(Context context, boolean flip) { setPref(context, KEY_FOR_PERFS_MAKE_RTL_FLIP_LEFT_AND_RIGHT_STYLES, flip); } /** Could be used to test RTL layout with English Used for development and testing purpose */ private boolean isRTLForced(Context context) { return isPrefSet(context, KEY_FOR_PREFS_FORCERTL, false); } public void forceRTL(Context context, boolean forceRTL) { setPref(context, KEY_FOR_PREFS_FORCERTL, forceRTL); } // Check if the current device language is RTL private boolean isDevicePreferredLanguageRTL() { final int directionality = TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()); return directionality == ViewCompat.LAYOUT_DIRECTION_RTL; } private boolean isPrefSet(Context context, String key, boolean defaultValue) { SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE); return prefs.getBoolean(key, defaultValue); } private void setPref(Context context, String key, boolean value) { SharedPreferences.Editor editor = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE).edit(); editor.putBoolean(key, value); editor.apply(); } }
exponent/exponent
android/ReactAndroid/src/main/java/com/facebook/react/modules/i18nmanager/I18nUtil.java
Java
bsd-3-clause
3,388
cdb.admin.overlays.LayerSelector = cdb.core.View.extend({ tagName: 'div', className: 'cartodb-layer-selector-box', events: { "click": '_openDropdown', "dblclick": 'killEvent', "mousedown": 'killEvent' }, default_options: { timeout: 0, msg: '' }, initialize: function() { _.bindAll(this, "_close"); this.map = this.options.mapView.map; this.mapView = this.options.mapView; this.mapView.bind('click zoomstart drag', function() { this.dropdown && this.dropdown.hide() }, this); this.add_related_model(this.mapView); this.layers = []; this.map = this.options.map; _.defaults(this.options, this.default_options); this._setupModels(); }, _killEvent: function(e) { e && e.preventDefault(); e && e.stopPropagation(); }, // Setup the internal and custom model _setupModels: function() { this.model = this.options.model; this.model.on("change:display", this._onChangeDisplay, this); this.model.on("change:y", this._onChangeY, this); this.model.on("change:x", this._onChangeX, this); this.model.on("destroy", function() { this.$el.remove(); }, this); }, _onChangeX: function() { var x = this.model.get("x"); this.$el.animate({ right: x }, 150); this.trigger("change_x", this); //this.model.save(); }, _onChangeY: function() { var y = this.model.get("y"); this.$el.animate({ top: y }, 150); this.trigger("change_y", this); //this.model.save(); }, _onChangeDisplay: function() { var display = this.model.get("display"); if (display) { this.show(); } else { this.hide(); } }, _checkZoom: function() { var zoom = this.map.get('zoom'); this.$('.zoom_in')[ zoom < this.map.get('maxZoom') ? 'removeClass' : 'addClass' ]('disabled') this.$('.zoom_out')[ zoom > this.map.get('minZoom') ? 'removeClass' : 'addClass' ]('disabled') }, zoom_in: function(ev) { if (this.map.get("maxZoom") > this.map.getZoom()) { this.map.setZoom(this.map.getZoom() + 1); } ev.preventDefault(); ev.stopPropagation(); }, zoom_out: function(ev) { if (this.map.get("minZoom") < this.map.getZoom()) { this.map.setZoom(this.map.getZoom() - 1); } ev.preventDefault(); ev.stopPropagation(); }, _onMouseDown: function() { }, _onMouseEnterText: function() { }, _onMouseLeaveText: function() { }, _onMouseEnter: function() { }, _onMouseLeave: function() { }, show: function() { this.$el.fadeIn(250); }, hide: function(callback) { var self = this; callback && callback(); this.$el.fadeOut(250); }, _close: function(e) { this._killEvent(e); var self = this; this.hide(function() { self.trigger("remove", self); }); }, _toggleFullScreen: function(ev) { ev.stopPropagation(); ev.preventDefault(); var doc = window.document; var docEl = doc.documentElement; if (this.options.doc) { // we use a custom element docEl = $(this.options.doc)[0]; } var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen; var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen; var mapView = this.options.mapView; if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement) { requestFullScreen.call(docEl); if (mapView) { if (this.model.get("allowWheelOnFullscreen")) { mapView.options.map.set("scrollwheel", true); } } } else { cancelFullScreen.call(doc); } }, _getLayers: function() { var self = this; this.layers = []; _.each(this.mapView.map.layers.models, function(layer) { if (layer.get("type") == 'layergroup' || layer.get('type') === 'namedmap') { var layerGroupView = self.mapView.getLayerByCid(layer.cid); for (var i = 0 ; i < layerGroupView.getLayerCount(); ++i) { var l = layerGroupView.getLayer(i); var m = new cdb.core.Model(l); m.set('order', i); m.set('type', 'layergroup'); m.set('visible', !layerGroupView.getSubLayer(i).get('hidden')); m.bind('change:visible', function(model) { this.trigger("change:visible", model.get('visible'), model.get('order'), model); model.save(); }, self); if(self.options.layer_names) { m.set('layer_name', self.options.layer_names[i]); } else { m.set('layer_name', l.options.layer_name); } var layerView = self._createLayer('LayerViewFromLayerGroup', { model: m, layerView: layerGroupView, layerIndex: i }); layerView.bind('switchChanged', self._setCount, self); self.layers.push(layerView); } } else if (layer.get("type") === "CartoDB" || layer.get('type') === 'torque') { var layerView = self._createLayer('LayerView', { model: layer }); layerView.bind('switchChanged', self._setCount, self); self.layers.push(layerView); layerView.model.bind('change:visible', function(model) { this.trigger("change:visible", model.get('visible'), model.get('order'), model); model.save(); }, self); } }); }, _createLayer: function(_class, opts) { var layerView = new cdb.geo.ui[_class](opts); this.$("ul").append(layerView.render().el); this.addView(layerView); return layerView; }, _setCount: function() { var count = 0; for (var i = 0, l = this.layers.length; i < l; ++i) { var lyr = this.layers[i]; if (lyr.model.get('visible')) { count++; } } this.$('.count').text(count); this.trigger("switchChanged", this); }, _openDropdown: function() { this.dropdown.open(); }, render: function() { var self = this; this.$el.html(this.options.template(this.options)); this.$el.css({ right: this.model.get("x"), top: this.model.get("y") }); this.dropdown = new cdb.ui.common.Dropdown({ className:"cartodb-dropdown border", template: this.options.dropdown_template, target: this.$el.find("a"), speedIn: 300, speedOut: 200, position: "position", tick: "right", vertical_position: "down", horizontal_position: "right", vertical_offset: 7, horizontal_offset: 13 }); if (cdb.god) cdb.god.bind("closeDialogs", this.dropdown.hide, this.dropdown); this.$el.append(this.dropdown.render().el); this._getLayers(); this._setCount(); return this; } });
nyimbi/cartodb
lib/assets/javascripts/cartodb/table/overlays/layer_selector.js
JavaScript
bsd-3-clause
6,825
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; const React = require('react'); const ReactDOM = require('react-dom'); describe('ReactMount', () => { it('should destroy a react root upon request', () => { const mainContainerDiv = document.createElement('div'); document.body.appendChild(mainContainerDiv); const instanceOne = <div className="firstReactDiv" />; const firstRootDiv = document.createElement('div'); mainContainerDiv.appendChild(firstRootDiv); ReactDOM.render(instanceOne, firstRootDiv); const instanceTwo = <div className="secondReactDiv" />; const secondRootDiv = document.createElement('div'); mainContainerDiv.appendChild(secondRootDiv); ReactDOM.render(instanceTwo, secondRootDiv); // Test that two react roots are rendered in isolation expect(firstRootDiv.firstChild.className).toBe('firstReactDiv'); expect(secondRootDiv.firstChild.className).toBe('secondReactDiv'); // Test that after unmounting each, they are no longer in the document. ReactDOM.unmountComponentAtNode(firstRootDiv); expect(firstRootDiv.firstChild).toBeNull(); ReactDOM.unmountComponentAtNode(secondRootDiv); expect(secondRootDiv.firstChild).toBeNull(); }); it('should warn when unmounting a non-container root node', () => { const mainContainerDiv = document.createElement('div'); const component = ( <div> <div /> </div> ); ReactDOM.render(component, mainContainerDiv); // Test that unmounting at a root node gives a helpful warning const rootDiv = mainContainerDiv.firstChild; expect(() => ReactDOM.unmountComponentAtNode(rootDiv)).toWarnDev( "Warning: unmountComponentAtNode(): The node you're attempting to " + 'unmount was rendered by React and is not a top-level container. You ' + 'may have accidentally passed in a React root node instead of its ' + 'container.', {withoutStack: true}, ); }); it('should warn when unmounting a non-container, non-root node', () => { const mainContainerDiv = document.createElement('div'); const component = ( <div> <div> <div /> </div> </div> ); ReactDOM.render(component, mainContainerDiv); // Test that unmounting at a non-root node gives a different warning const nonRootDiv = mainContainerDiv.firstChild.firstChild; expect(() => ReactDOM.unmountComponentAtNode(nonRootDiv)).toWarnDev( "Warning: unmountComponentAtNode(): The node you're attempting to " + 'unmount was rendered by React and is not a top-level container. ' + 'Instead, have the parent component update its state and rerender in ' + 'order to remove this component.', {withoutStack: true}, ); }); });
jdlehman/react
packages/react-dom/src/__tests__/ReactMountDestruction-test.js
JavaScript
mit
2,971
//------------------------------------------------------------------------------ // <copyright file="XmlReservedNS.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml { /// <summary> /// This class defines a set of common XML namespaces for sharing across multiple source files. /// </summary> internal static class XmlReservedNs { internal const string NsXml = "http://www.w3.org/XML/1998/namespace"; internal const string NsXmlNs = "http://www.w3.org/2000/xmlns/"; #if !SILVERLIGHT // These strings are not needed in Silverlight internal const string NsDataType = "urn:schemas-microsoft-com:datatypes"; internal const string NsDataTypeAlias = "uuid:C2F41010-65B3-11D1-A29F-00AA00C14882"; internal const string NsDataTypeOld = "urn:uuid:C2F41010-65B3-11D1-A29F-00AA00C14882/"; internal const string NsMsxsl = "urn:schemas-microsoft-com:xslt"; internal const string NsXdr = "urn:schemas-microsoft-com:xml-data"; internal const string NsXslDebug = "urn:schemas-microsoft-com:xslt-debug"; internal const string NsXdrAlias = "uuid:BDC6E3F0-6DA3-11D1-A2A3-00AA00C14882"; internal const string NsWdXsl = "http://www.w3.org/TR/WD-xsl"; internal const string NsXs = "http://www.w3.org/2001/XMLSchema"; internal const string NsXsd = "http://www.w3.org/2001/XMLSchema-datatypes"; internal const string NsXsi = "http://www.w3.org/2001/XMLSchema-instance"; internal const string NsXslt = "http://www.w3.org/1999/XSL/Transform"; internal const string NsExsltCommon = "http://exslt.org/common"; internal const string NsExsltDates = "http://exslt.org/dates-and-times"; internal const string NsExsltMath = "http://exslt.org/math"; internal const string NsExsltRegExps = "http://exslt.org/regular-expressions"; internal const string NsExsltSets = "http://exslt.org/sets"; internal const string NsExsltStrings = "http://exslt.org/strings"; internal const string NsXQueryFunc = "http://www.w3.org/2003/11/xpath-functions"; internal const string NsXQueryDataType = "http://www.w3.org/2003/11/xpath-datatypes"; internal const string NsCollationBase = "http://collations.microsoft.com"; internal const string NsCollCodePoint = "http://www.w3.org/2004/10/xpath-functions/collation/codepoint"; internal const string NsXsltInternal = "http://schemas.microsoft.com/framework/2003/xml/xslt/internal"; #endif }; }
sekcheong/referencesource
System.Xml/System/Xml/XmlReservedNs.cs
C#
mit
2,890
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ReflectiveInjector, ɵglobal as global} from '@angular/core'; import {ApplicationRef, ApplicationRef_} from '@angular/core/src/application_ref'; import {SpyObject} from '@angular/core/testing/src/testing_internal'; export class SpyApplicationRef extends SpyObject { constructor() { super(ApplicationRef_); } } export class SpyComponentRef extends SpyObject { injector: any /** TODO #9100 */; constructor() { super(); this.injector = ReflectiveInjector.resolveAndCreate( [{provide: ApplicationRef, useClass: SpyApplicationRef}]); } } export function callNgProfilerTimeChangeDetection(config?: any /** TODO #9100 */): void { (<any>global).ng.profiler.timeChangeDetection(config); }
souvikbasu/angular
packages/platform-browser/test/browser/tools/spies.ts
TypeScript
mit
921
// This code is in the public domain -- Ignacio Castaño <castano@gmail.com> #include "Debug.h" #include "Array.inl" #include "StrLib.h" // StringBuilder #include "StdStream.h" // fileOpen #include <stdlib.h> // Extern #if NV_OS_WIN32 //&& NV_CC_MSVC # define WIN32_LEAN_AND_MEAN # define VC_EXTRALEAN # include <windows.h> # include <direct.h> # if NV_CC_MSVC # include <crtdbg.h> # if _MSC_VER < 1300 # define DECLSPEC_DEPRECATED // VC6: change this path to your Platform SDK headers # include <dbghelp.h> // must be XP version of file // include "M:\\dev7\\vs\\devtools\\common\\win32sdk\\include\\dbghelp.h" # else // VC7: ships with updated headers # include <dbghelp.h> # endif # endif # pragma comment(lib,"dbghelp.lib") #endif #if NV_OS_XBOX # include <Xtl.h> # ifdef _DEBUG # include <xbdm.h> # endif //_DEBUG #endif //NV_OS_XBOX #if !NV_OS_WIN32 && defined(HAVE_SIGNAL_H) # include <signal.h> #endif #if NV_OS_UNIX # include <unistd.h> // getpid #endif #if NV_OS_LINUX && defined(HAVE_EXECINFO_H) # include <execinfo.h> // backtrace # if NV_CC_GNUC // defined(HAVE_CXXABI_H) # include <cxxabi.h> # endif #endif #if NV_OS_DARWIN || NV_OS_FREEBSD || NV_OS_OPENBSD # include <sys/types.h> # include <sys/param.h> # include <sys/sysctl.h> // sysctl # if !defined(NV_OS_OPENBSD) # include <sys/ucontext.h> # endif # if defined(HAVE_EXECINFO_H) // only after OSX 10.5 # include <execinfo.h> // backtrace # if NV_CC_GNUC // defined(HAVE_CXXABI_H) # include <cxxabi.h> # endif # endif #endif #if NV_OS_ORBIS #include <libdbg.h> #endif #define NV_USE_SEPARATE_THREAD 1 using namespace nv; namespace { static MessageHandler * s_message_handler = NULL; static AssertHandler * s_assert_handler = NULL; static bool s_sig_handler_enabled = false; static bool s_interactive = true; #if NV_OS_WIN32 && NV_CC_MSVC // Old exception filter. static LPTOP_LEVEL_EXCEPTION_FILTER s_old_exception_filter = NULL; #elif !NV_OS_WIN32 && defined(HAVE_SIGNAL_H) // Old signal handlers. struct sigaction s_old_sigsegv; struct sigaction s_old_sigtrap; struct sigaction s_old_sigfpe; struct sigaction s_old_sigbus; #endif #if NV_OS_WIN32 && NV_CC_MSVC // We should try to simplify the top level filter as much as possible. // http://www.nynaeve.net/?p=128 #if NV_USE_SEPARATE_THREAD // The critical section enforcing the requirement that only one exception be // handled by a handler at a time. static CRITICAL_SECTION s_handler_critical_section; // Semaphores used to move exception handling between the exception thread // and the handler thread. handler_start_semaphore_ is signalled by the // exception thread to wake up the handler thread when an exception occurs. // handler_finish_semaphore_ is signalled by the handler thread to wake up // the exception thread when handling is complete. static HANDLE s_handler_start_semaphore = NULL; static HANDLE s_handler_finish_semaphore = NULL; // The exception handler thread. static HANDLE s_handler_thread = NULL; static DWORD s_requesting_thread_id = 0; static EXCEPTION_POINTERS * s_exception_info = NULL; #endif // NV_USE_SEPARATE_THREAD struct MinidumpCallbackContext { ULONG64 memory_base; ULONG memory_size; bool finished; }; // static static BOOL CALLBACK miniDumpWriteDumpCallback(PVOID context, const PMINIDUMP_CALLBACK_INPUT callback_input, PMINIDUMP_CALLBACK_OUTPUT callback_output) { switch (callback_input->CallbackType) { case MemoryCallback: { MinidumpCallbackContext* callback_context = reinterpret_cast<MinidumpCallbackContext*>(context); if (callback_context->finished) return FALSE; // Include the specified memory region. callback_output->MemoryBase = callback_context->memory_base; callback_output->MemorySize = callback_context->memory_size; callback_context->finished = true; return TRUE; } // Include all modules. case IncludeModuleCallback: case ModuleCallback: return TRUE; // Include all threads. case IncludeThreadCallback: case ThreadCallback: return TRUE; // Stop receiving cancel callbacks. case CancelCallback: callback_output->CheckCancel = FALSE; callback_output->Cancel = FALSE; return TRUE; } // Ignore other callback types. return FALSE; } static bool writeMiniDump(EXCEPTION_POINTERS * pExceptionInfo) { // create the file HANDLE hFile = CreateFileA("crash.dmp", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { //nvDebug("*** Failed to create dump file.\n"); return false; } MINIDUMP_EXCEPTION_INFORMATION * pExInfo = NULL; MINIDUMP_CALLBACK_INFORMATION * pCallback = NULL; if (pExceptionInfo != NULL) { MINIDUMP_EXCEPTION_INFORMATION ExInfo; ExInfo.ThreadId = ::GetCurrentThreadId(); ExInfo.ExceptionPointers = pExceptionInfo; ExInfo.ClientPointers = NULL; pExInfo = &ExInfo; MINIDUMP_CALLBACK_INFORMATION callback; MinidumpCallbackContext context; // Find a memory region of 256 bytes centered on the // faulting instruction pointer. const ULONG64 instruction_pointer = #if defined(_M_IX86) pExceptionInfo->ContextRecord->Eip; #elif defined(_M_AMD64) pExceptionInfo->ContextRecord->Rip; #else #error Unsupported platform #endif MEMORY_BASIC_INFORMATION info; if (VirtualQuery(reinterpret_cast<LPCVOID>(instruction_pointer), &info, sizeof(MEMORY_BASIC_INFORMATION)) != 0 && info.State == MEM_COMMIT) { // Attempt to get 128 bytes before and after the instruction // pointer, but settle for whatever's available up to the // boundaries of the memory region. const ULONG64 kIPMemorySize = 256; context.memory_base = max(reinterpret_cast<ULONG64>(info.BaseAddress), instruction_pointer - (kIPMemorySize / 2)); ULONG64 end_of_range = min(instruction_pointer + (kIPMemorySize / 2), reinterpret_cast<ULONG64>(info.BaseAddress) + info.RegionSize); context.memory_size = static_cast<ULONG>(end_of_range - context.memory_base); context.finished = false; callback.CallbackRoutine = miniDumpWriteDumpCallback; callback.CallbackParam = reinterpret_cast<void*>(&context); pCallback = &callback; } } MINIDUMP_TYPE miniDumpType = (MINIDUMP_TYPE)(MiniDumpNormal|MiniDumpWithHandleData|MiniDumpWithThreadInfo); // write the dump BOOL ok = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, miniDumpType, pExInfo, NULL, pCallback) != 0; CloseHandle(hFile); if (ok == FALSE) { //nvDebug("*** Failed to save dump file.\n"); return false; } //nvDebug("\nDump file saved.\n"); return true; } #if NV_USE_SEPARATE_THREAD static DWORD WINAPI ExceptionHandlerThreadMain(void* lpParameter) { nvDebugCheck(s_handler_start_semaphore != NULL); nvDebugCheck(s_handler_finish_semaphore != NULL); while (true) { if (WaitForSingleObject(s_handler_start_semaphore, INFINITE) == WAIT_OBJECT_0) { writeMiniDump(s_exception_info); // Allow the requesting thread to proceed. ReleaseSemaphore(s_handler_finish_semaphore, 1, NULL); } } // This statement is not reached when the thread is unconditionally // terminated by the ExceptionHandler destructor. return 0; } #endif // NV_USE_SEPARATE_THREAD static bool hasStackTrace() { return true; } /*static NV_NOINLINE int backtrace(void * trace[], int maxcount) { // In Windows XP and Windows Server 2003, the sum of the FramesToSkip and FramesToCapture parameters must be less than 63. int xp_maxcount = min(63-1, maxcount); int count = RtlCaptureStackBackTrace(1, xp_maxcount, trace, NULL); nvDebugCheck(count <= maxcount); return count; }*/ static NV_NOINLINE int backtraceWithSymbols(CONTEXT * ctx, void * trace[], int maxcount, int skip = 0) { // Init the stack frame for this function STACKFRAME64 stackFrame = { 0 }; #if NV_CPU_X86_64 DWORD dwMachineType = IMAGE_FILE_MACHINE_AMD64; stackFrame.AddrPC.Offset = ctx->Rip; stackFrame.AddrFrame.Offset = ctx->Rbp; stackFrame.AddrStack.Offset = ctx->Rsp; #elif NV_CPU_X86 DWORD dwMachineType = IMAGE_FILE_MACHINE_I386; stackFrame.AddrPC.Offset = ctx->Eip; stackFrame.AddrFrame.Offset = ctx->Ebp; stackFrame.AddrStack.Offset = ctx->Esp; #else #error "Platform not supported!" #endif stackFrame.AddrPC.Mode = AddrModeFlat; stackFrame.AddrFrame.Mode = AddrModeFlat; stackFrame.AddrStack.Mode = AddrModeFlat; // Walk up the stack const HANDLE hThread = GetCurrentThread(); const HANDLE hProcess = GetCurrentProcess(); int i; for (i = 0; i < maxcount; i++) { // walking once first makes us skip self if (!StackWalk64(dwMachineType, hProcess, hThread, &stackFrame, ctx, NULL, &SymFunctionTableAccess64, &SymGetModuleBase64, NULL)) { break; } /*if (stackFrame.AddrPC.Offset == stackFrame.AddrReturn.Offset || stackFrame.AddrPC.Offset == 0) { break; }*/ if (i >= skip) { trace[i - skip] = (PVOID)stackFrame.AddrPC.Offset; } } return i - skip; } #pragma warning(push) #pragma warning(disable:4748) static NV_NOINLINE int backtrace(void * trace[], int maxcount) { CONTEXT ctx = { 0 }; #if NV_CPU_X86 && !NV_CPU_X86_64 ctx.ContextFlags = CONTEXT_CONTROL; _asm { call x x: pop eax mov ctx.Eip, eax mov ctx.Ebp, ebp mov ctx.Esp, esp } #else RtlCaptureContext(&ctx); // Not implemented correctly in x86. #endif return backtraceWithSymbols(&ctx, trace, maxcount, 1); } #pragma warning(pop) static NV_NOINLINE void writeStackTrace(void * trace[], int size, int start, Array<const char *> & lines) { StringBuilder builder(512); HANDLE hProcess = GetCurrentProcess(); // Resolve PC to function names for (int i = start; i < size; i++) { // Check for end of stack walk DWORD64 ip = (DWORD64)trace[i]; if (ip == NULL) break; // Get function name #define MAX_STRING_LEN (512) unsigned char byBuffer[sizeof(IMAGEHLP_SYMBOL64) + MAX_STRING_LEN] = { 0 }; IMAGEHLP_SYMBOL64 * pSymbol = (IMAGEHLP_SYMBOL64*)byBuffer; pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64); pSymbol->MaxNameLength = MAX_STRING_LEN; DWORD64 dwDisplacement; if (SymGetSymFromAddr64(hProcess, ip, &dwDisplacement, pSymbol)) { pSymbol->Name[MAX_STRING_LEN-1] = 0; /* // Make the symbol readable for humans UnDecorateSymbolName( pSym->Name, lpszNonUnicodeUnDSymbol, BUFFERSIZE, UNDNAME_COMPLETE | UNDNAME_NO_THISTYPE | UNDNAME_NO_SPECIAL_SYMS | UNDNAME_NO_MEMBER_TYPE | UNDNAME_NO_MS_KEYWORDS | UNDNAME_NO_ACCESS_SPECIFIERS ); */ // pSymbol->Name const char * pFunc = pSymbol->Name; // Get file/line number IMAGEHLP_LINE64 theLine = { 0 }; theLine.SizeOfStruct = sizeof(theLine); DWORD dwDisplacement; if (!SymGetLineFromAddr64(hProcess, ip, &dwDisplacement, &theLine)) { // Do not print unknown symbols anymore. break; //builder.format("unknown(%08X) : %s\n", (uint32)ip, pFunc); } else { /* const char* pFile = strrchr(theLine.FileName, '\\'); if ( pFile == NULL ) pFile = theLine.FileName; else pFile++; */ const char * pFile = theLine.FileName; int line = theLine.LineNumber; builder.format("%s(%d) : %s\n", pFile, line, pFunc); } lines.append(builder.release()); if (pFunc != NULL && strcmp(pFunc, "WinMain") == 0) { break; } } } } // Write mini dump and print stack trace. static LONG WINAPI handleException(EXCEPTION_POINTERS * pExceptionInfo) { EnterCriticalSection(&s_handler_critical_section); #if NV_USE_SEPARATE_THREAD s_requesting_thread_id = GetCurrentThreadId(); s_exception_info = pExceptionInfo; // This causes the handler thread to call writeMiniDump. ReleaseSemaphore(s_handler_start_semaphore, 1, NULL); // Wait until WriteMinidumpWithException is done and collect its return value. WaitForSingleObject(s_handler_finish_semaphore, INFINITE); //bool status = s_handler_return_value; // Clean up. s_requesting_thread_id = 0; s_exception_info = NULL; #else // First of all, write mini dump. writeMiniDump(pExceptionInfo); #endif LeaveCriticalSection(&s_handler_critical_section); nvDebug("\nDump file saved.\n"); // Try to attach to debugger. if (s_interactive && debug::attachToDebugger()) { nvDebugBreak(); return EXCEPTION_CONTINUE_EXECUTION; } // If that fails, then try to pretty print a stack trace and terminate. void * trace[64]; int size = backtraceWithSymbols(pExceptionInfo->ContextRecord, trace, 64); // @@ Use win32's CreateFile? FILE * fp = fileOpen("crash.txt", "wb"); if (fp != NULL) { Array<const char *> lines; writeStackTrace(trace, size, 0, lines); for (uint i = 0; i < lines.count(); i++) { fputs(lines[i], fp); delete lines[i]; } // @@ Add more info to crash.txt? fclose(fp); } // This should terminate the process and set the error exit code. TerminateProcess(GetCurrentProcess(), EXIT_FAILURE + 2); return EXCEPTION_EXECUTE_HANDLER; // Terminate app. In case terminate process did not succeed. } static void handlePureVirtualCall() { nvDebugBreak(); TerminateProcess(GetCurrentProcess(), EXIT_FAILURE + 8); } static void handleInvalidParameter(const wchar_t * wexpresion, const wchar_t * wfunction, const wchar_t * wfile, unsigned int line, uintptr_t reserved) { size_t convertedCharCount = 0; StringBuilder expresion; if (wexpresion != NULL) { uint size = U32(wcslen(wexpresion) + 1); expresion.reserve(size); wcstombs_s(&convertedCharCount, expresion.str(), size, wexpresion, _TRUNCATE); } StringBuilder file; if (wfile != NULL) { uint size = U32(wcslen(wfile) + 1); file.reserve(size); wcstombs_s(&convertedCharCount, file.str(), size, wfile, _TRUNCATE); } StringBuilder function; if (wfunction != NULL) { uint size = U32(wcslen(wfunction) + 1); function.reserve(size); wcstombs_s(&convertedCharCount, function.str(), size, wfunction, _TRUNCATE); } int result = nvAbort(expresion.str(), file.str(), line, function.str()); if (result == NV_ABORT_DEBUG) { nvDebugBreak(); } } #elif !NV_OS_WIN32 && defined(HAVE_SIGNAL_H) // NV_OS_LINUX || NV_OS_DARWIN #if defined(HAVE_EXECINFO_H) static bool hasStackTrace() { #if NV_OS_DARWIN return backtrace != NULL; #else return true; #endif } static void writeStackTrace(void * trace[], int size, int start, Array<const char *> & lines) { StringBuilder builder(512); char ** string_array = backtrace_symbols(trace, size); for(int i = start; i < size-1; i++ ) { # if NV_CC_GNUC // defined(HAVE_CXXABI_H) // @@ Write a better parser for the possible formats. char * begin = strchr(string_array[i], '('); char * end = strrchr(string_array[i], '+'); char * module = string_array[i]; if (begin == 0 && end != 0) { *(end - 1) = '\0'; begin = strrchr(string_array[i], ' '); module = NULL; // Ignore module. } if (begin != 0 && begin < end) { int stat; *end = '\0'; *begin = '\0'; char * name = abi::__cxa_demangle(begin+1, 0, 0, &stat); if (module == NULL) { if (name == NULL || stat != 0) { builder.format(" In: '%s'\n", begin+1); } else { builder.format(" In: '%s'\n", name); } } else { if (name == NULL || stat != 0) { builder.format(" In: [%s] '%s'\n", module, begin+1); } else { builder.format(" In: [%s] '%s'\n", module, name); } } free(name); } else { builder.format(" In: '%s'\n", string_array[i]); } # else builder.format(" In: '%s'\n", string_array[i]); # endif lines.append(builder.release()); } free(string_array); } static void printStackTrace(void * trace[], int size, int start=0) { nvDebug( "\nDumping stacktrace:\n" ); Array<const char *> lines; writeStackTrace(trace, size, 1, lines); for (uint i = 0; i < lines.count(); i++) { nvDebug(lines[i]); delete lines[i]; } nvDebug("\n"); } #endif // defined(HAVE_EXECINFO_H) static void * callerAddress(void * secret) { #if NV_OS_DARWIN # if defined(_STRUCT_MCONTEXT) # if NV_CPU_PPC ucontext_t * ucp = (ucontext_t *)secret; return (void *) ucp->uc_mcontext->__ss.__srr0; # elif NV_CPU_X86_64 ucontext_t * ucp = (ucontext_t *)secret; return (void *) ucp->uc_mcontext->__ss.__rip; # elif NV_CPU_X86 ucontext_t * ucp = (ucontext_t *)secret; return (void *) ucp->uc_mcontext->__ss.__eip; # elif NV_CPU_ARM ucontext_t * ucp = (ucontext_t *)secret; return (void *) ucp->uc_mcontext->__ss.__pc; # else # error "Unknown CPU" # endif # else # if NV_CPU_PPC ucontext_t * ucp = (ucontext_t *)secret; return (void *) ucp->uc_mcontext->ss.srr0; # elif NV_CPU_X86 ucontext_t * ucp = (ucontext_t *)secret; return (void *) ucp->uc_mcontext->ss.eip; # else # error "Unknown CPU" # endif # endif #elif NV_OS_FREEBSD # if NV_CPU_X86_64 ucontext_t * ucp = (ucontext_t *)secret; return (void *)ucp->uc_mcontext.mc_rip; # elif NV_CPU_X86 ucontext_t * ucp = (ucontext_t *)secret; return (void *)ucp->uc_mcontext.mc_eip; # else # error "Unknown CPU" # endif #elif NV_OS_OPENBSD # if NV_CPU_X86_64 ucontext_t * ucp = (ucontext_t *)secret; return (void *)ucp->sc_rip; # elif NV_CPU_X86 ucontext_t * ucp = (ucontext_t *)secret; return (void *)ucp->sc_eip; # else # error "Unknown CPU" # endif #else # if NV_CPU_X86_64 // #define REG_RIP REG_INDEX(rip) // seems to be 16 ucontext_t * ucp = (ucontext_t *)secret; return (void *)ucp->uc_mcontext.gregs[REG_RIP]; # elif NV_CPU_X86 ucontext_t * ucp = (ucontext_t *)secret; return (void *)ucp->uc_mcontext.gregs[14/*REG_EIP*/]; # elif NV_CPU_PPC ucontext_t * ucp = (ucontext_t *)secret; return (void *) ucp->uc_mcontext.regs->nip; # else # error "Unknown CPU" # endif #endif // How to obtain the instruction pointers in different platforms, from mlton's source code. // http://mlton.org/ // OpenBSD && NetBSD // ucp->sc_eip // FreeBSD: // ucp->uc_mcontext.mc_eip // HPUX: // ucp->uc_link // Solaris: // ucp->uc_mcontext.gregs[REG_PC] // Linux hppa: // uc->uc_mcontext.sc_iaoq[0] & ~0x3UL // Linux sparc: // ((struct sigcontext*) secret)->sigc_regs.tpc // Linux sparc64: // ((struct sigcontext*) secret)->si_regs.pc // potentially correct for other archs: // Linux alpha: ucp->m_context.sc_pc // Linux arm: ucp->m_context.ctx.arm_pc // Linux ia64: ucp->m_context.sc_ip & ~0x3UL // Linux mips: ucp->m_context.sc_pc // Linux s390: ucp->m_context.sregs->regs.psw.addr } static void nvSigHandler(int sig, siginfo_t *info, void *secret) { void * pnt = callerAddress(secret); // Do something useful with siginfo_t if (sig == SIGSEGV) { if (pnt != NULL) nvDebug("Got signal %d, faulty address is %p, from %p\n", sig, info->si_addr, pnt); else nvDebug("Got signal %d, faulty address is %p\n", sig, info->si_addr); } else if(sig == SIGTRAP) { nvDebug("Breakpoint hit.\n"); } else { nvDebug("Got signal %d\n", sig); } #if defined(HAVE_EXECINFO_H) if (hasStackTrace()) // in case of weak linking { void * trace[64]; int size = backtrace(trace, 64); if (pnt != NULL) { // Overwrite sigaction with caller's address. trace[1] = pnt; } printStackTrace(trace, size, 1); } #endif // defined(HAVE_EXECINFO_H) exit(0); } #endif // defined(HAVE_SIGNAL_H) #if NV_OS_WIN32 //&& NV_CC_MSVC /** Win32 assert handler. */ struct Win32AssertHandler : public AssertHandler { // Flush the message queue. This is necessary for the message box to show up. static void flushMessageQueue() { MSG msg; while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { //if( msg.message == WM_QUIT ) break; TranslateMessage( &msg ); DispatchMessage( &msg ); } } // Assert handler method. virtual int assertion(const char * exp, const char * file, int line, const char * func, const char * msg, va_list arg) { int ret = NV_ABORT_EXIT; StringBuilder error_string; error_string.format("*** Assertion failed: %s\n On file: %s\n On line: %d\n", exp, file, line ); if (func != NULL) { error_string.appendFormat(" On function: %s\n", func); } if (msg != NULL) { error_string.append(" Message: "); va_list tmp; va_copy(tmp, arg); error_string.appendFormatList(msg, tmp); va_end(tmp); error_string.append("\n"); } nvDebug( error_string.str() ); // Print stack trace: debug::dumpInfo(); if (debug::isDebuggerPresent()) { return NV_ABORT_DEBUG; } if (s_interactive) { flushMessageQueue(); int action = MessageBoxA(NULL, error_string.str(), "Assertion failed", MB_ABORTRETRYIGNORE | MB_ICONERROR | MB_TOPMOST); switch( action ) { case IDRETRY: ret = NV_ABORT_DEBUG; break; case IDIGNORE: ret = NV_ABORT_IGNORE; break; case IDABORT: default: ret = NV_ABORT_EXIT; break; } /*if( _CrtDbgReport( _CRT_ASSERT, file, line, module, exp ) == 1 ) { return NV_ABORT_DEBUG; }*/ } if (ret == NV_ABORT_EXIT) { // Exit cleanly. exit(EXIT_FAILURE + 1); } return ret; } }; #elif NV_OS_XBOX /** Xbox360 assert handler. */ struct Xbox360AssertHandler : public AssertHandler { // Assert handler method. virtual int assertion(const char * exp, const char * file, int line, const char * func, const char * msg, va_list arg) { int ret = NV_ABORT_EXIT; StringBuilder error_string; if( func != NULL ) { error_string.format( "*** Assertion failed: %s\n On file: %s\n On function: %s\n On line: %d\n ", exp, file, func, line ); nvDebug( error_string.str() ); } else { error_string.format( "*** Assertion failed: %s\n On file: %s\n On line: %d\n ", exp, file, line ); nvDebug( error_string.str() ); } if (debug::isDebuggerPresent()) { return NV_ABORT_DEBUG; } if( ret == NV_ABORT_EXIT ) { // Exit cleanly. exit(EXIT_FAILURE + 1); } return ret; } }; #elif NV_OS_ORBIS /** Orbis assert handler. */ struct OrbisAssertHandler : public AssertHandler { // Assert handler method. virtual int assertion(const char * exp, const char * file, int line, const char * func, const char * msg, va_list arg) { if( func != NULL ) { nvDebug( "*** Assertion failed: %s\n On file: %s\n On function: %s\n On line: %d\n ", exp, file, func, line ); } else { nvDebug( "*** Assertion failed: %s\n On file: %s\n On line: %d\n ", exp, file, line ); } //SBtodoORBIS print stack trace /*if (hasStackTrace()) { void * trace[64]; int size = backtrace(trace, 64); printStackTrace(trace, size, 2); }*/ if (debug::isDebuggerPresent()) return NV_ABORT_DEBUG; return NV_ABORT_IGNORE; } }; #else /** Unix assert handler. */ struct UnixAssertHandler : public AssertHandler { // Assert handler method. virtual int assertion(const char * exp, const char * file, int line, const char * func, const char * msg, va_list arg) { int ret = NV_ABORT_EXIT; if( func != NULL ) { nvDebug( "*** Assertion failed: %s\n On file: %s\n On function: %s\n On line: %d\n ", exp, file, func, line ); } else { nvDebug( "*** Assertion failed: %s\n On file: %s\n On line: %d\n ", exp, file, line ); } #if _DEBUG if (debug::isDebuggerPresent()) { return NV_ABORT_DEBUG; } #endif #if defined(HAVE_EXECINFO_H) if (hasStackTrace()) { void * trace[64]; int size = backtrace(trace, 64); printStackTrace(trace, size, 2); } #endif if( ret == NV_ABORT_EXIT ) { // Exit cleanly. exit(EXIT_FAILURE + 1); } return ret; } }; #endif } // namespace /// Handle assertion through the assert handler. int nvAbort(const char * exp, const char * file, int line, const char * func/*=NULL*/, const char * msg/*= NULL*/, ...) { #if NV_OS_WIN32 //&& NV_CC_MSVC static Win32AssertHandler s_default_assert_handler; #elif NV_OS_XBOX static Xbox360AssertHandler s_default_assert_handler; #elif NV_OS_ORBIS static OrbisAssertHandler s_default_assert_handler; #else static UnixAssertHandler s_default_assert_handler; #endif va_list arg; va_start(arg,msg); AssertHandler * handler = s_assert_handler != NULL ? s_assert_handler : &s_default_assert_handler; int result = handler->assertion(exp, file, line, func, msg, arg); va_end(arg); return result; } // Abnormal termination. Create mini dump and output call stack. void debug::terminate(int code) { #if NV_OS_WIN32 EnterCriticalSection(&s_handler_critical_section); writeMiniDump(NULL); const int max_stack_size = 64; void * trace[max_stack_size]; int size = backtrace(trace, max_stack_size); // @@ Use win32's CreateFile? FILE * fp = fileOpen("crash.txt", "wb"); if (fp != NULL) { Array<const char *> lines; writeStackTrace(trace, size, 0, lines); for (uint i = 0; i < lines.count(); i++) { fputs(lines[i], fp); delete lines[i]; } // @@ Add more info to crash.txt? fclose(fp); } LeaveCriticalSection(&s_handler_critical_section); #endif exit(code); } /// Shows a message through the message handler. void NV_CDECL nvDebugPrint(const char *msg, ...) { va_list arg; va_start(arg,msg); if (s_message_handler != NULL) { s_message_handler->log( msg, arg ); } va_end(arg); } /// Dump debug info. void debug::dumpInfo() { #if (NV_OS_WIN32 && NV_CC_MSVC) || (defined(HAVE_SIGNAL_H) && defined(HAVE_EXECINFO_H)) if (hasStackTrace()) { void * trace[64]; int size = backtrace(trace, 64); nvDebug( "\nDumping stacktrace:\n" ); Array<const char *> lines; writeStackTrace(trace, size, 1, lines); for (uint i = 0; i < lines.count(); i++) { nvDebug(lines[i]); delete lines[i]; } } #endif } /// Dump callstack using the specified handler. void debug::dumpCallstack(MessageHandler *messageHandler, int callstackLevelsToSkip /*= 0*/) { #if (NV_OS_WIN32 && NV_CC_MSVC) || (defined(HAVE_SIGNAL_H) && defined(HAVE_EXECINFO_H)) if (hasStackTrace()) { void * trace[64]; int size = backtrace(trace, 64); Array<const char *> lines; writeStackTrace(trace, size, callstackLevelsToSkip + 1, lines); // + 1 to skip the call to dumpCallstack for (uint i = 0; i < lines.count(); i++) { messageHandler->log(lines[i], NULL); delete lines[i]; } } #endif } /// Set the debug message handler. void debug::setMessageHandler(MessageHandler * message_handler) { s_message_handler = message_handler; } /// Reset the debug message handler. void debug::resetMessageHandler() { s_message_handler = NULL; } /// Set the assert handler. void debug::setAssertHandler(AssertHandler * assert_handler) { s_assert_handler = assert_handler; } /// Reset the assert handler. void debug::resetAssertHandler() { s_assert_handler = NULL; } #if NV_OS_WIN32 #if NV_USE_SEPARATE_THREAD static void initHandlerThread() { static const int kExceptionHandlerThreadInitialStackSize = 64 * 1024; // Set synchronization primitives and the handler thread. Each // ExceptionHandler object gets its own handler thread because that's the // only way to reliably guarantee sufficient stack space in an exception, // and it allows an easy way to get a snapshot of the requesting thread's // context outside of an exception. InitializeCriticalSection(&s_handler_critical_section); s_handler_start_semaphore = CreateSemaphore(NULL, 0, 1, NULL); nvDebugCheck(s_handler_start_semaphore != NULL); s_handler_finish_semaphore = CreateSemaphore(NULL, 0, 1, NULL); nvDebugCheck(s_handler_finish_semaphore != NULL); // Don't attempt to create the thread if we could not create the semaphores. if (s_handler_finish_semaphore != NULL && s_handler_start_semaphore != NULL) { DWORD thread_id; s_handler_thread = CreateThread(NULL, // lpThreadAttributes kExceptionHandlerThreadInitialStackSize, ExceptionHandlerThreadMain, NULL, // lpParameter 0, // dwCreationFlags &thread_id); nvDebugCheck(s_handler_thread != NULL); } /* @@ We should avoid loading modules in the exception handler! dbghelp_module_ = LoadLibrary(L"dbghelp.dll"); if (dbghelp_module_) { minidump_write_dump_ = reinterpret_cast<MiniDumpWriteDump_type>(GetProcAddress(dbghelp_module_, "MiniDumpWriteDump")); } */ } static void shutHandlerThread() { // @@ Free stuff. Terminate thread. } #endif // NV_USE_SEPARATE_THREAD #endif // NV_OS_WIN32 // Enable signal handler. void debug::enableSigHandler(bool interactive) { nvCheck(s_sig_handler_enabled != true); s_sig_handler_enabled = true; s_interactive = interactive; #if NV_OS_WIN32 && NV_CC_MSVC if (interactive) { // Do not display message boxes on error. // http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621(v=vs.85).aspx SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX); // CRT reports errors to debug output only. // http://msdn.microsoft.com/en-us/library/1y71x448(v=vs.80).aspx _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); } #if NV_USE_SEPARATE_THREAD initHandlerThread(); #endif s_old_exception_filter = ::SetUnhandledExceptionFilter( handleException ); #if _MSC_VER >= 1400 // MSVC 2005/8 _set_invalid_parameter_handler(handleInvalidParameter); #endif // _MSC_VER >= 1400 _set_purecall_handler(handlePureVirtualCall); // SYMOPT_DEFERRED_LOADS make us not take a ton of time unless we actual log traces SymSetOptions(SYMOPT_DEFERRED_LOADS|SYMOPT_FAIL_CRITICAL_ERRORS|SYMOPT_LOAD_LINES|SYMOPT_UNDNAME); if (!SymInitialize(GetCurrentProcess(), NULL, TRUE)) { DWORD error = GetLastError(); nvDebug("SymInitialize returned error : %d\n", error); } #elif !NV_OS_WIN32 && defined(HAVE_SIGNAL_H) // Install our signal handler struct sigaction sa; sa.sa_sigaction = nvSigHandler; sigemptyset (&sa.sa_mask); sa.sa_flags = SA_ONSTACK | SA_RESTART | SA_SIGINFO; sigaction(SIGSEGV, &sa, &s_old_sigsegv); sigaction(SIGTRAP, &sa, &s_old_sigtrap); sigaction(SIGFPE, &sa, &s_old_sigfpe); sigaction(SIGBUS, &sa, &s_old_sigbus); #endif } /// Disable signal handler. void debug::disableSigHandler() { nvCheck(s_sig_handler_enabled == true); s_sig_handler_enabled = false; #if NV_OS_WIN32 && NV_CC_MSVC ::SetUnhandledExceptionFilter( s_old_exception_filter ); s_old_exception_filter = NULL; SymCleanup(GetCurrentProcess()); #elif !NV_OS_WIN32 && defined(HAVE_SIGNAL_H) sigaction(SIGSEGV, &s_old_sigsegv, NULL); sigaction(SIGTRAP, &s_old_sigtrap, NULL); sigaction(SIGFPE, &s_old_sigfpe, NULL); sigaction(SIGBUS, &s_old_sigbus, NULL); #endif } bool debug::isDebuggerPresent() { #if NV_OS_WIN32 HINSTANCE kernel32 = GetModuleHandleA("kernel32.dll"); if (kernel32) { FARPROC IsDebuggerPresent = GetProcAddress(kernel32, "IsDebuggerPresent"); if (IsDebuggerPresent != NULL && IsDebuggerPresent()) { return true; } } return false; #elif NV_OS_XBOX #ifdef _DEBUG return DmIsDebuggerPresent() == TRUE; #else return false; #endif #elif NV_OS_ORBIS #if PS4_FINAL_REQUIREMENTS return false; #else return sceDbgIsDebuggerAttached() == 1; #endif #elif NV_OS_DARWIN int mib[4]; struct kinfo_proc info; size_t size; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); size = sizeof(info); info.kp_proc.p_flag = 0; sysctl(mib,4,&info,&size,NULL,0); return ((info.kp_proc.p_flag & P_TRACED) == P_TRACED); #else // if ppid != sid, some process spawned our app, probably a debugger. return getsid(getpid()) != getppid(); #endif } bool debug::attachToDebugger() { #if NV_OS_WIN32 if (isDebuggerPresent() == FALSE) { Path process(1024); process.copy("\""); GetSystemDirectoryA(process.str() + 1, 1024 - 1); process.appendSeparator(); process.appendFormat("VSJitDebugger.exe\" -p %lu", ::GetCurrentProcessId()); STARTUPINFOA sSi; memset(&sSi, 0, sizeof(sSi)); PROCESS_INFORMATION sPi; memset(&sPi, 0, sizeof(sPi)); BOOL b = CreateProcessA(NULL, process.str(), NULL, NULL, FALSE, 0, NULL, NULL, &sSi, &sPi); if (b != FALSE) { ::WaitForSingleObject(sPi.hProcess, INFINITE); DWORD dwExitCode; ::GetExitCodeProcess(sPi.hProcess, &dwExitCode); if (dwExitCode != 0) //if exit code is zero, a debugger was selected b = FALSE; } if (sPi.hThread != NULL) ::CloseHandle(sPi.hThread); if (sPi.hProcess != NULL) ::CloseHandle(sPi.hProcess); if (b == FALSE) return false; for (int i = 0; i < 5*60; i++) { if (isDebuggerPresent()) break; ::Sleep(200); } } #endif // NV_OS_WIN32 return true; }
dmsovetov/nvidia-texture-tools
src/nvcore/Debug.cpp
C++
mit
40,281
module Fog module Compute class XenServer module Models class Vlans < Collection model Fog::Compute::XenServer::Models::Vlan end end end end end
jonpstone/portfolio-project-rails-mean-movie-reviews
vendor/bundle/ruby/2.3.0/gems/fog-xenserver-0.3.0/lib/fog/compute/xen_server/models/vlans.rb
Ruby
mit
194
/** @module ember-data */ import Ember from 'ember'; import Model from "ember-data/model"; var get = Ember.get; var capitalize = Ember.String.capitalize; var underscore = Ember.String.underscore; const { assert } = Ember; /* Extend `Ember.DataAdapter` with ED specific code. @class DebugAdapter @namespace DS @extends Ember.DataAdapter @private */ export default Ember.DataAdapter.extend({ getFilters() { return [ { name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' } ]; }, detect(typeClass) { return typeClass !== Model && Model.detect(typeClass); }, columnsForType(typeClass) { var columns = [{ name: 'id', desc: 'Id' }]; var count = 0; var self = this; get(typeClass, 'attributes').forEach((meta, name) => { if (count++ > self.attributeLimit) { return false; } var desc = capitalize(underscore(name).replace('_', ' ')); columns.push({ name: name, desc: desc }); }); return columns; }, getRecords(modelClass, modelName) { if (arguments.length < 2) { // Legacy Ember.js < 1.13 support let containerKey = modelClass._debugContainerKey; if (containerKey) { let match = containerKey.match(/model:(.*)/); if (match) { modelName = match[1]; } } } assert("Cannot find model name. Please upgrade to Ember.js >= 1.13 for Ember Inspector support", !!modelName); return this.get('store').peekAll(modelName); }, getRecordColumnValues(record) { var count = 0; var columnValues = { id: get(record, 'id') }; record.eachAttribute((key) => { if (count++ > this.attributeLimit) { return false; } var value = get(record, key); columnValues[key] = value; }); return columnValues; }, getRecordKeywords(record) { var keywords = []; var keys = Ember.A(['id']); record.eachAttribute((key) => keys.push(key)); keys.forEach((key) => keywords.push(get(record, key))); return keywords; }, getRecordFilterValues(record) { return { isNew: record.get('isNew'), isModified: record.get('hasDirtyAttributes') && !record.get('isNew'), isClean: !record.get('hasDirtyAttributes') }; }, getRecordColor(record) { var color = 'black'; if (record.get('isNew')) { color = 'green'; } else if (record.get('hasDirtyAttributes')) { color = 'blue'; } return color; }, observeRecord(record, recordUpdated) { var releaseMethods = Ember.A(); var keysToObserve = Ember.A(['id', 'isNew', 'hasDirtyAttributes']); record.eachAttribute((key) => keysToObserve.push(key)); var adapter = this; keysToObserve.forEach(function(key) { var handler = function() { recordUpdated(adapter.wrapRecord(record)); }; Ember.addObserver(record, key, handler); releaseMethods.push(function() { Ember.removeObserver(record, key, handler); }); }); var release = function() { releaseMethods.forEach((fn) => fn()); }; return release; } });
r0zar/ember-rails-stocks
stocks/node_modules/ember-data/addon/-private/system/debug/debug-adapter.js
JavaScript
mit
3,163
<?php /** * @package wpml-core * @subpackage wpml-user-language */ class WPML_User_Language_Switcher_UI { /** * WPML_User_Language_Switcher_UI constructor. * * @param WPML_User_Language_Switcher $WPML_User_Language_Switcher * @param WPML_User_Language_Switcher_Resources $WPML_User_Language_Switcher_Resources */ public function __construct( &$WPML_User_Language_Switcher, &$WPML_User_Language_Switcher_Resources ) { $this->user_language_switcher = &$WPML_User_Language_Switcher; $this->resources = &$WPML_User_Language_Switcher_Resources; } public function language_switcher( $args, $model ) { $this->resources->enqueue_scripts( $args ); return $this->get_view( $model ); } /** * @param array $model * * @return string */ protected function get_view( $model ) { $template_paths = array( ICL_PLUGIN_PATH . '/templates/user-language/', ); $template = 'language-switcher.twig'; $loader = new Twig_Loader_Filesystem( $template_paths ); $environment_args = array(); if ( WP_DEBUG ) { $environment_args['debug'] = true; } $twig = new Twig_Environment( $loader, $environment_args ); return $twig->render( $template, $model ); } }
Bamboo3000/searchit
wp-content/plugins/sitepress-multilingual-cms/classes/user-language/class-wpml-user-language-switcher-ui.php
PHP
gpl-2.0
1,231
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2013 Budiarto Herman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Budiarto Herman <budiarto.herman@magister.fi> * */ #include <ns3/test.h> #include <ns3/log.h> #include <ns3/nstime.h> #include <ns3/callback.h> #include <ns3/config.h> #include <ns3/boolean.h> #include <ns3/double.h> #include <ns3/uinteger.h> #include <ns3/simulator.h> #include <ns3/node-container.h> #include <ns3/net-device-container.h> #include <ns3/ipv4-interface-container.h> #include <ns3/lte-helper.h> #include <ns3/point-to-point-epc-helper.h> #include <ns3/internet-stack-helper.h> #include <ns3/point-to-point-helper.h> #include <ns3/ipv4-address-helper.h> #include <ns3/ipv4-static-routing-helper.h> #include <ns3/mobility-helper.h> #include <ns3/data-rate.h> #include <ns3/ipv4-static-routing.h> #include <ns3/position-allocator.h> #include <ns3/lte-enb-net-device.h> #include <ns3/lte-enb-phy.h> using namespace ns3; NS_LOG_COMPONENT_DEFINE ("LteHandoverTargetTest"); /** * \ingroup lte-test * \ingroup tests * * \brief Testing a handover algorithm, verifying that it selects the right * target cell when more than one options available. * * Part of the `lte-handover-target` test suite. * * The test case will run a 1-second LTE-EPC simulation using the parameters * provided to the constructor function. * * \sa ns3::LteHandoverTargetTestCase */ class LteHandoverTargetTestCase : public TestCase { public: /** * \brief Construct a new test case and providing input parameters for the * simulation. * \param name the name of the test case, to be displayed in the test result * \param uePosition the point in (x, y, z) coordinate where the UE will be * placed in the simulation * \param gridSizeX number of eNodeBs in a row * \param gridSizeY number of eNodeBs in a column * \param sourceCellId the cell ID of the eNodeB which the UE will be * initially attached to in the beginning of simulation, * and also the eNodeB which will "shutdown" in the * middle of simulation * \param targetCellId the cell ID of the expected eNodeB where the UE will * perform handover to after the "shutdown" of the source * cell * \param handoverAlgorithmType the type of handover algorithm to be used in * all eNodeBs */ LteHandoverTargetTestCase (std::string name, Vector uePosition, uint8_t gridSizeX, uint8_t gridSizeY, uint16_t sourceCellId, uint16_t targetCellId, std::string handoverAlgorithmType); virtual ~LteHandoverTargetTestCase (); /** * \brief Triggers when an eNodeB starts a handover and then verifies that * the handover has the right source and target cells. * * The trigger is set up beforehand by connecting to the * `LteEnbRrc::HandoverStart` trace source. * * \param context the context string * \param imsi the IMSI * \param sourceCellId the source cell ID * \param rnti the RNTI * \param targetCellId the target cell ID */ void HandoverStartCallback (std::string context, uint64_t imsi, uint16_t sourceCellId, uint16_t rnti, uint16_t targetCellId); /** * \brief A trigger that can be scheduled to "shutdown" the cell pointed by * `m_sourceCellId` by reducing its power to 1 dB. */ void CellShutdownCallback (); private: /** * \brief Run a simulation of a micro-cell network using the parameters * provided to the constructor function. */ virtual void DoRun (); /** * \brief Called at the end of simulation and verifies that a handover has * occurred in the simulation. */ virtual void DoTeardown (); // simulation parameters Vector m_uePosition; ///< UE positions uint8_t m_gridSizeX; ///< X grid size uint8_t m_gridSizeY; ///< Y grid size uint16_t m_sourceCellId; ///< source cell ID uint16_t m_targetCellId; ///< target cell ID std::string m_handoverAlgorithmType; ///< handover algorithm type Ptr<LteEnbNetDevice> m_sourceEnbDev; ///< source ENB device bool m_hasHandoverOccurred; ///< has handover occurred? }; // end of class LteHandoverTargetTestCase LteHandoverTargetTestCase::LteHandoverTargetTestCase (std::string name, Vector uePosition, uint8_t gridSizeX, uint8_t gridSizeY, uint16_t sourceCellId, uint16_t targetCellId, std::string handoverAlgorithmType) : TestCase (name), m_uePosition (uePosition), m_gridSizeX (gridSizeX), m_gridSizeY (gridSizeY), m_sourceCellId (sourceCellId), m_targetCellId (targetCellId), m_handoverAlgorithmType (handoverAlgorithmType), m_sourceEnbDev (0), m_hasHandoverOccurred (false) { NS_LOG_INFO (this << " name=" << name); // SANITY CHECK uint16_t nEnb = gridSizeX * gridSizeY; if (sourceCellId > nEnb) { NS_FATAL_ERROR ("Invalid source cell ID " << sourceCellId); } if (targetCellId > nEnb) { NS_FATAL_ERROR ("Invalid target cell ID " << targetCellId); } } LteHandoverTargetTestCase::~LteHandoverTargetTestCase () { NS_LOG_FUNCTION (this); } void LteHandoverTargetTestCase::HandoverStartCallback (std::string context, uint64_t imsi, uint16_t sourceCellId, uint16_t rnti, uint16_t targetCellId) { NS_LOG_FUNCTION (this << context << imsi << sourceCellId << rnti << targetCellId); uint64_t timeNowMs = Simulator::Now ().GetMilliSeconds (); NS_TEST_ASSERT_MSG_GT (timeNowMs, 500, "Handover occurred but too early"); NS_TEST_ASSERT_MSG_EQ (sourceCellId, m_sourceCellId, "Handover occurred but with wrong source cell"); NS_TEST_ASSERT_MSG_EQ (targetCellId, m_targetCellId, "Handover occurred but with wrong target cell"); m_hasHandoverOccurred = true; } void LteHandoverTargetTestCase::CellShutdownCallback () { NS_LOG_FUNCTION (this); if (m_sourceEnbDev != 0) { // set the Tx power to 1 dBm NS_ASSERT (m_sourceEnbDev->GetCellId () == m_sourceCellId); NS_LOG_INFO ("Shutting down cell " << m_sourceCellId); Ptr<LteEnbPhy> phy = m_sourceEnbDev->GetPhy (); phy->SetTxPower (1); } } void LteHandoverTargetTestCase::DoRun () { NS_LOG_INFO (this << " " << GetName ()); Config::SetDefault ("ns3::LteEnbPhy::TxPower", DoubleValue (38)); // micro cell Config::SetDefault ("ns3::LteSpectrumPhy::CtrlErrorModelEnabled", BooleanValue (false)); // disable control channel error model Ptr<LteHelper> lteHelper = CreateObject<LteHelper> (); Ptr<PointToPointEpcHelper> epcHelper = CreateObject<PointToPointEpcHelper> (); lteHelper->SetEpcHelper (epcHelper); lteHelper->SetAttribute ("PathlossModel", StringValue ("ns3::FriisSpectrumPropagationLossModel")); lteHelper->SetAttribute ("UseIdealRrc", BooleanValue (true)); if (m_handoverAlgorithmType == "ns3::A2A4RsrqHandoverAlgorithm") { lteHelper->SetHandoverAlgorithmType ("ns3::A2A4RsrqHandoverAlgorithm"); lteHelper->SetHandoverAlgorithmAttribute ("ServingCellThreshold", UintegerValue (30)); lteHelper->SetHandoverAlgorithmAttribute ("NeighbourCellOffset", UintegerValue (1)); } else if (m_handoverAlgorithmType == "ns3::A3RsrpHandoverAlgorithm") { lteHelper->SetHandoverAlgorithmType ("ns3::A3RsrpHandoverAlgorithm"); lteHelper->SetHandoverAlgorithmAttribute ("Hysteresis", DoubleValue (1.5)); lteHelper->SetHandoverAlgorithmAttribute ("TimeToTrigger", TimeValue (MilliSeconds (128))); } else { NS_FATAL_ERROR ("Unknown handover algorithm " << m_handoverAlgorithmType); } // Create Nodes: eNodeB and UE NodeContainer enbNodes; NodeContainer ueNodes; enbNodes.Create (m_gridSizeX * m_gridSizeY); ueNodes.Create (1); /* * The size of the grid is determined by m_gridSizeX and m_gridSizeY. The * following figure is the topology when m_gridSizeX = 4 and m_gridSizeY = 3. * * 9 -- 10 -- 11 -- 12 * | | | | * | | | | * 5 --- 6 --- 7 --- 8 * | | | | * | | | | * (0, 0, 0) ---> 1 --- 2 --- 3 --- 4 * * The grid starts at (0, 0, 0) point on the bottom left corner. The distance * between two adjacent eNodeBs is 130 m. */ // Set up eNodeB position MobilityHelper enbMobility; enbMobility.SetPositionAllocator ("ns3::GridPositionAllocator", "MinX", DoubleValue (0.0), "MinY", DoubleValue (0.0), "DeltaX", DoubleValue (130.0), "DeltaY", DoubleValue (130.0), "GridWidth", UintegerValue (m_gridSizeX), "LayoutType", StringValue ("RowFirst")); enbMobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel"); enbMobility.Install (enbNodes); // Setup UE position Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> (); positionAlloc->Add (m_uePosition); MobilityHelper ueMobility; ueMobility.SetPositionAllocator (positionAlloc); ueMobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel"); ueMobility.Install (ueNodes); // Create P-GW node Ptr<Node> pgw = epcHelper->GetPgwNode (); // Create a single RemoteHost NodeContainer remoteHostContainer; remoteHostContainer.Create (1); Ptr<Node> remoteHost = remoteHostContainer.Get (0); InternetStackHelper internet; internet.Install (remoteHostContainer); // Create the Internet PointToPointHelper p2ph; p2ph.SetDeviceAttribute ("DataRate", DataRateValue (DataRate ("100Gb/s"))); p2ph.SetDeviceAttribute ("Mtu", UintegerValue (1500)); p2ph.SetChannelAttribute ("Delay", TimeValue (Seconds (0.010))); NetDeviceContainer internetDevices = p2ph.Install (pgw, remoteHost); Ipv4AddressHelper ipv4h; ipv4h.SetBase ("1.0.0.0", "255.0.0.0"); Ipv4InterfaceContainer internetIpIfaces = ipv4h.Assign (internetDevices); // Routing of the Internet Host (towards the LTE network) Ipv4StaticRoutingHelper ipv4RoutingHelper; Ptr<Ipv4StaticRouting> remoteHostStaticRouting = ipv4RoutingHelper.GetStaticRouting (remoteHost->GetObject<Ipv4> ()); remoteHostStaticRouting->AddNetworkRouteTo (Ipv4Address ("7.0.0.0"), Ipv4Mask ("255.0.0.0"), 1); // Create Devices and install them in the Nodes (eNB and UE) NetDeviceContainer enbDevs; NetDeviceContainer ueDevs; enbDevs = lteHelper->InstallEnbDevice (enbNodes); ueDevs = lteHelper->InstallUeDevice (ueNodes); // Install the IP stack on the UEs internet.Install (ueNodes); Ipv4InterfaceContainer ueIpIfaces; ueIpIfaces = epcHelper->AssignUeIpv4Address (NetDeviceContainer (ueDevs)); // Assign IP address to UEs for (uint32_t u = 0; u < ueNodes.GetN (); ++u) { Ptr<Node> ueNode = ueNodes.Get (u); // Set the default gateway for the UE Ptr<Ipv4StaticRouting> ueStaticRouting = ipv4RoutingHelper.GetStaticRouting (ueNode->GetObject<Ipv4> ()); ueStaticRouting->SetDefaultRoute (epcHelper->GetUeDefaultGatewayAddress (), 1); } // Add X2 interface lteHelper->AddX2Interface (enbNodes); // Connect to trace sources in all eNodeB Config::Connect ("/NodeList/*/DeviceList/*/LteEnbRrc/HandoverStart", MakeCallback (&LteHandoverTargetTestCase::HandoverStartCallback, this)); // Get the source eNodeB Ptr<NetDevice> sourceEnb = enbDevs.Get (m_sourceCellId - 1); m_sourceEnbDev = sourceEnb->GetObject<LteEnbNetDevice> (); NS_ASSERT (m_sourceEnbDev != 0); NS_ASSERT (m_sourceEnbDev->GetCellId () == m_sourceCellId); // Attach UE to the source eNodeB lteHelper->Attach (ueDevs.Get (0), sourceEnb); // Schedule a "shutdown" of the source eNodeB Simulator::Schedule (Seconds (0.5), &LteHandoverTargetTestCase::CellShutdownCallback, this); // Run simulation Simulator::Stop (Seconds (1)); Simulator::Run (); Simulator::Destroy (); } // end of void LteX2HandoverTargetTestCase::DoRun () void LteHandoverTargetTestCase::DoTeardown () { NS_LOG_FUNCTION (this); NS_TEST_ASSERT_MSG_EQ (m_hasHandoverOccurred, true, "Handover did not occur"); } /** * \brief Test suite ``lte-handover-target``, verifying that handover * algorithms are able to select the right target cell. * * Handover algorithm tested in this test suite: * - A2-A4-RSRQ handover algorithm (ns3::A2A4RsrqHandoverAlgorithm) * - Strongest cell handover algorithm (ns3::A3RsrpHandoverAlgorithm) */ class LteHandoverTargetTestSuite : public TestSuite { public: LteHandoverTargetTestSuite (); }; LteHandoverTargetTestSuite::LteHandoverTargetTestSuite () : TestSuite ("lte-handover-target", SYSTEM) { // LogComponentEnable ("LteHandoverTargetTest", LOG_PREFIX_ALL); // LogComponentEnable ("LteHandoverTargetTest", LOG_LEVEL_ALL); // LogComponentEnable ("A2A4RsrqHandoverAlgorithm", LOG_PREFIX_ALL); // LogComponentEnable ("A2A4RsrqHandoverAlgorithm", LOG_LEVEL_ALL); // LogComponentEnable ("A3RsrpHandoverAlgorithm", LOG_PREFIX_ALL); // LogComponentEnable ("A3RsrpHandoverAlgorithm", LOG_LEVEL_ALL); /* * 3 --- 4 * | | * |o | * 1 --- 2 o = UE */ AddTestCase (new LteHandoverTargetTestCase ("4 cells and A2-A4-RSRQ algorithm", Vector (20, 40, 0), 2, 2, 1, 3, "ns3::A2A4RsrqHandoverAlgorithm"), TestCase::QUICK); AddTestCase (new LteHandoverTargetTestCase ("4 cells and strongest cell algorithm", Vector (20, 40, 0), 2, 2, 1, 3, "ns3::A3RsrpHandoverAlgorithm"), TestCase::QUICK); /* * 4 --- 5 --- 6 * | |o | * | | | * 1 --- 2 --- 3 o = UE */ AddTestCase (new LteHandoverTargetTestCase ("6 cells and A2-A4-RSRQ algorithm", Vector (150, 90, 0), 3, 2, 5, 2, "ns3::A2A4RsrqHandoverAlgorithm"), TestCase::EXTENSIVE); AddTestCase (new LteHandoverTargetTestCase ("6 cells and strongest cell algorithm", Vector (150, 90, 0), 3, 2, 5, 2, "ns3::A3RsrpHandoverAlgorithm"), TestCase::EXTENSIVE); } // end of LteHandoverTargetTestSuite () static LteHandoverTargetTestSuite g_lteHandoverTargetTestSuiteInstance;
pradeepnazareth/NS-3-begining
src/lte/test/test-lte-handover-target.cc
C++
gpl-2.0
16,072
from PyQt5.uic import properties
drnextgis/QGIS
python/PyQt/PyQt5/uic/properties.py
Python
gpl-2.0
33
<?php /** * Date Exception * * PHP version 5 * * Copyright (C) Villanova University 2011. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category VuFind * @package Exceptions * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development Wiki */ namespace VuFind\Exception; /** * Date Exception * * @category VuFind * @package Exceptions * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development Wiki */ class Date extends \Exception { }
ubtue/KrimDok
module/VuFind/src/VuFind/Exception/Date.php
PHP
gpl-2.0
1,319
<?php /** * This class is used for Manages all the options related With Magic Fields * */ class RCCWP_Options { /** * Update the options of Magic Fields * * @params array $options is a array with the options of Magic Fields */ function Update($options) { $options = serialize($options); update_option(RC_CWP_OPTION_KEY, $options); } /** * Get the options of magic fields * * if is not specified a key is return a array with all the options of magic fields * * @param string $key is the name of the option. * */ function Get($key = null) { if (get_option(RC_CWP_OPTION_KEY) == "") return ""; if (is_array(get_option(RC_CWP_OPTION_KEY))) $options = get_option(RC_CWP_OPTION_KEY); else $options = unserialize(get_option(RC_CWP_OPTION_KEY)); if (!empty($key)){ if( isset($options[$key]) ) return $options[$key]; return false; }else{ return $options; } } /** * Save a new value in the options * * @param string $key is the name of the option to will be updated * @param string $val is the new value of the option */ function Set($key, $val) { $options = RCCWP_Options::Get(); $options[$key] = $val; RCCWP_Options::Update($options); } }
matthewbirtch/birtchfarms.com
wp-content/plugins/magic-fields/RCCWP_Options.php
PHP
gpl-2.0
1,237
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2013-2014 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::PhaseIncompressibleTurbulenceModel Description Templated abstract base class for multiphase incompressible turbulence models. SourceFiles PhaseIncompressibleTurbulenceModel.C \*---------------------------------------------------------------------------*/ #ifndef PhaseIncompressibleTurbulenceModel_H #define PhaseIncompressibleTurbulenceModel_H #include "TurbulenceModel.H" #include "incompressibleTurbulenceModel.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class PhaseIncompressibleTurbulenceModel Declaration \*---------------------------------------------------------------------------*/ template<class TransportModel> class PhaseIncompressibleTurbulenceModel : public TurbulenceModel < volScalarField, geometricOneField, incompressibleTurbulenceModel, TransportModel > { public: typedef volScalarField alphaField; typedef geometricOneField rhoField; typedef TransportModel transportModel; // Constructors //- Construct PhaseIncompressibleTurbulenceModel ( const alphaField& alpha, const geometricOneField& rho, const volVectorField& U, const surfaceScalarField& alphaRhoPhi, const surfaceScalarField& phi, const TransportModel& trasportModel, const word& propertiesName ); // Selectors //- Return a reference to the selected turbulence model static autoPtr<PhaseIncompressibleTurbulenceModel> New ( const alphaField& alpha, const volVectorField& U, const surfaceScalarField& alphaRhoPhi, const surfaceScalarField& phi, const TransportModel& trasportModel, const word& propertiesName = turbulenceModel::propertiesName ); //- Destructor virtual ~PhaseIncompressibleTurbulenceModel() {} // Member Functions //- Return the phase-pressure' // (derivative of phase-pressure w.r.t. phase-fraction) virtual tmp<volScalarField> pPrime() const; //- Return the face-phase-pressure' // (derivative of phase-pressure w.r.t. phase-fraction) virtual tmp<surfaceScalarField> pPrimef() const; //- Return the effective stress tensor virtual tmp<volSymmTensorField> devReff() const; //- Return the source term for the momentum equation virtual tmp<fvVectorMatrix> divDevReff(volVectorField& U) const; //- Return the effective stress tensor virtual tmp<volSymmTensorField> devRhoReff() const; //- Return the source term for the momentum equation virtual tmp<fvVectorMatrix> divDevRhoReff(volVectorField& U) const; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifdef NoRepository # include "PhaseIncompressibleTurbulenceModel.C" #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
Atizar/RapidCFD-dev
src/TurbulenceModels/phaseIncompressible/PhaseIncompressibleTurbulenceModel/PhaseIncompressibleTurbulenceModel.H
C++
gpl-3.0
4,433
/*! * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ (function () { describe('startFromFilter', function() { var startFrom; beforeEach(module('piwikApp.filter')); beforeEach(inject(function($injector) { var $filter = $injector.get('$filter'); startFrom = $filter('startFrom'); })); describe('#startFrom()', function() { it('should return all entries if index is zero', function() { var result = startFrom([1,2,3], 0); expect(result).to.eql([1,2,3]); }); it('should return only partial entries if filter is higher than zero', function() { var result = startFrom([1,2,3], 2); expect(result).to.eql([3]); }); it('should return no entries if start is higher than input length', function() { var result = startFrom([1,2,3], 11); expect(result).to.eql([]); }); }); }); })();
befair/soulShape
wp/soulshape.earth/piwik/plugins/CoreHome/angularjs/common/filters/startfrom.spec.js
JavaScript
agpl-3.0
1,121
// Accord Unit Tests // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.Tests.Statistics { using System; using System.Globalization; using Accord.Statistics; using Accord.Statistics.Distributions.Multivariate; using Accord.Statistics.Distributions.Univariate; using NUnit.Framework; [TestFixture] public class NormalDistributionTest { [Test] public void ConstructorTest5() { var normal = new NormalDistribution(mean: 4, stdDev: 4.2); double mean = normal.Mean; // 4.0 double median = normal.Median; // 4.0 double mode = normal.Mode; // 4.0 double var = normal.Variance; // 17.64 double cdf = normal.DistributionFunction(x: 1.4); // 0.26794249453351904 double pdf = normal.ProbabilityDensityFunction(x: 1.4); // 0.078423391448155175 double lpdf = normal.LogProbabilityDensityFunction(x: 1.4); // -2.5456330358182586 double ccdf = normal.ComplementaryDistributionFunction(x: 1.4); // 0.732057505466481 double icdf = normal.InverseDistributionFunction(p: cdf); // 1.4 double hf = normal.HazardFunction(x: 1.4); // 0.10712736480747137 double chf = normal.CumulativeHazardFunction(x: 1.4); // 0.31189620872601354 string str = normal.ToString(CultureInfo.InvariantCulture); // N(x; μ = 4, σ² = 17.64) Assert.AreEqual(4.0, mean); Assert.AreEqual(4.0, median); Assert.AreEqual(4.0, mode); Assert.AreEqual(17.64, var); Assert.AreEqual(0.31189620872601354, chf); Assert.AreEqual(0.26794249453351904, cdf); Assert.AreEqual(0.078423391448155175, pdf); Assert.AreEqual(-2.5456330358182586, lpdf); Assert.AreEqual(0.10712736480747137, hf); Assert.AreEqual(0.732057505466481, ccdf); Assert.AreEqual(1.4, icdf); Assert.AreEqual("N(x; μ = 4, σ² = 17.64)", str); Assert.AreEqual(Accord.Math.Normal.Function(normal.ZScore(4.2)), normal.DistributionFunction(4.2)); Assert.AreEqual(Accord.Math.Normal.Derivative(normal.ZScore(4.2)) / normal.StandardDeviation, normal.ProbabilityDensityFunction(4.2), 1e-16); Assert.AreEqual(Accord.Math.Normal.LogDerivative(normal.ZScore(4.2)) - Math.Log(normal.StandardDeviation), normal.LogProbabilityDensityFunction(4.2), 1e-15); var range1 = normal.GetRange(0.95); var range2 = normal.GetRange(0.99); var range3 = normal.GetRange(0.01); Assert.AreEqual(-2.9083852331961833, range1.Min); Assert.AreEqual(10.908385233196183, range1.Max); Assert.AreEqual(-5.7706610709715314, range2.Min); Assert.AreEqual(13.770661070971531, range2.Max); Assert.AreEqual(-5.7706610709715314, range3.Min); Assert.AreEqual(13.770661070971531, range3.Max); } [Test] public void FitTest() { double expectedMean = 1.125; double expectedSigma = 1.01775897605147; NormalDistribution target; target = new NormalDistribution(); double[] observations = { 0.10, 0.40, 2.00, 2.00 }; double[] weights = { 0.25, 0.25, 0.25, 0.25 }; target.Fit(observations, weights); Assert.AreEqual(expectedMean, target.Mean); Assert.AreEqual(expectedSigma, target.StandardDeviation, 1e-6); target = new NormalDistribution(); double[] observations2 = { 0.10, 0.10, 0.40, 2.00 }; double[] weights2 = { 0.125, 0.125, 0.25, 0.50 }; target.Fit(observations2, weights2); Assert.AreEqual(expectedMean, target.Mean); } [Test] public void FitTest2() { NormalDistribution target; target = new NormalDistribution(); double[] observations = { 1, 1, 1, 1 }; bool thrown = false; try { target.Fit(observations); } catch (ArgumentException) { thrown = true; } Assert.IsTrue(thrown); } [Test] public void ConstructorTest() { double mean = 7; double dev = 5; double var = 25; NormalDistribution target = new NormalDistribution(mean, dev); Assert.AreEqual(mean, target.Mean); Assert.AreEqual(dev, target.StandardDeviation); Assert.AreEqual(var, target.Variance); target = new NormalDistribution(); Assert.AreEqual(0, target.Mean); Assert.AreEqual(1, target.StandardDeviation); Assert.AreEqual(1, target.Variance); target = new NormalDistribution(3); Assert.AreEqual(3, target.Mean); Assert.AreEqual(1, target.StandardDeviation); Assert.AreEqual(1, target.Variance); } [Test] public void ConstructorTest2() { bool thrown = false; try { NormalDistribution target = new NormalDistribution(4.2, 0); } catch (ArgumentOutOfRangeException) { thrown = true; } Assert.IsTrue(thrown); } [Test] public void ConstructorTest3() { Accord.Math.Tools.SetupGenerator(0); // Create a normal distribution with mean 2 and sigma 3 var normal = new NormalDistribution(mean: 2, stdDev: 3); // In a normal distribution, the median and // the mode coincide with the mean, so double mean = normal.Mean; // 2 double mode = normal.Mode; // 2 double median = normal.Median; // 2 // The variance is the square of the standard deviation double variance = normal.Variance; // 3² = 9 // Let's check what is the cumulative probability of // a value less than 3 occurring in this distribution: double cdf = normal.DistributionFunction(3); // 0.63055 // Finally, let's generate 1000 samples from this distribution // and check if they have the specified mean and standard dev. double[] samples = normal.Generate(1000); double sampleMean = samples.Mean(); // 1.92 double sampleDev = samples.StandardDeviation(); // 3.00 Assert.AreEqual(2, mean); Assert.AreEqual(2, mode); Assert.AreEqual(2, median); Assert.AreEqual(9, variance); Assert.AreEqual(1000, samples.Length); Assert.AreEqual(1.9245, sampleMean, 1e-4); Assert.AreEqual(3.0008, sampleDev, 1e-4); } [Test] public void ProbabilityDensityFunctionTest() { double x = 3; double mean = 7; double dev = 5; NormalDistribution target = new NormalDistribution(mean, dev); double expected = 0.0579383105522966; double actual = target.ProbabilityDensityFunction(x); Assert.IsFalse(double.IsNaN(actual)); Assert.AreEqual(expected, actual, 1e-15); } [Test] public void ToMultivariateTest() { double x = 3; double mean = 7; double dev = 5; NormalDistribution target = new NormalDistribution(mean, dev); MultivariateNormalDistribution multi = target.ToMultivariateDistribution(); Assert.AreEqual(target.Mean, multi.Mean[0]); Assert.AreEqual(target.Variance, multi.Covariance[0, 0]); Assert.AreEqual(target.Variance, multi.Variance[0]); double expected = 0.0579383105522966; double actual = multi.ProbabilityDensityFunction(x); Assert.IsFalse(double.IsNaN(actual)); Assert.AreEqual(expected, actual, 1e-15); } [Test] public void ProbabilityDensityFunctionTest2() { double expected, actual; // Test for small variance NormalDistribution target = new NormalDistribution(4.2, double.Epsilon); expected = 0; actual = target.ProbabilityDensityFunction(0); Assert.AreEqual(expected, actual); expected = double.PositiveInfinity; actual = target.ProbabilityDensityFunction(4.2); Assert.AreEqual(expected, actual); } [Test] public void LogProbabilityDensityFunctionTest() { double x = 3; double mean = 7; double dev = 5; NormalDistribution target = new NormalDistribution(mean, dev); double expected = System.Math.Log(0.0579383105522966); double actual = target.LogProbabilityDensityFunction(x); Assert.IsFalse(double.IsNaN(actual)); Assert.AreEqual(expected, actual, 1e-15); } [Test] public void StandardDensityFunctionTest() { for (int i = -100; i < 100; i++) { double x = i / 100.0; double expected = Accord.Math.Normal.Derivative(x); double actual = NormalDistribution.Standard.ProbabilityDensityFunction(x); Assert.AreEqual(expected, actual); } } [Test] public void LogStandardDensityFunctionTest() { for (int i = -100; i < 100; i++) { double x = i / 100.0; double expected = Accord.Math.Normal.LogDerivative(x); double actual = NormalDistribution.Standard.LogProbabilityDensityFunction(x); Assert.AreEqual(expected, actual); } } [Test] public void DistributionFunctionTest() { double x = 3; double mean = 7; double dev = 5; NormalDistribution target = new NormalDistribution(mean, dev); double expected = 0.211855398583397; double actual = target.DistributionFunction(x); Assert.IsFalse(double.IsNaN(actual)); Assert.AreEqual(expected, actual, 1e-15); } [Test] public void DistributionFunctionTest3() { double expected, actual; // Test small variance NormalDistribution target = new NormalDistribution(1.0, double.Epsilon); expected = 0; actual = target.DistributionFunction(0); Assert.AreEqual(expected, actual); expected = 0.5; actual = target.DistributionFunction(1.0); Assert.AreEqual(expected, actual); expected = 1.0; actual = target.DistributionFunction(1.0 + 1e-15); Assert.AreEqual(expected, actual); expected = 0.0; actual = target.DistributionFunction(1.0 - 1e-15); Assert.AreEqual(expected, actual); } [Test] public void InverseDistributionFunctionTest() { double[] expected = { Double.NegativeInfinity, -4.38252, -2.53481, -1.20248, -0.0640578, 1.0, 2.06406, 3.20248, 4.53481, 6.38252, Double.PositiveInfinity }; NormalDistribution target = new NormalDistribution(1.0, 4.2); for (int i = 0; i < expected.Length; i++) { double x = i / 10.0; double actual = target.InverseDistributionFunction(x); Assert.AreEqual(expected[i], actual, 1e-5); Assert.IsFalse(Double.IsNaN(actual)); } } [Test] public void ZScoreTest() { double x = 5; double mean = 3; double dev = 6; NormalDistribution target = new NormalDistribution(mean, dev); double expected = (x - 3) / 6; double actual = target.ZScore(x); Assert.AreEqual(expected, actual); } [Test] public void CloneTest() { NormalDistribution target = new NormalDistribution(0.5, 4.2); NormalDistribution clone = (NormalDistribution)target.Clone(); Assert.AreNotSame(target, clone); Assert.AreEqual(target.Entropy, clone.Entropy); Assert.AreEqual(target.Mean, clone.Mean); Assert.AreEqual(target.StandardDeviation, clone.StandardDeviation); Assert.AreEqual(target.Variance, clone.Variance); } [Test] public void GenerateTest() { NormalDistribution target = new NormalDistribution(2, 5); double[] samples = target.Generate(1000000); var actual = NormalDistribution.Estimate(samples); Assert.AreEqual(2, actual.Mean, 0.01); Assert.AreEqual(5, actual.StandardDeviation, 0.01); } [Test] public void GenerateTest2() { NormalDistribution target = new NormalDistribution(4, 2); double[] samples = new double[1000000]; for (int i = 0; i < samples.Length; i++) samples[i] = target.Generate(); var actual = NormalDistribution.Estimate(samples); actual.Fit(samples); Assert.AreEqual(4, actual.Mean, 0.01); Assert.AreEqual(2, actual.StandardDeviation, 0.01); } [Test] public void MedianTest() { NormalDistribution target = new NormalDistribution(0.4, 2.2); Assert.AreEqual(target.Median, target.InverseDistributionFunction(0.5)); } [Test] public void EstimateTest() { double[] values = { 1 }; bool thrown = false; try { NormalDistribution.Estimate(values); } catch (ArgumentException) { thrown = true; } Assert.IsTrue(thrown); } } }
AnnaPeng/framework
Unit Tests/Accord.Tests.Statistics/Distributions/Univariate/Continuous/NormalDistributionTest.cs
C#
lgpl-2.1
15,010
// AForge Image Processing Library // AForge.NET framework // http://www.aforgenet.com/framework/ // // Copyright © Andrew Kirillov, 2005-2010 // andrew.kirillov@aforgenet.com // namespace AForge.Imaging.Filters { using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using AForge; /// <summary> /// Linear correction of RGB channels. /// </summary> /// /// <remarks><para>The filter performs linear correction of RGB channels by mapping specified /// channels' input ranges to output ranges. It is similar to the /// <see cref="ColorRemapping"/>, but the remapping is linear.</para> /// /// <para>The filter accepts 8 bpp grayscale and 24/32 bpp color images for processing.</para> /// /// <para>Sample usage:</para> /// <code> /// // create filter /// LevelsLinear filter = new LevelsLinear( ); /// // set ranges /// filter.InRed = new IntRange( 30, 230 ); /// filter.InGreen = new IntRange( 50, 240 ); /// filter.InBlue = new IntRange( 10, 210 ); /// // apply the filter /// filter.ApplyInPlace( image ); /// </code> /// /// <para><b>Initial image:</b></para> /// <img src="img/imaging/sample1.jpg" width="480" height="361" /> /// <para><b>Result image:</b></para> /// <img src="img/imaging/levels_linear.jpg" width="480" height="361" /> /// </remarks> /// /// <seealso cref="HSLLinear"/> /// <seealso cref="YCbCrLinear"/> /// public class LevelsLinear : BaseInPlacePartialFilter { private IntRange inRed = new IntRange(0, 255); private IntRange inGreen = new IntRange(0, 255); private IntRange inBlue = new IntRange(0, 255); private IntRange outRed = new IntRange(0, 255); private IntRange outGreen = new IntRange(0, 255); private IntRange outBlue = new IntRange(0, 255); private byte[] mapRed = new byte[256]; private byte[] mapGreen = new byte[256]; private byte[] mapBlue = new byte[256]; // private format translation dictionary private Dictionary<PixelFormat, PixelFormat> formatTranslations = new Dictionary<PixelFormat, PixelFormat>(); /// <summary> /// Format translations dictionary. /// </summary> public override Dictionary<PixelFormat, PixelFormat> FormatTranslations { get { return formatTranslations; } } #region Public Propertis /// <summary> /// Red component's input range. /// </summary> public IntRange InRed { get { return inRed; } set { inRed = value; CalculateMap(inRed, outRed, mapRed); } } /// <summary> /// Green component's input range. /// </summary> public IntRange InGreen { get { return inGreen; } set { inGreen = value; CalculateMap(inGreen, outGreen, mapGreen); } } /// <summary> /// Blue component's input range. /// </summary> public IntRange InBlue { get { return inBlue; } set { inBlue = value; CalculateMap(inBlue, outBlue, mapBlue); } } /// <summary> /// Gray component's input range. /// </summary> public IntRange InGray { get { return inGreen; } set { inGreen = value; CalculateMap(inGreen, outGreen, mapGreen); } } /// <summary> /// Input range for RGB components. /// </summary> /// /// <remarks>The property allows to set red, green and blue input ranges to the same value.</remarks> /// public IntRange Input { set { inRed = inGreen = inBlue = value; CalculateMap(inRed, outRed, mapRed); CalculateMap(inGreen, outGreen, mapGreen); CalculateMap(inBlue, outBlue, mapBlue); } } /// <summary> /// Red component's output range. /// </summary> public IntRange OutRed { get { return outRed; } set { outRed = value; CalculateMap(inRed, outRed, mapRed); } } /// <summary> /// Green component's output range. /// </summary> public IntRange OutGreen { get { return outGreen; } set { outGreen = value; CalculateMap(inGreen, outGreen, mapGreen); } } /// <summary> /// Blue component's output range. /// </summary> public IntRange OutBlue { get { return outBlue; } set { outBlue = value; CalculateMap(inBlue, outBlue, mapBlue); } } /// <summary> /// Gray component's output range. /// </summary> public IntRange OutGray { get { return outGreen; } set { outGreen = value; CalculateMap(inGreen, outGreen, mapGreen); } } /// <summary> /// Output range for RGB components. /// </summary> /// /// <remarks>The property allows to set red, green and blue output ranges to the same value.</remarks> /// public IntRange Output { set { outRed = outGreen = outBlue = value; CalculateMap(inRed, outRed, mapRed); CalculateMap(inGreen, outGreen, mapGreen); CalculateMap(inBlue, outBlue, mapBlue); } } #endregion /// <summary> /// Initializes a new instance of the <see cref="LevelsLinear"/> class. /// </summary> public LevelsLinear() { CalculateMap(inRed, outRed, mapRed); CalculateMap(inGreen, outGreen, mapGreen); CalculateMap(inBlue, outBlue, mapBlue); formatTranslations[PixelFormat.Format8bppIndexed] = PixelFormat.Format8bppIndexed; formatTranslations[PixelFormat.Format24bppRgb] = PixelFormat.Format24bppRgb; formatTranslations[PixelFormat.Format32bppRgb] = PixelFormat.Format32bppRgb; formatTranslations[PixelFormat.Format32bppArgb] = PixelFormat.Format32bppArgb; } /// <summary> /// Process the filter on the specified image. /// </summary> /// /// <param name="image">Source image data.</param> /// <param name="rect">Image rectangle for processing by the filter.</param> /// protected override unsafe void ProcessFilter(UnmanagedImage image, Rectangle rect) { int pixelSize = Image.GetPixelFormatSize(image.PixelFormat) / 8; // processing start and stop X,Y positions int startX = rect.Left; int startY = rect.Top; int stopX = startX + rect.Width; int stopY = startY + rect.Height; int offset = image.Stride - rect.Width * pixelSize; // do the job byte* ptr = (byte*)image.ImageData.ToPointer(); // allign pointer to the first pixel to process ptr += (startY * image.Stride + startX * pixelSize); if (image.PixelFormat == PixelFormat.Format8bppIndexed) { // grayscale image for (int y = startY; y < stopY; y++) { for (int x = startX; x < stopX; x++, ptr++) { // gray *ptr = mapGreen[*ptr]; } ptr += offset; } } else { // RGB image for (int y = startY; y < stopY; y++) { for (int x = startX; x < stopX; x++, ptr += pixelSize) { // red ptr[RGB.R] = mapRed[ptr[RGB.R]]; // green ptr[RGB.G] = mapGreen[ptr[RGB.G]]; // blue ptr[RGB.B] = mapBlue[ptr[RGB.B]]; } ptr += offset; } } } /// <summary> /// Calculate conversion map. /// </summary> /// /// <param name="inRange">Input range.</param> /// <param name="outRange">Output range.</param> /// <param name="map">Conversion map.</param> /// private static void CalculateMap(IntRange inRange, IntRange outRange, byte[] map) { double k = 0, b = 0; if (inRange.Max != inRange.Min) { k = (double)(outRange.Max - outRange.Min) / (double)(inRange.Max - inRange.Min); b = (double)(outRange.Min) - k * inRange.Min; } for (int i = 0; i < 256; i++) { byte v = (byte)i; if (v >= inRange.Max) v = (byte)outRange.Max; else if (v <= inRange.Min) v = (byte)outRange.Min; else v = (byte)(k * v + b); map[i] = v; } } } }
AnnaPeng/framework
Sources/Accord.Imaging/AForge/Filters/Color Filters/LevelsLinear.cs
C#
lgpl-2.1
10,124
/** * Vosao CMS. Simple CMS for Google App Engine. * * Copyright (C) 2009-2010 Vosao development team. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * email: vosao.dev@gmail.com */ package org.vosao.business; import java.util.Date; import java.util.List; import org.apache.velocity.VelocityContext; import org.vosao.business.decorators.TreeItemDecorator; import org.vosao.business.page.PageRenderDecorator; import org.vosao.entity.ContentEntity; import org.vosao.entity.FolderEntity; import org.vosao.entity.PageEntity; import org.vosao.entity.StructureTemplateEntity; import org.vosao.entity.UserEntity; import org.vosao.velocity.VelocityPluginService; import org.vosao.velocity.VelocityService; public interface PageBusiness { /** * Security filtered dao version. * @return found page. */ PageEntity getById(final Long id); /** * Security filtered dao version. * @return list of pages. */ List<PageEntity> select(); /** * Security filtered dao version. * @return found page. */ PageEntity getByUrl(final String url); /** * Security filtered dao version. * @return list of pages. */ List<PageEntity> getByParent(final String url); /** * Security filtered dao version. * @return list of pages. */ List<PageEntity> getByParentApproved(final String url); /** * Security filtered dao version. * @return list of pages. */ List<PageEntity> getByParentApproved(final String url, Date startDate, Date endDate); /** * Security filtered dao version. */ void remove(final List<Long> ids); /** * Security filtered dao version. */ void removeVersion(Long id); /** * Security filtered dao version. */ List<ContentEntity> getContents(final Long pageId); /** * Security filtered dao version. */ List<PageEntity> selectByUrl(final String url); /** * With added business processing dao version. */ void save(PageEntity page); TreeItemDecorator<PageEntity> getTree(final List<PageEntity> pages); TreeItemDecorator<PageEntity> getTree(); /** * Render page with page bound template. With applied postProcessing and * using PageRenderDecorator. * @param page - page to render. * @param languageCode - language code. * @return rendered html. */ String render(final PageEntity page, final String languageCode); /** * Render page using provided template. With applied postProcessing and * using PageRenderDecorator. * @param page - page to render. * @param template - page template. * @param languageCode - language code. * @return rendered html. */ String render(final PageEntity page, final String tempate, final String languageCode); VelocityContext createContext(final String languageCode, PageEntity page); PageRenderDecorator createPageRenderDecorator(final PageEntity page, final String languageCode); PageRenderDecorator createStructuredPageRenderDecorator( final PageEntity page, final String languageCode, StructureTemplateEntity template); List<String> validateBeforeUpdate(final PageEntity page); ContentEntity getPageContent(final PageEntity page, final String languageCode); /** * Add new version of specified page. * @param oldPage - page to create version from. */ PageEntity addVersion(final PageEntity oldPage, final Integer version, final String versionTitle, final UserEntity user); boolean canChangeContent(String url, String languageCode); /** * Save page content and update search index. * @param page * @param content * @param language */ void saveContent(PageEntity page, String language, String content); /** * Get next sort index for new page. * @param friendlyURL - new page url. */ Integer getNextSortIndex(final String friendlyURL); /** * Move page down in sort order. * @param page */ void moveDown(PageEntity page); /** * Move page up in sort order. * @param page */ void moveUp(PageEntity page); /** * Place page after refPage in sort order. * @param page * @param refPage */ void moveAfter(PageEntity page, PageEntity refPage); /** * Place page before refPage in sort order. * @param page * @param refPage */ void moveBefore(PageEntity page, PageEntity refPage); VelocityService getVelocityService(); VelocityPluginService getVelocityPluginService(); /** * Remove page by URL with all subpages and page resouces. */ void remove(String pageURL); /** * Check for free url and if not then add suffix number. * @param url - url to check * @return - free page friendly URL. */ String makeUniquePageURL(String url); /** * Move page to new friendlyURL. Also change friendlyURL recursively * for all children pages. * @param page - page to change. * @param friendlyURL - new friendlyURL. */ void move(PageEntity page, String friendlyURL); /** * Copy page with subpages to new parent URL. */ void copy(PageEntity page, String parentURL); void addVelocityTools(VelocityContext context); /** * Find or create default child page for given parent page url. Every page has default * settings page for children with url "/_default". * @param url - parent page url. * @return - found or created default page. */ PageEntity getPageDefaultSettings(String url); /** * Set default values from parent default page. * @param page - page to set default values from parent. */ void setDefaultValues(PageEntity page); /** * Create/update page content to parent default content. * @param page - page to set/update content. */ void updateDefaultContent(PageEntity page); FolderEntity getPageFolder(String pageURL); PageEntity getRestPage(String url); }
vosaocms/vosao
api/src/org/vosao/business/PageBusiness.java
Java
lgpl-2.1
6,389
namespace AForge.Video.DirectShow { partial class VideoCaptureDeviceForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cancelButton = new System.Windows.Forms.Button(); this.okButton = new System.Windows.Forms.Button(); this.devicesCombo = new System.Windows.Forms.ComboBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.videoInputsCombo = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.snapshotsLabel = new System.Windows.Forms.Label(); this.snapshotResolutionsCombo = new System.Windows.Forms.ComboBox(); this.videoResolutionsCombo = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.pictureBox = new System.Windows.Forms.PictureBox(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); this.SuspendLayout(); // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.cancelButton.Location = new System.Drawing.Point(358, 292); this.cancelButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(112, 35); this.cancelButton.TabIndex = 11; this.cancelButton.Text = "Cancel"; // // okButton // this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.okButton.FlatStyle = System.Windows.Forms.FlatStyle.System; this.okButton.Location = new System.Drawing.Point(224, 292); this.okButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(112, 35); this.okButton.TabIndex = 10; this.okButton.Text = "OK"; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // devicesCombo // this.devicesCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.devicesCombo.FormattingEnabled = true; this.devicesCombo.Location = new System.Drawing.Point(150, 62); this.devicesCombo.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.devicesCombo.Name = "devicesCombo"; this.devicesCombo.Size = new System.Drawing.Size(486, 28); this.devicesCombo.TabIndex = 9; this.devicesCombo.SelectedIndexChanged += new System.EventHandler(this.devicesCombo_SelectedIndexChanged); // // groupBox1 // this.groupBox1.Controls.Add(this.videoInputsCombo); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.snapshotsLabel); this.groupBox1.Controls.Add(this.snapshotResolutionsCombo); this.groupBox1.Controls.Add(this.videoResolutionsCombo); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.pictureBox); this.groupBox1.Controls.Add(this.devicesCombo); this.groupBox1.Location = new System.Drawing.Point(15, 15); this.groupBox1.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.groupBox1.Name = "groupBox1"; this.groupBox1.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); this.groupBox1.Size = new System.Drawing.Size(660, 254); this.groupBox1.TabIndex = 12; this.groupBox1.TabStop = false; this.groupBox1.Text = "Video capture device settings"; // // videoInputsCombo // this.videoInputsCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.videoInputsCombo.FormattingEnabled = true; this.videoInputsCombo.Location = new System.Drawing.Point(150, 200); this.videoInputsCombo.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.videoInputsCombo.Name = "videoInputsCombo"; this.videoInputsCombo.Size = new System.Drawing.Size(223, 28); this.videoInputsCombo.TabIndex = 17; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(150, 177); this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(93, 20); this.label3.TabIndex = 16; this.label3.Text = "Video input:"; // // snapshotsLabel // this.snapshotsLabel.AutoSize = true; this.snapshotsLabel.Location = new System.Drawing.Point(412, 108); this.snapshotsLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.snapshotsLabel.Name = "snapshotsLabel"; this.snapshotsLabel.Size = new System.Drawing.Size(152, 20); this.snapshotsLabel.TabIndex = 15; this.snapshotsLabel.Text = "Snapshot resoluton:"; // // snapshotResolutionsCombo // this.snapshotResolutionsCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.snapshotResolutionsCombo.FormattingEnabled = true; this.snapshotResolutionsCombo.Location = new System.Drawing.Point(412, 131); this.snapshotResolutionsCombo.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.snapshotResolutionsCombo.Name = "snapshotResolutionsCombo"; this.snapshotResolutionsCombo.Size = new System.Drawing.Size(223, 28); this.snapshotResolutionsCombo.TabIndex = 14; // // videoResolutionsCombo // this.videoResolutionsCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.videoResolutionsCombo.FormattingEnabled = true; this.videoResolutionsCombo.Location = new System.Drawing.Point(150, 131); this.videoResolutionsCombo.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.videoResolutionsCombo.Name = "videoResolutionsCombo"; this.videoResolutionsCombo.Size = new System.Drawing.Size(223, 28); this.videoResolutionsCombo.TabIndex = 13; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(150, 108); this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(124, 20); this.label2.TabIndex = 12; this.label2.Text = "Video resoluton:"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(150, 38); this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(103, 20); this.label1.TabIndex = 11; this.label1.Text = "Video device:"; // // pictureBox // this.pictureBox.Image = global::Accord.Video.DirectShow.Properties.Resources.camera; this.pictureBox.Location = new System.Drawing.Point(30, 43); this.pictureBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.pictureBox.Name = "pictureBox"; this.pictureBox.Size = new System.Drawing.Size(96, 98); this.pictureBox.TabIndex = 10; this.pictureBox.TabStop = false; // // VideoCaptureDeviceForm // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(144F, 144F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(693, 340); this.Controls.Add(this.groupBox1); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okButton); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.Name = "VideoCaptureDeviceForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Open local video capture device"; this.Load += new System.EventHandler(this.VideoCaptureDeviceForm_Load); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button okButton; private System.Windows.Forms.ComboBox devicesCombo; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.PictureBox pictureBox; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label snapshotsLabel; private System.Windows.Forms.ComboBox snapshotResolutionsCombo; private System.Windows.Forms.ComboBox videoResolutionsCombo; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox videoInputsCombo; private System.Windows.Forms.Label label3; } }
AnnaPeng/framework
Sources/Accord.Video.DirectShow/VideoCaptureDeviceForm.Designer.cs
C#
lgpl-2.1
11,285
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * 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@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_Adminhtml * @copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Product attribute add/edit form main tab * * @category Mage * @package Mage_Adminhtml * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Adminhtml_Block_Catalog_Product_Attribute_Edit_Tab_Main extends Mage_Eav_Block_Adminhtml_Attribute_Edit_Main_Abstract { /** * Adding product form elements for editing attribute * * @return Mage_Adminhtml_Block_Catalog_Product_Attribute_Edit_Tab_Main */ protected function _prepareForm() { parent::_prepareForm(); $attributeObject = $this->getAttributeObject(); /* @var $form Varien_Data_Form */ $form = $this->getForm(); /* @var $fieldset Varien_Data_Form_Element_Fieldset */ $fieldset = $form->getElement('base_fieldset'); $frontendInputElm = $form->getElement('frontend_input'); $additionalTypes = array( array( 'value' => 'price', 'label' => Mage::helper('catalog')->__('Price') ), array( 'value' => 'media_image', 'label' => Mage::helper('catalog')->__('Media Image') ) ); if ($attributeObject->getFrontendInput() == 'gallery') { $additionalTypes[] = array( 'value' => 'gallery', 'label' => Mage::helper('catalog')->__('Gallery') ); } $response = new Varien_Object(); $response->setTypes(array()); Mage::dispatchEvent('adminhtml_product_attribute_types', array('response'=>$response)); $_disabledTypes = array(); $_hiddenFields = array(); foreach ($response->getTypes() as $type) { $additionalTypes[] = $type; if (isset($type['hide_fields'])) { $_hiddenFields[$type['value']] = $type['hide_fields']; } if (isset($type['disabled_types'])) { $_disabledTypes[$type['value']] = $type['disabled_types']; } } Mage::register('attribute_type_hidden_fields', $_hiddenFields); Mage::register('attribute_type_disabled_types', $_disabledTypes); $frontendInputValues = array_merge($frontendInputElm->getValues(), $additionalTypes); $frontendInputElm->setValues($frontendInputValues); $yesnoSource = Mage::getModel('adminhtml/system_config_source_yesno')->toOptionArray(); $scopes = array( Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE =>Mage::helper('catalog')->__('Store View'), Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_WEBSITE =>Mage::helper('catalog')->__('Website'), Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL =>Mage::helper('catalog')->__('Global'), ); if ($attributeObject->getAttributeCode() == 'status' || $attributeObject->getAttributeCode() == 'tax_class_id') { unset($scopes[Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE]); } $fieldset->addField('is_global', 'select', array( 'name' => 'is_global', 'label' => Mage::helper('catalog')->__('Scope'), 'title' => Mage::helper('catalog')->__('Scope'), 'note' => Mage::helper('catalog')->__('Declare attribute value saving scope'), 'values'=> $scopes ), 'attribute_code'); $fieldset->addField('apply_to', 'apply', array( 'name' => 'apply_to[]', 'label' => Mage::helper('catalog')->__('Apply To'), 'values' => Mage_Catalog_Model_Product_Type::getOptions(), 'mode_labels' => array( 'all' => Mage::helper('catalog')->__('All Product Types'), 'custom' => Mage::helper('catalog')->__('Selected Product Types') ), 'required' => true ), 'frontend_class'); $fieldset->addField('is_configurable', 'select', array( 'name' => 'is_configurable', 'label' => Mage::helper('catalog')->__('Use To Create Configurable Product'), 'values' => $yesnoSource, ), 'apply_to'); // frontend properties fieldset $fieldset = $form->addFieldset('front_fieldset', array('legend'=>Mage::helper('catalog')->__('Frontend Properties'))); $fieldset->addField('is_searchable', 'select', array( 'name' => 'is_searchable', 'label' => Mage::helper('catalog')->__('Use in Quick Search'), 'title' => Mage::helper('catalog')->__('Use in Quick Search'), 'values' => $yesnoSource, )); $fieldset->addField('is_visible_in_advanced_search', 'select', array( 'name' => 'is_visible_in_advanced_search', 'label' => Mage::helper('catalog')->__('Use in Advanced Search'), 'title' => Mage::helper('catalog')->__('Use in Advanced Search'), 'values' => $yesnoSource, )); $fieldset->addField('is_comparable', 'select', array( 'name' => 'is_comparable', 'label' => Mage::helper('catalog')->__('Comparable on Front-end'), 'title' => Mage::helper('catalog')->__('Comparable on Front-end'), 'values' => $yesnoSource, )); $fieldset->addField('is_filterable', 'select', array( 'name' => 'is_filterable', 'label' => Mage::helper('catalog')->__("Use In Layered Navigation"), 'title' => Mage::helper('catalog')->__('Can be used only with catalog input type Dropdown, Multiple Select and Price'), 'note' => Mage::helper('catalog')->__('Can be used only with catalog input type Dropdown, Multiple Select and Price'), 'values' => array( array('value' => '0', 'label' => Mage::helper('catalog')->__('No')), array('value' => '1', 'label' => Mage::helper('catalog')->__('Filterable (with results)')), array('value' => '2', 'label' => Mage::helper('catalog')->__('Filterable (no results)')), ), )); $fieldset->addField('is_filterable_in_search', 'select', array( 'name' => 'is_filterable_in_search', 'label' => Mage::helper('catalog')->__("Use In Search Results Layered Navigation"), 'title' => Mage::helper('catalog')->__('Can be used only with catalog input type Dropdown, Multiple Select and Price'), 'note' => Mage::helper('catalog')->__('Can be used only with catalog input type Dropdown, Multiple Select and Price'), 'values' => $yesnoSource, )); $fieldset->addField('is_used_for_promo_rules', 'select', array( 'name' => 'is_used_for_promo_rules', 'label' => Mage::helper('catalog')->__('Use for Promo Rule Conditions'), 'title' => Mage::helper('catalog')->__('Use for Promo Rule Conditions'), 'values' => $yesnoSource, )); $fieldset->addField('position', 'text', array( 'name' => 'position', 'label' => Mage::helper('catalog')->__('Position'), 'title' => Mage::helper('catalog')->__('Position in Layered Navigation'), 'note' => Mage::helper('catalog')->__('Position of attribute in layered navigation block'), 'class' => 'validate-digits', )); $fieldset->addField('is_wysiwyg_enabled', 'select', array( 'name' => 'is_wysiwyg_enabled', 'label' => Mage::helper('catalog')->__('Enable WYSIWYG'), 'title' => Mage::helper('catalog')->__('Enable WYSIWYG'), 'values' => $yesnoSource, )); $htmlAllowed = $fieldset->addField('is_html_allowed_on_front', 'select', array( 'name' => 'is_html_allowed_on_front', 'label' => Mage::helper('catalog')->__('Allow HTML Tags on Frontend'), 'title' => Mage::helper('catalog')->__('Allow HTML Tags on Frontend'), 'values' => $yesnoSource, )); if (!$attributeObject->getId() || $attributeObject->getIsWysiwygEnabled()) { $attributeObject->setIsHtmlAllowedOnFront(1); } $fieldset->addField('is_visible_on_front', 'select', array( 'name' => 'is_visible_on_front', 'label' => Mage::helper('catalog')->__('Visible on Product View Page on Front-end'), 'title' => Mage::helper('catalog')->__('Visible on Product View Page on Front-end'), 'values' => $yesnoSource, )); $fieldset->addField('used_in_product_listing', 'select', array( 'name' => 'used_in_product_listing', 'label' => Mage::helper('catalog')->__('Used in Product Listing'), 'title' => Mage::helper('catalog')->__('Used in Product Listing'), 'note' => Mage::helper('catalog')->__('Depends on design theme'), 'values' => $yesnoSource, )); $fieldset->addField('used_for_sort_by', 'select', array( 'name' => 'used_for_sort_by', 'label' => Mage::helper('catalog')->__('Used for Sorting in Product Listing'), 'title' => Mage::helper('catalog')->__('Used for Sorting in Product Listing'), 'note' => Mage::helper('catalog')->__('Depends on design theme'), 'values' => $yesnoSource, )); $form->getElement('apply_to')->setSize(5); if ($applyTo = $attributeObject->getApplyTo()) { $applyTo = is_array($applyTo) ? $applyTo : explode(',', $applyTo); $form->getElement('apply_to')->setValue($applyTo); } else { $form->getElement('apply_to')->addClass('no-display ignore-validate'); } // define field dependencies $this->setChild('form_after', $this->getLayout()->createBlock('adminhtml/widget_form_element_dependence') ->addFieldMap("is_wysiwyg_enabled", 'wysiwyg_enabled') ->addFieldMap("is_html_allowed_on_front", 'html_allowed_on_front') ->addFieldMap("frontend_input", 'frontend_input_type') ->addFieldDependence('wysiwyg_enabled', 'frontend_input_type', 'textarea') ->addFieldDependence('html_allowed_on_front', 'wysiwyg_enabled', '0') ); Mage::dispatchEvent('adminhtml_catalog_product_attribute_edit_prepare_form', array( 'form' => $form, 'attribute' => $attributeObject )); return $this; } /** * Retrieve additional element types for product attributes * * @return array */ protected function _getAdditionalElementTypes() { return array( 'apply' => Mage::getConfig()->getBlockClassName('adminhtml/catalog_product_helper_form_apply'), ); } }
dbashyal/MagentoStarterBase
trunk/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Edit/Tab/Main.php
PHP
lgpl-3.0
11,823
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OfficeDevPnP.Core; using Contoso.Provisioning.Hybrid.Contract; using System.IO; using System.Diagnostics; using Microsoft.SharePoint.Client; using OfficeDevPnP.Core.Entities; using Microsoft.WindowsAzure.ServiceRuntime; using System.Configuration; namespace Contoso.Provisioning.Hybrid.Core.SiteTemplates { public abstract class SiteProvisioningBase { ClientContext appOnlyClientContext = null; ClientContext createdSiteContext = null; ClientContext siteDirectorySiteContext = null; /// <summary> /// Returns the app only client context (the one with tenant level permissions) /// </summary> public ClientContext AppOnlyClientContext { get { return this.appOnlyClientContext; } } /// <summary> /// Returns the client context to manipulate the created site (collection) /// </summary> public ClientContext CreatedSiteContext { get { return this.createdSiteContext; } } /// <summary> /// Returns the client context to manipulate the site directory in the site directory site /// </summary> public ClientContext SiteDirectorySiteContext { get { return this.siteDirectorySiteContext; } } /// <summary> /// Class instance that will be used for on-premises specific provisioning code /// </summary> public ISiteProvisioningOnPremises SiteProvisioningOnPremises { get; set; } /// <summary> /// Information about the site to be provisioned /// </summary> public SharePointProvisioningData SharePointProvisioningData { get; set; } /// <summary> /// We're creating on-premises /// </summary> public bool CreateOnPremises { get { return SharePointProvisioningData.DataClassification.Equals("HBI", StringComparison.InvariantCultureIgnoreCase); } } /// <summary> /// Returns the root directory of the current deployment /// </summary> public string AppRootPath { get { string roleRoot = Environment.GetEnvironmentVariable("RoleRoot"); if (null != roleRoot && roleRoot.Length > 0) { // We're running on azure (real or emulated) return roleRoot + @"\approot"; } else { Process process = Process.GetCurrentProcess(); string fullPath = Path.GetDirectoryName(process.MainModule.FileName); return fullPath; } } } /// <summary> /// Realm to use for the access token's nameid and audience. In Office 365 use MSOL PowerShell (Get-MsolCompanyInformation).ObjectID to obtain Target/Tenant realm /// </summary> public string Realm { get; set; } /// <summary> /// The Application ID generated when you deploy an app (Visual Studio) or when you register an app via the appregnew.aspx page /// </summary> public string AppId { get; set; } /// <summary> /// The Application Secret generated when you deploy an app (Visual Studio) or when you register an app via the appregnew.aspx page /// </summary> public string AppSecret { get; set; } /// <summary> /// Triggers the provisioning /// </summary> /// <returns>True if OK, false otherwise</returns> public virtual bool Execute() { bool result = false; return result; } /// <summary> /// Instantiate an app only client context (the one with tenant level permissions) /// </summary> /// <param name="siteUrl">Url of the tenant admin site</param> public void InstantiateAppOnlyClientContext(string siteUrl) { this.appOnlyClientContext = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, this.Realm, this.AppId, this.AppSecret); } /// <summary> /// Instantiate an app only client context (the one with tenant level permissions) /// </summary> /// <param name="siteUrl">Url of the tenant admin site</param> public void InstantiateCreatedSiteClientContext(string siteUrl) { this.createdSiteContext = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, this.Realm, this.AppId, this.AppSecret); } /// <summary> /// Instantiate an app only client context (the one with tenant level permissions) /// </summary> /// <param name="siteUrl">Url of the tenant admin site</param> public void InstantiateSiteDirectorySiteClientContext(string siteUrl) { this.siteDirectorySiteContext = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, this.Realm, this.AppId, this.AppSecret); } public string GetNextSiteCollectionUrl(string siteDirectoryUrl, string siteDirectoryListName, string baseSiteUrl) { if (this.CreateOnPremises) { return this.SiteProvisioningOnPremises.GetNextSiteCollectionUrl(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, siteDirectoryUrl, siteDirectoryListName, baseSiteUrl); } else { return new SiteDirectoryManager().GetNextSiteCollectionUrlTenant(this.AppOnlyClientContext, this.AppOnlyClientContext.Web, this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, siteDirectoryUrl, siteDirectoryListName, baseSiteUrl); } } /// <summary> /// Launches a site collection creation and waits for the creation to finish /// </summary> /// <param name="properties">Describes the site collection to be created</param> public void AddSiteCollection(SharePointProvisioningData properties) { if (this.CreateOnPremises) { this.SiteProvisioningOnPremises.CreateSiteCollectionOnPremises(this.SharePointProvisioningData); this.createdSiteContext = this.SiteProvisioningOnPremises.SpOnPremiseAuthentication(this.SharePointProvisioningData.Url); } else { SiteEntity newSite = new SiteEntity { Description = properties.Description, Title = properties.Title, Url = properties.Url, Template = properties.Template, Lcid = properties.Lcid, SiteOwnerLogin = properties.SiteOwner.Login, StorageMaximumLevel = properties.StorageMaximumLevel, StorageWarningLevel = properties.StorageWarningLevel, TimeZoneId = properties.TimeZoneId, UserCodeMaximumLevel = properties.UserCodeMaximumLevel, UserCodeWarningLevel = properties.UserCodeWarningLevel, }; this.AppOnlyClientContext.Web.AddSiteCollectionTenant(newSite); InstantiateCreatedSiteClientContext(newSite.Url); } } internal string GetConfiguration(string key) { string value = ""; if (this.CreateOnPremises) { value = ConfigurationManager.AppSettings[key]; } else { value = RoleEnvironment.GetConfigurationSettingValue(key); } return value; } } }
stijnneirinckx/PnP
Solutions/Provisioning.Hybrid/Provisioning.Hybrid.Core/SiteTemplates/SiteProvisioningBase.cs
C#
apache-2.0
8,236
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // http://code.google.com/p/goprotobuf/ // // 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. package proto_test import ( "math" "reflect" "testing" . "./testdata" . "github.com/coreos/etcd/third_party/code.google.com/p/gogoprotobuf/proto" ) type UnmarshalTextTest struct { in string err string // if "", no error expected out *MyMessage } func buildExtStructTest(text string) UnmarshalTextTest { msg := &MyMessage{ Count: Int32(42), } SetExtension(msg, E_Ext_More, &Ext{ Data: String("Hello, world!"), }) return UnmarshalTextTest{in: text, out: msg} } func buildExtDataTest(text string) UnmarshalTextTest { msg := &MyMessage{ Count: Int32(42), } SetExtension(msg, E_Ext_Text, String("Hello, world!")) SetExtension(msg, E_Ext_Number, Int32(1729)) return UnmarshalTextTest{in: text, out: msg} } func buildExtRepStringTest(text string) UnmarshalTextTest { msg := &MyMessage{ Count: Int32(42), } if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { panic(err) } return UnmarshalTextTest{in: text, out: msg} } var unMarshalTextTests = []UnmarshalTextTest{ // Basic { in: " count:42\n name:\"Dave\" ", out: &MyMessage{ Count: Int32(42), Name: String("Dave"), }, }, // Empty quoted string { in: `count:42 name:""`, out: &MyMessage{ Count: Int32(42), Name: String(""), }, }, // Quoted string concatenation { in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, out: &MyMessage{ Count: Int32(42), Name: String("My name is elsewhere"), }, }, // Quoted string with escaped apostrophe { in: `count:42 name: "HOLIDAY - New Year\'s Day"`, out: &MyMessage{ Count: Int32(42), Name: String("HOLIDAY - New Year's Day"), }, }, // Quoted string with single quote { in: `count:42 name: 'Roger "The Ramster" Ramjet'`, out: &MyMessage{ Count: Int32(42), Name: String(`Roger "The Ramster" Ramjet`), }, }, // Quoted string with all the accepted special characters from the C++ test { in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", out: &MyMessage{ Count: Int32(42), Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), }, }, // Quoted string with quoted backslash { in: `count:42 name: "\\'xyz"`, out: &MyMessage{ Count: Int32(42), Name: String(`\'xyz`), }, }, // Quoted string with UTF-8 bytes. { in: "count:42 name: '\303\277\302\201\xAB'", out: &MyMessage{ Count: Int32(42), Name: String("\303\277\302\201\xAB"), }, }, // Bad quoted string { in: `inner: < host: "\0" >` + "\n", err: `line 1.15: invalid quoted string "\0"`, }, // Number too large for int64 { in: "count: 123456789012345678901", err: "line 1.7: invalid int32: 123456789012345678901", }, // Number too large for int32 { in: "count: 1234567890123", err: "line 1.7: invalid int32: 1234567890123", }, // Number in hexadecimal { in: "count: 0x2beef", out: &MyMessage{ Count: Int32(0x2beef), }, }, // Number in octal { in: "count: 024601", out: &MyMessage{ Count: Int32(024601), }, }, // Floating point number with "f" suffix { in: "count: 4 others:< weight: 17.0f >", out: &MyMessage{ Count: Int32(4), Others: []*OtherMessage{ { Weight: Float32(17), }, }, }, }, // Floating point positive infinity { in: "count: 4 bigfloat: inf", out: &MyMessage{ Count: Int32(4), Bigfloat: Float64(math.Inf(1)), }, }, // Floating point negative infinity { in: "count: 4 bigfloat: -inf", out: &MyMessage{ Count: Int32(4), Bigfloat: Float64(math.Inf(-1)), }, }, // Number too large for float32 { in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", }, // Number posing as a quoted string { in: `inner: < host: 12 >` + "\n", err: `line 1.15: invalid string: 12`, }, // Quoted string posing as int32 { in: `count: "12"`, err: `line 1.7: invalid int32: "12"`, }, // Quoted string posing a float32 { in: `others:< weight: "17.4" >`, err: `line 1.17: invalid float32: "17.4"`, }, // Enum { in: `count:42 bikeshed: BLUE`, out: &MyMessage{ Count: Int32(42), Bikeshed: MyMessage_BLUE.Enum(), }, }, // Repeated field { in: `count:42 pet: "horsey" pet:"bunny"`, out: &MyMessage{ Count: Int32(42), Pet: []string{"horsey", "bunny"}, }, }, // Repeated message with/without colon and <>/{} { in: `count:42 others:{} others{} others:<> others:{}`, out: &MyMessage{ Count: Int32(42), Others: []*OtherMessage{ {}, {}, {}, {}, }, }, }, // Missing colon for inner message { in: `count:42 inner < host: "cauchy.syd" >`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("cauchy.syd"), }, }, }, // Missing colon for string field { in: `name "Dave"`, err: `line 1.5: expected ':', found "\"Dave\""`, }, // Missing colon for int32 field { in: `count 42`, err: `line 1.6: expected ':', found "42"`, }, // Missing required field { in: ``, err: `line 1.0: message testdata.MyMessage missing required field "count"`, }, // Repeated non-repeated field { in: `name: "Rob" name: "Russ"`, err: `line 1.12: non-repeated field "name" was repeated`, }, // Group { in: `count: 17 SomeGroup { group_field: 12 }`, out: &MyMessage{ Count: Int32(17), Somegroup: &MyMessage_SomeGroup{ GroupField: Int32(12), }, }, }, // Semicolon between fields { in: `count:3;name:"Calvin"`, out: &MyMessage{ Count: Int32(3), Name: String("Calvin"), }, }, // Comma between fields { in: `count:4,name:"Ezekiel"`, out: &MyMessage{ Count: Int32(4), Name: String("Ezekiel"), }, }, // Extension buildExtStructTest(`count: 42 [testdata.Ext.more]:<data:"Hello, world!" >`), buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`), buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`), buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`), // Big all-in-one { in: "count:42 # Meaning\n" + `name:"Dave" ` + `quote:"\"I didn't want to go.\"" ` + `pet:"bunny" ` + `pet:"kitty" ` + `pet:"horsey" ` + `inner:<` + ` host:"footrest.syd" ` + ` port:7001 ` + ` connected:true ` + `> ` + `others:<` + ` key:3735928559 ` + ` value:"\x01A\a\f" ` + `> ` + `others:<` + " weight:58.9 # Atomic weight of Co\n" + ` inner:<` + ` host:"lesha.mtv" ` + ` port:8002 ` + ` >` + `>`, out: &MyMessage{ Count: Int32(42), Name: String("Dave"), Quote: String(`"I didn't want to go."`), Pet: []string{"bunny", "kitty", "horsey"}, Inner: &InnerMessage{ Host: String("footrest.syd"), Port: Int32(7001), Connected: Bool(true), }, Others: []*OtherMessage{ { Key: Int64(3735928559), Value: []byte{0x1, 'A', '\a', '\f'}, }, { Weight: Float32(58.9), Inner: &InnerMessage{ Host: String("lesha.mtv"), Port: Int32(8002), }, }, }, }, }, } func TestUnmarshalText(t *testing.T) { for i, test := range unMarshalTextTests { pb := new(MyMessage) err := UnmarshalText(test.in, pb) if test.err == "" { // We don't expect failure. if err != nil { t.Errorf("Test %d: Unexpected error: %v", i, err) } else if !reflect.DeepEqual(pb, test.out) { t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", i, pb, test.out) } } else { // We do expect failure. if err == nil { t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) } else if err.Error() != test.err { t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", i, err.Error(), test.err) } } } } func TestUnmarshalTextCustomMessage(t *testing.T) { msg := &textMessage{} if err := UnmarshalText("custom", msg); err != nil { t.Errorf("Unexpected error from custom unmarshal: %v", err) } if UnmarshalText("not custom", msg) == nil { t.Errorf("Didn't get expected error from custom unmarshal") } } // Regression test; this caused a panic. func TestRepeatedEnum(t *testing.T) { pb := new(RepeatedEnum) if err := UnmarshalText("color: RED", pb); err != nil { t.Fatal(err) } exp := &RepeatedEnum{ Color: []RepeatedEnum_Color{RepeatedEnum_RED}, } if !Equal(pb, exp) { t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) } } var benchInput string func init() { benchInput = "count: 4\n" for i := 0; i < 1000; i++ { benchInput += "pet: \"fido\"\n" } // Check it is valid input. pb := new(MyMessage) err := UnmarshalText(benchInput, pb) if err != nil { panic("Bad benchmark input: " + err.Error()) } } func BenchmarkUnmarshalText(b *testing.B) { pb := new(MyMessage) for i := 0; i < b.N; i++ { UnmarshalText(benchInput, pb) } b.SetBytes(int64(len(benchInput))) }
cvik/etcd
third_party/code.google.com/p/gogoprotobuf/proto/text_parser_test.go
GO
apache-2.0
10,773
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Windows.Automation; using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudioTools.VSTestHost; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; using Task = System.Threading.Tasks.Task; namespace TestUtilities.UI { /// <summary> /// Provides wrappers for automating the VisualStudio UI. /// </summary> public class VisualStudioApp : AutomationWrapper, IDisposable { private SolutionExplorerTree _solutionExplorerTreeView; private ObjectBrowser _objectBrowser, _resourceView; private AzureCloudServiceActivityLog _azureActivityLog; private IntPtr _mainWindowHandle; private readonly DTE _dte; private IServiceProvider _provider; private List<Action> _onDispose; private bool _isDisposed, _skipCloseAll; public VisualStudioApp(DTE dte = null) : this(new IntPtr((dte ?? VSTestContext.DTE).MainWindow.HWnd)) { _dte = dte ?? VSTestContext.DTE; foreach (var p in ((DTE2)_dte).ToolWindows.OutputWindow.OutputWindowPanes.OfType<OutputWindowPane>()) { p.Clear(); } } private VisualStudioApp(IntPtr windowHandle) : base(AutomationElement.FromHandle(windowHandle)) { _mainWindowHandle = windowHandle; } public bool IsDisposed { get { return _isDisposed; } } public void OnDispose(Action action) { Debug.Assert(action != null); if (_onDispose == null) { _onDispose = new List<Action> { action }; } else { _onDispose.Add(action); } } protected virtual void Dispose(bool disposing) { if (!_isDisposed) { _isDisposed = true; try { if (_onDispose != null) { foreach (var action in _onDispose) { action(); } } if (_dte != null && _dte.Debugger.CurrentMode != dbgDebugMode.dbgDesignMode) { _dte.Debugger.TerminateAll(); _dte.Debugger.Stop(); } DismissAllDialogs(); for (int i = 0; i < 100 && !_skipCloseAll; i++) { try { _dte.Solution.Close(false); break; } catch { _dte.Documents.CloseAll(EnvDTE.vsSaveChanges.vsSaveChangesNo); System.Threading.Thread.Sleep(200); } } } catch (Exception ex) { Debug.WriteLine("Exception disposing VisualStudioApp: {0}", ex); } } } public void Dispose() { Dispose(true); } public void SuppressCloseAllOnDispose() { _skipCloseAll = true; } public IComponentModel ComponentModel { get { return GetService<IComponentModel>(typeof(SComponentModel)); } } public IServiceProvider ServiceProvider { get { if (_provider == null) { if (_dte == null) { _provider = VSTestContext.ServiceProvider; } else { _provider = new ServiceProvider((IOleServiceProvider)_dte); OnDispose(() => ((ServiceProvider)_provider).Dispose()); } } return _provider; } } public T GetService<T>(Type type = null) { return (T)ServiceProvider.GetService(type ?? typeof(T)); } /// <summary> /// File->Save /// </summary> public void SaveSelection() { Dte.ExecuteCommand("File.SaveSelectedItems"); } /// <summary> /// Opens and activates the solution explorer window. /// </summary> public SolutionExplorerTree OpenSolutionExplorer() { _solutionExplorerTreeView = null; Dte.ExecuteCommand("View.SolutionExplorer"); return SolutionExplorerTreeView; } /// <summary> /// Opens and activates the object browser window. /// </summary> public void OpenObjectBrowser() { Dte.ExecuteCommand("View.ObjectBrowser"); } /// <summary> /// Opens and activates the Resource View window. /// </summary> public void OpenResourceView() { Dte.ExecuteCommand("View.ResourceView"); } public IntPtr OpenDialogWithDteExecuteCommand(string commandName, string commandArgs = "") { Task task = Task.Factory.StartNew(() => { Dte.ExecuteCommand(commandName, commandArgs); Console.WriteLine("Successfully executed command {0} {1}", commandName, commandArgs); }); IntPtr dialog = IntPtr.Zero; try { dialog = WaitForDialog(task); } finally { if (dialog == IntPtr.Zero) { if (task.IsFaulted && task.Exception != null) { Assert.Fail("Unexpected Exception - VSTestContext.DTE.ExecuteCommand({0},{1}){2}{3}", commandName, commandArgs, Environment.NewLine, task.Exception.ToString()); } Assert.Fail("Task failed - VSTestContext.DTE.ExecuteCommand({0},{1})", commandName, commandArgs); } } return dialog; } public void ExecuteCommand(string commandName, string commandArgs = "", int timeout = 25000) { Task task = Task.Factory.StartNew(() => { Console.WriteLine("Executing command {0} {1}", commandName, commandArgs); Dte.ExecuteCommand(commandName, commandArgs); Console.WriteLine("Successfully executed command {0} {1}", commandName, commandArgs); }); bool timedOut = false; try { timedOut = !task.Wait(timeout); } catch (AggregateException ae) { foreach (var ex in ae.InnerExceptions) { Console.WriteLine(ex.ToString()); } throw ae.InnerException; } if (timedOut) { string msg = String.Format("Command {0} failed to execute in specified timeout", commandName); Console.WriteLine(msg); DumpVS(); Assert.Fail(msg); } } /// <summary> /// Opens and activates the Navigate To window. /// </summary> public NavigateToDialog OpenNavigateTo() { Task task = Task.Factory.StartNew(() => { Dte.ExecuteCommand("Edit.NavigateTo"); Console.WriteLine("Successfully executed Edit.NavigateTo"); }); for (int retries = 10; retries > 0; --retries) { #if DEV12_OR_LATER foreach (var element in Element.FindAll( TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, "Window") ).OfType<AutomationElement>()) { if (element.FindAll(TreeScope.Children, new OrCondition( new PropertyCondition(AutomationElement.AutomationIdProperty, "PART_SearchHost"), new PropertyCondition(AutomationElement.AutomationIdProperty, "PART_ResultList") )).Count == 2) { return new NavigateToDialog(element); } } #else var element = Element.FindFirst( TreeScope.Descendants, new AndCondition( new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window), new PropertyCondition(AutomationElement.NameProperty, "Navigate To") ) ); if (element != null) { return new NavigateToDialog(element); } #endif System.Threading.Thread.Sleep(500); } Assert.Fail("Could not find Navigate To window"); return null; } public SaveDialog SaveAs() { return SaveDialog.FromDte(this); } /// <summary> /// Gets the specified document. Filename should be fully qualified filename. /// </summary> public EditorWindow GetDocument(string filename) { Debug.Assert(Path.IsPathRooted(filename)); string windowName = Path.GetFileName(filename); var elem = GetDocumentTab(windowName); elem = elem.FindFirst(TreeScope.Descendants, new PropertyCondition( AutomationElement.ClassNameProperty, "WpfTextView" ) ); return new EditorWindow(filename, elem); } public AutomationElement GetDocumentTab(string windowName) { var elem = Element.FindFirst(TreeScope.Descendants, new AndCondition( new PropertyCondition( AutomationElement.ClassNameProperty, "TabItem" ), new PropertyCondition( AutomationElement.NameProperty, windowName ) ) ); if (elem == null) { // maybe the file has been modified, try again with a * elem = Element.FindFirst(TreeScope.Descendants, new AndCondition( new PropertyCondition( AutomationElement.ClassNameProperty, "TabItem" ), new PropertyCondition( AutomationElement.NameProperty, windowName + "*" ) ) ); } return elem; } /// <summary> /// Selects the given source control provider. Name merely needs to be /// enough text to disambiguate from other source control providers. /// </summary> public void SelectSourceControlProvider(string providerName) { Element.SetFocus(); using (var dialog = ToolsOptionsDialog.FromDte(this)) { dialog.SelectedView = "Source Control/Plug-in Selection"; var currentSourceControl = new ComboBox( dialog.FindByAutomationId("2001") // Current source control plug-in ); currentSourceControl.SelectItem(providerName); dialog.OK(); } } public NewProjectDialog FileNewProject() { var dialog = OpenDialogWithDteExecuteCommand("File.NewProject"); return new NewProjectDialog(this, AutomationElement.FromHandle(dialog)); } public AttachToProcessDialog OpenDebugAttach() { var dialog = OpenDialogWithDteExecuteCommand("Debug.AttachtoProcess"); return new AttachToProcessDialog(dialog); } public OutputWindowPane GetOutputWindow(string name) { return ((DTE2)Dte).ToolWindows.OutputWindow.OutputWindowPanes.Item(name); } public IEnumerable<Window> OpenDocumentWindows { get { return Dte.Windows.OfType<Window>().Where(w => w.Document != null); } } public void WaitForBuildComplete(int timeout) { for (int i = 0; i < timeout; i += 500) { if (Dte.Solution.SolutionBuild.BuildState == vsBuildState.vsBuildStateDone) { return; } System.Threading.Thread.Sleep(500); } throw new TimeoutException("Timeout waiting for build to complete"); } public string GetOutputWindowText(string name) { var window = GetOutputWindow(name); var doc = window.TextDocument; doc.Selection.SelectAll(); return doc.Selection.Text; } public void WaitForOutputWindowText(string name, string containsText, int timeout=5000) { for (int i = 0; i < timeout; i += 500) { var text = GetOutputWindowText(name); if (text.Contains(containsText)) { return; } System.Threading.Thread.Sleep(500); } Assert.Fail("Failed to find {0} in output window {1}, found:\r\n{2}", containsText, name, GetOutputWindowText(name)); } public void DismissAllDialogs() { int foundWindow = 2; while (foundWindow != 0) { IVsUIShell uiShell = GetService<IVsUIShell>(typeof(IVsUIShell)); if (uiShell == null) { return; } IntPtr hwnd; uiShell.GetDialogOwnerHwnd(out hwnd); for (int j = 0; j < 10 && hwnd == _mainWindowHandle; j++) { System.Threading.Thread.Sleep(100); uiShell.GetDialogOwnerHwnd(out hwnd); } //We didn't see any dialogs if (hwnd == IntPtr.Zero || hwnd == _mainWindowHandle) { foundWindow--; continue; } //MessageBoxButton.Abort //MessageBoxButton.Cancel //MessageBoxButton.No //MessageBoxButton.Ok //MessageBoxButton.Yes //The second parameter is going to be the value returned... We always send Ok Debug.WriteLine("Dismissing dialog"); AutomationWrapper.DumpElement(AutomationElement.FromHandle(hwnd)); NativeMethods.EndDialog(hwnd, new IntPtr(1)); } } /// <summary> /// Waits for a modal dialog to take over VS's main window and returns the HWND for the dialog. /// </summary> /// <returns></returns> public IntPtr WaitForDialog(Task task) { return WaitForDialogToReplace(_mainWindowHandle, task); } public IntPtr WaitForDialog() { return WaitForDialogToReplace(_mainWindowHandle, null); } public ExceptionHelperDialog WaitForException() { var window = FindByName("Exception Helper Indicator Window"); if (window != null) { var innerPane = window.FindFirst(TreeScope.Descendants, new PropertyCondition( AutomationElement.ControlTypeProperty, ControlType.Pane ) ); Assert.IsNotNull(innerPane); return new ExceptionHelperDialog(innerPane); } Assert.Fail("Failed to find exception helper window"); return null; } /// <summary> /// Waits for a modal dialog to take over a given window and returns the HWND for the new dialog. /// </summary> /// <returns>An IntPtr which should be interpreted as an HWND</returns> public IntPtr WaitForDialogToReplace(IntPtr originalHwnd) { return WaitForDialogToReplace(originalHwnd, null); } /// <summary> /// Waits for a modal dialog to take over a given window and returns the HWND for the new dialog. /// </summary> /// <returns>An IntPtr which should be interpreted as an HWND</returns> public IntPtr WaitForDialogToReplace(AutomationElement element) { return WaitForDialogToReplace(new IntPtr(element.Current.NativeWindowHandle), null); } private IntPtr WaitForDialogToReplace(IntPtr originalHwnd, Task task) { IVsUIShell uiShell = GetService<IVsUIShell>(typeof(IVsUIShell)); IntPtr hwnd; uiShell.GetDialogOwnerHwnd(out hwnd); int timeout = task == null ? 10000 : 60000; while (timeout > 0 && hwnd == originalHwnd && (task == null || !(task.IsFaulted || task.IsCanceled))) { timeout -= 500; System.Threading.Thread.Sleep(500); uiShell.GetDialogOwnerHwnd(out hwnd); } if (task != null && (task.IsFaulted || task.IsCanceled)) { return IntPtr.Zero; } if (hwnd == originalHwnd) { DumpElement(AutomationElement.FromHandle(hwnd)); } Assert.AreNotEqual(IntPtr.Zero, hwnd); Assert.AreNotEqual(originalHwnd, hwnd, "Main window still has focus"); return hwnd; } /// <summary> /// Waits for the VS main window to receive the focus. /// </summary> /// <returns> /// True if the main window has the focus. Otherwise, false. /// </returns> public bool WaitForDialogDismissed(bool assertIfFailed = true, int timeout = 100000) { IVsUIShell uiShell = GetService<IVsUIShell>(typeof(IVsUIShell)); IntPtr hwnd; uiShell.GetDialogOwnerHwnd(out hwnd); for (int i = 0; i < (timeout / 100) && hwnd != _mainWindowHandle; i++) { System.Threading.Thread.Sleep(100); uiShell.GetDialogOwnerHwnd(out hwnd); } if (assertIfFailed) { Assert.AreEqual(_mainWindowHandle, hwnd); return true; } return _mainWindowHandle == hwnd; } /// <summary> /// Waits for no dialog. If a dialog appears before the timeout expires /// then the test fails and the dialog is closed. /// </summary> public void WaitForNoDialog(TimeSpan timeout) { IVsUIShell uiShell = GetService<IVsUIShell>(typeof(IVsUIShell)); IntPtr hwnd; uiShell.GetDialogOwnerHwnd(out hwnd); for (int i = 0; i < 100 && hwnd == _mainWindowHandle; i++) { System.Threading.Thread.Sleep((int)timeout.TotalMilliseconds / 100); uiShell.GetDialogOwnerHwnd(out hwnd); } if (hwnd != (IntPtr)_mainWindowHandle) { AutomationWrapper.DumpElement(AutomationElement.FromHandle(hwnd)); NativeMethods.EndDialog(hwnd, (IntPtr)(int)MessageBoxButton.Cancel); Assert.Fail("Dialog appeared - see output for details"); } } public static void CheckMessageBox(params string[] text) { CheckMessageBox(MessageBoxButton.Cancel, text); } public static void CheckMessageBox(MessageBoxButton button, params string[] text) { CheckAndDismissDialog(text, 65535, new IntPtr((int)button)); } /// <summary> /// Checks the text of a dialog and dismisses it. /// /// dlgField is the field to check the text of. /// buttonId is the button to press to dismiss. /// </summary> private static void CheckAndDismissDialog(string[] text, int dlgField, IntPtr buttonId) { var handle = new IntPtr(VSTestContext.DTE.MainWindow.HWnd); IVsUIShell uiShell = VSTestContext.ServiceProvider.GetService(typeof(IVsUIShell)) as IVsUIShell; IntPtr hwnd; uiShell.GetDialogOwnerHwnd(out hwnd); for (int i = 0; i < 20 && hwnd == handle; i++) { System.Threading.Thread.Sleep(500); uiShell.GetDialogOwnerHwnd(out hwnd); } Assert.AreNotEqual(IntPtr.Zero, hwnd, "hwnd is null, We failed to get the dialog"); Assert.AreNotEqual(handle, hwnd, "hwnd is Dte.MainWindow, We failed to get the dialog"); Console.WriteLine("Ending dialog: "); AutomationWrapper.DumpElement(AutomationElement.FromHandle(hwnd)); Console.WriteLine("--------"); try { StringBuilder title = new StringBuilder(4096); Assert.AreNotEqual(NativeMethods.GetDlgItemText(hwnd, dlgField, title, title.Capacity), (uint)0); string t = title.ToString(); AssertUtil.Contains(t, text); } finally { NativeMethods.EndDialog(hwnd, buttonId); } } /// <summary> /// Provides access to Visual Studio's solution explorer tree view. /// </summary> public SolutionExplorerTree SolutionExplorerTreeView { get { if (_solutionExplorerTreeView == null) { AutomationElement element = null; for (int i = 0; i < 20 && element == null; i++) { element = Element.FindFirst(TreeScope.Descendants, new AndCondition( new PropertyCondition( AutomationElement.ControlTypeProperty, ControlType.Pane ), new PropertyCondition( AutomationElement.NameProperty, "Solution Explorer" ) ) ); if (element == null) { System.Threading.Thread.Sleep(500); } } AutomationElement treeElement = null; if (element != null) { for (int i = 0; i < 20 && treeElement == null; i++) { treeElement = element.FindFirst(TreeScope.Descendants, new PropertyCondition( AutomationElement.ControlTypeProperty, ControlType.Tree ) ); if (treeElement == null) { System.Threading.Thread.Sleep(500); } } } _solutionExplorerTreeView = new SolutionExplorerTree(treeElement); } return _solutionExplorerTreeView; } } /// <summary> /// Provides access to Visual Studio's object browser. /// </summary> public ObjectBrowser ObjectBrowser { get { if (_objectBrowser == null) { AutomationElement element = null; for (int i = 0; i < 10 && element == null; i++) { element = Element.FindFirst(TreeScope.Descendants, new AndCondition( new PropertyCondition( AutomationElement.ClassNameProperty, "ViewPresenter" ), new PropertyCondition( AutomationElement.NameProperty, "Object Browser" ) ) ); if (element == null) { System.Threading.Thread.Sleep(500); } } _objectBrowser = new ObjectBrowser(element); } return _objectBrowser; } } /// <summary> /// Provides access to Visual Studio's resource view. /// </summary> public ObjectBrowser ResourceView { get { if (_resourceView == null) { AutomationElement element = null; for (int i = 0; i < 10 && element == null; i++) { element = Element.FindFirst(TreeScope.Descendants, new AndCondition( new PropertyCondition( AutomationElement.ClassNameProperty, "ViewPresenter" ), new PropertyCondition( AutomationElement.NameProperty, "Resource View" ) ) ); if (element == null) { System.Threading.Thread.Sleep(500); } } _resourceView = new ObjectBrowser(element); } return _resourceView; } } /// <summary> /// Provides access to Azure's VS Activity Log window. /// </summary> public AzureCloudServiceActivityLog AzureActivityLog { get { if (_azureActivityLog == null) { AutomationElement element = null; for (int i = 0; i < 10 && element == null; i++) { element = Element.FindFirst(TreeScope.Descendants, new AndCondition( new PropertyCondition( AutomationElement.ClassNameProperty, "GenericPane" ), new OrCondition( new PropertyCondition( AutomationElement.NameProperty, "Microsoft Azure Activity Log" ), new PropertyCondition( AutomationElement.NameProperty, "Windows Azure Activity Log" ) ) ) ); if (element == null) { System.Threading.Thread.Sleep(500); } } _azureActivityLog = new AzureCloudServiceActivityLog(element); } return _azureActivityLog; } } /// <summary> /// Produces a name which is compatible with x:Name requirements (starts with a letter/underscore, contains /// only letter, numbers, or underscores). /// </summary> public static string GetName(string title) { if (title.Length == 0) { return "InteractiveWindowHost"; } StringBuilder res = new StringBuilder(); if (!Char.IsLetter(title[0])) { res.Append('_'); } foreach (char c in title) { if (Char.IsLetter(c) || Char.IsDigit(c) || c == '_') { res.Append(c); } } res.Append("Host"); return res.ToString(); } public DTE Dte { get { return _dte; } } public void WaitForMode(dbgDebugMode mode) { for (int i = 0; i < 60 && Dte.Debugger.CurrentMode != mode; i++) { System.Threading.Thread.Sleep(500); } Assert.AreEqual(mode, VSTestContext.DTE.Debugger.CurrentMode); } public virtual Project CreateProject( string languageName, string templateName, string createLocation, string projectName, bool newSolution = true, bool suppressUI = true ) { var sln = (Solution2)Dte.Solution; var templatePath = sln.GetProjectTemplate(templateName, languageName); Assert.IsTrue(File.Exists(templatePath) || Directory.Exists(templatePath), string.Format("Cannot find template '{0}' for language '{1}'", templateName, languageName)); var origName = projectName; var projectDir = Path.Combine(createLocation, projectName); for (int i = 1; Directory.Exists(projectDir); ++i) { projectName = string.Format("{0}{1}", origName, i); projectDir = Path.Combine(createLocation, projectName); } var previousSuppressUI = Dte.SuppressUI; try { Dte.SuppressUI = suppressUI; sln.AddFromTemplate(templatePath, projectDir, projectName, newSolution); } finally { Dte.SuppressUI = previousSuppressUI; } return sln.Projects.Cast<Project>().FirstOrDefault(p => p.Name == projectName); } public Project OpenProject( string projName, string startItem = null, int? expectedProjects = null, string projectName = null, bool setStartupItem = true, Func<AutomationDialog, bool> onDialog = null ) { string fullPath = TestData.GetPath(projName); Assert.IsTrue(File.Exists(fullPath), "Cannot find " + fullPath); Console.WriteLine("Opening {0}", fullPath); // If there is a .suo file, delete that so that there is no state carried over from another test. for (int i = 10; i <= 14; ++i) { string suoPath = Path.ChangeExtension(fullPath, ".v" + i + ".suo"); if (File.Exists(suoPath)) { File.Delete(suoPath); } } var t = Task.Run(() => Dte.Solution.Open(fullPath)); using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30))) { try { if (!t.Wait(1000, cts.Token)) { // Load has taken a while, start checking whether a dialog has // appeared IVsUIShell uiShell = GetService<IVsUIShell>(typeof(IVsUIShell)); IntPtr hwnd; while (!t.Wait(1000, cts.Token)) { ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out hwnd)); if (hwnd != _mainWindowHandle) { using (var dlg = new AutomationDialog(this, AutomationElement.FromHandle(hwnd))) { if (onDialog == null || onDialog(dlg) == false) { Console.WriteLine("Unexpected dialog"); DumpElement(dlg.Element); Assert.Fail("Unexpected dialog while loading project"); } } } } } } catch (OperationCanceledException) { Assert.Fail("Failed to open project quickly enough"); } } Assert.IsTrue(Dte.Solution.IsOpen, "The solution is not open"); // Force all projects to load before running any tests. var solution = GetService<IVsSolution4>(typeof(SVsSolution)); Assert.IsNotNull(solution, "Failed to obtain SVsSolution service"); solution.EnsureSolutionIsLoaded((uint)__VSBSLFLAGS.VSBSLFLAGS_None); int count = Dte.Solution.Projects.Count; if (expectedProjects != null && expectedProjects.Value != count) { // if we have other files open we can end up with a bonus project... int i = 0; foreach (EnvDTE.Project proj in Dte.Solution.Projects) { if (proj.Name != "Miscellaneous Files") { i++; } } Assert.AreEqual(expectedProjects, i, "Wrong number of loaded projects"); } Project project = GetProject(projectName); string outputText = "(unable to get Solution output)"; try { outputText = GetOutputWindowText("Solution"); } catch (Exception) { } Assert.IsNotNull(project, "No project loaded: " + outputText); // HACK: Testing whether Properties is just slow to initialize for (int retries = 10; retries > 0 && project.Properties == null; --retries) { Trace.TraceWarning("Waiting for project.Properties to become non-null"); System.Threading.Thread.Sleep(250); } Assert.IsNotNull(project.Properties, "No project properties: " + outputText); Assert.IsTrue(project.Properties.GetEnumerator().MoveNext(), "No items in project properties: " + outputText); if (startItem != null && setStartupItem) { project.SetStartupFile(startItem); for (var i = 0; i < 20; i++) { //Wait for the startupItem to be set before returning from the project creation try { if (((string)project.Properties.Item("StartupFile").Value) == startItem) { break; } } catch { } System.Threading.Thread.Sleep(250); } } DeleteAllBreakPoints(); return project; } public Project GetProject(string projectName) { var iter = Dte.Solution.Projects.GetEnumerator(); if (!iter.MoveNext()) { return null; } Project project = (Project)iter.Current; if (projectName != null) { while (project.Name != projectName) { Assert.IsTrue(iter.MoveNext(), "Failed to find project named " + projectName); project = (Project)iter.Current; } } return project; } public void DeleteAllBreakPoints() { var debug3 = (EnvDTE90.Debugger3)Dte.Debugger; if (debug3.Breakpoints != null) { foreach (var bp in debug3.Breakpoints) { ((EnvDTE90a.Breakpoint3)bp).Delete(); } } } public Uri PublishToAzureCloudService(string serviceName, string subscriptionPublishSettingsFilePath) { using (var publishDialog = AzureCloudServicePublishDialog.FromDte(this)) { using (var manageSubscriptionsDialog = publishDialog.SelectManageSubscriptions()) { LoadPublishSettings(manageSubscriptionsDialog, subscriptionPublishSettingsFilePath); manageSubscriptionsDialog.Close(); } publishDialog.ClickNext(); using (var createServiceDialog = publishDialog.SelectCreateNewService()) { createServiceDialog.ServiceName = serviceName; createServiceDialog.Location = "West US"; createServiceDialog.ClickCreate(); } publishDialog.ClickPublish(); } return new Uri(string.Format("http://{0}.cloudapp.net", serviceName)); } public Uri PublishToAzureWebSite(string siteName, string subscriptionPublishSettingsFilePath) { using (var publishDialog = AzureWebSitePublishDialog.FromDte(this)) { using (var importSettingsDialog = publishDialog.ClickImportSettings()) { importSettingsDialog.ClickImportFromWindowsAzureWebSite(); using (var manageSubscriptionsDialog = importSettingsDialog.ClickImportOrManageSubscriptions()) { LoadPublishSettings(manageSubscriptionsDialog, subscriptionPublishSettingsFilePath); manageSubscriptionsDialog.Close(); } using (var createSiteDialog = importSettingsDialog.ClickNew()) { createSiteDialog.SiteName = siteName; createSiteDialog.ClickCreate(); } importSettingsDialog.ClickOK(); } publishDialog.ClickPublish(); } return new Uri(string.Format("http://{0}.azurewebsites.net", siteName)); } private void LoadPublishSettings(AzureManageSubscriptionsDialog manageSubscriptionsDialog, string publishSettingsFilePath) { manageSubscriptionsDialog.ClickCertificates(); while (manageSubscriptionsDialog.SubscriptionsListBox.Count > 0) { manageSubscriptionsDialog.SubscriptionsListBox[0].Select(); manageSubscriptionsDialog.ClickRemove(); WaitForDialogToReplace(manageSubscriptionsDialog.Element); VisualStudioApp.CheckMessageBox(TestUtilities.MessageBoxButton.Yes); } using (var importSubscriptionDialog = manageSubscriptionsDialog.ClickImport()) { importSubscriptionDialog.FileName = publishSettingsFilePath; importSubscriptionDialog.ClickImport(); } } public List<IVsTaskItem> WaitForErrorListItems(int expectedCount) { return WaitForTaskListItems(typeof(SVsErrorList), expectedCount, exactMatch: false); } public List<IVsTaskItem> WaitForTaskListItems(Type taskListService, int expectedCount, bool exactMatch = true) { Console.Write("Waiting for {0} items on {1} ... ", expectedCount, taskListService.Name); var errorList = GetService<IVsTaskList>(taskListService); var allItems = new List<IVsTaskItem>(); if (expectedCount == 0) { // Allow time for errors to appear. Otherwise when we expect 0 // errors we will get a false pass. System.Threading.Thread.Sleep(5000); } for (int retries = 20; retries > 0; --retries) { allItems.Clear(); IVsEnumTaskItems items; ErrorHandler.ThrowOnFailure(errorList.EnumTaskItems(out items)); IVsTaskItem[] taskItems = new IVsTaskItem[1]; uint[] itemCnt = new uint[1]; while (ErrorHandler.Succeeded(items.Next(1, taskItems, itemCnt)) && itemCnt[0] == 1) { allItems.Add(taskItems[0]); } if (allItems.Count >= expectedCount) { break; } // give time for errors to process... System.Threading.Thread.Sleep(1000); } if (exactMatch) { Assert.AreEqual(expectedCount, allItems.Count); } return allItems; } internal ProjectItem AddItem(Project project, string language, string template, string filename) { var fullTemplate = ((Solution2)project.DTE.Solution).GetProjectItemTemplate(template, language); return project.ProjectItems.AddFromTemplate(fullTemplate, filename); } } }
dut3062796s/PTVS
Common/Tests/Utilities.UI/UI/VisualStudioApp.cs
C#
apache-2.0
42,155
/* ------------------------------------------------------------------ * Copyright (C) 1998-2009 PacketVideo * * 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. * ------------------------------------------------------------------- */ /**************************************************************************************** Portions of this file are derived from the following 3GPP standard: 3GPP TS 26.073 ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec Available from http://www.3gpp.org (C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC) Permission to distribute, modify and use this file under the standard license terms listed above has been obtained from the copyright holder. ****************************************************************************************/ /* ------------------------------------------------------------------------------ Pathname: ./audio/gsm-amr/c/src/d_gain_p.c Functions: d_gain_p Date: 01/31/2002 ------------------------------------------------------------------------------ REVISION HISTORY Description: (1) Removed extra includes (2) Replaced function calls to basic math operations with ANSI C standard mathemtical operations. (3) Placed code in the proper software template. Description: Replaced "int" and/or "char" with OSCL defined types. Description: Added #ifdef __cplusplus around extern'ed table. Description: ------------------------------------------------------------------------------ INPUT AND OUTPUT DEFINITIONS Inputs: mode -- enumerated type -- AMR mode index -- Word16 -- index of quantization Outputs: None Returns: Word16 gain -- (Q14) Global Variables Used: None Local Variables Needed: None ------------------------------------------------------------------------------ FUNCTION DESCRIPTION Function : d_gain_pitch Purpose : Decodes the pitch gain using the received index. output is in Q14 ------------------------------------------------------------------------------ REQUIREMENTS ------------------------------------------------------------------------------ REFERENCES d_gain_p.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001 ------------------------------------------------------------------------------ PSEUDO-CODE ------------------------------------------------------------------------------ RESOURCES USED When the code is written for a specific target processor the the resources used should be documented below. STACK USAGE: [stack count for this module] + [variable to represent stack usage for each subroutine called] where: [stack usage variable] = stack usage for [subroutine name] (see [filename].ext) DATA MEMORY USED: x words PROGRAM MEMORY USED: x words CLOCK CYCLES: [cycle count equation for this module] + [variable used to represent cycle count for each subroutine called] where: [cycle count variable] = cycle count for [subroutine name] (see [filename].ext) ------------------------------------------------------------------------------ */ /*---------------------------------------------------------------------------- ; INCLUDES ----------------------------------------------------------------------------*/ #include "d_gain_p.h" #include "typedef.h" #include "mode.h" /*--------------------------------------------------------------------------*/ #ifdef __cplusplus extern "C" { #endif /*---------------------------------------------------------------------------- ; MACROS ; Define module specific macros here ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; DEFINES ; Include all pre-processor statements here. Include conditional ; compile variables also. ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL FUNCTION DEFINITIONS ; Function Prototype declaration ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL STORE/BUFFER/POINTER DEFINITIONS ; Variable declaration - defined here and used outside this module ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL FUNCTION REFERENCES ; Declare functions defined elsewhere and referenced in this module ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES ; Declare variables used in this module but defined elsewhere ----------------------------------------------------------------------------*/ extern const Word16 qua_gain_pitch[]; /*--------------------------------------------------------------------------*/ #ifdef __cplusplus } #endif /*---------------------------------------------------------------------------- ; FUNCTION CODE ----------------------------------------------------------------------------*/ Word16 d_gain_pitch( /* return value: gain (Q14) */ enum Mode mode, /* i : AMR mode */ Word16 index /* i : index of quantization */ ) { Word16 gain; gain = qua_gain_pitch[index]; if (mode == MR122) { /* clear 2 LSBits */ gain &= 0xFFFC; } return gain; }
dAck2cC2/m3e
src/frameworks/av/media/libstagefright/codecs/amrnb/dec/src/d_gain_p.cpp
C++
apache-2.0
6,349
#region Copyright notice and license // Copyright 2015 gRPC 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. #endregion using Grpc.Core.Internal; namespace Grpc.Core.Tests { internal class FakeChannelCredentials : ChannelCredentials { readonly bool composable; public FakeChannelCredentials(bool composable) { this.composable = composable; } internal override bool IsComposable { get { return composable; } } public override void InternalPopulateConfiguration(ChannelCredentialsConfiguratorBase configurator, object state) { // not invoking configuration on purpose } } internal class FakeCallCredentials : CallCredentials { public override void InternalPopulateConfiguration(CallCredentialsConfiguratorBase configurator, object state) { // not invoking the configurator on purpose } } }
ctiller/grpc
src/csharp/Grpc.Core.Tests/FakeCredentials.cs
C#
apache-2.0
1,490
/* Copyright 2016 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 kubelet import ( "errors" "fmt" "io/ioutil" "os" "path/filepath" "sort" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" utilfeature "k8s.io/apiserver/pkg/util/feature" utilfeaturetesting "k8s.io/apiserver/pkg/util/feature/testing" core "k8s.io/client-go/testing" "k8s.io/client-go/tools/record" // TODO: remove this import if // api.Registry.GroupOrDie(v1.GroupName).GroupVersions[0].String() is changed // to "v1"? _ "k8s.io/kubernetes/pkg/apis/core/install" "k8s.io/kubernetes/pkg/features" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" containertest "k8s.io/kubernetes/pkg/kubelet/container/testing" "k8s.io/kubernetes/pkg/kubelet/server/portforward" "k8s.io/kubernetes/pkg/kubelet/server/remotecommand" "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/volume/util/subpath" ) func TestDisabledSubpath(t *testing.T) { fm := &mount.FakeMounter{} fsp := &subpath.FakeSubpath{} pod := v1.Pod{ Spec: v1.PodSpec{ HostNetwork: true, }, } podVolumes := kubecontainer.VolumeMap{ "disk": kubecontainer.VolumeInfo{Mounter: &stubVolume{path: "/mnt/disk"}}, } cases := map[string]struct { container v1.Container expectError bool }{ "subpath not specified": { v1.Container{ VolumeMounts: []v1.VolumeMount{ { MountPath: "/mnt/path3", Name: "disk", ReadOnly: true, }, }, }, false, }, "subpath specified": { v1.Container{ VolumeMounts: []v1.VolumeMount{ { MountPath: "/mnt/path3", SubPath: "/must/not/be/absolute", Name: "disk", ReadOnly: true, }, }, }, true, }, } defer utilfeaturetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.VolumeSubpath, false)() for name, test := range cases { _, _, err := makeMounts(&pod, "/pod", &test.container, "fakepodname", "", "", podVolumes, fm, fsp, nil) if err != nil && !test.expectError { t.Errorf("test %v failed: %v", name, err) } if err == nil && test.expectError { t.Errorf("test %v failed: expected error", name) } } } func TestNodeHostsFileContent(t *testing.T) { testCases := []struct { hostsFileName string hostAliases []v1.HostAlias rawHostsFileContent string expectedHostsFileContent string }{ { "hosts_test_file1", []v1.HostAlias{}, `# hosts file for testing. 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet fe00::0 ip6-mcastprefix fe00::1 ip6-allnodes fe00::2 ip6-allrouters 123.45.67.89 some.domain `, `# Kubernetes-managed hosts file (host network). # hosts file for testing. 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet fe00::0 ip6-mcastprefix fe00::1 ip6-allnodes fe00::2 ip6-allrouters 123.45.67.89 some.domain `, }, { "hosts_test_file2", []v1.HostAlias{}, `# another hosts file for testing. 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet fe00::0 ip6-mcastprefix fe00::1 ip6-allnodes fe00::2 ip6-allrouters 12.34.56.78 another.domain `, `# Kubernetes-managed hosts file (host network). # another hosts file for testing. 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet fe00::0 ip6-mcastprefix fe00::1 ip6-allnodes fe00::2 ip6-allrouters 12.34.56.78 another.domain `, }, { "hosts_test_file1_with_host_aliases", []v1.HostAlias{ {IP: "123.45.67.89", Hostnames: []string{"foo", "bar", "baz"}}, }, `# hosts file for testing. 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet fe00::0 ip6-mcastprefix fe00::1 ip6-allnodes fe00::2 ip6-allrouters 123.45.67.89 some.domain `, `# Kubernetes-managed hosts file (host network). # hosts file for testing. 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet fe00::0 ip6-mcastprefix fe00::1 ip6-allnodes fe00::2 ip6-allrouters 123.45.67.89 some.domain # Entries added by HostAliases. 123.45.67.89 foo bar baz `, }, { "hosts_test_file2_with_host_aliases", []v1.HostAlias{ {IP: "123.45.67.89", Hostnames: []string{"foo", "bar", "baz"}}, {IP: "456.78.90.123", Hostnames: []string{"park", "doo", "boo"}}, }, `# another hosts file for testing. 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet fe00::0 ip6-mcastprefix fe00::1 ip6-allnodes fe00::2 ip6-allrouters 12.34.56.78 another.domain `, `# Kubernetes-managed hosts file (host network). # another hosts file for testing. 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet fe00::0 ip6-mcastprefix fe00::1 ip6-allnodes fe00::2 ip6-allrouters 12.34.56.78 another.domain # Entries added by HostAliases. 123.45.67.89 foo bar baz 456.78.90.123 park doo boo `, }, } for _, testCase := range testCases { tmpdir, err := writeHostsFile(testCase.hostsFileName, testCase.rawHostsFileContent) require.NoError(t, err, "could not create a temp hosts file") defer os.RemoveAll(tmpdir) actualContent, fileReadErr := nodeHostsFileContent(filepath.Join(tmpdir, testCase.hostsFileName), testCase.hostAliases) require.NoError(t, fileReadErr, "could not create read hosts file") assert.Equal(t, testCase.expectedHostsFileContent, string(actualContent), "hosts file content not expected") } } // writeHostsFile will write a hosts file into a temporary dir, and return that dir. // Caller is responsible for deleting the dir and its contents. func writeHostsFile(filename string, cfg string) (string, error) { tmpdir, err := ioutil.TempDir("", "kubelet=kubelet_pods_test.go=") if err != nil { return "", err } return tmpdir, ioutil.WriteFile(filepath.Join(tmpdir, filename), []byte(cfg), 0644) } func TestManagedHostsFileContent(t *testing.T) { testCases := []struct { hostIP string hostName string hostDomainName string hostAliases []v1.HostAlias expectedContent string }{ { "123.45.67.89", "podFoo", "", []v1.HostAlias{}, `# Kubernetes-managed hosts file. 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet fe00::0 ip6-mcastprefix fe00::1 ip6-allnodes fe00::2 ip6-allrouters 123.45.67.89 podFoo `, }, { "203.0.113.1", "podFoo", "domainFoo", []v1.HostAlias{}, `# Kubernetes-managed hosts file. 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet fe00::0 ip6-mcastprefix fe00::1 ip6-allnodes fe00::2 ip6-allrouters 203.0.113.1 podFoo.domainFoo podFoo `, }, { "203.0.113.1", "podFoo", "domainFoo", []v1.HostAlias{ {IP: "123.45.67.89", Hostnames: []string{"foo", "bar", "baz"}}, }, `# Kubernetes-managed hosts file. 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet fe00::0 ip6-mcastprefix fe00::1 ip6-allnodes fe00::2 ip6-allrouters 203.0.113.1 podFoo.domainFoo podFoo # Entries added by HostAliases. 123.45.67.89 foo bar baz `, }, { "203.0.113.1", "podFoo", "domainFoo", []v1.HostAlias{ {IP: "123.45.67.89", Hostnames: []string{"foo", "bar", "baz"}}, {IP: "456.78.90.123", Hostnames: []string{"park", "doo", "boo"}}, }, `# Kubernetes-managed hosts file. 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet fe00::0 ip6-mcastprefix fe00::1 ip6-allnodes fe00::2 ip6-allrouters 203.0.113.1 podFoo.domainFoo podFoo # Entries added by HostAliases. 123.45.67.89 foo bar baz 456.78.90.123 park doo boo `, }, } for _, testCase := range testCases { actualContent := managedHostsFileContent(testCase.hostIP, testCase.hostName, testCase.hostDomainName, testCase.hostAliases) assert.Equal(t, testCase.expectedContent, string(actualContent), "hosts file content not expected") } } func TestRunInContainerNoSuchPod(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) defer testKubelet.Cleanup() kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime fakeRuntime.PodList = []*containertest.FakePod{} podName := "podFoo" podNamespace := "nsFoo" containerName := "containerFoo" output, err := kubelet.RunInContainer( kubecontainer.GetPodFullName(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: podName, Namespace: podNamespace}}), "", containerName, []string{"ls"}) assert.Error(t, err) assert.Nil(t, output, "output should be nil") } func TestRunInContainer(t *testing.T) { for _, testError := range []error{nil, errors.New("bar")} { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) defer testKubelet.Cleanup() kubelet := testKubelet.kubelet fakeRuntime := testKubelet.fakeRuntime fakeCommandRunner := containertest.FakeContainerCommandRunner{ Err: testError, Stdout: "foo", } kubelet.runner = &fakeCommandRunner containerID := kubecontainer.ContainerID{Type: "test", ID: "abc1234"} fakeRuntime.PodList = []*containertest.FakePod{ {Pod: &kubecontainer.Pod{ ID: "12345678", Name: "podFoo", Namespace: "nsFoo", Containers: []*kubecontainer.Container{ {Name: "containerFoo", ID: containerID, }, }, }}, } cmd := []string{"ls"} actualOutput, err := kubelet.RunInContainer("podFoo_nsFoo", "", "containerFoo", cmd) assert.Equal(t, containerID, fakeCommandRunner.ContainerID, "(testError=%v) ID", testError) assert.Equal(t, cmd, fakeCommandRunner.Cmd, "(testError=%v) command", testError) // this isn't 100% foolproof as a bug in a real ContainerCommandRunner where it fails to copy to stdout/stderr wouldn't be caught by this test assert.Equal(t, "foo", string(actualOutput), "(testError=%v) output", testError) assert.Equal(t, err, testError, "(testError=%v) err", testError) } } type testServiceLister struct { services []*v1.Service } func (ls testServiceLister) List(labels.Selector) ([]*v1.Service, error) { return ls.services, nil } type envs []kubecontainer.EnvVar func (e envs) Len() int { return len(e) } func (e envs) Swap(i, j int) { e[i], e[j] = e[j], e[i] } func (e envs) Less(i, j int) bool { return e[i].Name < e[j].Name } func buildService(name, namespace, clusterIP, protocol string, port int) *v1.Service { return &v1.Service{ ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace}, Spec: v1.ServiceSpec{ Ports: []v1.ServicePort{{ Protocol: v1.Protocol(protocol), Port: int32(port), }}, ClusterIP: clusterIP, }, } } func TestMakeEnvironmentVariables(t *testing.T) { trueVal := true services := []*v1.Service{ buildService("kubernetes", metav1.NamespaceDefault, "1.2.3.1", "TCP", 8081), buildService("test", "test1", "1.2.3.3", "TCP", 8083), buildService("kubernetes", "test2", "1.2.3.4", "TCP", 8084), buildService("test", "test2", "1.2.3.5", "TCP", 8085), buildService("test", "test2", "None", "TCP", 8085), buildService("test", "test2", "", "TCP", 8085), buildService("kubernetes", "kubernetes", "1.2.3.6", "TCP", 8086), buildService("not-special", "kubernetes", "1.2.3.8", "TCP", 8088), buildService("not-special", "kubernetes", "None", "TCP", 8088), buildService("not-special", "kubernetes", "", "TCP", 8088), } trueValue := true falseValue := false testCases := []struct { name string // the name of the test case ns string // the namespace to generate environment for enableServiceLinks *bool // enabling service links container *v1.Container // the container to use masterServiceNs string // the namespace to read master service info from nilLister bool // whether the lister should be nil configMap *v1.ConfigMap // an optional ConfigMap to pull from secret *v1.Secret // an optional Secret to pull from expectedEnvs []kubecontainer.EnvVar // a set of expected environment vars expectedError bool // does the test fail expectedEvent string // does the test emit an event }{ { name: "api server = Y, kubelet = Y", ns: "test1", enableServiceLinks: &falseValue, container: &v1.Container{ Env: []v1.EnvVar{ {Name: "FOO", Value: "BAR"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, }, }, masterServiceNs: metav1.NamespaceDefault, nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "BAR"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, {Name: "KUBERNETES_SERVICE_PORT", Value: "8081"}, {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.1"}, {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.1:8081"}, {Name: "KUBERNETES_PORT_8081_TCP", Value: "tcp://1.2.3.1:8081"}, {Name: "KUBERNETES_PORT_8081_TCP_PROTO", Value: "tcp"}, {Name: "KUBERNETES_PORT_8081_TCP_PORT", Value: "8081"}, {Name: "KUBERNETES_PORT_8081_TCP_ADDR", Value: "1.2.3.1"}, }, }, { name: "api server = Y, kubelet = N", ns: "test1", enableServiceLinks: &falseValue, container: &v1.Container{ Env: []v1.EnvVar{ {Name: "FOO", Value: "BAR"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, }, }, masterServiceNs: metav1.NamespaceDefault, nilLister: true, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "BAR"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, }, }, { name: "api server = N; kubelet = Y", ns: "test1", enableServiceLinks: &falseValue, container: &v1.Container{ Env: []v1.EnvVar{ {Name: "FOO", Value: "BAZ"}, }, }, masterServiceNs: metav1.NamespaceDefault, nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "BAZ"}, {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.1"}, {Name: "KUBERNETES_SERVICE_PORT", Value: "8081"}, {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.1:8081"}, {Name: "KUBERNETES_PORT_8081_TCP", Value: "tcp://1.2.3.1:8081"}, {Name: "KUBERNETES_PORT_8081_TCP_PROTO", Value: "tcp"}, {Name: "KUBERNETES_PORT_8081_TCP_PORT", Value: "8081"}, {Name: "KUBERNETES_PORT_8081_TCP_ADDR", Value: "1.2.3.1"}, }, }, { name: "api server = N; kubelet = Y; service env vars", ns: "test1", enableServiceLinks: &trueValue, container: &v1.Container{ Env: []v1.EnvVar{ {Name: "FOO", Value: "BAZ"}, }, }, masterServiceNs: metav1.NamespaceDefault, nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "BAZ"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, {Name: "TEST_SERVICE_PORT", Value: "8083"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.1"}, {Name: "KUBERNETES_SERVICE_PORT", Value: "8081"}, {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.1:8081"}, {Name: "KUBERNETES_PORT_8081_TCP", Value: "tcp://1.2.3.1:8081"}, {Name: "KUBERNETES_PORT_8081_TCP_PROTO", Value: "tcp"}, {Name: "KUBERNETES_PORT_8081_TCP_PORT", Value: "8081"}, {Name: "KUBERNETES_PORT_8081_TCP_ADDR", Value: "1.2.3.1"}, }, }, { name: "master service in pod ns", ns: "test2", enableServiceLinks: &falseValue, container: &v1.Container{ Env: []v1.EnvVar{ {Name: "FOO", Value: "ZAP"}, }, }, masterServiceNs: "kubernetes", nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "ZAP"}, {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.6"}, {Name: "KUBERNETES_SERVICE_PORT", Value: "8086"}, {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.6:8086"}, {Name: "KUBERNETES_PORT_8086_TCP", Value: "tcp://1.2.3.6:8086"}, {Name: "KUBERNETES_PORT_8086_TCP_PROTO", Value: "tcp"}, {Name: "KUBERNETES_PORT_8086_TCP_PORT", Value: "8086"}, {Name: "KUBERNETES_PORT_8086_TCP_ADDR", Value: "1.2.3.6"}, }, }, { name: "master service in pod ns, service env vars", ns: "test2", enableServiceLinks: &trueValue, container: &v1.Container{ Env: []v1.EnvVar{ {Name: "FOO", Value: "ZAP"}, }, }, masterServiceNs: "kubernetes", nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "FOO", Value: "ZAP"}, {Name: "TEST_SERVICE_HOST", Value: "1.2.3.5"}, {Name: "TEST_SERVICE_PORT", Value: "8085"}, {Name: "TEST_PORT", Value: "tcp://1.2.3.5:8085"}, {Name: "TEST_PORT_8085_TCP", Value: "tcp://1.2.3.5:8085"}, {Name: "TEST_PORT_8085_TCP_PROTO", Value: "tcp"}, {Name: "TEST_PORT_8085_TCP_PORT", Value: "8085"}, {Name: "TEST_PORT_8085_TCP_ADDR", Value: "1.2.3.5"}, {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.4"}, {Name: "KUBERNETES_SERVICE_PORT", Value: "8084"}, {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.4:8084"}, {Name: "KUBERNETES_PORT_8084_TCP", Value: "tcp://1.2.3.4:8084"}, {Name: "KUBERNETES_PORT_8084_TCP_PROTO", Value: "tcp"}, {Name: "KUBERNETES_PORT_8084_TCP_PORT", Value: "8084"}, {Name: "KUBERNETES_PORT_8084_TCP_ADDR", Value: "1.2.3.4"}, }, }, { name: "pod in master service ns", ns: "kubernetes", enableServiceLinks: &falseValue, container: &v1.Container{}, masterServiceNs: "kubernetes", nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.6"}, {Name: "KUBERNETES_SERVICE_PORT", Value: "8086"}, {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.6:8086"}, {Name: "KUBERNETES_PORT_8086_TCP", Value: "tcp://1.2.3.6:8086"}, {Name: "KUBERNETES_PORT_8086_TCP_PROTO", Value: "tcp"}, {Name: "KUBERNETES_PORT_8086_TCP_PORT", Value: "8086"}, {Name: "KUBERNETES_PORT_8086_TCP_ADDR", Value: "1.2.3.6"}, }, }, { name: "pod in master service ns, service env vars", ns: "kubernetes", enableServiceLinks: &trueValue, container: &v1.Container{}, masterServiceNs: "kubernetes", nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ {Name: "NOT_SPECIAL_SERVICE_HOST", Value: "1.2.3.8"}, {Name: "NOT_SPECIAL_SERVICE_PORT", Value: "8088"}, {Name: "NOT_SPECIAL_PORT", Value: "tcp://1.2.3.8:8088"}, {Name: "NOT_SPECIAL_PORT_8088_TCP", Value: "tcp://1.2.3.8:8088"}, {Name: "NOT_SPECIAL_PORT_8088_TCP_PROTO", Value: "tcp"}, {Name: "NOT_SPECIAL_PORT_8088_TCP_PORT", Value: "8088"}, {Name: "NOT_SPECIAL_PORT_8088_TCP_ADDR", Value: "1.2.3.8"}, {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.6"}, {Name: "KUBERNETES_SERVICE_PORT", Value: "8086"}, {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.6:8086"}, {Name: "KUBERNETES_PORT_8086_TCP", Value: "tcp://1.2.3.6:8086"}, {Name: "KUBERNETES_PORT_8086_TCP_PROTO", Value: "tcp"}, {Name: "KUBERNETES_PORT_8086_TCP_PORT", Value: "8086"}, {Name: "KUBERNETES_PORT_8086_TCP_ADDR", Value: "1.2.3.6"}, }, }, { name: "downward api pod", ns: "downward-api", enableServiceLinks: &falseValue, container: &v1.Container{ Env: []v1.EnvVar{ { Name: "POD_NAME", ValueFrom: &v1.EnvVarSource{ FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "metadata.name", }, }, }, { Name: "POD_NAMESPACE", ValueFrom: &v1.EnvVarSource{ FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "metadata.namespace", }, }, }, { Name: "POD_NODE_NAME", ValueFrom: &v1.EnvVarSource{ FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "spec.nodeName", }, }, }, { Name: "POD_SERVICE_ACCOUNT_NAME", ValueFrom: &v1.EnvVarSource{ FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "spec.serviceAccountName", }, }, }, { Name: "POD_IP", ValueFrom: &v1.EnvVarSource{ FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "status.podIP", }, }, }, { Name: "HOST_IP", ValueFrom: &v1.EnvVarSource{ FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "status.hostIP", }, }, }, }, }, masterServiceNs: "nothing", nilLister: true, expectedEnvs: []kubecontainer.EnvVar{ {Name: "POD_NAME", Value: "dapi-test-pod-name"}, {Name: "POD_NAMESPACE", Value: "downward-api"}, {Name: "POD_NODE_NAME", Value: "node-name"}, {Name: "POD_SERVICE_ACCOUNT_NAME", Value: "special"}, {Name: "POD_IP", Value: "1.2.3.4"}, {Name: "HOST_IP", Value: testKubeletHostIP}, }, }, { name: "env expansion", ns: "test1", enableServiceLinks: &falseValue, container: &v1.Container{ Env: []v1.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "POD_NAME", ValueFrom: &v1.EnvVarSource{ FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", //legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(), FieldPath: "metadata.name", }, }, }, { Name: "OUT_OF_ORDER_TEST", Value: "$(OUT_OF_ORDER_TARGET)", }, { Name: "OUT_OF_ORDER_TARGET", Value: "FOO", }, { Name: "EMPTY_VAR", }, { Name: "EMPTY_TEST", Value: "foo-$(EMPTY_VAR)", }, { Name: "POD_NAME_TEST2", Value: "test2-$(POD_NAME)", }, { Name: "POD_NAME_TEST3", Value: "$(POD_NAME_TEST2)-3", }, { Name: "LITERAL_TEST", Value: "literal-$(TEST_LITERAL)", }, { Name: "TEST_UNDEFINED", Value: "$(UNDEFINED_VAR)", }, }, }, masterServiceNs: "nothing", nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "POD_NAME", Value: "dapi-test-pod-name", }, { Name: "POD_NAME_TEST2", Value: "test2-dapi-test-pod-name", }, { Name: "POD_NAME_TEST3", Value: "test2-dapi-test-pod-name-3", }, { Name: "LITERAL_TEST", Value: "literal-test-test-test", }, { Name: "OUT_OF_ORDER_TEST", Value: "$(OUT_OF_ORDER_TARGET)", }, { Name: "OUT_OF_ORDER_TARGET", Value: "FOO", }, { Name: "TEST_UNDEFINED", Value: "$(UNDEFINED_VAR)", }, { Name: "EMPTY_VAR", }, { Name: "EMPTY_TEST", Value: "foo-", }, }, }, { name: "env expansion, service env vars", ns: "test1", enableServiceLinks: &trueValue, container: &v1.Container{ Env: []v1.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "POD_NAME", ValueFrom: &v1.EnvVarSource{ FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath: "metadata.name", }, }, }, { Name: "OUT_OF_ORDER_TEST", Value: "$(OUT_OF_ORDER_TARGET)", }, { Name: "OUT_OF_ORDER_TARGET", Value: "FOO", }, { Name: "EMPTY_VAR", }, { Name: "EMPTY_TEST", Value: "foo-$(EMPTY_VAR)", }, { Name: "POD_NAME_TEST2", Value: "test2-$(POD_NAME)", }, { Name: "POD_NAME_TEST3", Value: "$(POD_NAME_TEST2)-3", }, { Name: "LITERAL_TEST", Value: "literal-$(TEST_LITERAL)", }, { Name: "SERVICE_VAR_TEST", Value: "$(TEST_SERVICE_HOST):$(TEST_SERVICE_PORT)", }, { Name: "TEST_UNDEFINED", Value: "$(UNDEFINED_VAR)", }, }, }, masterServiceNs: "nothing", nilLister: false, expectedEnvs: []kubecontainer.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "POD_NAME", Value: "dapi-test-pod-name", }, { Name: "POD_NAME_TEST2", Value: "test2-dapi-test-pod-name", }, { Name: "POD_NAME_TEST3", Value: "test2-dapi-test-pod-name-3", }, { Name: "LITERAL_TEST", Value: "literal-test-test-test", }, { Name: "TEST_SERVICE_HOST", Value: "1.2.3.3", }, { Name: "TEST_SERVICE_PORT", Value: "8083", }, { Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083", }, { Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083", }, { Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp", }, { Name: "TEST_PORT_8083_TCP_PORT", Value: "8083", }, { Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3", }, { Name: "SERVICE_VAR_TEST", Value: "1.2.3.3:8083", }, { Name: "OUT_OF_ORDER_TEST", Value: "$(OUT_OF_ORDER_TARGET)", }, { Name: "OUT_OF_ORDER_TARGET", Value: "FOO", }, { Name: "TEST_UNDEFINED", Value: "$(UNDEFINED_VAR)", }, { Name: "EMPTY_VAR", }, { Name: "EMPTY_TEST", Value: "foo-", }, }, }, { name: "configmapkeyref_missing_optional", ns: "test", enableServiceLinks: &falseValue, container: &v1.Container{ Env: []v1.EnvVar{ { Name: "POD_NAME", ValueFrom: &v1.EnvVarSource{ ConfigMapKeyRef: &v1.ConfigMapKeySelector{ LocalObjectReference: v1.LocalObjectReference{Name: "missing-config-map"}, Key: "key", Optional: &trueVal, }, }, }, }, }, masterServiceNs: "nothing", expectedEnvs: nil, }, { name: "configmapkeyref_missing_key_optional", ns: "test", enableServiceLinks: &falseValue, container: &v1.Container{ Env: []v1.EnvVar{ { Name: "POD_NAME", ValueFrom: &v1.EnvVarSource{ ConfigMapKeyRef: &v1.ConfigMapKeySelector{ LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}, Key: "key", Optional: &trueVal, }, }, }, }, }, masterServiceNs: "nothing", nilLister: true, configMap: &v1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Namespace: "test1", Name: "test-configmap", }, Data: map[string]string{ "a": "b", }, }, expectedEnvs: nil, }, { name: "secretkeyref_missing_optional", ns: "test", enableServiceLinks: &falseValue, container: &v1.Container{ Env: []v1.EnvVar{ { Name: "POD_NAME", ValueFrom: &v1.EnvVarSource{ SecretKeyRef: &v1.SecretKeySelector{ LocalObjectReference: v1.LocalObjectReference{Name: "missing-secret"}, Key: "key", Optional: &trueVal, }, }, }, }, }, masterServiceNs: "nothing", expectedEnvs: nil, }, { name: "secretkeyref_missing_key_optional", ns: "test", enableServiceLinks: &falseValue, container: &v1.Container{ Env: []v1.EnvVar{ { Name: "POD_NAME", ValueFrom: &v1.EnvVarSource{ SecretKeyRef: &v1.SecretKeySelector{ LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}, Key: "key", Optional: &trueVal, }, }, }, }, }, masterServiceNs: "nothing", nilLister: true, secret: &v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: "test1", Name: "test-secret", }, Data: map[string][]byte{ "a": []byte("b"), }, }, expectedEnvs: nil, }, { name: "configmap", ns: "test1", enableServiceLinks: &falseValue, container: &v1.Container{ EnvFrom: []v1.EnvFromSource{ { ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}}, }, { Prefix: "p_", ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}}, }, }, Env: []v1.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "EXPANSION_TEST", Value: "$(REPLACE_ME)", }, { Name: "DUPE_TEST", Value: "ENV_VAR", }, }, }, masterServiceNs: "nothing", nilLister: false, configMap: &v1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Namespace: "test1", Name: "test-configmap", }, Data: map[string]string{ "REPLACE_ME": "FROM_CONFIG_MAP", "DUPE_TEST": "CONFIG_MAP", }, }, expectedEnvs: []kubecontainer.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "REPLACE_ME", Value: "FROM_CONFIG_MAP", }, { Name: "EXPANSION_TEST", Value: "FROM_CONFIG_MAP", }, { Name: "DUPE_TEST", Value: "ENV_VAR", }, { Name: "p_REPLACE_ME", Value: "FROM_CONFIG_MAP", }, { Name: "p_DUPE_TEST", Value: "CONFIG_MAP", }, }, }, { name: "configmap, service env vars", ns: "test1", enableServiceLinks: &trueValue, container: &v1.Container{ EnvFrom: []v1.EnvFromSource{ { ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}}, }, { Prefix: "p_", ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}}, }, }, Env: []v1.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "EXPANSION_TEST", Value: "$(REPLACE_ME)", }, { Name: "DUPE_TEST", Value: "ENV_VAR", }, }, }, masterServiceNs: "nothing", nilLister: false, configMap: &v1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Namespace: "test1", Name: "test-configmap", }, Data: map[string]string{ "REPLACE_ME": "FROM_CONFIG_MAP", "DUPE_TEST": "CONFIG_MAP", }, }, expectedEnvs: []kubecontainer.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "TEST_SERVICE_HOST", Value: "1.2.3.3", }, { Name: "TEST_SERVICE_PORT", Value: "8083", }, { Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083", }, { Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083", }, { Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp", }, { Name: "TEST_PORT_8083_TCP_PORT", Value: "8083", }, { Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3", }, { Name: "REPLACE_ME", Value: "FROM_CONFIG_MAP", }, { Name: "EXPANSION_TEST", Value: "FROM_CONFIG_MAP", }, { Name: "DUPE_TEST", Value: "ENV_VAR", }, { Name: "p_REPLACE_ME", Value: "FROM_CONFIG_MAP", }, { Name: "p_DUPE_TEST", Value: "CONFIG_MAP", }, }, }, { name: "configmap_missing", ns: "test1", enableServiceLinks: &falseValue, container: &v1.Container{ EnvFrom: []v1.EnvFromSource{ {ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}}}, }, }, masterServiceNs: "nothing", expectedError: true, }, { name: "configmap_missing_optional", ns: "test", enableServiceLinks: &falseValue, container: &v1.Container{ EnvFrom: []v1.EnvFromSource{ {ConfigMapRef: &v1.ConfigMapEnvSource{ Optional: &trueVal, LocalObjectReference: v1.LocalObjectReference{Name: "missing-config-map"}}}, }, }, masterServiceNs: "nothing", expectedEnvs: nil, }, { name: "configmap_invalid_keys", ns: "test", enableServiceLinks: &falseValue, container: &v1.Container{ EnvFrom: []v1.EnvFromSource{ {ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}}}, }, }, masterServiceNs: "nothing", configMap: &v1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Namespace: "test1", Name: "test-configmap", }, Data: map[string]string{ "1234": "abc", "1z": "abc", "key": "value", }, }, expectedEnvs: []kubecontainer.EnvVar{ { Name: "key", Value: "value", }, }, expectedEvent: "Warning InvalidEnvironmentVariableNames Keys [1234, 1z] from the EnvFrom configMap test/test-config-map were skipped since they are considered invalid environment variable names.", }, { name: "configmap_invalid_keys_valid", ns: "test", enableServiceLinks: &falseValue, container: &v1.Container{ EnvFrom: []v1.EnvFromSource{ { Prefix: "p_", ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}}, }, }, }, masterServiceNs: "", configMap: &v1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Namespace: "test1", Name: "test-configmap", }, Data: map[string]string{ "1234": "abc", }, }, expectedEnvs: []kubecontainer.EnvVar{ { Name: "p_1234", Value: "abc", }, }, }, { name: "secret", ns: "test1", enableServiceLinks: &falseValue, container: &v1.Container{ EnvFrom: []v1.EnvFromSource{ { SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}}, }, { Prefix: "p_", SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}}, }, }, Env: []v1.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "EXPANSION_TEST", Value: "$(REPLACE_ME)", }, { Name: "DUPE_TEST", Value: "ENV_VAR", }, }, }, masterServiceNs: "nothing", nilLister: false, secret: &v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: "test1", Name: "test-secret", }, Data: map[string][]byte{ "REPLACE_ME": []byte("FROM_SECRET"), "DUPE_TEST": []byte("SECRET"), }, }, expectedEnvs: []kubecontainer.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "REPLACE_ME", Value: "FROM_SECRET", }, { Name: "EXPANSION_TEST", Value: "FROM_SECRET", }, { Name: "DUPE_TEST", Value: "ENV_VAR", }, { Name: "p_REPLACE_ME", Value: "FROM_SECRET", }, { Name: "p_DUPE_TEST", Value: "SECRET", }, }, }, { name: "secret, service env vars", ns: "test1", enableServiceLinks: &trueValue, container: &v1.Container{ EnvFrom: []v1.EnvFromSource{ { SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}}, }, { Prefix: "p_", SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}}, }, }, Env: []v1.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "EXPANSION_TEST", Value: "$(REPLACE_ME)", }, { Name: "DUPE_TEST", Value: "ENV_VAR", }, }, }, masterServiceNs: "nothing", nilLister: false, secret: &v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: "test1", Name: "test-secret", }, Data: map[string][]byte{ "REPLACE_ME": []byte("FROM_SECRET"), "DUPE_TEST": []byte("SECRET"), }, }, expectedEnvs: []kubecontainer.EnvVar{ { Name: "TEST_LITERAL", Value: "test-test-test", }, { Name: "TEST_SERVICE_HOST", Value: "1.2.3.3", }, { Name: "TEST_SERVICE_PORT", Value: "8083", }, { Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083", }, { Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083", }, { Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp", }, { Name: "TEST_PORT_8083_TCP_PORT", Value: "8083", }, { Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3", }, { Name: "REPLACE_ME", Value: "FROM_SECRET", }, { Name: "EXPANSION_TEST", Value: "FROM_SECRET", }, { Name: "DUPE_TEST", Value: "ENV_VAR", }, { Name: "p_REPLACE_ME", Value: "FROM_SECRET", }, { Name: "p_DUPE_TEST", Value: "SECRET", }, }, }, { name: "secret_missing", ns: "test1", enableServiceLinks: &falseValue, container: &v1.Container{ EnvFrom: []v1.EnvFromSource{ {SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}}}, }, }, masterServiceNs: "nothing", expectedError: true, }, { name: "secret_missing_optional", ns: "test", enableServiceLinks: &falseValue, container: &v1.Container{ EnvFrom: []v1.EnvFromSource{ {SecretRef: &v1.SecretEnvSource{ LocalObjectReference: v1.LocalObjectReference{Name: "missing-secret"}, Optional: &trueVal}}, }, }, masterServiceNs: "nothing", expectedEnvs: nil, }, { name: "secret_invalid_keys", ns: "test", enableServiceLinks: &falseValue, container: &v1.Container{ EnvFrom: []v1.EnvFromSource{ {SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}}}, }, }, masterServiceNs: "nothing", secret: &v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: "test1", Name: "test-secret", }, Data: map[string][]byte{ "1234": []byte("abc"), "1z": []byte("abc"), "key.1": []byte("value"), }, }, expectedEnvs: []kubecontainer.EnvVar{ { Name: "key.1", Value: "value", }, }, expectedEvent: "Warning InvalidEnvironmentVariableNames Keys [1234, 1z] from the EnvFrom secret test/test-secret were skipped since they are considered invalid environment variable names.", }, { name: "secret_invalid_keys_valid", ns: "test", enableServiceLinks: &falseValue, container: &v1.Container{ EnvFrom: []v1.EnvFromSource{ { Prefix: "p_", SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}}, }, }, }, masterServiceNs: "", secret: &v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: "test1", Name: "test-secret", }, Data: map[string][]byte{ "1234.name": []byte("abc"), }, }, expectedEnvs: []kubecontainer.EnvVar{ { Name: "p_1234.name", Value: "abc", }, }, }, { name: "nil_enableServiceLinks", ns: "test", enableServiceLinks: nil, container: &v1.Container{ EnvFrom: []v1.EnvFromSource{ { Prefix: "p_", SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}}, }, }, }, masterServiceNs: "", secret: &v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: "test1", Name: "test-secret", }, Data: map[string][]byte{ "1234.name": []byte("abc"), }, }, expectedError: true, }, } for _, tc := range testCases { fakeRecorder := record.NewFakeRecorder(1) testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) testKubelet.kubelet.recorder = fakeRecorder defer testKubelet.Cleanup() kl := testKubelet.kubelet kl.masterServiceNamespace = tc.masterServiceNs if tc.nilLister { kl.serviceLister = nil } else { kl.serviceLister = testServiceLister{services} } testKubelet.fakeKubeClient.AddReactor("get", "configmaps", func(action core.Action) (bool, runtime.Object, error) { var err error if tc.configMap == nil { err = apierrors.NewNotFound(action.GetResource().GroupResource(), "configmap-name") } return true, tc.configMap, err }) testKubelet.fakeKubeClient.AddReactor("get", "secrets", func(action core.Action) (bool, runtime.Object, error) { var err error if tc.secret == nil { err = apierrors.NewNotFound(action.GetResource().GroupResource(), "secret-name") } return true, tc.secret, err }) testKubelet.fakeKubeClient.AddReactor("get", "secrets", func(action core.Action) (bool, runtime.Object, error) { var err error if tc.secret == nil { err = errors.New("no secret defined") } return true, tc.secret, err }) testPod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Namespace: tc.ns, Name: "dapi-test-pod-name", }, Spec: v1.PodSpec{ ServiceAccountName: "special", NodeName: "node-name", EnableServiceLinks: tc.enableServiceLinks, }, } podIP := "1.2.3.4" result, err := kl.makeEnvironmentVariables(testPod, tc.container, podIP) select { case e := <-fakeRecorder.Events: assert.Equal(t, tc.expectedEvent, e) default: assert.Equal(t, "", tc.expectedEvent) } if tc.expectedError { assert.Error(t, err, tc.name) } else { assert.NoError(t, err, "[%s]", tc.name) sort.Sort(envs(result)) sort.Sort(envs(tc.expectedEnvs)) assert.Equal(t, tc.expectedEnvs, result, "[%s] env entries", tc.name) } } } func waitingState(cName string) v1.ContainerStatus { return v1.ContainerStatus{ Name: cName, State: v1.ContainerState{ Waiting: &v1.ContainerStateWaiting{}, }, } } func waitingStateWithLastTermination(cName string) v1.ContainerStatus { return v1.ContainerStatus{ Name: cName, State: v1.ContainerState{ Waiting: &v1.ContainerStateWaiting{}, }, LastTerminationState: v1.ContainerState{ Terminated: &v1.ContainerStateTerminated{ ExitCode: 0, }, }, } } func runningState(cName string) v1.ContainerStatus { return v1.ContainerStatus{ Name: cName, State: v1.ContainerState{ Running: &v1.ContainerStateRunning{}, }, } } func stoppedState(cName string) v1.ContainerStatus { return v1.ContainerStatus{ Name: cName, State: v1.ContainerState{ Terminated: &v1.ContainerStateTerminated{}, }, } } func succeededState(cName string) v1.ContainerStatus { return v1.ContainerStatus{ Name: cName, State: v1.ContainerState{ Terminated: &v1.ContainerStateTerminated{ ExitCode: 0, }, }, } } func failedState(cName string) v1.ContainerStatus { return v1.ContainerStatus{ Name: cName, State: v1.ContainerState{ Terminated: &v1.ContainerStateTerminated{ ExitCode: -1, }, }, } } func TestPodPhaseWithRestartAlways(t *testing.T) { desiredState := v1.PodSpec{ NodeName: "machine", Containers: []v1.Container{ {Name: "containerA"}, {Name: "containerB"}, }, RestartPolicy: v1.RestartPolicyAlways, } tests := []struct { pod *v1.Pod status v1.PodPhase test string }{ {&v1.Pod{Spec: desiredState, Status: v1.PodStatus{}}, v1.PodPending, "waiting"}, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), runningState("containerB"), }, }, }, v1.PodRunning, "all running", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ stoppedState("containerA"), stoppedState("containerB"), }, }, }, v1.PodRunning, "all stopped with restart always", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), stoppedState("containerB"), }, }, }, v1.PodRunning, "mixed state #1 with restart always", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), }, }, }, v1.PodPending, "mixed state #2 with restart always", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), waitingState("containerB"), }, }, }, v1.PodPending, "mixed state #3 with restart always", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), waitingStateWithLastTermination("containerB"), }, }, }, v1.PodRunning, "backoff crashloop container with restart always", }, } for _, test := range tests { status := getPhase(&test.pod.Spec, test.pod.Status.ContainerStatuses) assert.Equal(t, test.status, status, "[test %s]", test.test) } } func TestPodPhaseWithRestartNever(t *testing.T) { desiredState := v1.PodSpec{ NodeName: "machine", Containers: []v1.Container{ {Name: "containerA"}, {Name: "containerB"}, }, RestartPolicy: v1.RestartPolicyNever, } tests := []struct { pod *v1.Pod status v1.PodPhase test string }{ {&v1.Pod{Spec: desiredState, Status: v1.PodStatus{}}, v1.PodPending, "waiting"}, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), runningState("containerB"), }, }, }, v1.PodRunning, "all running with restart never", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ succeededState("containerA"), succeededState("containerB"), }, }, }, v1.PodSucceeded, "all succeeded with restart never", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ failedState("containerA"), failedState("containerB"), }, }, }, v1.PodFailed, "all failed with restart never", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), succeededState("containerB"), }, }, }, v1.PodRunning, "mixed state #1 with restart never", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), }, }, }, v1.PodPending, "mixed state #2 with restart never", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), waitingState("containerB"), }, }, }, v1.PodPending, "mixed state #3 with restart never", }, } for _, test := range tests { status := getPhase(&test.pod.Spec, test.pod.Status.ContainerStatuses) assert.Equal(t, test.status, status, "[test %s]", test.test) } } func TestPodPhaseWithRestartOnFailure(t *testing.T) { desiredState := v1.PodSpec{ NodeName: "machine", Containers: []v1.Container{ {Name: "containerA"}, {Name: "containerB"}, }, RestartPolicy: v1.RestartPolicyOnFailure, } tests := []struct { pod *v1.Pod status v1.PodPhase test string }{ {&v1.Pod{Spec: desiredState, Status: v1.PodStatus{}}, v1.PodPending, "waiting"}, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), runningState("containerB"), }, }, }, v1.PodRunning, "all running with restart onfailure", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ succeededState("containerA"), succeededState("containerB"), }, }, }, v1.PodSucceeded, "all succeeded with restart onfailure", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ failedState("containerA"), failedState("containerB"), }, }, }, v1.PodRunning, "all failed with restart never", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), succeededState("containerB"), }, }, }, v1.PodRunning, "mixed state #1 with restart onfailure", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), }, }, }, v1.PodPending, "mixed state #2 with restart onfailure", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), waitingState("containerB"), }, }, }, v1.PodPending, "mixed state #3 with restart onfailure", }, { &v1.Pod{ Spec: desiredState, Status: v1.PodStatus{ ContainerStatuses: []v1.ContainerStatus{ runningState("containerA"), waitingStateWithLastTermination("containerB"), }, }, }, v1.PodRunning, "backoff crashloop container with restart onfailure", }, } for _, test := range tests { status := getPhase(&test.pod.Spec, test.pod.Status.ContainerStatuses) assert.Equal(t, test.status, status, "[test %s]", test.test) } } type fakeReadWriteCloser struct{} func (f *fakeReadWriteCloser) Write(data []byte) (int, error) { return 0, nil } func (f *fakeReadWriteCloser) Read(data []byte) (int, error) { return 0, nil } func (f *fakeReadWriteCloser) Close() error { return nil } func TestGetExec(t *testing.T) { const ( podName = "podFoo" podNamespace = "nsFoo" podUID types.UID = "12345678" containerID = "containerFoo" tty = true ) var ( podFullName = kubecontainer.GetPodFullName(podWithUIDNameNs(podUID, podName, podNamespace)) command = []string{"ls"} ) testcases := []struct { description string podFullName string container string expectError bool }{{ description: "success case", podFullName: podFullName, container: containerID, }, { description: "no such pod", podFullName: "bar" + podFullName, container: containerID, expectError: true, }, { description: "no such container", podFullName: podFullName, container: "containerBar", expectError: true, }} for _, tc := range testcases { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) defer testKubelet.Cleanup() kubelet := testKubelet.kubelet testKubelet.fakeRuntime.PodList = []*containertest.FakePod{ {Pod: &kubecontainer.Pod{ ID: podUID, Name: podName, Namespace: podNamespace, Containers: []*kubecontainer.Container{ {Name: containerID, ID: kubecontainer.ContainerID{Type: "test", ID: containerID}, }, }, }}, } description := "streaming - " + tc.description fakeRuntime := &containertest.FakeStreamingRuntime{FakeRuntime: testKubelet.fakeRuntime} kubelet.containerRuntime = fakeRuntime kubelet.streamingRuntime = fakeRuntime redirect, err := kubelet.GetExec(tc.podFullName, podUID, tc.container, command, remotecommand.Options{}) if tc.expectError { assert.Error(t, err, description) } else { assert.NoError(t, err, description) assert.Equal(t, containertest.FakeHost, redirect.Host, description+": redirect") } } } func TestGetPortForward(t *testing.T) { const ( podName = "podFoo" podNamespace = "nsFoo" podUID types.UID = "12345678" port int32 = 5000 ) testcases := []struct { description string podName string expectError bool }{{ description: "success case", podName: podName, }, { description: "no such pod", podName: "bar", expectError: true, }} for _, tc := range testcases { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) defer testKubelet.Cleanup() kubelet := testKubelet.kubelet testKubelet.fakeRuntime.PodList = []*containertest.FakePod{ {Pod: &kubecontainer.Pod{ ID: podUID, Name: podName, Namespace: podNamespace, Containers: []*kubecontainer.Container{ {Name: "foo", ID: kubecontainer.ContainerID{Type: "test", ID: "foo"}, }, }, }}, } description := "streaming - " + tc.description fakeRuntime := &containertest.FakeStreamingRuntime{FakeRuntime: testKubelet.fakeRuntime} kubelet.containerRuntime = fakeRuntime kubelet.streamingRuntime = fakeRuntime redirect, err := kubelet.GetPortForward(tc.podName, podNamespace, podUID, portforward.V4Options{}) if tc.expectError { assert.Error(t, err, description) } else { assert.NoError(t, err, description) assert.Equal(t, containertest.FakeHost, redirect.Host, description+": redirect") } } } func TestHasHostMountPVC(t *testing.T) { tests := map[string]struct { pvError error pvcError error expected bool podHasPVC bool pvcIsHostPath bool }{ "no pvc": {podHasPVC: false, expected: false}, "error fetching pvc": { podHasPVC: true, pvcError: fmt.Errorf("foo"), expected: false, }, "error fetching pv": { podHasPVC: true, pvError: fmt.Errorf("foo"), expected: false, }, "host path pvc": { podHasPVC: true, pvcIsHostPath: true, expected: true, }, "non host path pvc": { podHasPVC: true, pvcIsHostPath: false, expected: false, }, } for k, v := range tests { testKubelet := newTestKubelet(t, false) defer testKubelet.Cleanup() pod := &v1.Pod{ Spec: v1.PodSpec{}, } volumeToReturn := &v1.PersistentVolume{ Spec: v1.PersistentVolumeSpec{}, } if v.podHasPVC { pod.Spec.Volumes = []v1.Volume{ { VolumeSource: v1.VolumeSource{ PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{}, }, }, } if v.pvcIsHostPath { volumeToReturn.Spec.PersistentVolumeSource = v1.PersistentVolumeSource{ HostPath: &v1.HostPathVolumeSource{}, } } } testKubelet.fakeKubeClient.AddReactor("get", "persistentvolumeclaims", func(action core.Action) (bool, runtime.Object, error) { return true, &v1.PersistentVolumeClaim{ Spec: v1.PersistentVolumeClaimSpec{ VolumeName: "foo", }, }, v.pvcError }) testKubelet.fakeKubeClient.AddReactor("get", "persistentvolumes", func(action core.Action) (bool, runtime.Object, error) { return true, volumeToReturn, v.pvError }) actual := testKubelet.kubelet.hasHostMountPVC(pod) if actual != v.expected { t.Errorf("%s expected %t but got %t", k, v.expected, actual) } } } func TestHasNonNamespacedCapability(t *testing.T) { createPodWithCap := func(caps []v1.Capability) *v1.Pod { pod := &v1.Pod{ Spec: v1.PodSpec{ Containers: []v1.Container{{}}, }, } if len(caps) > 0 { pod.Spec.Containers[0].SecurityContext = &v1.SecurityContext{ Capabilities: &v1.Capabilities{ Add: caps, }, } } return pod } nilCaps := createPodWithCap([]v1.Capability{v1.Capability("foo")}) nilCaps.Spec.Containers[0].SecurityContext = nil tests := map[string]struct { pod *v1.Pod expected bool }{ "nil security contxt": {createPodWithCap(nil), false}, "nil caps": {nilCaps, false}, "namespaced cap": {createPodWithCap([]v1.Capability{v1.Capability("foo")}), false}, "non-namespaced cap MKNOD": {createPodWithCap([]v1.Capability{v1.Capability("MKNOD")}), true}, "non-namespaced cap SYS_TIME": {createPodWithCap([]v1.Capability{v1.Capability("SYS_TIME")}), true}, "non-namespaced cap SYS_MODULE": {createPodWithCap([]v1.Capability{v1.Capability("SYS_MODULE")}), true}, } for k, v := range tests { actual := hasNonNamespacedCapability(v.pod) if actual != v.expected { t.Errorf("%s failed, expected %t but got %t", k, v.expected, actual) } } } func TestHasHostVolume(t *testing.T) { pod := &v1.Pod{ Spec: v1.PodSpec{ Volumes: []v1.Volume{ { VolumeSource: v1.VolumeSource{ HostPath: &v1.HostPathVolumeSource{}, }, }, }, }, } result := hasHostVolume(pod) if !result { t.Errorf("expected host volume to enable host user namespace") } pod.Spec.Volumes[0].VolumeSource.HostPath = nil result = hasHostVolume(pod) if result { t.Errorf("expected nil host volume to not enable host user namespace") } } func TestHasHostNamespace(t *testing.T) { tests := map[string]struct { ps v1.PodSpec expected bool }{ "nil psc": { ps: v1.PodSpec{}, expected: false}, "host pid true": { ps: v1.PodSpec{ HostPID: true, SecurityContext: &v1.PodSecurityContext{}, }, expected: true, }, "host ipc true": { ps: v1.PodSpec{ HostIPC: true, SecurityContext: &v1.PodSecurityContext{}, }, expected: true, }, "host net true": { ps: v1.PodSpec{ HostNetwork: true, SecurityContext: &v1.PodSecurityContext{}, }, expected: true, }, "no host ns": { ps: v1.PodSpec{ SecurityContext: &v1.PodSecurityContext{}, }, expected: false, }, } for k, v := range tests { pod := &v1.Pod{ Spec: v.ps, } actual := hasHostNamespace(pod) if actual != v.expected { t.Errorf("%s failed, expected %t but got %t", k, v.expected, actual) } } } func TestTruncatePodHostname(t *testing.T) { for c, test := range map[string]struct { input string output string }{ "valid hostname": { input: "test.pod.hostname", output: "test.pod.hostname", }, "too long hostname": { input: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.1234567.1234567.", // 8*9=72 chars output: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.1234567", //8*8-1=63 chars }, "hostname end with .": { input: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456.1234567.", // 8*9-1=71 chars output: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456", //8*8-2=62 chars }, "hostname end with -": { input: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456-1234567.", // 8*9-1=71 chars output: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456", //8*8-2=62 chars }, } { t.Logf("TestCase: %q", c) output, err := truncatePodHostnameIfNeeded("test-pod", test.input) assert.NoError(t, err) assert.Equal(t, test.output, output) } }
Stackdriver/heapster
vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_pods_test.go
GO
apache-2.0
61,774
// Copyright 2015 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package tests import ( "testing" ) func TestBlockchain(t *testing.T) { t.Parallel() bt := new(testMatcher) // General state tests are 'exported' as blockchain tests, but we can run them natively. bt.skipLoad(`^GeneralStateTests/`) // Skip random failures due to selfish mining test. bt.skipLoad(`^bcForgedTest/bcForkUncle\.json`) bt.skipLoad(`^bcMultiChainTest/(ChainAtoChainB_blockorder|CallContractFromNotBestBlock)`) bt.skipLoad(`^bcTotalDifficultyTest/(lotsOfLeafs|lotsOfBranches|sideChainWithMoreTransactions)`) // Constantinople is not implemented yet. bt.skipLoad(`(?i)(constantinople)`) // Still failing tests bt.skipLoad(`^bcWalletTest.*_Byzantium$`) bt.walk(t, blockTestDir, func(t *testing.T, name string, test *BlockTest) { if err := bt.checkFailure(t, name, test.Run()); err != nil { t.Error(err) } }) }
Getline-Network/getline
vendor/github.com/ethereum/go-ethereum/tests/block_test.go
GO
apache-2.0
1,637
package org.keycloak.provider; import org.jboss.logging.Logger; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.ServiceLoader; /** * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a> */ public class ProviderManager { private static final Logger log = Logger.getLogger(ProviderManager.class); private List<ProviderLoader> loaders = new LinkedList<ProviderLoader>(); private Map<String, List<ProviderFactory>> cache = new HashMap<String, List<ProviderFactory>>(); public ProviderManager(ClassLoader baseClassLoader, String... resources) { List<ProviderLoaderFactory> factories = new LinkedList<ProviderLoaderFactory>(); for (ProviderLoaderFactory f : ServiceLoader.load(ProviderLoaderFactory.class, getClass().getClassLoader())) { factories.add(f); } log.debugv("Provider loaders {0}", factories); loaders.add(new DefaultProviderLoader(baseClassLoader)); if (resources != null) { for (String r : resources) { String type = r.substring(0, r.indexOf(':')); String resource = r.substring(r.indexOf(':') + 1, r.length()); boolean found = false; for (ProviderLoaderFactory f : factories) { if (f.supports(type)) { loaders.add(f.create(baseClassLoader, resource)); found = true; break; } } if (!found) { throw new RuntimeException("Provider loader for " + r + " not found"); } } } } public synchronized List<ProviderFactory> load(Spi spi) { List<ProviderFactory> factories = cache.get(spi.getName()); if (factories == null) { factories = new LinkedList<ProviderFactory>(); for (ProviderLoader loader : loaders) { List<ProviderFactory> f = loader.load(spi); if (f != null) { factories.addAll(f); } } } return factories; } public synchronized ProviderFactory load(Spi spi, String providerId) { for (ProviderFactory f : load(spi)) { if (f.getId().equals(providerId)) { return f; } } return null; } }
matzew/keycloak
services/src/main/java/org/keycloak/provider/ProviderManager.java
Java
apache-2.0
2,461
/* * 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.facebook.presto.sql.tree; import com.google.common.collect.ImmutableList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.collectingAndThen; public final class GroupingSets extends GroupingElement { private final List<List<QualifiedName>> sets; public GroupingSets(List<List<QualifiedName>> groupingSetList) { this(Optional.empty(), groupingSetList); } public GroupingSets(NodeLocation location, List<List<QualifiedName>> sets) { this(Optional.of(location), sets); } private GroupingSets(Optional<NodeLocation> location, List<List<QualifiedName>> sets) { super(location); requireNonNull(sets, "sets is null"); checkArgument(!sets.isEmpty(), "grouping sets cannot be empty"); this.sets = ImmutableList.copyOf(sets.stream().map(ImmutableList::copyOf).collect(Collectors.toList())); } public List<List<QualifiedName>> getSets() { return sets; } @Override public List<Set<Expression>> enumerateGroupingSets() { return sets.stream() .map(groupingSet -> groupingSet.stream() .map(DereferenceExpression::from) .collect(Collectors.<Expression>toSet())) .collect(collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } @Override protected <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitGroupingSets(this, context); } @Override public List<Node> getChildren() { return ImmutableList.of(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GroupingSets groupingSets = (GroupingSets) o; return Objects.equals(sets, groupingSets.sets); } @Override public int hashCode() { return Objects.hash(sets); } @Override public String toString() { return toStringHelper(this) .add("sets", sets) .toString(); } }
marsorp/blog
presto166/presto-parser/src/main/java/com/facebook/presto/sql/tree/GroupingSets.java
Java
apache-2.0
3,087
/* * 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.ignite.cache.store.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Map; import javax.cache.Cache; import javax.cache.configuration.Factory; import javax.cache.integration.CacheLoaderException; import javax.cache.integration.CacheWriterException; import org.apache.ignite.cache.store.CacheStore; import org.apache.ignite.cache.store.CacheStoreAdapter; import org.apache.ignite.cache.store.CacheStoreSession; import org.apache.ignite.cache.store.CacheStoreSessionListener; import org.apache.ignite.cache.store.CacheStoreSessionListenerAbstractSelfTest; import org.apache.ignite.lang.IgniteBiInClosure; import org.apache.ignite.resources.CacheStoreSessionResource; import org.apache.ignite.testframework.MvccFeatureChecker; import org.h2.jdbcx.JdbcConnectionPool; import org.junit.Before; /** * Tests for {@link CacheJdbcStoreSessionListener}. */ public class CacheJdbcStoreSessionListenerSelfTest extends CacheStoreSessionListenerAbstractSelfTest { /** */ @Before public void beforeCacheJdbcStoreSessionListenerSelfTest() { MvccFeatureChecker.skipIfNotSupported(MvccFeatureChecker.Feature.CACHE_STORE); } /** {@inheritDoc} */ @Override protected Factory<? extends CacheStore<Integer, Integer>> storeFactory() { return new Factory<CacheStore<Integer, Integer>>() { @Override public CacheStore<Integer, Integer> create() { return new Store(); } }; } /** {@inheritDoc} */ @Override protected Factory<CacheStoreSessionListener> sessionListenerFactory() { return new Factory<CacheStoreSessionListener>() { @Override public CacheStoreSessionListener create() { CacheJdbcStoreSessionListener lsnr = new CacheJdbcStoreSessionListener(); lsnr.setDataSource(JdbcConnectionPool.create(URL, "", "")); return lsnr; } }; } /** */ private static class Store extends CacheStoreAdapter<Integer, Integer> { /** */ private static String SES_CONN_KEY = "ses_conn"; /** */ @CacheStoreSessionResource private CacheStoreSession ses; /** {@inheritDoc} */ @Override public void loadCache(IgniteBiInClosure<Integer, Integer> clo, Object... args) { loadCacheCnt.incrementAndGet(); checkConnection(); } /** {@inheritDoc} */ @Override public Integer load(Integer key) throws CacheLoaderException { loadCnt.incrementAndGet(); checkConnection(); return null; } /** {@inheritDoc} */ @Override public void write(Cache.Entry<? extends Integer, ? extends Integer> entry) throws CacheWriterException { writeCnt.incrementAndGet(); checkConnection(); if (write.get()) { Connection conn = ses.attachment(); try { String table; switch (ses.cacheName()) { case "cache1": table = "Table1"; break; case "cache2": if (fail.get()) throw new CacheWriterException("Expected failure."); table = "Table2"; break; default: throw new CacheWriterException("Wring cache: " + ses.cacheName()); } PreparedStatement stmt = conn.prepareStatement( "INSERT INTO " + table + " (key, value) VALUES (?, ?)"); stmt.setInt(1, entry.getKey()); stmt.setInt(2, entry.getValue()); stmt.executeUpdate(); } catch (SQLException e) { throw new CacheWriterException(e); } } } /** {@inheritDoc} */ @Override public void delete(Object key) throws CacheWriterException { deleteCnt.incrementAndGet(); checkConnection(); } /** {@inheritDoc} */ @Override public void sessionEnd(boolean commit) { assertNull(ses.attachment()); } /** */ private void checkConnection() { Connection conn = ses.attachment(); assertNotNull(conn); try { assertFalse(conn.isClosed()); assertFalse(conn.getAutoCommit()); } catch (SQLException e) { throw new RuntimeException(e); } verifySameInstance(conn); } /** * @param conn Connection. */ private void verifySameInstance(Connection conn) { Map<String, Connection> props = ses.properties(); Connection sesConn = props.get(SES_CONN_KEY); if (sesConn == null) props.put(SES_CONN_KEY, conn); else { assertSame(conn, sesConn); reuseCnt.incrementAndGet(); } } } }
samaitra/ignite
modules/core/src/test/java/org/apache/ignite/cache/store/jdbc/CacheJdbcStoreSessionListenerSelfTest.java
Java
apache-2.0
6,111
// +build !windows package devices import ( "errors" "golang.org/x/sys/unix" ) func (d *Rule) Mkdev() (uint64, error) { if d.Major == Wildcard || d.Minor == Wildcard { return 0, errors.New("cannot mkdev() device with wildcards") } return unix.Mkdev(uint32(d.Major), uint32(d.Minor)), nil }
xychu/kubernetes
vendor/github.com/opencontainers/runc/libcontainer/devices/device_unix.go
GO
apache-2.0
301
package com.salesmanager.web.entity.shop; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; public class ContactForm { @NotEmpty private String name; @NotEmpty private String subject; @Email private String email; @NotEmpty private String comment; private String captchaResponseField; private String captchaChallengeField; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getCaptchaResponseField() { return captchaResponseField; } public void setCaptchaResponseField(String captchaResponseField) { this.captchaResponseField = captchaResponseField; } public String getCaptchaChallengeField() { return captchaChallengeField; } public void setCaptchaChallengeField(String captchaChallengeField) { this.captchaChallengeField = captchaChallengeField; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } }
asheshsaraf/ecommerce-simple
sm-shop/src/main/java/com/salesmanager/web/entity/shop/ContactForm.java
Java
apache-2.0
1,264
/* * [The "BSD license"] * Copyright (c) 2013 Terence Parr * Copyright (c) 2013 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 Antlr4.Runtime; using Antlr4.Runtime.Atn; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Sharpen; namespace Antlr4.Runtime { /// <summary> /// Indicates that the parser could not decide which of two or more paths /// to take based upon the remaining input. /// </summary> /// <remarks> /// Indicates that the parser could not decide which of two or more paths /// to take based upon the remaining input. It tracks the starting token /// of the offending input and also knows where the parser was /// in the various paths when the error. Reported by reportNoViableAlternative() /// </remarks> [System.Serializable] public class NoViableAltException : RecognitionException { private const long serialVersionUID = 5096000008992867052L; /// <summary>Which configurations did we try at input.index() that couldn't match input.LT(1)?</summary> [Nullable] private readonly ATNConfigSet deadEndConfigs; /// <summary> /// The token object at the start index; the input stream might /// not be buffering tokens so get a reference to it. /// </summary> /// <remarks> /// The token object at the start index; the input stream might /// not be buffering tokens so get a reference to it. (At the /// time the error occurred, of course the stream needs to keep a /// buffer all of the tokens but later we might not have access to those.) /// </remarks> [NotNull] private readonly IToken startToken; public NoViableAltException(Parser recognizer) : this(recognizer, ((ITokenStream)recognizer.InputStream), recognizer.CurrentToken, recognizer.CurrentToken, null, recognizer.RuleContext) { } public NoViableAltException(IRecognizer recognizer, ITokenStream input, IToken startToken, IToken offendingToken, ATNConfigSet deadEndConfigs, ParserRuleContext ctx) : base(recognizer, input, ctx) { // LL(1) error this.deadEndConfigs = deadEndConfigs; this.startToken = startToken; this.OffendingToken = offendingToken; } public virtual IToken StartToken { get { return startToken; } } [Nullable] public virtual ATNConfigSet DeadEndConfigs { get { return deadEndConfigs; } } } }
hce/antlr4
runtime/CSharp/runtime/CSharp/Antlr4.Runtime/NoViableAltException.cs
C#
bsd-3-clause
4,073
<?php // autoload.php @generated by Composer require_once __DIR__ . '/composer' . '/autoload_real.php'; return ComposerAutoloaderInitcdf72ff6e7f034c7d87f9bb5bd53f8da::getLoader();
ThreePeple/xjqjsjpgldjkkuiloojjloj
vendor/autoload.php
PHP
bsd-3-clause
183
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "platform/platform.h" #include "platformWin32/platformWin32.h" #include "time.h" void Platform::sleep(U32 ms) { Sleep(ms); } //-------------------------------------- void Platform::getLocalTime(LocalTime &lt) { struct tm *systime; time_t long_time; time( &long_time ); // Get time as long integer. systime = localtime( &long_time ); // Convert to local time. lt.sec = systime->tm_sec; lt.min = systime->tm_min; lt.hour = systime->tm_hour; lt.month = systime->tm_mon; lt.monthday = systime->tm_mday; lt.weekday = systime->tm_wday; lt.year = systime->tm_year; lt.yearday = systime->tm_yday; lt.isdst = systime->tm_isdst; } String Platform::localTimeToString( const LocalTime &lt ) { // Converting a LocalTime to SYSTEMTIME // requires a few annoying adjustments. SYSTEMTIME st; st.wMilliseconds = 0; st.wSecond = lt.sec; st.wMinute = lt.min; st.wHour = lt.hour; st.wDay = lt.monthday; st.wDayOfWeek = lt.weekday; st.wMonth = lt.month + 1; st.wYear = lt.year + 1900; TCHAR buffer[1024] = {0}; S32 result = 0; String outStr; // Note: The 'Ex' version of GetDateFormat and GetTimeFormat are preferred // and have better support for supplemental locales but are not supported // for version of windows prior to Vista. // // Would be nice if Torque was more aware of the OS version and // take full advantage of it. result = GetDateFormat( LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st, NULL, (LPTSTR)buffer, 1024 ); // Also would be nice to have a standard system for torque to // retrieve and display windows level errors using GetLastError and // FormatMessage... AssertWarn( result != 0, "Platform::getLocalTime" ); outStr += buffer; outStr += "\t"; result = GetTimeFormat( LOCALE_USER_DEFAULT, 0, &st, NULL, (LPTSTR)buffer, 1024 ); AssertWarn( result != 0, "Platform::localTimeToString, error occured!" ); outStr += buffer; return outStr; } U32 Platform::getTime() { time_t long_time; time( &long_time ); return long_time; } void Platform::fileToLocalTime(const FileTime & ft, LocalTime * lt) { if(!lt) return; dMemset(lt, 0, sizeof(LocalTime)); FILETIME winFileTime; winFileTime.dwLowDateTime = ft.v1; winFileTime.dwHighDateTime = ft.v2; SYSTEMTIME winSystemTime; // convert the filetime to local time FILETIME convertedFileTime; if(::FileTimeToLocalFileTime(&winFileTime, &convertedFileTime)) { // get the time into system time struct if(::FileTimeToSystemTime((const FILETIME *)&convertedFileTime, &winSystemTime)) { SYSTEMTIME * time = &winSystemTime; // fill it in... lt->sec = time->wSecond; lt->min = time->wMinute; lt->hour = time->wHour; lt->month = time->wMonth - 1; lt->monthday = time->wDay; lt->weekday = time->wDayOfWeek; lt->year = (time->wYear < 1900) ? 1900 : (time->wYear - 1900); // not calculated lt->yearday = 0; lt->isdst = false; } } } U32 Platform::getRealMilliseconds() { return GetTickCount(); } U32 Platform::getVirtualMilliseconds() { return winState.currentTime; } void Platform::advanceTime(U32 delta) { winState.currentTime += delta; }
elfprince13/Torque3D
Engine/source/platformWin32/winTime.cpp
C++
mit
4,979
require 'spec_helper' describe SCSSLint::Linter::DeclarationOrder do context 'when rule is empty' do let(:scss) { <<-SCSS } p { } SCSS it { should_not report_lint } end context 'when rule contains only properties' do let(:scss) { <<-SCSS } p { background: #000; margin: 5px; } SCSS it { should_not report_lint } end context 'when rule contains only mixins' do let(:scss) { <<-SCSS } p { @include border-radius(5px); @include box-shadow(5px); } SCSS it { should_not report_lint } end context 'when rule contains no mixins or properties' do let(:scss) { <<-SCSS } p { a { color: #f00; } } SCSS it { should_not report_lint } end context 'when rule contains properties after nested rules' do let(:scss) { <<-SCSS } p { a { color: #f00; } color: #f00; margin: 5px; } SCSS it { should report_lint } end context 'when @extend appears before any properties or rules' do let(:scss) { <<-SCSS } .warn { font-weight: bold; } .error { @extend .warn; color: #f00; a { color: #ccc; } } SCSS it { should_not report_lint } end context 'when @extend appears after a property' do let(:scss) { <<-SCSS } .warn { font-weight: bold; } .error { color: #f00; @extend .warn; a { color: #ccc; } } SCSS it { should report_lint line: 6 } end context 'when nested rule set' do context 'contains @extend before a property' do let(:scss) { <<-SCSS } p { a { @extend foo; color: #f00; } } SCSS it { should_not report_lint } end context 'contains @extend after a property' do let(:scss) { <<-SCSS } p { a { color: #f00; @extend foo; } } SCSS it { should report_lint line: 4 } end context 'contains @extend after nested rule set' do let(:scss) { <<-SCSS } p { a { span { color: #000; } @extend foo; } } SCSS it { should report_lint line: 6 } end end context 'when @include appears' do context 'before a property and rule set' do let(:scss) { <<-SCSS } .error { @include warn; color: #f00; a { color: #ccc; } } SCSS it { should_not report_lint } end context 'after a property and before a rule set' do let(:scss) { <<-SCSS } .error { color: #f00; @include warn; a { color: #ccc; } } SCSS it { should report_lint line: 3 } end end context 'when @include that features @content appears' do context 'before a property' do let(:scss) { <<-SCSS } .foo { @include breakpoint("phone") { color: #ccc; } color: #f00; } SCSS it { should report_lint line: 5 } end context 'after a property' do let(:scss) { <<-SCSS } .foo { color: #f00; @include breakpoint("phone") { color: #ccc; } } SCSS it { should_not report_lint } end context 'before an @extend' do let(:scss) { <<-SCSS } .foo { @include breakpoint("phone") { color: #ccc; } @extend .bar; } SCSS it { should report_lint line: 5 } end context 'before a rule set' do let(:scss) { <<-SCSS } .foo { @include breakpoint("phone") { color: #ccc; } a { color: #fff; } } SCSS it { should_not report_lint } end context 'after a rule set' do let(:scss) { <<-SCSS } .foo { a { color: #fff; } @include breakpoint("phone") { color: #ccc; } } SCSS it { should report_lint line: 5 } end context 'with its own nested rule set' do context 'before a property' do let(:scss) { <<-SCSS } @include breakpoint("phone") { a { color: #000; } color: #ccc; } SCSS it { should report_lint line: 5 } end context 'after a property' do let(:scss) { <<-SCSS } @include breakpoint("phone") { color: #ccc; a { color: #000; } } SCSS it { should_not report_lint } end end end context 'when the nesting is crazy deep' do context 'and nothing is wrong' do let(:scss) { <<-SCSS } div { ul { @extend .thing; li { @include box-shadow(yes); background: green; a { span { @include border-radius(5px); color: #000; } } } } } SCSS it { should_not report_lint } end context 'and something is wrong' do let(:scss) { <<-SCSS } div { ul { li { a { span { color: #000; @include border-radius(5px); } } } } } SCSS it { should report_lint line: 7 } end end context 'when inside a @media query and rule set' do context 'contains @extend before a property' do let(:scss) { <<-SCSS } @media only screen and (max-width: 1px) { a { @extend foo; color: #f00; } } SCSS it { should_not report_lint } end context 'contains @extend after a property' do let(:scss) { <<-SCSS } @media only screen and (max-width: 1px) { a { color: #f00; @extend foo; } } SCSS it { should report_lint line: 4 } end context 'contains @extend after nested rule set' do let(:scss) { <<-SCSS } @media only screen and (max-width: 1px) { a { span { color: #000; } @extend foo; } } SCSS it { should report_lint line: 6 } end end context 'when a pseudo-element appears before a property' do let(:scss) { <<-SCSS } a { &:hover { color: #000; } color: #fff; } SCSS it { should report_lint line: 5 } end context 'when a pseudo-element appears after a property' do let(:scss) { <<-SCSS } a { color: #fff; &:focus { color: #000; } } SCSS it { should_not report_lint } end context 'when a chained selector appears after a property' do let(:scss) { <<-SCSS } a { color: #fff; &.is-active { color: #000; } } SCSS it { should_not report_lint } end context 'when a chained selector appears before a property' do let(:scss) { <<-SCSS } a { &.is-active { color: #000; } color: #fff; } SCSS it { should report_lint line: 5 } end context 'when a selector with parent reference appears after a property' do let(:scss) { <<-SCSS } a { color: #fff; .is-active & { color: #000; } } SCSS it { should_not report_lint } end context 'when a selector with parent reference appears before a property' do let(:scss) { <<-SCSS } a { .is-active & { color: #000; } color: #fff; } SCSS it { should report_lint line: 5 } end context 'when a pseudo-element appears after a property' do let(:scss) { <<-SCSS } a { color: #fff; &:before { color: #000; } } SCSS it { should_not report_lint } end context 'when a pseudo-element appears before a property' do let(:scss) { <<-SCSS } a { &:before { color: #000; } color: #fff; } SCSS it { should report_lint line: 5 } end context 'when a direct descendent appears after a property' do let(:scss) { <<-SCSS } a { color: #fff; > .foo { color: #000; } } SCSS it { should_not report_lint } end context 'when a direct descendent appears before a property' do let(:scss) { <<-SCSS } a { > .foo { color: #000; } color: #fff; } SCSS it { should report_lint line: 5 } end context 'when an adjacent sibling appears after a property' do let(:scss) { <<-SCSS } a { color: #fff; & + .foo { color: #000; } } SCSS it { should_not report_lint } end context 'when an adjacent sibling appears before a property' do let(:scss) { <<-SCSS } a { & + .foo { color: #000; } color: #fff; } SCSS it { should report_lint line: 5 } end context 'when a general sibling appears after a property' do let(:scss) { <<-SCSS } a { color: #fff; & ~ .foo { color: #000; } } SCSS it { should_not report_lint } end context 'when a general sibling appears before a property' do let(:scss) { <<-SCSS } a { & ~ .foo { color: #000; } color: #fff; } SCSS it { should report_lint line: 5 } end context 'when a descendent appears after a property' do let(:scss) { <<-SCSS } a { color: #fff; .foo { color: #000; } } SCSS it { should_not report_lint } end context 'when a descendent appears before a property' do let(:scss) { <<-SCSS } a { .foo { color: #000; } color: #fff; } SCSS it { should report_lint line: 5 } end context 'when order within a media query is incorrect' do let(:scss) { <<-SCSS } @media screen and (max-width: 600px) { @include mix1(); width: 100%; height: 100%; @include mix2(); } SCSS it { should report_lint } end end
ingdir/scss-lint
spec/scss_lint/linter/declaration_order_spec.rb
Ruby
mit
10,847
/** * Module dependencies */ var fs = require('fs-extra') , _ = require('lodash') , path = require('path') , reportback = require('reportback')(); /** * Generate a JSON file * * @option {String} rootPath * @option {Object} data * [@option {Boolean} force=false] * * @handlers success * @handlers error * @handlers alreadyExists */ module.exports = function ( options, handlers ) { // Provide default values for handlers handlers = reportback.extend(handlers, { alreadyExists: 'error' }); // Provide defaults and validate required options _.defaults(options, { force: false }); var missingOpts = _.difference([ 'rootPath', 'data' ], Object.keys(options)); if ( missingOpts.length ) return handlers.invalid(missingOpts); var rootPath = path.resolve( process.cwd() , options.rootPath ); // Only override an existing file if `options.force` is true fs.exists(rootPath, function (exists) { if (exists && !options.force) { return handlers.alreadyExists('Something else already exists at ::'+rootPath); } if ( exists ) { fs.remove(rootPath, function deletedOldINode (err) { if (err) return handlers.error(err); _afterwards_(); }); } else _afterwards_(); function _afterwards_ () { fs.outputJSON(rootPath, options.data, function (err){ if (err) return handlers.error(err); else handlers.success(); }); } }); };
harindaka/node-mvc-starter
node_modules/sails/node_modules/sails-generate/lib/helpers/jsonfile/index.js
JavaScript
mit
1,395
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web.Http; using WebStack.QA.Share.Controllers.TypeLibrary; namespace WebStack.QA.Share.Controllers { public class CollectionController : ApiController { #region IEnumerable, IEnumerable<T> [AcceptVerbs("PUT", "POST", "DELETE")] public IEnumerable EchoIEnumerable(IEnumerable input) { return input; } [AcceptVerbs("PUT", "POST", "DELETE")] public IEnumerable<string> EchoIEnumerableOfString(IEnumerable<string> input) { return input; } [AcceptVerbs("PUT", "POST", "DELETE")] public IEnumerable<Address> EchoIEnumerableOfAddress(IEnumerable<Address> input) { return input; } #endregion #region IList, IList<T>, List<T> [AcceptVerbs("PUT", "POST", "DELETE")] public IList EchoIList(IList input) { return input; } [AcceptVerbs("PUT", "POST", "DELETE")] public IList<int?> EchoIListNullableInt(IList<int?> input) { return input; } [AcceptVerbs("PUT", "POST", "DELETE")] public List<object> EchoListOfObject(List<object> input) { return input; } #endregion #region Array [AcceptVerbs("PUT", "POST", "DELETE")] public Guid[] ReverseGuidArray(Guid[] input) { return (input == null) ? null : input.Reverse().ToArray(); } [AcceptVerbs("PUT", "POST", "DELETE")] public double?[] ReverseNullableDoubleArray(double?[] input) { return (input == null) ? null : input.Reverse().ToArray(); } [AcceptVerbs("PUT", "POST", "DELETE")] public Nullable<DateTime>[] ReverseNullableDateTimeArray(Nullable<DateTime>[] input) { return (input == null) ? null : input.Reverse().ToArray(); } [AcceptVerbs("PUT", "POST", "DELETE")] public Person[] ReversePersonArray(Person[] input) { return (input == null) ? null : input.Reverse().ToArray(); } #endregion #region IDictionary, Dictionary<K,V> [AcceptVerbs("PUT", "POST", "DELETE")] public IDictionary EchoIDictionary(IDictionary input) { return input; } [AcceptVerbs("PUT", "POST", "DELETE")] public IDictionary<string, Person> EchoIDictionaryOfStringAndPerson(IDictionary<string, Person> input) { return input; } [AcceptVerbs("PUT", "POST", "DELETE")] public Dictionary<int, string> EchoListOfObject(Dictionary<int, string> input) { return input; } #endregion } }
lungisam/WebApi
OData/test/E2ETestV3/WebStack.QA.Share/Controllers/CollectionController.cs
C#
mit
2,854
require 'active_support/execution_wrapper' module ActiveSupport #-- # This class defines several callbacks: # # to_prepare -- Run once at application startup, and also from # +to_run+. # # to_run -- Run before a work run that is reloading. If # +reload_classes_only_on_change+ is true (the default), the class # unload will have already occurred. # # to_complete -- Run after a work run that has reloaded. If # +reload_classes_only_on_change+ is false, the class unload will # have occurred after the work run, but before this callback. # # before_class_unload -- Run immediately before the classes are # unloaded. # # after_class_unload -- Run immediately after the classes are # unloaded. # class Reloader < ExecutionWrapper define_callbacks :prepare define_callbacks :class_unload def self.to_prepare(*args, &block) set_callback(:prepare, *args, &block) end def self.before_class_unload(*args, &block) set_callback(:class_unload, *args, &block) end def self.after_class_unload(*args, &block) set_callback(:class_unload, :after, *args, &block) end to_run(:after) { self.class.prepare! } # Initiate a manual reload def self.reload! executor.wrap do new.tap do |instance| begin instance.run! ensure instance.complete! end end end prepare! end def self.run! # :nodoc: if check! super else Null end end # Run the supplied block as a work unit, reloading code as needed def self.wrap executor.wrap do super end end class_attribute :executor class_attribute :check self.executor = Executor self.check = lambda { false } def self.check! # :nodoc: @should_reload ||= check.call end def self.reloaded! # :nodoc: @should_reload = false end def self.prepare! # :nodoc: new.run_callbacks(:prepare) end def initialize super @locked = false end # Acquire the ActiveSupport::Dependencies::Interlock unload lock, # ensuring it will be released automatically def require_unload_lock! unless @locked ActiveSupport::Dependencies.interlock.start_unloading @locked = true end end # Release the unload lock if it has been previously obtained def release_unload_lock! if @locked @locked = false ActiveSupport::Dependencies.interlock.done_unloading end end def run! # :nodoc: super release_unload_lock! end def class_unload!(&block) # :nodoc: require_unload_lock! run_callbacks(:class_unload, &block) end def complete! # :nodoc: super self.class.reloaded! ensure release_unload_lock! end end end
afuerstenau/daily-notes
vendor/cache/ruby/2.5.0/gems/activesupport-5.0.6/lib/active_support/reloader.rb
Ruby
mit
2,922
Boxen::Application.configure do config.action_controller.perform_caching = false config.action_dispatch.best_standards_support = :builtin config.active_record.auto_explain_threshold_in_seconds = 0.5 config.active_record.mass_assignment_sanitizer = :strict config.active_support.deprecation = :log config.assets.compress = false config.assets.debug = true config.cache_classes = false config.consider_all_requests_local = true config.whiny_nils = true end
wednesdayagency/boxen-web
config/environments/development.rb
Ruby
mit
685
// 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; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal static class FailFast { [DebuggerHidden] [DoesNotReturn] internal static void OnFatalException(Exception exception) { // EDMAURER Now using the managed API to fail fast so as to default // to the managed VS debug engine and hopefully get great // Watson bucketing. Before vanishing trigger anyone listening. if (Debugger.IsAttached) { Debugger.Break(); } #if !NET20 // don't fail fast with an aggregate exception that is masking true exception if (exception is AggregateException aggregate && aggregate.InnerExceptions.Count == 1) { exception = aggregate.InnerExceptions[0]; } #endif DumpStackTrace(exception: exception); Environment.FailFast(exception.ToString(), exception); throw ExceptionUtilities.Unreachable; // to satisfy [DoesNotReturn] } [DebuggerHidden] [DoesNotReturn] internal static void Fail(string message) { DumpStackTrace(message: message); Environment.FailFast(message); throw ExceptionUtilities.Unreachable; // to satisfy [DoesNotReturn] } /// <summary> /// Dumps the stack trace of the exception and the handler to the console. This is useful /// for debugging unit tests that hit a fatal exception /// </summary> [Conditional("DEBUG")] internal static void DumpStackTrace(Exception? exception = null, string? message = null) { Console.WriteLine("Dumping info before call to failfast"); if (message is object) { Console.WriteLine(message); } if (exception is object) { Console.WriteLine("Exception info"); for (Exception? current = exception; current is object; current = current.InnerException) { Console.WriteLine(current.Message); Console.WriteLine(current.StackTrace); } } #if !NET20 && !NETSTANDARD1_3 Console.WriteLine("Stack trace of handler"); var stackTrace = new StackTrace(); Console.WriteLine(stackTrace.ToString()); #endif Console.Out.Flush(); } /// <summary> /// Checks for the given <paramref name="condition"/>; if the <paramref name="condition"/> is <c>true</c>, /// immediately terminates the process without running any pending <c>finally</c> blocks or finalizers /// and causes a crash dump to be collected (if the system is configured to do so). /// Otherwise, the process continues normally. /// </summary> /// <param name="condition">The conditional expression to evaluate.</param> /// <param name="message">An optional message to be recorded in the dump in case of failure. Can be <c>null</c>.</param> [Conditional("DEBUG")] [DebuggerHidden] internal static void Assert([DoesNotReturnIf(false)] bool condition, string? message = null) { if (condition) { return; } if (Debugger.IsAttached) { Debugger.Break(); } DumpStackTrace(message: message); Environment.FailFast("ASSERT FAILED" + Environment.NewLine + message); } } }
AlekseyTs/roslyn
src/Compilers/Core/Portable/InternalUtilities/FailFast.cs
C#
mit
3,898
/* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ package com.phonegap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.phonegap.api.Plugin; import com.phonegap.api.PluginResult; import android.util.Log; public class ContactManager extends Plugin { private ContactAccessor contactAccessor; private static final String LOG_TAG = "Contact Query"; public static final int UNKNOWN_ERROR = 0; public static final int INVALID_ARGUMENT_ERROR = 1; public static final int TIMEOUT_ERROR = 2; public static final int PENDING_OPERATION_ERROR = 3; public static final int IO_ERROR = 4; public static final int NOT_SUPPORTED_ERROR = 5; public static final int PERMISSION_DENIED_ERROR = 20; /** * Constructor. */ public ContactManager() { } /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackId The callback id used when calling back into JavaScript. * @return A PluginResult object with a status and message. */ public PluginResult execute(String action, JSONArray args, String callbackId) { PluginResult.Status status = PluginResult.Status.OK; String result = ""; /** * Check to see if we are on an Android 1.X device. If we are return an error as we * do not support this as of PhoneGap 1.0. */ if (android.os.Build.VERSION.RELEASE.startsWith("1.")) { JSONObject res = null; try { res = new JSONObject(); res.put("code", NOT_SUPPORTED_ERROR); res.put("message", "Contacts are not supported in Android 1.X devices"); } catch (JSONException e) { // This should never happen Log.e(LOG_TAG, e.getMessage(), e); } return new PluginResult(PluginResult.Status.ERROR, res); } /** * Only create the contactAccessor after we check the Android version or the program will crash * older phones. */ if (this.contactAccessor == null) { this.contactAccessor = new ContactAccessorSdk5(this.webView, this.ctx); } try { if (action.equals("search")) { JSONArray res = contactAccessor.search(args.getJSONArray(0), args.optJSONObject(1)); return new PluginResult(status, res, "navigator.contacts.cast"); } else if (action.equals("save")) { String id = contactAccessor.save(args.getJSONObject(0)); if (id != null) { JSONObject res = contactAccessor.getContactById(id); if (res != null) { return new PluginResult(status, res); } } } else if (action.equals("remove")) { if (contactAccessor.remove(args.getString(0))) { return new PluginResult(status, result); } } // If we get to this point an error has occurred JSONObject r = new JSONObject(); r.put("code", UNKNOWN_ERROR); return new PluginResult(PluginResult.Status.ERROR, r); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); return new PluginResult(PluginResult.Status.JSON_EXCEPTION); } } }
roadlabs/android
appMobiLib/src/com/phonegap/ContactManager.java
Java
mit
3,535
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2016 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #include "Trace.hpp" #include "Vector.hpp" #include "Util/GlobalSliceAllocator.hpp" #include <algorithm> Trace::Trace(const unsigned _no_thin_time, const unsigned max_time, const unsigned max_size) :cached_size(0), max_time(max_time), no_thin_time(_no_thin_time), max_size(max_size), opt_size((3 * max_size) / 4) { assert(max_size >= 4); } void Trace::clear() { assert(cached_size == delta_list.size()); assert(cached_size == chronological_list.size()); average_delta_distance = 0; average_delta_time = 0; delta_list.clear(); chronological_list.clear_and_dispose(MakeDisposer()); cached_size = 0; assert(cached_size == delta_list.size()); assert(cached_size == chronological_list.size()); ++modify_serial; ++append_serial; } unsigned Trace::GetRecentTime(const unsigned t) const { if (empty()) return 0; const TracePoint &last = back(); if (last.GetTime() > t) return last.GetTime() - t; return 0; } void Trace::UpdateDelta(TraceDelta &td) { assert(cached_size == delta_list.size()); assert(cached_size == chronological_list.size()); if (&td == &chronological_list.front() || &td == &chronological_list.back()) return; const auto ci = chronological_list.iterator_to(td); const TraceDelta &previous = *std::prev(ci); const TraceDelta &next = *std::next(ci); delta_list.erase(delta_list.iterator_to(td)); td.Update(previous.point, next.point); delta_list.insert(td); } void Trace::EraseInside(DeltaList::iterator it) { assert(cached_size > 0); assert(cached_size == delta_list.size()); assert(cached_size == chronological_list.size()); assert(it != delta_list.end()); const TraceDelta &td = *it; assert(!td.IsEdge()); const auto ci = chronological_list.iterator_to(td); TraceDelta &previous = const_cast<TraceDelta &>(*std::prev(ci)); TraceDelta &next = const_cast<TraceDelta &>(*std::next(ci)); // now delete the item chronological_list.erase(chronological_list.iterator_to(td)); delta_list.erase_and_dispose(it, MakeDisposer()); --cached_size; // and update the deltas UpdateDelta(previous); UpdateDelta(next); } bool Trace::EraseDelta(const unsigned target_size, const unsigned recent) { assert(cached_size == delta_list.size()); assert(cached_size == chronological_list.size()); if (size() <= 2) return false; bool modified = false; const unsigned recent_time = GetRecentTime(recent); auto candidate = delta_list.begin(); while (size() > target_size) { const TraceDelta &td = *candidate; if (!td.IsEdge() && td.point.GetTime() < recent_time) { EraseInside(candidate); candidate = delta_list.begin(); // find new top modified = true; } else { ++candidate; // suppressed removal, skip it. } } return modified; } bool Trace::EraseEarlierThan(const unsigned p_time) { if (p_time == 0 || empty() || GetFront().point.GetTime() >= p_time) // there will be nothing to remove return false; do { auto ci = chronological_list.begin(); TraceDelta &td = *ci; chronological_list.erase(ci); auto i = delta_list.find(td); assert(i != delta_list.end()); delta_list.erase_and_dispose(i, MakeDisposer()); --cached_size; } while (!empty() && GetFront().point.GetTime() < p_time); // need to set deltas for first point, only one of these // will occur (have to search for this point) if (!empty()) EraseStart(GetFront()); ++modify_serial; ++append_serial; return true; } void Trace::EraseLaterThan(const unsigned min_time) { assert(min_time > 0); assert(!empty()); while (!empty() && GetBack().point.GetTime() > min_time) { TraceDelta &td = GetBack(); chronological_list.erase(chronological_list.iterator_to(td)); auto i = delta_list.find(td); assert(i != delta_list.end()); delta_list.erase_and_dispose(i, MakeDisposer()); --cached_size; } /* need to set deltas for first point, only one of these will occur (have to search for this point) */ if (!empty()) EraseStart(GetBack()); } /** * Update start node (and neighbour) after min time pruning */ void Trace::EraseStart(TraceDelta &td) { delta_list.erase(delta_list.iterator_to(td)); td.elim_distance = null_delta; td.elim_time = null_time; delta_list.insert(td); } void Trace::push_back(const TracePoint &point) { assert(cached_size == delta_list.size()); assert(cached_size == chronological_list.size()); if (empty()) { // first point determines origin for flat projection task_projection.Reset(point.GetLocation()); task_projection.Update(); } else if (point.GetTime() < back().GetTime()) { // gone back in time if (point.GetTime() + 180 < back().GetTime()) { /* not fixable, clear the trace and restart from scratch */ clear(); return; } /* not much, try to fix it */ EraseLaterThan(point.GetTime() - 10); ++modify_serial; } else if (point.GetTime() - back().GetTime() < 2) // only add one item per two seconds return; EnforceTimeWindow(point.GetTime()); if (size() >= max_size) Thin(); assert(size() < max_size); TraceDelta *td = allocator.allocate(1); allocator.construct(td, point); td->point.Project(task_projection); delta_list.insert(*td); chronological_list.push_back(*td); ++cached_size; if (td != &chronological_list.front()) UpdateDelta(*std::prev(chronological_list.iterator_to(*td))); ++append_serial; } unsigned Trace::CalcAverageDeltaDistance(const unsigned no_thin) const { unsigned r = GetRecentTime(no_thin); unsigned acc = 0; unsigned counter = 0; const auto end = chronological_list.end(); for (auto it = chronological_list.begin(); it != end && it->point.GetTime() < r; ++it, ++counter) acc += it->delta_distance; if (counter) return acc / counter; return 0; } unsigned Trace::CalcAverageDeltaTime(const unsigned no_thin) const { unsigned r = GetRecentTime(no_thin); unsigned counter = 0; /* find the last item before the "r" timestamp */ const auto end = chronological_list.end(); ChronologicalList::const_iterator it; for (it = chronological_list.begin(); it != end && it->point.GetTime() < r; ++it) ++counter; if (counter < 2) return 0; --it; --counter; unsigned start_time = front().GetTime(); unsigned end_time = it->point.GetTime(); return (end_time - start_time) / counter; } void Trace::EnforceTimeWindow(unsigned latest_time) { if (max_time == null_time) /* no time window configured */ return; if (latest_time <= max_time) /* this can only happen if the flight launched shortly after midnight; this check is just here to avoid unsigned integer underflow */ return; EraseEarlierThan(latest_time - max_time); } void Trace::Thin2() { const unsigned target_size = opt_size; assert(size() > target_size); // if still too big, remove points based on line simplification EraseDelta(target_size, no_thin_time); if (size() <= target_size) return; // if still too big, thin again, ignoring recency if (no_thin_time > 0) EraseDelta(target_size, 0); assert(size() <= target_size); } void Trace::Thin() { assert(cached_size == delta_list.size()); assert(cached_size == chronological_list.size()); assert(size() == max_size); Thin2(); assert(size() < max_size); average_delta_distance = CalcAverageDeltaDistance(no_thin_time); average_delta_time = CalcAverageDeltaTime(no_thin_time); ++modify_serial; ++append_serial; } void Trace::GetPoints(TracePointVector& iov) const { iov.clear(); iov.reserve(size()); std::copy(begin(), end(), std::back_inserter(iov)); } template<typename I> class PointerIterator { I i; public: typedef typename I::iterator_category iterator_category; typedef typename I::pointer value_type; typedef typename I::pointer *pointer; typedef value_type &reference; typedef typename I::difference_type difference_type; PointerIterator() = default; explicit PointerIterator(I _i):i(_i) {} PointerIterator<I> &operator=(const PointerIterator<I> &other) = default; PointerIterator<I> &operator--() { --i; return *this; } PointerIterator<I> &operator++() { ++i; return *this; } typename I::pointer operator*() { return &*i; } bool operator==(const PointerIterator<I> &other) const { return i == other.i; } bool operator!=(const PointerIterator<I> &other) const { return i != other.i; } }; void Trace::GetPoints(TracePointerVector &v) const { v.clear(); v.reserve(size()); std::copy(PointerIterator<decltype(begin())>(begin()), PointerIterator<decltype(end())>(end()), std::back_inserter(v)); } bool Trace::SyncPoints(TracePointerVector &v) const { assert(v.size() <= size()); if (v.size() == size()) /* no news */ return false; v.reserve(size()); PointerIterator<decltype(end())> e(end()); std::copy(std::prev(e, size() - v.size()), e, std::back_inserter(v)); assert(v.size() == size()); return true; } void Trace::GetPoints(TracePointVector &v, unsigned min_time, const GeoPoint &location, double min_distance) const { /* skip the trace points that are before min_time */ Trace::const_iterator i = begin(), end = this->end(); unsigned skipped = 0; while (true) { if (i == end) /* nothing left */ return; if (i->GetTime() >= min_time) /* found the first point that is within range */ break; ++i; ++skipped; } assert(skipped < size()); v.reserve(size() - skipped); const unsigned range = ProjectRange(location, min_distance); const unsigned sq_range = range * range; do { v.push_back(*i); i.NextSquareRange(sq_range, end); } while (i != end); }
matthewturnbull/xcsoar
src/Engine/Trace/Trace.cpp
C++
gpl-2.0
10,776
/* * 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 io.mycat.util; /* * BE ADVISED: New imports added here might introduce new dependencies for * the clientutil jar. If in doubt, run the `ant test-clientutil-jar' target * afterward, and ensure the tests still pass. */ import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; /** * Utility methods to make ByteBuffers less painful * The following should illustrate the different ways byte buffers can be used * * public void testArrayOffet() * { * * byte[] b = "test_slice_array".getBytes(); * ByteBuffer bb = ByteBuffer.allocate(1024); * * assert bb.position() == 0; * assert bb.limit() == 1024; * assert bb.capacity() == 1024; * * bb.put(b); * * assert bb.position() == b.length; * assert bb.remaining() == bb.limit() - bb.position(); * * ByteBuffer bb2 = bb.slice(); * * assert bb2.position() == 0; * * //slice should begin at other buffers current position * assert bb2.arrayOffset() == bb.position(); * * //to match the position in the underlying array one needs to * //track arrayOffset * assert bb2.limit()+bb2.arrayOffset() == bb.limit(); * * * assert bb2.remaining() == bb.remaining(); * * } * * } * */ public class ByteBufferUtil { public static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.wrap(new byte[0]); public static int compareUnsigned(ByteBuffer o1, ByteBuffer o2) { return FastByteOperations.compareUnsigned(o1, o2); } public static int compare(byte[] o1, ByteBuffer o2) { return FastByteOperations.compareUnsigned(o1, 0, o1.length, o2); } public static int compare(ByteBuffer o1, byte[] o2) { return FastByteOperations.compareUnsigned(o1, o2, 0, o2.length); } /** * Decode a String representation. * This method assumes that the encoding charset is UTF_8. * * @param buffer a byte buffer holding the string representation * @return the decoded string */ public static String string(ByteBuffer buffer) throws CharacterCodingException { return string(buffer, StandardCharsets.UTF_8); } /** * Decode a String representation. * This method assumes that the encoding charset is UTF_8. * * @param buffer a byte buffer holding the string representation * @param position the starting position in {@code buffer} to start decoding from * @param length the number of bytes from {@code buffer} to use * @return the decoded string */ public static String string(ByteBuffer buffer, int position, int length) throws CharacterCodingException { return string(buffer, position, length, StandardCharsets.UTF_8); } /** * Decode a String representation. * * @param buffer a byte buffer holding the string representation * @param position the starting position in {@code buffer} to start decoding from * @param length the number of bytes from {@code buffer} to use * @param charset the String encoding charset * @return the decoded string */ public static String string(ByteBuffer buffer, int position, int length, Charset charset) throws CharacterCodingException { ByteBuffer copy = buffer.duplicate(); copy.position(position); copy.limit(copy.position() + length); return string(copy, charset); } /** * Decode a String representation. * * @param buffer a byte buffer holding the string representation * @param charset the String encoding charset * @return the decoded string */ public static String string(ByteBuffer buffer, Charset charset) throws CharacterCodingException { return charset.newDecoder().decode(buffer.duplicate()).toString(); } /** * You should almost never use this. Instead, use the write* methods to avoid copies. */ public static byte[] getArray(ByteBuffer buffer) { int length = buffer.remaining(); if (buffer.hasArray()) { int boff = buffer.arrayOffset() + buffer.position(); return Arrays.copyOfRange(buffer.array(), boff, boff + length); } // else, DirectByteBuffer.get() is the fastest route byte[] bytes = new byte[length]; buffer.duplicate().get(bytes); return bytes; } /** * ByteBuffer adaptation of org.apache.commons.lang3.ArrayUtils.lastIndexOf method * * @param buffer the array to traverse for looking for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the start index (i.e. BB position) to travers backwards from * @return the last index (i.e. BB position) of the value within the array * [between buffer.position() and buffer.limit()]; <code>-1</code> if not found. */ public static int lastIndexOf(ByteBuffer buffer, byte valueToFind, int startIndex) { assert buffer != null; if (startIndex < buffer.position()) { return -1; } else if (startIndex >= buffer.limit()) { startIndex = buffer.limit() - 1; } for (int i = startIndex; i >= buffer.position(); i--) { if (valueToFind == buffer.get(i)) { return i; } } return -1; } /** * Encode a String in a ByteBuffer using UTF_8. * * @param s the string to encode * @return the encoded string */ public static ByteBuffer bytes(String s) { return ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8)); } /** * Encode a String in a ByteBuffer using the provided charset. * * @param s the string to encode * @param charset the String encoding charset to use * @return the encoded string */ public static ByteBuffer bytes(String s, Charset charset) { return ByteBuffer.wrap(s.getBytes(charset)); } /** * @return a new copy of the data in @param buffer * USUALLY YOU SHOULD USE ByteBuffer.duplicate() INSTEAD, which creates a new Buffer * (so you can mutate its position without affecting the original) without copying the underlying array. */ public static ByteBuffer clone(ByteBuffer buffer) { assert buffer != null; if (buffer.remaining() == 0) { return EMPTY_BYTE_BUFFER; } ByteBuffer clone = ByteBuffer.allocate(buffer.remaining()); if (buffer.hasArray()) { System.arraycopy(buffer.array(), buffer.arrayOffset() + buffer.position(), clone.array(), 0, buffer.remaining()); } else { clone.put(buffer.duplicate()); clone.flip(); } return clone; } public static void arrayCopy(ByteBuffer src, int srcPos, byte[] dst, int dstPos, int length) { FastByteOperations.copy(src, srcPos, dst, dstPos, length); } /** * Transfer bytes from one ByteBuffer to another. * This function acts as System.arrayCopy() but for ByteBuffers. * * @param src the source ByteBuffer * @param srcPos starting position in the source ByteBuffer * @param dst the destination ByteBuffer * @param dstPos starting position in the destination ByteBuffer * @param length the number of bytes to copy */ public static void arrayCopy(ByteBuffer src, int srcPos, ByteBuffer dst, int dstPos, int length) { FastByteOperations.copy(src, srcPos, dst, dstPos, length); } public static void writeWithLength(byte[] bytes, DataOutput out) throws IOException { out.writeInt(bytes.length); out.write(bytes); } /* @return An unsigned short in an integer. */ public static int readShortLength(DataInput in) throws IOException { return in.readUnsignedShort(); } public static byte[] readBytes(DataInput in, int length) throws IOException { assert length > 0 : "length is not > 0: " + length; byte[] bytes = new byte[length]; in.readFully(bytes); return bytes; } /** * Convert a byte buffer to an integer. * Does not change the byte buffer position. * * @param bytes byte buffer to convert to integer * @return int representation of the byte buffer */ public static int toInt(ByteBuffer bytes) { return bytes.getInt(bytes.position()); } public static long toLong(ByteBuffer bytes) { return bytes.getLong(bytes.position()); } public static float toFloat(ByteBuffer bytes) { return bytes.getFloat(bytes.position()); } public static double toDouble(ByteBuffer bytes) { return bytes.getDouble(bytes.position()); } public static ByteBuffer bytes(int i) { return ByteBuffer.allocate(4).putInt(0, i); } public static ByteBuffer bytes(long n) { return ByteBuffer.allocate(8).putLong(0, n); } public static ByteBuffer bytes(float f) { return ByteBuffer.allocate(4).putFloat(0, f); } public static ByteBuffer bytes(double d) { return ByteBuffer.allocate(8).putDouble(0, d); } public static InputStream inputStream(ByteBuffer bytes) { final ByteBuffer copy = bytes.duplicate(); return new InputStream() { public int read() { if (!copy.hasRemaining()) { return -1; } return copy.get() & 0xFF; } @Override public int read(byte[] bytes, int off, int len) { if (!copy.hasRemaining()) { return -1; } len = Math.min(len, copy.remaining()); copy.get(bytes, off, len); return len; } @Override public int available() { return copy.remaining(); } }; } /** * Compare two ByteBuffer at specified offsets for length. * Compares the non equal bytes as unsigned. * @param bytes1 First byte buffer to compare. * @param offset1 Position to start the comparison at in the first array. * @param bytes2 Second byte buffer to compare. * @param offset2 Position to start the comparison at in the second array. * @param length How many bytes to compare? * @return -1 if byte1 is less than byte2, 1 if byte2 is less than byte1 or 0 if equal. */ public static int compareSubArrays(ByteBuffer bytes1, int offset1, ByteBuffer bytes2, int offset2, int length) { if (bytes1 == null) { return bytes2 == null ? 0 : -1; } if (bytes2 == null) { return 1; } assert bytes1.limit() >= offset1 + length : "The first byte array isn't long enough for the specified offset and length."; assert bytes2.limit() >= offset2 + length : "The second byte array isn't long enough for the specified offset and length."; for (int i = 0; i < length; i++) { byte byte1 = bytes1.get(offset1 + i); byte byte2 = bytes2.get(offset2 + i); // if (byte1 == byte2) // continue; // compare non-equal bytes as unsigned if( byte1 != byte2 ) { return (byte1 & 0xFF) < (byte2 & 0xFF) ? -1 : 1; } } return 0; } public static ByteBuffer bytes(InetAddress address) { return ByteBuffer.wrap(address.getAddress()); } // Returns whether {@code prefix} is a prefix of {@code value}. public static boolean isPrefix(ByteBuffer prefix, ByteBuffer value) { if (prefix.remaining() > value.remaining()) { return false; } int diff = value.remaining() - prefix.remaining(); return prefix.equals(value.duplicate().limit(value.remaining() - diff)); } /** trims size of bytebuffer to exactly number of bytes in it, to do not hold too much memory */ public static ByteBuffer minimalBufferFor(ByteBuffer buf) { return buf.capacity() > buf.remaining() || !buf.hasArray() ? ByteBuffer.wrap(getArray(buf)) : buf; } // Doesn't change bb position public static int getShortLength(ByteBuffer bb, int position) { int length = (bb.get(position) & 0xFF) << 8; return length | (bb.get(position + 1) & 0xFF); } // changes bb position public static int readShortLength(ByteBuffer bb) { int length = (bb.get() & 0xFF) << 8; return length | (bb.get() & 0xFF); } // changes bb position public static void writeShortLength(ByteBuffer bb, int length) { bb.put((byte) ((length >> 8) & 0xFF)); bb.put((byte) (length & 0xFF)); } // changes bb position public static ByteBuffer readBytes(ByteBuffer bb, int length) { ByteBuffer copy = bb.duplicate(); copy.limit(copy.position() + length); bb.position(bb.position() + length); return copy; } // changes bb position public static ByteBuffer readBytesWithShortLength(ByteBuffer bb) { int length = readShortLength(bb); return readBytes(bb, length); } }
zagnix/Mycat-Server
src/main/java/io/mycat/util/ByteBufferUtil.java
Java
gpl-2.0
14,659
/* 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. * */ #include "mohawk/cstime_game.h" #include "mohawk/cstime_ui.h" #include "mohawk/cstime_view.h" #include "mohawk/resource.h" #include "common/algorithm.h" // find #include "common/events.h" #include "common/system.h" #include "common/textconsole.h" #include "graphics/fontman.h" namespace Mohawk { // read a null-terminated string from a stream static Common::String readString(Common::SeekableReadStream *stream) { Common::String ret; while (!stream->eos()) { byte in = stream->readByte(); if (!in) break; ret += in; } return ret; } CSTimeInterface::CSTimeInterface(MohawkEngine_CSTime *vm) : _vm(vm) { _sceneRect = Common::Rect(0, 0, 640, 340); _uiRect = Common::Rect(0, 340, 640, 480); _bookRect = Common::Rect(_uiRect.right - 95, _uiRect.top + 32, _uiRect.right - 25, _uiRect.top + 122); _noteRect = Common::Rect(_uiRect.left + 27, _uiRect.top + 31, _uiRect.left + 103, _uiRect.top + 131); _dialogTextRect = Common::Rect(0 + 125, 340 + 40, 640 - 125, 480 - 20); _cursorActive = false; _cursorShapes[0] = 0xFFFF; _cursorShapes[1] = 0xFFFF; _cursorShapes[2] = 0xFFFF; _cursorNextTime = 0; _help = new CSTimeHelp(_vm); _inventoryDisplay = new CSTimeInventoryDisplay(_vm, _dialogTextRect); _book = new CSTimeBook(_vm); _note = new CSTimeCarmenNote(_vm); _options = new CSTimeOptions(_vm); // The demo uses hardcoded system fonts if (!(_vm->getFeatures() & GF_DEMO)) { if (!_normalFont.loadFromFON("EvP14.fon")) error("failed to load normal font"); if (!_dialogFont.loadFromFON("Int1212.fon")) error("failed to load dialog font"); if (!_rolloverFont.loadFromFON("Int1818.fon")) error("failed to load rollover font"); } _uiFeature = NULL; _dialogTextFeature = NULL; _rolloverTextFeature = NULL; _bubbleTextFeature = NULL; _mouseWasInScene = false; _state = kCSTimeInterfaceStateNormal; _dialogLines.resize(5); _dialogLineColors.resize(5); } CSTimeInterface::~CSTimeInterface() { delete _help; delete _inventoryDisplay; delete _book; delete _note; delete _options; } const Graphics::Font &CSTimeInterface::getNormalFont() const { // HACK: Use a ScummVM GUI font in place of a system one for the demo if (_vm->getFeatures() & GF_DEMO) return *FontMan.getFontByUsage(Graphics::FontManager::kGUIFont); return _normalFont; } const Graphics::Font &CSTimeInterface::getDialogFont() const { // HACK: Use a ScummVM GUI font in place of a system one for the demo if (_vm->getFeatures() & GF_DEMO) return *FontMan.getFontByUsage(Graphics::FontManager::kGUIFont); return _dialogFont; } const Graphics::Font &CSTimeInterface::getRolloverFont() const { // HACK: Use a ScummVM GUI font in place of a system one for the demo if (_vm->getFeatures() & GF_DEMO) return *FontMan.getFontByUsage(Graphics::FontManager::kBigGUIFont); return _rolloverFont; } void CSTimeInterface::cursorInstall() { _vm->getView()->loadBitmapCursors(200); } void CSTimeInterface::cursorIdle() { if (!_cursorActive || _cursorShapes[1] == 0xFFFF) return; if (_vm->_system->getMillis() <= _cursorNextTime + 250) return; cursorSetShape(_cursorShapes[1], false); _cursorShapes[1] = _cursorShapes[2]; _cursorShapes[2] = 0xFFFF; } void CSTimeInterface::cursorActivate(bool state) { _cursorActive = state; } void CSTimeInterface::cursorChangeShape(uint16 id) { if (_cursorShapes[1] == 0xFFFF) _cursorShapes[1] = id; else _cursorShapes[2] = id; } uint16 CSTimeInterface::cursorGetShape() { if (_cursorShapes[2] != 0xFFFF) return _cursorShapes[2]; else if (_cursorShapes[1] != 0xFFFF) return _cursorShapes[1]; else return _cursorShapes[0]; } void CSTimeInterface::cursorSetShape(uint16 id, bool reset) { if (_cursorShapes[0] != id) { _cursorShapes[0] = id; _vm->getView()->setBitmapCursor(id); _cursorNextTime = _vm->_system->getMillis(); } } void CSTimeInterface::cursorSetWaitCursor() { uint16 shape = cursorGetShape(); switch (shape) { case 8: cursorChangeShape(9); break; case 9: break; case 11: cursorChangeShape(12); break; case 13: cursorChangeShape(15); break; default: cursorChangeShape(3); break; } } void CSTimeInterface::openResFile() { _vm->loadResourceFile("data/iface"); } void CSTimeInterface::install() { uint16 resourceId = 100; // TODO _vm->getView()->installGroup(resourceId, 16, 0, true, 100); // TODO: store/reset these _dialogTextFeature = _vm->getView()->installViewFeature(0, 0, NULL); _dialogTextFeature->_data.bounds = _dialogTextRect; _dialogTextFeature->_data.bitmapIds[0] = 0; // We don't set a port. _dialogTextFeature->_moveProc = (Module::FeatureProc)&CSTimeModule::dialogTextMoveProc; _dialogTextFeature->_drawProc = (Module::FeatureProc)&CSTimeModule::dialogTextDrawProc; _dialogTextFeature->_timeProc = NULL; _dialogTextFeature->_flags = kFeatureOldSortForeground; // FIXME: not in original _rolloverTextFeature = _vm->getView()->installViewFeature(0, 0, NULL); _rolloverTextFeature->_data.bounds = Common::Rect(0 + 100, 340 + 5, 640 - 100, 480 - 25); _rolloverTextFeature->_data.bitmapIds[0] = 0; _rolloverTextFeature->_moveProc = (Module::FeatureProc)&CSTimeModule::rolloverTextMoveProc; _rolloverTextFeature->_drawProc = (Module::FeatureProc)&CSTimeModule::rolloverTextDrawProc; _rolloverTextFeature->_timeProc = NULL; _rolloverTextFeature->_flags = kFeatureOldSortForeground; // FIXME: not in original } void CSTimeInterface::draw() { // TODO if (!_uiFeature) { uint32 flags = kFeatureSortStatic | kFeatureNewNoLoop; assert(flags == 0x4800000); uint16 resourceId = 100; // TODO _uiFeature = _vm->getView()->installViewFeature(resourceId, flags, NULL); // TODO: special-case for case 20 } else { _uiFeature->resetFeatureScript(1, 0); // TODO: special-case for case 20 } // TODO: special-case for cases 19 and 20 _note->drawSmallNote(); _book->drawSmallBook(); _inventoryDisplay->draw(); } void CSTimeInterface::idle() { // TODO: inv sound handling _vm->getCase()->getCurrScene()->idle(); _inventoryDisplay->idle(); cursorIdle(); _vm->getView()->idleView(); } void CSTimeInterface::mouseDown(Common::Point pos) { _vm->resetTimeout(); if (_options->getState()) { // TODO: _options->mouseDown(pos); return; } if (!cursorGetState()) return; if (_vm->getCase()->getCurrScene()->eventIsActive()) return; switch (cursorGetShape()) { case 1: cursorChangeShape(4); break; case 2: cursorChangeShape(5); break; case 13: cursorChangeShape(14); break; } if (_book->getState() == 2) { // TODO: _book->mouseDown(pos); return; } // TODO: if in sailing puzzle, sailing puzzle mouse down, return if (_note->getState() > 0) { return; } if (_sceneRect.contains(pos)) { _vm->getCase()->getCurrScene()->mouseDown(pos); return; } // TODO: case 20 ui craziness is handled seperately.. CSTimeConversation *conv = _vm->getCase()->getCurrConversation(); if (_bookRect.contains(pos) || (_noteRect.contains(pos) && _note->havePiece(0xffff))) { if (conv->getState() != (uint)~0) conv->end(false); if (_help->getState() != (uint)~0) _help->end(); return; } if (_help->getState() != (uint)~0) { _help->mouseDown(pos); return; } if (conv->getState() != (uint)~0) { conv->mouseDown(pos); return; } // TODO: handle symbols if (_inventoryDisplay->_invRect.contains(pos)) { // TODO: special handling for case 6 _inventoryDisplay->mouseDown(pos); } } void CSTimeInterface::mouseMove(Common::Point pos) { if (_options->getState()) { // TODO: _options->mouseMove(pos); return; } if (!cursorGetState()) return; if (_mouseWasInScene && _uiRect.contains(pos)) { clearTextLine(); _mouseWasInScene = false; } if (_book->getState() == 2) { // TODO: _book->mouseMove(pos); return; } if (_note->getState() == 2) return; // TODO: case 20 ui craziness is handled seperately.. if (_sceneRect.contains(pos) && !_vm->getCase()->getCurrScene()->eventIsActive()) { _vm->getCase()->getCurrScene()->mouseMove(pos); _mouseWasInScene = true; return; } if (cursorGetShape() == 13) { cursorSetShape(1); return; } else if (cursorGetShape() == 14) { cursorSetShape(4); return; } bool mouseIsDown = _vm->getEventManager()->getButtonState() & 1; if (_book->getState() == 1 && !_bookRect.contains(pos)) { if (_state != kCSTimeInterfaceStateDragging) { clearTextLine(); cursorSetShape(mouseIsDown ? 4 : 1); _book->setState(0); } return; } // TODO: case 20 ui craziness again if (_note->getState() == 1 && !_noteRect.contains(pos)) { if (_state != kCSTimeInterfaceStateDragging) { clearTextLine(); cursorSetShape(mouseIsDown ? 4 : 1); _note->setState(0); } return; } // TODO: handle symbols if (_bookRect.contains(pos)) { if (_state != kCSTimeInterfaceStateDragging) { displayTextLine("Open Chronopedia"); cursorSetShape(mouseIsDown ? 5 : 2); _book->setState(1); } return; } if (_noteRect.contains(pos)) { if (_state != kCSTimeInterfaceStateDragging && _note->havePiece(0xffff) && !_note->getState()) { displayTextLine("Look at Note"); cursorSetShape(mouseIsDown ? 5 : 2); _note->setState(1); } return; } if (_vm->getCase()->getCurrConversation()->getState() != (uint)~0) { _vm->getCase()->getCurrConversation()->mouseMove(pos); return; } if (_help->getState() != (uint)~0) { _help->mouseMove(pos); return; } if (_state == kCSTimeInterfaceStateDragging) { // FIXME: dragging return; } // FIXME: if case is 20, we're done, return if (_inventoryDisplay->_invRect.contains(pos)) { _inventoryDisplay->mouseMove(pos); } } void CSTimeInterface::mouseUp(Common::Point pos) { if (_options->getState()) { // TODO: options->mouseUp(pos); return; } if (!cursorGetState()) return; if (_state == kCSTimeInterfaceStateDragging) { stopDragging(); return; } if (_state == kCSTimeInterfaceStateDragStart) _state = kCSTimeInterfaceStateNormal; switch (cursorGetShape()) { case 4: cursorChangeShape(1); break; case 5: cursorChangeShape(2); break; case 14: cursorChangeShape(13); break; } if (_vm->getCase()->getCurrScene()->eventIsActive()) { if (_vm->getCurrentEventType() == kCSTimeEventWaitForClick) _vm->mouseClicked(); return; } if (_book->getState() == 2) { // TODO: _book->mouseUp(pos); return; } if (_note->getState() == 2) { _note->closeNote(); mouseMove(pos); return; } // TODO: if in sailing puzzle, sailing puzzle mouse up, return // TODO: case 20 ui craziness is handled seperately.. if (_sceneRect.contains(pos)) { _vm->getCase()->getCurrScene()->mouseUp(pos); return; } if (_vm->getCase()->getCurrConversation()->getState() != (uint)~0) { _vm->getCase()->getCurrConversation()->mouseUp(pos); return; } if (_help->getState() != (uint)~0) { _help->mouseUp(pos); return; } // TODO: handle symbols if (_bookRect.contains(pos)) { // TODO: handle flashing cuffs // TODO: _book->open(); return; } if (_noteRect.contains(pos)) { // TODO: special-casing for case 19 if (_note->havePiece(0xffff)) _note->drawBigNote(); } if (_inventoryDisplay->_invRect.contains(pos)) { // TODO: special-casing for case 6 _inventoryDisplay->mouseUp(pos); } } void CSTimeInterface::cursorOverHotspot() { if (!cursorGetState()) return; if (_state == kCSTimeInterfaceStateDragStart || _state == kCSTimeInterfaceStateDragging) return; if (cursorGetShape() == 3 || cursorGetShape() == 9) return; bool mouseIsDown = _vm->getEventManager()->getButtonState() & 1; if (mouseIsDown) cursorSetShape(5); else if (cursorGetShape() == 1) cursorChangeShape(2); } void CSTimeInterface::setCursorForCurrentPoint() { uint16 shape = 1; Common::Point mousePos = _vm->getEventManager()->getMousePos(); if (_bookRect.contains(mousePos)) { shape = 2; } else { uint convState = _vm->getCase()->getCurrConversation()->getState(); uint helpState = _help->getState(); // TODO: symbols too if (convState == (uint)~0 || convState == 0 || helpState == (uint)~0 || helpState == 0) { // FIXME: set cursor to 2 if inventory display occupied } else if (convState == 1 || helpState == 1) { // FIXME: set cursor to 2 if over conversation rect } } cursorSetShape(shape); } void CSTimeInterface::clearTextLine() { _rolloverText.clear(); } void CSTimeInterface::displayTextLine(Common::String text) { _rolloverText = text; } void CSTimeInterface::clearDialogArea() { _dialogLines.clear(); _dialogLines.resize(5); // TODO: dirty feature } void CSTimeInterface::clearDialogLine(uint line) { _dialogLines[line].clear(); // TODO: dirty feature } void CSTimeInterface::displayDialogLine(uint16 id, uint line, byte color) { Common::SeekableReadStream *stream = _vm->getResource(ID_STRI, id); Common::String text = readString(stream); delete stream; _dialogLines[line] = text; _dialogLineColors[line] = color; // TODO: dirty feature } void CSTimeInterface::drawTextIdToBubble(uint16 id) { Common::SeekableReadStream *stream = _vm->getResource(ID_STRI, id); Common::String text = readString(stream); delete stream; drawTextToBubble(&text); } void CSTimeInterface::drawTextToBubble(Common::String *text) { if (_bubbleTextFeature) error("Attempt to display two text objects"); if (!text) text = &_bubbleText; if (text->empty()) return; _currentBubbleText = *text; uint bubbleId = _vm->getCase()->getCurrScene()->getBubbleType(); Common::Rect bounds; switch (bubbleId) { case 0: bounds = Common::Rect(15, 7, 625, 80); break; case 1: bounds = Common::Rect(160, 260, 625, 333); break; case 2: bounds = Common::Rect(356, 3, 639, 90); break; case 3: bounds = Common::Rect(10, 7, 380, 80); break; case 4: bounds = Common::Rect(15, 270, 625, 328); break; case 5: bounds = Common::Rect(15, 7, 550, 70); break; case 6: bounds = Common::Rect(0, 0, 313, 76); break; case 7: bounds = Common::Rect(200, 25, 502, 470); break; default: error("unknown bubble type %d in drawTextToBubble", bubbleId); } _bubbleTextFeature = _vm->getView()->installViewFeature(0, 0, NULL); _bubbleTextFeature->_data.bounds = bounds; _bubbleTextFeature->_data.bitmapIds[0] = 0; _bubbleTextFeature->_moveProc = (Module::FeatureProc)&CSTimeModule::bubbleTextMoveProc; _bubbleTextFeature->_drawProc = (Module::FeatureProc)&CSTimeModule::bubbleTextDrawProc; _bubbleTextFeature->_timeProc = NULL; _bubbleTextFeature->_flags = kFeatureOldSortForeground; // FIXME: not in original } void CSTimeInterface::closeBubble() { if (_bubbleTextFeature) _vm->getView()->removeFeature(_bubbleTextFeature, true); _bubbleTextFeature = NULL; } void CSTimeInterface::startDragging(uint16 id) { CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[id]; cursorSetShape(11); _draggedItem = id; if (_draggedItem == TIME_CUFFS_ID) { if (_inventoryDisplay->getCuffsShape() == 11) { _inventoryDisplay->setCuffsFlashing(); _vm->getView()->idleView(); } } uint32 dragFlags = (grabbedFromInventory() ? 0x800 : 0x600); _vm->getView()->dragFeature((NewFeature *)invObj->feature, _grabPoint, 4, dragFlags, NULL); if (_vm->getCase()->getId() == 1 && id == 2) { // Hardcoded behavior for the torch in the first case. if (_vm->getCase()->getCurrScene()->getId() == 4) { // This is the dark tomb. // FIXME: apply torch hack _vm->_caseVariable[2]++; } else { // FIXME: unapply torch hack } } _state = kCSTimeInterfaceStateDragging; if (grabbedFromInventory()) return; // Hide the associated scene feature, if there is one. if (invObj->featureId != 0xffff) { CSTimeEvent event; event.type = kCSTimeEventDisableFeature; event.param2 = invObj->featureId; _vm->addEvent(event); } _vm->addEventList(invObj->events); } void CSTimeInterface::stopDragging() { CSTimeScene *scene = _vm->getCase()->getCurrScene(); CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[_draggedItem]; Common::Point mousePos = _vm->_system->getEventManager()->getMousePos(); _state = kCSTimeInterfaceStateNormal; if (_sceneRect.contains(mousePos)) scene->setCursorForCurrentPoint(); else setCursorForCurrentPoint(); // Find the inventory object hotspot which is topmost for this drop, if any. uint16 foundInvObjHotspot = 0xffff; const Common::Array<CSTimeHotspot> &hotspots = scene->getHotspots(); for (uint i = 0; i < hotspots.size(); i++) { if (hotspots[i].state != 1) continue; if (!hotspots[i].region.containsPoint(mousePos)) continue; for (uint j = 0; j < invObj->hotspots.size(); j++) { if (invObj->hotspots[j].sceneId != scene->getId()) continue; if (invObj->hotspots[j].hotspotId != i) continue; if (foundInvObjHotspot != 0xffff && invObj->hotspots[foundInvObjHotspot].hotspotId < invObj->hotspots[j].hotspotId) continue; foundInvObjHotspot = j; } } // Work out if we're going to consume (nom-nom) the object after the drop. bool consumeObj = false; bool runConsumeEvents = false; if (foundInvObjHotspot != 0xffff) { CSTimeInventoryHotspot &hotspot = invObj->hotspots[foundInvObjHotspot]; clearTextLine(); for (uint i = 0; i < invObj->locations.size(); i++) { if (invObj->locations[i].sceneId != hotspot.sceneId) continue; if (invObj->locations[i].hotspotId != hotspot.hotspotId) continue; consumeObj = true; break; } if (_draggedItem == TIME_CUFFS_ID && !_inventoryDisplay->getCuffsState()) { consumeObj = false; // Nuh-uh, they're not activated yet. _vm->addEvent(CSTimeEvent(kCSTimeEventCharStartFlapping, _vm->getCase()->getCurrScene()->getHelperId(), 9902)); } else { // FIXME: ding(); runConsumeEvents = true; } } // Deal with the actual drop. if (grabbedFromInventory()) { if (!consumeObj) { _vm->getView()->dragFeature((NewFeature *)invObj->feature, mousePos, 2, 0x800, NULL); // TODO: playSound(151); } else if (_draggedItem != TIME_CUFFS_ID) { _vm->getView()->dragFeature((NewFeature *)invObj->feature, mousePos, 2, 0x600, NULL); _vm->_haveInvItem[_draggedItem] = 0; invObj->feature = NULL; invObj->featureDisabled = true; _inventoryDisplay->removeItem(_draggedItem); } else if (!_inventoryDisplay->getCuffsState()) { // Inactive cuffs. // TODO: We never actually get here? Which would explain why it makes no sense. _vm->getView()->dragFeature((NewFeature *)invObj->feature, mousePos, 2, 0x800, NULL); invObj->feature = NULL; } else { // Active cuffs. _vm->getView()->dragFeature((NewFeature *)invObj->feature, mousePos, 2, 0x600, NULL); _vm->_haveInvItem[_draggedItem] = 0; invObj->feature = NULL; invObj->featureDisabled = true; } if (runConsumeEvents) { _vm->addEventList(invObj->hotspots[foundInvObjHotspot].events); } _inventoryDisplay->draw(); } else { uint32 dragFlags = 0x600; _vm->getView()->dragFeature((NewFeature *)invObj->feature, mousePos, 2, dragFlags, NULL); if (_inventoryDisplay->_invRect.contains(mousePos)) { // Dropped into the inventory. invObj->feature = NULL; if (invObj->canTake) { dropItemInInventory(_draggedItem); if (invObj->hotspotId) _vm->addEvent(CSTimeEvent(kCSTimeEventDisableHotspot, 0xffff, invObj->hotspotId)); } else { if (invObj->featureId) _vm->addEvent(CSTimeEvent(kCSTimeEventAddFeature, 0xffff, invObj->featureId)); } for (uint i = 0; i < invObj->hotspots.size(); i++) { if (invObj->hotspots[i].sceneId != scene->getId()) continue; if (invObj->hotspots[i].hotspotId != 0xffff) continue; _vm->addEventList(invObj->hotspots[i].events); } } else { // Dropped into the scene. CSTimeEvent event; event.param1 = 0xffff; if (consumeObj) { invObj->feature = NULL; invObj->featureDisabled = true; event.type = kCSTimeEventDisableHotspot; event.param2 = invObj->hotspotId; } else { invObj->feature = NULL; event.type = kCSTimeEventAddFeature; event.param2 = invObj->featureId; } _vm->addEvent(event); if (runConsumeEvents) { _vm->addEventList(invObj->hotspots[foundInvObjHotspot].events); } else { for (uint i = 0; i < invObj->hotspots.size(); i++) { if (invObj->hotspots[i].sceneId != scene->getId()) continue; if (invObj->hotspots[i].hotspotId != 0xfffe) continue; _vm->addEventList(invObj->hotspots[i].events); } } } } if (_vm->getCase()->getId() == 1 && _vm->getCase()->getCurrScene()->getId() == 4) { // Hardcoded behavior for torches in the dark tomb, in the first case. if (_draggedItem == 1 && foundInvObjHotspot == 0xffff) { // Trying to drag an unlit torch around? _vm->addEvent(CSTimeEvent(kCSTimeEventCharStartFlapping, 0, 16352)); } else if (_draggedItem == 2 && _vm->_caseVariable[2] == 1) { // This the first time we tried dragging the lit torch around. _vm->addEvent(CSTimeEvent(kCSTimeEventCharStartFlapping, 0, 16354)); } } // TODO: Is this necessary? _draggedItem = 0xffff; } void CSTimeInterface::setGrabPoint() { _grabPoint = _vm->_system->getEventManager()->getMousePos(); } bool CSTimeInterface::grabbedFromInventory() { return (_inventoryDisplay->_invRect.contains(_grabPoint)); } void CSTimeInterface::dropItemInInventory(uint16 id) { if (_vm->_haveInvItem[id]) return; _vm->_haveInvItem[id] = 1; _vm->getCase()->_inventoryObjs[id]->feature = NULL; _inventoryDisplay->insertItemInDisplay(id); // TODO: deal with symbols if (_vm->getCase()->getCurrConversation()->getState() == (uint)~0 || _vm->getCase()->getCurrConversation()->getState() == 0) { // FIXME: additional check here // FIXME: play sound 151? _inventoryDisplay->draw(); return; } // FIXME: ding(); clearDialogArea(); _inventoryDisplay->show(); _inventoryDisplay->draw(); _inventoryDisplay->setState(kCSTimeInterfaceDroppedInventory); } CSTimeHelp::CSTimeHelp(MohawkEngine_CSTime *vm) : _vm(vm) { _state = (uint)~0; _currEntry = 0xffff; _currHover = 0xffff; _nextToProcess = 0xffff; } CSTimeHelp::~CSTimeHelp() { } void CSTimeHelp::addQaR(uint16 text, uint16 speech) { CSTimeHelpQaR qar; qar.text = text; qar.speech = speech; _qars.push_back(qar); } void CSTimeHelp::start() { if (_vm->getInterface()->getInventoryDisplay()->getState() == 4) return; _state = 2; uint16 speech = 5900 + _vm->_rnd->getRandomNumberRng(0, 2); _vm->addEvent(CSTimeEvent(kCSTimeEventCharStartFlapping, _vm->getCase()->getCurrScene()->getHelperId(), speech)); if (noHelperChanges()) return; // Play a NIS, making sure the Good Guide is disabled. _vm->addEvent(CSTimeEvent(kCSTimeEventCharSetState, _vm->getCase()->getCurrScene()->getHelperId(), 0)); _vm->addEvent(CSTimeEvent(kCSTimeEventCharPlayNIS, _vm->getCase()->getCurrScene()->getHelperId(), 0)); _vm->addEvent(CSTimeEvent(kCSTimeEventCharSetState, _vm->getCase()->getCurrScene()->getHelperId(), 0)); } void CSTimeHelp::end(bool runEvents) { _state = (uint)~0; _currHover = 0xffff; _vm->getInterface()->clearDialogArea(); _vm->getInterface()->getInventoryDisplay()->show(); if (noHelperChanges()) return; _vm->addEvent(CSTimeEvent(kCSTimeEventCharSetState, _vm->getCase()->getCurrScene()->getHelperId(), 1)); _vm->addEvent(CSTimeEvent(kCSTimeEventCharSomeNIS55, _vm->getCase()->getCurrScene()->getHelperId(), 1)); } void CSTimeHelp::cleanupAfterFlapping() { if (_state == 2) { // Startup. _vm->getInterface()->getInventoryDisplay()->hide(); selectStrings(); display(); _state = 1; return; } if (_nextToProcess == 0xffff) return; unhighlightLine(_nextToProcess); _nextToProcess = 0xffff; // TODO: case 18 hard-coding } void CSTimeHelp::mouseDown(Common::Point &pos) { for (uint i = 0; i < _qars.size(); i++) { Common::Rect thisRect = _vm->getInterface()->_dialogTextRect; thisRect.top += 1 + i*15; thisRect.bottom = thisRect.top + 15; if (!thisRect.contains(pos)) continue; _currEntry = i; highlightLine(i); _vm->getInterface()->cursorSetShape(5); } } void CSTimeHelp::mouseMove(Common::Point &pos) { bool mouseIsDown = _vm->getEventManager()->getButtonState() & 1; for (uint i = 0; i < _qars.size(); i++) { Common::Rect thisRect = _vm->getInterface()->_dialogTextRect; thisRect.top += 1 + i*15; thisRect.bottom = thisRect.top + 15; if (!thisRect.contains(pos)) continue; if (mouseIsDown) { if (i != _currEntry) break; highlightLine(i); } _vm->getInterface()->cursorOverHotspot(); _currHover = i; return; } if (_currHover != 0xffff) { if (_vm->getInterface()->cursorGetShape() != 3) { unhighlightLine(_currHover); _vm->getInterface()->cursorSetShape(1); } _currHover = 0xffff; } } void CSTimeHelp::mouseUp(Common::Point &pos) { if (_currEntry == 0xffff || _qars[_currEntry].speech == 0) { _vm->getInterface()->cursorSetShape(1); end(); return; } Common::Rect thisRect = _vm->getInterface()->_dialogTextRect; thisRect.top += 1 + _currEntry*15; thisRect.bottom = thisRect.top + 15; if (!thisRect.contains(pos)) return; _vm->addEvent(CSTimeEvent(kCSTimeEventCharStartFlapping, _vm->getCase()->getCurrScene()->getHelperId(), 5900 + _qars[_currEntry].speech)); _nextToProcess = _currEntry; _askedAlready.push_back(_qars[_currEntry].text); } void CSTimeHelp::display() { _vm->getInterface()->clearDialogArea(); for (uint i = 0; i < _qars.size(); i++) { uint16 text = _qars[i].text; bool askedAlready = Common::find(_askedAlready.begin(), _askedAlready.end(), text) != _askedAlready.end(); _vm->getInterface()->displayDialogLine(5900 + text, i, askedAlready ? 13 : 32); } } void CSTimeHelp::highlightLine(uint line) { uint16 text = _qars[line].text; _vm->getInterface()->displayDialogLine(5900 + text, line, 244); } void CSTimeHelp::unhighlightLine(uint line) { uint16 text = _qars[line].text; bool askedAlready = Common::find(_askedAlready.begin(), _askedAlready.end(), text) != _askedAlready.end(); _vm->getInterface()->displayDialogLine(5900 + text, line, askedAlready ? 13 : 32); } void CSTimeHelp::selectStrings() { _qars.clear(); _vm->getCase()->selectHelpStrings(); } bool CSTimeHelp::noHelperChanges() { // These are hardcoded. if (_vm->getCase()->getId() == 4 && _vm->getCase()->getCurrScene()->getId() == 5) return true; if (_vm->getCase()->getId() == 5) return true; if (_vm->getCase()->getId() == 14 && _vm->getCase()->getCurrScene()->getId() == 4) return true; if (_vm->getCase()->getId() == 17 && _vm->getCase()->getCurrScene()->getId() == 2) return true; return false; } CSTimeInventoryDisplay::CSTimeInventoryDisplay(MohawkEngine_CSTime *vm, Common::Rect baseRect) : _vm(vm) { _state = 0; _cuffsState = false; _cuffsShape = 10; _invRect = baseRect; for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) { _itemRect[i].left = baseRect.left + 15 + i * 92; _itemRect[i].top = baseRect.top + 5; _itemRect[i].right = _itemRect[i].left + 90; _itemRect[i].bottom = _itemRect[i].top + 70; } } CSTimeInventoryDisplay::~CSTimeInventoryDisplay() { } void CSTimeInventoryDisplay::install() { uint count = _vm->getCase()->_inventoryObjs.size() - 1; // FIXME: some cases have hard-coded counts _vm->getView()->installGroup(9000, count, 0, true, 9000); } void CSTimeInventoryDisplay::draw() { for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) { if (_displayedItems[i] == 0xffff) continue; CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[_displayedItems[i]]; if (invObj->featureDisabled) continue; if (invObj->feature) { invObj->feature->resetFeatureScript(1, 0); continue; } // TODO: 0x2000 is set! help? uint32 flags = kFeatureSortStatic | kFeatureNewNoLoop | 0x2000; if (i == TIME_CUFFS_ID) { // Time Cuffs are handled differently. // TODO: Can we not use _cuffsShape here? uint16 id = 100 + 10; if (_cuffsState) { id = 100 + 12; flags &= ~kFeatureNewNoLoop; } invObj->feature = _vm->getView()->installViewFeature(id, flags, NULL); } else { Common::Point pos((_itemRect[i].left + _itemRect[i].right) / 2, (_itemRect[i].top + _itemRect[i].bottom) / 2); uint16 id = 9000 + (invObj->id - 1); invObj->feature = _vm->getView()->installViewFeature(id, flags, &pos); } } } void CSTimeInventoryDisplay::show() { for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) { if (_displayedItems[i] == 0xffff) continue; CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[_displayedItems[i]]; if (!invObj->feature) continue; invObj->feature->show(); } } void CSTimeInventoryDisplay::hide() { for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) { if (_displayedItems[i] == 0xffff) continue; CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[_displayedItems[i]]; if (!invObj->feature) continue; invObj->feature->hide(true); } } void CSTimeInventoryDisplay::idle() { if (_vm->getInterface()->getCarmenNote()->getState() || _vm->getCase()->getCurrConversation()->getState() != 0xffff || _vm->getInterface()->getHelp()->getState() != 0xffff) { if (_state == 4) { // FIXME: check timeout! hide(); _vm->getCase()->getCurrConversation()->display(); _state = 0; } return; } if (!_state) return; // FIXME: deal with actual inventory stuff } void CSTimeInventoryDisplay::clearDisplay() { for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) _displayedItems[i] = 0xffff; // We always start out with the Time Cuffs. _vm->_haveInvItem[TIME_CUFFS_ID] = 1; insertItemInDisplay(TIME_CUFFS_ID); _cuffsState = false; } void CSTimeInventoryDisplay::insertItemInDisplay(uint16 id) { for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) if (_displayedItems[i] == id) return; for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) if (_displayedItems[i] == 0xffff) { _displayedItems[i] = id; return; } error("couldn't insert item into display"); } void CSTimeInventoryDisplay::removeItem(uint16 id) { CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[id]; if (invObj->feature) { _vm->getView()->removeFeature(invObj->feature, true); invObj->feature = NULL; } for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) if (_displayedItems[i] == id) _displayedItems[i] = 0xffff; } void CSTimeInventoryDisplay::mouseDown(Common::Point &pos) { for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) { if (_displayedItems[i] == 0xffff) continue; if (!_itemRect[i].contains(pos)) continue; _draggedItem = i; _vm->getInterface()->cursorSetShape(8); _vm->getInterface()->setGrabPoint(); _vm->getInterface()->setState(kCSTimeInterfaceStateDragStart); } } void CSTimeInventoryDisplay::mouseMove(Common::Point &pos) { bool mouseIsDown = _vm->getEventManager()->getButtonState() & 1; if (mouseIsDown && _vm->getInterface()->cursorGetShape() == 8) { Common::Point grabPoint = _vm->getInterface()->getGrabPoint(); if (mouseIsDown && (abs(grabPoint.x - pos.x) > 2 || abs(grabPoint.y - pos.y) > 2)) { if (_vm->getInterface()->grabbedFromInventory()) { _vm->getInterface()->startDragging(getLastDisplayedClicked()); } else { // TODO: CSTimeScene::mouseMove does quite a lot more, why not here too? _vm->getInterface()->startDragging(_vm->getCase()->getCurrScene()->getInvObjForCurrentHotspot()); } } } for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) { if (_displayedItems[i] == 0xffff) continue; if (!_itemRect[i].contains(pos)) continue; CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[_displayedItems[i]]; Common::String text = "Pick up "; // TODO: special-case for case 11, scene 3, inv obj 1 (just use "Read " instead) text += _vm->getCase()->getRolloverText(invObj->stringId); _vm->getInterface()->displayTextLine(text); _vm->getInterface()->cursorOverHotspot(); // FIXME: there's some trickery here to store the id for the below return; } if (false /* FIXME: if we get here and the stored id mentioned above is set.. */) { _vm->getInterface()->clearTextLine(); if (_vm->getInterface()->getState() != kCSTimeInterfaceStateDragging) { if (_vm->getInterface()->cursorGetShape() != 3 && _vm->getInterface()->cursorGetShape() != 9) _vm->getInterface()->cursorSetShape(1); } // FIXME: reset that stored id } } void CSTimeInventoryDisplay::mouseUp(Common::Point &pos) { for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) { if (_displayedItems[i] == 0xffff) continue; if (!_itemRect[i].contains(pos)) continue; // TODO: instead, stupid hack for case 11, scene 3, inv obj 1 (kCSTimeEventUnknown39, 0xffff, 0xffff) // TODO: instead, stupid hack for case 18, scene not 3, inv obj 4 (kCSTimeEventCondition, 1, 29) CSTimeEvent event; event.param1 = _vm->getCase()->getCurrScene()->getHelperId(); if (event.param1 == 0xffff) event.type = kCSTimeEventSpeech; else event.type = kCSTimeEventCharStartFlapping; if (i == TIME_CUFFS_ID) { if (_cuffsState) event.param2 = 9903; else event.param2 = 9902; } else { event.param2 = 9905 + _displayedItems[i]; } _vm->addEvent(event); } } void CSTimeInventoryDisplay::activateCuffs(bool active) { _cuffsState = active; if (!_cuffsState) return; CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[TIME_CUFFS_ID]; _cuffsShape = 11; if (invObj->feature) _vm->getView()->removeFeature(invObj->feature, true); uint32 flags = kFeatureSortStatic | kFeatureNewNoLoop; invObj->feature = _vm->getView()->installViewFeature(100 + _cuffsShape, flags, NULL); invObj->featureDisabled = false; } void CSTimeInventoryDisplay::setCuffsFlashing() { CSTimeInventoryObject *invObj = _vm->getCase()->_inventoryObjs[TIME_CUFFS_ID]; _cuffsShape = 12; if (invObj->feature) _vm->getView()->removeFeature(invObj->feature, true); uint32 flags = kFeatureSortStatic | 0x2000; invObj->feature = _vm->getView()->installViewFeature(100 + _cuffsShape, flags, NULL); invObj->featureDisabled = false; } bool CSTimeInventoryDisplay::isItemDisplayed(uint16 id) { for (uint i = 0; i < MAX_DISPLAYED_ITEMS; i++) { if (_displayedItems[i] == id) return true; } return false; } CSTimeBook::CSTimeBook(MohawkEngine_CSTime *vm) : _vm(vm) { _state = 0; _smallBookFeature = NULL; } CSTimeBook::~CSTimeBook() { } void CSTimeBook::drawSmallBook() { if (!_smallBookFeature) { _smallBookFeature = _vm->getView()->installViewFeature(101, kFeatureSortStatic | kFeatureNewNoLoop, NULL); } else { _smallBookFeature->resetFeature(false, NULL, 0); } } CSTimeCarmenNote::CSTimeCarmenNote(MohawkEngine_CSTime *vm) : _vm(vm) { _state = 0; _feature = NULL; clearPieces(); } CSTimeCarmenNote::~CSTimeCarmenNote() { } void CSTimeCarmenNote::clearPieces() { for (uint i = 0; i < NUM_NOTE_PIECES; i++) _pieces[i] = 0xffff; } bool CSTimeCarmenNote::havePiece(uint16 piece) { for (uint i = 0; i < NUM_NOTE_PIECES; i++) { if (piece == 0xffff) { if (_pieces[i] != 0xffff) return true; } else if (_pieces[i] == piece) return true; } return false; } void CSTimeCarmenNote::addPiece(uint16 piece, uint16 speech) { uint i; for (i = 0; i < NUM_NOTE_PIECES; i++) { if (_pieces[i] == 0xffff) { _pieces[i] = piece; break; } } if (i == NUM_NOTE_PIECES) error("addPiece couldn't add piece to carmen note"); // Get the Good Guide to say something. if (i == 2) speech = 9900; // Found the third piece. if (speech != 0xffff) _vm->addEvent(CSTimeEvent(kCSTimeEventCharStartFlapping, _vm->getCase()->getCurrScene()->getHelperId(), speech)); // Remove the note feature, if any. uint16 noteFeatureId = _vm->getCase()->getNoteFeatureId(piece); if (noteFeatureId != 0xffff) _vm->addEvent(CSTimeEvent(kCSTimeEventDisableFeature, 0xffff, noteFeatureId)); _vm->addEvent(CSTimeEvent(kCSTimeEventShowBigNote, 0xffff, 0xffff)); if (i != 2) return; // TODO: special-casing for case 5 _vm->addEvent(CSTimeEvent(kCSTimeEventCharPlayNIS, _vm->getCase()->getCurrScene()->getHelperId(), 3)); // TODO: special-casing for case 5 _vm->addEvent(CSTimeEvent(kCSTimeEventCharStartFlapping, _vm->getCase()->getCurrScene()->getHelperId(), 9901)); _vm->addEvent(CSTimeEvent(kCSTimeEventActivateCuffs, 0xffff, 0xffff)); } void CSTimeCarmenNote::drawSmallNote() { if (!havePiece(0xffff)) return; uint16 id = 100; if (_pieces[2] != 0xffff) id += 5; else if (_pieces[1] != 0xffff) id += 4; else id += 2; if (_feature) _vm->getView()->removeFeature(_feature, true); _feature = _vm->getView()->installViewFeature(id, kFeatureSortStatic | kFeatureNewNoLoop, NULL); } void CSTimeCarmenNote::drawBigNote() { if (_vm->getCase()->getCurrConversation()->getState() != (uint)~0) { _vm->getCase()->getCurrConversation()->end(false); } else if (_vm->getInterface()->getHelp()->getState() != (uint)~0) { _vm->getInterface()->getHelp()->end(); } // TODO: kill symbols too uint16 id = 100; if (_pieces[2] != 0xffff) id += 9; else if (_pieces[1] != 0xffff) id += 8; else id += 6; if (_feature) _vm->getView()->removeFeature(_feature, true); _feature = _vm->getView()->installViewFeature(id, kFeatureSortStatic | kFeatureNewNoLoop, NULL); // FIXME: attach note drawing proc _state = 2; } void CSTimeCarmenNote::closeNote() { _state = 0; drawSmallNote(); } CSTimeOptions::CSTimeOptions(MohawkEngine_CSTime *vm) : _vm(vm) { _state = 0; } CSTimeOptions::~CSTimeOptions() { } } // End of namespace Mohawk
lordhoto/scummvm
engines/mohawk/cstime_ui.cpp
C++
gpl-2.0
38,280
class PermalinkSerializer < ApplicationSerializer attributes :id, :url, :topic_id, :topic_title, :topic_url, :post_id, :post_url, :post_number, :post_topic_title, :category_id, :category_name, :category_url, :external_url def topic_title object&.topic&.title end def topic_url object&.topic&.url end def post_url # use `full_url` to support subfolder setups object&.post&.full_url end def post_number object&.post&.post_number end def post_topic_title object&.post&.topic&.title end def category_name object&.category&.name end def category_url object&.category&.url end end
andriy-kravchuck/discourse9323
app/serializers/permalink_serializer.rb
Ruby
gpl-2.0
670
package info.novatec.inspectit.indexing.aggregation.impl; import info.novatec.inspectit.communication.IAggregatedData; import info.novatec.inspectit.communication.data.ThreadInformationData; import info.novatec.inspectit.indexing.aggregation.IAggregator; import java.io.Serializable; /** * {@link IAggregator} for the {@link ThreadInformationData}. * * @author Ivan Senic * */ public class ThreadInformationDataAggregator implements IAggregator<ThreadInformationData>, Serializable { /** * Generated UID. */ private static final long serialVersionUID = 749269646913958594L; /** * {@inheritDoc} */ public void aggregate(IAggregatedData<ThreadInformationData> aggregatedObject, ThreadInformationData objectToAdd) { aggregatedObject.aggregate(objectToAdd); } /** * {@inheritDoc} */ public ThreadInformationData getClone(ThreadInformationData threadInformationData) { ThreadInformationData clone = new ThreadInformationData(); clone.setPlatformIdent(threadInformationData.getPlatformIdent()); clone.setSensorTypeIdent(threadInformationData.getSensorTypeIdent()); return clone; } /** * {@inheritDoc} */ public boolean isCloning() { return true; } /** * {@inheritDoc} */ public Object getAggregationKey(ThreadInformationData object) { return object.getPlatformIdent(); } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; // we must make constant hashCode because of the caching result = prime * result + this.getClass().getName().hashCode(); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return true; } }
kugelr/inspectIT
CommonsCS/src/info/novatec/inspectit/indexing/aggregation/impl/ThreadInformationDataAggregator.java
Java
agpl-3.0
1,820
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "bytes" "encoding/json" "fmt" "io" "github.com/ghodss/yaml" "github.com/spf13/cobra" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" apijson "k8s.io/apimachinery/pkg/util/json" api "k8s.io/kubernetes/pkg/apis/core" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/kubectl/cmd/templates" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "k8s.io/kubernetes/pkg/kubectl/cmd/util/editor" "k8s.io/kubernetes/pkg/kubectl/resource" "k8s.io/kubernetes/pkg/kubectl/scheme" "k8s.io/kubernetes/pkg/kubectl/util/i18n" ) type SetLastAppliedOptions struct { FilenameOptions resource.FilenameOptions Selector string InfoList []*resource.Info Mapper meta.RESTMapper Typer runtime.ObjectTyper Namespace string EnforceNamespace bool DryRun bool ShortOutput bool CreateAnnotation bool Output string PatchBufferList []PatchBuffer Factory cmdutil.Factory Out io.Writer ErrOut io.Writer } type PatchBuffer struct { Patch []byte PatchType types.PatchType } var ( applySetLastAppliedLong = templates.LongDesc(i18n.T(` Set the latest last-applied-configuration annotations by setting it to match the contents of a file. This results in the last-applied-configuration being updated as though 'kubectl apply -f <file>' was run, without updating any other parts of the object.`)) applySetLastAppliedExample = templates.Examples(i18n.T(` # Set the last-applied-configuration of a resource to match the contents of a file. kubectl apply set-last-applied -f deploy.yaml # Execute set-last-applied against each configuration file in a directory. kubectl apply set-last-applied -f path/ # Set the last-applied-configuration of a resource to match the contents of a file, will create the annotation if it does not already exist. kubectl apply set-last-applied -f deploy.yaml --create-annotation=true `)) ) func NewCmdApplySetLastApplied(f cmdutil.Factory, out, err io.Writer) *cobra.Command { options := &SetLastAppliedOptions{Out: out, ErrOut: err} cmd := &cobra.Command{ Use: "set-last-applied -f FILENAME", DisableFlagsInUseLine: true, Short: i18n.T("Set the last-applied-configuration annotation on a live object to match the contents of a file."), Long: applySetLastAppliedLong, Example: applySetLastAppliedExample, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(options.Complete(f, cmd)) cmdutil.CheckErr(options.Validate(f, cmd)) cmdutil.CheckErr(options.RunSetLastApplied(f, cmd)) }, } cmdutil.AddDryRunFlag(cmd) cmdutil.AddRecordFlag(cmd) cmdutil.AddPrinterFlags(cmd) cmd.Flags().BoolVar(&options.CreateAnnotation, "create-annotation", false, "Will create 'last-applied-configuration' annotations if current objects doesn't have one") usage := "that contains the last-applied-configuration annotations" kubectl.AddJsonFilenameFlag(cmd, &options.FilenameOptions.Filenames, "Filename, directory, or URL to files "+usage) return cmd } func (o *SetLastAppliedOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error { o.DryRun = cmdutil.GetDryRunFlag(cmd) o.Output = cmdutil.GetFlagString(cmd, "output") o.ShortOutput = o.Output == "name" var err error o.Mapper, o.Typer = f.Object() if err != nil { return err } o.Namespace, o.EnforceNamespace, err = f.DefaultNamespace() return err } func (o *SetLastAppliedOptions) Validate(f cmdutil.Factory, cmd *cobra.Command) error { r := f.NewBuilder(). Unstructured(). NamespaceParam(o.Namespace).DefaultNamespace(). FilenameParam(o.EnforceNamespace, &o.FilenameOptions). Flatten(). Do() err := r.Visit(func(info *resource.Info, err error) error { if err != nil { return err } patchBuf, diffBuf, patchType, err := editor.GetApplyPatch(info.Object, scheme.DefaultJSONEncoder()) if err != nil { return err } // Verify the object exists in the cluster before trying to patch it. if err := info.Get(); err != nil { if errors.IsNotFound(err) { return err } else { return cmdutil.AddSourceToErr(fmt.Sprintf("retrieving current configuration of:\n%v\nfrom server for:", info), info.Source, err) } } originalBuf, err := kubectl.GetOriginalConfiguration(info.Mapping, info.Object) if err != nil { return cmdutil.AddSourceToErr(fmt.Sprintf("retrieving current configuration of:\n%v\nfrom server for:", info), info.Source, err) } if originalBuf == nil && !o.CreateAnnotation { return cmdutil.UsageErrorf(cmd, "no last-applied-configuration annotation found on resource: %s, to create the annotation, run the command with --create-annotation", info.Name) } //only add to PatchBufferList when changed if !bytes.Equal(cmdutil.StripComments(originalBuf), cmdutil.StripComments(diffBuf)) { p := PatchBuffer{Patch: patchBuf, PatchType: patchType} o.PatchBufferList = append(o.PatchBufferList, p) o.InfoList = append(o.InfoList, info) } else { fmt.Fprintf(o.Out, "set-last-applied %s: no changes required.\n", info.Name) } return nil }) return err } func (o *SetLastAppliedOptions) RunSetLastApplied(f cmdutil.Factory, cmd *cobra.Command) error { for i, patch := range o.PatchBufferList { info := o.InfoList[i] if !o.DryRun { mapping := info.ResourceMapping() client, err := f.UnstructuredClientForMapping(mapping) if err != nil { return err } helper := resource.NewHelper(client, mapping) patchedObj, err := helper.Patch(o.Namespace, info.Name, patch.PatchType, patch.Patch) if err != nil { return err } if len(o.Output) > 0 && !o.ShortOutput { info.Refresh(patchedObj, false) return cmdutil.PrintObject(cmd, info.Object, o.Out) } cmdutil.PrintSuccess(o.ShortOutput, o.Out, info.Object, o.DryRun, "configured") } else { err := o.formatPrinter(o.Output, patch.Patch, o.Out) if err != nil { return err } cmdutil.PrintSuccess(o.ShortOutput, o.Out, info.Object, o.DryRun, "configured") } } return nil } func (o *SetLastAppliedOptions) formatPrinter(output string, buf []byte, w io.Writer) error { yamlOutput, err := yaml.JSONToYAML(buf) if err != nil { return err } switch output { case "json": jsonBuffer := &bytes.Buffer{} err = json.Indent(jsonBuffer, buf, "", " ") if err != nil { return err } fmt.Fprintf(w, "%s\n", jsonBuffer.String()) case "yaml": fmt.Fprintf(w, "%s\n", string(yamlOutput)) } return nil } func (o *SetLastAppliedOptions) getPatch(info *resource.Info) ([]byte, []byte, error) { objMap := map[string]map[string]map[string]string{} metadataMap := map[string]map[string]string{} annotationsMap := map[string]string{} localFile, err := runtime.Encode(scheme.DefaultJSONEncoder(), info.Object) if err != nil { return nil, localFile, err } annotationsMap[api.LastAppliedConfigAnnotation] = string(localFile) metadataMap["annotations"] = annotationsMap objMap["metadata"] = metadataMap jsonString, err := apijson.Marshal(objMap) return jsonString, localFile, err }
dobbymoodge/origin
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/apply_set_last_applied.go
GO
apache-2.0
7,729
/* Copyright 2012 Harri Smatt 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 fi.harism.curl; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.RectF; /** * Storage class for page textures, blend colors and possibly some other values * in the future. * * @author harism */ public class CurlPage { public static final int SIDE_BACK = 2; public static final int SIDE_BOTH = 3; public static final int SIDE_FRONT = 1; private int mColorBack; private int mColorFront; private Bitmap mTextureBack; private Bitmap mTextureFront; private boolean mTexturesChanged; /** * Default constructor. */ public CurlPage() { reset(); } /** * Getter for color. */ public int getColor(int side) { switch (side) { case SIDE_FRONT: return mColorFront; default: return mColorBack; } } /** * Calculates the next highest power of two for a given integer. */ private int getNextHighestPO2(int n) { n -= 1; n = n | (n >> 1); n = n | (n >> 2); n = n | (n >> 4); n = n | (n >> 8); n = n | (n >> 16); n = n | (n >> 32); return n + 1; } /** * Generates nearest power of two sized Bitmap for give Bitmap. Returns this * new Bitmap using default return statement + original texture coordinates * are stored into RectF. */ private Bitmap getTexture(Bitmap bitmap, RectF textureRect) { // Bitmap original size. int w = bitmap.getWidth(); int h = bitmap.getHeight(); // Bitmap size expanded to next power of two. This is done due to // the requirement on many devices, texture width and height should // be power of two. int newW = getNextHighestPO2(w); int newH = getNextHighestPO2(h); // TODO: Is there another way to create a bigger Bitmap and copy // original Bitmap to it more efficiently? Immutable bitmap anyone? Bitmap bitmapTex = Bitmap.createBitmap(newW, newH, bitmap.getConfig()); Canvas c = new Canvas(bitmapTex); c.drawBitmap(bitmap, 0, 0, null); // Calculate final texture coordinates. float texX = (float) w / newW; float texY = (float) h / newH; textureRect.set(0f, 0f, texX, texY); return bitmapTex; } /** * Getter for textures. Creates Bitmap sized to nearest power of two, copies * original Bitmap into it and returns it. RectF given as parameter is * filled with actual texture coordinates in this new upscaled texture * Bitmap. */ public Bitmap getTexture(RectF textureRect, int side) { switch (side) { case SIDE_FRONT: return getTexture(mTextureFront, textureRect); default: return getTexture(mTextureBack, textureRect); } } /** * Returns true if textures have changed. */ public boolean getTexturesChanged() { return mTexturesChanged; } /** * Returns true if back siding texture exists and it differs from front * facing one. */ public boolean hasBackTexture() { return !mTextureFront.equals(mTextureBack); } /** * Recycles and frees underlying Bitmaps. */ public void recycle() { if (mTextureFront != null) { mTextureFront.recycle(); } mTextureFront = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565); mTextureFront.eraseColor(mColorFront); if (mTextureBack != null) { mTextureBack.recycle(); } mTextureBack = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565); mTextureBack.eraseColor(mColorBack); mTexturesChanged = false; } /** * Resets this CurlPage into its initial state. */ public void reset() { mColorBack = Color.WHITE; mColorFront = Color.WHITE; recycle(); } /** * Setter blend color. */ public void setColor(int color, int side) { switch (side) { case SIDE_FRONT: mColorFront = color; break; case SIDE_BACK: mColorBack = color; break; default: mColorFront = mColorBack = color; break; } } /** * Setter for textures. */ public void setTexture(Bitmap texture, int side) { if (texture == null) { texture = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565); if (side == SIDE_BACK) { texture.eraseColor(mColorBack); } else { texture.eraseColor(mColorFront); } } switch (side) { case SIDE_FRONT: if (mTextureFront != null) mTextureFront.recycle(); mTextureFront = texture; break; case SIDE_BACK: if (mTextureBack != null) mTextureBack.recycle(); mTextureBack = texture; break; case SIDE_BOTH: if (mTextureFront != null) mTextureFront.recycle(); if (mTextureBack != null) mTextureBack.recycle(); mTextureFront = mTextureBack = texture; break; } mTexturesChanged = true; } }
yytang2012/android_page_curl
src/fi/harism/curl/CurlPage.java
Java
apache-2.0
5,100
/* * 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.api.common.serialization; import org.apache.flink.annotation.PublicEvolving; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; /** * A simple {@link Encoder} that uses {@code toString()} on the input elements and writes them to * the output bucket file separated by newline. * * @param <IN> The type of the elements that are being written by the sink. */ @PublicEvolving public class SimpleStringEncoder<IN> implements Encoder<IN> { private static final long serialVersionUID = -6865107843734614452L; private String charsetName; private transient Charset charset; /** * Creates a new {@code StringWriter} that uses {@code "UTF-8"} charset to convert strings to * bytes. */ public SimpleStringEncoder() { this("UTF-8"); } /** * Creates a new {@code StringWriter} that uses the given charset to convert strings to bytes. * * @param charsetName Name of the charset to be used, must be valid input for {@code * Charset.forName(charsetName)} */ public SimpleStringEncoder(String charsetName) { this.charsetName = charsetName; } @Override public void encode(IN element, OutputStream stream) throws IOException { if (charset == null) { charset = Charset.forName(charsetName); } stream.write(element.toString().getBytes(charset)); stream.write('\n'); } }
lincoln-lil/flink
flink-core/src/main/java/org/apache/flink/api/common/serialization/SimpleStringEncoder.java
Java
apache-2.0
2,282
<?php final class PhabricatorApplicationEditEngine extends PhabricatorEditEngine { const ENGINECONST = 'application.application'; public function getEngineApplicationClass() { return 'PhabricatorApplicationsApplication'; } public function getEngineName() { return pht('Applications'); } public function getSummaryHeader() { return pht('Configure Application Forms'); } public function getSummaryText() { return pht('Configure creation and editing forms in Applications.'); } public function isEngineConfigurable() { return false; } protected function newEditableObject() { throw new PhutilMethodNotImplementedException(); } protected function newObjectQuery() { return new PhabricatorApplicationQuery(); } protected function getObjectCreateTitleText($object) { return pht('Create New Application'); } protected function getObjectEditTitleText($object) { return pht('Edit Application: %s', $object->getName()); } protected function getObjectEditShortText($object) { return $object->getName(); } protected function getObjectCreateShortText() { return pht('Create Application'); } protected function getObjectName() { return pht('Application'); } protected function getObjectViewURI($object) { return $object->getViewURI(); } protected function buildCustomEditFields($object) { return array(); } }
folsom-labs/phabricator
src/applications/meta/editor/PhabricatorApplicationEditEngine.php
PHP
apache-2.0
1,428
/* * Copyright (C) 2013 salesforce.com, 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. */ ({ doInit: function(component, event, helper) { // Add some data to the "data" attribute to show in the iteration var mapdata = { items: [ { "label": "0"}, { "label": "1"}, { "label": "2"}, { "label": "3"}, { "label": "4"} ] }; component.set("v.mapdata", mapdata); }, })
forcedotcom/aura
aura-components/src/test/components/iterationTest/iterationArrayValueChange_ObjectFromAttribute_PassThroughValue/iterationArrayValueChange_ObjectFromAttribute_PassThroughValueController.js
JavaScript
apache-2.0
919
/** * Copyright (C) 2014-2015 LinkedIn Corp. (pinot-core@linkedin.com) * * 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.linkedin.pinot.core.query.aggregation.function; import com.linkedin.pinot.core.common.Block; import com.linkedin.pinot.core.common.BlockDocIdIterator; import com.linkedin.pinot.core.common.BlockSingleValIterator; import com.linkedin.pinot.core.common.Constants; public class MaxAggregationNoDictionaryFunction extends MaxAggregationFunction { @Override public Double aggregate(Block docIdSetBlock, Block[] block) { double ret = Double.NEGATIVE_INFINITY; double tmp = 0; int docId = 0; BlockDocIdIterator docIdIterator = docIdSetBlock.getBlockDocIdSet().iterator(); BlockSingleValIterator blockValIterator = (BlockSingleValIterator) block[0].getBlockValueSet().iterator(); while ((docId = docIdIterator.next()) != Constants.EOF) { if (blockValIterator.skipTo(docId)) { tmp = blockValIterator.nextDoubleVal(); if (tmp > ret) { ret = tmp; } } } return ret; } @Override public Double aggregate(Double mergedResult, int docId, Block[] block) { BlockSingleValIterator blockValIterator = (BlockSingleValIterator) block[0].getBlockValueSet().iterator(); if (blockValIterator.skipTo(docId)) { if (mergedResult == null) { return blockValIterator.nextDoubleVal(); } double tmp = blockValIterator.nextDoubleVal(); if (tmp > mergedResult) { return tmp; } } return mergedResult; } }
pinotlytics/pinot
pinot-core/src/main/java/com/linkedin/pinot/core/query/aggregation/function/MaxAggregationNoDictionaryFunction.java
Java
apache-2.0
2,078
package services_test import ( "os" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" slclientfakes "github.com/maximilien/softlayer-go/client/fakes" softlayer "github.com/maximilien/softlayer-go/softlayer" testhelpers "github.com/maximilien/softlayer-go/test_helpers" ) var _ = Describe("SoftLayer_Network_Storage_Allowed_Host", func() { var ( username, apiKey string fakeClient *slclientfakes.FakeSoftLayerClient networkStorageAllowedHostService softlayer.SoftLayer_Network_Storage_Allowed_Host_Service err error ) BeforeEach(func() { username = os.Getenv("SL_USERNAME") Expect(username).ToNot(Equal("")) apiKey = os.Getenv("SL_API_KEY") Expect(apiKey).ToNot(Equal("")) fakeClient = slclientfakes.NewFakeSoftLayerClient(username, apiKey) Expect(fakeClient).ToNot(BeNil()) networkStorageAllowedHostService, err = fakeClient.GetSoftLayer_Network_Storage_Allowed_Host_Service() Expect(err).ToNot(HaveOccurred()) Expect(networkStorageAllowedHostService).ToNot(BeNil()) }) Context("#GetName", func() { It("returns the name for the service", func() { name := networkStorageAllowedHostService.GetName() Expect(name).To(Equal("SoftLayer_Network_Storage_Allowed_Host")) }) }) Context("#GetCredential", func() { BeforeEach(func() { fakeClient.FakeHttpClient.DoRawHttpRequestResponse, err = testhelpers.ReadJsonTestFixtures("services", "SoftLayer_Network_Storage_Allowed_Host_Service_getCredential.json") Expect(err).ToNot(HaveOccurred()) }) It("return the credential with allowed host id", func() { credential, err := networkStorageAllowedHostService.GetCredential(123456) Expect(err).NotTo(HaveOccurred()) Expect(credential).ToNot(BeNil()) Expect(credential.Username).To(Equal("fake-username")) Expect(credential.Password).To(Equal("fake-password")) }) Context("when HTTP client returns error codes 40x or 50x", func() { It("fails for error code 40x", func() { errorCodes := []int{400, 401, 499} for _, errorCode := range errorCodes { fakeClient.FakeHttpClient.DoRawHttpRequestInt = errorCode _, err := networkStorageAllowedHostService.GetCredential(123456) Expect(err).To(HaveOccurred()) } }) It("fails for error code 50x", func() { errorCodes := []int{500, 501, 599} for _, errorCode := range errorCodes { fakeClient.FakeHttpClient.DoRawHttpRequestInt = errorCode _, err := networkStorageAllowedHostService.GetCredential(123456) Expect(err).To(HaveOccurred()) } }) }) }) })
mattcui/softlayer-go
services/softlayer_network_storage_allowed_host_test.go
GO
apache-2.0
2,568
/* * Copyright (C) 2014 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.problem27; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * @author Pedro Vicente Gómez Sánchez. */ public class ReverseSentenceTest { private ReverseSentence reverseSentence; @Before public void setUp() { reverseSentence = new ReverseSentence(); } @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullStringsAsInput() { reverseSentence.reverse(null); } @Test public void shouldReturnEmptyIfInputIsEmpty() { assertEquals("", reverseSentence.reverse("")); } @Test public void shouldReverseOneSentenceWithJustOneWord() { String input = "pedro"; String result = reverseSentence.reverse(input); assertEquals("pedro", result); } @Test public void shouldReverseSentenceWithMoreThanOneWord() { String input = "pedro vicente gómez"; String result = reverseSentence.reverse(input); assertEquals("gómez vicente pedro", result); } }
Ariloum/Algorithms
src/test/java/com/github/pedrovgs/problem27/ReverseSentenceTest.java
Java
apache-2.0
1,618
/** * 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 backtype.storm.generated; public class NotAliveException extends Exception { private static final long serialVersionUID = -6138719666490739879L; }
mycFelix/heron
storm-compatibility/src/java/backtype/storm/generated/NotAliveException.java
Java
apache-2.0
962
/* * Copyright 2000-2014 Vaadin Ltd. * * 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.vaadin.ui; import java.util.Date; import com.vaadin.data.Property; import com.vaadin.server.PaintException; import com.vaadin.server.PaintTarget; import com.vaadin.shared.ui.datefield.PopupDateFieldState; /** * <p> * A date entry component, which displays the actual date selector as a popup. * * </p> * * @see DateField * @see InlineDateField * @author Vaadin Ltd. * @since 5.0 */ public class PopupDateField extends DateField { private String inputPrompt = null; public PopupDateField() { super(); } public PopupDateField(Property dataSource) throws IllegalArgumentException { super(dataSource); } public PopupDateField(String caption, Date value) { super(caption, value); } public PopupDateField(String caption, Property dataSource) { super(caption, dataSource); } public PopupDateField(String caption) { super(caption); } @Override public void paintContent(PaintTarget target) throws PaintException { super.paintContent(target); if (inputPrompt != null) { target.addAttribute("prompt", inputPrompt); } } /** * Gets the current input prompt. * * @see #setInputPrompt(String) * @return the current input prompt, or null if not enabled */ public String getInputPrompt() { return inputPrompt; } /** * Sets the input prompt - a textual prompt that is displayed when the field * would otherwise be empty, to prompt the user for input. * * @param inputPrompt */ public void setInputPrompt(String inputPrompt) { this.inputPrompt = inputPrompt; markAsDirty(); } @Override protected PopupDateFieldState getState() { return (PopupDateFieldState) super.getState(); } @Override protected PopupDateFieldState getState(boolean markAsDirty) { return (PopupDateFieldState) super.getState(markAsDirty); } /** * Checks whether the text field is enabled (default) or not. * * @see PopupDateField#setTextFieldEnabled(boolean); * * @return <b>true</b> if the text field is enabled, <b>false</b> otherwise. */ public boolean isTextFieldEnabled() { return getState(false).textFieldEnabled; } /** * Enables or disables the text field. By default the text field is enabled. * Disabling it causes only the button for date selection to be active, thus * preventing the user from entering invalid dates. * * See {@link http://dev.vaadin.com/ticket/6790}. * * @param state * <b>true</b> to enable text field, <b>false</b> to disable it. */ public void setTextFieldEnabled(boolean state) { getState().textFieldEnabled = state; } /** * Set a description that explains the usage of the Widget for users of * assistive devices. * * @param description * String with the description */ public void setAssistiveText(String description) { getState().descriptionForAssistiveDevices = description; } /** * Get the description that explains the usage of the Widget for users of * assistive devices. * * @return String with the description */ public String getAssistiveText() { return getState(false).descriptionForAssistiveDevices; } }
jdahlstrom/vaadin.react
server/src/main/java/com/vaadin/ui/PopupDateField.java
Java
apache-2.0
4,052
'''This module implements specialized container datatypes providing alternatives to Python's general purpose built-in containers, dict, list, set, and tuple. * namedtuple factory function for creating tuple subclasses with named fields * deque list-like container with fast appends and pops on either end * ChainMap dict-like class for creating a single view of multiple mappings * Counter dict subclass for counting hashable objects * OrderedDict dict subclass that remembers the order entries were added * defaultdict dict subclass that calls a factory function to supply missing values * UserDict wrapper around dictionary objects for easier dict subclassing * UserList wrapper around list objects for easier list subclassing * UserString wrapper around string objects for easier string subclassing ''' __all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList', 'UserString', 'Counter', 'OrderedDict', 'ChainMap'] import _collections_abc from operator import itemgetter as _itemgetter, eq as _eq from keyword import iskeyword as _iskeyword import sys as _sys import heapq as _heapq from _weakref import proxy as _proxy from itertools import repeat as _repeat, chain as _chain, starmap as _starmap from reprlib import recursive_repr as _recursive_repr try: from _collections import deque except ImportError: pass else: _collections_abc.MutableSequence.register(deque) try: from _collections import defaultdict except ImportError: pass def __getattr__(name): # For backwards compatibility, continue to make the collections ABCs # through Python 3.6 available through the collections module. # Note, no new collections ABCs were added in Python 3.7 if name in _collections_abc.__all__: obj = getattr(_collections_abc, name) import warnings warnings.warn("Using or importing the ABCs from 'collections' instead " "of from 'collections.abc' is deprecated, " "and in 3.8 it will stop working", DeprecationWarning, stacklevel=2) globals()[name] = obj return obj raise AttributeError(f'module {__name__!r} has no attribute {name!r}') ################################################################################ ### OrderedDict ################################################################################ class _OrderedDictKeysView(_collections_abc.KeysView): def __reversed__(self): yield from reversed(self._mapping) class _OrderedDictItemsView(_collections_abc.ItemsView): def __reversed__(self): for key in reversed(self._mapping): yield (key, self._mapping[key]) class _OrderedDictValuesView(_collections_abc.ValuesView): def __reversed__(self): for key in reversed(self._mapping): yield self._mapping[key] class _Link(object): __slots__ = 'prev', 'next', 'key', '__weakref__' class OrderedDict(dict): 'Dictionary that remembers insertion order' # An inherited dict maps keys to values. # The inherited dict provides __getitem__, __len__, __contains__, and get. # The remaining methods are order-aware. # Big-O running times for all methods are the same as regular dictionaries. # The internal self.__map dict maps keys to links in a doubly linked list. # The circular doubly linked list starts and ends with a sentinel element. # The sentinel element never gets deleted (this simplifies the algorithm). # The sentinel is in self.__hardroot with a weakref proxy in self.__root. # The prev links are weakref proxies (to prevent circular references). # Individual links are kept alive by the hard reference in self.__map. # Those hard references disappear when a key is deleted from an OrderedDict. def __init__(*args, **kwds): '''Initialize an ordered dictionary. The signature is the same as regular dictionaries. Keyword argument order is preserved. ''' if not args: raise TypeError("descriptor '__init__' of 'OrderedDict' object " "needs an argument") self, *args = args if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__root except AttributeError: self.__hardroot = _Link() self.__root = root = _proxy(self.__hardroot) root.prev = root.next = root self.__map = {} self.__update(*args, **kwds) def __setitem__(self, key, value, dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link): 'od.__setitem__(i, y) <==> od[i]=y' # Setting a new item creates a new link at the end of the linked list, # and the inherited dictionary is updated with the new key/value pair. if key not in self: self.__map[key] = link = Link() root = self.__root last = root.prev link.prev, link.next, link.key = last, root, key last.next = link root.prev = proxy(link) dict_setitem(self, key, value) def __delitem__(self, key, dict_delitem=dict.__delitem__): 'od.__delitem__(y) <==> del od[y]' # Deleting an existing item uses self.__map to find the link which gets # removed by updating the links in the predecessor and successor nodes. dict_delitem(self, key) link = self.__map.pop(key) link_prev = link.prev link_next = link.next link_prev.next = link_next link_next.prev = link_prev link.prev = None link.next = None def __iter__(self): 'od.__iter__() <==> iter(od)' # Traverse the linked list in order. root = self.__root curr = root.next while curr is not root: yield curr.key curr = curr.next def __reversed__(self): 'od.__reversed__() <==> reversed(od)' # Traverse the linked list in reverse order. root = self.__root curr = root.prev while curr is not root: yield curr.key curr = curr.prev def clear(self): 'od.clear() -> None. Remove all items from od.' root = self.__root root.prev = root.next = root self.__map.clear() dict.clear(self) def popitem(self, last=True): '''Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order if last is true or FIFO order if false. ''' if not self: raise KeyError('dictionary is empty') root = self.__root if last: link = root.prev link_prev = link.prev link_prev.next = root root.prev = link_prev else: link = root.next link_next = link.next root.next = link_next link_next.prev = root key = link.key del self.__map[key] value = dict.pop(self, key) return key, value def move_to_end(self, key, last=True): '''Move an existing element to the end (or beginning if last is false). Raise KeyError if the element does not exist. ''' link = self.__map[key] link_prev = link.prev link_next = link.next soft_link = link_next.prev link_prev.next = link_next link_next.prev = link_prev root = self.__root if last: last = root.prev link.prev = last link.next = root root.prev = soft_link last.next = link else: first = root.next link.prev = root link.next = first first.prev = soft_link root.next = link def __sizeof__(self): sizeof = _sys.getsizeof n = len(self) + 1 # number of links including root size = sizeof(self.__dict__) # instance dictionary size += sizeof(self.__map) * 2 # internal dict and inherited dict size += sizeof(self.__hardroot) * n # link objects size += sizeof(self.__root) * n # proxy objects return size update = __update = _collections_abc.MutableMapping.update def keys(self): "D.keys() -> a set-like object providing a view on D's keys" return _OrderedDictKeysView(self) def items(self): "D.items() -> a set-like object providing a view on D's items" return _OrderedDictItemsView(self) def values(self): "D.values() -> an object providing a view on D's values" return _OrderedDictValuesView(self) __ne__ = _collections_abc.MutableMapping.__ne__ __marker = object() def pop(self, key, default=__marker): '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. ''' if key in self: result = self[key] del self[key] return result if default is self.__marker: raise KeyError(key) return default def setdefault(self, key, default=None): '''Insert key with a value of default if key is not in the dictionary. Return the value for key if key is in the dictionary, else default. ''' if key in self: return self[key] self[key] = default return default @_recursive_repr() def __repr__(self): 'od.__repr__() <==> repr(od)' if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, list(self.items())) def __reduce__(self): 'Return state information for pickling' inst_dict = vars(self).copy() for k in vars(OrderedDict()): inst_dict.pop(k, None) return self.__class__, (), inst_dict or None, None, iter(self.items()) def copy(self): 'od.copy() -> a shallow copy of od' return self.__class__(self) @classmethod def fromkeys(cls, iterable, value=None): '''Create a new ordered dictionary with keys from iterable and values set to value. ''' self = cls() for key in iterable: self[key] = value return self def __eq__(self, other): '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive. ''' if isinstance(other, OrderedDict): return dict.__eq__(self, other) and all(map(_eq, self, other)) return dict.__eq__(self, other) try: from _collections import OrderedDict except ImportError: # Leave the pure Python version in place. pass ################################################################################ ### namedtuple ################################################################################ _nt_itemgetters = {} def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None): """Returns a new subclass of tuple with named fields. >>> Point = namedtuple('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1] # indexable like a plain tuple 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessible by name 33 >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields Point(x=100, y=22) """ # Validate the field names. At the user's option, either generate an error # message or automatically replace the field name with a valid name. if isinstance(field_names, str): field_names = field_names.replace(',', ' ').split() field_names = list(map(str, field_names)) typename = _sys.intern(str(typename)) if rename: seen = set() for index, name in enumerate(field_names): if (not name.isidentifier() or _iskeyword(name) or name.startswith('_') or name in seen): field_names[index] = f'_{index}' seen.add(name) for name in [typename] + field_names: if type(name) is not str: raise TypeError('Type names and field names must be strings') if not name.isidentifier(): raise ValueError('Type names and field names must be valid ' f'identifiers: {name!r}') if _iskeyword(name): raise ValueError('Type names and field names cannot be a ' f'keyword: {name!r}') seen = set() for name in field_names: if name.startswith('_') and not rename: raise ValueError('Field names cannot start with an underscore: ' f'{name!r}') if name in seen: raise ValueError(f'Encountered duplicate field name: {name!r}') seen.add(name) field_defaults = {} if defaults is not None: defaults = tuple(defaults) if len(defaults) > len(field_names): raise TypeError('Got more default values than field names') field_defaults = dict(reversed(list(zip(reversed(field_names), reversed(defaults))))) # Variables used in the methods and docstrings field_names = tuple(map(_sys.intern, field_names)) num_fields = len(field_names) arg_list = repr(field_names).replace("'", "")[1:-1] repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')' tuple_new = tuple.__new__ _len = len # Create all the named tuple methods to be added to the class namespace s = f'def __new__(_cls, {arg_list}): return _tuple_new(_cls, ({arg_list}))' namespace = {'_tuple_new': tuple_new, '__name__': f'namedtuple_{typename}'} # Note: exec() has the side-effect of interning the field names exec(s, namespace) __new__ = namespace['__new__'] __new__.__doc__ = f'Create new instance of {typename}({arg_list})' if defaults is not None: __new__.__defaults__ = defaults @classmethod def _make(cls, iterable): result = tuple_new(cls, iterable) if _len(result) != num_fields: raise TypeError(f'Expected {num_fields} arguments, got {len(result)}') return result _make.__func__.__doc__ = (f'Make a new {typename} object from a sequence ' 'or iterable') def _replace(_self, **kwds): result = _self._make(map(kwds.pop, field_names, _self)) if kwds: raise ValueError(f'Got unexpected field names: {list(kwds)!r}') return result _replace.__doc__ = (f'Return a new {typename} object replacing specified ' 'fields with new values') def __repr__(self): 'Return a nicely formatted representation string' return self.__class__.__name__ + repr_fmt % self def _asdict(self): 'Return a new OrderedDict which maps field names to their values.' return OrderedDict(zip(self._fields, self)) def __getnewargs__(self): 'Return self as a plain tuple. Used by copy and pickle.' return tuple(self) # Modify function metadata to help with introspection and debugging for method in (__new__, _make.__func__, _replace, __repr__, _asdict, __getnewargs__): method.__qualname__ = f'{typename}.{method.__name__}' # Build-up the class namespace dictionary # and use type() to build the result class class_namespace = { '__doc__': f'{typename}({arg_list})', '__slots__': (), '_fields': field_names, '_fields_defaults': field_defaults, '__new__': __new__, '_make': _make, '_replace': _replace, '__repr__': __repr__, '_asdict': _asdict, '__getnewargs__': __getnewargs__, } cache = _nt_itemgetters for index, name in enumerate(field_names): try: itemgetter_object, doc = cache[index] except KeyError: itemgetter_object = _itemgetter(index) doc = f'Alias for field number {index}' cache[index] = itemgetter_object, doc class_namespace[name] = property(itemgetter_object, doc=doc) result = type(typename, (tuple,), class_namespace) # For pickling to work, the __module__ variable needs to be set to the frame # where the named tuple is created. Bypass this step in environments where # sys._getframe is not defined (Jython for example) or sys._getframe is not # defined for arguments greater than 0 (IronPython), or where the user has # specified a particular module. if module is None: try: module = _sys._getframe(1).f_globals.get('__name__', '__main__') except (AttributeError, ValueError): pass if module is not None: result.__module__ = module return result ######################################################################## ### Counter ######################################################################## def _count_elements(mapping, iterable): 'Tally elements from the iterable.' mapping_get = mapping.get for elem in iterable: mapping[elem] = mapping_get(elem, 0) + 1 try: # Load C helper function if available from _collections import _count_elements except ImportError: pass class Counter(dict): '''Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values. >>> c = Counter('abcdeabcdabcaba') # count elements from a string >>> c.most_common(3) # three most common elements [('a', 5), ('b', 4), ('c', 3)] >>> sorted(c) # list all unique elements ['a', 'b', 'c', 'd', 'e'] >>> ''.join(sorted(c.elements())) # list elements with repetitions 'aaaaabbbbcccdde' >>> sum(c.values()) # total of all counts 15 >>> c['a'] # count of letter 'a' 5 >>> for elem in 'shazam': # update counts from an iterable ... c[elem] += 1 # by adding 1 to each element's count >>> c['a'] # now there are seven 'a' 7 >>> del c['b'] # remove all 'b' >>> c['b'] # now there are zero 'b' 0 >>> d = Counter('simsalabim') # make another counter >>> c.update(d) # add in the second counter >>> c['a'] # now there are nine 'a' 9 >>> c.clear() # empty the counter >>> c Counter() Note: If a count is set to zero or reduced to zero, it will remain in the counter until the entry is deleted or the counter is cleared: >>> c = Counter('aaabbc') >>> c['b'] -= 2 # reduce the count of 'b' by two >>> c.most_common() # 'b' is still in, but its count is zero [('a', 3), ('c', 1), ('b', 0)] ''' # References: # http://en.wikipedia.org/wiki/Multiset # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm # http://code.activestate.com/recipes/259174/ # Knuth, TAOCP Vol. II section 4.6.3 def __init__(*args, **kwds): '''Create a new, empty Counter object. And if given, count elements from an input iterable. Or, initialize the count from another mapping of elements to their counts. >>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping >>> c = Counter(a=4, b=2) # a new counter from keyword args ''' if not args: raise TypeError("descriptor '__init__' of 'Counter' object " "needs an argument") self, *args = args if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) super(Counter, self).__init__() self.update(*args, **kwds) def __missing__(self, key): 'The count of elements not in the Counter is zero.' # Needed so that self[missing_item] does not raise KeyError return 0 def most_common(self, n=None): '''List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts. >>> Counter('abcdeabcdabcaba').most_common(3) [('a', 5), ('b', 4), ('c', 3)] ''' # Emulate Bag.sortedByCount from Smalltalk if n is None: return sorted(self.items(), key=_itemgetter(1), reverse=True) return _heapq.nlargest(n, self.items(), key=_itemgetter(1)) def elements(self): '''Iterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> product = 1 >>> for factor in prime_factors.elements(): # loop over factors ... product *= factor # and multiply them >>> product 1836 Note, if an element's count has been set to zero or is a negative number, elements() will ignore it. ''' # Emulate Bag.do from Smalltalk and Multiset.begin from C++. return _chain.from_iterable(_starmap(_repeat, self.items())) # Override dict methods where necessary @classmethod def fromkeys(cls, iterable, v=None): # There is no equivalent method for counters because setting v=1 # means that no element can have a count greater than one. raise NotImplementedError( 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') def update(*args, **kwds): '''Like dict.update() but add counts instead of replacing them. Source can be an iterable, a dictionary, or another Counter instance. >>> c = Counter('which') >>> c.update('witch') # add elements from another iterable >>> d = Counter('watch') >>> c.update(d) # add elements from another counter >>> c['h'] # four 'h' in which, witch, and watch 4 ''' # The regular dict.update() operation makes no sense here because the # replace behavior results in the some of original untouched counts # being mixed-in with all of the other counts for a mismash that # doesn't have a straight-forward interpretation in most counting # contexts. Instead, we implement straight-addition. Both the inputs # and outputs are allowed to contain zero and negative counts. if not args: raise TypeError("descriptor 'update' of 'Counter' object " "needs an argument") self, *args = args if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) iterable = args[0] if args else None if iterable is not None: if isinstance(iterable, _collections_abc.Mapping): if self: self_get = self.get for elem, count in iterable.items(): self[elem] = count + self_get(elem, 0) else: super(Counter, self).update(iterable) # fast path when counter is empty else: _count_elements(self, iterable) if kwds: self.update(kwds) def subtract(*args, **kwds): '''Like dict.update() but subtracts counts instead of replacing them. Counts can be reduced below zero. Both the inputs and outputs are allowed to contain zero and negative counts. Source can be an iterable, a dictionary, or another Counter instance. >>> c = Counter('which') >>> c.subtract('witch') # subtract elements from another iterable >>> c.subtract(Counter('watch')) # subtract elements from another counter >>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch 0 >>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch -1 ''' if not args: raise TypeError("descriptor 'subtract' of 'Counter' object " "needs an argument") self, *args = args if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) iterable = args[0] if args else None if iterable is not None: self_get = self.get if isinstance(iterable, _collections_abc.Mapping): for elem, count in iterable.items(): self[elem] = self_get(elem, 0) - count else: for elem in iterable: self[elem] = self_get(elem, 0) - 1 if kwds: self.subtract(kwds) def copy(self): 'Return a shallow copy.' return self.__class__(self) def __reduce__(self): return self.__class__, (dict(self),) def __delitem__(self, elem): 'Like dict.__delitem__() but does not raise KeyError for missing values.' if elem in self: super().__delitem__(elem) def __repr__(self): if not self: return '%s()' % self.__class__.__name__ try: items = ', '.join(map('%r: %r'.__mod__, self.most_common())) return '%s({%s})' % (self.__class__.__name__, items) except TypeError: # handle case where values are not orderable return '{0}({1!r})'.format(self.__class__.__name__, dict(self)) # Multiset-style mathematical operations discussed in: # Knuth TAOCP Volume II section 4.6.3 exercise 19 # and at http://en.wikipedia.org/wiki/Multiset # # Outputs guaranteed to only include positive counts. # # To strip negative and zero counts, add-in an empty counter: # c += Counter() def __add__(self, other): '''Add counts from two counters. >>> Counter('abbb') + Counter('bcc') Counter({'b': 4, 'c': 2, 'a': 1}) ''' if not isinstance(other, Counter): return NotImplemented result = Counter() for elem, count in self.items(): newcount = count + other[elem] if newcount > 0: result[elem] = newcount for elem, count in other.items(): if elem not in self and count > 0: result[elem] = count return result def __sub__(self, other): ''' Subtract count, but keep only results with positive counts. >>> Counter('abbbc') - Counter('bccd') Counter({'b': 2, 'a': 1}) ''' if not isinstance(other, Counter): return NotImplemented result = Counter() for elem, count in self.items(): newcount = count - other[elem] if newcount > 0: result[elem] = newcount for elem, count in other.items(): if elem not in self and count < 0: result[elem] = 0 - count return result def __or__(self, other): '''Union is the maximum of value in either of the input counters. >>> Counter('abbb') | Counter('bcc') Counter({'b': 3, 'c': 2, 'a': 1}) ''' if not isinstance(other, Counter): return NotImplemented result = Counter() for elem, count in self.items(): other_count = other[elem] newcount = other_count if count < other_count else count if newcount > 0: result[elem] = newcount for elem, count in other.items(): if elem not in self and count > 0: result[elem] = count return result def __and__(self, other): ''' Intersection is the minimum of corresponding counts. >>> Counter('abbb') & Counter('bcc') Counter({'b': 1}) ''' if not isinstance(other, Counter): return NotImplemented result = Counter() for elem, count in self.items(): other_count = other[elem] newcount = count if count < other_count else other_count if newcount > 0: result[elem] = newcount return result def __pos__(self): 'Adds an empty counter, effectively stripping negative and zero counts' result = Counter() for elem, count in self.items(): if count > 0: result[elem] = count return result def __neg__(self): '''Subtracts from an empty counter. Strips positive and zero counts, and flips the sign on negative counts. ''' result = Counter() for elem, count in self.items(): if count < 0: result[elem] = 0 - count return result def _keep_positive(self): '''Internal method to strip elements with a negative or zero count''' nonpositive = [elem for elem, count in self.items() if not count > 0] for elem in nonpositive: del self[elem] return self def __iadd__(self, other): '''Inplace add from another counter, keeping only positive counts. >>> c = Counter('abbb') >>> c += Counter('bcc') >>> c Counter({'b': 4, 'c': 2, 'a': 1}) ''' for elem, count in other.items(): self[elem] += count return self._keep_positive() def __isub__(self, other): '''Inplace subtract counter, but keep only results with positive counts. >>> c = Counter('abbbc') >>> c -= Counter('bccd') >>> c Counter({'b': 2, 'a': 1}) ''' for elem, count in other.items(): self[elem] -= count return self._keep_positive() def __ior__(self, other): '''Inplace union is the maximum of value from either counter. >>> c = Counter('abbb') >>> c |= Counter('bcc') >>> c Counter({'b': 3, 'c': 2, 'a': 1}) ''' for elem, other_count in other.items(): count = self[elem] if other_count > count: self[elem] = other_count return self._keep_positive() def __iand__(self, other): '''Inplace intersection is the minimum of corresponding counts. >>> c = Counter('abbb') >>> c &= Counter('bcc') >>> c Counter({'b': 1}) ''' for elem, count in self.items(): other_count = other[elem] if other_count < count: self[elem] = other_count return self._keep_positive() ######################################################################## ### ChainMap ######################################################################## class ChainMap(_collections_abc.MutableMapping): ''' A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view. The underlying mappings are stored in a list. That list is public and can be accessed or updated using the *maps* attribute. There is no other state. Lookups search the underlying mappings successively until a key is found. In contrast, writes, updates, and deletions only operate on the first mapping. ''' def __init__(self, *maps): '''Initialize a ChainMap by setting *maps* to the given mappings. If no mappings are provided, a single empty dictionary is used. ''' self.maps = list(maps) or [{}] # always at least one map def __missing__(self, key): raise KeyError(key) def __getitem__(self, key): for mapping in self.maps: try: return mapping[key] # can't use 'key in mapping' with defaultdict except KeyError: pass return self.__missing__(key) # support subclasses that define __missing__ def get(self, key, default=None): return self[key] if key in self else default def __len__(self): return len(set().union(*self.maps)) # reuses stored hash values if possible def __iter__(self): d = {} for mapping in reversed(self.maps): d.update(mapping) # reuses stored hash values if possible return iter(d) def __contains__(self, key): return any(key in m for m in self.maps) def __bool__(self): return any(self.maps) @_recursive_repr() def __repr__(self): return '{0.__class__.__name__}({1})'.format( self, ', '.join(map(repr, self.maps))) @classmethod def fromkeys(cls, iterable, *args): 'Create a ChainMap with a single dict created from the iterable.' return cls(dict.fromkeys(iterable, *args)) def copy(self): 'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]' return self.__class__(self.maps[0].copy(), *self.maps[1:]) __copy__ = copy def new_child(self, m=None): # like Django's Context.push() '''New ChainMap with a new map followed by all previous maps. If no map is provided, an empty dict is used. ''' if m is None: m = {} return self.__class__(m, *self.maps) @property def parents(self): # like Django's Context.pop() 'New ChainMap from maps[1:].' return self.__class__(*self.maps[1:]) def __setitem__(self, key, value): self.maps[0][key] = value def __delitem__(self, key): try: del self.maps[0][key] except KeyError: raise KeyError('Key not found in the first mapping: {!r}'.format(key)) def popitem(self): 'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.' try: return self.maps[0].popitem() except KeyError: raise KeyError('No keys found in the first mapping.') def pop(self, key, *args): 'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].' try: return self.maps[0].pop(key, *args) except KeyError: raise KeyError('Key not found in the first mapping: {!r}'.format(key)) def clear(self): 'Clear maps[0], leaving maps[1:] intact.' self.maps[0].clear() ################################################################################ ### UserDict ################################################################################ class UserDict(_collections_abc.MutableMapping): # Start by filling-out the abstract methods def __init__(*args, **kwargs): if not args: raise TypeError("descriptor '__init__' of 'UserDict' object " "needs an argument") self, *args = args if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) if args: dict = args[0] elif 'dict' in kwargs: dict = kwargs.pop('dict') import warnings warnings.warn("Passing 'dict' as keyword argument is deprecated", DeprecationWarning, stacklevel=2) else: dict = None self.data = {} if dict is not None: self.update(dict) if len(kwargs): self.update(kwargs) def __len__(self): return len(self.data) def __getitem__(self, key): if key in self.data: return self.data[key] if hasattr(self.__class__, "__missing__"): return self.__class__.__missing__(self, key) raise KeyError(key) def __setitem__(self, key, item): self.data[key] = item def __delitem__(self, key): del self.data[key] def __iter__(self): return iter(self.data) # Modify __contains__ to work correctly when __missing__ is present def __contains__(self, key): return key in self.data # Now, add the methods in dicts but not in MutableMapping def __repr__(self): return repr(self.data) def copy(self): if self.__class__ is UserDict: return UserDict(self.data.copy()) import copy data = self.data try: self.data = {} c = copy.copy(self) finally: self.data = data c.update(self) return c @classmethod def fromkeys(cls, iterable, value=None): d = cls() for key in iterable: d[key] = value return d ################################################################################ ### UserList ################################################################################ class UserList(_collections_abc.MutableSequence): """A more or less complete user-defined wrapper around list objects.""" def __init__(self, initlist=None): self.data = [] if initlist is not None: # XXX should this accept an arbitrary sequence? if type(initlist) == type(self.data): self.data[:] = initlist elif isinstance(initlist, UserList): self.data[:] = initlist.data[:] else: self.data = list(initlist) def __repr__(self): return repr(self.data) def __lt__(self, other): return self.data < self.__cast(other) def __le__(self, other): return self.data <= self.__cast(other) def __eq__(self, other): return self.data == self.__cast(other) def __gt__(self, other): return self.data > self.__cast(other) def __ge__(self, other): return self.data >= self.__cast(other) def __cast(self, other): return other.data if isinstance(other, UserList) else other def __contains__(self, item): return item in self.data def __len__(self): return len(self.data) def __getitem__(self, i): return self.data[i] def __setitem__(self, i, item): self.data[i] = item def __delitem__(self, i): del self.data[i] def __add__(self, other): if isinstance(other, UserList): return self.__class__(self.data + other.data) elif isinstance(other, type(self.data)): return self.__class__(self.data + other) return self.__class__(self.data + list(other)) def __radd__(self, other): if isinstance(other, UserList): return self.__class__(other.data + self.data) elif isinstance(other, type(self.data)): return self.__class__(other + self.data) return self.__class__(list(other) + self.data) def __iadd__(self, other): if isinstance(other, UserList): self.data += other.data elif isinstance(other, type(self.data)): self.data += other else: self.data += list(other) return self def __mul__(self, n): return self.__class__(self.data*n) __rmul__ = __mul__ def __imul__(self, n): self.data *= n return self def append(self, item): self.data.append(item) def insert(self, i, item): self.data.insert(i, item) def pop(self, i=-1): return self.data.pop(i) def remove(self, item): self.data.remove(item) def clear(self): self.data.clear() def copy(self): return self.__class__(self) def count(self, item): return self.data.count(item) def index(self, item, *args): return self.data.index(item, *args) def reverse(self): self.data.reverse() def sort(self, *args, **kwds): self.data.sort(*args, **kwds) def extend(self, other): if isinstance(other, UserList): self.data.extend(other.data) else: self.data.extend(other) ################################################################################ ### UserString ################################################################################ class UserString(_collections_abc.Sequence): def __init__(self, seq): if isinstance(seq, str): self.data = seq elif isinstance(seq, UserString): self.data = seq.data[:] else: self.data = str(seq) def __str__(self): return str(self.data) def __repr__(self): return repr(self.data) def __int__(self): return int(self.data) def __float__(self): return float(self.data) def __complex__(self): return complex(self.data) def __hash__(self): return hash(self.data) def __getnewargs__(self): return (self.data[:],) def __eq__(self, string): if isinstance(string, UserString): return self.data == string.data return self.data == string def __lt__(self, string): if isinstance(string, UserString): return self.data < string.data return self.data < string def __le__(self, string): if isinstance(string, UserString): return self.data <= string.data return self.data <= string def __gt__(self, string): if isinstance(string, UserString): return self.data > string.data return self.data > string def __ge__(self, string): if isinstance(string, UserString): return self.data >= string.data return self.data >= string def __contains__(self, char): if isinstance(char, UserString): char = char.data return char in self.data def __len__(self): return len(self.data) def __getitem__(self, index): return self.__class__(self.data[index]) def __add__(self, other): if isinstance(other, UserString): return self.__class__(self.data + other.data) elif isinstance(other, str): return self.__class__(self.data + other) return self.__class__(self.data + str(other)) def __radd__(self, other): if isinstance(other, str): return self.__class__(other + self.data) return self.__class__(str(other) + self.data) def __mul__(self, n): return self.__class__(self.data*n) __rmul__ = __mul__ def __mod__(self, args): return self.__class__(self.data % args) def __rmod__(self, format): return self.__class__(format % args) # the following methods are defined in alphabetical order: def capitalize(self): return self.__class__(self.data.capitalize()) def casefold(self): return self.__class__(self.data.casefold()) def center(self, width, *args): return self.__class__(self.data.center(width, *args)) def count(self, sub, start=0, end=_sys.maxsize): if isinstance(sub, UserString): sub = sub.data return self.data.count(sub, start, end) def encode(self, encoding=None, errors=None): # XXX improve this? if encoding: if errors: return self.__class__(self.data.encode(encoding, errors)) return self.__class__(self.data.encode(encoding)) return self.__class__(self.data.encode()) def endswith(self, suffix, start=0, end=_sys.maxsize): return self.data.endswith(suffix, start, end) def expandtabs(self, tabsize=8): return self.__class__(self.data.expandtabs(tabsize)) def find(self, sub, start=0, end=_sys.maxsize): if isinstance(sub, UserString): sub = sub.data return self.data.find(sub, start, end) def format(self, *args, **kwds): return self.data.format(*args, **kwds) def format_map(self, mapping): return self.data.format_map(mapping) def index(self, sub, start=0, end=_sys.maxsize): return self.data.index(sub, start, end) def isalpha(self): return self.data.isalpha() def isalnum(self): return self.data.isalnum() def isascii(self): return self.data.isascii() def isdecimal(self): return self.data.isdecimal() def isdigit(self): return self.data.isdigit() def isidentifier(self): return self.data.isidentifier() def islower(self): return self.data.islower() def isnumeric(self): return self.data.isnumeric() def isprintable(self): return self.data.isprintable() def isspace(self): return self.data.isspace() def istitle(self): return self.data.istitle() def isupper(self): return self.data.isupper() def join(self, seq): return self.data.join(seq) def ljust(self, width, *args): return self.__class__(self.data.ljust(width, *args)) def lower(self): return self.__class__(self.data.lower()) def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars)) maketrans = str.maketrans def partition(self, sep): return self.data.partition(sep) def replace(self, old, new, maxsplit=-1): if isinstance(old, UserString): old = old.data if isinstance(new, UserString): new = new.data return self.__class__(self.data.replace(old, new, maxsplit)) def rfind(self, sub, start=0, end=_sys.maxsize): if isinstance(sub, UserString): sub = sub.data return self.data.rfind(sub, start, end) def rindex(self, sub, start=0, end=_sys.maxsize): return self.data.rindex(sub, start, end) def rjust(self, width, *args): return self.__class__(self.data.rjust(width, *args)) def rpartition(self, sep): return self.data.rpartition(sep) def rstrip(self, chars=None): return self.__class__(self.data.rstrip(chars)) def split(self, sep=None, maxsplit=-1): return self.data.split(sep, maxsplit) def rsplit(self, sep=None, maxsplit=-1): return self.data.rsplit(sep, maxsplit) def splitlines(self, keepends=False): return self.data.splitlines(keepends) def startswith(self, prefix, start=0, end=_sys.maxsize): return self.data.startswith(prefix, start, end) def strip(self, chars=None): return self.__class__(self.data.strip(chars)) def swapcase(self): return self.__class__(self.data.swapcase()) def title(self): return self.__class__(self.data.title()) def translate(self, *args): return self.__class__(self.data.translate(*args)) def upper(self): return self.__class__(self.data.upper()) def zfill(self, width): return self.__class__(self.data.zfill(width))
mdanielwork/intellij-community
python/testData/MockSdk3.7/Lib/collections/__init__.py
Python
apache-2.0
47,640
/*************************GO-LICENSE-START********************************* * Copyright 2014 ThoughtWorks, 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. *************************GO-LICENSE-END***********************************/ package com.thoughtworks.go.plugin.api.task; /** * Used to define the view of the task configuration. */ @Deprecated //Will be moved to internal scope public interface TaskView { /** * Specifies the display value of this task plugin. This value is used in the job UI's task dropdown * as well as in the title of the task definition dialog box. * * @return display value for the task plugin */ String displayValue(); /** * The template for the task configuration, written using Angular.js templating language. * * @return Angular.js template for the task configuration */ String template(); }
varshavaradarajan/gocd
plugin-infra/go-plugin-api/src/main/java/com/thoughtworks/go/plugin/api/task/TaskView.java
Java
apache-2.0
1,405
/* Copyright 2016 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 v1alpha1 import ( "k8s.io/client-go/1.4/pkg/api/unversioned" "k8s.io/client-go/1.4/pkg/api/v1" "k8s.io/client-go/1.4/pkg/util/intstr" ) // PodDisruptionBudgetSpec is a description of a PodDisruptionBudget. type PodDisruptionBudgetSpec struct { // The minimum number of pods that must be available simultaneously. This // can be either an integer or a string specifying a percentage, e.g. "28%". MinAvailable intstr.IntOrString `json:"minAvailable,omitempty" protobuf:"bytes,1,opt,name=minAvailable"` // Label query over pods whose evictions are managed by the disruption // budget. Selector *unversioned.LabelSelector `json:"selector,omitempty" protobuf:"bytes,2,opt,name=selector"` } // PodDisruptionBudgetStatus represents information about the status of a // PodDisruptionBudget. Status may trail the actual state of a system. type PodDisruptionBudgetStatus struct { // Whether or not a disruption is currently allowed. PodDisruptionAllowed bool `json:"disruptionAllowed" protobuf:"varint,1,opt,name=disruptionAllowed"` // current number of healthy pods CurrentHealthy int32 `json:"currentHealthy" protobuf:"varint,2,opt,name=currentHealthy"` // minimum desired number of healthy pods DesiredHealthy int32 `json:"desiredHealthy" protobuf:"varint,3,opt,name=desiredHealthy"` // total number of pods counted by this disruption budget ExpectedPods int32 `json:"expectedPods" protobuf:"varint,4,opt,name=expectedPods"` } // +genclient=true // +noMethods=true // PodDisruptionBudget is an object to define the max disruption that can be caused to a collection of pods type PodDisruptionBudget struct { unversioned.TypeMeta `json:",inline"` v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` // Specification of the desired behavior of the PodDisruptionBudget. Spec PodDisruptionBudgetSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` // Most recently observed status of the PodDisruptionBudget. Status PodDisruptionBudgetStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` } // PodDisruptionBudgetList is a collection of PodDisruptionBudgets. type PodDisruptionBudgetList struct { unversioned.TypeMeta `json:",inline"` unversioned.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` Items []PodDisruptionBudget `json:"items" protobuf:"bytes,2,rep,name=items"` }
matthewdupre/kubernetes
staging/src/k8s.io/client-go/1.4/pkg/apis/policy/v1alpha1/types.go
GO
apache-2.0
2,978
/* * Copyright 2019 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.provider.wildfly; import javax.naming.InitialContext; import org.keycloak.Config; import org.keycloak.cluster.ManagedCacheManagerProvider; /** * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a> */ public class WildflyCacheManagerProvider implements ManagedCacheManagerProvider { @Override public <C> C getCacheManager(Config.Scope config) { String cacheContainer = config.get("cacheContainer"); if (cacheContainer == null) { return null; } try { return (C) new InitialContext().lookup(cacheContainer); } catch (Exception e) { throw new RuntimeException("Failed to retrieve cache container", e); } } }
thomasdarimont/keycloak
wildfly/extensions/src/main/java/org/keycloak/provider/wildfly/WildflyCacheManagerProvider.java
Java
apache-2.0
1,431
// Copyright 2009 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Test that getters can be defined and called with an index as a parameter. var o = {}; o.x = 42; o.__defineGetter__('0', function() { return o.x; }); assertEquals(o.x, o[0]); assertEquals(o.x, o.__lookupGetter__('0')()); o.__defineSetter__('0', function(y) { o.x = y; }); assertEquals(o.x, o[0]); assertEquals(o.x, o.__lookupGetter__('0')()); o[0] = 21; assertEquals(21, o.x); o.__lookupSetter__(0)(7); assertEquals(7, o.x); function Pair(x, y) { this.x = x; this.y = y; }; Pair.prototype.__defineGetter__('0', function() { return this.x; }); Pair.prototype.__defineGetter__('1', function() { return this.y; }); Pair.prototype.__defineSetter__('0', function(x) { this.x = x; }); Pair.prototype.__defineSetter__('1', function(y) { this.y = y; }); var p = new Pair(2, 3); assertEquals(2, p[0]); assertEquals(3, p[1]); p.x = 7; p[1] = 8; assertEquals(7, p[0]); assertEquals(7, p.x); assertEquals(8, p[1]); assertEquals(8, p.y); // Testing that a defined getter doesn't get lost due to inline caching. var expected = {}; var actual = {}; for (var i = 0; i < 10; i++) { expected[i] = actual[i] = i; } function testArray() { for (var i = 0; i < 10; i++) { assertEquals(expected[i], actual[i]); } } actual[1000000] = -1; testArray(); testArray(); actual.__defineGetter__('0', function() { return expected[0]; }); expected[0] = 42; testArray(); expected[0] = 111; testArray(); // Using a setter where only a getter is defined does not throw an exception, // unless we are in strict mode. var q = {}; q.__defineGetter__('0', function() { return 42; }); assertDoesNotThrow('q[0] = 7'); // Using a getter where only a setter is defined returns undefined. var q1 = {}; q1.__defineSetter__('0', function() {q1.b = 17;}); assertEquals(q1[0], undefined); // Setter works q1[0] = 3; assertEquals(q1[0], undefined); assertEquals(q1.b, 17); // Complex case of using an undefined getter. // From http://code.google.com/p/v8/issues/detail?id=298 // Reported by nth10sd. a = function() {}; this.__defineSetter__("0", function() {}); if (a |= '') {}; assertThrows('this[a].__parent__'); assertEquals(a, 0); assertEquals(this[a], undefined);
zero-rp/miniblink49
v8_7_5/test/mjsunit/indexed-accessors.js
JavaScript
apache-2.0
3,743
/** * An assortment of Windows Store app-related tools. * * @module winstore * * @copyright * Copyright (c) 2014 by Appcelerator, Inc. All Rights Reserved. * * @license * Licensed under the terms of the Apache Public License. * Please see the LICENSE included with this distribution for details. */ const appc = require('node-appc'), async = require('async'), fs = require('fs'), magik = require('./utilities').magik, path = require('path'), visualstudio = require('./visualstudio'), __ = appc.i18n(__dirname).__; var architectures = [ 'arm', 'x86', 'x64' ]; var detectCache, deviceCache = {}; exports.install = install; exports.launch = launch; exports.uninstall = uninstall; exports.detect = detect; /** * Installs a Windows Store application. * * @param {Object} [options] - An object containing various settings. * @param {String} [options.buildConfiguration='Release'] - The type of configuration to build using. Example: "Release" or "Debug". * @param {Function} [callback(err)] - A function to call after installing the Windows Store app. * * @emits module:winstore#error * @emits module:winstore#installed * * @returns {EventEmitter} */ function install(projectDir, options, callback) { return magik(options, callback, function (emitter, options, callback) { var scripts = [], packageScript = 'Add-AppDevPackage.ps1'; // find the Add-AppDevPackage.ps1 (function walk(dir) { fs.readdirSync(dir).forEach(function (name) { var file = path.join(dir, name); if (fs.statSync(file).isDirectory()) { walk(file); } else if (name === packageScript && (!options.buildConfiguration || path.basename(dir).indexOf('_' + options.buildConfiguration) !== -1)) { scripts.push(file); } }); }(projectDir)); if (!scripts.length) { var err = new Error(__('Unable to find built application. Please rebuild the project.')); emitter.emit('error', err); return callback(err); } // let's grab the first match appc.subprocess.getRealName(scripts[0], function (err, psScript) { if (err) { emitter.emit('error', err); return callback(err); } appc.subprocess.run(options.powershell || 'powershell', ['-ExecutionPolicy', 'Bypass', '-NoLogo', '-NoProfile', '-File', psScript, '-Force'], function (code, out, err) { if (!code) { emitter.emit('installed'); return callback(); } // I'm seeing "Please run this script without the -Force parameter" for Win 8.1 store apps. // This originally was "Please rerun the script without the -Force parameter" (for Win 8 hybrid apps?) // It's a hack to check for the common substring. Hopefully use of the exact error codes works better first // Error codes 9 and 14 mean rerun without -Force if ((code && (code == 9 || code == 14)) || out.indexOf('script without the -Force parameter') !== -1) { appc.subprocess.run(options.powershell || 'powershell', ['-ExecutionPolicy', 'Bypass', '-NoLogo', '-NoProfile', '-File', psScript], function (code, out, err) { if (err) { emitter.emit('error', err); callback(err); } else { emitter.emit('installed'); callback(); } }); return; } // must have been some other issue, error out var ex = new Error(__('Failed to install app: %s', out)); emitter.emit('error', ex); callback(ex); }); }); }); } /** * Uninstalls a Windows Store application. * * @param {String} appId - The application id. * @param {Object} [options] - An object containing various settings. * @param {String} [options.powershell='powershell'] - Path to the 'powershell' executable. * @param {Function} [callback(err)] - A function to call after uninstalling the Windows Store app. * * @emits module:winstore#error * @emits module:winstore#uninstalled * * @returns {EventEmitter} */ function uninstall(appId, options, callback) { return magik(options, callback, function (emitter, options, callback) { appc.subprocess.run(options.powershell || 'powershell', ['-command', 'Get-AppxPackage'], function (code, out, err) { if (code) { var ex = new Error(__('Could not query the list of installed Windows Store apps: %s', err || code)); emitter.emit('error', ex); return callback(ex); } var packageNameRegExp = new RegExp('PackageFullName[\\s]*:[\\s]*(' + appId + '.*)'), packageName; out.split(/\r\n|\n/).some(function (line) { var m = line.trim().match(packageNameRegExp); if (m) { packageName = m[1]; return true; } }); if (packageName) { appc.subprocess.run(options.powershell || 'powershell', ['-command', 'Remove-AppxPackage', packageName], function (code, out, err) { if (err) { emitter.emit('error', err); callback(err); } else { emitter.emit('uninstalled'); callback(); } }); } else { emitter.emit('uninstalled'); callback(); } }); }); } /** * Launches a Windows Store application. * * @param {String} appId - The application id. * @param {String} version - The application version. * @param {Object} [options] - An object containing various settings. * @param {String} [options.powershell='powershell'] - Path to the 'powershell' executable. * @param {String} [options.version] - The specific version of the app to launch. If empty, picks the largest version. * @param {Function} [callback(err)] - A function to call after uninstalling the Windows Store app. * * @emits module:winstore#error * @emits module:winstore#launched * * @returns {EventEmitter} */ function launch(appId, options, callback) { return magik(options, callback, function (emitter, options, callback) { var wstool = path.resolve(__dirname, '..', 'bin', 'wstool.exe'); function runTool() { var args = ['launch', appId]; options.version && args.push(options.version); appc.subprocess.run(wstool, args, function (code, out, err) { if (code) { var ex = new Error(__('Erroring running wstool (code %s)', code) + '\n' + out); emitter.emit('error', ex); callback(ex); } else { emitter.emit('installed'); callback(); } }); } if (fs.existsSync(wstool)) { runTool(); } else { visualstudio.build(appc.util.mix({ buildConfiguration: 'Release', project: path.resolve(__dirname, '..', 'wstool', 'wstool.csproj') }, options), function (err, result) { if (err) { emitter.emit('error', err); return callback(err); } var src = path.resolve(__dirname, '..', 'wstool', 'bin', 'Release', 'wstool.exe'); if (!fs.existsSync(src)) { var ex = new Error(__('Failed to build the wstool executable.') + (result ? '\n' + result.out : '')); emitter.emit('error', ex); return callback(ex); } // sanity check that the wstool.exe wasn't copied by another async task in windowslib if (!fs.existsSync(wstool)) { fs.writeFileSync(wstool, fs.readFileSync(src)); } runTool(); }); } }); } /** * Detects Windows Store SDKs. * * @param {Object} [options] - An object containing various settings. * @param {Boolean} [options.bypassCache=false] - When true, re-detects the Windows SDKs. * @param {String} [options.preferredWindowsSDK] - The preferred version of the Windows SDK to use by default. Example "8.0". * @param {String} [options.supportedWindowsSDKVersions] - A string with a version number or range to check if a Windows SDK is supported. * @param {Function} [callback(err, results)] - A function to call with the Windows SDK information. * * @emits module:windowsphone#detected * @emits module:windowsphone#error * * @returns {EventEmitter} */ function detect(options, callback) { return magik(options, callback, function (emitter, options, callback) { if (detectCache && !options.bypassCache) { emitter.emit('detected', detectCache); return callback(null, detectCache); } var results = { windows: {}, issues: [] }, searchPaths = [ 'HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Microsoft SDKs\\Windows', // probably nothing here 'HKEY_LOCAL_MACHINE\\Software\\Wow6432Node\\Microsoft\\Microsoft SDKs\\Windows' // this is most likely where Windows SDK will be found ]; function finalize() { detectCache = results; emitter.emit('detected', results); callback(null, results); } async.each(searchPaths, function (keyPath, next) { appc.subprocess.run('reg', ['query', keyPath], function (code, out, err) { var keyRegExp = /.+\\(v\d+\.\d)$/; if (!code) { out.trim().split(/\r\n|\n/).forEach(function (key) { key = key.trim(); var m = key.match(keyRegExp); if (!m) { return; } var version = m[1].replace(/^v/, ''); if (m) { results.windows || (results.windows = {}); results.windows[version] = { version: version, registryKey: keyPath + '\\' + m[1], supported: !options.supportedWindowsSDKVersions || appc.version.satisfies(version, options.supportedWindowsSDKVersions, false), // no maybes path: null, signTool: null, makeCert: null, pvk2pfx: null, selected: false }; } }); } next(); }); }, function () { // check if we didn't find any Windows SDKs, then we're done if (!Object.keys(results.windows).length) { results.issues.push({ id: 'WINDOWS_STORE_SDK_NOT_INSTALLED', type: 'error', message: __('Microsoft Windows Store SDK not found.') + '\n' + __('You will be unable to build Windows Store apps.') }); return finalize(); } // fetch Windows SDK install information async.each(Object.keys(results.windows), function (ver, next) { appc.subprocess.run('reg', ['query', results.windows[ver].registryKey, '/v', '*'], function (code, out, err) { if (code) { // bad key? either way, remove this version delete results.windows[ver]; } else { // get only the values we are interested in out.trim().split(/\r\n|\n/).forEach(function (line) { var parts = line.trim().split(' ').map(function (p) { return p.trim(); }); if (parts.length == 3) { if (parts[0] == 'InstallationFolder') { results.windows[ver].path = parts[2]; function addIfExists(key, exe) { for (var i = 0; i < architectures.length; i++) { var arch = architectures[i], tool = path.join(parts[2], 'bin', arch, exe); if (fs.existsSync(tool)) { !results.windows[ver][key] && (results.windows[ver][key] = {}); results.windows[ver][key][arch] = tool; } } } addIfExists('signTool', 'SignTool.exe'); addIfExists('makeCert', 'MakeCert.exe'); addIfExists('pvk2pfx', 'pvk2pfx.exe'); } } }); } next(); }); }, function () { // double check if we didn't find any Windows SDKs, then we're done if (Object.keys(results.windows).every(function (v) { return !results.windows[v].path; })) { results.issues.push({ id: 'WINDOWS_STORE_SDK_NOT_INSTALLED', type: 'error', message: __('Microsoft Windows Store SDK not found.') + '\n' + __('You will be unable to build Windows Store apps.') }); return finalize(); } if (Object.keys(results.windows).every(function (v) { return !results.windows[v].deployCmd; })) { results.issues.push({ id: 'WINDOWS_STORE_SDK_MISSING_DEPLOY_CMD', type: 'error', message: __('Microsoft Windows Store SDK is missing the deploy command.') + '\n' + __('You will be unable to build Windows Store apps.') }); return finalize(); } var preferred = options.preferred; if (!results.windows[preferred] || !results.windows[preferred].supported) { preferred = Object.keys(results.windows).filter(function (v) { return results.windows[v].supported; }).sort().pop(); } if (preferred) { results.windows[preferred].selected = true; } finalize(); }); }); }); }
prop/titanium_mobile
node_modules/windowslib/lib/winstore.js
JavaScript
apache-2.0
12,463
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.kns.web.taglib.html; import org.apache.commons.lang.StringUtils; import org.apache.struts.action.ActionForm; import org.apache.struts.taglib.html.TextareaTag; import org.kuali.rice.kns.util.WebUtils; import org.kuali.rice.kns.web.struts.form.pojo.PojoForm; import javax.servlet.jsp.JspException; /** * This is a description of what this class does - bhargavp don't forget to fill this in. * * @author Kuali Rice Team (rice.collab@kuali.org) * * @deprecated KNS Struts deprecated, use KRAD and the Spring MVC framework. */ @Deprecated public class KNSTextareaTag extends TextareaTag { /** * @see org.apache.struts.taglib.html.BaseInputTag#doEndTag() */ @Override public int doEndTag() throws JspException { int returnVal = super.doEndTag(); if (!getDisabled() && !getReadonly()) { String name = prepareName(); if (StringUtils.isNotBlank(name)) { ActionForm form = WebUtils.getKualiForm(pageContext); if(form!=null && form instanceof PojoForm) { ((PojoForm) form).registerEditableProperty(name); } } } return returnVal; } }
bhutchinson/rice
rice-middleware/kns/src/main/java/org/kuali/rice/kns/web/taglib/html/KNSTextareaTag.java
Java
apache-2.0
1,855
/* * 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.installer.factories.configuration.impl; import java.util.Hashtable; import org.apache.sling.installer.api.ResourceChangeListener; import org.apache.sling.installer.api.tasks.InstallTaskFactory; import org.apache.sling.installer.api.tasks.ResourceTransformer; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.cm.ConfigurationListener; /** * The <code>ServicesListener</code> listens for the required services * and starts/stops the scanners based on the availability of the * services. */ public class ServicesListener { /** Vendor of all registered services. */ public static final String VENDOR = "The Apache Software Foundation"; /** The bundle context. */ private final BundleContext bundleContext; /** The listener for the change list handler. */ private final Listener changeHandlerListener; /** The listener for the configuration admin. */ private final Listener configAdminListener; /** Registration the service. */ private ServiceRegistration<?> configTaskCreatorRegistration; private ConfigTaskCreator configTaskCreator; public ServicesListener(final BundleContext bundleContext) { this.bundleContext = bundleContext; this.changeHandlerListener = new Listener(ResourceChangeListener.class.getName()); this.configAdminListener = new Listener(ConfigurationAdmin.class.getName()); this.changeHandlerListener.start(); this.configAdminListener.start(); } public synchronized void notifyChange() { // check if all services are available final ResourceChangeListener listener = (ResourceChangeListener)this.changeHandlerListener.getService(); final ConfigurationAdmin configAdmin = (ConfigurationAdmin)this.configAdminListener.getService(); if ( configAdmin != null && listener != null ) { if ( configTaskCreator == null ) { final Hashtable<String, String> props = new Hashtable<String, String>(); props.put(Constants.SERVICE_DESCRIPTION, "Apache Sling Configuration Install Task Factory"); props.put(Constants.SERVICE_VENDOR, VENDOR); props.put(InstallTaskFactory.NAME, "org.osgi.service.cm"); props.put(ResourceTransformer.NAME, "org.osgi.service.cm"); this.configTaskCreator = new ConfigTaskCreator(listener, configAdmin); // start and register osgi installer service final String [] serviceInterfaces = { InstallTaskFactory.class.getName(), ConfigurationListener.class.getName(), ResourceTransformer.class.getName() }; configTaskCreatorRegistration = this.bundleContext.registerService(serviceInterfaces, configTaskCreator, props); } } else { this.stop(); } } private void stop() { // unregister if ( this.configTaskCreatorRegistration != null ) { this.configTaskCreatorRegistration.unregister(); this.configTaskCreatorRegistration = null; } this.configTaskCreator = null; } /** * Deactivate this listener. */ public void deactivate() { this.changeHandlerListener.deactivate(); this.configAdminListener.deactivate(); this.stop(); } protected final class Listener implements ServiceListener { private final String serviceName; private ServiceReference<?> reference; private Object service; public Listener(final String serviceName) { this.serviceName = serviceName; } public void start() { this.retainService(); try { bundleContext.addServiceListener(this, "(" + Constants.OBJECTCLASS + "=" + serviceName + ")"); } catch (final InvalidSyntaxException ise) { // this should really never happen throw new RuntimeException("Unexpected exception occured.", ise); } } public void deactivate() { bundleContext.removeServiceListener(this); } public synchronized Object getService() { return this.service; } private synchronized void retainService() { if ( this.reference == null ) { this.reference = bundleContext.getServiceReference(this.serviceName); if ( this.reference != null ) { this.service = bundleContext.getService(this.reference); if ( this.service == null ) { this.reference = null; } else { notifyChange(); } } } } private synchronized void releaseService() { if ( this.reference != null ) { this.service = null; bundleContext.ungetService(this.reference); this.reference = null; notifyChange(); } } /** * @see org.osgi.framework.ServiceListener#serviceChanged(org.osgi.framework.ServiceEvent) */ @Override public void serviceChanged(ServiceEvent event) { if (event.getType() == ServiceEvent.REGISTERED ) { this.retainService(); } else if ( event.getType() == ServiceEvent.UNREGISTERING ) { this.releaseService(); } } } }
cleliameneghin/sling
installer/factories/configuration/src/main/java/org/apache/sling/installer/factories/configuration/impl/ServicesListener.java
Java
apache-2.0
6,734
// 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. #include "chrome/browser/sync_file_system/drive_backend/metadata_database.h" #include "base/bind.h" #include "base/files/scoped_temp_dir.h" #include "base/message_loop/message_loop.h" #include "base/strings/string_number_conversions.h" #include "base/thread_task_runner_handle.h" #include "chrome/browser/sync_file_system/drive_backend/drive_backend_constants.h" #include "chrome/browser/sync_file_system/drive_backend/drive_backend_test_util.h" #include "chrome/browser/sync_file_system/drive_backend/drive_backend_util.h" #include "chrome/browser/sync_file_system/drive_backend/leveldb_wrapper.h" #include "chrome/browser/sync_file_system/drive_backend/metadata_database.pb.h" #include "chrome/browser/sync_file_system/drive_backend/metadata_database_index.h" #include "chrome/browser/sync_file_system/drive_backend/metadata_database_index_interface.h" #include "chrome/browser/sync_file_system/drive_backend/metadata_database_index_on_disk.h" #include "chrome/browser/sync_file_system/sync_file_system_test_util.h" #include "google_apis/drive/drive_api_parser.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/leveldatabase/src/helpers/memenv/memenv.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" #include "third_party/leveldatabase/src/include/leveldb/env.h" #include "third_party/leveldatabase/src/include/leveldb/write_batch.h" #define FPL(a) FILE_PATH_LITERAL(a) namespace sync_file_system { namespace drive_backend { namespace { typedef MetadataDatabase::FileIDList FileIDList; const int64 kInitialChangeID = 1234; const int64 kSyncRootTrackerID = 100; const char kSyncRootFolderID[] = "sync_root_folder_id"; // This struct is used to setup initial state of the database in the test and // also used to match to the modified content of the database as the // expectation. struct TrackedFile { // Holds the latest remote metadata which may be not-yet-synced to |tracker|. FileMetadata metadata; FileTracker tracker; // Implies the file should not in the database. bool should_be_absent; // Implies the file should have a tracker in the database but should have no // metadata. bool tracker_only; TrackedFile() : should_be_absent(false), tracker_only(false) {} }; void ExpectEquivalentServiceMetadata( const MetadataDatabaseIndexInterface* left, const MetadataDatabaseIndexInterface* right) { EXPECT_EQ(left->GetLargestChangeID(), right->GetLargestChangeID()); EXPECT_EQ(left->GetSyncRootTrackerID(), right->GetSyncRootTrackerID()); EXPECT_EQ(left->GetNextTrackerID(), right->GetNextTrackerID()); } void ExpectEquivalent(const FileMetadata* left, const FileMetadata* right) { if (!left) { ASSERT_FALSE(right); return; } ASSERT_TRUE(right); test_util::ExpectEquivalentMetadata(*left, *right); } void ExpectEquivalent(const FileTracker* left, const FileTracker* right) { if (!left) { ASSERT_FALSE(right); return; } ASSERT_TRUE(right); test_util::ExpectEquivalentTrackers(*left, *right); } void ExpectEquivalent(int64 left, int64 right) { EXPECT_EQ(left, right); } template <typename Container> void ExpectEquivalentMaps(const Container& left, const Container& right); template <typename Key, typename Value> void ExpectEquivalent(const std::map<Key, Value>& left, const std::map<Key, Value>& right) { ExpectEquivalentMaps(left, right); } template <typename Key, typename Value> void ExpectEquivalent(const base::hash_map<Key, Value>& left, const base::hash_map<Key, Value>& right) { ExpectEquivalentMaps(std::map<Key, Value>(left.begin(), left.end()), std::map<Key, Value>(right.begin(), right.end())); } template <typename Key, typename Value> void ExpectEquivalent(const base::ScopedPtrHashMap<Key, Value>& left, const base::ScopedPtrHashMap<Key, Value>& right) { ExpectEquivalentMaps(std::map<Key, Value*>(left.begin(), left.end()), std::map<Key, Value*>(right.begin(), right.end())); } template <typename Container> void ExpectEquivalentSets(const Container& left, const Container& right); template <typename Value, typename Comparator> void ExpectEquivalent(const std::set<Value, Comparator>& left, const std::set<Value, Comparator>& right) { return ExpectEquivalentSets(left, right); } template <typename Value> void ExpectEquivalent(const base::hash_set<Value>& left, const base::hash_set<Value>& right) { return ExpectEquivalentSets(std::set<Value>(left.begin(), left.end()), std::set<Value>(right.begin(), right.end())); } void ExpectEquivalent(const TrackerIDSet& left, const TrackerIDSet& right) { { SCOPED_TRACE("Expect equivalent active_tracker"); EXPECT_EQ(left.active_tracker(), right.active_tracker()); } ExpectEquivalent(left.tracker_set(), right.tracker_set()); } template <typename Container> void ExpectEquivalentMaps(const Container& left, const Container& right) { ASSERT_EQ(left.size(), right.size()); typedef typename Container::const_iterator const_iterator; const_iterator left_itr = left.begin(); const_iterator right_itr = right.begin(); while (left_itr != left.end()) { EXPECT_EQ(left_itr->first, right_itr->first); ExpectEquivalent(left_itr->second, right_itr->second); ++left_itr; ++right_itr; } } template <typename Container> void ExpectEquivalentSets(const Container& left, const Container& right) { ASSERT_EQ(left.size(), right.size()); typedef typename Container::const_iterator const_iterator; const_iterator left_itr = left.begin(); const_iterator right_itr = right.begin(); while (left_itr != left.end()) { ExpectEquivalent(*left_itr, *right_itr); ++left_itr; ++right_itr; } } base::FilePath CreateNormalizedPath(const base::FilePath::StringType& path) { return base::FilePath(path).NormalizePathSeparators(); } } // namespace class MetadataDatabaseTest : public testing::TestWithParam<bool> { public: MetadataDatabaseTest() : current_change_id_(kInitialChangeID), next_tracker_id_(kSyncRootTrackerID + 1), next_file_id_number_(1), next_md5_sequence_number_(1) {} virtual ~MetadataDatabaseTest() {} void SetUp() override { ASSERT_TRUE(database_dir_.CreateUniqueTempDir()); in_memory_env_.reset(leveldb::NewMemEnv(leveldb::Env::Default())); } void TearDown() override { DropDatabase(); } protected: std::string GenerateFileID() { return "file_id_" + base::Int64ToString(next_file_id_number_++); } int64 GetTrackerIDByFileID(const std::string& file_id) { TrackerIDSet trackers; if (metadata_database_->FindTrackersByFileID(file_id, &trackers)) { EXPECT_FALSE(trackers.empty()); return *trackers.begin(); } return 0; } SyncStatusCode InitializeMetadataDatabase() { SyncStatusCode status = SYNC_STATUS_UNKNOWN; metadata_database_ = MetadataDatabase::CreateInternal( database_dir_.path(), in_memory_env_.get(), GetParam(), &status); return status; } void DropDatabase() { metadata_database_.reset(); message_loop_.RunUntilIdle(); } void SetUpDatabaseByTrackedFiles(const TrackedFile** tracked_files, int size) { scoped_ptr<LevelDBWrapper> db = InitializeLevelDB(); ASSERT_TRUE(db); for (int i = 0; i < size; ++i) { const TrackedFile* file = tracked_files[i]; if (file->should_be_absent) continue; if (!file->tracker_only) EXPECT_TRUE(PutFileToDB(db.get(), file->metadata).ok()); EXPECT_TRUE(PutTrackerToDB(db.get(), file->tracker).ok()); } } void VerifyTrackedFile(const TrackedFile& file) { if (!file.should_be_absent) { if (file.tracker_only) { EXPECT_FALSE(metadata_database()->FindFileByFileID( file.metadata.file_id(), nullptr)); } else { VerifyFile(file.metadata); } VerifyTracker(file.tracker); return; } EXPECT_FALSE(metadata_database()->FindFileByFileID( file.metadata.file_id(), nullptr)); EXPECT_FALSE(metadata_database()->FindTrackerByTrackerID( file.tracker.tracker_id(), nullptr)); } void VerifyTrackedFiles(const TrackedFile** tracked_files, int size) { for (int i = 0; i < size; ++i) VerifyTrackedFile(*tracked_files[i]); } MetadataDatabase* metadata_database() { return metadata_database_.get(); } scoped_ptr<LevelDBWrapper> InitializeLevelDB() { leveldb::DB* db = nullptr; leveldb::Options options; options.create_if_missing = true; options.max_open_files = 0; // Use minimum. options.env = in_memory_env_.get(); leveldb::Status status = leveldb::DB::Open(options, database_dir_.path().AsUTF8Unsafe(), &db); EXPECT_TRUE(status.ok()); scoped_ptr<LevelDBWrapper> wrapper(new LevelDBWrapper(make_scoped_ptr(db))); wrapper->Put(kDatabaseVersionKey, base::Int64ToString(3)); SetUpServiceMetadata(wrapper.get()); return wrapper.Pass(); } void SetUpServiceMetadata(LevelDBWrapper* db) { ServiceMetadata service_metadata; service_metadata.set_largest_change_id(kInitialChangeID); service_metadata.set_sync_root_tracker_id(kSyncRootTrackerID); service_metadata.set_next_tracker_id(next_tracker_id_); PutServiceMetadataToDB(service_metadata, db); EXPECT_TRUE(db->Commit().ok()); } FileMetadata CreateSyncRootMetadata() { FileMetadata sync_root; sync_root.set_file_id(kSyncRootFolderID); FileDetails* details = sync_root.mutable_details(); details->set_title(kSyncRootFolderTitle); details->set_file_kind(FILE_KIND_FOLDER); details->set_change_id(current_change_id_); return sync_root; } FileMetadata CreateFileMetadata(const FileMetadata& parent, const std::string& title) { FileMetadata file; file.set_file_id(GenerateFileID()); FileDetails* details = file.mutable_details(); details->add_parent_folder_ids(parent.file_id()); details->set_title(title); details->set_file_kind(FILE_KIND_FILE); details->set_md5( "md5_value_" + base::Int64ToString(next_md5_sequence_number_++)); details->set_change_id(current_change_id_); return file; } FileMetadata CreateFolderMetadata(const FileMetadata& parent, const std::string& title) { FileMetadata folder; folder.set_file_id(GenerateFileID()); FileDetails* details = folder.mutable_details(); details->add_parent_folder_ids(parent.file_id()); details->set_title(title); details->set_file_kind(FILE_KIND_FOLDER); details->set_change_id(current_change_id_); return folder; } FileTracker CreateSyncRootTracker(const FileMetadata& sync_root) { FileTracker sync_root_tracker; sync_root_tracker.set_tracker_id(kSyncRootTrackerID); sync_root_tracker.set_parent_tracker_id(0); sync_root_tracker.set_file_id(sync_root.file_id()); sync_root_tracker.set_dirty(false); sync_root_tracker.set_active(true); sync_root_tracker.set_needs_folder_listing(false); *sync_root_tracker.mutable_synced_details() = sync_root.details(); return sync_root_tracker; } FileTracker CreateTracker(const FileTracker& parent_tracker, const FileMetadata& file) { FileTracker tracker; tracker.set_tracker_id(next_tracker_id_++); tracker.set_parent_tracker_id(parent_tracker.tracker_id()); tracker.set_file_id(file.file_id()); tracker.set_app_id(parent_tracker.app_id()); tracker.set_tracker_kind(TRACKER_KIND_REGULAR); tracker.set_dirty(false); tracker.set_active(true); tracker.set_needs_folder_listing(false); *tracker.mutable_synced_details() = file.details(); return tracker; } TrackedFile CreateTrackedSyncRoot() { TrackedFile sync_root; sync_root.metadata = CreateSyncRootMetadata(); sync_root.tracker = CreateSyncRootTracker(sync_root.metadata); return sync_root; } TrackedFile CreateTrackedAppRoot(const TrackedFile& sync_root, const std::string& app_id) { TrackedFile app_root(CreateTrackedFolder(sync_root, app_id)); app_root.tracker.set_app_id(app_id); app_root.tracker.set_tracker_kind(TRACKER_KIND_APP_ROOT); return app_root; } TrackedFile CreateTrackedFile(const TrackedFile& parent, const std::string& title) { TrackedFile file; file.metadata = CreateFileMetadata(parent.metadata, title); file.tracker = CreateTracker(parent.tracker, file.metadata); return file; } TrackedFile CreateTrackedFolder(const TrackedFile& parent, const std::string& title) { TrackedFile folder; folder.metadata = CreateFolderMetadata(parent.metadata, title); folder.tracker = CreateTracker(parent.tracker, folder.metadata); return folder; } scoped_ptr<google_apis::FileResource> CreateFileResourceFromMetadata( const FileMetadata& file) { scoped_ptr<google_apis::FileResource> file_resource( new google_apis::FileResource); for (int i = 0; i < file.details().parent_folder_ids_size(); ++i) { google_apis::ParentReference parent; parent.set_file_id(file.details().parent_folder_ids(i)); file_resource->mutable_parents()->push_back(parent); } file_resource->set_file_id(file.file_id()); file_resource->set_title(file.details().title()); if (file.details().file_kind() == FILE_KIND_FOLDER) { file_resource->set_mime_type("application/vnd.google-apps.folder"); } else if (file.details().file_kind() == FILE_KIND_FILE) { file_resource->set_mime_type("text/plain"); file_resource->set_file_size(0); } else { file_resource->set_mime_type("application/vnd.google-apps.document"); } file_resource->set_md5_checksum(file.details().md5()); file_resource->set_etag(file.details().etag()); file_resource->set_created_date(base::Time::FromInternalValue( file.details().creation_time())); file_resource->set_modified_date(base::Time::FromInternalValue( file.details().modification_time())); return file_resource.Pass(); } scoped_ptr<google_apis::ChangeResource> CreateChangeResourceFromMetadata( const FileMetadata& file) { scoped_ptr<google_apis::ChangeResource> change( new google_apis::ChangeResource); change->set_change_id(file.details().change_id()); change->set_file_id(file.file_id()); change->set_deleted(file.details().missing()); if (change->is_deleted()) return change.Pass(); change->set_file(CreateFileResourceFromMetadata(file)); return change.Pass(); } void ApplyRenameChangeToMetadata(const std::string& new_title, FileMetadata* file) { FileDetails* details = file->mutable_details(); details->set_title(new_title); details->set_change_id(++current_change_id_); } void ApplyReorganizeChangeToMetadata(const std::string& new_parent, FileMetadata* file) { FileDetails* details = file->mutable_details(); details->clear_parent_folder_ids(); details->add_parent_folder_ids(new_parent); details->set_change_id(++current_change_id_); } void ApplyContentChangeToMetadata(FileMetadata* file) { FileDetails* details = file->mutable_details(); details->set_md5( "md5_value_" + base::Int64ToString(next_md5_sequence_number_++)); details->set_change_id(++current_change_id_); } void ApplyNoopChangeToMetadata(FileMetadata* file) { file->mutable_details()->set_change_id(++current_change_id_); } void PushToChangeList(scoped_ptr<google_apis::ChangeResource> change, ScopedVector<google_apis::ChangeResource>* changes) { changes->push_back(change.release()); } leveldb::Status PutFileToDB(LevelDBWrapper* db, const FileMetadata& file) { PutFileMetadataToDB(file, db); return db->Commit(); } leveldb::Status PutTrackerToDB(LevelDBWrapper* db, const FileTracker& tracker) { PutFileTrackerToDB(tracker, db); return db->Commit(); } void VerifyReloadConsistencyForOnMemory(MetadataDatabaseIndex* index1, MetadataDatabaseIndex* index2) { ExpectEquivalentServiceMetadata(index1, index2); { SCOPED_TRACE("Expect equivalent metadata_by_id_ contents."); ExpectEquivalent(index1->metadata_by_id_, index2->metadata_by_id_); } { SCOPED_TRACE("Expect equivalent tracker_by_id_ contents."); ExpectEquivalent(index1->tracker_by_id_, index2->tracker_by_id_); } { SCOPED_TRACE("Expect equivalent trackers_by_file_id_ contents."); ExpectEquivalent(index1->trackers_by_file_id_, index2->trackers_by_file_id_); } { SCOPED_TRACE("Expect equivalent app_root_by_app_id_ contents."); ExpectEquivalent(index1->app_root_by_app_id_, index2->app_root_by_app_id_); } { SCOPED_TRACE("Expect equivalent trackers_by_parent_and_title_ contents."); ExpectEquivalent(index1->trackers_by_parent_and_title_, index2->trackers_by_parent_and_title_); } { SCOPED_TRACE("Expect equivalent dirty_trackers_ contents."); ExpectEquivalent(index1->dirty_trackers_, index2->dirty_trackers_); } } void VerifyReloadConsistencyForOnDisk( MetadataDatabaseIndexOnDisk* index1, MetadataDatabaseIndexOnDisk* index2) { ExpectEquivalentServiceMetadata(index1, index2); scoped_ptr<LevelDBWrapper::Iterator> itr1 = index1->GetDBForTesting()->NewIterator(); scoped_ptr<LevelDBWrapper::Iterator> itr2 = index2->GetDBForTesting()->NewIterator(); for (itr1->SeekToFirst(), itr2->SeekToFirst(); itr1->Valid() && itr2->Valid(); itr1->Next(), itr2->Next()) { EXPECT_EQ(itr1->key().ToString(), itr2->key().ToString()); EXPECT_EQ(itr1->value().ToString(), itr2->value().ToString()); } EXPECT_TRUE(!itr1->Valid()); EXPECT_TRUE(!itr2->Valid()); } void VerifyReloadConsistency() { scoped_ptr<MetadataDatabase> metadata_database_2; ASSERT_EQ(SYNC_STATUS_OK, MetadataDatabase::CreateForTesting( metadata_database_->db_.Pass(), metadata_database_->enable_on_disk_index_, &metadata_database_2)); metadata_database_->db_ = metadata_database_2->db_.Pass(); MetadataDatabaseIndexInterface* index1 = metadata_database_->index_.get(); MetadataDatabaseIndexInterface* index2 = metadata_database_2->index_.get(); if (GetParam()) { VerifyReloadConsistencyForOnDisk( static_cast<MetadataDatabaseIndexOnDisk*>(index1), static_cast<MetadataDatabaseIndexOnDisk*>(index2)); } else { VerifyReloadConsistencyForOnMemory( static_cast<MetadataDatabaseIndex*>(index1), static_cast<MetadataDatabaseIndex*>(index2)); } } void VerifyFile(const FileMetadata& file) { FileMetadata file_in_metadata_database; ASSERT_TRUE(metadata_database()->FindFileByFileID( file.file_id(), &file_in_metadata_database)); SCOPED_TRACE("Expect equivalent " + file.file_id()); ExpectEquivalent(&file, &file_in_metadata_database); } void VerifyTracker(const FileTracker& tracker) { FileTracker tracker_in_metadata_database; ASSERT_TRUE(metadata_database()->FindTrackerByTrackerID( tracker.tracker_id(), &tracker_in_metadata_database)); SCOPED_TRACE("Expect equivalent tracker[" + base::Int64ToString(tracker.tracker_id()) + "]"); ExpectEquivalent(&tracker, &tracker_in_metadata_database); } SyncStatusCode RegisterApp(const std::string& app_id, const std::string& folder_id) { return metadata_database_->RegisterApp(app_id, folder_id); } SyncStatusCode DisableApp(const std::string& app_id) { return metadata_database_->DisableApp(app_id); } SyncStatusCode EnableApp(const std::string& app_id) { return metadata_database_->EnableApp(app_id); } SyncStatusCode UnregisterApp(const std::string& app_id) { return metadata_database_->UnregisterApp(app_id); } SyncStatusCode UpdateByChangeList( ScopedVector<google_apis::ChangeResource> changes) { return metadata_database_->UpdateByChangeList( current_change_id_, changes.Pass()); } SyncStatusCode PopulateFolder(const std::string& folder_id, const FileIDList& listed_children) { return metadata_database_->PopulateFolderByChildList( folder_id, listed_children); } SyncStatusCode UpdateTracker(const FileTracker& tracker) { return metadata_database_->UpdateTracker( tracker.tracker_id(), tracker.synced_details()); } SyncStatusCode PopulateInitialData( int64 largest_change_id, const google_apis::FileResource& sync_root_folder, const ScopedVector<google_apis::FileResource>& app_root_folders) { return metadata_database_->PopulateInitialData( largest_change_id, sync_root_folder, app_root_folders); } void ResetTrackerID(FileTracker* tracker) { tracker->set_tracker_id(GetTrackerIDByFileID(tracker->file_id())); } int64 current_change_id() const { return current_change_id_; } private: base::ScopedTempDir database_dir_; base::MessageLoop message_loop_; scoped_ptr<leveldb::Env> in_memory_env_; scoped_ptr<MetadataDatabase> metadata_database_; int64 current_change_id_; int64 next_tracker_id_; int64 next_file_id_number_; int64 next_md5_sequence_number_; DISALLOW_COPY_AND_ASSIGN(MetadataDatabaseTest); }; INSTANTIATE_TEST_CASE_P(MetadataDatabaseTestWithIndexesOnDisk, MetadataDatabaseTest, ::testing::Values(true, false)); TEST_P(MetadataDatabaseTest, InitializationTest_Empty) { EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase()); DropDatabase(); EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase()); DropDatabase(); scoped_ptr<LevelDBWrapper> db = InitializeLevelDB(); db->Put(kServiceMetadataKey, "Unparsable string"); EXPECT_TRUE(db->Commit().ok()); db.reset(); EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase()); } TEST_P(MetadataDatabaseTest, InitializationTest_SimpleTree) { TrackedFile sync_root(CreateTrackedSyncRoot()); TrackedFile app_root(CreateTrackedFolder(sync_root, "app_id")); app_root.tracker.set_app_id(app_root.metadata.details().title()); app_root.tracker.set_tracker_kind(TRACKER_KIND_APP_ROOT); TrackedFile file(CreateTrackedFile(app_root, "file")); TrackedFile folder(CreateTrackedFolder(app_root, "folder")); TrackedFile file_in_folder(CreateTrackedFile(folder, "file_in_folder")); TrackedFile orphaned_file(CreateTrackedFile(sync_root, "orphaned_file")); orphaned_file.metadata.mutable_details()->clear_parent_folder_ids(); orphaned_file.tracker.set_parent_tracker_id(0); const TrackedFile* tracked_files[] = { &sync_root, &app_root, &file, &folder, &file_in_folder, &orphaned_file }; SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files)); EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase()); orphaned_file.should_be_absent = true; VerifyTrackedFiles(tracked_files, arraysize(tracked_files)); } TEST_P(MetadataDatabaseTest, AppManagementTest) { TrackedFile sync_root(CreateTrackedSyncRoot()); TrackedFile app_root(CreateTrackedFolder(sync_root, "app_id")); app_root.tracker.set_app_id(app_root.metadata.details().title()); app_root.tracker.set_tracker_kind(TRACKER_KIND_APP_ROOT); TrackedFile file(CreateTrackedFile(app_root, "file")); TrackedFile folder(CreateTrackedFolder(sync_root, "folder")); folder.tracker.set_active(false); const TrackedFile* tracked_files[] = { &sync_root, &app_root, &file, &folder, }; SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files)); EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase()); VerifyTrackedFiles(tracked_files, arraysize(tracked_files)); folder.tracker.set_app_id("foo"); EXPECT_EQ(SYNC_STATUS_OK, RegisterApp( folder.tracker.app_id(), folder.metadata.file_id())); folder.tracker.set_tracker_kind(TRACKER_KIND_APP_ROOT); folder.tracker.set_active(true); folder.tracker.set_dirty(true); folder.tracker.set_needs_folder_listing(true); VerifyTrackedFile(folder); VerifyReloadConsistency(); EXPECT_EQ(SYNC_STATUS_OK, DisableApp(folder.tracker.app_id())); folder.tracker.set_tracker_kind(TRACKER_KIND_DISABLED_APP_ROOT); VerifyTrackedFile(folder); VerifyReloadConsistency(); EXPECT_EQ(SYNC_STATUS_OK, EnableApp(folder.tracker.app_id())); folder.tracker.set_tracker_kind(TRACKER_KIND_APP_ROOT); VerifyTrackedFile(folder); VerifyReloadConsistency(); EXPECT_EQ(SYNC_STATUS_OK, UnregisterApp(folder.tracker.app_id())); folder.tracker.set_app_id(std::string()); folder.tracker.set_tracker_kind(TRACKER_KIND_REGULAR); folder.tracker.set_active(false); VerifyTrackedFile(folder); VerifyReloadConsistency(); EXPECT_EQ(SYNC_STATUS_OK, UnregisterApp(app_root.tracker.app_id())); app_root.tracker.set_app_id(std::string()); app_root.tracker.set_tracker_kind(TRACKER_KIND_REGULAR); app_root.tracker.set_active(false); app_root.tracker.set_dirty(true); file.should_be_absent = true; VerifyTrackedFile(app_root); VerifyTrackedFile(file); VerifyReloadConsistency(); } TEST_P(MetadataDatabaseTest, BuildPathTest) { FileMetadata sync_root(CreateSyncRootMetadata()); FileTracker sync_root_tracker(CreateSyncRootTracker(sync_root)); FileMetadata app_root(CreateFolderMetadata(sync_root, "app_id")); FileTracker app_root_tracker( CreateTracker(sync_root_tracker, app_root)); app_root_tracker.set_app_id(app_root.details().title()); app_root_tracker.set_tracker_kind(TRACKER_KIND_APP_ROOT); FileMetadata folder(CreateFolderMetadata(app_root, "folder")); FileTracker folder_tracker(CreateTracker(app_root_tracker, folder)); FileMetadata file(CreateFileMetadata(folder, "file")); FileTracker file_tracker(CreateTracker(folder_tracker, file)); FileMetadata inactive_folder(CreateFolderMetadata(app_root, "folder")); FileTracker inactive_folder_tracker(CreateTracker(app_root_tracker, inactive_folder)); inactive_folder_tracker.set_active(false); { scoped_ptr<LevelDBWrapper> db = InitializeLevelDB(); ASSERT_TRUE(db); EXPECT_TRUE(PutFileToDB(db.get(), sync_root).ok()); EXPECT_TRUE(PutTrackerToDB(db.get(), sync_root_tracker).ok()); EXPECT_TRUE(PutFileToDB(db.get(), app_root).ok()); EXPECT_TRUE(PutTrackerToDB(db.get(), app_root_tracker).ok()); EXPECT_TRUE(PutFileToDB(db.get(), folder).ok()); EXPECT_TRUE(PutTrackerToDB(db.get(), folder_tracker).ok()); EXPECT_TRUE(PutFileToDB(db.get(), file).ok()); EXPECT_TRUE(PutTrackerToDB(db.get(), file_tracker).ok()); } EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase()); base::FilePath path; EXPECT_FALSE(metadata_database()->BuildPathForTracker( sync_root_tracker.tracker_id(), &path)); EXPECT_TRUE(metadata_database()->BuildPathForTracker( app_root_tracker.tracker_id(), &path)); EXPECT_EQ(base::FilePath(FPL("/")).NormalizePathSeparators(), path); EXPECT_TRUE(metadata_database()->BuildPathForTracker( file_tracker.tracker_id(), &path)); EXPECT_EQ(base::FilePath(FPL("/folder/file")).NormalizePathSeparators(), path); } TEST_P(MetadataDatabaseTest, FindNearestActiveAncestorTest) { const std::string kAppID = "app_id"; FileMetadata sync_root(CreateSyncRootMetadata()); FileTracker sync_root_tracker(CreateSyncRootTracker(sync_root)); FileMetadata app_root(CreateFolderMetadata(sync_root, kAppID)); FileTracker app_root_tracker( CreateTracker(sync_root_tracker, app_root)); app_root_tracker.set_app_id(app_root.details().title()); app_root_tracker.set_tracker_kind(TRACKER_KIND_APP_ROOT); // Create directory structure like this: "/folder1/folder2/file" FileMetadata folder1(CreateFolderMetadata(app_root, "folder1")); FileTracker folder_tracker1(CreateTracker(app_root_tracker, folder1)); FileMetadata folder2(CreateFolderMetadata(folder1, "folder2")); FileTracker folder_tracker2(CreateTracker(folder_tracker1, folder2)); FileMetadata file(CreateFileMetadata(folder2, "file")); FileTracker file_tracker(CreateTracker(folder_tracker2, file)); FileMetadata inactive_folder(CreateFolderMetadata(app_root, "folder1")); FileTracker inactive_folder_tracker(CreateTracker(app_root_tracker, inactive_folder)); inactive_folder_tracker.set_active(false); { scoped_ptr<LevelDBWrapper> db = InitializeLevelDB(); ASSERT_TRUE(db); EXPECT_TRUE(PutFileToDB(db.get(), sync_root).ok()); EXPECT_TRUE(PutTrackerToDB(db.get(), sync_root_tracker).ok()); EXPECT_TRUE(PutFileToDB(db.get(), app_root).ok()); EXPECT_TRUE(PutTrackerToDB(db.get(), app_root_tracker).ok()); EXPECT_TRUE(PutFileToDB(db.get(), folder1).ok()); EXPECT_TRUE(PutTrackerToDB(db.get(), folder_tracker1).ok()); EXPECT_TRUE(PutFileToDB(db.get(), folder2).ok()); EXPECT_TRUE(PutTrackerToDB(db.get(), folder_tracker2).ok()); EXPECT_TRUE(PutFileToDB(db.get(), file).ok()); EXPECT_TRUE(PutTrackerToDB(db.get(), file_tracker).ok()); EXPECT_TRUE(PutFileToDB(db.get(), inactive_folder).ok()); EXPECT_TRUE(PutTrackerToDB(db.get(), inactive_folder_tracker).ok()); } EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase()); { base::FilePath path; FileTracker tracker; EXPECT_FALSE(metadata_database()->FindNearestActiveAncestor( "non_registered_app_id", CreateNormalizedPath(FPL("folder1/folder2/file")), &tracker, &path)); } { base::FilePath path; FileTracker tracker; EXPECT_TRUE(metadata_database()->FindNearestActiveAncestor( kAppID, CreateNormalizedPath(FPL("")), &tracker, &path)); EXPECT_EQ(app_root_tracker.tracker_id(), tracker.tracker_id()); EXPECT_EQ(CreateNormalizedPath(FPL("")), path); } { base::FilePath path; FileTracker tracker; EXPECT_TRUE(metadata_database()->FindNearestActiveAncestor( kAppID, CreateNormalizedPath(FPL("folder1/folder2")), &tracker, &path)); EXPECT_EQ(folder_tracker2.tracker_id(), tracker.tracker_id()); EXPECT_EQ(CreateNormalizedPath(FPL("folder1/folder2")), path); } { base::FilePath path; FileTracker tracker; EXPECT_TRUE(metadata_database()->FindNearestActiveAncestor( kAppID, CreateNormalizedPath(FPL("folder1/folder2/file")), &tracker, &path)); EXPECT_EQ(file_tracker.tracker_id(), tracker.tracker_id()); EXPECT_EQ(CreateNormalizedPath(FPL("folder1/folder2/file")), path); } { base::FilePath path; FileTracker tracker; EXPECT_TRUE(metadata_database()->FindNearestActiveAncestor( kAppID, CreateNormalizedPath(FPL("folder1/folder2/folder3/folder4/file")), &tracker, &path)); EXPECT_EQ(folder_tracker2.tracker_id(), tracker.tracker_id()); EXPECT_EQ(CreateNormalizedPath(FPL("folder1/folder2")), path); } { base::FilePath path; FileTracker tracker; EXPECT_TRUE(metadata_database()->FindNearestActiveAncestor( kAppID, CreateNormalizedPath(FPL("folder1/folder2/file/folder4/file")), &tracker, &path)); EXPECT_EQ(folder_tracker2.tracker_id(), tracker.tracker_id()); EXPECT_EQ(CreateNormalizedPath(FPL("folder1/folder2")), path); } } TEST_P(MetadataDatabaseTest, UpdateByChangeListTest) { TrackedFile sync_root(CreateTrackedSyncRoot()); TrackedFile app_root(CreateTrackedFolder(sync_root, "app_id")); TrackedFile disabled_app_root(CreateTrackedFolder(sync_root, "disabled_app")); TrackedFile file(CreateTrackedFile(app_root, "file")); TrackedFile renamed_file(CreateTrackedFile(app_root, "to be renamed")); TrackedFile folder(CreateTrackedFolder(app_root, "folder")); TrackedFile reorganized_file( CreateTrackedFile(app_root, "to be reorganized")); TrackedFile updated_file( CreateTrackedFile(app_root, "to be updated")); TrackedFile noop_file(CreateTrackedFile(app_root, "has noop change")); TrackedFile new_file(CreateTrackedFile(app_root, "to be added later")); new_file.should_be_absent = true; const TrackedFile* tracked_files[] = { &sync_root, &app_root, &disabled_app_root, &file, &renamed_file, &folder, &reorganized_file, &updated_file, &noop_file, &new_file, }; SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files)); EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase()); ApplyRenameChangeToMetadata("renamed", &renamed_file.metadata); ApplyReorganizeChangeToMetadata(folder.metadata.file_id(), &reorganized_file.metadata); ApplyContentChangeToMetadata(&updated_file.metadata); // Update change ID. ApplyNoopChangeToMetadata(&noop_file.metadata); ScopedVector<google_apis::ChangeResource> changes; PushToChangeList( CreateChangeResourceFromMetadata(renamed_file.metadata), &changes); PushToChangeList( CreateChangeResourceFromMetadata(reorganized_file.metadata), &changes); PushToChangeList( CreateChangeResourceFromMetadata(updated_file.metadata), &changes); PushToChangeList( CreateChangeResourceFromMetadata(noop_file.metadata), &changes); PushToChangeList( CreateChangeResourceFromMetadata(new_file.metadata), &changes); EXPECT_EQ(SYNC_STATUS_OK, UpdateByChangeList(changes.Pass())); renamed_file.tracker.set_dirty(true); reorganized_file.tracker.set_dirty(true); updated_file.tracker.set_dirty(true); noop_file.tracker.set_dirty(true); new_file.tracker.mutable_synced_details()->set_missing(true); new_file.tracker.mutable_synced_details()->clear_md5(); new_file.tracker.set_active(false); new_file.tracker.set_dirty(true); ResetTrackerID(&new_file.tracker); EXPECT_NE(0, new_file.tracker.tracker_id()); new_file.should_be_absent = false; VerifyTrackedFiles(tracked_files, arraysize(tracked_files)); VerifyReloadConsistency(); } TEST_P(MetadataDatabaseTest, PopulateFolderTest_RegularFolder) { TrackedFile sync_root(CreateTrackedSyncRoot()); TrackedFile app_root(CreateTrackedAppRoot(sync_root, "app_id")); app_root.tracker.set_app_id(app_root.metadata.details().title()); TrackedFile folder_to_populate( CreateTrackedFolder(app_root, "folder_to_populate")); folder_to_populate.tracker.set_needs_folder_listing(true); folder_to_populate.tracker.set_dirty(true); TrackedFile known_file(CreateTrackedFile(folder_to_populate, "known_file")); TrackedFile new_file(CreateTrackedFile(folder_to_populate, "new_file")); new_file.should_be_absent = true; const TrackedFile* tracked_files[] = { &sync_root, &app_root, &folder_to_populate, &known_file, &new_file }; SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files)); EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase()); VerifyTrackedFiles(tracked_files, arraysize(tracked_files)); FileIDList listed_children; listed_children.push_back(known_file.metadata.file_id()); listed_children.push_back(new_file.metadata.file_id()); EXPECT_EQ(SYNC_STATUS_OK, PopulateFolder(folder_to_populate.metadata.file_id(), listed_children)); folder_to_populate.tracker.set_dirty(false); folder_to_populate.tracker.set_needs_folder_listing(false); ResetTrackerID(&new_file.tracker); new_file.tracker.set_dirty(true); new_file.tracker.set_active(false); new_file.tracker.clear_synced_details(); new_file.should_be_absent = false; new_file.tracker_only = true; VerifyTrackedFiles(tracked_files, arraysize(tracked_files)); VerifyReloadConsistency(); } TEST_P(MetadataDatabaseTest, PopulateFolderTest_InactiveFolder) { TrackedFile sync_root(CreateTrackedSyncRoot()); TrackedFile app_root(CreateTrackedAppRoot(sync_root, "app_id")); TrackedFile inactive_folder(CreateTrackedFolder(app_root, "inactive_folder")); inactive_folder.tracker.set_active(false); inactive_folder.tracker.set_dirty(true); TrackedFile new_file( CreateTrackedFile(inactive_folder, "file_in_inactive_folder")); new_file.should_be_absent = true; const TrackedFile* tracked_files[] = { &sync_root, &app_root, &inactive_folder, &new_file, }; SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files)); EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase()); VerifyTrackedFiles(tracked_files, arraysize(tracked_files)); FileIDList listed_children; listed_children.push_back(new_file.metadata.file_id()); EXPECT_EQ(SYNC_STATUS_OK, PopulateFolder(inactive_folder.metadata.file_id(), listed_children)); VerifyTrackedFiles(tracked_files, arraysize(tracked_files)); VerifyReloadConsistency(); } TEST_P(MetadataDatabaseTest, PopulateFolderTest_DisabledAppRoot) { TrackedFile sync_root(CreateTrackedSyncRoot()); TrackedFile disabled_app_root( CreateTrackedAppRoot(sync_root, "disabled_app")); disabled_app_root.tracker.set_dirty(true); disabled_app_root.tracker.set_needs_folder_listing(true); TrackedFile known_file(CreateTrackedFile(disabled_app_root, "known_file")); TrackedFile file(CreateTrackedFile(disabled_app_root, "file")); file.should_be_absent = true; const TrackedFile* tracked_files[] = { &sync_root, &disabled_app_root, &disabled_app_root, &known_file, &file, }; SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files)); EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase()); VerifyTrackedFiles(tracked_files, arraysize(tracked_files)); FileIDList disabled_app_children; disabled_app_children.push_back(file.metadata.file_id()); EXPECT_EQ(SYNC_STATUS_OK, PopulateFolder( disabled_app_root.metadata.file_id(), disabled_app_children)); ResetTrackerID(&file.tracker); file.tracker.clear_synced_details(); file.tracker.set_dirty(true); file.tracker.set_active(false); file.should_be_absent = false; file.tracker_only = true; disabled_app_root.tracker.set_dirty(false); disabled_app_root.tracker.set_needs_folder_listing(false); VerifyTrackedFiles(tracked_files, arraysize(tracked_files)); VerifyReloadConsistency(); } // TODO(tzik): Fix expectation and re-enable this test. TEST_P(MetadataDatabaseTest, DISABLED_UpdateTrackerTest) { TrackedFile sync_root(CreateTrackedSyncRoot()); TrackedFile app_root(CreateTrackedAppRoot(sync_root, "app_root")); TrackedFile file(CreateTrackedFile(app_root, "file")); file.tracker.set_dirty(true); file.metadata.mutable_details()->set_title("renamed file"); TrackedFile inactive_file(CreateTrackedFile(app_root, "inactive_file")); inactive_file.tracker.set_active(false); inactive_file.tracker.set_dirty(true); inactive_file.metadata.mutable_details()->set_title("renamed inactive file"); inactive_file.metadata.mutable_details()->set_md5("modified_md5"); TrackedFile new_conflict(CreateTrackedFile(app_root, "new conflict file")); new_conflict.tracker.set_dirty(true); new_conflict.metadata.mutable_details()->set_title("renamed file"); const TrackedFile* tracked_files[] = { &sync_root, &app_root, &file, &inactive_file, &new_conflict }; SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files)); EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase()); VerifyTrackedFiles(tracked_files, arraysize(tracked_files)); VerifyReloadConsistency(); *file.tracker.mutable_synced_details() = file.metadata.details(); file.tracker.set_dirty(false); EXPECT_EQ(SYNC_STATUS_OK, UpdateTracker(file.tracker)); VerifyTrackedFiles(tracked_files, arraysize(tracked_files)); VerifyReloadConsistency(); *inactive_file.tracker.mutable_synced_details() = inactive_file.metadata.details(); inactive_file.tracker.set_dirty(false); inactive_file.tracker.set_active(true); EXPECT_EQ(SYNC_STATUS_OK, UpdateTracker(inactive_file.tracker)); VerifyTrackedFiles(tracked_files, arraysize(tracked_files)); VerifyReloadConsistency(); *new_conflict.tracker.mutable_synced_details() = new_conflict.metadata.details(); new_conflict.tracker.set_dirty(false); new_conflict.tracker.set_active(true); file.tracker.set_dirty(true); file.tracker.set_active(false); EXPECT_EQ(SYNC_STATUS_OK, UpdateTracker(new_conflict.tracker)); VerifyTrackedFiles(tracked_files, arraysize(tracked_files)); VerifyReloadConsistency(); } TEST_P(MetadataDatabaseTest, PopulateInitialDataTest) { TrackedFile sync_root(CreateTrackedSyncRoot()); TrackedFile app_root(CreateTrackedFolder(sync_root, "app_root")); app_root.tracker.set_active(false); const TrackedFile* tracked_files[] = { &sync_root, &app_root }; scoped_ptr<google_apis::FileResource> sync_root_folder( CreateFileResourceFromMetadata(sync_root.metadata)); scoped_ptr<google_apis::FileResource> app_root_folder( CreateFileResourceFromMetadata(app_root.metadata)); ScopedVector<google_apis::FileResource> app_root_folders; app_root_folders.push_back(app_root_folder.release()); EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase()); EXPECT_EQ(SYNC_STATUS_OK, PopulateInitialData( current_change_id(), *sync_root_folder, app_root_folders)); ResetTrackerID(&sync_root.tracker); ResetTrackerID(&app_root.tracker); app_root.tracker.set_parent_tracker_id(sync_root.tracker.tracker_id()); VerifyTrackedFiles(tracked_files, arraysize(tracked_files)); VerifyReloadConsistency(); } TEST_P(MetadataDatabaseTest, DumpFiles) { TrackedFile sync_root(CreateTrackedSyncRoot()); TrackedFile app_root(CreateTrackedAppRoot(sync_root, "app_id")); app_root.tracker.set_app_id(app_root.metadata.details().title()); TrackedFile folder_0(CreateTrackedFolder(app_root, "folder_0")); TrackedFile file_0(CreateTrackedFile(folder_0, "file_0")); const TrackedFile* tracked_files[] = { &sync_root, &app_root, &folder_0, &file_0 }; SetUpDatabaseByTrackedFiles(tracked_files, arraysize(tracked_files)); EXPECT_EQ(SYNC_STATUS_OK, InitializeMetadataDatabase()); VerifyTrackedFiles(tracked_files, arraysize(tracked_files)); scoped_ptr<base::ListValue> files = metadata_database()->DumpFiles(app_root.tracker.app_id()); ASSERT_EQ(2u, files->GetSize()); base::DictionaryValue* file = nullptr; std::string str; ASSERT_TRUE(files->GetDictionary(0, &file)); EXPECT_TRUE(file->GetString("title", &str) && str == "folder_0"); EXPECT_TRUE(file->GetString("type", &str) && str == "folder"); EXPECT_TRUE(file->HasKey("details")); ASSERT_TRUE(files->GetDictionary(1, &file)); EXPECT_TRUE(file->GetString("title", &str) && str == "file_0"); EXPECT_TRUE(file->GetString("type", &str) && str == "file"); EXPECT_TRUE(file->HasKey("details")); } } // namespace drive_backend } // namespace sync_file_system
Jonekee/chromium.src
chrome/browser/sync_file_system/drive_backend/metadata_database_unittest.cc
C++
bsd-3-clause
43,484
// 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 "ui/display/types/display_snapshot.h" namespace ui { DisplaySnapshot::DisplaySnapshot(int64_t display_id, const gfx::Point& origin, const gfx::Size& physical_size, DisplayConnectionType type, bool is_aspect_preserving_scaling, bool has_overscan, std::string display_name, const std::vector<const DisplayMode*>& modes, const DisplayMode* current_mode, const DisplayMode* native_mode) : display_id_(display_id), origin_(origin), physical_size_(physical_size), type_(type), is_aspect_preserving_scaling_(is_aspect_preserving_scaling), has_overscan_(has_overscan), display_name_(display_name), modes_(modes), current_mode_(current_mode), native_mode_(native_mode) {} DisplaySnapshot::~DisplaySnapshot() {} } // namespace ui
Jonekee/chromium.src
ui/display/types/display_snapshot.cc
C++
bsd-3-clause
1,255
""" Helpers for embarrassingly parallel code. """ # Author: Gael Varoquaux < gael dot varoquaux at normalesup dot org > # Copyright: 2010, Gael Varoquaux # License: BSD 3 clause from __future__ import division import os import sys from math import sqrt import functools import time import threading import itertools from numbers import Integral from contextlib import contextmanager import warnings try: import cPickle as pickle except ImportError: import pickle from ._multiprocessing_helpers import mp from .format_stack import format_outer_frames from .logger import Logger, short_format_time from .my_exceptions import TransportableException, _mk_exception from .disk import memstr_to_bytes from ._parallel_backends import (FallbackToBackend, MultiprocessingBackend, ThreadingBackend, SequentialBackend) from ._compat import _basestring # Make sure that those two classes are part of the public joblib.parallel API # so that 3rd party backend implementers can import them from here. from ._parallel_backends import AutoBatchingMixin # noqa from ._parallel_backends import ParallelBackendBase # noqa BACKENDS = { 'multiprocessing': MultiprocessingBackend, 'threading': ThreadingBackend, 'sequential': SequentialBackend, } # name of the backend used by default by Parallel outside of any context # managed by ``parallel_backend``. DEFAULT_BACKEND = 'multiprocessing' DEFAULT_N_JOBS = 1 # Thread local value that can be overridden by the ``parallel_backend`` context # manager _backend = threading.local() def get_active_backend(): """Return the active default backend""" active_backend_and_jobs = getattr(_backend, 'backend_and_jobs', None) if active_backend_and_jobs is not None: return active_backend_and_jobs # We are outside of the scope of any parallel_backend context manager, # create the default backend instance now active_backend = BACKENDS[DEFAULT_BACKEND]() return active_backend, DEFAULT_N_JOBS @contextmanager def parallel_backend(backend, n_jobs=-1, **backend_params): """Change the default backend used by Parallel inside a with block. If ``backend`` is a string it must match a previously registered implementation using the ``register_parallel_backend`` function. Alternatively backend can be passed directly as an instance. By default all available workers will be used (``n_jobs=-1``) unless the caller passes an explicit value for the ``n_jobs`` parameter. This is an alternative to passing a ``backend='backend_name'`` argument to the ``Parallel`` class constructor. It is particularly useful when calling into library code that uses joblib internally but does not expose the backend argument in its own API. >>> from operator import neg >>> with parallel_backend('threading'): ... print(Parallel()(delayed(neg)(i + 1) for i in range(5))) ... [-1, -2, -3, -4, -5] Warning: this function is experimental and subject to change in a future version of joblib. .. versionadded:: 0.10 """ if isinstance(backend, _basestring): backend = BACKENDS[backend](**backend_params) old_backend_and_jobs = getattr(_backend, 'backend_and_jobs', None) try: _backend.backend_and_jobs = (backend, n_jobs) # return the backend instance to make it easier to write tests yield backend, n_jobs finally: if old_backend_and_jobs is None: if getattr(_backend, 'backend_and_jobs', None) is not None: del _backend.backend_and_jobs else: _backend.backend_and_jobs = old_backend_and_jobs # Under Linux or OS X the default start method of multiprocessing # can cause third party libraries to crash. Under Python 3.4+ it is possible # to set an environment variable to switch the default start method from # 'fork' to 'forkserver' or 'spawn' to avoid this issue albeit at the cost # of causing semantic changes and some additional pool instantiation overhead. if hasattr(mp, 'get_context'): method = os.environ.get('JOBLIB_START_METHOD', '').strip() or None DEFAULT_MP_CONTEXT = mp.get_context(method=method) else: DEFAULT_MP_CONTEXT = None class BatchedCalls(object): """Wrap a sequence of (func, args, kwargs) tuples as a single callable""" def __init__(self, iterator_slice): self.items = list(iterator_slice) self._size = len(self.items) def __call__(self): return [func(*args, **kwargs) for func, args, kwargs in self.items] def __len__(self): return self._size ############################################################################### # CPU count that works also when multiprocessing has been disabled via # the JOBLIB_MULTIPROCESSING environment variable def cpu_count(): """Return the number of CPUs.""" if mp is None: return 1 return mp.cpu_count() ############################################################################### # For verbosity def _verbosity_filter(index, verbose): """ Returns False for indices increasingly apart, the distance depending on the value of verbose. We use a lag increasing as the square of index """ if not verbose: return True elif verbose > 10: return False if index == 0: return False verbose = .5 * (11 - verbose) ** 2 scale = sqrt(index / verbose) next_scale = sqrt((index + 1) / verbose) return (int(next_scale) == int(scale)) ############################################################################### def delayed(function, check_pickle=True): """Decorator used to capture the arguments of a function. Pass `check_pickle=False` when: - performing a possibly repeated check is too costly and has been done already once outside of the call to delayed. - when used in conjunction `Parallel(backend='threading')`. """ # Try to pickle the input function, to catch the problems early when # using with multiprocessing: if check_pickle: pickle.dumps(function) def delayed_function(*args, **kwargs): return function, args, kwargs try: delayed_function = functools.wraps(function)(delayed_function) except AttributeError: " functools.wraps fails on some callable objects " return delayed_function ############################################################################### class BatchCompletionCallBack(object): """Callback used by joblib.Parallel's multiprocessing backend. This callable is executed by the parent process whenever a worker process has returned the results of a batch of tasks. It is used for progress reporting, to update estimate of the batch processing duration and to schedule the next batch of tasks to be processed. """ def __init__(self, dispatch_timestamp, batch_size, parallel): self.dispatch_timestamp = dispatch_timestamp self.batch_size = batch_size self.parallel = parallel def __call__(self, out): self.parallel.n_completed_tasks += self.batch_size this_batch_duration = time.time() - self.dispatch_timestamp self.parallel._backend.batch_completed(self.batch_size, this_batch_duration) self.parallel.print_progress() if self.parallel._original_iterator is not None: self.parallel.dispatch_next() ############################################################################### def register_parallel_backend(name, factory, make_default=False): """Register a new Parallel backend factory. The new backend can then be selected by passing its name as the backend argument to the Parallel class. Moreover, the default backend can be overwritten globally by setting make_default=True. The factory can be any callable that takes no argument and return an instance of ``ParallelBackendBase``. Warning: this function is experimental and subject to change in a future version of joblib. .. versionadded:: 0.10 """ BACKENDS[name] = factory if make_default: global DEFAULT_BACKEND DEFAULT_BACKEND = name def effective_n_jobs(n_jobs=-1): """Determine the number of jobs that can actually run in parallel n_jobs is the number of workers requested by the callers. Passing n_jobs=-1 means requesting all available workers for instance matching the number of CPU cores on the worker host(s). This method should return a guesstimate of the number of workers that can actually perform work concurrently with the currently enabled default backend. The primary use case is to make it possible for the caller to know in how many chunks to slice the work. In general working on larger data chunks is more efficient (less scheduling overhead and better use of CPU cache prefetching heuristics) as long as all the workers have enough work to do. Warning: this function is experimental and subject to change in a future version of joblib. .. versionadded:: 0.10 """ backend, _ = get_active_backend() return backend.effective_n_jobs(n_jobs=n_jobs) ############################################################################### class Parallel(Logger): ''' Helper class for readable parallel mapping. Parameters ----------- n_jobs: int, default: 1 The maximum number of concurrently running jobs, such as the number of Python worker processes when backend="multiprocessing" or the size of the thread-pool when backend="threading". If -1 all CPUs are used. If 1 is given, no parallel computing code is used at all, which is useful for debugging. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used. backend: str, ParallelBackendBase instance or None, \ default: 'multiprocessing' Specify the parallelization backend implementation. Supported backends are: - "multiprocessing" used by default, can induce some communication and memory overhead when exchanging input and output data with the worker Python processes. - "threading" is a very low-overhead backend but it suffers from the Python Global Interpreter Lock if the called function relies a lot on Python objects. "threading" is mostly useful when the execution bottleneck is a compiled extension that explicitly releases the GIL (for instance a Cython loop wrapped in a "with nogil" block or an expensive call to a library such as NumPy). - finally, you can register backends by calling register_parallel_backend. This will allow you to implement a backend of your liking. verbose: int, optional The verbosity level: if non zero, progress messages are printed. Above 50, the output is sent to stdout. The frequency of the messages increases with the verbosity level. If it more than 10, all iterations are reported. timeout: float, optional Timeout limit for each task to complete. If any task takes longer a TimeOutError will be raised. Only applied when n_jobs != 1 pre_dispatch: {'all', integer, or expression, as in '3*n_jobs'} The number of batches (of tasks) to be pre-dispatched. Default is '2*n_jobs'. When batch_size="auto" this is reasonable default and the multiprocessing workers should never starve. batch_size: int or 'auto', default: 'auto' The number of atomic tasks to dispatch at once to each worker. When individual evaluations are very fast, multiprocessing can be slower than sequential computation because of the overhead. Batching fast computations together can mitigate this. The ``'auto'`` strategy keeps track of the time it takes for a batch to complete, and dynamically adjusts the batch size to keep the time on the order of half a second, using a heuristic. The initial batch size is 1. ``batch_size="auto"`` with ``backend="threading"`` will dispatch batches of a single task at a time as the threading backend has very little overhead and using larger batch size has not proved to bring any gain in that case. temp_folder: str, optional Folder to be used by the pool for memmaping large arrays for sharing memory with worker processes. If None, this will try in order: - a folder pointed by the JOBLIB_TEMP_FOLDER environment variable, - /dev/shm if the folder exists and is writable: this is a RAMdisk filesystem available by default on modern Linux distributions, - the default system temporary folder that can be overridden with TMP, TMPDIR or TEMP environment variables, typically /tmp under Unix operating systems. Only active when backend="multiprocessing". max_nbytes int, str, or None, optional, 1M by default Threshold on the size of arrays passed to the workers that triggers automated memory mapping in temp_folder. Can be an int in Bytes, or a human-readable string, e.g., '1M' for 1 megabyte. Use None to disable memmaping of large arrays. Only active when backend="multiprocessing". mmap_mode: {None, 'r+', 'r', 'w+', 'c'} Memmapping mode for numpy arrays passed to workers. See 'max_nbytes' parameter documentation for more details. Notes ----- This object uses the multiprocessing module to compute in parallel the application of a function to many different arguments. The main functionality it brings in addition to using the raw multiprocessing API are (see examples for details): * More readable code, in particular since it avoids constructing list of arguments. * Easier debugging: - informative tracebacks even when the error happens on the client side - using 'n_jobs=1' enables to turn off parallel computing for debugging without changing the codepath - early capture of pickling errors * An optional progress meter. * Interruption of multiprocesses jobs with 'Ctrl-C' * Flexible pickling control for the communication to and from the worker processes. * Ability to use shared memory efficiently with worker processes for large numpy-based datastructures. Examples -------- A simple example: >>> from math import sqrt >>> from sklearn.externals.joblib import Parallel, delayed >>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10)) [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] Reshaping the output when the function has several return values: >>> from math import modf >>> from sklearn.externals.joblib import Parallel, delayed >>> r = Parallel(n_jobs=1)(delayed(modf)(i/2.) for i in range(10)) >>> res, i = zip(*r) >>> res (0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5) >>> i (0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0) The progress meter: the higher the value of `verbose`, the more messages: >>> from time import sleep >>> from sklearn.externals.joblib import Parallel, delayed >>> r = Parallel(n_jobs=2, verbose=5)(delayed(sleep)(.1) for _ in range(10)) #doctest: +SKIP [Parallel(n_jobs=2)]: Done 1 out of 10 | elapsed: 0.1s remaining: 0.9s [Parallel(n_jobs=2)]: Done 3 out of 10 | elapsed: 0.2s remaining: 0.5s [Parallel(n_jobs=2)]: Done 6 out of 10 | elapsed: 0.3s remaining: 0.2s [Parallel(n_jobs=2)]: Done 9 out of 10 | elapsed: 0.5s remaining: 0.1s [Parallel(n_jobs=2)]: Done 10 out of 10 | elapsed: 0.5s finished Traceback example, note how the line of the error is indicated as well as the values of the parameter passed to the function that triggered the exception, even though the traceback happens in the child process: >>> from heapq import nlargest >>> from sklearn.externals.joblib import Parallel, delayed >>> Parallel(n_jobs=2)(delayed(nlargest)(2, n) for n in (range(4), 'abcde', 3)) #doctest: +SKIP #... --------------------------------------------------------------------------- Sub-process traceback: --------------------------------------------------------------------------- TypeError Mon Nov 12 11:37:46 2012 PID: 12934 Python 2.7.3: /usr/bin/python ........................................................................... /usr/lib/python2.7/heapq.pyc in nlargest(n=2, iterable=3, key=None) 419 if n >= size: 420 return sorted(iterable, key=key, reverse=True)[:n] 421 422 # When key is none, use simpler decoration 423 if key is None: --> 424 it = izip(iterable, count(0,-1)) # decorate 425 result = _nlargest(n, it) 426 return map(itemgetter(0), result) # undecorate 427 428 # General case, slowest method TypeError: izip argument #1 must support iteration ___________________________________________________________________________ Using pre_dispatch in a producer/consumer situation, where the data is generated on the fly. Note how the producer is first called 3 times before the parallel loop is initiated, and then called to generate new data on the fly. In this case the total number of iterations cannot be reported in the progress messages: >>> from math import sqrt >>> from sklearn.externals.joblib import Parallel, delayed >>> def producer(): ... for i in range(6): ... print('Produced %s' % i) ... yield i >>> out = Parallel(n_jobs=2, verbose=100, pre_dispatch='1.5*n_jobs')( ... delayed(sqrt)(i) for i in producer()) #doctest: +SKIP Produced 0 Produced 1 Produced 2 [Parallel(n_jobs=2)]: Done 1 jobs | elapsed: 0.0s Produced 3 [Parallel(n_jobs=2)]: Done 2 jobs | elapsed: 0.0s Produced 4 [Parallel(n_jobs=2)]: Done 3 jobs | elapsed: 0.0s Produced 5 [Parallel(n_jobs=2)]: Done 4 jobs | elapsed: 0.0s [Parallel(n_jobs=2)]: Done 5 out of 6 | elapsed: 0.0s remaining: 0.0s [Parallel(n_jobs=2)]: Done 6 out of 6 | elapsed: 0.0s finished ''' def __init__(self, n_jobs=1, backend=None, verbose=0, timeout=None, pre_dispatch='2 * n_jobs', batch_size='auto', temp_folder=None, max_nbytes='1M', mmap_mode='r'): active_backend, default_n_jobs = get_active_backend() if backend is None and n_jobs == 1: # If we are under a parallel_backend context manager, look up # the default number of jobs and use that instead: n_jobs = default_n_jobs self.n_jobs = n_jobs self.verbose = verbose self.timeout = timeout self.pre_dispatch = pre_dispatch if isinstance(max_nbytes, _basestring): max_nbytes = memstr_to_bytes(max_nbytes) self._backend_args = dict( max_nbytes=max_nbytes, mmap_mode=mmap_mode, temp_folder=temp_folder, verbose=max(0, self.verbose - 50), ) if DEFAULT_MP_CONTEXT is not None: self._backend_args['context'] = DEFAULT_MP_CONTEXT if backend is None: backend = active_backend elif isinstance(backend, ParallelBackendBase): # Use provided backend as is pass elif hasattr(backend, 'Pool') and hasattr(backend, 'Lock'): # Make it possible to pass a custom multiprocessing context as # backend to change the start method to forkserver or spawn or # preload modules on the forkserver helper process. self._backend_args['context'] = backend backend = MultiprocessingBackend() else: try: backend_factory = BACKENDS[backend] except KeyError: raise ValueError("Invalid backend: %s, expected one of %r" % (backend, sorted(BACKENDS.keys()))) backend = backend_factory() if (batch_size == 'auto' or isinstance(batch_size, Integral) and batch_size > 0): self.batch_size = batch_size else: raise ValueError( "batch_size must be 'auto' or a positive integer, got: %r" % batch_size) self._backend = backend self._output = None self._jobs = list() self._managed_backend = False # This lock is used coordinate the main thread of this process with # the async callback thread of our the pool. self._lock = threading.Lock() def __enter__(self): self._managed_backend = True self._initialize_backend() return self def __exit__(self, exc_type, exc_value, traceback): self._terminate_backend() self._managed_backend = False def _initialize_backend(self): """Build a process or thread pool and return the number of workers""" try: n_jobs = self._backend.configure(n_jobs=self.n_jobs, parallel=self, **self._backend_args) if self.timeout is not None and not self._backend.supports_timeout: warnings.warn( 'The backend class {!r} does not support timeout. ' "You have set 'timeout={}' in Parallel but " "the 'timeout' parameter will not be used.".format( self._backend.__class__.__name__, self.timeout)) except FallbackToBackend as e: # Recursively initialize the backend in case of requested fallback. self._backend = e.backend n_jobs = self._initialize_backend() return n_jobs def _effective_n_jobs(self): if self._backend: return self._backend.effective_n_jobs(self.n_jobs) return 1 def _terminate_backend(self): if self._backend is not None: self._backend.terminate() def _dispatch(self, batch): """Queue the batch for computing, with or without multiprocessing WARNING: this method is not thread-safe: it should be only called indirectly via dispatch_one_batch. """ # If job.get() catches an exception, it closes the queue: if self._aborting: return self.n_dispatched_tasks += len(batch) self.n_dispatched_batches += 1 dispatch_timestamp = time.time() cb = BatchCompletionCallBack(dispatch_timestamp, len(batch), self) job = self._backend.apply_async(batch, callback=cb) self._jobs.append(job) def dispatch_next(self): """Dispatch more data for parallel processing This method is meant to be called concurrently by the multiprocessing callback. We rely on the thread-safety of dispatch_one_batch to protect against concurrent consumption of the unprotected iterator. """ if not self.dispatch_one_batch(self._original_iterator): self._iterating = False self._original_iterator = None def dispatch_one_batch(self, iterator): """Prefetch the tasks for the next batch and dispatch them. The effective size of the batch is computed here. If there are no more jobs to dispatch, return False, else return True. The iterator consumption and dispatching is protected by the same lock so calling this function should be thread safe. """ if self.batch_size == 'auto': batch_size = self._backend.compute_batch_size() else: # Fixed batch size strategy batch_size = self.batch_size with self._lock: tasks = BatchedCalls(itertools.islice(iterator, batch_size)) if len(tasks) == 0: # No more tasks available in the iterator: tell caller to stop. return False else: self._dispatch(tasks) return True def _print(self, msg, msg_args): """Display the message on stout or stderr depending on verbosity""" # XXX: Not using the logger framework: need to # learn to use logger better. if not self.verbose: return if self.verbose < 50: writer = sys.stderr.write else: writer = sys.stdout.write msg = msg % msg_args writer('[%s]: %s\n' % (self, msg)) def print_progress(self): """Display the process of the parallel execution only a fraction of time, controlled by self.verbose. """ if not self.verbose: return elapsed_time = time.time() - self._start_time # Original job iterator becomes None once it has been fully # consumed : at this point we know the total number of jobs and we are # able to display an estimation of the remaining time based on already # completed jobs. Otherwise, we simply display the number of completed # tasks. if self._original_iterator is not None: if _verbosity_filter(self.n_dispatched_batches, self.verbose): return self._print('Done %3i tasks | elapsed: %s', (self.n_completed_tasks, short_format_time(elapsed_time), )) else: index = self.n_completed_tasks # We are finished dispatching total_tasks = self.n_dispatched_tasks # We always display the first loop if not index == 0: # Display depending on the number of remaining items # A message as soon as we finish dispatching, cursor is 0 cursor = (total_tasks - index + 1 - self._pre_dispatch_amount) frequency = (total_tasks // self.verbose) + 1 is_last_item = (index + 1 == total_tasks) if (is_last_item or cursor % frequency): return remaining_time = (elapsed_time / index) * \ (self.n_dispatched_tasks - index * 1.0) # only display status if remaining time is greater or equal to 0 self._print('Done %3i out of %3i | elapsed: %s remaining: %s', (index, total_tasks, short_format_time(elapsed_time), short_format_time(remaining_time), )) def retrieve(self): self._output = list() while self._iterating or len(self._jobs) > 0: if len(self._jobs) == 0: # Wait for an async callback to dispatch new jobs time.sleep(0.01) continue # We need to be careful: the job list can be filling up as # we empty it and Python list are not thread-safe by default hence # the use of the lock with self._lock: job = self._jobs.pop(0) try: if getattr(self._backend, 'supports_timeout', False): self._output.extend(job.get(timeout=self.timeout)) else: self._output.extend(job.get()) except BaseException as exception: # Note: we catch any BaseException instead of just Exception # instances to also include KeyboardInterrupt. # Stop dispatching any new job in the async callback thread self._aborting = True # If the backend allows it, cancel or kill remaining running # tasks without waiting for the results as we will raise # the exception we got back to the caller instead of returning # any result. backend = self._backend if (backend is not None and hasattr(backend, 'abort_everything')): # If the backend is managed externally we need to make sure # to leave it in a working state to allow for future jobs # scheduling. ensure_ready = self._managed_backend backend.abort_everything(ensure_ready=ensure_ready) if not isinstance(exception, TransportableException): raise else: # Capture exception to add information on the local # stack in addition to the distant stack this_report = format_outer_frames(context=10, stack_start=1) report = """Multiprocessing exception: %s --------------------------------------------------------------------------- Sub-process traceback: --------------------------------------------------------------------------- %s""" % (this_report, exception.message) # Convert this to a JoblibException exception_type = _mk_exception(exception.etype)[0] exception = exception_type(report) raise exception def __call__(self, iterable): if self._jobs: raise ValueError('This Parallel instance is already running') # A flag used to abort the dispatching of jobs in case an # exception is found self._aborting = False if not self._managed_backend: n_jobs = self._initialize_backend() else: n_jobs = self._effective_n_jobs() iterator = iter(iterable) pre_dispatch = self.pre_dispatch if pre_dispatch == 'all' or n_jobs == 1: # prevent further dispatch via multiprocessing callback thread self._original_iterator = None self._pre_dispatch_amount = 0 else: self._original_iterator = iterator if hasattr(pre_dispatch, 'endswith'): pre_dispatch = eval(pre_dispatch) self._pre_dispatch_amount = pre_dispatch = int(pre_dispatch) # The main thread will consume the first pre_dispatch items and # the remaining items will later be lazily dispatched by async # callbacks upon task completions. iterator = itertools.islice(iterator, pre_dispatch) self._start_time = time.time() self.n_dispatched_batches = 0 self.n_dispatched_tasks = 0 self.n_completed_tasks = 0 try: # Only set self._iterating to True if at least a batch # was dispatched. In particular this covers the edge # case of Parallel used with an exhausted iterator. while self.dispatch_one_batch(iterator): self._iterating = True else: self._iterating = False if pre_dispatch == "all" or n_jobs == 1: # The iterable was consumed all at once by the above for loop. # No need to wait for async callbacks to trigger to # consumption. self._iterating = False self.retrieve() # Make sure that we get a last message telling us we are done elapsed_time = time.time() - self._start_time self._print('Done %3i out of %3i | elapsed: %s finished', (len(self._output), len(self._output), short_format_time(elapsed_time))) finally: if not self._managed_backend: self._terminate_backend() self._jobs = list() output = self._output self._output = None return output def __repr__(self): return '%s(n_jobs=%s)' % (self.__class__.__name__, self.n_jobs)
herilalaina/scikit-learn
sklearn/externals/joblib/parallel.py
Python
bsd-3-clause
33,164
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2016 Red Hat, Inc. # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ovirt_job short_description: Module to manage jobs in oVirt/RHV version_added: "2.9" author: "Martin Necas (@mnecas)" description: - "This module manage jobs in oVirt/RHV. It can also manage steps of the job." options: description: description: - "Description of the job." required: true state: description: - "Should the job be C(present)/C(absent)/C(failed)." - "C(started) is alias for C(present). C(finished) is alias for C(absent). Same in the steps." - "Note when C(finished)/C(failed) it will finish/fail all steps." choices: ['present', 'absent', 'started', 'finished', 'failed'] default: present steps: description: - "The steps of the job." suboptions: description: description: - "Description of the step." required: true state: description: - "Should the step be present/absent/failed." - "Note when one step fail whole job will fail" - "Note when all steps are finished it will finish job." choices: ['present', 'absent', 'started', 'finished', 'failed'] default: present type: list extends_documentation_fragment: ovirt ''' EXAMPLES = ''' # Examples don't contain auth parameter for simplicity, # look at ovirt_auth module to see how to reuse authentication: - name: Create job with two steps ovirt_job: description: job_name steps: - description: step_name_A - description: step_name_B - name: Finish one step ovirt_job: description: job_name steps: - description: step_name_A state: finished - name: When you fail one step whole job will stop ovirt_job: description: job_name steps: - description: step_name_B state: failed - name: Finish all steps ovirt_job: description: job_name state: finished ''' RETURN = ''' id: description: ID of the job which is managed returned: On success if job is found. type: str sample: 7de90f31-222c-436c-a1ca-7e655bd5b60c job: description: "Dictionary of all the job attributes. Job attributes can be found on your oVirt/RHV instance at following url: http://ovirt.github.io/ovirt-engine-api-model/master/#types/job." returned: On success if job is found. type: dict ''' import traceback try: import ovirtsdk4.types as otypes except ImportError: pass from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ovirt import ( check_sdk, create_connection, equal, get_id_by_name, ovirt_full_argument_spec, get_dict_of_struct, ) def build_job(description): return otypes.Job( description=description, status=otypes.JobStatus.STARTED, external=True, auto_cleared=True ) def build_step(description, job_id): return otypes.Step( description=description, type=otypes.StepEnum.UNKNOWN, job=otypes.Job( id=job_id ), status=otypes.StepStatus.STARTED, external=True, ) def attach_steps(module, job_id, jobs_service): changed = False steps_service = jobs_service.job_service(job_id).steps_service() if module.params.get('steps'): for step in module.params.get('steps'): step_entity = get_entity(steps_service, step.get('description')) step_state = step.get('state', 'present') if step_state in ['present', 'started']: if step_entity is None: steps_service.add(build_step(step.get('description'), job_id)) changed = True if step_entity is not None and step_entity.status not in [otypes.StepStatus.FINISHED, otypes.StepStatus.FAILED]: if step_state in ['absent', 'finished']: steps_service.step_service(step_entity.id).end(succeeded=True) changed = True elif step_state == 'failed': steps_service.step_service(step_entity.id).end(succeeded=False) changed = True return changed def get_entity(service, description): all_entities = service.list() for entity in all_entities: if entity.description == description and entity.status not in [otypes.StepStatus.FINISHED, otypes.JobStatus.FINISHED]: return entity def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent', 'started', 'finished', 'failed'], default='present', ), description=dict(default=None), steps=dict(default=None, type='list'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=False, ) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) jobs_service = connection.system_service().jobs_service() state = module.params['state'] job = get_entity(jobs_service, module.params['description']) changed = False if state in ['present', 'started']: if job is None: job = jobs_service.add(build_job(module.params['description'])) changed = True changed = attach_steps(module, job.id, jobs_service) or changed if job is not None and job.status not in [otypes.JobStatus.FINISHED, otypes.JobStatus.FAILED]: if state in ['absent', 'finished']: jobs_service.job_service(job.id).end(succeeded=True) changed = True elif state == 'failed': jobs_service.job_service(job.id).end(succeeded=False) changed = True ret = { 'changed': changed, 'id': getattr(job, 'id', None), 'job': get_dict_of_struct( struct=job, connection=connection, fetch_nested=True, attributes=module.params.get('nested_attributes'), ), } module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None) if __name__ == "__main__": main()
thaim/ansible
lib/ansible/modules/cloud/ovirt/ovirt_job.py
Python
mit
7,379
/* * 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. */ /* * * (C) Copyright IBM Corp. 1999 All Rights Reserved. * Copyright 1997 The Open Group Research Institute. All rights reserved. */ package sun.security.krb5.internal; import java.util.TimeZone; import sun.security.util.*; import sun.security.krb5.Config; import sun.security.krb5.KrbException; import sun.security.krb5.Asn1Exception; import java.util.Date; import java.util.GregorianCalendar; import java.util.Calendar; import java.io.IOException; /** * Implements the ASN.1 KerberosTime type. * * <xmp> * KerberosTime ::= GeneralizedTime -- with no fractional seconds * </xmp> * * The timestamps used in Kerberos are encoded as GeneralizedTimes. A * KerberosTime value shall not include any fractional portions of the * seconds. As required by the DER, it further shall not include any * separators, and it shall specify the UTC time zone (Z). * * <p> * This definition reflects the Network Working Group RFC 4120 * specification available at * <a href="http://www.ietf.org/rfc/rfc4120.txt"> * http://www.ietf.org/rfc/rfc4120.txt</a>. * * The implementation also includes the microseconds info so that the * same class can be used as a precise timestamp in Authenticator etc. */ public class KerberosTime implements Cloneable { private long kerberosTime; // milliseconds since epoch, a Date.getTime() value private int microSeconds; // the last three digits of the microsecond value // The time when this class is loaded. Used in setNow() private static final long initMilli = System.currentTimeMillis(); private static final long initMicro = System.nanoTime() / 1000; private static long syncTime; private static boolean DEBUG = Krb5.DEBUG; public static final boolean NOW = true; public static final boolean UNADJUSTED_NOW = false; public KerberosTime(long time) { kerberosTime = time; } private KerberosTime(long time, int micro) { kerberosTime = time; microSeconds = micro; } public Object clone() { return new KerberosTime(kerberosTime, microSeconds); } // This constructor is used in the native code // src/windows/native/sun/security/krb5/NativeCreds.c public KerberosTime(String time) throws Asn1Exception { kerberosTime = toKerberosTime(time); } /** * Constructs a KerberosTime object. * @param encoding a DER-encoded data. * @exception Asn1Exception if an error occurs while decoding an ASN1 encoded data. * @exception IOException if an I/O error occurs while reading encoded data. */ public KerberosTime(DerValue encoding) throws Asn1Exception, IOException { GregorianCalendar calendar = new GregorianCalendar(); Date temp = encoding.getGeneralizedTime(); kerberosTime = temp.getTime(); } private static long toKerberosTime(String time) throws Asn1Exception { // this method only used by KerberosTime class. // ASN.1 GeneralizedTime format: // "19700101000000Z" // | | | | | | | // 0 4 6 8 | | | // 10 | | // 12 | // 14 if (time.length() != 15) throw new Asn1Exception(Krb5.ASN1_BAD_TIMEFORMAT); if (time.charAt(14) != 'Z') throw new Asn1Exception(Krb5.ASN1_BAD_TIMEFORMAT); int year = Integer.parseInt(time.substring(0, 4)); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.clear(); // so that millisecond is zero calendar.set(year, Integer.parseInt(time.substring(4, 6)) - 1, Integer.parseInt(time.substring(6, 8)), Integer.parseInt(time.substring(8, 10)), Integer.parseInt(time.substring(10, 12)), Integer.parseInt(time.substring(12, 14))); //The Date constructor assumes the setting are local relative //and converts the time to UTC before storing it. Since we //want the internal representation to correspond to local //and not UTC time we subtract the UTC time offset. return (calendar.getTime().getTime()); } // should be moved to sun.security.krb5.util class public static String zeroPad(String s, int length) { StringBuffer temp = new StringBuffer(s); while (temp.length() < length) temp.insert(0, '0'); return temp.toString(); } public KerberosTime(Date time) { kerberosTime = time.getTime(); // (time.getTimezoneOffset() * 60000L); } public KerberosTime(boolean initToNow) { if (initToNow) { setNow(); } } /** * Returns a string representation of KerberosTime object. * @return a string representation of this object. */ public String toGeneralizedTimeString() { Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.clear(); calendar.setTimeInMillis(kerberosTime); return zeroPad(Integer.toString(calendar.get(Calendar.YEAR)), 4) + zeroPad(Integer.toString(calendar.get(Calendar.MONTH) + 1), 2) + zeroPad(Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)), 2) + zeroPad(Integer.toString(calendar.get(Calendar.HOUR_OF_DAY)), 2) + zeroPad(Integer.toString(calendar.get(Calendar.MINUTE)), 2) + zeroPad(Integer.toString(calendar.get(Calendar.SECOND)), 2) + 'Z'; } /** * Encodes this object to a byte array. * @return a byte array of encoded data. * @exception Asn1Exception if an error occurs while decoding an ASN1 encoded data. * @exception IOException if an I/O error occurs while reading encoded data. */ public byte[] asn1Encode() throws Asn1Exception, IOException { DerOutputStream out = new DerOutputStream(); out.putGeneralizedTime(this.toDate()); return out.toByteArray(); } public long getTime() { return kerberosTime; } public void setTime(Date time) { kerberosTime = time.getTime(); // (time.getTimezoneOffset() * 60000L); microSeconds = 0; } public void setTime(long time) { kerberosTime = time; microSeconds = 0; } public Date toDate() { Date temp = new Date(kerberosTime); temp.setTime(temp.getTime()); return temp; } public void setNow() { long microElapsed = System.nanoTime() / 1000 - initMicro; setTime(initMilli + microElapsed/1000); microSeconds = (int)(microElapsed % 1000); } public int getMicroSeconds() { Long temp_long = new Long((kerberosTime % 1000L) * 1000L); return temp_long.intValue() + microSeconds; } public void setMicroSeconds(int usec) { microSeconds = usec % 1000; Integer temp_int = new Integer(usec); long temp_long = temp_int.longValue() / 1000L; kerberosTime = kerberosTime - (kerberosTime % 1000L) + temp_long; } public void setMicroSeconds(Integer usec) { if (usec != null) { microSeconds = usec.intValue() % 1000; long temp_long = usec.longValue() / 1000L; kerberosTime = kerberosTime - (kerberosTime % 1000L) + temp_long; } } public boolean inClockSkew(int clockSkew) { KerberosTime now = new KerberosTime(KerberosTime.NOW); if (java.lang.Math.abs(kerberosTime - now.kerberosTime) > clockSkew * 1000L) return false; return true; } public boolean inClockSkew() { return inClockSkew(getDefaultSkew()); } public boolean inClockSkew(int clockSkew, KerberosTime now) { if (java.lang.Math.abs(kerberosTime - now.kerberosTime) > clockSkew * 1000L) return false; return true; } public boolean inClockSkew(KerberosTime time) { return inClockSkew(getDefaultSkew(), time); } public boolean greaterThanWRTClockSkew(KerberosTime time, int clockSkew) { if ((kerberosTime - time.kerberosTime) > clockSkew * 1000L) return true; return false; } public boolean greaterThanWRTClockSkew(KerberosTime time) { return greaterThanWRTClockSkew(time, getDefaultSkew()); } public boolean greaterThan(KerberosTime time) { return kerberosTime > time.kerberosTime || kerberosTime == time.kerberosTime && microSeconds > time.microSeconds; } public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof KerberosTime)) { return false; } return kerberosTime == ((KerberosTime)obj).kerberosTime && microSeconds == ((KerberosTime)obj).microSeconds; } public int hashCode() { int result = 37 * 17 + (int)(kerberosTime ^ (kerberosTime >>> 32)); return result * 17 + microSeconds; } public boolean isZero() { return kerberosTime == 0 && microSeconds == 0; } public int getSeconds() { Long temp_long = new Long(kerberosTime / 1000L); return temp_long.intValue(); } public void setSeconds(int sec) { Integer temp_int = new Integer(sec); kerberosTime = temp_int.longValue() * 1000L; } /** * Parse (unmarshal) a kerberostime from a DER input stream. This form * parsing might be used when expanding a value which is part of * a constructed sequence and uses explicitly tagged type. * * @exception Asn1Exception on error. * @param data the Der input stream value, which contains one or more marshaled value. * @param explicitTag tag number. * @param optional indicates if this data field is optional * @return an instance of KerberosTime. * */ public static KerberosTime parse(DerInputStream data, byte explicitTag, boolean optional) throws Asn1Exception, IOException { if ((optional) && (((byte)data.peekByte() & (byte)0x1F)!= explicitTag)) return null; DerValue der = data.getDerValue(); if (explicitTag != (der.getTag() & (byte)0x1F)) { throw new Asn1Exception(Krb5.ASN1_BAD_ID); } else { DerValue subDer = der.getData().getDerValue(); return new KerberosTime(subDer); } } public static int getDefaultSkew() { int tdiff = Krb5.DEFAULT_ALLOWABLE_CLOCKSKEW; try { Config c = Config.getInstance(); if ((tdiff = c.getDefaultIntValue("clockskew", "libdefaults")) == Integer.MIN_VALUE) { //value is not defined tdiff = Krb5.DEFAULT_ALLOWABLE_CLOCKSKEW; } } catch (KrbException e) { if (DEBUG) { System.out.println("Exception in getting clockskew from " + "Configuration " + "using default value " + e.getMessage()); } } return tdiff; } public String toString() { return toGeneralizedTimeString(); } }
rokn/Count_Words_2015
testing/openjdk/jdk/src/share/classes/sun/security/krb5/internal/KerberosTime.java
Java
mit
12,458
/*jslint node:true, vars:true, bitwise:true, unparam:true */ /*jshint unused:true */ /*global */ /* * Author: Zion Orent <zorent@ics.com> * Copyright (c) 2014 Intel Corporation. * * 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. */ //Load Grove Moisture module var grove_moisture = require('jsupm_grovemoisture'); // Instantiate a Grove Moisture sensor on analog pin A0 var myMoistureObj = new grove_moisture.GroveMoisture(0); // Values (approximate): // 0-300, sensor in air or dry soil // 300-600, sensor in humid soil // 600+, sensor in wet soil or submerged in water // Read the value every second and print the corresponding moisture level setInterval(function() { var result; var moisture_val = parseInt(myMoistureObj.value()); if (moisture_val >= 0 && moisture_val < 300) result = "Dry"; else if (moisture_val >= 300 && moisture_val < 600) result = "Moist"; else result = "Wet"; console.log("Moisture value: " + moisture_val + ", " + result); }, 1000); // Print message when exiting process.on('SIGINT', function() { console.log("Exiting..."); process.exit(0); });
yoyojacky/upm
examples/javascript/grovemoisture.js
JavaScript
mit
2,103
# flake8: NOQA # "flake8: NOQA" to suppress warning "H104 File contains nothing but comments" # TODO(okuta): Implement packbits # TODO(okuta): Implement unpackbits
tigerneil/chainer
cupy/binary/packing.py
Python
mit
168
// 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. // The native type of Vector3 is struct {float x,y,z} whose size is 12 bytes. RyuJit uses 16-byte // register or stack location to store a Vector3 variable with the assumptions below. New testcases // are added to check whether: // // - RyuJit correctly generates code and memory layout that matches the native side. // // - RyuJIt back-end assumptions about Vector3 types are satisfied. // // - Assumption1: Vector3 type args passed in registers or on stack is rounded to POINTER_SIZE // and hence on 64-bit targets it can be read/written as if it were TYP_SIMD16. // // - Assumption2: Vector3 args passed in registers (e.g. unix) or on stack have their upper // 4-bytes being zero. Similarly Vector3 return type value returned from a method will have // its upper 4-bytes zeroed out using System; using System.Diagnostics; using System.Numerics; using System.Runtime.InteropServices; using System.Text; public struct DT { public Vector3 a; public Vector3 b; }; [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ComplexDT { public int iv; public DT vecs; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)] public string str; public Vector3 v3; }; class PInvokeTest { [DllImport(@"Vector3TestNative", CallingConvention = CallingConvention.StdCall)] public static extern int nativeCall_PInvoke_CheckVector3Size(); [DllImport(@"Vector3TestNative", CallingConvention = CallingConvention.StdCall)] public static extern float nativeCall_PInvoke_Vector3Arg( int i, Vector3 v1, [MarshalAs(UnmanagedType.LPStr)] string s, Vector3 v2); [DllImport(@"Vector3TestNative", CallingConvention = CallingConvention.StdCall)] public static extern float nativeCall_PInvoke_Vector3Arg_Unix( Vector3 v3f32_xmm0, float f32_xmm2, float f32_xmm3, float f32_xmm4, float f32_xmm5, float f32_xmm6, float f32_xmm7, float f32_mem0, Vector3 v3f32_mem1, float f32_mem2, float f32_mem3); [DllImport(@"Vector3TestNative", CallingConvention = CallingConvention.StdCall)] public static extern float nativeCall_PInvoke_Vector3Arg_Unix2( Vector3 v3f32_xmm0, float f32_xmm2, float f32_xmm3, float f32_xmm4, float f32_xmm5, float f32_xmm6, float f32_xmm7, float f32_mem0, Vector3 v3f32_mem1, float f32_mem2, float f32_mem3, Vector3 v3f32_mem4, float f32_mem5); [DllImport(@"Vector3TestNative", CallingConvention = CallingConvention.StdCall)] public static extern Vector3 nativeCall_PInvoke_Vector3Ret(); [DllImport(@"Vector3TestNative", CallingConvention = CallingConvention.StdCall)] public static extern float nativeCall_PInvoke_Vector3Array(Vector3[] v_array); [DllImport(@"Vector3TestNative", CallingConvention = CallingConvention.StdCall)] public static extern DT nativeCall_PInvoke_Vector3InStruct(DT d); [DllImport(@"Vector3TestNative", CallingConvention = CallingConvention.StdCall)] public static extern void nativeCall_PInvoke_Vector3InComplexStruct(ref ComplexDT cdt); public static bool test() { // Expected return value is 12 bytes. if (nativeCall_PInvoke_CheckVector3Size() != 12) { Console.WriteLine("The size of native Vector3 type is not 12 bytes"); return false; } // Argument passing test. // The native code accesses only 12 bytes for each Vector object. { int iv = 123; Vector3 v1 = new Vector3(1,2,3); string str = "abcdefg"; Vector3 v2 = new Vector3(10,11,12); // Expected return value = 1 + 2 + 3 + 10 + 11 + 12 = 39 if (nativeCall_PInvoke_Vector3Arg(iv, v1, str, v2) != 39) { Console.Write("PInvoke Vector3Arg test failed\n"); return false; } } // Argument passing test for Unix. // Few arguments are passed onto stack. { Vector3 v1 = new Vector3(1, 2, 3); Vector3 v2 = new Vector3(10, 20, 30); float f0 = 100, f1 = 101, f2 = 102, f3 = 103, f4 = 104, f5 = 105, f6 = 106, f7 = 107, f8 = 108; float sum = nativeCall_PInvoke_Vector3Arg_Unix( v1, // register f0, f1, f2, f3, f4, f5, // register f6, v2, // stack f7, f8); // stack if (sum != 1002) { Console.Write("PInvoke Vector3Arg_Unix test failed\n"); return false; } } // Argument passing test for Unix. // Few arguments are passed onto stack. { Vector3 v1 = new Vector3(1, 2, 3); Vector3 v2 = new Vector3(4, 5, 6); Vector3 v3 = new Vector3(7, 8, 9); float f0 = 100, f1 = 101, f2 = 102, f3 = 103, f4 = 104, f5 = 105, f6 = 106, f7 = 107, f8 = 108, f9 = 109; float sum = nativeCall_PInvoke_Vector3Arg_Unix2( v1, // register f0, f1, f2, f3, f4, f5, // register f6, v2, // stack f7, f8, // stack v3, // stack f9); // stack if (sum != 1090) { Console.Write("PInvoke Vector3Arg_Unix2 test failed\n"); return false; } } // Return test { Vector3 ret = nativeCall_PInvoke_Vector3Ret(); // Expected return value = (1, 2, 3) dot (1, 2, 3) = 14 float sum = Vector3.Dot(ret, ret); if (sum != 14) { Console.WriteLine("PInvoke Vector3Ret test failed"); return false; } } // Array argument test. // Both the managed and native code assumes 12 bytes for each element. { Vector3[] v3_array = new Vector3[2]; v3_array[0].X = 1; v3_array[0].Y = 2; v3_array[0].Z = 3; v3_array[1].X = 5; v3_array[1].Y = 6; v3_array[1].Z = 7; // Expected resutn value = 1 + 2 + 3 + 5 + 6 + 7 = 24 if (nativeCall_PInvoke_Vector3Array(v3_array) != 24) { Console.WriteLine("PInvoke Vector3Array test failed"); return false; } } // Structure pass and return test. // Both the managed and native side use 12 bytes for each Vector3 object. // Dot product makes sure that the backend assumption 1 and 2 are met. { DT data = new DT(); data.a = new Vector3(1,2,3); data.b = new Vector3(5,6,7); DT ret = nativeCall_PInvoke_Vector3InStruct(data); // Expected return value = (2, 3, 4) dot (6, 7, 8) = 12 + 21 + 32 = 65 float sum = Vector3.Dot(ret.a, ret.b); if (sum != 65) { Console.WriteLine("PInvoke Vector3InStruct test failed"); return false; } } // Complex struct test // Dot product makes sure that the backend assumption 1 and 2 are met. { ComplexDT cdt = new ComplexDT(); cdt.iv = 99; cdt.str = "arg_string"; cdt.vecs.a = new Vector3(1,2,3); cdt.vecs.b = new Vector3(5,6,7); cdt.v3 = new Vector3(10, 20, 30); nativeCall_PInvoke_Vector3InComplexStruct(ref cdt); Console.WriteLine(" Managed ival: {0}", cdt.iv); Console.WriteLine(" Managed Vector3 v1: ({0} {1} {2})", cdt.vecs.a.X, cdt.vecs.a.Y, cdt.vecs.a.Z); Console.WriteLine(" Managed Vector3 v2: ({0} {1} {2})", cdt.vecs.b.X, cdt.vecs.b.Y, cdt.vecs.b.Z); Console.WriteLine(" Managed Vector3 v3: ({0} {1} {2})", cdt.v3.X, cdt.v3.Y, cdt.v3.Z); Console.WriteLine(" Managed string arg: {0}", cdt.str); // (2, 3, 4) dot (6, 7 , 8) = 12 + 21 + 32 = 65 float t0 = Vector3.Dot(cdt.vecs.a, cdt.vecs.b); // (6, 7, 8) dot (11, 21, 31) = 66 + 147 + 248 = 461 float t1 = Vector3.Dot(cdt.vecs.b, cdt.v3); // (11, 21, 31) dot (2, 3, 4) = 209 float t2 = Vector3.Dot(cdt.v3, cdt.vecs.a); float sum = t0 + t1 + t2; Console.WriteLine(" Managed Sum = {0}", sum); if ((sum != 735) || (cdt.iv != 100) || (cdt.str.ToString() != "ret_string")) { Console.WriteLine("PInvoke Vector3InStruct test failed"); return false; } } Console.WriteLine("All PInvoke testcases passed"); return true; } } class RPInvokeTest { public delegate void CallBackDelegate_RPInvoke_Vector3Arg( int i, Vector3 v1, [MarshalAs(UnmanagedType.LPStr)] string s, Vector3 v2); public delegate void CallBackDelegate_RPInvoke_Vector3Arg_Unix( Vector3 v3f32_xmm0, float f32_xmm2, float f32_xmm3, float f32_xmm4, float f32_xmm5, float f32_xmm6, float f32_xmm7, float f32_mem0, Vector3 v3f32_mem1, float f32_mem2, float f32_mem3); public delegate void CallBackDelegate_RPInvoke_Vector3Arg_Unix2( Vector3 v3f32_xmm0, float f32_xmm2, float f32_xmm3, float f32_xmm4, float f32_xmm5, float f32_xmm6, float f32_xmm7, float f32_mem0, Vector3 v3f32_mem1, float f32_mem2, float f32_mem3, Vector3 v3f32_mem4, float f32_mem5); public delegate Vector3 CallBackDelegate_RPInvoke_Vector3Ret(); public delegate void CallBackDelegate_RPInvoke_Vector3Array( [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] Vector3[] v, int size); public delegate void CallBackDelegate_RPInvoke_Vector3InStruct( DT v); public delegate void CallBackDelegate_RPInvoke_Vector3InComplexStruct( ref ComplexDT v); [DllImport(@"Vector3TestNative", CallingConvention = CallingConvention.StdCall)] public static extern void nativeCall_RPInvoke_Vector3Arg( CallBackDelegate_RPInvoke_Vector3Arg callBack); [DllImport(@"Vector3TestNative", CallingConvention = CallingConvention.StdCall)] public static extern void nativeCall_RPInvoke_Vector3Arg_Unix( CallBackDelegate_RPInvoke_Vector3Arg_Unix callBack); [DllImport(@"Vector3TestNative", CallingConvention = CallingConvention.StdCall)] public static extern void nativeCall_RPInvoke_Vector3Arg_Unix2( CallBackDelegate_RPInvoke_Vector3Arg_Unix2 callBack); [DllImport(@"Vector3TestNative", CallingConvention = CallingConvention.StdCall)] public static extern bool nativeCall_RPInvoke_Vector3Ret( CallBackDelegate_RPInvoke_Vector3Ret callBack); [DllImport(@"Vector3TestNative", CallingConvention = CallingConvention.StdCall)] public static extern void nativeCall_RPInvoke_Vector3Array( CallBackDelegate_RPInvoke_Vector3Array callBack, int v); [DllImport(@"Vector3TestNative", CallingConvention = CallingConvention.StdCall)] public static extern void nativeCall_RPInvoke_Vector3InStruct( CallBackDelegate_RPInvoke_Vector3InStruct callBack, int v); [DllImport(@"Vector3TestNative", CallingConvention = CallingConvention.StdCall)] public static extern bool nativeCall_RPInvoke_Vector3InComplexStruct( CallBackDelegate_RPInvoke_Vector3InComplexStruct callBack); static bool result = false; static float x,y,z; // Argument pass test // Test if the managed side correctly reads 12-byte Vector3 argument from the native side // and meet the backend assumption 1 and 2. static void callBack_RPInvoke_Vector3Arg( int i, Vector3 v1, [MarshalAs(UnmanagedType.LPStr)] string s, Vector3 v2) { // sum = (1, 2, 3) dot (1, 2, 3) = 14 float sum0 = Vector3.Dot(v1, v1); // sum = (10, 20, 30) dot (10, 20, 30) = 1400 float sum1 = Vector3.Dot(v2, v2); // sum = (10, 20, 30) dot (1, 2, 3) = 140 float sum2 = Vector3.Dot(v2, v1); Console.WriteLine("callBack_RPInvoke_Vector3Arg:"); Console.WriteLine(" iVal {0}", i); Console.WriteLine(" Sum0,1,2 = {0}, {1}, {2}", sum0, sum1, sum2); Console.WriteLine(" str {0}", s); result = (sum0 == 14) && (sum1 == 1400) && (sum2 == 140) && (s == "abcdefg") && (i == 123); } // Arugument test for Unix // Some arguments are mapped onto stack static void callBack_RPInvoke_Vector3Arg_Unix( Vector3 v3f32_xmm0, float f32_xmm2, float f32_xmm3, float f32_xmm4, float f32_xmm5, float f32_xmm6, float f32_xmm7, float f32_mem0, Vector3 v3f32_mem0, float f32_mem1, float f32_mem2) { // sum = (1, 2, 3) dot (1, 2, 3) = 14 float sum0 = Vector3.Dot(v3f32_xmm0, v3f32_xmm0); // sum = (10, 20, 30) dot (10, 20, 30) = 1400 float sum1 = Vector3.Dot(v3f32_mem0, v3f32_mem0); // sum = (1, 2, 3) dot (10, 20, 30) = 140 float sum2 = Vector3.Dot(v3f32_xmm0, v3f32_mem0); // sum = 100 + 101 + 102 + 103 + 104 + 105 + 106 + 107 + 108 = 936 float sum3 = f32_xmm2 + f32_xmm3 + f32_xmm4 + f32_xmm5 + f32_xmm6 + f32_xmm7 + f32_mem0 + f32_mem1 + f32_mem2; Console.WriteLine("callBack_RPInvoke_Vector3Arg_Unix:"); Console.WriteLine(" {0}, {1}, {2}", v3f32_xmm0.X, v3f32_xmm0.Y, v3f32_xmm0.Z); Console.WriteLine(" {0}, {1}, {2}", v3f32_mem0.X, v3f32_mem0.Y, v3f32_mem0.Z); Console.WriteLine(" Sum0,1,2,3 = {0}, {1}, {2}, {3}", sum0, sum1, sum2, sum3); result = (sum0 == 14) && (sum1 == 1400) && (sum2 == 140) && (sum3==936); } // Arugument test for Unix // Some arguments are mapped onto stack static void callBack_RPInvoke_Vector3Arg_Unix2( Vector3 v3f32_xmm0, float f32_xmm2, float f32_xmm3, float f32_xmm4, float f32_xmm5, float f32_xmm6, float f32_xmm7, float f32_mem0, Vector3 v3f32_mem0, float f32_mem1, float f32_mem2, Vector3 v3f32_mem3, float f32_mem4) { // sum = (1, 2, 3) dot (1, 2, 3) = 14 float sum0 = Vector3.Dot(v3f32_xmm0, v3f32_xmm0); // sum = (4, 5, 6) dot (4, 5, 6) = 77 float sum1 = Vector3.Dot(v3f32_mem0, v3f32_mem0); // sum = (7, 8, 9) dot (7, 8, 9) = 194 float sum2 = Vector3.Dot(v3f32_mem3, v3f32_mem3); // sum = (1, 2, 3) dot (4, 5, 6) = 32 float sum3 = Vector3.Dot(v3f32_xmm0, v3f32_mem0); // sum = (4, 5, 6) dot (7, 8, 9) = 122 float sum4 = Vector3.Dot(v3f32_mem0, v3f32_mem3); // sum = 100 + 101 + 102 + 103 + 104 + 105 + 106 + 107 + 108 + 109 = 1045 float sum5 = f32_xmm2 + f32_xmm3 + f32_xmm4 + f32_xmm5 + f32_xmm6 + f32_xmm7 + f32_mem0 + f32_mem1 + f32_mem2 + f32_mem4; Console.WriteLine("callBack_RPInvoke_Vector3Arg_Unix2:"); Console.WriteLine(" {0}, {1}, {2}", v3f32_xmm0.X, v3f32_xmm0.Y, v3f32_xmm0.Z); Console.WriteLine(" {0}, {1}, {2}", v3f32_mem0.X, v3f32_mem0.Y, v3f32_mem0.Z); Console.WriteLine(" {0}, {1}, {2}", v3f32_mem3.X, v3f32_mem3.Y, v3f32_mem3.Z); Console.WriteLine(" Sum0,1,2,3,4,5 = {0}, {1}, {2}, {3}, {4}, {5}", sum0, sum1, sum2, sum3, sum4, sum5); result = (sum0 == 14) && (sum1 == 77) && (sum2 == 194) && (sum3 == 32) && (sum4 == 122) && (sum5 == 1045); } // Return test. static Vector3 callBack_RPInvoke_Vector3Ret() { Vector3 tmp = new Vector3(1, 2, 3); return tmp; } // Test if the managed side correctly reads an array of 12-byte Vector3 elements // from the native side and meets the backend assumptions. static void callBack_RPInvoke_Vector3Array( [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] Vector3[] v, int size) { // sum0 = (2,3,4) dot (2,3,4) = 4 + 9 + 16 = 29 float sum0 = Vector3.Dot(v[0], v[0]); // sum0 = (11,21,31) dot (11,21,31) = 121 + 441 + 961 = 1523 float sum1 = Vector3.Dot(v[1], v[1]); // sum0 = (11,21,31) dot (2,3,4) = 22 + 63 + 124 = 209 float sum2 = Vector3.Dot(v[0], v[1]); Console.WriteLine("callBack_RPInvoke_Vector3Array:"); Console.WriteLine(" Sum0 = {0} Sum1 = {1} Sum2 = {2}", sum0, sum1, sum2); result = (sum0 == 29) && (sum1 == 1523) && (sum2 == 209); } // Test if the managed side correctly reads 12-byte Vector objects in a struct and // meet the backend assumptions. static void callBack_RPInvoke_Vector3InStruct(DT v) { // sum0 = (2,3,4) dot (2,3,4) = 29 float sum0 = Vector3.Dot(v.a, v.a); // sum1 = (11,21,31) dot (11,21,31) = 22 + 42 + 62 = 1523 float sum1 = Vector3.Dot(v.b, v.b); // sum2 = (2,3,4) dot (11,21,31) = 209 float sum2 = Vector3.Dot(v.a, v.b); Console.WriteLine("callBack_RPInvoke_Vector3InStruct:"); Console.WriteLine(" Sum0 = {0} Sum1 = {1} Sum2 = {2}", sum0, sum1, sum2); result = (sum0 == 29) && (sum1 == 1523) == (sum2 == 209); } // Complex struct type test static void callBack_RPInvoke_Vector3InComplexStruct(ref ComplexDT arg) { ComplexDT ret; Console.WriteLine("callBack_RPInvoke_Vector3InComplexStruct"); Console.WriteLine(" Arg ival: {0}", arg.iv); Console.WriteLine(" Arg Vector3 v1: ({0} {1} {2})", arg.vecs.a.X, arg.vecs.a.Y, arg.vecs.a.Z); Console.WriteLine(" Arg Vector3 v2: ({0} {1} {2})", arg.vecs.b.X, arg.vecs.b.Y, arg.vecs.b.Z); Console.WriteLine(" Arg Vector3 v3: ({0} {1} {2})", arg.v3.X, arg.v3.Y, arg.v3.Z); Console.WriteLine(" Arg string arg: {0}", arg.str); arg.vecs.a.X = arg.vecs.a.X + 1; arg.vecs.a.Y = arg.vecs.a.Y + 1; arg.vecs.a.Z = arg.vecs.a.Z + 1; arg.vecs.b.X = arg.vecs.b.X + 1; arg.vecs.b.Y = arg.vecs.b.Y + 1; arg.vecs.b.Z = arg.vecs.b.Z + 1; arg.v3.X = arg.v3.X + 1; arg.v3.Y = arg.v3.Y + 1; arg.v3.Z = arg.v3.Z + 1; arg.iv = arg.iv + 1; arg.str = "ret_string"; Console.WriteLine(" Return ival: {0}", arg.iv); Console.WriteLine(" Return Vector3 v1: ({0} {1} {2})", arg.vecs.a.X, arg.vecs.a.Y, arg.vecs.a.Z); Console.WriteLine(" Return Vector3 v2: ({0} {1} {2})", arg.vecs.b.X, arg.vecs.b.Y, arg.vecs.b.Z); Console.WriteLine(" Return Vector3 v3: ({0} {1} {2})", arg.v3.X, arg.v3.Y, arg.v3.Z); Console.WriteLine(" Return string arg: {0}", arg.str); float sum = arg.vecs.a.X + arg.vecs.a.Y + arg.vecs.a.Z + arg.vecs.b.X + arg.vecs.b.Y + arg.vecs.b.Z + arg.v3.X + arg.v3.Y + arg.v3.Z; Console.WriteLine(" Sum of all return float scalar values = {0}", sum); } public static bool test() { int x = 1; nativeCall_RPInvoke_Vector3Arg(callBack_RPInvoke_Vector3Arg); if (!result) { Console.WriteLine("RPInvoke Vector3Arg test failed"); return false; } nativeCall_RPInvoke_Vector3Arg_Unix(callBack_RPInvoke_Vector3Arg_Unix); if (!result) { Console.WriteLine("RPInvoke Vector3Arg_Unix test failed"); return false; } nativeCall_RPInvoke_Vector3Arg_Unix2(callBack_RPInvoke_Vector3Arg_Unix2); if (!result) { Console.WriteLine("RPInvoke Vector3Arg_Unix2 test failed"); return false; } result = nativeCall_RPInvoke_Vector3Ret(callBack_RPInvoke_Vector3Ret); if (!result) { Console.WriteLine("RPInvoke Vector3Ret test failed"); return false; } nativeCall_RPInvoke_Vector3Array(callBack_RPInvoke_Vector3Array, x); if (!result) { Console.WriteLine("RPInvoke Vector3Array test failed"); return false; } nativeCall_RPInvoke_Vector3InStruct(callBack_RPInvoke_Vector3InStruct, x); if (!result) { Console.WriteLine("RPInvoke Vector3InStruct test failed"); return false; } result = nativeCall_RPInvoke_Vector3InComplexStruct(callBack_RPInvoke_Vector3InComplexStruct); if (!result) { Console.WriteLine("RPInvoke Vector3InComplexStruct test failed"); return false; } Console.WriteLine("All RPInvoke testcases passed"); return true; } } class Test { public static int Main() { if (!PInvokeTest.test()) { return 101; } if (!RPInvokeTest.test()) { return 101; } return 100; } }
LLITCHEV/coreclr
tests/src/JIT/SIMD/Vector3Interop.cs
C#
mit
22,259
<?php /** * WPSEO plugin file. * * @package WPSEO\Admin\Views */ /** * @var Yoast_Form $yform */ if ( ! defined( 'WPSEO_VERSION' ) ) { header( 'Status: 403 Forbidden' ); header( 'HTTP/1.1 403 Forbidden' ); exit(); } /* translators: %1$s expands to Yoast SEO */ $submit_button_value = sprintf( __( 'Export your %1$s settings', 'wordpress-seo' ), 'Yoast SEO' ); $wpseo_export_phrase = sprintf( /* translators: %1$s expands to Yoast SEO */ __( 'Export your %1$s settings here, to import them again later or to import them on another site.', 'wordpress-seo' ), 'Yoast SEO' ); ?> <p><?php echo esc_html( $wpseo_export_phrase ); ?></p> <form action="<?php echo esc_url( admin_url( 'admin.php?page=wpseo_tools&tool=import-export#top#wpseo-export' ) ); ?>" method="post" accept-charset="<?php echo esc_attr( get_bloginfo( 'charset' ) ); ?>"> <?php wp_nonce_field( WPSEO_Export::NONCE_ACTION, WPSEO_Export::NONCE_NAME ); ?> <button type="submit" class="button button-primary" id="export-button"><?php echo esc_html( $submit_button_value ); ?></button> </form>
smpetrey/leahconstantine.com
web/app/plugins/wordpress-seo/admin/views/tabs/tool/wpseo-export.php
PHP
mit
1,073