text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::beforeunloadevent::BeforeUnloadEvent;
use dom::bindings::callback::{CallbackContainer, ExceptionHandling, CallbackFunction};
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventMethods;
use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::EventHandlerBinding::OnBeforeUnloadEventHandlerNonNull;
use dom::bindings::codegen::Bindings::EventHandlerBinding::OnErrorEventHandlerNonNull;
use dom::bindings::codegen::Bindings::EventListenerBinding::EventListener;
use dom::bindings::codegen::Bindings::EventTargetBinding::AddEventListenerOptions;
use dom::bindings::codegen::Bindings::EventTargetBinding::EventListenerOptions;
use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::UnionTypes::AddEventListenerOptionsOrBoolean;
use dom::bindings::codegen::UnionTypes::EventListenerOptionsOrBoolean;
use dom::bindings::codegen::UnionTypes::EventOrString;
use dom::bindings::error::{Error, Fallible, report_pending_exception};
use dom::bindings::inheritance::Castable;
use dom::bindings::reflector::{DomObject, Reflector};
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString;
use dom::element::Element;
use dom::errorevent::ErrorEvent;
use dom::event::{Event, EventBubbles, EventCancelable, EventStatus};
use dom::node::document_from_node;
use dom::virtualmethods::VirtualMethods;
use dom::window::Window;
use dom_struct::dom_struct;
use fnv::FnvHasher;
use js::jsapi::{CompileFunction, JS_GetFunctionObject, JSAutoCompartment};
use js::rust::{AutoObjectVectorWrapper, CompileOptionsWrapper};
use libc::{c_char, size_t};
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::default::Default;
use std::ffi::CString;
use std::hash::BuildHasherDefault;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::ptr;
use std::rc::Rc;

#[derive(Clone, JSTraceable, MallocSizeOf, PartialEq)]
pub enum CommonEventHandler {
    EventHandler(
        #[ignore_malloc_size_of = "Rc"]
        Rc<EventHandlerNonNull>),

    ErrorEventHandler(
        #[ignore_malloc_size_of = "Rc"]
        Rc<OnErrorEventHandlerNonNull>),

    BeforeUnloadEventHandler(
        #[ignore_malloc_size_of = "Rc"]
        Rc<OnBeforeUnloadEventHandlerNonNull>),
}

impl CommonEventHandler {
    fn parent(&self) -> &CallbackFunction {
        match *self {
            CommonEventHandler::EventHandler(ref handler) => &handler.parent,
            CommonEventHandler::ErrorEventHandler(ref handler) => &handler.parent,
            CommonEventHandler::BeforeUnloadEventHandler(ref handler) => &handler.parent,
        }
    }
}

#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
pub enum ListenerPhase {
    Capturing,
    Bubbling,
}

/// <https://html.spec.whatwg.org/multipage/#internal-raw-uncompiled-handler>
#[derive(Clone, JSTraceable, MallocSizeOf, PartialEq)]
struct InternalRawUncompiledHandler {
    source: DOMString,
    url: ServoUrl,
    line: usize,
}

/// A representation of an event handler, either compiled or uncompiled raw source, or null.
#[derive(Clone, JSTraceable, MallocSizeOf, PartialEq)]
enum InlineEventListener {
    Uncompiled(InternalRawUncompiledHandler),
    Compiled(CommonEventHandler),
    Null,
}

impl InlineEventListener {
    /// Get a compiled representation of this event handler, compiling it from its
    /// raw source if necessary.
    /// <https://html.spec.whatwg.org/multipage/#getting-the-current-value-of-the-event-handler>
    fn get_compiled_handler(&mut self, owner: &EventTarget, ty: &Atom)
                            -> Option<CommonEventHandler> {
        match mem::replace(self, InlineEventListener::Null) {
            InlineEventListener::Null => None,
            InlineEventListener::Uncompiled(handler) => {
                let result = owner.get_compiled_event_handler(handler, ty);
                if let Some(ref compiled) = result {
                    *self = InlineEventListener::Compiled(compiled.clone());
                }
                result
            }
            InlineEventListener::Compiled(handler) => {
                *self = InlineEventListener::Compiled(handler.clone());
                Some(handler)
            }
        }
    }
}

#[derive(Clone, JSTraceable, MallocSizeOf, PartialEq)]
enum EventListenerType {
    Additive(#[ignore_malloc_size_of = "Rc"] Rc<EventListener>),
    Inline(InlineEventListener),
}

impl EventListenerType {
    fn get_compiled_listener(&mut self, owner: &EventTarget, ty: &Atom)
                             -> Option<CompiledEventListener> {
        match self {
            &mut EventListenerType::Inline(ref mut inline) =>
                inline.get_compiled_handler(owner, ty)
                      .map(CompiledEventListener::Handler),
            &mut EventListenerType::Additive(ref listener) =>
                Some(CompiledEventListener::Listener(listener.clone())),
        }
    }
}

/// A representation of an EventListener/EventHandler object that has previously
/// been compiled successfully, if applicable.
pub enum CompiledEventListener {
    Listener(Rc<EventListener>),
    Handler(CommonEventHandler),
}

impl CompiledEventListener {
    #[allow(unsafe_code)]
    // https://html.spec.whatwg.org/multipage/#the-event-handler-processing-algorithm
    pub fn call_or_handle_event<T: DomObject>(&self,
                                              object: &T,
                                              event: &Event,
                                              exception_handle: ExceptionHandling) {
        // Step 3
        match *self {
            CompiledEventListener::Listener(ref listener) => {
                let _ = listener.HandleEvent_(object, event, exception_handle);
            },
            CompiledEventListener::Handler(ref handler) => {
                match *handler {
                    CommonEventHandler::ErrorEventHandler(ref handler) => {
                        if let Some(event) = event.downcast::<ErrorEvent>() {
                            let cx = object.global().get_cx();
                            rooted!(in(cx) let error = unsafe { event.Error(cx) });
                            let return_value = handler.Call_(object,
                                                             EventOrString::String(event.Message()),
                                                             Some(event.Filename()),
                                                             Some(event.Lineno()),
                                                             Some(event.Colno()),
                                                             Some(error.handle()),
                                                             exception_handle);
                            // Step 4
                            if let Ok(return_value) = return_value {
                                rooted!(in(cx) let return_value = return_value);
                                if return_value.handle().is_boolean() && return_value.handle().to_boolean() == true {
                                    event.upcast::<Event>().PreventDefault();
                                }
                            }
                            return;
                        }

                        let _ = handler.Call_(object, EventOrString::Event(DomRoot::from_ref(event)),
                                              None, None, None, None, exception_handle);
                    }

                    CommonEventHandler::BeforeUnloadEventHandler(ref handler) => {
                        if let Some(event) = event.downcast::<BeforeUnloadEvent>() {
                            let rv = event.ReturnValue();

                            if let Ok(value) = handler.Call_(object,
                                                             event.upcast::<Event>(),
                                                             exception_handle) {
                                match value {
                                    Some(value) => {
                                        if rv.is_empty() {
                                            event.SetReturnValue(value);
                                        }
                                    }
                                    None => {
                                        event.upcast::<Event>().PreventDefault();
                                    }
                                }
                            }
                        }
                    }

                    CommonEventHandler::EventHandler(ref handler) => {
                        if let Ok(value) = handler.Call_(object, event, exception_handle) {
                            let cx = object.global().get_cx();
                            rooted!(in(cx) let value = value);
                            let value = value.handle();

                            //Step 4
                            let should_cancel = match event.type_() {
                                atom!("mouseover") => value.is_boolean() && value.to_boolean() == true,
                                _ => value.is_boolean() && value.to_boolean() == false
                            };
                            if should_cancel {
                                event.PreventDefault();
                            }
                        }
                    }
                }
            }
        }
    }
}

#[derive(Clone, DenyPublicFields, JSTraceable, MallocSizeOf, PartialEq)]
/// A listener in a collection of event listeners.
struct EventListenerEntry {
    phase: ListenerPhase,
    listener: EventListenerType
}

#[derive(JSTraceable, MallocSizeOf)]
/// A mix of potentially uncompiled and compiled event listeners of the same type.
struct EventListeners(Vec<EventListenerEntry>);

impl Deref for EventListeners {
    type Target = Vec<EventListenerEntry>;
    fn deref(&self) -> &Vec<EventListenerEntry> {
        &self.0
    }
}

impl DerefMut for EventListeners {
    fn deref_mut(&mut self) -> &mut Vec<EventListenerEntry> {
        &mut self.0
    }
}

impl EventListeners {
    // https://html.spec.whatwg.org/multipage/#getting-the-current-value-of-the-event-handler
    fn get_inline_listener(&mut self, owner: &EventTarget, ty: &Atom) -> Option<CommonEventHandler> {
        for entry in &mut self.0 {
            if let EventListenerType::Inline(ref mut inline) = entry.listener {
                // Step 1.1-1.8 and Step 2
                return inline.get_compiled_handler(owner, ty);
            }
        }

        // Step 2
        None
    }

    // https://html.spec.whatwg.org/multipage/#getting-the-current-value-of-the-event-handler
    fn get_listeners(&mut self, phase: Option<ListenerPhase>, owner: &EventTarget, ty: &Atom)
                     -> Vec<CompiledEventListener> {
        self.0.iter_mut().filter_map(|entry| {
            if phase.is_none() || Some(entry.phase) == phase {
                // Step 1.1-1.8, 2
                entry.listener.get_compiled_listener(owner, ty)
            } else {
                None
            }
        }).collect()
    }
}

#[dom_struct]
pub struct EventTarget {
    reflector_: Reflector,
    handlers: DomRefCell<HashMap<Atom, EventListeners, BuildHasherDefault<FnvHasher>>>,
}

impl EventTarget {
    pub fn new_inherited() -> EventTarget {
        EventTarget {
            reflector_: Reflector::new(),
            handlers: DomRefCell::new(Default::default()),
        }
    }

    pub fn get_listeners_for(&self,
                             type_: &Atom,
                             specific_phase: Option<ListenerPhase>)
                             -> Vec<CompiledEventListener> {
        self.handlers.borrow_mut().get_mut(type_).map_or(vec![], |listeners| {
            listeners.get_listeners(specific_phase, self, type_)
        })
    }

    pub fn dispatch_event_with_target(&self,
                                      target: &EventTarget,
                                      event: &Event) -> EventStatus {
        event.dispatch(self, Some(target))
    }

    pub fn dispatch_event(&self, event: &Event) -> EventStatus {
        event.dispatch(self, None)
    }

    pub fn remove_all_listeners(&self) {
        *self.handlers.borrow_mut() = Default::default();
    }

    /// <https://html.spec.whatwg.org/multipage/#event-handler-attributes:event-handlers-11>
    fn set_inline_event_listener(&self,
                                 ty: Atom,
                                 listener: Option<InlineEventListener>) {
        let mut handlers = self.handlers.borrow_mut();
        let entries = match handlers.entry(ty) {
            Occupied(entry) => entry.into_mut(),
            Vacant(entry) => entry.insert(EventListeners(vec!())),
        };

        let idx = entries.iter().position(|ref entry| {
            match entry.listener {
                EventListenerType::Inline(_) => true,
                _ => false,
            }
        });

        match idx {
            Some(idx) => {
                entries[idx].listener =
                    EventListenerType::Inline(listener.unwrap_or(InlineEventListener::Null));
            }
            None => {
                if let Some(listener) = listener {
                    entries.push(EventListenerEntry {
                        phase: ListenerPhase::Bubbling,
                        listener: EventListenerType::Inline(listener),
                    });
                }
            }
        }
    }

