code
stringlengths
2
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
2
1.05M
// 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 Microsoft.DotNet.Build.VstsBuildsApi.Configuration; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Microsoft.DotNet.Build.VstsBuildsApi { internal class VstsReleaseHttpClient : VstsDefinitionHttpClient { private const string ReleaseApiType = "release"; public VstsReleaseHttpClient(JObject definition, VstsApiEndpointConfig config) : base(new Uri(definition["url"].ToString()), config, ReleaseApiType) { } public override async Task<JObject> UpdateDefinitionAsync(JObject definition) => await JsonClient.PutAsync( GetRequestUri(definition, "definitions"), definition); protected override bool IsMatching(JObject localDefinition, JObject retrievedDefinition) { return localDefinition["name"].ToString() == retrievedDefinition["name"].ToString(); } protected override IEnumerable<JObject> FindObjectsWithIdentifiableProperties(JObject definition) { IEnumerable<JObject> environments = definition["environments"].Children<JObject>(); IEnumerable<JObject> approvals = environments .SelectMany(env => new[] { env["preDeployApprovals"], env["postDeployApprovals"] }) .SelectMany(approvalWrapper => approvalWrapper["approvals"].Values<JObject>()); return new[] { definition } .Concat(environments) .Concat(approvals); } /// <summary> /// From a url like https://devdiv.vsrm.visualstudio.com/1234/_apis/Release/definitions/1 /// in the url property of the given definition, gets the project, "1234". /// </summary> protected override string GetDefinitionProject(JObject definition) { return new Uri(definition["url"].ToString()).Segments[1].TrimEnd('/'); } } }
AlexGhiondea/buildtools
src/Microsoft.DotNet.Build.VstsBuildsApi/VstsReleaseHttpClient.cs
C#
mit
2,198
// 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. // Add any internal types that we need to forward from mscorlib. // These types are required for Desktop to Core serialization as they are not covered by GenAPI because they are marked as internal. [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.CultureAwareComparer))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.OrdinalComparer))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.GenericComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.NullableComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.ObjectComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.GenericEqualityComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.NullableEqualityComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.ObjectEqualityComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.NonRandomizedStringEqualityComparer))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.ByteEqualityComparer))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.EnumEqualityComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.SByteEnumEqualityComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.ShortEnumEqualityComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.LongEnumEqualityComparer<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.ListDictionaryInternal))] // This is temporary as we are building the mscorlib shim against netfx461 which doesn't contain ValueTuples. [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,,>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,,,>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,,,,>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,,,,,>))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,,,,,,>))]
nbarbettini/corefx
src/shims/manual/mscorlib.forwards.cs
C#
mit
3,065
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Threading; enum AsyncReceiveResult { Completed, Pending, } interface IMessageSource { AsyncReceiveResult BeginReceive(TimeSpan timeout, WaitCallback callback, object state); Message EndReceive(); Message Receive(TimeSpan timeout); AsyncReceiveResult BeginWaitForMessage(TimeSpan timeout, WaitCallback callback, object state); bool EndWaitForMessage(); bool WaitForMessage(TimeSpan timeout); } }
akoeplinger/referencesource
System.ServiceModel/System/ServiceModel/Channels/IMessageSource.cs
C#
mit
733
/* * Chromaprint -- Audio fingerprinting toolkit * Copyright (C) 2010 Lukas Lalinsky <lalinsky@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 Street, Fifth Floor, Boston, MA 02110-1301 * USA */ #include <limits> #include <assert.h> #include <math.h> #include "chroma_filter.h" #include "utils.h" using namespace std; using namespace Chromaprint; ChromaFilter::ChromaFilter(const double *coefficients, int length, FeatureVectorConsumer *consumer) : m_coefficients(coefficients), m_length(length), m_buffer(8), m_result(12), m_buffer_offset(0), m_buffer_size(1), m_consumer(consumer) { } ChromaFilter::~ChromaFilter() { } void ChromaFilter::Reset() { m_buffer_size = 1; m_buffer_offset = 0; } void ChromaFilter::Consume(std::vector<double> &features) { m_buffer[m_buffer_offset] = features; m_buffer_offset = (m_buffer_offset + 1) % 8; if (m_buffer_size >= m_length) { int offset = (m_buffer_offset + 8 - m_length) % 8; fill(m_result.begin(), m_result.end(), 0.0); for (int i = 0; i < 12; i++) { for (int j = 0; j < m_length; j++) { m_result[i] += m_buffer[(offset + j) % 8][i] * m_coefficients[j]; } } m_consumer->Consume(m_result); } else { m_buffer_size++; } }
josephwilk/finger-smudge
vendor/chromaprint/src/chroma_filter.cpp
C++
epl-1.0
1,885
///////////////////////////////////////////////////////////////////////////// // Name: src/msw/tbar95.cpp // Purpose: wxToolBar // Author: Julian Smart // Modified by: // Created: 04/01/98 // RCS-ID: $Id: tbar95.cpp 58446 2009-01-26 23:32:16Z VS $ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_TOOLBAR && wxUSE_TOOLBAR_NATIVE && !defined(__SMARTPHONE__) #include "wx/toolbar.h" #ifndef WX_PRECOMP #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly" #include "wx/dynarray.h" #include "wx/frame.h" #include "wx/log.h" #include "wx/intl.h" #include "wx/settings.h" #include "wx/bitmap.h" #include "wx/dcmemory.h" #include "wx/control.h" #include "wx/app.h" // for GetComCtl32Version #include "wx/image.h" #endif #include "wx/sysopt.h" #include "wx/msw/private.h" #if wxUSE_UXTHEME #include "wx/msw/uxtheme.h" #endif // this define controls whether the code for button colours remapping (only // useful for 16 or 256 colour images) is active at all, it's always turned off // for CE where it doesn't compile (and is probably not needed anyhow) and may // also be turned off for other systems if you always use 24bpp images and so // never need it #ifndef __WXWINCE__ #define wxREMAP_BUTTON_COLOURS #endif // !__WXWINCE__ // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // these standard constants are not always defined in compilers headers // Styles #ifndef TBSTYLE_FLAT #define TBSTYLE_LIST 0x1000 #define TBSTYLE_FLAT 0x0800 #endif #ifndef TBSTYLE_TRANSPARENT #define TBSTYLE_TRANSPARENT 0x8000 #endif #ifndef TBSTYLE_TOOLTIPS #define TBSTYLE_TOOLTIPS 0x0100 #endif // Messages #ifndef TB_GETSTYLE #define TB_SETSTYLE (WM_USER + 56) #define TB_GETSTYLE (WM_USER + 57) #endif #ifndef TB_HITTEST #define TB_HITTEST (WM_USER + 69) #endif #ifndef TB_GETMAXSIZE #define TB_GETMAXSIZE (WM_USER + 83) #endif // these values correspond to those used by comctl32.dll #define DEFAULTBITMAPX 16 #define DEFAULTBITMAPY 15 // ---------------------------------------------------------------------------- // wxWin macros // ---------------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxToolBar, wxControl) /* TOOLBAR PROPERTIES tool bitmap bitmap2 tooltip longhelp radio (bool) toggle (bool) separator style ( wxNO_BORDER | wxTB_HORIZONTAL) bitmapsize margins packing separation dontattachtoframe */ BEGIN_EVENT_TABLE(wxToolBar, wxToolBarBase) EVT_MOUSE_EVENTS(wxToolBar::OnMouseEvent) EVT_SYS_COLOUR_CHANGED(wxToolBar::OnSysColourChanged) EVT_ERASE_BACKGROUND(wxToolBar::OnEraseBackground) END_EVENT_TABLE() // ---------------------------------------------------------------------------- // private classes // ---------------------------------------------------------------------------- class wxToolBarTool : public wxToolBarToolBase { public: wxToolBarTool(wxToolBar *tbar, int id, const wxString& label, const wxBitmap& bmpNormal, const wxBitmap& bmpDisabled, wxItemKind kind, wxObject *clientData, const wxString& shortHelp, const wxString& longHelp) : wxToolBarToolBase(tbar, id, label, bmpNormal, bmpDisabled, kind, clientData, shortHelp, longHelp) { m_nSepCount = 0; } wxToolBarTool(wxToolBar *tbar, wxControl *control) : wxToolBarToolBase(tbar, control) { m_nSepCount = 1; } virtual void SetLabel(const wxString& label) { if ( label == m_label ) return; wxToolBarToolBase::SetLabel(label); // we need to update the label shown in the toolbar because it has a // pointer to the internal buffer of the old label // // TODO: use TB_SETBUTTONINFO } // set/get the number of separators which we use to cover the space used by // a control in the toolbar void SetSeparatorsCount(size_t count) { m_nSepCount = count; } size_t GetSeparatorsCount() const { return m_nSepCount; } private: size_t m_nSepCount; DECLARE_NO_COPY_CLASS(wxToolBarTool) }; // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // wxToolBarTool // ---------------------------------------------------------------------------- wxToolBarToolBase *wxToolBar::CreateTool(int id, const wxString& label, const wxBitmap& bmpNormal, const wxBitmap& bmpDisabled, wxItemKind kind, wxObject *clientData, const wxString& shortHelp, const wxString& longHelp) { return new wxToolBarTool(this, id, label, bmpNormal, bmpDisabled, kind, clientData, shortHelp, longHelp); } wxToolBarToolBase *wxToolBar::CreateTool(wxControl *control) { return new wxToolBarTool(this, control); } // ---------------------------------------------------------------------------- // wxToolBar construction // ---------------------------------------------------------------------------- void wxToolBar::Init() { m_hBitmap = 0; m_disabledImgList = NULL; m_nButtons = 0; m_defaultWidth = DEFAULTBITMAPX; m_defaultHeight = DEFAULTBITMAPY; m_pInTool = 0; } bool wxToolBar::Create(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) { // common initialisation if ( !CreateControl(parent, id, pos, size, style, wxDefaultValidator, name) ) return false; FixupStyle(); // MSW-specific initialisation if ( !MSWCreateToolbar(pos, size) ) return false; wxSetCCUnicodeFormat(GetHwnd()); // workaround for flat toolbar on Windows XP classic style: we have to set // the style after creating the control; doing it at creation time doesn't work #if wxUSE_UXTHEME if ( style & wxTB_FLAT ) { LRESULT style = GetMSWToolbarStyle(); if ( !(style & TBSTYLE_FLAT) ) ::SendMessage(GetHwnd(), TB_SETSTYLE, 0, style | TBSTYLE_FLAT); } #endif // wxUSE_UXTHEME return true; } bool wxToolBar::MSWCreateToolbar(const wxPoint& pos, const wxSize& size) { if ( !MSWCreateControl(TOOLBARCLASSNAME, wxEmptyString, pos, size) ) return false; // toolbar-specific post initialisation ::SendMessage(GetHwnd(), TB_BUTTONSTRUCTSIZE, sizeof(TBBUTTON), 0); // Fix a bug on e.g. the Silver theme on WinXP where control backgrounds // are incorrectly drawn, by forcing the background to a specific colour. int majorVersion, minorVersion; wxGetOsVersion(& majorVersion, & minorVersion); if (majorVersion < 6) SetBackgroundColour(GetBackgroundColour()); return true; } void wxToolBar::Recreate() { const HWND hwndOld = GetHwnd(); if ( !hwndOld ) { // we haven't been created yet, no need to recreate return; } // get the position and size before unsubclassing the old toolbar const wxPoint pos = GetPosition(); const wxSize size = GetSize(); UnsubclassWin(); if ( !MSWCreateToolbar(pos, size) ) { // what can we do? wxFAIL_MSG( _T("recreating the toolbar failed") ); return; } // reparent all our children under the new toolbar for ( wxWindowList::compatibility_iterator node = m_children.GetFirst(); node; node = node->GetNext() ) { wxWindow *win = node->GetData(); if ( !win->IsTopLevel() ) ::SetParent(GetHwndOf(win), GetHwnd()); } // only destroy the old toolbar now -- // after all the children had been reparented ::DestroyWindow(hwndOld); // it is for the old bitmap control and can't be used with the new one if ( m_hBitmap ) { ::DeleteObject((HBITMAP) m_hBitmap); m_hBitmap = 0; } if ( m_disabledImgList ) { delete m_disabledImgList; m_disabledImgList = NULL; } Realize(); } wxToolBar::~wxToolBar() { // we must refresh the frame size when the toolbar is deleted but the frame // is not - otherwise toolbar leaves a hole in the place it used to occupy wxFrame *frame = wxDynamicCast(GetParent(), wxFrame); if ( frame && !frame->IsBeingDeleted() ) frame->SendSizeEvent(); if ( m_hBitmap ) ::DeleteObject((HBITMAP) m_hBitmap); delete m_disabledImgList; } wxSize wxToolBar::DoGetBestSize() const { wxSize sizeBest; SIZE size; if ( !::SendMessage(GetHwnd(), TB_GETMAXSIZE, 0, (LPARAM)&size) ) { // maybe an old (< 0x400) Windows version? try to approximate the // toolbar size ourselves sizeBest = GetToolSize(); sizeBest.y += 2 * ::GetSystemMetrics(SM_CYBORDER); // Add borders sizeBest.x *= GetToolsCount(); // reverse horz and vertical components if necessary if ( IsVertical() ) { int t = sizeBest.x; sizeBest.x = sizeBest.y; sizeBest.y = t; } } else // TB_GETMAXSIZE succeeded { // but it could still return an incorrect result due to what appears to // be a bug in old comctl32.dll versions which don't handle controls in // the toolbar correctly, so work around it (see SF patch 1902358) if ( !IsVertical() && wxApp::GetComCtl32Version() < 600 ) { // calculate the toolbar width in alternative way RECT rcFirst, rcLast; if ( ::SendMessage(GetHwnd(), TB_GETITEMRECT, 0, (LPARAM)&rcFirst) && ::SendMessage(GetHwnd(), TB_GETITEMRECT, GetToolsCount() - 1, (LPARAM)&rcLast) ) { const int widthAlt = rcLast.right - rcFirst.left; if ( widthAlt > size.cx ) size.cx = widthAlt; } } sizeBest.x = size.cx; sizeBest.y = size.cy; } if (!IsVertical()) { // Without the extra height, DoGetBestSize can report a size that's // smaller than the actual window, causing windows to overlap slightly // in some circumstances, leading to missing borders (especially noticeable // in AUI layouts). if (!(GetWindowStyle() & wxTB_NODIVIDER)) sizeBest.y += 2; sizeBest.y ++; } CacheBestSize(sizeBest); return sizeBest; } WXDWORD wxToolBar::MSWGetStyle(long style, WXDWORD *exstyle) const { // toolbars never have border, giving one to them results in broken // appearance WXDWORD msStyle = wxControl::MSWGetStyle ( (style & ~wxBORDER_MASK) | wxBORDER_NONE, exstyle ); if ( !(style & wxTB_NO_TOOLTIPS) ) msStyle |= TBSTYLE_TOOLTIPS; if ( style & (wxTB_FLAT | wxTB_HORZ_LAYOUT) ) { // static as it doesn't change during the program lifetime static const int s_verComCtl = wxApp::GetComCtl32Version(); // comctl32.dll 4.00 doesn't support the flat toolbars and using this // style with 6.00 (part of Windows XP) leads to the toolbar with // incorrect background colour - and not using it still results in the // correct (flat) toolbar, so don't use it there if ( s_verComCtl > 400 && s_verComCtl < 600 ) msStyle |= TBSTYLE_FLAT | TBSTYLE_TRANSPARENT; if ( s_verComCtl >= 470 && style & wxTB_HORZ_LAYOUT ) msStyle |= TBSTYLE_LIST; } if ( style & wxTB_NODIVIDER ) msStyle |= CCS_NODIVIDER; if ( style & wxTB_NOALIGN ) msStyle |= CCS_NOPARENTALIGN; if ( style & wxTB_VERTICAL ) msStyle |= CCS_VERT; if( style & wxTB_BOTTOM ) msStyle |= CCS_BOTTOM; if ( style & wxTB_RIGHT ) msStyle |= CCS_RIGHT; return msStyle; } // ---------------------------------------------------------------------------- // adding/removing tools // ---------------------------------------------------------------------------- bool wxToolBar::DoInsertTool(size_t WXUNUSED(pos), wxToolBarToolBase *tool) { // nothing special to do here - we really create the toolbar buttons in // Realize() later tool->Attach(this); InvalidateBestSize(); return true; } bool wxToolBar::DoDeleteTool(size_t pos, wxToolBarToolBase *tool) { // the main difficulty we have here is with the controls in the toolbars: // as we (sometimes) use several separators to cover up the space used by // them, the indices are not the same for us and the toolbar // first determine the position of the first button to delete: it may be // different from pos if we use several separators to cover the space used // by a control wxToolBarToolsList::compatibility_iterator node; for ( node = m_tools.GetFirst(); node; node = node->GetNext() ) { wxToolBarToolBase *tool2 = node->GetData(); if ( tool2 == tool ) { // let node point to the next node in the list node = node->GetNext(); break; } if ( tool2->IsControl() ) pos += ((wxToolBarTool *)tool2)->GetSeparatorsCount() - 1; } // now determine the number of buttons to delete and the area taken by them size_t nButtonsToDelete = 1; // get the size of the button we're going to delete RECT r; if ( !::SendMessage(GetHwnd(), TB_GETITEMRECT, pos, (LPARAM)&r) ) { wxLogLastError(_T("TB_GETITEMRECT")); } int width = r.right - r.left; if ( tool->IsControl() ) { nButtonsToDelete = ((wxToolBarTool *)tool)->GetSeparatorsCount(); width *= nButtonsToDelete; tool->GetControl()->Destroy(); } // do delete all buttons m_nButtons -= nButtonsToDelete; while ( nButtonsToDelete-- > 0 ) { if ( !::SendMessage(GetHwnd(), TB_DELETEBUTTON, pos, 0) ) { wxLogLastError(wxT("TB_DELETEBUTTON")); return false; } } tool->Detach(); // and finally reposition all the controls after this button (the toolbar // takes care of all normal items) for ( /* node -> first after deleted */ ; node; node = node->GetNext() ) { wxToolBarToolBase *tool2 = node->GetData(); if ( tool2->IsControl() ) { int x; wxControl *control = tool2->GetControl(); control->GetPosition(&x, NULL); control->Move(x - width, wxDefaultCoord); } } InvalidateBestSize(); return true; } void wxToolBar::CreateDisabledImageList() { if (m_disabledImgList != NULL) { delete m_disabledImgList; m_disabledImgList = NULL; } // as we can't use disabled image list with older versions of comctl32.dll, // don't even bother creating it if ( wxApp::GetComCtl32Version() >= 470 ) { // search for the first disabled button img in the toolbar, if any for ( wxToolBarToolsList::compatibility_iterator node = m_tools.GetFirst(); node; node = node->GetNext() ) { wxToolBarToolBase *tool = node->GetData(); wxBitmap bmpDisabled = tool->GetDisabledBitmap(); if ( bmpDisabled.Ok() ) { m_disabledImgList = new wxImageList ( m_defaultWidth, m_defaultHeight, bmpDisabled.GetMask() != NULL, GetToolsCount() ); break; } } // we don't have any disabled bitmaps } } void wxToolBar::AdjustToolBitmapSize() { wxSize s(m_defaultWidth, m_defaultHeight); const wxSize orig_s(s); for ( wxToolBarToolsList::const_iterator i = m_tools.begin(); i != m_tools.end(); ++i ) { const wxBitmap& bmp = (*i)->GetNormalBitmap(); s.IncTo(wxSize(bmp.GetWidth(), bmp.GetHeight())); } if ( s != orig_s ) SetToolBitmapSize(s); } bool wxToolBar::Realize() { const size_t nTools = GetToolsCount(); if ( nTools == 0 ) // nothing to do return true; // make sure tool size is larger enough for all all bitmaps to fit in // (this is consistent with what other ports do): AdjustToolBitmapSize(); #ifdef wxREMAP_BUTTON_COLOURS // don't change the values of these constants, they can be set from the // user code via wxSystemOptions enum { Remap_None = -1, Remap_Bg, Remap_Buttons, Remap_TransparentBg }; // the user-specified option overrides anything, but if it wasn't set, only // remap the buttons on 8bpp displays as otherwise the bitmaps usually look // much worse after remapping static const wxChar *remapOption = wxT("msw.remap"); const int remapValue = wxSystemOptions::HasOption(remapOption) ? wxSystemOptions::GetOptionInt(remapOption) : wxDisplayDepth() <= 8 ? Remap_Buttons : Remap_None; #endif // wxREMAP_BUTTON_COLOURS // delete all old buttons, if any for ( size_t pos = 0; pos < m_nButtons; pos++ ) { if ( !::SendMessage(GetHwnd(), TB_DELETEBUTTON, 0, 0) ) { wxLogDebug(wxT("TB_DELETEBUTTON failed")); } } // First, add the bitmap: we use one bitmap for all toolbar buttons // ---------------------------------------------------------------- wxToolBarToolsList::compatibility_iterator node; int bitmapId = 0; wxSize sizeBmp; if ( HasFlag(wxTB_NOICONS) ) { // no icons, don't leave space for them sizeBmp.x = sizeBmp.y = 0; } else // do show icons { // if we already have a bitmap, we'll replace the existing one -- // otherwise we'll install a new one HBITMAP oldToolBarBitmap = (HBITMAP)m_hBitmap; sizeBmp.x = m_defaultWidth; sizeBmp.y = m_defaultHeight; const wxCoord totalBitmapWidth = m_defaultWidth * wx_truncate_cast(wxCoord, nTools), totalBitmapHeight = m_defaultHeight; // Create a bitmap and copy all the tool bitmaps into it wxMemoryDC dcAllButtons; wxBitmap bitmap(totalBitmapWidth, totalBitmapHeight); dcAllButtons.SelectObject(bitmap); #ifdef wxREMAP_BUTTON_COLOURS if ( remapValue != Remap_TransparentBg ) #endif // wxREMAP_BUTTON_COLOURS { // VZ: why do we hardcode grey colour for CE? dcAllButtons.SetBackground(wxBrush( #ifdef __WXWINCE__ wxColour(0xc0, 0xc0, 0xc0) #else // !__WXWINCE__ GetBackgroundColour() #endif // __WXWINCE__/!__WXWINCE__ )); dcAllButtons.Clear(); } m_hBitmap = bitmap.GetHBITMAP(); HBITMAP hBitmap = (HBITMAP)m_hBitmap; #ifdef wxREMAP_BUTTON_COLOURS if ( remapValue == Remap_Bg ) { dcAllButtons.SelectObject(wxNullBitmap); // Even if we're not remapping the bitmap // content, we still have to remap the background. hBitmap = (HBITMAP)MapBitmap((WXHBITMAP) hBitmap, totalBitmapWidth, totalBitmapHeight); dcAllButtons.SelectObject(bitmap); } #endif // wxREMAP_BUTTON_COLOURS // the button position wxCoord x = 0; // the number of buttons (not separators) int nButtons = 0; CreateDisabledImageList(); for ( node = m_tools.GetFirst(); node; node = node->GetNext() ) { wxToolBarToolBase *tool = node->GetData(); if ( tool->IsButton() ) { const wxBitmap& bmp = tool->GetNormalBitmap(); const int w = bmp.GetWidth(); const int h = bmp.GetHeight(); if ( bmp.Ok() ) { int xOffset = wxMax(0, (m_defaultWidth - w)/2); int yOffset = wxMax(0, (m_defaultHeight - h)/2); // notice the last parameter: do use mask dcAllButtons.DrawBitmap(bmp, x + xOffset, yOffset, true); } else { wxFAIL_MSG( _T("invalid tool button bitmap") ); } // also deal with disabled bitmap if we want to use them if ( m_disabledImgList ) { wxBitmap bmpDisabled = tool->GetDisabledBitmap(); #if wxUSE_IMAGE && wxUSE_WXDIB if ( !bmpDisabled.Ok() ) { // no disabled bitmap specified but we still need to // fill the space in the image list with something, so // we grey out the normal bitmap wxImage imgGreyed; wxCreateGreyedImage(bmp.ConvertToImage(), imgGreyed); #ifdef wxREMAP_BUTTON_COLOURS if ( remapValue == Remap_Buttons ) { // we need to have light grey background colour for // MapBitmap() to work correctly for ( int y = 0; y < h; y++ ) { for ( int x = 0; x < w; x++ ) { if ( imgGreyed.IsTransparent(x, y) ) imgGreyed.SetRGB(x, y, wxLIGHT_GREY->Red(), wxLIGHT_GREY->Green(), wxLIGHT_GREY->Blue()); } } } #endif // wxREMAP_BUTTON_COLOURS bmpDisabled = wxBitmap(imgGreyed); } #endif // wxUSE_IMAGE #ifdef wxREMAP_BUTTON_COLOURS if ( remapValue == Remap_Buttons ) MapBitmap(bmpDisabled.GetHBITMAP(), w, h); #endif // wxREMAP_BUTTON_COLOURS m_disabledImgList->Add(bmpDisabled); } // still inc width and number of buttons because otherwise the // subsequent buttons will all be shifted which is rather confusing // (and like this you'd see immediately which bitmap was bad) x += m_defaultWidth; nButtons++; } } dcAllButtons.SelectObject(wxNullBitmap); // don't delete this HBITMAP! bitmap.SetHBITMAP(0); #ifdef wxREMAP_BUTTON_COLOURS if ( remapValue == Remap_Buttons ) { // Map to system colours hBitmap = (HBITMAP)MapBitmap((WXHBITMAP) hBitmap, totalBitmapWidth, totalBitmapHeight); } #endif // wxREMAP_BUTTON_COLOURS bool addBitmap = true; if ( oldToolBarBitmap ) { #ifdef TB_REPLACEBITMAP if ( wxApp::GetComCtl32Version() >= 400 ) { TBREPLACEBITMAP replaceBitmap; replaceBitmap.hInstOld = NULL; replaceBitmap.hInstNew = NULL; replaceBitmap.nIDOld = (UINT) oldToolBarBitmap; replaceBitmap.nIDNew = (UINT) hBitmap; replaceBitmap.nButtons = nButtons; if ( !::SendMessage(GetHwnd(), TB_REPLACEBITMAP, 0, (LPARAM) &replaceBitmap) ) { wxFAIL_MSG(wxT("Could not replace the old bitmap")); } ::DeleteObject(oldToolBarBitmap); // already done addBitmap = false; } else #endif // TB_REPLACEBITMAP { // we can't replace the old bitmap, so we will add another one // (awfully inefficient, but what else to do?) and shift the bitmap // indices accordingly addBitmap = true; bitmapId = m_nButtons; } } if ( addBitmap ) // no old bitmap or we can't replace it { TBADDBITMAP addBitmap; addBitmap.hInst = 0; addBitmap.nID = (UINT) hBitmap; if ( ::SendMessage(GetHwnd(), TB_ADDBITMAP, (WPARAM) nButtons, (LPARAM)&addBitmap) == -1 ) { wxFAIL_MSG(wxT("Could not add bitmap to toolbar")); } } // disable image lists are only supported in comctl32.dll 4.70+ if ( wxApp::GetComCtl32Version() >= 470 ) { HIMAGELIST hil = m_disabledImgList ? GetHimagelistOf(m_disabledImgList) : 0; // notice that we set the image list even if don't have one right // now as we could have it before and need to reset it in this case HIMAGELIST oldImageList = (HIMAGELIST) ::SendMessage(GetHwnd(), TB_SETDISABLEDIMAGELIST, 0, (LPARAM)hil); // delete previous image list if any if ( oldImageList ) ::DeleteObject(oldImageList); } } // don't call SetToolBitmapSize() as we don't want to change the values of // m_defaultWidth/Height if ( !::SendMessage(GetHwnd(), TB_SETBITMAPSIZE, 0, MAKELONG(sizeBmp.x, sizeBmp.y)) ) { wxLogLastError(_T("TB_SETBITMAPSIZE")); } // Next add the buttons and separators // ----------------------------------- TBBUTTON *buttons = new TBBUTTON[nTools]; // this array will hold the indices of all controls in the toolbar wxArrayInt controlIds; bool lastWasRadio = false; int i = 0; for ( node = m_tools.GetFirst(); node; node = node->GetNext() ) { wxToolBarToolBase *tool = node->GetData(); // don't add separators to the vertical toolbar with old comctl32.dll // versions as they didn't handle this properly if ( IsVertical() && tool->IsSeparator() && wxApp::GetComCtl32Version() <= 472 ) { continue; } TBBUTTON& button = buttons[i]; wxZeroMemory(button); bool isRadio = false; switch ( tool->GetStyle() ) { case wxTOOL_STYLE_CONTROL: button.idCommand = tool->GetId(); // fall through: create just a separator too case wxTOOL_STYLE_SEPARATOR: button.fsState = TBSTATE_ENABLED; button.fsStyle = TBSTYLE_SEP; break; case wxTOOL_STYLE_BUTTON: if ( !HasFlag(wxTB_NOICONS) ) button.iBitmap = bitmapId; if ( HasFlag(wxTB_TEXT) ) { const wxString& label = tool->GetLabel(); if ( !label.empty() ) button.iString = (int)label.c_str(); } button.idCommand = tool->GetId(); if ( tool->IsEnabled() ) button.fsState |= TBSTATE_ENABLED; if ( tool->IsToggled() ) button.fsState |= TBSTATE_CHECKED; switch ( tool->GetKind() ) { case wxITEM_RADIO: button.fsStyle = TBSTYLE_CHECKGROUP; if ( !lastWasRadio ) { // the first item in the radio group is checked by // default to be consistent with wxGTK and the menu // radio items button.fsState |= TBSTATE_CHECKED; if (tool->Toggle(true)) { DoToggleTool(tool, true); } } else if ( tool->IsToggled() ) { wxToolBarToolsList::compatibility_iterator nodePrev = node->GetPrevious(); int prevIndex = i - 1; while ( nodePrev ) { TBBUTTON& prevButton = buttons[prevIndex]; wxToolBarToolBase *tool = nodePrev->GetData(); if ( !tool->IsButton() || tool->GetKind() != wxITEM_RADIO ) break; if ( tool->Toggle(false) ) DoToggleTool(tool, false); prevButton.fsState &= ~TBSTATE_CHECKED; nodePrev = nodePrev->GetPrevious(); prevIndex--; } } isRadio = true; break; case wxITEM_CHECK: button.fsStyle = TBSTYLE_CHECK; break; case wxITEM_NORMAL: button.fsStyle = TBSTYLE_BUTTON; break; default: wxFAIL_MSG( _T("unexpected toolbar button kind") ); button.fsStyle = TBSTYLE_BUTTON; break; } bitmapId++; break; } lastWasRadio = isRadio; i++; } if ( !::SendMessage(GetHwnd(), TB_ADDBUTTONS, (WPARAM)i, (LPARAM)buttons) ) { wxLogLastError(wxT("TB_ADDBUTTONS")); } delete [] buttons; // Deal with the controls finally // ------------------------------ // adjust the controls size to fit nicely in the toolbar int y = 0; size_t index = 0; for ( node = m_tools.GetFirst(); node; node = node->GetNext(), index++ ) { wxToolBarToolBase *tool = node->GetData(); // we calculate the running y coord for vertical toolbars so we need to // get the items size for all items but for the horizontal ones we // don't need to deal with the non controls bool isControl = tool->IsControl(); if ( !isControl && !IsVertical() ) continue; // note that we use TB_GETITEMRECT and not TB_GETRECT because the // latter only appeared in v4.70 of comctl32.dll RECT r; if ( !::SendMessage(GetHwnd(), TB_GETITEMRECT, index, (LPARAM)(LPRECT)&r) ) { wxLogLastError(wxT("TB_GETITEMRECT")); } if ( !isControl ) { // can only be control if isVertical y += r.bottom - r.top; continue; } wxControl *control = tool->GetControl(); wxSize size = control->GetSize(); // the position of the leftmost controls corner int left = wxDefaultCoord; // TB_SETBUTTONINFO message is only supported by comctl32.dll 4.71+ #ifdef TB_SETBUTTONINFO // available in headers, now check whether it is available now // (during run-time) if ( wxApp::GetComCtl32Version() >= 471 ) { // set the (underlying) separators width to be that of the // control TBBUTTONINFO tbbi; tbbi.cbSize = sizeof(tbbi); tbbi.dwMask = TBIF_SIZE; tbbi.cx = (WORD)size.x; if ( !::SendMessage(GetHwnd(), TB_SETBUTTONINFO, tool->GetId(), (LPARAM)&tbbi) ) { // the id is probably invalid? wxLogLastError(wxT("TB_SETBUTTONINFO")); } } else #endif // comctl32.dll 4.71 // TB_SETBUTTONINFO unavailable { // try adding several separators to fit the controls width int widthSep = r.right - r.left; left = r.left; TBBUTTON tbb; wxZeroMemory(tbb); tbb.idCommand = 0; tbb.fsState = TBSTATE_ENABLED; tbb.fsStyle = TBSTYLE_SEP; size_t nSeparators = size.x / widthSep; for ( size_t nSep = 0; nSep < nSeparators; nSep++ ) { if ( !::SendMessage(GetHwnd(), TB_INSERTBUTTON, index, (LPARAM)&tbb) ) { wxLogLastError(wxT("TB_INSERTBUTTON")); } index++; } // remember the number of separators we used - we'd have to // delete all of them later ((wxToolBarTool *)tool)->SetSeparatorsCount(nSeparators); // adjust the controls width to exactly cover the separators control->SetSize((nSeparators + 1)*widthSep, wxDefaultCoord); } // position the control itself correctly vertically int height = r.bottom - r.top; int diff = height - size.y; if ( diff < 0 ) { // the control is too high, resize to fit control->SetSize(wxDefaultCoord, height - 2); diff = 2; } int top; if ( IsVertical() ) { left = 0; top = y; y += height + 2 * GetMargins().y; } else // horizontal toolbar { if ( left == wxDefaultCoord ) left = r.left; top = r.top; } control->Move(left, top + (diff + 1) / 2); } // the max index is the "real" number of buttons - i.e. counting even the // separators which we added just for aligning the controls m_nButtons = index; if ( !IsVertical() ) { if ( m_maxRows == 0 ) // if not set yet, only one row SetRows(1); } else if ( m_nButtons > 0 ) // vertical non empty toolbar { // if not set yet, have one column m_maxRows = 1; SetRows(m_nButtons); } InvalidateBestSize(); UpdateSize(); return true; } // ---------------------------------------------------------------------------- // message handlers // ---------------------------------------------------------------------------- bool wxToolBar::MSWCommand(WXUINT WXUNUSED(cmd), WXWORD id) { wxToolBarToolBase *tool = FindById((int)id); if ( !tool ) return false; bool toggled = false; // just to suppress warnings LRESULT state = ::SendMessage(GetHwnd(), TB_GETSTATE, id, 0); if ( tool->CanBeToggled() ) { toggled = (state & TBSTATE_CHECKED) != 0; // ignore the event when a radio button is released, as this doesn't // seem to happen at all, and is handled otherwise if ( tool->GetKind() == wxITEM_RADIO && !toggled ) return true; tool->Toggle(toggled); UnToggleRadioGroup(tool); } // Without the two lines of code below, if the toolbar was repainted during // OnLeftClick(), then it could end up without the tool bitmap temporarily // (see http://lists.nongnu.org/archive/html/lmi/2008-10/msg00014.html). // The Update() call bellow ensures that this won't happen, by repainting // invalidated areas of the toolbar immediately. // // To complicate matters, the tool would be drawn in depressed state (this // code is called when mouse button is released, not pressed). That's not // ideal, having the tool pressed for the duration of OnLeftClick() // provides the user with useful visual clue that the app is busy reacting // to the event. So we manually put the tool into pressed state, handle the // event and then finally restore tool's original state. ::SendMessage(GetHwnd(), TB_SETSTATE, id, MAKELONG(state | TBSTATE_PRESSED, 0)); Update(); bool allowLeftClick = OnLeftClick((int)id, toggled); // Restore the unpressed state. Enabled/toggled state might have been // changed since so take care of it. if (tool->IsEnabled()) state |= TBSTATE_ENABLED; else state &= ~TBSTATE_ENABLED; if (tool->IsToggled()) state |= TBSTATE_CHECKED; else state &= ~TBSTATE_CHECKED; ::SendMessage(GetHwnd(), TB_SETSTATE, id, MAKELONG(state, 0)); // OnLeftClick() can veto the button state change - for buttons which // may be toggled only, of couse if ( !allowLeftClick && tool->CanBeToggled() ) { // revert back tool->Toggle(!toggled); ::SendMessage(GetHwnd(), TB_CHECKBUTTON, id, MAKELONG(!toggled, 0)); } return true; } bool wxToolBar::MSWOnNotify(int WXUNUSED(idCtrl), WXLPARAM lParam, WXLPARAM *WXUNUSED(result)) { if( !HasFlag(wxTB_NO_TOOLTIPS) ) { #if wxUSE_TOOLTIPS // First check if this applies to us NMHDR *hdr = (NMHDR *)lParam; // the tooltips control created by the toolbar is sometimes Unicode, even // in an ANSI application - this seems to be a bug in comctl32.dll v5 UINT code = hdr->code; if ( (code != (UINT) TTN_NEEDTEXTA) && (code != (UINT) TTN_NEEDTEXTW) ) return false; HWND toolTipWnd = (HWND)::SendMessage(GetHwnd(), TB_GETTOOLTIPS, 0, 0); if ( toolTipWnd != hdr->hwndFrom ) return false; LPTOOLTIPTEXT ttText = (LPTOOLTIPTEXT)lParam; int id = (int)ttText->hdr.idFrom; wxToolBarToolBase *tool = FindById(id); if ( tool ) return HandleTooltipNotify(code, lParam, tool->GetShortHelp()); #else wxUnusedVar(lParam); #endif } return false; } // ---------------------------------------------------------------------------- // toolbar geometry // ---------------------------------------------------------------------------- void wxToolBar::SetToolBitmapSize(const wxSize& size) { wxToolBarBase::SetToolBitmapSize(size); ::SendMessage(GetHwnd(), TB_SETBITMAPSIZE, 0, MAKELONG(size.x, size.y)); } void wxToolBar::SetRows(int nRows) { if ( nRows == m_maxRows ) { // avoid resizing the frame uselessly return; } // TRUE in wParam means to create at least as many rows, FALSE - // at most as many RECT rect; ::SendMessage(GetHwnd(), TB_SETROWS, MAKEWPARAM(nRows, !(GetWindowStyle() & wxTB_VERTICAL)), (LPARAM) &rect); m_maxRows = nRows; UpdateSize(); } // The button size is bigger than the bitmap size wxSize wxToolBar::GetToolSize() const { // TB_GETBUTTONSIZE is supported from version 4.70 #if defined(_WIN32_IE) && (_WIN32_IE >= 0x300 ) \ && !( defined(__GNUWIN32__) && !wxCHECK_W32API_VERSION( 1, 0 ) ) \ && !defined (__DIGITALMARS__) if ( wxApp::GetComCtl32Version() >= 470 ) { DWORD dw = ::SendMessage(GetHwnd(), TB_GETBUTTONSIZE, 0, 0); return wxSize(LOWORD(dw), HIWORD(dw)); } else #endif // comctl32.dll 4.70+ { // defaults return wxSize(m_defaultWidth + 8, m_defaultHeight + 7); } } static wxToolBarToolBase *GetItemSkippingDummySpacers(const wxToolBarToolsList& tools, size_t index ) { wxToolBarToolsList::compatibility_iterator current = tools.GetFirst(); for ( ; current ; current = current->GetNext() ) { if ( index == 0 ) return current->GetData(); wxToolBarTool *tool = (wxToolBarTool *)current->GetData(); size_t separators = tool->GetSeparatorsCount(); // if it is a normal button, sepcount == 0, so skip 1 item (the button) // otherwise, skip as many items as the separator count, plus the // control itself index -= separators ? separators + 1 : 1; } return 0; } wxToolBarToolBase *wxToolBar::FindToolForPosition(wxCoord x, wxCoord y) const { POINT pt; pt.x = x; pt.y = y; int index = (int)::SendMessage(GetHwnd(), TB_HITTEST, 0, (LPARAM)&pt); // MBN: when the point ( x, y ) is close to the toolbar border // TB_HITTEST returns m_nButtons ( not -1 ) if ( index < 0 || (size_t)index >= m_nButtons ) // it's a separator or there is no tool at all there return (wxToolBarToolBase *)NULL; // when TB_SETBUTTONINFO is available (both during compile- and run-time), // we don't use the dummy separators hack #ifdef TB_SETBUTTONINFO if ( wxApp::GetComCtl32Version() >= 471 ) { return m_tools.Item((size_t)index)->GetData(); } else #endif // TB_SETBUTTONINFO { return GetItemSkippingDummySpacers( m_tools, (size_t) index ); } } void wxToolBar::UpdateSize() { wxPoint pos = GetPosition(); ::SendMessage(GetHwnd(), TB_AUTOSIZE, 0, 0); if (pos != GetPosition()) Move(pos); // In case Realize is called after the initial display (IOW the programmer // may have rebuilt the toolbar) give the frame the option of resizing the // toolbar to full width again, but only if the parent is a frame and the // toolbar is managed by the frame. Otherwise assume that some other // layout mechanism is controlling the toolbar size and leave it alone. wxFrame *frame = wxDynamicCast(GetParent(), wxFrame); if ( frame && frame->GetToolBar() == this ) { frame->SendSizeEvent(); } } // ---------------------------------------------------------------------------- // toolbar styles // --------------------------------------------------------------------------- // get the TBSTYLE of the given toolbar window long wxToolBar::GetMSWToolbarStyle() const { return ::SendMessage(GetHwnd(), TB_GETSTYLE, 0, 0L); } void wxToolBar::SetWindowStyleFlag(long style) { // the style bits whose changes force us to recreate the toolbar static const long MASK_NEEDS_RECREATE = wxTB_TEXT | wxTB_NOICONS; const long styleOld = GetWindowStyle(); wxToolBarBase::SetWindowStyleFlag(style); // don't recreate an empty toolbar: not only this is unnecessary, but it is // also fatal as we'd then try to recreate the toolbar when it's just being // created if ( GetToolsCount() && (style & MASK_NEEDS_RECREATE) != (styleOld & MASK_NEEDS_RECREATE) ) { // to remove the text labels, simply re-realizing the toolbar is enough // but I don't know of any way to add the text to an existing toolbar // other than by recreating it entirely Recreate(); } } // ---------------------------------------------------------------------------- // tool state // ---------------------------------------------------------------------------- void wxToolBar::DoEnableTool(wxToolBarToolBase *tool, bool enable) { ::SendMessage(GetHwnd(), TB_ENABLEBUTTON, (WPARAM)tool->GetId(), (LPARAM)MAKELONG(enable, 0)); } void wxToolBar::DoToggleTool(wxToolBarToolBase *tool, bool toggle) { ::SendMessage(GetHwnd(), TB_CHECKBUTTON, (WPARAM)tool->GetId(), (LPARAM)MAKELONG(toggle, 0)); } void wxToolBar::DoSetToggle(wxToolBarToolBase *WXUNUSED(tool), bool WXUNUSED(toggle)) { // VZ: AFAIK, the button has to be created either with TBSTYLE_CHECK or // without, so we really need to delete the button and recreate it here wxFAIL_MSG( _T("not implemented") ); } void wxToolBar::SetToolNormalBitmap( int id, const wxBitmap& bitmap ) { wxToolBarTool* tool = wx_static_cast(wxToolBarTool*, FindById(id)); if ( tool ) { wxCHECK_RET( tool->IsButton(), wxT("Can only set bitmap on button tools.")); tool->SetNormalBitmap(bitmap); Realize(); } } void wxToolBar::SetToolDisabledBitmap( int id, const wxBitmap& bitmap ) { wxToolBarTool* tool = wx_static_cast(wxToolBarTool*, FindById(id)); if ( tool ) { wxCHECK_RET( tool->IsButton(), wxT("Can only set bitmap on button tools.")); tool->SetDisabledBitmap(bitmap); Realize(); } } // ---------------------------------------------------------------------------- // event handlers // ---------------------------------------------------------------------------- // Responds to colour changes, and passes event on to children. void wxToolBar::OnSysColourChanged(wxSysColourChangedEvent& event) { wxRGBToColour(m_backgroundColour, ::GetSysColor(COLOR_BTNFACE)); // Remap the buttons Realize(); // Relayout the toolbar int nrows = m_maxRows; m_maxRows = 0; // otherwise SetRows() wouldn't do anything SetRows(nrows); Refresh(); // let the event propagate further event.Skip(); } void wxToolBar::OnMouseEvent(wxMouseEvent& event) { if (event.Leaving() && m_pInTool) { OnMouseEnter( -1 ); event.Skip(); return; } if ( event.RightDown() ) { // find the tool under the mouse wxCoord x = 0, y = 0; event.GetPosition(&x, &y); wxToolBarToolBase *tool = FindToolForPosition(x, y); OnRightClick(tool ? tool->GetId() : -1, x, y); } else { event.Skip(); } } // This handler is required to allow the toolbar to be set to a non-default // colour: for example, when it must blend in with a notebook page. void wxToolBar::OnEraseBackground(wxEraseEvent& event) { RECT rect = wxGetClientRect(GetHwnd()); HDC hdc = GetHdcOf((*event.GetDC())); int majorVersion, minorVersion; wxGetOsVersion(& majorVersion, & minorVersion); #if wxUSE_UXTHEME // we may need to draw themed colour so that we appear correctly on // e.g. notebook page under XP with themes but only do it if the parent // draws themed background itself if ( !UseBgCol() && !GetParent()->UseBgCol() ) { wxUxThemeEngine *theme = wxUxThemeEngine::GetIfActive(); if ( theme ) { HRESULT hr = theme->DrawThemeParentBackground(GetHwnd(), hdc, &rect); if ( hr == S_OK ) return; // it can also return S_FALSE which seems to simply say that it // didn't draw anything but no error really occurred if ( FAILED(hr) ) wxLogApiError(_T("DrawThemeParentBackground(toolbar)"), hr); } } // Only draw a rebar theme on Vista, since it doesn't jive so well with XP if ( !UseBgCol() && majorVersion >= 6 ) { wxUxThemeEngine *theme = wxUxThemeEngine::GetIfActive(); if ( theme ) { wxUxThemeHandle hTheme(this, L"REBAR"); RECT r; wxRect rect = GetClientRect(); wxCopyRectToRECT(rect, r); HRESULT hr = theme->DrawThemeBackground(hTheme, hdc, 0, 0, & r, NULL); if ( hr == S_OK ) return; // it can also return S_FALSE which seems to simply say that it // didn't draw anything but no error really occurred if ( FAILED(hr) ) wxLogApiError(_T("DrawThemeBackground(toolbar)"), hr); } } #endif // wxUSE_UXTHEME if ( UseBgCol() || (GetMSWToolbarStyle() & TBSTYLE_TRANSPARENT) ) { // do draw our background // // notice that this 'dumb' implementation may cause flicker for some of // the controls in which case they should intercept wxEraseEvent and // process it themselves somehow AutoHBRUSH hBrush(wxColourToRGB(GetBackgroundColour())); wxCHANGE_HDC_MAP_MODE(hdc, MM_TEXT); ::FillRect(hdc, &rect, hBrush); } else // we have no non default background colour { // let the system do it for us event.Skip(); } } bool wxToolBar::HandleSize(WXWPARAM WXUNUSED(wParam), WXLPARAM lParam) { // calculate our minor dimension ourselves - we're confusing the standard // logic (TB_AUTOSIZE) with our horizontal toolbars and other hacks RECT r; if ( ::SendMessage(GetHwnd(), TB_GETITEMRECT, 0, (LPARAM)&r) ) { int w, h; if ( IsVertical() ) { w = r.right - r.left; if ( m_maxRows ) { w *= (m_nButtons + m_maxRows - 1)/m_maxRows; } h = HIWORD(lParam); } else { w = LOWORD(lParam); if (HasFlag( wxTB_FLAT )) h = r.bottom - r.top - 3; else h = r.bottom - r.top; if ( m_maxRows ) { // FIXME: hardcoded separator line height... h += HasFlag(wxTB_NODIVIDER) ? 4 : 6; h *= m_maxRows; } } if ( MAKELPARAM(w, h) != lParam ) { // size really changed SetSize(w, h); } // message processed return true; } return false; } bool wxToolBar::HandlePaint(WXWPARAM wParam, WXLPARAM lParam) { // erase any dummy separators which were used // for aligning the controls if any here // first of all, are there any controls at all? wxToolBarToolsList::compatibility_iterator node; for ( node = m_tools.GetFirst(); node; node = node->GetNext() ) { if ( node->GetData()->IsControl() ) break; } if ( !node ) // no controls, nothing to erase return false; wxSize clientSize = GetClientSize(); int majorVersion, minorVersion; wxGetOsVersion(& majorVersion, & minorVersion); // prepare the DC on which we'll be drawing // prepare the DC on which we'll be drawing wxClientDC dc(this); dc.SetBrush(wxBrush(GetBackgroundColour(), wxSOLID)); dc.SetPen(*wxTRANSPARENT_PEN); RECT r; if ( !::GetUpdateRect(GetHwnd(), &r, FALSE) ) // nothing to redraw anyhow return false; wxRect rectUpdate; wxCopyRECTToRect(r, rectUpdate); dc.SetClippingRegion(rectUpdate); // draw the toolbar tools, separators &c normally wxControl::MSWWindowProc(WM_PAINT, wParam, lParam); // for each control in the toolbar find all the separators intersecting it // and erase them // // NB: this is really the only way to do it as we don't know if a separator // corresponds to a control (i.e. is a dummy one) or a real one // otherwise for ( node = m_tools.GetFirst(); node; node = node->GetNext() ) { wxToolBarToolBase *tool = node->GetData(); if ( tool->IsControl() ) { // get the control rect in our client coords wxControl *control = tool->GetControl(); wxRect rectCtrl = control->GetRect(); // iterate over all buttons TBBUTTON tbb; int count = ::SendMessage(GetHwnd(), TB_BUTTONCOUNT, 0, 0); for ( int n = 0; n < count; n++ ) { // is it a separator? if ( !::SendMessage(GetHwnd(), TB_GETBUTTON, n, (LPARAM)&tbb) ) { wxLogDebug(_T("TB_GETBUTTON failed?")); continue; } if ( tbb.fsStyle != TBSTYLE_SEP ) continue; // get the bounding rect of the separator RECT r; if ( !::SendMessage(GetHwnd(), TB_GETITEMRECT, n, (LPARAM)&r) ) { wxLogDebug(_T("TB_GETITEMRECT failed?")); continue; } // does it intersect the control? wxRect rectItem; wxCopyRECTToRect(r, rectItem); if ( rectCtrl.Intersects(rectItem) ) { // yes, do erase it! bool haveRefreshed = false; #if wxUSE_UXTHEME if ( !UseBgCol() && !GetParent()->UseBgCol() ) { // Don't use DrawThemeBackground } else if (!UseBgCol() && majorVersion >= 6 ) { wxUxThemeEngine *theme = wxUxThemeEngine::GetIfActive(); if ( theme ) { wxUxThemeHandle hTheme(this, L"REBAR"); RECT clipRect = r; // Draw the whole background since the pattern may be position sensitive; // but clip it to the area of interest. r.left = 0; r.right = clientSize.x; r.top = 0; r.bottom = clientSize.y; HRESULT hr = theme->DrawThemeBackground(hTheme, (HDC) dc.GetHDC(), 0, 0, & r, & clipRect); if ( hr == S_OK ) haveRefreshed = true; } } #endif if (!haveRefreshed) dc.DrawRectangle(rectItem); // Necessary in case we use a no-paint-on-size // style in the parent: the controls can disappear control->Refresh(false); } } } } return true; } void wxToolBar::HandleMouseMove(WXWPARAM WXUNUSED(wParam), WXLPARAM lParam) { wxCoord x = GET_X_LPARAM(lParam), y = GET_Y_LPARAM(lParam); wxToolBarToolBase* tool = FindToolForPosition( x, y ); // cursor left current tool if ( tool != m_pInTool && !tool ) { m_pInTool = 0; OnMouseEnter( -1 ); } // cursor entered a tool if ( tool != m_pInTool && tool ) { m_pInTool = tool; OnMouseEnter( tool->GetId() ); } } WXLRESULT wxToolBar::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam) { switch ( nMsg ) { case WM_MOUSEMOVE: // we don't handle mouse moves, so always pass the message to // wxControl::MSWWindowProc (HandleMouseMove just calls OnMouseEnter) HandleMouseMove(wParam, lParam); break; case WM_SIZE: if ( HandleSize(wParam, lParam) ) return 0; break; #ifndef __WXWINCE__ case WM_PAINT: if ( HandlePaint(wParam, lParam) ) return 0; #endif default: break; } return wxControl::MSWWindowProc(nMsg, wParam, lParam); } // ---------------------------------------------------------------------------- // private functions // ---------------------------------------------------------------------------- #ifdef wxREMAP_BUTTON_COLOURS WXHBITMAP wxToolBar::MapBitmap(WXHBITMAP bitmap, int width, int height) { MemoryHDC hdcMem; if ( !hdcMem ) { wxLogLastError(_T("CreateCompatibleDC")); return bitmap; } SelectInHDC bmpInHDC(hdcMem, (HBITMAP)bitmap); if ( !bmpInHDC ) { wxLogLastError(_T("SelectObject")); return bitmap; } wxCOLORMAP *cmap = wxGetStdColourMap(); for ( int i = 0; i < width; i++ ) { for ( int j = 0; j < height; j++ ) { COLORREF pixel = ::GetPixel(hdcMem, i, j); for ( size_t k = 0; k < wxSTD_COL_MAX; k++ ) { COLORREF col = cmap[k].from; if ( abs(GetRValue(pixel) - GetRValue(col)) < 10 && abs(GetGValue(pixel) - GetGValue(col)) < 10 && abs(GetBValue(pixel) - GetBValue(col)) < 10 ) { if ( cmap[k].to != pixel ) ::SetPixel(hdcMem, i, j, cmap[k].to); break; } } } } return bitmap; } #endif // wxREMAP_BUTTON_COLOURS #endif // wxUSE_TOOLBAR
radiaku/decoda
libs/wxWidgets/src/msw/tbar95.cpp
C++
gpl-3.0
58,053
/** Messages for Sinhala (සිංහල) * Exported from translatewiki.net * * Translators: * - Singhalawap */ var I18n = { on_leave_page: "ඔබගේ වෙනස්කිරීම් අහිමිවනු ඇත" };
railsfactory-sriman/knowledgeBase
public/javascripts/i18n/si.js
JavaScript
agpl-3.0
235
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nest { public class FieldDataFilterDescriptor { internal FieldDataFilter Filter { get; private set; } public FieldDataFilterDescriptor() { this.Filter = new FieldDataFilter(); } public FieldDataFilterDescriptor Frequency( Func<FieldDataFrequencyFilterDescriptor, FieldDataFrequencyFilterDescriptor> frequencyFilterSelector) { var selector = frequencyFilterSelector(new FieldDataFrequencyFilterDescriptor()); this.Filter.Frequency = selector.FrequencyFilter; return this; } public FieldDataFilterDescriptor Regex( Func<FieldDataRegexFilterDescriptor, FieldDataRegexFilterDescriptor> regexFilterSelector) { var selector = regexFilterSelector(new FieldDataRegexFilterDescriptor()); this.Filter.Regex = selector.RegexFilter; return this; } } }
amyzheng424/elasticsearch-net
src/Nest/Domain/Mapping/Descriptors/FieldDataFilterDescriptor.cs
C#
apache-2.0
893
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt. using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq.Expressions; namespace Sce.Atf.Controls.PropertyEditing { /// <summary> /// Helper to support INotifyPropertyChanged using expression trees and lambda expression.</summary> internal static class PropertyChangedExtensions { public static bool NotifyIfChanged<T>(this PropertyChangedEventHandler handler, ref T field, T value, Expression<Func<T>> memberExpression) { if (memberExpression == null) { throw new ArgumentNullException("memberExpression"); } var body = memberExpression.Body as MemberExpression; if (body == null) { throw new ArgumentException("Lambda must return a property."); } if (EqualityComparer<T>.Default.Equals(field, value)) { return false; } field = value; var vmExpression = body.Expression as ConstantExpression; if (vmExpression != null) { LambdaExpression lambda = Expression.Lambda(vmExpression); Delegate vmFunc = lambda.Compile(); object sender = vmFunc.DynamicInvoke(); if (handler != null) { handler(sender, new PropertyChangedEventArgs(body.Member.Name)); } } return true; } } }
jethac/ATF
Framework/Atf.Gui/Controls/PropertyEditing/PropertyChangedExtensions.cs
C#
apache-2.0
1,642
'use strict'; var utils = require('./utils'); var normalizeHeaderName = require('./helpers/normalizeHeaderName'); var PROTECTION_PREFIX = /^\)\]\}',?\n/; var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; function setContentTypeIfUnset(headers, value) { if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = value; } } module.exports = { transformRequest: [function transformRequest(data, headers) { normalizeHeaderName(headers, 'Content-Type'); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data) ) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isURLSearchParams(data)) { setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString(); } if (utils.isObject(data)) { setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); return JSON.stringify(data); } return data; }], transformResponse: [function transformResponse(data) { /*eslint no-param-reassign:0*/ if (typeof data === 'string') { data = data.replace(PROTECTION_PREFIX, ''); try { data = JSON.parse(data); } catch (e) { /* Ignore */ } } return data; }], headers: { common: { 'Accept': 'application/json, text/plain, */*' }, patch: utils.merge(DEFAULT_CONTENT_TYPE), post: utils.merge(DEFAULT_CONTENT_TYPE), put: utils.merge(DEFAULT_CONTENT_TYPE) }, timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; } };
MichaelTsao/yanpei
web/js/node_modules/leancloud-realtime/node_modules/axios/lib/defaults.js
JavaScript
bsd-3-clause
1,867
<?php function foo($foo, $bar, $foobar) {} ?>
drBenway/siteResearch
vendor/pdepend/pdepend/src/test/resources/files/issues/067/testParserHandlesParameterOptionalIsFalseForAllParameters_1.php
PHP
mit
46
package myrcpapp; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.part.ViewPart; public class View extends ViewPart { @Override public void createPartControl(final Composite parent) { Text text = new Text(parent, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); text.setText("Hello, world!"); } @Override public void setFocus() { } }
mcmil/wuff
examples/RcpApp-3/MyRcpApp/src/main/java/myrcpapp/View.java
Java
mit
435
module.exports = require('./lib/rework');
atomify/atomify-css
test/fixtures/css/node_modules/rework-clone/node_modules/rework/index.js
JavaScript
mit
42
<?php /* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Updated by Dan Lester 2014 * */ require_once realpath(dirname(__FILE__) . '/../../../autoload.php'); /** * Signs data with PEM key (e.g. taken from new JSON files). * * @author Dan Lester <dan@danlester.com> */ class GoogleGAL_Signer_PEM extends GoogleGAL_Signer_Abstract { // OpenSSL private key resource private $privateKey; // Creates a new signer from a PEM text string public function __construct($pem, $password) { if (!function_exists('openssl_x509_read')) { throw new GoogleGAL_Exception( 'The Google PHP API library needs the openssl PHP extension' ); } $this->privateKey = $pem; if (!$this->privateKey) { throw new GoogleGAL_Auth_Exception("Unable to load private key"); } } public function __destruct() { } public function sign($data) { if (version_compare(PHP_VERSION, '5.3.0') < 0) { throw new GoogleGAL_Auth_Exception( "PHP 5.3.0 or higher is required to use service accounts." ); } $hash = defined("OPENSSL_ALGO_SHA256") ? OPENSSL_ALGO_SHA256 : "sha256"; if (!openssl_sign($data, $signature, $this->privateKey, $hash)) { throw new GoogleGAL_Auth_Exception("Unable to sign data"); } return $signature; } }
nsberrow/pi.parklands.co.za
wp-content/plugins/googleappslogin-enterprise/core/Google/Signer/PEM.php
PHP
gpl-2.0
1,783
package introsde.document.ws; import introsde.document.model.LifeStatus; import introsde.document.model.Person; import java.util.List; import javax.jws.WebService; //Service Implementation @WebService(endpointInterface = "introsde.document.ws.People", serviceName="PeopleService") public class PeopleImpl implements People { @Override public Person readPerson(int id) { System.out.println("---> Reading Person by id = "+id); Person p = Person.getPersonById(id); if (p!=null) { System.out.println("---> Found Person by id = "+id+" => "+p.getName()); } else { System.out.println("---> Didn't find any Person with id = "+id); } return p; } @Override public List<Person> getPeople() { return Person.getAll(); } @Override public int addPerson(Person person) { Person.savePerson(person); return person.getIdPerson(); } @Override public int updatePerson(Person person) { Person.updatePerson(person); return person.getIdPerson(); } @Override public int deletePerson(int id) { Person p = Person.getPersonById(id); if (p!=null) { Person.removePerson(p); return 0; } else { return -1; } } @Override public int updatePersonHP(int id, LifeStatus hp) { LifeStatus ls = LifeStatus.getLifeStatusById(hp.getIdMeasure()); if (ls.getPerson().getIdPerson() == id) { LifeStatus.updateLifeStatus(hp); return hp.getIdMeasure(); } else { return -1; } } }
orlera/introsde
lab09/Server/src/introsde/document/ws/PeopleImpl.java
Java
gpl-3.0
1,425
/* * kmp_debug.cpp -- debug utilities for the Guide library */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "kmp.h" #include "kmp_debug.h" /* really necessary? */ #include "kmp_i18n.h" #include "kmp_io.h" #ifdef KMP_DEBUG void __kmp_debug_printf_stdout(char const *format, ...) { va_list ap; va_start(ap, format); __kmp_vprintf(kmp_out, format, ap); va_end(ap); } #endif void __kmp_debug_printf(char const *format, ...) { va_list ap; va_start(ap, format); __kmp_vprintf(kmp_err, format, ap); va_end(ap); } #ifdef KMP_USE_ASSERT int __kmp_debug_assert(char const *msg, char const *file, int line) { if (file == NULL) { file = KMP_I18N_STR(UnknownFile); } else { // Remove directories from path, leave only file name. File name is enough, // there is no need in bothering developers and customers with full paths. char const *slash = strrchr(file, '/'); if (slash != NULL) { file = slash + 1; } } #ifdef KMP_DEBUG __kmp_acquire_bootstrap_lock(&__kmp_stdio_lock); __kmp_debug_printf("Assertion failure at %s(%d): %s.\n", file, line, msg); __kmp_release_bootstrap_lock(&__kmp_stdio_lock); #ifdef USE_ASSERT_BREAK #if KMP_OS_WINDOWS DebugBreak(); #endif #endif // USE_ASSERT_BREAK #ifdef USE_ASSERT_STALL /* __kmp_infinite_loop(); */ for (;;) ; #endif // USE_ASSERT_STALL #ifdef USE_ASSERT_SEG { int volatile *ZERO = (int *)0; ++(*ZERO); } #endif // USE_ASSERT_SEG #endif __kmp_fatal(KMP_MSG(AssertionFailure, file, line), KMP_HNT(SubmitBugReport), __kmp_msg_null); return 0; } // __kmp_debug_assert #endif // KMP_USE_ASSERT /* Dump debugging buffer to stderr */ void __kmp_dump_debug_buffer(void) { if (__kmp_debug_buffer != NULL) { int i; int dc = __kmp_debug_count; char *db = &__kmp_debug_buffer[(dc % __kmp_debug_buf_lines) * __kmp_debug_buf_chars]; char *db_end = &__kmp_debug_buffer[__kmp_debug_buf_lines * __kmp_debug_buf_chars]; char *db2; __kmp_acquire_bootstrap_lock(&__kmp_stdio_lock); __kmp_printf_no_lock("\nStart dump of debugging buffer (entry=%d):\n", dc % __kmp_debug_buf_lines); for (i = 0; i < __kmp_debug_buf_lines; i++) { if (*db != '\0') { /* Fix up where no carriage return before string termination char */ for (db2 = db + 1; db2 < db + __kmp_debug_buf_chars - 1; db2++) { if (*db2 == '\0') { if (*(db2 - 1) != '\n') { *db2 = '\n'; *(db2 + 1) = '\0'; } break; } } /* Handle case at end by shortening the printed message by one char if * necessary */ if (db2 == db + __kmp_debug_buf_chars - 1 && *db2 == '\0' && *(db2 - 1) != '\n') { *(db2 - 1) = '\n'; } __kmp_printf_no_lock("%4d: %.*s", i, __kmp_debug_buf_chars, db); *db = '\0'; /* only let it print once! */ } db += __kmp_debug_buf_chars; if (db >= db_end) db = __kmp_debug_buffer; } __kmp_printf_no_lock("End dump of debugging buffer (entry=%d).\n\n", (dc + i - 1) % __kmp_debug_buf_lines); __kmp_release_bootstrap_lock(&__kmp_stdio_lock); } }
endlessm/chromium-browser
third_party/llvm/openmp/runtime/src/kmp_debug.cpp
C++
bsd-3-clause
3,628
// PR c++/82293 // { dg-do compile { target c++11 } } // { dg-options "-Wshadow" } template <typename> struct S { int f{[this](){return 42;}()}; }; int main(){ return S<int>{}.f; }
Gurgel100/gcc
gcc/testsuite/g++.dg/cpp0x/lambda/lambda-ice24.C
C++
gpl-2.0
187
/* * CommandWithArg.java * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.core.client; public interface CommandWithArg<T> { void execute(T arg); }
maligulzar/Rstudio-instrumented
src/gwt/src/org/rstudio/core/client/CommandWithArg.java
Java
agpl-3.0
682
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-7-c-ii-10.js * @description Array.prototype.some - callbackfn is called with 1 formal parameter */ function testcase() { function callbackfn(val) { return val > 10; } return [11, 12].some(callbackfn); } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.4/15.4.4/15.4.4.17/15.4.4.17-7-c-ii-10.js
JavaScript
bsd-3-clause
388
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-8-b-16.js * @description Array.prototype.map - decreasing length of array does not delete non-configurable properties */ function testcase() { function callbackfn(val, idx, obj) { if (idx === 2 && val === "unconfigurable") { return false; } else { return true; } } var arr = [0, 1, 2]; Object.defineProperty(arr, "2", { get: function () { return "unconfigurable"; }, configurable: false }); Object.defineProperty(arr, "1", { get: function () { arr.length = 2; return 1; }, configurable: true }); var testResult = arr.map(callbackfn); return testResult.length === 3 && testResult[2] === false; } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-8-b-16.js
JavaScript
bsd-3-clause
1,006
import { PlatformRef } from '@angular/core'; export * from './private_export_testing'; /** * @experimental API related to bootstrapping are still under review. */ export declare const platformBrowserDynamicTesting: (extraProviders?: any[]) => PlatformRef; /** * NgModule for testing. * * @stable */ export declare class BrowserDynamicTestingModule { } /** * @deprecated Use initTestEnvironment with platformBrowserDynamicTesting instead. */ export declare const TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS: Array<any>; /** * @deprecated Use initTestEnvironment with BrowserDynamicTestingModule instead. */ export declare const TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS: Array<any>;
oleksandr-minakov/northshore
ui/node_modules/@angular/platform-browser-dynamic/testing.d.ts
TypeScript
apache-2.0
689
// "Replace with Optional.ofNullable() chain" "GENERIC_ERROR_OR_WARNING" import java.util.Optional; class Test { interface V {} interface Type { V getValue(); } // IDEA-179273 public Optional<V> foo(Type arg) { return Optional.ofNullable(arg).map(Type::getValue); } }
siosio/intellij-community
java/java-tests/testData/inspection/conditionalCanBeOptional/afterOptionalReturn.java
Java
apache-2.0
291
<?php /* * The RandomLib library for securely generating random numbers and strings in PHP * * @author Anthony Ferrara <ircmaxell@ircmaxell.com> * @copyright 2011 The Authors * @license http://www.opensource.org/licenses/mit-license.html MIT License * @version Build @@version@@ */ namespace RandomLib\Mixer; use SecurityLib\Strength; class HashTest extends \PHPUnit_Framework_TestCase { public static function provideMix() { $data = array( array(array(), ''), array(array('1', '1'), '0d'), array(array('a'), '61'), // This expects 'b' because of how the mock hmac function works array(array('a', 'b'), '9a'), array(array('aa', 'ba'), '6e84'), array(array('ab', 'bb'), 'b0cb'), array(array('aa', 'bb'), 'ae8d'), array(array('aa', 'bb', 'cc'), 'a14c'), array(array('aabbcc', 'bbccdd', 'ccddee'), 'a8aff3939934'), ); return $data; } public function testConstructWithoutArgument() { $hash = new Hash(); $this->assertTrue($hash instanceof \RandomLib\Mixer); } public function testGetStrength() { $strength = new Strength(Strength::MEDIUM); $actual = Hash::getStrength(); $this->assertEquals($actual, $strength); } public function testTest() { $actual = Hash::test(); $this->assertTrue($actual); } /** * @dataProvider provideMix */ public function testMix($parts, $result) { $mixer = new Hash('md5'); $actual = $mixer->mix($parts); $this->assertEquals($result, bin2hex($actual)); } }
masmike/accu
vendor/ircmaxell/random-lib/test/Unit/RandomLib/Mixer/HashTest.php
PHP
mit
1,704
import { ThisSideUp32 } from "../../"; export = ThisSideUp32;
markogresak/DefinitelyTyped
types/carbon__icons-react/lib/this-side-up/32.d.ts
TypeScript
mit
63
import { SendToBack32 } from "../../"; export = SendToBack32;
markogresak/DefinitelyTyped
types/carbon__icons-react/lib/send-to-back/32.d.ts
TypeScript
mit
63
import { WindGusts24 } from "../../"; export = WindGusts24;
markogresak/DefinitelyTyped
types/carbon__icons-react/lib/wind-gusts/24.d.ts
TypeScript
mit
61
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.hbase; /** * Encapsulates the information for a delete operation. */ public class DeleteRequest { private byte[] rowId; private byte[] columnFamily; private byte[] columnQualifier; private String visibilityLabel; public DeleteRequest(byte[] rowId, byte[] columnFamily, byte[] columnQualifier, String visibilityLabel) { this.rowId = rowId; this.columnFamily = columnFamily; this.columnQualifier = columnQualifier; this.visibilityLabel = visibilityLabel; } public byte[] getRowId() { return rowId; } public byte[] getColumnFamily() { return columnFamily; } public byte[] getColumnQualifier() { return columnQualifier; } public String getVisibilityLabel() { return visibilityLabel; } @Override public String toString() { return new StringBuilder() .append(String.format("Row ID: %s\n", new String(rowId))) .append(String.format("Column Family: %s\n", new String(columnFamily))) .append(String.format("Column Qualifier: %s\n", new String(columnQualifier))) .append(visibilityLabel != null ? String.format("Visibility Label: %s", visibilityLabel) : "") .toString(); } }
ijokarumawak/nifi
nifi-nar-bundles/nifi-standard-services/nifi-hbase-client-service-api/src/main/java/org/apache/nifi/hbase/DeleteRequest.java
Java
apache-2.0
2,100
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <iomanip> // quoted #include <iomanip> #include <sstream> #include <string> #include <cassert> #if _LIBCPP_STD_VER > 11 bool is_skipws ( const std::istream *is ) { return ( is->flags() & std::ios_base::skipws ) != 0; } bool is_skipws ( const std::wistream *is ) { return ( is->flags() & std::ios_base::skipws ) != 0; } void both_ways ( const char *p ) { std::string str(p); auto q = std::quoted(str); std::stringstream ss; bool skippingws = is_skipws ( &ss ); ss << q; ss >> q; } void round_trip ( const char *p ) { std::stringstream ss; bool skippingws = is_skipws ( &ss ); ss << std::quoted(p); std::string s; ss >> std::quoted(s); assert ( s == p ); assert ( skippingws == is_skipws ( &ss )); } void round_trip_ws ( const char *p ) { std::stringstream ss; std::noskipws ( ss ); bool skippingws = is_skipws ( &ss ); ss << std::quoted(p); std::string s; ss >> std::quoted(s); assert ( s == p ); assert ( skippingws == is_skipws ( &ss )); } void round_trip_d ( const char *p, char delim ) { std::stringstream ss; ss << std::quoted(p, delim); std::string s; ss >> std::quoted(s, delim); assert ( s == p ); } void round_trip_e ( const char *p, char escape ) { std::stringstream ss; ss << std::quoted(p, '"', escape ); std::string s; ss >> std::quoted(s, '"', escape ); assert ( s == p ); } std::string quote ( const char *p, char delim='"', char escape='\\' ) { std::stringstream ss; ss << std::quoted(p, delim, escape); std::string s; ss >> s; // no quote return s; } std::string unquote ( const char *p, char delim='"', char escape='\\' ) { std::stringstream ss; ss << p; std::string s; ss >> std::quoted(s, delim, escape); return s; } void test_padding () { { std::stringstream ss; ss << std::left << std::setw(10) << std::setfill('!') << std::quoted("abc", '`'); assert ( ss.str() == "`abc`!!!!!" ); } { std::stringstream ss; ss << std::right << std::setw(10) << std::setfill('!') << std::quoted("abc", '`'); assert ( ss.str() == "!!!!!`abc`" ); } } void round_trip ( const wchar_t *p ) { std::wstringstream ss; bool skippingws = is_skipws ( &ss ); ss << std::quoted(p); std::wstring s; ss >> std::quoted(s); assert ( s == p ); assert ( skippingws == is_skipws ( &ss )); } void round_trip_ws ( const wchar_t *p ) { std::wstringstream ss; std::noskipws ( ss ); bool skippingws = is_skipws ( &ss ); ss << std::quoted(p); std::wstring s; ss >> std::quoted(s); assert ( s == p ); assert ( skippingws == is_skipws ( &ss )); } void round_trip_d ( const wchar_t *p, wchar_t delim ) { std::wstringstream ss; ss << std::quoted(p, delim); std::wstring s; ss >> std::quoted(s, delim); assert ( s == p ); } void round_trip_e ( const wchar_t *p, wchar_t escape ) { std::wstringstream ss; ss << std::quoted(p, wchar_t('"'), escape ); std::wstring s; ss >> std::quoted(s, wchar_t('"'), escape ); assert ( s == p ); } std::wstring quote ( const wchar_t *p, wchar_t delim='"', wchar_t escape='\\' ) { std::wstringstream ss; ss << std::quoted(p, delim, escape); std::wstring s; ss >> s; // no quote return s; } std::wstring unquote ( const wchar_t *p, wchar_t delim='"', wchar_t escape='\\' ) { std::wstringstream ss; ss << p; std::wstring s; ss >> std::quoted(s, delim, escape); return s; } int main() { both_ways ( "" ); // This is a compilation check round_trip ( "" ); round_trip_ws ( "" ); round_trip_d ( "", 'q' ); round_trip_e ( "", 'q' ); round_trip ( L"" ); round_trip_ws ( L"" ); round_trip_d ( L"", 'q' ); round_trip_e ( L"", 'q' ); round_trip ( "Hi" ); round_trip_ws ( "Hi" ); round_trip_d ( "Hi", '!' ); round_trip_e ( "Hi", '!' ); assert ( quote ( "Hi", '!' ) == "!Hi!" ); assert ( quote ( "Hi!", '!' ) == R"(!Hi\!!)" ); round_trip ( L"Hi" ); round_trip_ws ( L"Hi" ); round_trip_d ( L"Hi", '!' ); round_trip_e ( L"Hi", '!' ); assert ( quote ( L"Hi", '!' ) == L"!Hi!" ); assert ( quote ( L"Hi!", '!' ) == LR"(!Hi\!!)" ); round_trip ( "Hi Mom" ); round_trip_ws ( "Hi Mom" ); round_trip ( L"Hi Mom" ); round_trip_ws ( L"Hi Mom" ); assert ( quote ( "" ) == "\"\"" ); assert ( quote ( L"" ) == L"\"\"" ); assert ( quote ( "a" ) == "\"a\"" ); assert ( quote ( L"a" ) == L"\"a\"" ); // missing end quote - must not hang assert ( unquote ( "\"abc" ) == "abc" ); assert ( unquote ( L"\"abc" ) == L"abc" ); assert ( unquote ( "abc" ) == "abc" ); // no delimiter assert ( unquote ( L"abc" ) == L"abc" ); // no delimiter assert ( unquote ( "abc def" ) == "abc" ); // no delimiter assert ( unquote ( L"abc def" ) == L"abc" ); // no delimiter assert ( unquote ( "" ) == "" ); // nothing there assert ( unquote ( L"" ) == L"" ); // nothing there test_padding (); } #else int main() {} #endif
mxOBS/deb-pkg_trusty_chromium-browser
third_party/libc++/trunk/test/input.output/iostream.format/quoted.manip/quoted.pass.cpp
C++
bsd-3-clause
5,616
module.exports = function isString (value) { return Object.prototype.toString.call(value) === '[object String]' }
chrisdavidmills/express-local-library
node_modules/helmet-csp/lib/is-string.js
JavaScript
mit
116
import { Teammates } from "../../"; export = Teammates;
georgemarshall/DefinitelyTyped
types/carbon__pictograms-react/lib/teammates/index.d.ts
TypeScript
mit
57
package hclog import ( "bufio" "bytes" "encoding" "encoding/json" "fmt" "log" "os" "reflect" "runtime" "sort" "strconv" "strings" "sync" "sync/atomic" "time" ) var ( _levelToBracket = map[Level]string{ Debug: "[DEBUG]", Trace: "[TRACE]", Info: "[INFO] ", Warn: "[WARN] ", Error: "[ERROR]", } ) // Given the options (nil for defaults), create a new Logger func New(opts *LoggerOptions) Logger { if opts == nil { opts = &LoggerOptions{} } output := opts.Output if output == nil { output = os.Stderr } level := opts.Level if level == NoLevel { level = DefaultLevel } mtx := opts.Mutex if mtx == nil { mtx = new(sync.Mutex) } ret := &intLogger{ m: mtx, json: opts.JSONFormat, caller: opts.IncludeLocation, name: opts.Name, timeFormat: TimeFormat, w: bufio.NewWriter(output), level: new(int32), } if opts.TimeFormat != "" { ret.timeFormat = opts.TimeFormat } atomic.StoreInt32(ret.level, int32(level)) return ret } // The internal logger implementation. Internal in that it is defined entirely // by this package. type intLogger struct { json bool caller bool name string timeFormat string // this is a pointer so that it's shared by any derived loggers, since // those derived loggers share the bufio.Writer as well. m *sync.Mutex w *bufio.Writer level *int32 implied []interface{} } // Make sure that intLogger is a Logger var _ Logger = &intLogger{} // The time format to use for logging. This is a version of RFC3339 that // contains millisecond precision const TimeFormat = "2006-01-02T15:04:05.000Z0700" // Log a message and a set of key/value pairs if the given level is at // or more severe that the threshold configured in the Logger. func (z *intLogger) Log(level Level, msg string, args ...interface{}) { if level < Level(atomic.LoadInt32(z.level)) { return } t := time.Now() z.m.Lock() defer z.m.Unlock() if z.json { z.logJson(t, level, msg, args...) } else { z.log(t, level, msg, args...) } z.w.Flush() } // Cleanup a path by returning the last 2 segments of the path only. func trimCallerPath(path string) string { // lovely borrowed from zap // nb. To make sure we trim the path correctly on Windows too, we // counter-intuitively need to use '/' and *not* os.PathSeparator here, // because the path given originates from Go stdlib, specifically // runtime.Caller() which (as of Mar/17) returns forward slashes even on // Windows. // // See https://github.com/golang/go/issues/3335 // and https://github.com/golang/go/issues/18151 // // for discussion on the issue on Go side. // // Find the last separator. // idx := strings.LastIndexByte(path, '/') if idx == -1 { return path } // Find the penultimate separator. idx = strings.LastIndexByte(path[:idx], '/') if idx == -1 { return path } return path[idx+1:] } // Non-JSON logging format function func (z *intLogger) log(t time.Time, level Level, msg string, args ...interface{}) { z.w.WriteString(t.Format(z.timeFormat)) z.w.WriteByte(' ') s, ok := _levelToBracket[level] if ok { z.w.WriteString(s) } else { z.w.WriteString("[?????]") } if z.caller { if _, file, line, ok := runtime.Caller(3); ok { z.w.WriteByte(' ') z.w.WriteString(trimCallerPath(file)) z.w.WriteByte(':') z.w.WriteString(strconv.Itoa(line)) z.w.WriteByte(':') } } z.w.WriteByte(' ') if z.name != "" { z.w.WriteString(z.name) z.w.WriteString(": ") } z.w.WriteString(msg) args = append(z.implied, args...) var stacktrace CapturedStacktrace if args != nil && len(args) > 0 { if len(args)%2 != 0 { cs, ok := args[len(args)-1].(CapturedStacktrace) if ok { args = args[:len(args)-1] stacktrace = cs } else { args = append(args, "<unknown>") } } z.w.WriteByte(':') FOR: for i := 0; i < len(args); i = i + 2 { var ( val string raw bool ) switch st := args[i+1].(type) { case string: val = st case int: val = strconv.FormatInt(int64(st), 10) case int64: val = strconv.FormatInt(int64(st), 10) case int32: val = strconv.FormatInt(int64(st), 10) case int16: val = strconv.FormatInt(int64(st), 10) case int8: val = strconv.FormatInt(int64(st), 10) case uint: val = strconv.FormatUint(uint64(st), 10) case uint64: val = strconv.FormatUint(uint64(st), 10) case uint32: val = strconv.FormatUint(uint64(st), 10) case uint16: val = strconv.FormatUint(uint64(st), 10) case uint8: val = strconv.FormatUint(uint64(st), 10) case CapturedStacktrace: stacktrace = st continue FOR case Format: val = fmt.Sprintf(st[0].(string), st[1:]...) default: v := reflect.ValueOf(st) if v.Kind() == reflect.Slice { val = z.renderSlice(v) raw = true } else { val = fmt.Sprintf("%v", st) } } z.w.WriteByte(' ') z.w.WriteString(args[i].(string)) z.w.WriteByte('=') if !raw && strings.ContainsAny(val, " \t\n\r") { z.w.WriteByte('"') z.w.WriteString(val) z.w.WriteByte('"') } else { z.w.WriteString(val) } } } z.w.WriteString("\n") if stacktrace != "" { z.w.WriteString(string(stacktrace)) } } func (z *intLogger) renderSlice(v reflect.Value) string { var buf bytes.Buffer buf.WriteRune('[') for i := 0; i < v.Len(); i++ { if i > 0 { buf.WriteString(", ") } sv := v.Index(i) var val string switch sv.Kind() { case reflect.String: val = sv.String() case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64: val = strconv.FormatInt(sv.Int(), 10) case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: val = strconv.FormatUint(sv.Uint(), 10) default: val = fmt.Sprintf("%v", sv.Interface()) } if strings.ContainsAny(val, " \t\n\r") { buf.WriteByte('"') buf.WriteString(val) buf.WriteByte('"') } else { buf.WriteString(val) } } buf.WriteRune(']') return buf.String() } // JSON logging function func (z *intLogger) logJson(t time.Time, level Level, msg string, args ...interface{}) { vals := map[string]interface{}{ "@message": msg, "@timestamp": t.Format("2006-01-02T15:04:05.000000Z07:00"), } var levelStr string switch level { case Error: levelStr = "error" case Warn: levelStr = "warn" case Info: levelStr = "info" case Debug: levelStr = "debug" case Trace: levelStr = "trace" default: levelStr = "all" } vals["@level"] = levelStr if z.name != "" { vals["@module"] = z.name } if z.caller { if _, file, line, ok := runtime.Caller(3); ok { vals["@caller"] = fmt.Sprintf("%s:%d", file, line) } } args = append(z.implied, args...) if args != nil && len(args) > 0 { if len(args)%2 != 0 { cs, ok := args[len(args)-1].(CapturedStacktrace) if ok { args = args[:len(args)-1] vals["stacktrace"] = cs } else { args = append(args, "<unknown>") } } for i := 0; i < len(args); i = i + 2 { if _, ok := args[i].(string); !ok { // As this is the logging function not much we can do here // without injecting into logs... continue } val := args[i+1] switch sv := val.(type) { case error: // Check if val is of type error. If error type doesn't // implement json.Marshaler or encoding.TextMarshaler // then set val to err.Error() so that it gets marshaled switch sv.(type) { case json.Marshaler, encoding.TextMarshaler: default: val = sv.Error() } case Format: val = fmt.Sprintf(sv[0].(string), sv[1:]...) } vals[args[i].(string)] = val } } err := json.NewEncoder(z.w).Encode(vals) if err != nil { panic(err) } } // Emit the message and args at DEBUG level func (z *intLogger) Debug(msg string, args ...interface{}) { z.Log(Debug, msg, args...) } // Emit the message and args at TRACE level func (z *intLogger) Trace(msg string, args ...interface{}) { z.Log(Trace, msg, args...) } // Emit the message and args at INFO level func (z *intLogger) Info(msg string, args ...interface{}) { z.Log(Info, msg, args...) } // Emit the message and args at WARN level func (z *intLogger) Warn(msg string, args ...interface{}) { z.Log(Warn, msg, args...) } // Emit the message and args at ERROR level func (z *intLogger) Error(msg string, args ...interface{}) { z.Log(Error, msg, args...) } // Indicate that the logger would emit TRACE level logs func (z *intLogger) IsTrace() bool { return Level(atomic.LoadInt32(z.level)) == Trace } // Indicate that the logger would emit DEBUG level logs func (z *intLogger) IsDebug() bool { return Level(atomic.LoadInt32(z.level)) <= Debug } // Indicate that the logger would emit INFO level logs func (z *intLogger) IsInfo() bool { return Level(atomic.LoadInt32(z.level)) <= Info } // Indicate that the logger would emit WARN level logs func (z *intLogger) IsWarn() bool { return Level(atomic.LoadInt32(z.level)) <= Warn } // Indicate that the logger would emit ERROR level logs func (z *intLogger) IsError() bool { return Level(atomic.LoadInt32(z.level)) <= Error } // Return a sub-Logger for which every emitted log message will contain // the given key/value pairs. This is used to create a context specific // Logger. func (z *intLogger) With(args ...interface{}) Logger { if len(args)%2 != 0 { panic("With() call requires paired arguments") } var nz intLogger = *z result := make(map[string]interface{}, len(z.implied)+len(args)) keys := make([]string, 0, len(z.implied)+len(args)) // Read existing args, store map and key for consistent sorting for i := 0; i < len(z.implied); i += 2 { key := z.implied[i].(string) keys = append(keys, key) result[key] = z.implied[i+1] } // Read new args, store map and key for consistent sorting for i := 0; i < len(args); i += 2 { key := args[i].(string) _, exists := result[key] if !exists { keys = append(keys, key) } result[key] = args[i+1] } // Sort keys to be consistent sort.Strings(keys) nz.implied = make([]interface{}, 0, len(z.implied)+len(args)) for _, k := range keys { nz.implied = append(nz.implied, k) nz.implied = append(nz.implied, result[k]) } return &nz } // Create a new sub-Logger that a name decending from the current name. // This is used to create a subsystem specific Logger. func (z *intLogger) Named(name string) Logger { var nz intLogger = *z if nz.name != "" { nz.name = nz.name + "." + name } else { nz.name = name } return &nz } // Create a new sub-Logger with an explicit name. This ignores the current // name. This is used to create a standalone logger that doesn't fall // within the normal hierarchy. func (z *intLogger) ResetNamed(name string) Logger { var nz intLogger = *z nz.name = name return &nz } // Update the logging level on-the-fly. This will affect all subloggers as // well. func (z *intLogger) SetLevel(level Level) { atomic.StoreInt32(z.level, int32(level)) } // Create a *log.Logger that will send it's data through this Logger. This // allows packages that expect to be using the standard library log to actually // use this logger. func (z *intLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger { if opts == nil { opts = &StandardLoggerOptions{} } return log.New(&stdlogAdapter{z, opts.InferLevels}, "", 0) }
xanzy/terraform-provider-cosmic
vendor/github.com/hashicorp/go-hclog/int.go
GO
apache-2.0
11,348
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/usb/usb_chooser_context_factory.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/usb/usb_chooser_context.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" UsbChooserContextFactory::UsbChooserContextFactory() : BrowserContextKeyedServiceFactory( "UsbChooserContext", BrowserContextDependencyManager::GetInstance()) { DependsOn(HostContentSettingsMapFactory::GetInstance()); } UsbChooserContextFactory::~UsbChooserContextFactory() {} KeyedService* UsbChooserContextFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { return new UsbChooserContext(Profile::FromBrowserContext(context)); } // static UsbChooserContextFactory* UsbChooserContextFactory::GetInstance() { return base::Singleton<UsbChooserContextFactory>::get(); } // static UsbChooserContext* UsbChooserContextFactory::GetForProfile(Profile* profile) { return static_cast<UsbChooserContext*>( GetInstance()->GetServiceForBrowserContext(profile, true)); } content::BrowserContext* UsbChooserContextFactory::GetBrowserContextToUse( content::BrowserContext* context) const { return chrome::GetBrowserContextOwnInstanceInIncognito(context); }
endlessm/chromium-browser
chrome/browser/usb/usb_chooser_context_factory.cc
C++
bsd-3-clause
1,559
// Inspired from https://github.com/tsi/inlineDisqussions (function () { 'use strict'; var website = openerp.website, qweb = openerp.qweb; website.blog_discussion = openerp.Class.extend({ init: function(options) { var self = this ; self.discus_identifier; var defaults = { position: 'right', post_id: $('#blog_post_name').attr('data-blog-id'), content : false, public_user: false, }; self.settings = $.extend({}, defaults, options); // TODO: bundlify qweb templates website.add_template_file('/website_blog/static/src/xml/website_blog.inline.discussion.xml').then(function () { self.do_render(self); }); }, do_render: function(data) { var self = this; if ($('#discussions_wrapper').length === 0 && self.settings.content.length > 0) { $('<div id="discussions_wrapper"></div>').insertAfter($('#blog_content')); } // Attach a discussion to each paragraph. self.discussions_handler(self.settings.content); // Hide the discussion. $('html').click(function(event) { if($(event.target).parents('#discussions_wrapper, .main-discussion-link-wrp').length === 0) { self.hide_discussion(); } if(!$(event.target).hasClass('discussion-link') && !$(event.target).parents('.popover').length){ if($('.move_discuss').length){ $('[enable_chatter_discuss=True]').removeClass('move_discuss'); $('[enable_chatter_discuss=True]').animate({ 'marginLeft': "+=40%" }); $('#discussions_wrapper').animate({ 'marginLeft': "+=250px" }); } } }); }, prepare_data : function(identifier, comment_count) { var self = this; return openerp.jsonRpc("/blogpost/get_discussion/", 'call', { 'post_id': self.settings.post_id, 'path': identifier, 'count': comment_count, //if true only get length of total comment, display on discussion thread. }) }, prepare_multi_data : function(identifiers, comment_count) { var self = this; return openerp.jsonRpc("/blogpost/get_discussions/", 'call', { 'post_id': self.settings.post_id, 'paths': identifiers, 'count': comment_count, //if true only get length of total comment, display on discussion thread. }) }, discussions_handler: function() { var self = this; var node_by_id = {}; $(self.settings.content).each(function(i) { var node = $(this); var identifier = node.attr('data-chatter-id'); if (identifier) { node_by_id[identifier] = node; } }); self.prepare_multi_data(_.keys(node_by_id), true).then( function (multi_data) { _.forEach(multi_data, function(data) { self.prepare_discuss_link(data.val, data.path, node_by_id[data.path]); }); }); }, prepare_discuss_link : function(data, identifier, node) { var self = this; var cls = data > 0 ? 'discussion-link has-comments' : 'discussion-link'; var a = $('<a class="'+ cls +' css_editable_mode_hidden" />') .attr('data-discus-identifier', identifier) .attr('data-discus-position', self.settings.position) .text(data > 0 ? data : '+') .attr('data-contentwrapper', '.mycontent') .wrap('<div class="discussion" />') .parent() .appendTo('#discussions_wrapper'); a.css({ 'top': node.offset().top, 'left': self.settings.position == 'right' ? node.outerWidth() + node.offset().left: node.offset().left - a.outerWidth() }); // node.attr('data-discus-identifier', identifier) node.mouseover(function() { a.addClass("hovered"); }).mouseout(function() { a.removeClass("hovered"); }); a.delegate('a.discussion-link', "click", function(e) { e.preventDefault(); if(!$('.move_discuss').length){ $('[enable_chatter_discuss=True]').addClass('move_discuss'); $('[enable_chatter_discuss=True]').animate({ 'marginLeft': "-=40%" }); $('#discussions_wrapper').animate({ 'marginLeft': "-=250px" }); } if ($(this).is('.active')) { e.stopPropagation(); self.hide_discussion(); } else { self.get_discussion($(this), function(source) {}); } }); }, get_discussion : function(source, callback) { var self = this; var identifier = source.attr('data-discus-identifier'); self.hide_discussion(); self.discus_identifier = identifier; var elt = $('a[data-discus-identifier="'+identifier+'"]'); elt.append(qweb.render("website.blog_discussion.popover", {'identifier': identifier , 'options': self.settings})); var comment = ''; self.prepare_data(identifier,false).then(function(data){ _.each(data, function(res){ comment += qweb.render("website.blog_discussion.comment", {'res': res}); }); $('.discussion_history').html('<ul class="media-list">'+comment+'</ul>'); self.create_popover(elt, identifier); // Add 'active' class. $('a.discussion-link, a.main-discussion-link').removeClass('active').filter(source).addClass('active'); elt.popover('hide').filter(source).popover('show'); callback(source); }); }, create_popover : function(elt, identifier) { var self = this; elt.popover({ placement:'right', trigger:'manual', html:true, content:function(){ return $($(this).data('contentwrapper')).html(); } }).parent().delegate(self).on('click','button#comment_post',function(e) { e.stopImmediatePropagation(); self.post_discussion(identifier); }); }, validate : function(public_user){ var comment = $(".popover textarea#inline_comment").val(); if (public_user){ var author_name = $('.popover input#author_name').val(); var author_email = $('.popover input#author_email').val(); if(!comment || !author_name || !author_email){ if (!author_name) $('div#author_name').addClass('has-error'); else $('div#author_name').removeClass('has-error'); if (!author_email) $('div#author_email').addClass('has-error'); else $('div#author_email').removeClass('has-error'); if(!comment) $('div#inline_comment').addClass('has-error'); else $('div#inline_comment').removeClass('has-error'); return false } } else if(!comment) { $('div#inline_comment').addClass('has-error'); return false } $("div#inline_comment").removeClass('has-error'); $('div#author_name').removeClass('has-error'); $('div#author_email').removeClass('has-error'); $(".popover textarea#inline_comment").val(''); $('.popover input#author_name').val(''); $('.popover input#author_email').val(''); return [comment, author_name, author_email] }, post_discussion : function(identifier) { var self = this; var val = self.validate(self.settings.public_user) if(!val) return openerp.jsonRpc("/blogpost/post_discussion", 'call', { 'blog_post_id': self.settings.post_id, 'path': self.discus_identifier, 'comment': val[0], 'name' : val[1], 'email': val[2], }).then(function(res){ $(".popover ul.media-list").prepend(qweb.render("website.blog_discussion.comment", {'res': res[0]})) var ele = $('a[data-discus-identifier="'+ self.discus_identifier +'"]'); ele.text(_.isNaN(parseInt(ele.text())) ? 1 : parseInt(ele.text())+1) ele.addClass('has-comments'); }); }, hide_discussion : function() { var self = this; $('a[data-discus-identifier="'+ self.discus_identifier+'"]').popover('destroy'); $('a.discussion-link').removeClass('active'); } }); })();
jjscarafia/odoo
addons/website_blog/static/src/js/website_blog.inline.discussion.js
JavaScript
agpl-3.0
9,713
require 'formula' class Sratom < Formula homepage 'http://drobilla.net/software/sratom/' url 'http://download.drobilla.net/sratom-0.4.6.tar.bz2' sha1 '5f7d18e4917e5a2fee6eedc6ae06aa72d47fa52a' bottle do cellar :any sha256 "9023b8427d0e4068c7ca9e9a66a18545c51af3e30fcf9566db74aacceff18d2b" => :yosemite sha256 "9720a29b9fc95760edc5d96a36d89fee9a44403e0ce1cbe76fbf4a805c8c9571" => :mavericks sha256 "4b2acde2a46119ac0d6ae10a0d161b5f644e507296f44defc036ab311d93cf27" => :mountain_lion end depends_on 'pkg-config' => :build depends_on 'lv2' depends_on 'serd' depends_on 'sord' def install system "./waf", "configure", "--prefix=#{prefix}" system "./waf" system "./waf", "install" end end
robrix/homebrew
Library/Formula/sratom.rb
Ruby
bsd-2-clause
738
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using UICore; namespace SlimTuneUI.CoreVis { [DisplayName("Hotspots")] public partial class HotSpots : UserControl, IVisualizer { ProfilerWindowBase m_mainWindow; Connection m_connection; Snapshot m_snapshot; //drawing stuff Font m_functionFont = new Font(SystemFonts.DefaultFont.FontFamily, 12, FontStyle.Bold); Font m_objectFont = new Font(SystemFonts.DefaultFont.FontFamily, 9, FontStyle.Regular); class ListTag { public ListBox Right; public double TotalTime; } public event EventHandler Refreshed; public string DisplayName { get { return "Hotspots"; } } public UserControl Control { get { return this; } } public Snapshot Snapshot { get { return m_snapshot; } } public bool SupportsRefresh { get { return true; } } public HotSpots() { InitializeComponent(); HotspotsList.Tag = new ListTag(); } public bool Initialize(ProfilerWindowBase mainWindow, Connection connection, Snapshot snapshot) { if(mainWindow == null) throw new ArgumentNullException("mainWindow"); if(connection == null) throw new ArgumentNullException("connection"); m_mainWindow = mainWindow; m_connection = connection; m_snapshot = snapshot; UpdateHotspots(); return true; } public void OnClose() { } public void RefreshView() { var rightTag = HotspotsList.Tag as ListTag; if(rightTag != null) RemoveList(rightTag.Right); UpdateHotspots(); Utilities.FireEvent(this, Refreshed); } private void UpdateHotspots() { HotspotsList.Items.Clear(); using(var session = m_connection.DataEngine.OpenSession(m_snapshot.Id)) using(var tx = session.BeginTransaction()) { //find the total time consumed var totalQuery = session.CreateQuery("select sum(call.Time) from Call call where call.ChildId = 0"); var totalTimeFuture = totalQuery.FutureValue<double>(); //find the functions that consumed the most time-exclusive. These are hotspots. var query = session.CreateQuery("from Call c inner join fetch c.Parent where c.ChildId = 0 order by c.Time desc"); query.SetMaxResults(20); var hotspots = query.Future<Call>(); var totalTime = totalTimeFuture.Value; (HotspotsList.Tag as ListTag).TotalTime = totalTime; foreach(var call in hotspots) { if(call.Time / totalTime < 0.01f) { //less than 1% is not a hotspot, and since we're ordered by Time we can exit break; } HotspotsList.Items.Add(call); } tx.Commit(); } } private bool UpdateParents(Call child, ListBox box) { using(var session = m_connection.DataEngine.OpenSession(m_snapshot.Id)) using(var tx = session.BeginTransaction()) { var query = session.CreateQuery("from Call c inner join fetch c.Parent where c.ChildId = :funcId order by c.Time desc") .SetInt32("funcId", child.Parent.Id); var parents = query.List<Call>(); double totalTime = 0; foreach(var call in parents) { if(call.ParentId == 0) return false; totalTime += call.Time; box.Items.Add(call); } (box.Tag as ListTag).TotalTime = totalTime; tx.Commit(); } return true; } private void RefreshTimer_Tick(object sender, EventArgs e) { //UpdateHotspots(); } private void RemoveList(ListBox list) { if(list == null) return; RemoveList((list.Tag as ListTag).Right); ScrollPanel.Controls.Remove(list); } private void CallList_SelectedIndexChanged(object sender, EventArgs e) { ListBox list = sender as ListBox; RemoveList((list.Tag as ListTag).Right); //create a new listbox to the right ListBox lb = new ListBox(); lb.Size = list.Size; lb.Location = new Point(list.Right + 4, 4); lb.IntegralHeight = false; lb.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left; lb.FormattingEnabled = true; lb.DrawMode = DrawMode.OwnerDrawFixed; lb.ItemHeight = HotspotsList.ItemHeight; lb.Tag = new ListTag(); lb.Format += new ListControlConvertEventHandler(CallList_Format); lb.SelectedIndexChanged += new EventHandler(CallList_SelectedIndexChanged); lb.DrawItem += new DrawItemEventHandler(CallList_DrawItem); if(UpdateParents(list.SelectedItem as Call, lb)) { ScrollPanel.Controls.Add(lb); ScrollPanel.ScrollControlIntoView(lb); (list.Tag as ListTag).Right = lb; } } private void CallList_Format(object sender, ListControlConvertEventArgs e) { Call call = e.ListItem as Call; e.Value = call.Parent.Name; } private void CallList_DrawItem(object sender, DrawItemEventArgs e) { ListBox list = sender as ListBox; Call item = list.Items[e.Index] as Call; int splitIndex = item.Parent.Name.LastIndexOf('.'); string functionName = item.Parent.Name.Substring(splitIndex + 1); string objectName = "- " + item.Parent.Name.Substring(0, splitIndex); double percent = 100 * item.Time / (list.Tag as ListTag).TotalTime; string functionString = string.Format("{0:0.##}%: {1}", percent, functionName); Brush brush = Brushes.Black; if((e.State & DrawItemState.Selected) == DrawItemState.Selected) brush = Brushes.White; e.DrawBackground(); e.Graphics.DrawString(functionString, m_functionFont, brush, new PointF(e.Bounds.X, e.Bounds.Y)); e.Graphics.DrawString(objectName, m_objectFont, brush, new PointF(e.Bounds.X + 4, e.Bounds.Y + 18)); e.DrawFocusRectangle(); } } }
mohdmasd/slimtune
CoreVis/HotSpots.cs
C#
mit
5,633
// 2005-12-20 Paolo Carlini <pcarlini@suse.de> // Copyright (C) 2005-2013 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 23.2.1.3 deque::swap #include <deque> #include <testsuite_hooks.h> #include <testsuite_allocator.h> // uneq_allocator as a non-empty allocator. void test01() { bool test __attribute__((unused)) = true; using namespace std; typedef __gnu_test::uneq_allocator<char> my_alloc; typedef deque<char, my_alloc> my_deque; const char title01[] = "Rivers of sand"; const char title02[] = "Concret PH"; const char title03[] = "Sonatas and Interludes for Prepared Piano"; const char title04[] = "never as tired as when i'm waking up"; const size_t N1 = sizeof(title01); const size_t N2 = sizeof(title02); const size_t N3 = sizeof(title03); const size_t N4 = sizeof(title04); my_deque::size_type size01, size02; my_alloc alloc01(1); my_deque deq01(alloc01); size01 = deq01.size(); my_deque deq02(alloc01); size02 = deq02.size(); deq01.swap(deq02); VERIFY( deq01.size() == size02 ); VERIFY( deq01.empty() ); VERIFY( deq02.size() == size01 ); VERIFY( deq02.empty() ); my_deque deq03(alloc01); size01 = deq03.size(); my_deque deq04(title02, title02 + N2, alloc01); size02 = deq04.size(); deq03.swap(deq04); VERIFY( deq03.size() == size02 ); VERIFY( equal(deq03.begin(), deq03.end(), title02) ); VERIFY( deq04.size() == size01 ); VERIFY( deq04.empty() ); my_deque deq05(title01, title01 + N1, alloc01); size01 = deq05.size(); my_deque deq06(title02, title02 + N2, alloc01); size02 = deq06.size(); deq05.swap(deq06); VERIFY( deq05.size() == size02 ); VERIFY( equal(deq05.begin(), deq05.end(), title02) ); VERIFY( deq06.size() == size01 ); VERIFY( equal(deq06.begin(), deq06.end(), title01) ); my_deque deq07(title01, title01 + N1, alloc01); size01 = deq07.size(); my_deque deq08(title03, title03 + N3, alloc01); size02 = deq08.size(); deq07.swap(deq08); VERIFY( deq07.size() == size02 ); VERIFY( equal(deq07.begin(), deq07.end(), title03) ); VERIFY( deq08.size() == size01 ); VERIFY( equal(deq08.begin(), deq08.end(), title01) ); my_deque deq09(title03, title03 + N3, alloc01); size01 = deq09.size(); my_deque deq10(title04, title04 + N4, alloc01); size02 = deq10.size(); deq09.swap(deq10); VERIFY( deq09.size() == size02 ); VERIFY( equal(deq09.begin(), deq09.end(), title04) ); VERIFY( deq10.size() == size01 ); VERIFY( equal(deq10.begin(), deq10.end(), title03) ); my_deque deq11(title04, title04 + N4, alloc01); size01 = deq11.size(); my_deque deq12(title01, title01 + N1, alloc01); size02 = deq12.size(); deq11.swap(deq12); VERIFY( deq11.size() == size02 ); VERIFY( equal(deq11.begin(), deq11.end(), title01) ); VERIFY( deq12.size() == size01 ); VERIFY( equal(deq12.begin(), deq12.end(), title04) ); my_deque deq13(title03, title03 + N3, alloc01); size01 = deq13.size(); my_deque deq14(title03, title03 + N3, alloc01); size02 = deq14.size(); deq13.swap(deq14); VERIFY( deq13.size() == size02 ); VERIFY( equal(deq13.begin(), deq13.end(), title03) ); VERIFY( deq14.size() == size01 ); VERIFY( equal(deq14.begin(), deq14.end(), title03) ); } int main() { test01(); return 0; }
skristiansson/eco32-gcc
libstdc++-v3/testsuite/23_containers/deque/modifiers/swap/2.cc
C++
gpl-2.0
3,966
<?php require_once($CFG->libdir.'/simpletest/testportfoliolib.php'); require_once($CFG->dirroot.'/portfolio/download/lib.php'); /* * TODO: The portfolio unit tests were obselete and did not work. * They have been commented out so that they do not break the * unit tests in Moodle 2. * * At some point: * 1. These tests should be audited to see which ones were valuable. * 2. The useful ones should be rewritten using the current standards * for writing test cases. * * This might be left until Moodle 2.1 when the test case framework * is due to change. Mock::generate('boxclient', 'mock_boxclient'); Mock::generatePartial('portfolio_plugin_download', 'mock_downloadplugin', array('ensure_ticket', 'ensure_account_tree')); */ class testPortfolioPluginDownload extends portfoliolib_test { public static $includecoverage = array('lib/portfoliolib.php', 'portfolio/download/lib.php'); public function setUp() { parent::setUp(); // $this->plugin = new mock_boxnetplugin($this); // $this->plugin->boxclient = new mock_boxclient(); } public function tearDown() { parent::tearDown(); } }
dhamma-dev/SEA
web/portfolio/download/simpletest/testportfolioplugindownload.php
PHP
gpl-3.0
1,151
/********** 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. (See <http://www.gnu.org/copyleft/lesser.html>.) 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 **********/ // "liveMedia" // Copyright (c) 1996-2012 Live Networks, Inc. All rights reserved. // RTP sink for VP8 video // C++ header #ifndef _VP8_VIDEO_RTP_SINK_HH #define _VP8_VIDEO_RTP_SINK_HH #ifndef _VIDEO_RTP_SINK_HH #include "VideoRTPSink.hh" #endif class VP8VideoRTPSink: public VideoRTPSink { public: static VP8VideoRTPSink* createNew(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat); protected: VP8VideoRTPSink(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat); // called only by createNew() virtual ~VP8VideoRTPSink(); private: // redefined virtual functions: virtual void doSpecialFrameHandling(unsigned fragmentationOffset, unsigned char* frameStart, unsigned numBytesInFrame, struct timeval framePresentationTime, unsigned numRemainingBytes); virtual Boolean frameCanAppearAfterPacketStart(unsigned char const* frameStart, unsigned numBytesInFrame) const; virtual unsigned specialHeaderSize() const; }; #endif
hungld87/live555-for-win32
liveMedia/include/VP8VideoRTPSink.hh
C++
lgpl-2.1
1,917
// { dg-do assemble { target fpic } } // { dg-options "-O0 -fpic" } // Origin: Jakub Jelinek <jakub@redhat.com> struct bar { bar() {} double x[3]; }; static bar y[4]; void foo(int z) { bar w; y[z] = w; }
shaotuanchen/sunflower_exp
tools/source/gcc-4.2.4/gcc/testsuite/g++.old-deja/g++.other/local-alloc1.C
C++
bsd-3-clause
215
/** * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ 'use strict'; ( function() { var template = '<img alt="" src="" />', templateBlock = new CKEDITOR.template( '<figure class="{captionedClass}">' + template + '<figcaption>{captionPlaceholder}</figcaption>' + '</figure>' ), alignmentsObj = { left: 0, center: 1, right: 2 }, regexPercent = /^\s*(\d+\%)\s*$/i; CKEDITOR.plugins.add( 'image2', { // jscs:disable maximumLineLength lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,tt,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE% // jscs:enable maximumLineLength requires: 'widget,dialog', icons: 'image', hidpi: true, onLoad: function() { CKEDITOR.addCss( '.cke_image_nocaption{' + // This is to remove unwanted space so resize // wrapper is displayed property. 'line-height:0' + '}' + '.cke_editable.cke_image_sw, .cke_editable.cke_image_sw *{cursor:sw-resize !important}' + '.cke_editable.cke_image_se, .cke_editable.cke_image_se *{cursor:se-resize !important}' + '.cke_image_resizer{' + 'display:none;' + 'position:absolute;' + 'width:10px;' + 'height:10px;' + 'bottom:-5px;' + 'right:-5px;' + 'background:#000;' + 'outline:1px solid #fff;' + // Prevent drag handler from being misplaced (#11207). 'line-height:0;' + 'cursor:se-resize;' + '}' + '.cke_image_resizer_wrapper{' + 'position:relative;' + 'display:inline-block;' + 'line-height:0;' + '}' + // Bottom-left corner style of the resizer. '.cke_image_resizer.cke_image_resizer_left{' + 'right:auto;' + 'left:-5px;' + 'cursor:sw-resize;' + '}' + '.cke_widget_wrapper:hover .cke_image_resizer,' + '.cke_image_resizer.cke_image_resizing{' + 'display:block' + '}' + // Expand widget wrapper when linked inline image. '.cke_widget_wrapper>a{' + 'display:inline-block' + '}' ); }, init: function( editor ) { // Adapts configuration from original image plugin. Should be removed // when we'll rename image2 to image. var config = editor.config, lang = editor.lang.image2, image = widgetDef( editor ); // Since filebrowser plugin discovers config properties by dialog (plugin?) // names (sic!), this hack will be necessary as long as Image2 is not named // Image. And since Image2 will never be Image, for sure some filebrowser logic // got to be refined. config.filebrowserImage2BrowseUrl = config.filebrowserImageBrowseUrl; config.filebrowserImage2UploadUrl = config.filebrowserImageUploadUrl; // Add custom elementspath names to widget definition. image.pathName = lang.pathName; image.editables.caption.pathName = lang.pathNameCaption; // Register the widget. editor.widgets.add( 'image', image ); // Add toolbar button for this plugin. editor.ui.addButton && editor.ui.addButton( 'Image', { label: editor.lang.common.image, command: 'image', toolbar: 'insert,10' } ); // Register context menu option for editing widget. if ( editor.contextMenu ) { editor.addMenuGroup( 'image', 10 ); editor.addMenuItem( 'image', { label: lang.menu, command: 'image', group: 'image' } ); } CKEDITOR.dialog.add( 'image2', this.path + 'dialogs/image2.js' ); }, afterInit: function( editor ) { // Integrate with align commands (justify plugin). var align = { left: 1, right: 1, center: 1, block: 1 }, integrate = alignCommandIntegrator( editor ); for ( var value in align ) integrate( value ); // Integrate with link commands (link plugin). linkCommandIntegrator( editor ); } } ); // Wiget states (forms) depending on alignment and configuration. // // Non-captioned widget (inline styles) // ┌──────┬───────────────────────────────┬─────────────────────────────┐ // │Align │Internal form │Data │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │none │<wrapper> │<img /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │left │<wrapper style=”float:left”> │<img style=”float:left” /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │center│<wrapper> │<p style=”text-align:center”>│ // │ │ <p style=”text-align:center”> │ <img /> │ // │ │ <img /> │</p> │ // │ │ </p> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │right │<wrapper style=”float:right”> │<img style=”float:right” /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // └──────┴───────────────────────────────┴─────────────────────────────┘ // // Non-captioned widget (config.image2_alignClasses defined) // ┌──────┬───────────────────────────────┬─────────────────────────────┐ // │Align │Internal form │Data │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │none │<wrapper> │<img /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │left │<wrapper class=”left”> │<img class=”left” /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │center│<wrapper> │<p class=”center”> │ // │ │ <p class=”center”> │ <img /> │ // │ │ <img /> │</p> │ // │ │ </p> │ │ // │ │</wrapper> │ │ // ├──────┼───────────────────────────────┼─────────────────────────────┤ // │right │<wrapper class=”right”> │<img class=”right” /> │ // │ │ <img /> │ │ // │ │</wrapper> │ │ // └──────┴───────────────────────────────┴─────────────────────────────┘ // // Captioned widget (inline styles) // ┌──────┬────────────────────────────────────────┬────────────────────────────────────────┐ // │Align │Internal form │Data │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │none │<wrapper> │<figure /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │left │<wrapper style=”float:left”> │<figure style=”float:left” /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │center│<wrapper style=”text-align:center”> │<div style=”text-align:center”> │ // │ │ <figure style=”display:inline-block” />│ <figure style=”display:inline-block” />│ // │ │</wrapper> │</p> │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │right │<wrapper style=”float:right”> │<figure style=”float:right” /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // └──────┴────────────────────────────────────────┴────────────────────────────────────────┘ // // Captioned widget (config.image2_alignClasses defined) // ┌──────┬────────────────────────────────────────┬────────────────────────────────────────┐ // │Align │Internal form │Data │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │none │<wrapper> │<figure /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │left │<wrapper class=”left”> │<figure class=”left” /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │center│<wrapper class=”center”> │<div class=”center”> │ // │ │ <figure /> │ <figure /> │ // │ │</wrapper> │</p> │ // ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤ // │right │<wrapper class=”right”> │<figure class=”right” /> │ // │ │ <figure /> │ │ // │ │</wrapper> │ │ // └──────┴────────────────────────────────────────┴────────────────────────────────────────┘ // // @param {CKEDITOR.editor} // @returns {Object} function widgetDef( editor ) { var alignClasses = editor.config.image2_alignClasses, captionedClass = editor.config.image2_captionedClass; function deflate() { if ( this.deflated ) return; // Remember whether widget was focused before destroyed. if ( editor.widgets.focused == this.widget ) this.focused = true; editor.widgets.destroy( this.widget ); // Mark widget was destroyed. this.deflated = true; } function inflate() { var editable = editor.editable(), doc = editor.document; // Create a new widget. This widget will be either captioned // non-captioned, block or inline according to what is the // new state of the widget. if ( this.deflated ) { this.widget = editor.widgets.initOn( this.element, 'image', this.widget.data ); // Once widget was re-created, it may become an inline element without // block wrapper (i.e. when unaligned, end not captioned). Let's do some // sort of autoparagraphing here (#10853). if ( this.widget.inline && !( new CKEDITOR.dom.elementPath( this.widget.wrapper, editable ).block ) ) { var block = doc.createElement( editor.activeEnterMode == CKEDITOR.ENTER_P ? 'p' : 'div' ); block.replace( this.widget.wrapper ); this.widget.wrapper.move( block ); } // The focus must be transferred from the old one (destroyed) // to the new one (just created). if ( this.focused ) { this.widget.focus(); delete this.focused; } delete this.deflated; } // If now widget was destroyed just update wrapper's alignment. // According to the new state. else { setWrapperAlign( this.widget, alignClasses ); } } return { allowedContent: getWidgetAllowedContent( editor ), requiredContent: 'img[src,alt]', features: getWidgetFeatures( editor ), styleableElements: 'img figure', // This widget converts style-driven dimensions to attributes. contentTransformations: [ [ 'img[width]: sizeToAttribute' ] ], // This widget has an editable caption. editables: { caption: { selector: 'figcaption', allowedContent: 'br em strong sub sup u s; a[!href]' } }, parts: { image: 'img', caption: 'figcaption' // parts#link defined in widget#init }, // The name of this widget's dialog. dialog: 'image2', // Template of the widget: plain image. template: template, data: function() { var features = this.features; // Image can't be captioned when figcaption is disallowed (#11004). if ( this.data.hasCaption && !editor.filter.checkFeature( features.caption ) ) this.data.hasCaption = false; // Image can't be aligned when floating is disallowed (#11004). if ( this.data.align != 'none' && !editor.filter.checkFeature( features.align ) ) this.data.align = 'none'; // Convert the internal form of the widget from the old state to the new one. this.shiftState( { widget: this, element: this.element, oldData: this.oldData, newData: this.data, deflate: deflate, inflate: inflate } ); // Update widget.parts.link since it will not auto-update unless widget // is destroyed and re-inited. if ( !this.data.link ) { if ( this.parts.link ) delete this.parts.link; } else { if ( !this.parts.link ) this.parts.link = this.parts.image.getParent(); } this.parts.image.setAttributes( { src: this.data.src, // This internal is required by the editor. 'data-cke-saved-src': this.data.src, alt: this.data.alt } ); // If shifting non-captioned -> captioned, remove classes // related to styles from <img/>. if ( this.oldData && !this.oldData.hasCaption && this.data.hasCaption ) { for ( var c in this.data.classes ) this.parts.image.removeClass( c ); } // Set dimensions of the image according to gathered data. // Do it only when the attributes are allowed (#11004). if ( editor.filter.checkFeature( features.dimension ) ) setDimensions( this ); // Cache current data. this.oldData = CKEDITOR.tools.extend( {}, this.data ); }, init: function() { var helpers = CKEDITOR.plugins.image2, image = this.parts.image, data = { hasCaption: !!this.parts.caption, src: image.getAttribute( 'src' ), alt: image.getAttribute( 'alt' ) || '', width: image.getAttribute( 'width' ) || '', height: image.getAttribute( 'height' ) || '', // Lock ratio is on by default (#10833). lock: this.ready ? helpers.checkHasNaturalRatio( image ) : true }; // If we used 'a' in widget#parts definition, it could happen that // selected element is a child of widget.parts#caption. Since there's no clever // way to solve it with CSS selectors, it's done like that. (#11783). var link = image.getAscendant( 'a' ); if ( link && this.wrapper.contains( link ) ) this.parts.link = link; // Depending on configuration, read style/class from element and // then remove it. Removed style/class will be set on wrapper in #data listener. // Note: Center alignment is detected during upcast, so only left/right cases // are checked below. if ( !data.align ) { var alignElement = data.hasCaption ? this.element : image; // Read the initial left/right alignment from the class set on element. if ( alignClasses ) { if ( alignElement.hasClass( alignClasses[ 0 ] ) ) { data.align = 'left'; } else if ( alignElement.hasClass( alignClasses[ 2 ] ) ) { data.align = 'right'; } if ( data.align ) { alignElement.removeClass( alignClasses[ alignmentsObj[ data.align ] ] ); } else { data.align = 'none'; } } // Read initial float style from figure/image and then remove it. else { data.align = alignElement.getStyle( 'float' ) || 'none'; alignElement.removeStyle( 'float' ); } } // Update data.link object with attributes if the link has been discovered. if ( editor.plugins.link && this.parts.link ) { data.link = CKEDITOR.plugins.link.parseLinkAttributes( editor, this.parts.link ); // Get rid of cke_widget_* classes in data. Otherwise // they might appear in link dialog. var advanced = data.link.advanced; if ( advanced && advanced.advCSSClasses ) { advanced.advCSSClasses = CKEDITOR.tools.trim( advanced.advCSSClasses.replace( /cke_\S+/, '' ) ); } } // Get rid of extra vertical space when there's no caption. // It will improve the look of the resizer. this.wrapper[ ( data.hasCaption ? 'remove' : 'add' ) + 'Class' ]( 'cke_image_nocaption' ); this.setData( data ); // Setup dynamic image resizing with mouse. // Don't initialize resizer when dimensions are disallowed (#11004). if ( editor.filter.checkFeature( this.features.dimension ) && editor.config.image2_disableResizer !== true ) setupResizer( this ); this.shiftState = helpers.stateShifter( this.editor ); // Add widget editing option to its context menu. this.on( 'contextMenu', function( evt ) { evt.data.image = CKEDITOR.TRISTATE_OFF; // Integrate context menu items for link. // Note that widget may be wrapped in a link, which // does not belong to that widget (#11814). if ( this.parts.link || this.wrapper.getAscendant( 'a' ) ) evt.data.link = evt.data.unlink = CKEDITOR.TRISTATE_OFF; } ); // Pass the reference to this widget to the dialog. this.on( 'dialog', function( evt ) { evt.data.widget = this; }, this ); }, // Overrides default method to handle internal mutability of Image2. // @see CKEDITOR.plugins.widget#addClass addClass: function( className ) { getStyleableElement( this ).addClass( className ); }, // Overrides default method to handle internal mutability of Image2. // @see CKEDITOR.plugins.widget#hasClass hasClass: function( className ) { return getStyleableElement( this ).hasClass( className ); }, // Overrides default method to handle internal mutability of Image2. // @see CKEDITOR.plugins.widget#removeClass removeClass: function( className ) { getStyleableElement( this ).removeClass( className ); }, // Overrides default method to handle internal mutability of Image2. // @see CKEDITOR.plugins.widget#getClasses getClasses: ( function() { var classRegex = new RegExp( '^(' + [].concat( captionedClass, alignClasses ).join( '|' ) + ')$' ); return function() { var classes = this.repository.parseElementClasses( getStyleableElement( this ).getAttribute( 'class' ) ); // Neither config.image2_captionedClass nor config.image2_alignClasses // do not belong to style classes. for ( var c in classes ) { if ( classRegex.test( c ) ) delete classes[ c ]; } return classes; }; } )(), upcast: upcastWidgetElement( editor ), downcast: downcastWidgetElement( editor ) }; } CKEDITOR.plugins.image2 = { stateShifter: function( editor ) { // Tag name used for centering non-captioned widgets. var doc = editor.document, alignClasses = editor.config.image2_alignClasses, captionedClass = editor.config.image2_captionedClass, editable = editor.editable(), // The order that stateActions get executed. It matters! shiftables = [ 'hasCaption', 'align', 'link' ]; // Atomic procedures, one per state variable. var stateActions = { align: function( shift, oldValue, newValue ) { var el = shift.element; // Alignment changed. if ( shift.changed.align ) { // No caption in the new state. if ( !shift.newData.hasCaption ) { // Changed to "center" (non-captioned). if ( newValue == 'center' ) { shift.deflate(); shift.element = wrapInCentering( editor, el ); } // Changed to "non-center" from "center" while caption removed. if ( !shift.changed.hasCaption && oldValue == 'center' && newValue != 'center' ) { shift.deflate(); shift.element = unwrapFromCentering( el ); } } } // Alignment remains and "center" removed caption. else if ( newValue == 'center' && shift.changed.hasCaption && !shift.newData.hasCaption ) { shift.deflate(); shift.element = wrapInCentering( editor, el ); } // Finally set display for figure. if ( !alignClasses && el.is( 'figure' ) ) { if ( newValue == 'center' ) el.setStyle( 'display', 'inline-block' ); else el.removeStyle( 'display' ); } }, hasCaption: function( shift, oldValue, newValue ) { // This action is for real state change only. if ( !shift.changed.hasCaption ) return; // Get <img/> or <a><img/></a> from widget. Note that widget element might itself // be what we're looking for. Also element can be <p style="text-align:center"><a>...</a></p>. var imageOrLink; if ( shift.element.is( { img: 1, a: 1 } ) ) imageOrLink = shift.element; else imageOrLink = shift.element.findOne( 'a,img' ); // Switching hasCaption always destroys the widget. shift.deflate(); // There was no caption, but the caption is to be added. if ( newValue ) { // Create new <figure> from widget template. var figure = CKEDITOR.dom.element.createFromHtml( templateBlock.output( { captionedClass: captionedClass, captionPlaceholder: editor.lang.image2.captionPlaceholder } ), doc ); // Replace element with <figure>. replaceSafely( figure, shift.element ); // Use old <img/> or <a><img/></a> instead of the one from the template, // so we won't lose additional attributes. imageOrLink.replace( figure.findOne( 'img' ) ); // Update widget's element. shift.element = figure; } // The caption was present, but now it's to be removed. else { // Unwrap <img/> or <a><img/></a> from figure. imageOrLink.replace( shift.element ); // Update widget's element. shift.element = imageOrLink; } }, link: function( shift, oldValue, newValue ) { if ( shift.changed.link ) { var img = shift.element.is( 'img' ) ? shift.element : shift.element.findOne( 'img' ), link = shift.element.is( 'a' ) ? shift.element : shift.element.findOne( 'a' ), // Why deflate: // If element is <img/>, it will be wrapped into <a>, // which becomes a new widget.element. // If element is <a><img/></a>, it will be unlinked // so <img/> becomes a new widget.element. needsDeflate = ( shift.element.is( 'a' ) && !newValue ) || ( shift.element.is( 'img' ) && newValue ), newEl; if ( needsDeflate ) shift.deflate(); // If unlinked the image, returned element is <img>. if ( !newValue ) newEl = unwrapFromLink( link ); else { // If linked the image, returned element is <a>. if ( !oldValue ) newEl = wrapInLink( img, shift.newData.link ); // Set and remove all attributes associated with this state. var attributes = CKEDITOR.plugins.link.getLinkAttributes( editor, newValue ); if ( !CKEDITOR.tools.isEmpty( attributes.set ) ) ( newEl || link ).setAttributes( attributes.set ); if ( attributes.removed.length ) ( newEl || link ).removeAttributes( attributes.removed ); } if ( needsDeflate ) shift.element = newEl; } } }; function wrapInCentering( editor, element ) { var attribsAndStyles = {}; if ( alignClasses ) attribsAndStyles.attributes = { 'class': alignClasses[ 1 ] }; else attribsAndStyles.styles = { 'text-align': 'center' }; // There's no gentle way to center inline element with CSS, so create p/div // that wraps widget contents and does the trick either with style or class. var center = doc.createElement( editor.activeEnterMode == CKEDITOR.ENTER_P ? 'p' : 'div', attribsAndStyles ); // Replace element with centering wrapper. replaceSafely( center, element ); element.move( center ); return center; } function unwrapFromCentering( element ) { var imageOrLink = element.findOne( 'a,img' ); imageOrLink.replace( element ); return imageOrLink; } // Wraps <img/> -> <a><img/></a>. // Returns reference to <a>. // // @param {CKEDITOR.dom.element} img // @param {Object} linkData // @returns {CKEDITOR.dom.element} function wrapInLink( img, linkData ) { var link = doc.createElement( 'a', { attributes: { href: linkData.url } } ); link.replace( img ); img.move( link ); return link; } // De-wraps <a><img/></a> -> <img/>. // Returns the reference to <img/> // // @param {CKEDITOR.dom.element} link // @returns {CKEDITOR.dom.element} function unwrapFromLink( link ) { var img = link.findOne( 'img' ); img.replace( link ); return img; } function replaceSafely( replacing, replaced ) { if ( replaced.getParent() ) { var range = editor.createRange(); range.moveToPosition( replaced, CKEDITOR.POSITION_BEFORE_START ); // Remove old element. Do it before insertion to avoid a case when // element is moved from 'replaced' element before it, what creates // a tricky case which insertElementIntorRange does not handle. replaced.remove(); editable.insertElementIntoRange( replacing, range ); } else { replacing.replace( replaced ); } } return function( shift ) { var name, i; shift.changed = {}; for ( i = 0; i < shiftables.length; i++ ) { name = shiftables[ i ]; shift.changed[ name ] = shift.oldData ? shift.oldData[ name ] !== shift.newData[ name ] : false; } // Iterate over possible state variables. for ( i = 0; i < shiftables.length; i++ ) { name = shiftables[ i ]; stateActions[ name ]( shift, shift.oldData ? shift.oldData[ name ] : null, shift.newData[ name ] ); } shift.inflate(); }; }, // Checks whether current ratio of the image match the natural one. // by comparing dimensions. // @param {CKEDITOR.dom.element} image // @returns {Boolean} checkHasNaturalRatio: function( image ) { var $ = image.$, natural = this.getNatural( image ); // The reason for two alternative comparisons is that the rounding can come from // both dimensions, e.g. there are two cases: // 1. height is computed as a rounded relation of the real height and the value of width, // 2. width is computed as a rounded relation of the real width and the value of heigh. return Math.round( $.clientWidth / natural.width * natural.height ) == $.clientHeight || Math.round( $.clientHeight / natural.height * natural.width ) == $.clientWidth; }, // Returns natural dimensions of the image. For modern browsers // it uses natural(Width|Height) for old ones (IE8), creates // a new image and reads dimensions. // @param {CKEDITOR.dom.element} image // @returns {Object} getNatural: function( image ) { var dimensions; if ( image.$.naturalWidth ) { dimensions = { width: image.$.naturalWidth, height: image.$.naturalHeight }; } else { var img = new Image(); img.src = image.getAttribute( 'src' ); dimensions = { width: img.width, height: img.height }; } return dimensions; } }; function setWrapperAlign( widget, alignClasses ) { var wrapper = widget.wrapper, align = widget.data.align, hasCaption = widget.data.hasCaption; if ( alignClasses ) { // Remove all align classes first. for ( var i = 3; i--; ) wrapper.removeClass( alignClasses[ i ] ); if ( align == 'center' ) { // Avoid touching non-captioned, centered widgets because // they have the class set on the element instead of wrapper: // // <div class="cke_widget_wrapper"> // <p class="center-class"> // <img /> // </p> // </div> if ( hasCaption ) { wrapper.addClass( alignClasses[ 1 ] ); } } else if ( align != 'none' ) { wrapper.addClass( alignClasses[ alignmentsObj[ align ] ] ); } } else { if ( align == 'center' ) { if ( hasCaption ) wrapper.setStyle( 'text-align', 'center' ); else wrapper.removeStyle( 'text-align' ); wrapper.removeStyle( 'float' ); } else { if ( align == 'none' ) wrapper.removeStyle( 'float' ); else wrapper.setStyle( 'float', align ); wrapper.removeStyle( 'text-align' ); } } } // Returns a function that creates widgets from all <img> and // <figure class="{config.image2_captionedClass}"> elements. // // @param {CKEDITOR.editor} editor // @returns {Function} function upcastWidgetElement( editor ) { var isCenterWrapper = centerWrapperChecker( editor ), captionedClass = editor.config.image2_captionedClass; // @param {CKEDITOR.htmlParser.element} el // @param {Object} data return function( el, data ) { var dimensions = { width: 1, height: 1 }, name = el.name, image; // #11110 Don't initialize on pasted fake objects. if ( el.attributes[ 'data-cke-realelement' ] ) return; // If a center wrapper is found, there are 3 possible cases: // // 1. <div style="text-align:center"><figure>...</figure></div>. // In this case centering is done with a class set on widget.wrapper. // Simply replace centering wrapper with figure (it's no longer necessary). // // 2. <p style="text-align:center"><img/></p>. // Nothing to do here: <p> remains for styling purposes. // // 3. <div style="text-align:center"><img/></div>. // Nothing to do here (2.) but that case is only possible in enterMode different // than ENTER_P. if ( isCenterWrapper( el ) ) { if ( name == 'div' ) { var figure = el.getFirst( 'figure' ); // Case #1. if ( figure ) { el.replaceWith( figure ); el = figure; } } // Cases #2 and #3 (handled transparently) // If there's a centering wrapper, save it in data. data.align = 'center'; // Image can be wrapped in link <a><img/></a>. image = el.getFirst( 'img' ) || el.getFirst( 'a' ).getFirst( 'img' ); } // No center wrapper has been found. else if ( name == 'figure' && el.hasClass( captionedClass ) ) { image = el.getFirst( 'img' ) || el.getFirst( 'a' ).getFirst( 'img' ); // Upcast linked image like <a><img/></a>. } else if ( isLinkedOrStandaloneImage( el ) ) { image = el.name == 'a' ? el.children[ 0 ] : el; } if ( !image ) return; // If there's an image, then cool, we got a widget. // Now just remove dimension attributes expressed with %. for ( var d in dimensions ) { var dimension = image.attributes[ d ]; if ( dimension && dimension.match( regexPercent ) ) delete image.attributes[ d ]; } return el; }; } // Returns a function which transforms the widget to the external format // according to the current configuration. // // @param {CKEDITOR.editor} function downcastWidgetElement( editor ) { var alignClasses = editor.config.image2_alignClasses; // @param {CKEDITOR.htmlParser.element} el return function( el ) { // In case of <a><img/></a>, <img/> is the element to hold // inline styles or classes (image2_alignClasses). var attrsHolder = el.name == 'a' ? el.getFirst() : el, attrs = attrsHolder.attributes, align = this.data.align; // De-wrap the image from resize handle wrapper. // Only block widgets have one. if ( !this.inline ) { var resizeWrapper = el.getFirst( 'span' ); if ( resizeWrapper ) resizeWrapper.replaceWith( resizeWrapper.getFirst( { img: 1, a: 1 } ) ); } if ( align && align != 'none' ) { var styles = CKEDITOR.tools.parseCssText( attrs.style || '' ); // When the widget is captioned (<figure>) and internally centering is done // with widget's wrapper style/class, in the external data representation, // <figure> must be wrapped with an element holding an style/class: // // <div style="text-align:center"> // <figure class="image" style="display:inline-block">...</figure> // </div> // or // <div class="some-center-class"> // <figure class="image">...</figure> // </div> // if ( align == 'center' && el.name == 'figure' ) { el = el.wrapWith( new CKEDITOR.htmlParser.element( 'div', alignClasses ? { 'class': alignClasses[ 1 ] } : { style: 'text-align:center' } ) ); } // If left/right, add float style to the downcasted element. else if ( align in { left: 1, right: 1 } ) { if ( alignClasses ) attrsHolder.addClass( alignClasses[ alignmentsObj[ align ] ] ); else styles[ 'float' ] = align; } // Update element styles. if ( !alignClasses && !CKEDITOR.tools.isEmpty( styles ) ) attrs.style = CKEDITOR.tools.writeCssText( styles ); } return el; }; } // Returns a function that checks if an element is a centering wrapper. // // @param {CKEDITOR.editor} editor // @returns {Function} function centerWrapperChecker( editor ) { var captionedClass = editor.config.image2_captionedClass, alignClasses = editor.config.image2_alignClasses, validChildren = { figure: 1, a: 1, img: 1 }; return function( el ) { // Wrapper must be either <div> or <p>. if ( !( el.name in { div: 1, p: 1 } ) ) return false; var children = el.children; // Centering wrapper can have only one child. if ( children.length !== 1 ) return false; var child = children[ 0 ]; // Only <figure> or <img /> can be first (only) child of centering wrapper, // regardless of its type. if ( !( child.name in validChildren ) ) return false; // If centering wrapper is <p>, only <img /> can be the child. // <p style="text-align:center"><img /></p> if ( el.name == 'p' ) { if ( !isLinkedOrStandaloneImage( child ) ) return false; } // Centering <div> can hold <img/> or <figure>, depending on enterMode. else { // If a <figure> is the first (only) child, it must have a class. // <div style="text-align:center"><figure>...</figure><div> if ( child.name == 'figure' ) { if ( !child.hasClass( captionedClass ) ) return false; } else { // Centering <div> can hold <img/> or <a><img/></a> only when enterMode // is ENTER_(BR|DIV). // <div style="text-align:center"><img /></div> // <div style="text-align:center"><a><img /></a></div> if ( editor.enterMode == CKEDITOR.ENTER_P ) return false; // Regardless of enterMode, a child which is not <figure> must be // either <img/> or <a><img/></a>. if ( !isLinkedOrStandaloneImage( child ) ) return false; } } // Centering wrapper got to be... centering. If image2_alignClasses are defined, // check for centering class. Otherwise, check the style. if ( alignClasses ? el.hasClass( alignClasses[ 1 ] ) : CKEDITOR.tools.parseCssText( el.attributes.style || '', true )[ 'text-align' ] == 'center' ) return true; return false; }; } // Checks whether element is <img/> or <a><img/></a>. // // @param {CKEDITOR.htmlParser.element} function isLinkedOrStandaloneImage( el ) { if ( el.name == 'img' ) return true; else if ( el.name == 'a' ) return el.children.length == 1 && el.getFirst( 'img' ); return false; } // Sets width and height of the widget image according to current widget data. // // @param {CKEDITOR.plugins.widget} widget function setDimensions( widget ) { var data = widget.data, dimensions = { width: data.width, height: data.height }, image = widget.parts.image; for ( var d in dimensions ) { if ( dimensions[ d ] ) image.setAttribute( d, dimensions[ d ] ); else image.removeAttribute( d ); } } // Defines all features related to drag-driven image resizing. // // @param {CKEDITOR.plugins.widget} widget function setupResizer( widget ) { var editor = widget.editor, editable = editor.editable(), doc = editor.document, // Store the resizer in a widget for testing (#11004). resizer = widget.resizer = doc.createElement( 'span' ); resizer.addClass( 'cke_image_resizer' ); resizer.setAttribute( 'title', editor.lang.image2.resizer ); resizer.append( new CKEDITOR.dom.text( '\u200b', doc ) ); // Inline widgets don't need a resizer wrapper as an image spans the entire widget. if ( !widget.inline ) { var imageOrLink = widget.parts.link || widget.parts.image, oldResizeWrapper = imageOrLink.getParent(), resizeWrapper = doc.createElement( 'span' ); resizeWrapper.addClass( 'cke_image_resizer_wrapper' ); resizeWrapper.append( imageOrLink ); resizeWrapper.append( resizer ); widget.element.append( resizeWrapper, true ); // Remove the old wrapper which could came from e.g. pasted HTML // and which could be corrupted (e.g. resizer span has been lost). if ( oldResizeWrapper.is( 'span' ) ) oldResizeWrapper.remove(); } else { widget.wrapper.append( resizer ); } // Calculate values of size variables and mouse offsets. resizer.on( 'mousedown', function( evt ) { var image = widget.parts.image, // "factor" can be either 1 or -1. I.e.: For right-aligned images, we need to // subtract the difference to get proper width, etc. Without "factor", // resizer starts working the opposite way. factor = widget.data.align == 'right' ? -1 : 1, // The x-coordinate of the mouse relative to the screen // when button gets pressed. startX = evt.data.$.screenX, startY = evt.data.$.screenY, // The initial dimensions and aspect ratio of the image. startWidth = image.$.clientWidth, startHeight = image.$.clientHeight, ratio = startWidth / startHeight, listeners = [], // A class applied to editable during resizing. cursorClass = 'cke_image_s' + ( !~factor ? 'w' : 'e' ), nativeEvt, newWidth, newHeight, updateData, moveDiffX, moveDiffY, moveRatio; // Save the undo snapshot first: before resizing. editor.fire( 'saveSnapshot' ); // Mousemove listeners are removed on mouseup. attachToDocuments( 'mousemove', onMouseMove, listeners ); // Clean up the mousemove listener. Update widget data if valid. attachToDocuments( 'mouseup', onMouseUp, listeners ); // The entire editable will have the special cursor while resizing goes on. editable.addClass( cursorClass ); // This is to always keep the resizer element visible while resizing. resizer.addClass( 'cke_image_resizing' ); // Attaches an event to a global document if inline editor. // Additionally, if classic (`iframe`-based) editor, also attaches the same event to `iframe`'s document. function attachToDocuments( name, callback, collection ) { var globalDoc = CKEDITOR.document, listeners = []; if ( !doc.equals( globalDoc ) ) listeners.push( globalDoc.on( name, callback ) ); listeners.push( doc.on( name, callback ) ); if ( collection ) { for ( var i = listeners.length; i--; ) collection.push( listeners.pop() ); } } // Calculate with first, and then adjust height, preserving ratio. function adjustToX() { newWidth = startWidth + factor * moveDiffX; newHeight = Math.round( newWidth / ratio ); } // Calculate height first, and then adjust width, preserving ratio. function adjustToY() { newHeight = startHeight - moveDiffY; newWidth = Math.round( newHeight * ratio ); } // This is how variables refer to the geometry. // Note: x corresponds to moveOffset, this is the position of mouse // Note: o corresponds to [startX, startY]. // // +--------------+--------------+ // | | | // | I | II | // | | | // +------------- o -------------+ _ _ _ // | | | ^ // | VI | III | | moveDiffY // | | x _ _ _ _ _ v // +--------------+---------|----+ // | | // <-------> // moveDiffX function onMouseMove( evt ) { nativeEvt = evt.data.$; // This is how far the mouse is from the point the button was pressed. moveDiffX = nativeEvt.screenX - startX; moveDiffY = startY - nativeEvt.screenY; // This is the aspect ratio of the move difference. moveRatio = Math.abs( moveDiffX / moveDiffY ); // Left, center or none-aligned widget. if ( factor == 1 ) { if ( moveDiffX <= 0 ) { // Case: IV. if ( moveDiffY <= 0 ) adjustToX(); // Case: I. else { if ( moveRatio >= ratio ) adjustToX(); else adjustToY(); } } else { // Case: III. if ( moveDiffY <= 0 ) { if ( moveRatio >= ratio ) adjustToY(); else adjustToX(); } // Case: II. else { adjustToY(); } } } // Right-aligned widget. It mirrors behaviours, so I becomes II, // IV becomes III and vice-versa. else { if ( moveDiffX <= 0 ) { // Case: IV. if ( moveDiffY <= 0 ) { if ( moveRatio >= ratio ) adjustToY(); else adjustToX(); } // Case: I. else { adjustToY(); } } else { // Case: III. if ( moveDiffY <= 0 ) adjustToX(); // Case: II. else { if ( moveRatio >= ratio ) { adjustToX(); } else { adjustToY(); } } } } // Don't update attributes if less than 10. // This is to prevent images to visually disappear. if ( newWidth >= 15 && newHeight >= 15 ) { image.setAttributes( { width: newWidth, height: newHeight } ); updateData = true; } else { updateData = false; } } function onMouseUp() { var l; while ( ( l = listeners.pop() ) ) l.removeListener(); // Restore default cursor by removing special class. editable.removeClass( cursorClass ); // This is to bring back the regular behaviour of the resizer. resizer.removeClass( 'cke_image_resizing' ); if ( updateData ) { widget.setData( { width: newWidth, height: newHeight } ); // Save another undo snapshot: after resizing. editor.fire( 'saveSnapshot' ); } // Don't update data twice or more. updateData = false; } } ); // Change the position of the widget resizer when data changes. widget.on( 'data', function() { resizer[ widget.data.align == 'right' ? 'addClass' : 'removeClass' ]( 'cke_image_resizer_left' ); } ); } // Integrates widget alignment setting with justify // plugin's commands (execution and refreshment). // @param {CKEDITOR.editor} editor // @param {String} value 'left', 'right', 'center' or 'block' function alignCommandIntegrator( editor ) { var execCallbacks = [], enabled; return function( value ) { var command = editor.getCommand( 'justify' + value ); // Most likely, the justify plugin isn't loaded. if ( !command ) return; // This command will be manually refreshed along with // other commands after exec. execCallbacks.push( function() { command.refresh( editor, editor.elementPath() ); } ); if ( value in { right: 1, left: 1, center: 1 } ) { command.on( 'exec', function( evt ) { var widget = getFocusedWidget( editor ); if ( widget ) { widget.setData( 'align', value ); // Once the widget changed its align, all the align commands // must be refreshed: the event is to be cancelled. for ( var i = execCallbacks.length; i--; ) execCallbacks[ i ](); evt.cancel(); } } ); } command.on( 'refresh', function( evt ) { var widget = getFocusedWidget( editor ), allowed = { right: 1, left: 1, center: 1 }; if ( !widget ) return; // Cache "enabled" on first use. This is because filter#checkFeature may // not be available during plugin's afterInit in the future — a moment when // alignCommandIntegrator is called. if ( enabled === undefined ) enabled = editor.filter.checkFeature( editor.widgets.registered.image.features.align ); // Don't allow justify commands when widget alignment is disabled (#11004). if ( !enabled ) this.setState( CKEDITOR.TRISTATE_DISABLED ); else { this.setState( ( widget.data.align == value ) ? ( CKEDITOR.TRISTATE_ON ) : ( ( value in allowed ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED ) ); } evt.cancel(); } ); }; } function linkCommandIntegrator( editor ) { // Nothing to integrate with if link is not loaded. if ( !editor.plugins.link ) return; CKEDITOR.on( 'dialogDefinition', function( evt ) { var dialog = evt.data; if ( dialog.name == 'link' ) { var def = dialog.definition; var onShow = def.onShow, onOk = def.onOk; def.onShow = function() { var widget = getFocusedWidget( editor ); // Widget cannot be enclosed in a link, i.e. // <a>foo<inline widget/>bar</a> if ( widget && ( widget.inline ? !widget.wrapper.getAscendant( 'a' ) : 1 ) ) this.setupContent( widget.data.link || {} ); else onShow.apply( this, arguments ); }; // Set widget data if linking the widget using // link dialog (instead of default action). // State shifter handles data change and takes // care of internal DOM structure of linked widget. def.onOk = function() { var widget = getFocusedWidget( editor ); // Widget cannot be enclosed in a link, i.e. // <a>foo<inline widget/>bar</a> if ( widget && ( widget.inline ? !widget.wrapper.getAscendant( 'a' ) : 1 ) ) { var data = {}; // Collect data from fields. this.commitContent( data ); // Set collected data to widget. widget.setData( 'link', data ); } else { onOk.apply( this, arguments ); } }; } } ); // Overwrite default behaviour of unlink command. editor.getCommand( 'unlink' ).on( 'exec', function( evt ) { var widget = getFocusedWidget( editor ); // Override unlink only when link truly belongs to the widget. // If wrapped inline widget in a link, let default unlink work (#11814). if ( !widget || !widget.parts.link ) return; widget.setData( 'link', null ); // Selection (which is fake) may not change if unlinked image in focused widget, // i.e. if captioned image. Let's refresh command state manually here. this.refresh( editor, editor.elementPath() ); evt.cancel(); } ); // Overwrite default refresh of unlink command. editor.getCommand( 'unlink' ).on( 'refresh', function( evt ) { var widget = getFocusedWidget( editor ); if ( !widget ) return; // Note that widget may be wrapped in a link, which // does not belong to that widget (#11814). this.setState( widget.data.link || widget.wrapper.getAscendant( 'a' ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED ); evt.cancel(); } ); } // Returns the focused widget, if of the type specific for this plugin. // If no widget is focused, `null` is returned. // // @param {CKEDITOR.editor} // @returns {CKEDITOR.plugins.widget} function getFocusedWidget( editor ) { var widget = editor.widgets.focused; if ( widget && widget.name == 'image' ) return widget; return null; } // Returns a set of widget allowedContent rules, depending // on configurations like config#image2_alignClasses or // config#image2_captionedClass. // // @param {CKEDITOR.editor} // @returns {Object} function getWidgetAllowedContent( editor ) { var alignClasses = editor.config.image2_alignClasses, rules = { // Widget may need <div> or <p> centering wrapper. div: { match: centerWrapperChecker( editor ) }, p: { match: centerWrapperChecker( editor ) }, img: { attributes: '!src,alt,width,height' }, figure: { classes: '!' + editor.config.image2_captionedClass }, figcaption: true }; if ( alignClasses ) { // Centering class from the config. rules.div.classes = alignClasses[ 1 ]; rules.p.classes = rules.div.classes; // Left/right classes from the config. rules.img.classes = alignClasses[ 0 ] + ',' + alignClasses[ 2 ]; rules.figure.classes += ',' + rules.img.classes; } else { // Centering with text-align. rules.div.styles = 'text-align'; rules.p.styles = 'text-align'; rules.img.styles = 'float'; rules.figure.styles = 'float,display'; } return rules; } // Returns a set of widget feature rules, depending // on editor configuration. Note that the following may not cover // all the possible cases since requiredContent supports a single // tag only. // // @param {CKEDITOR.editor} // @returns {Object} function getWidgetFeatures( editor ) { var alignClasses = editor.config.image2_alignClasses, features = { dimension: { requiredContent: 'img[width,height]' }, align: { requiredContent: 'img' + ( alignClasses ? '(' + alignClasses[ 0 ] + ')' : '{float}' ) }, caption: { requiredContent: 'figcaption' } }; return features; } // Returns element which is styled, considering current // state of the widget. // // @see CKEDITOR.plugins.widget#applyStyle // @param {CKEDITOR.plugins.widget} widget // @returns {CKEDITOR.dom.element} function getStyleableElement( widget ) { return widget.data.hasCaption ? widget.element : widget.parts.image; } } )(); /** * A CSS class applied to the `<figure>` element of a captioned image. * * // Changes the class to "captionedImage". * config.image2_captionedClass = 'captionedImage'; * * @cfg {String} [image2_captionedClass='image'] * @member CKEDITOR.config */ CKEDITOR.config.image2_captionedClass = 'image'; /** * Determines whether dimension inputs should be automatically filled when the image URL changes in the Enhanced Image * plugin dialog window. * * config.image2_prefillDimensions = false; * * @since 4.5 * @cfg {Boolean} [image2_prefillDimensions=true] * @member CKEDITOR.config */ /** * Disables the image resizer. By default the resizer is enabled. * * config.image2_disableResizer = true; * * @since 4.5 * @cfg {Boolean} [image2_disableResizer=false] * @member CKEDITOR.config */ /** * CSS classes applied to aligned images. Useful to take control over the way * the images are aligned, i.e. to customize output HTML and integrate external stylesheets. * * Classes should be defined in an array of three elements, containing left, center, and right * alignment classes, respectively. For example: * * config.image2_alignClasses = [ 'align-left', 'align-center', 'align-right' ]; * * **Note**: Once this configuration option is set, the plugin will no longer produce inline * styles for alignment. It means that e.g. the following HTML will be produced: * * <img alt="My image" class="custom-center-class" src="foo.png" /> * * instead of: * * <img alt="My image" style="float:left" src="foo.png" /> * * **Note**: Once this configuration option is set, corresponding style definitions * must be supplied to the editor: * * * For [classic editor](#!/guide/dev_framed) it can be done by defining additional * styles in the {@link CKEDITOR.config#contentsCss stylesheets loaded by the editor}. The same * styles must be provided on the target page where the content will be loaded. * * For [inline editor](#!/guide/dev_inline) the styles can be defined directly * with `<style> ... <style>` or `<link href="..." rel="stylesheet">`, i.e. within the `<head>` * of the page. * * For example, considering the following configuration: * * config.image2_alignClasses = [ 'align-left', 'align-center', 'align-right' ]; * * CSS rules can be defined as follows: * * .align-left { * float: left; * } * * .align-right { * float: right; * } * * .align-center { * text-align: center; * } * * .align-center > figure { * display: inline-block; * } * * @since 4.4 * @cfg {String[]} [image2_alignClasses=null] * @member CKEDITOR.config */
quepasso/dashboard
web/bundles/ivoryckeditor/plugins/image2/plugin.js
JavaScript
mit
58,206
using Microsoft.IdentityModel.Clients.ActiveDirectory; using Office365Api.Graph.Simple.MailAndFiles.Helpers; using Office365Api.Graph.Simple.MailAndFiles.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace Office365Api.Graph.Simple.MailAndFiles.Controllers { public class HomeController : Controller { // The URL that auth should redirect to after a successful login. Uri loginRedirectUri => new Uri(Url.Action(nameof(Authorize), "Home", null, Request.Url.Scheme)); // The URL to redirect to after a logout. Uri logoutRedirectUri => new Uri(Url.Action(nameof(Index), "Home", null, Request.Url.Scheme)); public ActionResult Index() { // Let's get the user details from the session, stored when user was signed in. if (Session[Helpers.SessionKeys.Login.UserInfo] != null) { ViewBag.Name = (Session[Helpers.SessionKeys.Login.UserInfo] as UserInformation).Name; } return View(); } public ActionResult Logout() { Session.Clear(); return Redirect(Settings.LogoutAuthority + logoutRedirectUri.ToString()); } public ActionResult Login() { if (string.IsNullOrEmpty(Settings.ClientId) || string.IsNullOrEmpty(Settings.ClientSecret)) { ViewBag.Message = "Please set your client ID and client secret in the Web.config file"; return View(); } var authContext = new AuthenticationContext(Settings.AzureADAuthority); // Generate the parameterized URL for Azure login. Uri authUri = authContext.GetAuthorizationRequestURL( Settings.O365UnifiedAPIResource, Settings.ClientId, loginRedirectUri, UserIdentifier.AnyUser, null); // Redirect the browser to the login page, then come back to the Authorize method below. return Redirect(authUri.ToString()); } public async Task<ActionResult> Authorize() { var authContext = new AuthenticationContext(Settings.AzureADAuthority); // Get the token. var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync( Request.Params["code"], // the auth 'code' parameter from the Azure redirect. loginRedirectUri, // same redirectUri as used before in Login method. new ClientCredential(Settings.ClientId, Settings.ClientSecret), // use the client ID and secret to establish app identity. Settings.O365UnifiedAPIResource); // Save the token in the session. Session[SessionKeys.Login.AccessToken] = authResult.AccessToken; // Get info about the current logged in user. Session[SessionKeys.Login.UserInfo] = await GraphHelper.GetUserInfoAsync(authResult.AccessToken); return RedirectToAction(nameof(Index), "PersonalData"); } } }
yagoto/PnP
Samples/MicrosoftGraph.Office365.Simple.MailAndFiles/Office365Api.Graph.Simple.MailAndFiles/Controllers/HomeController.cs
C#
mit
3,267
from random import shuffle def bogosort(arr): while not sorted(arr) == arr: shuffle(arr) return arr
warreee/Algorithm-Implementations
Bogosort/Python/jcla1/bogosort.py
Python
mit
116
export { VolumeMuteFilled16 as default } from "../../";
markogresak/DefinitelyTyped
types/carbon__icons-react/es/volume--mute--filled/16.d.ts
TypeScript
mit
56
<?php require_once('HTML/QuickForm/submit.php'); /** * HTML class for a submit type element * * @author Jamie Pratt * @access public */ class MoodleQuickForm_cancel extends MoodleQuickForm_submit { // {{{ constructor /** * Class constructor * * @since 1.0 * @access public * @return void */ function MoodleQuickForm_cancel($elementName=null, $value=null, $attributes=null) { if ($elementName==null){ $elementName='cancel'; } if ($value==null){ $value=get_string('cancel'); } MoodleQuickForm_submit::MoodleQuickForm_submit($elementName, $value, $attributes); $this->updateAttributes(array('onclick'=>'skipClientValidation = true; return true;')); } //end constructor function onQuickFormEvent($event, $arg, &$caller) { switch ($event) { case 'createElement': $className = get_class($this); $this->$className($arg[0], $arg[1], $arg[2]); $caller->_registerCancelButton($this->getName()); return true; break; } return parent::onQuickFormEvent($event, $arg, $caller); } // end func onQuickFormEvent function getFrozenHtml(){ return HTML_QuickForm_submit::getFrozenHtml(); } function freeze(){ return HTML_QuickForm_submit::freeze(); } // }}} } //end class MoodleQuickForm_cancel ?>
feniix/moodle
lib/form/cancel.php
PHP
gpl-2.0
1,501
package teammates.test.pageobjects; public class EntityNotFoundPage extends AppPage { public EntityNotFoundPage(Browser browser) { super(browser); } @Override protected boolean containsExpectedPageContents() { return getPageSource().contains("TEAMMATES could not locate what you were trying to access."); } }
LiHaoTan/teammates
src/test/java/teammates/test/pageobjects/EntityNotFoundPage.java
Java
gpl-2.0
349
/* * Copyright (c) 2015, 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. 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. */ package jdk.nashorn.test.models; /** * Simple function interface with a varargs SAM method. */ @FunctionalInterface public interface VarArgConsumer { public void apply(Object... o); }
FauxFaux/jdk9-nashorn
test/src/jdk/nashorn/test/models/VarArgConsumer.java
Java
gpl-2.0
1,400
/** * 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.hadoop.hbase.regionserver.compactions; import java.util.List; import org.apache.hadoop.hbase.regionserver.StoreFile; public abstract class StoreFileListGenerator extends MockStoreFileGenerator implements Iterable<List<StoreFile>> { public static final int MAX_FILE_GEN_ITERS = 10; public static final int NUM_FILES_GEN = 1000; StoreFileListGenerator(final Class klass) { super(klass); } }
Guavus/hbase
hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/compactions/StoreFileListGenerator.java
Java
apache-2.0
1,237
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.schema.validation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.apache.nifi.serialization.record.validation.SchemaValidationResult; import org.apache.nifi.serialization.record.validation.ValidationError; public class StandardSchemaValidationResult implements SchemaValidationResult { private final List<ValidationError> validationErrors = new ArrayList<>(); @Override public boolean isValid() { return validationErrors.isEmpty(); } @Override public Collection<ValidationError> getValidationErrors() { return Collections.unmodifiableList(validationErrors); } public void addValidationError(final ValidationError validationError) { this.validationErrors.add(validationError); } }
mcgilman/nifi
nifi-nar-bundles/nifi-extension-utils/nifi-record-utils/nifi-standard-record-utils/src/main/java/org/apache/nifi/schema/validation/StandardSchemaValidationResult.java
Java
apache-2.0
1,648
module.exports = function(client, test) { test.ok(typeof client == 'object'); this.testPageAction = function() { return this; }; };
miguelangel6/nightwatchbamboo
tests/extra/pageobjects/SimplePageFn.js
JavaScript
mit
142
package builder import ( "os" "github.com/spf13/cobra" kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "github.com/openshift/origin/pkg/build/builder/cmd" ocmd "github.com/openshift/origin/pkg/cmd/cli/cmd" "github.com/openshift/origin/pkg/cmd/templates" ) var ( s2iBuilderLong = templates.LongDesc(` Perform a Source-to-Image build This command executes a Source-to-Image build using arguments passed via the environment. It expects to be run inside of a container.`) dockerBuilderLong = templates.LongDesc(` Perform a Docker build This command executes a Docker build using arguments passed via the environment. It expects to be run inside of a container.`) ) // NewCommandS2IBuilder provides a CLI handler for S2I build type func NewCommandS2IBuilder(name string) *cobra.Command { cmd := &cobra.Command{ Use: name, Short: "Run a Source-to-Image build", Long: s2iBuilderLong, Run: func(c *cobra.Command, args []string) { err := cmd.RunS2IBuild(c.OutOrStderr()) kcmdutil.CheckErr(err) }, } cmd.AddCommand(ocmd.NewCmdVersion(name, nil, os.Stdout, ocmd.VersionOptions{})) return cmd } // NewCommandDockerBuilder provides a CLI handler for Docker build type func NewCommandDockerBuilder(name string) *cobra.Command { cmd := &cobra.Command{ Use: name, Short: "Run a Docker build", Long: dockerBuilderLong, Run: func(c *cobra.Command, args []string) { err := cmd.RunDockerBuild(c.OutOrStderr()) kcmdutil.CheckErr(err) }, } cmd.AddCommand(ocmd.NewCmdVersion(name, nil, os.Stdout, ocmd.VersionOptions{})) return cmd }
rawlingsj/gofabric8
vendor/github.com/openshift/origin/pkg/cmd/infra/builder/builder.go
GO
apache-2.0
1,590
// runoutput // Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import "fmt" // Check that expressions like (c*n + d*(n+k)) get correctly merged by // the compiler into (c+d)*n + d*k (with c+d and d*k computed at // compile time). // // The merging is performed by a combination of the multiplication // merge rules // (c*n + d*n) -> (c+d)*n // and the distributive multiplication rules // c * (d+x) -> c*d + c*x // Generate a MergeTest that looks like this: // // a8, b8 = m1*n8 + m2*(n8+k), (m1+m2)*n8 + m2*k // if a8 != b8 { // // print error msg and panic // } func makeMergeAddTest(m1, m2, k int, size string) string { model := " a" + size + ", b" + size model += fmt.Sprintf(" = %%d*n%s + %%d*(n%s+%%d), (%%d+%%d)*n%s + (%%d*%%d)", size, size, size) test := fmt.Sprintf(model, m1, m2, k, m1, m2, m2, k) test += fmt.Sprintf(` if a%s != b%s { fmt.Printf("MergeAddTest(%d, %d, %d, %s) failed\n") fmt.Printf("%%d != %%d\n", a%s, b%s) panic("FAIL") } `, size, size, m1, m2, k, size, size, size) return test + "\n" } // Check that expressions like (c*n - d*(n+k)) get correctly merged by // the compiler into (c-d)*n - d*k (with c-d and d*k computed at // compile time). // // The merging is performed by a combination of the multiplication // merge rules // (c*n - d*n) -> (c-d)*n // and the distributive multiplication rules // c * (d-x) -> c*d - c*x // Generate a MergeTest that looks like this: // // a8, b8 = m1*n8 - m2*(n8+k), (m1-m2)*n8 - m2*k // if a8 != b8 { // // print error msg and panic // } func makeMergeSubTest(m1, m2, k int, size string) string { model := " a" + size + ", b" + size model += fmt.Sprintf(" = %%d*n%s - %%d*(n%s+%%d), (%%d-%%d)*n%s - (%%d*%%d)", size, size, size) test := fmt.Sprintf(model, m1, m2, k, m1, m2, m2, k) test += fmt.Sprintf(` if a%s != b%s { fmt.Printf("MergeSubTest(%d, %d, %d, %s) failed\n") fmt.Printf("%%d != %%d\n", a%s, b%s) panic("FAIL") } `, size, size, m1, m2, k, size, size, size) return test + "\n" } func makeAllSizes(m1, m2, k int) string { var tests string tests += makeMergeAddTest(m1, m2, k, "8") tests += makeMergeAddTest(m1, m2, k, "16") tests += makeMergeAddTest(m1, m2, k, "32") tests += makeMergeAddTest(m1, m2, k, "64") tests += makeMergeSubTest(m1, m2, k, "8") tests += makeMergeSubTest(m1, m2, k, "16") tests += makeMergeSubTest(m1, m2, k, "32") tests += makeMergeSubTest(m1, m2, k, "64") tests += "\n" return tests } func main() { fmt.Println(`package main import "fmt" var n8 int8 = 42 var n16 int16 = 42 var n32 int32 = 42 var n64 int64 = 42 func main() { var a8, b8 int8 var a16, b16 int16 var a32, b32 int32 var a64, b64 int64 `) fmt.Println(makeAllSizes(03, 05, 0)) // 3*n + 5*n fmt.Println(makeAllSizes(17, 33, 0)) fmt.Println(makeAllSizes(80, 45, 0)) fmt.Println(makeAllSizes(32, 64, 0)) fmt.Println(makeAllSizes(7, 11, +1)) // 7*n + 11*(n+1) fmt.Println(makeAllSizes(9, 13, +2)) fmt.Println(makeAllSizes(11, 16, -1)) fmt.Println(makeAllSizes(17, 9, -2)) fmt.Println("}") }
codestation/go
test/mergemul.go
GO
bsd-3-clause
3,236
// tslint:disable:no-unnecessary-generics import { ComponentType } from 'react'; import { EditorColor } from '../../'; declare namespace withColorContext { interface Props { colors: EditorColor[]; disableCustomColors: boolean; hasColorsToChoose: boolean; } } // prettier-ignore declare function withColorContext< ProvidedProps extends Partial<withColorContext.Props>, OwnProps extends any = any, T extends ComponentType<ProvidedProps & OwnProps> = ComponentType<ProvidedProps & OwnProps> >(component: T): T extends ComponentType<infer U> ? ComponentType< Omit<U, 'colors' | 'disableCustomColors' | 'hasColorsToChoose'> & Omit<ProvidedProps, 'hasColorsToChoose'>> : never; export default withColorContext;
markogresak/DefinitelyTyped
types/wordpress__block-editor/components/color-palette/with-color-context.d.ts
TypeScript
mit
777
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.example.customsettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ESTestCase; import static org.elasticsearch.example.customsettings.ExampleCustomSettingsConfig.VALIDATED_SETTING; /** * {@link ExampleCustomSettingsConfigTests} is a unit test class for {@link ExampleCustomSettingsConfig}. * <p> * It's a JUnit test class that extends {@link ESTestCase} which provides useful methods for testing. * <p> * The tests can be executed in the IDE or using the command: ./gradlew :example-plugins:custom-settings:test */ public class ExampleCustomSettingsConfigTests extends ESTestCase { public void testValidatedSetting() { final String expected = randomAlphaOfLengthBetween(1, 5); final String actual = VALIDATED_SETTING.get(Settings.builder().put(VALIDATED_SETTING.getKey(), expected).build()); assertEquals(expected, actual); final IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> VALIDATED_SETTING.get(Settings.builder().put("custom.validated", "it's forbidden").build())); assertEquals("Setting must not contain [forbidden]", exception.getMessage()); } }
GlenRSmith/elasticsearch
plugins/examples/custom-settings/src/test/java/org/elasticsearch/example/customsettings/ExampleCustomSettingsConfigTests.java
Java
apache-2.0
1,583
<?php /** * Test LocoAdmin::resolve_file_domain */ class ResolveFileDomainTest extends PHPUnit_Framework_TestCase { public function testDomainOnlySeparatesFromFileExtension(){ $domain = LocoAdmin::resolve_file_domain( '/foo.pot' ); $this->assertEquals( 'foo', $domain ); } public function testFullLocaleSeparatesFromDomainByHyphen(){ $domain = LocoAdmin::resolve_file_domain( '/foo-en_GB.po' ); $this->assertEquals( 'foo', $domain ); } public function testFullLocaleWithLongLanguageSeparatesFromDomainByHyphen(){ $domain = LocoAdmin::resolve_file_domain( '/foo-rup_MK.po' ); $this->assertEquals( 'foo', $domain ); } public function testLanguageCodeSeparatesFromDomainByHyphen(){ $domain = LocoAdmin::resolve_file_domain( '/foo-en.po' ); $this->assertEquals( 'foo', $domain ); } public function testValidLanguageCodeNotUsedAsDomain(){ $domain = LocoAdmin::resolve_file_domain( '/fr_FR.po' ); $this->assertSame( '', $domain ); } public function testInvalidLanguageCodeNotUsedAsDomain(){ $domain = LocoAdmin::resolve_file_domain( '/en_EN.po' ); $this->assertSame( '', $domain ); } public function testValidLanguageCodeNotUsedAsDomainWhenPot(){ $domain = LocoAdmin::resolve_file_domain( '/fr_FR.pot' ); $this->assertSame( '', $domain ); } public function testInvalidLanguageCodeNotUsedAsDomainWhenPot(){ $domain = LocoAdmin::resolve_file_domain( '/en_EN.pot' ); $this->assertSame( '', $domain ); } }
trungdovan87/bongda69
wp-content/plugins/loco-translate/lib/test/tests/ResolveFileDomainTest.php
PHP
gpl-2.0
1,625
package liquibase.change.core.supplier; import liquibase.change.Change; import liquibase.change.ColumnConfig; import liquibase.change.core.CreateTableChange; import liquibase.change.core.RenameTableChange; import liquibase.diff.DiffResult; import liquibase.sdk.supplier.change.AbstractChangeSupplier; import liquibase.structure.core.Table; import static junit.framework.TestCase.assertNotNull; public class RenameTableChangeSupplier extends AbstractChangeSupplier<RenameTableChange> { public RenameTableChangeSupplier() { super(RenameTableChange.class); } @Override public Change[] prepareDatabase(RenameTableChange change) throws Exception { CreateTableChange createTableChange = new CreateTableChange(); createTableChange.setCatalogName(change.getCatalogName()); createTableChange.setSchemaName(change.getSchemaName()); createTableChange.setTableName(change.getOldTableName()); createTableChange.addColumn(new ColumnConfig().setName("id").setType("int")); createTableChange.addColumn(new ColumnConfig().setName("other_column").setType("varchar(10)")); return new Change[] {createTableChange }; } @Override public void checkDiffResult(DiffResult diffResult, RenameTableChange change) { assertNotNull(diffResult.getMissingObject(new Table(change.getCatalogName(), change.getSchemaName(), change.getOldTableName()))); assertNotNull(diffResult.getUnexpectedObject(new Table(change.getCatalogName(), change.getSchemaName(), change.getNewTableName()))); } }
tjardo83/liquibase
liquibase-core/src/main/java/liquibase/change/core/supplier/RenameTableChangeSupplier.java
Java
apache-2.0
1,575
// 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. // /*============================================================================= ** ** ** ** Purpose: This class is a Delegate which defines the start method ** for starting a thread. That method must match this delegate. ** ** =============================================================================*/ namespace System.Threading { using System.Security.Permissions; using System.Threading; // Define the delegate // NOTE: If you change the signature here, there is code in COMSynchronization // that invokes this delegate in native. [System.Runtime.InteropServices.ComVisible(true)] public delegate void ThreadStart(); }
swgillespie/coreclr
src/mscorlib/src/System/Threading/ThreadStart.cs
C#
mit
862
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Build.Logging.StructuredLogger { /// <summary> /// Class representation of a logged item group entry. /// </summary> internal class ItemGroup : TaskParameter { /// <summary> /// Initializes a new instance of the <see cref="ItemGroup"/> class. /// </summary> /// <param name="message">The message from the logger.</param> /// <param name="prefix">The prefix string (e.g. 'Added item(s): ').</param> /// <param name="itemAttributeName">Name of the item attribute ('Include' or 'Remove').</param> public ItemGroup(string message, string prefix, string itemAttributeName) : base(message, prefix, false, itemAttributeName) { } } }
cdmihai/msbuild
src/Samples/XmlFileLogger/ObjectModel/ItemGroup.cs
C#
mit
909
//// [noImplicitReturnsWithoutReturnExpression.ts] function isMissingReturnExpression(): number { return; } function isMissingReturnExpression2(): any { return; } function isMissingReturnExpression3(): number|void { return; } function isMissingReturnExpression4(): void { return; } function isMissingReturnExpression5(x) { if (x) { return 0; } else { return; } } //// [noImplicitReturnsWithoutReturnExpression.js] function isMissingReturnExpression() { return; } function isMissingReturnExpression2() { return; } function isMissingReturnExpression3() { return; } function isMissingReturnExpression4() { return; } function isMissingReturnExpression5(x) { if (x) { return 0; } else { return; } }
plantain-00/TypeScript
tests/baselines/reference/noImplicitReturnsWithoutReturnExpression.js
JavaScript
apache-2.0
820
/** * @license * Copyright 2013 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as ts from "typescript"; import * as Lint from "../index"; export declare class Rule extends Lint.Rules.AbstractRule { static metadata: Lint.IRuleMetadata; static FAILURE_STRING_FACTORY: (memberType: string, memberName: string | undefined, publicOnly: boolean) => string; apply(sourceFile: ts.SourceFile): Lint.RuleFailure[]; } export declare class MemberAccessWalker extends Lint.RuleWalker { visitConstructorDeclaration(node: ts.ConstructorDeclaration): void; visitMethodDeclaration(node: ts.MethodDeclaration): void; visitPropertyDeclaration(node: ts.PropertyDeclaration): void; visitGetAccessor(node: ts.AccessorDeclaration): void; visitSetAccessor(node: ts.AccessorDeclaration): void; private validateVisibilityModifiers(node); }
mo-norant/FinHeartBel
website/node_modules/tslint/lib/rules/memberAccessRule.d.ts
TypeScript
gpl-3.0
1,404
WebMock.disable_net_connect!(allow: 'coveralls.io') # iTunes Lookup API RSpec.configure do |config| config.before(:each) do # iTunes Lookup API by Apple ID ["invalid", "", 0, '284882215', ['338986109', 'FR']].each do |current| if current.kind_of? Array id = current[0] country = current[1] url = "https://itunes.apple.com/lookup?id=#{id}&country=#{country}" body_file = "spec/responses/itunesLookup-#{id}_#{country}.json" else id = current url = "https://itunes.apple.com/lookup?id=#{id}" body_file = "spec/responses/itunesLookup-#{id}.json" end stub_request(:get, url). with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }). to_return(status: 200, body: File.read(body_file), headers: {}) end # iTunes Lookup API by App Identifier stub_request(:get, "https://itunes.apple.com/lookup?bundleId=com.facebook.Facebook"). with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }). to_return(status: 200, body: File.read("spec/responses/itunesLookup-com.facebook.Facebook.json"), headers: {}) stub_request(:get, "https://itunes.apple.com/lookup?bundleId=net.sunapps.invalid"). with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }). to_return(status: 200, body: File.read("spec/responses/itunesLookup-net.sunapps.invalid.json"), headers: {}) end end describe FastlaneCore do describe FastlaneCore::ItunesSearchApi do it "returns nil when it could not be found" do expect(FastlaneCore::ItunesSearchApi.fetch("invalid")).to eq(nil) expect(FastlaneCore::ItunesSearchApi.fetch("")).to eq(nil) expect(FastlaneCore::ItunesSearchApi.fetch(0)).to eq(nil) end it "returns the actual object if it could be found" do response = FastlaneCore::ItunesSearchApi.fetch("284882215") expect(response['kind']).to eq('software') expect(response['supportedDevices'].count).to be > 8 expect(FastlaneCore::ItunesSearchApi.fetch_bundle_identifier("284882215")).to eq('com.facebook.Facebook') end it "returns the actual object if it could be found" do response = FastlaneCore::ItunesSearchApi.fetch_by_identifier("com.facebook.Facebook") expect(response['kind']).to eq('software') expect(response['supportedDevices'].count).to be > 8 expect(response['trackId']).to eq(284_882_215) end it "can find country specific object" do response = FastlaneCore::ItunesSearchApi.fetch(338_986_109, 'FR') expect(response['kind']).to eq('software') expect(response['supportedDevices'].count).to be > 8 expect(response['trackId']).to eq(338_986_109) end end end
mathiasAichinger/fastlane_core
spec/itunes_search_api_spec.rb
Ruby
mit
2,907
var baz = "baz"; export default baz;
EliteScientist/webpack
test/statsCases/import-context-filter/templates/baz.noimport.js
JavaScript
mit
38
package im.actor.model.api.rpc; /* * Generated by the Actor API Scheme generator. DO NOT EDIT! */ import im.actor.model.droidkit.bser.Bser; import im.actor.model.droidkit.bser.BserParser; import im.actor.model.droidkit.bser.BserObject; import im.actor.model.droidkit.bser.BserValues; import im.actor.model.droidkit.bser.BserWriter; import im.actor.model.droidkit.bser.DataInput; import im.actor.model.droidkit.bser.DataOutput; import im.actor.model.droidkit.bser.util.SparseArray; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NotNull; import com.google.j2objc.annotations.ObjectiveCName; import static im.actor.model.droidkit.bser.Utils.*; import java.io.IOException; import im.actor.model.network.parser.*; import java.util.List; import java.util.ArrayList; import im.actor.model.api.*; public class RequestSendMessage extends Request<ResponseSeqDate> { public static final int HEADER = 0x5c; public static RequestSendMessage fromBytes(byte[] data) throws IOException { return Bser.parse(new RequestSendMessage(), data); } private OutPeer peer; private long rid; private Message message; public RequestSendMessage(@NotNull OutPeer peer, long rid, @NotNull Message message) { this.peer = peer; this.rid = rid; this.message = message; } public RequestSendMessage() { } @NotNull public OutPeer getPeer() { return this.peer; } public long getRid() { return this.rid; } @NotNull public Message getMessage() { return this.message; } @Override public void parse(BserValues values) throws IOException { this.peer = values.getObj(1, new OutPeer()); this.rid = values.getLong(3); this.message = Message.fromBytes(values.getBytes(4)); } @Override public void serialize(BserWriter writer) throws IOException { if (this.peer == null) { throw new IOException(); } writer.writeObject(1, this.peer); writer.writeLong(3, this.rid); if (this.message == null) { throw new IOException(); } writer.writeBytes(4, this.message.buildContainer()); } @Override public String toString() { String res = "rpc SendMessage{"; res += "peer=" + this.peer; res += ", rid=" + this.rid; res += ", message=" + this.message; res += "}"; return res; } @Override public int getHeaderKey() { return HEADER; } }
Rogerlin2013/actor-platform
actor-apps/core/src/main/java/im/actor/model/api/rpc/RequestSendMessage.java
Java
mit
2,557
public class Test { void fooBarGoo() { try {} finally {} fbg<caret> } }
smmribeiro/intellij-community
java/java-tests/testData/codeInsight/completion/normal/MethodCallAfterFinally.java
Java
apache-2.0
87
# rank 1 class CandidateTest def test4 end def test5 end end
phstc/sshp
vendor/ruby/1.9.1/gems/pry-0.9.12.2/spec/fixtures/candidate_helper2.rb
Ruby
mit
70
import frappe def execute(): duplicates = frappe.db.sql("""select email_group, email, count(name) from `tabEmail Group Member` group by email_group, email having count(name) > 1""") # delete all duplicates except 1 for email_group, email, count in duplicates: frappe.db.sql("""delete from `tabEmail Group Member` where email_group=%s and email=%s limit %s""", (email_group, email, count-1))
hassanibi/erpnext
erpnext/patches/v6_2/remove_newsletter_duplicates.py
Python
gpl-3.0
407
if (!self.GLOBAL || self.GLOBAL.isWindow()) { test(() => { assert_equals(document.title, "foo"); }, '<title> exists'); test(() => { assert_equals(document.querySelectorAll("meta[name=timeout][content=long]").length, 1); }, '<meta name=timeout> exists'); } scripts.push('expect-title-meta.js');
scheib/chromium
third_party/blink/web_tests/external/wpt/infrastructure/server/resources/expect-title-meta.js
JavaScript
bsd-3-clause
312
/* * bag.js - js/css/other loader + kv storage * * Copyright 2013-2014 Vitaly Puzrin * https://github.com/nodeca/bag.js * * License MIT */ /*global define*/ (function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define(factory); } else if (typeof module === 'object' && typeof module.exports === 'object') { module.exports = factory(); } else { root.Bag = factory(); } } (this, function () { 'use strict'; var head = document.head || document.getElementsByTagName('head')[0]; ////////////////////////////////////////////////////////////////////////////// // helpers function _nope() { return; } function _isString(obj) { return Object.prototype.toString.call(obj) === '[object String]'; } var _isArray = Array.isArray || function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }; function _isFunction(obj) { return Object.prototype.toString.call(obj) === '[object Function]'; } function _each(obj, iterator) { if (_isArray(obj)) { if (obj.forEach) { return obj.forEach(iterator); } for (var i = 0; i < obj.length; i++) { iterator(obj[i], i, obj); } } else { for (var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) { iterator(obj[k], k); } } } } function _default(obj, src) { // extend obj with src properties if not exists; _each(src, function (val, key) { if (!obj[key]) { obj[key] = src[key]; } }); } function _asyncEach(arr, iterator, callback) { callback = callback || _nope; if (!arr.length) { return callback(); } var completed = 0; _each(arr, function (x) { iterator(x, function (err) { if (err) { callback(err); callback = _nope; } else { completed += 1; if (completed >= arr.length) { callback(); } } }); }); } ////////////////////////////////////////////////////////////////////////////// // Adapters for Store class function DomStorage(namespace) { var self = this; var _ns = namespace + '__'; var _storage = localStorage; this.init = function (callback) { callback(); }; this.remove = function (key, callback) { callback = callback || _nope; _storage.removeItem(_ns + key); callback(); }; this.set = function (key, value, expire, callback) { var obj = { value: value, expire: expire }; var err; try { _storage.setItem(_ns + key, JSON.stringify(obj)); } catch (e) { // On quota error try to reset storage & try again. // Just remove all keys, without conditions, no optimizations needed. if (e.name.toUpperCase().indexOf('QUOTA') >= 0) { try { _each(_storage, function (val, name) { var k = name.split(_ns)[1]; if (k) { self.remove(k); } }); _storage.setItem(_ns + key, JSON.stringify(obj)); } catch (e2) { err = e2; } } else { err = e; } } callback(err); }; this.get = function (key, raw, callback) { if (_isFunction(raw)) { callback = raw; raw = false; } var err, data; try { data = JSON.parse(_storage.getItem(_ns + key)); data = raw ? data : data.value; } catch (e) { err = new Error('Can\'t read key: ' + key); } callback(err, data); }; this.clear = function (expiredOnly, callback) { var now = +new Date(); _each(_storage, function (val, name) { var key = name.split(_ns)[1]; if (!key) { return; } if (!expiredOnly) { self.remove(key); return; } var raw; self.get(key, true, function (__, data) { raw = data; // can use this hack, because get is sync; }); if (raw && (raw.expire > 0) && ((raw.expire - now) < 0)) { self.remove(key); } }); callback(); }; } DomStorage.prototype.exists = function () { try { localStorage.setItem('__ls_test__', '__ls_test__'); localStorage.removeItem('__ls_test__'); return true; } catch (e) { return false; } }; function WebSql(namespace) { var db; this.init = function (callback) { db = window.openDatabase(namespace, '1.0', 'bag.js db', 2e5); if (!db) { return callback('Can\'t open webdql database'); } db.transaction(function (tx) { tx.executeSql( 'CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT, expire INTEGER KEY)', [], function () { return callback(); }, function (tx, err) { return callback(err); } ); }); }; this.remove = function (key, callback) { callback = callback || _nope; db.transaction(function (tx) { tx.executeSql( 'DELETE FROM kv WHERE key = ?', [ key ], function () { return callback(); }, function (tx, err) { return callback(err); } ); }); }; this.set = function (key, value, expire, callback) { db.transaction(function (tx) { tx.executeSql( 'INSERT OR REPLACE INTO kv (key, value, expire) VALUES (?, ?, ?)', [ key, JSON.stringify(value), expire ], function () { return callback(); }, function (tx, err) { return callback(err); } ); }); }; this.get = function (key, callback) { db.readTransaction(function (tx) { tx.executeSql( 'SELECT value FROM kv WHERE key = ?', [ key ], function (tx, result) { if (result.rows.length === 0) { return callback(new Error('key not found: ' + key)); } var value = result.rows.item(0).value; var err, data; try { data = JSON.parse(value); } catch (e) { err = new Error('Can\'t unserialise data: ' + value); } callback(err, data); }, function (tx, err) { return callback(err); } ); }); }; this.clear = function (expiredOnly, callback) { db.transaction(function (tx) { if (expiredOnly) { tx.executeSql( 'DELETE FROM kv WHERE expire > 0 AND expire < ?', [ +new Date() ], function () { return callback(); }, function (tx, err) { return callback(err); } ); } else { db.transaction(function (tx) { tx.executeSql( 'DELETE FROM kv', [], function () { return callback(); }, function (tx, err) { return callback(err); } ); }); } }); }; } WebSql.prototype.exists = function () { return (!!window.openDatabase); }; function Idb(namespace) { var db; this.init = function (callback) { var idb = this.idb = window.indexedDB; /* || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;*/ var req = idb.open(namespace, 2 /*version*/); req.onsuccess = function (e) { db = e.target.result; callback(); }; req.onblocked = function (e) { callback(new Error('IndexedDB blocked. ' + e.target.errorCode)); }; req.onerror = function (e) { callback(new Error('IndexedDB opening error. ' + e.target.errorCode)); }; req.onupgradeneeded = function (e) { db = e.target.result; if (db.objectStoreNames.contains('kv')) { db.deleteObjectStore('kv'); } var store = db.createObjectStore('kv', { keyPath: 'key' }); store.createIndex('expire', 'expire', { unique: false }); }; }; this.remove = function (key, callback) { var tx = db.transaction('kv', 'readwrite'); tx.oncomplete = function () { callback(); }; tx.onerror = tx.onabort = function (e) { callback(new Error('Key remove error: ', e.target)); }; // IE 8 not allow to use reserved keywords as functions. More info: // http://tiffanybbrown.com/2013/09/10/expected-identifier-bug-in-internet-explorer-8/ tx.objectStore('kv')['delete'](key).onerror = function () { tx.abort(); }; }; this.set = function (key, value, expire, callback) { var tx = db.transaction('kv', 'readwrite'); tx.oncomplete = function () { callback(); }; tx.onerror = tx.onabort = function (e) { callback(new Error('Key set error: ', e.target)); }; tx.objectStore('kv').put({ key: key, value: value, expire: expire }).onerror = function () { tx.abort(); }; }; this.get = function (key, callback) { var err, result; var tx = db.transaction('kv'); tx.oncomplete = function () { callback(err, result); }; tx.onerror = tx.onabort = function (e) { callback(new Error('Key get error: ', e.target)); }; tx.objectStore('kv').get(key).onsuccess = function (e) { if (e.target.result) { result = e.target.result.value; } else { err = new Error('key not found: ' + key); } }; }; this.clear = function (expiredOnly, callback) { var keyrange = window.IDBKeyRange; /* || window.webkitIDBKeyRange || window.msIDBKeyRange;*/ var tx, store; tx = db.transaction('kv', 'readwrite'); store = tx.objectStore('kv'); tx.oncomplete = function () { callback(); }; tx.onerror = tx.onabort = function (e) { callback(new Error('Clear error: ', e.target)); }; if (expiredOnly) { var cursor = store.index('expire').openCursor(keyrange.bound(1, +new Date())); cursor.onsuccess = function (e) { var _cursor = e.target.result; if (_cursor) { // IE 8 not allow to use reserved keywords as functions (`delete` and `continue`). More info: // http://tiffanybbrown.com/2013/09/10/expected-identifier-bug-in-internet-explorer-8/ store['delete'](_cursor.primaryKey).onerror = function () { tx.abort(); }; _cursor['continue'](); } }; } else { // Just clear everything tx.objectStore('kv').clear().onerror = function () { tx.abort(); }; } }; } Idb.prototype.exists = function () { var db = window.indexedDB /*|| window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB*/; if (!db) { return false; } // Check outdated idb implementations, where `onupgradeneede` event doesn't work, // see https://github.com/pouchdb/pouchdb/issues/1207 for more details var dbName = '__idb_test__'; var result = db.open(dbName, 1).onupgradeneeded === null; if (db.deleteDatabase) { db.deleteDatabase(dbName); } return result; }; ///////////////////////////////////////////////////////////////////////////// // key/value storage with expiration var storeAdapters = { indexeddb: Idb, websql: WebSql, localstorage: DomStorage }; // namespace - db name or similar // storesList - array of allowed adapter names to use // function Storage(namespace, storesList) { var self = this; var db = null; // States of db init singletone process // 'done' / 'progress' / 'failed' / undefined var initState; var initStack = []; _each(storesList, function (name) { // do storage names case insensitive name = name.toLowerCase(); if (!storeAdapters[name]) { throw new Error('Wrong storage adapter name: ' + name, storesList); } if (storeAdapters[name].prototype.exists() && !db) { db = new storeAdapters[name](namespace); return false; // terminate search on first success } }); if (!db) { /* eslint-disable no-console */ // If no adaprets - don't make error for correct fallback. // Just log that we continue work without storing results. if (typeof console !== 'undefined' && console.log) { console.log('None of requested storages available: ' + storesList); } /* eslint-enable no-console */ } this.init = function (callback) { if (!db) { callback(new Error('No available db')); return; } if (initState === 'done') { callback(); return; } if (initState === 'progress') { initStack.push(callback); return; } initStack.push(callback); initState = 'progress'; db.init(function (err) { initState = !err ? 'done' : 'failed'; _each(initStack, function (cb) { cb(err); }); initStack = []; // Clear expired. A bit dirty without callback, // but we don't care until clear compleete if (!err) { self.clear(true); } }); }; this.set = function (key, value, expire, callback) { if (_isFunction(expire)) { callback = expire; expire = null; } callback = callback || _nope; expire = expire ? +(new Date()) + (expire * 1000) : 0; this.init(function (err) { if (err) { return callback(err); } db.set(key, value, expire, callback); }); }; this.get = function (key, callback) { this.init(function (err) { if (err) { return callback(err); } db.get(key, callback); }); }; this.remove = function (key, callback) { callback = callback || _nope; this.init(function (err) { if (err) { return callback(err); } db.remove(key, callback); }); }; this.clear = function (expiredOnly, callback) { if (_isFunction(expiredOnly)) { callback = expiredOnly; expiredOnly = false; } callback = callback || _nope; this.init(function (err) { if (err) { return callback(err); } db.clear(expiredOnly, callback); }); }; } ////////////////////////////////////////////////////////////////////////////// // Bag class implementation function Bag(options) { if (!(this instanceof Bag)) { return new Bag(options); } var self = this; options = options || {}; this.prefix = options.prefix || 'bag'; this.timeout = options.timeout || 20; // 20 seconds this.expire = options.expire || 30 * 24; // 30 days this.isValidItem = options.isValidItem || null; this.stores = _isArray(options.stores) ? options.stores : [ 'indexeddb', 'websql', 'localstorage' ]; var storage = null; this._queue = []; this._chained = false; this._createStorage = function () { if (!storage) { storage = new Storage(self.prefix, self.stores); } }; function getUrl(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { callback(null, { content: xhr.responseText, type: xhr.getResponseHeader('content-type') }); callback = _nope; } else { callback(new Error('Can\'t open url ' + url + (xhr.status ? xhr.statusText + ' (' + xhr.status + ')' : ''))); callback = _nope; } } }; setTimeout(function () { if (xhr.readyState < 4) { xhr.abort(); callback(new Error('Timeout')); callback = _nope; } }, self.timeout * 1000); xhr.send(); } function createCacheObj(obj, response) { var cacheObj = {}; _each([ 'url', 'key', 'unique' ], function (key) { if (obj[key]) { cacheObj[key] = obj[key]; } }); var now = +new Date(); cacheObj.data = response.content; cacheObj.originalType = response.type; cacheObj.type = obj.type || response.type; cacheObj.stamp = now; return cacheObj; } function saveUrl(obj, callback) { getUrl(obj.url_real, function (err, result) { if (err) { return callback(err); } var delay = (obj.expire || self.expire) * 60 * 60; // in seconds var cached = createCacheObj(obj, result); self.set(obj.key, cached, delay, function () { // Don't check error - have to return data anyway _default(obj, cached); callback(null, obj); }); }); } function isCacheValid(cached, obj) { return !cached || cached.expire - +new Date() < 0 || obj.unique !== cached.unique || obj.url !== cached.url || (self.isValidItem && !self.isValidItem(cached, obj)); } function fetch(obj, callback) { if (!obj.url) { return callback(); } obj.key = (obj.key || obj.url); self.get(obj.key, function (err_cache, cached) { // Check error only on forced fetch from cache if (err_cache && obj.cached) { callback(err_cache); return; } // if can't get object from store, then just load it from web. obj.execute = (obj.execute !== false); var shouldFetch = !!err_cache || isCacheValid(cached, obj); // If don't have to load new date - return one from cache if (!obj.live && !shouldFetch) { obj.type = obj.type || cached.originalType; _default(obj, cached); callback(null, obj); return; } // calculate loading url obj.url_real = obj.url; if (obj.unique) { // set parameter to prevent browser cache obj.url_real = obj.url + ((obj.url.indexOf('?') > 0) ? '&' : '?') + 'bag-unique=' + obj.unique; } saveUrl(obj, function (err_load) { if (err_cache && err_load) { callback(err_load); return; } if (err_load) { obj.type = obj.type || cached.originalType; _default(obj, cached); callback(null, obj); return; } callback(null, obj); }); }); } //////////////////////////////////////////////////////////////////////////// // helpers to set absolute sourcemap url /* eslint-disable max-len */ var sourceMappingRe = /(?:^([ \t]*\/\/[@|#][ \t]+sourceMappingURL=)(.+?)([ \t]*)$)|(?:^([ \t]*\/\*[@#][ \t]+sourceMappingURL=)(.+?)([ \t]*\*\/[ \t])*$)/mg; /* eslint-enable max-len */ function parse_url(url) { var pattern = new RegExp('^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?'); var matches = url.match(pattern); return { scheme: matches[2], authority: matches[4], path: matches[5], query: matches[7], fragment: matches[9] }; } function patchMappingUrl(obj) { var refUrl = parse_url(obj.url); var done = false; var res = obj.data.replace(sourceMappingRe, function (match, p1, p2, p3, p4, p5, p6) { if (!match) { return null; } done = true; // select matched group of params if (!p1) { p1 = p4; p2 = p5; p3 = p6; } var mapUrl = parse_url(p2); var scheme = (mapUrl.scheme ? mapUrl.scheme : refUrl.scheme) || window.location.protocol.slice(0, -1); var authority = (mapUrl.authority ? mapUrl.authority : refUrl.authority) || window.location.host; /* eslint-disable max-len */ var path = mapUrl.path[0] === '/' ? mapUrl.path : refUrl.path.split('/').slice(0, -1).join('/') + '/' + mapUrl.path; /* eslint-enable max-len */ return p1 + (scheme + '://' + authority + path) + p3; }); return done ? res : ''; } //////////////////////////////////////////////////////////////////////////// var handlers = { 'application/javascript': function injectScript(obj) { var script = document.createElement('script'), txt; // try to change sourcemap address to absolute txt = patchMappingUrl(obj); if (!txt) { // or add script name for dev tools txt = obj.data + '\n//# sourceURL=' + obj.url; } // Have to use .text, since we support IE8, // which won't allow appending to a script script.text = txt; head.appendChild(script); return; }, 'text/css': function injectStyle(obj) { var style = document.createElement('style'), txt; // try to change sourcemap address to absolute txt = patchMappingUrl(obj); if (!txt) { // or add stylesheet script name for dev tools txt = obj.data + '\n/*# sourceURL=' + obj.url + ' */'; } // Needed to enable `style.styleSheet` in IE style.setAttribute('type', 'text/css'); if (style.styleSheet) { // We should append style element to DOM before assign css text to // workaround IE bugs with `@import` and `@font-face`. // https://github.com/andrewwakeling/ie-css-bugs head.appendChild(style); style.styleSheet.cssText = txt; // IE method } else { style.appendChild(document.createTextNode(txt)); // others head.appendChild(style); } return; } }; function execute(obj) { if (!obj.type) { return; } // Cut off encoding if exists: // application/javascript; charset=UTF-8 var handlerName = obj.type.split(';')[0]; // Fix outdated mime types if needed, to use single handler if (handlerName === 'application/x-javascript' || handlerName === 'text/javascript') { handlerName = 'application/javascript'; } if (handlers[handlerName]) { handlers[handlerName](obj); } return; } //////////////////////////////////////////////////////////////////////////// // // Public methods // this.require = function (resources, callback) { var queue = self._queue; if (_isFunction(resources)) { callback = resources; resources = null; } if (resources) { var res = _isArray(resources) ? resources : [ resources ]; // convert string urls to structures // and push to queue _each(res, function (r, i) { if (_isString(r)) { res[i] = { url: r }; } queue.push(res[i]); }); } self._createStorage(); if (!callback) { self._chained = true; return self; } _asyncEach(queue, fetch, function (err) { if (err) { // cleanup self._chained = false; self._queue = []; callback(err); return; } _each(queue, function (obj) { if (obj.execute) { execute(obj); } }); // return content only, if one need fuul info - // check input object, that will be extended. var replies = []; _each(queue, function (r) { replies.push(r.data); }); var result = (_isArray(resources) || self._chained) ? replies : replies[0]; // cleanup self._chained = false; self._queue = []; callback(null, result); }); }; // Create proxy methods (init store then subcall) _each([ 'remove', 'get', 'set', 'clear' ], function (method) { self[method] = function () { self._createStorage(); storage[method].apply(storage, arguments); }; }); this.addHandler = function (types, handler) { types = _isArray(types) ? types : [ types ]; _each(types, function (type) { handlers[type] = handler; }); }; this.removeHandler = function (types) { self.addHandler(types/*, undefined*/); }; } return Bag; }));
kiwi89/cdnjs
ajax/libs/bagjs/1.0.0/bag.js
JavaScript
mit
24,235
using System; using NLog; using NLog.Targets; using NLog.Targets.Wrappers; class Example { static void Main(string[] args) { try { NLog.Internal.InternalLogger.LogToConsole = true; NLog.Internal.InternalLogger.LogLevel = LogLevel.Trace; Console.WriteLine("Setting up the target..."); MailTarget target = new MailTarget(); target.SmtpServer = "192.168.0.15"; target.From = "jaak@jkowalski.net"; target.To = "jaak@jkowalski.net"; target.Subject = "sample subject"; target.Body = "${message}${newline}"; BufferingTargetWrapper buffer = new BufferingTargetWrapper(target, 5); NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(buffer, LogLevel.Debug); Console.WriteLine("Sending..."); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message 1"); logger.Debug("log message 2"); logger.Debug("log message 3"); logger.Debug("log message 4"); logger.Debug("log message 5"); logger.Debug("log message 6"); logger.Debug("log message 7"); logger.Debug("log message 8"); // this should send 2 mails - one with messages 1..5, the other with messages 6..8 Console.WriteLine("Sent."); } catch (Exception ex) { Console.WriteLine("EX: {0}", ex); } } }
reasyrf/XBeeMultiTerminal
src/NLog/examples/targets/Configuration API/Mail/Buffered/Example.cs
C#
gpl-3.0
1,532
(function (env) { "use strict"; env.ddg_spice_bacon_ipsum = function(api_result){ if (!api_result || api_result.error) { return Spice.failed('bacon_ipsum'); } var pageContent = ''; for (var i in api_result) { pageContent += "<p>" + api_result[i] + "</p>"; } Spice.add({ id: 'bacon_ipsum', name: 'Bacon Ipsum', data: { content: pageContent, title: "Bacon Ipsum", subtitle: "Randomly generated text" }, meta: { sourceName: 'Bacon Ipsum', sourceUrl: 'http://baconipsum.com/' }, templates: { group: 'text', options: { content: Spice.bacon_ipsum.content } } }); }; }(this));
hshackathons/zeroclickinfo-spice
share/spice/bacon_ipsum/bacon_ipsum.js
JavaScript
apache-2.0
910
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public static class DiagnosticFixerTestsExtensions { internal static Document Apply(this Document document, CodeAction action) { var operations = action.GetOperationsAsync(CancellationToken.None).Result; var solution = operations.OfType<ApplyChangesOperation>().Single().ChangedSolution; return solution.GetDocument(document.Id); } } }
mavasani/roslyn-analyzers
tools/AnalyzerCodeGenerator/template/src/Test/Utilities/CodeFixTests.Extensions.cs
C#
apache-2.0
826
require('../lib/node_loader'); var AWS = require('../lib/core'); var Service = require('../lib/service'); var apiLoader = require('../lib/api_loader'); apiLoader.services['cloudsearchdomain'] = {}; AWS.CloudSearchDomain = Service.defineService('cloudsearchdomain', ['2013-01-01']); require('../lib/services/cloudsearchdomain'); Object.defineProperty(apiLoader.services['cloudsearchdomain'], '2013-01-01', { get: function get() { var model = require('../apis/cloudsearchdomain-2013-01-01.min.json'); return model; }, enumerable: true, configurable: true }); module.exports = AWS.CloudSearchDomain;
edeati/alexa-translink-skill-js
test/node_modules/aws-sdk/clients/cloudsearchdomain.js
JavaScript
apache-2.0
615
<?php namespace Drupal\file\Plugin\Field\FieldFormatter; /** * Defines getter methods for FileMediaFormatterBase. * * This interface is used on the FileMediaFormatterBase class to ensure that * each file media formatter will be based on a media type. * * Abstract classes are not able to implement abstract static methods, * this interface will work around that. * * @see \Drupal\file\Plugin\Field\FieldFormatter\FileMediaFormatterBase */ interface FileMediaFormatterInterface { /** * Gets the applicable media type for a formatter. * * @return string * The media type of this formatter. */ public static function getMediaType(); }
tobiasbuhrer/tobiasb
web/core/modules/file/src/Plugin/Field/FieldFormatter/FileMediaFormatterInterface.php
PHP
gpl-2.0
667
import { OpaqueToken } from './di'; /** * A DI Token representing a unique string id assigned to the application by Angular and used * primarily for prefixing application attributes and CSS styles when * {@link ViewEncapsulation#Emulated} is being used. * * If you need to avoid randomly generated value to be used as an application id, you can provide * a custom value via a DI provider <!-- TODO: provider --> configuring the root {@link Injector} * using this token. * @experimental */ export declare const APP_ID: any; export declare function _appIdRandomProviderFactory(): string; /** * Providers that will generate a random APP_ID_TOKEN. * @experimental */ export declare const APP_ID_RANDOM_PROVIDER: { provide: any; useFactory: () => string; deps: any[]; }; /** * A function that will be executed when a platform is initialized. * @experimental */ export declare const PLATFORM_INITIALIZER: any; /** * All callbacks provided via this token will be called for every component that is bootstrapped. * Signature of the callback: * * `(componentRef: ComponentRef) => void`. * * @experimental */ export declare const APP_BOOTSTRAP_LISTENER: OpaqueToken; /** * A token which indicates the root directory of the application * @experimental */ export declare const PACKAGE_ROOT_URL: any;
oleksandr-minakov/northshore
ui/node_modules/@angular/core/src/application_tokens.d.ts
TypeScript
apache-2.0
1,325
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), available at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * TIANI Medgraph AG. * Portions created by the Initial Developer are Copyright (C) 2003-2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gunter Zeilinger <gunter.zeilinger@tiani.com> * Franz Willer <franz.willer@gwi-ag.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4chex.archive.common; import java.util.Arrays; /** * @author gunter.zeilinger@tiani.com * @version $Revision: 2772 $ $Date: 2006-09-20 16:58:51 +0800 (周三, 20 9月 2006) $ * @since 06.10.2004 * */ public class SPSStatus { private static final String[] ENUM = { "SCHEDULED", "ARRIVED", "READY", "STARTED", "COMPLETED", "DISCONTINUED" }; public static final int SCHEDULED = 0; public static final int ARRIVED = 1; public static final int READY = 2; public static final int STARTED = 3; public static final int COMPLETED = 4; public static final int DISCONTINUED = 5; public static final String toString(int value) { return ENUM[value]; } public static final int toInt(String s) { final int index = Arrays.asList(ENUM).indexOf(s); if (index == -1) throw new IllegalArgumentException(s); return index; } public static int[] toInts(String[] ss) { if (ss == null) { return null; } int[] ret = new int[ss.length]; for (int i = 0; i < ret.length; i++) { ret[i] = toInt(ss[i]); } return ret; } }
medicayun/medicayundicom
dcm4jboss-all/trunk/dcm4jboss-ejb/src/java/org/dcm4chex/archive/common/SPSStatus.java
Java
apache-2.0
3,087
--TEST-- GH-1351: Test result does not serialize test class in process isolation --SKIPIF-- <?php if (!extension_loaded('pdo') || !in_array('sqlite', PDO::getAvailableDrivers())) { print 'skip: PDO_SQLITE is required'; } ?> --FILE-- <?php $_SERVER['argv'][1] = '--no-configuration'; $_SERVER['argv'][2] = '--process-isolation'; $_SERVER['argv'][3] = 'Issue1351Test'; $_SERVER['argv'][4] = __DIR__ . '/1351/Issue1351Test.php'; require __DIR__ . '/../../bootstrap.php'; PHPUnit_TextUI_Command::main(); ?> --EXPECTF-- PHPUnit %s by Sebastian Bergmann and contributors. F.E.E 5 / 5 (100%) Time: %s, Memory: %sMb There were 2 errors: 1) Issue1351Test::testExceptionPre RuntimeException: Expected rethrown exception. %A Caused by LogicException: Expected exception. %A 2) Issue1351Test::testPhpCoreLanguageException PDOException: SQLSTATE[HY000]: General error: 1 no such table: php_wtf %A -- There was 1 failure: 1) Issue1351Test::testFailurePre Expected failure. %A FAILURES! Tests: 5, Assertions: 5, Errors: 2, Failures: 1.
shankarnakai/gbdesign
wp-content/mu-plugins/vsigestao/vendor/phpunit/phpunit/tests/Regression/GitHub/1351.phpt
PHP
gpl-2.0
1,097
module ChefCompat module CopiedFromChef def self.extend_chef_module(chef_module, target) target.instance_eval do include chef_module @chef_module = chef_module def self.method_missing(name, *args, &block) @chef_module.send(name, *args, &block) end def self.const_missing(name) @chef_module.const_get(name) end end end # This patch to CopiedFromChef's ActionClass is necessary for the include to work require 'chef/resource' class Chef < ::Chef class Resource < ::Chef::Resource module ActionClass def self.use_inline_resources end def self.include_resource_dsl(include_resource_dsl) end end end end end end
Coveros/starcanada2016
www-db/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef.rb
Ruby
apache-2.0
784
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2013 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btMultiBodyDynamicsWorld.h" #include "btMultiBodyConstraintSolver.h" #include "btMultiBody.h" #include "btMultiBodyLinkCollider.h" #include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h" #include "LinearMath/btQuickprof.h" #include "btMultiBodyConstraint.h" #include "LinearMath/btIDebugDraw.h" void btMultiBodyDynamicsWorld::addMultiBody(btMultiBody* body, short group, short mask) { m_multiBodies.push_back(body); } void btMultiBodyDynamicsWorld::removeMultiBody(btMultiBody* body) { m_multiBodies.remove(body); } void btMultiBodyDynamicsWorld::calculateSimulationIslands() { BT_PROFILE("calculateSimulationIslands"); getSimulationIslandManager()->updateActivationState(getCollisionWorld(),getCollisionWorld()->getDispatcher()); { //merge islands based on speculative contact manifolds too for (int i=0;i<this->m_predictiveManifolds.size();i++) { btPersistentManifold* manifold = m_predictiveManifolds[i]; const btCollisionObject* colObj0 = manifold->getBody0(); const btCollisionObject* colObj1 = manifold->getBody1(); if (((colObj0) && (!(colObj0)->isStaticOrKinematicObject())) && ((colObj1) && (!(colObj1)->isStaticOrKinematicObject()))) { getSimulationIslandManager()->getUnionFind().unite((colObj0)->getIslandTag(),(colObj1)->getIslandTag()); } } } { int i; int numConstraints = int(m_constraints.size()); for (i=0;i< numConstraints ; i++ ) { btTypedConstraint* constraint = m_constraints[i]; if (constraint->isEnabled()) { const btRigidBody* colObj0 = &constraint->getRigidBodyA(); const btRigidBody* colObj1 = &constraint->getRigidBodyB(); if (((colObj0) && (!(colObj0)->isStaticOrKinematicObject())) && ((colObj1) && (!(colObj1)->isStaticOrKinematicObject()))) { getSimulationIslandManager()->getUnionFind().unite((colObj0)->getIslandTag(),(colObj1)->getIslandTag()); } } } } //merge islands linked by Featherstone link colliders for (int i=0;i<m_multiBodies.size();i++) { btMultiBody* body = m_multiBodies[i]; { btMultiBodyLinkCollider* prev = body->getBaseCollider(); for (int b=0;b<body->getNumLinks();b++) { btMultiBodyLinkCollider* cur = body->getLink(b).m_collider; if (((cur) && (!(cur)->isStaticOrKinematicObject())) && ((prev) && (!(prev)->isStaticOrKinematicObject()))) { int tagPrev = prev->getIslandTag(); int tagCur = cur->getIslandTag(); getSimulationIslandManager()->getUnionFind().unite(tagPrev, tagCur); } if (cur && !cur->isStaticOrKinematicObject()) prev = cur; } } } //merge islands linked by multibody constraints { for (int i=0;i<this->m_multiBodyConstraints.size();i++) { btMultiBodyConstraint* c = m_multiBodyConstraints[i]; int tagA = c->getIslandIdA(); int tagB = c->getIslandIdB(); if (tagA>=0 && tagB>=0) getSimulationIslandManager()->getUnionFind().unite(tagA, tagB); } } //Store the island id in each body getSimulationIslandManager()->storeIslandActivationState(getCollisionWorld()); } void btMultiBodyDynamicsWorld::updateActivationState(btScalar timeStep) { BT_PROFILE("btMultiBodyDynamicsWorld::updateActivationState"); for ( int i=0;i<m_multiBodies.size();i++) { btMultiBody* body = m_multiBodies[i]; if (body) { body->checkMotionAndSleepIfRequired(timeStep); if (!body->isAwake()) { btMultiBodyLinkCollider* col = body->getBaseCollider(); if (col && col->getActivationState() == ACTIVE_TAG) { col->setActivationState( WANTS_DEACTIVATION); col->setDeactivationTime(0.f); } for (int b=0;b<body->getNumLinks();b++) { btMultiBodyLinkCollider* col = body->getLink(b).m_collider; if (col && col->getActivationState() == ACTIVE_TAG) { col->setActivationState( WANTS_DEACTIVATION); col->setDeactivationTime(0.f); } } } else { btMultiBodyLinkCollider* col = body->getBaseCollider(); if (col && col->getActivationState() != DISABLE_DEACTIVATION) col->setActivationState( ACTIVE_TAG ); for (int b=0;b<body->getNumLinks();b++) { btMultiBodyLinkCollider* col = body->getLink(b).m_collider; if (col && col->getActivationState() != DISABLE_DEACTIVATION) col->setActivationState( ACTIVE_TAG ); } } } } btDiscreteDynamicsWorld::updateActivationState(timeStep); } SIMD_FORCE_INLINE int btGetConstraintIslandId2(const btTypedConstraint* lhs) { int islandId; const btCollisionObject& rcolObj0 = lhs->getRigidBodyA(); const btCollisionObject& rcolObj1 = lhs->getRigidBodyB(); islandId= rcolObj0.getIslandTag()>=0?rcolObj0.getIslandTag():rcolObj1.getIslandTag(); return islandId; } class btSortConstraintOnIslandPredicate2 { public: bool operator() ( const btTypedConstraint* lhs, const btTypedConstraint* rhs ) const { int rIslandId0,lIslandId0; rIslandId0 = btGetConstraintIslandId2(rhs); lIslandId0 = btGetConstraintIslandId2(lhs); return lIslandId0 < rIslandId0; } }; SIMD_FORCE_INLINE int btGetMultiBodyConstraintIslandId(const btMultiBodyConstraint* lhs) { int islandId; int islandTagA = lhs->getIslandIdA(); int islandTagB = lhs->getIslandIdB(); islandId= islandTagA>=0?islandTagA:islandTagB; return islandId; } class btSortMultiBodyConstraintOnIslandPredicate { public: bool operator() ( const btMultiBodyConstraint* lhs, const btMultiBodyConstraint* rhs ) const { int rIslandId0,lIslandId0; rIslandId0 = btGetMultiBodyConstraintIslandId(rhs); lIslandId0 = btGetMultiBodyConstraintIslandId(lhs); return lIslandId0 < rIslandId0; } }; struct MultiBodyInplaceSolverIslandCallback : public btSimulationIslandManager::IslandCallback { btContactSolverInfo* m_solverInfo; btMultiBodyConstraintSolver* m_solver; btMultiBodyConstraint** m_multiBodySortedConstraints; int m_numMultiBodyConstraints; btTypedConstraint** m_sortedConstraints; int m_numConstraints; btIDebugDraw* m_debugDrawer; btDispatcher* m_dispatcher; btAlignedObjectArray<btCollisionObject*> m_bodies; btAlignedObjectArray<btPersistentManifold*> m_manifolds; btAlignedObjectArray<btTypedConstraint*> m_constraints; btAlignedObjectArray<btMultiBodyConstraint*> m_multiBodyConstraints; MultiBodyInplaceSolverIslandCallback( btMultiBodyConstraintSolver* solver, btDispatcher* dispatcher) :m_solverInfo(NULL), m_solver(solver), m_multiBodySortedConstraints(NULL), m_numConstraints(0), m_debugDrawer(NULL), m_dispatcher(dispatcher) { } MultiBodyInplaceSolverIslandCallback& operator=(MultiBodyInplaceSolverIslandCallback& other) { btAssert(0); (void)other; return *this; } SIMD_FORCE_INLINE void setup ( btContactSolverInfo* solverInfo, btTypedConstraint** sortedConstraints, int numConstraints, btMultiBodyConstraint** sortedMultiBodyConstraints, int numMultiBodyConstraints, btIDebugDraw* debugDrawer) { btAssert(solverInfo); m_solverInfo = solverInfo; m_multiBodySortedConstraints = sortedMultiBodyConstraints; m_numMultiBodyConstraints = numMultiBodyConstraints; m_sortedConstraints = sortedConstraints; m_numConstraints = numConstraints; m_debugDrawer = debugDrawer; m_bodies.resize (0); m_manifolds.resize (0); m_constraints.resize (0); m_multiBodyConstraints.resize(0); } virtual void processIsland(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifolds,int numManifolds, int islandId) { if (islandId<0) { ///we don't split islands, so all constraints/contact manifolds/bodies are passed into the solver regardless the island id m_solver->solveMultiBodyGroup( bodies,numBodies,manifolds, numManifolds,m_sortedConstraints, m_numConstraints, &m_multiBodySortedConstraints[0],m_numConstraints,*m_solverInfo,m_debugDrawer,m_dispatcher); } else { //also add all non-contact constraints/joints for this island btTypedConstraint** startConstraint = 0; btMultiBodyConstraint** startMultiBodyConstraint = 0; int numCurConstraints = 0; int numCurMultiBodyConstraints = 0; int i; //find the first constraint for this island for (i=0;i<m_numConstraints;i++) { if (btGetConstraintIslandId2(m_sortedConstraints[i]) == islandId) { startConstraint = &m_sortedConstraints[i]; break; } } //count the number of constraints in this island for (;i<m_numConstraints;i++) { if (btGetConstraintIslandId2(m_sortedConstraints[i]) == islandId) { numCurConstraints++; } } for (i=0;i<m_numMultiBodyConstraints;i++) { if (btGetMultiBodyConstraintIslandId(m_multiBodySortedConstraints[i]) == islandId) { startMultiBodyConstraint = &m_multiBodySortedConstraints[i]; break; } } //count the number of multi body constraints in this island for (;i<m_numMultiBodyConstraints;i++) { if (btGetMultiBodyConstraintIslandId(m_multiBodySortedConstraints[i]) == islandId) { numCurMultiBodyConstraints++; } } if (m_solverInfo->m_minimumSolverBatchSize<=1) { m_solver->solveGroup( bodies,numBodies,manifolds, numManifolds,startConstraint,numCurConstraints,*m_solverInfo,m_debugDrawer,m_dispatcher); } else { for (i=0;i<numBodies;i++) m_bodies.push_back(bodies[i]); for (i=0;i<numManifolds;i++) m_manifolds.push_back(manifolds[i]); for (i=0;i<numCurConstraints;i++) m_constraints.push_back(startConstraint[i]); for (i=0;i<numCurMultiBodyConstraints;i++) m_multiBodyConstraints.push_back(startMultiBodyConstraint[i]); if ((m_constraints.size()+m_manifolds.size())>m_solverInfo->m_minimumSolverBatchSize) { processConstraints(); } else { //printf("deferred\n"); } } } } void processConstraints() { btCollisionObject** bodies = m_bodies.size()? &m_bodies[0]:0; btPersistentManifold** manifold = m_manifolds.size()?&m_manifolds[0]:0; btTypedConstraint** constraints = m_constraints.size()?&m_constraints[0]:0; btMultiBodyConstraint** multiBodyConstraints = m_multiBodyConstraints.size() ? &m_multiBodyConstraints[0] : 0; //printf("mb contacts = %d, mb constraints = %d\n", mbContacts, m_multiBodyConstraints.size()); m_solver->solveMultiBodyGroup( bodies,m_bodies.size(),manifold, m_manifolds.size(),constraints, m_constraints.size() ,multiBodyConstraints, m_multiBodyConstraints.size(), *m_solverInfo,m_debugDrawer,m_dispatcher); m_bodies.resize(0); m_manifolds.resize(0); m_constraints.resize(0); m_multiBodyConstraints.resize(0); } }; btMultiBodyDynamicsWorld::btMultiBodyDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btMultiBodyConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration) :btDiscreteDynamicsWorld(dispatcher,pairCache,constraintSolver,collisionConfiguration), m_multiBodyConstraintSolver(constraintSolver) { //split impulse is not yet supported for Featherstone hierarchies getSolverInfo().m_splitImpulse = false; getSolverInfo().m_solverMode |=SOLVER_USE_2_FRICTION_DIRECTIONS; m_solverMultiBodyIslandCallback = new MultiBodyInplaceSolverIslandCallback(constraintSolver,dispatcher); } btMultiBodyDynamicsWorld::~btMultiBodyDynamicsWorld () { delete m_solverMultiBodyIslandCallback; } void btMultiBodyDynamicsWorld::solveConstraints(btContactSolverInfo& solverInfo) { btAlignedObjectArray<btScalar> scratch_r; btAlignedObjectArray<btVector3> scratch_v; btAlignedObjectArray<btMatrix3x3> scratch_m; BT_PROFILE("solveConstraints"); m_sortedConstraints.resize( m_constraints.size()); int i; for (i=0;i<getNumConstraints();i++) { m_sortedConstraints[i] = m_constraints[i]; } m_sortedConstraints.quickSort(btSortConstraintOnIslandPredicate2()); btTypedConstraint** constraintsPtr = getNumConstraints() ? &m_sortedConstraints[0] : 0; m_sortedMultiBodyConstraints.resize(m_multiBodyConstraints.size()); for (i=0;i<m_multiBodyConstraints.size();i++) { m_sortedMultiBodyConstraints[i] = m_multiBodyConstraints[i]; } m_sortedMultiBodyConstraints.quickSort(btSortMultiBodyConstraintOnIslandPredicate()); btMultiBodyConstraint** sortedMultiBodyConstraints = m_sortedMultiBodyConstraints.size() ? &m_sortedMultiBodyConstraints[0] : 0; m_solverMultiBodyIslandCallback->setup(&solverInfo,constraintsPtr,m_sortedConstraints.size(),sortedMultiBodyConstraints,m_sortedMultiBodyConstraints.size(), getDebugDrawer()); m_constraintSolver->prepareSolve(getCollisionWorld()->getNumCollisionObjects(), getCollisionWorld()->getDispatcher()->getNumManifolds()); /// solve all the constraints for this island m_islandManager->buildAndProcessIslands(getCollisionWorld()->getDispatcher(),getCollisionWorld(),m_solverMultiBodyIslandCallback); { BT_PROFILE("btMultiBody addForce and stepVelocities"); for (int i=0;i<this->m_multiBodies.size();i++) { btMultiBody* bod = m_multiBodies[i]; bool isSleeping = false; if (bod->getBaseCollider() && bod->getBaseCollider()->getActivationState() == ISLAND_SLEEPING) { isSleeping = true; } for (int b=0;b<bod->getNumLinks();b++) { if (bod->getLink(b).m_collider && bod->getLink(b).m_collider->getActivationState()==ISLAND_SLEEPING) isSleeping = true; } if (!isSleeping) { //useless? they get resized in stepVelocities once again (AND DIFFERENTLY) scratch_r.resize(bod->getNumLinks()+1); //multidof? ("Y"s use it and it is used to store qdd) scratch_v.resize(bod->getNumLinks()+1); scratch_m.resize(bod->getNumLinks()+1); bod->addBaseForce(m_gravity * bod->getBaseMass()); for (int j = 0; j < bod->getNumLinks(); ++j) { bod->addLinkForce(j, m_gravity * bod->getLinkMass(j)); } bool doNotUpdatePos = false; if(bod->isMultiDof()) { if(!bod->isUsingRK4Integration()) { bod->stepVelocitiesMultiDof(solverInfo.m_timeStep, scratch_r, scratch_v, scratch_m); } else { // int numDofs = bod->getNumDofs() + 6; int numPosVars = bod->getNumPosVars() + 7; btAlignedObjectArray<btScalar> scratch_r2; scratch_r2.resize(2*numPosVars + 8*numDofs); //convenience btScalar *pMem = &scratch_r2[0]; btScalar *scratch_q0 = pMem; pMem += numPosVars; btScalar *scratch_qx = pMem; pMem += numPosVars; btScalar *scratch_qd0 = pMem; pMem += numDofs; btScalar *scratch_qd1 = pMem; pMem += numDofs; btScalar *scratch_qd2 = pMem; pMem += numDofs; btScalar *scratch_qd3 = pMem; pMem += numDofs; btScalar *scratch_qdd0 = pMem; pMem += numDofs; btScalar *scratch_qdd1 = pMem; pMem += numDofs; btScalar *scratch_qdd2 = pMem; pMem += numDofs; btScalar *scratch_qdd3 = pMem; pMem += numDofs; btAssert((pMem - (2*numPosVars + 8*numDofs)) == &scratch_r2[0]); ///// //copy q0 to scratch_q0 and qd0 to scratch_qd0 scratch_q0[0] = bod->getWorldToBaseRot().x(); scratch_q0[1] = bod->getWorldToBaseRot().y(); scratch_q0[2] = bod->getWorldToBaseRot().z(); scratch_q0[3] = bod->getWorldToBaseRot().w(); scratch_q0[4] = bod->getBasePos().x(); scratch_q0[5] = bod->getBasePos().y(); scratch_q0[6] = bod->getBasePos().z(); // for(int link = 0; link < bod->getNumLinks(); ++link) { for(int dof = 0; dof < bod->getLink(link).m_posVarCount; ++dof) scratch_q0[7 + bod->getLink(link).m_cfgOffset + dof] = bod->getLink(link).m_jointPos[dof]; } // for(int dof = 0; dof < numDofs; ++dof) scratch_qd0[dof] = bod->getVelocityVector()[dof]; //// struct { btMultiBody *bod; btScalar *scratch_qx, *scratch_q0; void operator()() { for(int dof = 0; dof < bod->getNumPosVars() + 7; ++dof) scratch_qx[dof] = scratch_q0[dof]; } } pResetQx = {bod, scratch_qx, scratch_q0}; // struct { void operator()(btScalar dt, const btScalar *pDer, const btScalar *pCurVal, btScalar *pVal, int size) { for(int i = 0; i < size; ++i) pVal[i] = pCurVal[i] + dt * pDer[i]; } } pEulerIntegrate; // struct { void operator()(btMultiBody *pBody, const btScalar *pData) { btScalar *pVel = const_cast<btScalar*>(pBody->getVelocityVector()); for(int i = 0; i < pBody->getNumDofs() + 6; ++i) pVel[i] = pData[i]; } } pCopyToVelocityVector; // struct { void operator()(const btScalar *pSrc, btScalar *pDst, int start, int size) { for(int i = 0; i < size; ++i) pDst[i] = pSrc[start + i]; } } pCopy; // btScalar h = solverInfo.m_timeStep; #define output &scratch_r[bod->getNumDofs()] //calc qdd0 from: q0 & qd0 bod->stepVelocitiesMultiDof(0., scratch_r, scratch_v, scratch_m); pCopy(output, scratch_qdd0, 0, numDofs); //calc q1 = q0 + h/2 * qd0 pResetQx(); bod->stepPositionsMultiDof(btScalar(.5)*h, scratch_qx, scratch_qd0); //calc qd1 = qd0 + h/2 * qdd0 pEulerIntegrate(btScalar(.5)*h, scratch_qdd0, scratch_qd0, scratch_qd1, numDofs); // //calc qdd1 from: q1 & qd1 pCopyToVelocityVector(bod, scratch_qd1); bod->stepVelocitiesMultiDof(0., scratch_r, scratch_v, scratch_m); pCopy(output, scratch_qdd1, 0, numDofs); //calc q2 = q0 + h/2 * qd1 pResetQx(); bod->stepPositionsMultiDof(btScalar(.5)*h, scratch_qx, scratch_qd1); //calc qd2 = qd0 + h/2 * qdd1 pEulerIntegrate(btScalar(.5)*h, scratch_qdd1, scratch_qd0, scratch_qd2, numDofs); // //calc qdd2 from: q2 & qd2 pCopyToVelocityVector(bod, scratch_qd2); bod->stepVelocitiesMultiDof(0., scratch_r, scratch_v, scratch_m); pCopy(output, scratch_qdd2, 0, numDofs); //calc q3 = q0 + h * qd2 pResetQx(); bod->stepPositionsMultiDof(h, scratch_qx, scratch_qd2); //calc qd3 = qd0 + h * qdd2 pEulerIntegrate(h, scratch_qdd2, scratch_qd0, scratch_qd3, numDofs); // //calc qdd3 from: q3 & qd3 pCopyToVelocityVector(bod, scratch_qd3); bod->stepVelocitiesMultiDof(0., scratch_r, scratch_v, scratch_m); pCopy(output, scratch_qdd3, 0, numDofs); // //calc q = q0 + h/6(qd0 + 2*(qd1 + qd2) + qd3) //calc qd = qd0 + h/6(qdd0 + 2*(qdd1 + qdd2) + qdd3) btAlignedObjectArray<btScalar> delta_q; delta_q.resize(numDofs); btAlignedObjectArray<btScalar> delta_qd; delta_qd.resize(numDofs); for(int i = 0; i < numDofs; ++i) { delta_q[i] = h/btScalar(6.)*(scratch_qd0[i] + 2*scratch_qd1[i] + 2*scratch_qd2[i] + scratch_qd3[i]); delta_qd[i] = h/btScalar(6.)*(scratch_qdd0[i] + 2*scratch_qdd1[i] + 2*scratch_qdd2[i] + scratch_qdd3[i]); //delta_q[i] = h*scratch_qd0[i]; //delta_qd[i] = h*scratch_qdd0[i]; } // pCopyToVelocityVector(bod, scratch_qd0); bod->applyDeltaVeeMultiDof(&delta_qd[0], 1); // if(!doNotUpdatePos) { btScalar *pRealBuf = const_cast<btScalar *>(bod->getVelocityVector()); pRealBuf += 6 + bod->getNumDofs() + bod->getNumDofs()*bod->getNumDofs(); for(int i = 0; i < numDofs; ++i) pRealBuf[i] = delta_q[i]; //bod->stepPositionsMultiDof(1, 0, &delta_q[0]); bod->setPosUpdated(true); } //ugly hack which resets the cached data to t0 (needed for constraint solver) { for(int link = 0; link < bod->getNumLinks(); ++link) bod->getLink(link).updateCacheMultiDof(); bod->stepVelocitiesMultiDof(0, scratch_r, scratch_v, scratch_m); } } } else//if(bod->isMultiDof()) { bod->stepVelocities(solverInfo.m_timeStep, scratch_r, scratch_v, scratch_m); } bod->clearForcesAndTorques(); }//if (!isSleeping) } } m_solverMultiBodyIslandCallback->processConstraints(); m_constraintSolver->allSolved(solverInfo, m_debugDrawer); } void btMultiBodyDynamicsWorld::integrateTransforms(btScalar timeStep) { btDiscreteDynamicsWorld::integrateTransforms(timeStep); { BT_PROFILE("btMultiBody stepPositions"); //integrate and update the Featherstone hierarchies btAlignedObjectArray<btQuaternion> world_to_local; btAlignedObjectArray<btVector3> local_origin; for (int b=0;b<m_multiBodies.size();b++) { btMultiBody* bod = m_multiBodies[b]; bool isSleeping = false; if (bod->getBaseCollider() && bod->getBaseCollider()->getActivationState() == ISLAND_SLEEPING) { isSleeping = true; } for (int b=0;b<bod->getNumLinks();b++) { if (bod->getLink(b).m_collider && bod->getLink(b).m_collider->getActivationState()==ISLAND_SLEEPING) isSleeping = true; } if (!isSleeping) { int nLinks = bod->getNumLinks(); ///base + num m_links world_to_local.resize(nLinks+1); local_origin.resize(nLinks+1); if(bod->isMultiDof()) { if(!bod->isPosUpdated()) bod->stepPositionsMultiDof(timeStep); else { btScalar *pRealBuf = const_cast<btScalar *>(bod->getVelocityVector()); pRealBuf += 6 + bod->getNumDofs() + bod->getNumDofs()*bod->getNumDofs(); bod->stepPositionsMultiDof(1, 0, pRealBuf); bod->setPosUpdated(false); } } else bod->stepPositions(timeStep); world_to_local[0] = bod->getWorldToBaseRot(); local_origin[0] = bod->getBasePos(); if (bod->getBaseCollider()) { btVector3 posr = local_origin[0]; // float pos[4]={posr.x(),posr.y(),posr.z(),1}; btScalar quat[4]={-world_to_local[0].x(),-world_to_local[0].y(),-world_to_local[0].z(),world_to_local[0].w()}; btTransform tr; tr.setIdentity(); tr.setOrigin(posr); tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3])); bod->getBaseCollider()->setWorldTransform(tr); } for (int k=0;k<bod->getNumLinks();k++) { const int parent = bod->getParent(k); world_to_local[k+1] = bod->getParentToLocalRot(k) * world_to_local[parent+1]; local_origin[k+1] = local_origin[parent+1] + (quatRotate(world_to_local[k+1].inverse() , bod->getRVector(k))); } for (int m=0;m<bod->getNumLinks();m++) { btMultiBodyLinkCollider* col = bod->getLink(m).m_collider; if (col) { int link = col->m_link; btAssert(link == m); int index = link+1; btVector3 posr = local_origin[index]; // float pos[4]={posr.x(),posr.y(),posr.z(),1}; btScalar quat[4]={-world_to_local[index].x(),-world_to_local[index].y(),-world_to_local[index].z(),world_to_local[index].w()}; btTransform tr; tr.setIdentity(); tr.setOrigin(posr); tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3])); col->setWorldTransform(tr); } } } else { bod->clearVelocities(); } } } } void btMultiBodyDynamicsWorld::addMultiBodyConstraint( btMultiBodyConstraint* constraint) { m_multiBodyConstraints.push_back(constraint); } void btMultiBodyDynamicsWorld::removeMultiBodyConstraint( btMultiBodyConstraint* constraint) { m_multiBodyConstraints.remove(constraint); } void btMultiBodyDynamicsWorld::debugDrawMultiBodyConstraint(btMultiBodyConstraint* constraint) { constraint->debugDraw(getDebugDrawer()); } void btMultiBodyDynamicsWorld::debugDrawWorld() { BT_PROFILE("btMultiBodyDynamicsWorld debugDrawWorld"); bool drawConstraints = false; if (getDebugDrawer()) { int mode = getDebugDrawer()->getDebugMode(); if (mode & (btIDebugDraw::DBG_DrawConstraints | btIDebugDraw::DBG_DrawConstraintLimits)) { drawConstraints = true; } if (drawConstraints) { BT_PROFILE("btMultiBody debugDrawWorld"); btAlignedObjectArray<btQuaternion> world_to_local; btAlignedObjectArray<btVector3> local_origin; for (int c=0;c<m_multiBodyConstraints.size();c++) { btMultiBodyConstraint* constraint = m_multiBodyConstraints[c]; debugDrawMultiBodyConstraint(constraint); } for (int b = 0; b<m_multiBodies.size(); b++) { btMultiBody* bod = m_multiBodies[b]; int nLinks = bod->getNumLinks(); ///base + num m_links world_to_local.resize(nLinks + 1); local_origin.resize(nLinks + 1); world_to_local[0] = bod->getWorldToBaseRot(); local_origin[0] = bod->getBasePos(); { btVector3 posr = local_origin[0]; // float pos[4]={posr.x(),posr.y(),posr.z(),1}; btScalar quat[4] = { -world_to_local[0].x(), -world_to_local[0].y(), -world_to_local[0].z(), world_to_local[0].w() }; btTransform tr; tr.setIdentity(); tr.setOrigin(posr); tr.setRotation(btQuaternion(quat[0], quat[1], quat[2], quat[3])); getDebugDrawer()->drawTransform(tr, 0.1); } for (int k = 0; k<bod->getNumLinks(); k++) { const int parent = bod->getParent(k); world_to_local[k + 1] = bod->getParentToLocalRot(k) * world_to_local[parent + 1]; local_origin[k + 1] = local_origin[parent + 1] + (quatRotate(world_to_local[k + 1].inverse(), bod->getRVector(k))); } for (int m = 0; m<bod->getNumLinks(); m++) { int link = m; int index = link + 1; btVector3 posr = local_origin[index]; // float pos[4]={posr.x(),posr.y(),posr.z(),1}; btScalar quat[4] = { -world_to_local[index].x(), -world_to_local[index].y(), -world_to_local[index].z(), world_to_local[index].w() }; btTransform tr; tr.setIdentity(); tr.setOrigin(posr); tr.setRotation(btQuaternion(quat[0], quat[1], quat[2], quat[3])); getDebugDrawer()->drawTransform(tr, 0.1); } } } } btDiscreteDynamicsWorld::debugDrawWorld(); }
LauriM/PropellerEngine
thirdparty/Bullet/src/BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.cpp
C++
bsd-2-clause
27,139
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai 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/ECL-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.sakaiproject.portal.api; import java.util.List; import java.util.Map; import org.sakaiproject.site.api.Site; /** * @author ieb * */ public interface PageFilter { /** * @param newPages * @param site * @return */ List filter(List newPages, Site site); /** * Filter the list of placements, potentially making them hierachical if required * @param l * @param site * @return */ List<Map> filterPlacements(List<Map> l, Site site); }
bzhouduke123/sakai
portal/portal-api/api/src/java/org/sakaiproject/portal/api/PageFilter.java
Java
apache-2.0
1,396
#!/usr/bin/env node var DocGenerator = require('../lib/utilities/doc-generator.js'); (new DocGenerator()).generate();
waddedMeat/ember-proxy-example
test-app/node_modules/ember-cli/bin/generate-docs.js
JavaScript
mit
119
// 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.Collections.Generic; using System.Linq; using System.Reflection; namespace Microsoft.Internal { internal static class AttributeServices { // MemberInfo Attribute helpers public static IEnumerable<T> GetAttributes<T>(this MemberInfo memberInfo) where T : System.Attribute { return memberInfo.GetCustomAttributes<T>(false); } public static IEnumerable<T> GetAttributes<T>(this MemberInfo memberInfo, bool inherit) where T : System.Attribute { return memberInfo.GetCustomAttributes<T>(inherit); } public static T GetFirstAttribute<T>(this MemberInfo memberInfo) where T : System.Attribute { return GetAttributes<T>(memberInfo).FirstOrDefault(); } public static T GetFirstAttribute<T>(this MemberInfo memberInfo, bool inherit) where T : System.Attribute { return GetAttributes<T>(memberInfo, inherit).FirstOrDefault(); } public static bool IsAttributeDefined<T>(this MemberInfo memberInfo) where T : System.Attribute { return memberInfo.IsDefined(typeof(T), false); } public static bool IsAttributeDefined<T>(this MemberInfo memberInfo, bool inherit) where T : System.Attribute { return memberInfo.IsDefined(typeof(T), inherit); } // ParameterInfo Attribute helpers public static IEnumerable<T> GetAttributes<T>(this ParameterInfo parameterInfo) where T : System.Attribute { return parameterInfo.GetCustomAttributes<T>(false); } public static IEnumerable<T> GetAttributes<T>(this ParameterInfo parameterInfo, bool inherit) where T : System.Attribute { return parameterInfo.GetCustomAttributes<T>(inherit); } public static T GetFirstAttribute<T>(this ParameterInfo parameterInfo) where T : System.Attribute { return GetAttributes<T>(parameterInfo).FirstOrDefault(); } public static T GetFirstAttribute<T>(this ParameterInfo parameterInfo, bool inherit) where T : System.Attribute { return GetAttributes<T>(parameterInfo, inherit).FirstOrDefault(); } public static bool IsAttributeDefined<T>(this ParameterInfo parameterInfo) where T : System.Attribute { return parameterInfo.IsDefined(typeof(T), false); } public static bool IsAttributeDefined<T>(this ParameterInfo parameterInfo, bool inherit) where T : System.Attribute { return parameterInfo.IsDefined(typeof(T), inherit); } } }
iamjasonp/corefx
src/System.Composition.Convention/src/Microsoft/Internal/AttributeServices.cs
C#
mit
2,881
package rancher import ( "testing" "github.com/hashicorp/terraform/helper/resource" ) func TestAccRancherEnvironment_importBasic(t *testing.T) { resourceName := "rancher_environment.foo" resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckRancherEnvironmentDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccRancherEnvironmentConfig, }, resource.TestStep{ ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) }
stardog-union/stardog-graviton
vendor/github.com/hashicorp/terraform/builtin/providers/rancher/import_rancher_environment_test.go
GO
apache-2.0
605
<?php namespace Gliph\Visitor; /** * Interface for stateful algorithm visitors. */ interface StatefulVisitorInterface { const NOT_STARTED = 0; const IN_PROGRESS = 1; const COMPLETE = 2; /** * Returns an integer indicating the current state of the visitor. * * @return int * State should be one of the three StatefulVisitorInterface constants: * - 0: indicates the algorithm has not yet started. * - 1: indicates the algorithm is in progress. * - 2: indicates the algorithm is complete. */ public function getState(); }
webflo/d8-core
vendor/sdboyer/gliph/src/Gliph/Visitor/StatefulVisitorInterface.php
PHP
gpl-2.0
594
cask 'pocket-tanks' do version :latest sha256 :no_check url 'http://www.blitwise.com/ptanks_mac.dmg' name 'Pocket Tanks' homepage 'http://www.blitwise.com/index.html' app 'Pocket Tanks.app' end
wastrachan/homebrew-cask
Casks/pocket-tanks.rb
Ruby
bsd-2-clause
208
// Utility functions String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g, ''); }; function supportsHtmlStorage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } } function get_text(el) { ret = " "; var length = el.childNodes.length; for(var i = 0; i < length; i++) { var node = el.childNodes[i]; if(node.nodeType != 8) { if ( node.nodeType != 1 ) { // Strip white space. ret += node.nodeValue; } else { ret += get_text( node ); } } } return ret.trim(); }
sandbox-team/techtalk-portal
vendor/zenpen/js/utils.js
JavaScript
mit
641
using System; namespace Notifications.Model { public interface IScenario { string Name { get; } bool Contains(Type scenarioType); Scenario FindScenario(Type scenarioType); } }
TA-Team-Giant/PAaaS
pAaaS/Notifications/Model/IScenario.cs
C#
mit
218
/* */ module.exports = { "default": require("core-js/library/fn/math/sign"), __esModule: true };
pauldijou/outdated
test/basic/jspm_packages/npm/babel-runtime@5.8.9/core-js/math/sign.js
JavaScript
apache-2.0
97
require 'formula' class Avce00 < Formula homepage 'http://avce00.maptools.org/avce00/index.html' url 'http://avce00.maptools.org/dl/avce00-2.0.0.tar.gz' sha1 '2948d9b1cfb6e80faf2e9b90c86fd224617efd75' def install system "make", "CC=#{ENV.cc}" bin.install "avcimport", "avcexport", "avcdelete", "avctest" end end
jtrag/homebrew
Library/Formula/avce00.rb
Ruby
bsd-2-clause
333
function loadedScript() { return "externalScript1"; }
nwjs/chromium.src
third_party/blink/web_tests/external/wpt/svg/linking/scripted/testScripts/externalScript1.js
JavaScript
bsd-3-clause
56
/** * angular-strap * @version v2.1.2 - 2014-10-19 * @link http://mgcrea.github.io/angular-strap * @author Olivier Louvignes (olivier@mg-crea.com) * @license MIT License, http://www.opensource.org/licenses/MIT */ 'use strict'; angular.module('mgcrea.ngStrap.popover').run(['$templateCache', function($templateCache) { $templateCache.put('popover/popover.tpl.html', '<div class="popover"><div class="arrow"></div><h3 class="popover-title" ng-bind="title" ng-show="title"></h3><div class="popover-content" ng-bind="content"></div></div>'); }]);
radhikabhanu/crowdsource-platform
staticfiles/bower_components/angular-strap/dist/modules/popover.tpl.js
JavaScript
mit
553
/* * Copyright (C) 2011 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WKMediaCacheManager.h" #include "WKAPICast.h" #include "WebMediaCacheManagerProxy.h" using namespace WebKit; WKTypeID WKMediaCacheManagerGetTypeID() { return toAPI(WebMediaCacheManagerProxy::APIType); } void WKMediaCacheManagerGetHostnamesWithMediaCache(WKMediaCacheManagerRef mediaCacheManagerRef, void* context, WKMediaCacheManagerGetHostnamesWithMediaCacheFunction callback) { toImpl(mediaCacheManagerRef)->getHostnamesWithMediaCache(ArrayCallback::create(context, callback)); } void WKMediaCacheManagerClearCacheForHostname(WKMediaCacheManagerRef mediaCacheManagerRef, WKStringRef hostname) { toImpl(mediaCacheManagerRef)->clearCacheForHostname(toWTFString(hostname)); } void WKMediaCacheManagerClearCacheForAllHostnames(WKMediaCacheManagerRef mediaCacheManagerRef) { toImpl(mediaCacheManagerRef)->clearCacheForAllHostnames(); }
danialbehzadi/Nokia-RM-1013-2.0.0.11
webkit/Source/WebKit2/UIProcess/API/C/WKMediaCacheManager.cpp
C++
gpl-3.0
2,241
require('./angular-locale_nl-cw'); module.exports = 'ngLocale';
DamascenoRafael/cos482-qualidade-de-software
www/src/main/webapp/bower_components/angular-i18n/nl-cw.js
JavaScript
mit
64
require('./angular-locale_en-im'); module.exports = 'ngLocale';
DamascenoRafael/cos482-qualidade-de-software
www/src/main/webapp/bower_components/angular-i18n/en-im.js
JavaScript
mit
64
var assert = require('assert'); var Kareem = require('../'); describe('execPre', function() { var hooks; beforeEach(function() { hooks = new Kareem(); }); it('handles errors with multiple pres', function(done) { var execed = {}; hooks.pre('cook', function(done) { execed.first = true; done(); }); hooks.pre('cook', function(done) { execed.second = true; done('error!'); }); hooks.pre('cook', function(done) { execed.third = true; done(); }); hooks.execPre('cook', null, function(err) { assert.equal('error!', err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('handles async errors', function(done) { var execed = {}; hooks.pre('cook', true, function(next, done) { execed.first = true; setTimeout( function() { done('error!'); }, 5); next(); }); hooks.pre('cook', true, function(next, done) { execed.second = true; setTimeout( function() { done('other error!'); }, 10); next(); }); hooks.execPre('cook', null, function(err) { assert.equal('error!', err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('handles async errors in next()', function(done) { var execed = {}; hooks.pre('cook', true, function(next, done) { execed.first = true; setTimeout( function() { done('other error!'); }, 15); next(); }); hooks.pre('cook', true, function(next, done) { execed.second = true; setTimeout( function() { next('error!'); done('another error!'); }, 5); }); hooks.execPre('cook', null, function(err) { assert.equal('error!', err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('handles async errors in next() when already done', function(done) { var execed = {}; hooks.pre('cook', true, function(next, done) { execed.first = true; setTimeout( function() { done('other error!'); }, 5); next(); }); hooks.pre('cook', true, function(next, done) { execed.second = true; setTimeout( function() { next('error!'); done('another error!'); }, 25); }); hooks.execPre('cook', null, function(err) { assert.equal('other error!', err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('async pres with clone()', function(done) { var execed = false; hooks.pre('cook', true, function(next, done) { execed = true; setTimeout( function() { done(); }, 5); next(); }); hooks.clone().execPre('cook', null, function(err) { assert.ifError(err); assert.ok(execed); done(); }); }); it('returns correct error when async pre errors', function(done) { var execed = {}; hooks.pre('cook', true, function(next, done) { execed.first = true; setTimeout( function() { done('other error!'); }, 5); next(); }); hooks.pre('cook', function(next) { execed.second = true; setTimeout( function() { next('error!'); }, 15); }); hooks.execPre('cook', null, function(err) { assert.equal('other error!', err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('lets async pres run when fully sync pres are done', function(done) { var execed = {}; hooks.pre('cook', true, function(next, done) { execed.first = true; setTimeout( function() { done(); }, 5); next(); }); hooks.pre('cook', function() { execed.second = true; }); hooks.execPre('cook', null, function(err) { assert.ifError(err); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); done(); }); }); it('allows passing arguments to the next pre', function(done) { var execed = {}; hooks.pre('cook', function(next) { execed.first = true; next(null, 'test'); }); hooks.pre('cook', function(next, p) { execed.second = true; assert.equal(p, 'test'); next(); }); hooks.pre('cook', function(next, p) { execed.third = true; assert.ok(!p); next(); }); hooks.execPre('cook', null, function(err) { assert.ifError(err); assert.equal(3, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); assert.ok(execed.third); done(); }); }); }); describe('execPreSync', function() { var hooks; beforeEach(function() { hooks = new Kareem(); }); it('executes hooks synchronously', function() { var execed = {}; hooks.pre('cook', function() { execed.first = true; }); hooks.pre('cook', function() { execed.second = true; }); hooks.execPreSync('cook', null); assert.ok(execed.first); assert.ok(execed.second); }); it('works with no hooks specified', function() { assert.doesNotThrow(function() { hooks.execPreSync('cook', null); }); }); });
ChrisChenSZ/code
表单注册验证/node_modules/kareem/test/pre.test.js
JavaScript
apache-2.0
5,771
var s = `a b c`; assert.equal(s, 'a\n b\n c');
oleksandr-minakov/northshore
ui/node_modules/es6-templates/test/examples/multi-line.js
JavaScript
apache-2.0
61
// { dg-do assemble } // Copyright (C) 2000 Free Software Foundation // Contributed by Kriang Lerdsuwanakij <lerdsuwa@users.sourceforge.net> // Bug: We used reject template unification of two bound template template // parameters. template <class T, class U=int> class C { }; template <class T, class U> void f(C<T,U> c) { } template <class T> void f(C<T> c) { } template <template<class,class=int> class C, class T, class U> void g(C<T,U> c) { } template <template<class,class=int> class C, class T> void g(C<T> c) { } int main() { C<int,char> c1; f(c1); g(c1); C<int,int> c2; f(c2); g(c2); }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.old-deja/g++.pt/ttp65.C
C++
gpl-2.0
615
var gulp = require('gulp'); var browserSync = require('browser-sync'); var sass = require('gulp-sass'); var reload = browserSync.reload; var src = { scss: 'app/scss/*.scss', css: 'app/css', html: 'app/*.html' }; // Static Server + watching scss/html files gulp.task('serve', ['sass'], function() { browserSync({ server: "./app" }); gulp.watch(src.scss, ['sass']); gulp.watch(src.html).on('change', reload); }); // Compile sass into CSS gulp.task('sass', function() { return gulp.src(src.scss) .pipe(sass()) .pipe(gulp.dest(src.css)) .pipe(reload({stream: true})); }); gulp.task('default', ['serve']);
yuyang545262477/Resume
项目二电商首页/node_modules/bs-recipes/recipes/gulp.sass/gulpfile.js
JavaScript
mit
691