code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/aura/root_window_host_linux.h" #include <X11/Xatom.h> #include <X11/cursorfont.h> #include <X11/extensions/XInput2.h> #include <X11/extensions/Xfixes.h> #include <X11/extensions/Xrandr.h> #include <algorithm> #include "base/message_pump_x.h" #include "base/stl_util.h" #include "base/stringprintf.h" #include "ui/aura/client/user_gesture_client.h" #include "ui/aura/dispatcher_linux.h" #include "ui/aura/env.h" #include "ui/aura/event.h" #include "ui/aura/root_window.h" #include "ui/base/cursor/cursor.h" #include "ui/base/keycodes/keyboard_codes.h" #include "ui/base/touch/touch_factory.h" #include "ui/base/x/x11_util.h" #include "ui/base/view_prop.h" #include "ui/gfx/compositor/layer.h" using std::max; using std::min; namespace aura { namespace { // Standard Linux mouse buttons for going back and forward. const int kBackMouseButton = 8; const int kForwardMouseButton = 9; const char kRootWindowHostLinuxKey[] = "__AURA_ROOT_WINDOW_HOST_LINUX__"; // The events reported for slave devices can have incorrect information for some // fields. This utility function is used to check for such inconsistencies. void CheckXEventForConsistency(XEvent* xevent) { static bool expect_master_event = false; static XIDeviceEvent slave_event; static gfx::Point slave_location; static int slave_button; // Note: If an event comes from a slave pointer device, then it will be // followed by the same event, but reported from its master pointer device. // However, if the event comes from a floating slave device (e.g. a // touchscreen), then it will not be followed by a duplicate event, since the // floating slave isn't attached to a master. bool was_expecting_master_event = expect_master_event; expect_master_event = false; if (!xevent || xevent->type != GenericEvent) return; XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(xevent->xcookie.data); if (xievent->evtype != XI_Motion && xievent->evtype != XI_ButtonPress && xievent->evtype != XI_ButtonRelease) { return; } if (xievent->sourceid == xievent->deviceid) { slave_event = *xievent; slave_location = ui::EventLocationFromNative(xevent); slave_button = ui::EventButtonFromNative(xevent); expect_master_event = true; } else if (was_expecting_master_event) { CHECK_EQ(slave_location.x(), ui::EventLocationFromNative(xevent).x()); CHECK_EQ(slave_location.y(), ui::EventLocationFromNative(xevent).y()); CHECK_EQ(slave_event.type, xievent->type); CHECK_EQ(slave_event.evtype, xievent->evtype); CHECK_EQ(slave_button, ui::EventButtonFromNative(xevent)); CHECK_EQ(slave_event.flags, xievent->flags); CHECK_EQ(slave_event.buttons.mask_len, xievent->buttons.mask_len); CHECK_EQ(slave_event.valuators.mask_len, xievent->valuators.mask_len); CHECK_EQ(slave_event.mods.base, xievent->mods.base); CHECK_EQ(slave_event.mods.latched, xievent->mods.latched); CHECK_EQ(slave_event.mods.locked, xievent->mods.locked); CHECK_EQ(slave_event.mods.effective, xievent->mods.effective); } } // Returns X font cursor shape from an Aura cursor. int CursorShapeFromNative(gfx::NativeCursor native_cursor) { switch (native_cursor.native_type()) { case ui::kCursorNull: return XC_left_ptr; case ui::kCursorPointer: return XC_left_ptr; case ui::kCursorCross: return XC_crosshair; case ui::kCursorHand: return XC_hand2; case ui::kCursorIBeam: return XC_xterm; case ui::kCursorWait: return XC_watch; case ui::kCursorHelp: return XC_question_arrow; case ui::kCursorEastResize: return XC_right_side; case ui::kCursorNorthResize: return XC_top_side; case ui::kCursorNorthEastResize: return XC_top_right_corner; case ui::kCursorNorthWestResize: return XC_top_left_corner; case ui::kCursorSouthResize: return XC_bottom_side; case ui::kCursorSouthEastResize: return XC_bottom_right_corner; case ui::kCursorSouthWestResize: return XC_bottom_left_corner; case ui::kCursorWestResize: return XC_left_side; case ui::kCursorNorthSouthResize: return XC_sb_v_double_arrow; case ui::kCursorEastWestResize: return XC_sb_h_double_arrow; case ui::kCursorNorthEastSouthWestResize: case ui::kCursorNorthWestSouthEastResize: // There isn't really a useful cursor available for these. return XC_left_ptr; case ui::kCursorColumnResize: return XC_sb_h_double_arrow; case ui::kCursorRowResize: return XC_sb_v_double_arrow; case ui::kCursorMiddlePanning: return XC_fleur; case ui::kCursorEastPanning: return XC_sb_right_arrow; case ui::kCursorNorthPanning: return XC_sb_up_arrow; case ui::kCursorNorthEastPanning: return XC_top_right_corner; case ui::kCursorNorthWestPanning: return XC_top_left_corner; case ui::kCursorSouthPanning: return XC_sb_down_arrow; case ui::kCursorSouthEastPanning: return XC_bottom_right_corner; case ui::kCursorSouthWestPanning: return XC_bottom_left_corner; case ui::kCursorWestPanning: return XC_sb_left_arrow; case ui::kCursorMove: return XC_fleur; case ui::kCursorVerticalText: case ui::kCursorCell: case ui::kCursorContextMenu: case ui::kCursorAlias: case ui::kCursorProgress: case ui::kCursorNoDrop: case ui::kCursorCopy: case ui::kCursorNone: case ui::kCursorNotAllowed: case ui::kCursorZoomIn: case ui::kCursorZoomOut: case ui::kCursorGrab: case ui::kCursorGrabbing: // TODO(jamescook): Need cursors for these. crbug.com/111650 return XC_left_ptr; case ui::kCursorCustom: NOTREACHED(); return XC_left_ptr; } NOTREACHED(); return XC_left_ptr; } // Coalesce all pending motion events that are at the top of the queue, and // return the number eliminated, storing the last one in |last_event|. int CoalescePendingXIMotionEvents(const XEvent* xev, XEvent* last_event) { XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(xev->xcookie.data); int num_coalesed = 0; Display* display = xev->xany.display; while (XPending(display)) { XEvent next_event; XPeekEvent(display, &next_event); // If we can't get the cookie, abort the check. if (!XGetEventData(next_event.xgeneric.display, &next_event.xcookie)) return num_coalesed; // If this isn't from a valid device, throw the event away, as // that's what the message pump would do. Device events come in pairs // with one from the master and one from the slave so there will // always be at least one pending. if (!ui::TouchFactory::GetInstance()->ShouldProcessXI2Event(&next_event)) { // See crbug.com/109884. // CheckXEventForConsistency(&next_event); XFreeEventData(display, &next_event.xcookie); XNextEvent(display, &next_event); continue; } if (next_event.type == GenericEvent && next_event.xgeneric.evtype == XI_Motion && !ui::GetScrollOffsets(&next_event, NULL, NULL)) { XIDeviceEvent* next_xievent = static_cast<XIDeviceEvent*>(next_event.xcookie.data); // Confirm that the motion event is targeted at the same window // and that no buttons or modifiers have changed. if (xievent->event == next_xievent->event && xievent->child == next_xievent->child && xievent->buttons.mask_len == next_xievent->buttons.mask_len && (memcmp(xievent->buttons.mask, next_xievent->buttons.mask, xievent->buttons.mask_len) == 0) && xievent->mods.base == next_xievent->mods.base && xievent->mods.latched == next_xievent->mods.latched && xievent->mods.locked == next_xievent->mods.locked && xievent->mods.effective == next_xievent->mods.effective) { XFreeEventData(display, &next_event.xcookie); // Free the previous cookie. if (num_coalesed > 0) XFreeEventData(display, &last_event->xcookie); // Get the event and its cookie data. XNextEvent(display, last_event); XGetEventData(display, &last_event->xcookie); // See crbug.com/109884. // CheckXEventForConsistency(last_event); ++num_coalesed; continue; } else { // This isn't an event we want so free its cookie data. XFreeEventData(display, &next_event.xcookie); } } break; } return num_coalesed; } // We emulate Windows' WM_KEYDOWN and WM_CHAR messages. WM_CHAR events are only // generated for certain keys; see // http://msdn.microsoft.com/en-us/library/windows/desktop/ms646268.aspx. Per // discussion on http://crbug.com/108480, char events should furthermore not be // generated for Tab, Escape, and Backspace. bool ShouldSendCharEventForKeyboardCode(ui::KeyboardCode keycode) { if ((keycode >= ui::VKEY_0 && keycode <= ui::VKEY_9) || (keycode >= ui::VKEY_A && keycode <= ui::VKEY_Z) || (keycode >= ui::VKEY_NUMPAD0 && keycode <= ui::VKEY_NUMPAD9)) { return true; } switch (keycode) { case ui::VKEY_RETURN: case ui::VKEY_SPACE: // In addition to the keys listed at MSDN, we include other // graphic-character and numpad keys. case ui::VKEY_MULTIPLY: case ui::VKEY_ADD: case ui::VKEY_SUBTRACT: case ui::VKEY_DECIMAL: case ui::VKEY_DIVIDE: case ui::VKEY_OEM_1: case ui::VKEY_OEM_2: case ui::VKEY_OEM_3: case ui::VKEY_OEM_4: case ui::VKEY_OEM_5: case ui::VKEY_OEM_6: case ui::VKEY_OEM_7: case ui::VKEY_OEM_102: case ui::VKEY_OEM_PLUS: case ui::VKEY_OEM_COMMA: case ui::VKEY_OEM_MINUS: case ui::VKEY_OEM_PERIOD: return true; default: return false; } } // A list of atoms that we'll intern on host creation to save roundtrips to the // X11 server. Must be kept in sync with RootWindowHostLinux::AtomList const char* kAtomList[] = { "WM_DELETE_WINDOW", "_NET_WM_PING", "_NET_WM_PID", "WM_S0" }; } // namespace RootWindowHostLinux::RootWindowHostLinux(const gfx::Rect& bounds) : root_window_(NULL), xdisplay_(base::MessagePumpX::GetDefaultXDisplay()), xwindow_(0), x_root_window_(DefaultRootWindow(xdisplay_)), current_cursor_(ui::kCursorNull), cursor_shown_(true), bounds_(bounds), focus_when_shown_(false), pointer_barriers_(NULL) { XSetWindowAttributes swa; memset(&swa, 0, sizeof(swa)); swa.background_pixmap = None; xwindow_ = XCreateWindow( xdisplay_, x_root_window_, bounds.x(), bounds.y(), bounds.width(), bounds.height(), 0, // border width CopyFromParent, // depth InputOutput, CopyFromParent, // visual CWBackPixmap, &swa); static_cast<DispatcherLinux*>(Env::GetInstance()->GetDispatcher())-> WindowDispatcherCreated(xwindow_, this); prop_.reset(new ui::ViewProp(xwindow_, kRootWindowHostLinuxKey, this)); long event_mask = ButtonPressMask | ButtonReleaseMask | FocusChangeMask | KeyPressMask | KeyReleaseMask | EnterWindowMask | LeaveWindowMask | ExposureMask | VisibilityChangeMask | StructureNotifyMask | PropertyChangeMask | PointerMotionMask; XSelectInput(xdisplay_, xwindow_, event_mask); XFlush(xdisplay_); if (base::MessagePumpForUI::HasXInput2()) ui::TouchFactory::GetInstance()->SetupXI2ForXWindow(xwindow_); // Initialize invisible cursor. char nodata[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; XColor black; black.red = black.green = black.blue = 0; Pixmap blank = XCreateBitmapFromData(xdisplay_, xwindow_, nodata, 8, 8); invisible_cursor_ = XCreatePixmapCursor(xdisplay_, blank, blank, &black, &black, 0, 0); XFreePixmap(xdisplay_, blank); if (RootWindow::hide_host_cursor()) XDefineCursor(xdisplay_, x_root_window_, invisible_cursor_); // Grab all the atoms we need now to minimize roundtrips to the X11 server. XInternAtoms(xdisplay_, const_cast<char**>(kAtomList), ATOM_COUNT, False, cached_atoms_); // TODO(erg): We currently only request window deletion events. We also // should listen for activation events and anything else that GTK+ listens // for, and do something useful. ::Atom protocols[2]; protocols[0] = cached_atoms_[ATOM_WM_DELETE_WINDOW]; protocols[1] = cached_atoms_[ATOM__NET_WM_PING]; XSetWMProtocols(xdisplay_, xwindow_, protocols, 2); // We need a WM_CLIENT_MACHINE and WM_LOCALE_NAME value so we integrate with // the desktop environment. XSetWMProperties(xdisplay_, xwindow_, NULL, NULL, NULL, 0, NULL, NULL, NULL); // Likewise, the X server needs to know this window's pid so it knows which // program to kill if the window hangs. pid_t pid = getpid(); XChangeProperty(xdisplay_, xwindow_, cached_atoms_[ATOM__NET_WM_PID], XA_CARDINAL, 32, PropModeReplace, reinterpret_cast<unsigned char*>(&pid), 1); // crbug.com/120229 - set the window title so gtalk can find the primary root // window to broadcast. // TODO(jhorwich) Remove this once Chrome supports window-based broadcasting. static int root_window_number = 0; std::string name = StringPrintf("aura_root_%d", root_window_number++); XStoreName(xdisplay_, xwindow_, name.c_str()); } RootWindowHostLinux::~RootWindowHostLinux() { static_cast<DispatcherLinux*>(Env::GetInstance()->GetDispatcher())-> WindowDispatcherDestroying(xwindow_); UnConfineCursor(); XDestroyWindow(xdisplay_, xwindow_); // Clears XCursorCache. ui::GetXCursor(ui::kCursorClearXCursorCache); XFreeCursor(xdisplay_, invisible_cursor_); } bool RootWindowHostLinux::Dispatch(const base::NativeEvent& event) { XEvent* xev = event; // See crbug.com/109884. // CheckXEventForConsistency(xev); switch (xev->type) { case Expose: root_window_->ScheduleFullDraw(); break; case KeyPress: { KeyEvent keydown_event(xev, false); root_window_->DispatchKeyEvent(&keydown_event); break; } case KeyRelease: { KeyEvent keyup_event(xev, false); root_window_->DispatchKeyEvent(&keyup_event); break; } case ButtonPress: { if (static_cast<int>(xev->xbutton.button) == kBackMouseButton || static_cast<int>(xev->xbutton.button) == kForwardMouseButton) { client::UserGestureClient* gesture_client = client::GetUserGestureClient(root_window_); if (gesture_client) { gesture_client->OnUserGesture( static_cast<int>(xev->xbutton.button) == kBackMouseButton ? client::UserGestureClient::GESTURE_BACK : client::UserGestureClient::GESTURE_FORWARD); } break; } } // fallthrough case ButtonRelease: { MouseEvent mouseev(xev); root_window_->DispatchMouseEvent(&mouseev); break; } case FocusOut: if (xev->xfocus.mode != NotifyGrab) root_window_->SetCapture(NULL, 0); break; case ConfigureNotify: { DCHECK_EQ(xwindow_, xev->xconfigure.window); DCHECK_EQ(xwindow_, xev->xconfigure.event); // Update barrier and mouse location when the root window has // moved/resized. if (pointer_barriers_.get()) { UnConfineCursor(); gfx::Point p = root_window_->last_mouse_location(); XWarpPointer(xdisplay_, None, xwindow_, 0, 0, 0, 0, p.x(), p.y()); ConfineCursorToRootWindow(); } // It's possible that the X window may be resized by some other means than // from within aura (e.g. the X window manager can change the size). Make // sure the root window size is maintained properly. gfx::Rect bounds(xev->xconfigure.x, xev->xconfigure.y, xev->xconfigure.width, xev->xconfigure.height); bool size_changed = bounds_.size() != bounds.size(); bounds_ = bounds; if (size_changed) root_window_->OnHostResized(bounds.size()); break; } case GenericEvent: { ui::TouchFactory* factory = ui::TouchFactory::GetInstance(); if (!factory->ShouldProcessXI2Event(xev)) break; ui::EventType type = ui::EventTypeFromNative(xev); XEvent last_event; int num_coalesced = 0; switch (type) { case ui::ET_TOUCH_PRESSED: case ui::ET_TOUCH_RELEASED: case ui::ET_TOUCH_MOVED: { TouchEvent touchev(xev); root_window_->DispatchTouchEvent(&touchev); break; } case ui::ET_MOUSE_MOVED: case ui::ET_MOUSE_DRAGGED: case ui::ET_MOUSE_PRESSED: case ui::ET_MOUSE_RELEASED: case ui::ET_MOUSEWHEEL: case ui::ET_MOUSE_ENTERED: case ui::ET_MOUSE_EXITED: { if (type == ui::ET_MOUSE_MOVED || type == ui::ET_MOUSE_DRAGGED) { // If this is a motion event, we want to coalesce all pending motion // events that are at the top of the queue. num_coalesced = CoalescePendingXIMotionEvents(xev, &last_event); if (num_coalesced > 0) xev = &last_event; } else if (type == ui::ET_MOUSE_PRESSED) { XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(xev->xcookie.data); int button = xievent->detail; if (button == kBackMouseButton || button == kForwardMouseButton) { client::UserGestureClient* gesture_client = client::GetUserGestureClient(root_window_); if (gesture_client) { bool reverse_direction = ui::IsTouchpadEvent(xev) && ui::IsNaturalScrollEnabled(); gesture_client->OnUserGesture( (button == kBackMouseButton && !reverse_direction) || (button == kForwardMouseButton && reverse_direction) ? client::UserGestureClient::GESTURE_BACK : client::UserGestureClient::GESTURE_FORWARD); } break; } } MouseEvent mouseev(xev); root_window_->DispatchMouseEvent(&mouseev); break; } case ui::ET_SCROLL_FLING_START: case ui::ET_SCROLL_FLING_CANCEL: case ui::ET_SCROLL: { ScrollEvent scrollev(xev); root_window_->DispatchScrollEvent(&scrollev); break; } case ui::ET_UNKNOWN: break; default: NOTREACHED(); } // If we coalesced an event we need to free its cookie. if (num_coalesced > 0) XFreeEventData(xev->xgeneric.display, &last_event.xcookie); break; } case MapNotify: { // If there's no window manager running, we need to assign the X input // focus to our host window. if (!IsWindowManagerPresent() && focus_when_shown_) XSetInputFocus(xdisplay_, xwindow_, RevertToNone, CurrentTime); break; } case ClientMessage: { Atom message_type = static_cast<Atom>(xev->xclient.data.l[0]); if (message_type == cached_atoms_[ATOM_WM_DELETE_WINDOW]) { // We have received a close message from the window manager. root_window_->OnRootWindowHostClosed(); } else if (message_type == cached_atoms_[ATOM__NET_WM_PING]) { XEvent reply_event = *xev; reply_event.xclient.window = x_root_window_; XSendEvent(xdisplay_, reply_event.xclient.window, False, SubstructureRedirectMask | SubstructureNotifyMask, &reply_event); } break; } case MappingNotify: { switch (xev->xmapping.request) { case MappingModifier: case MappingKeyboard: XRefreshKeyboardMapping(&xev->xmapping); root_window_->OnKeyboardMappingChanged(); break; case MappingPointer: ui::UpdateButtonMap(); break; default: NOTIMPLEMENTED() << " Unknown request: " << xev->xmapping.request; break; } break; } case MotionNotify: { // Discard all but the most recent motion event that targets the same // window with unchanged state. XEvent last_event; while (XPending(xev->xany.display)) { XEvent next_event; XPeekEvent(xev->xany.display, &next_event); if (next_event.type == MotionNotify && next_event.xmotion.window == xev->xmotion.window && next_event.xmotion.subwindow == xev->xmotion.subwindow && next_event.xmotion.state == xev->xmotion.state) { XNextEvent(xev->xany.display, &last_event); xev = &last_event; } else { break; } } MouseEvent mouseev(xev); root_window_->DispatchMouseEvent(&mouseev); break; } } return true; } void RootWindowHostLinux::SetRootWindow(RootWindow* root_window) { root_window_ = root_window; } RootWindow* RootWindowHostLinux::GetRootWindow() { return root_window_; } gfx::AcceleratedWidget RootWindowHostLinux::GetAcceleratedWidget() { return xwindow_; } void RootWindowHostLinux::Show() { // Before we map the window, set size hints. Otherwise, some window managers // will ignore toplevel XMoveWindow commands. XSizeHints size_hints; size_hints.flags = PPosition; size_hints.x = bounds_.x(); size_hints.y = bounds_.y(); XSetWMNormalHints(xdisplay_, xwindow_, &size_hints); XMapWindow(xdisplay_, xwindow_); } void RootWindowHostLinux::ToggleFullScreen() { NOTIMPLEMENTED(); } gfx::Rect RootWindowHostLinux::GetBounds() const { return bounds_; } void RootWindowHostLinux::SetBounds(const gfx::Rect& bounds) { bool size_changed = bounds_.size() != bounds.size(); if (bounds == bounds_) { root_window_->SchedulePaintInRect(root_window_->bounds()); return; } if (bounds.size() != bounds_.size()) XResizeWindow(xdisplay_, xwindow_, bounds.width(), bounds.height()); if (bounds.origin() != bounds_.origin()) XMoveWindow(xdisplay_, xwindow_, bounds.x(), bounds.y()); // Assume that the resize will go through as requested, which should be the // case if we're running without a window manager. If there's a window // manager, it can modify or ignore the request, but (per ICCCM) we'll get a // (possibly synthetic) ConfigureNotify about the actual size and correct // |bounds_| later. bounds_ = bounds; if (size_changed) root_window_->OnHostResized(bounds.size()); } gfx::Point RootWindowHostLinux::GetLocationOnNativeScreen() const { return bounds_.origin(); } void RootWindowHostLinux::SetCapture() { } void RootWindowHostLinux::ReleaseCapture() { } void RootWindowHostLinux::SetCursor(gfx::NativeCursor cursor) { if (cursor == current_cursor_) return; current_cursor_ = cursor; if (cursor_shown_) SetCursorInternal(cursor); } void RootWindowHostLinux::ShowCursor(bool show) { if (show == cursor_shown_) return; cursor_shown_ = show; SetCursorInternal(show ? current_cursor_ : ui::kCursorNone); } gfx::Point RootWindowHostLinux::QueryMouseLocation() { ::Window root_return, child_return; int root_x_return, root_y_return, win_x_return, win_y_return; unsigned int mask_return; XQueryPointer(xdisplay_, xwindow_, &root_return, &child_return, &root_x_return, &root_y_return, &win_x_return, &win_y_return, &mask_return); return gfx::Point(max(0, min(bounds_.width(), win_x_return)), max(0, min(bounds_.height(), win_y_return))); } bool RootWindowHostLinux::ConfineCursorToRootWindow() { #if XFIXES_MAJOR >= 5 DCHECK(!pointer_barriers_.get()); if (pointer_barriers_.get()) return false; // Pointer barriers extend all the way across the screen to // avoid leaks at the corners. gfx::Size screen_size = RootWindowHost::GetNativeScreenSize(); pointer_barriers_.reset(new XID[4]); // Horizontal barriers. pointer_barriers_[0] = XFixesCreatePointerBarrier( xdisplay_, x_root_window_, 0, bounds_.y(), screen_size.width(), bounds_.y(), BarrierPositiveY, 0, NULL); // default device pointer_barriers_[1] = XFixesCreatePointerBarrier( xdisplay_, x_root_window_, 0, bounds_.bottom(), screen_size.width(), bounds_.bottom(), BarrierNegativeY, 0, NULL); // default device // Vertical barriers. pointer_barriers_[2] = XFixesCreatePointerBarrier( xdisplay_, x_root_window_, bounds_.x(), 0, bounds_.x(), screen_size.height(), BarrierPositiveX, 0, NULL); // default device pointer_barriers_[3] = XFixesCreatePointerBarrier( xdisplay_, x_root_window_, bounds_.right(), 0, bounds_.right(), screen_size.height(), BarrierNegativeX, 0, NULL); // default device #endif return true; } void RootWindowHostLinux::UnConfineCursor() { #if XFIXES_MAJOR >= 5 if (pointer_barriers_.get()) { XFixesDestroyPointerBarrier(xdisplay_, pointer_barriers_[0]); XFixesDestroyPointerBarrier(xdisplay_, pointer_barriers_[1]); XFixesDestroyPointerBarrier(xdisplay_, pointer_barriers_[2]); XFixesDestroyPointerBarrier(xdisplay_, pointer_barriers_[3]); pointer_barriers_.reset(); } #endif } void RootWindowHostLinux::MoveCursorTo(const gfx::Point& location) { XWarpPointer(xdisplay_, None, xwindow_, 0, 0, 0, 0, location.x(), location.y()); } void RootWindowHostLinux::SetFocusWhenShown(bool focus_when_shown) { static const char* k_NET_WM_USER_TIME = "_NET_WM_USER_TIME"; focus_when_shown_ = focus_when_shown; if (IsWindowManagerPresent() && !focus_when_shown_) { ui::SetIntProperty(xwindow_, k_NET_WM_USER_TIME, k_NET_WM_USER_TIME, 0); } } void RootWindowHostLinux::PostNativeEvent( const base::NativeEvent& native_event) { DCHECK(xwindow_); DCHECK(xdisplay_); XEvent xevent = *native_event; xevent.xany.display = xdisplay_; xevent.xany.window = xwindow_; switch (xevent.type) { case EnterNotify: case LeaveNotify: case MotionNotify: case KeyPress: case KeyRelease: case ButtonPress: case ButtonRelease: { // The fields used below are in the same place for all of events // above. Using xmotion from XEvent's unions to avoid repeating // the code. xevent.xmotion.root = x_root_window_; xevent.xmotion.time = CurrentTime; gfx::Point point(xevent.xmotion.x, xevent.xmotion.y); root_window_->ConvertPointToNativeScreen(&point); xevent.xmotion.x_root = point.x(); xevent.xmotion.y_root = point.y(); } default: break; } XSendEvent(xdisplay_, xwindow_, False, 0, &xevent); } bool RootWindowHostLinux::IsWindowManagerPresent() { // Per ICCCM 2.8, "Manager Selections", window managers should take ownership // of WM_Sn selections (where n is a screen number). return XGetSelectionOwner(xdisplay_, cached_atoms_[ATOM_WM_S0]) != None; } void RootWindowHostLinux::SetCursorInternal(gfx::NativeCursor cursor) { ::Cursor xcursor = cursor == ui::kCursorNone ? invisible_cursor_ : cursor == ui::kCursorCustom ? cursor.platform() : ui::GetXCursor(CursorShapeFromNative(cursor)); XDefineCursor(xdisplay_, xwindow_, xcursor); } // static RootWindowHost* RootWindowHost::Create(const gfx::Rect& bounds) { return new RootWindowHostLinux(bounds); } // static RootWindowHost* RootWindowHost::GetForAcceleratedWidget( gfx::AcceleratedWidget accelerated_widget) { return reinterpret_cast<RootWindowHost*>( ui::ViewProp::GetValue(accelerated_widget, kRootWindowHostLinuxKey)); } // static gfx::Size RootWindowHost::GetNativeScreenSize() { ::Display* xdisplay = base::MessagePumpX::GetDefaultXDisplay(); return gfx::Size(DisplayWidth(xdisplay, 0), DisplayHeight(xdisplay, 0)); } } // namespace aura
ropik/chromium
ui/aura/root_window_host_linux.cc
C++
bsd-3-clause
28,419
import numpy as np from menpo.image import Image, BooleanImage, MaskedImage from menpo.shape import PointCloud from menpo.testing import is_same_array def test_image_copy(): pixels = np.ones([1, 10, 10]) landmarks = PointCloud(np.ones([3, 2]), copy=False) im = Image(pixels, copy=False) im.landmarks['test'] = landmarks im_copy = im.copy() assert (not is_same_array(im.pixels, im_copy.pixels)) assert (not is_same_array(im_copy.landmarks['test'].points, im.landmarks['test'].points)) def test_booleanimage_copy(): pixels = np.ones([10, 10], dtype=np.bool) landmarks = PointCloud(np.ones([3, 2]), copy=False) im = BooleanImage(pixels, copy=False) im.landmarks['test'] = landmarks im_copy = im.copy() assert (not is_same_array(im.pixels, im_copy.pixels)) assert (not is_same_array(im_copy.landmarks['test'].points, im.landmarks['test'].points)) def test_maskedimage_copy(): pixels = np.ones([1, 10, 10]) landmarks = PointCloud(np.ones([3, 2]), copy=False) im = MaskedImage(pixels, copy=False) im.landmarks['test'] = landmarks im_copy = im.copy() assert (not is_same_array(im.pixels, im_copy.pixels)) assert (not is_same_array(im_copy.landmarks['test'].points, im.landmarks['test'].points))
grigorisg9gr/menpo
menpo/image/test/image_copy_test.py
Python
bsd-3-clause
1,372
<header>Dies d'avís</header> El nombre de dies abans que es forci l'usuari a canviar la seva contrasenya durant els quals s'avisa l'usuari en entrar al sistema. <hr>
xtso520ok/webmin
useradmin/help/warn.ca.UTF-8.html
HTML
bsd-3-clause
171
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include <atomic> #include <cstdint> #include <folly/io/async/EventBase.h> #include <mutex> #include <thread> namespace folly { class EventBaseManager; } namespace proxygen { /** * A WorkerThread represents an independent event loop that runs in its own * thread. */ class WorkerThread { public: explicit WorkerThread(folly::EventBaseManager* ebm); virtual ~WorkerThread(); /** * Begin execution of the worker. * * This starts the worker thread, and returns immediately. */ void start(); /** * Request that the worker thread stop when there are no more events to * process. * * Normally each worker thread runs forever, even if it is idle with no * events to process. This function requests that the worker thread return * when it becomes idle. * * This is used for graceful shutdown: Once the services have been asked to * shutdown, stopWhenIdle() can be called on the WorkerThread so that it will * return as soon as the services in this thread no longer have any events to * process. * * Typically you will still want to call forceStop() after a timeout, in case * some of the services take too long to shut down gracefully. */ void stopWhenIdle(); /** * Request that the worker stop executing as soon as possible. * * This will terminate the worker thread's event loop, and cause the thread * to return. If there are any services still running in the worker thread, * their events will no longer be processed. * * This function is asynchronous: it signals the worker thread to stop, and * returns without waiting for the thread to actually terminate. The wait() * method must be called to wait for the thread to terminate. */ void forceStop(); /** * Synchronously wait for termination of the worker thread. * * Note that the worker thread will only terminate after stopWhenIdle() or * forceStop() has been called, so you typically should only call wait() * after first using one of these functions. */ void wait(); /** * Get the EventBase used to drive the events in this worker thread. */ folly::EventBase* getEventBase() { return &eventBase_; } /** * Get the current WorkerThread running this thread. * * Returns nullptr if called from a thread that is not running inside * WorkerThread. */ static WorkerThread* getCurrentWorkerThread() { return currentWorker_; } protected: virtual void setup(); virtual void cleanup(); private: enum class State : uint8_t { IDLE, // Not yet started STARTING, // start() called, thread not fully started yet RUNNING, // Thread running normally STOP_WHEN_IDLE, // stopWhenIdle() called, not stopped yet FORCE_STOP, // forceStop() called, but the loop is still cleaning up }; // Forbidden copy constructor and assignment operator WorkerThread(WorkerThread const &) = delete; WorkerThread& operator=(WorkerThread const &) = delete; void runLoop(); State state_{State::IDLE}; std::thread thread_; std::mutex joinLock_; folly::EventBase eventBase_; folly::EventBaseManager* eventBaseManager_{nullptr}; // A thread-local pointer to the current WorkerThread for this thread static __thread WorkerThread* currentWorker_; // A count of the number of WorkerThreads that have been constructed static std::atomic_uint objectCounter_; }; } // proxygen
joelgarciajr84/proxygen
proxygen/lib/services/WorkerThread.h
C
bsd-3-clause
3,774
#!/usr/bin/env python from __future__ import print_function from builtins import input import sys import pmagpy.pmag as pmag def main(): """ NAME gofish.py DESCRIPTION calculates fisher parameters from dec inc data INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX gofish.py [options] [< filename] OPTIONS -h prints help message and quits -i for interactive filename entry -f FILE, specify input file -F FILE, specifies output file name < filename for reading from standard input OUTPUT mean dec, mean inc, N, R, k, a95, csd """ if '-h' in sys.argv: # check if help is needed print(main.__doc__) sys.exit() # graceful quit if '-i' in sys.argv: # ask for filename file=input("Enter file name with dec, inc data: ") f=open(file,'r') data=f.readlines() elif '-f' in sys.argv: dat=[] ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'r') data=f.readlines() else: data = sys.stdin.readlines() # read from standard input ofile = "" if '-F' in sys.argv: ind = sys.argv.index('-F') ofile= sys.argv[ind+1] out = open(ofile, 'w + a') DIs= [] # set up list for dec inc data for line in data: # read in the data from standard input if '\t' in line: rec=line.split('\t') # split each line on space to get records else: rec=line.split() # split each line on space to get records DIs.append((float(rec[0]),float(rec[1]))) # fpars=pmag.fisher_mean(DIs) outstring='%7.1f %7.1f %i %10.4f %8.1f %7.1f %7.1f'%(fpars['dec'],fpars['inc'],fpars['n'],fpars['r'],fpars['k'],fpars['alpha95'], fpars['csd']) if ofile == "": print(outstring) else: out.write(outstring+'\n') # if __name__ == "__main__": main()
Caoimhinmg/PmagPy
programs/gofish.py
Python
bsd-3-clause
1,976
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/button/blue_button.h" #include "grit/ui_resources.h" #include "ui/base/accessibility/accessible_view_state.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/sys_color_change_listener.h" #include "ui/views/controls/button/label_button_border.h" namespace { const int kBlueNormalImages[] = IMAGE_GRID(IDR_BLUE_BUTTON_NORMAL); const int kBlueHoveredImages[] = IMAGE_GRID(IDR_BLUE_BUTTON_HOVER); const int kBluePressedImages[] = IMAGE_GRID(IDR_BLUE_BUTTON_PRESSED); const int kBlueFocusedNormalImages[] = IMAGE_GRID( IDR_BLUE_BUTTON_FOCUSED_NORMAL); const int kBlueFocusedHoveredImages[] = IMAGE_GRID( IDR_BLUE_BUTTON_FOCUSED_HOVER); const int kBlueFocusedPressedImages[] = IMAGE_GRID( IDR_BLUE_BUTTON_FOCUSED_PRESSED); // Default text and shadow colors for the blue button. const SkColor kBlueButtonTextColor = SK_ColorWHITE; const SkColor kBlueButtonShadowColor = SkColorSetRGB(0x53, 0x8C, 0xEA); } // namespace namespace views { // static const char BlueButton::kViewClassName[] = "views/BlueButton"; BlueButton::BlueButton(ButtonListener* listener, const string16& text) : LabelButton(listener, text) { // Inherit STYLE_BUTTON insets, minimum size, alignment, etc. SetStyle(STYLE_BUTTON); LabelButtonBorder* button_border = static_cast<LabelButtonBorder*>(border()); button_border->SetPainter(false, STATE_NORMAL, Painter::CreateImageGridPainter(kBlueNormalImages)); button_border->SetPainter(false, STATE_HOVERED, Painter::CreateImageGridPainter(kBlueHoveredImages)); button_border->SetPainter(false, STATE_PRESSED, Painter::CreateImageGridPainter(kBluePressedImages)); button_border->SetPainter(false, STATE_DISABLED, Painter::CreateImageGridPainter(kBlueNormalImages)); button_border->SetPainter(true, STATE_NORMAL, Painter::CreateImageGridPainter(kBlueFocusedNormalImages)); button_border->SetPainter(true, STATE_HOVERED, Painter::CreateImageGridPainter(kBlueFocusedHoveredImages)); button_border->SetPainter(true, STATE_PRESSED, Painter::CreateImageGridPainter(kBlueFocusedPressedImages)); button_border->SetPainter(true, STATE_DISABLED, Painter::CreateImageGridPainter(kBlueNormalImages)); if (!gfx::IsInvertedColorScheme()) { for (size_t state = STATE_NORMAL; state < STATE_COUNT; ++state) SetTextColor(static_cast<ButtonState>(state), kBlueButtonTextColor); label()->SetShadowColors(kBlueButtonShadowColor, kBlueButtonShadowColor); label()->SetShadowOffset(0, 1); } } BlueButton::~BlueButton() {} const char* BlueButton::GetClassName() const { return BlueButton::kViewClassName; } // TODO(msw): Re-enable animations for blue buttons. See crbug.com/239121. const ui::Animation* BlueButton::GetThemeAnimation() const { return NULL; } } // namespace views
pozdnyakov/chromium-crosswalk
ui/views/controls/button/blue_button.cc
C++
bsd-3-clause
2,999
// Copyright 2010-2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "base/win_util.h" #include "base/system_util.h" #include "base/util.h" #include "testing/base/public/googletest.h" #include "testing/base/public/gunit.h" namespace mozc { namespace { bool LooksLikeNtPath(const wstring &nt_path) { const wchar_t kPrefix[] = L"\\Device\\"; return nt_path.find(kPrefix) != wstring::npos; } } // namespace class WinUtilLoaderLockTest : public testing::Test { protected: WinUtilLoaderLockTest() : module_(nullptr) {} virtual void SetUp() { // Dynamically load the DLL to test the loader lock detection. // This dll checks the loader lock in the DllMain and // returns the result via IsLockHeld exported function. if (module_ == nullptr) { module_= ::LoadLibraryW(L"win_util_test_dll.dll"); } } virtual void TearDown() { if (module_ != nullptr) { ::FreeLibrary(module_); } module_ = nullptr; } HMODULE module_; }; TEST_F(WinUtilLoaderLockTest, IsDLLSynchronizationHeldTest) { ASSERT_NE(nullptr, module_); typedef int (__stdcall *CheckProc)(); CheckProc is_lock_check_succeeded = reinterpret_cast<CheckProc>( ::GetProcAddress(module_, "IsLockCheckSucceeded")); EXPECT_NE(nullptr, is_lock_check_succeeded); EXPECT_NE(FALSE, is_lock_check_succeeded()); CheckProc is_lock_held = reinterpret_cast<CheckProc>( ::GetProcAddress(module_, "IsLockHeld")); EXPECT_NE(nullptr, is_lock_held); // The loader lock should be held in the DllMain. EXPECT_NE(FALSE, is_lock_held()); // Clear flags and check again from the caller which does not // own the loader lock. The loader lock should not be detected. CheckProc clear_flags_and_check_again = reinterpret_cast<CheckProc>( ::GetProcAddress(module_, "ClearFlagsAndCheckAgain")); EXPECT_NE(nullptr, clear_flags_and_check_again); clear_flags_and_check_again(); EXPECT_NE(FALSE, is_lock_check_succeeded()); EXPECT_FALSE(is_lock_held()); } TEST(WinUtilTest, Win32EqualStringTest) { bool result = false; result = false; EXPECT_TRUE(WinUtil::Win32EqualString( L"abc", L"AbC", true, &result)); EXPECT_TRUE(result); // case-sensitive EXPECT_TRUE(WinUtil::Win32EqualString( L"abc", L"AbC", false, &result)); EXPECT_FALSE(result); // Test case in http://b/2977223 result = false; EXPECT_TRUE(WinUtil::Win32EqualString( L"abc", L"a" L"\x202c" L"bc", // U+202C: POP DIRECTIONAL FORMATTING true, &result)); EXPECT_FALSE(result); // Test case in http://b/2977235 result = false; EXPECT_TRUE(WinUtil::Win32EqualString( L"\x01bf", // U+01BF: LATIN LETTER WYNN L"\x01f7", // U+01F7: LATIN CAPITAL LETTER WYNN true, &result)); EXPECT_TRUE(result); // http://blogs.msdn.com/b/michkap/archive/2005/05/26/421987.aspx result = false; EXPECT_TRUE(WinUtil::Win32EqualString( L"\x03c2", // U+03C2: GREEK SMALL LETTER FINAL SIGMA L"\x03a3", // U+03A3: GREEK CAPITAL LETTER SIGMA true, &result)); // Windows XP En/Ja: U+03C2 and U+03A3 are the same caracter. // Windows Vista En/Ja: U+03C2 and U+03A3 are the same caracter. // Windows 7 En/Ja: U+03C2 and U+03A3 are different from each other. if (SystemUtil::IsWindows7OrLater()) { EXPECT_FALSE(result); } else { EXPECT_TRUE(result); } // http://blogs.msdn.com/b/michkap/archive/2005/05/26/421987.aspx result = false; EXPECT_TRUE(WinUtil::Win32EqualString( L"\x03c3", // U+03C3: GREEK SMALL LETTER SIGMA L"\x03a3", // U+03A3: GREEK CAPITAL LETTER SIGMA true, &result)); EXPECT_TRUE(result); } TEST(WinUtilTest, NativeEqualStringTest) { bool result = false; result = false; EXPECT_TRUE(WinUtil::NativeEqualString( L"abc", L"AbC", true, &result)); EXPECT_TRUE(result); // case-sensitive EXPECT_TRUE(WinUtil::NativeEqualString( L"abc", L"AbC", false, &result)); EXPECT_FALSE(result); // Test case in http://b/2977223 result = false; EXPECT_TRUE(WinUtil::NativeEqualString( L"abc", L"a" L"\x202c" L"bc", // U+202C: POP DIRECTIONAL FORMATTING true, &result)); EXPECT_FALSE(result); // Test case in http://b/2977235 result = false; EXPECT_TRUE(WinUtil::NativeEqualString( L"\x01bf", // U+01BF: LATIN LETTER WYNN L"\x01f7", // U+01F7: LATIN CAPITAL LETTER WYNN true, &result)); EXPECT_TRUE(result); // http://blogs.msdn.com/b/michkap/archive/2005/05/26/421987.aspx result = false; EXPECT_TRUE(WinUtil::NativeEqualString( L"\x03c2", // U+03C2: GREEK SMALL LETTER FINAL SIGMA L"\x03a3", // U+03A3: GREEK CAPITAL LETTER SIGMA true, &result)); // Windows XP En/Ja: U+03C2 and U+03A3 are the same caracter. // Windows Vista En/Ja: U+03C2 and U+03A3 are the same caracter. // Windows 7 En/Ja: U+03C2 and U+03A3 are different from each other. if (SystemUtil::IsWindows7OrLater()) { EXPECT_FALSE(result); } else { EXPECT_TRUE(result); } // http://blogs.msdn.com/b/michkap/archive/2005/05/26/421987.aspx result = false; EXPECT_TRUE(WinUtil::NativeEqualString( L"\x03c3", // U+03C3: GREEK SMALL LETTER SIGMA L"\x03a3", // U+03A3: GREEK CAPITAL LETTER SIGMA true, &result)); EXPECT_TRUE(result); } TEST(WinUtilTest, CrtEqualStringTest) { bool result = false; WinUtil::CrtEqualString( L"abc", L"AbC", true, &result); EXPECT_TRUE(result); // case-sensitive WinUtil::CrtEqualString( L"abc", L"AbC", false, &result); EXPECT_FALSE(result); // Test case in http://b/2977223 result = false; WinUtil::CrtEqualString( L"abc", L"a" L"\x202c" L"bc", // U+202C: POP DIRECTIONAL FORMATTING true, &result); EXPECT_FALSE(result); // Test case in http://b/2977235 result = false; WinUtil::CrtEqualString( L"\x01bf", // U+01BF: LATIN LETTER WYNN L"\x01f7", // U+01F7: LATIN CAPITAL LETTER WYNN true, &result); EXPECT_TRUE(result); // http://blogs.msdn.com/b/michkap/archive/2005/05/26/421987.aspx result = false; WinUtil::CrtEqualString( L"\x03c2", // U+03C2: GREEK SMALL LETTER FINAL SIGMA L"\x03a3", // U+03A3: GREEK CAPITAL LETTER SIGMA true, &result); // Unfortunately, this result is not compatible with Win32EqualString/ // NativeEqualString. EXPECT_FALSE(result); // http://blogs.msdn.com/b/michkap/archive/2005/05/26/421987.aspx result = false; WinUtil::CrtEqualString( L"\x03c3", // U+03C3: GREEK SMALL LETTER SIGMA L"\x03a3", // U+03A3: GREEK CAPITAL LETTER SIGMA true, &result); EXPECT_TRUE(result); } // Actually WinUtil::SystemEqualString raises DCHECK error when argument // strings contain any NUL character in debug build. #if !defined(DEBUG) TEST(WinUtilTest, SystemEqualStringTestForNUL) { { const wchar_t kTestBuffer[] = L"abc"; const wstring test_string1(kTestBuffer); const wstring test_string2(kTestBuffer, kTestBuffer + arraysize(kTestBuffer)); EXPECT_EQ(3, test_string1.size()); EXPECT_EQ(4, test_string2.size()); EXPECT_TRUE(WinUtil::SystemEqualString( test_string1, test_string2, true)); } { const wchar_t kTestBuffer[] = L"abc\0def"; const wstring test_string1(kTestBuffer); const wstring test_string2(kTestBuffer, kTestBuffer + arraysize(kTestBuffer)); EXPECT_EQ(3, test_string1.size()); EXPECT_EQ(8, test_string2.size()); EXPECT_TRUE(WinUtil::SystemEqualString( test_string1, test_string2, true)); } } #endif // DEBUG TEST(WinUtilTest, AreEqualFileSystemObjectTest) { const wstring system_dir = SystemUtil::GetSystemDir(); const wstring notepad = system_dir + L"\\notepad.exe"; const wstring notepad_with_prefix = L"\\\\?\\" + notepad; const wchar_t kThisFileNeverExists[] = L"/this/file/never/exists"; EXPECT_TRUE(WinUtil::AreEqualFileSystemObject(system_dir, system_dir)) << "Can work against a directory"; EXPECT_FALSE(WinUtil::AreEqualFileSystemObject(system_dir, notepad)); EXPECT_TRUE(WinUtil::AreEqualFileSystemObject(notepad, notepad_with_prefix)) << "Long path prefix should be supported."; EXPECT_FALSE(WinUtil::AreEqualFileSystemObject( kThisFileNeverExists, kThisFileNeverExists)) << "Must returns false against a file that does not exist."; } TEST(WinUtilTest, GetNtPath) { const wstring system_dir = SystemUtil::GetSystemDir(); const wstring notepad = system_dir + L"\\notepad.exe"; const wchar_t kThisFileNeverExists[] = L"/this/file/never/exists"; wstring nt_system_dir; EXPECT_TRUE(WinUtil::GetNtPath(system_dir, &nt_system_dir)) << "Can work against a directory."; EXPECT_TRUE(LooksLikeNtPath(nt_system_dir)); EXPECT_FALSE(WinUtil::GetNtPath(system_dir, nullptr)) << "Must fail against a NULL argument."; wstring nt_notepad; EXPECT_TRUE(WinUtil::GetNtPath(notepad, &nt_notepad)) << "Can work against a file."; EXPECT_TRUE(LooksLikeNtPath(nt_notepad)); EXPECT_TRUE(nt_system_dir != nt_notepad); wstring nt_not_exists = L"foo"; EXPECT_FALSE(WinUtil::GetNtPath(kThisFileNeverExists, &nt_not_exists)) << "Must fail against non-exist file."; EXPECT_TRUE(nt_not_exists.empty()) << "Must be cleared when fails."; } TEST(WinUtilTest, GetProcessInitialNtPath) { wstring nt_path; EXPECT_TRUE(WinUtil::GetProcessInitialNtPath(::GetCurrentProcessId(), &nt_path)); EXPECT_TRUE(LooksLikeNtPath(nt_path)); } } // namespace mozc
takahashikenichi/mozc
src/base/win_util_test.cc
C++
bsd-3-clause
11,295
package com.dslplatform.json.generated.types.Double; import com.dslplatform.json.generated.types.StaticJson; import com.dslplatform.json.generated.ocd.javaasserts.DoubleAsserts; import java.io.IOException; public class NullableSetOfOneDoublesDefaultValueTurtle { private static StaticJson.JsonSerialization jsonSerialization; @org.junit.BeforeClass public static void initializeJsonSerialization() throws IOException { jsonSerialization = StaticJson.getSerialization(); } @org.junit.Test public void testDefaultValueEquality() throws IOException { final java.util.Set<Double> defaultValue = null; final StaticJson.Bytes defaultValueJsonSerialized = jsonSerialization.serialize(defaultValue); final java.util.List<Double> deserializedTmpList = jsonSerialization.deserializeList(Double.class, defaultValueJsonSerialized.content, defaultValueJsonSerialized.length); final java.util.Set<Double> defaultValueJsonDeserialized = deserializedTmpList == null ? null : new java.util.HashSet<Double>(deserializedTmpList); DoubleAsserts.assertNullableSetOfOneEquals(defaultValue, defaultValueJsonDeserialized); } @org.junit.Test public void testBorderValue1Equality() throws IOException { final java.util.Set<Double> borderValue1 = new java.util.HashSet<Double>(java.util.Arrays.asList(0.0)); final StaticJson.Bytes borderValue1JsonSerialized = jsonSerialization.serialize(borderValue1); final java.util.List<Double> deserializedTmpList = jsonSerialization.deserializeList(Double.class, borderValue1JsonSerialized.content, borderValue1JsonSerialized.length); final java.util.Set<Double> borderValue1JsonDeserialized = deserializedTmpList == null ? null : new java.util.HashSet<Double>(deserializedTmpList); DoubleAsserts.assertNullableSetOfOneEquals(borderValue1, borderValue1JsonDeserialized); } @org.junit.Test public void testBorderValue2Equality() throws IOException { final java.util.Set<Double> borderValue2 = new java.util.HashSet<Double>(java.util.Arrays.asList(Double.NaN)); final StaticJson.Bytes borderValue2JsonSerialized = jsonSerialization.serialize(borderValue2); final java.util.List<Double> deserializedTmpList = jsonSerialization.deserializeList(Double.class, borderValue2JsonSerialized.content, borderValue2JsonSerialized.length); final java.util.Set<Double> borderValue2JsonDeserialized = deserializedTmpList == null ? null : new java.util.HashSet<Double>(deserializedTmpList); DoubleAsserts.assertNullableSetOfOneEquals(borderValue2, borderValue2JsonDeserialized); } @org.junit.Test public void testBorderValue3Equality() throws IOException { final java.util.Set<Double> borderValue3 = new java.util.HashSet<Double>(java.util.Arrays.asList(0.0, 1E-307, 9E307, -1.23456789012345E-10, 1.23456789012345E20, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.NaN)); final StaticJson.Bytes borderValue3JsonSerialized = jsonSerialization.serialize(borderValue3); final java.util.List<Double> deserializedTmpList = jsonSerialization.deserializeList(Double.class, borderValue3JsonSerialized.content, borderValue3JsonSerialized.length); final java.util.Set<Double> borderValue3JsonDeserialized = deserializedTmpList == null ? null : new java.util.HashSet<Double>(deserializedTmpList); DoubleAsserts.assertNullableSetOfOneEquals(borderValue3, borderValue3JsonDeserialized); } }
ngs-doo/dsl-json
library/src/test/java/com/dslplatform/json/generated/types/Double/NullableSetOfOneDoublesDefaultValueTurtle.java
Java
bsd-3-clause
3,353
<?php $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar'); $p['file1.txt'] = 'hi'; $p->stopBuffering(); var_dump(strlen($p->getStub())); $p->setStub("<?php function __autoload(\$class) { include 'phar://' . str_replace('_', '/', \$class); } Phar::mapPhar('brandnewphar.phar'); include 'phar://brandnewphar.phar/startup.php'; __HALT_COMPILER(); ?>"); var_dump($p->getStub()); ?> ===DONE===
JSchwehn/php
testdata/fuzzdir/corpus/ext_phar_tests_phar_commitwrite.php
PHP
bsd-3-clause
421
TOP=../../.. include $(TOP)/mk/boilerplate.mk include $(TOP)/mk/test.mk S03_OPTS=$(TEST_HC_OPTS) -outputdir tmp_sigof03 -i -itmp_sigof03 sigof03: rm -rf tmp_sigof03 mkdir tmp_sigof03 '$(TEST_HC)' $(S03_OPTS) -c A.hs '$(TEST_HC)' $(S03_OPTS) -c ASig1.hsig -sig-of "ASig1 is main:A, ASig2 is main:A" '$(TEST_HC)' $(S03_OPTS) -c ASig2.hsig -sig-of "ASig1 is main:A, ASig2 is main:A" '$(TEST_HC)' $(S03_OPTS) -c Main.hs '$(TEST_HC)' $(S03_OPTS) tmp_sigof03/A.o tmp_sigof03/Main.o -o tmp_sigof03/Main ./tmp_sigof03/Main S03M_OPTS=$(TEST_HC_OPTS) -outputdir tmp_sigof03m sigof03m: rm -rf tmp_sigof03m mkdir tmp_sigof03m '$(TEST_HC)' $(S03M_OPTS) --make Main.hs -sig-of "ASig1 is main:A, ASig2 is main:A" ./tmp_sigof03m/Main # Currently, the type-check tests are omitted, because we don't have a # way of telling GHC that ASig1 and ASig2 have the same identities # (sig-of is not right because it requires the target to have an hi # file, but in general we won't have it.)
vTurbine/ghc
testsuite/tests/driver/sigof03/Makefile
Makefile
bsd-3-clause
981
Behaviors ========= Behaviors are instances of [[yii\base\Behavior]], or of a child class. Behaviors, also known as [mixins](http://en.wikipedia.org/wiki/Mixin), allow you to enhance the functionality of an existing [[yii\base\Component|component]] class without needing to change the class's inheritance. Attaching a behavior to a component "injects" the behavior's methods and properties into the component, making those methods and properties accessible as if they were defined in the component class itself. Moreover, a behavior can respond to the [events](concept-events.md) triggered by the component, which allows behaviors to also customize the normal code execution of the component. Defining Behaviors <span id="defining-behaviors"></span> ------------------ To define a behavior, create a class that extends [[yii\base\Behavior]], or extends a child class. For example: ```php namespace app\components; use yii\base\Behavior; class MyBehavior extends Behavior { public $prop1; private $_prop2; public function getProp2() { return $this->_prop2; } public function setProp2($value) { $this->_prop2 = $value; } public function foo() { // ... } } ``` The above code defines the behavior class `app\components\MyBehavior`, with two properties `prop1` and `prop2` and one method `foo()`. Note that property `prop2` is defined via the getter `getProp2()` and the setter `setProp2()`. This is the case because [[yii\base\Behavior]] extends [[yii\base\BaseObject]] and therefore supports defining [properties](concept-properties.md) via getters and setters. Because this class is a behavior, when it is attached to a component, that component will then also have the `prop1` and `prop2` properties and the `foo()` method. > Tip: Within a behavior, you can access the component that the behavior is attached to through the [[yii\base\Behavior::owner]] property. > Note: In case [[yii\base\Behavior::__get()]] and/or [[yii\base\Behavior::__set()]] method of behavior is overridden you need to override [[yii\base\Behavior::canGetProperty()]] and/or [[yii\base\Behavior::canSetProperty()]] as well. Handling Component Events ------------------ If a behavior needs to respond to the events triggered by the component it is attached to, it should override the [[yii\base\Behavior::events()]] method. For example: ```php namespace app\components; use yii\db\ActiveRecord; use yii\base\Behavior; class MyBehavior extends Behavior { // ... public function events() { return [ ActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate', ]; } public function beforeValidate($event) { // ... } } ``` The [[yii\base\Behavior::events()|events()]] method should return a list of events and their corresponding handlers. The above example declares that the [[yii\db\ActiveRecord::EVENT_BEFORE_VALIDATE|EVENT_BEFORE_VALIDATE]] event exists and defines its handler, `beforeValidate()`. When specifying an event handler, you may use one of the following formats: * a string that refers to the name of a method of the behavior class, like the example above * an array of an object or class name, and a method name as a string (without parentheses), e.g., `[$object, 'methodName']`; * an anonymous function The signature of an event handler should be as follows, where `$event` refers to the event parameter. Please refer to the [Events](concept-events.md) section for more details about events. ```php function ($event) { } ``` Attaching Behaviors <span id="attaching-behaviors"></span> ------------------- You can attach a behavior to a [[yii\base\Component|component]] either statically or dynamically. The former is more common in practice. To attach a behavior statically, override the [[yii\base\Component::behaviors()|behaviors()]] method of the component class to which the behavior is being attached. The [[yii\base\Component::behaviors()|behaviors()]] method should return a list of behavior [configurations](concept-configurations.md). Each behavior configuration can be either a behavior class name or a configuration array: ```php namespace app\models; use yii\db\ActiveRecord; use app\components\MyBehavior; class User extends ActiveRecord { public function behaviors() { return [ // anonymous behavior, behavior class name only MyBehavior::class, // named behavior, behavior class name only 'myBehavior2' => MyBehavior::class, // anonymous behavior, configuration array [ 'class' => MyBehavior::class, 'prop1' => 'value1', 'prop2' => 'value2', ], // named behavior, configuration array 'myBehavior4' => [ 'class' => MyBehavior::class, 'prop1' => 'value1', 'prop2' => 'value2', ] ]; } } ``` You may associate a name with a behavior by specifying the array key corresponding to the behavior configuration. In this case, the behavior is called a *named behavior*. In the above example, there are two named behaviors: `myBehavior2` and `myBehavior4`. If a behavior is not associated with a name, it is called an *anonymous behavior*. To attach a behavior dynamically, call the [[yii\base\Component::attachBehavior()]] method of the component to which the behavior is being attached: ```php use app\components\MyBehavior; // attach a behavior object $component->attachBehavior('myBehavior1', new MyBehavior()); // attach a behavior class $component->attachBehavior('myBehavior2', MyBehavior::class); // attach a configuration array $component->attachBehavior('myBehavior3', [ 'class' => MyBehavior::class, 'prop1' => 'value1', 'prop2' => 'value2', ]); ``` You may attach multiple behaviors at once using the [[yii\base\Component::attachBehaviors()]] method: ```php $component->attachBehaviors([ 'myBehavior1' => new MyBehavior(), // a named behavior MyBehavior::class, // an anonymous behavior ]); ``` You may also attach behaviors through [configurations](concept-configurations.md) like the following: ```php [ 'as myBehavior2' => MyBehavior::class, 'as myBehavior3' => [ 'class' => MyBehavior::class, 'prop1' => 'value1', 'prop2' => 'value2', ], ] ``` For more details, please refer to the [Configurations](concept-configurations.md#configuration-format) section. Using Behaviors <span id="using-behaviors"></span> --------------- To use a behavior, first attach it to a [[yii\base\Component|component]] per the instructions above. Once a behavior is attached to a component, its usage is straightforward. You can access a *public* member variable or a [property](concept-properties.md) defined by a getter and/or a setter of the behavior through the component it is attached to: ```php // "prop1" is a property defined in the behavior class echo $component->prop1; $component->prop1 = $value; ``` You can also call a *public* method of the behavior similarly: ```php // foo() is a public method defined in the behavior class $component->foo(); ``` As you can see, although `$component` does not define `prop1` and `foo()`, they can be used as if they are part of the component definition due to the attached behavior. If two behaviors define the same property or method and they are both attached to the same component, the behavior that is attached to the component *first* will take precedence when the property or method is accessed. A behavior may be associated with a name when it is attached to a component. If this is the case, you may access the behavior object using the name: ```php $behavior = $component->getBehavior('myBehavior'); ``` You may also get all behaviors attached to a component: ```php $behaviors = $component->getBehaviors(); ``` Detaching Behaviors <span id="detaching-behaviors"></span> ------------------- To detach a behavior, call [[yii\base\Component::detachBehavior()]] with the name associated with the behavior: ```php $component->detachBehavior('myBehavior1'); ``` You may also detach *all* behaviors: ```php $component->detachBehaviors(); ``` Using `TimestampBehavior` <span id="using-timestamp-behavior"></span> ------------------------- To wrap up, let's take a look at [[yii\behaviors\TimestampBehavior]]. This behavior supports automatically updating the timestamp attributes of an [[yii\db\ActiveRecord|Active Record]] model anytime the model is saved via `insert()`, `update()` or `save()` method. First, attach this behavior to the [[yii\db\ActiveRecord|Active Record]] class that you plan to use: ```php namespace app\models\User; use yii\db\ActiveRecord; use yii\behaviors\TimestampBehavior; class User extends ActiveRecord { // ... public function behaviors() { return [ [ 'class' => TimestampBehavior::class, 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'], ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'], ], // if you're using datetime instead of UNIX timestamp: // 'value' => new Expression('NOW()'), ], ]; } } ``` The behavior configuration above specifies that when the record is being: * inserted, the behavior should assign the current UNIX timestamp to the `created_at` and `updated_at` attributes * updated, the behavior should assign the current UNIX timestamp to the `updated_at` attribute > Note: For the above implementation to work with MySQL database, please declare the columns(`created_at`, `updated_at`) as int(11) for being UNIX timestamp. With that code in place, if you have a `User` object and try to save it, you will find its `created_at` and `updated_at` are automatically filled with the current UNIX timestamp: ```php $user = new User; $user->email = 'test@example.com'; $user->save(); echo $user->created_at; // shows the current timestamp ``` The [[yii\behaviors\TimestampBehavior|TimestampBehavior]] also offers a useful method [[yii\behaviors\TimestampBehavior::touch()|touch()]], which will assign the current timestamp to a specified attribute and save it to the database: ```php $user->touch('login_time'); ``` Other behaviors --------------- There are several built-in and external behaviors available: - [[yii\behaviors\BlameableBehavior]] - automatically fills the specified attributes with the current user ID. - [[yii\behaviors\SluggableBehavior]] - automatically fills the specified attribute with a value that can be used as a slug in a URL. - [[yii\behaviors\AttributeBehavior]] - automatically assigns a specified value to one or multiple attributes of an ActiveRecord object when certain events happen. - [yii2tech\ar\softdelete\SoftDeleteBehavior](https://github.com/yii2tech/ar-softdelete) - provides methods to soft-delete and soft-restore ActiveRecord i.e. set flag or status which marks record as deleted. - [yii2tech\ar\position\PositionBehavior](https://github.com/yii2tech/ar-position) - allows managing records order in an integer field by providing reordering methods. Comparing Behaviors with Traits <span id="comparison-with-traits"></span> ---------------------- While behaviors are similar to [traits](https://secure.php.net/traits) in that they both "inject" their properties and methods to the primary class, they differ in many aspects. As explained below, they both have pros and cons. They are more like complements to each other rather than alternatives. ### Reasons to Use Behaviors <span id="pros-for-behaviors"></span> Behavior classes, like normal classes, support inheritance. Traits, on the other hand, can be considered as language-supported copy and paste. They do not support inheritance. Behaviors can be attached and detached to a component dynamically without requiring modification of the component class. To use a trait, you must modify the code of the class using it. Behaviors are configurable while traits are not. Behaviors can customize the code execution of a component by responding to its events. When there can be name conflicts among different behaviors attached to the same component, the conflicts are automatically resolved by prioritizing the behavior attached to the component first. Name conflicts caused by different traits requires manual resolution by renaming the affected properties or methods. ### Reasons to Use Traits <span id="pros-for-traits"></span> Traits are much more efficient than behaviors as behaviors are objects that take both time and memory. IDEs are more friendly to traits as they are a native language construct.
rob006/yii2-dev
docs/guide/concept-behaviors.md
Markdown
bsd-3-clause
12,847
# frozen_string_literal: true # == Schema Information # # Table name: alchemy_folded_pages # # id :integer not null, primary key # page_id :integer not null # user_id :integer not null # folded :boolean default(FALSE) # module Alchemy class FoldedPage < ActiveRecord::Base belongs_to :page, required: true belongs_to :user, required: true, class_name: Alchemy.user_class_name end end
mtomov/alchemy_cms
app/models/alchemy/folded_page.rb
Ruby
bsd-3-clause
450
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm/gm.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkColorSpace.h" #include "include/core/SkData.h" #include "include/core/SkEncodedImageFormat.h" #include "include/core/SkImage.h" #include "include/core/SkImageInfo.h" #include "include/core/SkMatrix.h" #include "include/core/SkPaint.h" #include "include/core/SkPicture.h" #include "include/core/SkPictureRecorder.h" #include "include/core/SkRect.h" #include "include/core/SkRefCnt.h" #include "include/core/SkShader.h" #include "include/core/SkSize.h" #include "include/core/SkString.h" #include "include/core/SkSurface.h" #include "include/core/SkTileMode.h" #include "include/core/SkTypes.h" #include <utility> class GrContext; static void draw_something(SkCanvas* canvas, const SkRect& bounds) { SkPaint paint; paint.setAntiAlias(true); paint.setColor(SK_ColorRED); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(10); canvas->drawRect(bounds, paint); paint.setStyle(SkPaint::kFill_Style); paint.setColor(SK_ColorBLUE); canvas->drawOval(bounds, paint); } typedef sk_sp<SkImage> (*ImageMakerProc)(GrContext*, SkPicture*, const SkImageInfo&); static sk_sp<SkImage> make_raster(GrContext*, SkPicture* pic, const SkImageInfo& info) { auto surface(SkSurface::MakeRaster(info)); surface->getCanvas()->clear(0); surface->getCanvas()->drawPicture(pic); return surface->makeImageSnapshot(); } static sk_sp<SkImage> make_texture(GrContext* ctx, SkPicture* pic, const SkImageInfo& info) { if (!ctx) { return nullptr; } auto surface(SkSurface::MakeRenderTarget(ctx, SkBudgeted::kNo, info)); if (!surface) { return nullptr; } surface->getCanvas()->clear(0); surface->getCanvas()->drawPicture(pic); return surface->makeImageSnapshot(); } static sk_sp<SkImage> make_pict_gen(GrContext*, SkPicture* pic, const SkImageInfo& info) { return SkImage::MakeFromPicture(sk_ref_sp(pic), info.dimensions(), nullptr, nullptr, SkImage::BitDepth::kU8, SkColorSpace::MakeSRGB()); } static sk_sp<SkImage> make_encode_gen(GrContext* ctx, SkPicture* pic, const SkImageInfo& info) { sk_sp<SkImage> src(make_raster(ctx, pic, info)); if (!src) { return nullptr; } sk_sp<SkData> encoded = src->encodeToData(SkEncodedImageFormat::kPNG, 100); if (!encoded) { return nullptr; } return SkImage::MakeFromEncoded(std::move(encoded)); } const ImageMakerProc gProcs[] = { make_raster, make_texture, make_pict_gen, make_encode_gen, }; /* * Exercise drawing pictures inside an image, showing that the image version is pixelated * (correctly) when it is inside an image. */ class ImageShaderGM : public skiagm::GM { sk_sp<SkPicture> fPicture; public: ImageShaderGM() {} protected: SkString onShortName() override { return SkString("image-shader"); } SkISize onISize() override { return SkISize::Make(850, 450); } void onOnceBeforeDraw() override { const SkRect bounds = SkRect::MakeWH(100, 100); SkPictureRecorder recorder; draw_something(recorder.beginRecording(bounds), bounds); fPicture = recorder.finishRecordingAsPicture(); } void testImage(SkCanvas* canvas, SkImage* image) { SkAutoCanvasRestore acr(canvas, true); canvas->drawImage(image, 0, 0); canvas->translate(0, 120); const SkTileMode tile = SkTileMode::kRepeat; const SkMatrix localM = SkMatrix::MakeTrans(-50, -50); SkPaint paint; paint.setShader(image->makeShader(tile, tile, &localM)); paint.setAntiAlias(true); canvas->drawCircle(50, 50, 50, paint); } void onDraw(SkCanvas* canvas) override { canvas->translate(20, 20); const SkImageInfo info = SkImageInfo::MakeN32Premul(100, 100); for (size_t i = 0; i < SK_ARRAY_COUNT(gProcs); ++i) { sk_sp<SkImage> image(gProcs[i](canvas->getGrContext(), fPicture.get(), info)); if (image) { this->testImage(canvas, image.get()); } canvas->translate(120, 0); } } private: typedef skiagm::GM INHERITED; }; DEF_GM( return new ImageShaderGM; )
endlessm/chromium-browser
third_party/skia/gm/image_shader.cpp
C++
bsd-3-clause
4,501
using System; namespace AggregateSource.Testing { static class Catch { public static Optional<Exception> Exception(Action action) { var result = Optional<Exception>.Empty; try { action(); } catch (Exception exception) { result = new Optional<Exception>(exception); } return result; } } }
yreynhout/AggregateSource
src/Testing/AggregateSource.Testing/Catch.cs
C#
bsd-3-clause
455
/** ****************************************************************************** * @file stm32f4xx_can.c * @author MCD Application Team * @version V1.6.0 * @date 10-July-2015 * @brief This file provides firmware functions to manage the following * functionalities of the Controller area network (CAN) peripheral: * + Initialization and Configuration * + CAN Frames Transmission * + CAN Frames Reception * + Operation modes switch * + Error management * + Interrupts and flags * @verbatim =============================================================================== ##### How to use this driver ##### =============================================================================== [..] (#) Enable the CAN controller interface clock using RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN1, ENABLE); for CAN1 and RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN2, ENABLE); for CAN2 -@- In case you are using CAN2 only, you have to enable the CAN1 clock. (#) CAN pins configuration (++) Enable the clock for the CAN GPIOs using the following function: RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOx, ENABLE); (++) Connect the involved CAN pins to AF9 using the following function GPIO_PinAFConfig(GPIOx, GPIO_PinSourcex, GPIO_AF_CANx); (++) Configure these CAN pins in alternate function mode by calling the function GPIO_Init(); (#) Initialize and configure the CAN using CAN_Init() and CAN_FilterInit() functions. (#) Transmit the desired CAN frame using CAN_Transmit() function. (#) Check the transmission of a CAN frame using CAN_TransmitStatus() function. (#) Cancel the transmission of a CAN frame using CAN_CancelTransmit() function. (#) Receive a CAN frame using CAN_Receive() function. (#) Release the receive FIFOs using CAN_FIFORelease() function. (#) Return the number of pending received frames using CAN_MessagePending() function. (#) To control CAN events you can use one of the following two methods: (++) Check on CAN flags using the CAN_GetFlagStatus() function. (++) Use CAN interrupts through the function CAN_ITConfig() at initialization phase and CAN_GetITStatus() function into interrupt routines to check if the event has occurred or not. After checking on a flag you should clear it using CAN_ClearFlag() function. And after checking on an interrupt event you should clear it using CAN_ClearITPendingBit() function. @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2015 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2 * * 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_can.h" #include "stm32f4xx_rcc.h" /** @addtogroup STM32F4xx_StdPeriph_Driver * @{ */ /** @defgroup CAN * @brief CAN driver modules * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* CAN Master Control Register bits */ #define MCR_DBF ((uint32_t)0x00010000) /* software master reset */ /* CAN Mailbox Transmit Request */ #define TMIDxR_TXRQ ((uint32_t)0x00000001) /* Transmit mailbox request */ /* CAN Filter Master Register bits */ #define FMR_FINIT ((uint32_t)0x00000001) /* Filter init mode */ /* Time out for INAK bit */ #define INAK_TIMEOUT ((uint32_t)0x0000FFFF) /* Time out for SLAK bit */ #define SLAK_TIMEOUT ((uint32_t)0x0000FFFF) /* Flags in TSR register */ #define CAN_FLAGS_TSR ((uint32_t)0x08000000) /* Flags in RF1R register */ #define CAN_FLAGS_RF1R ((uint32_t)0x04000000) /* Flags in RF0R register */ #define CAN_FLAGS_RF0R ((uint32_t)0x02000000) /* Flags in MSR register */ #define CAN_FLAGS_MSR ((uint32_t)0x01000000) /* Flags in ESR register */ #define CAN_FLAGS_ESR ((uint32_t)0x00F00000) /* Mailboxes definition */ #define CAN_TXMAILBOX_0 ((uint8_t)0x00) #define CAN_TXMAILBOX_1 ((uint8_t)0x01) #define CAN_TXMAILBOX_2 ((uint8_t)0x02) #define CAN_MODE_MASK ((uint32_t) 0x00000003) /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ static ITStatus CheckITStatus(uint32_t CAN_Reg, uint32_t It_Bit); /** @defgroup CAN_Private_Functions * @{ */ /** @defgroup CAN_Group1 Initialization and Configuration functions * @brief Initialization and Configuration functions * @verbatim =============================================================================== ##### Initialization and Configuration functions ##### =============================================================================== [..] This section provides functions allowing to (+) Initialize the CAN peripherals : Prescaler, operating mode, the maximum number of time quanta to perform resynchronization, the number of time quanta in Bit Segment 1 and 2 and many other modes. Refer to @ref CAN_InitTypeDef for more details. (+) Configures the CAN reception filter. (+) Select the start bank filter for slave CAN. (+) Enables or disables the Debug Freeze mode for CAN (+)Enables or disables the CAN Time Trigger Operation communication mode @endverbatim * @{ */ /** * @brief Deinitializes the CAN peripheral registers to their default reset values. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @retval None. */ void CAN_DeInit(CAN_TypeDef* CANx) { /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); if (CANx == CAN1) { /* Enable CAN1 reset state */ RCC_APB1PeriphResetCmd(RCC_APB1Periph_CAN1, ENABLE); /* Release CAN1 from reset state */ RCC_APB1PeriphResetCmd(RCC_APB1Periph_CAN1, DISABLE); } else { /* Enable CAN2 reset state */ RCC_APB1PeriphResetCmd(RCC_APB1Periph_CAN2, ENABLE); /* Release CAN2 from reset state */ RCC_APB1PeriphResetCmd(RCC_APB1Periph_CAN2, DISABLE); } } /** * @brief Initializes the CAN peripheral according to the specified * parameters in the CAN_InitStruct. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @param CAN_InitStruct: pointer to a CAN_InitTypeDef structure that contains * the configuration information for the CAN peripheral. * @retval Constant indicates initialization succeed which will be * CAN_InitStatus_Failed or CAN_InitStatus_Success. */ uint8_t CAN_Init(CAN_TypeDef* CANx, CAN_InitTypeDef* CAN_InitStruct) { uint8_t InitStatus = CAN_InitStatus_Failed; uint32_t wait_ack = 0x00000000; /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); assert_param(IS_FUNCTIONAL_STATE(CAN_InitStruct->CAN_TTCM)); assert_param(IS_FUNCTIONAL_STATE(CAN_InitStruct->CAN_ABOM)); assert_param(IS_FUNCTIONAL_STATE(CAN_InitStruct->CAN_AWUM)); assert_param(IS_FUNCTIONAL_STATE(CAN_InitStruct->CAN_NART)); assert_param(IS_FUNCTIONAL_STATE(CAN_InitStruct->CAN_RFLM)); assert_param(IS_FUNCTIONAL_STATE(CAN_InitStruct->CAN_TXFP)); assert_param(IS_CAN_MODE(CAN_InitStruct->CAN_Mode)); assert_param(IS_CAN_SJW(CAN_InitStruct->CAN_SJW)); assert_param(IS_CAN_BS1(CAN_InitStruct->CAN_BS1)); assert_param(IS_CAN_BS2(CAN_InitStruct->CAN_BS2)); assert_param(IS_CAN_PRESCALER(CAN_InitStruct->CAN_Prescaler)); /* Exit from sleep mode */ CANx->MCR &= (~(uint32_t)CAN_MCR_SLEEP); /* Request initialisation */ CANx->MCR |= CAN_MCR_INRQ ; /* Wait the acknowledge */ while (((CANx->MSR & CAN_MSR_INAK) != CAN_MSR_INAK) && (wait_ack != INAK_TIMEOUT)) { wait_ack++; } /* Check acknowledge */ if ((CANx->MSR & CAN_MSR_INAK) != CAN_MSR_INAK) { InitStatus = CAN_InitStatus_Failed; } else { /* Set the time triggered communication mode */ if (CAN_InitStruct->CAN_TTCM == ENABLE) { CANx->MCR |= CAN_MCR_TTCM; } else { CANx->MCR &= ~(uint32_t)CAN_MCR_TTCM; } /* Set the automatic bus-off management */ if (CAN_InitStruct->CAN_ABOM == ENABLE) { CANx->MCR |= CAN_MCR_ABOM; } else { CANx->MCR &= ~(uint32_t)CAN_MCR_ABOM; } /* Set the automatic wake-up mode */ if (CAN_InitStruct->CAN_AWUM == ENABLE) { CANx->MCR |= CAN_MCR_AWUM; } else { CANx->MCR &= ~(uint32_t)CAN_MCR_AWUM; } /* Set the no automatic retransmission */ if (CAN_InitStruct->CAN_NART == ENABLE) { CANx->MCR |= CAN_MCR_NART; } else { CANx->MCR &= ~(uint32_t)CAN_MCR_NART; } /* Set the receive FIFO locked mode */ if (CAN_InitStruct->CAN_RFLM == ENABLE) { CANx->MCR |= CAN_MCR_RFLM; } else { CANx->MCR &= ~(uint32_t)CAN_MCR_RFLM; } /* Set the transmit FIFO priority */ if (CAN_InitStruct->CAN_TXFP == ENABLE) { CANx->MCR |= CAN_MCR_TXFP; } else { CANx->MCR &= ~(uint32_t)CAN_MCR_TXFP; } /* Set the bit timing register */ CANx->BTR = (uint32_t)((uint32_t)CAN_InitStruct->CAN_Mode << 30) | \ ((uint32_t)CAN_InitStruct->CAN_SJW << 24) | \ ((uint32_t)CAN_InitStruct->CAN_BS1 << 16) | \ ((uint32_t)CAN_InitStruct->CAN_BS2 << 20) | \ ((uint32_t)CAN_InitStruct->CAN_Prescaler - 1); /* Request leave initialisation */ CANx->MCR &= ~(uint32_t)CAN_MCR_INRQ; /* Wait the acknowledge */ wait_ack = 0; while (((CANx->MSR & CAN_MSR_INAK) == CAN_MSR_INAK) && (wait_ack != INAK_TIMEOUT)) { wait_ack++; } /* ...and check acknowledged */ if ((CANx->MSR & CAN_MSR_INAK) == CAN_MSR_INAK) { InitStatus = CAN_InitStatus_Failed; } else { InitStatus = CAN_InitStatus_Success ; } } /* At this step, return the status of initialization */ return InitStatus; } /** * @brief Configures the CAN reception filter according to the specified * parameters in the CAN_FilterInitStruct. * @param CAN_FilterInitStruct: pointer to a CAN_FilterInitTypeDef structure that * contains the configuration information. * @retval None */ void CAN_FilterInit(CAN_FilterInitTypeDef* CAN_FilterInitStruct) { uint32_t filter_number_bit_pos = 0; /* Check the parameters */ assert_param(IS_CAN_FILTER_NUMBER(CAN_FilterInitStruct->CAN_FilterNumber)); assert_param(IS_CAN_FILTER_MODE(CAN_FilterInitStruct->CAN_FilterMode)); assert_param(IS_CAN_FILTER_SCALE(CAN_FilterInitStruct->CAN_FilterScale)); assert_param(IS_CAN_FILTER_FIFO(CAN_FilterInitStruct->CAN_FilterFIFOAssignment)); assert_param(IS_FUNCTIONAL_STATE(CAN_FilterInitStruct->CAN_FilterActivation)); filter_number_bit_pos = ((uint32_t)1) << CAN_FilterInitStruct->CAN_FilterNumber; /* Initialisation mode for the filter */ CAN1->FMR |= FMR_FINIT; /* Filter Deactivation */ CAN1->FA1R &= ~(uint32_t)filter_number_bit_pos; /* Filter Scale */ if (CAN_FilterInitStruct->CAN_FilterScale == CAN_FilterScale_16bit) { /* 16-bit scale for the filter */ CAN1->FS1R &= ~(uint32_t)filter_number_bit_pos; /* First 16-bit identifier and First 16-bit mask */ /* Or First 16-bit identifier and Second 16-bit identifier */ CAN1->sFilterRegister[CAN_FilterInitStruct->CAN_FilterNumber].FR1 = ((0x0000FFFF & (uint32_t)CAN_FilterInitStruct->CAN_FilterMaskIdLow) << 16) | (0x0000FFFF & (uint32_t)CAN_FilterInitStruct->CAN_FilterIdLow); /* Second 16-bit identifier and Second 16-bit mask */ /* Or Third 16-bit identifier and Fourth 16-bit identifier */ CAN1->sFilterRegister[CAN_FilterInitStruct->CAN_FilterNumber].FR2 = ((0x0000FFFF & (uint32_t)CAN_FilterInitStruct->CAN_FilterMaskIdHigh) << 16) | (0x0000FFFF & (uint32_t)CAN_FilterInitStruct->CAN_FilterIdHigh); } if (CAN_FilterInitStruct->CAN_FilterScale == CAN_FilterScale_32bit) { /* 32-bit scale for the filter */ CAN1->FS1R |= filter_number_bit_pos; /* 32-bit identifier or First 32-bit identifier */ CAN1->sFilterRegister[CAN_FilterInitStruct->CAN_FilterNumber].FR1 = ((0x0000FFFF & (uint32_t)CAN_FilterInitStruct->CAN_FilterIdHigh) << 16) | (0x0000FFFF & (uint32_t)CAN_FilterInitStruct->CAN_FilterIdLow); /* 32-bit mask or Second 32-bit identifier */ CAN1->sFilterRegister[CAN_FilterInitStruct->CAN_FilterNumber].FR2 = ((0x0000FFFF & (uint32_t)CAN_FilterInitStruct->CAN_FilterMaskIdHigh) << 16) | (0x0000FFFF & (uint32_t)CAN_FilterInitStruct->CAN_FilterMaskIdLow); } /* Filter Mode */ if (CAN_FilterInitStruct->CAN_FilterMode == CAN_FilterMode_IdMask) { /*Id/Mask mode for the filter*/ CAN1->FM1R &= ~(uint32_t)filter_number_bit_pos; } else /* CAN_FilterInitStruct->CAN_FilterMode == CAN_FilterMode_IdList */ { /*Identifier list mode for the filter*/ CAN1->FM1R |= (uint32_t)filter_number_bit_pos; } /* Filter FIFO assignment */ if (CAN_FilterInitStruct->CAN_FilterFIFOAssignment == CAN_Filter_FIFO0) { /* FIFO 0 assignation for the filter */ CAN1->FFA1R &= ~(uint32_t)filter_number_bit_pos; } if (CAN_FilterInitStruct->CAN_FilterFIFOAssignment == CAN_Filter_FIFO1) { /* FIFO 1 assignation for the filter */ CAN1->FFA1R |= (uint32_t)filter_number_bit_pos; } /* Filter activation */ if (CAN_FilterInitStruct->CAN_FilterActivation == ENABLE) { CAN1->FA1R |= filter_number_bit_pos; } /* Leave the initialisation mode for the filter */ CAN1->FMR &= ~FMR_FINIT; } /** * @brief Fills each CAN_InitStruct member with its default value. * @param CAN_InitStruct: pointer to a CAN_InitTypeDef structure which ill be initialized. * @retval None */ void CAN_StructInit(CAN_InitTypeDef* CAN_InitStruct) { /* Reset CAN init structure parameters values */ /* Initialize the time triggered communication mode */ CAN_InitStruct->CAN_TTCM = DISABLE; /* Initialize the automatic bus-off management */ CAN_InitStruct->CAN_ABOM = DISABLE; /* Initialize the automatic wake-up mode */ CAN_InitStruct->CAN_AWUM = DISABLE; /* Initialize the no automatic retransmission */ CAN_InitStruct->CAN_NART = DISABLE; /* Initialize the receive FIFO locked mode */ CAN_InitStruct->CAN_RFLM = DISABLE; /* Initialize the transmit FIFO priority */ CAN_InitStruct->CAN_TXFP = DISABLE; /* Initialize the CAN_Mode member */ CAN_InitStruct->CAN_Mode = CAN_Mode_Normal; /* Initialize the CAN_SJW member */ CAN_InitStruct->CAN_SJW = CAN_SJW_1tq; /* Initialize the CAN_BS1 member */ CAN_InitStruct->CAN_BS1 = CAN_BS1_4tq; /* Initialize the CAN_BS2 member */ CAN_InitStruct->CAN_BS2 = CAN_BS2_3tq; /* Initialize the CAN_Prescaler member */ CAN_InitStruct->CAN_Prescaler = 1; } /** * @brief Select the start bank filter for slave CAN. * @param CAN_BankNumber: Select the start slave bank filter from 1..27. * @retval None */ void CAN_SlaveStartBank(uint8_t CAN_BankNumber) { /* Check the parameters */ assert_param(IS_CAN_BANKNUMBER(CAN_BankNumber)); /* Enter Initialisation mode for the filter */ CAN1->FMR |= FMR_FINIT; /* Select the start slave bank */ CAN1->FMR &= (uint32_t)0xFFFFC0F1 ; CAN1->FMR |= (uint32_t)(CAN_BankNumber)<<8; /* Leave Initialisation mode for the filter */ CAN1->FMR &= ~FMR_FINIT; } /** * @brief Enables or disables the DBG Freeze for CAN. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @param NewState: new state of the CAN peripheral. * This parameter can be: ENABLE (CAN reception/transmission is frozen * during debug. Reception FIFOs can still be accessed/controlled normally) * or DISABLE (CAN is working during debug). * @retval None */ void CAN_DBGFreeze(CAN_TypeDef* CANx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable Debug Freeze */ CANx->MCR |= MCR_DBF; } else { /* Disable Debug Freeze */ CANx->MCR &= ~MCR_DBF; } } /** * @brief Enables or disables the CAN Time TriggerOperation communication mode. * @note DLC must be programmed as 8 in order Time Stamp (2 bytes) to be * sent over the CAN bus. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @param NewState: Mode new state. This parameter can be: ENABLE or DISABLE. * When enabled, Time stamp (TIME[15:0]) value is sent in the last two * data bytes of the 8-byte message: TIME[7:0] in data byte 6 and TIME[15:8] * in data byte 7. * @retval None */ void CAN_TTComModeCmd(CAN_TypeDef* CANx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the TTCM mode */ CANx->MCR |= CAN_MCR_TTCM; /* Set TGT bits */ CANx->sTxMailBox[0].TDTR |= ((uint32_t)CAN_TDT0R_TGT); CANx->sTxMailBox[1].TDTR |= ((uint32_t)CAN_TDT1R_TGT); CANx->sTxMailBox[2].TDTR |= ((uint32_t)CAN_TDT2R_TGT); } else { /* Disable the TTCM mode */ CANx->MCR &= (uint32_t)(~(uint32_t)CAN_MCR_TTCM); /* Reset TGT bits */ CANx->sTxMailBox[0].TDTR &= ((uint32_t)~CAN_TDT0R_TGT); CANx->sTxMailBox[1].TDTR &= ((uint32_t)~CAN_TDT1R_TGT); CANx->sTxMailBox[2].TDTR &= ((uint32_t)~CAN_TDT2R_TGT); } } /** * @} */ /** @defgroup CAN_Group2 CAN Frames Transmission functions * @brief CAN Frames Transmission functions * @verbatim =============================================================================== ##### CAN Frames Transmission functions ##### =============================================================================== [..] This section provides functions allowing to (+) Initiate and transmit a CAN frame message (if there is an empty mailbox). (+) Check the transmission status of a CAN Frame (+) Cancel a transmit request @endverbatim * @{ */ /** * @brief Initiates and transmits a CAN frame message. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @param TxMessage: pointer to a structure which contains CAN Id, CAN DLC and CAN data. * @retval The number of the mailbox that is used for transmission or * CAN_TxStatus_NoMailBox if there is no empty mailbox. */ uint8_t CAN_Transmit(CAN_TypeDef* CANx, CanTxMsg* TxMessage) { uint8_t transmit_mailbox = 0; /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); assert_param(IS_CAN_IDTYPE(TxMessage->IDE)); assert_param(IS_CAN_RTR(TxMessage->RTR)); assert_param(IS_CAN_DLC(TxMessage->DLC)); /* Select one empty transmit mailbox */ if ((CANx->TSR&CAN_TSR_TME0) == CAN_TSR_TME0) { transmit_mailbox = 0; } else if ((CANx->TSR&CAN_TSR_TME1) == CAN_TSR_TME1) { transmit_mailbox = 1; } else if ((CANx->TSR&CAN_TSR_TME2) == CAN_TSR_TME2) { transmit_mailbox = 2; } else { transmit_mailbox = CAN_TxStatus_NoMailBox; } if (transmit_mailbox != CAN_TxStatus_NoMailBox) { /* Set up the Id */ CANx->sTxMailBox[transmit_mailbox].TIR &= TMIDxR_TXRQ; if (TxMessage->IDE == CAN_Id_Standard) { assert_param(IS_CAN_STDID(TxMessage->StdId)); CANx->sTxMailBox[transmit_mailbox].TIR |= ((TxMessage->StdId << 21) | \ TxMessage->RTR); } else { assert_param(IS_CAN_EXTID(TxMessage->ExtId)); CANx->sTxMailBox[transmit_mailbox].TIR |= ((TxMessage->ExtId << 3) | \ TxMessage->IDE | \ TxMessage->RTR); } /* Set up the DLC */ TxMessage->DLC &= (uint8_t)0x0000000F; CANx->sTxMailBox[transmit_mailbox].TDTR &= (uint32_t)0xFFFFFFF0; CANx->sTxMailBox[transmit_mailbox].TDTR |= TxMessage->DLC; /* Set up the data field */ CANx->sTxMailBox[transmit_mailbox].TDLR = (((uint32_t)TxMessage->Data[3] << 24) | ((uint32_t)TxMessage->Data[2] << 16) | ((uint32_t)TxMessage->Data[1] << 8) | ((uint32_t)TxMessage->Data[0])); CANx->sTxMailBox[transmit_mailbox].TDHR = (((uint32_t)TxMessage->Data[7] << 24) | ((uint32_t)TxMessage->Data[6] << 16) | ((uint32_t)TxMessage->Data[5] << 8) | ((uint32_t)TxMessage->Data[4])); /* Request transmission */ CANx->sTxMailBox[transmit_mailbox].TIR |= TMIDxR_TXRQ; } return transmit_mailbox; } /** * @brief Checks the transmission status of a CAN Frame. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @param TransmitMailbox: the number of the mailbox that is used for transmission. * @retval CAN_TxStatus_Ok if the CAN driver transmits the message, * CAN_TxStatus_Failed in an other case. */ uint8_t CAN_TransmitStatus(CAN_TypeDef* CANx, uint8_t TransmitMailbox) { uint32_t state = 0; /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); assert_param(IS_CAN_TRANSMITMAILBOX(TransmitMailbox)); switch (TransmitMailbox) { case (CAN_TXMAILBOX_0): state = CANx->TSR & (CAN_TSR_RQCP0 | CAN_TSR_TXOK0 | CAN_TSR_TME0); break; case (CAN_TXMAILBOX_1): state = CANx->TSR & (CAN_TSR_RQCP1 | CAN_TSR_TXOK1 | CAN_TSR_TME1); break; case (CAN_TXMAILBOX_2): state = CANx->TSR & (CAN_TSR_RQCP2 | CAN_TSR_TXOK2 | CAN_TSR_TME2); break; default: state = CAN_TxStatus_Failed; break; } switch (state) { /* transmit pending */ case (0x0): state = CAN_TxStatus_Pending; break; /* transmit failed */ case (CAN_TSR_RQCP0 | CAN_TSR_TME0): state = CAN_TxStatus_Failed; break; case (CAN_TSR_RQCP1 | CAN_TSR_TME1): state = CAN_TxStatus_Failed; break; case (CAN_TSR_RQCP2 | CAN_TSR_TME2): state = CAN_TxStatus_Failed; break; /* transmit succeeded */ case (CAN_TSR_RQCP0 | CAN_TSR_TXOK0 | CAN_TSR_TME0):state = CAN_TxStatus_Ok; break; case (CAN_TSR_RQCP1 | CAN_TSR_TXOK1 | CAN_TSR_TME1):state = CAN_TxStatus_Ok; break; case (CAN_TSR_RQCP2 | CAN_TSR_TXOK2 | CAN_TSR_TME2):state = CAN_TxStatus_Ok; break; default: state = CAN_TxStatus_Failed; break; } return (uint8_t) state; } /** * @brief Cancels a transmit request. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @param Mailbox: Mailbox number. * @retval None */ void CAN_CancelTransmit(CAN_TypeDef* CANx, uint8_t Mailbox) { /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); assert_param(IS_CAN_TRANSMITMAILBOX(Mailbox)); /* abort transmission */ switch (Mailbox) { case (CAN_TXMAILBOX_0): CANx->TSR |= CAN_TSR_ABRQ0; break; case (CAN_TXMAILBOX_1): CANx->TSR |= CAN_TSR_ABRQ1; break; case (CAN_TXMAILBOX_2): CANx->TSR |= CAN_TSR_ABRQ2; break; default: break; } } /** * @} */ /** @defgroup CAN_Group3 CAN Frames Reception functions * @brief CAN Frames Reception functions * @verbatim =============================================================================== ##### CAN Frames Reception functions ##### =============================================================================== [..] This section provides functions allowing to (+) Receive a correct CAN frame (+) Release a specified receive FIFO (2 FIFOs are available) (+) Return the number of the pending received CAN frames @endverbatim * @{ */ /** * @brief Receives a correct CAN frame. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @param FIFONumber: Receive FIFO number, CAN_FIFO0 or CAN_FIFO1. * @param RxMessage: pointer to a structure receive frame which contains CAN Id, * CAN DLC, CAN data and FMI number. * @retval None */ void CAN_Receive(CAN_TypeDef* CANx, uint8_t FIFONumber, CanRxMsg* RxMessage) { /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); assert_param(IS_CAN_FIFO(FIFONumber)); /* Get the Id */ RxMessage->IDE = (uint8_t)0x04 & CANx->sFIFOMailBox[FIFONumber].RIR; if (RxMessage->IDE == CAN_Id_Standard) { RxMessage->StdId = (uint32_t)0x000007FF & (CANx->sFIFOMailBox[FIFONumber].RIR >> 21); } else { RxMessage->ExtId = (uint32_t)0x1FFFFFFF & (CANx->sFIFOMailBox[FIFONumber].RIR >> 3); } RxMessage->RTR = (uint8_t)0x02 & CANx->sFIFOMailBox[FIFONumber].RIR; /* Get the DLC */ RxMessage->DLC = (uint8_t)0x0F & CANx->sFIFOMailBox[FIFONumber].RDTR; /* Get the FMI */ RxMessage->FMI = (uint8_t)0xFF & (CANx->sFIFOMailBox[FIFONumber].RDTR >> 8); /* Get the data field */ RxMessage->Data[0] = (uint8_t)0xFF & CANx->sFIFOMailBox[FIFONumber].RDLR; RxMessage->Data[1] = (uint8_t)0xFF & (CANx->sFIFOMailBox[FIFONumber].RDLR >> 8); RxMessage->Data[2] = (uint8_t)0xFF & (CANx->sFIFOMailBox[FIFONumber].RDLR >> 16); RxMessage->Data[3] = (uint8_t)0xFF & (CANx->sFIFOMailBox[FIFONumber].RDLR >> 24); RxMessage->Data[4] = (uint8_t)0xFF & CANx->sFIFOMailBox[FIFONumber].RDHR; RxMessage->Data[5] = (uint8_t)0xFF & (CANx->sFIFOMailBox[FIFONumber].RDHR >> 8); RxMessage->Data[6] = (uint8_t)0xFF & (CANx->sFIFOMailBox[FIFONumber].RDHR >> 16); RxMessage->Data[7] = (uint8_t)0xFF & (CANx->sFIFOMailBox[FIFONumber].RDHR >> 24); /* Release the FIFO */ /* Release FIFO0 */ if (FIFONumber == CAN_FIFO0) { CANx->RF0R |= CAN_RF0R_RFOM0; } /* Release FIFO1 */ else /* FIFONumber == CAN_FIFO1 */ { CANx->RF1R |= CAN_RF1R_RFOM1; } } /** * @brief Releases the specified receive FIFO. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @param FIFONumber: FIFO to release, CAN_FIFO0 or CAN_FIFO1. * @retval None */ void CAN_FIFORelease(CAN_TypeDef* CANx, uint8_t FIFONumber) { /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); assert_param(IS_CAN_FIFO(FIFONumber)); /* Release FIFO0 */ if (FIFONumber == CAN_FIFO0) { CANx->RF0R |= CAN_RF0R_RFOM0; } /* Release FIFO1 */ else /* FIFONumber == CAN_FIFO1 */ { CANx->RF1R |= CAN_RF1R_RFOM1; } } /** * @brief Returns the number of pending received messages. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @param FIFONumber: Receive FIFO number, CAN_FIFO0 or CAN_FIFO1. * @retval NbMessage : which is the number of pending message. */ uint8_t CAN_MessagePending(CAN_TypeDef* CANx, uint8_t FIFONumber) { uint8_t message_pending=0; /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); assert_param(IS_CAN_FIFO(FIFONumber)); if (FIFONumber == CAN_FIFO0) { message_pending = (uint8_t)(CANx->RF0R&(uint32_t)0x03); } else if (FIFONumber == CAN_FIFO1) { message_pending = (uint8_t)(CANx->RF1R&(uint32_t)0x03); } else { message_pending = 0; } return message_pending; } /** * @} */ /** @defgroup CAN_Group4 CAN Operation modes functions * @brief CAN Operation modes functions * @verbatim =============================================================================== ##### CAN Operation modes functions ##### =============================================================================== [..] This section provides functions allowing to select the CAN Operation modes (+) sleep mode (+) normal mode (+) initialization mode @endverbatim * @{ */ /** * @brief Selects the CAN Operation mode. * @param CAN_OperatingMode: CAN Operating Mode. * This parameter can be one of @ref CAN_OperatingMode_TypeDef enumeration. * @retval status of the requested mode which can be * - CAN_ModeStatus_Failed: CAN failed entering the specific mode * - CAN_ModeStatus_Success: CAN Succeed entering the specific mode */ uint8_t CAN_OperatingModeRequest(CAN_TypeDef* CANx, uint8_t CAN_OperatingMode) { uint8_t status = CAN_ModeStatus_Failed; /* Timeout for INAK or also for SLAK bits*/ uint32_t timeout = INAK_TIMEOUT; /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); assert_param(IS_CAN_OPERATING_MODE(CAN_OperatingMode)); if (CAN_OperatingMode == CAN_OperatingMode_Initialization) { /* Request initialisation */ CANx->MCR = (uint32_t)((CANx->MCR & (uint32_t)(~(uint32_t)CAN_MCR_SLEEP)) | CAN_MCR_INRQ); /* Wait the acknowledge */ while (((CANx->MSR & CAN_MODE_MASK) != CAN_MSR_INAK) && (timeout != 0)) { timeout--; } if ((CANx->MSR & CAN_MODE_MASK) != CAN_MSR_INAK) { status = CAN_ModeStatus_Failed; } else { status = CAN_ModeStatus_Success; } } else if (CAN_OperatingMode == CAN_OperatingMode_Normal) { /* Request leave initialisation and sleep mode and enter Normal mode */ CANx->MCR &= (uint32_t)(~(CAN_MCR_SLEEP|CAN_MCR_INRQ)); /* Wait the acknowledge */ while (((CANx->MSR & CAN_MODE_MASK) != 0) && (timeout!=0)) { timeout--; } if ((CANx->MSR & CAN_MODE_MASK) != 0) { status = CAN_ModeStatus_Failed; } else { status = CAN_ModeStatus_Success; } } else if (CAN_OperatingMode == CAN_OperatingMode_Sleep) { /* Request Sleep mode */ CANx->MCR = (uint32_t)((CANx->MCR & (uint32_t)(~(uint32_t)CAN_MCR_INRQ)) | CAN_MCR_SLEEP); /* Wait the acknowledge */ while (((CANx->MSR & CAN_MODE_MASK) != CAN_MSR_SLAK) && (timeout!=0)) { timeout--; } if ((CANx->MSR & CAN_MODE_MASK) != CAN_MSR_SLAK) { status = CAN_ModeStatus_Failed; } else { status = CAN_ModeStatus_Success; } } else { status = CAN_ModeStatus_Failed; } return (uint8_t) status; } /** * @brief Enters the Sleep (low power) mode. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @retval CAN_Sleep_Ok if sleep entered, CAN_Sleep_Failed otherwise. */ uint8_t CAN_Sleep(CAN_TypeDef* CANx) { uint8_t sleepstatus = CAN_Sleep_Failed; /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); /* Request Sleep mode */ CANx->MCR = (((CANx->MCR) & (uint32_t)(~(uint32_t)CAN_MCR_INRQ)) | CAN_MCR_SLEEP); /* Sleep mode status */ if ((CANx->MSR & (CAN_MSR_SLAK|CAN_MSR_INAK)) == CAN_MSR_SLAK) { /* Sleep mode not entered */ sleepstatus = CAN_Sleep_Ok; } /* return sleep mode status */ return (uint8_t)sleepstatus; } /** * @brief Wakes up the CAN peripheral from sleep mode . * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @retval CAN_WakeUp_Ok if sleep mode left, CAN_WakeUp_Failed otherwise. */ uint8_t CAN_WakeUp(CAN_TypeDef* CANx) { uint32_t wait_slak = SLAK_TIMEOUT; uint8_t wakeupstatus = CAN_WakeUp_Failed; /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); /* Wake up request */ CANx->MCR &= ~(uint32_t)CAN_MCR_SLEEP; /* Sleep mode status */ while(((CANx->MSR & CAN_MSR_SLAK) == CAN_MSR_SLAK)&&(wait_slak!=0x00)) { wait_slak--; } if((CANx->MSR & CAN_MSR_SLAK) != CAN_MSR_SLAK) { /* wake up done : Sleep mode exited */ wakeupstatus = CAN_WakeUp_Ok; } /* return wakeup status */ return (uint8_t)wakeupstatus; } /** * @} */ /** @defgroup CAN_Group5 CAN Bus Error management functions * @brief CAN Bus Error management functions * @verbatim =============================================================================== ##### CAN Bus Error management functions ##### =============================================================================== [..] This section provides functions allowing to (+) Return the CANx's last error code (LEC) (+) Return the CANx Receive Error Counter (REC) (+) Return the LSB of the 9-bit CANx Transmit Error Counter(TEC). -@- If TEC is greater than 255, The CAN is in bus-off state. -@- if REC or TEC are greater than 96, an Error warning flag occurs. -@- if REC or TEC are greater than 127, an Error Passive Flag occurs. @endverbatim * @{ */ /** * @brief Returns the CANx's last error code (LEC). * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @retval Error code: * - CAN_ERRORCODE_NoErr: No Error * - CAN_ERRORCODE_StuffErr: Stuff Error * - CAN_ERRORCODE_FormErr: Form Error * - CAN_ERRORCODE_ACKErr : Acknowledgment Error * - CAN_ERRORCODE_BitRecessiveErr: Bit Recessive Error * - CAN_ERRORCODE_BitDominantErr: Bit Dominant Error * - CAN_ERRORCODE_CRCErr: CRC Error * - CAN_ERRORCODE_SoftwareSetErr: Software Set Error */ uint8_t CAN_GetLastErrorCode(CAN_TypeDef* CANx) { uint8_t errorcode=0; /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); /* Get the error code*/ errorcode = (((uint8_t)CANx->ESR) & (uint8_t)CAN_ESR_LEC); /* Return the error code*/ return errorcode; } /** * @brief Returns the CANx Receive Error Counter (REC). * @note In case of an error during reception, this counter is incremented * by 1 or by 8 depending on the error condition as defined by the CAN * standard. After every successful reception, the counter is * decremented by 1 or reset to 120 if its value was higher than 128. * When the counter value exceeds 127, the CAN controller enters the * error passive state. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @retval CAN Receive Error Counter. */ uint8_t CAN_GetReceiveErrorCounter(CAN_TypeDef* CANx) { uint8_t counter=0; /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); /* Get the Receive Error Counter*/ counter = (uint8_t)((CANx->ESR & CAN_ESR_REC)>> 24); /* Return the Receive Error Counter*/ return counter; } /** * @brief Returns the LSB of the 9-bit CANx Transmit Error Counter(TEC). * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @retval LSB of the 9-bit CAN Transmit Error Counter. */ uint8_t CAN_GetLSBTransmitErrorCounter(CAN_TypeDef* CANx) { uint8_t counter=0; /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); /* Get the LSB of the 9-bit CANx Transmit Error Counter(TEC) */ counter = (uint8_t)((CANx->ESR & CAN_ESR_TEC)>> 16); /* Return the LSB of the 9-bit CANx Transmit Error Counter(TEC) */ return counter; } /** * @} */ /** @defgroup CAN_Group6 Interrupts and flags management functions * @brief Interrupts and flags management functions * @verbatim =============================================================================== ##### Interrupts and flags management functions ##### =============================================================================== [..] This section provides functions allowing to configure the CAN Interrupts and to get the status and clear flags and Interrupts pending bits. The CAN provides 14 Interrupts sources and 15 Flags: *** Flags *** ============= [..] The 15 flags can be divided on 4 groups: (+) Transmit Flags (++) CAN_FLAG_RQCP0, (++) CAN_FLAG_RQCP1, (++) CAN_FLAG_RQCP2 : Request completed MailBoxes 0, 1 and 2 Flags Set when the last request (transmit or abort) has been performed. (+) Receive Flags (++) CAN_FLAG_FMP0, (++) CAN_FLAG_FMP1 : FIFO 0 and 1 Message Pending Flags set to signal that messages are pending in the receive FIFO. These Flags are cleared only by hardware. (++) CAN_FLAG_FF0, (++) CAN_FLAG_FF1 : FIFO 0 and 1 Full Flags set when three messages are stored in the selected FIFO. (++) CAN_FLAG_FOV0 (++) CAN_FLAG_FOV1 : FIFO 0 and 1 Overrun Flags set when a new message has been received and passed the filter while the FIFO was full. (+) Operating Mode Flags (++) CAN_FLAG_WKU : Wake up Flag set to signal that a SOF bit has been detected while the CAN hardware was in Sleep mode. (++) CAN_FLAG_SLAK : Sleep acknowledge Flag Set to signal that the CAN has entered Sleep Mode. (+) Error Flags (++) CAN_FLAG_EWG : Error Warning Flag Set when the warning limit has been reached (Receive Error Counter or Transmit Error Counter greater than 96). This Flag is cleared only by hardware. (++) CAN_FLAG_EPV : Error Passive Flag Set when the Error Passive limit has been reached (Receive Error Counter or Transmit Error Counter greater than 127). This Flag is cleared only by hardware. (++) CAN_FLAG_BOF : Bus-Off Flag set when CAN enters the bus-off state. The bus-off state is entered on TEC overflow, greater than 255. This Flag is cleared only by hardware. (++) CAN_FLAG_LEC : Last error code Flag set If a message has been transferred (reception or transmission) with error, and the error code is hold. *** Interrupts *** ================== [..] The 14 interrupts can be divided on 4 groups: (+) Transmit interrupt (++) CAN_IT_TME : Transmit mailbox empty Interrupt if enabled, this interrupt source is pending when no transmit request are pending for Tx mailboxes. (+) Receive Interrupts (++) CAN_IT_FMP0, (++) CAN_IT_FMP1 : FIFO 0 and FIFO1 message pending Interrupts if enabled, these interrupt sources are pending when messages are pending in the receive FIFO. The corresponding interrupt pending bits are cleared only by hardware. (++) CAN_IT_FF0, (++) CAN_IT_FF1 : FIFO 0 and FIFO1 full Interrupts if enabled, these interrupt sources are pending when three messages are stored in the selected FIFO. (++) CAN_IT_FOV0, (++) CAN_IT_FOV1 : FIFO 0 and FIFO1 overrun Interrupts if enabled, these interrupt sources are pending when a new message has been received and passed the filter while the FIFO was full. (+) Operating Mode Interrupts (++) CAN_IT_WKU : Wake-up Interrupt if enabled, this interrupt source is pending when a SOF bit has been detected while the CAN hardware was in Sleep mode. (++) CAN_IT_SLK : Sleep acknowledge Interrupt if enabled, this interrupt source is pending when the CAN has entered Sleep Mode. (+) Error Interrupts (++) CAN_IT_EWG : Error warning Interrupt if enabled, this interrupt source is pending when the warning limit has been reached (Receive Error Counter or Transmit Error Counter=96). (++) CAN_IT_EPV : Error passive Interrupt if enabled, this interrupt source is pending when the Error Passive limit has been reached (Receive Error Counter or Transmit Error Counter>127). (++) CAN_IT_BOF : Bus-off Interrupt if enabled, this interrupt source is pending when CAN enters the bus-off state. The bus-off state is entered on TEC overflow, greater than 255. This Flag is cleared only by hardware. (++) CAN_IT_LEC : Last error code Interrupt if enabled, this interrupt source is pending when a message has been transferred (reception or transmission) with error, and the error code is hold. (++) CAN_IT_ERR : Error Interrupt if enabled, this interrupt source is pending when an error condition is pending. [..] Managing the CAN controller events : The user should identify which mode will be used in his application to manage the CAN controller events: Polling mode or Interrupt mode. (#) In the Polling Mode it is advised to use the following functions: (++) CAN_GetFlagStatus() : to check if flags events occur. (++) CAN_ClearFlag() : to clear the flags events. (#) In the Interrupt Mode it is advised to use the following functions: (++) CAN_ITConfig() : to enable or disable the interrupt source. (++) CAN_GetITStatus() : to check if Interrupt occurs. (++) CAN_ClearITPendingBit() : to clear the Interrupt pending Bit (corresponding Flag). -@@- This function has no impact on CAN_IT_FMP0 and CAN_IT_FMP1 Interrupts pending bits since there are cleared only by hardware. @endverbatim * @{ */ /** * @brief Enables or disables the specified CANx interrupts. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @param CAN_IT: specifies the CAN interrupt sources to be enabled or disabled. * This parameter can be: * @arg CAN_IT_TME: Transmit mailbox empty Interrupt * @arg CAN_IT_FMP0: FIFO 0 message pending Interrupt * @arg CAN_IT_FF0: FIFO 0 full Interrupt * @arg CAN_IT_FOV0: FIFO 0 overrun Interrupt * @arg CAN_IT_FMP1: FIFO 1 message pending Interrupt * @arg CAN_IT_FF1: FIFO 1 full Interrupt * @arg CAN_IT_FOV1: FIFO 1 overrun Interrupt * @arg CAN_IT_WKU: Wake-up Interrupt * @arg CAN_IT_SLK: Sleep acknowledge Interrupt * @arg CAN_IT_EWG: Error warning Interrupt * @arg CAN_IT_EPV: Error passive Interrupt * @arg CAN_IT_BOF: Bus-off Interrupt * @arg CAN_IT_LEC: Last error code Interrupt * @arg CAN_IT_ERR: Error Interrupt * @param NewState: new state of the CAN interrupts. * This parameter can be: ENABLE or DISABLE. * @retval None */ void CAN_ITConfig(CAN_TypeDef* CANx, uint32_t CAN_IT, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); assert_param(IS_CAN_IT(CAN_IT)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected CANx interrupt */ CANx->IER |= CAN_IT; } else { /* Disable the selected CANx interrupt */ CANx->IER &= ~CAN_IT; } } /** * @brief Checks whether the specified CAN flag is set or not. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @param CAN_FLAG: specifies the flag to check. * This parameter can be one of the following values: * @arg CAN_FLAG_RQCP0: Request MailBox0 Flag * @arg CAN_FLAG_RQCP1: Request MailBox1 Flag * @arg CAN_FLAG_RQCP2: Request MailBox2 Flag * @arg CAN_FLAG_FMP0: FIFO 0 Message Pending Flag * @arg CAN_FLAG_FF0: FIFO 0 Full Flag * @arg CAN_FLAG_FOV0: FIFO 0 Overrun Flag * @arg CAN_FLAG_FMP1: FIFO 1 Message Pending Flag * @arg CAN_FLAG_FF1: FIFO 1 Full Flag * @arg CAN_FLAG_FOV1: FIFO 1 Overrun Flag * @arg CAN_FLAG_WKU: Wake up Flag * @arg CAN_FLAG_SLAK: Sleep acknowledge Flag * @arg CAN_FLAG_EWG: Error Warning Flag * @arg CAN_FLAG_EPV: Error Passive Flag * @arg CAN_FLAG_BOF: Bus-Off Flag * @arg CAN_FLAG_LEC: Last error code Flag * @retval The new state of CAN_FLAG (SET or RESET). */ FlagStatus CAN_GetFlagStatus(CAN_TypeDef* CANx, uint32_t CAN_FLAG) { FlagStatus bitstatus = RESET; /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); assert_param(IS_CAN_GET_FLAG(CAN_FLAG)); if((CAN_FLAG & CAN_FLAGS_ESR) != (uint32_t)RESET) { /* Check the status of the specified CAN flag */ if ((CANx->ESR & (CAN_FLAG & 0x000FFFFF)) != (uint32_t)RESET) { /* CAN_FLAG is set */ bitstatus = SET; } else { /* CAN_FLAG is reset */ bitstatus = RESET; } } else if((CAN_FLAG & CAN_FLAGS_MSR) != (uint32_t)RESET) { /* Check the status of the specified CAN flag */ if ((CANx->MSR & (CAN_FLAG & 0x000FFFFF)) != (uint32_t)RESET) { /* CAN_FLAG is set */ bitstatus = SET; } else { /* CAN_FLAG is reset */ bitstatus = RESET; } } else if((CAN_FLAG & CAN_FLAGS_TSR) != (uint32_t)RESET) { /* Check the status of the specified CAN flag */ if ((CANx->TSR & (CAN_FLAG & 0x000FFFFF)) != (uint32_t)RESET) { /* CAN_FLAG is set */ bitstatus = SET; } else { /* CAN_FLAG is reset */ bitstatus = RESET; } } else if((CAN_FLAG & CAN_FLAGS_RF0R) != (uint32_t)RESET) { /* Check the status of the specified CAN flag */ if ((CANx->RF0R & (CAN_FLAG & 0x000FFFFF)) != (uint32_t)RESET) { /* CAN_FLAG is set */ bitstatus = SET; } else { /* CAN_FLAG is reset */ bitstatus = RESET; } } else /* If(CAN_FLAG & CAN_FLAGS_RF1R != (uint32_t)RESET) */ { /* Check the status of the specified CAN flag */ if ((uint32_t)(CANx->RF1R & (CAN_FLAG & 0x000FFFFF)) != (uint32_t)RESET) { /* CAN_FLAG is set */ bitstatus = SET; } else { /* CAN_FLAG is reset */ bitstatus = RESET; } } /* Return the CAN_FLAG status */ return bitstatus; } /** * @brief Clears the CAN's pending flags. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @param CAN_FLAG: specifies the flag to clear. * This parameter can be one of the following values: * @arg CAN_FLAG_RQCP0: Request MailBox0 Flag * @arg CAN_FLAG_RQCP1: Request MailBox1 Flag * @arg CAN_FLAG_RQCP2: Request MailBox2 Flag * @arg CAN_FLAG_FF0: FIFO 0 Full Flag * @arg CAN_FLAG_FOV0: FIFO 0 Overrun Flag * @arg CAN_FLAG_FF1: FIFO 1 Full Flag * @arg CAN_FLAG_FOV1: FIFO 1 Overrun Flag * @arg CAN_FLAG_WKU: Wake up Flag * @arg CAN_FLAG_SLAK: Sleep acknowledge Flag * @arg CAN_FLAG_LEC: Last error code Flag * @retval None */ void CAN_ClearFlag(CAN_TypeDef* CANx, uint32_t CAN_FLAG) { uint32_t flagtmp=0; /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); assert_param(IS_CAN_CLEAR_FLAG(CAN_FLAG)); if (CAN_FLAG == CAN_FLAG_LEC) /* ESR register */ { /* Clear the selected CAN flags */ CANx->ESR = (uint32_t)RESET; } else /* MSR or TSR or RF0R or RF1R */ { flagtmp = CAN_FLAG & 0x000FFFFF; if ((CAN_FLAG & CAN_FLAGS_RF0R)!=(uint32_t)RESET) { /* Receive Flags */ CANx->RF0R = (uint32_t)(flagtmp); } else if ((CAN_FLAG & CAN_FLAGS_RF1R)!=(uint32_t)RESET) { /* Receive Flags */ CANx->RF1R = (uint32_t)(flagtmp); } else if ((CAN_FLAG & CAN_FLAGS_TSR)!=(uint32_t)RESET) { /* Transmit Flags */ CANx->TSR = (uint32_t)(flagtmp); } else /* If((CAN_FLAG & CAN_FLAGS_MSR)!=(uint32_t)RESET) */ { /* Operating mode Flags */ CANx->MSR = (uint32_t)(flagtmp); } } } /** * @brief Checks whether the specified CANx interrupt has occurred or not. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @param CAN_IT: specifies the CAN interrupt source to check. * This parameter can be one of the following values: * @arg CAN_IT_TME: Transmit mailbox empty Interrupt * @arg CAN_IT_FMP0: FIFO 0 message pending Interrupt * @arg CAN_IT_FF0: FIFO 0 full Interrupt * @arg CAN_IT_FOV0: FIFO 0 overrun Interrupt * @arg CAN_IT_FMP1: FIFO 1 message pending Interrupt * @arg CAN_IT_FF1: FIFO 1 full Interrupt * @arg CAN_IT_FOV1: FIFO 1 overrun Interrupt * @arg CAN_IT_WKU: Wake-up Interrupt * @arg CAN_IT_SLK: Sleep acknowledge Interrupt * @arg CAN_IT_EWG: Error warning Interrupt * @arg CAN_IT_EPV: Error passive Interrupt * @arg CAN_IT_BOF: Bus-off Interrupt * @arg CAN_IT_LEC: Last error code Interrupt * @arg CAN_IT_ERR: Error Interrupt * @retval The current state of CAN_IT (SET or RESET). */ ITStatus CAN_GetITStatus(CAN_TypeDef* CANx, uint32_t CAN_IT) { ITStatus itstatus = RESET; /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); assert_param(IS_CAN_IT(CAN_IT)); /* check the interrupt enable bit */ if((CANx->IER & CAN_IT) != RESET) { /* in case the Interrupt is enabled, .... */ switch (CAN_IT) { case CAN_IT_TME: /* Check CAN_TSR_RQCPx bits */ itstatus = CheckITStatus(CANx->TSR, CAN_TSR_RQCP0|CAN_TSR_RQCP1|CAN_TSR_RQCP2); break; case CAN_IT_FMP0: /* Check CAN_RF0R_FMP0 bit */ itstatus = CheckITStatus(CANx->RF0R, CAN_RF0R_FMP0); break; case CAN_IT_FF0: /* Check CAN_RF0R_FULL0 bit */ itstatus = CheckITStatus(CANx->RF0R, CAN_RF0R_FULL0); break; case CAN_IT_FOV0: /* Check CAN_RF0R_FOVR0 bit */ itstatus = CheckITStatus(CANx->RF0R, CAN_RF0R_FOVR0); break; case CAN_IT_FMP1: /* Check CAN_RF1R_FMP1 bit */ itstatus = CheckITStatus(CANx->RF1R, CAN_RF1R_FMP1); break; case CAN_IT_FF1: /* Check CAN_RF1R_FULL1 bit */ itstatus = CheckITStatus(CANx->RF1R, CAN_RF1R_FULL1); break; case CAN_IT_FOV1: /* Check CAN_RF1R_FOVR1 bit */ itstatus = CheckITStatus(CANx->RF1R, CAN_RF1R_FOVR1); break; case CAN_IT_WKU: /* Check CAN_MSR_WKUI bit */ itstatus = CheckITStatus(CANx->MSR, CAN_MSR_WKUI); break; case CAN_IT_SLK: /* Check CAN_MSR_SLAKI bit */ itstatus = CheckITStatus(CANx->MSR, CAN_MSR_SLAKI); break; case CAN_IT_EWG: /* Check CAN_ESR_EWGF bit */ itstatus = CheckITStatus(CANx->ESR, CAN_ESR_EWGF); break; case CAN_IT_EPV: /* Check CAN_ESR_EPVF bit */ itstatus = CheckITStatus(CANx->ESR, CAN_ESR_EPVF); break; case CAN_IT_BOF: /* Check CAN_ESR_BOFF bit */ itstatus = CheckITStatus(CANx->ESR, CAN_ESR_BOFF); break; case CAN_IT_LEC: /* Check CAN_ESR_LEC bit */ itstatus = CheckITStatus(CANx->ESR, CAN_ESR_LEC); break; case CAN_IT_ERR: /* Check CAN_MSR_ERRI bit */ itstatus = CheckITStatus(CANx->MSR, CAN_MSR_ERRI); break; default: /* in case of error, return RESET */ itstatus = RESET; break; } } else { /* in case the Interrupt is not enabled, return RESET */ itstatus = RESET; } /* Return the CAN_IT status */ return itstatus; } /** * @brief Clears the CANx's interrupt pending bits. * @param CANx: where x can be 1 or 2 to select the CAN peripheral. * @param CAN_IT: specifies the interrupt pending bit to clear. * This parameter can be one of the following values: * @arg CAN_IT_TME: Transmit mailbox empty Interrupt * @arg CAN_IT_FF0: FIFO 0 full Interrupt * @arg CAN_IT_FOV0: FIFO 0 overrun Interrupt * @arg CAN_IT_FF1: FIFO 1 full Interrupt * @arg CAN_IT_FOV1: FIFO 1 overrun Interrupt * @arg CAN_IT_WKU: Wake-up Interrupt * @arg CAN_IT_SLK: Sleep acknowledge Interrupt * @arg CAN_IT_EWG: Error warning Interrupt * @arg CAN_IT_EPV: Error passive Interrupt * @arg CAN_IT_BOF: Bus-off Interrupt * @arg CAN_IT_LEC: Last error code Interrupt * @arg CAN_IT_ERR: Error Interrupt * @retval None */ void CAN_ClearITPendingBit(CAN_TypeDef* CANx, uint32_t CAN_IT) { /* Check the parameters */ assert_param(IS_CAN_ALL_PERIPH(CANx)); assert_param(IS_CAN_CLEAR_IT(CAN_IT)); switch (CAN_IT) { case CAN_IT_TME: /* Clear CAN_TSR_RQCPx (rc_w1)*/ CANx->TSR = CAN_TSR_RQCP0|CAN_TSR_RQCP1|CAN_TSR_RQCP2; break; case CAN_IT_FF0: /* Clear CAN_RF0R_FULL0 (rc_w1)*/ CANx->RF0R = CAN_RF0R_FULL0; break; case CAN_IT_FOV0: /* Clear CAN_RF0R_FOVR0 (rc_w1)*/ CANx->RF0R = CAN_RF0R_FOVR0; break; case CAN_IT_FF1: /* Clear CAN_RF1R_FULL1 (rc_w1)*/ CANx->RF1R = CAN_RF1R_FULL1; break; case CAN_IT_FOV1: /* Clear CAN_RF1R_FOVR1 (rc_w1)*/ CANx->RF1R = CAN_RF1R_FOVR1; break; case CAN_IT_WKU: /* Clear CAN_MSR_WKUI (rc_w1)*/ CANx->MSR = CAN_MSR_WKUI; break; case CAN_IT_SLK: /* Clear CAN_MSR_SLAKI (rc_w1)*/ CANx->MSR = CAN_MSR_SLAKI; break; case CAN_IT_EWG: /* Clear CAN_MSR_ERRI (rc_w1) */ CANx->MSR = CAN_MSR_ERRI; /* @note the corresponding Flag is cleared by hardware depending on the CAN Bus status*/ break; case CAN_IT_EPV: /* Clear CAN_MSR_ERRI (rc_w1) */ CANx->MSR = CAN_MSR_ERRI; /* @note the corresponding Flag is cleared by hardware depending on the CAN Bus status*/ break; case CAN_IT_BOF: /* Clear CAN_MSR_ERRI (rc_w1) */ CANx->MSR = CAN_MSR_ERRI; /* @note the corresponding Flag is cleared by hardware depending on the CAN Bus status*/ break; case CAN_IT_LEC: /* Clear LEC bits */ CANx->ESR = RESET; /* Clear CAN_MSR_ERRI (rc_w1) */ CANx->MSR = CAN_MSR_ERRI; break; case CAN_IT_ERR: /*Clear LEC bits */ CANx->ESR = RESET; /* Clear CAN_MSR_ERRI (rc_w1) */ CANx->MSR = CAN_MSR_ERRI; /* @note BOFF, EPVF and EWGF Flags are cleared by hardware depending on the CAN Bus status*/ break; default: break; } } /** * @} */ /** * @brief Checks whether the CAN interrupt has occurred or not. * @param CAN_Reg: specifies the CAN interrupt register to check. * @param It_Bit: specifies the interrupt source bit to check. * @retval The new state of the CAN Interrupt (SET or RESET). */ static ITStatus CheckITStatus(uint32_t CAN_Reg, uint32_t It_Bit) { ITStatus pendingbitstatus = RESET; if ((CAN_Reg & It_Bit) != (uint32_t)RESET) { /* CAN_IT is set */ pendingbitstatus = SET; } else { /* CAN_IT is reset */ pendingbitstatus = RESET; } return pendingbitstatus; } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
nobk/oh-my-keyboard
ref/hidapp/src/Libraries/STM32F4xx_StdPeriph_Driver/src/stm32f4xx_can.c
C
bsd-3-clause
60,113
/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <grpc/support/port_platform.h> #ifdef GRPC_STAP_PROFILER #include "src/core/profiling/timers.h" #include <sys/sdt.h> /* Generated from src/core/profiling/stap_probes.d */ #include "src/core/profiling/stap_probes.h" /* Latency profiler API implementation. */ void grpc_timer_add_mark(int tag, const char *tagstr, void *id, const char *file, int line) { _STAP_ADD_MARK(tag); } void grpc_timer_add_important_mark(int tag, const char *tagstr, void *id, const char *file, int line) { _STAP_ADD_IMPORTANT_MARK(tag); } void grpc_timer_begin(int tag, const char *tagstr, void *id, const char *file, int line) { _STAP_TIMING_NS_BEGIN(tag); } void grpc_timer_end(int tag, const char *tagstr, void *id, const char *file, int line) { _STAP_TIMING_NS_END(tag); } #endif /* GRPC_STAP_PROFILER */
ofrobots/grpc
src/core/profiling/stap_timers.c
C
bsd-3-clause
2,479
#ifndef FT_SOCK_STREAM_H_ #define FT_SOCK_STREAM_H_ struct ft_stream; extern const char * ft_stream_class; struct ft_stream_delegate { struct ft_frame * (*get_read_frame)(struct ft_stream *); // If NULL, then simple frame will be used bool (*read)(struct ft_stream *, struct ft_frame * frame); // True as a return value means, that the frame has been handed over to upstream protocol void (*connected)(struct ft_stream *); // Called when connect() is successfully finished; can be NULL void (*fini)(struct ft_stream *); void (*error)(struct ft_stream *); // Don't use this for close() or shutdown, it will be done automatically and it can lead to wierd results void (*frame_return)(struct ft_stream *, struct ft_frame * frame, char frame_type); // If set, called instead of ft_frame_return, frame_type is 'R' or 'W' }; struct ft_stream { union { struct ft_socket socket; } base; const struct ft_stream_delegate * delegate; struct { bool connecting : 1; bool active : 1; // Yes - we initiated connection using connect(), No - accept() bool read_partial : 1; // When yes, read() callback is triggered for any incoming data bool read_shutdown : 1; // Socket is read-wise connected bool read_paused_noframes : 1; // Read has been paused because there are no frames in the memory pool, this is indicative flag only, it is set by implementation, has to be clear be an user together with ft_stream_cntl(this, FT_STREAM_READ_RESUME) bool write_shutdown : 1; // Socket is write-wise connected bool write_open : 1; // Write queue is open for adding new frames bool write_ready : 1; // We can write to the socket (no need to wait for EV_WRITE) bool ssl_server : 1; // Yes - we are SSL server (SSL_accept will be used in accept), No - we are SSL client (SSL_connect will be used) bool ssl_hsconf: 1; // Yes - handshake direction has been configured (accept/connect) unsigned int ssl_status : 2; // 0 - disconnected; 1 - in handshake; 2 - established } flags; int read_pause_level; ev_tstamp created_at; ev_tstamp connected_at; ev_tstamp read_shutdown_at; ev_tstamp write_shutdown_at; struct { int sys_errno; unsigned long ssl_error; // ERR_peek_error() } error; // Input struct ev_io read_watcher; struct ft_frame * read_frame; unsigned int read_events; // Output struct ev_io write_watcher; struct ft_frame * write_frames; // Queue of write frames struct ft_frame ** write_frame_last; unsigned int write_events; // SSL SSL *ssl; // Statistics struct { unsigned int read_events; unsigned int write_events; unsigned int write_direct; //Writes without need of wait for EV_WRITE unsigned int write_queue_length; unsigned long read_bytes; unsigned long write_bytes; } stats; }; bool ft_stream_init(struct ft_stream *, const struct ft_stream_delegate * delegate, struct ft_context * context, int fd); bool ft_stream_accept(struct ft_stream *, const struct ft_stream_delegate * delegate, struct ft_listener * listening_socket, int fd, const struct sockaddr * peer_addr, socklen_t peer_addr_len); bool ft_stream_connect(struct ft_stream *, const struct ft_stream_delegate * delegate, struct ft_context * context, const struct addrinfo * addr); void ft_stream_fini(struct ft_stream *); bool ft_stream_write(struct ft_stream *, struct ft_frame * frame); bool ft_stream_enable_ssl(struct ft_stream *, SSL_CTX *ctx); void ft_stream_diagnose(struct ft_stream *); /// enum ft_stream_cntl_codes { FT_STREAM_READ_START = 0x0001, FT_STREAM_READ_STOP = 0x0002, FT_STREAM_READ_PAUSE = 0x0004, // Start read throttling FT_STREAM_READ_RESUME = 0x0008, // Stop read throttling FT_STREAM_WRITE_START = 0x0010, FT_STREAM_WRITE_STOP = 0x0020, FT_STREAM_WRITE_SHUTDOWN = 0x0040, // Submit write shutdown FT_STREAM_ABORT = 0x0080, // Immediatelly shutdown read and writea (aka reaction to non-recoverable error) }; static inline bool ft_stream_cntl(struct ft_stream * this, const int control_code) { assert(this != NULL); bool _ft_stream_cntl_read_start(struct ft_stream *); bool _ft_stream_cntl_read_stop(struct ft_stream *); bool _ft_stream_cntl_read_pause(struct ft_stream *, bool on); bool _ft_stream_cntl_write_start(struct ft_stream *); bool _ft_stream_cntl_write_stop(struct ft_stream *); bool _ft_stream_cntl_write_shutdown(struct ft_stream *); bool _ft_stream_cntl_abort(struct ft_stream *); bool ok = true; if ((control_code & FT_STREAM_READ_START) != 0) ok &= _ft_stream_cntl_read_start(this); if ((control_code & FT_STREAM_READ_STOP) != 0) ok &= _ft_stream_cntl_read_stop(this); if ((control_code & FT_STREAM_READ_PAUSE) != 0) ok &= _ft_stream_cntl_read_pause(this, true); if ((control_code & FT_STREAM_READ_RESUME) != 0) ok &= _ft_stream_cntl_read_pause(this, false); if ((control_code & FT_STREAM_WRITE_START) != 0) ok &= _ft_stream_cntl_write_start(this); if ((control_code & FT_STREAM_WRITE_STOP) != 0) ok &= _ft_stream_cntl_write_stop(this); if ((control_code & FT_STREAM_WRITE_SHUTDOWN) != 0) ok &= _ft_stream_cntl_write_shutdown(this); if ((control_code & FT_STREAM_ABORT) != 0) ok &= _ft_stream_cntl_abort(this); return ok; } /// static inline bool ft_stream_is_shutdown(struct ft_stream * this) { return ((this->flags.read_shutdown) && (this->flags.write_shutdown)); } static inline void ft_stream_set_partial(struct ft_stream * this, bool read_partial) { assert(this != NULL); this->flags.read_partial = read_partial; } /// static inline struct ft_stream * ft_stream_from_ssl(SSL * ssl) { return SSL_get_ex_data(ssl, ft_config.stream_ssl_ex_data_index); } // This function is to be used within SSL_CTX_set_verify() callback static inline struct ft_stream * ft_stream_from_x509_store_ctx(X509_STORE_CTX * ctx) { SSL * ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); assert(ssl != NULL); return ft_stream_from_ssl(ssl); } #endif // FT_SOCK_STREAM_H_
TeskaLabs/Frame_Transporter
include/ft/sock/stream.h
C
bsd-3-clause
5,974
/* * Copyright (c) 2015, Oracle America, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of "Oracle America, Inc." nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _TIRPC_SVC_AUTH_GSS_H #define _TIRPC_SVC_AUTH_GSS_H #include <rpc/svc_auth.h> #include <gssapi/gssapi.h> /* * Legacy U-M server GSS APIs */ #ifdef __cplusplus extern "C" { #endif extern bool_t svcauth_gss_set_svc_name(gss_name_t name); extern char *svcauth_gss_get_principal(SVCAUTH *); #ifdef __cplusplus } #endif #endif /* !_TIRPC_SVC_AUTH_GSS_H */
Distrotech/libtirpc
tirpc/rpc/svc_auth_gss.h
C
bsd-3-clause
1,945
#!/usr/bin/env python """ fs.tests: testcases for the fs module """ from __future__ import with_statement # Send any output from the logging module to stdout, so it will # be captured by nose and reported appropriately import sys import logging logging.basicConfig(level=logging.ERROR, stream=sys.stdout) from fs.base import * from fs.path import * from fs.errors import * from fs.filelike import StringIO import datetime import unittest import os import os.path import pickle import random import copy import time try: import threading except ImportError: import dummy_threading as threading import six from six import PY3, b class FSTestCases(object): """Base suite of testcases for filesystem implementations. Any FS subclass should be capable of passing all of these tests. To apply the tests to your own FS implementation, simply use FSTestCase as a mixin for your own unittest.TestCase subclass and have the setUp method set self.fs to an instance of your FS implementation. NB. The Filesystem being tested must have a capacity of at least 3MB. This class is designed as a mixin so that it's not detected by test loading tools such as nose. """ def check(self, p): """Check that a file exists within self.fs""" return self.fs.exists(p) def test_invalid_chars(self): """Check paths validate ok""" # Will have to be overriden selectively for custom validepath methods self.assertEqual(self.fs.validatepath(''), None) self.assertEqual(self.fs.validatepath('.foo'), None) self.assertEqual(self.fs.validatepath('foo'), None) self.assertEqual(self.fs.validatepath('foo/bar'), None) self.assert_(self.fs.isvalidpath('foo/bar')) def test_meta(self): """Checks getmeta / hasmeta are functioning""" # getmeta / hasmeta are hard to test, since there is no way to validate # the implementation's response meta_names = ["read_only", "network", "unicode_paths"] stupid_meta = 'thismetashouldnotexist!"r$$%^&&*()_+' self.assertRaises(NoMetaError, self.fs.getmeta, stupid_meta) self.assertFalse(self.fs.hasmeta(stupid_meta)) self.assertEquals(None, self.fs.getmeta(stupid_meta, None)) self.assertEquals(3.14, self.fs.getmeta(stupid_meta, 3.14)) for meta_name in meta_names: try: meta = self.fs.getmeta(meta_name) self.assertTrue(self.fs.hasmeta(meta_name)) except NoMetaError: self.assertFalse(self.fs.hasmeta(meta_name)) def test_root_dir(self): self.assertTrue(self.fs.isdir("")) self.assertTrue(self.fs.isdir("/")) # These may be false (e.g. empty dict) but mustn't raise errors self.fs.getinfo("") self.assertTrue(self.fs.getinfo("/") is not None) def test_getsyspath(self): try: syspath = self.fs.getsyspath("/") except NoSysPathError: pass else: self.assertTrue(isinstance(syspath, unicode)) syspath = self.fs.getsyspath("/", allow_none=True) if syspath is not None: self.assertTrue(isinstance(syspath, unicode)) def test_debug(self): str(self.fs) repr(self.fs) self.assert_(hasattr(self.fs, 'desc')) def test_open_on_directory(self): self.fs.makedir("testdir") try: f = self.fs.open("testdir") except ResourceInvalidError: pass except Exception: raise ecls = sys.exc_info()[0] assert False, "%s raised instead of ResourceInvalidError" % (ecls,) else: f.close() assert False, "ResourceInvalidError was not raised" def test_writefile(self): self.assertRaises(ResourceNotFoundError, self.fs.open, "test1.txt") f = self.fs.open("test1.txt", "wb") f.write(b("testing")) f.close() self.assertTrue(self.check("test1.txt")) f = self.fs.open("test1.txt", "rb") self.assertEquals(f.read(), b("testing")) f.close() f = self.fs.open("test1.txt", "wb") f.write(b("test file overwrite")) f.close() self.assertTrue(self.check("test1.txt")) f = self.fs.open("test1.txt", "rb") self.assertEquals(f.read(), b("test file overwrite")) f.close() def test_createfile(self): test = b('now with content') self.fs.createfile("test.txt") self.assert_(self.fs.exists("test.txt")) self.assertEqual(self.fs.getcontents("test.txt", "rb"), b('')) self.fs.setcontents("test.txt", test) self.fs.createfile("test.txt") self.assertEqual(self.fs.getcontents("test.txt", "rb"), test) self.fs.createfile("test.txt", wipe=True) self.assertEqual(self.fs.getcontents("test.txt", "rb"), b('')) def test_setcontents(self): # setcontents() should accept both a string... self.fs.setcontents("hello", b("world")) self.assertEquals(self.fs.getcontents("hello", "rb"), b("world")) # ...and a file-like object self.fs.setcontents("hello", StringIO(b("to you, good sir!"))) self.assertEquals(self.fs.getcontents( "hello", "rb"), b("to you, good sir!")) # setcontents() should accept both a string... self.fs.setcontents("hello", b("world"), chunk_size=2) self.assertEquals(self.fs.getcontents("hello", "rb"), b("world")) # ...and a file-like object self.fs.setcontents("hello", StringIO( b("to you, good sir!")), chunk_size=2) self.assertEquals(self.fs.getcontents( "hello", "rb"), b("to you, good sir!")) self.fs.setcontents("hello", b("")) self.assertEquals(self.fs.getcontents("hello", "rb"), b("")) def test_setcontents_async(self): # setcontents() should accept both a string... self.fs.setcontents_async("hello", b("world")).wait() self.assertEquals(self.fs.getcontents("hello", "rb"), b("world")) # ...and a file-like object self.fs.setcontents_async("hello", StringIO( b("to you, good sir!"))).wait() self.assertEquals(self.fs.getcontents("hello"), b("to you, good sir!")) self.fs.setcontents_async("hello", b("world"), chunk_size=2).wait() self.assertEquals(self.fs.getcontents("hello", "rb"), b("world")) # ...and a file-like object self.fs.setcontents_async("hello", StringIO( b("to you, good sir!")), chunk_size=2).wait() self.assertEquals(self.fs.getcontents( "hello", "rb"), b("to you, good sir!")) def test_isdir_isfile(self): self.assertFalse(self.fs.exists("dir1")) self.assertFalse(self.fs.isdir("dir1")) self.assertFalse(self.fs.isfile("a.txt")) self.fs.setcontents("a.txt", b('')) self.assertFalse(self.fs.isdir("dir1")) self.assertTrue(self.fs.exists("a.txt")) self.assertTrue(self.fs.isfile("a.txt")) self.assertFalse(self.fs.exists("a.txt/thatsnotadir")) self.fs.makedir("dir1") self.assertTrue(self.fs.isdir("dir1")) self.assertTrue(self.fs.exists("dir1")) self.assertTrue(self.fs.exists("a.txt")) self.fs.remove("a.txt") self.assertFalse(self.fs.exists("a.txt")) def test_listdir(self): def check_unicode(items): for item in items: self.assertTrue(isinstance(item, unicode)) self.fs.setcontents(u"a", b('')) self.fs.setcontents("b", b('')) self.fs.setcontents("foo", b('')) self.fs.setcontents("bar", b('')) # Test listing of the root directory d1 = self.fs.listdir() self.assertEqual(len(d1), 4) self.assertEqual(sorted(d1), [u"a", u"b", u"bar", u"foo"]) check_unicode(d1) d1 = self.fs.listdir("") self.assertEqual(len(d1), 4) self.assertEqual(sorted(d1), [u"a", u"b", u"bar", u"foo"]) check_unicode(d1) d1 = self.fs.listdir("/") self.assertEqual(len(d1), 4) check_unicode(d1) # Test listing absolute paths d2 = self.fs.listdir(absolute=True) self.assertEqual(len(d2), 4) self.assertEqual(sorted(d2), [u"/a", u"/b", u"/bar", u"/foo"]) check_unicode(d2) # Create some deeper subdirectories, to make sure their # contents are not inadvertantly included self.fs.makedir("p/1/2/3", recursive=True) self.fs.setcontents("p/1/2/3/a", b('')) self.fs.setcontents("p/1/2/3/b", b('')) self.fs.setcontents("p/1/2/3/foo", b('')) self.fs.setcontents("p/1/2/3/bar", b('')) self.fs.makedir("q") # Test listing just files, just dirs, and wildcards dirs_only = self.fs.listdir(dirs_only=True) files_only = self.fs.listdir(files_only=True) contains_a = self.fs.listdir(wildcard="*a*") self.assertEqual(sorted(dirs_only), [u"p", u"q"]) self.assertEqual(sorted(files_only), [u"a", u"b", u"bar", u"foo"]) self.assertEqual(sorted(contains_a), [u"a", u"bar"]) check_unicode(dirs_only) check_unicode(files_only) check_unicode(contains_a) # Test listing a subdirectory d3 = self.fs.listdir("p/1/2/3") self.assertEqual(len(d3), 4) self.assertEqual(sorted(d3), [u"a", u"b", u"bar", u"foo"]) check_unicode(d3) # Test listing a subdirectory with absoliute and full paths d4 = self.fs.listdir("p/1/2/3", absolute=True) self.assertEqual(len(d4), 4) self.assertEqual(sorted(d4), [u"/p/1/2/3/a", u"/p/1/2/3/b", u"/p/1/2/3/bar", u"/p/1/2/3/foo"]) check_unicode(d4) d4 = self.fs.listdir("p/1/2/3", full=True) self.assertEqual(len(d4), 4) self.assertEqual(sorted(d4), [u"p/1/2/3/a", u"p/1/2/3/b", u"p/1/2/3/bar", u"p/1/2/3/foo"]) check_unicode(d4) # Test that appropriate errors are raised self.assertRaises(ResourceNotFoundError, self.fs.listdir, "zebra") self.assertRaises(ResourceInvalidError, self.fs.listdir, "foo") def test_listdirinfo(self): def check_unicode(items): for (nm, info) in items: self.assertTrue(isinstance(nm, unicode)) def check_equal(items, target): names = [nm for (nm, info) in items] self.assertEqual(sorted(names), sorted(target)) self.fs.setcontents(u"a", b('')) self.fs.setcontents("b", b('')) self.fs.setcontents("foo", b('')) self.fs.setcontents("bar", b('')) # Test listing of the root directory d1 = self.fs.listdirinfo() self.assertEqual(len(d1), 4) check_equal(d1, [u"a", u"b", u"bar", u"foo"]) check_unicode(d1) d1 = self.fs.listdirinfo("") self.assertEqual(len(d1), 4) check_equal(d1, [u"a", u"b", u"bar", u"foo"]) check_unicode(d1) d1 = self.fs.listdirinfo("/") self.assertEqual(len(d1), 4) check_equal(d1, [u"a", u"b", u"bar", u"foo"]) check_unicode(d1) # Test listing absolute paths d2 = self.fs.listdirinfo(absolute=True) self.assertEqual(len(d2), 4) check_equal(d2, [u"/a", u"/b", u"/bar", u"/foo"]) check_unicode(d2) # Create some deeper subdirectories, to make sure their # contents are not inadvertantly included self.fs.makedir("p/1/2/3", recursive=True) self.fs.setcontents("p/1/2/3/a", b('')) self.fs.setcontents("p/1/2/3/b", b('')) self.fs.setcontents("p/1/2/3/foo", b('')) self.fs.setcontents("p/1/2/3/bar", b('')) self.fs.makedir("q") # Test listing just files, just dirs, and wildcards dirs_only = self.fs.listdirinfo(dirs_only=True) files_only = self.fs.listdirinfo(files_only=True) contains_a = self.fs.listdirinfo(wildcard="*a*") check_equal(dirs_only, [u"p", u"q"]) check_equal(files_only, [u"a", u"b", u"bar", u"foo"]) check_equal(contains_a, [u"a", u"bar"]) check_unicode(dirs_only) check_unicode(files_only) check_unicode(contains_a) # Test listing a subdirectory d3 = self.fs.listdirinfo("p/1/2/3") self.assertEqual(len(d3), 4) check_equal(d3, [u"a", u"b", u"bar", u"foo"]) check_unicode(d3) # Test listing a subdirectory with absoliute and full paths d4 = self.fs.listdirinfo("p/1/2/3", absolute=True) self.assertEqual(len(d4), 4) check_equal(d4, [u"/p/1/2/3/a", u"/p/1/2/3/b", u"/p/1/2/3/bar", u"/p/1/2/3/foo"]) check_unicode(d4) d4 = self.fs.listdirinfo("p/1/2/3", full=True) self.assertEqual(len(d4), 4) check_equal(d4, [u"p/1/2/3/a", u"p/1/2/3/b", u"p/1/2/3/bar", u"p/1/2/3/foo"]) check_unicode(d4) # Test that appropriate errors are raised self.assertRaises(ResourceNotFoundError, self.fs.listdirinfo, "zebra") self.assertRaises(ResourceInvalidError, self.fs.listdirinfo, "foo") def test_walk(self): self.fs.setcontents('a.txt', b('hello')) self.fs.setcontents('b.txt', b('world')) self.fs.makeopendir('foo').setcontents('c', b('123')) sorted_walk = sorted([(d, sorted(fs)) for (d, fs) in self.fs.walk()]) self.assertEquals(sorted_walk, [("/", ["a.txt", "b.txt"]), ("/foo", ["c"])]) # When searching breadth-first, shallow entries come first found_a = False for _, files in self.fs.walk(search="breadth"): if "a.txt" in files: found_a = True if "c" in files: break assert found_a, "breadth search order was wrong" # When searching depth-first, deep entries come first found_c = False for _, files in self.fs.walk(search="depth"): if "c" in files: found_c = True if "a.txt" in files: break assert found_c, "depth search order was wrong: " + \ str(list(self.fs.walk(search="depth"))) def test_walk_wildcard(self): self.fs.setcontents('a.txt', b('hello')) self.fs.setcontents('b.txt', b('world')) self.fs.makeopendir('foo').setcontents('c', b('123')) self.fs.makeopendir('.svn').setcontents('ignored', b('')) for dir_path, paths in self.fs.walk(wildcard='*.txt'): for path in paths: self.assert_(path.endswith('.txt')) for dir_path, paths in self.fs.walk(wildcard=lambda fn: fn.endswith('.txt')): for path in paths: self.assert_(path.endswith('.txt')) def test_walk_dir_wildcard(self): self.fs.setcontents('a.txt', b('hello')) self.fs.setcontents('b.txt', b('world')) self.fs.makeopendir('foo').setcontents('c', b('123')) self.fs.makeopendir('.svn').setcontents('ignored', b('')) for dir_path, paths in self.fs.walk(dir_wildcard=lambda fn: not fn.endswith('.svn')): for path in paths: self.assert_('.svn' not in path) def test_walkfiles(self): self.fs.makeopendir('bar').setcontents('a.txt', b('123')) self.fs.makeopendir('foo').setcontents('b', b('123')) self.assertEquals(sorted( self.fs.walkfiles()), ["/bar/a.txt", "/foo/b"]) self.assertEquals(sorted(self.fs.walkfiles( dir_wildcard="*foo*")), ["/foo/b"]) self.assertEquals(sorted(self.fs.walkfiles( wildcard="*.txt")), ["/bar/a.txt"]) def test_walkdirs(self): self.fs.makeopendir('bar').setcontents('a.txt', b('123')) self.fs.makeopendir('foo').makeopendir( "baz").setcontents('b', b('123')) self.assertEquals(sorted(self.fs.walkdirs()), [ "/", "/bar", "/foo", "/foo/baz"]) self.assertEquals(sorted(self.fs.walkdirs( wildcard="*foo*")), ["/", "/foo", "/foo/baz"]) def test_unicode(self): alpha = u"\N{GREEK SMALL LETTER ALPHA}" beta = u"\N{GREEK SMALL LETTER BETA}" self.fs.makedir(alpha) self.fs.setcontents(alpha + "/a", b('')) self.fs.setcontents(alpha + "/" + beta, b('')) self.assertTrue(self.check(alpha)) self.assertEquals(sorted(self.fs.listdir(alpha)), ["a", beta]) def test_makedir(self): check = self.check self.fs.makedir("a") self.assertTrue(check("a")) self.assertRaises( ParentDirectoryMissingError, self.fs.makedir, "a/b/c") self.fs.makedir("a/b/c", recursive=True) self.assert_(check("a/b/c")) self.fs.makedir("foo/bar/baz", recursive=True) self.assert_(check("foo/bar/baz")) self.fs.makedir("a/b/child") self.assert_(check("a/b/child")) self.assertRaises(DestinationExistsError, self.fs.makedir, "/a/b") self.fs.makedir("/a/b", allow_recreate=True) self.fs.setcontents("/a/file", b('')) self.assertRaises(ResourceInvalidError, self.fs.makedir, "a/file") def test_remove(self): self.fs.setcontents("a.txt", b('')) self.assertTrue(self.check("a.txt")) self.fs.remove("a.txt") self.assertFalse(self.check("a.txt")) self.assertRaises(ResourceNotFoundError, self.fs.remove, "a.txt") self.fs.makedir("dir1") self.assertRaises(ResourceInvalidError, self.fs.remove, "dir1") self.fs.setcontents("/dir1/a.txt", b('')) self.assertTrue(self.check("dir1/a.txt")) self.fs.remove("dir1/a.txt") self.assertFalse(self.check("/dir1/a.txt")) def test_removedir(self): check = self.check self.fs.makedir("a") self.assert_(check("a")) self.fs.removedir("a") self.assertRaises(ResourceNotFoundError, self.fs.removedir, "a") self.assert_(not check("a")) self.fs.makedir("a/b/c/d", recursive=True) self.assertRaises(DirectoryNotEmptyError, self.fs.removedir, "a/b") self.fs.removedir("a/b/c/d") self.assert_(not check("a/b/c/d")) self.fs.removedir("a/b/c") self.assert_(not check("a/b/c")) self.fs.removedir("a/b") self.assert_(not check("a/b")) # Test recursive removal of empty parent dirs self.fs.makedir("foo/bar/baz", recursive=True) self.fs.removedir("foo/bar/baz", recursive=True) self.assert_(not check("foo/bar/baz")) self.assert_(not check("foo/bar")) self.assert_(not check("foo")) self.fs.makedir("foo/bar/baz", recursive=True) self.fs.setcontents("foo/file.txt", b("please don't delete me")) self.fs.removedir("foo/bar/baz", recursive=True) self.assert_(not check("foo/bar/baz")) self.assert_(not check("foo/bar")) self.assert_(check("foo/file.txt")) # Ensure that force=True works as expected self.fs.makedir("frollic/waggle", recursive=True) self.fs.setcontents("frollic/waddle.txt", b("waddlewaddlewaddle")) self.assertRaises(DirectoryNotEmptyError, self.fs.removedir, "frollic") self.assertRaises( ResourceInvalidError, self.fs.removedir, "frollic/waddle.txt") self.fs.removedir("frollic", force=True) self.assert_(not check("frollic")) # Test removing unicode dirs kappa = u"\N{GREEK CAPITAL LETTER KAPPA}" self.fs.makedir(kappa) self.assert_(self.fs.isdir(kappa)) self.fs.removedir(kappa) self.assertRaises(ResourceNotFoundError, self.fs.removedir, kappa) self.assert_(not self.fs.isdir(kappa)) self.fs.makedir(pathjoin("test", kappa), recursive=True) self.assert_(check(pathjoin("test", kappa))) self.fs.removedir("test", force=True) self.assert_(not check("test")) def test_rename(self): check = self.check # test renaming a file in the same directory self.fs.setcontents("foo.txt", b("Hello, World!")) self.assert_(check("foo.txt")) self.fs.rename("foo.txt", "bar.txt") self.assert_(check("bar.txt")) self.assert_(not check("foo.txt")) # test renaming a directory in the same directory self.fs.makedir("dir_a") self.fs.setcontents("dir_a/test.txt", b("testerific")) self.assert_(check("dir_a")) self.fs.rename("dir_a", "dir_b") self.assert_(check("dir_b")) self.assert_(check("dir_b/test.txt")) self.assert_(not check("dir_a/test.txt")) self.assert_(not check("dir_a")) # test renaming a file into a different directory self.fs.makedir("dir_a") self.fs.rename("dir_b/test.txt", "dir_a/test.txt") self.assert_(not check("dir_b/test.txt")) self.assert_(check("dir_a/test.txt")) # test renaming a file into a non-existent directory self.assertRaises(ParentDirectoryMissingError, self.fs.rename, "dir_a/test.txt", "nonexistent/test.txt") def test_info(self): test_str = b("Hello, World!") self.fs.setcontents("info.txt", test_str) info = self.fs.getinfo("info.txt") self.assertEqual(info['size'], len(test_str)) self.fs.desc("info.txt") self.assertRaises(ResourceNotFoundError, self.fs.getinfo, "notafile") self.assertRaises( ResourceNotFoundError, self.fs.getinfo, "info.txt/inval") def test_infokeys(self): test_str = b("Hello, World!") self.fs.setcontents("info.txt", test_str) info = self.fs.getinfo("info.txt") for k, v in info.iteritems(): self.assertEqual(self.fs.getinfokeys('info.txt', k), {k: v}) test_info = {} if 'modified_time' in info: test_info['modified_time'] = info['modified_time'] if 'size' in info: test_info['size'] = info['size'] self.assertEqual(self.fs.getinfokeys('info.txt', 'size', 'modified_time'), test_info) self.assertEqual(self.fs.getinfokeys('info.txt', 'thiscantpossiblyexistininfo'), {}) def test_getsize(self): test_str = b("*") * 23 self.fs.setcontents("info.txt", test_str) size = self.fs.getsize("info.txt") self.assertEqual(size, len(test_str)) def test_movefile(self): check = self.check contents = b( "If the implementation is hard to explain, it's a bad idea.") def makefile(path): self.fs.setcontents(path, contents) def checkcontents(path): check_contents = self.fs.getcontents(path, "rb") self.assertEqual(check_contents, contents) return contents == check_contents self.fs.makedir("foo/bar", recursive=True) makefile("foo/bar/a.txt") self.assert_(check("foo/bar/a.txt")) self.assert_(checkcontents("foo/bar/a.txt")) self.fs.move("foo/bar/a.txt", "foo/b.txt") self.assert_(not check("foo/bar/a.txt")) self.assert_(check("foo/b.txt")) self.assert_(checkcontents("foo/b.txt")) self.fs.move("foo/b.txt", "c.txt") self.assert_(not check("foo/b.txt")) self.assert_(check("/c.txt")) self.assert_(checkcontents("/c.txt")) makefile("foo/bar/a.txt") self.assertRaises( DestinationExistsError, self.fs.move, "foo/bar/a.txt", "/c.txt") self.assert_(check("foo/bar/a.txt")) self.assert_(check("/c.txt")) self.fs.move("foo/bar/a.txt", "/c.txt", overwrite=True) self.assert_(not check("foo/bar/a.txt")) self.assert_(check("/c.txt")) def test_movedir(self): check = self.check contents = b( "If the implementation is hard to explain, it's a bad idea.") def makefile(path): self.fs.setcontents(path, contents) self.assertRaises(ResourceNotFoundError, self.fs.movedir, "a", "b") self.fs.makedir("a") self.fs.makedir("b") makefile("a/1.txt") makefile("a/2.txt") makefile("a/3.txt") self.fs.makedir("a/foo/bar", recursive=True) makefile("a/foo/bar/baz.txt") self.fs.movedir("a", "copy of a") self.assert_(self.fs.isdir("copy of a")) self.assert_(check("copy of a/1.txt")) self.assert_(check("copy of a/2.txt")) self.assert_(check("copy of a/3.txt")) self.assert_(check("copy of a/foo/bar/baz.txt")) self.assert_(not check("a/1.txt")) self.assert_(not check("a/2.txt")) self.assert_(not check("a/3.txt")) self.assert_(not check("a/foo/bar/baz.txt")) self.assert_(not check("a/foo/bar")) self.assert_(not check("a/foo")) self.assert_(not check("a")) self.fs.makedir("a") self.assertRaises( DestinationExistsError, self.fs.movedir, "copy of a", "a") self.fs.movedir("copy of a", "a", overwrite=True) self.assert_(not check("copy of a")) self.assert_(check("a/1.txt")) self.assert_(check("a/2.txt")) self.assert_(check("a/3.txt")) self.assert_(check("a/foo/bar/baz.txt")) def test_cant_copy_from_os(self): sys_executable = os.path.abspath(os.path.realpath(sys.executable)) self.assertRaises(FSError, self.fs.copy, sys_executable, "py.exe") def test_copyfile(self): check = self.check contents = b( "If the implementation is hard to explain, it's a bad idea.") def makefile(path, contents=contents): self.fs.setcontents(path, contents) def checkcontents(path, contents=contents): check_contents = self.fs.getcontents(path, "rb") self.assertEqual(check_contents, contents) return contents == check_contents self.fs.makedir("foo/bar", recursive=True) makefile("foo/bar/a.txt") self.assert_(check("foo/bar/a.txt")) self.assert_(checkcontents("foo/bar/a.txt")) # import rpdb2; rpdb2.start_embedded_debugger('password'); self.fs.copy("foo/bar/a.txt", "foo/b.txt") self.assert_(check("foo/bar/a.txt")) self.assert_(check("foo/b.txt")) self.assert_(checkcontents("foo/bar/a.txt")) self.assert_(checkcontents("foo/b.txt")) self.fs.copy("foo/b.txt", "c.txt") self.assert_(check("foo/b.txt")) self.assert_(check("/c.txt")) self.assert_(checkcontents("/c.txt")) makefile("foo/bar/a.txt", b("different contents")) self.assert_(checkcontents("foo/bar/a.txt", b("different contents"))) self.assertRaises( DestinationExistsError, self.fs.copy, "foo/bar/a.txt", "/c.txt") self.assert_(checkcontents("/c.txt")) self.fs.copy("foo/bar/a.txt", "/c.txt", overwrite=True) self.assert_(checkcontents("foo/bar/a.txt", b("different contents"))) self.assert_(checkcontents("/c.txt", b("different contents"))) def test_copydir(self): check = self.check contents = b( "If the implementation is hard to explain, it's a bad idea.") def makefile(path): self.fs.setcontents(path, contents) def checkcontents(path): check_contents = self.fs.getcontents(path) self.assertEqual(check_contents, contents) return contents == check_contents self.fs.makedir("a") self.fs.makedir("b") makefile("a/1.txt") makefile("a/2.txt") makefile("a/3.txt") self.fs.makedir("a/foo/bar", recursive=True) makefile("a/foo/bar/baz.txt") self.fs.copydir("a", "copy of a") self.assert_(check("copy of a/1.txt")) self.assert_(check("copy of a/2.txt")) self.assert_(check("copy of a/3.txt")) self.assert_(check("copy of a/foo/bar/baz.txt")) checkcontents("copy of a/1.txt") self.assert_(check("a/1.txt")) self.assert_(check("a/2.txt")) self.assert_(check("a/3.txt")) self.assert_(check("a/foo/bar/baz.txt")) checkcontents("a/1.txt") self.assertRaises(DestinationExistsError, self.fs.copydir, "a", "b") self.fs.copydir("a", "b", overwrite=True) self.assert_(check("b/1.txt")) self.assert_(check("b/2.txt")) self.assert_(check("b/3.txt")) self.assert_(check("b/foo/bar/baz.txt")) checkcontents("b/1.txt") def test_copydir_with_dotfile(self): check = self.check contents = b( "If the implementation is hard to explain, it's a bad idea.") def makefile(path): self.fs.setcontents(path, contents) self.fs.makedir("a") makefile("a/1.txt") makefile("a/2.txt") makefile("a/.hidden.txt") self.fs.copydir("a", "copy of a") self.assert_(check("copy of a/1.txt")) self.assert_(check("copy of a/2.txt")) self.assert_(check("copy of a/.hidden.txt")) self.assert_(check("a/1.txt")) self.assert_(check("a/2.txt")) self.assert_(check("a/.hidden.txt")) def test_readwriteappendseek(self): def checkcontents(path, check_contents): read_contents = self.fs.getcontents(path, "rb") self.assertEqual(read_contents, check_contents) return read_contents == check_contents test_strings = [b("Beautiful is better than ugly."), b("Explicit is better than implicit."), b("Simple is better than complex.")] all_strings = b("").join(test_strings) self.assertRaises(ResourceNotFoundError, self.fs.open, "a.txt", "r") self.assert_(not self.fs.exists("a.txt")) f1 = self.fs.open("a.txt", "wb") pos = 0 for s in test_strings: f1.write(s) pos += len(s) self.assertEqual(pos, f1.tell()) f1.close() self.assert_(self.fs.exists("a.txt")) self.assert_(checkcontents("a.txt", all_strings)) f2 = self.fs.open("b.txt", "wb") f2.write(test_strings[0]) f2.close() self.assert_(checkcontents("b.txt", test_strings[0])) f3 = self.fs.open("b.txt", "ab") # On win32, tell() gives zero until you actually write to the file # self.assertEquals(f3.tell(),len(test_strings[0])) f3.write(test_strings[1]) self.assertEquals(f3.tell(), len(test_strings[0])+len(test_strings[1])) f3.write(test_strings[2]) self.assertEquals(f3.tell(), len(all_strings)) f3.close() self.assert_(checkcontents("b.txt", all_strings)) f4 = self.fs.open("b.txt", "wb") f4.write(test_strings[2]) f4.close() self.assert_(checkcontents("b.txt", test_strings[2])) f5 = self.fs.open("c.txt", "wb") for s in test_strings: f5.write(s+b("\n")) f5.close() f6 = self.fs.open("c.txt", "rb") for s, t in zip(f6, test_strings): self.assertEqual(s, t+b("\n")) f6.close() f7 = self.fs.open("c.txt", "rb") f7.seek(13) word = f7.read(6) self.assertEqual(word, b("better")) f7.seek(1, os.SEEK_CUR) word = f7.read(4) self.assertEqual(word, b("than")) f7.seek(-9, os.SEEK_END) word = f7.read(7) self.assertEqual(word, b("complex")) f7.close() self.assertEqual(self.fs.getcontents("a.txt", "rb"), all_strings) def test_truncate(self): def checkcontents(path, check_contents): read_contents = self.fs.getcontents(path, "rb") self.assertEqual(read_contents, check_contents) return read_contents == check_contents self.fs.setcontents("hello", b("world")) checkcontents("hello", b("world")) self.fs.setcontents("hello", b("hi")) checkcontents("hello", b("hi")) self.fs.setcontents("hello", b("1234567890")) checkcontents("hello", b("1234567890")) with self.fs.open("hello", "rb+") as f: f.truncate(7) checkcontents("hello", b("1234567")) with self.fs.open("hello", "rb+") as f: f.seek(5) f.truncate() checkcontents("hello", b("12345")) def test_truncate_to_larger_size(self): with self.fs.open("hello", "wb") as f: f.truncate(30) self.assertEquals(self.fs.getsize("hello"), 30) # Some file systems (FTPFS) don't support both reading and writing if self.fs.getmeta('file.read_and_write', True): with self.fs.open("hello", "rb+") as f: f.seek(25) f.write(b("123456")) with self.fs.open("hello", "rb") as f: f.seek(25) self.assertEquals(f.read(), b("123456")) def test_write_past_end_of_file(self): if self.fs.getmeta('file.read_and_write', True): with self.fs.open("write_at_end", "wb") as f: f.seek(25) f.write(b("EOF")) with self.fs.open("write_at_end", "rb") as f: self.assertEquals(f.read(), b("\x00")*25 + b("EOF")) def test_with_statement(self): # This is a little tricky since 'with' is actually new syntax. # We use eval() to make this method safe for old python versions. import sys if sys.version_info[0] >= 2 and sys.version_info[1] >= 5: # A successful 'with' statement contents = "testing the with statement" code = "from __future__ import with_statement\n" code += "with self.fs.open('f.txt','wb-') as testfile:\n" code += " testfile.write(contents)\n" code += "self.assertEquals(self.fs.getcontents('f.txt', 'rb'),contents)" code = compile(code, "<string>", 'exec') eval(code) # A 'with' statement raising an error contents = "testing the with statement" code = "from __future__ import with_statement\n" code += "with self.fs.open('f.txt','wb-') as testfile:\n" code += " testfile.write(contents)\n" code += " raise ValueError\n" code = compile(code, "<string>", 'exec') self.assertRaises(ValueError, eval, code, globals(), locals()) self.assertEquals(self.fs.getcontents('f.txt', 'rb'), contents) def test_pickling(self): if self.fs.getmeta('pickle_contents', True): self.fs.setcontents("test1", b("hello world")) fs2 = pickle.loads(pickle.dumps(self.fs)) self.assert_(fs2.isfile("test1")) fs3 = pickle.loads(pickle.dumps(self.fs, -1)) self.assert_(fs3.isfile("test1")) else: # Just make sure it doesn't throw an exception fs2 = pickle.loads(pickle.dumps(self.fs)) def test_big_file(self): """Test handling of a big file (1MB)""" chunk_size = 1024 * 256 num_chunks = 4 def chunk_stream(): """Generate predictable-but-randomy binary content.""" r = random.Random(0) randint = r.randint int2byte = six.int2byte for _i in xrange(num_chunks): c = b("").join(int2byte(randint( 0, 255)) for _j in xrange(chunk_size//8)) yield c * 8 f = self.fs.open("bigfile", "wb") try: for chunk in chunk_stream(): f.write(chunk) finally: f.close() chunks = chunk_stream() f = self.fs.open("bigfile", "rb") try: try: while True: if chunks.next() != f.read(chunk_size): assert False, "bigfile was corrupted" except StopIteration: if f.read() != b(""): assert False, "bigfile was corrupted" finally: f.close() def test_settimes(self): def cmp_datetimes(d1, d2): """Test datetime objects are the same to within the timestamp accuracy""" dts1 = time.mktime(d1.timetuple()) dts2 = time.mktime(d2.timetuple()) return int(dts1) == int(dts2) d1 = datetime.datetime(2010, 6, 20, 11, 0, 9, 987699) d2 = datetime.datetime(2010, 7, 5, 11, 0, 9, 500000) self.fs.setcontents('/dates.txt', b('check dates')) # If the implementation supports settimes, check that the times # can be set and then retrieved try: self.fs.settimes('/dates.txt', d1, d2) except UnsupportedError: pass else: info = self.fs.getinfo('/dates.txt') self.assertTrue(cmp_datetimes(d1, info['accessed_time'])) self.assertTrue(cmp_datetimes(d2, info['modified_time'])) def test_removeroot(self): self.assertRaises(RemoveRootError, self.fs.removedir, "/") def test_zero_read(self): """Test read(0) returns empty string""" self.fs.setcontents('foo.txt', b('Hello, World')) with self.fs.open('foo.txt', 'rb') as f: self.assert_(len(f.read(0)) == 0) with self.fs.open('foo.txt', 'rt') as f: self.assert_(len(f.read(0)) == 0) # May be disabled - see end of file class ThreadingTestCases(object): """Testcases for thread-safety of FS implementations.""" # These are either too slow to be worth repeating, # or cannot possibly break cross-thread. _dont_retest = ("test_pickling", "test_multiple_overwrite",) __lock = threading.RLock() def _yield(self): # time.sleep(0.001) # Yields without a delay time.sleep(0) def _lock(self): self.__lock.acquire() def _unlock(self): self.__lock.release() def _makeThread(self, func, errors): def runThread(): try: func() except Exception: errors.append(sys.exc_info()) thread = threading.Thread(target=runThread) thread.daemon = True return thread def _runThreads(self, *funcs): check_interval = sys.getcheckinterval() sys.setcheckinterval(1) try: errors = [] threads = [self._makeThread(f, errors) for f in funcs] for t in threads: t.start() for t in threads: t.join() for (c, e, t) in errors: raise e, None, t finally: sys.setcheckinterval(check_interval) def test_setcontents_threaded(self): def setcontents(name, contents): f = self.fs.open(name, "wb") self._yield() try: f.write(contents) self._yield() finally: f.close() def thread1(): c = b("thread1 was 'ere") setcontents("thread1.txt", c) self.assertEquals(self.fs.getcontents("thread1.txt", 'rb'), c) def thread2(): c = b("thread2 was 'ere") setcontents("thread2.txt", c) self.assertEquals(self.fs.getcontents("thread2.txt", 'rb'), c) self._runThreads(thread1, thread2) def test_setcontents_threaded_samefile(self): def setcontents(name, contents): f = self.fs.open(name, "wb") self._yield() try: f.write(contents) self._yield() finally: f.close() def thread1(): c = b("thread1 was 'ere") setcontents("threads.txt", c) self._yield() self.assertEquals(self.fs.listdir("/"), ["threads.txt"]) def thread2(): c = b("thread2 was 'ere") setcontents("threads.txt", c) self._yield() self.assertEquals(self.fs.listdir("/"), ["threads.txt"]) def thread3(): c = b("thread3 was 'ere") setcontents("threads.txt", c) self._yield() self.assertEquals(self.fs.listdir("/"), ["threads.txt"]) try: self._runThreads(thread1, thread2, thread3) except ResourceLockedError: # that's ok, some implementations don't support concurrent writes pass def test_cases_in_separate_dirs(self): class TestCases_in_subdir(self.__class__, unittest.TestCase): """Run all testcases against a subdir of self.fs""" def __init__(this, subdir): super(TestCases_in_subdir, this).__init__("test_listdir") this.subdir = subdir for meth in dir(this): if not meth.startswith("test_"): continue if meth in self._dont_retest: continue if not hasattr(FSTestCases, meth): continue if self.fs.exists(subdir): self.fs.removedir(subdir, force=True) self.assertFalse(self.fs.isdir(subdir)) self.assertTrue(self.fs.isdir("/")) self.fs.makedir(subdir) self._yield() getattr(this, meth)() @property def fs(this): return self.fs.opendir(this.subdir) def check(this, p): return self.check(pathjoin(this.subdir, relpath(p))) def thread1(): TestCases_in_subdir("thread1") def thread2(): TestCases_in_subdir("thread2") def thread3(): TestCases_in_subdir("thread3") self._runThreads(thread1, thread2, thread3) def test_makedir_winner(self): errors = [] def makedir(): try: self.fs.makedir("testdir") except DestinationExistsError, e: errors.append(e) def makedir_noerror(): try: self.fs.makedir("testdir", allow_recreate=True) except DestinationExistsError, e: errors.append(e) def removedir(): try: self.fs.removedir("testdir") except (ResourceNotFoundError, ResourceLockedError), e: errors.append(e) # One thread should succeed, one should error self._runThreads(makedir, makedir) self.assertEquals(len(errors), 1) self.fs.removedir("testdir") # One thread should succeed, two should error errors = [] self._runThreads(makedir, makedir, makedir) if len(errors) != 2: raise AssertionError(errors) self.fs.removedir("testdir") # All threads should succeed errors = [] self._runThreads(makedir_noerror, makedir_noerror, makedir_noerror) self.assertEquals(len(errors), 0) self.assertTrue(self.fs.isdir("testdir")) self.fs.removedir("testdir") # makedir() can beat removedir() and vice-versa errors = [] self._runThreads(makedir, removedir) if self.fs.isdir("testdir"): self.assertEquals(len(errors), 1) self.assertFalse(isinstance(errors[0], DestinationExistsError)) self.fs.removedir("testdir") else: self.assertEquals(len(errors), 0) def test_concurrent_copydir(self): self.fs.makedir("a") self.fs.makedir("a/b") self.fs.setcontents("a/hello.txt", b("hello world")) self.fs.setcontents("a/guido.txt", b("is a space alien")) self.fs.setcontents("a/b/parrot.txt", b("pining for the fiords")) def copydir(): self._yield() self.fs.copydir("a", "copy of a") def copydir_overwrite(): self._yield() self.fs.copydir("a", "copy of a", overwrite=True) # This should error out since we're not overwriting self.assertRaises( DestinationExistsError, self._runThreads, copydir, copydir) self.assert_(self.fs.isdir('a')) self.assert_(self.fs.isdir('a')) copydir_overwrite() self.assert_(self.fs.isdir('a')) # This should run to completion and give a valid state, unless # files get locked when written to. try: self._runThreads(copydir_overwrite, copydir_overwrite) except ResourceLockedError: pass self.assertTrue(self.fs.isdir("copy of a")) self.assertTrue(self.fs.isdir("copy of a/b")) self.assertEqual(self.fs.getcontents( "copy of a/b/parrot.txt", 'rb'), b("pining for the fiords")) self.assertEqual(self.fs.getcontents( "copy of a/hello.txt", 'rb'), b("hello world")) self.assertEqual(self.fs.getcontents( "copy of a/guido.txt", 'rb'), b("is a space alien")) def test_multiple_overwrite(self): contents = [b("contents one"), b( "contents the second"), b("number three")] def thread1(): for i in xrange(30): for c in contents: self.fs.setcontents("thread1.txt", c) self.assertEquals(self.fs.getsize("thread1.txt"), len(c)) self.assertEquals(self.fs.getcontents( "thread1.txt", 'rb'), c) def thread2(): for i in xrange(30): for c in contents: self.fs.setcontents("thread2.txt", c) self.assertEquals(self.fs.getsize("thread2.txt"), len(c)) self.assertEquals(self.fs.getcontents( "thread2.txt", 'rb'), c) self._runThreads(thread1, thread2) # Uncomment to temporarily disable threading tests # class ThreadingTestCases(object): # _dont_retest = ()
duedil-ltd/pyfilesystem
fs/tests/__init__.py
Python
bsd-3-clause
46,382
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//RU"> <!-- Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007,2008,2009 Josh Coalson --> <!-- Permission is granted to copy, distribute and/or modify this document --> <!-- under the terms of the GNU Free Documentation License, Version 1.1 --> <!-- or any later version published by the Free Software Foundation; --> <!-- with no invariant sections. --> <!-- A copy of the license can be found at http://www.gnu.org/copyleft/fdl.html --> <HTML> <HEAD> <META CHARSET="windows-1251"> <META NAME="author" CONTENT="Josh Coalson"> <META NAME="description" CONTENT="An open source codec for lossless audio compression and decompression"> <META NAME="keywords" CONTENT="lossless,audio,codec,encoder,decoder,compression,compressor,archive,archiving,backup"> <TITLE>FLAC: íà÷àëî</TITLE> </HEAD> <BODY> <CENTER><TABLE cellpadding=0 cellspacing=0 border=0> <TR> <TD align=center>|</TD> <TD height=22 align=center nowrap> &nbsp;íà÷àëî&nbsp;</TD> <TD align=center>|</TD> <TD align=center nowrap> &nbsp;<A HREF="news.html">íîâîñòè</A>&nbsp;</TD> <TD align=center>|</TD> <TD align=center nowrap> &nbsp;<A HREF="download.html">ôàéëû</A>&nbsp;</TD> <TD align=center>|</TD> <TD align=center nowrap> &nbsp;<A HREF="features.html">õàðàêòåðèñòèêè</A>&nbsp;</TD> <TD align=center>|</TD> <TD align=center nowrap> &nbsp;<A HREF="goals.html">öåëè</A>&nbsp;</TD> <TD align=center>|</TD> <TD align=center nowrap> &nbsp;<A HREF="format.html">ôîðìàò</A>&nbsp;</TD> <TD align=center>|</TD></TR> <TR> <TD align=center>|</TD> <TD align=center nowrap> &nbsp;<A HREF="id.html">id</A>&nbsp;</TD> <TD align=center>|</TD> <TD align=center nowrap> &nbsp;<A HREF="comparison.html">ñðàâíåíèå</A>&nbsp;</TD> <TD align=center>|</TD> <TD align=center nowrap> &nbsp;<A HREF="developers.html">ðàçðàáîòêà</A>&nbsp;</TD> <TD align=center>|</TD> <TD align=center nowrap> &nbsp;<A HREF="documentation.html">äîêóìåíòàöèÿ</A>&nbsp;</TD> <TD align=center>|</TD> <TD align=center nowrap> &nbsp;<A HREF="links.html">ññûëêè</A>&nbsp;</TD> <TD align=center>|</TD> <TD align=center nowrap> &nbsp;<A HREF="authors.html">àâòîðû</A>&nbsp;</TD> <TD align=center>|</TD></TR> </TABLE></CENTER> <P><CENTER><TABLE cellpadding=0 cellspacing=0 border=0> <TR><TD align=center>|</TD> <TD height=22 align=center nowrap> &nbsp;<A HREF="../index.html">english</A>&nbsp;</TD> <TD align=center>|</TD> <TD align=center nowrap> &nbsp;ðóññêèé</A>&nbsp;</TD> <TD align=center>|</TD></TR> </TABLE></CENTER></P> <CENTER><H2>FLAC: íà÷àëî</H2></CENTER> <H3>Ñòàòóñ</H3> <P>26 ÿíâàðÿ 2003: <B>FLAC 1.1.0</B></P> <P>Âûøëà âåðñèÿ FLAC 1.1.0. Ñðåäè íîâûõ âîçìîæíîñòåé ïîääåðæêà ReplayGain è ñïèñêîâ ðàçìåòêè àóäèîäèñêîâ. Êðîìå òîãî óëó÷øåíî ñæàòèå 24-áèòíûõ ôàéëîâ è äîáàâëåíèà ïîääåðæêà ðåäàêòèðîâàíèÿ òåãîâ â ïëàãèíàõ. Ïîäðîáíåå îá ýòîì íà ñòðàíèöå <A HREF="news.html">íîâîñòåé</A>.</P> <P>Îáðàòèòå âíèìàíèå íà òî, ÷òî áûë óâåëè÷åí ìëàäøèé íîìåð âåðñèè, à çíà÷èò ñîâìåñòèìîñòü ñíèçó ââåðõ áûëà íàðóøåíà (ò.å. áîëåå ðàííèå âåðñèè äåêîäåðîâ íå ñìîãóò âîñïðîèçâîäèòü ôàéëû, ñîçäàííûå áîëåå ïîçäíèìè âåðñèÿìè êîäåðà). Ýòî ïðîèçîøëî èç-çà îøèáêè â äåêîäåðàõ â âåðñèÿõ äî 1.0.4 âêëþ÷èòåëüíî, èç-çà êîòîðîé äåêîäåðû íåïðàâèëüíî ïðîïóñêàëè íåèçâåñòíûå áëîêè ìåòàäàííûõ. Ïîòîêîâûé ôîðìàò íå èçìåíèëñÿ, ïîýòîìó îáðàòíàÿ ñîâìåñòèìîñòü íå íàðóøåíà. Ýòî çíà÷èò, ÷òî ôàéë FLAC ñî ñïèñêîì ðàçìåòêè àóäèîäèñêà íå áóäåò äåêîäèðîâàòüñÿ âåðñèÿìè äî 1.1.0, â êîòîðîé áûëà èñïðàâëåíà óïîìÿíóòàÿ âûøå îøèáêà.</P> <P>Åñëè âû èñïîëüçóåòå FLAC è ó âàñ åñòü ïðåäîëîæåíèÿ èëè ïàò÷è, ïîæàëóéñòà, ïðèñîäèíÿéòåñü ê <A HREF="http://sourceforge.net/mail/?group_id=13478">ñïèñêó ðàññûëêè</A> èëè <A HREF="http://sourceforge.net/project/memberlist.php?group_id=13478">ãðóïïå ðàçðàáîò÷èêîâ</A>. Ñîîáùèòü îá îøèáêå ìîæíî <A HREF="http://sourceforge.net/bugs/?func=addbug&group_id=13478">çäåñü</A>.</P> <H3>×òî òàêîå FLAC?</H3> <P>FLAC - ýòî àááðåâèàòóðà îò Free Lossless Audio Codec (ñâîáîäíûé àóäèîêîäåê, ñæèìàþùèé áåç ïîòåðü). Ïðîåêò FLAC âêëþ÷àåò:</P> <P><BLOCKQUOTE><UL> <LI>ïîòîêîâûé ôîðìàò;</LI> <LI>áàçîâûå êîäåðû è äåêîäåðû â âèäå áèáëèîòåê;</LI> <LI><B><TT>flac</TT></B>, óòèëèòó êîìàíäíîé ñòðîêè, âûïîëíÿþùóþ ñæàòèå è ðàñïàêîâêó ôàéëîâ .flac;</LI> <LI><B><TT>metaflac</TT></B>, óòèëèòó êîìàíäíîé ñòðîêè äëÿ ðåäàêòèðîâàíèÿ ìåòàäàííûõ â ôàéëàõ .flac;</LI> <LI>ïëàãèíû äëÿ ðàçíûõ ïëåéåðîâ.</LI> </UL></BLOCKQUOTE></P> <P>"Ñâîáîäà" îçíà÷àåò, ÷òî ñïåöèôèêàöèÿ ïîòîêîâîãî ôîðìàòà îòêðûòà äëÿ âñåõ è ìîæåò áûòü èñïîëüçîâàíà äëÿ ëþáûõ öåëåé (ïðîåêò FLAC îñòàâëÿåò çà ñîáîé ïðàâî óñòàíàâëèâàòü ñïåöèôèêàöèè è ñåðòèôèöèðîâàòü îòíîñÿùèåñÿ ê íåìó ïðîäóêòû íà ñîâìåñòèìîñòü), à òàêæå òî, ÷òî íè ôîðìàò, íè îäèí èç ðåàëèçîâàííûõ ìåòîäîâ êîäèðîâàíèÿ/äåêîäèðîâàíèÿ íå çàïàòåíòîâàíû. Ýòî òàêæå çíà÷èò, ÷òî âñå èñõîäíûå òåêñòû äîñòóïíû ïî ëèöåíçèÿì, îáÿçûâàþùèì ïðåäîñòàâëÿòü èñõîäíûå êîäû.</P> <P>FLAC êîìïèëèðóåòñÿ íà ìíîæåñòâå ïëàòôîðì: Unixes (Linux, *BSD, Solaris, OS X), Windows, BeOS è OS/2. Èìåþòñÿ ñèñòåìû ñáîðêè äëÿ autoconf/automake, MSVC, Watcom C è Project Builder.</P> <P>×òîáû óçíàòü áîëüøå î ïðîåêòå FLAC, ñìîòðèòå ñòðàíèöû <A HREF="features.html">õàðàêòåðèñòèêè</A>, <A HREF="documentation.html">äîêóìåíòàöèÿ</A> è <A HREF="format.html">ôîðìàò</A>. Òàêæå ïðèâåäåíî <A HREF="comparison.html">ñðàâíåíèå</A> êîäåðîâ, ñæèìàþùèõ áåç ïîòåðü, è ñïèñîê <A HREF="goals.html">öåëåé</A>, ñòîÿùèõ ïåðåä ó÷àñòíèêàìè ïðîåêòà.</P> <H3>Ôàéëû</H3> <P>Íà <A HREF="download.html">ýòîé</A> ñòðàíèöå íàõîäÿòñÿ ññûëêè íà èñõîäíûå òåêñòû, à òàêæå ñêîïèëèðîâàííûå âåðñèè äëÿ ðàçëè÷íûõ îïåðàöèîííûõ ñèñòåì, êðîìå òîãî èõ ìîæíî ïîëó÷èòü ïðÿìî íà <A HREF="http://www.sourceforge.net/projects/flac/">SourceForge</A>.</P> <H3>Äîêóìåíòàöèÿ</H3> <P>Äîêóìåíòàöèÿ äîñòóïíà â ðåæèìå îíëàéí è â äèñòðèáóòèâàõ. Èíôîðìàöèÿ ïî óñòàíîâêå è èñïîëüçîâàíèþ <B><TT>flac</TT></B> è ïëàãèíîâ íàõîäèòñÿ <A HREF="documentation.html">çäåñü</A>. Áîëåå äåòàëüíàÿ èíôîðìàöèÿ î ôîðìàòå FLAC è áàçîâîì êîäåðå ïðèâåäåíà íà <A HREF="format.html">ýòîé ñòðàíèöå</A>.</P> <H3>Ðåãèñòðàöèÿ id</H3> <P>Åñëè ó âàñ åñòü ïðèëîæåíèå, èñïîëüçóþùåå FLAC, è âû õîòèòå, ÷òîáû îíî ðàáîòàëî ñ äîáàâëÿåìûìè â ôàéë ìåòàäàííûìè, çàéäèòå íà <A HREF="id.html">ñòðàíèöó</A> ðåãèñòðàöèè è çàðåçåðâèðóéòå äëÿ íåãî èäåíòèôèêàòîð.</P> <P>&nbsp;Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007,2008,2009 Josh Coalson</P> </BODY> </HTML>
jeeb/flac
doc/html/ru/index.html
HTML
bsd-3-clause
6,342
<?php /* Template Name: Welcome */ ?> <?php get_header(); ?> <!-- welcome.php --> <div id="wrapper"> <div id="main_wrapper" class="clearfix"> <div id="page_wrapper"> <div id="content"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="post<?php echo commentpress_get_post_css_override( get_the_ID() ); ?>" id="post-<?php the_ID(); ?>"> <?php // default to hidden $cp_title_visibility = ' style="display: none;"'; // override if we've elected to show the title... if ( commentpress_get_post_title_visibility( get_the_ID() ) ) { $cp_title_visibility = ''; } ?> <h2 class="post_title"<?php echo $cp_title_visibility; ?>><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2> <?php // default to hidden $cp_meta_visibility = ' style="display: none;"'; // overrideif we've elected to show the meta... if ( commentpress_get_post_meta_visibility( get_the_ID() ) ) { $cp_meta_visibility = ''; } ?> <div class="search_meta"<?php echo $cp_meta_visibility; ?>> <?php commentpress_echo_post_meta(); ?> </div> <?php global $more; $more = true; the_content(''); ?> <?php // NOTE: Comment permalinks are filtered if the comment is not on the first page // in a multipage post... see: commentpress_multipage_comment_link in functions.php echo commentpress_multipager(); ?> </div><!-- /post --> <?php endwhile; else: ?> <div class="post"> <h2 class="post_title"><?php _e( 'Page Not Found', 'commentpress-core' ); ?></h2> <p><?php _e( "Sorry, but you are looking for something that isn't here.", 'commentpress-core' ); ?></p> <?php get_search_form(); ?> </div><!-- /post --> <?php endif; ?> </div><!-- /content --> </div><!-- /page_wrapper --> </div><!-- /main_wrapper --> </div><!-- /wrapper --> <?php get_sidebar(); ?> <?php get_footer(); ?>
wiratama/rama-yii2
wp/wp-content/plugins/commentpress-core/themes/commentpress-theme/welcome.php
PHP
bsd-3-clause
1,868
<?php /* * This file is part of the Ariadne Component Library. * * (c) Muze <info@muze.nl> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace arc\url; /** * Query parses any valid url query part and generates array accessible values for it * - you can use the same name multiple times -- ?name=value1&name=value2 * this will result in name becoming an array, similarly arrays will not be encoded with trailing [] behind the name * - you can use names without values -- ?name&name2&name3 * - names may include any valid character -- ?valid+name * */ class Query extends \ArrayObject implements QueryInterface { public function __construct($query = '') { parent::__construct( $this->parse( $query ), \ArrayObject::ARRAY_AS_PROPS ); } public function __toString() { return $this->compile( (array) $this ); } /** * Import a query string or an array of key => value pairs into the UrlQuery. * * Usage: * $query->import( 'foo=bar&bar=1' ); * $query->import( array( 'foo' => 'bar', 'bar' => 1 ) ); * * @param string|array $values query string or array of values to import into this query */ public function import($values) { $this->exchangeArray( $this->parse( $values ) + $this->getArrayCopy() ); return $this; } /** * Removes all current query parameters. * @return $this */ public function reset() { $this->exchangeArray( [] ); return $this; } // === \arc\KeyValueStoreInterface === /** * @param string $name name of the query parameter * @return mixed The named query parameter */ public function getvar($name) { return $this->offsetGet($name); } /** * @param string $name name for the query parameter * @param mixed $value value of the query parameter */ public function putvar($name, $value) { $this->offsetSet($name, $value); } protected function compile($values) { $result = array(); foreach ($values as $name => $value) { $result[] = $this->encodeValue( $name, $value ); } return implode( '&', $result ); } protected function parse($values) { $result = array(); if (is_array( $values ) || ( $values instanceof \Traversable )) { foreach ($values as $name => $value) { $result[$name] = $value; } } elseif (is_string( $values )) { $result = $this->parseQueryString( $values ); } return $result; } protected function parseQueryString($queryString) { $result = array(); if ($queryString) { $values = preg_split( '/[\&\;]/', $queryString ); foreach ($values as $queryStringEntry) { list( $name, $value ) = $this->parseQueryStringEntry( $queryStringEntry ); if (!isset($value)) { // no '=' in query entry e.g: ?name&... $result[] = $name; } elseif (!isset( $result[$name] )) { // a new entry e.g: ?name=1&... $result[ $name ] = $value; } elseif (!is_array( $result[$name] )) { // entry with same name exists already but is not an array yet => ?name=1&name=2&... $result[ $name ] = array( $result[$name], $value ); } else { // entry with same name exists and is an array => ?name=1&name=2&name=3&... $result[ $name ][] = $value; } } } return $result; } private function parseQueryStringEntry($queryStringEntry) { $result = explode( '=', $queryStringEntry, 2 ) + array( 1 => null ); // value may be null if no '=' is found in the query string foreach ($result as $key => $value) { if (isset($value)) { $value = urldecode( $value ); } $result[$key] = $value; } return $result; } private function encodeValue($name, $value = null) { if (is_array( $value )) { $result = array(); foreach ($value as $val) { $result[] = $this->encodeValue( $name, $val ); } return implode( '&', $result ); } else { return ( is_numeric( $name ) ? RawUrlEncode( $value ) : RawUrlEncode( $name ) . ( isset( $value ) ? '=' . RawUrlEncode( (string) $value ) : '' ) ); } } }
mjrider/arc-web
src/url/Query.php
PHP
bsd-3-clause
4,760
/* LibMemcached * Copyright (C) 2011-2012 Data Differential, http://datadifferential.com/ * Copyright (C) 2006-2009 Brian Aker * All rights reserved. * * Use and distribution licensed under the BSD license. See * the COPYING file in the parent directory for full text. * * Summary: * * Authors: * Brian Aker * Toru Maesaka */ #include <mem_config.h> #include <cstdio> #include <cstring> #include <ctime> #include <iostream> #include <fcntl.h> #include <getopt.h> #include <unistd.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/types.h> #include <libmemcached-1.2/memcached.h> #include "client_options.h" #include "utilities.h" #define PROGRAM_NAME "memstat" #define PROGRAM_DESCRIPTION "Output the state of a memcached cluster." /* Prototypes */ static void options_parse(int argc, char *argv[]); static void run_analyzer(memcached_st *memc, memcached_stat_st *memc_stat); static void print_analysis_report(memcached_st *memc, memcached_analysis_st *report); static bool opt_binary= false; static bool opt_verbose= false; static bool opt_server_version= false; static bool opt_analyze= false; static char *opt_servers= NULL; static char *stat_args= NULL; static char *analyze_mode= NULL; static char *opt_username; static char *opt_passwd; static struct option long_options[]= { {(OPTIONSTRING)"args", required_argument, NULL, OPT_STAT_ARGS}, {(OPTIONSTRING)"version", no_argument, NULL, OPT_VERSION}, {(OPTIONSTRING)"help", no_argument, NULL, OPT_HELP}, {(OPTIONSTRING)"quiet", no_argument, NULL, OPT_QUIET}, {(OPTIONSTRING)"verbose", no_argument, NULL, OPT_VERBOSE}, {(OPTIONSTRING)"binary", no_argument, NULL, OPT_BINARY}, {(OPTIONSTRING)"debug", no_argument, NULL, OPT_DEBUG}, {(OPTIONSTRING)"server-version", no_argument, NULL, OPT_SERVER_VERSION}, {(OPTIONSTRING)"servers", required_argument, NULL, OPT_SERVERS}, {(OPTIONSTRING)"analyze", optional_argument, NULL, OPT_ANALYZE}, {(OPTIONSTRING)"username", required_argument, NULL, OPT_USERNAME}, {(OPTIONSTRING)"password", required_argument, NULL, OPT_PASSWD}, {0, 0, 0, 0}, }; static memcached_return_t stat_printer(const memcached_instance_st * instance, const char *key, size_t key_length, const char *value, size_t value_length, void *context) { static const memcached_instance_st * last= NULL; (void)context; if (last != instance) { printf("Server: %s (%u)\n", memcached_server_name(instance), (uint32_t)memcached_server_port(instance)); last= instance; } printf("\t %.*s: %.*s\n", (int)key_length, key, (int)value_length, value); return MEMCACHED_SUCCESS; } static memcached_return_t server_print_callback(const memcached_st *, const memcached_instance_st * instance, void *) { std::cerr << memcached_server_name(instance) << ":" << memcached_server_port(instance) << " " << int(memcached_server_major_version(instance)) << "." << int(memcached_server_minor_version(instance)) << "." << int(memcached_server_micro_version(instance)) << std::endl; return MEMCACHED_SUCCESS; } int main(int argc, char *argv[]) { options_parse(argc, argv); initialize_sockets(); if (opt_servers == NULL) { char *temp; if ((temp= getenv("MEMCACHED_SERVERS"))) { opt_servers= strdup(temp); } if (opt_servers == NULL) { std::cerr << "No Servers provided" << std::endl; return EXIT_FAILURE; } } memcached_server_st* servers= memcached_servers_parse(opt_servers); if (servers == NULL or memcached_server_list_count(servers) == 0) { std::cerr << "Invalid server list provided:" << opt_servers << std::endl; return EXIT_FAILURE; } if (opt_servers) { free(opt_servers); } memcached_st *memc= memcached_create(NULL); memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, opt_binary); memcached_return_t rc= memcached_server_push(memc, servers); memcached_server_list_free(servers); if (opt_username and libmemcached_has_feature(LIBMEMCACHED_FEATURE_HAS_SASL) == false) { memcached_free(memc); std::cerr << "--username was supplied, but binary was not built with SASL support." << std::endl; return EXIT_FAILURE; } if (opt_username) { memcached_return_t ret; if (memcached_failed(ret= memcached_set_sasl_auth_data(memc, opt_username, opt_passwd))) { std::cerr << memcached_last_error_message(memc) << std::endl; memcached_free(memc); return EXIT_FAILURE; } } if (rc != MEMCACHED_SUCCESS and rc != MEMCACHED_SOME_ERRORS) { printf("Failure to communicate with servers (%s)\n", memcached_strerror(memc, rc)); exit(EXIT_FAILURE); } if (opt_server_version) { if (memcached_failed(memcached_version(memc))) { std::cerr << "Unable to obtain server version"; exit(EXIT_FAILURE); } memcached_server_fn callbacks[1]; callbacks[0]= server_print_callback; memcached_server_cursor(memc, callbacks, NULL, 1); } else if (opt_analyze) { memcached_stat_st *memc_stat= memcached_stat(memc, NULL, &rc); if (memc_stat == NULL) { exit(EXIT_FAILURE); } run_analyzer(memc, memc_stat); memcached_stat_free(memc, memc_stat); } else { rc= memcached_stat_execute(memc, stat_args, stat_printer, NULL); } memcached_free(memc); return rc == MEMCACHED_SUCCESS ? EXIT_SUCCESS: EXIT_FAILURE; } static void run_analyzer(memcached_st *memc, memcached_stat_st *memc_stat) { memcached_return_t rc; if (analyze_mode == NULL) { memcached_analysis_st *report; report= memcached_analyze(memc, memc_stat, &rc); if (rc != MEMCACHED_SUCCESS || report == NULL) { printf("Failure to analyze servers (%s)\n", memcached_strerror(memc, rc)); exit(1); } print_analysis_report(memc, report); free(report); } else if (strcmp(analyze_mode, "latency") == 0) { uint32_t flags, server_count= memcached_server_count(memc); uint32_t num_of_tests= 32; const char *test_key= "libmemcached_test_key"; memcached_st **servers= static_cast<memcached_st**>(malloc(sizeof(memcached_st*) * server_count)); if (servers == NULL) { fprintf(stderr, "Failed to allocate memory\n"); return; } for (uint32_t x= 0; x < server_count; x++) { const memcached_instance_st * instance= memcached_server_instance_by_position(memc, x); if ((servers[x]= memcached_create(NULL)) == NULL) { fprintf(stderr, "Failed to memcached_create()\n"); if (x > 0) { memcached_free(servers[0]); } x--; for (; x > 0; x--) { memcached_free(servers[x]); } free(servers); return; } memcached_server_add(servers[x], memcached_server_name(instance), memcached_server_port(instance)); } printf("Network Latency Test:\n\n"); struct timeval start_time, end_time; uint32_t slowest_server= 0; long elapsed_time, slowest_time= 0; for (uint32_t x= 0; x < server_count; x++) { const memcached_instance_st * instance= memcached_server_instance_by_position(memc, x); gettimeofday(&start_time, NULL); for (uint32_t y= 0; y < num_of_tests; y++) { size_t vlen; char *val= memcached_get(servers[x], test_key, strlen(test_key), &vlen, &flags, &rc); if (rc != MEMCACHED_NOTFOUND and rc != MEMCACHED_SUCCESS) { break; } free(val); } gettimeofday(&end_time, NULL); elapsed_time= (long) timedif(end_time, start_time); elapsed_time /= (long) num_of_tests; if (elapsed_time > slowest_time) { slowest_server= x; slowest_time= elapsed_time; } if (rc != MEMCACHED_NOTFOUND && rc != MEMCACHED_SUCCESS) { printf("\t %s (%d) => failed to reach the server\n", memcached_server_name(instance), memcached_server_port(instance)); } else { printf("\t %s (%d) => %ld.%ld seconds\n", memcached_server_name(instance), memcached_server_port(instance), elapsed_time / 1000, elapsed_time % 1000); } } if (server_count > 1 && slowest_time > 0) { const memcached_instance_st * slowest= memcached_server_instance_by_position(memc, slowest_server); printf("---\n"); printf("Slowest Server: %s (%d) => %ld.%ld seconds\n", memcached_server_name(slowest), memcached_server_port(slowest), slowest_time / 1000, slowest_time % 1000); } printf("\n"); for (uint32_t x= 0; x < server_count; x++) { memcached_free(servers[x]); } free(servers); free(analyze_mode); } else { fprintf(stderr, "Invalid Analyzer Option provided\n"); free(analyze_mode); } } static void print_analysis_report(memcached_st *memc, memcached_analysis_st *report) { uint32_t server_count= memcached_server_count(memc); const memcached_instance_st * most_consumed_server= memcached_server_instance_by_position(memc, report->most_consumed_server); const memcached_instance_st * least_free_server= memcached_server_instance_by_position(memc, report->least_free_server); const memcached_instance_st * oldest_server= memcached_server_instance_by_position(memc, report->oldest_server); printf("Memcached Cluster Analysis Report\n\n"); printf("\tNumber of Servers Analyzed : %u\n", server_count); printf("\tAverage Item Size (incl/overhead) : %u bytes\n", report->average_item_size); if (server_count == 1) { printf("\nFor a detailed report, you must supply multiple servers.\n"); return; } printf("\n"); printf("\tNode with most memory consumption : %s:%u (%llu bytes)\n", memcached_server_name(most_consumed_server), (uint32_t)memcached_server_port(most_consumed_server), (unsigned long long)report->most_used_bytes); printf("\tNode with least free space : %s:%u (%llu bytes remaining)\n", memcached_server_name(least_free_server), (uint32_t)memcached_server_port(least_free_server), (unsigned long long)report->least_remaining_bytes); printf("\tNode with longest uptime : %s:%u (%us)\n", memcached_server_name(oldest_server), (uint32_t)memcached_server_port(oldest_server), report->longest_uptime); printf("\tPool-wide Hit Ratio : %1.f%%\n", report->pool_hit_ratio); printf("\n"); } static void options_parse(int argc, char *argv[]) { memcached_programs_help_st help_options[]= { {0}, }; int option_index= 0; bool opt_version= false; bool opt_help= false; while (1) { int option_rv= getopt_long(argc, argv, "Vhvds:a", long_options, &option_index); if (option_rv == -1) break; switch (option_rv) { case 0: break; case OPT_VERBOSE: /* --verbose or -v */ opt_verbose= true; break; case OPT_DEBUG: /* --debug or -d */ opt_verbose= true; break; case OPT_BINARY: opt_binary= true; break; case OPT_SERVER_VERSION: opt_server_version= true; break; case OPT_VERSION: /* --version or -V */ opt_version= true; break; case OPT_HELP: /* --help or -h */ opt_help= true; break; case OPT_SERVERS: /* --servers or -s */ opt_servers= strdup(optarg); break; case OPT_STAT_ARGS: stat_args= strdup(optarg); break; case OPT_ANALYZE: /* --analyze or -a */ opt_analyze= OPT_ANALYZE; analyze_mode= (optarg) ? strdup(optarg) : NULL; break; case OPT_QUIET: close_stdio(); break; case OPT_USERNAME: opt_username= optarg; opt_binary= true; break; case OPT_PASSWD: opt_passwd= optarg; break; case '?': /* getopt_long already printed an error message. */ exit(1); default: abort(); } } if (opt_version) { version_command(PROGRAM_NAME); exit(EXIT_SUCCESS); } if (opt_help) { help_command(PROGRAM_NAME, PROGRAM_DESCRIPTION, long_options, help_options); exit(EXIT_SUCCESS); } }
zzak/libmemcached
clients/memstat.cc
C++
bsd-3-clause
12,766
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>YUIDoc Syntax Reference</title> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Maven+Pro:400,700"> <link rel="stylesheet" href="http://yui.yahooapis.com/3.4.1/build/cssgrids/grids-min.css"> <link rel="stylesheet" href="../assets/css/main.css"> <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css"> <link rel="shortcut icon" type="image/png" href="../assets/favicon.png"> <script src="http://yui.yahooapis.com/3.5.1/build/yui/yui.js"></script> </head> <body> <a href="https://github.com/yui/yuidoc"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"></a> <div id="doc"> <div id="hd"> <h1><img src="http://yuilibrary.com/img/yui-logo.png">YUIDoc Syntax Reference</h1> </div> <div class="crumbs"> <a href="../">Main Page</a> <a name="Arrow">&gt;</a> <a href="../syntax/index.html">YUIDoc Syntax Reference</a> </div> <a href="#toc" class="jump">Jump to Table of Contents</a> <div class="yui3-g"> <div class="yui3-u-3-4"> <div id="main"> <div class="content"><div class="intro"> <p>YUIDoc's syntax should be familiar if you've used Javadoc, JSDoc, Doxygen, or most other documentation generator tools. YUIDoc relies on <dfn>tags</dfn> such as <code>@param</code> or <code>@return</code> embedded in comments blocks that start with <code>&#x2F;**</code> and end with <code>*&#x2F;</code>. It includes a small number of tags for documenting specific YUI features, but most tags are generic enough to use with any object-oriented language.</p> <p><b>IMPORTANT:</b> YUIDoc only parses YUIDoc comment blocks, not source code. This keeps YUIDoc relatively simple and language agnostic. However, it also means you must declare everything to YUIDoc explicitly. A code snippet will not display as a "method" or "class" until you describe it as such. A corollary is that YUIDoc will never generate empty, "stub" doc entries for API members that lack comment blocks.</p> </div> <h2 id="basic-requirements">Basic Requirements</h2> <p>A given comment block must contain one (and only one) <a href="#primary-tags">primary tag</a> such as <code>@class</code> or <code>@method</code>, and zero or more <a href="#secondary-tag">secondary tags</a> such as <code>@param</code>, <code>@type</code>, and <code>@extends</code>. Some secondary tags can be used in any comment block, while others only make sense alongside a particular primary tag.</p> <p>A source tree must contain at least one comment block with a <code>@module</code> tag.</p> <p>Each module must have at least one comment block with a <code>@class</code> tag.</p> <p>Each class may then have zero or more comment blocks with an <code>attribute</code>, <code>@class</code>, <code>@event</code>, <code>@method</code>, or <code>@property</code> tag.</p> <h2 id="primary-tags">Primary Tags</h2> <p>Each comment block must have one (and only one) of the following tags</p> <table> <tr> <th>Name</th> <th>Example</th> <th>Description</th> </tr> <tr id="module"> <td><code>module</code></td> <td> <pre class="code prettyprint">&#x2F;** Provides the base Widget class... @module widget **&#x2F;</pre> </td> <td> <p>Indicates that the block describes a group of related classes. For example, YUI's <code>app</code> module includes classes such as <code>App.Base</code>, <code>Model</code>, and <code>Router</code>. You can optionally break modules up into submodules. <p>YUIDoc requires you to provide at least one module per source tree. Since there isn't always an obvious place to insert module documentation in JavaScript source, the convention is to declare your module at the top of the file that contains your module's "primary" or "base" class.</p> <p> See also: <a href="#class"><code>@class</code></a>, <a href="#for"><code>@for</code></a>, <a href="#maintag"><code>@main</code></a>, <a href="#submodule"><code>@submodule</code></a>. </p> </td> </tr> <tr id="maintag"> <td><code>main</code></td> <td> <pre class="code prettyprint">&#x2F;** Provides more functionality for the widget module.. @module widget @submodule widget-foo @main widget **&#x2F;</pre> </td> <td> <p> When YUIDoc parses a module's directory, there may be several files in this directory that provides documentation for that module and it's submodules. YUIDoc will attempt to determine which module contains the main description for this module. If it has trouble doing that you can add a <code>@main</code> tag to your module/submodule description and YUIDoc will use that as the main module description on the modules API landing page. </p> </td> </tr> <tr id="class"> <td><code>class</code></td> <td> <pre class="code prettyprint">&#x2F;** A utility that brokers HTTP requests... @class IO @constructor **&#x2F; function IO (config) {</pre> </td> <td> <p>Indicates that the block describes a class. In JavaScript, this is generally an object with a constructor function. The value of <code>@class</code> should be the string that identifies the functional class on its parent object. For example, the <code>@class</code> for <code>Y.DD.Drag</code> would be <code>Drag</code> (and its <a href="#@namespace"><code>@namespace</code></a> would be <code>DD</code>).</p> <p>YUIDoc expects methods, properties, attributes, and events to belong to a class, so in general you must provide at least one class for each module in your source tree. A <code>@class</code> block should reside just above the class's constructor function, and above all methods, events, properties, and attributes that belong to the class.</p> <p>A <a href="#class"><code>@class</code></a> tag should be paired with either a <code>@constructor</code> tag or a <code>@static</code> tag.</p> <p> See also: <a href="#constructor"><code>@constructor</code></a>, <a href="#extends"><code>@extends</code></a>, <a href="#extensionfor"><code>@extensionfor</code></a>, <a href="#for"><code>@for</code></a>, <a href="#module"><code>@module</code></a>, <a href="#namespace"><code>@namespace</code></a>, <a href="#static"><code>@static</code></a>, <a href="#uses"><code>@uses</code></a>. </p> </td> </td> </tr> <tr id="method"> <td><code>method</code></td> <td> <pre class="code prettyprint">&#x2F;** Returns this model&#x27;s attributes as... @method toJSON @return {Object} Copy of ... **&#x2F; toJSON: function () {</pre> </td> <td> <p>Indicates that the block describes a method for the current class. By default, the "current" class is the last class that YUIDoc parsed, but you can reset this with the <a href="#for"><code>@for</code></a> tag.</p> <p>A <code>@method</code> block should always reside directly above the method's definition. At a minimum, you should also document any parameters (<a href="#param"><code>@param</code></a>) and return values (<a href="#return"><code>@return</code></a>).</p> <p> See also: <a href="#chainable"><code>@chainable</code></a>, <a href="#class"><code>@class</code></a>, <a href="#constructor"><code>@constructor</code></a>, <a href="#for"><code>@for</code></a>, <a href="#param"><code>@param</code></a>, <a href="#return"><code>@return</code></a>, <a href="#static"><code>@static</code></a>. </p> </td> </td> </tr> <tr id="event"> <td><code>event</code></td> <td> <pre class="code prettyprint">&#x2F;** Fired when an error occurs... @event error @param {String} msg A description of... **&#x2F; var EVT_ERROR = &#x27;error&#x27;,</pre> </td> <td> <p>Indicates that the block describes a custom event that the class can fire at some interesting moment of code execution. An <code>@event</code> block is somewhat similar to a <a href="#param"><code>@method</code></a> block, except that <a href="#return"><code>@return</code></a> is irrelevant, and <a href="#param"><code>@param</code></a> is used to describe properties hanging off the event object that callbacks listening for the event receive. </p> <p>Ideally, an <code>@event</code> block should reside above the code that defines the event, even if that code is just a simple string declaration. If you find that your <code>@event</code> block is "floating in space," you should at least place it underneath the class that owns the event, grouped with any other events that the class can fire.</p> <p> See also: <a href="#bubbles"><code>@bubbles</code></a>, <a href="#class"><code>@class</code></a>, <a href="#for"><code>@for</code></a>, <a href="#param"><code>@param</code></a>. </p> </td> </tr> <tr id="property"> <td><code>property</code></td> <td> <pre class="code prettyprint">&#x2F;** Template for this view&#x27;s container... @property containerTemplate @type String @default &quot;&lt;div&#x2F;&gt;&quot; **&#x2F; containerTemplate: &#x27;&lt;div&#x2F;&gt;&#x27;,</pre> </td> <td> <p>Indicates that the block describes a property belonging to the current class.</p> <p>As with methods, a <code>@property</code> block should always reside directly above the point where the property is defined. At a minimum, you should also provide the property's <code>@type</code>, even if the value is <code>&quot;any&quot;</code> or <code>&quot;mixed&quot;</code>.</p> <p> See also: <a href="#attribute"><code>@attribute</code></a>, <a href="#default"><code>@default</code></a>, <a href="#class"><code>@class</code></a>, <a href="#for"><code>@for</code></a>, <a href="#type"><code>@type</code></a>. </p> </td> </tr> <tr id="attribute"> <td><code>attribute</code></td> <td> <pre class="code prettyprint">&#x2F;** * Indicates whether this Widget * has been rendered... * * @attribute rendered * @readOnly * @default false * @type boolean *&#x2F; ATTRS[RENDERED] = {</pre> </td> <td> <p>[YUI-specific] Indicates that the block describes a managed configuration attribute. An attribute is an object created and managed by the YUI <a href="http://yuilibrary.com/yui/docs/api/classes/Attribute.html"><code>Attribute</code> API</a>. It is a kind of "super-property", with getters, setters, and other nifty features, including the ability to automatically fire change events.</p> <p>An <code>@attribute</code> block should reside directly above the definition of the attribute, whether that is inside a <code>Y.Base</code> object's <code>ATTRS</code> property or elsewhere. Note that if your <code>yuidoc.json</code> file sets <code>attributesEmit</code> to <code>true</code>, YUI will automatically generate documentation for the attribute's change events throughout the source tree, with no extra YUIDoc comments needed from you.</p> <p> See also: <a href="#property"><code>@property</code></a>, <a href="#default"><code>@default</code></a>, <a href="#class"><code>@class</code></a>, <a href="#for"><code>@for</code></a>, <a href="#type"><code>@type</code></a>, <a href="#required"><code>@required</code></a>, <a href="#optional"><code>@optional</code></a>. </p> </td> </tr> </table> <h2 id="secondary-tags">Secondary tags</h2> <p> After choosing one of the five primary tags, you can further document a module, class, method, event or property with one or more of the following secondary tags. </p> <table> <tr> <th>Name</th> <th>Example</th> <th>Description</th> </tr> <tr id="submodule"> <td><code>submodule</code></td> <td> <pre class="code prettyprint">&#x2F;** @module app @submodule view **&#x2F;</pre> </td> <td> <p>Specifies that the module is actually a submodule of some parent module. For example, the <code>app-transitions</code> module is a submodule of the larger <code>app</code> module.</p> <p>In YUI, submodules enable you to make very fine-grained choices about loading code. For example, the <code>foo</code> module might have a minimal <code>foo-core</code> or <code>foo-base</code> submodule that supplies <code>foo</code>'s basic functionality, plus additional <code>foo-*</code> modules that carry optional features. Using the YUI Loader, you can choose to load just <code>foo-core</code>, <code>foo-core</code> plus a couple of extra modules, or the entire <code>foo</code> "rollup".</p> <p> See also: <a href="#module"><code>@module</code></a>. </p> </td> </tr> <tr id="namespace"> <td><code>namespace</code></td> <td> <pre class="code prettyprint">&#x2F;** @namespace Test.Mock **&#x2F;</pre> </td> <td> <p>Specifies a class's namespace. The <code>@namespace</code> should <em>not</em> include the "root" or "global" object that your entire library hangs off of. For example, <code>Y.DD.Drag</code> has a <a href="#class"><code>@class</code></a> of <code>Drag</code> and a <code>@namespace</code> of <code>DD</code>, not <code>Y.DD</code>.</p> <p>Supplying a <code>@namespace</code> enables you to refer to the class in YUIDoc using just the simple class name.</p> <p> See also: <a href="#class"><code>@class</code></a>. </p> </td> </tr> <tr id="extends"> <td><code>extends</code></td> <td> <pre class="code prettyprint">&#x2F;** @class View @constructor @extends Base **&#x2F;</pre> </td> <td> <p>Specifies that the class inherits members from a parent class, perhaps using <a href="http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_extend"><code>Y.extend()</code></a>, <a href="http://yuilibrary.com/yui/docs/api/classes/Base.html#method_create"><code>Y.Base.create()</code></a>, or similar methods. YUIDoc will generate API documentation for methods, properties, events, and attributes inherited from the parent class, and link back to the parent class's documentation. In the default YUIDoc theme, users can toggle whether inherited members should display.</p> <p> See also: <a href="#class"><code>@class</code></a>, <a href="#extensionfor"><code>@extensionfor</code></a>, <a href="#uses"><code>@uses</code></a>. </p> </td> </tr> <tr id="config"> <td><code>config</code></td> <td> <pre class="code prettyprint">&#x2F;** @config docScrollX @type Number **&#x2F;</pre> </td> <td> <p>[YUI-specific] Alias for <a href="#attribute"><code>@attribute</code></a>. In older versions of YUI, <code>@config</code> was a slightly different take on attributes, but the two concepts have merged. Modern YUIDoc comments should use <code>@attribute</code> instead.</p> </td> </tr> <tr id="constructor"> <td><code>constructor</code></td> <td> <pre class="code prettyprint">&#x2F;** @class IO @constructor **&#x2F;</pre> </td> <td> <p>Indicates that the class is instantiable (you can use it by calling <code>var foo = new Foo();</code>). A <a href="#class"><code>@class</code></a> tag should be paired with either a <code>@constructor</code> tag or a <code>@static</code> tag.</p> <p> See also: <a href="#class"><code>@class</code></a>, <a href="#static"><code>@static</code></a>. </p> </td> </tr> <tr id="static"> <td><code>static</code></td> <td> <pre class="code prettyprint">&#x2F;** YUI user agent detection... @class UA @static **&#x2F;</pre> </td> <td> <p>Indicates that the method or class is static:</p> <ul> <li>For methods, indicates that the method is meant to be called without instantiating the class: <code>var node = Y.Node.create(&#x27;&lt;div&#x2F;&gt;&#x27;);</code></li> <li>For classes, indicates that you should not instantiate the class with <code>new</code>. You can call all of the class's methods statically. </ul> <p>A <a href="#class"><code>@class</code></a> tag should be paired with either a <code>@constructor</code> tag or a <code>@static</code> tag.</p> <p> See also: <a href="#class"><code>@class</code></a>, <a href="#constructor"><code>@constructor</code></a>, <a href="#method"><code>@method</code></a>. </p> </td> </tr> </tr> <tr id="final"> <td><code>final</code></td> <td> <pre class="code prettyprint">&#x2F;** Identifies state changes originating from... @property SRC_REPLACE @type String @static @final **&#x2F;</pre> </td> <td> <p>Indicates that the property or attribute is a constant and should not be changed.</p> <p> See also: <a href="#attribute"><code>@attribute</code></a>, <a href="#property"><code>@property</code></a>, <a href="#readOnly"><code>@readOnly</code></a>, <a href="#writeOnce"><code>@writeOnce</code></a>. </p> </td> </tr> <tr id="readOnly"> <td><code>readOnly</code></td> <td> <pre class="code prettyprint">&#x2F;** The current default button as configured through... @attribute defaultButton @type Node @default null @readOnly **&#x2F;</pre> </td> <td> <p>[YUI-specific] Indicates that the attribute is configured with the <a href="http://yuilibrary.com/yui/docs/api/classes/Attribute.html#method_addAttr"><code>readOnly</code></a> property and cannot be changed by calling the <a href="http://yuilibrary.com/yui/docs/api/classes/Attribute.html#method_set"><code>set()</code></a> method. Read-only attributes should always document their <a href="#default"><code>@default</code></a> value.</p> <p>Sometimes used with properties, as an alias for <a href="#final"><code>@final</code></a>.</p> <p> See also: <a href="#attribute"><code>@attribute</code></a>, <a href="#default"><code>@default</code></a>, <a href="#final"><code>@final</code></a>, <a href="#property"><code>@property</code></a>, <a href="#required"><code>@required</code></a>, <a href="#optional"><code>@optional</code></a>, <a href="#writeOnce"><code>@writeOnce</code></a>. </p> </td> </tr> <tr id="writeOnce"> <td><code>writeOnce</code></td> <td> <pre class="code prettyprint">&#x2F;** Diameter of the circular background object. Other objects scale accordingly. Set this only before rendering. @attribute diameter @type {Number} number of px in diameter @default 100 @writeOnce **&#x2F;</pre> </td> <td> <p>[YUI-specific] Indicates that the attribute is configured with the <a href="http://yuilibrary.com/yui/docs/api/classes/Attribute.html#method_addAttr"><code>writeOnce</code></a> property and can only be set once -- by applying a <a href="#default"><code>@default</code></a>, by setting the value in the constructior, or by calling the <a href="http://yuilibrary.com/yui/docs/api/classes/Attribute.html#method_set"><code>set()</code></a> method for the first time.</p> <p> See also: <a href="#attribute"><code>@attribute</code></a>, <a href="#default"><code>@default</code></a>, <a href="#final"><code>@final</code></a>, <a href="#required"><code>@required</code></a>, <a href="#optional"><code>@optional</code></a>, <a href="#readOnly"><code>@readOnly</code></a>. </p> </td> </tr> <tr id="optional"> <td><code>optional</code></td> <td> <pre class="code prettyprint">&#x2F;** An optional attribute, not required for proper use. @attribute extras @type {Object} extra data @optional **&#x2F;</pre> </td> <td> <p> [YUI-specific] Indicates that the attribute is not required to be provided for proper use of this class. </p> <p> See also: <a href="#attribute"><code>@attribute</code></a>, <a href="#default"><code>@default</code></a>, <a href="#final"><code>@final</code></a>, <a href="#required"><code>@required</code></a>, <a href="#readOnly"><code>@readOnly</code></a>. </p> </td> </tr> <tr id="required"> <td><code>required</code></td> <td> <pre class="code prettyprint">&#x2F;** A required attribute that is required for proper use, module will likely fail if this is not provided. @attribute url @type {String} url to fetch remote data from @required **&#x2F;</pre> </td> <td> <p> [YUI-specific] Indicates that the attribute is required to be provided for proper use of this class. </p> <p> See also: <a href="#attribute"><code>@attribute</code></a>, <a href="#default"><code>@default</code></a>, <a href="#final"><code>@final</code></a>, <a href="#optional"><code>@optional</code></a>, <a href="#readOnly"><code>@readOnly</code></a>. </p> </td> </tr> <tr id="param"> <td><code>*param</code></td> <td> <pre class="code prettyprint">&#x2F;** @param {String} name An Attribute name or object property path. **&#x2F;</pre> <pre class="code prettyprint">&#x2F;** @param {Object} [options] Data to be mixed into the event facade of the &#x60;change&#x60; event(s) for these attributes. @param {Boolean} [options.silent] If &#x60;true&#x60;, no &#x60;change&#x60; event will be fired. **&#x2F;</pre> </td> <td> <p>Defines a parameter for an ordinary <a href="#method"><code>@method</code></a>, a parameter for a <a href="#constructor"><code>@constructor</code></a> (generally defined inside a <a href="#class"><code>@class</code></a> block), <em>or</em> a property that resides on an <a href="#method"><code>@event</code></a> object. Can take either of the forms:</p> <ul> <li><code>@param {type} name description</code></li> <li><code>@param name {type} description</code></li> </ul> <p>The <code>{type}</code> is optional, but if you include it, you must surround it in curly braces so that YUIDoc can distinguish it from the <code>name</code>. The <code>name</code> also has optional syntax:</p> <ul> <li><code>[name]</code> &mdash; optional parameter</li> <li><code>[name=foo]</code> &mdash; default value is foo</li> <li><code>name*</code> &mdash; placeholder for 1..n args</li> <li><code>[name]*</code> &mdash; placeholder for 0..n args</li> </ul> <p>As shown in the example, you can also nest <code>@param</code> tags. This enables you to document object parameters that have their own particular nested structure.</p> <p> See also: <a href="#class"><code>@class</code></a>, <a href="#constructor"><code>@constructor</code></a>, <a href="#event"><code>@event</code></a>, <a href="#method"><code>@method</code></a>, <a href="#return"><code>@return</code></a>. </p> </td> </tr> <tr id="return"> <td><code>return</code></td> <td> <pre class="code prettyprint">&#x2F;** @method generateClientId @return {String} Unique clientId. **&#x2F;</pre> </td> <td> <p>Specifies a method's return value. A <code>@return</code> tag has the structure <code>@return {type} description</code>. The <code>{type}</code> is optional.</p> <!--p>If a return value is an object with a complex structure, you can <a href="#param">nest <code>@param</code> tags</a> underneath the <code>@return</code> value.</p--> <p> See also: <a href="#method"><code>@method</code></a>, <a href="#param"><code>@param</code></a>. </p> </td> </tr> <tr id="for"> <td><code>for</code></td> <td> <pre class="code prettyprint">&#x2F;** Some inner class &#x27;foo&#x27;... @class foo @for OuterClass **&#x2F;</pre> <pre class="code prettyprint">&#x2F;** Some method &#x27;bar&#x27; disconnected from its class &#x27;FarawayClass&#x27;... @method bar @for FarawayClass **&#x2F;</pre> </td> <td> <p>Sets YUIDoc's class scope.</p> <p>Using <code>@for OuterClass</code> in a <code>@class</code> block creates an inner class. YUIDoc will document methods and other items that follow that block as belonging to the inner class, but the inner class is correctly shown as belonging to its parent outer class.</p> <p>To close an inner class, add <code>@for OuterClass</code> (again!) to the <em>last</em> <code>@attribute</code>, <code>@event</code>, <code>@method</code>, or <code>@property</code> block in the inner class. This resets the YUIDoc parser to use <code>OuterClass</code> as the owner of subsequent items.</p> <p>If you are not inside an inner class, using <code>@for FarawayClass</code> in an <code>@attribute</code>, <code>@event</code>, <code>@method</code>, or <code>@property</code> block will attach all that item and subsequent items to the specified faraway class. This is useful when you have a module that attaches extra methods to a class's prototype, but the main class definition is in some entirely different file.</p> <p> See also: <a href="#class"><code>@class</code></a>, <a href="#method"><code>@method</code></a>. </p> </td> </tr> <tr id="type"> <td><code>type</code></td> <td> <pre class="code prettyprint">&#x2F;** @type String **&#x2F;</pre> <pre class="code prettyprint">&#x2F;** @type HTMLElement|Node|String **&#x2F;</pre> </td> <td> <p>Specifies the type of a property or attribute. You can specify a single type, a list of legal types separated by vertical bars, or if you are lazy, "any" or "mixed".</p> <p> See also: <a href="#attribute"><code>@attribute</code></a>, <a href="#default"><code>@default</code></a>, <a href="#property"><code>@property</code></a>. <p> </td> </tr> <tr id="private"> <td><code>private</code></td> <td> <pre class="code prettyprint">&#x2F;** Reference to the internal JSONP instance used to make the queries. @private @property _jsonp **&#x2F;</pre> </td> <td> <p>Indicates a member that should not be used externally. Although YUIDoc does not generate documentation for <code>@private</code> blocks, YUIDoc comments are still a nice, structured way to document internals in source code. All methods and properties are assumed to be public unless marked as private or protected.</p> <p> See also: <a href="#protected"><code>@protected</code></a>. <p> </td> </tr> <tr id="protected"> <td><code>protected</code></td> <td> <pre class="code prettyprint">&#x2F;** Removes the &#x60;container&#x60; from the DOM and ... @method _destroyContainer @protected **&#x2F;</pre> </td> <td> <p>Indicates a member that should not be modified by implementers unless they are creating a subclass. All methods and properties are assumed to be public unless marked as private or protected.</p> <p> See also: <a href="#private"><code>@private</code></a>. <p> </td> </tr> <tr id="requires"> <td><code>requires</code></td> <td> <pre class="code prettyprint">&#x2F;** @module event-simulate @requires event **&#x2F;</pre> </td> <td> <p>[Uncommon] Identifies one or more dependencies in the module declaration. Can be a single module name or a comma-separated list.</p> <p> See also: <a href="#extends"><code>@extends</code></a>, <a href="#extensionfor"><code>@extensionfor</code></a>, <a href="#module"><code>@module</code></a>, <a href="#submodule"><code>@submodule</code></a>. <p> </td> </tr> <tr id="default"> <td><code>default</code></td> <td> <pre class="code prettyprint">&#x2F;** @default false **&#x2F;</pre> </td> <td> <p>Specifies the default value of a property or attribute. Should be paired with a <a href="#type"><code>@type</code></a> tag.</p> <p> See also: <a href="#attribute"><code>@attribute</code></a>, <a href="#property"><code>@property</code></a>, <a href="#type"><code>@type</code></a>. <p> </td> </td> </tr> <tr id="uses"> <td><code>*uses</code></td> <td> <pre class="code prettyprint">&#x2F;** @class Panel @constructor @extends Widget @uses WidgetAutohide @uses WidgetButtons ... **&#x2F;</pre> </td> <td> <p>Specifies that the class has some other class's properties, methods, and other members mixed into its prototype, perhaps using <a href="http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_mix"><code>Y.mix()</code></a>, <a href="http://yuilibrary.com/yui/docs/api/classes/Base.html#method_mix"><code>Y.Base.mix()</code></a>, <a href="http://yuilibrary.com/yui/docs/api/classes/Base.html#method_create"><code>Y.Base.create()</code></a>, or similar methods. YUIDoc will generate API documentation for methods, properties, events, and attributes mixed into the parent class, and link back to the parent class's documentation. In the default YUIDoc theme, users can toggle whether mixed in members should display.</p> <p>Note that <code>@uses</code> does not indicate inheritance. To establish an "is a" relationship, use <a href="#extends"><code>@extends</code></a>. Unlike <code>@extends</code>, you can provide multiple <code>@uses</code> tags. </p> <p> See also: <a href="#class"><code>@class</code></a>, <a href="#extends"><code>@extends</code></a>, <a href="#extensionfor"><code>@extensionfor</code></a>. </p> </td> </tr> <tr id="example"> <td><code>*example</code></td> <td> <pre class="code prettyprint">&#x2F;** @example model.set(&#x27;foo&#x27;, &#x27;bar&#x27;); **&#x2F;</pre> </td> <td> <p>Indicates a block of example code to be automatically parsed and displayed with YUIDoc's Markdown and code highlighting parser. Your code sample should be indented beneath the <code>@example</code> tag. YUIDoc displays all examples highlighted with <code>&lt;span&gt;</code> elements and other markup.</p> <p>A block may include multiple <code>@example</code> tags.</p> </td> </tr> <tr id="chainable"> <td><code>chainable</code></td> <td> <pre class="code prettyprint">&#x2F;** Renders this view ... @method render @chainable **&#x2F; render: function () { return this; }, **&#x2F;</pre> </td> <td> <p>Indicates that a method returns <code>this</code> (the parent object), enabling you to chain it with other calls on the same object.</p> <p> See also: <a href="#method"><code>@method</code></a>. </p> </tr> <tr id="deprecated"> <td><code>deprecated</code></td> <td> <pre class="code prettyprint">&#x2F;** @property locale @type String @deprecated Use &#x60;config.lang&#x60; instead. **&#x2F;</pre> </td> <td> <p>Indicates that the module, class, or member is deprecated and will be removed in a future release. You can optionally supply a string message describing what to use instead.</p> <p> See also: <a href="#beta"><code>@beta</code></a>, <a href="#since"><code>@since</code></a>. </p> </td> </tr> <tr id="since"> <td><code>since</code></td> <td> <pre class="code prettyprint">&#x2F;** @since 3.4.0 **&#x2F;</pre> </td> <td> <p>Indicates that the module, class, or member was added to the source at the specified version.</p> <p> See also: <a href="#beta"><code>@beta</code></a>, <a href="#deprecated"><code>@deprecated</code></a>. </p> </td> </tr> <tr id="async"> <td><code>async</code></td> <td> <pre class="code prettyprint">&#x2F;** @async **&#x2F;</pre> </td> <td> <p>[Uncommon] Indicates that the method is asynchronous and requires a callback.</p> </td> </tr> <tr id="beta"> <td><code>beta</code></td> <td> <pre class="code prettyprint">&#x2F;** @beta **&#x2F;</pre> </td> <td> <p>Indicates that the method, class, or member is in beta and might undergo backwards-incompatible changes in the near future.</p> <p> See also: <a href="#deprecated"><code>@deprecated</code></a>, <a href="#since"><code>@since</code></a>. </p> </td> </tr> <tr id="bubbles"> <td><code>bubbles</code></td> <td> <pre class="code prettyprint">&#x2F;** Handles the mouseup DOM event... @event drag:mouseup @bubbles DDM **&#x2F;</pre> </td> <td> <p>Specifies the default target that a custom event bubbles to. This is a useful tag if your API has a "manager" class that is responsible for capturing a set of related custom events.</p> <p> See also: <a href="#event"><code>@event</code></a>. </p> </td> </tr> <tr id="extensionfor"> <td><code>extension</code><br><code>extensionfor</code><br><code>extension_for</code></td> <td> <pre class="code prettyprint">&#x2F;** @class PjaxBase @extensionfor Router **&#x2F;</pre> </td> <td> <p>Indicates that the class is an extension object designed to be optionally mixed into the specified class.</p> <p><code>@extensionfor</code> is <em>almost</em> the inverse of <a href="#uses"><code>@uses</code></a>. The key difference is that <code>@uses</code> means, "this class <em>always</em> has the 'used' class mixed into its prototype," while <code>@extensionfor</code> means, "this class <em>can</em> be mixed into the 'extensionfor' class, but it isn't baked in by default."</p> <p> See also: <a href="#class"><code>@class</code></a>, <a href="#extends"><code>@extends</code></a>, <a href="#uses"><code>@uses</code></a>. </p> </td> </tr> </table> <p>A <strong>*</strong> indicates that you can supply multiple tags of that type in the same block.</p> <h3 id="parsed-but-not-in-the-theme-yet">Parsed but not in the theme yet</h3> <p> The following tags are parsed by the <code>DocParser</code> but are not in the default theme yet. </p> <table> <tr id="author"> <td><code>author</code></td> <td> <pre class="code prettyprint"></pre> </td> <td>Author information about this item</td> </tr> <tr id="broadcast"> <td><code>broadcast</code></td> <td> <pre class="code prettyprint"></pre> </td> <td>Event broadcasts to a large audience than scoped</td> </tr> <tr id="category"> <td><code>*category</code></td> <td> <pre class="code prettyprint"></pre> </td> <td>Category to place this item into.</td> </tr> </table> <h2 id="extra-formatting">Extra formatting</h2> <p> YUIDoc supports 3 main forms of formatting your documentation. HTML, <a href="http://daringfireball.net/projects/markdown/">Markdown</a> &amp; <a href="http://rgrove.github.com/selleck/">Selleck</a>. </p> <table> <tr> <td><code>HTML</code></td> <td>Doc comments may contain standard HTML markup and YUIDoc will display it as is.</td> </tr> <tr> <td><code>Markdown</code></td> <td>Full <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> is also supported. </td> </tr> <tr> <td><code>Selleck</code></td> <td><a href="http://rgrove.github.com/selleck/">Selleck's</a> additional parsing is also supported.</td> </tr> </table> <h3 id="markdown-and-code-highlighting">Markdown and Code Highlighting</h3> <p> Inside any documentation block you may use Markdown or Selleck based markup. If you indent your code snippets YUIDoc will automatically wrap them in a code block and syntax highlight them for you. </p> <pre class="code prettyprint">&#x2F;** This is the __module__ description for the &#x60;YUIDoc&#x60; module. var options = { paths: [ &#x27;.&#x2F;lib&#x27; ], outdir: &#x27;.&#x2F;out&#x27; }; var Y = require(&#x27;yuidoc&#x27;); var json = (new Y.YUIDoc(options)).run(); @class YUIDoc @main yuidoc *&#x2F;</pre> <p> This is what the above would render to: </p> <div class="intro"> <p>This is the <strong>module</strong> description for the <code>YUIDoc</code> module.</p> <pre class="code prettyprint">var options = { paths: [ &#x27;.&#x2F;lib&#x27; ], outdir: &#x27;.&#x2F;out&#x27; }; var Y = require(&#x27;yuidoc&#x27;); var json = (new Y.YUIDoc(options)).run();</pre> </div> <h3 id="cross-referencing-modules-and-classes">Cross-referencing Modules and Classes</h3> <p>YUIDoc also includes a Handlebars <code>blockHelper</code> that enables you to easily cross-reference classes and modules. For example, if you include:</p> <pre class="code prettyprint">&#x2F;** This module also uses {{#crossLink &quot;Foo&quot;}}{{&#x2F;crossLink}}, where Foo is a class name. Also see {{#crossLink &quot;myClass&#x2F;Foo&quot;}}{{&#x2F;crossLink}}, where myClass is a class name and Foo is a method on that class. This module uses {{#crossLinkModule &quot;widget&quot;}}{{&#x2F;crossLinkModule}}, where widget is a module name *&#x2F;</pre> <p> This automatically generates an internal link to Foo's API reference page: </p> <pre class="code prettyprint">&lt;p&gt; This module also uses &lt;a href=&quot;..&#x2F;classes&#x2F;Foo.html&quot; class=&quot;crosslink&quot;&gt;Foo&lt;&#x2F;a&gt;, where Foo is a class or module name. &lt;&#x2F;p&gt; &lt;p&gt; Also see &lt;a href=&quot;..&#x2F;classes&#x2F;myClass.html#method_Foo&quot;&gt;Foo&lt;&#x2F;a&gt;, where myClass is a class name and Foo is a method on that class. &lt;&#x2F;p&gt; &lt;p&gt; This module uses &lt;a href=&quot;..&#x2F;modules&#x2F;widget.html&quot;&gt;widget&lt;&#x2F;a&gt;, where widget is a module name &lt;&#x2F;p&gt;</pre> <p> You can also call <code>crossLinkRaw</code> to retun only the HREF portion of the link, so you can link it yourself. </p> <h3 id="using-custom-handlebars-block-helpers">Using custom Handlebars block helpers</h3> <p> You can tell <code>YUIDoc</code> to include custom <code>Y.Handlebars</code> helpers with the <code>-H</code> or <code>--helpers</code> command line arguments (or <code>helpers</code> Array in the <code>yuidoc.json</code> file). Here is an example <code>helper.js</code> file: <pre class="code prettyprint">module.exports = { davglass: function(item) { return &quot;Dav Glass says: &quot; + item } };</pre> <p> Now you can use the <code>davglass</code> helper inside your own docs like this: </p> <pre class="code prettyprint">&#x2F;** * This is also a test {{#davglass &quot;Foo&quot;}}{{&#x2F;davglass}} *&#x2F;</pre> This will output this in your documentation: <pre class="code prettyprint">&lt;p&gt; This is also a test Dav Glass says: Foo &lt;&#x2F;p&gt;</pre> </div> </div> </div> <div class="yui3-u-1-4"> <div class="sidebar"> <ul class="links"> <li><a href="https://github.com/yui/yuidoc/" class="button">Get the Source</a></li> <li><a href="https://groups.google.com/forum/#!forum/yuidoc" class="button">Questions? Join the Mailing List</a></li> <li><a href="https://github.com/yui/yuidoc/issues/" class="button">File an Issue</a></li> <li><a href="../api/" class="button">View API Documentation</a></li> </ul> <div id="toc" class="sidebox"> <div class="hd"> <h2 class="no-toc">Table of Contents</h2> </div> <div class="bd"> <ul class="toc"> <li> <a href="#basic-requirements">Basic Requirements</a> </li> <li> <a href="#primary-tags">Primary Tags</a> </li> <li> <a href="#secondary-tags">Secondary tags</a> <ul class="toc"> <li> <a href="#parsed-but-not-in-the-theme-yet">Parsed but not in the theme yet</a> </li> </ul> </li> <li> <a href="#extra-formatting">Extra formatting</a> <ul class="toc"> <li> <a href="#markdown-and-code-highlighting">Markdown and Code Highlighting</a> </li> <li> <a href="#cross-referencing-modules-and-classes">Cross-referencing Modules and Classes</a> </li> <li> <a href="#using-custom-handlebars-block-helpers">Using custom Handlebars block helpers</a> </li> </ul> </li> </ul> </div> </div> </div> </div> </div> </div> <script src="../assets/vendor/prettify/prettify-min.js"></script> <script>prettyPrint();</script> </body> </html>
naver/auidoc
output/syntax/index.html
HTML
bsd-3-clause
43,256
package net.dongliu.apk.parser.bean; import java.io.Serializable; /** * Android adaptive icon, from android 8.0 */ public class AdaptiveIcon implements IconFace, Serializable { private static final long serialVersionUID = 4185750290211529320L; private final Icon foreground; private final Icon background; public AdaptiveIcon(Icon foreground, Icon background) { this.foreground = foreground; this.background = background; } /** * The foreground icon */ public Icon getForeground() { return foreground; } /** * The background icon */ public Icon getBackground() { return background; } @Override public String toString() { return "AdaptiveIcon{" + "foreground=" + foreground + ", background=" + background + '}'; } @Override public boolean isFile() { return foreground.isFile(); } @Override public byte[] getData() { return foreground.getData(); } @Override public String getPath() { return foreground.getPath(); } }
CaoQianLi/apk-parser
src/main/java/net/dongliu/apk/parser/bean/AdaptiveIcon.java
Java
bsd-3-clause
1,151
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow */ 'use strict'; const invariant = require('invariant'); import type EventSubscription from './_EventSubscription'; /** * EventSubscriptionVendor stores a set of EventSubscriptions that are * subscribed to a particular event type. */ class EventSubscriptionVendor { _subscriptionsForType: Object; _currentSubscription: ?EventSubscription; constructor() { this._subscriptionsForType = {}; this._currentSubscription = null; } /** * Adds a subscription keyed by an event type. * * @param {string} eventType * @param {EventSubscription} subscription */ addSubscription( eventType: string, subscription: EventSubscription, ): EventSubscription { invariant( subscription.subscriber === this, 'The subscriber of the subscription is incorrectly set.', ); if (!this._subscriptionsForType[eventType]) { this._subscriptionsForType[eventType] = []; } const key = this._subscriptionsForType[eventType].length; this._subscriptionsForType[eventType].push(subscription); subscription.eventType = eventType; subscription.key = key; return subscription; } /** * Removes a bulk set of the subscriptions. * * @param {?string} eventType - Optional name of the event type whose * registered supscriptions to remove, if null remove all subscriptions. */ removeAllSubscriptions(eventType: ?string) { if (eventType === undefined) { this._subscriptionsForType = {}; } else { delete this._subscriptionsForType[eventType]; } } /** * Removes a specific subscription. Instead of calling this function, call * `subscription.remove()` directly. * * @param {object} subscription */ removeSubscription(subscription: Object) { const eventType = subscription.eventType; const key = subscription.key; const subscriptionsForType = this._subscriptionsForType[eventType]; if (subscriptionsForType) { delete subscriptionsForType[key]; } } /** * Returns the array of subscriptions that are currently registered for the * given event type. * * Note: This array can be potentially sparse as subscriptions are deleted * from it when they are removed. * * TODO: This returns a nullable array. wat? * * @param {string} eventType * @returns {?array} */ getSubscriptionsForType(eventType: string): ?[EventSubscription] { return this._subscriptionsForType[eventType]; } } module.exports = EventSubscriptionVendor;
hoangpham95/react-native
Libraries/vendor/emitter/_EventSubscriptionVendor.js
JavaScript
bsd-3-clause
2,725
/* * Copyright 2003-2006 Rick Knowles <winstone-devel at lists sourceforge net> * Distributed under the terms of either: * - the common development and distribution license (CDDL), v1.0; or * - the GNU Lesser General Public License, v2.1 or later */ package javax.servlet.http; import java.util.Enumeration; import javax.servlet.ServletContext; /** * Interface for http sessions on the server. * * @author <a href="mailto:rick_knowles@hotmail.com">Rick Knowles</a> */ public interface HttpSession { public Object getAttribute(String name); public Enumeration getAttributeNames(); public long getCreationTime(); public String getId(); public long getLastAccessedTime(); public int getMaxInactiveInterval(); public ServletContext getServletContext(); public void invalidate(); public boolean isNew(); public void removeAttribute(String name); public void setAttribute(String name, Object value); public void setMaxInactiveInterval(int interval); /** * @deprecated As of Version 2.1, this method is deprecated and has no * replacement. It will be removed in a future version of the * Java Servlet API. */ public HttpSessionContext getSessionContext(); /** * @deprecated As of Version 2.2, this method is replaced by * getAttribute(java.lang.String). */ public Object getValue(String name); /** * @deprecated As of Version 2.2, this method is replaced by * getAttributeNames() */ public String[] getValueNames(); /** * @deprecated As of Version 2.2, this method is replaced by * setAttribute(java.lang.String, java.lang.Object) */ public void putValue(String name, Object value); /** * @deprecated As of Version 2.2, this method is replaced by * removeAttribute(java.lang.String) */ public void removeValue(String name); }
KingBowser/hatter-source-code
tools/winstone/src/java/javax/servlet/http/HttpSession.java
Java
bsd-3-clause
1,988
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Alessandro Tasora // ============================================================================= #ifndef CHCASCADEDOC_H #define CHCASCADEDOC_H #include "chrono_cascade/ChApiCASCADE.h" #include "chrono/core/ChStream.h" #include "chrono/core/ChFrameMoving.h" #include "chrono/physics/ChBodyAuxRef.h" class TopoDS_Face; class TopoDS_Shape; class Handle_TDocStd_Document; class TopLoc_Location; class TDF_Label; namespace chrono { namespace cascade { /// Class that contains an OCAF document (a tree hierarchy of /// shapes in the OpenCascade framework). Most often this is /// populated by loading a STEP file from disk. class ChApiCASCADE ChCascadeDoc { public: ChCascadeDoc(); virtual ~ChCascadeDoc(); /// Populate the document with all shapes that are contained in /// the STEP file, saved from some CAD. If load was ok, return true. bool Load_STEP(const char* filename); /// Show shape hierarchy, writing on mstream (mstream could be GetLog() /// to print in default console log) void Dump(ChStreamOutAscii& mstream); /// Get the root shape. Note that there could be more than one root, /// if so, use 'num' to select the one that you need. bool GetRootShape(TopoDS_Shape& mshape, const int num = 1); /// Get a sub-shape with a given name, returned in 'mshape'. /// Since the document can contain assembles, subassemblies etc, the name /// can use a 'directory type' syntax, using the / slash such as in /// "assembly/subassebmly/subsubassembly/mypart" /// It is possible to use # and ? wildcards as in Unix. /// If there are multiple parts (or assemblies) with the same name, only the first /// instance is returned in 'mshape'; otherwise, one can use the # wildcard /// to get the n-th object, for example "MyAssembly/bolt#3", "Car/Wheel#2/hub", etc. /// If the 'set_location_to_root' parameter is true (default), the location of the /// shape is changed so that it represents its position respect to the root, that is /// the shape .Location() function will give the absolute position, otherwise if false /// it will give its position relative to the assembly where it is a sub-shape. /// If the 'get_multiple' = true, if there are multiple parts satisfying the search string, /// they are all returned in a single shape of compound type (with null location). bool GetNamedShape(TopoDS_Shape& mshape, char* name, bool set_location_to_root = true, bool get_multiple = false); /// Get the volume properties (center of mass, inertia moments, volume) /// of a given shape. bool static GetVolumeProperties( const TopoDS_Shape& mshape, ///< pass the shape here const double density, ///< pass the density here ChVector<>& center_position, ///< get the COG position center, respect to shape pos. ChVector<>& inertiaXX, ///< get the inertia diagonal terms ChVector<>& inertiaXY, ///< get the inertia extradiagonal terms double& volume, ///< get the volume double& mass ///< get the mass ); class callback_CascadeDoc { public: virtual bool ForShape(TopoDS_Shape& mshape, TopLoc_Location& mloc, char* mname, int mlevel, TDF_Label& mlabel) = 0; }; /// Execute a callback on all contained shapes, with user-defined callback inherited /// from callback_CascadeDoc. Btw. If the callback_CascadeDoc::ForShape callback returns false, subshapes are not /// processed. void ScanCascadeShapes(callback_CascadeDoc& mcallback); /// Convert OpenCascade coordinates into Chrono coordinates static void FromCascadeToChrono(const TopLoc_Location& from_coord, ChFrame<>& to_coord); /// Convert Chrono coordinates into OpenCascade coordinates static void FromChronoToCascade(const ChFrame<>& from_coord, TopLoc_Location& to_coord); /// Create a ChBodyAuxRef with assets for the given TopoDS_Shape static std::shared_ptr<ChBodyAuxRef> CreateBodyFromShape( const TopoDS_Shape& mshape, ///< pass the shape here const double density ///< pass the density here ); private: // pointer to cascade OCAF doc handle; Handle_TDocStd_Document* doc; }; } // END_OF_NAMESPACE____ } // END_OF_NAMESPACE____ #endif // END of header
amelmquist/chrono
src/chrono_cascade/ChCascadeDoc.h
C
bsd-3-clause
4,996
DIRS=$(wildcard *_tests) DIRS_TEST=$(addsuffix .test,$(DIRS)) DIRS_CLEAN=$(addsuffix .clean,$(DIRS)) SHELL=/bin/bash test: $(DIRS_TEST) clean: $(DIRS_CLEAN) $(DIRS_TEST): %.test: @echo -n "Testing $* " @$(MAKE) -s -C $* test @echo $(DIRS_CLEAN): %.clean: $(MAKE) -C $* clean .PHONY: test $(DIRS_TEST) clean $(DIRS_CLEAN) .SILENT: test
MatkoBotincan/corestar-old
unit_tests/Makefile
Makefile
bsd-3-clause
344
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.egl; import java.nio.*; import org.lwjgl.system.*; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.JNI.*; import static org.lwjgl.system.MemoryUtil.*; /** * Native bindings to the <a target="_blank" href="https://www.khronos.org/registry/EGL/extensions/ANGLE/EGL_ANGLE_sync_control_rate.txt">ANGLE_sync_control_rate</a> extension. * * <p>This extension provides counters which let applications know about the timing of the last vertical retrace. By looking at the system clock, as well as * the refresh rate of the monitor, this should enable applications to predict the position of future retraces so as to schedule an optimal workload.</p> * * <p>This extension incorporates the use of a counter that provides the necessary synchronization. The graphics Media Stream Counter (or graphics MSC) is a * counter that is unique to the graphics subsystem and increments for each vertical retrace that occurs.</p> * * <p>By querying the MSC rate for a given surface, the application can accurately predict the timing for the next vertical retraces and schedule rendering * accordingly.</p> */ public class ANGLESyncControlRate { protected ANGLESyncControlRate() { throw new UnsupportedOperationException(); } // --- [ eglGetMscRateANGLE ] --- public static int neglGetMscRateANGLE(long dpy, long surface, long numerator, long denominator) { long __functionAddress = EGL.getCapabilities().eglGetMscRateANGLE; if (CHECKS) { check(__functionAddress); check(dpy); check(surface); } return callPPPPI(dpy, surface, numerator, denominator, __functionAddress); } @NativeType("EGLBoolean") public static boolean eglGetMscRateANGLE(@NativeType("EGLDisplay") long dpy, @NativeType("EGLSurface") long surface, @NativeType("int32_t *") IntBuffer numerator, @NativeType("int32_t *") IntBuffer denominator) { if (CHECKS) { check(numerator, 1); check(denominator, 1); } return neglGetMscRateANGLE(dpy, surface, memAddress(numerator), memAddress(denominator)) != 0; } /** Array version of: {@link #eglGetMscRateANGLE GetMscRateANGLE} */ @NativeType("EGLBoolean") public static boolean eglGetMscRateANGLE(@NativeType("EGLDisplay") long dpy, @NativeType("EGLSurface") long surface, @NativeType("int32_t *") int[] numerator, @NativeType("int32_t *") int[] denominator) { long __functionAddress = EGL.getCapabilities().eglGetMscRateANGLE; if (CHECKS) { check(__functionAddress); check(dpy); check(surface); check(numerator, 1); check(denominator, 1); } return callPPPPI(dpy, surface, numerator, denominator, __functionAddress) != 0; } }
LWJGL-CI/lwjgl3
modules/lwjgl/egl/src/generated/java/org/lwjgl/egl/ANGLESyncControlRate.java
Java
bsd-3-clause
2,975
<?php new SoapClient(dirname(__FILE__) . '/bug50698_4.wsdl'); echo "ok\n"; ?>
JSchwehn/php
testdata/fuzzdir/corpus/ext_soap_tests_bugs_bug50698_4.php
PHP
bsd-3-clause
78
/* * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* Internal tests for the modes module */ /* * This file uses the low level AES functions (which are deprecated for * non-internal use) in order to test the modes code */ #include "internal/deprecated.h" #include <stdio.h> #include <string.h> #include <openssl/aes.h> #include <openssl/modes.h> #include "testutil.h" #include "crypto/modes.h" #include "internal/nelem.h" typedef struct { size_t size; const unsigned char *data; } SIZED_DATA; /********************************************************************** * * Test of cts128 * ***/ /* cts128 test vectors from RFC 3962 */ static const unsigned char cts128_test_key[16] = "chicken teriyaki"; static const unsigned char cts128_test_input[64] = "I would like the" " General Gau's C" "hicken, please, " "and wonton soup."; static const unsigned char cts128_test_iv[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static const unsigned char vector_17[17] = { 0xc6, 0x35, 0x35, 0x68, 0xf2, 0xbf, 0x8c, 0xb4, 0xd8, 0xa5, 0x80, 0x36, 0x2d, 0xa7, 0xff, 0x7f, 0x97 }; static const unsigned char vector_31[31] = { 0xfc, 0x00, 0x78, 0x3e, 0x0e, 0xfd, 0xb2, 0xc1, 0xd4, 0x45, 0xd4, 0xc8, 0xef, 0xf7, 0xed, 0x22, 0x97, 0x68, 0x72, 0x68, 0xd6, 0xec, 0xcc, 0xc0, 0xc0, 0x7b, 0x25, 0xe2, 0x5e, 0xcf, 0xe5 }; static const unsigned char vector_32[32] = { 0x39, 0x31, 0x25, 0x23, 0xa7, 0x86, 0x62, 0xd5, 0xbe, 0x7f, 0xcb, 0xcc, 0x98, 0xeb, 0xf5, 0xa8, 0x97, 0x68, 0x72, 0x68, 0xd6, 0xec, 0xcc, 0xc0, 0xc0, 0x7b, 0x25, 0xe2, 0x5e, 0xcf, 0xe5, 0x84 }; static const unsigned char vector_47[47] = { 0x97, 0x68, 0x72, 0x68, 0xd6, 0xec, 0xcc, 0xc0, 0xc0, 0x7b, 0x25, 0xe2, 0x5e, 0xcf, 0xe5, 0x84, 0xb3, 0xff, 0xfd, 0x94, 0x0c, 0x16, 0xa1, 0x8c, 0x1b, 0x55, 0x49, 0xd2, 0xf8, 0x38, 0x02, 0x9e, 0x39, 0x31, 0x25, 0x23, 0xa7, 0x86, 0x62, 0xd5, 0xbe, 0x7f, 0xcb, 0xcc, 0x98, 0xeb, 0xf5 }; static const unsigned char vector_48[48] = { 0x97, 0x68, 0x72, 0x68, 0xd6, 0xec, 0xcc, 0xc0, 0xc0, 0x7b, 0x25, 0xe2, 0x5e, 0xcf, 0xe5, 0x84, 0x9d, 0xad, 0x8b, 0xbb, 0x96, 0xc4, 0xcd, 0xc0, 0x3b, 0xc1, 0x03, 0xe1, 0xa1, 0x94, 0xbb, 0xd8, 0x39, 0x31, 0x25, 0x23, 0xa7, 0x86, 0x62, 0xd5, 0xbe, 0x7f, 0xcb, 0xcc, 0x98, 0xeb, 0xf5, 0xa8 }; static const unsigned char vector_64[64] = { 0x97, 0x68, 0x72, 0x68, 0xd6, 0xec, 0xcc, 0xc0, 0xc0, 0x7b, 0x25, 0xe2, 0x5e, 0xcf, 0xe5, 0x84, 0x39, 0x31, 0x25, 0x23, 0xa7, 0x86, 0x62, 0xd5, 0xbe, 0x7f, 0xcb, 0xcc, 0x98, 0xeb, 0xf5, 0xa8, 0x48, 0x07, 0xef, 0xe8, 0x36, 0xee, 0x89, 0xa5, 0x26, 0x73, 0x0d, 0xbc, 0x2f, 0x7b, 0xc8, 0x40, 0x9d, 0xad, 0x8b, 0xbb, 0x96, 0xc4, 0xcd, 0xc0, 0x3b, 0xc1, 0x03, 0xe1, 0xa1, 0x94, 0xbb, 0xd8 }; #define CTS128_TEST_VECTOR(len) \ { \ sizeof(vector_##len), vector_##len \ } static const SIZED_DATA aes_cts128_vectors[] = { CTS128_TEST_VECTOR(17), CTS128_TEST_VECTOR(31), CTS128_TEST_VECTOR(32), CTS128_TEST_VECTOR(47), CTS128_TEST_VECTOR(48), CTS128_TEST_VECTOR(64), }; static AES_KEY *cts128_encrypt_key_schedule(void) { static int init_key = 1; static AES_KEY ks; if (init_key) { AES_set_encrypt_key(cts128_test_key, 128, &ks); init_key = 0; } return &ks; } static AES_KEY *cts128_decrypt_key_schedule(void) { static int init_key = 1; static AES_KEY ks; if (init_key) { AES_set_decrypt_key(cts128_test_key, 128, &ks); init_key = 0; } return &ks; } typedef struct { const char *case_name; size_t (*last_blocks_correction)(const unsigned char *in, unsigned char *out, size_t len); size_t (*encrypt_block)(const unsigned char *in, unsigned char *out, size_t len, const void *key, unsigned char ivec[16], block128_f block); size_t (*encrypt_stream)(const unsigned char *in, unsigned char *out, size_t len, const void *key, unsigned char ivec[16], cbc128_f cbc); size_t (*decrypt_block)(const unsigned char *in, unsigned char *out, size_t len, const void *key, unsigned char ivec[16], block128_f block); size_t (*decrypt_stream)(const unsigned char *in, unsigned char *out, size_t len, const void *key, unsigned char ivec[16], cbc128_f cbc); } CTS128_FIXTURE; static size_t last_blocks_correction(const unsigned char *in, unsigned char *out, size_t len) { size_t tail; memcpy(out, in, len); if ((tail = len % 16) == 0) tail = 16; tail += 16; return tail; } static size_t last_blocks_correction_nist(const unsigned char *in, unsigned char *out, size_t len) { size_t tail; if ((tail = len % 16) == 0) tail = 16; len -= 16 + tail; memcpy(out, in, len); /* flip two last blocks */ memcpy(out + len, in + len + 16, tail); memcpy(out + len + tail, in + len, 16); len += 16 + tail; tail = 16; return tail; } static int execute_cts128(const CTS128_FIXTURE *fixture, int num) { const unsigned char *test_iv = cts128_test_iv; size_t test_iv_len = sizeof(cts128_test_iv); const unsigned char *orig_vector = aes_cts128_vectors[num].data; size_t len = aes_cts128_vectors[num].size; const unsigned char *test_input = cts128_test_input; const AES_KEY *encrypt_key_schedule = cts128_encrypt_key_schedule(); const AES_KEY *decrypt_key_schedule = cts128_decrypt_key_schedule(); unsigned char iv[16]; /* The largest test inputs are = 64 bytes. */ unsigned char cleartext[64], ciphertext[64], vector[64]; size_t tail, size; TEST_info("%s_vector_%lu", fixture->case_name, (unsigned long)len); tail = fixture->last_blocks_correction(orig_vector, vector, len); /* test block-based encryption */ memcpy(iv, test_iv, test_iv_len); if (!TEST_size_t_eq(fixture->encrypt_block(test_input, ciphertext, len, encrypt_key_schedule, iv, (block128_f)AES_encrypt), len) || !TEST_mem_eq(ciphertext, len, vector, len) || !TEST_mem_eq(iv, sizeof(iv), vector + len - tail, sizeof(iv))) return 0; /* test block-based decryption */ memcpy(iv, test_iv, test_iv_len); size = fixture->decrypt_block(ciphertext, cleartext, len, decrypt_key_schedule, iv, (block128_f)AES_decrypt); if (!TEST_true(len == size || len + 16 == size) || !TEST_mem_eq(cleartext, len, test_input, len) || !TEST_mem_eq(iv, sizeof(iv), vector + len - tail, sizeof(iv))) return 0; /* test streamed encryption */ memcpy(iv, test_iv, test_iv_len); if (!TEST_size_t_eq(fixture->encrypt_stream(test_input, ciphertext, len, encrypt_key_schedule, iv, (cbc128_f) AES_cbc_encrypt), len) || !TEST_mem_eq(ciphertext, len, vector, len) || !TEST_mem_eq(iv, sizeof(iv), vector + len - tail, sizeof(iv))) return 0; /* test streamed decryption */ memcpy(iv, test_iv, test_iv_len); if (!TEST_size_t_eq(fixture->decrypt_stream(ciphertext, cleartext, len, decrypt_key_schedule, iv, (cbc128_f)AES_cbc_encrypt), len) || !TEST_mem_eq(cleartext, len, test_input, len) || !TEST_mem_eq(iv, sizeof(iv), vector + len - tail, sizeof(iv))) return 0; return 1; } static int test_aes_cts128(int idx) { static const CTS128_FIXTURE fixture_cts128 = { "aes_cts128", last_blocks_correction, CRYPTO_cts128_encrypt_block, CRYPTO_cts128_encrypt, CRYPTO_cts128_decrypt_block, CRYPTO_cts128_decrypt }; return execute_cts128(&fixture_cts128, idx); } static int test_aes_cts128_nist(int idx) { static const CTS128_FIXTURE fixture_cts128_nist = { "aes_cts128_nist", last_blocks_correction_nist, CRYPTO_nistcts128_encrypt_block, CRYPTO_nistcts128_encrypt, CRYPTO_nistcts128_decrypt_block, CRYPTO_nistcts128_decrypt }; return execute_cts128(&fixture_cts128_nist, idx); } /* * * Test of gcm128 * */ /* Test Case 1 */ static const u8 K1[16], P1[] = { 0 }, A1[] = { 0 }, IV1[12], C1[] = { 0 }; static const u8 T1[] = { 0x58, 0xe2, 0xfc, 0xce, 0xfa, 0x7e, 0x30, 0x61, 0x36, 0x7f, 0x1d, 0x57, 0xa4, 0xe7, 0x45, 0x5a }; /* Test Case 2 */ # define K2 K1 # define A2 A1 # define IV2 IV1 static const u8 P2[16]; static const u8 C2[] = { 0x03, 0x88, 0xda, 0xce, 0x60, 0xb6, 0xa3, 0x92, 0xf3, 0x28, 0xc2, 0xb9, 0x71, 0xb2, 0xfe, 0x78 }; static const u8 T2[] = { 0xab, 0x6e, 0x47, 0xd4, 0x2c, 0xec, 0x13, 0xbd, 0xf5, 0x3a, 0x67, 0xb2, 0x12, 0x57, 0xbd, 0xdf }; /* Test Case 3 */ # define A3 A2 static const u8 K3[] = { 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08 }; static const u8 P3[] = { 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, 0xba, 0x63, 0x7b, 0x39, 0x1a, 0xaf, 0xd2, 0x55 }; static const u8 IV3[] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88 }; static const u8 C3[] = { 0x42, 0x83, 0x1e, 0xc2, 0x21, 0x77, 0x74, 0x24, 0x4b, 0x72, 0x21, 0xb7, 0x84, 0xd0, 0xd4, 0x9c, 0xe3, 0xaa, 0x21, 0x2f, 0x2c, 0x02, 0xa4, 0xe0, 0x35, 0xc1, 0x7e, 0x23, 0x29, 0xac, 0xa1, 0x2e, 0x21, 0xd5, 0x14, 0xb2, 0x54, 0x66, 0x93, 0x1c, 0x7d, 0x8f, 0x6a, 0x5a, 0xac, 0x84, 0xaa, 0x05, 0x1b, 0xa3, 0x0b, 0x39, 0x6a, 0x0a, 0xac, 0x97, 0x3d, 0x58, 0xe0, 0x91, 0x47, 0x3f, 0x59, 0x85 }; static const u8 T3[] = { 0x4d, 0x5c, 0x2a, 0xf3, 0x27, 0xcd, 0x64, 0xa6, 0x2c, 0xf3, 0x5a, 0xbd, 0x2b, 0xa6, 0xfa, 0xb4 }; /* Test Case 4 */ # define K4 K3 # define IV4 IV3 static const u8 P4[] = { 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, 0xba, 0x63, 0x7b, 0x39 }; static const u8 A4[] = { 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, 0xab, 0xad, 0xda, 0xd2 }; static const u8 C4[] = { 0x42, 0x83, 0x1e, 0xc2, 0x21, 0x77, 0x74, 0x24, 0x4b, 0x72, 0x21, 0xb7, 0x84, 0xd0, 0xd4, 0x9c, 0xe3, 0xaa, 0x21, 0x2f, 0x2c, 0x02, 0xa4, 0xe0, 0x35, 0xc1, 0x7e, 0x23, 0x29, 0xac, 0xa1, 0x2e, 0x21, 0xd5, 0x14, 0xb2, 0x54, 0x66, 0x93, 0x1c, 0x7d, 0x8f, 0x6a, 0x5a, 0xac, 0x84, 0xaa, 0x05, 0x1b, 0xa3, 0x0b, 0x39, 0x6a, 0x0a, 0xac, 0x97, 0x3d, 0x58, 0xe0, 0x91 }; static const u8 T4[] = { 0x5b, 0xc9, 0x4f, 0xbc, 0x32, 0x21, 0xa5, 0xdb, 0x94, 0xfa, 0xe9, 0x5a, 0xe7, 0x12, 0x1a, 0x47 }; /* Test Case 5 */ # define K5 K4 # define P5 P4 # define A5 A4 static const u8 IV5[] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad }; static const u8 C5[] = { 0x61, 0x35, 0x3b, 0x4c, 0x28, 0x06, 0x93, 0x4a, 0x77, 0x7f, 0xf5, 0x1f, 0xa2, 0x2a, 0x47, 0x55, 0x69, 0x9b, 0x2a, 0x71, 0x4f, 0xcd, 0xc6, 0xf8, 0x37, 0x66, 0xe5, 0xf9, 0x7b, 0x6c, 0x74, 0x23, 0x73, 0x80, 0x69, 0x00, 0xe4, 0x9f, 0x24, 0xb2, 0x2b, 0x09, 0x75, 0x44, 0xd4, 0x89, 0x6b, 0x42, 0x49, 0x89, 0xb5, 0xe1, 0xeb, 0xac, 0x0f, 0x07, 0xc2, 0x3f, 0x45, 0x98 }; static const u8 T5[] = { 0x36, 0x12, 0xd2, 0xe7, 0x9e, 0x3b, 0x07, 0x85, 0x56, 0x1b, 0xe1, 0x4a, 0xac, 0xa2, 0xfc, 0xcb }; /* Test Case 6 */ # define K6 K5 # define P6 P5 # define A6 A5 static const u8 IV6[] = { 0x93, 0x13, 0x22, 0x5d, 0xf8, 0x84, 0x06, 0xe5, 0x55, 0x90, 0x9c, 0x5a, 0xff, 0x52, 0x69, 0xaa, 0x6a, 0x7a, 0x95, 0x38, 0x53, 0x4f, 0x7d, 0xa1, 0xe4, 0xc3, 0x03, 0xd2, 0xa3, 0x18, 0xa7, 0x28, 0xc3, 0xc0, 0xc9, 0x51, 0x56, 0x80, 0x95, 0x39, 0xfc, 0xf0, 0xe2, 0x42, 0x9a, 0x6b, 0x52, 0x54, 0x16, 0xae, 0xdb, 0xf5, 0xa0, 0xde, 0x6a, 0x57, 0xa6, 0x37, 0xb3, 0x9b }; static const u8 C6[] = { 0x8c, 0xe2, 0x49, 0x98, 0x62, 0x56, 0x15, 0xb6, 0x03, 0xa0, 0x33, 0xac, 0xa1, 0x3f, 0xb8, 0x94, 0xbe, 0x91, 0x12, 0xa5, 0xc3, 0xa2, 0x11, 0xa8, 0xba, 0x26, 0x2a, 0x3c, 0xca, 0x7e, 0x2c, 0xa7, 0x01, 0xe4, 0xa9, 0xa4, 0xfb, 0xa4, 0x3c, 0x90, 0xcc, 0xdc, 0xb2, 0x81, 0xd4, 0x8c, 0x7c, 0x6f, 0xd6, 0x28, 0x75, 0xd2, 0xac, 0xa4, 0x17, 0x03, 0x4c, 0x34, 0xae, 0xe5 }; static const u8 T6[] = { 0x61, 0x9c, 0xc5, 0xae, 0xff, 0xfe, 0x0b, 0xfa, 0x46, 0x2a, 0xf4, 0x3c, 0x16, 0x99, 0xd0, 0x50 }; /* Test Case 7 */ static const u8 K7[24], P7[] = { 0 }, A7[] = { 0 }, IV7[12], C7[] = { 0 }; static const u8 T7[] = { 0xcd, 0x33, 0xb2, 0x8a, 0xc7, 0x73, 0xf7, 0x4b, 0xa0, 0x0e, 0xd1, 0xf3, 0x12, 0x57, 0x24, 0x35 }; /* Test Case 8 */ # define K8 K7 # define IV8 IV7 # define A8 A7 static const u8 P8[16]; static const u8 C8[] = { 0x98, 0xe7, 0x24, 0x7c, 0x07, 0xf0, 0xfe, 0x41, 0x1c, 0x26, 0x7e, 0x43, 0x84, 0xb0, 0xf6, 0x00 }; static const u8 T8[] = { 0x2f, 0xf5, 0x8d, 0x80, 0x03, 0x39, 0x27, 0xab, 0x8e, 0xf4, 0xd4, 0x58, 0x75, 0x14, 0xf0, 0xfb }; /* Test Case 9 */ # define A9 A8 static const u8 K9[] = { 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08, 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c }; static const u8 P9[] = { 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, 0xba, 0x63, 0x7b, 0x39, 0x1a, 0xaf, 0xd2, 0x55 }; static const u8 IV9[] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88 }; static const u8 C9[] = { 0x39, 0x80, 0xca, 0x0b, 0x3c, 0x00, 0xe8, 0x41, 0xeb, 0x06, 0xfa, 0xc4, 0x87, 0x2a, 0x27, 0x57, 0x85, 0x9e, 0x1c, 0xea, 0xa6, 0xef, 0xd9, 0x84, 0x62, 0x85, 0x93, 0xb4, 0x0c, 0xa1, 0xe1, 0x9c, 0x7d, 0x77, 0x3d, 0x00, 0xc1, 0x44, 0xc5, 0x25, 0xac, 0x61, 0x9d, 0x18, 0xc8, 0x4a, 0x3f, 0x47, 0x18, 0xe2, 0x44, 0x8b, 0x2f, 0xe3, 0x24, 0xd9, 0xcc, 0xda, 0x27, 0x10, 0xac, 0xad, 0xe2, 0x56 }; static const u8 T9[] = { 0x99, 0x24, 0xa7, 0xc8, 0x58, 0x73, 0x36, 0xbf, 0xb1, 0x18, 0x02, 0x4d, 0xb8, 0x67, 0x4a, 0x14 }; /* Test Case 10 */ # define K10 K9 # define IV10 IV9 static const u8 P10[] = { 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, 0xba, 0x63, 0x7b, 0x39 }; static const u8 A10[] = { 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, 0xab, 0xad, 0xda, 0xd2 }; static const u8 C10[] = { 0x39, 0x80, 0xca, 0x0b, 0x3c, 0x00, 0xe8, 0x41, 0xeb, 0x06, 0xfa, 0xc4, 0x87, 0x2a, 0x27, 0x57, 0x85, 0x9e, 0x1c, 0xea, 0xa6, 0xef, 0xd9, 0x84, 0x62, 0x85, 0x93, 0xb4, 0x0c, 0xa1, 0xe1, 0x9c, 0x7d, 0x77, 0x3d, 0x00, 0xc1, 0x44, 0xc5, 0x25, 0xac, 0x61, 0x9d, 0x18, 0xc8, 0x4a, 0x3f, 0x47, 0x18, 0xe2, 0x44, 0x8b, 0x2f, 0xe3, 0x24, 0xd9, 0xcc, 0xda, 0x27, 0x10 }; static const u8 T10[] = { 0x25, 0x19, 0x49, 0x8e, 0x80, 0xf1, 0x47, 0x8f, 0x37, 0xba, 0x55, 0xbd, 0x6d, 0x27, 0x61, 0x8c }; /* Test Case 11 */ # define K11 K10 # define P11 P10 # define A11 A10 static const u8 IV11[] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad }; static const u8 C11[] = { 0x0f, 0x10, 0xf5, 0x99, 0xae, 0x14, 0xa1, 0x54, 0xed, 0x24, 0xb3, 0x6e, 0x25, 0x32, 0x4d, 0xb8, 0xc5, 0x66, 0x63, 0x2e, 0xf2, 0xbb, 0xb3, 0x4f, 0x83, 0x47, 0x28, 0x0f, 0xc4, 0x50, 0x70, 0x57, 0xfd, 0xdc, 0x29, 0xdf, 0x9a, 0x47, 0x1f, 0x75, 0xc6, 0x65, 0x41, 0xd4, 0xd4, 0xda, 0xd1, 0xc9, 0xe9, 0x3a, 0x19, 0xa5, 0x8e, 0x8b, 0x47, 0x3f, 0xa0, 0xf0, 0x62, 0xf7 }; static const u8 T11[] = { 0x65, 0xdc, 0xc5, 0x7f, 0xcf, 0x62, 0x3a, 0x24, 0x09, 0x4f, 0xcc, 0xa4, 0x0d, 0x35, 0x33, 0xf8 }; /* Test Case 12 */ # define K12 K11 # define P12 P11 # define A12 A11 static const u8 IV12[] = { 0x93, 0x13, 0x22, 0x5d, 0xf8, 0x84, 0x06, 0xe5, 0x55, 0x90, 0x9c, 0x5a, 0xff, 0x52, 0x69, 0xaa, 0x6a, 0x7a, 0x95, 0x38, 0x53, 0x4f, 0x7d, 0xa1, 0xe4, 0xc3, 0x03, 0xd2, 0xa3, 0x18, 0xa7, 0x28, 0xc3, 0xc0, 0xc9, 0x51, 0x56, 0x80, 0x95, 0x39, 0xfc, 0xf0, 0xe2, 0x42, 0x9a, 0x6b, 0x52, 0x54, 0x16, 0xae, 0xdb, 0xf5, 0xa0, 0xde, 0x6a, 0x57, 0xa6, 0x37, 0xb3, 0x9b }; static const u8 C12[] = { 0xd2, 0x7e, 0x88, 0x68, 0x1c, 0xe3, 0x24, 0x3c, 0x48, 0x30, 0x16, 0x5a, 0x8f, 0xdc, 0xf9, 0xff, 0x1d, 0xe9, 0xa1, 0xd8, 0xe6, 0xb4, 0x47, 0xef, 0x6e, 0xf7, 0xb7, 0x98, 0x28, 0x66, 0x6e, 0x45, 0x81, 0xe7, 0x90, 0x12, 0xaf, 0x34, 0xdd, 0xd9, 0xe2, 0xf0, 0x37, 0x58, 0x9b, 0x29, 0x2d, 0xb3, 0xe6, 0x7c, 0x03, 0x67, 0x45, 0xfa, 0x22, 0xe7, 0xe9, 0xb7, 0x37, 0x3b }; static const u8 T12[] = { 0xdc, 0xf5, 0x66, 0xff, 0x29, 0x1c, 0x25, 0xbb, 0xb8, 0x56, 0x8f, 0xc3, 0xd3, 0x76, 0xa6, 0xd9 }; /* Test Case 13 */ static const u8 K13[32], P13[] = { 0 }, A13[] = { 0 }, IV13[12], C13[] = { 0 }; static const u8 T13[] = { 0x53, 0x0f, 0x8a, 0xfb, 0xc7, 0x45, 0x36, 0xb9, 0xa9, 0x63, 0xb4, 0xf1, 0xc4, 0xcb, 0x73, 0x8b }; /* Test Case 14 */ # define K14 K13 # define A14 A13 static const u8 P14[16], IV14[12]; static const u8 C14[] = { 0xce, 0xa7, 0x40, 0x3d, 0x4d, 0x60, 0x6b, 0x6e, 0x07, 0x4e, 0xc5, 0xd3, 0xba, 0xf3, 0x9d, 0x18 }; static const u8 T14[] = { 0xd0, 0xd1, 0xc8, 0xa7, 0x99, 0x99, 0x6b, 0xf0, 0x26, 0x5b, 0x98, 0xb5, 0xd4, 0x8a, 0xb9, 0x19 }; /* Test Case 15 */ # define A15 A14 static const u8 K15[] = { 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08, 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08 }; static const u8 P15[] = { 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, 0xba, 0x63, 0x7b, 0x39, 0x1a, 0xaf, 0xd2, 0x55 }; static const u8 IV15[] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88 }; static const u8 C15[] = { 0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07, 0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d, 0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9, 0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa, 0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d, 0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38, 0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a, 0xbc, 0xc9, 0xf6, 0x62, 0x89, 0x80, 0x15, 0xad }; static const u8 T15[] = { 0xb0, 0x94, 0xda, 0xc5, 0xd9, 0x34, 0x71, 0xbd, 0xec, 0x1a, 0x50, 0x22, 0x70, 0xe3, 0xcc, 0x6c }; /* Test Case 16 */ # define K16 K15 # define IV16 IV15 static const u8 P16[] = { 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, 0xba, 0x63, 0x7b, 0x39 }; static const u8 A16[] = { 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef, 0xab, 0xad, 0xda, 0xd2 }; static const u8 C16[] = { 0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07, 0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d, 0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9, 0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa, 0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d, 0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38, 0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a, 0xbc, 0xc9, 0xf6, 0x62 }; static const u8 T16[] = { 0x76, 0xfc, 0x6e, 0xce, 0x0f, 0x4e, 0x17, 0x68, 0xcd, 0xdf, 0x88, 0x53, 0xbb, 0x2d, 0x55, 0x1b }; /* Test Case 17 */ # define K17 K16 # define P17 P16 # define A17 A16 static const u8 IV17[] = { 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad }; static const u8 C17[] = { 0xc3, 0x76, 0x2d, 0xf1, 0xca, 0x78, 0x7d, 0x32, 0xae, 0x47, 0xc1, 0x3b, 0xf1, 0x98, 0x44, 0xcb, 0xaf, 0x1a, 0xe1, 0x4d, 0x0b, 0x97, 0x6a, 0xfa, 0xc5, 0x2f, 0xf7, 0xd7, 0x9b, 0xba, 0x9d, 0xe0, 0xfe, 0xb5, 0x82, 0xd3, 0x39, 0x34, 0xa4, 0xf0, 0x95, 0x4c, 0xc2, 0x36, 0x3b, 0xc7, 0x3f, 0x78, 0x62, 0xac, 0x43, 0x0e, 0x64, 0xab, 0xe4, 0x99, 0xf4, 0x7c, 0x9b, 0x1f }; static const u8 T17[] = { 0x3a, 0x33, 0x7d, 0xbf, 0x46, 0xa7, 0x92, 0xc4, 0x5e, 0x45, 0x49, 0x13, 0xfe, 0x2e, 0xa8, 0xf2 }; /* Test Case 18 */ # define K18 K17 # define P18 P17 # define A18 A17 static const u8 IV18[] = { 0x93, 0x13, 0x22, 0x5d, 0xf8, 0x84, 0x06, 0xe5, 0x55, 0x90, 0x9c, 0x5a, 0xff, 0x52, 0x69, 0xaa, 0x6a, 0x7a, 0x95, 0x38, 0x53, 0x4f, 0x7d, 0xa1, 0xe4, 0xc3, 0x03, 0xd2, 0xa3, 0x18, 0xa7, 0x28, 0xc3, 0xc0, 0xc9, 0x51, 0x56, 0x80, 0x95, 0x39, 0xfc, 0xf0, 0xe2, 0x42, 0x9a, 0x6b, 0x52, 0x54, 0x16, 0xae, 0xdb, 0xf5, 0xa0, 0xde, 0x6a, 0x57, 0xa6, 0x37, 0xb3, 0x9b }; static const u8 C18[] = { 0x5a, 0x8d, 0xef, 0x2f, 0x0c, 0x9e, 0x53, 0xf1, 0xf7, 0x5d, 0x78, 0x53, 0x65, 0x9e, 0x2a, 0x20, 0xee, 0xb2, 0xb2, 0x2a, 0xaf, 0xde, 0x64, 0x19, 0xa0, 0x58, 0xab, 0x4f, 0x6f, 0x74, 0x6b, 0xf4, 0x0f, 0xc0, 0xc3, 0xb7, 0x80, 0xf2, 0x44, 0x45, 0x2d, 0xa3, 0xeb, 0xf1, 0xc5, 0xd8, 0x2c, 0xde, 0xa2, 0x41, 0x89, 0x97, 0x20, 0x0e, 0xf8, 0x2e, 0x44, 0xae, 0x7e, 0x3f }; static const u8 T18[] = { 0xa4, 0x4a, 0x82, 0x66, 0xee, 0x1c, 0x8e, 0xb0, 0xc8, 0xb5, 0xd4, 0xcf, 0x5a, 0xe9, 0xf1, 0x9a }; /* Test Case 19 */ # define K19 K1 # define P19 P1 # define IV19 IV1 # define C19 C1 static const u8 A19[] = { 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a, 0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72, 0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25, 0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, 0xba, 0x63, 0x7b, 0x39, 0x1a, 0xaf, 0xd2, 0x55, 0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07, 0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d, 0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9, 0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa, 0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d, 0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38, 0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a, 0xbc, 0xc9, 0xf6, 0x62, 0x89, 0x80, 0x15, 0xad }; static const u8 T19[] = { 0x5f, 0xea, 0x79, 0x3a, 0x2d, 0x6f, 0x97, 0x4d, 0x37, 0xe6, 0x8e, 0x0c, 0xb8, 0xff, 0x94, 0x92 }; /* Test Case 20 */ # define K20 K1 # define A20 A1 /* this results in 0xff in counter LSB */ static const u8 IV20[64] = { 0xff, 0xff, 0xff, 0xff }; static const u8 P20[288]; static const u8 C20[] = { 0x56, 0xb3, 0x37, 0x3c, 0xa9, 0xef, 0x6e, 0x4a, 0x2b, 0x64, 0xfe, 0x1e, 0x9a, 0x17, 0xb6, 0x14, 0x25, 0xf1, 0x0d, 0x47, 0xa7, 0x5a, 0x5f, 0xce, 0x13, 0xef, 0xc6, 0xbc, 0x78, 0x4a, 0xf2, 0x4f, 0x41, 0x41, 0xbd, 0xd4, 0x8c, 0xf7, 0xc7, 0x70, 0x88, 0x7a, 0xfd, 0x57, 0x3c, 0xca, 0x54, 0x18, 0xa9, 0xae, 0xff, 0xcd, 0x7c, 0x5c, 0xed, 0xdf, 0xc6, 0xa7, 0x83, 0x97, 0xb9, 0xa8, 0x5b, 0x49, 0x9d, 0xa5, 0x58, 0x25, 0x72, 0x67, 0xca, 0xab, 0x2a, 0xd0, 0xb2, 0x3c, 0xa4, 0x76, 0xa5, 0x3c, 0xb1, 0x7f, 0xb4, 0x1c, 0x4b, 0x8b, 0x47, 0x5c, 0xb4, 0xf3, 0xf7, 0x16, 0x50, 0x94, 0xc2, 0x29, 0xc9, 0xe8, 0xc4, 0xdc, 0x0a, 0x2a, 0x5f, 0xf1, 0x90, 0x3e, 0x50, 0x15, 0x11, 0x22, 0x13, 0x76, 0xa1, 0xcd, 0xb8, 0x36, 0x4c, 0x50, 0x61, 0xa2, 0x0c, 0xae, 0x74, 0xbc, 0x4a, 0xcd, 0x76, 0xce, 0xb0, 0xab, 0xc9, 0xfd, 0x32, 0x17, 0xef, 0x9f, 0x8c, 0x90, 0xbe, 0x40, 0x2d, 0xdf, 0x6d, 0x86, 0x97, 0xf4, 0xf8, 0x80, 0xdf, 0xf1, 0x5b, 0xfb, 0x7a, 0x6b, 0x28, 0x24, 0x1e, 0xc8, 0xfe, 0x18, 0x3c, 0x2d, 0x59, 0xe3, 0xf9, 0xdf, 0xff, 0x65, 0x3c, 0x71, 0x26, 0xf0, 0xac, 0xb9, 0xe6, 0x42, 0x11, 0xf4, 0x2b, 0xae, 0x12, 0xaf, 0x46, 0x2b, 0x10, 0x70, 0xbe, 0xf1, 0xab, 0x5e, 0x36, 0x06, 0x87, 0x2c, 0xa1, 0x0d, 0xee, 0x15, 0xb3, 0x24, 0x9b, 0x1a, 0x1b, 0x95, 0x8f, 0x23, 0x13, 0x4c, 0x4b, 0xcc, 0xb7, 0xd0, 0x32, 0x00, 0xbc, 0xe4, 0x20, 0xa2, 0xf8, 0xeb, 0x66, 0xdc, 0xf3, 0x64, 0x4d, 0x14, 0x23, 0xc1, 0xb5, 0x69, 0x90, 0x03, 0xc1, 0x3e, 0xce, 0xf4, 0xbf, 0x38, 0xa3, 0xb6, 0x0e, 0xed, 0xc3, 0x40, 0x33, 0xba, 0xc1, 0x90, 0x27, 0x83, 0xdc, 0x6d, 0x89, 0xe2, 0xe7, 0x74, 0x18, 0x8a, 0x43, 0x9c, 0x7e, 0xbc, 0xc0, 0x67, 0x2d, 0xbd, 0xa4, 0xdd, 0xcf, 0xb2, 0x79, 0x46, 0x13, 0xb0, 0xbe, 0x41, 0x31, 0x5e, 0xf7, 0x78, 0x70, 0x8a, 0x70, 0xee, 0x7d, 0x75, 0x16, 0x5c }; static const u8 T20[] = { 0x8b, 0x30, 0x7f, 0x6b, 0x33, 0x28, 0x6d, 0x0a, 0xb0, 0x26, 0xa9, 0xed, 0x3f, 0xe1, 0xe8, 0x5f }; #define GCM128_TEST_VECTOR(n) \ { \ {sizeof(K##n), K##n}, \ {sizeof(IV##n), IV##n}, \ {sizeof(A##n), A##n}, \ {sizeof(P##n), P##n}, \ {sizeof(C##n), C##n}, \ {sizeof(T##n), T##n} \ } static struct gcm128_data { const SIZED_DATA K; const SIZED_DATA IV; const SIZED_DATA A; const SIZED_DATA P; const SIZED_DATA C; const SIZED_DATA T; } gcm128_vectors[] = { GCM128_TEST_VECTOR(1), GCM128_TEST_VECTOR(2), GCM128_TEST_VECTOR(3), GCM128_TEST_VECTOR(4), GCM128_TEST_VECTOR(5), GCM128_TEST_VECTOR(6), GCM128_TEST_VECTOR(7), GCM128_TEST_VECTOR(8), GCM128_TEST_VECTOR(9), GCM128_TEST_VECTOR(10), GCM128_TEST_VECTOR(11), GCM128_TEST_VECTOR(12), GCM128_TEST_VECTOR(13), GCM128_TEST_VECTOR(14), GCM128_TEST_VECTOR(15), GCM128_TEST_VECTOR(16), GCM128_TEST_VECTOR(17), GCM128_TEST_VECTOR(18), GCM128_TEST_VECTOR(19), GCM128_TEST_VECTOR(20) }; static int test_gcm128(int idx) { unsigned char out[512]; SIZED_DATA K = gcm128_vectors[idx].K; SIZED_DATA IV = gcm128_vectors[idx].IV; SIZED_DATA A = gcm128_vectors[idx].A; SIZED_DATA P = gcm128_vectors[idx].P; SIZED_DATA C = gcm128_vectors[idx].C; SIZED_DATA T = gcm128_vectors[idx].T; GCM128_CONTEXT ctx; AES_KEY key; /* Size 1 inputs are special-cased to signal NULL. */ if (A.size == 1) A.data = NULL; if (P.size == 1) P.data = NULL; if (C.size == 1) C.data = NULL; AES_set_encrypt_key(K.data, K.size * 8, &key); CRYPTO_gcm128_init(&ctx, &key, (block128_f)AES_encrypt); CRYPTO_gcm128_setiv(&ctx, IV.data, IV.size); memset(out, 0, P.size); if (A.data != NULL) CRYPTO_gcm128_aad(&ctx, A.data, A.size); if (P.data != NULL) if (!TEST_int_ge(CRYPTO_gcm128_encrypt( &ctx, P.data, out, P.size), 0)) return 0; if (!TEST_false(CRYPTO_gcm128_finish(&ctx, T.data, 16)) || (C.data != NULL && !TEST_mem_eq(out, P.size, C.data, P.size))) return 0; CRYPTO_gcm128_setiv(&ctx, IV.data, IV.size); memset(out, 0, P.size); if (A.data != NULL) CRYPTO_gcm128_aad(&ctx, A.data, A.size); if (C.data != NULL) CRYPTO_gcm128_decrypt(&ctx, C.data, out, P.size); if (!TEST_false(CRYPTO_gcm128_finish(&ctx, T.data, 16)) || (P.data != NULL && !TEST_mem_eq(out, P.size, P.data, P.size))) return 0; return 1; } int setup_tests(void) { ADD_ALL_TESTS(test_aes_cts128, OSSL_NELEM(aes_cts128_vectors)); ADD_ALL_TESTS(test_aes_cts128_nist, OSSL_NELEM(aes_cts128_vectors)); ADD_ALL_TESTS(test_gcm128, OSSL_NELEM(gcm128_vectors)); return 1; }
jens-maus/amissl
openssl/test/modes_internal_test.c
C
bsd-3-clause
29,892
<?php /** * @package ElkArte Forum * @copyright ElkArte Forum contributors * @license BSD http://opensource.org/licenses/BSD-3-Clause (see accompanying LICENSE.txt file) * * This file contains code covered by: * copyright: 2011 Simple Machines (http://www.simplemachines.org) * * @version 2.0 dev * */ /** * Template for the section that allows to modify weights for search settings * in admin panel. */ function template_modify_weights() { global $context, $scripturl, $txt, $modSettings; echo ' <div id="admincenter"> <form id="admin_form_wrapper" action="', $scripturl, '?action=admin;area=managesearch;sa=weights" method="post" accept-charset="UTF-8"> <h2 class="category_header"> <a class="hdicon cat_img_helptopics help" href="', $scripturl, '?action=quickhelp;help=search_weight_commonheader" onclick="return reqOverlayDiv(this.href);" title="', $txt['help'], '"></a> ', $txt['search_weights'], ' </h2>'; if (!empty($modSettings['search_index']) && (stripos($modSettings['search_index'], 'sphinx') === 0)) { echo ' <div class="content"> <div class="infobox">', $txt['search_weights_sphinx'], ' </div> </div>'; } echo ' <div class="content"> <dl class="settings large_caption"> <dt> <a href="', $scripturl, '?action=quickhelp;help=search_weight_frequency" onclick="return reqOverlayDiv(this.href);" class="helpicon i-help"><s>', $txt['help'], '</s></a> <label for="weight1_val">', $txt['search_weight_frequency'], ':</label> </dt> <dd> <span class="search_weight"><input type="text" name="search_weight_frequency" id="weight1_val" value="', empty($modSettings['search_weight_frequency']) ? '0' : $modSettings['search_weight_frequency'], '" onchange="calculateNewValues()" size="3" class="input_text" /></span> <span id="weight1" class="search_weight">', $context['relative_weights']['search_weight_frequency'], '%</span> </dd> <dt> <a href="', $scripturl, '?action=quickhelp;help=search_weight_age" onclick="return reqOverlayDiv(this.href);" class="helpicon i-help"><s>', $txt['help'], '</s></a> <label for="weight2_val">', $txt['search_weight_age'], ':</label> </dt> <dd> <span class="search_weight"><input type="text" name="search_weight_age" id="weight2_val" value="', empty($modSettings['search_weight_age']) ? '0' : $modSettings['search_weight_age'], '" onchange="calculateNewValues()" size="3" class="input_text" /></span> <span id="weight2" class="search_weight">', $context['relative_weights']['search_weight_age'], '%</span> </dd> <dt> <a href="', $scripturl, '?action=quickhelp;help=search_weight_length" onclick="return reqOverlayDiv(this.href);" class="helpicon i-help"><s>', $txt['help'], '</s></a> <label for="weight3_val">', $txt['search_weight_length'], ':</label> </dt> <dd> <span class="search_weight"><input type="text" name="search_weight_length" id="weight3_val" value="', empty($modSettings['search_weight_length']) ? '0' : $modSettings['search_weight_length'], '" onchange="calculateNewValues()" size="3" class="input_text" /></span> <span id="weight3" class="search_weight">', $context['relative_weights']['search_weight_length'], '%</span> </dd> <dt> <a href="', $scripturl, '?action=quickhelp;help=search_weight_subject" onclick="return reqOverlayDiv(this.href);" class="helpicon i-help"><s>', $txt['help'], '</s></a> <label for="weight4_val">', $txt['search_weight_subject'], ':</label> </dt> <dd> <span class="search_weight"><input type="text" name="search_weight_subject" id="weight4_val" value="', empty($modSettings['search_weight_subject']) ? '0' : $modSettings['search_weight_subject'], '" onchange="calculateNewValues()" size="3" class="input_text" /></span> <span id="weight4" class="search_weight">', $context['relative_weights']['search_weight_subject'], '%</span> </dd> <dt> <a href="', $scripturl, '?action=quickhelp;help=search_weight_first_message" onclick="return reqOverlayDiv(this.href);" class="helpicon i-help"><s>', $txt['help'], '</s></a> <label for="weight5_val">', $txt['search_weight_first_message'], ':</label> </dt> <dd> <span class="search_weight"><input type="text" name="search_weight_first_message" id="weight5_val" value="', empty($modSettings['search_weight_first_message']) ? '0' : $modSettings['search_weight_first_message'], '" onchange="calculateNewValues()" size="3" class="input_text" /></span> <span id="weight5" class="search_weight">', $context['relative_weights']['search_weight_first_message'], '%</span> </dd> <dt> <a href="', $scripturl, '?action=quickhelp;help=search_weight_sticky" onclick="return reqOverlayDiv(this.href);" class="helpicon i-help"><s>', $txt['help'], '</s></a> <label for="weight6_val">', $txt['search_weight_sticky'], ':</label> </dt> <dd> <span class="search_weight"><input type="text" name="search_weight_sticky" id="weight6_val" value="', empty($modSettings['search_weight_sticky']) ? '0' : $modSettings['search_weight_sticky'], '" onchange="calculateNewValues()" size="3" class="input_text" /></span> <span id="weight6" class="search_weight">', $context['relative_weights']['search_weight_sticky'], '%</span> </dd> <dt> <a href="', $scripturl, '?action=quickhelp;help=search_weight_likes" onclick="return reqOverlayDiv(this.href);" class="helpicon i-help"><s>', $txt['help'], '</s></a> <label for="weight7_val"> ', $txt['search_weight_likes'], ':</label> </dt> <dd> <span class="search_weight"><input type="text" name="search_weight_likes" id="weight7_val" value="', empty($modSettings['search_weight_likes']) ? '0' : $modSettings['search_weight_likes'], '" onchange="calculateNewValues()" size="3" class="input_text" /></span> <span id="weight7" class="search_weight">', $context['relative_weights']['search_weight_likes'], '%</span> </dd> <dt> <strong>', $txt['search_weights_total'], '</strong> </dt> <dd> <span id="weighttotal" class="search_weight"><strong>', $context['relative_weights']['total'], '</strong></span> <span class="search_weight"><strong>&nbsp;&nbsp;&nbsp;&nbsp;100%</strong></span> </dd> </dl> <div class="submitbutton"> <input type="submit" name="save" value="', $txt['search_weights_save'], '" /> <input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" /> <input type="hidden" name="', $context['admin-msw_token_var'], '" value="', $context['admin-msw_token'], '" /> </div> </div> </form> </div>'; } /** * Template for the section to select a search method * in search area of admin panel. */ function template_select_search_method() { global $context, $scripturl, $txt, $modSettings; echo ' <div id="admincenter"> <h2 class="category_header">', $txt['search_method'], '</h2> <div class="infobox"> <a href="', $scripturl, '?action=quickhelp;help=search_why_use_index" onclick="return reqOverlayDiv(this.href);">', $txt['search_create_index_why'], '</a> </div> <form id="admin_form_wrapper" action="', $scripturl, '?action=admin;area=managesearch;sa=method" method="post" accept-charset="UTF-8"> <h2 class="category_header">', $txt['search_method'], '</h2> <div class="content"> <dl class="settings"> '; if (!empty($context['table_info'])) { echo ' <dt> <label>', $txt['search_method_messages_table_space'], ':</label> </dt> <dd> ', $context['table_info']['data_length'], ' </dd> <dt> <label>', $txt['search_method_messages_index_space'], ':</label> </dt> <dd> ', $context['table_info']['index_length'], ' </dd>'; } echo ' </dl> ', $context['double_index'] ? '<div class="warningbox"> ' . $txt['search_double_index'] . '</div>' : '', ' <fieldset id="search_index" class="search_settings"> <legend>', $txt['search_index'], '</legend> <dl> <dt> <input type="radio" id="search_index_none" name="search_index" value="none"', empty($modSettings['search_index']) ? ' checked="checked"' : '', ' /> <label for="search_index_none">', $txt['search_index_none'], '</label> </dt>'; if ($context['supports_fulltext']) { echo ' <dt> <input type="radio" id="search_index_full" name="search_index" value="fulltext"', !empty($modSettings['search_index']) && $modSettings['search_index'] == 'fulltext' ? ' checked="checked"' : '', empty($context['fulltext_index']) ? ' onclick="alert(\'' . $txt['search_method_fulltext_warning'] . '\'); selectRadioByName(this.form.search_index, \'none\');"' : '', ' /> <label for="search_index_full">', $txt['search_method_fulltext_index'], '</label> </dt> <dd> <p>'; if (empty($context['fulltext_index']) && empty($context['cannot_create_fulltext'])) { echo ' <strong>', $txt['search_index_label'], ':</strong> ', $txt['search_method_no_index_exists'], ' <a class="linkbutton" href="', $scripturl, '?action=admin;area=managesearch;sa=createfulltext;', $context['session_var'], '=', $context['session_id'], ';', $context['admin-msm_token_var'], '=', $context['admin-msm_token'], '">', $txt['search_method_fulltext_create'], '</a>'; } elseif (empty($context['fulltext_index']) && !empty($context['cannot_create_fulltext'])) { echo ' <strong>', $txt['search_index_label'], ':</strong> ', $txt['search_method_fulltext_cannot_create']; } else { echo ' <strong>', $txt['search_index_label'], ':</strong> ', $txt['search_method_index_already_exists'], ' <a class="linkbutton" href="', $scripturl, '?action=admin;area=managesearch;sa=removefulltext;', $context['session_var'], '=', $context['session_id'], ';', $context['admin-msm_token_var'], '=', $context['admin-msm_token'], '">', $txt['search_method_fulltext_remove'], '</a><br /> <strong>', $txt['search_index_size'], ':</strong> ', $context['table_info']['fulltext_length']; } echo ' </p> </dd>'; } echo ' <dt> <input type="radio" id="search_index_custom" name="search_index" value="custom"', !empty($modSettings['search_index']) && $modSettings['search_index'] == 'custom' ? ' checked="checked"' : '', $context['custom_index'] ? '' : ' onclick="alert(\'' . $txt['search_index_custom_warning'] . '\'); selectRadioByName(this.form.search_index, \'none\');"', ' /> <label for="search_index_custom">', $txt['search_index_custom'], '</label> </dt> <dd> <p>'; if ($context['custom_index']) { echo ' <strong>', $txt['search_index_label'], ':</strong> ', $txt['search_method_index_already_exists'], ' <a class="linkbutton" href="', $scripturl, '?action=admin;area=managesearch;sa=removecustom;', $context['session_var'], '=', $context['session_id'], ';', $context['admin-msm_token_var'], '=', $context['admin-msm_token'], '">', $txt['search_index_custom_remove'], '</a><br /> <strong>', $txt['search_index_size'], ':</strong> ', $context['table_info']['custom_index_length']; } elseif ($context['partial_custom_index']) { echo ' <strong>', $txt['search_index_label'], ':</strong> ', $txt['search_method_index_partial'], ' <a class="linkbutton" href="', $scripturl, '?action=admin;area=managesearch;sa=removecustom;', $context['session_var'], '=', $context['session_id'], ';', $context['admin-msm_token_var'], '=', $context['admin-msm_token'], '">', $txt['search_index_custom_remove'], '</a> <a class="linkbutton" href="', $scripturl, '?action=admin;area=managesearch;sa=createmsgindex;resume;', $context['session_var'], '=', $context['session_id'], ';', $context['admin-msm_token_var'], '=', $context['admin-msm_token'], '">', $txt['search_index_custom_resume'], '</a><br /> <strong>', $txt['search_index_size'], ':</strong> ', $context['table_info']['custom_index_length']; } else { echo ' <strong>', $txt['search_index_label'], ':</strong> ', $txt['search_method_no_index_exists'], ' <a class="linkbutton" href="', $scripturl, '?action=admin;area=managesearch;sa=createmsgindex;', $context['session_var'], '=', $context['session_id'], '">', $txt['search_index_create_custom'], '</a>'; } echo ' </p> </dd>'; // Any search API's to include foreach ($context['search_apis'] as $api) { if (empty($api['label']) || $api['has_template']) { continue; } echo ' <dt> <input type="radio" id="search_index_', $api['setting_index'], '" name="search_index" value="', $api['setting_index'], '"', !empty($modSettings['search_index']) && $modSettings['search_index'] == $api['setting_index'] ? ' checked="checked"' : '', ' /> <label for="search_index_', $api['setting_index'], '">', $api['label'], '</label> </dt>'; if ($api['desc']) { echo ' <dd> <p>', $api['desc'], '</p> </dd>'; } } echo ' </dl> </fieldset> <fieldset id="search_method" class="search_settings"> <legend>', $txt['search_method'], '</legend> <input type="checkbox" name="search_force_index" id="search_force_index_check" value="1"', empty($modSettings['search_force_index']) ? '' : ' checked="checked"', ' /><label for="search_force_index_check">', $txt['search_force_index'], '</label><br /> <input type="checkbox" name="search_match_words" id="search_match_words_check" value="1"', empty($modSettings['search_match_words']) ? '' : ' checked="checked"', ' /><label for="search_match_words_check">', $txt['search_match_words'], '</label> </fieldset> </div> <div class="submitbutton"> <input type="submit" name="save" value="', $txt['search_method_save'], '" /> <input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" /> <input type="hidden" name="', $context['admin-msmpost_token_var'], '" value="', $context['admin-msmpost_token'], '" /> </div> </form> </div> <script> showhideSearchMethod(); $("#search_index").find("input").on("change", function() { showhideSearchMethod(); }); </script>'; } /** * Template to show progress during creation of a search index. */ function template_create_index_progress() { global $context, $scripturl, $txt; echo ' <div id="admincenter"> <form action="', $scripturl, '?action=admin;area=managesearch;sa=createmsgindex;step=1" name="autoSubmit" method="post" accept-charset="UTF-8"> <h2 class="category_header">', $txt['search_create_index'], '</h2> <div class="content"> <div> <p>', $txt['search_create_index_not_ready'], '</p> <div class="progress_bar"> <div class="green_percent" style="width: ', $context['percentage'], '%;">', $context['percentage'], '%</div> </div> </div> <div class="submitbutton"> <input type="submit" name="cont" value="', $txt['search_create_index_continue'], '" /> <input type="hidden" name="step" value="', $context['step'], '" /> <input type="hidden" name="start" value="', $context['start'], '" /> <input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" /> </div> </div> </form> </div> <script> doAutoSubmit(5, ', JavaScriptEscape($txt['search_create_index_continue']), '); </script>'; } /** * Used to show the completion of the search index creation */ function template_create_index_done() { global $scripturl, $txt; echo ' <div id="admincenter"> <h2 class="category_header">', $txt['search_create_index'], '</h2> <div class="content"> <p>', $txt['search_create_index_done'], '</p> <div class="submitbutton"> <strong><a class="linkbutton" href="', $scripturl, '?action=admin;area=managesearch;sa=method">', $txt['search_create_index_done_link'], '</a></strong> </div> </div> </div>'; } /** * Add or edit a search engine spider. */ function template_spider_edit() { global $context, $scripturl, $txt; echo ' <div id="admincenter"> <form id="admin_form_wrapper" action="', $scripturl, '?action=admin;area=sengines;sa=editspiders;sid=', $context['spider']['id'], '" method="post" accept-charset="UTF-8"> <h2 class="category_header">', $context['page_title'], '</h2> <div class="information"> ', $txt['add_spider_desc'], ' </div> <div class="content"> <dl class="settings"> <dt> <label for="spider_name">', $txt['spider_name'], ':</label><br /> <span class="smalltext">', $txt['spider_name_desc'], '</span> </dt> <dd> <input type="text" name="spider_name" id="spider_name" value="', $context['spider']['name'], '" class="input_text" /> </dd> <dt> <label for="spider_agent">', $txt['spider_agent'], ':</label><br /> <span class="smalltext">', $txt['spider_agent_desc'], '</span> </dt> <dd> <input type="text" name="spider_agent" id="spider_agent" value="', $context['spider']['agent'], '" class="input_text" /> </dd> <dt> <label for="spider_ip">', $txt['spider_ip_info'], ':</label><br /> <span class="smalltext">', $txt['spider_ip_info_desc'], '</span> </dt> <dd> <textarea name="spider_ip" id="spider_ip" rows="4" cols="20">', $context['spider']['ip_info'], '</textarea> </dd> </dl> <div class="submitbutton"> <input type="submit" name="save" value="', $context['page_title'], '" /> <input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" /> <input type="hidden" name="', $context['admin-ses_token_var'], '" value="', $context['admin-ses_token'], '" /> </div> </div> </form> </div>'; } /** * Spider logs page. */ function template_show_spider_logs() { global $context, $txt, $scripturl; echo ' <div id="admincenter">'; // Standard fields. template_show_list('spider_logs'); echo ' <form id="admin_form_wrapper" action="', $scripturl, '?action=admin;area=sengines;sa=logs" method="post" accept-charset="UTF-8"> <h2 class="category_header">', $txt['spider_logs_delete'], '</h2> <div class="content"> <p> <label for="older">', sprintf($txt['spider_stats_delete_older'], '<input type="text" name="older" id="older" value="7" size="3" class="input_text" />'), '</label> </p> <div class="submitbutton"> <input type="submit" name="delete_entries" value="', $txt['spider_logs_delete_submit'], '" onclick="if (document.getElementById(\'older\').value &lt; 1 &amp;&amp; !confirm(\'' . addcslashes($txt['spider_logs_delete_confirm'], "'") . '\')) return false; return true;" /> <input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" /> <input type="hidden" name="', $context['admin-sl_token_var'], '" value="', $context['admin-sl_token'], '" /> </div> </div> </form> </div>'; } /** * Spider stats section. */ function template_show_spider_stats() { global $context, $txt, $scripturl; echo ' <div id="admincenter">'; // Standard fields. template_show_list('spider_stat_list'); echo ' <form id="admin_form_wrapper" action="', $scripturl, '?action=admin;area=sengines;sa=stats" method="post" accept-charset="UTF-8"> <h2 class="category_header">', $txt['spider_logs_delete'], '</h2> <div class="content"> <p> <label for="older">', sprintf($txt['spider_stats_delete_older'], '<input type="text" name="older" id="older" value="7" size="3" class="input_text" />'), '</label> </p> <div class="submitbutton"> <input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" /> <input type="hidden" name="', $context['admin-ss_token_var'], '" value="', $context['admin-ss_token'], '" /> <input type="submit" name="delete_entries" value="', $txt['spider_logs_delete_submit'], '" onclick="if (document.getElementById(\'older\').value &lt; 1 &amp;&amp; !confirm(\'' . addcslashes($txt['spider_logs_delete_confirm'], "'") . '\')) return false; return true;" /> </div> </div> </form> </div>'; } /** * The settings page for sphinx search */ function template_manage_sphinx() { global $context, $modSettings, $txt, $scripturl; echo ' <div id="admincenter"> <form id="admin_form_wrapper" action="', $scripturl, '?action=admin;area=managesearch;sa=managesphinx;save=1" method="post" accept-charset="UTF-8" name="create_index"> <h2 class="category_header">', $context['page_title'], '</h2>'; // any results to show? if (!empty($context['settings_message'])) { echo ' <div class="', (empty($context['error_type']) ? 'successbox' : ($context['error_type'] !== 'serious' ? 'warningbox' : 'errorbox')), '" id="errors"> <ul> <li>', implode('</li><li>', $context['settings_message']), '</li> </ul> </div>'; } echo ' <div class="information"> ', $context['page_description'], ' </div> <div class="content"> <dl class="settings"> <dt> <label for="sphinx_index_prefix_input">', $txt['sphinx_index_prefix'], '</label><br /> <span class="smalltext">', $txt['sphinx_index_prefix_desc'], '</span> </dt> <dd> <input type="text" name="sphinx_index_prefix" id="sphinx_index_prefix_input" value="', isset($modSettings['sphinx_index_prefix']) ? $modSettings['sphinx_index_prefix'] : 'elkarte', '" size="65" /> </dd> <dt> <label for="sphinx_data_path_input">', $txt['sphinx_index_data_path'], '</label><br /> <span class="smalltext">', $txt['sphinx_index_data_path_desc'], '</span> </dt> <dd> <input type="text" name="sphinx_data_path" id="sphinx_data_path_input" value="', isset($modSettings['sphinx_data_path']) ? $modSettings['sphinx_data_path'] : '/var/sphinx/data', '" size="65" /> </dd> <dt> <label for="sphinx_log_path_input">', $txt['sphinx_log_file_path'], '</label><br /> <span class="smalltext">', $txt['sphinx_log_file_path_desc'], '</span> </dt> <dd> <input type="text" name="sphinx_log_path" id="sphinx_log_path_input" value="', isset($modSettings['sphinx_log_path']) ? $modSettings['sphinx_log_path'] : '/var/sphinx/log', '" size="65" /> </dd> <dt> <label for="sphinx_stopword_path_input">', $txt['sphinx_stop_word_path'], '</label><br /> <span class="smalltext">', $txt['sphinx_stop_word_path_desc'], '</span> </dt> <dd> <input type="text" name="sphinx_stopword_path" id="sphinx_stopword_path_input" value="', isset($modSettings['sphinx_stopword_path']) ? $modSettings['sphinx_stopword_path'] : '', '" size="65" /> </dd> <dt> <label for="sphinx_indexer_mem_input">', $txt['sphinx_memory_limit'], '</label><br /> <span class="smalltext">', $txt['sphinx_memory_limit_desc'], '</span> </dt> <dd> <input type="text" name="sphinx_indexer_mem" id="sphinx_indexer_mem_input" value="', isset($modSettings['sphinx_indexer_mem']) ? $modSettings['sphinx_indexer_mem'] : '128', '" size="4" /> MB </dd> <dt> <label for="sphinx_searchd_server_input">', $txt['sphinx_searchd_server'], '</label><br /> <span class="smalltext">', $txt['sphinx_searchd_server_desc'], '</span> </dt> <dd> <input type="text" name="sphinx_searchd_server" id="sphinx_searchd_server_input" value="', isset($modSettings['sphinx_searchd_server']) ? $modSettings['sphinx_searchd_server'] : 'localhost', '" size="65" /> </dd> <dt> <label for="sphinxql_searchd_port_input">', $txt['sphinx_searchd_qlport'], '</label><br /> <span class="smalltext">', $txt['sphinx_searchd_qlport_desc'], '</span> </dt> <dd> <input type="text" name="sphinxql_searchd_port" id="sphinxql_searchd_port_input" value="', isset($modSettings['sphinxql_searchd_port']) ? $modSettings['sphinxql_searchd_port'] : '9306', '" size="4" /> </dd> <dt> <label for="sphinx_searchd_port_input">', $txt['sphinx_searchd_port'], '</label><br /> <span class="smalltext">', $txt['sphinx_searchd_port_desc'], '</span> </dt> <dd> <input type="text" name="sphinx_searchd_port" id="sphinx_searchd_port_input" value="', isset($modSettings['sphinx_searchd_port']) ? $modSettings['sphinx_searchd_port'] : '9312', '" size="4" /> </dd> <dt> <label for="sphinx_max_results_input">', $txt['sphinx_max_matches'], '</label><br /> <span class="smalltext">', $txt['sphinx_max_matches_desc'], '</span> </dt> <dd> <input type="text" name="sphinx_max_results" id="sphinx_max_results_input" value="', isset($modSettings['sphinx_max_results']) ? $modSettings['sphinx_max_results'] : '2000', '" size="4" /> </dd> </dl> <div class="submitbutton"> <input type="submit" name="createconfig" value="', $txt['sphinx_create_config'], '" /> <input type="submit" name="checkconnect" value="', $txt['sphinx_test_connection'], '" /> <input type="submit" name="save" value="', $txt['save'], '" /> <input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" /> <input type="hidden" name="', $context['admin-mssphinx_token_var'], '" value="', $context['admin-mssphinx_token'], '" /> </div> </div> </form> </div>'; }
elkarte/Elkarte
themes/default/ManageSearch.template.php
PHP
bsd-3-clause
25,261
// 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. #ifndef CONTENT_CHILD_NAVIGATOR_CONNECT_SERVICE_PORT_DISPATCHER_IMPL_H_ #define CONTENT_CHILD_NAVIGATOR_CONNECT_SERVICE_PORT_DISPATCHER_IMPL_H_ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "content/common/service_port_service.mojom.h" #include "content/public/child/worker_thread.h" #include "third_party/mojo/src/mojo/public/cpp/bindings/strong_binding.h" namespace blink { class WebServiceWorkerContextProxy; } namespace content { // Mojo service that dispatches ServicePort related events to a service worker. // Instances are always created on a worker thread, and all methods are only // called on that same thread. Lifetime of this class is tied to both the mojo // channel and the lifetime of the worker thread. If either the channel is // disconnected or the worker thread stops the instance deletes itself. class ServicePortDispatcherImpl : public ServicePortDispatcher, public WorkerThread::Observer { public: static void Create(base::WeakPtr<blink::WebServiceWorkerContextProxy> proxy, mojo::InterfaceRequest<ServicePortDispatcher> request); ~ServicePortDispatcherImpl() override; private: ServicePortDispatcherImpl( base::WeakPtr<blink::WebServiceWorkerContextProxy> proxy, mojo::InterfaceRequest<ServicePortDispatcher> request); // WorkerThread::Observer implementation. void WillStopCurrentWorkerThread() override; // ServicePortDispatcher implementation. void Connect(const mojo::String& target_url, const mojo::String& origin, int32_t port_id, const ConnectCallback& callback) override; mojo::StrongBinding<ServicePortDispatcher> binding_; base::WeakPtr<blink::WebServiceWorkerContextProxy> proxy_; DISALLOW_COPY_AND_ASSIGN(ServicePortDispatcherImpl); }; } // namespace content #endif // CONTENT_CHILD_NAVIGATOR_CONNECT_SERVICE_PORT_DISPATCHER_IMPL_H_
CapOM/ChromiumGStreamerBackend
content/child/navigator_connect/service_port_dispatcher_impl.h
C
bsd-3-clause
2,105
<!DOCTYPE html> <html dir="ltr" lang="de"> <head> <title>Alte Generation - Rubinius</title> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta content='de' http-equiv='content-language'> <meta content='Rubinius is an implementation of the Ruby programming language. The Rubinius bytecode virtual machine is written in C++. The bytecode compiler is written in pure Ruby. The vast majority of the core library is also written in Ruby, with some supporting primitives that interact with the VM directly.' name='description'> <link href='/' rel='home'> <link href='/' rel='start'> <link href='/doc/de/garbage-collector/young-generation' rel='prev' title='Mittlere Generation'> <link href='/doc/de/garbage-collector/large-objects' rel='next' title='Große Objekte'> <!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script><![endif]--> <script src="/javascripts/jquery-1.3.2.js"></script> <script src="/javascripts/paging_keys.js"></script> <script src="/javascripts/application.js"></script> <style>article, aside, dialog, figure, footer, header, hgroup, menu, nav, section { display: block; }</style> <link href="/stylesheets/blueprint/screen.css" media="screen" rel="stylesheet" /> <link href="/stylesheets/application.css" media="screen" rel="stylesheet" /> <link href="/stylesheets/blueprint/print.css" media="print" rel="stylesheet" /> <!--[if IE]><link href="/stylesheets/blueprint/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]--> <!--[if IE]><link href="/stylesheets/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]--> <link href="/stylesheets/pygments.css" media="screen" rel="stylesheet" /> </head> <body> <div class='container'> <div class='span-21 doc_menu'> <header> <nav> <ul> <li><a href="/">Home</a></li> <li><a id="blog" href="/blog">Blog</a></li> <li><a id="documentation" href="/doc/en">Documentation</a></li> <li><a href="/projects">Projects</a></li> <li><a href="/roadmap">Roadmap</a></li> <li><a href="/releases">Releases</a></li> </ul> </nav> </header> </div> <div class='span-3 last'> <div id='version'> <a href="/releases/1.2.4">1.2.4</a> </div> </div> </div> <div class="container languages"> <nav> <span class="label">Sprachen:</span> <ul> <li><a href="/doc/de/garbage-collector/mature-generation/" class="current" >de</a></li> <li><a href="/doc/en/garbage-collector/mature-generation/" >en</a></li> <li><a href="/doc/es/garbage-collector/mature-generation/" >es</a></li> <li><a href="/doc/fr/garbage-collector/mature-generation/" >fr</a></li> <li><a href="/doc/ja/garbage-collector/mature-generation/" >ja</a></li> <li><a href="/doc/pl/garbage-collector/mature-generation/" >pl</a></li> <li><a href="/doc/pt-br/garbage-collector/mature-generation/" >pt-br</a></li> <li><a href="/doc/ru/garbage-collector/mature-generation/" >ru</a></li> </ul> </nav> </div> <div class="container doc_page_nav"> <span class="label">Vorherige:</span> <a href="/doc/de/garbage-collector/young-generation">Mittlere Generation</a> <span class="label">Aufwärts:</span> <a href="/doc/de/">Inhaltsverzeichnis</a> <span class="label">Nächste:</span> <a href="/doc/de/garbage-collector/large-objects">Große Objekte</a> </div> <div class="container documentation"> <h2>Alte Generation</h2> <div class="review"> <p>This topic has missing or partial documentation. Please help us improve it.</p> <p> See <a href="/doc/de/how-to/write-documentation">How-To - Write Documentation</a> </p> </div> <p>Alte Objekte sind Objekte, die aus der Mittleren Generation verlagert wurden, nachdem sie x Sammlungen überstanden haben.</p> <p>Autotune ist der Mechanismus, der benutzt wird, um die Anzahl der GC-Zyklen, die für eine Sammlung der Alten Generation benötigt werden, dynamisch anzupassen. Dieser kann ausgeschaltet werden oder es kann eine konstante Anzahl der nötigen GC-Zyklen via <code>gc.lifetime</code> angegeben werden. <code>gc.lifetime</code> ist die Ausgangsanzahl der Sammlungen, die für eine Sammlung der Alten Generation nötig sind.</p> <p>Weitere Informationen über die vorhandenen Konfigurationsvariablen sind in der <a href="https://github.com/rubinius/rubinius/blob/master/vm/configuration.hpp">Konfigurationsdatei der VM</a> einzusehen.</p> </div> <div class="container doc_page_nav"> <span class="label">Vorherige:</span> <a href="/doc/de/garbage-collector/young-generation">Mittlere Generation</a> <span class="label">Aufwärts:</span> <a href="/doc/de/">Inhaltsverzeichnis</a> <span class="label">Nächste:</span> <a href="/doc/de/garbage-collector/large-objects">Große Objekte</a> </div> <div class="container"> <div id="disqus_thread"></div> <script type="text/javascript"> var disqus_shortname = 'rubinius'; var disqus_identifier = '/doc/de/garbage-collector/mature-generation/'; var disqus_url = 'http://rubini.us/doc/de/garbage-collector/mature-generation/'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> <footer> <div class='container'> <nav> <ul> <li><a rel="external" href="http://twitter.com/rubinius">Follow Rubinius on Twitter</a></li> <li><a rel="external" href="http://github.com/rubinius/rubinius">Fork Rubinius on github</a></li> <li><a rel="external" href="http://engineyard.com">An Engine Yard project</a></li> </ul> </nav> </div> </footer> <script> var _gaq=[['_setAccount','UA-12328521-1'],['_trackPageview']]; (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1; g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js'; s.parentNode.insertBefore(g,s)}(document,'script')); </script> </body> </html>
slawosz/rubinius
web/_site/doc/de/garbage-collector/mature-generation/index.html
HTML
bsd-3-clause
6,722
/* * Copyright 2009 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. * Copyright 2009, Google Inc. */ #include "native_client/src/trusted/validator_arm/address_set.h" #include <stdio.h> #include <string.h> namespace nacl_arm_val { AddressSet::AddressSet(uint32_t base, uint32_t size) : base_(base), size_(size), bits_(new uint32_t[(size + 3) / 4]) { memset(bits_, 0, sizeof(uint32_t) * ((size + 3) / 4)); } AddressSet::~AddressSet() { delete[] bits_; } void AddressSet::add(uint32_t address) { if ((address - base_) < size_) { uint32_t word_address = (address - base_) / sizeof(uint32_t); bits_[word_address / 32] |= 1 << (word_address % 32); } } bool AddressSet::contains(uint32_t address) const { if ((address - base_) < size_) { uint32_t word_address = (address - base_) / sizeof(uint32_t); return (bits_[word_address / 32] & (1 << (word_address % 32))) != 0; } else { return false; } } AddressSet::Iterator AddressSet::begin() const { return Iterator(*this, 0, 0); } AddressSet::Iterator AddressSet::end() const { return Iterator(*this, (size_ + 3) / 4, 0); } AddressSet::Iterator::Iterator(const AddressSet &parent, uint32_t index, uint32_t shift) : parent_(parent), index_(index), shift_(shift) { advance(); } AddressSet::Iterator &AddressSet::Iterator::operator++() { shift_++; // Skip the current bit, if any, and advance(); // seek to the next 1 bit. return *this; } bool AddressSet::Iterator::operator!=(const AddressSet::Iterator &other) const { return index_ != other.index_ || shift_ != other.shift_; } uint32_t AddressSet::Iterator::operator*() const { return parent_.base_ + 4 * ((index_ * 32) + shift_); } void AddressSet::Iterator::advance() { uint32_t max_index = (parent_.size_ + 3) / 4; for (; index_ < max_index; index_++) { uint32_t word = (shift_ > 31)? 0 : parent_.bits_[index_] >> shift_; while (word) { if (word & 1) return; // A meager optimization for sparse words if (!(word & 0xFFFF)) { word >>= 16; shift_ += 16; } else if (!(word & 0xFF)) { word >>= 8; shift_ += 8; } else { word >>= 1; shift_++; } } shift_ = 0; } } } // namespace nacl_arm_val
sbc100/native_client
src/trusted/validator_arm/address_set.cc
C++
bsd-3-clause
2,431
@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^<target^>` where ^<target^> is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-secure.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-secure.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end
carljm/django-secure
doc/make.bat
Batchfile
bsd-3-clause
4,525
/* * vfh_estimator.h * * Created on: Mar 22, 2012 * Author: aitor */ #ifndef REC_FRAMEWORK_VFH_ESTIMATOR_H_ #define REC_FRAMEWORK_VFH_ESTIMATOR_H_ #include <pcl/apps/3d_rec_framework/feature_wrapper/global/global_estimator.h> #include <pcl/apps/3d_rec_framework/feature_wrapper/normal_estimator.h> #include <pcl/features/vfh.h> namespace pcl { namespace rec_3d_framework { template<typename PointInT, typename FeatureT> class VFHEstimation : public GlobalEstimator<PointInT, FeatureT> { typedef typename pcl::PointCloud<PointInT>::Ptr PointInTPtr; using GlobalEstimator<PointInT, FeatureT>::normal_estimator_; public: void estimate (PointInTPtr & in, PointInTPtr & processed, typename pcl::PointCloud<FeatureT>::CloudVectorType & signatures, std::vector<Eigen::Vector3f> & centroids) { if (!normal_estimator_) { PCL_ERROR("This feature needs normals... please provide a normal estimator\n"); return; } pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>); normal_estimator_->estimate (in, processed, normals); typedef typename pcl::VFHEstimation<PointInT, pcl::Normal, FeatureT> VFHEstimation; pcl::PointCloud<FeatureT> vfh_signature; VFHEstimation vfh; typename pcl::search::KdTree<PointInT>::Ptr vfh_tree (new pcl::search::KdTree<PointInT>); vfh.setSearchMethod (vfh_tree); vfh.setInputCloud (processed); vfh.setInputNormals (normals); vfh.setNormalizeBins (true); vfh.setNormalizeDistance (true); vfh.compute (vfh_signature); signatures.resize (1); centroids.resize (1); signatures[0] = vfh_signature; Eigen::Vector4f centroid4f; pcl::compute3DCentroid (*in, centroid4f); centroids[0] = Eigen::Vector3f (centroid4f[0], centroid4f[1], centroid4f[2]); } bool computedNormals () { return true; } }; } } #endif /* REC_FRAMEWORK_VFH_ESTIMATOR_H_ */
daviddoria/PCLMirror
apps/3d_rec_framework/include/pcl/apps/3d_rec_framework/feature_wrapper/global/vfh_estimator.h
C
bsd-3-clause
2,191
<?php class ExtendedGenerator extends Generator { } ?>
evnix/go-php-parser
testdata/fuzzdir/corpus/Zend_tests_generators_errors_generator_extend_error.php
PHP
bsd-3-clause
57
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.h" #include <string> #include <utility> #include "base/bind.h" #include "base/memory/ptr_util.h" #include "base/values.h" #include "chrome/browser/ash/kerberos/kerberos_credentials_manager.h" #include "chrome/browser/ash/kerberos/kerberos_credentials_manager_factory.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/settings/chromeos/os_settings_section.h" #include "chrome/browser/ui/webui/webui_util.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" #include "content/public/browser/web_ui_data_source.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/time_format.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/webui/web_ui_util.h" #include "ui/chromeos/resources/grit/ui_chromeos_resources.h" #include "ui/gfx/image/image_skia.h" namespace chromeos { namespace settings { namespace { bool IsKerberosEnabled( KerberosCredentialsManager* kerberos_credentials_manager) { return kerberos_credentials_manager != nullptr && kerberos_credentials_manager->IsKerberosEnabled(); } // Adds title for Kerberos subsection and Add Accounts page. void AddKerberosTitleStrings(content::WebUIDataSource* html_source) { static constexpr webui::LocalizedString kLocalizedStrings[] = { {"kerberosAccountsSubMenuLabel", IDS_SETTINGS_KERBEROS_ACCOUNTS_SUBMENU_LABEL}, {"kerberosAccountsPageTitle", IDS_SETTINGS_KERBEROS_ACCOUNTS_PAGE_TITLE}, }; html_source->AddLocalizedStrings(kLocalizedStrings); } // Adds load time boolean corresponding to Kerberos enable state. void AddKerberosEnabledFlag( content::WebUIDataSource* html_source, KerberosCredentialsManager* kerberos_credentials_manager) { html_source->AddBoolean("isKerberosEnabled", IsKerberosEnabled(kerberos_credentials_manager)); } // Adds load time strings to Kerberos Add Accounts dialog. void AddKerberosAddAccountDialogStrings(content::WebUIDataSource* html_source) { static constexpr webui::LocalizedString kLocalizedStrings[] = { {"kerberosAccountsAdvancedConfigLabel", IDS_SETTINGS_KERBEROS_ACCOUNTS_ADVANCED_CONFIG_LABEL}, {"kerberosAdvancedConfigTitle", IDS_SETTINGS_KERBEROS_ADVANCED_CONFIG_TITLE}, {"kerberosAdvancedConfigDesc", IDS_SETTINGS_KERBEROS_ADVANCED_CONFIG_DESC}, {"addKerberosAccountRememberPassword", IDS_SETTINGS_ADD_KERBEROS_ACCOUNT_REMEMBER_PASSWORD}, {"kerberosPassword", IDS_SETTINGS_KERBEROS_PASSWORD}, {"kerberosUsername", IDS_SETTINGS_KERBEROS_USERNAME}, {"addKerberosAccountDescription", IDS_SETTINGS_ADD_KERBEROS_ACCOUNT_DESCRIPTION}, {"kerberosErrorNetworkProblem", IDS_SETTINGS_KERBEROS_ERROR_NETWORK_PROBLEM}, {"kerberosErrorUsernameInvalid", IDS_SETTINGS_KERBEROS_ERROR_USERNAME_INVALID}, {"kerberosErrorUsernameUnknown", IDS_SETTINGS_KERBEROS_ERROR_USERNAME_UNKNOWN}, {"kerberosErrorDuplicatePrincipalName", IDS_SETTINGS_KERBEROS_ERROR_DUPLICATE_PRINCIPAL_NAME}, {"kerberosErrorContactingServer", IDS_SETTINGS_KERBEROS_ERROR_CONTACTING_SERVER}, {"kerberosErrorPasswordInvalid", IDS_SETTINGS_KERBEROS_ERROR_PASSWORD_INVALID}, {"kerberosErrorPasswordExpired", IDS_SETTINGS_KERBEROS_ERROR_PASSWORD_EXPIRED}, {"kerberosErrorKdcEncType", IDS_SETTINGS_KERBEROS_ERROR_KDC_ENC_TYPE}, {"kerberosErrorGeneral", IDS_SETTINGS_KERBEROS_ERROR_GENERAL}, {"kerberosConfigErrorSectionNestedInGroup", IDS_SETTINGS_KERBEROS_CONFIG_ERROR_SECTION_NESTED_IN_GROUP}, {"kerberosConfigErrorSectionSyntax", IDS_SETTINGS_KERBEROS_CONFIG_ERROR_SECTION_SYNTAX}, {"kerberosConfigErrorExpectedOpeningCurlyBrace", IDS_SETTINGS_KERBEROS_CONFIG_ERROR_EXPECTED_OPENING_CURLY_BRACE}, {"kerberosConfigErrorExtraCurlyBrace", IDS_SETTINGS_KERBEROS_CONFIG_ERROR_EXTRA_CURLY_BRACE}, {"kerberosConfigErrorRelationSyntax", IDS_SETTINGS_KERBEROS_CONFIG_ERROR_RELATION_SYNTAX_ERROR}, {"kerberosConfigErrorKeyNotSupported", IDS_SETTINGS_KERBEROS_CONFIG_ERROR_KEY_NOT_SUPPORTED}, {"kerberosConfigErrorSectionNotSupported", IDS_SETTINGS_KERBEROS_CONFIG_ERROR_SECTION_NOT_SUPPORTED}, {"kerberosConfigErrorKrb5FailedToParse", IDS_SETTINGS_KERBEROS_CONFIG_ERROR_KRB5_FAILED_TO_PARSE}, {"kerberosConfigErrorTooManyNestedGroups", IDS_SETTINGS_KERBEROS_CONFIG_ERROR_TOO_MANY_NESTED_GROUPS}, {"addKerberosAccountRefreshButtonLabel", IDS_SETTINGS_ADD_KERBEROS_ACCOUNT_REFRESH_BUTTON_LABEL}, {"addKerberosAccount", IDS_SETTINGS_ADD_KERBEROS_ACCOUNT}, {"refreshKerberosAccount", IDS_SETTINGS_REFRESH_KERBEROS_ACCOUNT}, }; html_source->AddLocalizedStrings(kLocalizedStrings); PrefService* local_state = g_browser_process->local_state(); // Whether the 'Remember password' checkbox is enabled. html_source->AddBoolean( "kerberosRememberPasswordEnabled", local_state->GetBoolean(::prefs::kKerberosRememberPasswordEnabled)); // Kerberos default configuration. html_source->AddString( "defaultKerberosConfig", chromeos::KerberosCredentialsManager::GetDefaultKerberosConfig()); } // Adds load time strings to Kerberos Accounts page. void AddKerberosAccountsPageStrings(content::WebUIDataSource* html_source) { static constexpr webui::LocalizedString kLocalizedStrings[] = { {"kerberosAccountsAddAccountLabel", IDS_SETTINGS_KERBEROS_ACCOUNTS_ADD_ACCOUNT_LABEL}, {"kerberosAccountsRefreshNowLabel", IDS_SETTINGS_KERBEROS_ACCOUNTS_REFRESH_NOW_LABEL}, {"kerberosAccountsSetAsActiveAccountLabel", IDS_SETTINGS_KERBEROS_ACCOUNTS_SET_AS_ACTIVE_ACCOUNT_LABEL}, {"kerberosAccountsSignedOut", IDS_SETTINGS_KERBEROS_ACCOUNTS_SIGNED_OUT}, {"kerberosAccountsListHeader", IDS_SETTINGS_KERBEROS_ACCOUNTS_LIST_HEADER}, {"kerberosAccountsRemoveAccountLabel", IDS_SETTINGS_KERBEROS_ACCOUNTS_REMOVE_ACCOUNT_LABEL}, {"kerberosAccountsReauthenticationLabel", IDS_SETTINGS_KERBEROS_ACCOUNTS_REAUTHENTICATION_LABEL}, {"kerberosAccountsTicketActive", IDS_SETTINGS_KERBEROS_ACCOUNTS_TICKET_ACTIVE}, {"kerberosAccountsAccountRemovedTip", IDS_SETTINGS_KERBEROS_ACCOUNTS_ACCOUNT_REMOVED_TIP}, {"kerberosAccountsAccountRefreshedTip", IDS_SETTINGS_KERBEROS_ACCOUNTS_ACCOUNT_REFRESHED_TIP}, {"kerberosAccountsSignedIn", IDS_SETTINGS_KERBEROS_ACCOUNTS_SIGNED_IN}, }; html_source->AddLocalizedStrings(kLocalizedStrings); PrefService* local_state = g_browser_process->local_state(); // Whether new Kerberos accounts may be added. html_source->AddBoolean( "kerberosAddAccountsAllowed", local_state->GetBoolean(::prefs::kKerberosAddAccountsAllowed)); // Kerberos accounts page with "Learn more" link. html_source->AddString( "kerberosAccountsDescription", l10n_util::GetStringFUTF16(IDS_SETTINGS_KERBEROS_ACCOUNTS_DESCRIPTION, OsSettingsSection::GetHelpUrlWithBoard( chrome::kKerberosAccountsLearnMoreURL))); } } // namespace // static std::unique_ptr<KerberosAccountsHandler> KerberosAccountsHandler::CreateIfKerberosEnabled(Profile* profile) { KerberosCredentialsManager* kerberos_credentials_manager = KerberosCredentialsManagerFactory::GetExisting(profile); if (!IsKerberosEnabled(kerberos_credentials_manager)) return nullptr; return base::WrapUnique( new KerberosAccountsHandler(kerberos_credentials_manager)); } // static void KerberosAccountsHandler::AddLoadTimeKerberosStrings( content::WebUIDataSource* html_source, KerberosCredentialsManager* kerberos_credentials_manager) { AddKerberosEnabledFlag(html_source, kerberos_credentials_manager); AddKerberosTitleStrings(html_source); AddKerberosAccountsPageStrings(html_source); AddKerberosAddAccountDialogStrings(html_source); } KerberosAccountsHandler::~KerberosAccountsHandler() = default; KerberosAccountsHandler::KerberosAccountsHandler( KerberosCredentialsManager* kerberos_credentials_manager) : kerberos_credentials_manager_(kerberos_credentials_manager) { DCHECK(kerberos_credentials_manager_); } void KerberosAccountsHandler::RegisterMessages() { web_ui()->RegisterDeprecatedMessageCallback( "getKerberosAccounts", base::BindRepeating(&KerberosAccountsHandler::HandleGetKerberosAccounts, weak_factory_.GetWeakPtr())); web_ui()->RegisterDeprecatedMessageCallback( "addKerberosAccount", base::BindRepeating(&KerberosAccountsHandler::HandleAddKerberosAccount, weak_factory_.GetWeakPtr())); web_ui()->RegisterDeprecatedMessageCallback( "removeKerberosAccount", base::BindRepeating(&KerberosAccountsHandler::HandleRemoveKerberosAccount, weak_factory_.GetWeakPtr())); web_ui()->RegisterDeprecatedMessageCallback( "validateKerberosConfig", base::BindRepeating( &KerberosAccountsHandler::HandleValidateKerberosConfig, weak_factory_.GetWeakPtr())); web_ui()->RegisterDeprecatedMessageCallback( "setAsActiveKerberosAccount", base::BindRepeating( &KerberosAccountsHandler::HandleSetAsActiveKerberosAccount, weak_factory_.GetWeakPtr())); } void KerberosAccountsHandler::HandleGetKerberosAccounts( const base::ListValue* args) { AllowJavascript(); CHECK_EQ(1U, args->GetList().size()); const std::string& callback_id = args->GetList()[0].GetString(); if (!kerberos_credentials_manager_->IsKerberosEnabled()) { ResolveJavascriptCallback(base::Value(callback_id), base::Value()); return; } kerberos_credentials_manager_->ListAccounts( base::BindOnce(&KerberosAccountsHandler::OnListAccounts, weak_factory_.GetWeakPtr(), callback_id)); } void KerberosAccountsHandler::OnListAccounts( const std::string& callback_id, const kerberos::ListAccountsResponse& response) { base::ListValue accounts; // Ticket icon is a key. gfx::ImageSkia skia_ticket_icon = *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_KERBEROS_ICON_KEY); std::string ticket_icon = webui::GetBitmapDataUrl( skia_ticket_icon.GetRepresentation(1.0f).GetBitmap()); const std::string& active_principal = kerberos_credentials_manager_->GetActiveAccount(); for (int n = 0; n < response.accounts_size(); ++n) { const kerberos::Account& account = response.accounts(n); // Format validity time as 'xx hours yy minutes' for validity < 1 day and // 'nn days' otherwise. base::TimeDelta tgt_validity = base::Seconds(account.tgt_validity_seconds()); const std::u16string valid_for_duration = ui::TimeFormat::Detailed( ui::TimeFormat::FORMAT_DURATION, ui::TimeFormat::LENGTH_LONG, tgt_validity < base::Days(1) ? -1 : 0, tgt_validity); base::DictionaryValue account_dict; account_dict.SetString("principalName", account.principal_name()); account_dict.SetString("config", account.krb5conf()); account_dict.SetBoolean("isSignedIn", account.tgt_validity_seconds() > 0); account_dict.SetString("validForDuration", valid_for_duration); account_dict.SetBoolean("isActive", account.principal_name() == active_principal); account_dict.SetBoolean("isManaged", account.is_managed()); account_dict.SetBoolean("passwordWasRemembered", account.password_was_remembered()); account_dict.SetString("pic", ticket_icon); accounts.Append(std::move(account_dict)); } ResolveJavascriptCallback(base::Value(callback_id), std::move(accounts)); } void KerberosAccountsHandler::HandleAddKerberosAccount( const base::ListValue* args) { AllowJavascript(); // TODO(https://crbug.com/961246): // - Prevent account changes when Kerberos is disabled. // - Remove all accounts when Kerberos is disabled. CHECK_EQ(6U, args->GetList().size()); const std::string& callback_id = args->GetList()[0].GetString(); const std::string& principal_name = args->GetList()[1].GetString(); const std::string& password = args->GetList()[2].GetString(); const bool remember_password = args->GetList()[3].GetBool(); const std::string& config = args->GetList()[4].GetString(); const bool allow_existing = args->GetList()[5].GetBool(); if (!kerberos_credentials_manager_->IsKerberosEnabled()) { ResolveJavascriptCallback(base::Value(callback_id), base::Value(kerberos::ERROR_KERBEROS_DISABLED)); return; } kerberos_credentials_manager_->AddAccountAndAuthenticate( principal_name, false /* is_managed */, password, remember_password, config, allow_existing, base::BindOnce(&KerberosAccountsHandler::OnAddAccountAndAuthenticate, weak_factory_.GetWeakPtr(), callback_id)); } void KerberosAccountsHandler::OnAddAccountAndAuthenticate( const std::string& callback_id, kerberos::ErrorType error) { ResolveJavascriptCallback(base::Value(callback_id), base::Value(static_cast<int>(error))); } void KerberosAccountsHandler::HandleRemoveKerberosAccount( const base::ListValue* args) { AllowJavascript(); CHECK_EQ(2U, args->GetList().size()); const std::string& callback_id = args->GetList()[0].GetString(); const std::string& principal_name = args->GetList()[1].GetString(); if (!kerberos_credentials_manager_->IsKerberosEnabled()) { ResolveJavascriptCallback(base::Value(callback_id), base::Value(kerberos::ERROR_KERBEROS_DISABLED)); return; } kerberos_credentials_manager_->RemoveAccount( principal_name, base::BindOnce(&KerberosAccountsHandler::OnRemoveAccount, weak_factory_.GetWeakPtr(), callback_id)); } void KerberosAccountsHandler::OnRemoveAccount(const std::string& callback_id, kerberos::ErrorType error) { ResolveJavascriptCallback(base::Value(callback_id), base::Value(static_cast<int>(error))); } void KerberosAccountsHandler::HandleValidateKerberosConfig( const base::ListValue* args) { AllowJavascript(); CHECK_EQ(2U, args->GetList().size()); const std::string& callback_id = args->GetList()[0].GetString(); const std::string& krb5conf = args->GetList()[1].GetString(); if (!kerberos_credentials_manager_->IsKerberosEnabled()) { ResolveJavascriptCallback(base::Value(callback_id), base::Value(kerberos::ERROR_KERBEROS_DISABLED)); return; } kerberos_credentials_manager_->ValidateConfig( krb5conf, base::BindOnce(&KerberosAccountsHandler::OnValidateConfig, weak_factory_.GetWeakPtr(), callback_id)); } void KerberosAccountsHandler::OnValidateConfig( const std::string& callback_id, const kerberos::ValidateConfigResponse& response) { base::Value error_info(base::Value::Type::DICTIONARY); error_info.SetKey("code", base::Value(response.error_info().code())); if (response.error_info().has_line_index()) { error_info.SetKey("lineIndex", base::Value(response.error_info().line_index())); } base::Value value(base::Value::Type::DICTIONARY); value.SetKey("error", base::Value(static_cast<int>(response.error()))); value.SetKey("errorInfo", std::move(error_info)); ResolveJavascriptCallback(base::Value(callback_id), std::move(value)); } void KerberosAccountsHandler::HandleSetAsActiveKerberosAccount( const base::ListValue* args) { AllowJavascript(); CHECK_EQ(1U, args->GetList().size()); const std::string& principal_name = args->GetList()[0].GetString(); kerberos_credentials_manager_->SetActiveAccount(principal_name); } void KerberosAccountsHandler::OnJavascriptAllowed() { credentials_manager_observation_.Observe(kerberos_credentials_manager_); } void KerberosAccountsHandler::OnJavascriptDisallowed() { credentials_manager_observation_.Reset(); } void KerberosAccountsHandler::OnAccountsChanged() { RefreshUI(); } void KerberosAccountsHandler::RefreshUI() { FireWebUIListener("kerberos-accounts-changed"); } } // namespace settings } // namespace chromeos
ric2b/Vivaldi-browser
chromium/chrome/browser/ui/webui/settings/chromeos/kerberos_accounts_handler.cc
C++
bsd-3-clause
16,834
"""Integration test for Notifications.""" import github3 from .helper import IntegrationHelper class TestThread(IntegrationHelper): """Integration test for methods on Test class""" def test_subscription(self): """Show that a user can retrieve notifications for repository""" self.token_login() cassette_name = self.cassette_name("subscription") with self.recorder.use_cassette(cassette_name): repository = self.gh.repository('sigmavirus24', 'github3.py') threads = list(repository.notifications(all=True)) assert len(threads) > 0 thread = threads[0] assert isinstance(thread, github3.notifications.Thread) assert isinstance(thread.subscription(), github3.notifications.Subscription) class TestSubscription(IntegrationHelper): """Integration test for methods on Test class""" def test_set(self): """Show that user can successful set subscription""" self.token_login() cassette_name = self.cassette_name("set") with self.recorder.use_cassette(cassette_name): repository = self.gh.repository('sigmavirus24', 'github3.py') threads = list(repository.notifications(all='true')) assert len(threads) > 0 subscription = threads[0].subscription() assert subscription.set(True, False) is None assert isinstance(subscription, github3.notifications.Subscription)
christophelec/github3.py
tests/integration/test_notifications.py
Python
bsd-3-clause
1,512
// Copyright (c) 2006-2008 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. #ifndef PRINTING_UNITS_H_ #define PRINTING_UNITS_H_ namespace printing { // Length of a thousanth of inches in 0.01mm unit. const int kHundrethsMMPerInch = 2540; // Converts from one unit system to another using integer arithmetics. int ConvertUnit(int value, int old_unit, int new_unit); // Converts from one unit system to another using doubles. double ConvertUnitDouble(double value, double old_unit, double new_unit); // Converts from 0.001 inch unit to 0.00001 meter. int ConvertMilliInchToHundredThousanthMeter(int milli_inch); // Converts from 0.00001 meter unit to 0.001 inch. int ConvertHundredThousanthMeterToMilliInch(int cmm); } // namespace printing #endif // PRINTING_UNITS_H_
rwatson/chromium-capsicum
printing/units.h
C
bsd-3-clause
876
/* * Copyright (c) 2009-2013, United States Government, as represented by the Secretary of Health and Human Services. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the United States Government nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package gov.hhs.fha.nhinc.docregistry; import gov.hhs.fha.nhinc.util.AbstractWSAddressingTest; public class WSAddressingTest extends AbstractWSAddressingTest { // empty implementation - superclass does classpath resolution }
sailajaa/CONNECT
Product/Production/Services/DocRegistryCore/src/test/java/gov/hhs/fha/nhinc/docregistry/WSAddressingTest.java
Java
bsd-3-clause
1,929
/* * SEGS - Super Entity Game Server * http://www.segs.dev/ * Copyright (c) 2006 - 2019 SEGS Team (see AUTHORS.md) * This software is licensed under the terms of the 3-clause BSD License. See LICENSE.md for details. */ #ifndef SLAVLOGIC_H #define SLAVLOGIC_H #include <QObject> class AppVersionManifest; struct ServerDescriptor; class SLAVLogic : public QObject { Q_OBJECT AppVersionManifest *m_current_manifest; class ServerConnection *m_serv_conn; class UpdaterDlg *m_ui_impl; bool needToOverwriteBaseInstall(); void createBackupIfNeeded(); void copyFilesOverBase(); void calculateHashes(AppVersionManifest *manifest); public: explicit SLAVLogic(QObject *parent = 0); void connectUI(); void start(); signals: // Notifying the UI void needUpdate(AppVersionManifest *manifest,const QString &changeLog); private slots: void onHashingProgress(QString chan,float percent); void onThreadError(QString v); public slots: // called from Network void onManifestReceived(const QString & manifest_url, const QString &manifestData); // called from UI void onUpdateRequested(ServerDescriptor * manifest); }; #endif // SLAVLOGIC_H
broxen/Segs
Utilities/slav/SLAVLogic.h
C
bsd-3-clause
1,206
/* * /MathJax/jax/output/SVG/fonts/TeX/Fraktur/Bold/Main.js * * Copyright (c) 2009-2015 The MathJax Consortium * * 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. */ MathJax.OutputJax.SVG.FONTDATA.FONTS["MathJax_Fraktur-bold"]={directory:"Fraktur/Bold",family:"MathJax_Fraktur",id:"MJFRAKB",weight:"bold",Ranges:[[0,127,"BasicLatin"],[128,57343,"Other"],[58112,58128,"PUA"]]};MathJax.Ajax.loadComplete(MathJax.OutputJax.SVG.fontDir+"/Fraktur/Bold/Main.js");
AndrewSyktyvkar/Math
wysivig/MathJax/jax/output/SVG/fonts/TeX/Fraktur/Bold/Main.js
JavaScript
bsd-3-clause
980
<?php namespace Chamilo\Core\Repository\ContentObject\Matterhorn\Common; use Chamilo\Core\Repository\Common\Import\ContentObjectImportImplementation; class ImportImplementation extends ContentObjectImportImplementation { }
forelo/cosnics
src/Chamilo/Core/Repository/ContentObject/Matterhorn/Common/ImportImplementation.php
PHP
mit
225
// Next-generation ES6 module bundler var gulp = require('gulp'), paths = require('./config/paths'), plumber = require('gulp-plumber'), rollup = require('gulp-rollup'), babel = require('rollup-plugin-babel'), rename = require('gulp-rename'); // Bundle ES6 modules. gulp.task('rollup:main', function() { return gulp.src(paths.dev.js + '/**/*.js') .pipe(plumber()) .pipe(rollup({ format: 'umd', entry: [ paths.dev.js + '/body.js', paths.dev.js + '/head.js' ], plugins: [ babel({ exclude: 'node_modules/**', presets: ['@babel/preset-env'], babelrc: false }) ] })) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest(paths.build.js)); });
website-templates/webstudio_responsive-template
gulp_tasks/rollup.js
JavaScript
mit
767
/** * This file has no copyright assigned and is placed in the Public Domain. * This file is part of the mingw-w64 runtime package. * No warranty is given; refer to the file DISCLAIMER.PD within this package. */ #include <fenv.h> #if !(defined(_ARM_) || defined(__arm__) || defined(_ARM64_) || defined(__aarch64__)) extern int __mingw_has_sse (void); #endif /* !(defined(_ARM_) || defined(__arm__) || defined(_ARM64_) || defined(__aarch64__)) */ /* 7.6.2.4 The fesetexceptflag function sets the complete status for those exception flags indicated by the argument excepts, according to the representation in the object pointed to by flagp. The value of *flagp shall have been set by a previous call to fegetexceptflag whose second argument represented at least those exceptions represented by the argument excepts. This function does not raise exceptions, but only sets the state of the flags. */ int fesetexceptflag (const fexcept_t * flagp, int excepts) { fenv_t _env; excepts &= FE_ALL_EXCEPT; #if defined(_ARM_) || defined(__arm__) __asm__ volatile ("fmrx %0, FPSCR" : "=r" (_env)); _env.__cw &= ~excepts; _env.__cw |= (*flagp & excepts); __asm__ volatile ("fmxr FPSCR, %0" : : "r" (_env)); #elif defined(_ARM64_) || defined(__aarch64__) unsigned __int64 fpcr; (void) _env; __asm__ volatile ("mrs %0, fpcr" : "=r" (fpcr)); fpcr &= ~excepts; fpcr |= (*flagp & excepts); __asm__ volatile ("msr fpcr, %0" : : "r" (fpcr)); #else __asm__ volatile ("fnstenv %0;" : "=m" (_env)); _env.__status_word &= ~excepts; _env.__status_word |= (*flagp & excepts); __asm__ volatile ("fldenv %0;" : : "m" (_env)); if (__mingw_has_sse ()) { int sse_cw; __asm__ volatile ("stmxcsr %0;" : "=m" (sse_cw)); sse_cw &= ~(excepts << 7); sse_cw |= ((*flagp & excepts) << 7); __asm__ volatile ("ldmxcsr %0" : : "m" (sse_cw)); } #endif /* defined(_ARM_) || defined(__arm__) || defined(_ARM64_) || defined(__aarch64__) */ return 0; }
zig-lang/zig
lib/libc/mingw/misc/fesetexceptflag.c
C
mit
2,014
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function from builtins import zip import pycrfsuite def compareTaggers(model1, model2, string_list, module_name): """ Compare two models. Given a list of strings, prints out tokens & tags whenever the two taggers parse a string differently. This is for spot-checking models :param tagger1: a .crfsuite filename :param tagger2: another .crfsuite filename :param string_list: a list of strings to be checked :param module_name: name of a parser module """ module = __import__(module_name) tagger1 = pycrfsuite.Tagger() tagger1.open(module_name+'/'+model1) tagger2 = pycrfsuite.Tagger() tagger2.open(module_name+'/'+model2) count_discrepancies = 0 for string in string_list: tokens = module.tokenize(string) if tokens: features = module.tokens2features(tokens) tags1 = tagger1.tag(features) tags2 = tagger2.tag(features) if tags1 != tags2: count_discrepancies += 1 print('\n') print("%s. %s" %(count_discrepancies, string)) print('-'*75) print_spaced('token', model1, model2) print('-'*75) for token in zip(tokens, tags1, tags2): print_spaced(token[0], token[1], token[2]) print("\n\n%s of %s strings were labeled differently"%(count_discrepancies, len(string_list))) def print_spaced(s1, s2, s3): n = 25 print(s1 + " "*(n-len(s1)) + s2 + " "*(n-len(s2)) + s3) def validateTaggers(model1, model2, labeled_string_list, module_name): module = __import__(module_name) tagger1 = pycrfsuite.Tagger() tagger1.open(module_name+'/'+model1) tagger2 = pycrfsuite.Tagger() tagger2.open(module_name+'/'+model2) wrong_count_1 = 0 wrong_count_2 = 0 wrong_count_both = 0 correct_count = 0 for labeled_string in labeled_string_list: unlabeled_string, components = labeled_string tokens = module.tokenize(unlabeled_string) if tokens: features = module.tokens2features(tokens) _, tags_true = list(zip(*components)) tags_true = list(tags_true) tags1 = tagger1.tag(features) tags2 = tagger2.tag(features) if (tags1 != tags_true) and (tags2 != tags_true): print("\nSTRING: ", unlabeled_string) print("TRUE: ", tags_true) print("*%s: "%model1, tags1) print("*%s: "%model2, tags2) wrong_count_both += 1 elif (tags1 != tags_true): print("\nSTRING: ", unlabeled_string) print("TRUE: ", tags_true) print("*%s: "%model1, tags1) print("%s: "%model2, tags2) wrong_count_1 += 1 elif (tags2 != tags_true): print("\nSTRING: ", unlabeled_string) print("TRUE: ", tags_true) print("%s: "%model1, tags1) print("*%s: "%model2, tags2) wrong_count_2 += 1 else: correct_count += 1 print("\n\nBOTH WRONG: ", wrong_count_both) print("%s WRONG: %s" %(model1, wrong_count_1)) print("%s WRONG: %s" %(model2, wrong_count_2)) print("BOTH CORRECT: ", correct_count)
et-al-Health/parserator
parserator/spotcheck.py
Python
mit
3,434
#XMind SDK for python **XMind SDK for python** to help Python developers to easily work with XMind files and build XMind extensions. ##Install XMind SDK for python Clone the repository to a local working directory git clone https://github.com/xmindltd/xmind-sdk-python.git Now there will be a directory named `xmind-sdk-python` under the current directory. Change to the directory `xmind-sdk-python` and install **XMind SDK for python**. python setup.py install *It is highly recommended to install __XMind SDK for python__ under an isolated python environment using [virtualenv](https://pypi.python.org/pypi/virtualenv)* ##Usage Open an existing XMind file or create a new XMind file and place it into a given path import xmind workbook = xmind.load(/path/to/file/) # Requires '.xmind' extension Save XMind file to a path. If the path is not given then the API will save to the path set in the workbook xmind.save(workbook) or: xmind.save(workbook, /save/file/to/path) ##LICENSE The MIT License (MIT) Copyright (c) 2013 XMind, Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
nacerix/xmind-sdk-python
README.md
Markdown
mit
2,085
//Copyright (c) Microsoft Corporation. All rights reserved. #pragma once namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace Direct3D11 { using namespace System; // REVIEW: is a ColorRgba really the correct abstraction for the blend factors? // It's true that it maps data-wise to the blend factor array the unmanaged API // expects, but blend factors aren't really colors per se. /// <summary> /// Stores the blend state, including blend factors and mask, for the merger pipeline stage /// </summary> public ref class OutputMergerBlendState { public: /// <summary> /// Gets the BlendState object for this merger pipeline stage blend state /// </summary> property BlendState^ BlendState { Direct3D11::BlendState^ get(void) { return blendState; } } /// <summary> /// Gets the blend factors for this merger pipeline stage blend state /// </summary> property ColorRgba BlendFactor { ColorRgba get(void) { return blendFactor; } } /// <summary> /// Gets the sample mask for this merger pipeline stage blend state /// </summary> property UInt32 SampleMask { UInt32 get(void) { return sampleMask; } } OutputMergerBlendState(void) { SetDefault(); } OutputMergerBlendState(Direct3D11::BlendState^ blendState) { SetDefault(); this->blendState = blendState; } OutputMergerBlendState(Direct3D11::BlendState^ blendState, ColorRgba blendFactor, UInt32 sampleMask) { this->blendState = blendState; this->blendFactor = blendFactor; this->sampleMask = sampleMask; } private: void SetDefault() { blendState = nullptr; blendFactor = ColorRgba(1.0, 1.0, 1.0, 1.0); sampleMask = 0xffffffff; } Direct3D11::BlendState^ blendState; ColorRgba blendFactor; UInt32 sampleMask; }; } } } }
devkimchi/Windows-API-Code-Pack-1.1
source/WindowsAPICodePack/DirectX/DirectX/Direct3D11/D3D11OutputMergerBlendState.h
C
mit
2,157
<!DOCTYPE html><html lang="ru"><head> <meta charset="utf-8"> <title>- Камера</title> <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:site" content="@threejs"> <meta name="twitter:title" content="Three.js – - Камера"> <meta property="og:image" content="https://threejs.org/files/share.png"> <link rel="shortcut icon" href="/files/favicon_white.ico" media="(prefers-color-scheme: dark)"> <link rel="shortcut icon" href="/files/favicon.ico" media="(prefers-color-scheme: light)"> <link rel="stylesheet" href="/manual/resources/lesson.css"> <link rel="stylesheet" href="/manual/resources/lang.css"> <!-- Import maps polyfill --> <!-- Remove this when import maps will be widely supported --> <script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script> <script type="importmap"> { "imports": { "three": "../../build/three.module.js" } } </script> </head> <body> <div class="container"> <div class="lesson-title"> <h1>- Камера</h1> </div> <div class="lesson"> <div class="lesson-main"> <p>Эта статья является частью серии статей о three.js. Первая была <a href="fundamentals.html">об основах</a>. Если вы её еще не читали, советую вам сделать это.</p> <p>Давайте поговорим о камерах в three.js. Мы рассмотрели некоторые из них в <a href="fundamentals.html">первой статье</a> , но мы расскажем здесь об этом более подробно.</p> <p>Самая распространенная камера в Three.js и та, которую мы использовали до этого момента, - <a href="/docs/#api/en/cameras/PerspectiveCamera"><code class="notranslate" translate="no">PerspectiveCamera</code></a>. Она дает трехмерный вид, где вещи на расстоянии кажутся меньше, чем вещи рядом.</p> <p><a href="/docs/#api/en/cameras/PerspectiveCamera"><code class="notranslate" translate="no">PerspectiveCamera</code></a> определяет <em>frustum</em>. <a href="https://ru.wikipedia.org/wiki/Усечённая_пирамида"><em>Frustum</em> - усеченная пирамида, твердое тело</a>. Под твердым телом я подразумеваю, например, куб, конус, сферу, цилиндр и усеченный конус - все названия различных видов твердых тел.</p> <div class="spread"> <div><div data-diagram="shapeCube"></div><div>cube</div></div> <div><div data-diagram="shapeCone"></div><div>cone</div></div> <div><div data-diagram="shapeSphere"></div><div>sphere</div></div> <div><div data-diagram="shapeCylinder"></div><div>cylinder</div></div> <div><div data-diagram="shapeFrustum"></div><div>frustum</div></div> </div> <p>Я только указываю на это, потому что я не знал это в течение многих лет. Если в какой-нибудь книге или на веб странице будет упоминание <em>frustum</em> я закатывал глаза. Понимание того, что это название сплошной формы, сделало эти описания внезапно более понятными 😅</p> <p>A <a href="/docs/#api/en/cameras/PerspectiveCamera"><code class="notranslate" translate="no">PerspectiveCamera</code></a>определяет свой frustum на основе 4 свойств. <code class="notranslate" translate="no">near</code> определяет, где начинается фронт усечения. <code class="notranslate" translate="no">far</code> определяет, где он заканчивается. <code class="notranslate" translate="no">fov</code>поле обзора определяет высоту передней и задней частей усеченного конуса, вычисляя правильную высоту, чтобы получить указанное поле обзора в <code class="notranslate" translate="no">near</code> единицах измерения от камеры. <code class="notranslate" translate="no">aspect</code> определяет, насколько широким передние и задняя часть усеченного есть. Ширина усеченного конуса - это просто высота, умноженная на aspect.</p> <p><img src="../resources/frustum-3d.svg" width="500" class="threejs_center"></p> <p>Давайте используем сцену из <a href="lights.html">предыдущей статьи</a> которая имеет плоскость земли, сферу и куб, и сделаем так, чтобы мы могли регулировать настройки камеры</p> <p>Для этого мы сделаем <code class="notranslate" translate="no">MinMaxGUIHelper</code> для параметров <code class="notranslate" translate="no">near</code> и <code class="notranslate" translate="no">far</code>, так чтобы <code class="notranslate" translate="no">far</code> всегда был больше, чем <code class="notranslate" translate="no">near</code>. У него будут свойства <code class="notranslate" translate="no">min</code> и <code class="notranslate" translate="no">max</code>, которые lil-gui будет настраивать. После настройки они установят 2 свойства, которые мы указываем.</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class MinMaxGUIHelper { constructor(obj, minProp, maxProp, minDif) { this.obj = obj; this.minProp = minProp; this.maxProp = maxProp; this.minDif = minDif; } get min() { return this.obj[this.minProp]; } set min(v) { this.obj[this.minProp] = v; this.obj[this.maxProp] = Math.max(this.obj[this.maxProp], v + this.minDif); } get max() { return this.obj[this.maxProp]; } set max(v) { this.obj[this.maxProp] = v; this.min = this.min; // это вызовет setter min } } </pre> <p>Теперь мы можем настроить наш графический интерфейс следующим образом</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function updateCamera() { camera.updateProjectionMatrix(); } const gui = new GUI(); gui.add(camera, 'fov', 1, 180).onChange(updateCamera); const minMaxGUIHelper = new MinMaxGUIHelper(camera, 'near', 'far', 0.1); gui.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near').onChange(updateCamera); gui.add(minMaxGUIHelper, 'max', 0.1, 50, 0.1).name('far').onChange(updateCamera); </pre> <p>Каждый раз, когда меняются настройки камеры, нам нужно вызывать функцию камеры <a href="/docs/#api/en/cameras/PerspectiveCamera#updateProjectionMatrix"><code class="notranslate" translate="no">updateProjectionMatrix</code></a> поэтому мы сделали функцию <code class="notranslate" translate="no">updateCamera</code> передав ее в lil-gui, чтобы вызывать ее, когда что-то меняется.</p> <p></p><div translate="no" class="threejs_example_container notranslate"> <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/cameras-perspective.html"></iframe></div> <a class="threejs_center" href="/manual/examples/cameras-perspective.html" target="_blank">нажмите здесь, чтобы открыть в отдельном окне</a> </div> <p></p> <p>Вы можете просто значения и посмотреть, как они работают. Обратите внимание, что мы не делали <code class="notranslate" translate="no">aspect</code> сеттер, так как aspect взят из размера окна, поэтому, если вы хотите настроить aspect, откройте пример в новом окне, а затем измените размер окна.</p> <p>Тем не менее, я думаю, что это немного трудно увидеть, поэтому давайте изменим пример, чтобы он имел 2 камеры. Один покажет нашу сцену, как мы видим ее выше, другой покажет другую камеру, смотрящую на сцену, которую рисует первая камера, и показывает frustum камеры.</p> <p>Для этого мы можем использовать функцию ножниц (scissor) Three.js. Давайте изменим это, чтобы нарисовать 2 сцены с 2 камерами рядом, используя функцию scissor</p> <p>Для начала давайте используем HTML и CSS, чтобы определить 2 элемента рядом друг с другом. Это также поможет нам с событиями, так что обе камеры могут иметь свои собственные <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a>.</p> <pre class="prettyprint showlinemods notranslate lang-html" translate="no">&lt;body&gt; &lt;canvas id="c"&gt;&lt;/canvas&gt; + &lt;div class="split"&gt; + &lt;div id="view1" tabindex="1"&gt;&lt;/div&gt; + &lt;div id="view2" tabindex="2"&gt;&lt;/div&gt; + &lt;/div&gt; &lt;/body&gt; </pre> <p>Для начала давайте используем HTML и CSS, чтобы расположить 2 элемента рядом друг с другом. Это также поможет нам с событиями, так что обе камеры могут иметь свои собственные</p> <pre class="prettyprint showlinemods notranslate lang-css" translate="no">.split { position: absolute; left: 0; top: 0; width: 100%; height: 100%; display: flex; } .split&gt;div { width: 100%; height: 100%; } </pre> <p>Затем в нашем коде мы добавим <a href="/docs/#api/en/helpers/CameraHelper"><code class="notranslate" translate="no">CameraHelper</code></a>. <a href="/docs/#api/en/helpers/CameraHelper"><code class="notranslate" translate="no">CameraHelper</code></a> рисует frustum для <a href="/docs/#api/en/cameras/Camera"><code class="notranslate" translate="no">Camera</code></a></p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const cameraHelper = new THREE.CameraHelper(camera); ... scene.add(cameraHelper); </pre> <p>Теперь давайте посмотрим на 2 элемента view.</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const view1Elem = document.querySelector('#view1'); const view2Elem = document.querySelector('#view2'); </pre> <p>И мы установим нашу существующую <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a> так, чтобы она отвечала только за первый элемент представления.</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-const controls = new OrbitControls(camera, canvas); +const controls = new OrbitControls(camera, view1Elem); </pre> <p>Создадим вторую <a href="/docs/#api/en/cameras/PerspectiveCamera"><code class="notranslate" translate="no">PerspectiveCamera</code></a> и вторую <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a>. Вторая <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a> привязана ко второй камере и получает ввод от второго элемента view.</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const camera2 = new THREE.PerspectiveCamera( 60, // fov 2, // aspect 0.1, // near 500, // far ); camera2.position.set(40, 10, 30); camera2.lookAt(0, 5, 0); const controls2 = new OrbitControls(camera2, view2Elem); controls2.target.set(0, 5, 0); controls2.update(); </pre> <p>Наконец, нам нужно визуализировать сцену с точки зрения каждой камеры, используя функцию ножниц (scissor), чтобы визуализировать только часть холста.</p> <p>Вот функция, которая для данного элемента будет вычислять прямоугольник этого элемента, который перекрывает холст. Затем он установит плоскость отсечения (scissor) и область просмотра (fov) в этот прямоугольник и вернет aspect для этого размера.</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function setScissorForElement(elem) { const canvasRect = canvas.getBoundingClientRect(); const elemRect = elem.getBoundingClientRect(); // вычисляем относительный прямоугольник холста const right = Math.min(elemRect.right, canvasRect.right) - canvasRect.left; const left = Math.max(0, elemRect.left - canvasRect.left); const bottom = Math.min(elemRect.bottom, canvasRect.bottom) - canvasRect.top; const top = Math.max(0, elemRect.top - canvasRect.top); const width = Math.min(canvasRect.width, right - left); const height = Math.min(canvasRect.height, bottom - top); // установка области отсечения для рендеринга только на эту часть холста renderer.setScissor(left, top, width, height); renderer.setViewport(left, top, width, height); // return aspect return width / height; } </pre> <p>И теперь мы можем использовать эту функцию, чтобы нарисовать сцену дважды в нашей функции <code class="notranslate" translate="no">render</code></p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no"> function render() { - if (resizeRendererToDisplaySize(renderer)) { - const canvas = renderer.domElement; - camera.aspect = canvas.clientWidth / canvas.clientHeight; - camera.updateProjectionMatrix(); - } + resizeRendererToDisplaySize(renderer); + + // включить область отсечения + renderer.setScissorTest(true); + + // render the original view + { + const aspect = setScissorForElement(view1Elem); + + // настроить камеру для этого соотношения сторон + camera.aspect = aspect; + camera.updateProjectionMatrix(); + cameraHelper.update(); + + // не рисуем Helper камеры в исходном представлении + cameraHelper.visible = false; + + scene.background.set(0x000000); + + // отрисовка + renderer.render(scene, camera); + } + + // отрисовка со 2-й камеры + { + const aspect = setScissorForElement(view2Elem); + + // настроить камеру для этого соотношения сторон + camera2.aspect = aspect; + camera2.updateProjectionMatrix(); + + // рисуем Helper камеры во втором представлении + cameraHelper.visible = true; + + scene.background.set(0x000040); + + renderer.render(scene, camera2); + } - renderer.render(scene, camera); requestAnimationFrame(render); } requestAnimationFrame(render); } </pre> <p>Приведенный выше код устанавливает цвет фона сцены при рендеринге второго представления темно-синим, чтобы было проще различать два представления.</p> <p>Мы также можем удалить наш <code class="notranslate" translate="no">updateCamera</code> код, так как мы обновляем все в функции <code class="notranslate" translate="no">render</code>.</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-function updateCamera() { - camera.updateProjectionMatrix(); -} const gui = new GUI(); -gui.add(camera, 'fov', 1, 180).onChange(updateCamera); +gui.add(camera, 'fov', 1, 180); const minMaxGUIHelper = new MinMaxGUIHelper(camera, 'near', 'far', 0.1); -gui.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near').onChange(updateCamera); -gui.add(minMaxGUIHelper, 'max', 0.1, 50, 0.1).name('far').onChange(updateCamera); +gui.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near'); +gui.add(minMaxGUIHelper, 'max', 0.1, 50, 0.1).name('far'); </pre> <p>И теперь вы можете использовать один вид, чтобы увидеть frustum другого.</p> <p></p><div translate="no" class="threejs_example_container notranslate"> <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/cameras-perspective-2-scenes.html"></iframe></div> <a class="threejs_center" href="/manual/examples/cameras-perspective-2-scenes.html" target="_blank">нажмите здесь, чтобы открыть в отдельном окне</a> </div> <p></p> <p>Слева вы можете увидеть исходный вид, а справа вы можете увидеть вид, показывающий frustum камеры слева. Можно настроить <code class="notranslate" translate="no">near</code>, <code class="notranslate" translate="no">far</code>, <code class="notranslate" translate="no">fov</code> и перемещать камеру с помощью мыши. Вы можете увидеть, как то, что внутри frustum, показаное справа, появляется на сцене слева.</p> <p>Отрегулируйте <code class="notranslate" translate="no">near</code> примерно до 20, и вы легко увидите, как передние объекты исчезают, поскольку их больше нет в усеченном конусе. Отрегулируйте <code class="notranslate" translate="no">far</code> ниже примерно 35, и вы начнете видеть, что наземная плоскость исчезает, поскольку она больше не находится в не усеченной области.</p> <p>Возникает вопрос, почему бы просто не установить <code class="notranslate" translate="no">near</code> значение 0,0000000001 и <code class="notranslate" translate="no">far</code> 10000000000000 или что-то в этом роде, чтобы вы могли видеть все? Причина в том, что ваш GPU имеет столько точности, чтобы решить, находится ли что-то впереди или позади чего-то другого. Эта точность распределена между <code class="notranslate" translate="no">near</code> и <code class="notranslate" translate="no">far</code>. Хуже того, по умолчанию точность закрытия камеры детализирована (резкое отсечение), а точность далеко от камеры - конечна. <code class="notranslate" translate="no">near</code> медленно расширяется по мере приближения <code class="notranslate" translate="no">far</code>.</p> <p>Начиная с верхнего примера, давайте изменим код, вставив 20 сфер в ряд.</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{ const sphereRadius = 3; const sphereWidthDivisions = 32; const sphereHeightDivisions = 16; const sphereGeo = new THREE.SphereGeometry(sphereRadius, sphereWidthDivisions, sphereHeightDivisions); const numSpheres = 20; for (let i = 0; i &lt; numSpheres; ++i) { const sphereMat = new THREE.MeshPhongMaterial(); sphereMat.color.setHSL(i * .73, 1, 0.5); const mesh = new THREE.Mesh(sphereGeo, sphereMat); mesh.position.set(-sphereRadius - 1, sphereRadius + 2, i * sphereRadius * -2.2); scene.add(mesh); } } </pre> <p>и давайте установим <code class="notranslate" translate="no">near</code> = 0.00001</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const fov = 45; const aspect = 2; // the canvas default -const near = 0.1; +const near = 0.00001; const far = 100; const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); </pre> <p>Нам также нужно немного подправить код графического интерфейса, чтобы позволить 0.00001, если значение редактируется</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-gui.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near').onChange(updateCamera); +gui.add(minMaxGUIHelper, 'min', 0.00001, 50, 0.00001).name('near').onChange(updateCamera); </pre> <p>Как ты думаешь, что произойдет?</p> <p></p><div translate="no" class="threejs_example_container notranslate"> <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/cameras-z-fighting.html"></iframe></div> <a class="threejs_center" href="/manual/examples/cameras-z-fighting.html" target="_blank">нажмите здесь, чтобы открыть в отдельном окне</a> </div> <p></p> <p>Это пример <em>z fighting</em> (<a href="https://en.wikipedia.org/wiki/Z-fighting">сшивание</a>), когда графический процессор на вашем компьютере не обладает достаточной точностью, чтобы определить, какие пиксели находятся спереди, а какие - сзади.</p> <p>На тот случай, если проблема не отображается на вашей машине, вот что я вижу на своей машине</p> <div class="threejs_center"><img src="../resources/images/z-fighting.png" style="width: 570px;"></div> <p>Одно из решений состоит в том, чтобы указать использование three.js другому методу для вычисления того, какие пиксели находятся спереди, а какие - сзади. Мы можем сделать это, включив, <code class="notranslate" translate="no">logarithmicDepthBuffer</code> когда мы создаем <a href="/docs/#api/en/renderers/WebGLRenderer"><code class="notranslate" translate="no">WebGLRenderer</code></a></p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-const renderer = new THREE.WebGLRenderer({canvas}); +const renderer = new THREE.WebGLRenderer({ + canvas, + logarithmicDepthBuffer: true, +}); </pre> <p>и с этим это может работать</p> <p></p><div translate="no" class="threejs_example_container notranslate"> <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/cameras-logarithmic-depth-buffer.html"></iframe></div> <a class="threejs_center" href="/manual/examples/cameras-logarithmic-depth-buffer.html" target="_blank">нажмите здесь, чтобы открыть в отдельном окне</a> </div> <p></p> <p>Если это не помогло решить проблему, вы столкнулись с одной из причин, по которой вы не всегда можете использовать это решение. Причина в том, что это поддерживают только определенные графические процессоры. По состоянию на сентябрь 2018 года практически ни одно мобильное устройство не поддерживает это решение, как это делают большинство настольных компьютеров.</p> <p>Другая причина не выбирать это решение - оно может быть значительно медленнее, чем стандартное решение.</p> <p>Даже при таком решении разрешение все еще ограничено. Сделайте <code class="notranslate" translate="no">near</code> еще меньше или <code class="notranslate" translate="no">far</code> больше, и вы в конечном итоге столкнетесь с теми же проблемами.</p> <p>Это означает, что вы всегда должны прилагать усилия к тому, чтобы выбрать параметр <code class="notranslate" translate="no">near</code> и <code class="notranslate" translate="no">far</code>, которые соответствуют вашему варианту использования. Установите <code class="notranslate" translate="no">near</code> как можно дальше от камеры, чтобы все не исчезло. Установите <code class="notranslate" translate="no">far</code> как можно ближе к камере, чтобы все не исчезло. Если вы пытаетесь нарисовать гигантскую сцену и показать крупным планом чье-то лицо, чтобы вы могли видеть их ресницы, в то время как на заднем плане вы можете видеть весь путь в горы на расстоянии 50 километров, тогда вам нужно будет найти другое креативные решения, которые, возможно, мы рассмотрим позже. На данный момент, просто знайте, что вы должны позаботиться о том, чтобы выбрать подходящие <code class="notranslate" translate="no">near</code> и <code class="notranslate" translate="no">far</code> для ваших нужд.</p> <p>2-ая ​​самая распространенная камера - <a href="/docs/#api/en/cameras/OrthographicCamera"><code class="notranslate" translate="no">OrthographicCamera</code></a>. Вместо того, чтобы указать frustum он указывает прямоугольный паралелепипед (box) с параметрами <code class="notranslate" translate="no">left</code>, <code class="notranslate" translate="no">right</code>, <code class="notranslate" translate="no">top</code>, <code class="notranslate" translate="no">bottom</code>, <code class="notranslate" translate="no">near</code>, и <code class="notranslate" translate="no">far</code>. Поскольку он проецирует box, перспективы нет.</p> <p>Давайте изменим приведенный выше пример 2 для использования <a href="/docs/#api/en/cameras/OrthographicCamera"><code class="notranslate" translate="no">OrthographicCamera</code></a> в первом представлении.</p> <p>Сначала давайте настроим <a href="/docs/#api/en/cameras/OrthographicCamera"><code class="notranslate" translate="no">OrthographicCamera</code></a>.</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const left = -1; const right = 1; const top = 1; const bottom = -1; const near = 5; const far = 50; const camera = new THREE.OrthographicCamera(left, right, top, bottom, near, far); camera.zoom = 0.2; </pre> <p>Мы устанавливаем <code class="notranslate" translate="no">left</code> и <code class="notranslate" translate="no">bottom</code> = -1 и <code class="notranslate" translate="no">right</code> и <code class="notranslate" translate="no">top</code> = 1. Это сделало бы прямоугольник шириной 2 единицы и высотой 2 единицы, но мы собираемся отрегулировать <code class="notranslate" translate="no">left</code> и <code class="notranslate" translate="no">top</code> в соответствии со отношением сторон прямоугольника, к которому мы рисуем. Мы будем использовать свойство <code class="notranslate" translate="no">zoom</code>, чтобы упростить настройку количества единиц, отображаемых камерой.</p> <p>Давайте добавим настройки GUI для <code class="notranslate" translate="no">zoom</code></p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const gui = new GUI(); +gui.add(camera, 'zoom', 0.01, 1, 0.01).listen(); </pre> <p>Вызовем <code class="notranslate" translate="no">listen</code> говорящий lil-gui следить за изменениями. Потому что <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a> также может управлять масштабированием. Например, колесо прокрутки на мыши будет масштабироваться с помощью <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a>.</p> <p>Наконец, нам просто нужно изменить часть, которая отображает левую сторону, чтобы обновить <a href="/docs/#api/en/cameras/OrthographicCamera"><code class="notranslate" translate="no">OrthographicCamera</code></a>.</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{ const aspect = setScissorForElement(view1Elem); // обновить камеру для этого соотношения сторон - camera.aspect = aspect; + camera.left = -aspect; + camera.right = aspect; camera.updateProjectionMatrix(); cameraHelper.update(); // не рисуем Helper камеры в исходном view cameraHelper.visible = false; scene.background.set(0x000000); renderer.render(scene, camera); } </pre> <p>и теперь вы можете увидеть <a href="/docs/#api/en/cameras/OrthographicCamera"><code class="notranslate" translate="no">OrthographicCamera</code></a> в работе.</p> <p></p><div translate="no" class="threejs_example_container notranslate"> <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/cameras-orthographic-2-scenes.html"></iframe></div> <a class="threejs_center" href="/manual/examples/cameras-orthographic-2-scenes.html" target="_blank">нажмите здесь, чтобы открыть в отдельном окне</a> </div> <p></p> <p><a href="/docs/#api/en/cameras/OrthographicCamera"><code class="notranslate" translate="no">OrthographicCamera</code></a> чаще всего используется для рисования 2D-объектов. Вы решаете, сколько единиц вы хотите, чтобы камера показывала. Например, если вы хотите, чтобы один пиксель холста соответствовал одному элементу камеры, вы можете сделать что-то вроде:</p> <p>Поместить начало координат в центр и иметь 1 пиксель = 1 единицу three.js что-то вроде:</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">camera.left = -canvas.width / 2; camera.right = canvas.width / 2; camera.top = canvas.heigth / 2; camera.bottom = -canvas.height / 2; camera.near = -1; camera.far = 1; camera.zoom = 1; </pre> <p>Или, если бы мы хотели, чтобы источник находился в верхнем левом углу, как 2D-холст, мы могли бы использовать это</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">camera.left = 0; camera.right = canvas.width; camera.top = 0; camera.bottom = canvas.height; camera.near = -1; camera.far = 1; camera.zoom = 1; </pre> <p>В этом случае верхний левый угол будет 0,0, как 2D холст</p> <p>Давай попробуем! Сначала давайте настроим камеру</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const left = 0; const right = 300; // default canvas size const top = 0; const bottom = 150; // default canvas size const near = -1; const far = 1; const camera = new THREE.OrthographicCamera(left, right, top, bottom, near, far); camera.zoom = 1; </pre> <p>Затем давайте загрузим 6 текстур и сделаем 6 плоскостей, по одной на каждую текстуру. Мы будем привязывать каждую плоскость к <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">THREE.Object3D</code></a> чтобы было легче сместить плоскость, чтобы ее центр находился в ее верхнем левом углу.</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const loader = new THREE.TextureLoader(); const textures = [ loader.load('../resources/images/flower-1.jpg'), loader.load('../resources/images/flower-2.jpg'), loader.load('../resources/images/flower-3.jpg'), loader.load('../resources/images/flower-4.jpg'), loader.load('../resources/images/flower-5.jpg'), loader.load('../resources/images/flower-6.jpg'), ]; const planeSize = 256; const planeGeo = new THREE.PlaneGeometry(planeSize, planeSize); const planes = textures.map((texture) =&gt; { const planePivot = new THREE.Object3D(); scene.add(planePivot); texture.magFilter = THREE.NearestFilter; const planeMat = new THREE.MeshBasicMaterial({ map: texture, side: THREE.DoubleSide, }); const mesh = new THREE.Mesh(planeGeo, planeMat); planePivot.add(mesh); // move plane so top left corner is origin mesh.position.set(planeSize / 2, planeSize / 2, 0); return planePivot; }); </pre> <p>и нам нужно обновить камеру, если размер холста изменится.</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function render() { if (resizeRendererToDisplaySize(renderer)) { camera.right = canvas.width; camera.bottom = canvas.height; camera.updateProjectionMatrix(); } ... </pre> <p><code class="notranslate" translate="no">planes</code> - массив <a href="/docs/#api/en/objects/Mesh"><code class="notranslate" translate="no">THREE.Mesh</code></a>, по одному для каждой плоскости. Давайте переместим их в зависимости от времени.</p> <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function render(time) { time *= 0.001; // конвертировать в секунды; ... const distAcross = Math.max(20, canvas.width - planeSize); const distDown = Math.max(20, canvas.height - planeSize); // total distance to move across and back const xRange = distAcross * 2; const yRange = distDown * 2; const speed = 180; planes.forEach((plane, ndx) =&gt; { // compute a unique time for each plane const t = time * speed + ndx * 300; // get a value between 0 and range const xt = t % xRange; const yt = t % yRange; // set our position going forward if 0 to half of range // and backward if half of range to range const x = xt &lt; distAcross ? xt : xRange - xt; const y = yt &lt; distDown ? yt : yRange - yt; plane.position.set(x, y, 0); }); renderer.render(scene, camera); </pre> <p>И вы можете видеть, как изображения отскакивают от пикселей идеально по краям холста, используя пиксельную математику, как 2D холст</p> <p></p><div translate="no" class="threejs_example_container notranslate"> <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/cameras-orthographic-canvas-top-left-origin.html"></iframe></div> <a class="threejs_center" href="/manual/examples/cameras-orthographic-canvas-top-left-origin.html" target="_blank">нажмите здесь, чтобы открыть в отдельном окне</a> </div> <p></p> <p>Другое распространенное использование <a href="/docs/#api/en/cameras/OrthographicCamera"><code class="notranslate" translate="no">OrthographicCamera</code></a> для рисования - это отображение вверх, вниз, влево, вправо, спереди, сзади программ трехмерного моделирования или редактора игрового движка.</p> <div class="threejs_center"><img src="../resources/images/quad-viewport.png" style="width: 574px;"></div> <p>На скриншоте выше вы можете видеть 1 вид в перспективе и 3 вида в ортогональном виде.</p> <p>Это основы камер. Мы рассмотрим несколько распространенных способов перемещения камер в других статьях. А пока давайте перейдем к <a href="shadows.html">теням</a>.</p> <p><canvas id="c"></canvas></p> <script type="module" src="../resources/threejs-cameras.js"></script> </div> </div> </div> <script src="/manual/resources/prettify.js"></script> <script src="/manual/resources/lesson.js"></script> </body></html>
mrdoob/three.js
manual/ru/cameras.html
HTML
mit
39,411
package server; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Classe Java pour sendNewsResponse complex type. * * <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe. * * <pre> * &lt;complexType name="sendNewsResponse"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "sendNewsResponse") public class SendNewsResponse { }
wanngyue/Projet-MailBoxMananger
MailBoxD/src/server/SendNewsResponse.java
Java
mit
720
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System { public sealed partial class AppDomain : System.MarshalByRefObject { private AppDomain() { } public static AppDomain CurrentDomain { get { throw null; } } public string BaseDirectory { get { throw null; } } public string RelativeSearchPath { get { throw null; } } public event System.UnhandledExceptionEventHandler UnhandledException { add { } remove { } } public string DynamicDirectory { get { throw null; } } public string FriendlyName { get { throw null; } } public int Id { get { throw null; } } public bool IsFullyTrusted { get { throw null; } } public bool IsHomogenous { get { throw null; } } public static bool MonitoringIsEnabled { get { throw null; } set { } } public long MonitoringSurvivedMemorySize { get { throw null; } } public static long MonitoringSurvivedProcessMemorySize { get { throw null; } } public long MonitoringTotalAllocatedMemorySize { get { throw null; } } public System.TimeSpan MonitoringTotalProcessorTime { get { throw null; } } public event System.AssemblyLoadEventHandler AssemblyLoad { add { } remove { } } public event System.ResolveEventHandler AssemblyResolve { add { } remove { } } public event System.EventHandler DomainUnload { add { } remove { } } public event System.EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> FirstChanceException { add { } remove { } } public event System.EventHandler ProcessExit { add { } remove { } } public event ResolveEventHandler ReflectionOnlyAssemblyResolve { add { } remove { } } public event System.ResolveEventHandler ResourceResolve { add { } remove { } } public event System.ResolveEventHandler TypeResolve { add { } remove { } } public string ApplyPolicy(string assemblyName) { throw null; } public static System.AppDomain CreateDomain(string friendlyName) { throw null; } public int ExecuteAssembly(string assemblyFile) { throw null; } public int ExecuteAssembly(string assemblyFile, string[] args) { throw null; } public int ExecuteAssembly(string assemblyFile, string[] args, byte[] hashValue, System.Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm) { throw null; } public int ExecuteAssemblyByName(System.Reflection.AssemblyName assemblyName, params string[] args) { throw null; } public int ExecuteAssemblyByName(string assemblyName) { throw null; } public int ExecuteAssemblyByName(string assemblyName, params string[] args) { throw null; } public System.Reflection.Assembly[] GetAssemblies() { throw null; } [Obsolete("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread. https://go.microsoft.com/fwlink/?linkid=14202", false)] public static int GetCurrentThreadId() { throw null; } public object GetData(string name) { throw null; } public System.Nullable<bool> IsCompatibilitySwitchSet(string value) { throw null; } public bool IsDefaultAppDomain() { throw null; } public bool IsFinalizingForUnload() { throw null; } public System.Reflection.Assembly Load(byte[] rawAssembly) { throw null; } public System.Reflection.Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore) { throw null; } public System.Reflection.Assembly Load(System.Reflection.AssemblyName assemblyRef) { throw null; } public System.Reflection.Assembly Load(string assemblyString) { throw null; } public System.Reflection.Assembly[] ReflectionOnlyGetAssemblies() { throw null; } public void SetData(string name, object data) { } [ObsoleteAttribute("AppDomain.SetDynamicBase has been deprecated. Please investigate the use of AppDomainSetup.DynamicBase instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void SetDynamicBase(string path) { } public void SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy policy) { } public void SetThreadPrincipal(System.Security.Principal.IPrincipal principal) { } public AppDomainSetup SetupInformation { get { throw null; } } public override string ToString() { throw null; } public static void Unload(System.AppDomain domain) { } public bool ShadowCopyFiles { get { throw null; } } [Obsolete("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void AppendPrivatePath(string path) { } [Obsolete("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void ClearPrivatePath() { } [Obsolete("AppDomain.ClearShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void ClearShadowCopyPath() { } [Obsolete("AppDomain.SetCachePath has been deprecated. Please investigate the use of AppDomainSetup.CachePath instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void SetCachePath(string path) { } [Obsolete("AppDomain.SetShadowCopyFiles has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyFiles instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void SetShadowCopyFiles() { } [Obsolete("AppDomain.SetShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void SetShadowCopyPath(string path) { } public System.Runtime.Remoting.ObjectHandle CreateInstance(string assemblyName, string typeName) { throw null; } public System.Runtime.Remoting.ObjectHandle CreateInstance(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes) { throw null; } public System.Runtime.Remoting.ObjectHandle CreateInstance(string assemblyName, string typeName, object[] activationAttributes) { throw null; } public object CreateInstanceAndUnwrap(string assemblyName, string typeName) { throw null; } public object CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes) { throw null; } public object CreateInstanceAndUnwrap(string assemblyName, string typeName, object[] activationAttributes) { throw null; } public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName) { throw null; } public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes) { throw null; } public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, object[] activationAttributes) { throw null; } public object CreateInstanceFromAndUnwrap(string assemblyFile, string typeName) { throw null; } public object CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes) { throw null; } public object CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, object[] activationAttributes) { throw null; } } public sealed partial class AppDomainSetup { private AppDomainSetup() { } public string ApplicationBase { get { throw null; } } public string TargetFrameworkName { get { throw null; } } } public delegate System.Reflection.Assembly ResolveEventHandler(Object sender, ResolveEventArgs args); public delegate void AssemblyLoadEventHandler(Object sender, AssemblyLoadEventArgs args); public class AssemblyLoadEventArgs : EventArgs { public System.Reflection.Assembly LoadedAssembly { get { throw null; } } public AssemblyLoadEventArgs(System.Reflection.Assembly loadedAssembly) { } } public partial class AppDomainUnloadedException : System.SystemException { public AppDomainUnloadedException() { } protected AppDomainUnloadedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public AppDomainUnloadedException(string message) { } public AppDomainUnloadedException(string message, System.Exception innerException) { } } public partial class CannotUnloadAppDomainException : System.SystemException { public CannotUnloadAppDomainException() { } protected CannotUnloadAppDomainException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public CannotUnloadAppDomainException(string message) { } public CannotUnloadAppDomainException(string message, System.Exception innerException) { } } public sealed class ApplicationId { public ApplicationId(byte[] publicKeyToken, string name, Version version, string processorArchitecture, string culture) { } public string Culture { get { throw null; } } public string Name { get { throw null; } } public string ProcessorArchitecture { get { throw null; } } public byte[] PublicKeyToken { get { throw null; } } public Version Version { get { throw null; } } public ApplicationId Copy() { throw null; } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } } [Flags] public enum Base64FormattingOptions { None = 0, InsertLineBreaks = 1 } public static partial class BitConverter { public static readonly bool IsLittleEndian; public static long DoubleToInt64Bits(double value) { throw null; } public static byte[] GetBytes(bool value) { throw null; } public static byte[] GetBytes(char value) { throw null; } public static byte[] GetBytes(double value) { throw null; } public static byte[] GetBytes(short value) { throw null; } public static byte[] GetBytes(int value) { throw null; } public static byte[] GetBytes(long value) { throw null; } public static byte[] GetBytes(float value) { throw null; } [System.CLSCompliantAttribute(false)] public static byte[] GetBytes(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static byte[] GetBytes(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static byte[] GetBytes(ulong value) { throw null; } public static float Int32BitsToSingle(int value) { throw null; } public static double Int64BitsToDouble(long value) { throw null; } public static int SingleToInt32Bits(float value) { throw null; } public static bool ToBoolean(byte[] value, int startIndex) { throw null; } public static bool ToBoolean(System.ReadOnlySpan<byte> value) { throw null; } public static char ToChar(byte[] value, int startIndex) { throw null; } public static char ToChar(System.ReadOnlySpan<byte> value) { throw null; } public static double ToDouble(byte[] value, int startIndex) { throw null; } public static double ToDouble(System.ReadOnlySpan<byte> value) { throw null; } public static short ToInt16(byte[] value, int startIndex) { throw null; } public static short ToInt16(System.ReadOnlySpan<byte> value) { throw null; } public static int ToInt32(byte[] value, int startIndex) { throw null; } public static int ToInt32(System.ReadOnlySpan<byte> value) { throw null; } public static long ToInt64(byte[] value, int startIndex) { throw null; } public static long ToInt64(System.ReadOnlySpan<byte> value) { throw null; } public static float ToSingle(byte[] value, int startIndex) { throw null; } public static float ToSingle(System.ReadOnlySpan<byte> value) { throw null; } public static string ToString(byte[] value) { throw null; } public static string ToString(byte[] value, int startIndex) { throw null; } public static string ToString(byte[] value, int startIndex, int length) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(byte[] value, int startIndex) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(System.ReadOnlySpan<byte> value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(byte[] value, int startIndex) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(System.ReadOnlySpan<byte> value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(byte[] value, int startIndex) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(System.ReadOnlySpan<byte> value) { throw null; } public static bool TryWriteBytes(System.Span<byte> destination, bool value) { throw null; } public static bool TryWriteBytes(System.Span<byte> destination, char value) { throw null; } public static bool TryWriteBytes(System.Span<byte> destination, double value) { throw null; } public static bool TryWriteBytes(System.Span<byte> destination, short value) { throw null; } public static bool TryWriteBytes(System.Span<byte> destination, int value) { throw null; } public static bool TryWriteBytes(System.Span<byte> destination, long value) { throw null; } public static bool TryWriteBytes(System.Span<byte> destination, float value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryWriteBytes(System.Span<byte> destination, ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryWriteBytes(System.Span<byte> destination, uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryWriteBytes(System.Span<byte> destination, ulong value) { throw null; } } public static partial class Convert { public static readonly object DBNull; public static object ChangeType(object value, TypeCode typeCode) { throw null; } public static bool IsDBNull(object value) { throw null; } public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut, Base64FormattingOptions options) { throw null; } public static string ToBase64String(byte[] inArray, Base64FormattingOptions options) { throw null; } public static string ToBase64String(byte[] inArray, int offset, int length, Base64FormattingOptions options) { throw null; } public static string ToBase64String(System.ReadOnlySpan<byte> bytes, Base64FormattingOptions options = Base64FormattingOptions.None) { throw null; } public static bool ToBoolean(char value) { throw null; } public static bool ToBoolean(DateTime value) { throw null; } public static byte ToByte(DateTime value) { throw null; } public static char ToChar(bool value) { throw null; } public static char ToChar(char value) { throw null; } public static char ToChar(DateTime value) { throw null; } public static char ToChar(decimal value) { throw null; } public static char ToChar(double value) { throw null; } public static char ToChar(float value) { throw null; } public static DateTime ToDateTime(bool value) { throw null; } public static DateTime ToDateTime(byte value) { throw null; } public static DateTime ToDateTime(char value) { throw null; } public static DateTime ToDateTime(DateTime value) { throw null; } public static DateTime ToDateTime(decimal value) { throw null; } public static DateTime ToDateTime(double value) { throw null; } public static DateTime ToDateTime(short value) { throw null; } public static DateTime ToDateTime(int value) { throw null; } public static DateTime ToDateTime(long value) { throw null; } [System.CLSCompliant(false)] public static DateTime ToDateTime(sbyte value) { throw null; } public static DateTime ToDateTime(float value) { throw null; } [System.CLSCompliant(false)] public static DateTime ToDateTime(ushort value) { throw null; } [System.CLSCompliant(false)] public static DateTime ToDateTime(uint value) { throw null; } [System.CLSCompliant(false)] public static DateTime ToDateTime(ulong value) { throw null; } public static decimal ToDecimal(char value) { throw null; } public static decimal ToDecimal(DateTime value) { throw null; } public static double ToDouble(char value) { throw null; } public static double ToDouble(DateTime value) { throw null; } public static short ToInt16(DateTime value) { throw null; } public static int ToInt32(DateTime value) { throw null; } public static long ToInt64(DateTime value) { throw null; } [System.CLSCompliant(false)] public static sbyte ToSByte(DateTime value) { throw null; } public static float ToSingle(char value) { throw null; } public static float ToSingle(DateTime value) { throw null; } public static string ToString(string value) { throw null; } public static string ToString(string value, IFormatProvider provider) { throw null; } [System.CLSCompliant(false)] public static ushort ToUInt16(DateTime value) { throw null; } [System.CLSCompliant(false)] public static uint ToUInt32(DateTime value) { throw null; } [System.CLSCompliant(false)] public static ulong ToUInt64(DateTime value) { throw null; } public static object ChangeType(object value, System.Type conversionType) { throw null; } public static object ChangeType(object value, System.Type conversionType, System.IFormatProvider provider) { throw null; } public static object ChangeType(object value, System.TypeCode typeCode, System.IFormatProvider provider) { throw null; } public static byte[] FromBase64CharArray(char[] inArray, int offset, int length) { throw null; } public static byte[] FromBase64String(string s) { throw null; } public static System.TypeCode GetTypeCode(object value) { throw null; } public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut) { throw null; } public static string ToBase64String(byte[] inArray) { throw null; } public static string ToBase64String(byte[] inArray, int offset, int length) { throw null; } public static bool ToBoolean(bool value) { throw null; } public static bool ToBoolean(byte value) { throw null; } public static bool ToBoolean(decimal value) { throw null; } public static bool ToBoolean(double value) { throw null; } public static bool ToBoolean(short value) { throw null; } public static bool ToBoolean(int value) { throw null; } public static bool ToBoolean(long value) { throw null; } public static bool ToBoolean(object value) { throw null; } public static bool ToBoolean(object value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static bool ToBoolean(sbyte value) { throw null; } public static bool ToBoolean(float value) { throw null; } public static bool ToBoolean(string value) { throw null; } public static bool ToBoolean(string value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static bool ToBoolean(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool ToBoolean(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool ToBoolean(ulong value) { throw null; } public static byte ToByte(bool value) { throw null; } public static byte ToByte(byte value) { throw null; } public static byte ToByte(char value) { throw null; } public static byte ToByte(decimal value) { throw null; } public static byte ToByte(double value) { throw null; } public static byte ToByte(short value) { throw null; } public static byte ToByte(int value) { throw null; } public static byte ToByte(long value) { throw null; } public static byte ToByte(object value) { throw null; } public static byte ToByte(object value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static byte ToByte(sbyte value) { throw null; } public static byte ToByte(float value) { throw null; } public static byte ToByte(string value) { throw null; } public static byte ToByte(string value, System.IFormatProvider provider) { throw null; } public static byte ToByte(string value, int fromBase) { throw null; } [System.CLSCompliantAttribute(false)] public static byte ToByte(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static byte ToByte(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static byte ToByte(ulong value) { throw null; } public static char ToChar(byte value) { throw null; } public static char ToChar(short value) { throw null; } public static char ToChar(int value) { throw null; } public static char ToChar(long value) { throw null; } public static char ToChar(object value) { throw null; } public static char ToChar(object value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static char ToChar(sbyte value) { throw null; } public static char ToChar(string value) { throw null; } public static char ToChar(string value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static char ToChar(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static char ToChar(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static char ToChar(ulong value) { throw null; } public static System.DateTime ToDateTime(object value) { throw null; } public static System.DateTime ToDateTime(object value, System.IFormatProvider provider) { throw null; } public static System.DateTime ToDateTime(string value) { throw null; } public static System.DateTime ToDateTime(string value, System.IFormatProvider provider) { throw null; } public static decimal ToDecimal(bool value) { throw null; } public static decimal ToDecimal(byte value) { throw null; } public static decimal ToDecimal(decimal value) { throw null; } public static decimal ToDecimal(double value) { throw null; } public static decimal ToDecimal(short value) { throw null; } public static decimal ToDecimal(int value) { throw null; } public static decimal ToDecimal(long value) { throw null; } public static decimal ToDecimal(object value) { throw null; } public static decimal ToDecimal(object value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static decimal ToDecimal(sbyte value) { throw null; } public static decimal ToDecimal(float value) { throw null; } public static decimal ToDecimal(string value) { throw null; } public static decimal ToDecimal(string value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static decimal ToDecimal(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static decimal ToDecimal(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static decimal ToDecimal(ulong value) { throw null; } public static double ToDouble(bool value) { throw null; } public static double ToDouble(byte value) { throw null; } public static double ToDouble(decimal value) { throw null; } public static double ToDouble(double value) { throw null; } public static double ToDouble(short value) { throw null; } public static double ToDouble(int value) { throw null; } public static double ToDouble(long value) { throw null; } public static double ToDouble(object value) { throw null; } public static double ToDouble(object value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static double ToDouble(sbyte value) { throw null; } public static double ToDouble(float value) { throw null; } public static double ToDouble(string value) { throw null; } public static double ToDouble(string value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static double ToDouble(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static double ToDouble(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static double ToDouble(ulong value) { throw null; } public static short ToInt16(bool value) { throw null; } public static short ToInt16(byte value) { throw null; } public static short ToInt16(char value) { throw null; } public static short ToInt16(decimal value) { throw null; } public static short ToInt16(double value) { throw null; } public static short ToInt16(short value) { throw null; } public static short ToInt16(int value) { throw null; } public static short ToInt16(long value) { throw null; } public static short ToInt16(object value) { throw null; } public static short ToInt16(object value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static short ToInt16(sbyte value) { throw null; } public static short ToInt16(float value) { throw null; } public static short ToInt16(string value) { throw null; } public static short ToInt16(string value, System.IFormatProvider provider) { throw null; } public static short ToInt16(string value, int fromBase) { throw null; } [System.CLSCompliantAttribute(false)] public static short ToInt16(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static short ToInt16(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static short ToInt16(ulong value) { throw null; } public static int ToInt32(bool value) { throw null; } public static int ToInt32(byte value) { throw null; } public static int ToInt32(char value) { throw null; } public static int ToInt32(decimal value) { throw null; } public static int ToInt32(double value) { throw null; } public static int ToInt32(short value) { throw null; } public static int ToInt32(int value) { throw null; } public static int ToInt32(long value) { throw null; } public static int ToInt32(object value) { throw null; } public static int ToInt32(object value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static int ToInt32(sbyte value) { throw null; } public static int ToInt32(float value) { throw null; } public static int ToInt32(string value) { throw null; } public static int ToInt32(string value, System.IFormatProvider provider) { throw null; } public static int ToInt32(string value, int fromBase) { throw null; } [System.CLSCompliantAttribute(false)] public static int ToInt32(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static int ToInt32(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static int ToInt32(ulong value) { throw null; } public static long ToInt64(bool value) { throw null; } public static long ToInt64(byte value) { throw null; } public static long ToInt64(char value) { throw null; } public static long ToInt64(decimal value) { throw null; } public static long ToInt64(double value) { throw null; } public static long ToInt64(short value) { throw null; } public static long ToInt64(int value) { throw null; } public static long ToInt64(long value) { throw null; } public static long ToInt64(object value) { throw null; } public static long ToInt64(object value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static long ToInt64(sbyte value) { throw null; } public static long ToInt64(float value) { throw null; } public static long ToInt64(string value) { throw null; } public static long ToInt64(string value, System.IFormatProvider provider) { throw null; } public static long ToInt64(string value, int fromBase) { throw null; } [System.CLSCompliantAttribute(false)] public static long ToInt64(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static long ToInt64(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static long ToInt64(ulong value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(bool value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(byte value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(char value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(decimal value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(double value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(short value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(int value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(long value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(object value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(object value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(sbyte value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(float value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(string value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(string value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(string value, int fromBase) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ToSByte(ulong value) { throw null; } public static float ToSingle(bool value) { throw null; } public static float ToSingle(byte value) { throw null; } public static float ToSingle(decimal value) { throw null; } public static float ToSingle(double value) { throw null; } public static float ToSingle(short value) { throw null; } public static float ToSingle(int value) { throw null; } public static float ToSingle(long value) { throw null; } public static float ToSingle(object value) { throw null; } public static float ToSingle(object value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static float ToSingle(sbyte value) { throw null; } public static float ToSingle(float value) { throw null; } public static float ToSingle(string value) { throw null; } public static float ToSingle(string value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static float ToSingle(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static float ToSingle(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static float ToSingle(ulong value) { throw null; } public static string ToString(bool value) { throw null; } public static string ToString(bool value, System.IFormatProvider provider) { throw null; } public static string ToString(byte value) { throw null; } public static string ToString(byte value, System.IFormatProvider provider) { throw null; } public static string ToString(byte value, int toBase) { throw null; } public static string ToString(char value) { throw null; } public static string ToString(char value, System.IFormatProvider provider) { throw null; } public static string ToString(System.DateTime value) { throw null; } public static string ToString(System.DateTime value, System.IFormatProvider provider) { throw null; } public static string ToString(decimal value) { throw null; } public static string ToString(decimal value, System.IFormatProvider provider) { throw null; } public static string ToString(double value) { throw null; } public static string ToString(double value, System.IFormatProvider provider) { throw null; } public static string ToString(short value) { throw null; } public static string ToString(short value, System.IFormatProvider provider) { throw null; } public static string ToString(short value, int toBase) { throw null; } public static string ToString(int value) { throw null; } public static string ToString(int value, System.IFormatProvider provider) { throw null; } public static string ToString(int value, int toBase) { throw null; } public static string ToString(long value) { throw null; } public static string ToString(long value, System.IFormatProvider provider) { throw null; } public static string ToString(long value, int toBase) { throw null; } public static string ToString(object value) { throw null; } public static string ToString(object value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static string ToString(sbyte value) { throw null; } [System.CLSCompliantAttribute(false)] public static string ToString(sbyte value, System.IFormatProvider provider) { throw null; } public static string ToString(float value) { throw null; } public static string ToString(float value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static string ToString(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static string ToString(ushort value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static string ToString(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static string ToString(uint value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static string ToString(ulong value) { throw null; } [System.CLSCompliantAttribute(false)] public static string ToString(ulong value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(bool value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(byte value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(char value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(decimal value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(double value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(short value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(int value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(long value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(object value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(object value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(sbyte value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(float value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(string value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(string value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(string value, int fromBase) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ToUInt16(ulong value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(bool value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(byte value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(char value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(decimal value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(double value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(short value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(int value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(long value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(object value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(object value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(sbyte value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(float value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(string value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(string value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(string value, int fromBase) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ToUInt32(ulong value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(bool value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(byte value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(char value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(decimal value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(double value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(short value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(int value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(long value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(object value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(object value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(sbyte value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(float value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(string value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(string value, System.IFormatProvider provider) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(string value, int fromBase) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ToUInt64(ulong value) { throw null; } public static bool TryToBase64Chars(System.ReadOnlySpan<byte> bytes, System.Span<char> chars, out int charsWritten, Base64FormattingOptions options = Base64FormattingOptions.None) { throw null; } public static bool TryFromBase64String(string s, System.Span<byte> bytes, out int bytesWritten) { throw null; } public static bool TryFromBase64Chars(System.ReadOnlySpan<char> chars, System.Span<byte> bytes, out int bytesWritten) { throw null; } } public static partial class Environment { public static string CommandLine { get { throw null; } } public static string CurrentDirectory { get { throw null; } set { } } public static int CurrentManagedThreadId { get { throw null; } } public static int ExitCode { get { throw null; } set { } } public static bool HasShutdownStarted { get { throw null; } } public static bool Is64BitProcess { get { throw null; } } public static bool Is64BitOperatingSystem { get { throw null; } } public static string MachineName { get { throw null; } } public static string NewLine { get { throw null; } } public static System.OperatingSystem OSVersion { get { throw null; } } public static int ProcessorCount { get { throw null; } } public static string StackTrace { get { throw null; } } public static string SystemDirectory { get { throw null; } } public static int SystemPageSize { get { throw null; } } public static int TickCount { get { throw null; } } public static bool UserInteractive { get { throw null; } } public static string UserName { get { throw null; } } public static string UserDomainName { get { throw null; } } public static System.Version Version { get { throw null; } } public static long WorkingSet { get { throw null; } } public static string ExpandEnvironmentVariables(string name) { throw null; } public static void Exit(int exitCode) { } public static void FailFast(string message) { } public static void FailFast(string message, System.Exception exception) { } public static string[] GetCommandLineArgs() { throw null; } public static string GetEnvironmentVariable(string variable) { throw null; } public static string GetEnvironmentVariable(string variable, System.EnvironmentVariableTarget target) { throw null; } public static System.Collections.IDictionary GetEnvironmentVariables() { throw null; } public static System.Collections.IDictionary GetEnvironmentVariables(System.EnvironmentVariableTarget target) { throw null; } public static string GetFolderPath(System.Environment.SpecialFolder folder) { throw null; } public static string GetFolderPath(System.Environment.SpecialFolder folder, System.Environment.SpecialFolderOption option) { throw null; } public static string[] GetLogicalDrives() { throw null; } public static void SetEnvironmentVariable(string variable, string value) { } public static void SetEnvironmentVariable(string variable, string value, System.EnvironmentVariableTarget target) { } public enum SpecialFolder { ApplicationData = 0x001a, CommonApplicationData = 0x0023, LocalApplicationData = 0x001c, Cookies = 0x0021, Desktop = 0x0000, Favorites = 0x0006, History = 0x0022, InternetCache = 0x0020, Programs = 0x0002, MyComputer = 0x0011, MyMusic = 0x000d, MyPictures = 0x0027, MyVideos = 0x000e, Recent = 0x0008, SendTo = 0x0009, StartMenu = 0x000b, Startup = 0x0007, System = 0x0025, Templates = 0x0015, DesktopDirectory = 0x0010, Personal = 0x0005, MyDocuments = 0x0005, ProgramFiles = 0x0026, CommonProgramFiles = 0x002b, AdminTools = 0x0030, CDBurning = 0x003b, CommonAdminTools = 0x002f, CommonDocuments = 0x002e, CommonMusic = 0x0035, CommonOemLinks = 0x003a, CommonPictures = 0x0036, CommonStartMenu = 0x0016, CommonPrograms = 0X0017, CommonStartup = 0x0018, CommonDesktopDirectory = 0x0019, CommonTemplates = 0x002d, CommonVideos = 0x0037, Fonts = 0x0014, NetworkShortcuts = 0x0013, PrinterShortcuts = 0x001b, UserProfile = 0x0028, CommonProgramFilesX86 = 0x002c, ProgramFilesX86 = 0x002a, Resources = 0x0038, LocalizedResources = 0x0039, SystemX86 = 0x0029, Windows = 0x0024, } public enum SpecialFolderOption { None = 0, Create = 0x8000, DoNotVerify = 0x4000, } } public enum EnvironmentVariableTarget { Process = 0, User = 1, Machine = 2, } public enum LoaderOptimization { [System.ObsoleteAttribute("This method has been deprecated. Please use Assembly.Load() instead. https://go.microsoft.com/fwlink/?linkid=14202")] DisallowBindings = 4, [System.ObsoleteAttribute("This method has been deprecated. Please use Assembly.Load() instead. https://go.microsoft.com/fwlink/?linkid=14202")] DomainMask = 3, MultiDomain = 2, MultiDomainHost = 3, NotSpecified = 0, SingleDomain = 1, } [System.AttributeUsageAttribute(System.AttributeTargets.Method)] public sealed partial class LoaderOptimizationAttribute : System.Attribute { public LoaderOptimizationAttribute(byte value) { } public LoaderOptimizationAttribute(System.LoaderOptimization value) { } public System.LoaderOptimization Value { get { throw null; } } } public static partial class Math { public static decimal Abs(decimal value) { throw null; } public static double Abs(double value) { throw null; } public static short Abs(short value) { throw null; } public static int Abs(int value) { throw null; } public static long Abs(long value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte Abs(sbyte value) { throw null; } public static float Abs(float value) { throw null; } public static double Acos(double d) { throw null; } public static double Acosh(double d) { throw null; } public static double Asin(double d) { throw null; } public static double Asinh(double d) { throw null; } public static double Atan(double d) { throw null; } public static double Atan2(double y, double x) { throw null; } public static double Atanh(double d) { throw null; } public static long BigMul(int a, int b) { throw null; } public static double Cbrt(double d) { throw null; } public static decimal Ceiling(decimal d) { throw null; } public static double Ceiling(double a) { throw null; } public static byte Clamp(byte value, byte min, byte max) { throw null; } public static decimal Clamp(decimal value, decimal min, decimal max) { throw null; } public static double Clamp(double value, double min, double max) { throw null; } public static short Clamp(short value, short min, short max) { throw null; } public static int Clamp(int value, int min, int max) { throw null; } public static long Clamp(long value, long min, long max) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte Clamp(sbyte value, sbyte min, sbyte max) { throw null; } public static float Clamp(float value, float min, float max) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort Clamp(ushort value, ushort min, ushort max) { throw null; } [System.CLSCompliantAttribute(false)] public static uint Clamp(uint value, uint min, uint max) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong Clamp(ulong value, ulong min, ulong max) { throw null; } public static double Cos(double d) { throw null; } public static double Cosh(double value) { throw null; } public static int DivRem(int a, int b, out int result) { throw null; } public static long DivRem(long a, long b, out long result) { throw null; } public static double Exp(double d) { throw null; } public static decimal Floor(decimal d) { throw null; } public static double Floor(double d) { throw null; } public static double IEEERemainder(double x, double y) { throw null; } public static double Log(double d) { throw null; } public static double Log(double a, double newBase) { throw null; } public static double Log10(double d) { throw null; } public static byte Max(byte val1, byte val2) { throw null; } public static decimal Max(decimal val1, decimal val2) { throw null; } public static double Max(double val1, double val2) { throw null; } public static short Max(short val1, short val2) { throw null; } public static int Max(int val1, int val2) { throw null; } public static long Max(long val1, long val2) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte Max(sbyte val1, sbyte val2) { throw null; } public static float Max(float val1, float val2) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort Max(ushort val1, ushort val2) { throw null; } [System.CLSCompliantAttribute(false)] public static uint Max(uint val1, uint val2) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong Max(ulong val1, ulong val2) { throw null; } public static byte Min(byte val1, byte val2) { throw null; } public static decimal Min(decimal val1, decimal val2) { throw null; } public static double Min(double val1, double val2) { throw null; } public static short Min(short val1, short val2) { throw null; } public static int Min(int val1, int val2) { throw null; } public static long Min(long val1, long val2) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte Min(sbyte val1, sbyte val2) { throw null; } public static float Min(float val1, float val2) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort Min(ushort val1, ushort val2) { throw null; } [System.CLSCompliantAttribute(false)] public static uint Min(uint val1, uint val2) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong Min(ulong val1, ulong val2) { throw null; } public static double Pow(double x, double y) { throw null; } public static decimal Round(decimal d) { throw null; } public static decimal Round(decimal d, int decimals) { throw null; } public static decimal Round(decimal d, int decimals, System.MidpointRounding mode) { throw null; } public static decimal Round(decimal d, System.MidpointRounding mode) { throw null; } public static double Round(double a) { throw null; } public static double Round(double value, int digits) { throw null; } public static double Round(double value, int digits, System.MidpointRounding mode) { throw null; } public static double Round(double value, System.MidpointRounding mode) { throw null; } public static int Sign(decimal value) { throw null; } public static int Sign(double value) { throw null; } public static int Sign(short value) { throw null; } public static int Sign(int value) { throw null; } public static int Sign(long value) { throw null; } [System.CLSCompliantAttribute(false)] public static int Sign(sbyte value) { throw null; } public static int Sign(float value) { throw null; } public static double Sin(double a) { throw null; } public static double Sinh(double value) { throw null; } public static double Sqrt(double d) { throw null; } public static double Tan(double a) { throw null; } public static double Tanh(double value) { throw null; } public static decimal Truncate(decimal d) { throw null; } public static double Truncate(double d) { throw null; } } public static partial class MathF { public static float Abs(float x) { throw null; } public static float Acos(float x) { throw null; } public static float Acosh(float x) { throw null; } public static float Asin(float x) { throw null; } public static float Asinh(float x) { throw null; } public static float Atan(float x) { throw null; } public static float Atanh(float x) { throw null; } public static float Atan2(float y, float x) { throw null; } public static float Cbrt(float x) { throw null; } public static float Ceiling(float x) { throw null; } public static float Cos(float x) { throw null; } public static float Cosh(float x) { throw null; } public static float Exp(float x) { throw null; } public static float Floor(float x) { throw null; } public static float IEEERemainder(float x, float y) { throw null; } public static float Log(float x) { throw null; } public static float Log(float x, float y) { throw null; } public static float Log10(float x) { throw null; } public static float Max(float x, float y) { throw null; } public static float Min(float x, float y) { throw null; } public static float Pow(float x, float y) { throw null; } public static float Round(float x) { throw null; } public static float Round(float x, int digits) { throw null; } public static float Round(float x, int digits, System.MidpointRounding mode) { throw null; } public static float Round(float x, System.MidpointRounding mode) { throw null; } public static int Sign(float x) { throw null; } public static float Sin(float x) { throw null; } public static float Sinh(float x) { throw null; } public static float Sqrt(float x) { throw null; } public static float Tan(float x) { throw null; } public static float Tanh(float x) { throw null; } public static float Truncate(float x) { throw null; } } public sealed class OperatingSystem : System.ICloneable, System.Runtime.Serialization.ISerializable { private OperatingSystem() { } public OperatingSystem(System.PlatformID platform, System.Version version) { } public System.PlatformID Platform { get { throw null; } } public string ServicePack { get { throw null; } } public System.Version Version { get { throw null; } } public object Clone() { throw null; } public override string ToString() { throw null; } public string VersionString { get { throw null; } } public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public enum PlatformID { [ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)] Win32S = 0, [ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)] Win32Windows = 1, Win32NT = 2, [ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)] WinCE = 3, Unix = 4, [ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)] Xbox = 5, [ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)] MacOSX = 6 } public partial class Progress<T> : System.IProgress<T> { public Progress() { } public Progress(System.Action<T> handler) { } public event System.EventHandler<T> ProgressChanged { add { } remove { } } protected virtual void OnReport(T value) { } void System.IProgress<T>.Report(T value) { } } public partial class Random { public Random() { } public Random(int Seed) { } public virtual int Next() { throw null; } public virtual int Next(int maxValue) { throw null; } public virtual int Next(int minValue, int maxValue) { throw null; } public virtual void NextBytes(byte[] buffer) { } public virtual void NextBytes(Span<byte> buffer) { } public virtual double NextDouble() { throw null; } protected virtual double Sample() { throw null; } } public abstract partial class StringComparer : System.Collections.Generic.IComparer<string>, System.Collections.Generic.IEqualityComparer<string>, System.Collections.IComparer, System.Collections.IEqualityComparer { protected StringComparer() { } public static System.StringComparer CurrentCulture { get { throw null; } } public static System.StringComparer CurrentCultureIgnoreCase { get { throw null; } } public static System.StringComparer InvariantCulture { get { throw null; } } public static System.StringComparer InvariantCultureIgnoreCase { get { throw null; } } public static System.StringComparer Ordinal { get { throw null; } } public static System.StringComparer OrdinalIgnoreCase { get { throw null; } } public static System.StringComparer FromComparison(System.StringComparison comparisonType) { throw null; } public abstract int Compare(string x, string y); public static System.StringComparer Create(System.Globalization.CultureInfo culture, bool ignoreCase) { throw null; } public static System.StringComparer Create(System.Globalization.CultureInfo culture, System.Globalization.CompareOptions options) { throw null; } public new bool Equals(object x, object y) { throw null; } public abstract bool Equals(string x, string y); public int GetHashCode(object obj) { throw null; } public abstract int GetHashCode(string obj); public int Compare(object x, object y) { throw null; } bool System.Collections.IEqualityComparer.Equals(object x, object y) { throw null; } int System.Collections.IEqualityComparer.GetHashCode(object obj) { throw null; } } public partial class UriBuilder { public UriBuilder() { } public UriBuilder(string uri) { } public UriBuilder(string schemeName, string hostName) { } public UriBuilder(string scheme, string host, int portNumber) { } public UriBuilder(string scheme, string host, int port, string pathValue) { } public UriBuilder(string scheme, string host, int port, string path, string extraValue) { } public UriBuilder(System.Uri uri) { } public string Fragment { get { throw null; } set { } } public string Host { get { throw null; } set { } } public string Password { get { throw null; } set { } } public string Path { get { throw null; } set { } } public int Port { get { throw null; } set { } } public string Query { get { throw null; } set { } } public string Scheme { get { throw null; } set { } } public System.Uri Uri { get { throw null; } } public string UserName { get { throw null; } set { } } public override bool Equals(object rparam) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } } public abstract partial class ContextBoundObject : System.MarshalByRefObject { protected ContextBoundObject() { } } public partial class ContextMarshalException : System.SystemException { public ContextMarshalException() { } protected ContextMarshalException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public ContextMarshalException(string message) { } public ContextMarshalException(string message, System.Exception inner) { } } [System.AttributeUsage(AttributeTargets.Field, Inherited = false)] public partial class ContextStaticAttribute : System.Attribute { public ContextStaticAttribute() { } } public static class StringNormalizationExtensions { public static bool IsNormalized(this string value) { throw null; } public static bool IsNormalized(this string value, System.Text.NormalizationForm normalizationForm) { throw null; } public static String Normalize(this string value) { throw null; } public static String Normalize(this string value, System.Text.NormalizationForm normalizationForm) { throw null; } } } namespace System.Globalization { public static partial class GlobalizationExtensions { public static System.StringComparer GetStringComparer(this System.Globalization.CompareInfo compareInfo, System.Globalization.CompareOptions options) { throw null; } } } namespace System.Collections { public partial class Hashtable : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable, System.Runtime.Serialization.ISerializable, System.Runtime.Serialization.IDeserializationCallback, System.ICloneable { public Hashtable() { } public Hashtable(System.Collections.IDictionary d) { } public Hashtable(System.Collections.IDictionary d, System.Collections.IEqualityComparer equalityComparer) { } [System.ObsoleteAttribute("Please use Hashtable(IDictionary, IEqualityComparer) instead.")] public Hashtable(System.Collections.IDictionary d, System.Collections.IHashCodeProvider hcp, System.Collections.IComparer comparer) { } public Hashtable(System.Collections.IDictionary d, float loadFactor) { } public Hashtable(System.Collections.IDictionary d, float loadFactor, System.Collections.IEqualityComparer equalityComparer) { } [System.ObsoleteAttribute("Please use Hashtable(IDictionary, float, IEqualityComparer) instead.")] public Hashtable(System.Collections.IDictionary d, float loadFactor, System.Collections.IHashCodeProvider hcp, System.Collections.IComparer comparer) { } public Hashtable(System.Collections.IEqualityComparer equalityComparer) { } [System.ObsoleteAttribute("Please use Hashtable(IEqualityComparer) instead.")] public Hashtable(System.Collections.IHashCodeProvider hcp, System.Collections.IComparer comparer) { } public Hashtable(int capacity) { } public Hashtable(int capacity, System.Collections.IEqualityComparer equalityComparer) { } [System.ObsoleteAttribute("Please use Hashtable(int, IEqualityComparer) instead.")] public Hashtable(int capacity, System.Collections.IHashCodeProvider hcp, System.Collections.IComparer comparer) { } public Hashtable(int capacity, float loadFactor) { } public Hashtable(int capacity, float loadFactor, System.Collections.IEqualityComparer equalityComparer) { } [System.ObsoleteAttribute("Please use Hashtable(int, float, IEqualityComparer) instead.")] public Hashtable(int capacity, float loadFactor, System.Collections.IHashCodeProvider hcp, System.Collections.IComparer comparer) { } protected Hashtable(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } [System.ObsoleteAttribute("Please use KeyComparer properties.")] protected System.Collections.IComparer comparer { get { throw null; } set { } } public virtual int Count { get { throw null; } } protected System.Collections.IEqualityComparer EqualityComparer { get { throw null; } } [System.ObsoleteAttribute("Please use EqualityComparer property.")] protected System.Collections.IHashCodeProvider hcp { get { throw null; } set { } } public virtual bool IsFixedSize { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual bool IsSynchronized { get { throw null; } } public virtual object this[object key] { get { throw null; } set { } } public virtual System.Collections.ICollection Keys { get { throw null; } } public virtual object SyncRoot { get { throw null; } } public virtual System.Collections.ICollection Values { get { throw null; } } public virtual void Add(object key, object value) { } public virtual void Clear() { } public virtual object Clone() { throw null; } public virtual bool Contains(object key) { throw null; } public virtual bool ContainsKey(object key) { throw null; } public virtual bool ContainsValue(object value) { throw null; } public virtual void CopyTo(System.Array array, int arrayIndex) { } public virtual System.Collections.IDictionaryEnumerator GetEnumerator() { throw null; } protected virtual int GetHash(object key) { throw null; } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } protected virtual bool KeyEquals(object item, object key) { throw null; } public virtual void OnDeserialization(object sender) { } public virtual void Remove(object key) { } public static System.Collections.Hashtable Synchronized(System.Collections.Hashtable table) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class ArrayList : System.Collections.IEnumerable, System.Collections.IList, System.ICloneable { public ArrayList() { } public ArrayList(System.Collections.ICollection c) { } public ArrayList(int capacity) { } public virtual int Capacity { get { throw null; } set { } } public virtual int Count { get { throw null; } } public virtual bool IsFixedSize { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual bool IsSynchronized { get { throw null; } } public virtual object this[int index] { get { throw null; } set { } } public virtual object SyncRoot { get { throw null; } } public static System.Collections.ArrayList Adapter(System.Collections.IList list) { throw null; } public virtual int Add(object value) { throw null; } public virtual void AddRange(System.Collections.ICollection c) { } public virtual int BinarySearch(int index, int count, object value, System.Collections.IComparer comparer) { throw null; } public virtual int BinarySearch(object value) { throw null; } public virtual int BinarySearch(object value, System.Collections.IComparer comparer) { throw null; } public virtual void Clear() { } public virtual object Clone() { throw null; } public virtual bool Contains(object item) { throw null; } public virtual void CopyTo(System.Array array) { } public virtual void CopyTo(System.Array array, int arrayIndex) { } public virtual void CopyTo(int index, System.Array array, int arrayIndex, int count) { } public static System.Collections.ArrayList FixedSize(System.Collections.ArrayList list) { throw null; } public static System.Collections.IList FixedSize(System.Collections.IList list) { throw null; } public virtual System.Collections.IEnumerator GetEnumerator() { throw null; } public virtual System.Collections.IEnumerator GetEnumerator(int index, int count) { throw null; } public virtual System.Collections.ArrayList GetRange(int index, int count) { throw null; } public virtual int IndexOf(object value) { throw null; } public virtual int IndexOf(object value, int startIndex) { throw null; } public virtual int IndexOf(object value, int startIndex, int count) { throw null; } public virtual void Insert(int index, object value) { } public virtual void InsertRange(int index, System.Collections.ICollection c) { } public virtual int LastIndexOf(object value) { throw null; } public virtual int LastIndexOf(object value, int startIndex) { throw null; } public virtual int LastIndexOf(object value, int startIndex, int count) { throw null; } public static System.Collections.ArrayList ReadOnly(System.Collections.ArrayList list) { throw null; } public static System.Collections.IList ReadOnly(System.Collections.IList list) { throw null; } public virtual void Remove(object obj) { } public virtual void RemoveAt(int index) { } public virtual void RemoveRange(int index, int count) { } public static System.Collections.ArrayList Repeat(object value, int count) { throw null; } public virtual void Reverse() { } public virtual void Reverse(int index, int count) { } public virtual void SetRange(int index, System.Collections.ICollection c) { } public virtual void Sort() { } public virtual void Sort(System.Collections.IComparer comparer) { } public virtual void Sort(int index, int count, System.Collections.IComparer comparer) { } public static System.Collections.ArrayList Synchronized(System.Collections.ArrayList list) { throw null; } public static System.Collections.IList Synchronized(System.Collections.IList list) { throw null; } public virtual object[] ToArray() { throw null; } public virtual System.Array ToArray(System.Type type) { throw null; } public virtual void TrimToSize() { } } public sealed partial class Comparer : System.Collections.IComparer, System.Runtime.Serialization.ISerializable { public static readonly System.Collections.Comparer Default; public static readonly System.Collections.Comparer DefaultInvariant; public Comparer(System.Globalization.CultureInfo culture) { } private Comparer(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public int Compare(object a, object b) { throw null; } public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } [System.ObsoleteAttribute("Please use IEqualityComparer instead.")] public partial interface IHashCodeProvider { int GetHashCode(object obj); } } namespace System.CodeDom.Compiler { public class IndentedTextWriter : System.IO.TextWriter { public const string DefaultTabString = " "; public IndentedTextWriter(System.IO.TextWriter writer) { } public IndentedTextWriter(System.IO.TextWriter writer, string tabString) { } public override System.Text.Encoding Encoding { get { throw null; } } public override string NewLine { get { throw null; } set { } } public int Indent { get { throw null; } set { } } public System.IO.TextWriter InnerWriter { get { throw null; } } internal string TabString { get { throw null; } } public override void Close() { } public override void Flush() { } protected virtual void OutputTabs() { } public override void Write(string s) { } public override void Write(bool value) { } public override void Write(char value) { } public override void Write(char[] buffer) { } public override void Write(char[] buffer, int index, int count) { } public override void Write(double value) { } public override void Write(float value) { } public override void Write(int value) { } public override void Write(long value) { } public override void Write(object value) { } public override void Write(string format, object arg0) { } public override void Write(string format, object arg0, object arg1) { } public override void Write(string format, params object[] arg) { } public void WriteLineNoTabs(string s) { } public override void WriteLine(string s) { } public override void WriteLine() { } public override void WriteLine(bool value) { } public override void WriteLine(char value) { } public override void WriteLine(char[] buffer) { } public override void WriteLine(char[] buffer, int index, int count) { } public override void WriteLine(double value) { } public override void WriteLine(float value) { } public override void WriteLine(int value) { } public override void WriteLine(long value) { } public override void WriteLine(object value) { } public override void WriteLine(string format, object arg0) { } public override void WriteLine(string format, object arg0, object arg1) { } public override void WriteLine(string format, params object[] arg) { } [CLSCompliant(false)] public override void WriteLine(uint value) { } } } namespace System.Diagnostics { public partial class Stopwatch { public static readonly long Frequency; public static readonly bool IsHighResolution; public Stopwatch() { } public System.TimeSpan Elapsed { get { throw null; } } public long ElapsedMilliseconds { get { throw null; } } public long ElapsedTicks { get { throw null; } } public bool IsRunning { get { throw null; } } public static long GetTimestamp() { throw null; } public void Reset() { } public void Restart() { } public void Start() { } public static System.Diagnostics.Stopwatch StartNew() { throw null; } public void Stop() { } } } namespace System.IO { public static partial class Path { public static readonly char AltDirectorySeparatorChar; public static readonly char DirectorySeparatorChar; [ObsoleteAttribute("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")] public static readonly char[] InvalidPathChars; public static readonly char PathSeparator; public static readonly char VolumeSeparatorChar; public static string ChangeExtension(string path, string extension) { throw null; } public static string Combine(string path1, string path2) { throw null; } public static string Combine(string path1, string path2, string path3) { throw null; } public static string Combine(string path1, string path2, string path3, string path4) { throw null; } public static string Combine(params string[] paths) { throw null; } public static string GetDirectoryName(string path) { throw null; } public static ReadOnlySpan<char> GetDirectoryName(ReadOnlySpan<char> path) { throw null; } public static string GetExtension(string path) { throw null; } public static ReadOnlySpan<char> GetExtension(ReadOnlySpan<char> path) { throw null; } public static string GetFileName(string path) { throw null; } public static ReadOnlySpan<char> GetFileName(ReadOnlySpan<char> path) { throw null; } public static string GetFileNameWithoutExtension(string path) { throw null; } public static ReadOnlySpan<char> GetFileNameWithoutExtension(ReadOnlySpan<char> path) { throw null; } public static string GetFullPath(string path) { throw null; } public static string GetFullPath(string path, string basePath) { throw null; } public static char[] GetInvalidFileNameChars() { throw null; } public static char[] GetInvalidPathChars() { throw null; } public static string GetPathRoot(string path) { throw null; } public static ReadOnlySpan<char> GetPathRoot(ReadOnlySpan<char> path) { throw null; } public static string GetRandomFileName() { throw null; } public static string GetTempFileName() { throw null; } public static string GetTempPath() { throw null; } public static bool HasExtension(string path) { throw null; } public static bool HasExtension(ReadOnlySpan<char> path) { throw null; } public static bool IsPathRooted(string path) { throw null; } public static bool IsPathRooted(ReadOnlySpan<char> path) { throw null; } public static bool IsPathFullyQualified(string path) { throw null; } public static bool IsPathFullyQualified(ReadOnlySpan<char> path) { throw null; } public static string GetRelativePath(string relativeTo, string path) { throw null; } public static string Join(ReadOnlySpan<char> path1, ReadOnlySpan<char> path2) { throw null; } public static string Join(ReadOnlySpan<char> path1, ReadOnlySpan<char> path2, ReadOnlySpan<char> path3) { throw null; } public static bool TryJoin(ReadOnlySpan<char> path1, ReadOnlySpan<char> path2, Span<char> destination, out int charsWritten) { throw null; } public static bool TryJoin(ReadOnlySpan<char> path1, ReadOnlySpan<char> path2, ReadOnlySpan<char> path3, Span<char> destination, out int charsWritten) { throw null; } public static string Join(string path1, string path2) { throw null; } public static string Join(string path1, string path2, string path3) { throw null; } } public partial class BinaryReader : System.IDisposable { public BinaryReader(System.IO.Stream input) { } public BinaryReader(System.IO.Stream input, System.Text.Encoding encoding) { } public BinaryReader(System.IO.Stream input, System.Text.Encoding encoding, bool leaveOpen) { } public virtual System.IO.Stream BaseStream { get { throw null; } } public virtual void Close() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } protected virtual void FillBuffer(int numBytes) { } public virtual int PeekChar() { throw null; } public virtual int Read() { throw null; } public virtual int Read(byte[] buffer, int index, int count) { throw null; } public virtual int Read(char[] buffer, int index, int count) { throw null; } public virtual int Read(System.Span<byte> buffer) { throw null; } public virtual int Read(System.Span<char> buffer) { throw null; } protected internal int Read7BitEncodedInt() { throw null; } public virtual bool ReadBoolean() { throw null; } public virtual byte ReadByte() { throw null; } public virtual byte[] ReadBytes(int count) { throw null; } public virtual char ReadChar() { throw null; } public virtual char[] ReadChars(int count) { throw null; } public virtual decimal ReadDecimal() { throw null; } public virtual double ReadDouble() { throw null; } public virtual short ReadInt16() { throw null; } public virtual int ReadInt32() { throw null; } public virtual long ReadInt64() { throw null; } [System.CLSCompliantAttribute(false)] public virtual sbyte ReadSByte() { throw null; } public virtual float ReadSingle() { throw null; } public virtual string ReadString() { throw null; } [System.CLSCompliantAttribute(false)] public virtual ushort ReadUInt16() { throw null; } [System.CLSCompliantAttribute(false)] public virtual uint ReadUInt32() { throw null; } [System.CLSCompliantAttribute(false)] public virtual ulong ReadUInt64() { throw null; } } public partial class BinaryWriter : System.IDisposable { public static readonly System.IO.BinaryWriter Null; protected System.IO.Stream OutStream; protected BinaryWriter() { } public BinaryWriter(System.IO.Stream output) { } public BinaryWriter(System.IO.Stream output, System.Text.Encoding encoding) { } public BinaryWriter(System.IO.Stream output, System.Text.Encoding encoding, bool leaveOpen) { } public virtual System.IO.Stream BaseStream { get { throw null; } } public virtual void Close() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual void Flush() { } public virtual long Seek(int offset, System.IO.SeekOrigin origin) { throw null; } public virtual void Write(bool value) { } public virtual void Write(byte value) { } public virtual void Write(byte[] buffer) { } public virtual void Write(byte[] buffer, int index, int count) { } public virtual void Write(char ch) { } public virtual void Write(char[] chars) { } public virtual void Write(char[] chars, int index, int count) { } public virtual void Write(decimal value) { } public virtual void Write(double value) { } public virtual void Write(short value) { } public virtual void Write(int value) { } public virtual void Write(long value) { } [System.CLSCompliantAttribute(false)] public virtual void Write(sbyte value) { } public virtual void Write(float value) { } public virtual void Write(string value) { } [System.CLSCompliantAttribute(false)] public virtual void Write(ushort value) { } [System.CLSCompliantAttribute(false)] public virtual void Write(uint value) { } [System.CLSCompliantAttribute(false)] public virtual void Write(ulong value) { } public virtual void Write(System.ReadOnlySpan<byte> buffer) { } public virtual void Write(System.ReadOnlySpan<char> chars) { } protected void Write7BitEncodedInt(int value) { } } public sealed partial class BufferedStream : System.IO.Stream { public BufferedStream(Stream stream) { } public BufferedStream(Stream stream, int bufferSize) { } public override bool CanRead { get { throw null; } } public override bool CanSeek { get { throw null; } } public override bool CanWrite { get { throw null; } } public override long Length { get { throw null; } } public override long Position { get { throw null; } set { } } public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { throw null; } public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { throw null; } protected override void Dispose(bool disposing) { } public override int EndRead(System.IAsyncResult asyncResult) { throw null; } public override void EndWrite(System.IAsyncResult asyncResult) { throw null; } public override void Flush() { } public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public override int Read(byte[] array, int offset, int count) { throw null; } public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override int ReadByte() { throw null; } public override long Seek(long offset, SeekOrigin origin) { throw null; } public override void SetLength(long value) { } public override void Write(byte[] array, int offset, int count) { } public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override void WriteByte(byte value) { } public Stream UnderlyingStream { get { throw null; } } public int BufferSize { get { throw null; } } } public partial class EndOfStreamException : System.IO.IOException { public EndOfStreamException() { } public EndOfStreamException(string message) { } public EndOfStreamException(string message, System.Exception innerException) { } protected EndOfStreamException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public sealed partial class InvalidDataException : System.SystemException { public InvalidDataException() { } public InvalidDataException(string message) { } public InvalidDataException(string message, System.Exception innerException) { } } public partial class MemoryStream : System.IO.Stream { public MemoryStream() { } public MemoryStream(byte[] buffer) { } public MemoryStream(byte[] buffer, bool writable) { } public MemoryStream(byte[] buffer, int index, int count) { } public MemoryStream(byte[] buffer, int index, int count, bool writable) { } public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) { } public MemoryStream(int capacity) { } public override bool CanRead { get { throw null; } } public override bool CanSeek { get { throw null; } } public override bool CanWrite { get { throw null; } } public virtual int Capacity { get { throw null; } set { } } public override long Length { get { throw null; } } public override long Position { get { throw null; } set { } } public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { throw null; } public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { throw null; } public override void CopyTo(System.IO.Stream destination, int bufferSize) { } public override System.Threading.Tasks.Task CopyToAsync(System.IO.Stream destination, int bufferSize, System.Threading.CancellationToken cancellationToken) { throw null; } protected override void Dispose(bool disposing) { } public override int EndRead(System.IAsyncResult asyncResult) { throw null; } public override void EndWrite(System.IAsyncResult asyncResult) { throw null; } public override void Flush() { } public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public virtual byte[] GetBuffer() { throw null; } public override int Read(byte[] buffer, int offset, int count) { throw null; } public override int Read(System.Span<byte> destination) { throw null; } public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<int> ReadAsync(Memory<byte> destination, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override int ReadByte() { throw null; } public override long Seek(long offset, System.IO.SeekOrigin loc) { throw null; } public override void SetLength(long value) { } public virtual byte[] ToArray() { throw null; } public virtual bool TryGetBuffer(out System.ArraySegment<byte> buffer) { throw null; } public override void Write(byte[] buffer, int offset, int count) { } public override void Write(System.ReadOnlySpan<byte> source) { } public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory<byte> source, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override void WriteByte(byte value) { } public virtual void WriteTo(System.IO.Stream stream) { } } public partial class StreamReader : System.IO.TextReader { public static readonly new System.IO.StreamReader Null; public StreamReader(System.IO.Stream stream) { } public StreamReader(System.IO.Stream stream, bool detectEncodingFromByteOrderMarks) { } public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding) { } public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks) { } public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { } public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen) { } public StreamReader(string path) { } public StreamReader(string path, bool detectEncodingFromByteOrderMarks) { } public StreamReader(string path, System.Text.Encoding encoding) { } public StreamReader(string path, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks) { } public StreamReader(string path, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { } public virtual System.IO.Stream BaseStream { get { throw null; } } public virtual System.Text.Encoding CurrentEncoding { get { throw null; } } public bool EndOfStream { get { throw null; } } public void DiscardBufferedData() { } public override void Close() { } protected override void Dispose(bool disposing) { } public override int Peek() { throw null; } public override int Read() { throw null; } public override int Read(char[] buffer, int index, int count) { throw null; } public override int Read(System.Span<char> buffer) { throw null; } public override int ReadBlock(System.Span<char> buffer) { throw null; } public override System.Threading.Tasks.Task<int> ReadAsync(char[] buffer, int index, int count) { throw null; } public override System.Threading.Tasks.ValueTask<int> ReadAsync(System.Memory<char> buffer, System.Threading.CancellationToken cancellationToken = default) { throw null; } public override int ReadBlock(char[] buffer, int index, int count) { throw null; } public override System.Threading.Tasks.Task<int> ReadBlockAsync(char[] buffer, int index, int count) { throw null; } public override System.Threading.Tasks.ValueTask<int> ReadBlockAsync(System.Memory<char> buffer, System.Threading.CancellationToken cancellationToken = default) { throw null; } public override string ReadLine() { throw null; } public override System.Threading.Tasks.Task<string> ReadLineAsync() { throw null; } public override string ReadToEnd() { throw null; } public override System.Threading.Tasks.Task<string> ReadToEndAsync() { throw null; } } public partial class StreamWriter : System.IO.TextWriter { public static readonly new System.IO.StreamWriter Null; public StreamWriter(System.IO.Stream stream) { } public StreamWriter(System.IO.Stream stream, System.Text.Encoding encoding) { } public StreamWriter(System.IO.Stream stream, System.Text.Encoding encoding, int bufferSize) { } public StreamWriter(System.IO.Stream stream, System.Text.Encoding encoding, int bufferSize, bool leaveOpen) { } public StreamWriter(string path) { } public StreamWriter(string path, bool append) { } public StreamWriter(string path, bool append, System.Text.Encoding encoding) { } public StreamWriter(string path, bool append, System.Text.Encoding encoding, int bufferSize) { } public virtual bool AutoFlush { get { throw null; } set { } } public virtual System.IO.Stream BaseStream { get { throw null; } } public override System.Text.Encoding Encoding { get { throw null; } } public override void Close() { } protected override void Dispose(bool disposing) { } public override void Flush() { } public override System.Threading.Tasks.Task FlushAsync() { throw null; } public override void Write(char value) { } public override void Write(char[] buffer) { } public override void Write(char[] buffer, int index, int count) { } public override void Write(System.ReadOnlySpan<char> buffer) { } public override void Write(string value) { } public override void WriteLine(string value) { } public override void WriteLine(System.ReadOnlySpan<char> buffer) { } public override System.Threading.Tasks.Task WriteAsync(char value) { throw null; } public override System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count) { throw null; } public override System.Threading.Tasks.Task WriteAsync(System.ReadOnlyMemory<char> buffer, System.Threading.CancellationToken cancellationToken = default) { throw null; } public override System.Threading.Tasks.Task WriteAsync(string value) { throw null; } public override System.Threading.Tasks.Task WriteLineAsync() { throw null; } public override System.Threading.Tasks.Task WriteLineAsync(char value) { throw null; } public override System.Threading.Tasks.Task WriteLineAsync(char[] buffer, int index, int count) { throw null; } public override System.Threading.Tasks.Task WriteLineAsync(System.ReadOnlyMemory<char> buffer, System.Threading.CancellationToken cancellationToken = default) { throw null; } public override System.Threading.Tasks.Task WriteLineAsync(string value) { throw null; } } public partial class StringReader : System.IO.TextReader { public StringReader(string s) { } public override void Close() { } protected override void Dispose(bool disposing) { } public override int Peek() { throw null; } public override int Read() { throw null; } public override int Read(char[] buffer, int index, int count) { throw null; } public override int Read(System.Span<char> buffer) { throw null; } public override int ReadBlock(System.Span<char> buffer) { throw null; } public override System.Threading.Tasks.Task<int> ReadAsync(char[] buffer, int index, int count) { throw null; } public override System.Threading.Tasks.ValueTask<int> ReadAsync(System.Memory<char> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.Task<int> ReadBlockAsync(char[] buffer, int index, int count) { throw null; } public override System.Threading.Tasks.ValueTask<int> ReadBlockAsync(System.Memory<char> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override string ReadLine() { throw null; } public override System.Threading.Tasks.Task<string> ReadLineAsync() { throw null; } public override string ReadToEnd() { throw null; } public override System.Threading.Tasks.Task<string> ReadToEndAsync() { throw null; } } public partial class StringWriter : System.IO.TextWriter { public StringWriter() { } public StringWriter(System.IFormatProvider formatProvider) { } public StringWriter(System.Text.StringBuilder sb) { } public StringWriter(System.Text.StringBuilder sb, System.IFormatProvider formatProvider) { } public override System.Text.Encoding Encoding { get { throw null; } } public override void Close() { } protected override void Dispose(bool disposing) { } public override System.Threading.Tasks.Task FlushAsync() { throw null; } public virtual System.Text.StringBuilder GetStringBuilder() { throw null; } public override string ToString() { throw null; } public override void Write(char value) { } public override void Write(char[] buffer, int index, int count) { } public override void Write(System.ReadOnlySpan<char> buffer) { throw null; } public override void Write(string value) { } public override void WriteLine(System.ReadOnlySpan<char> buffer) { throw null; } public override System.Threading.Tasks.Task WriteAsync(char value) { throw null; } public override System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count) { throw null; } public override System.Threading.Tasks.Task WriteAsync(System.ReadOnlyMemory<char> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.Task WriteAsync(string value) { throw null; } public override System.Threading.Tasks.Task WriteLineAsync(char value) { throw null; } public override System.Threading.Tasks.Task WriteLineAsync(char[] buffer, int index, int count) { throw null; } public override System.Threading.Tasks.Task WriteLineAsync(System.ReadOnlyMemory<char> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.Task WriteLineAsync(string value) { throw null; } } public abstract partial class TextReader : System.MarshalByRefObject, System.IDisposable { public static readonly System.IO.TextReader Null; protected TextReader() { } public virtual void Close() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual int Peek() { throw null; } public virtual int Read() { throw null; } public virtual int Read(char[] buffer, int index, int count) { throw null; } public virtual int Read(System.Span<char> buffer) { throw null; } public virtual System.Threading.Tasks.Task<int> ReadAsync(char[] buffer, int index, int count) { throw null; } public virtual System.Threading.Tasks.ValueTask<int> ReadAsync(System.Memory<char> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual int ReadBlock(char[] buffer, int index, int count) { throw null; } public virtual int ReadBlock(System.Span<char> buffer) { throw null; } public virtual System.Threading.Tasks.Task<int> ReadBlockAsync(char[] buffer, int index, int count) { throw null; } public virtual System.Threading.Tasks.ValueTask<int> ReadBlockAsync(System.Memory<char> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual string ReadLine() { throw null; } public virtual System.Threading.Tasks.Task<string> ReadLineAsync() { throw null; } public virtual string ReadToEnd() { throw null; } public virtual System.Threading.Tasks.Task<string> ReadToEndAsync() { throw null; } public static System.IO.TextReader Synchronized(System.IO.TextReader reader) { throw null; } } public abstract partial class TextWriter : System.MarshalByRefObject, System.IDisposable { protected char[] CoreNewLine; public static readonly System.IO.TextWriter Null; protected TextWriter() { } protected TextWriter(System.IFormatProvider formatProvider) { } public abstract System.Text.Encoding Encoding { get; } public virtual System.IFormatProvider FormatProvider { get { throw null; } } public virtual string NewLine { get { throw null; } set { } } public virtual void Close() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual void Flush() { } public virtual System.Threading.Tasks.Task FlushAsync() { throw null; } public static System.IO.TextWriter Synchronized(System.IO.TextWriter writer) { throw null; } public virtual void Write(bool value) { } public virtual void Write(char value) { } public virtual void Write(char[] buffer) { } public virtual void Write(char[] buffer, int index, int count) { } public virtual void Write(decimal value) { } public virtual void Write(double value) { } public virtual void Write(int value) { } public virtual void Write(long value) { } public virtual void Write(object value) { } public virtual void Write(float value) { } public virtual void Write(string value) { } public virtual void Write(string format, object arg0) { } public virtual void Write(string format, object arg0, object arg1) { } public virtual void Write(string format, object arg0, object arg1, object arg2) { } public virtual void Write(string format, params object[] arg) { } public virtual void Write(System.Text.StringBuilder value) { } [System.CLSCompliantAttribute(false)] public virtual void Write(uint value) { } [System.CLSCompliantAttribute(false)] public virtual void Write(ulong value) { } public virtual void Write(System.ReadOnlySpan<char> buffer) { } public virtual System.Threading.Tasks.Task WriteAsync(char value) { throw null; } public System.Threading.Tasks.Task WriteAsync(char[] buffer) { throw null; } public virtual System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count) { throw null; } public virtual System.Threading.Tasks.Task WriteAsync(System.ReadOnlyMemory<char> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task WriteAsync(string value) { throw null; } public virtual System.Threading.Tasks.Task WriteAsync(System.Text.StringBuilder value, System.Threading.CancellationToken cancellationToken = default) { throw null; } public virtual void WriteLine() { } public virtual void WriteLine(bool value) { } public virtual void WriteLine(char value) { } public virtual void WriteLine(char[] buffer) { } public virtual void WriteLine(char[] buffer, int index, int count) { } public virtual void WriteLine(decimal value) { } public virtual void WriteLine(double value) { } public virtual void WriteLine(int value) { } public virtual void WriteLine(long value) { } public virtual void WriteLine(object value) { } public virtual void WriteLine(float value) { } public virtual void WriteLine(string value) { } public virtual void WriteLine(string format, object arg0) { } public virtual void WriteLine(string format, object arg0, object arg1) { } public virtual void WriteLine(string format, object arg0, object arg1, object arg2) { } public virtual void WriteLine(string format, params object[] arg) { } public virtual void WriteLine(System.Text.StringBuilder value) { } [System.CLSCompliantAttribute(false)] public virtual void WriteLine(uint value) { } [System.CLSCompliantAttribute(false)] public virtual void WriteLine(ulong value) { } public virtual void WriteLine(System.ReadOnlySpan<char> buffer) { } public virtual System.Threading.Tasks.Task WriteLineAsync() { throw null; } public virtual System.Threading.Tasks.Task WriteLineAsync(char value) { throw null; } public System.Threading.Tasks.Task WriteLineAsync(char[] buffer) { throw null; } public virtual System.Threading.Tasks.Task WriteLineAsync(char[] buffer, int index, int count) { throw null; } public virtual System.Threading.Tasks.Task WriteLineAsync(System.ReadOnlyMemory<char> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task WriteLineAsync(string value) { throw null; } public virtual System.Threading.Tasks.Task WriteLineAsync(System.Text.StringBuilder value, System.Threading.CancellationToken cancellationToken = default) { throw null; } } } namespace System.Net { public static partial class WebUtility { public static string HtmlDecode(string value) { throw null; } public static void HtmlDecode(string value, System.IO.TextWriter output) { } public static string HtmlEncode(string value) { throw null; } public static void HtmlEncode(string value, System.IO.TextWriter output) { } public static string UrlDecode(string encodedValue) { throw null; } public static byte[] UrlDecodeToBytes(byte[] encodedValue, int offset, int count) { throw null; } public static string UrlEncode(string value) { throw null; } public static byte[] UrlEncodeToBytes(byte[] value, int offset, int count) { throw null; } } } namespace System.Security { public partial interface IPermission : System.Security.ISecurityEncodable { System.Security.IPermission Copy(); void Demand(); System.Security.IPermission Intersect(System.Security.IPermission target); bool IsSubsetOf(System.Security.IPermission target); System.Security.IPermission Union(System.Security.IPermission target); } public partial interface ISecurityEncodable { void FromXml(System.Security.SecurityElement e); System.Security.SecurityElement ToXml(); } public sealed partial class SecurityElement { public SecurityElement(string tag) { } public SecurityElement(string tag, string text) { } public System.Collections.Hashtable Attributes { get; set; } public System.Collections.ArrayList Children { get; set; } public string Tag { get; set; } public string Text { get; set; } public void AddAttribute(string name, string value) { } public void AddChild(System.Security.SecurityElement child) { } public string Attribute(string name) { throw null; } public System.Security.SecurityElement Copy() { throw null; } public bool Equal(System.Security.SecurityElement other) { throw null; } public static string Escape(string str) { throw null; } public static System.Security.SecurityElement FromString(string xml) { throw null; } public static bool IsValidAttributeName(string name) { throw null; } public static bool IsValidAttributeValue(string value) { throw null; } public static bool IsValidTag(string tag) { throw null; } public static bool IsValidText(string text) { throw null; } public System.Security.SecurityElement SearchForChildByTag(string tag) { throw null; } public string SearchForTextOfTag(string tag) { throw null; } public override string ToString() => base.ToString(); } } namespace System.Security.Permissions { [System.AttributeUsageAttribute((System.AttributeTargets)109, AllowMultiple = true, Inherited = false)] public abstract partial class CodeAccessSecurityAttribute : System.Security.Permissions.SecurityAttribute { protected CodeAccessSecurityAttribute(System.Security.Permissions.SecurityAction action) : base(default(System.Security.Permissions.SecurityAction)) { } } public enum SecurityAction { Assert = 3, Demand = 2, [System.ObsoleteAttribute("Deny is obsolete and will be removed in a future release of the .NET Framework. See https://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] Deny = 4, InheritanceDemand = 7, LinkDemand = 6, PermitOnly = 5, [System.ObsoleteAttribute("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See https://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] RequestMinimum = 8, [System.ObsoleteAttribute("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See https://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] RequestOptional = 9, [System.ObsoleteAttribute("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See https://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] RequestRefuse = 10, } [System.AttributeUsageAttribute((System.AttributeTargets)109, AllowMultiple = true, Inherited = false)] public abstract partial class SecurityAttribute : System.Attribute { protected SecurityAttribute(System.Security.Permissions.SecurityAction action) { } public System.Security.Permissions.SecurityAction Action { get; set; } public bool Unrestricted { get; set; } public abstract System.Security.IPermission CreatePermission(); } [System.AttributeUsageAttribute((System.AttributeTargets)109, AllowMultiple = true, Inherited = false)] public sealed partial class SecurityPermissionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute { public SecurityPermissionAttribute(System.Security.Permissions.SecurityAction action) : base(default(System.Security.Permissions.SecurityAction)) { } public bool Assertion { get; set; } public bool BindingRedirects { get; set; } public bool ControlAppDomain { get; set; } public bool ControlDomainPolicy { get; set; } public bool ControlEvidence { get; set; } public bool ControlPolicy { get; set; } public bool ControlPrincipal { get; set; } public bool ControlThread { get; set; } public bool Execution { get; set; } public System.Security.Permissions.SecurityPermissionFlag Flags { get; set; } public bool Infrastructure { get; set; } public bool RemotingConfiguration { get; set; } public bool SerializationFormatter { get; set; } public bool SkipVerification { get; set; } public bool UnmanagedCode { get; set; } public override System.Security.IPermission CreatePermission() { throw null; } } [System.FlagsAttribute] public enum SecurityPermissionFlag { AllFlags = 16383, Assertion = 1, BindingRedirects = 8192, ControlAppDomain = 1024, ControlDomainPolicy = 256, ControlEvidence = 32, ControlPolicy = 64, ControlPrincipal = 512, ControlThread = 16, Execution = 8, Infrastructure = 4096, NoFlags = 0, RemotingConfiguration = 2048, SerializationFormatter = 128, SkipVerification = 4, UnmanagedCode = 2, } } namespace System.Reflection { public class AssemblyNameProxy : System.MarshalByRefObject { public AssemblyNameProxy() { } public System.Reflection.AssemblyName GetAssemblyName(System.String assemblyFile) { throw null; } } } namespace System.Runtime { public static class ProfileOptimization { public static void SetProfileRoot(string directoryPath) { throw null; } public static void StartProfile(string profile) { throw null; } } } namespace System.Runtime.Versioning { public sealed partial class FrameworkName : System.IEquatable<System.Runtime.Versioning.FrameworkName> { public FrameworkName(string frameworkName) { } public FrameworkName(string identifier, System.Version version) { } public FrameworkName(string identifier, System.Version version, string profile) { } public string FullName { get { throw null; } } public string Identifier { get { throw null; } } public string Profile { get { throw null; } } public System.Version Version { get { throw null; } } public override bool Equals(object obj) { throw null; } public bool Equals(System.Runtime.Versioning.FrameworkName other) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Runtime.Versioning.FrameworkName left, System.Runtime.Versioning.FrameworkName right) { throw null; } public static bool operator !=(System.Runtime.Versioning.FrameworkName left, System.Runtime.Versioning.FrameworkName right) { throw null; } public override string ToString() { throw null; } } [System.AttributeUsageAttribute((System.AttributeTargets)(5887), AllowMultiple = false, Inherited = false)] public sealed partial class ComponentGuaranteesAttribute : System.Attribute { public ComponentGuaranteesAttribute(System.Runtime.Versioning.ComponentGuaranteesOptions guarantees) { } public System.Runtime.Versioning.ComponentGuaranteesOptions Guarantees { get { throw null; } } } [System.FlagsAttribute] public enum ComponentGuaranteesOptions { Exchange = 1, None = 0, SideBySide = 4, Stable = 2, } [System.AttributeUsageAttribute((System.AttributeTargets)(224), Inherited = false)] [System.Diagnostics.ConditionalAttribute("RESOURCE_ANNOTATION_WORK")] public sealed partial class ResourceConsumptionAttribute : System.Attribute { public ResourceConsumptionAttribute(System.Runtime.Versioning.ResourceScope resourceScope) { } public ResourceConsumptionAttribute(System.Runtime.Versioning.ResourceScope resourceScope, System.Runtime.Versioning.ResourceScope consumptionScope) { } public System.Runtime.Versioning.ResourceScope ConsumptionScope { get { throw null; } } public System.Runtime.Versioning.ResourceScope ResourceScope { get { throw null; } } } [System.AttributeUsageAttribute((System.AttributeTargets)(480), Inherited = false)] [System.Diagnostics.ConditionalAttribute("RESOURCE_ANNOTATION_WORK")] public sealed partial class ResourceExposureAttribute : System.Attribute { public ResourceExposureAttribute(System.Runtime.Versioning.ResourceScope exposureLevel) { } public System.Runtime.Versioning.ResourceScope ResourceExposureLevel { get { throw null; } } } [System.FlagsAttribute] public enum ResourceScope { AppDomain = 4, Assembly = 32, Library = 8, Machine = 1, None = 0, Private = 16, Process = 2, } public static partial class VersioningHelper { public static string MakeVersionSafeName(string name, System.Runtime.Versioning.ResourceScope from, System.Runtime.Versioning.ResourceScope to) { throw null; } public static string MakeVersionSafeName(string name, System.Runtime.Versioning.ResourceScope from, System.Runtime.Versioning.ResourceScope to, System.Type type) { throw null; } } }
Jiayili1/corefx
src/System.Runtime.Extensions/ref/System.Runtime.Extensions.cs
C#
mit
119,441
/* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of The Linux Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <debug.h> #include <reg.h> #include <platform/iomap.h> #include <platform/gpio.h> void gpio_tlmm_config(uint32_t gpio, uint8_t func, uint8_t dir, uint8_t pull, uint8_t drvstr, uint32_t enable) { uint32_t val = 0; val |= pull; val |= func << 2; val |= drvstr << 6; val |= enable << 9; writel(val, (uint32_t *)GPIO_CONFIG_ADDR(gpio)); return; } void gpio_set(uint32_t gpio, uint32_t dir) { writel(dir, (uint32_t *)GPIO_IN_OUT_ADDR(gpio)); return; } uint32_t gpio_status(uint32_t gpio) { return readl(GPIO_IN_OUT_ADDR(gpio)) & GPIO_IN; } /* Configure gpio for blsp uart 2 */ void gpio_config_uart_dm(uint8_t id) { /* Configure GPIOs for BLSP1 UART3. */ /* configure rx gpio */ gpio_tlmm_config(9, 2, GPIO_INPUT, GPIO_NO_PULL, GPIO_8MA, GPIO_DISABLE); /* configure tx gpio */ gpio_tlmm_config(8, 2, GPIO_OUTPUT, GPIO_NO_PULL, GPIO_8MA, GPIO_DISABLE); }
thornbirdblue/8064_project_lk
platform/msm8226/gpio.c
C
mit
2,568
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Weibull Distribution</title> <link rel="stylesheet" href="../../../math.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.77.1"> <link rel="home" href="../../../index.html" title="Math Toolkit 2.2.1"> <link rel="up" href="../dists.html" title="Distributions"> <link rel="prev" href="uniform_dist.html" title="Uniform Distribution"> <link rel="next" href="../dist_algorithms.html" title="Distribution Algorithms"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="uniform_dist.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../dists.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../dist_algorithms.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="math_toolkit.dist_ref.dists.weibull_dist"></a><a class="link" href="weibull_dist.html" title="Weibull Distribution">Weibull Distribution</a> </h4></div></div></div> <pre class="programlisting"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">math</span><span class="special">/</span><span class="identifier">distributions</span><span class="special">/</span><span class="identifier">weibull</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span></pre> <pre class="programlisting"><span class="keyword">namespace</span> <span class="identifier">boost</span><span class="special">{</span> <span class="keyword">namespace</span> <span class="identifier">math</span><span class="special">{</span> <span class="keyword">template</span> <span class="special">&lt;</span><span class="keyword">class</span> <span class="identifier">RealType</span> <span class="special">=</span> <span class="keyword">double</span><span class="special">,</span> <span class="keyword">class</span> <a class="link" href="../../../policy.html" title="Chapter&#160;14.&#160;Policies: Controlling Precision, Error Handling etc">Policy</a> <span class="special">=</span> <a class="link" href="../../pol_ref/pol_ref_ref.html" title="Policy Class Reference">policies::policy&lt;&gt;</a> <span class="special">&gt;</span> <span class="keyword">class</span> <span class="identifier">weibull_distribution</span><span class="special">;</span> <span class="keyword">typedef</span> <span class="identifier">weibull_distribution</span><span class="special">&lt;&gt;</span> <span class="identifier">weibull</span><span class="special">;</span> <span class="keyword">template</span> <span class="special">&lt;</span><span class="keyword">class</span> <span class="identifier">RealType</span><span class="special">,</span> <span class="keyword">class</span> <a class="link" href="../../../policy.html" title="Chapter&#160;14.&#160;Policies: Controlling Precision, Error Handling etc">Policy</a><span class="special">&gt;</span> <span class="keyword">class</span> <span class="identifier">weibull_distribution</span> <span class="special">{</span> <span class="keyword">public</span><span class="special">:</span> <span class="keyword">typedef</span> <span class="identifier">RealType</span> <span class="identifier">value_type</span><span class="special">;</span> <span class="keyword">typedef</span> <span class="identifier">Policy</span> <span class="identifier">policy_type</span><span class="special">;</span> <span class="comment">// Construct:</span> <span class="identifier">weibull_distribution</span><span class="special">(</span><span class="identifier">RealType</span> <span class="identifier">shape</span><span class="special">,</span> <span class="identifier">RealType</span> <span class="identifier">scale</span> <span class="special">=</span> <span class="number">1</span><span class="special">)</span> <span class="comment">// Accessors:</span> <span class="identifier">RealType</span> <span class="identifier">shape</span><span class="special">()</span><span class="keyword">const</span><span class="special">;</span> <span class="identifier">RealType</span> <span class="identifier">scale</span><span class="special">()</span><span class="keyword">const</span><span class="special">;</span> <span class="special">};</span> <span class="special">}}</span> <span class="comment">// namespaces</span> </pre> <p> The <a href="http://en.wikipedia.org/wiki/Weibull_distribution" target="_top">Weibull distribution</a> is a continuous distribution with the <a href="http://en.wikipedia.org/wiki/Probability_density_function" target="_top">probability density function</a>: </p> <p> f(x; &#945;, &#946;) = (&#945;/&#946;) * (x / &#946;)<sup>&#945; - 1</sup> * e<sup>-(x/&#946;)<sup>&#945;</sup></sup> </p> <p> For shape parameter &#945; &#160; &gt; 0, and scale parameter &#946; &#160; &gt; 0, and x &gt; 0. </p> <p> The Weibull distribution is often used in the field of failure analysis; in particular it can mimic distributions where the failure rate varies over time. If the failure rate is: </p> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> constant over time, then &#945; &#160; = 1, suggests that items are failing from random events. </li> <li class="listitem"> decreases over time, then &#945; &#160; &lt; 1, suggesting "infant mortality". </li> <li class="listitem"> increases over time, then &#945; &#160; &gt; 1, suggesting "wear out" - more likely to fail as time goes by. </li> </ul></div> <p> The following graph illustrates how the PDF varies with the shape parameter &#945;: </p> <p> <span class="inlinemediaobject"><img src="../../../../graphs/weibull_pdf1.svg" align="middle"></span> </p> <p> While this graph illustrates how the PDF varies with the scale parameter &#946;: </p> <p> <span class="inlinemediaobject"><img src="../../../../graphs/weibull_pdf2.svg" align="middle"></span> </p> <h5> <a name="math_toolkit.dist_ref.dists.weibull_dist.h0"></a> <span class="phrase"><a name="math_toolkit.dist_ref.dists.weibull_dist.related_distributions"></a></span><a class="link" href="weibull_dist.html#math_toolkit.dist_ref.dists.weibull_dist.related_distributions">Related distributions</a> </h5> <p> When &#945; &#160; = 3, the <a href="http://en.wikipedia.org/wiki/Weibull_distribution" target="_top">Weibull distribution</a> appears similar to the <a href="http://en.wikipedia.org/wiki/Normal_distribution" target="_top">normal distribution</a>. When &#945; &#160; = 1, the Weibull distribution reduces to the <a href="http://en.wikipedia.org/wiki/Exponential_distribution" target="_top">exponential distribution</a>. The relationship of the types of extreme value distributions, of which the Weibull is but one, is discussed by <a href="http://www.worldscibooks.com/mathematics/p191.html" target="_top">Extreme Value Distributions, Theory and Applications Samuel Kotz &amp; Saralees Nadarajah</a>. </p> <h5> <a name="math_toolkit.dist_ref.dists.weibull_dist.h1"></a> <span class="phrase"><a name="math_toolkit.dist_ref.dists.weibull_dist.member_functions"></a></span><a class="link" href="weibull_dist.html#math_toolkit.dist_ref.dists.weibull_dist.member_functions">Member Functions</a> </h5> <pre class="programlisting"><span class="identifier">weibull_distribution</span><span class="special">(</span><span class="identifier">RealType</span> <span class="identifier">shape</span><span class="special">,</span> <span class="identifier">RealType</span> <span class="identifier">scale</span> <span class="special">=</span> <span class="number">1</span><span class="special">);</span> </pre> <p> Constructs a <a href="http://en.wikipedia.org/wiki/Weibull_distribution" target="_top">Weibull distribution</a> with shape <span class="emphasis"><em>shape</em></span> and scale <span class="emphasis"><em>scale</em></span>. </p> <p> Requires that the <span class="emphasis"><em>shape</em></span> and <span class="emphasis"><em>scale</em></span> parameters are both greater than zero, otherwise calls <a class="link" href="../../error_handling.html#math_toolkit.error_handling.domain_error">domain_error</a>. </p> <pre class="programlisting"><span class="identifier">RealType</span> <span class="identifier">shape</span><span class="special">()</span><span class="keyword">const</span><span class="special">;</span> </pre> <p> Returns the <span class="emphasis"><em>shape</em></span> parameter of this distribution. </p> <pre class="programlisting"><span class="identifier">RealType</span> <span class="identifier">scale</span><span class="special">()</span><span class="keyword">const</span><span class="special">;</span> </pre> <p> Returns the <span class="emphasis"><em>scale</em></span> parameter of this distribution. </p> <h5> <a name="math_toolkit.dist_ref.dists.weibull_dist.h2"></a> <span class="phrase"><a name="math_toolkit.dist_ref.dists.weibull_dist.non_member_accessors"></a></span><a class="link" href="weibull_dist.html#math_toolkit.dist_ref.dists.weibull_dist.non_member_accessors">Non-member Accessors</a> </h5> <p> All the <a class="link" href="../nmp.html" title="Non-Member Properties">usual non-member accessor functions</a> that are generic to all distributions are supported: <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.cdf">Cumulative Distribution Function</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.pdf">Probability Density Function</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.quantile">Quantile</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.hazard">Hazard Function</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.chf">Cumulative Hazard Function</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.mean">mean</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.median">median</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.mode">mode</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.variance">variance</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.sd">standard deviation</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.skewness">skewness</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.kurtosis">kurtosis</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.kurtosis_excess">kurtosis_excess</a>, <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.range">range</a> and <a class="link" href="../nmp.html#math_toolkit.dist_ref.nmp.support">support</a>. </p> <p> The domain of the random variable is [0, &#8734;]. </p> <h5> <a name="math_toolkit.dist_ref.dists.weibull_dist.h3"></a> <span class="phrase"><a name="math_toolkit.dist_ref.dists.weibull_dist.accuracy"></a></span><a class="link" href="weibull_dist.html#math_toolkit.dist_ref.dists.weibull_dist.accuracy">Accuracy</a> </h5> <p> The Weibull distribution is implemented in terms of the standard library <code class="computeroutput"><span class="identifier">log</span></code> and <code class="computeroutput"><span class="identifier">exp</span></code> functions plus <a class="link" href="../../powers/expm1.html" title="expm1">expm1</a> and <a class="link" href="../../powers/log1p.html" title="log1p">log1p</a> and as such should have very low error rates. </p> <h5> <a name="math_toolkit.dist_ref.dists.weibull_dist.h4"></a> <span class="phrase"><a name="math_toolkit.dist_ref.dists.weibull_dist.implementation"></a></span><a class="link" href="weibull_dist.html#math_toolkit.dist_ref.dists.weibull_dist.implementation">Implementation</a> </h5> <p> In the following table &#945; &#160; is the shape parameter of the distribution, &#946; &#160; is its scale parameter, <span class="emphasis"><em>x</em></span> is the random variate, <span class="emphasis"><em>p</em></span> is the probability and <span class="emphasis"><em>q = 1-p</em></span>. </p> <div class="informaltable"><table class="table"> <colgroup> <col> <col> </colgroup> <thead><tr> <th> <p> Function </p> </th> <th> <p> Implementation Notes </p> </th> </tr></thead> <tbody> <tr> <td> <p> pdf </p> </td> <td> <p> Using the relation: pdf = &#945;&#946;<sup>-&#945; </sup>x<sup>&#945; - 1</sup> e<sup>-(x/beta)<sup>alpha</sup></sup> </p> </td> </tr> <tr> <td> <p> cdf </p> </td> <td> <p> Using the relation: p = -<a class="link" href="../../powers/expm1.html" title="expm1">expm1</a>(-(x/&#946;)<sup>&#945;</sup>) </p> </td> </tr> <tr> <td> <p> cdf complement </p> </td> <td> <p> Using the relation: q = e<sup>-(x/&#946;)<sup>&#945;</sup></sup> </p> </td> </tr> <tr> <td> <p> quantile </p> </td> <td> <p> Using the relation: x = &#946; * (-<a class="link" href="../../powers/log1p.html" title="log1p">log1p</a>(-p))<sup>1/&#945;</sup> </p> </td> </tr> <tr> <td> <p> quantile from the complement </p> </td> <td> <p> Using the relation: x = &#946; * (-log(q))<sup>1/&#945;</sup> </p> </td> </tr> <tr> <td> <p> mean </p> </td> <td> <p> &#946; * &#915;(1 + 1/&#945;) </p> </td> </tr> <tr> <td> <p> variance </p> </td> <td> <p> &#946;<sup>2</sup>(&#915;(1 + 2/&#945;) - &#915;<sup>2</sup>(1 + 1/&#945;)) </p> </td> </tr> <tr> <td> <p> mode </p> </td> <td> <p> &#946;((&#945; - 1) / &#945;)<sup>1/&#945;</sup> </p> </td> </tr> <tr> <td> <p> skewness </p> </td> <td> <p> Refer to <a href="http://mathworld.wolfram.com/WeibullDistribution.html" target="_top">Weisstein, Eric W. "Weibull Distribution." From MathWorld--A Wolfram Web Resource.</a> </p> </td> </tr> <tr> <td> <p> kurtosis </p> </td> <td> <p> Refer to <a href="http://mathworld.wolfram.com/WeibullDistribution.html" target="_top">Weisstein, Eric W. "Weibull Distribution." From MathWorld--A Wolfram Web Resource.</a> </p> </td> </tr> <tr> <td> <p> kurtosis excess </p> </td> <td> <p> Refer to <a href="http://mathworld.wolfram.com/WeibullDistribution.html" target="_top">Weisstein, Eric W. "Weibull Distribution." From MathWorld--A Wolfram Web Resource.</a> </p> </td> </tr> </tbody> </table></div> <h5> <a name="math_toolkit.dist_ref.dists.weibull_dist.h5"></a> <span class="phrase"><a name="math_toolkit.dist_ref.dists.weibull_dist.references"></a></span><a class="link" href="weibull_dist.html#math_toolkit.dist_ref.dists.weibull_dist.references">References</a> </h5> <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> <a href="http://en.wikipedia.org/wiki/Weibull_distribution" target="_top">http://en.wikipedia.org/wiki/Weibull_distribution</a> </li> <li class="listitem"> <a href="http://mathworld.wolfram.com/WeibullDistribution.html" target="_top">Weisstein, Eric W. "Weibull Distribution." From MathWorld--A Wolfram Web Resource.</a> </li> <li class="listitem"> <a href="http://www.itl.nist.gov/div898/handbook/eda/section3/eda3668.htm" target="_top">Weibull in NIST Exploratory Data Analysis</a> </li> </ul></div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2006-2010, 2012-2014 Nikhar Agrawal, Anton Bikineev, Paul A. Bristow, Marco Guazzone, Christopher Kormanyos, Hubert Holin, Bruno Lalande, John Maddock, Johan R&#229;de, Gautam Sewani, Benjamin Sobotta, Thijs van den Berg, Daryle Walker and Xiaogang Zhang<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="uniform_dist.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../dists.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../dist_algorithms.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
TyRoXx/cdm
original_sources/boost_1_59_0/libs/math/doc/html/math_toolkit/dist_ref/dists/weibull_dist.html
HTML
mit
19,882
<div id="test-template-div" style="display: block;">{{viewModel.placeholder}}</div>
guillaume317/elink-port
www/lib/ion-autocomplete/test/templates/test-template.html
HTML
mit
83
using System; using System.Text; using System.Runtime.InteropServices; #pragma warning disable 1591 namespace Microsoft.Diagnostics.Runtime.Interop { [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("e391bbd8-9d8c-4418-840b-c006592a1752")] public interface IDebugSymbols4 : IDebugSymbols3 { /* IDebugSymbols */ [PreserveSig] new int GetSymbolOptions( [Out] out SYMOPT Options); [PreserveSig] new int AddSymbolOptions( [In] SYMOPT Options); [PreserveSig] new int RemoveSymbolOptions( [In] SYMOPT Options); [PreserveSig] new int SetSymbolOptions( [In] SYMOPT Options); [PreserveSig] new int GetNameByOffset( [In] UInt64 Offset, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] Int32 NameBufferSize, [Out] out UInt32 NameSize, [Out] out UInt64 Displacement); [PreserveSig] new int GetOffsetByName( [In, MarshalAs(UnmanagedType.LPStr)] string Symbol, [Out] out UInt64 Offset); [PreserveSig] new int GetNearNameByOffset( [In] UInt64 Offset, [In] int Delta, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] Int32 NameBufferSize, [Out] out UInt32 NameSize, [Out] out UInt64 Displacement); [PreserveSig] new int GetLineByOffset( [In] UInt64 Offset, [Out] out UInt32 Line, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder FileBuffer, [In] Int32 FileBufferSize, [Out] out UInt32 FileSize, [Out] out UInt64 Displacement); [PreserveSig] new int GetOffsetByLine( [In] UInt32 Line, [In, MarshalAs(UnmanagedType.LPStr)] string File, [Out] out UInt64 Offset); [PreserveSig] new int GetNumberModules( [Out] out UInt32 Loaded, [Out] out UInt32 Unloaded); [PreserveSig] new int GetModuleByIndex( [In] UInt32 Index, [Out] out UInt64 Base); [PreserveSig] new int GetModuleByModuleName( [In, MarshalAs(UnmanagedType.LPStr)] string Name, [In] UInt32 StartIndex, [Out] out UInt32 Index, [Out] out UInt64 Base); [PreserveSig] new int GetModuleByOffset( [In] UInt64 Offset, [In] UInt32 StartIndex, [Out] out UInt32 Index, [Out] out UInt64 Base); [PreserveSig] new int GetModuleNames( [In] UInt32 Index, [In] UInt64 Base, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder ImageNameBuffer, [In] Int32 ImageNameBufferSize, [Out] out UInt32 ImageNameSize, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder ModuleNameBuffer, [In] Int32 ModuleNameBufferSize, [Out] out UInt32 ModuleNameSize, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder LoadedImageNameBuffer, [In] Int32 LoadedImageNameBufferSize, [Out] out UInt32 LoadedImageNameSize); [PreserveSig] new int GetModuleParameters( [In] UInt32 Count, [In, MarshalAs(UnmanagedType.LPArray)] UInt64[] Bases, [In] UInt32 Start, [Out, MarshalAs(UnmanagedType.LPArray)] DEBUG_MODULE_PARAMETERS[] Params); [PreserveSig] new int GetSymbolModule( [In, MarshalAs(UnmanagedType.LPStr)] string Symbol, [Out] out UInt64 Base); [PreserveSig] new int GetTypeName( [In] UInt64 Module, [In] UInt32 TypeId, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] Int32 NameBufferSize, [Out] out UInt32 NameSize); [PreserveSig] new int GetTypeId( [In] UInt64 Module, [In, MarshalAs(UnmanagedType.LPStr)] string Name, [Out] out UInt32 TypeId); [PreserveSig] new int GetTypeSize( [In] UInt64 Module, [In] UInt32 TypeId, [Out] out UInt32 Size); [PreserveSig] new int GetFieldOffset( [In] UInt64 Module, [In] UInt32 TypeId, [In, MarshalAs(UnmanagedType.LPStr)] string Field, [Out] out UInt32 Offset); [PreserveSig] new int GetSymbolTypeId( [In, MarshalAs(UnmanagedType.LPStr)] string Symbol, [Out] out UInt32 TypeId, [Out] out UInt64 Module); [PreserveSig] new int GetOffsetTypeId( [In] UInt64 Offset, [Out] out UInt32 TypeId, [Out] out UInt64 Module); [PreserveSig] new int ReadTypedDataVirtual( [In] UInt64 Offset, [In] UInt64 Module, [In] UInt32 TypeId, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] Buffer, [In] UInt32 BufferSize, [Out] out UInt32 BytesRead); [PreserveSig] new int WriteTypedDataVirtual( [In] UInt64 Offset, [In] UInt64 Module, [In] UInt32 TypeId, [In] IntPtr Buffer, [In] UInt32 BufferSize, [Out] out UInt32 BytesWritten); [PreserveSig] new int OutputTypedDataVirtual( [In] DEBUG_OUTCTL OutputControl, [In] UInt64 Offset, [In] UInt64 Module, [In] UInt32 TypeId, [In] DEBUG_TYPEOPTS Flags); [PreserveSig] new int ReadTypedDataPhysical( [In] UInt64 Offset, [In] UInt64 Module, [In] UInt32 TypeId, [In] IntPtr Buffer, [In] UInt32 BufferSize, [Out] out UInt32 BytesRead); [PreserveSig] new int WriteTypedDataPhysical( [In] UInt64 Offset, [In] UInt64 Module, [In] UInt32 TypeId, [In] IntPtr Buffer, [In] UInt32 BufferSize, [Out] out UInt32 BytesWritten); [PreserveSig] new int OutputTypedDataPhysical( [In] DEBUG_OUTCTL OutputControl, [In] UInt64 Offset, [In] UInt64 Module, [In] UInt32 TypeId, [In] DEBUG_TYPEOPTS Flags); [PreserveSig] new int GetScope( [Out] out UInt64 InstructionOffset, [Out] out DEBUG_STACK_FRAME ScopeFrame, [In] IntPtr ScopeContext, [In] UInt32 ScopeContextSize); [PreserveSig] new int SetScope( [In] UInt64 InstructionOffset, [In] DEBUG_STACK_FRAME ScopeFrame, [In] IntPtr ScopeContext, [In] UInt32 ScopeContextSize); [PreserveSig] new int ResetScope(); [PreserveSig] new int GetScopeSymbolGroup( [In] DEBUG_SCOPE_GROUP Flags, [In, MarshalAs(UnmanagedType.Interface)] IDebugSymbolGroup Update, [Out, MarshalAs(UnmanagedType.Interface)] out IDebugSymbolGroup Symbols); [PreserveSig] new int CreateSymbolGroup( [Out, MarshalAs(UnmanagedType.Interface)] out IDebugSymbolGroup Group); [PreserveSig] new int StartSymbolMatch( [In, MarshalAs(UnmanagedType.LPStr)] string Pattern, [Out] out UInt64 Handle); [PreserveSig] new int GetNextSymbolMatch( [In] UInt64 Handle, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 MatchSize, [Out] out UInt64 Offset); [PreserveSig] new int EndSymbolMatch( [In] UInt64 Handle); [PreserveSig] new int Reload( [In, MarshalAs(UnmanagedType.LPStr)] string Module); [PreserveSig] new int GetSymbolPath( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 PathSize); [PreserveSig] new int SetSymbolPath( [In, MarshalAs(UnmanagedType.LPStr)] string Path); [PreserveSig] new int AppendSymbolPath( [In, MarshalAs(UnmanagedType.LPStr)] string Addition); [PreserveSig] new int GetImagePath( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 PathSize); [PreserveSig] new int SetImagePath( [In, MarshalAs(UnmanagedType.LPStr)] string Path); [PreserveSig] new int AppendImagePath( [In, MarshalAs(UnmanagedType.LPStr)] string Addition); [PreserveSig] new int GetSourcePath( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 PathSize); [PreserveSig] new int GetSourcePathElement( [In] UInt32 Index, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 ElementSize); [PreserveSig] new int SetSourcePath( [In, MarshalAs(UnmanagedType.LPStr)] string Path); [PreserveSig] new int AppendSourcePath( [In, MarshalAs(UnmanagedType.LPStr)] string Addition); [PreserveSig] new int FindSourceFile( [In] UInt32 StartElement, [In, MarshalAs(UnmanagedType.LPStr)] string File, [In] DEBUG_FIND_SOURCE Flags, [Out] out UInt32 FoundElement, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 FoundSize); [PreserveSig] new int GetSourceFileLineOffsets( [In, MarshalAs(UnmanagedType.LPStr)] string File, [Out, MarshalAs(UnmanagedType.LPArray)] UInt64[] Buffer, [In] Int32 BufferLines, [Out] out UInt32 FileLines); /* IDebugSymbols2 */ [PreserveSig] new int GetModuleVersionInformation( [In] UInt32 Index, [In] UInt64 Base, [In, MarshalAs(UnmanagedType.LPStr)] string Item, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] buffer, [In] UInt32 BufferSize, [Out] out UInt32 VerInfoSize); [PreserveSig] new int GetModuleNameString( [In] DEBUG_MODNAME Which, [In] UInt32 Index, [In] UInt64 Base, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] UInt32 BufferSize, [Out] out UInt32 NameSize); [PreserveSig] new int GetConstantName( [In] UInt64 Module, [In] UInt32 TypeId, [In] UInt64 Value, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 NameSize); [PreserveSig] new int GetFieldName( [In] UInt64 Module, [In] UInt32 TypeId, [In] UInt32 FieldIndex, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 NameSize); [PreserveSig] new int GetTypeOptions( [Out] out DEBUG_TYPEOPTS Options); [PreserveSig] new int AddTypeOptions( [In] DEBUG_TYPEOPTS Options); [PreserveSig] new int RemoveTypeOptions( [In] DEBUG_TYPEOPTS Options); [PreserveSig] new int SetTypeOptions( [In] DEBUG_TYPEOPTS Options); /* IDebugSymbols3 */ [PreserveSig] new int GetNameByOffsetWide( [In] UInt64 Offset, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] Int32 NameBufferSize, [Out] out UInt32 NameSize, [Out] out UInt64 Displacement); [PreserveSig] new int GetOffsetByNameWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Symbol, [Out] out UInt64 Offset); [PreserveSig] new int GetNearNameByOffsetWide( [In] UInt64 Offset, [In] int Delta, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] Int32 NameBufferSize, [Out] out UInt32 NameSize, [Out] out UInt64 Displacement); [PreserveSig] new int GetLineByOffsetWide( [In] UInt64 Offset, [Out] out UInt32 Line, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder FileBuffer, [In] Int32 FileBufferSize, [Out] out UInt32 FileSize, [Out] out UInt64 Displacement); [PreserveSig] new int GetOffsetByLineWide( [In] UInt32 Line, [In, MarshalAs(UnmanagedType.LPWStr)] string File, [Out] out UInt64 Offset); [PreserveSig] new int GetModuleByModuleNameWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Name, [In] UInt32 StartIndex, [Out] out UInt32 Index, [Out] out UInt64 Base); [PreserveSig] new int GetSymbolModuleWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Symbol, [Out] out UInt64 Base); [PreserveSig] new int GetTypeNameWide( [In] UInt64 Module, [In] UInt32 TypeId, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] Int32 NameBufferSize, [Out] out UInt32 NameSize); [PreserveSig] new int GetTypeIdWide( [In] UInt64 Module, [In, MarshalAs(UnmanagedType.LPWStr)] string Name, [Out] out UInt32 TypeId); [PreserveSig] new int GetFieldOffsetWide( [In] UInt64 Module, [In] UInt32 TypeId, [In, MarshalAs(UnmanagedType.LPWStr)] string Field, [Out] out UInt32 Offset); [PreserveSig] new int GetSymbolTypeIdWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Symbol, [Out] out UInt32 TypeId, [Out] out UInt64 Module); [PreserveSig] new int GetScopeSymbolGroup2( [In] DEBUG_SCOPE_GROUP Flags, [In, MarshalAs(UnmanagedType.Interface)] IDebugSymbolGroup2 Update, [Out, MarshalAs(UnmanagedType.Interface)] out IDebugSymbolGroup2 Symbols); [PreserveSig] new int CreateSymbolGroup2( [Out, MarshalAs(UnmanagedType.Interface)] out IDebugSymbolGroup2 Group); [PreserveSig] new int StartSymbolMatchWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Pattern, [Out] out UInt64 Handle); [PreserveSig] new int GetNextSymbolMatchWide( [In] UInt64 Handle, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 MatchSize, [Out] out UInt64 Offset); [PreserveSig] new int ReloadWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Module); [PreserveSig] new int GetSymbolPathWide( [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 PathSize); [PreserveSig] new int SetSymbolPathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Path); [PreserveSig] new int AppendSymbolPathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Addition); [PreserveSig] new int GetImagePathWide( [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 PathSize); [PreserveSig] new int SetImagePathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Path); [PreserveSig] new int AppendImagePathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Addition); [PreserveSig] new int GetSourcePathWide( [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 PathSize); [PreserveSig] new int GetSourcePathElementWide( [In] UInt32 Index, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 ElementSize); [PreserveSig] new int SetSourcePathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Path); [PreserveSig] new int AppendSourcePathWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Addition); [PreserveSig] new int FindSourceFileWide( [In] UInt32 StartElement, [In, MarshalAs(UnmanagedType.LPWStr)] string File, [In] DEBUG_FIND_SOURCE Flags, [Out] out UInt32 FoundElement, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 FoundSize); [PreserveSig] new int GetSourceFileLineOffsetsWide( [In, MarshalAs(UnmanagedType.LPWStr)] string File, [Out, MarshalAs(UnmanagedType.LPArray)] UInt64[] Buffer, [In] Int32 BufferLines, [Out] out UInt32 FileLines); [PreserveSig] new int GetModuleVersionInformationWide( [In] UInt32 Index, [In] UInt64 Base, [In, MarshalAs(UnmanagedType.LPWStr)] string Item, [In] IntPtr Buffer, [In] Int32 BufferSize, [Out] out UInt32 VerInfoSize); [PreserveSig] new int GetModuleNameStringWide( [In] DEBUG_MODNAME Which, [In] UInt32 Index, [In] UInt64 Base, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 NameSize); [PreserveSig] new int GetConstantNameWide( [In] UInt64 Module, [In] UInt32 TypeId, [In] UInt64 Value, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 NameSize); [PreserveSig] new int GetFieldNameWide( [In] UInt64 Module, [In] UInt32 TypeId, [In] UInt32 FieldIndex, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 NameSize); [PreserveSig] new int IsManagedModule( [In] UInt32 Index, [In] UInt64 Base ); [PreserveSig] new int GetModuleByModuleName2( [In, MarshalAs(UnmanagedType.LPStr)] string Name, [In] UInt32 StartIndex, [In] DEBUG_GETMOD Flags, [Out] out UInt32 Index, [Out] out UInt64 Base ); [PreserveSig] new int GetModuleByModuleName2Wide( [In, MarshalAs(UnmanagedType.LPWStr)] string Name, [In] UInt32 StartIndex, [In] DEBUG_GETMOD Flags, [Out] out UInt32 Index, [Out] out UInt64 Base ); [PreserveSig] new int GetModuleByOffset2( [In] UInt64 Offset, [In] UInt32 StartIndex, [In] DEBUG_GETMOD Flags, [Out] out UInt32 Index, [Out] out UInt64 Base ); [PreserveSig] new int AddSyntheticModule( [In] UInt64 Base, [In] UInt32 Size, [In, MarshalAs(UnmanagedType.LPStr)] string ImagePath, [In, MarshalAs(UnmanagedType.LPStr)] string ModuleName, [In] DEBUG_ADDSYNTHMOD Flags ); [PreserveSig] new int AddSyntheticModuleWide( [In] UInt64 Base, [In] UInt32 Size, [In, MarshalAs(UnmanagedType.LPWStr)] string ImagePath, [In, MarshalAs(UnmanagedType.LPWStr)] string ModuleName, [In] DEBUG_ADDSYNTHMOD Flags ); [PreserveSig] new int RemoveSyntheticModule( [In] UInt64 Base ); [PreserveSig] new int GetCurrentScopeFrameIndex( [Out] out UInt32 Index ); [PreserveSig] new int SetScopeFrameByIndex( [In] UInt32 Index ); [PreserveSig] new int SetScopeFromJitDebugInfo( [In] UInt32 OutputControl, [In] UInt64 InfoOffset ); [PreserveSig] new int SetScopeFromStoredEvent( ); [PreserveSig] new int OutputSymbolByOffset( [In] UInt32 OutputControl, [In] DEBUG_OUTSYM Flags, [In] UInt64 Offset ); [PreserveSig] new int GetFunctionEntryByOffset( [In] UInt64 Offset, [In] DEBUG_GETFNENT Flags, [In] IntPtr Buffer, [In] UInt32 BufferSize, [Out] out UInt32 BufferNeeded ); [PreserveSig] new int GetFieldTypeAndOffset( [In] UInt64 Module, [In] UInt32 ContainerTypeId, [In, MarshalAs(UnmanagedType.LPStr)] string Field, [Out] out UInt32 FieldTypeId, [Out] out UInt32 Offset ); [PreserveSig] new int GetFieldTypeAndOffsetWide( [In] UInt64 Module, [In] UInt32 ContainerTypeId, [In, MarshalAs(UnmanagedType.LPWStr)] string Field, [Out] out UInt32 FieldTypeId, [Out] out UInt32 Offset ); [PreserveSig] new int AddSyntheticSymbol( [In] UInt64 Offset, [In] UInt32 Size, [In, MarshalAs(UnmanagedType.LPStr)] string Name, [In] DEBUG_ADDSYNTHSYM Flags, [Out] out DEBUG_MODULE_AND_ID Id ); [PreserveSig] new int AddSyntheticSymbolWide( [In] UInt64 Offset, [In] UInt32 Size, [In, MarshalAs(UnmanagedType.LPWStr)] string Name, [In] DEBUG_ADDSYNTHSYM Flags, [Out] out DEBUG_MODULE_AND_ID Id ); [PreserveSig] new int RemoveSyntheticSymbol([In, MarshalAs(UnmanagedType.LPStruct)] DEBUG_MODULE_AND_ID Id ); [PreserveSig] new int GetSymbolEntriesByOffset( [In] UInt64 Offset, [In] UInt32 Flags, [Out, MarshalAs(UnmanagedType.LPArray)] DEBUG_MODULE_AND_ID[] Ids, [Out, MarshalAs(UnmanagedType.LPArray)] UInt64[] Displacements, [In] UInt32 IdsCount, [Out] out UInt32 Entries ); [PreserveSig] new int GetSymbolEntriesByName( [In, MarshalAs(UnmanagedType.LPStr)] string Symbol, [In] UInt32 Flags, [Out, MarshalAs(UnmanagedType.LPArray)] DEBUG_MODULE_AND_ID[] Ids, [In] UInt32 IdsCount, [Out] out UInt32 Entries ); [PreserveSig] new int GetSymbolEntriesByNameWide( [In, MarshalAs(UnmanagedType.LPWStr)] string Symbol, [In] UInt32 Flags, [Out, MarshalAs(UnmanagedType.LPArray)] DEBUG_MODULE_AND_ID[] Ids, [In] UInt32 IdsCount, [Out] out UInt32 Entries ); [PreserveSig] new int GetSymbolEntryByToken( [In] UInt64 ModuleBase, [In] UInt32 Token, [Out] out DEBUG_MODULE_AND_ID Id ); [PreserveSig] new int GetSymbolEntryInformation( [In, MarshalAs(UnmanagedType.LPStruct)] DEBUG_MODULE_AND_ID Id, [Out] out DEBUG_SYMBOL_ENTRY Info ); [PreserveSig] new int GetSymbolEntryString( [In, MarshalAs(UnmanagedType.LPStruct)] DEBUG_MODULE_AND_ID Id, [In] UInt32 Which, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 StringSize ); [PreserveSig] new int GetSymbolEntryStringWide( [In, MarshalAs(UnmanagedType.LPStruct)] DEBUG_MODULE_AND_ID Id, [In] UInt32 Which, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 StringSize ); [PreserveSig] new int GetSymbolEntryOffsetRegions( [In, MarshalAs(UnmanagedType.LPStruct)] DEBUG_MODULE_AND_ID Id, [In] UInt32 Flags, [Out, MarshalAs(UnmanagedType.LPArray)] DEBUG_OFFSET_REGION[] Regions, [In] UInt32 RegionsCount, [Out] out UInt32 RegionsAvail ); [PreserveSig] new int GetSymbolEntryBySymbolEntry( [In, MarshalAs(UnmanagedType.LPStruct)] DEBUG_MODULE_AND_ID FromId, [In] UInt32 Flags, [Out] out DEBUG_MODULE_AND_ID ToId ); [PreserveSig] new int GetSourceEntriesByOffset( [In] UInt64 Offset, [In] UInt32 Flags, [Out, MarshalAs(UnmanagedType.LPArray)] DEBUG_SYMBOL_SOURCE_ENTRY[] Entries, [In] UInt32 EntriesCount, [Out] out UInt32 EntriesAvail ); [PreserveSig] new int GetSourceEntriesByLine( [In] UInt32 Line, [In, MarshalAs(UnmanagedType.LPStr)] string File, [In] UInt32 Flags, [Out, MarshalAs(UnmanagedType.LPArray)] DEBUG_SYMBOL_SOURCE_ENTRY[] Entries, [In] UInt32 EntriesCount, [Out] out UInt32 EntriesAvail ); [PreserveSig] new int GetSourceEntriesByLineWide( [In] UInt32 Line, [In, MarshalAs(UnmanagedType.LPWStr)] string File, [In] UInt32 Flags, [Out, MarshalAs(UnmanagedType.LPArray)] DEBUG_SYMBOL_SOURCE_ENTRY[] Entries, [In] UInt32 EntriesCount, [Out] out UInt32 EntriesAvail ); [PreserveSig] new int GetSourceEntryString( [In, MarshalAs(UnmanagedType.LPStruct)] DEBUG_SYMBOL_SOURCE_ENTRY Entry, [In] UInt32 Which, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 StringSize ); [PreserveSig] new int GetSourceEntryStringWide( [In, MarshalAs(UnmanagedType.LPStruct)] DEBUG_SYMBOL_SOURCE_ENTRY Entry, [In] UInt32 Which, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder Buffer, [In] Int32 BufferSize, [Out] out UInt32 StringSize ); [PreserveSig] new int GetSourceEntryOffsetRegions( [In, MarshalAs(UnmanagedType.LPStruct)] DEBUG_SYMBOL_SOURCE_ENTRY Entry, [In] UInt32 Flags, [Out, MarshalAs(UnmanagedType.LPArray)] DEBUG_OFFSET_REGION[] Regions, [In] UInt32 RegionsCount, [Out] out UInt32 RegionsAvail ); [PreserveSig] new int GetSourceEntryBySourceEntry( [In, MarshalAs(UnmanagedType.LPStruct)] DEBUG_SYMBOL_SOURCE_ENTRY FromEntry, [In] UInt32 Flags, [Out] out DEBUG_SYMBOL_SOURCE_ENTRY ToEntry ); /* IDebugSymbols4 */ [PreserveSig] int GetScopeEx( [Out] out UInt64 InstructionOffset, [Out] out DEBUG_STACK_FRAME_EX ScopeFrame, [In] IntPtr ScopeContext, [In] UInt32 ScopeContextSize ); [PreserveSig] int SetScopeEx( [In] UInt64 InstructionOffset, [In, MarshalAs(UnmanagedType.LPStruct)] DEBUG_STACK_FRAME_EX ScopeFrame, [In] IntPtr ScopeContext, [In] UInt32 ScopeContextSize ); [PreserveSig] int GetNameByInlineContext( [In] UInt64 Offset, [In] UInt32 InlineContext, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] Int32 NameBufferSize, [Out] out UInt32 NameSize, [Out] out UInt64 Displacement ); [PreserveSig] int GetNameByInlineContextWide( [In] UInt64 Offset, [In] UInt32 InlineContext, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder NameBuffer, [In] Int32 NameBufferSize, [Out] out UInt32 NameSize, [Out] out UInt64 Displacement ); [PreserveSig] int GetLineByInlineContext( [In] UInt64 Offset, [In] UInt32 InlineContext, [Out] out UInt32 Line, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder FileBuffer, [In] Int32 FileBufferSize, [Out] out UInt32 FileSize, [Out] out UInt64 Displacement ); [PreserveSig] int GetLineByInlineContextWide( [In] UInt64 Offset, [In] UInt32 InlineContext, [Out] out UInt32 Line, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder FileBuffer, [In] Int32 FileBufferSize, [Out] out UInt32 FileSize, [Out] out UInt64 Displacement ); [PreserveSig] int OutputSymbolByInlineContext( [In] UInt32 OutputControl, [In] UInt32 Flags, [In] UInt64 Offset, [In] UInt32 InlineContext ); } }
weltkante/dotnetsamples
Microsoft.Diagnostics.Runtime/CLRMD/ClrMemDiag/Debugger/IDebugSymbols4.cs
C#
mit
30,253
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.text.CharacterIterator ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_TEXT_CHARACTERITERATOR_HPP_DECL #define J2CPP_JAVA_TEXT_CHARACTERITERATOR_HPP_DECL namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace lang { class Cloneable; } } } #include <java/lang/Cloneable.hpp> #include <java/lang/Object.hpp> namespace j2cpp { namespace java { namespace text { class CharacterIterator; class CharacterIterator : public object<CharacterIterator> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) J2CPP_DECLARE_FIELD(0) explicit CharacterIterator(jobject jobj) : object<CharacterIterator>(jobj) { } operator local_ref<java::lang::Object>() const; operator local_ref<java::lang::Cloneable>() const; local_ref< java::lang::Object > clone(); jchar current(); jchar first(); jint getBeginIndex(); jint getEndIndex(); jint getIndex(); jchar last(); jchar next(); jchar previous(); jchar setIndex(jint); static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jchar > DONE; }; //class CharacterIterator } //namespace text } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_TEXT_CHARACTERITERATOR_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_TEXT_CHARACTERITERATOR_HPP_IMPL #define J2CPP_JAVA_TEXT_CHARACTERITERATOR_HPP_IMPL namespace j2cpp { java::text::CharacterIterator::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } java::text::CharacterIterator::operator local_ref<java::lang::Cloneable>() const { return local_ref<java::lang::Cloneable>(get_jobject()); } local_ref< java::lang::Object > java::text::CharacterIterator::clone() { return call_method< java::text::CharacterIterator::J2CPP_CLASS_NAME, java::text::CharacterIterator::J2CPP_METHOD_NAME(0), java::text::CharacterIterator::J2CPP_METHOD_SIGNATURE(0), local_ref< java::lang::Object > >(get_jobject()); } jchar java::text::CharacterIterator::current() { return call_method< java::text::CharacterIterator::J2CPP_CLASS_NAME, java::text::CharacterIterator::J2CPP_METHOD_NAME(1), java::text::CharacterIterator::J2CPP_METHOD_SIGNATURE(1), jchar >(get_jobject()); } jchar java::text::CharacterIterator::first() { return call_method< java::text::CharacterIterator::J2CPP_CLASS_NAME, java::text::CharacterIterator::J2CPP_METHOD_NAME(2), java::text::CharacterIterator::J2CPP_METHOD_SIGNATURE(2), jchar >(get_jobject()); } jint java::text::CharacterIterator::getBeginIndex() { return call_method< java::text::CharacterIterator::J2CPP_CLASS_NAME, java::text::CharacterIterator::J2CPP_METHOD_NAME(3), java::text::CharacterIterator::J2CPP_METHOD_SIGNATURE(3), jint >(get_jobject()); } jint java::text::CharacterIterator::getEndIndex() { return call_method< java::text::CharacterIterator::J2CPP_CLASS_NAME, java::text::CharacterIterator::J2CPP_METHOD_NAME(4), java::text::CharacterIterator::J2CPP_METHOD_SIGNATURE(4), jint >(get_jobject()); } jint java::text::CharacterIterator::getIndex() { return call_method< java::text::CharacterIterator::J2CPP_CLASS_NAME, java::text::CharacterIterator::J2CPP_METHOD_NAME(5), java::text::CharacterIterator::J2CPP_METHOD_SIGNATURE(5), jint >(get_jobject()); } jchar java::text::CharacterIterator::last() { return call_method< java::text::CharacterIterator::J2CPP_CLASS_NAME, java::text::CharacterIterator::J2CPP_METHOD_NAME(6), java::text::CharacterIterator::J2CPP_METHOD_SIGNATURE(6), jchar >(get_jobject()); } jchar java::text::CharacterIterator::next() { return call_method< java::text::CharacterIterator::J2CPP_CLASS_NAME, java::text::CharacterIterator::J2CPP_METHOD_NAME(7), java::text::CharacterIterator::J2CPP_METHOD_SIGNATURE(7), jchar >(get_jobject()); } jchar java::text::CharacterIterator::previous() { return call_method< java::text::CharacterIterator::J2CPP_CLASS_NAME, java::text::CharacterIterator::J2CPP_METHOD_NAME(8), java::text::CharacterIterator::J2CPP_METHOD_SIGNATURE(8), jchar >(get_jobject()); } jchar java::text::CharacterIterator::setIndex(jint a0) { return call_method< java::text::CharacterIterator::J2CPP_CLASS_NAME, java::text::CharacterIterator::J2CPP_METHOD_NAME(9), java::text::CharacterIterator::J2CPP_METHOD_SIGNATURE(9), jchar >(get_jobject(), a0); } static_field< java::text::CharacterIterator::J2CPP_CLASS_NAME, java::text::CharacterIterator::J2CPP_FIELD_NAME(0), java::text::CharacterIterator::J2CPP_FIELD_SIGNATURE(0), jchar > java::text::CharacterIterator::DONE; J2CPP_DEFINE_CLASS(java::text::CharacterIterator,"java/text/CharacterIterator") J2CPP_DEFINE_METHOD(java::text::CharacterIterator,0,"clone","()Ljava/lang/Object;") J2CPP_DEFINE_METHOD(java::text::CharacterIterator,1,"current","()C") J2CPP_DEFINE_METHOD(java::text::CharacterIterator,2,"first","()C") J2CPP_DEFINE_METHOD(java::text::CharacterIterator,3,"getBeginIndex","()I") J2CPP_DEFINE_METHOD(java::text::CharacterIterator,4,"getEndIndex","()I") J2CPP_DEFINE_METHOD(java::text::CharacterIterator,5,"getIndex","()I") J2CPP_DEFINE_METHOD(java::text::CharacterIterator,6,"last","()C") J2CPP_DEFINE_METHOD(java::text::CharacterIterator,7,"next","()C") J2CPP_DEFINE_METHOD(java::text::CharacterIterator,8,"previous","()C") J2CPP_DEFINE_METHOD(java::text::CharacterIterator,9,"setIndex","(I)C") J2CPP_DEFINE_FIELD(java::text::CharacterIterator,0,"DONE","C") } //namespace j2cpp #endif //J2CPP_JAVA_TEXT_CHARACTERITERATOR_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
hyEvans/ph-open
proj.android/jni/puzzleHero/platforms/android-8/java/text/CharacterIterator.hpp
C++
mit
6,355
import {Component} from 'angular2/core'; @Component({ selector: 'home', templateUrl: 'app/components/home/home.html', styleUrls: ['app/components/home/home.css'], providers: [], directives: [], pipes: [] }) export class Home { constructor() {} ngOnInit() { } }
deostroll/ang2routing
src/app/components/home/home.ts
TypeScript
mit
284
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: global::Android.Runtime.ResourceDesignerAttribute("MediaSample.Droid.Resource", IsApplication=true)] namespace MediaSample.Droid { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public static void UpdateIdValues() { } public partial class Attribute { static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class Drawable { // aapt resource value: 0x7f020000 public const int icon = 2130837504; static Drawable() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Drawable() { } } } } #pragma warning restore 1591
labdogg1003/Xamarin.Plugins
Media/Component/MediaPlugin/samples/MediaSample/MediaSample/MediaSample.Droid/Resources/Resource.Designer.cs
C#
mit
1,316
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('statmaps', '0026_populate_cogatlas'), ] operations = [ migrations.AddField( model_name='statisticmap', name='cognitive_paradigm_cogatlas', field=models.CharField(help_text=b"Task (or lack of it) performed by the subjects in the scanner described using <a href='http://www.cognitiveatlas.org/'>Cognitive Atlas</a> terms", max_length=200, null=True, verbose_name=b'Cognitive Paradigm'), preserve_default=True, ), migrations.AlterField( model_name='statisticmap', name='modality', field=models.CharField(help_text=b'Brain imaging procedure that was used to acquire the data.', max_length=200, verbose_name=b'Modality & Acquisition Type', choices=[(b'fMRI-BOLD', b'fMRI-BOLD'), (b'fMRI-CBF', b'fMRI-CBF'), (b'fMRI-CBV', b'fMRI-CBV'), (b'Diffusion MRI', b'Diffusion MRI'), (b'Structural MRI', b'Structural MRI'), (b'PET FDG', b'PET FDG'), (b'PET [15O]-water', b'PET [15O]-water'), (b'PET other', b'PET other'), (b'MEG', b'MEG'), (b'EEG', b'EEG'), (b'Other', b'Other')]), preserve_default=True, ), ]
chrisfilo/NeuroVault
neurovault/apps/statmaps/migrations/0027_auto_20150220_0305.py
Python
mit
1,314
package net.minecraft.block; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.util.EnumFacing; public abstract class BlockRotatedPillar extends Block { public static final PropertyEnum<EnumFacing.Axis> AXIS = PropertyEnum.<EnumFacing.Axis>create("axis", EnumFacing.Axis.class); protected BlockRotatedPillar(Material materialIn) { super(materialIn, materialIn.getMaterialMapColor()); } protected BlockRotatedPillar(Material p_i46385_1_, MapColor p_i46385_2_) { super(p_i46385_1_, p_i46385_2_); } }
TorchPowered/CraftBloom
src/net/minecraft/block/BlockRotatedPillar.java
Java
mit
661
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; var util = require('util'); /** * @class * Initializes a new instance of the ApplicationGatewaySslPolicy class. * @constructor * Application gateway SSL policy * * @member {array} [disabledSslProtocols] SSL protocols to be disabled on * Application Gateway * */ function ApplicationGatewaySslPolicy() { } /** * Defines the metadata of ApplicationGatewaySslPolicy * * @returns {object} metadata of ApplicationGatewaySslPolicy * */ ApplicationGatewaySslPolicy.prototype.mapper = function () { return { required: false, serializedName: 'ApplicationGatewaySslPolicy', type: { name: 'Composite', className: 'ApplicationGatewaySslPolicy', modelProperties: { disabledSslProtocols: { required: false, serializedName: 'disabledSslProtocols', type: { name: 'Sequence', element: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } } } } }; }; module.exports = ApplicationGatewaySslPolicy;
smithab/azure-sdk-for-node
lib/services/networkManagement2/lib/models/applicationGatewaySslPolicy.js
JavaScript
mit
1,482
<?php namespace Grav\Common; /** * The URI object provides information about the current URL * * @author RocketTheme * @license MIT */ class Uri { public $url; protected $base; protected $root; protected $bits; protected $extension; protected $host; protected $content_path; protected $path; protected $paths; protected $query; protected $params; /** * Constructor. */ public function __construct() { $base = 'http://'; $name = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost'; $port = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80; $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; $root_path = rtrim(substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'], 'index.php')), '/'); if (isset($_SERVER['HTTPS'])) { $base = (@$_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://'; } $base .= $name; if ($port != '80' && $port != '443') { $base .= ":".$port; } // check if userdir in the path and workaround PHP bug with PHP_SELF if (strpos($uri, '/~') !== false && strpos($_SERVER['PHP_SELF'], '/~') === false) { $root_path = substr($uri, 0, strpos($uri, '/', 1)) . $root_path; } // set hostname $address = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '::1'; // check for localhost variations if ($name == 'localhost' || $address == '::1' || $address == '127.0.0.1') { $this->host = 'localhost'; } else { $this->host = $name; } $this->base = $base; $this->root = $base . $root_path; $this->url = $base . $uri; } /** * Initializes the URI object based on the url set on the object */ public function init() { $config = Grav::instance()['config']; // get any params and remove them $uri = str_replace($this->root, '', $this->url); // reset params $this->params = []; // process params $uri = $this->processParams($uri, $config->get('system.param_sep')); // remove the extension if there is one set $parts = pathinfo($uri); if (preg_match("/\.(txt|xml|html|json|rss|atom)$/", $parts['basename'])) { $uri = rtrim($parts['dirname'], '/').'/'.$parts['filename']; $this->extension = $parts['extension']; } // set the new url $this->url = $this->root . $uri; // split into bits $this->bits = parse_url($uri); $this->query = array(); if (isset($this->bits['query'])) { parse_str($this->bits['query'], $this->query); } $this->paths = array(); $this->path = $this->bits['path']; $this->content_path = trim(str_replace($this->base, '', $this->path), '/'); if ($this->content_path != '') { $this->paths = explode('/', $this->content_path); } } /** * Process any params based in this URL, supports any valid delimiter * * @param $uri * @param string $delimiter * * @return string */ private function processParams($uri, $delimiter = ':') { if (strpos($uri, $delimiter) !== false) { $bits = explode('/', $uri); $path = array(); foreach ($bits as $bit) { if (strpos($bit, $delimiter) !== false) { $param = explode($delimiter, $bit); if (count($param) == 2) { $this->params[$param[0]] = str_replace(urlencode($delimiter), '/', filter_var($param[1], FILTER_SANITIZE_STRING)); } } else { $path[] = $bit; } } $uri = implode('/', $path); } return $uri; } /** * Return URI path. * * @param string $id * @return string */ public function paths($id = null) { if (isset($id)) { return $this->paths[$id]; } else { return $this->paths; } } /** * Return route to the current URI. By default route doesn't include base path. * * @param bool $absolute True to include full path. * @param bool $domain True to include domain. Works only if first parameter is also true. * @return string */ public function route($absolute = false, $domain = false) { return urldecode(($absolute ? $this->rootUrl($domain) : '') . '/' . implode('/', $this->paths)); } /** * Return full query string or a single query attribute. * * @param string $id Optional attribute. * @return string */ public function query($id = null, $raw = false) { if (isset($id)) { return isset($this->query[$id]) ? filter_var($this->query[$id], FILTER_SANITIZE_STRING) : null; } else { if ($raw) { return $this->query; } else { return http_build_query($this->query); } } } /** * Return all or a single query parameter as a URI compatible string. * * @param string $id Optional parameter name. * @return null|string */ public function params($id = null) { $config = Grav::instance()['config']; $params = null; if ($id === null) { $output = array(); foreach ($this->params as $key => $value) { $output[] = $key . $config->get('system.param_sep') . $value; $params = '/'.implode('/', $output); } } elseif (isset($this->params[$id])) { $params = "/{$id}". $config->get('system.param_sep') . $this->params[$id]; } return $params; } /** * Get URI parameter. * * @param string $id * @return bool|string */ public function param($id) { if (isset($this->params[$id])) { return urldecode($this->params[$id]); } else { return false; } } /** * Return URL. * * @param bool $include_host Include hostname. * @return string */ public function url($include_host = false) { if ($include_host) { return $this->url; } else { $url = (str_replace($this->base, '', rtrim($this->url, '/'))); return $url ? $url : '/'; } } /** * Return the Path * * @return String The path of the URI */ public function path() { return $this->path; } /** * Return the Extension of the URI * * @param null $default * * @return String The extension of the URI */ public function extension($default = null) { if (!$this->extension) { $this->extension = $default; } return $this->extension; } /** * Return the host of the URI * * @return String The host of the URI */ public function host() { return $this->host; } /** * Gets the environment name * * @return String */ public function environment() { return $this->host(); } /** * Return the base of the URI * * @return String The base of the URI */ public function base() { return $this->base; } /** * Return root URL to the site. * * @param bool $include_host Include hostname. * @return mixed */ public function rootUrl($include_host = false) { if ($include_host) { return $this->root; } else { $root = str_replace($this->base, '', $this->root); return $root; } } /** * Return current page number. * * @return int */ public function currentPage() { if (isset($this->params['page'])) { return $this->params['page']; } else { return 1; } } /** * Return relative path to the referrer defaulting to current or given page. * * @param string $default * @param string $attributes * @return string */ public function referrer($default = null, $attributes = null) { $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null; // Check that referrer came from our site. $root = $this->rootUrl(true); if ($referrer) { // Referrer should always have host set and it should come from the same base address. if (stripos($referrer, $root) !== 0) { $referrer = null; } } if (!$referrer) { $referrer = $default ? $default : $this->route(true, true); } if ($attributes) { $referrer .= $attributes; } // Return relative path. return substr($referrer, strlen($root)); } /** * Retrun the IP address of the current user * * @return string ip address */ public function ip() { if (getenv('HTTP_CLIENT_IP')) $ipaddress = getenv('HTTP_CLIENT_IP'); else if(getenv('HTTP_X_FORWARDED_FOR')) $ipaddress = getenv('HTTP_X_FORWARDED_FOR'); else if(getenv('HTTP_X_FORWARDED')) $ipaddress = getenv('HTTP_X_FORWARDED'); else if(getenv('HTTP_FORWARDED_FOR')) $ipaddress = getenv('HTTP_FORWARDED_FOR'); else if(getenv('HTTP_FORWARDED')) $ipaddress = getenv('HTTP_FORWARDED'); else if(getenv('REMOTE_ADDR')) $ipaddress = getenv('REMOTE_ADDR'); else $ipaddress = 'UNKNOWN'; return $ipaddress; } /** * The opposite of built-in PHP method parse_url() * * @param $parsed_url * @return string */ public static function buildUrl($parsed_url) { $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : ''; $host = isset($parsed_url['host']) ? $parsed_url['host'] : ''; $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : ''; $user = isset($parsed_url['user']) ? $parsed_url['user'] : ''; $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : ''; $pass = ($user || $pass) ? "$pass@" : ''; $path = isset($parsed_url['path']) ? $parsed_url['path'] : ''; $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : ''; $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : ''; return "$scheme$user$pass$host$port$path$query$fragment"; } }
nakagaw/grav
system/src/Grav/Common/Uri.php
PHP
mit
10,952
<?php namespace Braintree; use InvalidArgumentException; /** * Braintree PaymentMethodGateway module * * @package Braintree * @category Resources */ /** * Creates and manages Braintree PaymentMethods * * <b>== More information ==</b> * * * @package Braintree * @category Resources */ class PaymentMethodGateway { private $_gateway; private $_config; private $_http; public function __construct($gateway) { $this->_gateway = $gateway; $this->_config = $gateway->config; $this->_config->assertHasAccessTokenOrKeys(); $this->_http = new Http($gateway->config); } public function create($attribs) { Util::verifyKeys(self::createSignature(), $attribs); return $this->_doCreate('/payment_methods', ['payment_method' => $attribs]); } /** * find a PaymentMethod by token * * @param string $token payment method unique id * @return CreditCard|PayPalAccount * @throws Exception\NotFound */ public function find($token) { $this->_validateId($token); try { $path = $this->_config->merchantPath() . '/payment_methods/any/' . $token; $response = $this->_http->get($path); if (isset($response['creditCard'])) { return CreditCard::factory($response['creditCard']); } else if (isset($response['paypalAccount'])) { return PayPalAccount::factory($response['paypalAccount']); } else if (isset($response['coinbaseAccount'])) { return CoinbaseAccount::factory($response['coinbaseAccount']); } else if (isset($response['applePayCard'])) { return ApplePayCard::factory($response['applePayCard']); } else if (isset($response['androidPayCard'])) { return AndroidPayCard::factory($response['androidPayCard']); } else if (isset($response['amexExpressCheckoutCard'])) { return AmexExpressCheckoutCard::factory($response['amexExpressCheckoutCard']); } else if (isset($response['europeBankAccount'])) { return EuropeBankAccount::factory($response['europeBankAccount']); } else if (isset($response['usBankAccount'])) { return UsBankAccount::factory($response['usBankAccount']); } else if (isset($response['venmoAccount'])) { return VenmoAccount::factory($response['venmoAccount']); } else if (isset($response['visaCheckoutCard'])) { return VisaCheckoutCard::factory($response['visaCheckoutCard']); } else if (isset($response['masterpassCard'])) { return MasterpassCard::factory($response['masterpassCard']); } else if (isset($response['samsungPayCard'])) { return SamsungPayCard::factory($response['samsungPayCard']); } else if (is_array($response)) { return UnknownPaymentMethod::factory($response); } } catch (Exception\NotFound $e) { throw new Exception\NotFound( 'payment method with token ' . $token . ' not found' ); } } public function update($token, $attribs) { Util::verifyKeys(self::updateSignature(), $attribs); return $this->_doUpdate('/payment_methods/any/' . $token, ['payment_method' => $attribs]); } public function delete($token, $options=[]) { Util::verifyKeys(self::deleteSignature(), $options); $this->_validateId($token); $queryString = ""; if (!empty($options)) { $queryString = "?" . http_build_query(Util::camelCaseToDelimiterArray($options, '_')); } return $this->_doDelete('/payment_methods/any/' . $token . $queryString); } public function grant($sharedPaymentMethodToken, $attribs=[]) { if (is_bool($attribs) === true) { $attribs = ['allow_vaulting' => $attribs]; } $options = [ 'shared_payment_method_token' => $sharedPaymentMethodToken ]; return $this->_doCreate( '/payment_methods/grant', [ 'payment_method' => array_merge($attribs, $options) ] ); } public function revoke($sharedPaymentMethodToken) { return $this->_doCreate( '/payment_methods/revoke', [ 'payment_method' => [ 'shared_payment_method_token' => $sharedPaymentMethodToken ] ] ); } private static function baseSignature() { $billingAddressSignature = AddressGateway::createSignature(); $optionsSignature = [ 'failOnDuplicatePaymentMethod', 'makeDefault', 'verificationMerchantAccountId', 'verifyCard', 'verificationAmount', 'usBankAccountVerificationMethod', ['paypal' => [ 'payee_email', 'payeeEmail', 'order_id', 'orderId', 'custom_field', 'customField', 'description', 'amount', ['shipping' => [ 'firstName', 'lastName', 'company', 'countryName', 'countryCodeAlpha2', 'countryCodeAlpha3', 'countryCodeNumeric', 'extendedAddress', 'locality', 'postalCode', 'region', 'streetAddress'], ], ]], ]; return [ 'billingAddressId', 'cardholderName', 'cvv', 'deviceData', 'expirationDate', 'expirationMonth', 'expirationYear', 'number', 'paymentMethodNonce', 'token', ['options' => $optionsSignature], ['billingAddress' => $billingAddressSignature] ]; } public static function createSignature() { $signature = array_merge(self::baseSignature(), ['customerId', 'paypalRefreshToken', 'paypalVaultWithoutUpgrade']); return $signature; } public static function updateSignature() { $billingAddressSignature = AddressGateway::updateSignature(); array_push($billingAddressSignature, [ 'options' => [ 'updateExisting' ] ]); $signature = array_merge(self::baseSignature(), [ 'deviceSessionId', 'venmoSdkPaymentMethodCode', 'fraudMerchantId', ['billingAddress' => $billingAddressSignature] ]); return $signature; } private static function deleteSignature() { return ['revokeAllGrants']; } /** * sends the create request to the gateway * * @ignore * @param string $subPath * @param array $params * @return mixed */ public function _doCreate($subPath, $params) { $fullPath = $this->_config->merchantPath() . $subPath; $response = $this->_http->post($fullPath, $params); return $this->_verifyGatewayResponse($response); } /** * sends the update request to the gateway * * @ignore * @param string $subPath * @param array $params * @return mixed */ public function _doUpdate($subPath, $params) { $fullPath = $this->_config->merchantPath() . $subPath; $response = $this->_http->put($fullPath, $params); return $this->_verifyGatewayResponse($response); } /** * sends the delete request to the gateway * * @ignore * @param string $subPath * @return mixed */ public function _doDelete($subPath) { $fullPath = $this->_config->merchantPath() . $subPath; $this->_http->delete($fullPath); return new Result\Successful(); } /** * generic method for validating incoming gateway responses * * creates a new CreditCard or PayPalAccount object * and encapsulates it inside a Result\Successful object, or * encapsulates a Errors object inside a Result\Error * alternatively, throws an Unexpected exception if the response is invalid. * * @ignore * @param array $response gateway response values * @return Result\Successful|Result\Error * @throws Exception\Unexpected */ private function _verifyGatewayResponse($response) { if (isset($response['creditCard'])) { return new Result\Successful( CreditCard::factory($response['creditCard']), 'paymentMethod' ); } else if (isset($response['paypalAccount'])) { return new Result\Successful( PayPalAccount::factory($response['paypalAccount']), "paymentMethod" ); } else if (isset($response['coinbaseAccount'])) { return new Result\Successful( CoinbaseAccount::factory($response['coinbaseAccount']), "paymentMethod" ); } else if (isset($response['applePayCard'])) { return new Result\Successful( ApplePayCard::factory($response['applePayCard']), "paymentMethod" ); } else if (isset($response['androidPayCard'])) { return new Result\Successful( AndroidPayCard::factory($response['androidPayCard']), "paymentMethod" ); } else if (isset($response['amexExpressCheckoutCard'])) { return new Result\Successful( AmexExpressCheckoutCard::factory($response['amexExpressCheckoutCard']), "paymentMethod" ); } else if (isset($response['usBankAccount'])) { return new Result\Successful( UsBankAccount::factory($response['usBankAccount']), "paymentMethod" ); } else if (isset($response['venmoAccount'])) { return new Result\Successful( VenmoAccount::factory($response['venmoAccount']), "paymentMethod" ); } else if (isset($response['visaCheckoutCard'])) { return new Result\Successful( VisaCheckoutCard::factory($response['visaCheckoutCard']), "paymentMethod" ); } else if (isset($response['masterpassCard'])) { return new Result\Successful( MasterpassCard::factory($response['masterpassCard']), "paymentMethod" ); } else if (isset($response['samsungPayCard'])) { return new Result\Successful( MasterpassCard::factory($response['samsungPayCard']), "paymentMethod" ); } else if (isset($response['paymentMethodNonce'])) { return new Result\Successful( PaymentMethodNonce::factory($response['paymentMethodNonce']), "paymentMethodNonce" ); } else if (isset($response['apiErrorResponse'])) { return new Result\Error($response['apiErrorResponse']); } else if (is_array($response)) { return new Result\Successful( UnknownPaymentMethod::factory($response), "paymentMethod" ); } else { throw new Exception\Unexpected( 'Expected payment method or apiErrorResponse' ); } } /** * verifies that a valid payment method identifier is being used * @ignore * @param string $identifier * @param Optional $string $identifierType type of identifier supplied, default 'token' * @throws InvalidArgumentException */ private function _validateId($identifier = null, $identifierType = 'token') { if (empty($identifier)) { throw new InvalidArgumentException( 'expected payment method id to be set' ); } if (!preg_match('/^[0-9A-Za-z_-]+$/', $identifier)) { throw new InvalidArgumentException( $identifier . ' is an invalid payment method ' . $identifierType . '.' ); } } } class_alias('Braintree\PaymentMethodGateway', 'Braintree_PaymentMethodGateway');
cmaciasg/test
application/vendor/braintree/braintree_php/lib/Braintree/PaymentMethodGateway.php
PHP
mit
12,507
(function(){$(function(){return console.log("hello")})}).call(this);
tiy-hou-q1-2016-rails/tiy-hou-q1-2016-rails.github.io
javascripts/script-b9af7cd9.js
JavaScript
mit
68
/*! * Bootstrap-select v1.13.9 (https://developer.snapappointments.com/bootstrap-select) * * Copyright 2012-2019 SnapAppointments, LLC * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE) */ (function (root, factory) { if (root === undefined && window !== undefined) root = window; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module unless amdModuleId is set define(["jquery"], function (a0) { return (factory(a0)); }); } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(require("jquery")); } else { factory(root["jQuery"]); } }(this, function (jQuery) { (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Chưa chọn', noneResultsText: 'Không có kết quả cho {0}', countSelectedText: function (numSelected, numTotal) { return '{0} mục đã chọn'; }, maxOptionsText: function (numAll, numGroup) { return [ 'Không thể chọn (giới hạn {n} mục)', 'Không thể chọn (giới hạn {n} mục)' ]; }, selectAllText: 'Chọn tất cả', deselectAllText: 'Bỏ chọn', multipleSeparator: ', ' }; })(jQuery); })); //# sourceMappingURL=defaults-vi_VN.js.map
extend1994/cdnjs
ajax/libs/bootstrap-select/1.13.9/js/i18n/defaults-vi_VN.js
JavaScript
mit
1,504
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using Azure; using Azure.Core; namespace Azure.Storage.Blobs.Batch { internal partial class ContainerSubmitBatchHeaders { private readonly Response _response; public ContainerSubmitBatchHeaders(Response response) { _response = response; } /// <summary> The media type of the body of the response. For batch requests, this is multipart/mixed; boundary=batchresponse_GUID. </summary> public string ContentType => _response.Headers.TryGetValue("Content-Type", out string value) ? value : null; /// <summary> Indicates the version of the Blob service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. </summary> public string Version => _response.Headers.TryGetValue("x-ms-version", out string value) ? value : null; } }
ayeletshpigelman/azure-sdk-for-net
sdk/storage/Azure.Storage.Blobs.Batch/src/Generated/ContainerSubmitBatchHeaders.cs
C#
mit
1,003
import numpy as np import cudarray as ca from .base import PickleMixin _FLT_MIN = np.finfo(ca.float_).tiny class Loss(PickleMixin): # abll: I suspect that this interface is not ideal. It would be more # elegant if Loss only provided loss() and grad(). However, where should # we place the logic from fprop()? @classmethod def from_any(cls, arg): if isinstance(arg, Loss): return arg elif isinstance(arg, str): if arg == 'softmaxce': return SoftmaxCrossEntropy() elif arg == 'bce': return BinaryCrossEntropy() elif arg == 'mse': return MeanSquaredError() raise ValueError('Invalid constructor arguments: %s' % arg) def _setup(self, x_shape): pass def fprop(self, x): return x def loss(self, target, x): """ Returns the loss calculated from the target and the input. """ raise NotImplementedError() def grad(self, target, x): """ Returns the input gradient. """ raise NotImplementedError() def y_shape(self, x_shape): return x_shape class SoftmaxCrossEntropy(Loss): """ Softmax + cross entropy (aka. multinomial logistic loss) """ def __init__(self): self.name = 'softmaxce' self._tmp_x = None self._tmp_y = None self._tmp_target = None self._tmp_one_hot = None self.n_classes = None def _setup(self, x_shape): self.n_classes = x_shape[1] def _softmax(self, x): # caching wrapper if self._tmp_x is not x: self._tmp_y = ca.nnet.softmax(x) self._tmp_x = x return self._tmp_y def _one_hot(self, target): # caching wrapper if self._tmp_target is not target: self._tmp_one_hot = ca.nnet.one_hot_encode(target, self.n_classes) self._tmp_target = target return self._tmp_one_hot def fprop(self, x): return ca.nnet.one_hot_decode(self._softmax(x)) def loss(self, target, x): y = self._softmax(x) target = self._one_hot(target) return ca.nnet.categorical_cross_entropy(y_pred=y, y_true=target) def grad(self, target, x): y = self._softmax(x) target = self._one_hot(target) return -(target - y) def y_shape(self, x_shape): return (x_shape[0],) class BinaryCrossEntropy(Loss): def __init__(self): self.name = 'bce' def loss(self, y, y_pred): y_pred = ca.maximum(y_pred, _FLT_MIN) return -ca.mean(y*ca.log(y_pred) + (1 - y)*ca.log(1 - y_pred), axis=1) def grad(self, y, y_pred): y_pred = ca.maximum(y_pred, _FLT_MIN) return -(y/y_pred - (1-y)/(1-y_pred)) class MeanSquaredError(Loss): def __init__(self): self.name = 'mse' self.n_targets = None def _setup(self, x_shape): self.n_targets = x_shape[1] def loss(self, y, y_pred): return ca.mean((y-y_pred)**2, axis=1) def grad(self, y, y_pred): return 2.0 / self.n_targets * (y_pred - y)
lre/deeppy
deeppy/loss.py
Python
mit
3,134
<?php defined('BX_DOL') or die('hack attempt'); /** * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/ * CC-BY License - http://creativecommons.org/licenses/by/3.0/ * * @defgroup TridentStudio Trident Studio * @{ */ class BxDolStudioPolyglotEtemplates extends BxTemplStudioGrid { public function __construct ($aOptions, $oTemplate = false) { parent::__construct ($aOptions, $oTemplate); $this->oDb = new BxDolStudioPolyglotQuery(); } protected function _getDataSql($sFilter, $sOrderField, $sOrderDir, $iStart, $iPerPage) { $sModule = ''; if(strpos($sFilter, $this->sParamsDivider) !== false) list($sModule, $sFilter) = explode($this->sParamsDivider, $sFilter); if($sModule != '') $this->_aOptions['source'] .= $this->oDb->prepareAsString(" AND `Module`=?", $sModule); return parent::_getDataSql($sFilter, $sOrderField, $sOrderDir, $iStart, $iPerPage); } } /** @} */
camperjz/trident
upgrade/files/8.0.1-9.0.0.B1/files/studio/classes/BxDolStudioPolyglotEtemplates.php
PHP
mit
986
/** * Created by patricepaquette on 12/17/2013. */ angular.module("common") .directive('lazyLoad', ['$window', '$q', function ($window, $q) { function load_script(src) { var s = document.createElement('script'); // use global document since Angular's $document is weak s.src = src; document.body.appendChild(s); } function lazyLoadApi(src) { var deferred = $q.defer(); $window.initialize = function () { deferred.resolve(); }; // thanks to Emil Stenström: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/ if ($window.attachEvent) { $window.attachEvent('onload', function(){ load_script(src); }); } else { $window.addEventListener('load', function(){ load_script(src); }, false); } return deferred.promise; } return { restrict: 'E', scope: { src: "@src" }, link: function (scope, element, attrs) { // function content is optional // in this example, it shows how and when the promises are resolved if ($window.google && $window.google.maps) { } else { lazyLoadApi().then(function () { //console.log('promise resolved'); if ($window.google && $window.google.maps) { //console.log('gmaps loaded'); } else { //console.log('gmaps not loaded'); } }, function () { //console.log('promise rejected'); }); } } }; }]);
patpaquette/CampCarolinas
src/app/directives/lazyload.js
JavaScript
mit
1,911
require 'rubygems' require 'json' require 'time' require 'net/http' =begin = Class: Kelastic - Performs an elastic search request - Adds Kibana specific object for JS communication == Parameters: query:: The query object to send to ES index:: The index to query =end class Kelastic attr_accessor :response,:url def initialize(query,index) @url = "http://#{Kelastic.server}/#{index}/_search" # TODO: This badly needs error handling for missing indices @response = Kelastic.run(@url,query) @response['kibana'] = { "index" => index, } end def to_s JSON.pretty_generate(@response) end class << self def all_indices url = URI.parse("http://#{Kelastic.server}/_aliases") http = Net::HTTP.new(url.host,url.port) if KibanaConfig.constants.include?("ElasticsearchTimeout") if KibanaConfig::ElasticsearchTimeout != '' http.read_timeout = KibanaConfig::ElasticsearchTimeout end end @status = JSON.parse( http.request(Net::HTTP::Get.new(url.request_uri)).body) indices = @status.keys @status.keys.each do |index| if @status[index]['aliases'].count > 0 indices.concat(@status[index]['aliases'].keys) end end indices.uniq.sort end # Returns list of index-date names which intersect with range defined by # from and to def index_range(from,to,limit = -1) if KibanaConfig::Smart_index == true index_pattern = "logstash-%Y.%m.%d" if KibanaConfig::Smart_index_pattern != "" index_pattern = KibanaConfig::Smart_index_pattern end requested = [] # Initialize empty array index_pattern = index_pattern.kind_of?(Array) ? index_pattern : [index_pattern] for index in index_pattern do step_time = from begin requested << step_time.getutc.strftime(index) end while (step_time += KibanaConfig::Smart_index_step) <= to unless requested.include? to.getutc.strftime(index) requested << to.getutc.strftime(index) end end intersection = requested & all_indices if intersection.length <= KibanaConfig::Smart_index_limit intersection.sort.reverse[0..limit] else [KibanaConfig::Default_index] end else [KibanaConfig::Default_index] end end def server list = KibanaConfig::Elasticsearch if list.kind_of?(Array) $eslb ||= 0 $eslb = $eslb < list.length ? $eslb : 0 server = list[$eslb] $eslb += 1 server else list end end # TODO: Verify this index exists? This is no longer being called. # Possibly remove? def current_index if KibanaConfig::Smart_index == true index_pattern = (KibanaConfig::Smart_index_pattern.empty? ? "logstash-%Y.%m.%d" : KibanaConfig::Smart_index_pattern) index_patterns = (index_pattern.kind_of?(Array) ? index_pattern : [index_pattern]) index_patterns.map do |index| (Time.now.utc).strftime(index) end else KibanaConfig::Default_index end end def mapping(index) url = URI.parse("http://#{Kelastic.server}/#{index}/_mapping") http = Net::HTTP.new(url.host,url.port) if KibanaConfig.constants.include?("ElasticsearchTimeout") if KibanaConfig::ElasticsearchTimeout != '' http.read_timeout = KibanaConfig::ElasticsearchTimeout end end JSON.parse(http.request(Net::HTTP::Get.new(url.request_uri)).body) end # It would be nice to handle different types here, but we don't do that # anywhere else. def field_type(index,field) attributes = collect_item_attributes(mapping(index),field)[0] attributes['type'] end def collect_item_attributes(h,field) r = [] field = field.gsub("\.",".properties.") types = h.sort_by { |k,v| v }[0][1] types.each do | type | r << field.split(".",3).inject(type[1]['properties']) { |hash, key| if defined?hash[key] hash[key] end } end r.reject! { |c| c == nil } r end def error_msg(error) result = {} result['kibana'] = { 'error' => error } result end def run(url,query) url = URI.parse(url) http = Net::HTTP.new(url.host, url.port) if KibanaConfig.constants.include?("ElasticsearchTimeout") if KibanaConfig::ElasticsearchTimeout != '' http.read_timeout = KibanaConfig::ElasticsearchTimeout end end res = http.post(url.path, query.to_s, 'Accept' => 'application/json', 'Content-Type' => 'application/json') o = JSON.parse(res.body) o['kibana'] = {'per_page' => KibanaConfig::Per_page} o['kibana']['error'] = "Invalid query" if res.code.to_i.between?(500, 599) o['kibana']['curl_call'] = "curl -XGET #{url}?pretty -d '#{query}'" o end def index_path(index) if KibanaConfig::Type != '' path = "http://#{Kelastic.server}/#{index}/#{KibanaConfig::Type}" else path = "http://#{Kelastic.server}/#{index}" end path end end end =begin = Class: KelasticSegment - Query a specific index in an array of indices - Return the position of the next segment if one exists == Parameters: query:: The query object to send to ES indices:: An array of indices to query across segment:: Position in index array =end class KelasticSegment attr_accessor :response,:url def initialize(query,indices,segment) # Make sure we're passed an array, if not, make one indices = indices.kind_of?(Array) ? indices : [indices] if indices.length < 1 @response = Kelastic.error_msg("no index") return @response end index = indices[segment] @url = "#{Kelastic.index_path(index)}/_search" # TODO: This badly needs error handling for missing indices @response = Kelastic.run(@url,query) @response['kibana']['index'] = indices # If there are still indices left, tell the browser which one to request if (segment < indices.length - 1) @response['kibana']['next'] = segment + 1 end end def to_s JSON.pretty_generate(@response) end end =begin = Class: KelasticMulti - Will query indices sequentially and append to result set until query['size'] is reached == Requires: query['size'] query['from'] == Parameters: query:: The query object to send to ES indices:: An array of indices to query across =end class KelasticMulti attr_accessor :response,:url def initialize(query,indices) if indices.length < 1 @response = Kelastic.error_msg("no index") return @response end index = indices.first @url = "#{Kelastic.index_path(index)}/_search" # TODO: This badly needs error handling for missing indices @response = Kelastic.run(@url,query) if @response['kibana'].has_key?("error") return @response end # Store the original values for reference target = query.query['size'] offset = query.query['from'] i = 1 # Didn't get enough hits, and still have indices left? while @response['hits']['hits'].length < target and i < indices.length # Subtract from size however many hits we already have query.query['size'] = target - response['hits']['hits'].length # Calculate an offset to account for anything that might have been shown # on the previous page, otherwise, set to 0 query.query['from'] = (offset - response['hits']['total'] < 0) ? 0 : (offset - response['hits']['total']) index = indices[i] @url = "#{Kelastic.index_path(index)}/_search" if @response['kibana'].has_key?("error") return @response end segment_response = Kelastic.run(@url,query) if !segment_response['status'] && segment_response['hits'] # Concatonate the hits array @response['hits']['hits'] += segment_response['hits']['hits'] # Add the total hits together @response['hits']['total'] += segment_response['hits']['total'] i += 1 elsif segment_response['status'] && 404 == segment_response['status'] i += 1 else raise "Bad response for query to: #{@url}, query: #{query} response" + " data: #{segment_response.to_yaml}" end end @response['kibana']['index'] = indices end def to_s JSON.pretty_generate(@response) end end =begin = Class: KelasticMultiFlat - Performs an elastic search request across several indices in 1 query - Useful for things like faceting - Adds Kibana specific object for JS communication == Parameters: query:: The query object to send to ES index:: The indices to query =end class KelasticMultiFlat attr_accessor :response,:url def initialize(query,indices) if indices.length < 1 @response = Kelastic.error_msg("no index") return @response end index = indices.join(',') @url = "#{Kelastic.index_path(index)}/_search" # TODO: This badly needs error handling for missing indices @response = Kelastic.run(@url,query) if @response['kibana'].has_key?("error") return @response end @response['kibana']['index'] = index end def to_s JSON.pretty_generate(@response) end end =begin = Class: KelasticResponse - Helper methods for response objects =end class KelasticResponse class << self # Flatten a response object into an list of objects that contain only the # fields in 'fields' def flatten_response(response,fields) @flat = Array.new response['hits']['hits'].each do |hit| @flat << flatten_hit(hit,fields) end @flat end # Flatten a hit object into an array with only the fields in 'fields' def flatten_hit(hit,fields) @hit_list = Array.new fields.each do |field| @hit_list << get_field_value(hit,field) end @hit_list end # Retrieve a field value from a hit def get_field_value(hit,field) recurse_field_dots(hit['_source'],field) end # Recursively check for multi-dot fields and nested arrays def recurse_field_dots(obj,field) if !obj[field].nil? obj[field] elsif field =~ /(.*?)\.(.*)/ if !obj[$1].nil? and !obj[$1][$2].nil? obj[$1][$2] elsif !obj[$1].nil? recurse_field_dots(obj[$1],$2) end else nil end end # Very similar to flatten_response, except only returns an array of field # values, without seperating into hit objects things. # Not sure when this broke. Doesn't work for fields store as arrays =begin def collect_field_values(response,fields) @hit_list = Array.new fvs = Array.new response['hits']['hits'].each do |hit| count = 0 fields.each do |field| fv = get_field_value(hit,field) if fv.kind_of?(Array) fvs[count] = fv.map(&:to_s) else fvs[count] = fv.to_s end count=count+1 end @hit_list << fvs.join('||') end @hit_list end =end def collect_field_values(response,field) @hit_list = Array.new # TODO: Fix this Nasty hack field = field[0] response['hits']['hits'].each do |hit| fv = get_field_value(hit,field) if fv.kind_of?(Array) @hit_list = @hit_list + fv.map(&:to_s) else @hit_list << fv.to_s end end @hit_list end # Returns a hash with a count of values def count_field(response,field,limit = 0) count = Hash.new(0) collect_field_values(response,field).each do |value| count[value] += 1 end count = count.sort_by{|key, value| value}.reverse if limit > 0 Hash[count[0..(limit - 1)]] else Hash[count] end end end end
CSGOpenSource/Kibana2
lib/kelastic.rb
Ruby
mit
12,156
SRC_DIR = src BUILD_DIR = build DIST_DIR = dist DEMOS_DIR = demos OTHER_FILES = \ changelog.txt \ MIT-LICENSE.txt \ GPL-LICENSE.txt VER = $$(cat version.txt) VER_SED = sed s/@VERSION/"${VER}"/ DATE = $$(git log -1 --pretty=format:%ad) DATE_SED = sed s/@DATE/"${DATE}"/ JQ = $$(sed -n "s/.*JQUERY\s*=\s*[\"']\(.*\)[\"'].*/\1/p" "${SRC_DIR}/_loader.js") JQUI = $$(sed -n "s/.*JQUERY_UI\s*=\s*[\"']\(.*\)[\"'].*/\1/p" "${SRC_DIR}/_loader.js") DEMO_FILES = $$(cd ${DEMOS_DIR}; find . -mindepth 1 -maxdepth 1 -type f) DEMO_SUBDIRS = $$(cd ${DEMOS_DIR}; find . -mindepth 1 -maxdepth 1 -type d) DEMO_RE = \(<script[^>]*_loader\.js[^>]*><\/script>\|<!--\[\[\|\]\]-->\)\s* DEMO_SED = sed -n "1h;1!H;\$${;g;s/${DEMO_RE}//g;p;}" JS_SED = sed -n "s/\s*js([\"']\(.*\)[\"']).*/\1/p" CSS_SED = sed -n "s/\s*css([\"']\(.*\)[\"']).*/\1/p" concat_js = \ files=$$(cat "$(1)/_loader.js" | ${JS_SED}); \ if [ -f "$(1)/intro.js" ]; then \ files="intro.js $$files"; \ fi; \ if [ -f "$(1)/outro.js" ]; then \ files="$$files outro.js"; \ fi; \ old=$$PWD; \ (cd "$(1)"; cat $$files; cd "$$old") \ | ${VER_SED} \ | ${DATE_SED} \ > "$(2)" concat_css = \ files=$$(cat "$(1)/_loader.js" | ${CSS_SED}); \ if [ "$$files" ]; then \ old=$$PWD; \ (cd "$(1)"; cat $$files; cd "$$old") \ | ${VER_SED} \ | ${DATE_SED} \ > "$(2)"; \ fi zip: @rm -rf ${BUILD_DIR}/fullcalendar @rm -rf ${BUILD_DIR}/fullcalendar-* @mkdir -p ${BUILD_DIR}/fullcalendar/fullcalendar/ @echo "building core..." @$(call concat_js,${SRC_DIR},"${BUILD_DIR}/fullcalendar/fullcalendar/fullcalendar.js") @$(call concat_css,${SRC_DIR},"${BUILD_DIR}/fullcalendar/fullcalendar/fullcalendar.css") @cat "${SRC_DIR}/common/print.css" \ | ${VER_SED} \ | ${DATE_SED} \ > "${BUILD_DIR}/fullcalendar/fullcalendar/fullcalendar.print.css" @echo "compressing core js..." @java -jar ${BUILD_DIR}/compiler.jar --warning_level VERBOSE --jscomp_off checkTypes --externs build/externs.js \ --js ${BUILD_DIR}/fullcalendar/fullcalendar/fullcalendar.js \ > ${BUILD_DIR}/fullcalendar/fullcalendar/fullcalendar.min.js; \ @echo "building plugins..." @for loader in ${SRC_DIR}/*/_loader.js; do \ dir=`dirname $$loader`; \ name=`basename $$dir`; \ $(call concat_js,$$dir,"${BUILD_DIR}/fullcalendar/fullcalendar/$$name.js"); \ done @echo "copying jquery..." @mkdir -p ${BUILD_DIR}/fullcalendar/jquery @cp lib/${JQ} ${BUILD_DIR}/fullcalendar/jquery @cp lib/${JQUI} ${BUILD_DIR}/fullcalendar/jquery @echo "building demos..." @mkdir -p ${BUILD_DIR}/fullcalendar/demos @for f in ${DEMO_FILES}; do \ cat ${DEMOS_DIR}/$$f \ | ${DEMO_SED} \ | sed "s/jquery\.js/${JQ}/" \ | sed "s/jquery-ui\.js/${JQUI}/" \ > ${BUILD_DIR}/fullcalendar/demos/$$f; \ done @for d in ${DEMO_SUBDIRS}; do \ cp -r ${DEMOS_DIR}/$$d ${BUILD_DIR}/fullcalendar/demos/$$d; \ done @echo "copying other files..." @cp -r ${OTHER_FILES} ${BUILD_DIR}/fullcalendar @echo "zipping..." @mv ${BUILD_DIR}/fullcalendar ${BUILD_DIR}/fullcalendar-${VER} @cd ${BUILD_DIR}; for f in fullcalendar-*; do \ zip -q -r $$f.zip $$f; \ done @mv ${BUILD_DIR}/fullcalendar-${VER} ${BUILD_DIR}/fullcalendar @mkdir -p ${DIST_DIR} @mv ${BUILD_DIR}/fullcalendar-${VER}.zip ${DIST_DIR} @echo "done." clean: @rm -rf ${BUILD_DIR}/fullcalendar @rm -rf ${BUILD_DIR}/fullcalendar-* @rm -rf ${DIST_DIR}/*
PofMagicfingers/fullcalendar
Makefile
Makefile
mit
3,373
<!DOCTYPE html> <html lang="en-US" ng-app="Northwind"> <head> <base href="/"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Northwind</title> <link rel="stylesheet" href="lib/build.css"> <link rel="stylesheet" href="lib/foundation-icons/foundation-icons.css"> <link rel="stylesheet" href="css/main.css"> </head> <body> <div class="menu-top"> <div class="menu-group dark"> <div class="menu-group-left"> <ul class="dark menu-bar"> <li><a ui-sref="start.dash">Home</a></li> <li><a ui-sref="add">Add</a></li> </ul> </div> </div> </div> <ui-view class="grid-frame"></ui-view> </body> <script src="lib/build.js"></script> <script src="js/main.config.js"></script> <script src="js/dashboard.controller.js"></script> <script src="js/main.factory.js"></script> </html>
mattfili/node-postgres-testing
public/index.html
HTML
mit
942
<?php namespace Kendo\Dataviz\UI; class StockChartCategoryAxisItemSelect extends \Kendo\SerializableObject { //>> Properties /** * The lower boundary of the selected range. * @param $value * @return \Kendo\Dataviz\UI\StockChartCategoryAxisItemSelect */ public function from($value) { return $this->setProperty('from', $value); } /** * The upper boundary of the selected range.Note: The category with the specified index (date) is not included in the selected range unless the axis is justified. In order to select all categories specify a value larger than the last category index (date). * @param $value * @return \Kendo\Dataviz\UI\StockChartCategoryAxisItemSelect */ public function to($value) { return $this->setProperty('to', $value); } /** * The minimum value that is selectable by the user. * @param $value * @return \Kendo\Dataviz\UI\StockChartCategoryAxisItemSelect */ public function min($value) { return $this->setProperty('min', $value); } /** * The maximum value that is selectable by the user.Note: The category with the specified index (date) is not included in the selected range unless the axis is justified. In order to select all categories specify a value larger than the last category index (date). * @param $value * @return \Kendo\Dataviz\UI\StockChartCategoryAxisItemSelect */ public function max($value) { return $this->setProperty('max', $value); } /** * Mousewheel zoom settings for the selection. * @param \Kendo\Dataviz\UI\StockChartCategoryAxisItemSelectMousewheel|array $value * @return \Kendo\Dataviz\UI\StockChartCategoryAxisItemSelect */ public function mousewheel($value) { return $this->setProperty('mousewheel', $value); } //<< Properties } ?>
xuman3288/kui
src/Kendo/Dataviz/UI/StockChartCategoryAxisItemSelect.php
PHP
mit
1,872
<!-- GENERATED FROM SOURCE --> # vjs.VolumeHandle __EXTENDS__: [vjs.SliderHandle](vjs.SliderHandle.md) __DEFINED IN__: [src/js/control-bar/volume-control.js#L131](https://github.com/videojs/video.js/blob/master/src/js/control-bar/volume-control.js#L131) The volume handle can be dragged to adjust the volume level --- ## INDEX - [METHODS](#methods) - [createEl](#createel-tagname-attributes-) - [addChild](#addchild-child-options-) _`inherited`_ - [addClass](#addclass-classtoadd-) _`inherited`_ - [buildCSSClass](#buildcssclass) _`inherited`_ - [children](#children) _`inherited`_ - [contentEl](#contentel) _`inherited`_ - [dimensions](#dimensions-width-height-) _`inherited`_ - [dispose](#dispose) _`inherited`_ - [el](#el) _`inherited`_ - [enableTouchActivity](#enabletouchactivity) _`inherited`_ - [getChild](#getchild-name-) _`inherited`_ - [getChildById](#getchildbyid-id-) _`inherited`_ - [hasClass](#hasclass-classtocheck-) _`inherited`_ - [height](#height-num-skiplisteners-) _`inherited`_ - [hide](#hide) _`inherited`_ - [id](#id) _`inherited`_ - [init](#init-player-options-ready-) _`inherited`_ - [initChildren](#initchildren) _`inherited`_ - [name](#name) _`inherited`_ - [off](#off-first-second-third-) _`inherited`_ - [on](#on-first-second-third-) _`inherited`_ - [one](#one-first-second-third-) _`inherited`_ - [options](#options-obj-) _`inherited`_ - [player](#player) _`inherited`_ - [ready](#ready-fn-) _`inherited`_ - [removeChild](#removechild-component-) _`inherited`_ - [removeClass](#removeclass-classtoremove-) _`inherited`_ - [show](#show) _`inherited`_ - [trigger](#trigger-event-) _`inherited`_ - [triggerReady](#triggerready) _`inherited`_ - [width](#width-num-skiplisteners-) _`inherited`_ - [EVENTS](#events) - [resize](#resize-event) _`inherited`_ --- ## METHODS ### addChild( child, [options] ) > Adds a child component inside this component > > myComponent.el(); > // -> <div class='my-component'></div> > myComonent.children(); > // [empty array] > > var myButton = myComponent.addChild('MyButton'); > // -> <div class='my-component'><div class="my-button">myButton<div></div> > // -> myButton === myComonent.children()[0]; > > Pass in options for child constructors and options for children of the child > > var myButton = myComponent.addChild('MyButton', { > text: 'Press Me', > children: { > buttonChildExample: { > buttonChildOption: true > } > } > }); ##### PARAMETERS: * __child__ `String|vjs.Component` The class name or instance of a child to add * __options__ `Object` _(OPTIONAL)_ Options, including options to be passed to children of the child. ##### RETURNS: * `vjs.Component` The child component (created by this process if a string was used) _inherited from_: [src/js/component.js#L362](https://github.com/videojs/video.js/blob/master/src/js/component.js#L362) --- ### addClass( classToAdd ) > Add a CSS class name to the component's element ##### PARAMETERS: * __classToAdd__ `String` Classname to add ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L826](https://github.com/videojs/video.js/blob/master/src/js/component.js#L826) --- ### buildCSSClass() > Allows sub components to stack CSS class names ##### RETURNS: * `String` The constructed class name _inherited from_: [src/js/component.js#L536](https://github.com/videojs/video.js/blob/master/src/js/component.js#L536) --- ### children() > Get an array of all child components > > var kids = myComponent.children(); ##### RETURNS: * `Array` The children _inherited from_: [src/js/component.js#L296](https://github.com/videojs/video.js/blob/master/src/js/component.js#L296) --- ### contentEl() > Return the component's DOM element for embedding content. > Will either be el_ or a new element defined in createEl. ##### RETURNS: * `Element` _inherited from_: [src/js/component.js#L239](https://github.com/videojs/video.js/blob/master/src/js/component.js#L239) --- ### createEl( [tagName], [attributes] ) > Create the component's DOM element ##### PARAMETERS: * __tagName__ `String` _(OPTIONAL)_ Element's node type. e.g. 'div' * __attributes__ `Object` _(OPTIONAL)_ An object of element attributes that should be set on the element _defined in_: [src/js/control-bar/volume-control.js#L136](https://github.com/videojs/video.js/blob/master/src/js/control-bar/volume-control.js#L136) --- ### dimensions( width, height ) > Set both width and height at the same time ##### PARAMETERS: * __width__ `Number|String` * __height__ `Number|String` ##### RETURNS: * `vjs.Component` The component _inherited from_: [src/js/component.js#L938](https://github.com/videojs/video.js/blob/master/src/js/component.js#L938) --- ### dispose() > Dispose of the component and all child components _inherited from_: [src/js/component.js#L84](https://github.com/videojs/video.js/blob/master/src/js/component.js#L84) --- ### el() > Get the component's DOM element > > var domEl = myComponent.el(); ##### RETURNS: * `Element` _inherited from_: [src/js/component.js#L220](https://github.com/videojs/video.js/blob/master/src/js/component.js#L220) --- ### enableTouchActivity() > Report user touch activity when touch events occur > > User activity is used to determine when controls should show/hide. It's > relatively simple when it comes to mouse events, because any mouse event > should show the controls. So we capture mouse events that bubble up to the > player and report activity when that happens. > > With touch events it isn't as easy. We can't rely on touch events at the > player level, because a tap (touchstart + touchend) on the video itself on > mobile devices is meant to turn controls off (and on). User activity is > checked asynchronously, so what could happen is a tap event on the video > turns the controls off, then the touchend event bubbles up to the player, > which if it reported user activity, would turn the controls right back on. > (We also don't want to completely block touch events from bubbling up) > > Also a touchmove, touch+hold, and anything other than a tap is not supposed > to turn the controls back on on a mobile device. > > Here we're setting the default component behavior to report user activity > whenever touch events happen, and this can be turned off by components that > want touch events to act differently. _inherited from_: [src/js/component.js#L1120](https://github.com/videojs/video.js/blob/master/src/js/component.js#L1120) --- ### getChild( name ) > Returns a child component with the provided name ##### PARAMETERS: * __name__ ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L330](https://github.com/videojs/video.js/blob/master/src/js/component.js#L330) --- ### getChildById( id ) > Returns a child component with the provided ID ##### PARAMETERS: * __id__ ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L313](https://github.com/videojs/video.js/blob/master/src/js/component.js#L313) --- ### hasClass( classToCheck ) > Check if a component's element has a CSS class name ##### PARAMETERS: * __classToCheck__ `String` Classname to check ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L816](https://github.com/videojs/video.js/blob/master/src/js/component.js#L816) --- ### height( [num], [skipListeners] ) > Get or set the height of the component (CSS values) > > Setting the video tag dimension values only works with values in pixels. > Percent values will not work. > Some percents can be used, but width()/height() will return the number + %, > not the actual computed width/height. ##### PARAMETERS: * __num__ `Number|String` _(OPTIONAL)_ New component height * __skipListeners__ `Boolean` _(OPTIONAL)_ Skip the resize event trigger ##### RETURNS: * `vjs.Component` This component, when setting the height * `Number|String` The height, when getting _inherited from_: [src/js/component.js#L927](https://github.com/videojs/video.js/blob/master/src/js/component.js#L927) --- ### hide() > Hide the component element if currently showing ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L857](https://github.com/videojs/video.js/blob/master/src/js/component.js#L857) --- ### id() > Get the component's ID > > var id = myComponent.id(); ##### RETURNS: * `String` _inherited from_: [src/js/component.js#L258](https://github.com/videojs/video.js/blob/master/src/js/component.js#L258) --- ### init( player, options, ready ) > the constructor function for the class ##### PARAMETERS: * __player__ * __options__ * __ready__ _inherited from_: [src/js/component.js#L41](https://github.com/videojs/video.js/blob/master/src/js/component.js#L41) --- ### initChildren() > Add and initialize default child components from options > > // when an instance of MyComponent is created, all children in options > // will be added to the instance by their name strings and options > MyComponent.prototype.options_.children = { > myChildComponent: { > myChildOption: true > } > } > > // Or when creating the component > var myComp = new MyComponent(player, { > children: { > myChildComponent: { > myChildOption: true > } > } > }); > > The children option can also be an Array of child names or > child options objects (that also include a 'name' key). > > var myComp = new MyComponent(player, { > children: [ > 'button', > { > name: 'button', > someOtherOption: true > } > ] > }); _inherited from_: [src/js/component.js#L481](https://github.com/videojs/video.js/blob/master/src/js/component.js#L481) --- ### name() > Get the component's name. The name is often used to reference the component. > > var name = myComponent.name(); ##### RETURNS: * `String` _inherited from_: [src/js/component.js#L277](https://github.com/videojs/video.js/blob/master/src/js/component.js#L277) --- ### off( [first], [second], [third] ) > Remove an event listener from this component's element > > myComponent.off('eventType', myFunc); > > If myFunc is excluded, ALL listeners for the event type will be removed. > If eventType is excluded, ALL listeners will be removed from the component. > > Alternatively you can use `off` to remove listeners that were added to other > elements or components using `myComponent.on(otherComponent...`. > In this case both the event type and listener function are REQUIRED. > > myComponent.off(otherElement, 'eventType', myFunc); > myComponent.off(otherComponent, 'eventType', myFunc); ##### PARAMETERS: * __first__ `String|vjs.Component` _(OPTIONAL)_ The event type or other component * __second__ `Function|String` _(OPTIONAL)_ The listener function or event type * __third__ `Function` _(OPTIONAL)_ The listener for other component ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L646](https://github.com/videojs/video.js/blob/master/src/js/component.js#L646) --- ### on( first, second, third ) > Add an event listener to this component's element > > var myFunc = function(){ > var myComponent = this; > // Do something when the event is fired > }; > > myComponent.on('eventType', myFunc); > > The context of myFunc will be myComponent unless previously bound. > > Alternatively, you can add a listener to another element or component. > > myComponent.on(otherElement, 'eventName', myFunc); > myComponent.on(otherComponent, 'eventName', myFunc); > > The benefit of using this over `vjs.on(otherElement, 'eventName', myFunc)` > and `otherComponent.on('eventName', myFunc)` is that this way the listeners > will be automatically cleaned up when either component is diposed. > It will also bind myComponent as the context of myFunc. > > **NOTE**: When using this on elements in the page other than window > and document (both permanent), if you remove the element from the DOM > you need to call `vjs.trigger(el, 'dispose')` on it to clean up > references to it and allow the browser to garbage collect it. ##### PARAMETERS: * __first__ `String|vjs.Component` The event type or other component * __second__ `Function|String` The event handler or event type * __third__ `Function` The event handler ##### RETURNS: * `vjs.Component` self _inherited from_: [src/js/component.js#L577](https://github.com/videojs/video.js/blob/master/src/js/component.js#L577) --- ### one( first, second, [third] ) > Add an event listener to be triggered only once and then removed > > myComponent.one('eventName', myFunc); > > Alternatively you can add a listener to another element or component > that will be triggered only once. > > myComponent.one(otherElement, 'eventName', myFunc); > myComponent.one(otherComponent, 'eventName', myFunc); ##### PARAMETERS: * __first__ `String|vjs.Component` The event type or other component * __second__ `Function|String` The listener function or event type * __third__ `Function` _(OPTIONAL)_ The listener function for other component ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L691](https://github.com/videojs/video.js/blob/master/src/js/component.js#L691) --- ### options( obj ) > Deep merge of options objects > > Whenever a property is an object on both options objects > the two properties will be merged using vjs.obj.deepMerge. > > This is used for merging options for child components. We > want it to be easy to override individual options on a child > component without having to rewrite all the other default options. > > Parent.prototype.options_ = { > children: { > 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' }, > 'childTwo': {}, > 'childThree': {} > } > } > newOptions = { > children: { > 'childOne': { 'foo': 'baz', 'abc': '123' } > 'childTwo': null, > 'childFour': {} > } > } > > this.options(newOptions); > > RESULT > > { > children: { > 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' }, > 'childTwo': null, // Disabled. Won't be initialized. > 'childThree': {}, > 'childFour': {} > } > } ##### PARAMETERS: * __obj__ `Object` Object of new option values ##### RETURNS: * `Object` A NEW object of this.options_ and obj merged _inherited from_: [src/js/component.js#L179](https://github.com/videojs/video.js/blob/master/src/js/component.js#L179) --- ### player() > Return the component's player ##### RETURNS: * `vjs.Player` _inherited from_: [src/js/component.js#L126](https://github.com/videojs/video.js/blob/master/src/js/component.js#L126) --- ### ready( fn ) > Bind a listener to the component's ready state > > Different from event listeners in that if the ready event has already happend > it will trigger the function immediately. ##### PARAMETERS: * __fn__ `Function` Ready listener ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L769](https://github.com/videojs/video.js/blob/master/src/js/component.js#L769) --- ### removeChild( component ) > Remove a child component from this component's list of children, and the > child component's element from this component's element ##### PARAMETERS: * __component__ `vjs.Component` Component to remove _inherited from_: [src/js/component.js#L420](https://github.com/videojs/video.js/blob/master/src/js/component.js#L420) --- ### removeClass( classToRemove ) > Remove a CSS class name from the component's element ##### PARAMETERS: * __classToRemove__ `String` Classname to remove ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L837](https://github.com/videojs/video.js/blob/master/src/js/component.js#L837) --- ### show() > Show the component element if hidden ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L847](https://github.com/videojs/video.js/blob/master/src/js/component.js#L847) --- ### trigger( event ) > Trigger an event on an element > > myComponent.trigger('eventName'); > myComponent.trigger({'type':'eventName'}); ##### PARAMETERS: * __event__ `Event|Object|String` A string (the type) or an event object with a type attribute ##### RETURNS: * `vjs.Component` self _inherited from_: [src/js/component.js#L724](https://github.com/videojs/video.js/blob/master/src/js/component.js#L724) --- ### triggerReady() > Trigger the ready listeners ##### RETURNS: * `vjs.Component` _inherited from_: [src/js/component.js#L788](https://github.com/videojs/video.js/blob/master/src/js/component.js#L788) --- ### width( [num], skipListeners ) > Set or get the width of the component (CSS values) > > Setting the video tag dimension values only works with values in pixels. > Percent values will not work. > Some percents can be used, but width()/height() will return the number + %, > not the actual computed width/height. ##### PARAMETERS: * __num__ `Number|String` _(OPTIONAL)_ Optional width number * __skipListeners__ `Boolean` Skip the 'resize' event trigger ##### RETURNS: * `vjs.Component` This component, when setting the width * `Number|String` The width, when getting _inherited from_: [src/js/component.js#L910](https://github.com/videojs/video.js/blob/master/src/js/component.js#L910) --- ## EVENTS ### resize `EVENT` > Fired when the width and/or height of the component changes _inherited from_: [src/js/component.js#L1020](https://github.com/videojs/video.js/blob/master/src/js/component.js#L1020) ---
scimusmn/sd-oak-tree
js/vendor/video-js/docs/api/vjs.VolumeHandle.md
Markdown
mit
17,770
/** ****************************************************************************** * @file stm32f7xx_hal_can.h * @author MCD Application Team * @version V1.2.2 * @date 14-April-2017 * @brief Header file of CAN HAL module. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F7xx_HAL_CAN_H #define __STM32F7xx_HAL_CAN_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f7xx_hal_def.h" /** @addtogroup STM32F7xx_HAL_Driver * @{ */ /** @addtogroup CAN * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CAN_Exported_Types CAN Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_CAN_STATE_RESET = 0x00U, /*!< CAN not yet initialized or disabled */ HAL_CAN_STATE_READY = 0x01U, /*!< CAN initialized and ready for use */ HAL_CAN_STATE_BUSY = 0x02U, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_TX = 0x12U, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_RX0 = 0x22U, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_RX1 = 0x32U, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_TX_RX0 = 0x42U, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_TX_RX1 = 0x52U, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_RX0_RX1 = 0x62U, /*!< CAN process is ongoing */ HAL_CAN_STATE_BUSY_TX_RX0_RX1 = 0x72U, /*!< CAN process is ongoing */ HAL_CAN_STATE_TIMEOUT = 0x03U, /*!< CAN in Timeout state */ HAL_CAN_STATE_ERROR = 0x04U /*!< CAN error state */ }HAL_CAN_StateTypeDef; /** * @brief CAN init structure definition */ typedef struct { uint32_t Prescaler; /*!< Specifies the length of a time quantum. This parameter must be a number between Min_Data = 1 and Max_Data = 1024 */ uint32_t Mode; /*!< Specifies the CAN operating mode. This parameter can be a value of @ref CAN_operating_mode */ uint32_t SJW; /*!< Specifies the maximum number of time quanta the CAN hardware is allowed to lengthen or shorten a bit to perform resynchronization. This parameter can be a value of @ref CAN_synchronisation_jump_width */ uint32_t BS1; /*!< Specifies the number of time quanta in Bit Segment 1. This parameter can be a value of @ref CAN_time_quantum_in_bit_segment_1 */ uint32_t BS2; /*!< Specifies the number of time quanta in Bit Segment 2. This parameter can be a value of @ref CAN_time_quantum_in_bit_segment_2 */ uint32_t TTCM; /*!< Enable or disable the time triggered communication mode. This parameter can be set to ENABLE or DISABLE. */ uint32_t ABOM; /*!< Enable or disable the automatic bus-off management. This parameter can be set to ENABLE or DISABLE */ uint32_t AWUM; /*!< Enable or disable the automatic wake-up mode. This parameter can be set to ENABLE or DISABLE */ uint32_t NART; /*!< Enable or disable the non-automatic retransmission mode. This parameter can be set to ENABLE or DISABLE */ uint32_t RFLM; /*!< Enable or disable the receive FIFO Locked mode. This parameter can be set to ENABLE or DISABLE */ uint32_t TXFP; /*!< Enable or disable the transmit FIFO priority. This parameter can be set to ENABLE or DISABLE */ }CAN_InitTypeDef; /** * @brief CAN filter configuration structure definition */ typedef struct { uint32_t FilterIdHigh; /*!< Specifies the filter identification number (MSBs for a 32-bit configuration, first one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t FilterIdLow; /*!< Specifies the filter identification number (LSBs for a 32-bit configuration, second one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t FilterMaskIdHigh; /*!< Specifies the filter mask number or identification number, according to the mode (MSBs for a 32-bit configuration, first one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t FilterMaskIdLow; /*!< Specifies the filter mask number or identification number, according to the mode (LSBs for a 32-bit configuration, second one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ uint32_t FilterFIFOAssignment; /*!< Specifies the FIFO (0 or 1) which will be assigned to the filter. This parameter can be a value of @ref CAN_filter_FIFO */ uint32_t FilterNumber; /*!< Specifies the filter which will be initialized. This parameter must be a number between Min_Data = 0 and Max_Data = 27 */ uint32_t FilterMode; /*!< Specifies the filter mode to be initialized. This parameter can be a value of @ref CAN_filter_mode */ uint32_t FilterScale; /*!< Specifies the filter scale. This parameter can be a value of @ref CAN_filter_scale */ uint32_t FilterActivation; /*!< Enable or disable the filter. This parameter can be set to ENABLE or DISABLE. */ uint32_t BankNumber; /*!< Select the start slave bank filter. This parameter must be a number between Min_Data = 0 and Max_Data = 28 */ }CAN_FilterConfTypeDef; /** * @brief CAN Tx message structure definition */ typedef struct { uint32_t StdId; /*!< Specifies the standard identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF */ uint32_t ExtId; /*!< Specifies the extended identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF */ uint32_t IDE; /*!< Specifies the type of identifier for the message that will be transmitted. This parameter can be a value of @ref CAN_Identifier_Type */ uint32_t RTR; /*!< Specifies the type of frame for the message that will be transmitted. This parameter can be a value of @ref CAN_remote_transmission_request */ uint32_t DLC; /*!< Specifies the length of the frame that will be transmitted. This parameter must be a number between Min_Data = 0 and Max_Data = 8 */ uint8_t Data[8]; /*!< Contains the data to be transmitted. This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF */ }CanTxMsgTypeDef; /** * @brief CAN Rx message structure definition */ typedef struct { uint32_t StdId; /*!< Specifies the standard identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF */ uint32_t ExtId; /*!< Specifies the extended identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF */ uint32_t IDE; /*!< Specifies the type of identifier for the message that will be received. This parameter can be a value of @ref CAN_Identifier_Type */ uint32_t RTR; /*!< Specifies the type of frame for the received message. This parameter can be a value of @ref CAN_remote_transmission_request */ uint32_t DLC; /*!< Specifies the length of the frame that will be received. This parameter must be a number between Min_Data = 0 and Max_Data = 8 */ uint8_t Data[8]; /*!< Contains the data to be received. This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF */ uint32_t FMI; /*!< Specifies the index of the filter the message stored in the mailbox passes through. This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF */ uint32_t FIFONumber; /*!< Specifies the receive FIFO number. This parameter can be CAN_FIFO0 or CAN_FIFO1 */ }CanRxMsgTypeDef; /** * @brief CAN handle Structure definition */ typedef struct { CAN_TypeDef *Instance; /*!< Register base address */ CAN_InitTypeDef Init; /*!< CAN required parameters */ CanTxMsgTypeDef* pTxMsg; /*!< Pointer to transmit structure */ CanRxMsgTypeDef* pRxMsg; /*!< Pointer to reception structure for RX FIFO0 msg */ CanRxMsgTypeDef* pRx1Msg; /*!< Pointer to reception structure for RX FIFO1 msg */ __IO HAL_CAN_StateTypeDef State; /*!< CAN communication state */ HAL_LockTypeDef Lock; /*!< CAN locking object */ __IO uint32_t ErrorCode; /*!< CAN Error code This parameter can be a value of @ref CAN_Error_Code */ }CAN_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup CAN_Exported_Constants CAN Exported Constants * @{ */ /** @defgroup CAN_Error_Code CAN Error Code * @{ */ #define HAL_CAN_ERROR_NONE 0x00000000U /*!< No error */ #define HAL_CAN_ERROR_EWG 0x00000001U /*!< EWG error */ #define HAL_CAN_ERROR_EPV 0x00000002U /*!< EPV error */ #define HAL_CAN_ERROR_BOF 0x00000004U /*!< BOF error */ #define HAL_CAN_ERROR_STF 0x00000008U /*!< Stuff error */ #define HAL_CAN_ERROR_FOR 0x00000010U /*!< Form error */ #define HAL_CAN_ERROR_ACK 0x00000020U /*!< Acknowledgment error */ #define HAL_CAN_ERROR_BR 0x00000040U /*!< Bit recessive */ #define HAL_CAN_ERROR_BD 0x00000080U /*!< LEC dominant */ #define HAL_CAN_ERROR_CRC 0x00000100U /*!< LEC transfer error */ #define HAL_CAN_ERROR_FOV0 0x00000200U /*!< FIFO0 overrun error */ #define HAL_CAN_ERROR_FOV1 0x00000400U /*!< FIFO1 overrun error */ #define HAL_CAN_ERROR_TXFAIL 0x00000800U /*!< Transmit failure */ /** * @} */ /** @defgroup CAN_InitStatus CAN InitStatus * @{ */ #define CAN_INITSTATUS_FAILED ((uint8_t)0x00U) /*!< CAN initialization failed */ #define CAN_INITSTATUS_SUCCESS ((uint8_t)0x01U) /*!< CAN initialization OK */ /** * @} */ /** @defgroup CAN_operating_mode CAN Operating Mode * @{ */ #define CAN_MODE_NORMAL ((uint32_t)0x00000000U) /*!< Normal mode */ #define CAN_MODE_LOOPBACK ((uint32_t)CAN_BTR_LBKM) /*!< Loopback mode */ #define CAN_MODE_SILENT ((uint32_t)CAN_BTR_SILM) /*!< Silent mode */ #define CAN_MODE_SILENT_LOOPBACK ((uint32_t)(CAN_BTR_LBKM | CAN_BTR_SILM)) /*!< Loopback combined with silent mode */ /** * @} */ /** @defgroup CAN_synchronisation_jump_width CAN Synchronisation Jump Width * @{ */ #define CAN_SJW_1TQ ((uint32_t)0x00000000U) /*!< 1 time quantum */ #define CAN_SJW_2TQ ((uint32_t)CAN_BTR_SJW_0) /*!< 2 time quantum */ #define CAN_SJW_3TQ ((uint32_t)CAN_BTR_SJW_1) /*!< 3 time quantum */ #define CAN_SJW_4TQ ((uint32_t)CAN_BTR_SJW) /*!< 4 time quantum */ /** * @} */ /** @defgroup CAN_time_quantum_in_bit_segment_1 CAN Time Quantum in bit segment 1 * @{ */ #define CAN_BS1_1TQ ((uint32_t)0x00000000U) /*!< 1 time quantum */ #define CAN_BS1_2TQ ((uint32_t)CAN_BTR_TS1_0) /*!< 2 time quantum */ #define CAN_BS1_3TQ ((uint32_t)CAN_BTR_TS1_1) /*!< 3 time quantum */ #define CAN_BS1_4TQ ((uint32_t)(CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 4 time quantum */ #define CAN_BS1_5TQ ((uint32_t)CAN_BTR_TS1_2) /*!< 5 time quantum */ #define CAN_BS1_6TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_0)) /*!< 6 time quantum */ #define CAN_BS1_7TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_1)) /*!< 7 time quantum */ #define CAN_BS1_8TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 8 time quantum */ #define CAN_BS1_9TQ ((uint32_t)CAN_BTR_TS1_3) /*!< 9 time quantum */ #define CAN_BS1_10TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_0)) /*!< 10 time quantum */ #define CAN_BS1_11TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_1)) /*!< 11 time quantum */ #define CAN_BS1_12TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 12 time quantum */ #define CAN_BS1_13TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2)) /*!< 13 time quantum */ #define CAN_BS1_14TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2 | CAN_BTR_TS1_0)) /*!< 14 time quantum */ #define CAN_BS1_15TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2 | CAN_BTR_TS1_1)) /*!< 15 time quantum */ #define CAN_BS1_16TQ ((uint32_t)CAN_BTR_TS1) /*!< 16 time quantum */ /** * @} */ /** @defgroup CAN_time_quantum_in_bit_segment_2 CAN Time Quantum in bit segment 2 * @{ */ #define CAN_BS2_1TQ ((uint32_t)0x00000000U) /*!< 1 time quantum */ #define CAN_BS2_2TQ ((uint32_t)CAN_BTR_TS2_0) /*!< 2 time quantum */ #define CAN_BS2_3TQ ((uint32_t)CAN_BTR_TS2_1) /*!< 3 time quantum */ #define CAN_BS2_4TQ ((uint32_t)(CAN_BTR_TS2_1 | CAN_BTR_TS2_0)) /*!< 4 time quantum */ #define CAN_BS2_5TQ ((uint32_t)CAN_BTR_TS2_2) /*!< 5 time quantum */ #define CAN_BS2_6TQ ((uint32_t)(CAN_BTR_TS2_2 | CAN_BTR_TS2_0)) /*!< 6 time quantum */ #define CAN_BS2_7TQ ((uint32_t)(CAN_BTR_TS2_2 | CAN_BTR_TS2_1)) /*!< 7 time quantum */ #define CAN_BS2_8TQ ((uint32_t)CAN_BTR_TS2) /*!< 8 time quantum */ /** * @} */ /** @defgroup CAN_filter_mode CAN Filter Mode * @{ */ #define CAN_FILTERMODE_IDMASK ((uint8_t)0x00U) /*!< Identifier mask mode */ #define CAN_FILTERMODE_IDLIST ((uint8_t)0x01U) /*!< Identifier list mode */ /** * @} */ /** @defgroup CAN_filter_scale CAN Filter Scale * @{ */ #define CAN_FILTERSCALE_16BIT ((uint8_t)0x00U) /*!< Two 16-bit filters */ #define CAN_FILTERSCALE_32BIT ((uint8_t)0x01U) /*!< One 32-bit filter */ /** * @} */ /** @defgroup CAN_filter_FIFO CAN Filter FIFO * @{ */ #define CAN_FILTER_FIFO0 ((uint8_t)0x00U) /*!< Filter FIFO 0 assignment for filter x */ #define CAN_FILTER_FIFO1 ((uint8_t)0x01U) /*!< Filter FIFO 1 assignment for filter x */ /** * @} */ /** @defgroup CAN_Identifier_Type CAN Identifier Type * @{ */ #define CAN_ID_STD ((uint32_t)0x00000000U) /*!< Standard Id */ #define CAN_ID_EXT ((uint32_t)0x00000004U) /*!< Extended Id */ /** * @} */ /** @defgroup CAN_remote_transmission_request CAN Remote Transmission Request * @{ */ #define CAN_RTR_DATA ((uint32_t)0x00000000U) /*!< Data frame */ #define CAN_RTR_REMOTE ((uint32_t)0x00000002U) /*!< Remote frame */ /** * @} */ /** @defgroup CAN_receive_FIFO_number_constants CAN Receive FIFO Number Constants * @{ */ #define CAN_FIFO0 ((uint8_t)0x00U) /*!< CAN FIFO 0 used to receive */ #define CAN_FIFO1 ((uint8_t)0x01U) /*!< CAN FIFO 1 used to receive */ /** * @} */ /** @defgroup CAN_flags CAN Flags * @{ */ /* If the flag is 0x3XXXXXXX, it means that it can be used with CAN_GetFlagStatus() and CAN_ClearFlag() functions. */ /* If the flag is 0x1XXXXXXX, it means that it can only be used with CAN_GetFlagStatus() function. */ /* Transmit Flags */ #define CAN_FLAG_RQCP0 ((uint32_t)0x00000500U) /*!< Request MailBox0 flag */ #define CAN_FLAG_RQCP1 ((uint32_t)0x00000508U) /*!< Request MailBox1 flag */ #define CAN_FLAG_RQCP2 ((uint32_t)0x00000510U) /*!< Request MailBox2 flag */ #define CAN_FLAG_TXOK0 ((uint32_t)0x00000501U) /*!< Transmission OK MailBox0 flag */ #define CAN_FLAG_TXOK1 ((uint32_t)0x00000509U) /*!< Transmission OK MailBox1 flag */ #define CAN_FLAG_TXOK2 ((uint32_t)0x00000511U) /*!< Transmission OK MailBox2 flag */ #define CAN_FLAG_TME0 ((uint32_t)0x0000051AU) /*!< Transmit mailbox 0 empty flag */ #define CAN_FLAG_TME1 ((uint32_t)0x0000051BU) /*!< Transmit mailbox 0 empty flag */ #define CAN_FLAG_TME2 ((uint32_t)0x0000051CU) /*!< Transmit mailbox 0 empty flag */ /* Receive Flags */ #define CAN_FLAG_FF0 ((uint32_t)0x00000203U) /*!< FIFO 0 Full flag */ #define CAN_FLAG_FOV0 ((uint32_t)0x00000204U) /*!< FIFO 0 Overrun flag */ #define CAN_FLAG_FF1 ((uint32_t)0x00000403U) /*!< FIFO 1 Full flag */ #define CAN_FLAG_FOV1 ((uint32_t)0x00000404U) /*!< FIFO 1 Overrun flag */ /* Operating Mode Flags */ #define CAN_FLAG_INAK ((uint32_t)0x00000100U) /*!< Initialization acknowledge flag */ #define CAN_FLAG_SLAK ((uint32_t)0x00000101U) /*!< Sleep acknowledge flag */ #define CAN_FLAG_ERRI ((uint32_t)0x00000102U) /*!< Error flag */ #define CAN_FLAG_WKU ((uint32_t)0x00000103U) /*!< Wake up flag */ #define CAN_FLAG_SLAKI ((uint32_t)0x00000104U) /*!< Sleep acknowledge flag */ /* @note When SLAK interrupt is disabled (SLKIE=0), no polling on SLAKI is possible. In this case the SLAK bit can be polled.*/ /* Error Flags */ #define CAN_FLAG_EWG ((uint32_t)0x00000300U) /*!< Error warning flag */ #define CAN_FLAG_EPV ((uint32_t)0x00000301U) /*!< Error passive flag */ #define CAN_FLAG_BOF ((uint32_t)0x00000302U) /*!< Bus-Off flag */ /** * @} */ /** @defgroup CAN_Interrupts CAN Interrupts * @{ */ #define CAN_IT_TME ((uint32_t)CAN_IER_TMEIE) /*!< Transmit mailbox empty interrupt */ /* Receive Interrupts */ #define CAN_IT_FMP0 ((uint32_t)CAN_IER_FMPIE0) /*!< FIFO 0 message pending interrupt */ #define CAN_IT_FF0 ((uint32_t)CAN_IER_FFIE0) /*!< FIFO 0 full interrupt */ #define CAN_IT_FOV0 ((uint32_t)CAN_IER_FOVIE0) /*!< FIFO 0 overrun interrupt */ #define CAN_IT_FMP1 ((uint32_t)CAN_IER_FMPIE1) /*!< FIFO 1 message pending interrupt */ #define CAN_IT_FF1 ((uint32_t)CAN_IER_FFIE1) /*!< FIFO 1 full interrupt */ #define CAN_IT_FOV1 ((uint32_t)CAN_IER_FOVIE1) /*!< FIFO 1 overrun interrupt */ /* Operating Mode Interrupts */ #define CAN_IT_WKU ((uint32_t)CAN_IER_WKUIE) /*!< Wake-up interrupt */ #define CAN_IT_SLK ((uint32_t)CAN_IER_SLKIE) /*!< Sleep acknowledge interrupt */ /* Error Interrupts */ #define CAN_IT_EWG ((uint32_t)CAN_IER_EWGIE) /*!< Error warning interrupt */ #define CAN_IT_EPV ((uint32_t)CAN_IER_EPVIE) /*!< Error passive interrupt */ #define CAN_IT_BOF ((uint32_t)CAN_IER_BOFIE) /*!< Bus-off interrupt */ #define CAN_IT_LEC ((uint32_t)CAN_IER_LECIE) /*!< Last error code interrupt */ #define CAN_IT_ERR ((uint32_t)CAN_IER_ERRIE) /*!< Error Interrupt */ /** * @} */ /** @defgroup CAN_Mailboxes_Definition CAN Mailboxes Definition * @{ */ #define CAN_TXMAILBOX_0 ((uint8_t)0x00U) #define CAN_TXMAILBOX_1 ((uint8_t)0x01U) #define CAN_TXMAILBOX_2 ((uint8_t)0x02U) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup CAN_Exported_Macros CAN Exported Macros * @{ */ /** @brief Reset CAN handle state * @param __HANDLE__: specifies the CAN Handle. * @retval None */ #define __HAL_CAN_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CAN_STATE_RESET) /** * @brief Enable the specified CAN interrupts. * @param __HANDLE__: CAN handle * @param __INTERRUPT__: CAN Interrupt * @retval None */ #define __HAL_CAN_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) |= (__INTERRUPT__)) /** * @brief Disable the specified CAN interrupts. * @param __HANDLE__: CAN handle * @param __INTERRUPT__: CAN Interrupt * @retval None */ #define __HAL_CAN_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) &= ~(__INTERRUPT__)) /** * @brief Return the number of pending received messages. * @param __HANDLE__: CAN handle * @param __FIFONUMBER__: Receive FIFO number, CAN_FIFO0 or CAN_FIFO1. * @retval The number of pending message. */ #define __HAL_CAN_MSG_PENDING(__HANDLE__, __FIFONUMBER__) (((__FIFONUMBER__) == CAN_FIFO0)? \ ((uint8_t)((__HANDLE__)->Instance->RF0R&(uint32_t)0x03)) : ((uint8_t)((__HANDLE__)->Instance->RF1R&(uint32_t)0x03))) /** @brief Check whether the specified CAN flag is set or not. * @param __HANDLE__: CAN Handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg CAN_TSR_RQCP0: Request MailBox0 Flag * @arg CAN_TSR_RQCP1: Request MailBox1 Flag * @arg CAN_TSR_RQCP2: Request MailBox2 Flag * @arg CAN_FLAG_TXOK0: Transmission OK MailBox0 Flag * @arg CAN_FLAG_TXOK1: Transmission OK MailBox1 Flag * @arg CAN_FLAG_TXOK2: Transmission OK MailBox2 Flag * @arg CAN_FLAG_TME0: Transmit mailbox 0 empty Flag * @arg CAN_FLAG_TME1: Transmit mailbox 1 empty Flag * @arg CAN_FLAG_TME2: Transmit mailbox 2 empty Flag * @arg CAN_FLAG_FMP0: FIFO 0 Message Pending Flag * @arg CAN_FLAG_FF0: FIFO 0 Full Flag * @arg CAN_FLAG_FOV0: FIFO 0 Overrun Flag * @arg CAN_FLAG_FMP1: FIFO 1 Message Pending Flag * @arg CAN_FLAG_FF1: FIFO 1 Full Flag * @arg CAN_FLAG_FOV1: FIFO 1 Overrun Flag * @arg CAN_FLAG_WKU: Wake up Flag * @arg CAN_FLAG_SLAK: Sleep acknowledge Flag * @arg CAN_FLAG_SLAKI: Sleep acknowledge Flag * @arg CAN_FLAG_EWG: Error Warning Flag * @arg CAN_FLAG_EPV: Error Passive Flag * @arg CAN_FLAG_BOF: Bus-Off Flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_CAN_GET_FLAG(__HANDLE__, __FLAG__) \ ((((__FLAG__) >> 8) == 5)? ((((__HANDLE__)->Instance->TSR) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 2)? ((((__HANDLE__)->Instance->RF0R) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 4)? ((((__HANDLE__)->Instance->RF1R) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 1)? ((((__HANDLE__)->Instance->MSR) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ ((((__HANDLE__)->Instance->ESR) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK)))) /** @brief Clear the specified CAN pending flag. * @param __HANDLE__: CAN Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg CAN_TSR_RQCP0: Request MailBox0 Flag * @arg CAN_TSR_RQCP1: Request MailBox1 Flag * @arg CAN_TSR_RQCP2: Request MailBox2 Flag * @arg CAN_FLAG_TXOK0: Transmission OK MailBox0 Flag * @arg CAN_FLAG_TXOK1: Transmission OK MailBox1 Flag * @arg CAN_FLAG_TXOK2: Transmission OK MailBox2 Flag * @arg CAN_FLAG_TME0: Transmit mailbox 0 empty Flag * @arg CAN_FLAG_TME1: Transmit mailbox 1 empty Flag * @arg CAN_FLAG_TME2: Transmit mailbox 2 empty Flag * @arg CAN_FLAG_FMP0: FIFO 0 Message Pending Flag * @arg CAN_FLAG_FF0: FIFO 0 Full Flag * @arg CAN_FLAG_FOV0: FIFO 0 Overrun Flag * @arg CAN_FLAG_FMP1: FIFO 1 Message Pending Flag * @arg CAN_FLAG_FF1: FIFO 1 Full Flag * @arg CAN_FLAG_FOV1: FIFO 1 Overrun Flag * @arg CAN_FLAG_WKU: Wake up Flag * @arg CAN_FLAG_SLAK: Sleep acknowledge Flag * @arg CAN_FLAG_SLAKI: Sleep acknowledge Flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_CAN_CLEAR_FLAG(__HANDLE__, __FLAG__) \ ((((__FLAG__) >> 8) == 5)? (((__HANDLE__)->Instance->TSR) = ((uint32_t)1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 2)? (((__HANDLE__)->Instance->RF0R) = ((uint32_t)1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8) == 4)? (((__HANDLE__)->Instance->RF1R) = ((uint32_t)1 << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__HANDLE__)->Instance->MSR) = ((uint32_t)1 << ((__FLAG__) & CAN_FLAG_MASK)))) /** @brief Check if the specified CAN interrupt source is enabled or disabled. * @param __HANDLE__: CAN Handle * @param __INTERRUPT__: specifies the CAN interrupt source to check. * This parameter can be one of the following values: * @arg CAN_IT_TME: Transmit mailbox empty interrupt enable * @arg CAN_IT_FMP0: FIFO0 message pending interrupt enable * @arg CAN_IT_FMP1: FIFO1 message pending interrupt enable * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_CAN_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) /** * @brief Check the transmission status of a CAN Frame. * @param __HANDLE__: CAN Handle * @param __TRANSMITMAILBOX__: the number of the mailbox that is used for transmission. * @retval The new status of transmission (TRUE or FALSE). */ #define __HAL_CAN_TRANSMIT_STATUS(__HANDLE__, __TRANSMITMAILBOX__)\ (((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_0)? ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP0 | CAN_TSR_TXOK0 | CAN_TSR_TME0)) == (CAN_TSR_RQCP0 | CAN_TSR_TXOK0 | CAN_TSR_TME0)) :\ ((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_1)? ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP1 | CAN_TSR_TXOK1 | CAN_TSR_TME1)) == (CAN_TSR_RQCP1 | CAN_TSR_TXOK1 | CAN_TSR_TME1)) :\ ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP2 | CAN_TSR_TXOK2 | CAN_TSR_TME2)) == (CAN_TSR_RQCP2 | CAN_TSR_TXOK2 | CAN_TSR_TME2))) /** * @brief Release the specified receive FIFO. * @param __HANDLE__: CAN handle * @param __FIFONUMBER__: Receive FIFO number, CAN_FIFO0 or CAN_FIFO1. * @retval None */ #define __HAL_CAN_FIFO_RELEASE(__HANDLE__, __FIFONUMBER__) (((__FIFONUMBER__) == CAN_FIFO0)? \ ((__HANDLE__)->Instance->RF0R = CAN_RF0R_RFOM0) : ((__HANDLE__)->Instance->RF1R = CAN_RF1R_RFOM1)) /** * @brief Cancel a transmit request. * @param __HANDLE__: CAN Handle * @param __TRANSMITMAILBOX__: the number of the mailbox that is used for transmission. * @retval None */ #define __HAL_CAN_CANCEL_TRANSMIT(__HANDLE__, __TRANSMITMAILBOX__)\ (((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_0)? ((__HANDLE__)->Instance->TSR = CAN_TSR_ABRQ0) :\ ((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_1)? ((__HANDLE__)->Instance->TSR = CAN_TSR_ABRQ1) :\ ((__HANDLE__)->Instance->TSR = CAN_TSR_ABRQ2)) /** * @brief Enable or disable the DBG Freeze for CAN. * @param __HANDLE__: CAN Handle * @param __NEWSTATE__: new state of the CAN peripheral. * This parameter can be: ENABLE (CAN reception/transmission is frozen * during debug. Reception FIFOs can still be accessed/controlled normally) * or DISABLE (CAN is working during debug). * @retval None */ #define __HAL_CAN_DBG_FREEZE(__HANDLE__, __NEWSTATE__) (((__NEWSTATE__) == ENABLE)? \ ((__HANDLE__)->Instance->MCR |= CAN_MCR_DBF) : ((__HANDLE__)->Instance->MCR &= ~CAN_MCR_DBF)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CAN_Exported_Functions * @{ */ /** @addtogroup CAN_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions ***********************************/ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan); HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef* hcan, CAN_FilterConfTypeDef* sFilterConfig); HAL_StatusTypeDef HAL_CAN_DeInit(CAN_HandleTypeDef* hcan); void HAL_CAN_MspInit(CAN_HandleTypeDef* hcan); void HAL_CAN_MspDeInit(CAN_HandleTypeDef* hcan); /** * @} */ /** @addtogroup CAN_Exported_Functions_Group2 * @{ */ /* I/O operation functions ******************************************************/ HAL_StatusTypeDef HAL_CAN_Transmit(CAN_HandleTypeDef *hcan, uint32_t Timeout); HAL_StatusTypeDef HAL_CAN_Transmit_IT(CAN_HandleTypeDef *hcan); HAL_StatusTypeDef HAL_CAN_Receive(CAN_HandleTypeDef *hcan, uint8_t FIFONumber, uint32_t Timeout); HAL_StatusTypeDef HAL_CAN_Receive_IT(CAN_HandleTypeDef *hcan, uint8_t FIFONumber); HAL_StatusTypeDef HAL_CAN_Sleep(CAN_HandleTypeDef *hcan); HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef *hcan); void HAL_CAN_IRQHandler(CAN_HandleTypeDef* hcan); void HAL_CAN_TxCpltCallback(CAN_HandleTypeDef* hcan); void HAL_CAN_RxCpltCallback(CAN_HandleTypeDef* hcan); void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan); /** * @} */ /** @addtogroup CAN_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ***************************************************/ uint32_t HAL_CAN_GetError(CAN_HandleTypeDef *hcan); HAL_CAN_StateTypeDef HAL_CAN_GetState(CAN_HandleTypeDef* hcan); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup CAN_Private_Types CAN Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup CAN_Private_Variables CAN Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup CAN_Private_Constants CAN Private Constants * @{ */ #define CAN_TXSTATUS_NOMAILBOX ((uint8_t)0x04U) /*!< CAN cell did not provide CAN_TxStatus_NoMailBox */ #define CAN_FLAG_MASK ((uint32_t)0x000000FFU) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup CAN_Private_Macros CAN Private Macros * @{ */ #define IS_CAN_MODE(MODE) (((MODE) == CAN_MODE_NORMAL) || \ ((MODE) == CAN_MODE_LOOPBACK)|| \ ((MODE) == CAN_MODE_SILENT) || \ ((MODE) == CAN_MODE_SILENT_LOOPBACK)) #define IS_CAN_SJW(SJW) (((SJW) == CAN_SJW_1TQ) || ((SJW) == CAN_SJW_2TQ)|| \ ((SJW) == CAN_SJW_3TQ) || ((SJW) == CAN_SJW_4TQ)) #define IS_CAN_BS1(BS1) ((BS1) <= CAN_BS1_16TQ) #define IS_CAN_BS2(BS2) ((BS2) <= CAN_BS2_8TQ) #define IS_CAN_PRESCALER(PRESCALER) (((PRESCALER) >= 1) && ((PRESCALER) <= 1024)) #define IS_CAN_FILTER_NUMBER(NUMBER) ((NUMBER) <= 27) #define IS_CAN_FILTER_MODE(MODE) (((MODE) == CAN_FILTERMODE_IDMASK) || \ ((MODE) == CAN_FILTERMODE_IDLIST)) #define IS_CAN_FILTER_SCALE(SCALE) (((SCALE) == CAN_FILTERSCALE_16BIT) || \ ((SCALE) == CAN_FILTERSCALE_32BIT)) #define IS_CAN_FILTER_FIFO(FIFO) (((FIFO) == CAN_FILTER_FIFO0) || \ ((FIFO) == CAN_FILTER_FIFO1)) #define IS_CAN_BANKNUMBER(BANKNUMBER) ((BANKNUMBER) <= 28) #define IS_CAN_TRANSMITMAILBOX(TRANSMITMAILBOX) ((TRANSMITMAILBOX) <= ((uint8_t)0x02)) #define IS_CAN_STDID(STDID) ((STDID) <= ((uint32_t)0x7FF)) #define IS_CAN_EXTID(EXTID) ((EXTID) <= ((uint32_t)0x1FFFFFFF)) #define IS_CAN_DLC(DLC) ((DLC) <= ((uint8_t)0x08)) #define IS_CAN_IDTYPE(IDTYPE) (((IDTYPE) == CAN_ID_STD) || \ ((IDTYPE) == CAN_ID_EXT)) #define IS_CAN_RTR(RTR) (((RTR) == CAN_RTR_DATA) || ((RTR) == CAN_RTR_REMOTE)) #define IS_CAN_FIFO(FIFO) (((FIFO) == CAN_FIFO0) || ((FIFO) == CAN_FIFO1)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup CAN_Private_Functions CAN Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F7xx_CAN_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
ChangsoonKim/STM32F7DiscTutor
UART_TEST/Drivers/STM32F7xx_HAL_Driver/Inc/stm32f7xx_hal_can.h
C
mit
36,914
<?php defined('BX_DOL') or die('hack attempt'); /** * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/ * CC-BY License - http://creativecommons.org/licenses/by/3.0/ * * @defgroup Convos Convos * @ingroup TridentModules * * @{ */ /* * Module database queries */ class BxCnvDb extends BxBaseModTextDb { public function __construct(&$oConfig) { parent::__construct($oConfig); } public function conversationToFolder($iConversationId, $iFolderId, $iProfileCollaborator, $iReadCommentsNum = -1) { $sQuery = $this->prepare("INSERT INTO `" . $this->getPrefix() . "conv2folder` SET `conv_id` = ?, `folder_id` = ?, `collaborator` = ?, `read_comments` = ?", $iConversationId, $iFolderId, $iProfileCollaborator, $iReadCommentsNum); return $this->query($sQuery); } public function getFolder($iFolderId) { $sQuery = $this->prepare("SELECT `id`, `author`, `name` FROM `" . $this->getPrefix() . "folders` WHERE `id` = ?", $iFolderId); return $this->getRow($sQuery); } public function getConversationFolder($iConversationId, $iProfileCollaborator) { $sQuery = $this->prepare("SELECT `folder_id` FROM `" . $this->getPrefix() . "conv2folder` WHERE `conv_id` = ? AND `collaborator` = ?", $iConversationId, $iProfileCollaborator); return $this->getOne($sQuery); } public function getCollaborators($iConversationId) { $sQuery = $this->prepare("SELECT `collaborator`, `read_comments` FROM `" . $this->getPrefix() . "conv2folder` WHERE `conv_id` = ?", $iConversationId); return $this->getPairs($sQuery, 'collaborator', 'read_comments'); } public function updateReadComments($iProfileId, $iConversationId, $iReadComments) { $sQuery = $this->prepare("UPDATE `" . $this->getPrefix() . "conv2folder` SET `read_comments` = ? WHERE `conv_id` = ? AND `collaborator` = ?", $iReadComments, $iConversationId, $iProfileId); return $this->query($sQuery); } public function updateLastCommentTimeProfile($iConversationId, $iProfileId, $iCommentId, $iTimestamp) { $sQuery = $this->prepare("UPDATE `" . $this->getPrefix() . "conversations` SET `last_reply_profile_id` = ?, `last_reply_timestamp` = ?, `last_reply_comment_id` = ? WHERE `id` = ?", $iProfileId, $iTimestamp, $iCommentId, $iConversationId); return $this->query($sQuery); } public function moveConvo($iConversationId, $iProfileId, $iFolderId) { $sQuery = $this->prepare("SELECT `folder_id` FROM `" . $this->getPrefix() . "conv2folder` WHERE `conv_id` = ? AND `collaborator` = ?", $iConversationId, $iProfileId); $iFolderIdOld = $this->getOne($sQuery); if (BX_CNV_FOLDER_TRASH == $iFolderIdOld) // if convo is already in trash folder - delete it return $this->deleteConvo($iConversationId, $iProfileId); $sQuery = $this->prepare("UPDATE `" . $this->getPrefix() . "conv2folder` SET `folder_id` = ? WHERE `conv_id` = ? AND `collaborator` = ?", $iFolderId, $iConversationId, $iProfileId); return $this->query($sQuery); } public function deleteConvo($iConversationId, $iProfileId = 0) { $aContentInfo = $this->getContentInfoById ($iConversationId); if (!$aContentInfo) return true; // delete convo $sWhere = ''; if ($iProfileId) $sWhere = $this->prepare(" AND `collaborator` = ?", $iProfileId); $sQuery = $this->prepare("DELETE FROM `" . $this->getPrefix() . "conv2folder` WHERE `conv_id` = ?", $iConversationId); if (!$this->query($sQuery . $sWhere)) return false; // delete whole conversation if there is no refencences to the conversation in conv2folder table $sQuery = $this->prepare("SELECT `id` FROM `" . $this->getPrefix() . "conv2folder` WHERE `conv_id` = ?", $iConversationId); if (!$this->getOne($sQuery)) { $CNF = &$this->_oConfig->CNF; $oForm = BxDolForm::getObjectInstance($CNF['OBJECT_FORM_ENTRY'], $CNF['OBJECT_FORM_ENTRY_DISPLAY_ADD']); return $oForm->delete((int)$iConversationId, $aContentInfo); } return true; } public function getUnreadMessagesNum ($iProfileId, $iFolderId = BX_CNV_FOLDER_INBOX) { $sQuery = $this->prepare("SELECT SUM(`c`.`comments` - `f`.`read_comments`) FROM `" . $this->getPrefix() . "conv2folder` as `f` INNER JOIN `" . $this->getPrefix() . "conversations` AS `c` ON (`c`.`id` = `f`.`conv_id`) WHERE `f`.`collaborator` = ? AND `f`.`folder_id` = ?", $iProfileId, $iFolderId); return $this->getOne($sQuery); } public function getMessagesPreviews ($iProfileId, $iStart = 0, $iLimit = 4, $iFolderId = BX_CNV_FOLDER_INBOX) { $sQuery = $this->prepare("SELECT `c`.`id`, `c`.`text`, `c`.`author`, `cmts`.`cmt_text`, `c`.`last_reply_profile_id`, `c`.`comments`, (`c`.`comments` - `f`.`read_comments`) AS `unread_messages`, `last_reply_timestamp` FROM `" . $this->getPrefix() . "conv2folder` as `f` INNER JOIN `" . $this->getPrefix() . "conversations` AS `c` ON (`c`.`id` = `f`.`conv_id`) LEFT JOIN `" . $this->getPrefix() . "cmts` AS `cmts` ON (`cmts`.`cmt_id` = `c`.`last_reply_comment_id`) WHERE `f`.`collaborator` = ? AND `f`.`folder_id` = ? ORDER BY `c`.`last_reply_timestamp` DESC LIMIT ?, ?", $iProfileId, $iFolderId, $iStart, $iLimit); return $this->getAll($sQuery); } } /** @} */
camperjz/trident
modules/boonex/convos/updates/8.0.4_8.0.5/source/classes/BxCnvDb.php
PHP
mit
5,576
/** * $Id: editor_plugin_src.js,v 1.1 2012/11/16 23:22:25 delara Exp $ * * @author Moxiecode * @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved. */ (function() { tinymce.create('tinymce.plugins.Preview', { init : function(ed, url) { var t = this; t.editor = ed; ed.addCommand('mcePreview', t._preview, t); ed.addButton('preview', {title : 'preview.preview_desc', cmd : 'mcePreview'}); }, getInfo : function() { return { longname : 'Preview', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/preview', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _preview : function() { var ed = this.editor, win, html, c, pos, pos2, css, i, page = ed.getParam("plugin_preview_pageurl", null), w = ed.getParam("plugin_preview_width", "550"), h = ed.getParam("plugin_preview_height", "600"); // Use a custom preview page if (page) { ed.windowManager.open({ file : ed.getParam("plugin_preview_pageurl", null), width : w, height : h }, { resizable : "yes", scrollbars : "yes", inline : 1 }); } else { win = window.open("", "mcePreview", "menubar=no,toolbar=no,scrollbars=yes,resizable=yes,left=20,top=20,width=" + w + ",height=" + h); html = ""; c = ed.getContent(); pos = c.indexOf('<body'); css = ed.getParam("content_css", '').split(','); tinymce.map(css, function(u) { return ed.documentBaseURI.toAbsolute(u); }); if (pos != -1) { pos = c.indexOf('>', pos); pos2 = c.lastIndexOf('</body>'); c = c.substring(pos + 1, pos2); } html += ed.getParam('doctype'); html += '<html xmlns="http://www.w3.org/1999/xhtml">'; html += '<head>'; html += '<title>' + ed.getLang('preview.preview_desc') + '</title>'; html += '<base href="' + ed.documentBaseURI.getURI() + '" />'; html += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'; for (i=0; i<css.length; i++) html += '<link href="' + css[i] + '" rel="stylesheet" type="text/css" />'; html += '</head>'; html += '<body dir="' + ed.getParam("directionality") + '" onload="window.opener.tinymce.EditorManager.get(\'' + ed.id + '\').plugins[\'preview\']._onLoad(window,document);">'; html += c; html += '</body>'; html += '</html>'; win.document.write(html); win.document.close(); } }, _onLoad : function(w, d) { var t = this, nl, i, el = [], sv, ne; t._doc = d; w.writeFlash = t._writeFlash; w.writeShockWave = t._writeShockWave; w.writeQuickTime = t._writeQuickTime; w.writeRealMedia = t._writeRealMedia; w.writeWindowsMedia = t._writeWindowsMedia; w.writeEmbed = t._writeEmbed; nl = d.getElementsByTagName("script"); for (i=0; i<nl.length; i++) { sv = tinymce.isIE ? nl[i].innerHTML : nl[i].firstChild.nodeValue; if (new RegExp('write(Flash|ShockWave|WindowsMedia|QuickTime|RealMedia)\\(.*', 'g').test(sv)) el[el.length] = nl[i]; } for (i=0; i<el.length; i++) { ne = d.createElement("div"); ne.innerHTML = d._embeds[i]; el[i].parentNode.insertBefore(ne.firstChild, el[i]); } }, _writeFlash : function(p) { p.src = this.editor.documentBaseURI.toAbsolute(p.src); TinyMCE_PreviewPlugin._writeEmbed( 'D27CDB6E-AE6D-11cf-96B8-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'application/x-shockwave-flash', p ); }, _writeShockWave : function(p) { this.editor.documentBaseURI.toAbsolute(p.src); TinyMCE_PreviewPlugin._writeEmbed( '166B1BCA-3F9C-11CF-8075-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0', 'application/x-director', p ); }, _writeQuickTime : function(p) { this.editor.documentBaseURI.toAbsolute(p.src); TinyMCE_PreviewPlugin._writeEmbed( '02BF25D5-8C17-4B23-BC80-D3488ABDDC6B', 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0', 'video/quicktime', p ); }, _writeRealMedia : function(p) { this.editor.documentBaseURI.toAbsolute(p.src); TinyMCE_PreviewPlugin._writeEmbed( 'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'audio/x-pn-realaudio-plugin', p ); }, _writeWindowsMedia : function(p) { this.editor.documentBaseURI.toAbsolute(p.src); p.url = p.src; TinyMCE_PreviewPlugin._writeEmbed( '6BF52A52-394A-11D3-B153-00C04F79FAA6', 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701', 'application/x-mplayer2', p ); }, _writeEmbed : function(cls, cb, mt, p) { var h = '', n, d = t._doc, ne, c; h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"'; h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : ''; h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : ''; h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : ''; h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : ''; h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : ''; h += '>'; for (n in p) h += '<param name="' + n + '" value="' + p[n] + '">'; h += '<embed type="' + mt + '"'; for (n in p) h += n + '="' + p[n] + '" '; h += '></embed></object>'; d._embeds[d._embeds.length] = h; } }); // Register plugin tinymce.PluginManager.add('preview', tinymce.plugins.Preview); })();
StevenDao/Storefront-Calendar
website/js/tiny_mce/plugins/preview/editor_plugin_src.js
JavaScript
mit
5,686
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Message.updated' db.alter_column(u'mailer_message', 'updated', self.gf('django.db.models.fields.DateTimeField')(auto_now=True)) def backwards(self, orm): # Changing field 'Message.updated' db.alter_column(u'mailer_message', 'updated', self.gf('django.db.models.fields.DateTimeField')()) models = { u'mailer.message': { 'Meta': {'object_name': 'Message'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'message_data': ('django.db.models.fields.TextField', [], {}), 'priority': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '2'}), 'recipients': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'subject': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) } } complete_apps = ['mailer']
zamazaljiri/django-mailer
mailer/migrations/0002_auto__chg_field_message_updated.py
Python
mit
1,493
<div class="form-group {{options.col}}" ng-class="{'has-error': $invalid, 'has-success': !$invalid && $dirty}" style="position:relative" ng-hide="options.hidden"> <label for="{{id}}"> {{options.label}} {{options.required ? '*' : ''}} </label> <div class="input-group"> <span class="input-group-btn"> <button class="btn btn-{{options.typebutton || 'default' }} btn-{{options.inputSize || 'default'}}" type="button">{{options.textbutton}}</button> </span> <!--style="min-width:250px" --> <input type="text" class="form-control input-{{options.inputSize || 'default'}}" id="{{id}}" name="{{name}}" placeholder="{{options.placeholder}}" edu-focus="options.autofocus" ng-required="options.required" ng-disabled="options.disabled" ng-readonly="options.readonly" ng-minlength="options.min" ng-maxlength="options.max" ng-pattern="nifniecifValidator" ng-model="value" ng-blur="onBlur()" ng-focus="onFocus()" ng-change="onChange()"> </div> <div class="help-block has-error" ng-show="$invalid" style="position:absolute;top:50px"> <small class="error" ng-show="$invalidRequired">Campo obligatorio. Introduzca un {{options.textbutton|| 'Número de documento'}}</small> <small class="error" ng-show="$invalidMinlength">Debe tener al menos {{options.min}} caracteres</small> <small class="error" ng-show="$invalidMaxlength">No puede tener más de {{options.max}} caracteres</small> <small class="error" ng-show="$invalidPattern">Introduzca un {{options.textbutton|| 'Número de documento'}} válido</small> </div> </div>
educarm/edu-field
src/directives/edu-field-nifniecif-tpl.html
HTML
mit
1,640
// jsonCall: a jQuery plugin that makes it easy to make an API // request to a URL with JSON in BOTH directions. // // Copyright 2013 P'unk Avenue LLC // // Please see: // // https://github.com/punkave/jquery-json-call // // For complete documentation. (function( $ ) { // This is correct - we're adding a function called directly // like $.get or $.ajax, not a function that operates on // elements $.jsonCall = function(url, options, data, success, failure) { if (typeof(data) === 'function') { // No options argument passed, shift the others over failure = success; success = data; data = options; options = undefined; } options = options || {}; var ajax = $.ajax({ type: 'POST', url: url, processData: false, contentType: 'application/json', data: JSON.stringify(data), dataType: options.dataType || 'json', success: success, async: options.async, }); if (failure) { ajax.fail(failure); } }; })( jQuery );
koeppel/apocms
public/modules/apostrophe-assets/js/vendor/jquery.json-call.js
JavaScript
mit
1,033
// # ngReact // ### Use React Components inside of your Angular applications // // Composed of // - reactComponent (generic directive for delegating off to React Components) // - reactDirective (factory for creating specific directives that correspond to reactComponent directives) (function(React, angular) { 'use strict'; // get a react component from name (components can be an angular injectable e.g. value, factory or // available on window function getReactComponent( name, $injector ) { // if name is a function assume it is component and return it if (angular.isFunction(name)) { return name; } // a React component name must be specified if (!name) { throw new Error('ReactComponent name attribute must be specified'); } // ensure the specified React component is accessible, and fail fast if it's not var reactComponent; try { reactComponent = $injector.get(name); } catch(e) { } reactComponent = reactComponent || window[name]; if (!reactComponent) { throw Error('Cannot find react component ' + name); } return reactComponent; } // wraps a function with scope.$apply, if already applied just return function applied(fn, scope) { if (fn.wrappedInApply) { return fn; } return function() { var args = arguments; scope.$apply(function() { fn.wrappedInApply = true; fn.apply( null, args ); }); }; } // wraps all functions on obj in scope.$apply function applyFunctions(obj, scope) { return Object.keys(obj || {}).reduce(function(prev,key) { var value = obj[key]; // wrap functions in a function that ensures they are scope.$applied // ensures that when function is called from a React component // the Angular digest cycle is run prev[key] = angular.isFunction(value) ? applied(value, scope) : value; return prev; }, {}); } // render React component, with scope[attrs.props] being passed in as the component props function renderComponent(component, props, $timeout, elem) { $timeout(function() { React.render(React.createElement(component, props), elem[0]); }); } // # reactComponent // Directive that allows React components to be used in Angular templates. // // Usage: // <react-component name="Hello" props="name"/> // // This requires that there exists an injectable or globally available 'Hello' React component. // The 'props' attribute is optional and is passed to the component. // // The following would would create and register the component: // // /** @jsx React.DOM */ // var module = angular.module('ace.react.components'); // module.value('Hello', React.createClass({ // render: function() { // return <div>Hello {this.props.name}</div>; // } // })); // var reactComponent = function($timeout, $injector) { return { restrict: 'E', replace: true, link: function(scope, elem, attrs) { var reactComponent = getReactComponent(attrs.name, $injector); var renderMyComponent = function() { var scopeProps = scope[attrs.props]; var props = applyFunctions(scopeProps, scope); renderComponent(reactComponent, props, $timeout, elem); }; // If there are props, re-render when they change attrs.props ? scope.$watch(attrs.props, renderMyComponent, true) : renderMyComponent(); // cleanup when scope is destroyed scope.$on('$destroy', function() { React.unmountComponentAtNode(elem[0]); }); } }; }; // # reactDirective // Factory function to create directives for React components. // // With a component like this: // // /** @jsx React.DOM */ // var module = angular.module('ace.react.components'); // module.value('Hello', React.createClass({ // render: function() { // return <div>Hello {this.props.name}</div>; // } // })); // // A directive can be created and registered with: // // module.directive('hello', function(reactDirective) { // return reactDirective('Hello', ['name']); // }); // // Where the first argument is the injectable or globally accessible name of the React component // and the second argument is an array of property names to be watched and passed to the React component // as props. // // This directive can then be used like this: // // <hello name="name"/> // var reactDirective = function($timeout, $injector) { return function(reactComponentName, propNames) { return { restrict: 'E', replace: true, link: function(scope, elem, attrs) { var reactComponent = getReactComponent(reactComponentName, $injector); // if propNames is not defined, fall back to use the React component's propTypes if present propNames = propNames || Object.keys(reactComponent.propTypes || {}); // for each of the properties, get their scope value and set it to scope.props var renderMyComponent = function() { var props = {}; propNames.forEach(function(propName) { props[propName] = scope.$eval(attrs[propName]); }); renderComponent(reactComponent, applyFunctions(props, scope), $timeout, elem); }; // watch each property name and trigger an update whenever something changes, // to update scope.props with new values propNames.forEach(function(k) { scope.$watch(attrs[k], renderMyComponent, true); }); renderMyComponent(); // cleanup when scope is destroyed scope.$on('$destroy', function() { React.unmountComponentAtNode(elem[0]); }); } }; }; }; // create the end module without any dependencies, including reactComponent and reactDirective angular.module('react', []) .directive('reactComponent', ['$timeout', '$injector', reactComponent]) .factory('reactDirective', ['$timeout','$injector', reactDirective]); })(window.React, window.angular);
krunalifuturz/ngReact
ngReact.js
JavaScript
mit
6,266
<?php namespace Faker\Provider\de_AT; class Company extends \Faker\Provider\Company { protected static $formats = [ '{{lastName}} {{companySuffix}}', '{{lastName}}', ]; protected static $companySuffix = ['AG', 'EWIV', 'Ges.m.b.H.', 'GmbH', 'KEG', 'KG', 'OEG', 'OG', 'OHG', 'SE']; }
drakakisgeo/mailtester
vendor/fakerphp/faker/src/Faker/Provider/de_AT/Company.php
PHP
mit
313
<?php namespace Trello\Api\Board; use Trello\Api\AbstractApi; /** * Trello Board Memberships API * @link https://trello.com/docs/api/board * * Not implemented: * - https://trello.com/docs/api/board/#get-1-boards-board-id-memberships * - https://trello.com/docs/api/board/#get-1-boards-board-id-memberships-idmembership * - https://trello.com/docs/api/board/#put-1-boards-board-id-memberships-idmembership */ class Memberships extends AbstractApi { /** * Base path of board power ups api * @var string */ protected $path = 'boards/#id#/memberships'; }
hoangnghia/API-Trello
lib/Trello/Api/Board/Memberships.php
PHP
mit
585
#region License /*---------------------------------------------------------------------------------*\ Distributed under the terms of an MIT-style license: The MIT License Copyright (c) 2006-2010 Stephen M. McKamey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*---------------------------------------------------------------------------------*/ #endregion License using System; namespace JsonFx.Html { /// <summary> /// Defines a prioritized taxonomy of tags /// </summary> /// <remarks> /// The types are enumerated in ascending levels of risk for use in filtering HTML input /// </remarks> [Flags] public enum HtmlTaxonomy { /// <summary> /// Literal text, no tags /// </summary> Text = 0x0000, /// <summary> /// Inline character level elements and text strings /// </summary> /// <remarks> /// Tags of this type typically do not disrupt the text flow /// </remarks> Inline = 0x0001, /// <summary> /// style elements /// </summary> /// <remarks> /// Tags of this type change the visual appearance of text /// </remarks> Style = 0x0002, /// <summary> /// list elements /// </summary> /// <remarks> /// Tags of this type denote lists and typically change the text flow /// </remarks> List = 0x0004, /// <summary> /// Block-level elements /// </summary> /// <remarks> /// Tags of this type denote sections or change the text flow /// </remarks> Block = 0x0008, /// <summary> /// Media elements /// </summary> /// <remarks> /// Tags of this type safely embed media content /// </remarks> Media = 0x0010, /// <summary> /// Tabular elements /// </summary> /// <remarks> /// Tags of this type have a very specific structure and their own rendering model /// </remarks> Table = 0x0020, /// <summary> /// Form elements /// </summary> /// <remarks> /// Tags of this type are used in the construction of forms for capturing user input /// </remarks> Form = 0x0040, /// <summary> /// Script elements /// </summary> /// <remarks> /// Tags of this type represent a security risk to the containing document but must obey the browser security sandbox /// </remarks> Script = 0x0080, /// <summary> /// Document elements /// </summary> /// <remarks> /// Tags of this type are used to construct the document itself /// </remarks> Document = 0x0100, /// <summary> /// embedded elements /// </summary> /// <remarks> /// Tags of this type represent a large security risk to the containing document as plug-ins may circumvent the browser security sandbox /// </remarks> Plugin = 0x0200, /// <summary> /// Unknown elements /// </summary> Unknown = 0x8000 } }
jsonfx/jsonfx
src/JsonFx/Html/HtmlTaxonomy.cs
C#
mit
3,849
<a href='https://github.com/angular/angular.js/edit/v1.2.x/src/ngMock/angular-mocks.js?message=docs($log)%3A%20describe%20your%20change...#L277' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit">&nbsp;</i>Improve this Doc</a> <a href='https://github.com/angular/angular.js/tree/v1.2.27/src/ngMock/angular-mocks.js#L277' class='view-source pull-right btn btn-primary'> <i class="glyphicon glyphicon-zoom-in">&nbsp;</i>View Source </a> <header class="api-profile-header"> <h1 class="api-profile-header-heading">$log</h1> <ol class="api-profile-header-structure naked-list step-list"> <li> - service in module <a href="api/ngMock">ngMock</a> </li> </ol> </header> <div class="api-profile-description"> <p>Mock implementation of <a href="api/ng/service/$log"><code>$log</code></a> that gathers all logged messages in arrays (one array per logging level). These arrays are exposed as <code>logs</code> property of each of the level-specific log function, e.g. for level <code>error</code> the array is exposed as <code>$log.error.logs</code>.</p> </div> <div> <h2>Methods</h2> <ul class="methods"> <li id="reset"> <h3><p><code>reset();</code></p> </h3> <div><p>Reset all of the logging arrays to empty.</p> </div> </li> <li id="assertEmpty"> <h3><p><code>assertEmpty();</code></p> </h3> <div><p>Assert that the all of the logging methods have no logged messages. If messages present, an exception is thrown.</p> </div> </li> </ul> <h2>Properties</h2> <ul class="properties"> <li id="log.logs"> <h3><code>log.logs</code></h3> <table class="variables-matrix return-arguments"> <tr> <td></td> <td><p>Array of messages logged using <a href="api/ngMock/service/$log#log"><code>$log</code></a>.</p> </td> </tr> </table> </li> <li id="info.logs"> <h3><code>info.logs</code></h3> <table class="variables-matrix return-arguments"> <tr> <td></td> <td><p>Array of messages logged using <a href="api/ngMock/service/$log#info"><code>$log</code></a>.</p> </td> </tr> </table> </li> <li id="warn.logs"> <h3><code>warn.logs</code></h3> <table class="variables-matrix return-arguments"> <tr> <td></td> <td><p>Array of messages logged using <a href="api/ngMock/service/$log#warn"><code>$log</code></a>.</p> </td> </tr> </table> </li> <li id="error.logs"> <h3><code>error.logs</code></h3> <table class="variables-matrix return-arguments"> <tr> <td></td> <td><p>Array of messages logged using <a href="api/ngMock/service/$log#error"><code>$log</code></a>.</p> </td> </tr> </table> </li> <li id="debug.logs"> <h3><code>debug.logs</code></h3> <table class="variables-matrix return-arguments"> <tr> <td></td> <td><p>Array of messages logged using <a href="api/ngMock/service/$log#debug"><code>$log</code></a>.</p> </td> </tr> </table> </li> </ul> </div>
viral810/ngSimpleCMS
web/bundles/sunraangular/js/angular/angular-1.2.27/docs/partials/api/ngMock/service/$log.html
HTML
mit
3,037
registerTest ('Has a UTF-8 meta tag', function () { this .test('Do we have a UTF8 meta tag?', function($) { var sourceCode = this.page.source.toLowerCase(); // do we have an utf8 metatag ? notEqual(sourceCode.indexOf('<meta charset="utf-8">'),-1,'Has UTF-8 meta tag'); }); });
tunong/monkeytestjs
tests/tests/global/has_utf8_metatag.js
JavaScript
mit
313
<?php namespace Chamilo\Core\User; use Chamilo\Core\User\Storage\DataClass\User; /** * Helper object to prevent constructing a complete user object from the database when only an id is used in the end; * use with care. */ class UserIDWrapper extends User { private $wrapper_id; public function __construct($id) { // no need for calling the parent constructor // parent :: __construct(); $this->wrapper_id = $id; } public function get_id() { return $this->wrapper_id; } }
forelo/cosnics
src/Chamilo/Core/User/UserIDWrapper.php
PHP
mit
538
--- title: Docs - Using Yeoman layout: docs tags: ['docs', 'build'] --- # Using Yeoman #### > Complete [Yeoman](http://yeoman.io) generator for [Durandal](http://durandaljs.com/) with subgenerators. ### Install Yeoman This generator needs Yeoman to be installed. ``` $ npm install -g yo ``` ### Install Generator To install generator-durandal from npm, run: ``` $ npm install -g generator-durandal ``` Then, initiate the generator: ``` $ yo durandal ``` Your new application is ready. Start development using a little HTTP server and live reload: ``` $ grunt serve ``` ### Getting To Know Yeoman Yeoman has a heart of gold. He's a person with feelings and opinions, but he's very easy to work with. If you think he's too opinionated, he can be easily convinced. If you'd like to get to know Yeoman better and meet some of his friends, [Grunt](http://gruntjs.com) and [Bower](http://bower.io), check out the complete [Getting Started Guide](https://github.com/yeoman/yeoman/wiki/Getting-Started). ### Development Some build configurations are already defined using [Grunt](http://gruntjs.com). #### build Use build configuration to build your application to production. This concatenates and minifies your javascript, css and html and reduces your images' size. ``` $ grunt build ``` #### test Use the test configuration to test your application before building. This tests your application using [jasmine](http://pivotal.github.io/jasmine/) and [phantomjs](http://phantomjs.org/). ``` $ grunt test ``` #### serve Use the serve configuration to develop your application and test it in a browser. This hosts your application in a mini HTTP server with live reloading of your assets. ``` $ grunt serve ``` #### default Use the default configuration to build and test your application. This lints, builds and tests your application. ``` $ grunt ``` ### Sub Generators #### ViewModel You can create a viewmodel using a yeoman subgenerator. It allows you to create a viewmodel, its view and append it to the router. ``` $ yo durandal:viewmodel ```
Craga89/Durandal
docs/2.x/Yeoman.html.md
Markdown
mit
2,075
/* * 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. */ * { -webkit-tap-highlight-color: rgba(0,0,0,0); /* make transparent link selection, adjust last value opacity 0 to 1.0 */ } body { -webkit-touch-callout: none; /* prevent callout to copy image, etc when tap to hold */ -webkit-text-size-adjust: none; /* prevent webkit from resizing text to fit */ -webkit-user-select: none; /* prevent copy paste, to allow, change 'none' to 'text' */ background-color:#E4E4E4; background-image:linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%); background-image:-webkit-linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%); background-image:-ms-linear-gradient(top, #A7A7A7 0%, #E4E4E4 51%); background-image:-webkit-gradient( linear, left top, left bottom, color-stop(0, #A7A7A7), color-stop(0.51, #E4E4E4) ); background-attachment:fixed; font-family:'HelveticaNeue-Light', 'HelveticaNeue', Helvetica, Arial, sans-serif; font-size:12px; height:100%; margin:0px; padding:0px; text-transform:uppercase; width:100%; } /* Portrait layout (default) */ .app { background:url(../img/logo.png) no-repeat center top; /* 170px x 200px */ position:absolute; /* position in the center of the screen */ left:50%; top:50%; height:50px; /* text area height */ width:225px; /* text area width */ text-align:center; padding:180px 0px 0px 0px; /* image height is 200px (bottom 20px are overlapped with text) */ margin:-115px 0px 0px -112px; /* offset vertical: half of image height and text area height */ /* offset horizontal: half of text area width */ } /* Landscape layout (with min-width) */ @media screen and (min-aspect-ratio: 1/1) and (min-width:400px) { .app { background-position:left center; padding:75px 0px 75px 170px; /* padding-top + padding-bottom + text area = image height */ margin:-90px 0px 0px -198px; /* offset vertical: half of image height */ /* offset horizontal: half of image width and text area width */ } } h1 { font-size:24px; font-weight:normal; margin:0px; overflow:visible; padding:0px; text-align:center; } .event { border-radius:4px; -webkit-border-radius:4px; color:#FFFFFF; font-size:12px; margin:0px 30px; padding:2px 0px; } .event.listening { background-color:#333333; display:block; } .event.received { background-color:#4B946A; display:none; } @keyframes fade { from { opacity: 1.0; } 50% { opacity: 0.4; } to { opacity: 1.0; } } @-webkit-keyframes fade { from { opacity: 1.0; } 50% { opacity: 0.4; } to { opacity: 1.0; } } .blink { animation:fade 3000ms infinite; -webkit-animation:fade 3000ms infinite; }
Prygan/IMTA-cordova
www/css/index.css
CSS
mit
3,718
angular.module('ngCordova.plugins.deviceOrientation', []) .factory('$cordovaDeviceOrientation', ['$q', function($q) { return { getCurrentHeading: function() { var q = $q.defer(); navigator.compass.getCurrentHeading(function(heading) { q.resolve(heading); }, function(err) { q.reject(err); }); return q.promise; }, watchHeading: function(options) { var q = $q.defer(); var watchId = navigator.compass.watchHeading(function(result) { q.notify(result); }, function(err) { q.reject(err); }, options); return { watchId: watchId, promise: q.promise } }, clearWatch: function(watchID) { navigator.compass.clearWatch(); } } }]);
Prasanthmv/ngCordova
src/plugins/deviceOrientation.js
JavaScript
mit
775
# Azure Container Instances ![Azure Public Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/201-aci-linuxcontainer-volume-secret/PublicLastTestDate.svg) ![Azure Public Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/201-aci-linuxcontainer-volume-secret/PublicDeployment.svg) ![Azure US Gov Last Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/201-aci-linuxcontainer-volume-secret/FairfaxLastTestDate.svg) ![Azure US Gov Last Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/201-aci-linuxcontainer-volume-secret/FairfaxDeployment.svg) ![Best Practice Check](https://azurequickstartsservice.blob.core.windows.net/badges/201-aci-linuxcontainer-volume-secret/BestPracticeResult.svg) ![Cred Scan Check](https://azurequickstartsservice.blob.core.windows.net/badges/201-aci-linuxcontainer-volume-secret/CredScanResult.svg) [![Deploy To Azure](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazure.svg?sanitize=true)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2F201-aci-linuxcontainer-volume-secret%2Fazuredeploy.json) [![Visualize](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/visualizebutton.svg?sanitize=true)](http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2F201-aci-linuxcontainer-volume-secret%2Fazuredeploy.json) This template demonstrates a simple use case for secret volumes of [Azure Container Instances](https://docs.microsoft.com/en-us/azure/container-instances/). When creating a container with the image containerinstance/helloworld:ssl, it sets up HTTP connections with the certificate and password passed in as secret volumes. A PFX certificate is encoded in Base64 and mounted as a secret volume. Inside the container the certificate is accessible as a file with path /mnt/secrets/sslcertificateData. The password of the PFX certificate is also encoded in Base64, and mounted as a secret volume. Inside the container the certificate is accessible as a file with path /mnt/secrets/sslcertificatePwd. The parameters sslcertificateData and sslcertificatePwd are only for demo purpose. Please create your own certificate when creating container groups.
simongdavies/azure-quickstart-templates
201-aci-linuxcontainer-volume-secret/README.md
Markdown
mit
2,450
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Behat\Context\Api\Admin; use Behat\Behat\Context\Context; use Sylius\Behat\Client\ApiClientInterface; use Sylius\Behat\Client\ResponseCheckerInterface; use Sylius\Component\Shipping\Model\ShippingCategoryInterface; use Webmozart\Assert\Assert; final class ManagingShippingCategoriesContext implements Context { /** @var ApiClientInterface */ private $client; /** @var ResponseCheckerInterface */ private $responseChecker; public function __construct(ApiClientInterface $client, ResponseCheckerInterface $responseChecker) { $this->client = $client; $this->responseChecker = $responseChecker; } /** * @When I want to create a new shipping category */ public function iWantToCreateANewShippingCategory(): void { $this->client->buildCreateRequest(); } /** * @When I want to modify a shipping category :shippingCategory */ public function iWantToModifyAShippingCategory(ShippingCategoryInterface $shippingCategory): void { $this->client->buildUpdateRequest($shippingCategory->getCode()); } /** * @When I (try to) add it */ public function iAddIt(): void { $this->client->create(); } /** * @When I delete shipping category :shippingCategory */ public function iDeleteShippingCategory(ShippingCategoryInterface $shippingCategory): void { $this->client->delete($shippingCategory->getCode()); } /** * @When I browse shipping categories */ public function iBrowseShippingCategories(): void { $this->client->index(); } /** * @When I do not specify its code * @When I specify its code as :code */ public function iSpecifyItsCodeAs(?string $code = null): void { if ($code !== null) { $this->client->addRequestData('code', $code); } } /** * @When I name it :name * @When I do not specify its name * @When I rename it to :name */ public function iNameIt(?string $name = null): void { if ($name !== null) { $this->client->addRequestData('name', $name); } } /** * @When I modify a shipping category :shippingCategory */ public function iModifyAShippingCategory(ShippingCategoryInterface $shippingCategory): void { $this->client->buildUpdateRequest($shippingCategory->getCode()); } /** * @When I specify its description as :description */ public function iSpecifyItsDescriptionAs(string $description): void { $this->client->addRequestData('description', $description); } /** * @When I save my changes */ public function iSaveMyChanges(): void { $this->client->update(); } /** * @Then I should be notified that shipping category with this code already exists */ public function iShouldBeNotifiedThatShippingCategoryWithThisCodeAlreadyExists(): void { Assert::same( $this->responseChecker->getError($this->client->getLastResponse()), 'code: The shipping category with given code already exists.' ); } /** * @Then I should be notified that :element is required */ public function iShouldBeNotifiedThatElementIsRequired(string $element): void { Assert::same( $this->responseChecker->getError($this->client->getLastResponse()), sprintf('%s: Please enter shipping category %s.', $element, $element) ); } /** * @Then I should see a single shipping category in the list * @Then I should see :count shipping categories in the list */ public function iShouldSeeShippingCategoriesInTheList(int $count = 1): void { Assert::same($this->responseChecker->countCollectionItems($this->client->index()), $count); } /** * @Then the shipping category :shippingMethodName should be in the registry * @Then the shipping category :shippingMethodName should appear in the registry */ public function theShippingCategoryShouldAppearInTheRegistry(string $shippingCategoryName): void { Assert::true( $this->isItemOnIndex('name', $shippingCategoryName), sprintf('Shipping category with name %s does not exists', $shippingCategoryName) ); } /** * @Then shipping category with name :name should not be added */ public function shippingCategoryWithNameShouldNotBeAdded(string $name): void { Assert::false( $this->isItemOnIndex('name', $name), sprintf('Shipping category with name %s exists', $name) ); } /** * @Then /^(this shipping category) should no longer exist in the registry$/ */ public function thisShippingCategoryShouldNoLongerExistInTheRegistry( ShippingCategoryInterface $shippingCategory ): void { $shippingCategoryName = $shippingCategory->getName(); Assert::false( $this->isItemOnIndex('name', $shippingCategoryName), sprintf('Shipping category with name %s exist', $shippingCategoryName) ); } /** * @Then I should not be able to edit its code */ public function iShouldNotBeAbleToEditItsCode(): void { $this->client->addRequestData('code', 'NEW_CODE'); Assert::false( $this->responseChecker->hasValue($this->client->update(), 'code', 'NEW_CODE'), 'The shipping category code should not be changed to "NEW_CODE", but it is' ); } /** * @Then there should still be only one shipping category with code :code */ public function thereShouldStillBeOnlyOneShippingCategoryWith(string $code): void { Assert::same( count($this->responseChecker->getCollectionItemsWithValue($this->client->index(), 'code', $code)), 1 ); } /** * @Then this shipping category name should be :name */ public function thisShippingCategoryNameShouldBe(string $name): void { Assert::true( $this->responseChecker->hasValue($this->client->getLastResponse(), 'name', $name), sprintf('Shipping category with name %s does not exists', $name) ); } /** * @Then I should be notified that it has been successfully created */ public function iShouldBeNotifiedThatItHasBeenSuccessfullyCreated(): void { Assert::true( $this->responseChecker->isCreationSuccessful($this->client->getLastResponse()), 'Shipping category could not be created' ); } /** * @Then I should be notified that it has been successfully edited */ public function iShouldBeNotifiedThatItHasBeenSuccessfullyEdited(): void { Assert::true( $this->responseChecker->isUpdateSuccessful($this->client->getLastResponse()), 'Shipping category could not be edited' ); } /** * @Then I should be notified that it has been successfully deleted */ public function iShouldBeNotifiedThatItHasBeenSuccessfullyDeleted(): void { Assert::true( $this->responseChecker->isDeletionSuccessful($this->client->getLastResponse()), 'Shipping category could not be deleted' ); } private function isItemOnIndex(string $property, string $value): bool { $this->client->index(); return $this->responseChecker->hasItemWithValue($this->client->getLastResponse(), $property, $value); } }
GSadee/Sylius
src/Sylius/Behat/Context/Api/Admin/ManagingShippingCategoriesContext.php
PHP
mit
7,896
# Copyright (c) 2012-2013 Paul Tagliamonte <paultag@debian.org> # Copyright (c) 2013 Leo Cavaille <leo@cavaille.net> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from debile.slave.wrappers.pep8 import parse_pep8 from debile.slave.utils import cd from debile.utils.commands import run_command def pep8(dsc, analysis): run_command(["dpkg-source", "-x", dsc, "source-pep8"]) with cd('source-pep8'): out, _, ret = run_command(['pep8', '.']) failed = ret != 0 for issue in parse_pep8(out.splitlines()): analysis.results.append(issue) return (analysis, out, failed, None, None) def version(): out, _, ret = run_command(['pep8', '--version']) if ret != 0: raise Exception("pep8 is not installed") return ('pep8', out.strip())
lucaskanashiro/debile
debile/slave/runners/pep8.py
Python
mit
1,811
/* * modified version of https://github.com/valor-software/prismjs-loader * * The MIT License (MIT) * * Copyright (c) 2015-2016 Valor Software * Copyright (c) 2015-2016 Dmitriy Shekhovtsov<valorkin@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ "use strict"; const Prism = require("prismjs"); module.exports = function loader(content) { const query = this.query; if (!query.lang) { throw new Error("You need to provide `lang` query parameter"); } if (!Prism.languages[query.lang]) { /* eslint-disable */ require(`prismjs/components/prism-${query.lang}.js`); /* eslint-enable */ } const lang = Prism.languages[query.lang]; const value = Prism.highlight(content, lang); const str = JSON.stringify(value); return `module.exports = ${str}`; }; module.exports.seperable = true;
rackt/react-router
website/webpack/prismjs-loader.js
JavaScript
mit
1,864
{% extends 'templates/nhs_transaction_layout.html' %} {% import 'includes/form_macros.html' as form_macros %} {% block afterHeader %} {% include "includes/service-headers/low-income.html" %} {% endblock %} {% block content %} <main id="content" role="main"> <div class="grid-row"> <div class="column-two-thirds"> <h1 class="heading-large"> Do you or your partner have any shares? </h1> <form action="" method="get" class="form"> <div class="form-item-wrapper"> <fieldset> <div class="inline-form-groups"> <div class="form-group"> <input type="radio" id="binary-yes" name="binary"> <label class="form-control-radio" for="binary-yes"> Yes </label> </div> <div class="form-group"> <input type="radio" id="binary-no" name="binary"> <label class="form-control-radio" for="binary-no"> No </label> </div> </div> </fieldset> </div> {{ form_macros.button({ href: 'certificates', label: 'Save and continue' }) }} <p class="navigation"><a class="cancel" href="../lis-home">Save and come back later</a></p> </form> </div> </div> </main> {% endblock %}
nhsbsa/nhslis
app/views/lis/7/assets/shares.html
HTML
mit
1,466
#!/bin/bash set -e set -x sudo yum -y install https://download.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm sudo sed -i -e 's/^enabled=1/enabled=0/' /etc/yum.repos.d/epel.repo
matsumana/packer-templates-2
scripts/centos-7.1/repo.sh
Shell
mit
199
package com.reactnativenavigation.views.element.animators; import android.animation.Animator; import android.animation.ObjectAnimator; import android.widget.TextView; import com.facebook.react.views.text.ReactTextView; import com.reactnativenavigation.utils.TextViewUtils; import com.reactnativenavigation.views.element.Element; import static com.reactnativenavigation.utils.TextViewUtils.getTextSize; public class TextSizeAnimator extends PropertyAnimatorCreator<ReactTextView> { public TextSizeAnimator(Element from, Element to) { super(from, to); } @Override protected boolean shouldAnimateProperty(ReactTextView fromChild, ReactTextView toChild) { return getTextSize(fromChild) != getTextSize(toChild); } @Override public Animator create() { return ObjectAnimator.ofFloat( to, "textSize", TextViewUtils.getTextSize((TextView) from.getChild()), TextViewUtils.getTextSize((TextView) to.getChild()) ); } }
Jpoliachik/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/views/element/animators/TextSizeAnimator.java
Java
mit
1,042