    fn get_inline_event_listener(&self, ty: &Atom) -> Option<CommonEventHandler> {
        let mut handlers = self.handlers.borrow_mut();
        handlers.get_mut(ty).and_then(|entry| entry.get_inline_listener(self, ty))
    }

    /// Store the raw uncompiled event handler for on-demand compilation later.
    /// <https://html.spec.whatwg.org/multipage/#event-handler-attributes:event-handler-content-attributes-3>
    pub fn set_event_handler_uncompiled(&self,
                                        url: ServoUrl,
                                        line: usize,
                                        ty: &str,
                                        source: DOMString) {
        let handler = InternalRawUncompiledHandler {
            source: source,
            line: line,
            url: url,
        };
        self.set_inline_event_listener(Atom::from(ty),
                                       Some(InlineEventListener::Uncompiled(handler)));
    }

    // https://html.spec.whatwg.org/multipage/#getting-the-current-value-of-the-event-handler
    #[allow(unsafe_code)]
    fn get_compiled_event_handler(&self,
                                  handler: InternalRawUncompiledHandler,
                                  ty: &Atom)
                                  -> Option<CommonEventHandler> {
        // Step 1.1
        let element = self.downcast::<Element>();
        let document = match element {
            Some(element) => document_from_node(element),
            None => self.downcast::<Window>().unwrap().Document(),
        };

        // Step 1.2
        if !document.is_scripting_enabled() {
            return None;
        }

        // Step 1.3
        let body: Vec<u16> = handler.source.encode_utf16().collect();

        // TODO step 1.5 (form owner)

        // Step 1.6
        let window = document.window();

        let url_serialized = CString::new(handler.url.to_string()).unwrap();
        let name = CString::new(&**ty).unwrap();

        static mut ARG_NAMES: [*const c_char; 1] = [b"event\0" as *const u8 as *const c_char];
        static mut ERROR_ARG_NAMES: [*const c_char; 5] = [b"event\0" as *const u8 as *const c_char,
                                                          b"source\0" as *const u8 as *const c_char,
                                                          b"lineno\0" as *const u8 as *const c_char,
                                                          b"colno\0" as *const u8 as *const c_char,
                                                          b"error\0" as *const u8 as *const c_char];
        // step 10
        let is_error = ty == &atom!("error") && self.is::<Window>();
        let args = unsafe {
            if is_error {
                &ERROR_ARG_NAMES[..]
            } else {
                &ARG_NAMES[..]
            }
        };

        let cx = window.get_cx();
        let options = CompileOptionsWrapper::new(cx, url_serialized.as_ptr(), handler.line as u32);
        // TODO step 1.10.1-3 (document, form owner, element in scope chain)

        let scopechain = AutoObjectVectorWrapper::new(cx);

        let _ac = JSAutoCompartment::new(cx, window.reflector().get_jsobject().get());
        rooted!(in(cx) let mut handler = ptr::null_mut());
        let rv = unsafe {
            CompileFunction(cx,
                            scopechain.ptr,
                            options.ptr,
                            name.as_ptr(),
                            args.len() as u32,
                            args.as_ptr(),
                            body.as_ptr(),
                            body.len() as size_t,
                            handler.handle_mut())
        };
        if !rv || handler.get().is_null() {
            // Step 1.8.2
            unsafe {
                let _ac = JSAutoCompartment::new(cx, self.reflector().get_jsobject().get());
                // FIXME(#13152): dispatch error event.
                report_pending_exception(cx, false);
            }
            // Step 1.8.1 / 1.8.3
            return None;
        }

        // TODO step 1.11-13
        let funobj = unsafe { JS_GetFunctionObject(handler.get()) };
        assert!(!funobj.is_null());
        // Step 1.14
        if is_error {
            Some(CommonEventHandler::ErrorEventHandler(OnErrorEventHandlerNonNull::new(cx, funobj)))
        } else {
            if ty == &atom!("beforeunload") {
                Some(CommonEventHandler::BeforeUnloadEventHandler(
                        OnBeforeUnloadEventHandlerNonNull::new(cx, funobj)))
            } else {
                Some(CommonEventHandler::EventHandler(EventHandlerNonNull::new(cx, funobj)))
            }
        }
    }

    pub fn set_event_handler_common<T: CallbackContainer>(
        &self, ty: &str, listener: Option<Rc<T>>)
    {
        let cx = self.global().get_cx();

        let event_listener = listener.map(|listener|
                                          InlineEventListener::Compiled(
                                              CommonEventHandler::EventHandler(
                                                  EventHandlerNonNull::new(cx, listener.callback()))));
        self.set_inline_event_listener(Atom::from(ty), event_listener);
    }

    pub fn set_error_event_handler<T: CallbackContainer>(
        &self, ty: &str, listener: Option<Rc<T>>)
    {
        let cx = self.global().get_cx();

        let event_listener = listener.map(|listener|
                                          InlineEventListener::Compiled(
                                              CommonEventHandler::ErrorEventHandler(
                                                  OnErrorEventHandlerNonNull::new(cx, listener.callback()))));
        self.set_inline_event_listener(Atom::from(ty), event_listener);
    }

    pub fn set_beforeunload_event_handler<T: CallbackContainer>(&self, ty: &str,
                                                                listener: Option<Rc<T>>) {
        let cx = self.global().get_cx();

        let event_listener = listener.map(|listener|
            InlineEventListener::Compiled(
                CommonEventHandler::BeforeUnloadEventHandler(
                    OnBeforeUnloadEventHandlerNonNull::new(cx, listener.callback())))
        );
        self.set_inline_event_listener(Atom::from(ty), event_listener);
    }

    #[allow(unsafe_code)]
    pub fn get_event_handler_common<T: CallbackContainer>(&self, ty: &str) -> Option<Rc<T>> {
        let cx = self.global().get_cx();
        let listener = self.get_inline_event_listener(&Atom::from(ty));
        unsafe {
            listener.map(|listener|
                         CallbackContainer::new(cx, listener.parent().callback_holder().get()))
        }
    }

    pub fn has_handlers(&self) -> bool {
        !self.handlers.borrow().is_empty()
    }

    // https://dom.spec.whatwg.org/#concept-event-fire
    pub fn fire_event(&self, name: Atom) -> DomRoot<Event> {
        self.fire_event_with_params(name,
                                    EventBubbles::DoesNotBubble,
                                    EventCancelable::NotCancelable)
    }

    // https://dom.spec.whatwg.org/#concept-event-fire
    pub fn fire_bubbling_event(&self, name: Atom) -> DomRoot<Event> {
        self.fire_event_with_params(name,
                                    EventBubbles::Bubbles,
                                    EventCancelable::NotCancelable)
    }

    // https://dom.spec.whatwg.org/#concept-event-fire
    pub fn fire_cancelable_event(&self, name: Atom) -> DomRoot<Event> {
        self.fire_event_with_params(name,
                                    EventBubbles::DoesNotBubble,
                                    EventCancelable::Cancelable)
    }

    // https://dom.spec.whatwg.org/#concept-event-fire
    pub fn fire_bubbling_cancelable_event(&self, name: Atom) -> DomRoot<Event> {
        self.fire_event_with_params(name,
                                    EventBubbles::Bubbles,
                                    EventCancelable::Cancelable)
    }

    // https://dom.spec.whatwg.org/#concept-event-fire
    pub fn fire_event_with_params(&self,
                                  name: Atom,
                                  bubbles: EventBubbles,
                                  cancelable: EventCancelable)
                                  -> DomRoot<Event> {
        let event = Event::new(&self.global(), name, bubbles, cancelable);
        event.fire(self);
        event
    }
    // https://dom.spec.whatwg.org/#dom-eventtarget-addeventlistener
    pub fn add_event_listener(
        &self,
        ty: DOMString,
        listener: Option<Rc<EventListener>>,
        options: AddEventListenerOptions,
    ) {
        let listener = match listener {
            Some(l) => l,
            None => return,
        };
        let mut handlers = self.handlers.borrow_mut();
        let entry = match handlers.entry(Atom::from(ty)) {
            Occupied(entry) => entry.into_mut(),
            Vacant(entry) => entry.insert(EventListeners(vec!())),
        };

        let phase = if options.parent.capture {
            ListenerPhase::Capturing
        } else {
            ListenerPhase::Bubbling
        };
        let new_entry = EventListenerEntry {
            phase: phase,
            listener: EventListenerType::Additive(listener)
        };
        if !entry.contains(&new_entry) {
            entry.push(new_entry);
        }
    }

    // https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener
    pub fn remove_event_listener(
        &self,
        ty: DOMString,
        listener: Option<Rc<EventListener>>,
        options: EventListenerOptions,
    ) {
        let ref listener = match listener {
            Some(l) => l,
            None => return,
        };
        let mut handlers = self.handlers.borrow_mut();
        let entry = handlers.get_mut(&Atom::from(ty));
        for entry in entry {
            let phase = if options.capture {
                ListenerPhase::Capturing
            } else {
                ListenerPhase::Bubbling
            };
            let old_entry = EventListenerEntry {
                phase: phase,
                listener: EventListenerType::Additive(listener.clone())
            };
            if let Some(position) = entry.iter().position(|e| *e == old_entry) {
                entry.remove(position);
            }
        }
    }
}

impl EventTargetMethods for EventTarget {
    // https://dom.spec.whatwg.org/#dom-eventtarget-addeventlistener
    fn AddEventListener(
        &self,
        ty: DOMString,
        listener: Option<Rc<EventListener>>,
        options: AddEventListenerOptionsOrBoolean,
    ) {
        self.add_event_listener(ty, listener, options.into())
    }

    // https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener
    fn RemoveEventListener(
        &self,
        ty: DOMString,
        listener: Option<Rc<EventListener>>,
        options: EventListenerOptionsOrBoolean,
    ) {
        self.remove_event_listener(ty, listener, options.into())
    }

    // https://dom.spec.whatwg.org/#dom-eventtarget-dispatchevent
    fn DispatchEvent(&self, event: &Event) -> Fallible<bool> {
        if event.dispatching() || !event.initialized() {
            return Err(Error::InvalidState);
        }
        event.set_trusted(false);
        Ok(match self.dispatch_event(event) {
            EventStatus::Canceled => false,
            EventStatus::NotCanceled => true
        })
    }
}

impl VirtualMethods for EventTarget {
    fn super_type(&self) -> Option<&VirtualMethods> {
        None
    }
}

impl From<AddEventListenerOptionsOrBoolean> for AddEventListenerOptions {
    fn from(options: AddEventListenerOptionsOrBoolean) -> Self {
        match options {
            AddEventListenerOptionsOrBoolean::AddEventListenerOptions(options) => {
                options
            },
            AddEventListenerOptionsOrBoolean::Boolean(capture) => {
                Self { parent: EventListenerOptions { capture } }
            },
        }
    }
}

impl From<EventListenerOptionsOrBoolean> for EventListenerOptions {
    fn from(options: EventListenerOptionsOrBoolean) -> Self {
        match options {
            EventListenerOptionsOrBoolean::EventListenerOptions(options) => {
                options
            },
            EventListenerOptionsOrBoolean::Boolean(capture) => {
                Self { capture }
            },
        }
    }
}


text:
<?php
/**
 * @package rules
 * @author  Leigh MacDonald <leigh.macdonald@gmail.com>
 */
namespace RBAC\Exception;

class InsufficientPermission extends ValidationError
{
}

redpajama_set_name: RedPajamaGithub


text:
var BasemapCategoriesView = require('../../../../../../javascripts/cartodb3/editor/layers/basemap-content-views/basemap-categories-view');
var CarouselCollection = require('../../../../../../javascripts/cartodb3/components/custom-carousel/custom-carousel-collection');

describe('editor/layers/basemap-content-views/basemap-categories-view', function () {
  beforeEach(function () {
    this.collection = new CarouselCollection([{
      selected: true,
      val: 'CARTO',
      label: 'CARTO',
      template: function () {
        return 'CARTO';
      }
    }, {
      selected: false,
      val: 'Here',
      label: 'Here',
      template: function () {
        return 'Here';
      }
    }, {
      selected: false,
      val: 'Stamen',
      label: 'Stamen',
      template: function () {
        return 'Stamen';
      }
    }, {
      selected: false,
      val: 'Custom',
      label: 'Custom',
      template: function () {
        return 'Custom';
      }
    }, {
      selected: false,
      val: 'Color',
      label: 'Color',
      template: function () {
        return 'Color';
      }
    }]);

    this.view = new BasemapCategoriesView({
      categoriesCollection: this.collection
    });

    this.view.render();
  });

  it('should render properly', function () {
    expect(this.view.$('.Carousel-item').length).toBe(5);
  });

  it('should have no leaks', function () {
    expect(this.view).toHaveNoLeaks();
  });
});


text:
iBeaconService
==============

a basic beacon service that can be used to easily add beacon support to any app + demo


text:
<?php

namespace GeneratorNameSpace\Http\Controllers\Admin;

use Illuminate\Http\Request;
use GeneratorModelNameSpace\GeneratorNameModel;
use GeneratorNameSpace\Http\Requests\Admin\GeneratorNameRequest;
use GeneratorNameSpace\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
// {headgenerator}
class GeneratorNameController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $search = \Request::input('search');
        if(isset($search['text'])){
            Session::put('GeneratorName.search.text', $search['text']);
            return redirect()->action('Admin\GeneratorNameController@index');
        }

        $search_value = Session::get('GeneratorName.search.text', '');
        $data = GeneratorNameModel::search($search_value)->paginate(30);
        $data->setPath(''); // set default path to pagination

        return view('{list_view}', ['data' => $data, 'search_value' => $search_value]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        $item = new GeneratorNameModel();
        // {editor}
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(GeneratorNameRequest $request)
    {
        $data = $request->get('data');

        // Data strone
        $db_data = array();
        if(is_array($data)){
            foreach($data as $key => $value){
                $db_data[$key] = $value;
            }
        }
        // {files}
        $object = new GeneratorNameModel($db_data);
        $object->save();

        return redirect()->action('Admin\GeneratorNameController@index')->with('message', trans('panel.item.saved'));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        $item = GeneratorNameModel::find($id);
        $validator = \Validator::make(['check'=>$item],['check'=>'required'],['required'=>trans('panel.item.not_found')]);
        if($validator->fails()){
            return redirect()->action('Admin\GeneratorNameController@index')->withErrors($validator);
        }

        return $item;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        $item = GeneratorNameModel::find($id);
        $validator = \Validator::make(['check'=>$item],['check'=>'required'],['required'=>trans('panel.item.not_found')]);
        if($validator->fails()){
            return redirect()->action('Admin\GeneratorNameController@index')->withErrors($validator);
        }
        // {editor}
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(GeneratorNameRequest $request, $id)
    {
        $item = GeneratorNameModel::find($id);
        $validator = \Validator::make(['check'=>$item],['check'=>'required'],['required'=>trans('panel.item.not_found')]);
        if($validator->fails()){
            return redirect()->action('Admin\GeneratorNameController@index')->withErrors($validator);
        }

        $data = $request->get('data');

        $db_data = array();
        if(is_array($data)){
            foreach($data as $key => $value){
                $db_data[$key] = $value;
            }
        }
        // {files}
        $item->update($db_data);

        return redirect()->action('Admin\GeneratorNameController@index')->with('message', trans('panel.item.saved'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        $item = GeneratorNameModel::find($id);
        $validator = \Validator::make(['check'=>$item],['check'=>'required'],['required'=>trans('panel.item.not_found')]);
        if($validator->fails()){
            return redirect()->action('Admin\GeneratorNameController@index')->withErrors($validator);
        }
        else{
            $item->delete();
            return redirect()->action('Admin\GeneratorNameController@index')->with('message', trans('panel.item.removed'));
        }
    }
}


text:
#pragma once
#include "CCommManager.h"
#include "AvaraTCP.h"

#define	TCPSTREAMBUFFERSIZE	8192

class	CTCPConnection;
class	CTCPComm;

class	CTCPConnection : public CCommManager
{
public:
			TCPiopb			param;
			CTCPConnection	*next;
			CTCPComm		*itsOwner;
			TCPNotifyUPP	notify;

			StreamPtr		stream;
			char			streamBuffer[TCPSTREAMBUFFERSIZE];

			ip_addr			remoteAddr;
			short			remotePort;

			Boolean			isListening;
			Boolean			isClosing;

			TCPIOCompletionUPP		readCompletionProc;
			TCPIOCompletionUPP		writeCompletionProc;
			TCPIOCompletionUPP		passiveCompletionProc;

	virtual	void			ITCPConnection(CTCPComm *theOwner);
	virtual	void			Dispose();

	virtual	OSErr			ContactServer(ip_addr addr, short port, StringPtr password);

	virtual	OSErr			PassiveOpenAll(short localPort);
	virtual	void			Notify(ushort code, ushort termReason);

	virtual	void			ReadComplete(TCPiopbPtr pb);
	virtual	void			WriteComplete(TCPiopbPtr pb);
	virtual	void			PassiveComplete(TCPiopbPtr pb);

	virtual	PacketInfo		*GetPacket();
	virtual	void			ReleasePacket(PacketInfo *thePacket);
	virtual	void			DispatchPacket(PacketInfo *thePacket);
};


text:
title: "An Introduction to Programming"
slug: "an-introduction-to-programming"
blurb: "If you know nothing about programming, this is where to start!"
categories:
  - hackety
  - beginner
---

## Hello there!

### Round One

So, you'd like to learn how to hack code with the best of 'em, eh? Well, you've
come to the right place. This is the very first lesson I have to share with you.
It all starts here.

I want to get you started off on the best possible foot with making programs, so
we'll start off by talking a little bit about what programming is, and then
we'll write some basic programs to draw fun things on the screen. Sound good?
Off we go!

## Let's talk about programming

### It's all about instructions

When you get down to it, programming is all about __algorithms__. That's a big
fancy word for 'a list of instructions.' Every program is simply a big to-do
list of instructions for the computer to follow.

You can turn almost anything into a list of instructions if you really think
about it. Most of the time, you've got so much practice at doing things that you
don't even think about these individual steps. You just do them. It's very
natural.

### The computer is simple

Unfortunately, computers are actually quite simple. This may be contrary to
everything you've ever heard, but it's the truth. Even though we compare
computers to things like our brains, it's a really poor analogy. What computers
are actually really good at is performing simple, boring things over and over
again very accurately. They can't think for themselves!

This is why computers appear to be complex. They blindly follow whatever orders
they're given, without any thought about how those instructions are good or bad.
It's hard to think in such simple terms!

### Explain yourself well

It's important to remember that you have to fully explain yourself to the
computer when you're programming. It can't figure out what you're trying to say,
so you have to say what you mean!

This takes some practice, so we're going to start off with some exercises in
explaining ourselves in very basic terms. It's almost like trying to explain
math to a young child: you have to go slowly, triple check your work, and have
some patience when it just doesn't quite get it.

## Lists of Instructions

### A to-do list, not a shopping list

When I say that computers follow lists of instructions, I mean a to-do list, not
a shopping list. What I'm trying to say is that these lists have an __order__ to
them that the computer follows. It does each step in turn as quickly as it
possibly can.

A shopping list is a different kind of list entirely. You can go to whichever
aisle you choose, and as long as you get everything before you leave, you're
A-OK. This isn't what the computer does at all.

### How would you tell a person to do it?

Let's try an example: if you had to tell someone in words how to draw a square
on a piece of paper, how would you do it?

You're not allowed to say "like this" or "this way," that's cheating! You have
to spell out every detail.

### Once again: computers are simple

How'd you do? I can't see what you said, but here's an example of how simple
computers are compared to people. Did you forget to mention how long each side
of the square is? If you didn't good job!

Here's how I'd do it, by the way. This isn't the only right answer, it's just an
example:

1. Put your pen down on the paper.
2. Draw right one inch.
3. Draw down one inch.
4. Draw left one inch.
5. Draw up one inch.
6. Take your pen off of the paper.
7. Finished!

## Turtles, all the way down.

### Drawing... with turtles?

Okay! Enough of these thinking experiments. Let's actually make something. I bet
you've been wondering when that was going to start, right? It's really important
to get the basics down first.

We're going to tell the computer how to draw shapes... with turtles. Yes, you
heard me right. You're going to have to give these instructions to a turtle.

This particular turtle is carrying a pen. You have a piece of paper. The turtle
will follow your every word. But the turtle is a bit slow, and needs careful
instruction. Are you up to it?

### The Turtle and its commands

We have to tell Hackety Hack that we want to tell the Turtle what to do. To do
that, we have a `Turtle` command. We can tell the `Turtle` two things:

`draw`: the turtle will follow our instructions at lightning speed,

`start`: an interactive window will appear, which lets you see the turtle move
at each step in the program. You can move at your own pace. This is useful if
the turtle isn't doing what you expect!

Click on the editor tab to get started:

![Not this one, silly! the one on the left!](/assets/tab-new.png)

### Type it in!

Cool. Now type this:

    Turtle.draw

The period in between the `Turtle` and the `draw` connects them together.
Programming languages have rules, just like English has rules! You can think of
`Turtle` like a subject, and `draw` as a verb. Together, they make a sentence:
hey turtle, draw me something!

Once you've typed that in, go ahead and click the 'Run' button. The turtle moves
so quickly in `draw` mode that you won't even see him, but I assure you, he's
there!

### Do... what I tell you to

Awesome! We've got the turtle going, at least. Now we need to tell it what we
want to draw!

Remember when we said that all programs are lists of instructions? In this case,
our program only has one instruction: `Turtle`, draw something! But we need to
be able to give the `Turtle` its own list of instructions.

To do this, we'll use two words: `do` and `end`. These two words together make
up a _sublist_ of things, just for the `Turtle`!

### Changing the background

Let's try this: we can tell the `Turtle` that we want to use a different
background color by using the `background` command. Check it out:

    Turtle.draw do
      background maroon
    end

Type this in and click 'Run'!

### The Turtle gets its orders

Cool stuff! The background is now maroon. You can find a full list of colors
that are supported on the [Shoes
website](http://shoesrb.com/manual/Colors.html).

This is also how you make lists of instructions for the `Turtle` to follow. To
make it a little easier to see, programmers will often put two spaces before
sublists. Get in the habit now, you'll thank me later!

### The pen

Now that we've got a snazzy background color, how do we draw some lines? Well,
the first thing you need to know about is the pen. The `Turtle` carries a pen
along, and drags it along the ground behind itself. You can change the color of
line the pen draws with the `pencolor` command.

## Drawing lines

### Sally forth!

Okay, enough dilly-dallying. Let's tell the turtle to draw a line! Here's my
line. Give this one a shot, then try your own colors and numbers!

    Turtle.draw do
      background lightslategray
      pencolor honeydew
      forward 50
    end

50 is the number of pixels to move foward, by the way.

### You spin me right round, baby

Great! So you've got a line. But what if you don't want the `Turtle` to move
forward? Well, you can tell it to turn by using a `turnleft` or `turnright`
command, like this:

    Turtle.draw do
      background lightslategray
      pencolor honeydew
      forward 50
      turnright 90
      forward 50
    end

Give that a shot, then play with it a bit!

If you're wondering what 90 means, it's the number of degrees that it'll turn.

### I like to move it, move it

Okay, now we're cooking! Let's break this down again:

`Turtle.draw` tells the `Turtle` we want it to draw some things. The period
connects the two.

`do ... end` is a sublist of things. This is what we want the `Turtle` to be
drawing. Not for the rest of our program.

`pencolor` sets the color of the pen the `Turtle` is dragging along behind him,
and `background` sets the color of the background.

`turnright` (or its buddy `turnleft`) tells the `Turtle` to turn to the right or
left.

`forward` (or its friend `backward`) tells the `Turtle` to move.

### Let's try drawing that square

Go ahead. Give it a shot. Try to get the `Turtle` to draw a square.

I'll wait. :)

### Here's my version

Here's how I did it:

    Turtle.draw do
      background lightslategray
      pencolor honeydew
      forward 50
      turnright 90
      forward 50
      turnright 90
      forward 50
      turnright 90
      forward 50
    end

## Repeating ourselves

### Pete and Repeat...

Man, that was a ton of reptition! My fingers almost fell off typing `forward`
and `turnright` there!

I have good news, though: I mentioned something earlier about computers. It
turns out that doing boring, repetitive things is something they're really good
at! They'll do the same thing over and over again, forever even as long as you
ask nicely.

### Repeating repeating ourselves ourselves

Check it out: our `Turtle` actually knows numbers. For example:

    Turtle.draw do
      background lightslategray
      pencolor honeydew
      4.times do
        forward 50
        turnright 90
      end
    end

Try running this example. It also draws a square! Wow!

### 4.times

It's pretty easy: `4` can take instructions too, just like our `Turtle`. This
command repeats a list of instructions that many times. Fun! Four times. And the
`do` and `end` show which list of instructions go with the `4` rather than with
the `Turtle`.

### Try it out!

Have a blast: make some fun shapes of your own!

## Summary

### Congratulations!

Wow, you're awesome. Pat yourself on the back. High five someone. You've got
these basics down!

Check out the _Basic Ruby_ lesson to pick up some totally different and exciting
things!


text:
* `-C N`
* `--verbose`

## Possible Optimizations
* Use slice (`[u8]`) directly as the `control.current_line`.


text:
sitemap: false
title: OAuth2-as-a-Service Use Case: Server to Server Authentication
url: /oauth2-as-a-service
---

> World Mappers is a company that has been collecting geospatial data for many years and they are now planning to expose this data to third parties through new services that offer geocoding and route planning.
>
> Their customers will be able to register and request access to one or more of these services. The customers will for example use these services to find the closest restaurant to your current location, to find a taxi or even for route planning in an application managing drivers and deliveries.
>
> World Mappers decided to use a standards based approach instead of rolling their own authentication for their API. Using OAuth2, their services are represented as Resource Owners and their consumers are the Clients. These Clients will interact with Auth0, the Authorization Server to get an access token which they can use to talk to the World Mapper API.


text:
using aura::RootWindow;
using aura::Window;
using wallpaper::WallpaperLayout;
using wallpaper::WALLPAPER_LAYOUT_CENTER;
using wallpaper::WALLPAPER_LAYOUT_CENTER_CROPPED;
using wallpaper::WALLPAPER_LAYOUT_STRETCH;
using wallpaper::WALLPAPER_LAYOUT_TILE;

namespace ash {
namespace {

// Containers IDs used for tests.
const int kDesktopBackgroundId = ash::kShellWindowId_DesktopBackgroundContainer;
const int kLockScreenBackgroundId =
    ash::kShellWindowId_LockScreenBackgroundContainer;

// Returns number of child windows in a shell window container.
int ChildCountForContainer(int container_id) {
  Window* root = ash::Shell::GetPrimaryRootWindow();
  Window* container = root->GetChildById(container_id);
  return static_cast<int>(container->children().size());
}

// Steps a widget's layer animation until it is completed. Animations must be
// enabled.
void RunAnimationForWidget(views::Widget* widget) {
  // Animations must be enabled for stepping to work.
  ASSERT_NE(ui::ScopedAnimationDurationScaleMode::duration_scale_mode(),
            ui::ScopedAnimationDurationScaleMode::ZERO_DURATION);

  ui::Layer* layer = widget->GetNativeView()->layer();
  ui::LayerAnimatorTestController controller(layer->GetAnimator());
  // Multiple steps are required to complete complex animations.
  // TODO(vollick): This should not be necessary. crbug.com/154017
  while (controller.animator()->is_animating()) {
    controller.StartThreadedAnimationsIfNeeded();
    base::TimeTicks step_time = controller.animator()->last_step_time();
    layer->GetAnimator()->Step(step_time +
                               base::TimeDelta::FromMilliseconds(1000));
  }
}

// Monitors if any task is processed by the message loop.
class TaskObserver : public base::MessageLoop::TaskObserver {
 public:
  TaskObserver() : processed_(false) {}
  ~TaskObserver() override {}

  // MessageLoop::TaskObserver overrides.
  void WillProcessTask(const base::PendingTask& pending_task) override {}
  void DidProcessTask(const base::PendingTask& pending_task) override {
    processed_ = true;
  }

  // Returns true if any task was processed.
  bool processed() const { return processed_; }

 private:
  bool processed_;
  DISALLOW_COPY_AND_ASSIGN(TaskObserver);
};

void RunAllBlockingPoolTasksUntilIdle(base::SequencedWorkerPool* pool) {
  while (true) {
    pool->FlushForTesting();

    TaskObserver task_observer;
    base::MessageLoop::current()->AddTaskObserver(&task_observer);
    base::RunLoop().RunUntilIdle();
    base::MessageLoop::current()->RemoveTaskObserver(&task_observer);

    if (!task_observer.processed())
      break;
  }
}

}  // namespace

class DesktopBackgroundControllerTest : public test::AshTestBase {
 public:
  DesktopBackgroundControllerTest()
      : controller_(NULL),
        wallpaper_delegate_(NULL) {
  }
  ~DesktopBackgroundControllerTest() override {}

  void SetUp() override {
    test::AshTestBase::SetUp();
    // Ash shell initialization creates wallpaper. Reset it so we can manually
    // control wallpaper creation and animation in our tests.
    RootWindowController* root_window_controller =
        Shell::GetPrimaryRootWindowController();
    root_window_controller->SetWallpaperController(NULL);
    root_window_controller->SetAnimatingWallpaperController(NULL);
    controller_ = Shell::GetInstance()->desktop_background_controller();
    wallpaper_delegate_ = static_cast<test::TestUserWallpaperDelegate*>(
        Shell::GetInstance()->user_wallpaper_delegate());
    controller_->set_wallpaper_reload_delay_for_test(0);
  }

  DesktopBackgroundView* desktop_background_view() {
    DesktopBackgroundWidgetController* controller =
        Shell::GetPrimaryRootWindowController()
            ->animating_wallpaper_controller()
            ->GetController(false);
    EXPECT_TRUE(controller);
    return static_cast<DesktopBackgroundView*>(
        controller->widget()->GetContentsView()->child_at(0));
  }

 protected:
  // A color that can be passed to CreateImage(). Specifically chosen to not
  // conflict with any of the default wallpaper colors.
  static const SkColor kCustomWallpaperColor = SK_ColorMAGENTA;

  // Creates an image of size |size|.
  gfx::ImageSkia CreateImage(int width, int height, SkColor color) {
    SkBitmap bitmap;
    bitmap.allocN32Pixels(width, height);
    bitmap.eraseColor(color);
    gfx::ImageSkia image = gfx::ImageSkia::CreateFrom1xBitmap(bitmap);
    return image;
  }

  // Helper function that tests the wallpaper is always fitted to the native
  // display resolution when the layout is WALLPAPER_LAYOUT_CENTER.
  void WallpaperFitToNativeResolution(DesktopBackgroundView* view,
                                      float device_scale_factor,
                                      int image_width,
                                      int image_height,
                                      SkColor color) {
    gfx::Size size = view->bounds().size();
    gfx::Canvas canvas(size, device_scale_factor, true);
    view->OnPaint(&canvas);

    int canvas_width = canvas.sk_canvas()->imageInfo().width();
    int canvas_height = canvas.sk_canvas()->imageInfo().height();
    SkBitmap bitmap;
    bitmap.allocN32Pixels(canvas_width, canvas_height);
    canvas.sk_canvas()->readPixels(&bitmap, 0, 0);

    for (int i = 0; i < canvas_width; i++) {
      for (int j = 0; j < canvas_height; j++) {
        if (i >= (canvas_width - image_width) / 2 &&
            i < (canvas_width + image_width) / 2 &&
            j >= (canvas_height - image_height) / 2 &&
            j < (canvas_height + image_height) / 2) {
          EXPECT_EQ(color, bitmap.getColor(i, j));
        } else {
          EXPECT_EQ(SK_ColorBLACK, bitmap.getColor(i, j));
        }
      }
    }
  }

  // Runs kAnimatingDesktopController's animation to completion.
  // TODO(bshe): Don't require tests to run animations; it's slow.
  void RunDesktopControllerAnimation() {
    DesktopBackgroundWidgetController* controller =
        Shell::GetPrimaryRootWindowController()
            ->animating_wallpaper_controller()
            ->GetController(false);
    EXPECT_TRUE(controller);
    ASSERT_NO_FATAL_FAILURE(RunAnimationForWidget(controller->widget()));
  }

  DesktopBackgroundController* controller_;  // Not owned.

  test::TestUserWallpaperDelegate* wallpaper_delegate_;

 private:
  DISALLOW_COPY_AND_ASSIGN(DesktopBackgroundControllerTest);
};

TEST_F(DesktopBackgroundControllerTest, BasicReparenting) {
  DesktopBackgroundController* controller =
      Shell::GetInstance()->desktop_background_controller();
  controller->CreateEmptyWallpaper();

  // Wallpaper view/window exists in the desktop background container and
  // nothing is in the lock screen background container.
  EXPECT_EQ(1, ChildCountForContainer(kDesktopBackgroundId));
  EXPECT_EQ(0, ChildCountForContainer(kLockScreenBackgroundId));

  // Moving background to lock container should succeed the first time but
  // subsequent calls should do nothing.
  EXPECT_TRUE(controller->MoveDesktopToLockedContainer());
  EXPECT_FALSE(controller->MoveDesktopToLockedContainer());

  // One window is moved from desktop to lock container.
  EXPECT_EQ(0, ChildCountForContainer(kDesktopBackgroundId));
  EXPECT_EQ(1, ChildCountForContainer(kLockScreenBackgroundId));

  // Moving background to desktop container should succeed the first time.
  EXPECT_TRUE(controller->MoveDesktopToUnlockedContainer());
  EXPECT_FALSE(controller->MoveDesktopToUnlockedContainer());

  // One window is moved from lock to desktop container.
  EXPECT_EQ(1, ChildCountForContainer(kDesktopBackgroundId));
  EXPECT_EQ(0, ChildCountForContainer(kLockScreenBackgroundId));
}

TEST_F(DesktopBackgroundControllerTest, ControllerOwnership) {
  // We cannot short-circuit animations for this test.
  ui::ScopedAnimationDurationScaleMode test_duration_mode(
      ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);

  // Create wallpaper and background view.
  DesktopBackgroundController* controller =
      Shell::GetInstance()->desktop_background_controller();
  controller->CreateEmptyWallpaper();

  // The new wallpaper is ready to start animating. kAnimatingDesktopController
  // holds the widget controller instance. kDesktopController will get it later.
  RootWindowController* root_window_controller =
      Shell::GetPrimaryRootWindowController();
  EXPECT_TRUE(root_window_controller->animating_wallpaper_controller()->
              GetController(false));

  // kDesktopController will receive the widget controller when the animation
  // is done.
  EXPECT_FALSE(root_window_controller->wallpaper_controller());

  // Force the widget's layer animation to play to completion.
  RunDesktopControllerAnimation();

  // Ownership has moved from kAnimatingDesktopController to kDesktopController.
  EXPECT_FALSE(root_window_controller->animating_wallpaper_controller()->
               GetController(false));
  EXPECT_TRUE(root_window_controller->wallpaper_controller());
}

// Test for crbug.com/149043 "Unlock screen, no launcher appears". Ensure we
// move all desktop views if there are more than one.
TEST_F(DesktopBackgroundControllerTest, BackgroundMovementDuringUnlock) {
  // We cannot short-circuit animations for this test.
  ui::ScopedAnimationDurationScaleMode test_duration_mode(
      ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);

  // Reset wallpaper state, see ControllerOwnership above.
  DesktopBackgroundController* controller =
      Shell::GetInstance()->desktop_background_controller();
  controller->CreateEmptyWallpaper();

  // Run wallpaper show animation to completion.
  RunDesktopControllerAnimation();

  // User locks the screen, which moves the background forward.
  controller->MoveDesktopToLockedContainer();

  // Suspend/resume cycle causes wallpaper to refresh, loading a new desktop
  // background that will animate in on top of the old one.
  controller->CreateEmptyWallpaper();

  // In this state we have two desktop background views stored in different
  // properties. Both are in the lock screen background container.
  RootWindowController* root_window_controller =
      Shell::GetPrimaryRootWindowController();
  EXPECT_TRUE(root_window_controller->animating_wallpaper_controller()->
              GetController(false));
  EXPECT_TRUE(root_window_controller->wallpaper_controller());
  EXPECT_EQ(0, ChildCountForContainer(kDesktopBackgroundId));
  EXPECT_EQ(2, ChildCountForContainer(kLockScreenBackgroundId));

  // Before the wallpaper's animation completes, user unlocks the screen, which
  // moves the desktop to the back.
  controller->MoveDesktopToUnlockedContainer();

  // Ensure both desktop backgrounds have moved.
  EXPECT_EQ(2, ChildCountForContainer(kDesktopBackgroundId));
  EXPECT_EQ(0, ChildCountForContainer(kLockScreenBackgroundId));

  // Finish the new desktop background animation.
  RunDesktopControllerAnimation();

  // Now there is one desktop background, in the back.
  EXPECT_EQ(1, ChildCountForContainer(kDesktopBackgroundId));
  EXPECT_EQ(0, ChildCountForContainer(kLockScreenBackgroundId));
}

// Test for crbug.com/156542. Animating wallpaper should immediately finish
// animation and replace current wallpaper before next animation starts.
TEST_F(DesktopBackgroundControllerTest, ChangeWallpaperQuick) {
  // We cannot short-circuit animations for this test.
  ui::ScopedAnimationDurationScaleMode test_duration_mode(
      ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);

  // Reset wallpaper state, see ControllerOwnership above.
  DesktopBackgroundController* controller =
      Shell::GetInstance()->desktop_background_controller();
  controller->CreateEmptyWallpaper();

  // Run wallpaper show animation to completion.
  RunDesktopControllerAnimation();

  // Change to a new wallpaper.
  controller->CreateEmptyWallpaper();

  RootWindowController* root_window_controller =
      Shell::GetPrimaryRootWindowController();
  DesktopBackgroundWidgetController* animating_controller =
      root_window_controller->animating_wallpaper_controller()->GetController(
          false);
  EXPECT_TRUE(animating_controller);
  EXPECT_TRUE(root_window_controller->wallpaper_controller());

  // Change to another wallpaper before animation finished.
  controller->CreateEmptyWallpaper();

  // The animating controller should immediately move to desktop controller.
  EXPECT_EQ(animating_controller,
            root_window_controller->wallpaper_controller());

  // Cache the new animating controller.
  animating_controller = root_window_controller->
      animating_wallpaper_controller()->GetController(false);

  // Run wallpaper show animation to completion.
  ASSERT_NO_FATAL_FAILURE(
      RunAnimationForWidget(
          root_window_controller->animating_wallpaper_controller()->
              GetController(false)->widget()));

  EXPECT_TRUE(root_window_controller->wallpaper_controller());
  EXPECT_FALSE(root_window_controller->animating_wallpaper_controller()->
               GetController(false));
  // The desktop controller should be the last created animating controller.
  EXPECT_EQ(animating_controller,
            root_window_controller->wallpaper_controller());
}

TEST_F(DesktopBackgroundControllerTest, ResizeCustomWallpaper) {
  if (!SupportsMultipleDisplays())
    return;

  UpdateDisplay("320x200");

  gfx::ImageSkia image = CreateImage(640, 480, kCustomWallpaperColor);

  // Set the image as custom wallpaper, wait for the resize to finish, and check
  // that the resized image is the expected size.
  controller_->SetWallpaperImage(image, WALLPAPER_LAYOUT_STRETCH);
  EXPECT_TRUE(image.BackedBySameObjectAs(controller_->GetWallpaper()));
  RunAllBlockingPoolTasksUntilIdle(Shell::GetInstance()->blocking_pool());
  gfx::ImageSkia resized_image = controller_->GetWallpaper();
  EXPECT_FALSE(image.BackedBySameObjectAs(resized_image));
  EXPECT_EQ(gfx::Size(320, 200).ToString(), resized_image.size().ToString());

  // Load the original wallpaper again and check that we're still using the
  // previously-resized image instead of doing another resize
  // (http://crbug.com/321402).
  controller_->SetWallpaperImage(image, WALLPAPER_LAYOUT_STRETCH);
  RunAllBlockingPoolTasksUntilIdle(Shell::GetInstance()->blocking_pool());
  EXPECT_TRUE(resized_image.BackedBySameObjectAs(controller_->GetWallpaper()));
}

#if defined(OS_WIN) && !defined(USE_ASH)
// TODO(msw): Broken on Windows. http://crbug.com/584038
#define MAYBE_GetMaxDisplaySize DISABLED_GetMaxDisplaySize
#else
#define MAYBE_GetMaxDisplaySize GetMaxDisplaySize
#endif
TEST_F(DesktopBackgroundControllerTest, MAYBE_GetMaxDisplaySize) {
  // Device scale factor shouldn't affect the native size.
  UpdateDisplay("1000x300*2");
  EXPECT_EQ(
      "1000x300",
      DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString());

  // Rotated display should return the rotated size.
  UpdateDisplay("1000x300*2/r");
  EXPECT_EQ(
      "300x1000",
      DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString());

  // UI Scaling shouldn't affect the native size.
  UpdateDisplay("1000x300*2@1.5");
  EXPECT_EQ(
      "1000x300",
      DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString());

  if (!SupportsMultipleDisplays())
    return;

  // First display has maximum size.
  UpdateDisplay("400x300,100x100");
  EXPECT_EQ(
      "400x300",
      DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString());

  // Second display has maximum size.
  UpdateDisplay("400x300,500x600");
  EXPECT_EQ(
      "500x600",
      DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString());

  // Maximum width and height belongs to different displays.
  UpdateDisplay("400x300,100x500");
  EXPECT_EQ(
      "400x500",
      DesktopBackgroundController::GetMaxDisplaySizeInNative().ToString());
}

// Test that the wallpaper is always fitted to the native display resolution
// when the layout is WALLPAPER_LAYOUT_CENTER to prevent blurry images.
TEST_F(DesktopBackgroundControllerTest, DontScaleWallpaperWithCenterLayout) {
  // We cannot short-circuit animations for this test.
  ui::ScopedAnimationDurationScaleMode test_duration_mode(
      ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);

  const gfx::Size high_resolution(3600, 2400);
  const gfx::Size low_resolution(360, 240);
  const float high_dsf = 2.0f;
  const float low_dsf = 1.0f;

  gfx::ImageSkia image_high_res = CreateImage(
      high_resolution.width(), high_resolution.height(), kCustomWallpaperColor);
  gfx::ImageSkia image_low_res = CreateImage(
      low_resolution.width(), low_resolution.height(), kCustomWallpaperColor);

  UpdateDisplay("1200x600*2");
  {
    SCOPED_TRACE(base::StringPrintf("1200x600*2 high resolution"));
    controller_->SetWallpaperImage(image_high_res, WALLPAPER_LAYOUT_CENTER);
    WallpaperFitToNativeResolution(
        desktop_background_view(), high_dsf, high_resolution.width(),
        high_resolution.height(), kCustomWallpaperColor);
  }
  {
    SCOPED_TRACE(base::StringPrintf("1200x600*2 low resolution"));
    controller_->SetWallpaperImage(image_low_res, WALLPAPER_LAYOUT_CENTER);
    WallpaperFitToNativeResolution(
        desktop_background_view(), high_dsf, low_resolution.width(),
        low_resolution.height(), kCustomWallpaperColor);
  }

  UpdateDisplay("1200x600");
  {
    SCOPED_TRACE(base::StringPrintf("1200x600 high resolution"));
    controller_->SetWallpaperImage(image_high_res, WALLPAPER_LAYOUT_CENTER);
    WallpaperFitToNativeResolution(
        desktop_background_view(), low_dsf, high_resolution.width(),
        high_resolution.height(), kCustomWallpaperColor);
  }
  {
    SCOPED_TRACE(base::StringPrintf("1200x600 low resolution"));
    controller_->SetWallpaperImage(image_low_res, WALLPAPER_LAYOUT_CENTER);
    WallpaperFitToNativeResolution(
        desktop_background_view(), low_dsf, low_resolution.width(),
        low_resolution.height(), kCustomWallpaperColor);
  }

  UpdateDisplay("1200x600/u@1.5");  // 1.5 ui scale
  {
    SCOPED_TRACE(base::StringPrintf("1200x600/u@1.5 high resolution"));
    controller_->SetWallpaperImage(image_high_res, WALLPAPER_LAYOUT_CENTER);
    WallpaperFitToNativeResolution(
        desktop_background_view(), low_dsf, high_resolution.width(),
        high_resolution.height(), kCustomWallpaperColor);
  }
  {
    SCOPED_TRACE(base::StringPrintf("1200x600/u@1.5 low resolution"));
    controller_->SetWallpaperImage(image_low_res, WALLPAPER_LAYOUT_CENTER);
    WallpaperFitToNativeResolution(
        desktop_background_view(), low_dsf, low_resolution.width(),
        low_resolution.height(), kCustomWallpaperColor);
  }
}

}  // namespace ash


text:
/*	General CSS resets;
 *		The target itself is not affected, allowing
 *		the remainder of the document to use an
 *		alternate box-sizing model;
 *		Support for box-sizing is wide spread:
 *		/caniuse.com/#search=box-sizing
 */
	.noUi-target * {
-webkit-box-sizing: border-box;
   -moz-box-sizing: border-box;
		box-sizing: border-box;
-webkit-touch-callout: none;
    -ms-touch-action: none;
-webkit-user-select: none;
   -moz-user-select: none;
    -ms-user-select: none;
		cursor: default;
	}

/*	Main slider bar;
 *		Standard styles no longer incorrectly force a
 *		width or height on the slider.
 */
	.noUi-base {
		height: 40px;
		position: relative;
		max-width: 100%;
		max-height: 100%;
		border: 1px solid #bfbfbf;
		z-index: 1;
	}

/*	Handles + active state;
 *		The :after pseudo-element wont inherit
 *		box-sizing, so it needs to applied manually.
 */
	.noUi-handle {
		background: #EEE;
		height: 44px;
		width: 44px;
		border: 1px solid #BFBFBF;
		margin: -3px 0 0 -23px;
	}
	.noUi-active {
		background: #E9E9E9;
	}
	.noUi-active:after {
-webkit-box-sizing: border-box;
   -moz-box-sizing: border-box;
		box-sizing: border-box;
		content: "";
		display: block;
		height: 100%;
		border: 1px solid #DDD;
	}

/*	Styling-only classes;
 *		Structured to prevent double declarations
 *		for various states of the slider.
 */
	.noUi-connect {
		background: Teal;
	}
	.noUi-background {
		background: #DDD;
	}

/*	Functional styles for handle positioning;
 *		Note that the origins have z-index 0, the base has
 *		z-index 1; This fixes a bug where borders become invisible.
 */
	.noUi-origin {
		position: absolute;
		right: 0;
		top: 0;
		bottom: 0;
		z-index: 0;
	}
	.noUi-origin-upper {
		background: inherit !important;
	}
	.noUi-z-index {
		z-index: 10;
	}

/*	Adaptations for the vertical slider;
 *		Some standard styles have been extended to keep
 *		exceptions for the vertical slider as minimal as possible.
 */
	.noUi-vertical {
		width: 40px;
	}
	.noUi-vertical .noUi-origin {
		bottom: 0;
		left: 0;
	}
	.noUi-vertical .noUi-handle  {
		margin: -23px 0 0 -3px;
	}

/*	Various alternate slider states;
 *		Support for transition is widely available,
 *		Only IE7, IE8 and IE9 will ignore these rules.
 *		Since this is merely a progressive enhancement,
 *		this is no problem at all.
 *		/caniuse.com/#search=transition
 */
	.noUi-target[disabled] .noUi-base {
		background: #999;
	}
	.noUi-target[disabled] .noUi-connect {
		background: #BBB;
	}
	.noUi-state-tap .noUi-origin {
		-webkit-transition: left 0.3s, top 0.3s;
		transition: left 0.3s, top 0.3s;
	}


text:
FROM quantecon/lectures-base:latest
MAINTAINER me@arnavsood.com
USER quantecon

# So we can build on all sorts of machines (i.e. Xeon processors)
ARG OPENBLAS_CORETYPE=HASWELL

# Install Julia
ARG JULIA_VERSION=1.2.0
RUN sudo apt-get update && sudo  apt-get install wget
RUN cd ${HOME}/utils && mkdir julia-${JULIA_VERSION} && cd julia-${JULIA_VERSION} && \
    wget -q https://julialang-s3.julialang.org/bin/linux/x64/`echo ${JULIA_VERSION} | cut -d. -f 1,2`/julia-${JULIA_VERSION}-linux-x86_64.tar.gz && \
    echo "926ced5dec5d726ed0d2919e849ff084a320882fb67ab048385849f9483afc47 *julia-${JULIA_VERSION}-linux-x86_64.tar.gz" | sha256sum -c - && \
    tar xzf julia-${JULIA_VERSION}-linux-x86_64.tar.gz --strip-components=1 && \
    rm *.tar.gz
RUN sudo ln -fs ${HOME}/utils/julia-*/bin/julia /usr/local/bin/julia

# Install Jupinx
RUN /home/quantecon/utils/conda/bin/pip install sphinxcontrib-jupyter sphinxcontrib.bibtex

# Add Julia Packages
RUN julia -e "using Pkg; pkg\"add InstantiateFromURL IJulia\""
RUN cd ${HOME}/utils && julia -e "using InstantiateFromURL; github_project(\"QuantEcon/quantecon-notebooks-julia\"); packages_to_default_environment()"


text:
Meld Diff
===============================================================================

Launches a [Meld](http://meldmerge.org/) process for the current project.

The project must be the first one open.

The command is **Meld Diff: Launch**; the keyboard shortcut is `Alt+M`.

You can change which Meld process is spawned by going to
_Settings->Meld Diff_ and changing **Meld Path**; the default is
`meld`.

You can also change which arguments to pass to Meld by going to
_Settings->Love Launcher_ and changing **Meld Arguments**; the default is
`--auto-compare`.

If something isn't working be sure to check the console; that's where debug
info is dumped.

This is a fork of **footballhead**'s [love-launcher](https://atom.io/packages/love-launcher). Not sure if there's a specific place I'm supposed to accredit the original author, so I will put it here. I'm also not sure if I'm supposed to add my name to the LICENSE. But for now I will leave it as is.


text:
title: autoEscape
name: options-autoescape
---

Determine if text is autoescaped. The default is true.


text:
CREATE VIEW V_SelectActiveUsers AS
SELECT *
FROM Users
WHERE DATEDIFF(DAY, LastLoginTime, GETDATE()) = 0

GO
/*
SELECT *
FROM V_SelectActiveUsers
*/


text:
.class public Lcom/htc/wrap/android/media/HtcWrapMediaScanner;
.super Landroid/media/MediaScanner;
.source "HtcWrapMediaScanner.java"

# direct methods
.method public constructor <init>(Landroid/content/Context;)V
    .locals 0
    .parameter "context"

    .prologue
    .line 13
    invoke-direct {p0, p1}, Landroid/media/MediaScanner;-><init>(Landroid/content/Context;)V

    .line 14
    return-void
.end method

# virtual methods
.method public onSimChanged()V
    .locals 0

    .prologue
    .line 21
    invoke-super {p0}, Landroid/media/MediaScanner;->onSimChanged()V

    .line 22
    return-void
.end method

.method public stopScan()V
    .locals 0

    .prologue
    .line 25
    invoke-super {p0}, Landroid/media/MediaScanner;->stopScan()V

    .line 26
    return-void
.end method


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace slnStartupProjectLibrary
{
    public class Parser
    {
        public static void SetStartupProject(string slnFilename, string projectName)
        {
            string text = null;
            int projectsStartOffset = -1;
            int projectsEndOffset = -1;
            List<Project> projects = new List<Project>();

            /* check if the solution file has BOM */
            bool hasBOM = false;
            using(FileStream fs = new FileStream(slnFilename, FileMode.Open))
            {
                byte[] bits = new byte[3];
                fs.Read(bits, 0, 3);
                if (bits[0] == 0xEF && bits[1] == 0xBB && bits[2] == 0xBF)
                {
                    hasBOM = true;
                }
            }
            Encoding fileEncoding = new UTF8Encoding(hasBOM);

            try
            {
                text = File.ReadAllText(slnFilename, fileEncoding);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to read sln: " + ex.Message);
            }
            try
            {
                Regex projectRegex = new Regex(@"(\bProject\b\(.*?\bEndProject\b)", RegexOptions.Singleline);
                MatchCollection projectMatches = projectRegex.Matches(text);
                if (projectMatches.Count == 0)
                    throw new Exception("Could not find any projects in the solution");
                foreach (Match projectMatch in projectMatches)
                    projects.Add(new Project(projectMatch.Value, projectMatch.Index));
                if (!projects.Any(p => p.ProjectName == projectName))
                    throw new Exception(string.Format("Could not find a project named \"{0}\" in \"{1}\"", projectName, slnFilename));
                int count = projects.Count(p => p.ProjectName == projectName);
                if (count != 1)
                    throw new Exception(string.Format("Project \"{0}\" found more than once. \"{1}\" is probably malformed", projectName, slnFilename));
                Project startupProject = projects.First(p => p.ProjectName == projectName);
                projectsStartOffset = projects[0].Offset;
                projectsEndOffset = projects[projects.Count - 1].Offset + projects[projects.Count - 1].CDATA.Length;
                projects.Remove(startupProject);
                projects.Insert(0, startupProject);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to parse sln: " + ex.Message);
            }
            try
            {
                string newSln = text.Substring(0, projectsStartOffset);
                List<string> projectString = new List<string>();
                foreach (Project project in projects)
                {
                    projectString.Add(project.CDATA);
                }
                newSln += string.Join(Environment.NewLine, projectString.ToArray());
                newSln += text.Substring(projectsEndOffset, text.Length - projectsEndOffset);
                File.WriteAllText(slnFilename, newSln, fileEncoding);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to write sln: " + ex.Message);
            }
        }
    }
}


text:
#ifndef XENIA_DEBUG_DEBUG_CLIENT_H_
#define XENIA_DEBUG_DEBUG_CLIENT_H_

#include <memory>
#include <mutex>
#include <string>
#include <vector>

#include "xenia/base/socket.h"
#include "xenia/base/threading.h"
#include "xenia/debug/proto/packet_reader.h"
#include "xenia/debug/proto/packet_writer.h"
#include "xenia/debug/proto/xdp_protocol.h"

namespace xe {
namespace ui {
class Loop;
}  // namespace ui
}  // namespace xe

namespace xe {
namespace debug {

using proto::ModuleListEntry;
using proto::ThreadCallStackFrame;
using proto::ThreadListEntry;

enum class ExecutionState {
  kRunning,
  kStopped,
  kExited,
};

// NOTE: all callbacks are issued on the client thread and should be marshalled
// to the UI thread. All other methods can be called from any thread.

class DebugClientListener {
 public:
  virtual ~DebugClientListener() = default;

  virtual void OnExecutionStateChanged(ExecutionState execution_state) = 0;
  virtual void OnModulesUpdated(
      std::vector<const ModuleListEntry*> entries) = 0;
  virtual void OnThreadsUpdated(
      std::vector<const ThreadListEntry*> entries) = 0;
  virtual void OnThreadCallStackUpdated(
      uint32_t thread_handle,
      std::vector<const ThreadCallStackFrame*> frames) = 0;
};

class DebugClient {
 public:
  DebugClient();
  ~DebugClient();

  Socket* socket() const { return socket_.get(); }
  void set_listener(DebugClientListener* listener) { listener_ = listener; }
  void set_loop(xe::ui::Loop* loop) { loop_ = loop; }

  ExecutionState execution_state() const { return execution_state_; }

  bool Connect(std::string hostname, uint16_t port);

  void Continue();
  void StepOne(uint32_t thread_id);
  void StepTo(uint32_t thread_id, uint32_t target_pc);
  void Interrupt();
  void Exit();

 private:
  bool HandleSocketEvent();
  bool ProcessBuffer(const uint8_t* buffer, size_t buffer_length);
  bool ProcessPacket(proto::PacketReader* packet_reader,
                     const proto::Packet* packet);
  void Flush();

  void BeginUpdateAllState();

  std::recursive_mutex mutex_;
  std::unique_ptr<Socket> socket_;
  std::unique_ptr<xe::threading::Thread> thread_;
  std::vector<uint8_t> receive_buffer_;

  proto::PacketReader packet_reader_;
  proto::PacketWriter packet_writer_;

  DebugClientListener* listener_ = nullptr;
  xe::ui::Loop* loop_ = nullptr;

  ExecutionState execution_state_ = ExecutionState::kStopped;
};

}  // namespace debug
}  // namespace xe

#endif  // XENIA_DEBUG_DEBUG_CLIENT_H_


text:
struct PyArrayInterface {
	int two;                // contains the integer 2 -- simple sanity check
	int nd;                 // number of dimensions
	char typekind;          // kind in array --- character code of typestr
	int itemsize;           // size of each element
	int flags;              // flags indicating how the data should be interpreted, must set ARR_HAS_DESCR bit to validate descr
	Py_intptr_t * shape;    // A length-nd array of shape information
	Py_intptr_t * strides;  // A length-nd array of stride information
	void * data;            // A pointer to the first element of the array
	PyObject * descr;       // NULL or data-description (same as descr key of __array_interface__) -- must set ARR_HAS_DESCR flag or this will be ignored.
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
GenNegEx
</TITLE>

<META NAME="date" CONTENT="2014-02-18">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

lingscope.algorithms.negex

Class GenNegEx

java.lang.Object
  lingscope.algorithms.negex.GenNegEx

public class GenNegEx
extends java.lang.Object

Author: Imre Solti
 Date: 09/15/2008
 Modified: 04/15/2009
        Changed to specifications of test kit and discussions with WC and PH.
 Modified: 04/26/2009
 Fixed the deletion of last character in scope fo PREN, PREP negation scopes.

 Wendy Chapman's NegEx algorithm in Java.

 Sentence boundaries serve as WINDOW for negation (suggested by Wendy Chapman)

Constructor Summary

GenNegEx()

Method Summary

 java.lang.String
getCue(java.lang.String sentenceString,
       java.util.List<java.lang.String> ruleStrings,
       java.lang.String beginTag,
       java.lang.String interTag,
       java.lang.String otherTag)

 java.lang.String
getPreviousRunScope()

 java.lang.String
getScope(java.lang.String sentenceString,
         java.util.List<java.lang.String> ruleStrings,
         java.lang.String beginTag,
         java.lang.String interTag,
         java.lang.String otherTag)

 java.lang.String
negCheck(java.lang.String sentenceString,
         java.lang.String phraseString,
         java.util.ArrayList ruleStrings,
         boolean negatePossible)

 void
tagNegation(java.lang.String sentenceString,
            java.util.List<java.lang.String> ruleStrings)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

GenNegEx

public GenNegEx()

Method Detail

getCue

public java.lang.String getCue(java.lang.String sentenceString,
                               java.util.List<java.lang.String> ruleStrings,
                               java.lang.String beginTag,
                               java.lang.String interTag,
                               java.lang.String otherTag)

getScope

public java.lang.String getScope(java.lang.String sentenceString,
                                 java.util.List<java.lang.String> ruleStrings,
                                 java.lang.String beginTag,
                                 java.lang.String interTag,
                                 java.lang.String otherTag)

tagNegation

public void tagNegation(java.lang.String sentenceString,
                        java.util.List<java.lang.String> ruleStrings)

negCheck

public java.lang.String negCheck(java.lang.String sentenceString,
                                 java.lang.String phraseString,
                                 java.util.ArrayList ruleStrings,
                                 boolean negatePossible)
                          throws java.lang.Exception

Throws:

java.lang.Exception

getPreviousRunScope

public java.lang.String getPreviousRunScope()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
J2534Connection_ISO15765::J2534Connection_ISO15765(
	std::shared_ptr<PandaJ2534Device> panda_dev,
	unsigned long ProtocolID,
	unsigned long Flags,
	unsigned long BaudRate
) : J2534Connection(panda_dev, ProtocolID, Flags, BaudRate), wftMax(0) {
	this->port = 0;

	if (BaudRate % 100 || BaudRate < 10000 || BaudRate > 5000000)
		throw ERR_INVALID_BAUDRATE;

	panda_dev->panda->set_can_speed_cbps(panda::PANDA_CAN1, (uint16_t)(BaudRate / 100));
}

unsigned long J2534Connection_ISO15765::validateTxMsg(PASSTHRU_MSG* msg) {
	if ((msg->DataSize < this->getMinMsgLen() + (msg_is_extaddr(msg) ? 1 : 0) ||
		msg->DataSize > this->getMaxMsgLen() + (msg_is_extaddr(msg) ? 1 : 0) ||
		(val_is_29bit(msg->TxFlags) != this->_is_29bit() && !check_bmask(this->Flags, CAN_ID_BOTH))))
		return ERR_INVALID_MSG;

	int fid = get_matching_out_fc_filter_id(std::string((const char*)msg->Data, msg->DataSize), msg->TxFlags, 0xFFFFFFFF);
	if (msg->DataSize > getMaxMsgSingleFrameLen() && fid == -1) return ERR_NO_FLOW_CONTROL; //11 bytes (4 for CANid, 7 payload) is max length of input frame.

	return STATUS_NOERROR;
}

std::shared_ptr<MessageTx> J2534Connection_ISO15765::parseMessageTx(PASSTHRU_MSG& msg) {
	int fid = get_matching_out_fc_filter_id(std::string((const char*)msg.Data, msg.DataSize), msg.TxFlags, 0xFFFFFFFF);
	if (msg.DataSize > getMaxMsgSingleFrameLen() && fid == -1) 1;

	return std::dynamic_pointer_cast<MessageTx>(
		std::make_shared<MessageTx_ISO15765>(shared_from_this(), msg, (fid == -1) ? nullptr : this->filters[fid])
		);
}

//https://happilyembedded.wordpress.com/2016/02/15/can-multiple-frame-transmission/
void J2534Connection_ISO15765::processMessage(const J2534Frame& msg) {
	if (msg.ProtocolID != CAN) return;

	int fid = get_matching_in_fc_filter_id(msg, this->Flags);
	if (fid == -1) return;

	auto filter = this->filters[fid];
	bool is_ext_addr = check_bmask(filter->flags, ISO15765_ADDR_TYPE);
	uint8_t addrlen = is_ext_addr ? 5 : 4;

	switch (msg_get_type(msg, addrlen)) {
	case FRAME_FLOWCTRL:
		{
			if (this->txbuff.size() == 0)
				return;
			if (msg.Data.size() < addrlen + 3) return;
			uint8_t flow_status = msg.Data[addrlen] & 0x0F;
			uint8_t block_size = msg.Data[addrlen + 1];
			uint8_t st_min = msg.Data[addrlen + 2];

			auto txConvo = std::static_pointer_cast<MessageTx_ISO15765>(this->txbuff.front());
			switch (flow_status) {
			case FLOWCTRL_CONTINUE: {
				if (st_min > 0xF9) break;
				if (st_min >= 0xf1 && st_min <= 0xf9) {
					txConvo->flowControlContinue(block_size, std::chrono::microseconds((st_min & 0x0F) * 100));
				} else if(st_min <= 0x7f) {
					txConvo->flowControlContinue(block_size, std::chrono::microseconds(st_min * 1000));
				} else {
					break;
				}
				txConvo->scheduleImmediate();
				this->rescheduleExistingTxMsgs();
				break;
			}
			case FLOWCTRL_WAIT:
				txConvo->flowControlWait(this->wftMax);
				break;
			case FLOWCTRL_ABORT:
				txConvo->flowControlAbort();
				break;
			}
			break;
		}
	case FRAME_SINGLE:
		{
			this->rxConversations[fid] = nullptr; //Reset any current transaction.

			if (is_ext_addr) {
				if ((msg.Data[5] & 0x0F) > 6) return;
			} else {
				if ((msg.Data[4] & 0x0F) > 7) return;
			}

			J2534Frame outframe(ISO15765, msg.RxStatus, 0, msg.Timestamp);
			if (msg.Data.size() != 8 && check_bmask(this->Flags, ISO15765_FRAME_PAD))
				outframe.RxStatus |= ISO15765_PADDING_ERROR;
			if (is_ext_addr)
				outframe.RxStatus |= ISO15765_ADDR_TYPE;
			outframe.Data = msg.Data.substr(0, addrlen) + msg.Data.substr(addrlen + 1, msg.Data[addrlen]);
			outframe.ExtraDataIndex = outframe.Data.size();

			addMsgToRxQueue(outframe);
			break;
		}
	case FRAME_FIRST:
		{
			if (msg.Data.size() < 12) {
				//A frame was received that could have held more data.
				//No examples of this protocol show that happening, so
				//it will be assumed that it is grounds to reset rx.
				this->rxConversations[fid] = nullptr;
				return;
			}

			J2534Frame outframe(ISO15765, msg.RxStatus | START_OF_MESSAGE, 0, msg.Timestamp);
			if (is_ext_addr)
				outframe.RxStatus |= ISO15765_ADDR_TYPE;
			outframe.Data = msg.Data.substr(0, addrlen);

			addMsgToRxQueue(outframe);

			this->rxConversations[fid] = std::make_shared<MessageRx>(
				((msg.Data[addrlen] & 0x0F) << 8) | msg.Data[addrlen + 1],
				msg.Data.substr(addrlen + 2, 12 - (addrlen + 2)),
				msg.RxStatus, filter);

			//TODO maybe the flow control should also be scheduled in the TX list.
			//Doing it this way because the filter can be 5 bytes in ext address mode.
			std::string flowfilter = filter->get_flowctrl();
			uint32_t flow_addr = (((uint8_t)flowfilter[0]) << 24) | ((uint8_t)(flowfilter[1]) << 16) | ((uint8_t)(flowfilter[2]) << 8) | ((uint8_t)flowfilter[3]);

			std::string flowstrlresp;
			if (flowfilter.size() > 4)
				flowstrlresp += flowfilter[4];
			flowstrlresp += std::string("\x30\x00\x00", 3);
			if (check_bmask(filter->flags, ISO15765_FRAME_PAD)) {
				flowstrlresp += std::string(8 - flowstrlresp.size(), '\x00');
			}

			if (auto panda_dev_sp = this->panda_dev.lock()) {
				panda_dev_sp->panda->can_send(flow_addr, val_is_29bit(msg.RxStatus), (const uint8_t *)flowstrlresp.c_str(), (uint8_t)flowstrlresp.size(), panda::PANDA_CAN1);
			}
			break;
		}
	case FRAME_CONSEC:
		{
			auto& convo = this->rxConversations[fid];
			if (convo == nullptr) return;

			if (!convo->rx_add_frame(msg.Data[addrlen], (is_ext_addr ? 6 : 7), msg.Data.substr(addrlen + 1))) {
				//Delete this conversation.
				convo = nullptr;
				return;
			}

			std::string final_msg;
			if (convo->flush_result(final_msg)) {
				convo = nullptr;
				J2534Frame outframe(ISO15765, msg.RxStatus, 0, msg.Timestamp);
				if (is_ext_addr)
					outframe.RxStatus |= ISO15765_ADDR_TYPE;
				outframe.Data = msg.Data.substr(0, addrlen) + final_msg;
				outframe.ExtraDataIndex = outframe.Data.size();

				addMsgToRxQueue(outframe);
			}
			break;
		}
	}
}

void J2534Connection_ISO15765::setBaud(unsigned long BaudRate) {
	if (auto panda_dev = this->getPandaDev()) {
		if (BaudRate % 100 || BaudRate < 10000 || BaudRate > 5000000)
			throw ERR_NOT_SUPPORTED;

		panda_dev->panda->set_can_speed_cbps(panda::PANDA_CAN1, (uint16_t)(BaudRate / 100));
		return J2534Connection::setBaud(BaudRate);
	} else {
		throw ERR_DEVICE_NOT_CONNECTED;
	}
}

long J2534Connection_ISO15765::PassThruStartMsgFilter(unsigned long FilterType, PASSTHRU_MSG *pMaskMsg, PASSTHRU_MSG *pPatternMsg,
	PASSTHRU_MSG *pFlowControlMsg, unsigned long *pFilterID) {

	if (FilterType != FLOW_CONTROL_FILTER) return ERR_INVALID_FILTER_ID;
	return J2534Connection::PassThruStartMsgFilter(FilterType, pMaskMsg, pPatternMsg, pFlowControlMsg, pFilterID);
}

int J2534Connection_ISO15765::get_matching_out_fc_filter_id(const std::string& msgdata, unsigned long flags, unsigned long flagmask) {
	for (unsigned int i = 0; i < this->filters.size(); i++) {
		if (this->filters[i] == nullptr) continue;
		auto filter = this->filters[i]->get_flowctrl();
		if (filter == msgdata.substr(0, filter.size()) &&
			(this->filters[i]->flags & flagmask) == (flags & flagmask))
			return i;
	}
	return -1;
}

int J2534Connection_ISO15765::get_matching_in_fc_filter_id(const J2534Frame& msg, unsigned long flagmask) {
	for (unsigned int i = 0; i < this->filters.size(); i++) {
		if (this->filters[i] == nullptr) continue;
		if (this->filters[i]->check(msg) == FILTER_RESULT_MATCH &&
			(this->filters[i]->flags & flagmask) == (msg.RxStatus & flagmask))
			return i;
	}
	return -1;
}

void J2534Connection_ISO15765::processIOCTLSetConfig(unsigned long Parameter, unsigned long Value) {
	switch (Parameter) {
	case ISO15765_WFT_MAX:
		this->wftMax = Value;
		break;
	default:
		J2534Connection::processIOCTLSetConfig(Parameter, Value);
	}
}

unsigned long J2534Connection_ISO15765::processIOCTLGetConfig(unsigned long Parameter) {
	switch (Parameter) {
	case ISO15765_WFT_MAX:
		return this->wftMax;
	default:
		return J2534Connection::processIOCTLGetConfig(Parameter);
	}
}


text:
layout: post
author: elliott
category: exercise
title: Poetry slam Tina
---

Submit a well-formatted pull request to our class blog with embedded Trinket programs for the below exercises.
Complete these on your own, using any materials you need. Do not
look at other students' submissions until after you've completed your work.

**After your programs are done**, check other students' work and other resources online if you had questions.
Include a reflection about what you think you've learned and any concepts that are still fuzzy to you.
Did you encounter frustrating situations? Did you feel a lightbulb turn on?

___

![](https://fuller.pcssd.org/publicfiles/4/files/2014/09/keep-calm-and-slam-poetry.png)

Write a program that lets the user slam poetry.

Specifically, collect a series of text inputs by the user, until they type "done".

Use Python's Turtle to write these inputs on the screen, one under the other,
so that they're readable.


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="loginActionBean" class="net.codejava.web.LoginAction">
        <property name="userDAO" ref="userDAO"/>
    </bean>

    <bean id="userDAO" class="net.codejava.web.UserDAO"/>

</beans>


text:
let EP = {
      PLUGIN_ID: 'internal.compo.plugin.id',
      PLUGIN_LOADER: 'internal.compo.plugin.loader',
      SINGLETONS: 'internal.compo.singletons',
      MANIFEST_TRANSFORM: 'compo.manifest.transform',
      EXTENSION_TRANSFORM: 'compo.extension.transform',
    }

let EP_CONFIG_DEFAULTS = {
  key: '_id', // how the array is transformed into an object
  lazy: false, // is code loaded lazily or eagerly
  stringIs: 'object', // if the extension is just a string, what then?
  description: null, // should be something there, right?
}

const PERMISSION_ACCESSOR_NAME = 'plugin'

module.exports = {
  EP,
  EP_CONFIG_DEFAULTS,
  PERMISSION_ACCESSOR_NAME,
}


text:
title: Blog Post 2
layout: post
author: joshua.massey
permalink: /blog-post-2/
source-id: 1HL1J3E-_XQ7jMsL_1aQ7kCYp2UhTMG5SIvf-VR71K0Q
published: true
---
In our second lesson in the new school year we looked at a stock sheet and how to make the quantity number cell change colours depending on the number in that certain cell. We were also taught about product codes and how to use them to search up which product that code equates to. We were also taught about the vlookup formula but didn't have time to put it into our sheet and we had to finish our stock sheet for homework with the buying price, selling price, product, product code and quantity.


text:
package com.amazonaws.services.cloudfront.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * Contains information about a public key.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PublicKeySummary implements Serializable, Cloneable {

    /**
     *

     * The identifier of the public key.
     *

     */
    private String id;
    /**
     *

     * A name to help identify the public key.
     *

     */
    private String name;
    /**
     *

     * The date and time when the public key was uploaded.
     *

     */
    private java.util.Date createdTime;
    /**
     *

     * The public key.
     *

     */
    private String encodedKey;
    /**
     *

     * A comment to describe the public key. The comment cannot be longer than 128 characters.
     *

     */
    private String comment;

    /**
     *

     * The identifier of the public key.
     *

     *
     * @param id
     *        The identifier of the public key.
     */

    public void setId(String id) {
        this.id = id;
    }

    /**
     *

     * The identifier of the public key.
     *

     *
     * @return The identifier of the public key.
     */

    public String getId() {
        return this.id;
    }

    /**
     *

     * The identifier of the public key.
     *

     *
     * @param id
     *        The identifier of the public key.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PublicKeySummary withId(String id) {
        setId(id);
        return this;
    }

    /**
     *

     * A name to help identify the public key.
     *

     *
     * @param name
     *        A name to help identify the public key.
     */

    public void setName(String name) {
        this.name = name;
    }

    /**
     *

     * A name to help identify the public key.
     *

     *
     * @return A name to help identify the public key.
     */

    public String getName() {
        return this.name;
    }

    /**
     *

     * A name to help identify the public key.
     *

     *
     * @param name
     *        A name to help identify the public key.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PublicKeySummary withName(String name) {
        setName(name);
        return this;
    }

    /**
     *

     * The date and time when the public key was uploaded.
     *

     *
     * @param createdTime
     *        The date and time when the public key was uploaded.
     */

    public void setCreatedTime(java.util.Date createdTime) {
        this.createdTime = createdTime;
    }

    /**
     *

     * The date and time when the public key was uploaded.
     *

     *
     * @return The date and time when the public key was uploaded.
     */

    public java.util.Date getCreatedTime() {
        return this.createdTime;
    }

    /**
     *

     * The date and time when the public key was uploaded.
     *

     *
     * @param createdTime
     *        The date and time when the public key was uploaded.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PublicKeySummary withCreatedTime(java.util.Date createdTime) {
        setCreatedTime(createdTime);
        return this;
    }

    /**
     *

     * The public key.
     *

     *
     * @param encodedKey
     *        The public key.
     */

    public void setEncodedKey(String encodedKey) {
        this.encodedKey = encodedKey;
    }

    /**
     *

     * The public key.
     *

     *
     * @return The public key.
     */

    public String getEncodedKey() {
        return this.encodedKey;
    }

    /**
     *

     * The public key.
     *

     *
     * @param encodedKey
     *        The public key.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PublicKeySummary withEncodedKey(String encodedKey) {
        setEncodedKey(encodedKey);
        return this;
    }

    /**
     *

     * A comment to describe the public key. The comment cannot be longer than 128 characters.
     *

     *
     * @param comment
     *        A comment to describe the public key. The comment cannot be longer than 128 characters.
     */

    public void setComment(String comment) {
        this.comment = comment;
    }

    /**
     *

     * A comment to describe the public key. The comment cannot be longer than 128 characters.
     *

     *
     * @return A comment to describe the public key. The comment cannot be longer than 128 characters.
     */

    public String getComment() {
        return this.comment;
    }

    /**
     *

     * A comment to describe the public key. The comment cannot be longer than 128 characters.
     *

     *
     * @param comment
     *        A comment to describe the public key. The comment cannot be longer than 128 characters.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PublicKeySummary withComment(String comment) {
        setComment(comment);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getId() != null)
            sb.append("Id: ").append(getId()).append(",");
        if (getName() != null)
            sb.append("Name: ").append(getName()).append(",");
        if (getCreatedTime() != null)
            sb.append("CreatedTime: ").append(getCreatedTime()).append(",");
        if (getEncodedKey() != null)
            sb.append("EncodedKey: ").append(getEncodedKey()).append(",");
        if (getComment() != null)
            sb.append("Comment: ").append(getComment());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof PublicKeySummary == false)
            return false;
        PublicKeySummary other = (PublicKeySummary) obj;
        if (other.getId() == null ^ this.getId() == null)
            return false;
        if (other.getId() != null && other.getId().equals(this.getId()) == false)
            return false;
        if (other.getName() == null ^ this.getName() == null)
            return false;
        if (other.getName() != null && other.getName().equals(this.getName()) == false)
            return false;
        if (other.getCreatedTime() == null ^ this.getCreatedTime() == null)
            return false;
        if (other.getCreatedTime() != null && other.getCreatedTime().equals(this.getCreatedTime()) == false)
            return false;
        if (other.getEncodedKey() == null ^ this.getEncodedKey() == null)
            return false;
        if (other.getEncodedKey() != null && other.getEncodedKey().equals(this.getEncodedKey()) == false)
            return false;
        if (other.getComment() == null ^ this.getComment() == null)
            return false;
        if (other.getComment() != null && other.getComment().equals(this.getComment()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode());
        hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
        hashCode = prime * hashCode + ((getCreatedTime() == null) ? 0 : getCreatedTime().hashCode());
        hashCode = prime * hashCode + ((getEncodedKey() == null) ? 0 : getEncodedKey().hashCode());
        hashCode = prime * hashCode + ((getComment() == null) ? 0 : getComment().hashCode());
        return hashCode;
    }

    @Override
    public PublicKeySummary clone() {
        try {
            return (PublicKeySummary) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../shared/to_hash.rb', __FILE__)

describe "ENV.to_hash" do
  it_behaves_like(:env_to_hash, :to_hash)
end