text:
package route

import (
	"errors"
	"sort"
	"strings"
)

var (
	errRegConflict     = errors.New("multiple registration")
	errVarNameConflict = errors.New("variable name conflict")
	errNoHandler       = errors.New("handler not found")
)

type edge struct {
	label string
	node  node
}

type node struct {
	pattern   string
	name      string
	handlers  handlers
	edges     []*edge
	nVar      *node // nVar handles a variable pattern
	nWildcard *node // nWildcard handles a catch-all pattern
}

// The lookup method returns a Handler, Params if any, and the registered pattern for
// the given path and method. If no registered pattern matches the given path then errNoHandler
// will be returned and if no handler is registered for the given method a methodError is returned.
func (n *node) lookup(method, path string) (Handler, Params, string, error) {
	var (
		cn     = n // current node
		params = Params{}
	)

Loop:
	for {
		if path == "" {
			if cn.handlers == nil {
				return nil, params, "", errNoHandler
			}

			handler, err := cn.handlers.get(method)
			return handler, params, cn.pattern, err
		}

		// static
		for _, e := range cn.edges {
			if e.label[0] == path[0] {
				pl := cpl(e.label, path)
				if pl == len(e.label) {
					path = path[pl:]
					cn = &e.node
					continue Loop
				}
				break
			}
		}

		// variable
		if cn.nVar != nil {
			cn = cn.nVar
			i := strings.IndexByte(path, '/')
			if i == -1 {
				i = len(path)
			}
			//if params == nil {
			//	params = Params{}
			//}

			params[cn.name] = path[:i]
			path = path[i:]
			continue
		}

		// wildcard
		if cn.nWildcard != nil {
			cn = cn.nWildcard
			//if params == nil {
			//	params = Params{}
			//}
			params[cn.name] = path
			if cn.handlers == nil {
				return nil, params, "", errNoHandler
			}
			handler, err := cn.handlers.get(method)
			return handler, params, cn.pattern, err
		}

		// nothing found
		break Loop
	}
	return nil, params, "", errNoHandler
}

// The insert method registers the given Handler for the given pattern and method.
// If a Handler is already registered for the given pattern and method the error
// errRegConflict will be returned.
func (n *node) insert(method, pattern string, h Handler) error {
	var (
		cn  = n // current node
		pat = pattern
	)

Loop:
	for {
		if pat == "" {
			if cn.handlers == nil {
				cn.handlers = handlers{}
			}
			cn.pattern = pattern
			return cn.handlers.set(method, h)
		}

		// wildcard
		if pat[0] == '*' {
			name := pat[1:]
			if cn.nWildcard == nil {
				cn.nWildcard = &node{
					name:     name,
					handlers: handlers{},
				}
			} else if cn.nWildcard.name != name {
				return errVarNameConflict
			}
			cn.nWildcard.pattern = pattern
			return cn.nWildcard.handlers.set(method, h)
		}

		// variable
		if pat[0] == '{' {
			i := strings.IndexByte(pat, '}')
			if i == -1 {
				return errors.New("missing closing curly bracket '}'")
			}

			name := pat[1:i]
			if cn.nVar == nil {
				cn.nVar = &node{name: name}
			}
			if cn.nVar.name != "" && cn.nVar.name != name {
				return errVarNameConflict
			}

			pat = pat[i+1:]
			cn = cn.nVar
			continue Loop
		}

		// static
		for i, e := range cn.edges {
			if e.label != "" && e.label[0] == pat[0] {
				pl := cpl(e.label, pat)
				if pl < len(e.label) {
					// split the edge
					prefix, suffix := e.label[:pl], e.label[pl:]
					newEdge := &edge{suffix, e.node}
					newNode := node{edges: []*edge{newEdge}}
					*cn.edges[i] = edge{prefix, newNode}
				}

				pat = pat[pl:]
				cn = &e.node
				continue Loop
			}
		}

		label, vpat := splitParamPattern(pat)
		newEdge := &edge{label, node{}}
		cn.edges = append(cn.edges, newEdge)
		pat = vpat
		cn = &newEdge.node
	}

	return nil
}

// splitParamPattern splits the given pattern string just before the first occurence of a
// variable or catch-all indicator, if any, and returns the two resulting strings.
func splitParamPattern(pattern string) (string, string) {
	if i := strings.IndexByte(pattern, '{'); i != -1 {
		return pattern[:i], pattern[i:]
	}
	if i := strings.IndexByte(pattern, '*'); i != -1 {
		return pattern[:i], pattern[i:]
	}
	return pattern, ""
}

// The cpl function returns the common prefix lenght of the two arguments.
func cpl(a, b string) int {
	var i int
	for j := min(len(a), len(b)); i < j; i++ {
		if a[i] != b[i] {
			break
		}
	}
	return i
}

// The min function returns the smaller of its two arguments.
func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

type methodError struct {
	Allowed string
}

func (methodError) Error() string { return "method not found" }

// handlers is used to map HTTP methods to Handlers.
type handlers map[string]Handler

// set maps the given Handler to the given method string, the string might be a list
// of comma separated methods in which case they are split and mapped individually,
// if a Handler is already mapped to one of the methods errRegConflict will be returned,
// if any of the methods is an empty string an error will be returned.
func (hh handlers) set(method string, h Handler) error {
	ms := strings.Split(method, ",")
	for _, m := range ms {
		if m == "" {
			return errors.New("missing method")
		}
		if _, ok := hh[m]; ok {
			return errRegConflict
		}
		hh[m] = h
	}
	return nil
}

// get returns a Handler mapped to the given method, if no Handler exists for that
// method, get checks for a Handler mapped to the wildcard "*" (any method),
// if still no Handler is found get returns a methodError.
func (hh handlers) get(method string) (Handler, error) {
	if h, ok := hh[method]; ok {
		return h, nil
	}
	if h, ok := hh["*"]; ok {
		return h, nil
	}
	return nil, methodError{Allowed: hh.sortedMethods()}
}

// sortedMethods returns a string of all the handlers' methods, sorted and separated by commas.
func (hh handlers) sortedMethods() string {
	l := len(hh)
	if l == 0 {
		return ""
	}

	i := 0
	methods := make([]string, l, l)
	for m, _ := range hh {
		methods[i] = m
		i++
	}

	sort.Strings(methods)
	return strings.Join(methods, ",")
}


text:
using System;
using System.Collections.Generic;
using ESS.Framework.CQRS.Event;

namespace ESS.Domain.Foundation.EntityConfig.Events
{
    public class EntityCreated : Event
    {
        public string ModuleNo;
        public Dictionary<Guid, object> Fields;
    }
    public class EntityEdited : EntityCreated
    {

    }

    public class EntityDeleted : Event
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
package bank.interfaces;

import base.PersonAgent;

public interface BankTeller {

	public abstract void msgDeposit(BankCustomer c, int SSN, double amount);

	public abstract void msgLoan(BankCustomer c, int SSN, double amount);

	public abstract void msgPayment(BankCustomer c, int SSN, double amount);

	public abstract void msgOpen(BankCustomer c, int SSN, double amount, PersonAgent person);

	public abstract void msgRobbery(BankCustomer c, int SSN, double amount);

	//	SCHEDULER
	public abstract boolean pickAndExecuteAnAction();

	//	UTILITIES
	public abstract void addGuard(BankGuard guard);

	public abstract void setMaster(BankMasterTeller masterTeller);

	public abstract void setAccountIndex();

	public abstract void setAccounts();

	public abstract void msgLeaving();

	public abstract int getWindowNumber();

}


text:
package com.jayway.jsonpath;

import org.junit.Test;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import static com.jayway.jsonpath.JsonPath.parse;
import static java.util.Collections.emptyMap;
import static org.assertj.core.api.Assertions.assertThat;

public class WriteTest extends BaseTest {

    private static final Map<String, Object> EMPTY_MAP = emptyMap();

    @Test
    public void an_array_child_property_can_be_updated() {

        Object o = parse(JSON_DOCUMENT).set("$.store.book[*].display-price", 1).json();

        List<Integer> result = parse(o).read("$.store.book[*].display-price");

        assertThat(result).containsExactly(1, 1, 1, 1);
    }

    @Test
    public void an_root_property_can_be_updated() {

        Object o = parse(JSON_DOCUMENT).set("$.int-max-property", 1).json();

        Integer result = parse(o).read("$.int-max-property");

        assertThat(result).isEqualTo(1);
    }

    @Test
    public void an_deep_scan_can_update() {

        Object o = parse(JSON_DOCUMENT).set("$..display-price", 1).json();

        List<Integer> result = parse(o).read("$..display-price");

        assertThat(result).containsExactly(1, 1, 1, 1, 1);
    }

    @Test
    public void an_filter_can_update() {

        Object o = parse(JSON_DOCUMENT).set("$.store.book[?(@.display-price)].display-price", 1).json();

        List<Integer> result = parse(o).read("$.store.book[?(@.display-price)].display-price");

        assertThat(result).containsExactly(1, 1, 1, 1);
    }

    @Test
    public void a_path_can_be_deleted() {

        Object o = parse(JSON_DOCUMENT).delete("$.store.book[*].display-price").json();

        List<Integer> result = parse(o).read("$.store.book[*].display-price");

        assertThat(result).isEmpty();
    }

    @Test
    public void operations_can_chained() {

        Object o = parse(JSON_DOCUMENT)
                .delete("$.store.book[*].display-price")
                .set("$.store.book[*].category", "A")
                .json();

        List<Integer> prices = parse(o).read("$.store.book[*].display-price");
        List<String> categories = parse(o).read("$.store.book[*].category");

        assertThat(prices).isEmpty();
        assertThat(categories).containsExactly("A", "A", "A", "A");
    }

    @Test
    public void an_array_can_be_updated() {

        List<Integer> ints = parse("[0,1,2,3]").set("$[?(@ == 1)]", 9).json();

        assertThat(ints).containsExactly(0, 9, 2, 3);
    }

    @Test
    public void an_array_index_can_be_updated() {

        String res = parse(JSON_DOCUMENT).set("$.store.book[0]", "a").read("$.store.book[0]");

        assertThat(res).isEqualTo("a");
    }

    @Test
    public void an_array_slice_can_be_updated() {

        List<String> res = parse(JSON_DOCUMENT).set("$.store.book[0:2]", "a").read("$.store.book[0:2]");

        assertThat(res).containsExactly("a", "a");
    }

    @Test
    public void an_array_criteria_can_be_updated() {

        List<String> res = parse(JSON_DOCUMENT)
                .set("$.store.book[?(@.category == 'fiction')]", "a")
                .read("$.store.book[?(@ == 'a')]");

        assertThat(res).containsExactly("a", "a", "a");
    }

    @Test
    public void an_array_criteria_can_be_deleted() {

        List<String> res = parse(JSON_DOCUMENT)
                .delete("$.store.book[?(@.category == 'fiction')]")
                .read("$.store.book[*].category");

        assertThat(res).containsExactly("reference");
    }

    @Test
    public void multi_prop_delete() {

        List<Map<String, Object>> res = parse(JSON_DOCUMENT).delete("$.store.book[*]['author', 'category']").read("$.store.book[*]['author', 'category']");

        assertThat(res).containsExactly(EMPTY_MAP, EMPTY_MAP, EMPTY_MAP, EMPTY_MAP);
    }

    @Test
    public void multi_prop_update() {

        Map<String, Object> expected = new HashMap<String, Object>(){{
            put("author", "a");
            put("category", "a");
        }};

        List<Map<String, Object>> res = parse(JSON_DOCUMENT).set("$.store.book[*]['author', 'category']", "a").read("$.store.book[*]['author', 'category']");

        assertThat(res).containsExactly(expected, expected, expected, expected);
    }

    @Test
    public void multi_prop_update_not_all_defined() {

        Map<String, Object> expected = new HashMap<String, Object>(){{
            put("author", "a");
            put("isbn", "a");
        }};

        List<Map<String, Object>> res = parse(JSON_DOCUMENT).set("$.store.book[*]['author', 'isbn']", "a").read("$.store.book[*]['author', 'isbn']");

        assertThat(res).containsExactly(expected, expected, expected, expected);
    }

    @Test
    public void add_to_array() {
        Object res = parse(JSON_DOCUMENT).add("$.store.book", 1).read("$.store.book[4]");
        assertThat(res).isEqualTo(1);
    }

    @Test
    public void add_to_object() {
        Object res = parse(JSON_DOCUMENT).put("$.store.book[0]", "new-key", "new-value").read("$.store.book[0].new-key");
        assertThat(res).isEqualTo("new-value");
    }

    @Test
    public void item_can_be_added_to_root_array() {
        List<Integer> model = new LinkedList<Integer>();
        model.add(1);
        model.add(2);

        List<Integer> ints = parse(model).add("$", 3).read("$");

        assertThat(ints).containsExactly(1,2,3);
    }

    @Test
    public void key_val_can_be_added_to_root_object() {
        Map model = new HashMap();
        model.put("a", "a-val");

        String newVal = parse(model).put("$", "new-key", "new-val").read("$.new-key");

        assertThat(newVal).isEqualTo("new-val");
    }

    @Test(expected = InvalidModificationException.class)
    public void add_to_object_on_array() {
        parse(JSON_DOCUMENT).put("$.store.book", "new-key", "new-value");
    }

    @Test(expected = InvalidModificationException.class)
    public void add_to_array_on_object() {
        parse(JSON_DOCUMENT).add("$.store.book[0]", "new-value");
    }

    @Test(expected = InvalidModificationException.class)
    public void root_object_can_not_be_updated() {
        Map model = new HashMap();
        model.put("a", "a-val");

        parse(model).set("$[?(@.a == 'a-val')]", 1);
    }

}


text:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { ApiService } from '../shared/api.service';
import { AlbumDetail } from '../shared/types/albums';
import {LoadingPage} from '../shared/loading/loading';
// import { ProgressbarModule } from 'ng2-bootstrap/components/progressbar';

@Component({
  selector: 'abs-gallery',
  templateUrl: './gallery.component.html',
  styleUrls: ['./gallery.component.scss']
})
export class GalleryComponent extends LoadingPage implements OnInit {
  public albums: AlbumDetail[];
  private selectedAlbum: AlbumDetail;
  errorMessage: string;

  constructor(
      private apiService: ApiService,
      private router: Router
  ) {
    super(true);
  }

  getAlbums() {
    this.apiService.getAlbums()
        .subscribe(
            (ablums: any) => {
              this.ready();
              return this.albums = ablums;
            },
            error =>  this.errorMessage = <any>error);
  }

  onSelect ( album: AlbumDetail) {
    this.selectedAlbum = album;
    this.getSingleAlbum(this.selectedAlbum.id);
  }

  getSingleAlbum(albumId): void {
    this.router.navigate(['album/', albumId]);
  }

  ngOnInit() {
    this.getAlbums();
  }

}


text:
package com.opengamma.web.analytics.rest;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opengamma.id.UniqueId;
import com.opengamma.web.analytics.push.ConnectionManager;
import com.opengamma.web.analytics.push.WebPushServletContextUtils;
import com.sun.jersey.api.core.HttpContext;
import com.sun.jersey.api.model.AbstractMethod;
import com.sun.jersey.spi.container.ResourceFilter;
import com.sun.jersey.spi.container.ResourceFilterFactory;

/**
 * Creates {@link EntitySubscriptionFilter}s which create subscriptions for push notifications for changes to entities
 * requested via the REST interface.  If a REST method parameter is annotated with {@link Subscribe} it will be
 * interpreted as a {@link UniqueId} and any changes to the entity will cause an update to be pushed over
 * the long-polling HTTP interface.  The annotated parameter must be a string that can be parsed by
 * {@link UniqueId#parse(String)} and must also have a {@link PathParam} annotation.
 */
public class SubscribingFilterFactory implements ResourceFilterFactory {

  private static final Logger s_logger = LoggerFactory.getLogger(SubscribingFilterFactory.class);

  /** HTTP context injected by Jersey.  This is a proxy that always points to the context for the current request */
  @Context
  private HttpContext _httpContext;

  /** Servlet context injected by Jersey.  This is a proxy that always points to the context for the current request */
  @Context
  private ServletContext _servletContext;

  /** Request injected by Jersey.  This is a proxy that always points to the current request */
  @Context
  private HttpServletRequest _servletRequest;

  @Override
  public List<ResourceFilter> create(AbstractMethod abstractMethod) {

    if (!WebPushServletContextUtils.isConnectionManagerAvailable(_servletContext)) {
      return Collections.emptyList();
    }

    List<ResourceFilter> filters = new ArrayList<ResourceFilter>();
    ResourceFilter entityFilter = createEntitySubscriptionFilter(abstractMethod);
    if (entityFilter != null) {
      filters.add(entityFilter);
    }
    ResourceFilter masterFilter = createMasterSubscriptionFilter(abstractMethod);
    if (masterFilter != null) {
      filters.add(masterFilter);
    }
    return filters;
  }

  private ConnectionManager getUpdateManager() {
    return WebPushServletContextUtils.getConnectionManager(_servletContext);
  }

  /**
   * Creates a filter that creates a subscription for an entity when the method is invoked.  The method must have a
   * parameter annotated with {@link Subscribe} and {@link PathParam} which is a string that can be parsed by
   * {@link UniqueId#parse(String)}.  A notification is sent when the object with the specified {@link UniqueId}
   * changes.
   * @param abstractMethod A Jersey REST method
   * @return A filter to set up subscriptions when the method is invoked or null if the method doesn't
   * need entity subscriptions
   */
  private ResourceFilter createEntitySubscriptionFilter(AbstractMethod abstractMethod) {
    Method method = abstractMethod.getMethod();
    Annotation[][] annotations = method.getParameterAnnotations();
    List<String> uidParamNames = new ArrayList<String>();
    // find params annotated with @Subscribe.  must also have @PathParam
    for (Annotation[] paramAnnotations : annotations) {
      boolean subscribe = false;
      String paramName = null;
      for (Annotation annotation : paramAnnotations) {
        if (annotation instanceof Subscribe) {
          subscribe = true;
        } else if (annotation instanceof PathParam) {
          paramName = ((PathParam) annotation).value();
        }
      }
      if (subscribe) {
        if (paramName != null) {
          uidParamNames.add(paramName);
        } else {
          s_logger.warn("@Subscribe annotation found without matching @PathParam on method {}.{}(), no subscription " +
                            "will be created", method.getDeclaringClass().getSimpleName(), method.getName());
        }
      }
    }
    if (!uidParamNames.isEmpty()) {
      s_logger.debug("Creating subscribing filter for parameters {} on method {}.{}()",
                     new Object[]{uidParamNames, method.getDeclaringClass().getSimpleName(), method.getName()});
      return new EntitySubscriptionFilter(uidParamNames, getUpdateManager(), _httpContext, _servletRequest);
    } else {
      return null;
    }
  }

  /**
   * Creates a filter that creates a subscription for a master when the method is invoked.  The method must be
   * annotated with {@link SubscribeMaster}.  A notification is sent when any data in the master changes.
   * @param abstractMethod A Jersey REST method
   * @return A filter to set up subscriptions when the method is invoked or null if the method doesn't
   * need master subscriptions
   */
  private ResourceFilter createMasterSubscriptionFilter(AbstractMethod abstractMethod) {
    SubscribeMaster annotation = abstractMethod.getAnnotation(SubscribeMaster.class);
    if (annotation != null) {
      MasterType[] masterTypes = annotation.value();
      if (masterTypes.length > 0) {
        return new MasterSubscriptionFilter(getUpdateManager(), Arrays.asList(masterTypes), _httpContext, _servletRequest);
      } else {
        s_logger.warn("@SubscribeMaster annotation found on {}.{}() with no masters specified",
                      abstractMethod.getMethod().getDeclaringClass().getSimpleName(),
                      abstractMethod.getMethod().getName());
      }
    }
    return null;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using ArcGIS.Core.Data;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using System.Windows.Input;
using ArcGIS.Desktop.Catalog;
using ArcGIS.Desktop.Core;
using System.Windows.Data;
using ReplaceAttachments.Util;
using System.Threading.Tasks;

namespace ReplaceAttachments
{
    internal class AttachmentsDockpaneViewModel : DockPane
    {
        private const string _dockPaneID = "ReplaceAttachments_AttachmentsDockpane";

        private ObservableCollection<string> _layers = new ObservableCollection<string>();
        private ObservableCollection<string> _relationshipClasses = new ObservableCollection<string>();
        private ObservableCollection<string> _attachmentNames = new ObservableCollection<string>();
        private object _lockCollections = new object();
        private bool _isGoEnabled = false;

        protected AttachmentsDockpaneViewModel() {
            // when a new mapview is coming in we need to update the list of layers
            ArcGIS.Desktop.Mapping.Events.ActiveMapViewChangedEvent.Subscribe(OnMapViewChanged);

            BindingOperations.EnableCollectionSynchronization(_layers, _lockCollections);
            BindingOperations.EnableCollectionSynchronization(_relationshipClasses, _lockCollections);
            BindingOperations.EnableCollectionSynchronization(_attachmentNames, _lockCollections);
        }

        protected override Task InitializeAsync()
        {
            if (MapView.Active != null) UpdateLayers(MapView.Active.Map);
            return Task.FromResult(0);
        }

        private void OnMapViewChanged (ArcGIS.Desktop.Mapping.Events.ActiveMapViewChangedEventArgs args)
        {
            if (args.IncomingView == null) return;
            UpdateLayers(args.IncomingView.Map);
        }

        /// <summary>
        /// Show the DockPane.
        /// </summary>
        internal static void Show()
        {
            DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID);
            if (pane == null)
                return;

            pane.Activate();
        }

        /// <summary>
        /// Text shown near the top of the DockPane.
        /// </summary>
        private string _heading = "Replace Attachments for Related Feature Classes";
        public string Heading
        {
            get { return _heading; }
            set
            {
                SetProperty(ref _heading, value, () => Heading);
            }
        }

        private string _selectedLayer;
        private string _selectedRelationship;
        private string _relatedFeatureClass;
        private string oldAttachmentName;
        private string newAttachment;
        private Definition relatedFeatureClassDefinition;

        public ObservableCollection<string> Layers
        {
            get { return _layers; }
        }

        public ObservableCollection<string> RelationshipClasses
        {
            get { return _relationshipClasses; }
        }

        public ObservableCollection<string> AttachmentNames
        {
            get { return _attachmentNames; }
        }

        public string SelectedRelationship
        {
            get { return _selectedRelationship; }
            set
            {
                SetProperty(ref _selectedRelationship, value, () => SelectedRelationship);
                UpdateRelatedFeatureClass();
                UpdateIsGoEnabled();
            }
        }

        public string SelectedLayer
        {
            get { return _selectedLayer; }
            set
            {
                SetProperty(ref _selectedLayer, value, () => SelectedLayer);
                UpdateRelationshipClasses();
                UpdateIsGoEnabled();
            }
        }

        public bool IsGoEnabled
        {
            get { return _isGoEnabled; }
            set
            {
                SetProperty(ref _isGoEnabled, value, () => IsGoEnabled);
            }
        }
        public string RelatedFeatureClass
        {
            get { return _relatedFeatureClass; }
            set
            {
                SetProperty(ref _relatedFeatureClass, value, () => RelatedFeatureClass);
                QueuedTask.Run(() =>
                {
                    lock (_lockCollections) _attachmentNames.Clear();
                    using (Table table = (MapView.Active.Map.Layers.First(layer => layer.Name.Equals(SelectedLayer)) as FeatureLayer).GetTable())
                    {
                        if (!table.IsAttachmentEnabled()) return;
                        Geodatabase geodatabase = null;
                        if (table != null && table.GetDatastore() is Geodatabase)
                            geodatabase = table.GetDatastore() as Geodatabase;
                        if (geodatabase == null) return;

                        if (_relatedFeatureClass == null) return;
                        Table relatedTable = geodatabase.OpenDataset<Table>(_relatedFeatureClass);
                        if (relatedTable == null) return;

                        using (RowCursor rowCursor = table.Search(null, false))
                        {
                            while (rowCursor.MoveNext())
                            {
                                using (Row row = rowCursor.Current)
                                {
                                    IEnumerable<Attachment> attachments = row.GetAttachments(null, true);
                                    foreach (Attachment attachment in attachments)
                                    {
                                        lock (_lockCollections)
                                        {
                                            _attachmentNames.Add(attachment.GetName());
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }

        public string OldAttachmentName
        {
            get { return oldAttachmentName; }
            set
            {
                SetProperty(ref oldAttachmentName, value, () => OldAttachmentName);
                UpdateIsGoEnabled();
            }
        }
        public string NewAttachment
        {
            get { return newAttachment; }
            set
            {
                SetProperty(ref newAttachment, value, () => NewAttachment);
                UpdateIsGoEnabled();
            }
        }

        private ICommand _goReplaceAttachment = null;
        public ICommand GoReplaceAttachment
        {
            get
            {
                if (_goReplaceAttachment == null) _goReplaceAttachment = new RelayCommand(Work, () => true);
                return _goReplaceAttachment;
            }
        }

        private ICommand _selectPath = null;
        public ICommand SelectPath
        {
            get
            {
                if (_selectPath == null) _selectPath = new RelayCommand(GetPath, () => true);
                return _selectPath;
            }
        }

        private void GetPath(object param)
        {
            OpenItemDialog pathDialog = new OpenItemDialog();
            pathDialog.Title = "Select Path to attachment";
            pathDialog.InitialLocation = @"C:\Data\";
            pathDialog.MultiSelect = false;
            pathDialog.Filter = ItemFilters.Rasters;

            bool? ok = pathDialog.ShowDialog();

            if (ok == true)
            {
                IEnumerable<Item> selectedItems = pathDialog.Items;
                foreach (Item selectedItem in selectedItems)
                    NewAttachment = selectedItem.Path;
            }
        }

        /// <summary>
        /// Given that
        /// 1. A layer has been selected
        /// 2. A RelationshipClass has been selected
        /// 3. The Table/FeatureClass related to the Table/FeatureClass corresponding to the layer selected has Attachments enabled
        ///
        /// Then, this method will
        /// 1. Get all the rows of the Related Table/FeatureClass
        /// 2. Find if any row has Attachments which have the same name as the value of "OldAttachmentName"
        /// 3. Replace the Attachment Data for the matching Attachments with the Data corresponding to "NewAttachment"
        /// </summary>
        private void Work(object param)
        {
             QueuedTask.Run(() =>
             {
                 using (Table table = (MapView.Active.Map.Layers.First(layer => layer.Name.Equals(SelectedLayer)) as FeatureLayer).GetTable())
                 {
                     if (!table.IsAttachmentEnabled()) return;

                     Geodatabase geodatabase = null;
                     if (table != null && table.GetDatastore() is Geodatabase)
                         geodatabase = table.GetDatastore() as Geodatabase;
                     if (geodatabase == null) return;

                     if (_relatedFeatureClass == null) return;
                     Table relatedTable = geodatabase.OpenDataset<Table>(_relatedFeatureClass);
                     if (relatedTable == null) return;

                     if (String.IsNullOrEmpty(OldAttachmentName)) return;
                     if (String.IsNullOrEmpty(NewAttachment) || !File.Exists(NewAttachment)) return;

                     using (MemoryStream newAttachmentMemoryStream = CreateMemoryStreamFromContentsOf(NewAttachment))
                     {
                         using (RowCursor rowCursor = table.Search(null, false))
                         {
                             while (rowCursor.MoveNext())
                             {
                                 using (Row row = rowCursor.Current)
                                 {
                                     IEnumerable<Attachment> attachments = row.GetAttachments(null, true).Where(attachment => attachment.GetName().Equals(oldAttachmentName));
                                     foreach (Attachment attachment in attachments)
                                     {
                                         attachment.SetData(newAttachmentMemoryStream);
                                         row.UpdateAttachment(attachment);
                                     }
                                 }
                             }
                         }
                     }
                 }
             });
        }

        private async void UpdateIsGoEnabled()
        {
            IsGoEnabled = await QueuedTask.Run(() =>
            {
                bool isGoEnabled = false;
                using (Table table = (MapView.Active.Map.Layers.First(layer => layer.Name.Equals(SelectedLayer)) as FeatureLayer).GetTable())
                {
                    if (!table.IsAttachmentEnabled()) return isGoEnabled;

                    Geodatabase geodatabase = null;
                    if (table != null && table.GetDatastore() is Geodatabase)
                        geodatabase = table.GetDatastore() as Geodatabase;
                    if (geodatabase == null) return isGoEnabled;

                    if (_relatedFeatureClass == null) return isGoEnabled;
                    Table relatedTable = geodatabase.OpenDataset<Table>(_relatedFeatureClass);
                    if (relatedTable == null) return isGoEnabled;

                    if (String.IsNullOrEmpty(OldAttachmentName)) return isGoEnabled;
                    if (String.IsNullOrEmpty(NewAttachment) || !File.Exists(NewAttachment)) return isGoEnabled;
                    isGoEnabled = true;
                }
                return isGoEnabled;
            });
        }

        /// <summary>
        /// This method will populate the Layers (bound to the LayersComboBox) with all the Feature Layers present in the Active Map View
        /// </summary>
        public void UpdateLayers(Map map)
        {
            lock (_lockCollections)
            {
                _layers.Clear();
                _layers.AddRange(new ObservableCollection<string>(map.Layers.Where(layer => layer is FeatureLayer).Select(layer => layer.Name)));
            }
        }

        /// <summary>
        /// Given that a Layer has been selected, this method will populate the RelationshipClasses (bound to RelationshipClasses Combobox) with the names of the RelationshipClasses
        /// in which the FeatureClass/Table corresponding to the selected layer participates (as Origin or Destination)
        /// </summary>
        public void UpdateRelationshipClasses()
        {
            QueuedTask.Run(() =>
            {
                lock (_lockCollections) _relationshipClasses.Clear();
                using (Table table = (MapView.Active.Map.Layers.First(layer => layer.Name.Equals(SelectedLayer)) as FeatureLayer).GetTable())
                {
                    Geodatabase geodatabase = null;
                    if (table != null && table.GetDatastore() is Geodatabase)
                        geodatabase = table.GetDatastore() as Geodatabase;
                    if (geodatabase == null) return;
                    IReadOnlyList<RelationshipClassDefinition> relationshipClassDefinitions = geodatabase.GetDefinitions<RelationshipClassDefinition>();
                    IEnumerable<RelationshipClassDefinition> relavantRelationshipClassDefns = relationshipClassDefinitions.Where(definition =>
                                                                                definition.GetOriginClass().Contains(table.GetName()) ||
                                                                                definition.GetDestinationClass().Contains(table.GetName()));
                    IEnumerable<string> relationshipClassNames = relavantRelationshipClassDefns.Select(definition => definition.GetName());
                    lock (_lockCollections) _relationshipClasses.AddRange(new ObservableCollection<string>(relationshipClassNames));
                }
            });
        }

        /// <summary>
        /// Given that the RelationshipClass is selected, this method will
        /// 1. Get the Definitions of Datasets related by the selected relationship class
        /// 2. Set the RelatedFeatureClass property to the Table/FeatureClass which is related to the FeatureClass corresponding to the selected layer
        /// </summary>
        public void UpdateRelatedFeatureClass()
        {
            QueuedTask.Run(() =>
            {
                using (Table table = (MapView.Active.Map.Layers.First(layer => layer.Name.Equals(SelectedLayer)) as FeatureLayer).GetTable())
                {
                    Geodatabase geodatabase = null;
                    if (table != null && table.GetDatastore() is Geodatabase)
                        geodatabase = table.GetDatastore() as Geodatabase;
                    if (geodatabase == null) return;
                    if(SelectedRelationship == null) return;
                    IReadOnlyList<Definition> relatedDefinitions = geodatabase.GetRelatedDefinitions(geodatabase.GetDefinition<RelationshipClassDefinition>(SelectedRelationship),
                                                                                DefinitionRelationshipType.DatasetsRelatedThrough);
                    relatedFeatureClassDefinition = relatedDefinitions.First(definition => definition.GetName() != table.GetDefinition().GetName());
                    RelatedFeatureClass = relatedFeatureClassDefinition.GetName();
                }
            });
        }

        /// <summary>
        /// This is a helper method to generate a memory stream from a a file
        /// </summary>
        /// <param name="fileNameWithPath"></param>
        /// <returns>Memory Stream representing the File</returns>
        private static MemoryStream CreateMemoryStreamFromContentsOf(String fileNameWithPath)
        {
            MemoryStream memoryStream;
            using (memoryStream = new MemoryStream())
            using (FileStream file = new FileStream(fileNameWithPath, FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[file.Length];
                file.Read(bytes, 0, (int)file.Length);
                memoryStream.Write(bytes, 0, (int)file.Length);
            }
            return memoryStream;
        }
    }

    /// <summary>
    /// Button implementation to show the DockPane.
    /// </summary>
    internal class AttachmentsDockpane_ShowButton : Button
    {
        protected override void OnClick()
        {
            AttachmentsDockpaneViewModel.Show();
        }
    }
}


text:
<Alloy>
	<!-- UI deferred to login or home, check index.js -->
	<Window platform="!ios">
		<Label>This test app is only supported on iOS</Label>
	</Window>
</Alloy>


text:
using System;

using Microsoft.VisualStudio.TestTools.UnitTesting;

using AM.Reflection;

namespace UnitTests.AM.Reflection
{
    [TestClass]
    public class PropertyAccessorTest
    {
        private CanaryClass canary;

        private PropertyAccessor<CanaryClass, bool> booleanAccessor;
        private PropertyAccessor<CanaryClass, int> int32Accessor;
        private PropertyAccessor<CanaryClass, string> stringAccessor;

        [TestInitialize]
        public void Setup ()
        {
            canary = new CanaryClass
            {
                BooleanProperty = true,
                Int32Property = 123,
                StringProperty = "Hello"
            };

            booleanAccessor = new PropertyAccessor<CanaryClass, bool>
                    (
                        canary,
                        "BooleanProperty"
                    );
            int32Accessor = new PropertyAccessor<CanaryClass, int>
                    (
                        canary,
                        "Int32Property"
                    );
            stringAccessor = new PropertyAccessor<CanaryClass, string>
                    (
                        canary,
                        "StringProperty"
                    );
        }

        [TestMethod]
        public void PropertyAccessor_Get_Set_1()
        {
            Assert.AreEqual("BooleanProperty", booleanAccessor.Name);
            Assert.AreEqual("Int32Property", int32Accessor.Name);
            Assert.AreEqual("StringProperty", stringAccessor.Name);

            bool actualBoolean = booleanAccessor.Value;
            Assert.AreEqual(canary.BooleanProperty, actualBoolean);

            int actualInt32 = int32Accessor.Value;
            Assert.AreEqual(canary.Int32Property, actualInt32);

            string actualString = stringAccessor.Value;
            Assert.AreEqual(canary.StringProperty, actualString);

            booleanAccessor.Value = false;
            Assert.AreEqual(false, canary.BooleanProperty);

            int32Accessor.Value = 1234;
            Assert.AreEqual(1234, canary.Int32Property);

            stringAccessor.Value = "World";
            Assert.AreEqual("World", canary.StringProperty);
        }

        [TestMethod]
        [ExpectedException(typeof(NotSupportedException))]
        public void PropertyAccessor_Set_1()
        {
            PropertyAccessor<CanaryClass, int> accessor
                = new PropertyAccessor<CanaryClass, int>(canary, "NoSetterProperty");
            accessor.Value = 321;
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void PropertyAccessor_Construction_1()
        {
            PropertyAccessor<CanaryClass, bool> wrongAccessor
                = new PropertyAccessor<CanaryClass, bool>
                    (
                        canary,
                        "NonexistentProperty"
                    );
            Assert.AreEqual("NonexistentProperty", wrongAccessor.Name);
        }

        [TestMethod]
        public void PropertyAccessor_Events_1()
        {
            bool booleanGet = false, booleanSet = false;
            booleanAccessor.GettingValue += (target, value) => { booleanGet = true; };
            booleanAccessor.SettingValue += (target, value) => { booleanSet = true; };
            booleanAccessor.Value = !booleanAccessor.Value;
            Assert.IsTrue(booleanGet);
            Assert.IsTrue(booleanSet);

            bool int32Get = false, int32Set = false;
            int32Accessor.GettingValue += (target, value) => { int32Get = true; };
            int32Accessor.SettingValue += (target, value) => { int32Set = true; };
            int32Accessor.Value = int32Accessor.Value * 2;
            Assert.IsTrue(int32Get);
            Assert.IsTrue(int32Set);

            bool stringGet = false, stringSet = false;
            stringAccessor.GettingValue += (target, value) => { stringGet = true; };
            stringAccessor.SettingValue += (target, value) => { stringSet = true; };
            stringAccessor.Value = stringAccessor.Value + "World";
            Assert.IsTrue(stringGet);
            Assert.IsTrue(stringSet);
        }

        [TestMethod]
        public void PropertyAccessor_SetTarget_1()
        {
            CanaryClass newCanary = new CanaryClass
            {
                BooleanProperty = false
            };
            bool flag = false;
            booleanAccessor.TargetChanged += (accessor, target) =>
            {
                flag = true;
            };
            booleanAccessor.SetTarget(newCanary);
            Assert.IsTrue(flag);

            flag = false;
            booleanAccessor.SetTarget(canary);
            Assert.IsTrue(flag);
        }
    }
}


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

<TITLE>
Uses of Class org.hibernate.engine.EntityKey (Hibernate API Documentation)
</TITLE>

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.hibernate.engine.EntityKey

Packages that use EntityKey

org.hibernate.action

	This package defines "actions" that are scheduled for
	asycnchronous execution by the event listeners.

org.hibernate.engine

	This package contains classes that are "shared" by other packages,
	and implementations of some key algorithms.

org.hibernate.event.def

	This package defines a default set of event listeners that
	implements the default behaviors of Hibernate.

org.hibernate.impl

	This package contains implementations of the
	central Hibernate APIs, especially the
	Hibernate session.

Uses of EntityKey in org.hibernate.action

Methods in org.hibernate.action that return EntityKey

 EntityKey
EntityIdentityInsertAction.getDelayedEntityKey()

Uses of EntityKey in org.hibernate.engine

Methods in org.hibernate.engine with parameters of type EntityKey

static void
TwoPhaseLoad.addUninitializedEntity(EntityKey key,
                       Object object,
                       EntityPersister persister,
                       LockMode lockMode,
                       boolean lazyPropertiesAreUnfetched,
                       SessionImplementor session)

          Add an uninitialized instance of an entity class, as a placeholder to ensure object
 identity.

static void
TwoPhaseLoad.addUninitializedCachedEntity(EntityKey key,
                             Object object,
                             EntityPersister persister,
                             LockMode lockMode,
                             boolean lazyPropertiesAreUnfetched,
                             Object version,
                             SessionImplementor session)

 Object[]
StatefulPersistenceContext.getCachedDatabaseSnapshot(EntityKey key)

 void
StatefulPersistenceContext.addEntity(EntityKey key,
          Object entity)

 Object
StatefulPersistenceContext.getEntity(EntityKey key)

          Get the entity instance associated with the given
 <tt>EntityKey</tt>

 boolean
StatefulPersistenceContext.containsEntity(EntityKey key)

 Object
StatefulPersistenceContext.removeEntity(EntityKey key)

          Remove an entity from the session cache, also clear
 up other state associated with the entity, all except
 for the <tt>EntityEntry</tt>

 EntityEntry
StatefulPersistenceContext.addEntity(Object entity,
          Status status,
          Object[] loadedState,
          EntityKey entityKey,
          Object version,
          LockMode lockMode,
          boolean existsInDatabase,
          EntityPersister persister,
          boolean disableVersionIncrement,
          boolean lazyPropertiesAreUnfetched)

          Adds an entity to the internal caches.

 void
StatefulPersistenceContext.checkUniqueness(EntityKey key,
                Object object)

          Attempts to check whether the given key represents an entity already loaded within the
 current session.

 Object
StatefulPersistenceContext.narrowProxy(Object proxy,
            EntityPersister persister,
            EntityKey key,
            Object object)

          If the existing proxy is insufficiently "narrow" (derived), instantiate a new proxy
 and overwrite the registration of the old one.

 Object
StatefulPersistenceContext.proxyFor(EntityPersister persister,
         EntityKey key,
         Object impl)

          Return the existing proxy associated with the given <tt>EntityKey</tt>, or the
 third argument (the entity associated with the key) if no proxy exists.

 Object
StatefulPersistenceContext.getProxy(EntityKey key)

          Get an existing proxy by key

 void
StatefulPersistenceContext.addProxy(EntityKey key,
         Object proxy)

          Add a proxy to the session cache

 Object
StatefulPersistenceContext.removeProxy(EntityKey key)

          Remove a proxy from the session cache

 void
StatefulPersistenceContext.addNullProperty(EntityKey ownerKey,
                String propertyName)

          Record the fact that the association belonging to the keyed
 entity is null.

 boolean
StatefulPersistenceContext.isPropertyNull(EntityKey ownerKey,
               String propertyName)

          Is the association property belonging to the keyed entity null?

 void
StatefulPersistenceContext.replaceDelayedEntityIdentityInsertKeys(EntityKey oldKey,
                                       Serializable generatedId)

 Object
SessionImplementor.getEntityUsingInterceptor(EntityKey key)

          Get the entity instance associated with the given <tt>Key</tt>,
 calling the Interceptor if necessary

 Object[]
PersistenceContext.getCachedDatabaseSnapshot(EntityKey key)

 void
PersistenceContext.addEntity(EntityKey key,
          Object entity)

          Add a canonical mapping from entity key to entity instance

 Object
PersistenceContext.getEntity(EntityKey key)

          Get the entity instance associated with the given
 <tt>EntityKey</tt>

 boolean
PersistenceContext.containsEntity(EntityKey key)

          Is there an entity with the given key in the persistence context

 Object
PersistenceContext.removeEntity(EntityKey key)

          Remove an entity from the session cache, also clear
 up other state associated with the entity, all except
 for the <tt>EntityEntry</tt>

 EntityEntry
PersistenceContext.addEntity(Object entity,
          Status status,
          Object[] loadedState,
          EntityKey entityKey,
          Object version,
          LockMode lockMode,
          boolean existsInDatabase,
          EntityPersister persister,
          boolean disableVersionIncrement,
          boolean lazyPropertiesAreUnfetched)

          Adds an entity to the internal caches.

 void
PersistenceContext.checkUniqueness(EntityKey key,
                Object object)

          Attempts to check whether the given key represents an entity already loaded within the
 current session.

 Object
PersistenceContext.narrowProxy(Object proxy,
            EntityPersister persister,
            EntityKey key,
            Object object)

          If the existing proxy is insufficiently "narrow" (derived), instantiate a new proxy
 and overwrite the registration of the old one.

 Object
PersistenceContext.proxyFor(EntityPersister persister,
         EntityKey key,
         Object impl)

          Return the existing proxy associated with the given <tt>EntityKey</tt>, or the
 third argument (the entity associated with the key) if no proxy exists.

 Object
PersistenceContext.getProxy(EntityKey key)

          Get an existing proxy by key

 void
PersistenceContext.addProxy(EntityKey key,
         Object proxy)

          Add a proxy to the session cache

 Object
PersistenceContext.removeProxy(EntityKey key)

          Remove a proxy from the session cache

 void
PersistenceContext.addNullProperty(EntityKey ownerKey,
                String propertyName)

          Record the fact that the association belonging to the keyed
 entity is null.

 boolean
PersistenceContext.isPropertyNull(EntityKey ownerKey,
               String propertyName)

          Is the association property belonging to the keyed entity null?

 void
PersistenceContext.replaceDelayedEntityIdentityInsertKeys(EntityKey oldKey,
                                       Serializable generatedId)

 SubselectFetch
BatchFetchQueue.getSubselect(EntityKey key)

          Retrieve the fetch descriptor associated with the given entity key.

 void
BatchFetchQueue.addSubselect(EntityKey key,
             SubselectFetch subquery)

          Adds a subselect fetch decriptor for the given entity key.

 void
BatchFetchQueue.removeSubselect(EntityKey key)

          After evicting or deleting an entity, we don't need to
 know the query that was used to load it anymore (don't
 call this after loading the entity, since we might still
 need to load its collections)

 void
BatchFetchQueue.addBatchLoadableEntityKey(EntityKey key)

          If an EntityKey represents a batch loadable entity, add
 it to the queue.

 void
BatchFetchQueue.removeBatchLoadableEntityKey(EntityKey key)

          After evicting or deleting or loading an entity, we don't
 need to batch fetch it anymore, remove it from the queue
 if necessary

Uses of EntityKey in org.hibernate.event.def

Methods in org.hibernate.event.def with parameters of type EntityKey

protected  Object
DefaultLoadEventListener.load(LoadEvent event,
     EntityPersister persister,
     EntityKey keyToLoad,
     LoadEventListener.LoadType options)

          Perfoms the load of an entity.

protected  Object
DefaultLoadEventListener.proxyOrLoad(LoadEvent event,
            EntityPersister persister,
            EntityKey keyToLoad,
            LoadEventListener.LoadType options)

          Based on configured options, will either return a pre-existing proxy,
 generate a new proxy, or perform an actual load.

protected  Object
DefaultLoadEventListener.lockAndLoad(LoadEvent event,
            EntityPersister persister,
            EntityKey keyToLoad,
            LoadEventListener.LoadType options,
            SessionImplementor source)

          If the class to be loaded has been configured with a cache, then lock
 given id in that cache and then perform the load.

protected  Object
DefaultLoadEventListener.doLoad(LoadEvent event,
       EntityPersister persister,
       EntityKey keyToLoad,
       LoadEventListener.LoadType options)

          Coordinates the efforts to load a given entity.

protected  Object
DefaultLoadEventListener.loadFromDatasource(LoadEvent event,
                   EntityPersister persister,
                   EntityKey keyToLoad,
                   LoadEventListener.LoadType options)

          Performs the process of loading an entity from the configured
 underlying datasource.

protected  Object
DefaultLoadEventListener.loadFromSessionCache(LoadEvent event,
                     EntityKey keyToLoad,
                     LoadEventListener.LoadType options)

          Attempts to locate the entity in the session-level cache.

protected  void
DefaultEvictEventListener.doEvict(Object object,
        EntityKey key,
        EntityPersister persister,
        EventSource session)

protected  Serializable
AbstractSaveEventListener.performSaveOrReplicate(Object entity,
                       EntityKey key,
                       EntityPersister persister,
                       boolean useIdentityColumn,
                       Object anything,
                       EventSource source,
                       boolean requiresImmediateIdAccess)

          Performs all the actual work needed to save an entity (well to get the save moved to
 the execution queue).

Uses of EntityKey in org.hibernate.impl

Methods in org.hibernate.impl with parameters of type EntityKey

 Object
StatelessSessionImpl.getEntityUsingInterceptor(EntityKey key)

 Object
SessionImpl.getEntityUsingInterceptor(EntityKey key)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
namespace chromeos {

class ClockMenuButton;
class InputMethodMenuButton;
class NetworkMenuButton;
class PowerMenuButton;
class StatusAreaHost;
class WindowSwitcherButton;

// This class is used to wrap the small informative widgets in the upper-right
// of the window title bar. It is used on ChromeOS only.
class StatusAreaView : public AccessiblePaneView {
 public:
  explicit StatusAreaView(StatusAreaHost* host);
  virtual ~StatusAreaView() {}

  virtual void Init();
  void MakeButtonsActive(bool active);

  // views::View* overrides.
  virtual gfx::Size GetPreferredSize();
  virtual void Layout();
  virtual void ChildPreferredSizeChanged(View* child);

  ClockMenuButton* clock_view() { return clock_view_; }
  InputMethodMenuButton* input_method_view() { return input_method_view_; }
  NetworkMenuButton* network_view() { return network_view_; }
  PowerMenuButton* power_view() { return power_view_; }
  WindowSwitcherButton* window_switcher_view() {
    return window_switcher_view_;
  }

 private:
  StatusAreaHost* host_;

  ClockMenuButton* clock_view_;
  InputMethodMenuButton* input_method_view_;
  NetworkMenuButton* network_view_;
  PowerMenuButton* power_view_;
  WindowSwitcherButton* window_switcher_view_;

  DISALLOW_COPY_AND_ASSIGN(StatusAreaView);
};

}  // namespace chromeos

#endif  // CHROME_BROWSER_CHROMEOS_STATUS_STATUS_AREA_VIEW_H_


text:
/*
  eslint-disable
  no-unused-expressions,
  prefer-arrow-callback,
  import/no-extraneous-dependencies,
  func-names,
  no-tabs
 */

import chai from "chai";
import request from "supertest";
import faker from "faker";
import stoppable from "stoppable";
import createServer from "../../server/server";
import db from "../../server/database/db";
import { global } from "../../server/database/sql/sql";
import { addUser } from "../../server/api/services/users";
import { addReview } from "../../server/api/services/reviews";
import addCategories from "../../server/seeder/database/categoriesTableSeeder";
import { addProduct } from "../../server/api/services/products";
import invalidReview from "../../server/errors/api/reviewErrors";
import { unauthorizedAccess } from "../../server/errors/api/authorizationErrors";
import { userDoesNotExist } from "../../server/errors/api/userErrors";
import {
  dataNotFound,
  invalidId
} from "../../server/errors/api/controllerErrors";
import { getUser } from "../../server/seeder/database/usersTableSeeder";
import { createJwt } from "../../server/api/services/authentication";
import { cleanAllPreviouslyCreatedImages } from "../../server/seeder/filesystem/productsImagesSeeder";

chai.should();

let server = {};

const product = {
  name: "Ray Ban sunglasses",
  description: "Good as new, original Ray Ban sunglasses",
  category: "Accessories",
  price: 50,
  images: [
    `data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAeAB4AAD/2wBDAAcFBQYFBAcGBQYIBwcIChE
			LCgkJChUPEAwRGBUaGRgVGBcbHichGx0lHRcYIi4iJSgpKywrGiAvMy8qMicqKyr/2wBDAQcICAoJCh
			QLCxQqHBgcKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKir/w
			AARCAAXAB0DASIAAhEBAxEB/8QAGQAAAgMBAAAAAAAAAAAAAAAAAAUBAwQG/8QAIxAAAQMFAAICAwAA
			AAAAAAAAAQACEQMEEiExQVETImGRof/EABgBAAMBAQAAAAAAAAAAAAAAAAIDBgEF/8QAHREAAgICAwE
			AAAAAAAAAAAAAAAECAwQRBRJRQf/aAAwDAQACEQMRAD8AQNP7mIVr3wzsQFly+pJaOQ3flUV7ks1Oz0
			KZS2ccLq4AbA9SYS+pfMJGR/qmvXIBLRr17SmrlUdJdj+I4nxrTB6nW4yMna1KxXtOSXP5HR4QhJRov
			rAfIcSYIiUnurksuXMDSIjYPUIVLweLTlXyhdHaUd/fV4Gf/9k=`,

    `data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAeAB4AAD/2wBDAAcFBQYFBAcGBQYIBwcIChE
			LCgkJChUPEAwRGBUaGRgVGBcbHichGx0lHRcYIi4iJSgpKywrGiAvMy8qMicqKyr/2wBDAQcICAoJCh
			QLCxQqHBgcKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKir/w
			AARCAAXAB0DASIAAhEBAxEB/8QAGQAAAgMBAAAAAAAAAAAAAAAAAAUBAwQG/8QAIxAAAQMFAAICAwAA
			AAAAAAAAAQACEQMEEiExQVETImGRof/EABgBAAMBAQAAAAAAAAAAAAAAAAIDBgEF/8QAHREAAgICAwE
			AAAAAAAAAAAAAAAECAwQRBRJRQf/aAAwDAQACEQMRAD8AQNP7mIVr3wzsQFly+pJaOQ3flUV7ks1Oz0
			KZS2ccLq4AbA9SYS+pfMJGR/qmvXIBLRr17SmrlUdJdj+I4nxrTB6nW4yMna1KxXtOSXP5HR4QhJRov
			rAfIcSYIiUnurksuXMDSIjYPUIVLweLTlXyhdHaUd/fV4Gf/9k=`
  ]
};

const generateReviewData = () => {
  let usersData = {};

  return Promise.all([addUser(getUser()), addUser(getUser())])
    .then(([sourceUser, targetUser]) => {
      usersData = {
        source: {
          user: sourceUser,
          token: createJwt(sourceUser)
        },
        target: {
          user: targetUser,
          token: createJwt(targetUser)
        }
      };
    })
    .then(() =>
      addProduct({
        ...product,
        owner: usersData.target.user.id
      })
    )
    .then(data => ({
      ...usersData,
      productId: data.id
    }));
};

const addRandomReview = () =>
  generateReviewData().then(({ source, target, productId }) =>
    addReview({
      rating: 5,
      description: faker.lorem.sentences(),
      sourceId: source.user.id,
      targetId: target.user.id,
      productId
    })
  );

describe("Reviews", function() {
  beforeEach(function() {
    return cleanAllPreviouslyCreatedImages()
      .then(() => db.none(global.truncateAll))
      .then(() => addCategories())
      .then(() => {
        server = stoppable(createServer(5000), 0);
      });
  });

  afterEach(function() {
    return cleanAllPreviouslyCreatedImages()
      .then(() => db.none(global.truncateAll))
      .then(() => server.stop());
  });

  describe("GET /reviews/:userId", function() {
    it("should get the user reviews", function() {
      return addRandomReview()
        .then(({ target_id }) =>
          request(server)
            .get(`/api/reviews/${target_id}`)
            .expect(200)
        )
        .then(response => {
          const reviews = response.body;
          const review = response.body[0];

          reviews.should.be.instanceOf(Array);
          reviews.should.not.be.empty;

          review.should.include.all.keys([
            "id",
            "rating",
            "description",
            "sourceId",
            "targetId",
            "productId"
          ]);
        });
    });

    it("should show only selected fields", function() {
      const selectedFields = ["rating", "sourceId", "targetId"];

      return addRandomReview()
        .then(({ target_id }) =>
          request(server)
            .get(`/api/reviews/${target_id}`)
            .query({
              fields: selectedFields.join()
            })
            .expect(200)
        )
        .then(response => {
          const review = response.body[0];

          review.should.have.all.deep.keys(selectedFields);
        });
    });

    it("should embed included users", function() {
      const source = "source";
      const target = "target";

      return addRandomReview()
        .then(({ target_id }) =>
          request(server)
            .get(`/api/reviews/${target_id}`)
            .query({
              include: [source, target].join()
            })
            .expect(200)
        )
        .then(response => {
          const review = response.body[0];

          review.should.have.property(source);
          review.should.have.property(target);
        });
    });

    it("should embed included product", function() {
      return addRandomReview()
        .then(({ target_id }) =>
          request(server)
            .get(`/api/reviews/${target_id}`)
            .query({
              include: "product"
            })
            .expect(200)
        )
        .then(response => {
          const review = response.body[0];

          review.should.have.property("product");

          const { product: reviewedProduct } = review;

          reviewedProduct.should.include.all.keys([
            "id",
            "name",
            "images",
            "owner",
            "description",
            "category",
            "createdAt",
            "price",
            "latitude",
            "longitude",
            "sold"
          ]);
        });
    });

    it("should fail when the user id is not valid", function() {
      const userId = undefined;

      return request(server)
        .get(`/api/reviews/${userId}`)
        .expect(400)
        .then(response => {
          const error = response.body[0];

          error.should.be.deep.equal(invalidId());
        });
    });
    it("should fail if there's no user with the given id", function() {
      return request(server)
        .get(`/api/reviews/${faker.random.uuid()}`)
        .expect(404);
    });
  });

  describe("POST /reviews", function() {
    it("should add a new review", function() {
      return generateReviewData()
        .then(({ source, target, productId }) => {
          const {
            user: { id: buyerId },
            token
          } = source;
          const {
            user: { id: sellerId }
          } = target;

          return request(server)
            .post("/api/reviews")
            .set("Authorization", `Bearer ${token}`)
            .send({
              sourceId: buyerId,
              targetId: sellerId,
              rating: 4,
              description: "Good seller, product in good condition",
              productId
            })
            .expect(201)
            .expect("Location", `/api/reviews/${sellerId}`);
        })
        .then(response => {
          const review = response.body;

          review.should.include.all.keys([
            "id",
            "rating",
            "description",
            "sourceId",
            "targetId",
            "productId"
          ]);
        });
    });

    it("should fail when no data has been sent", function() {
      return generateReviewData()
        .then(({ source }) => {
          const { token } = source;

          return request(server)
            .post("/api/reviews")
            .set("Authorization", `Bearer ${token}`)
            .expect(400);
        })
        .then(response => {
          const error = response.body[0];

          error.should.be.deep.equal(dataNotFound("body"));
        });
    });

    it("should fail when invalid data has been sent", function() {
      return generateReviewData()
        .then(({ source, productId }) => {
          const {
            user: { id: buyerId },
            token
          } = source;

          return request(server)
            .post("/api/reviews")
            .set("Authorization", `Bearer ${token}`)
            .send({
              sourceId: buyerId,
              targetId: "Invalid seller",
              rating: "A rating",
              description: "Good seller",
              productId
            })
            .expect(400);
        })
        .then(response => {
          const errors = response.body;
          const ratingError = invalidReview("rating", "should be integer");
          const targetError = invalidReview(
            "targetId",
            'should match format "uuid"'
          );

          errors.should.be.instanceOf(Array);
          errors.should.not.be.empty;

          errors.should.deep.include.members([ratingError, targetError]);
        });
    });

    it("should fail when no token has been sent", function() {
      return request(server)
        .post("/api/reviews")
        .expect(401)
        .then(response => {
          const error = response.body[0];

          error.should.be.deep.equal(unauthorizedAccess());
        });
    });

    it("should fail when token is valid but the user can't be found", function() {
      const validTokenForNonExistentUser = createJwt(
        getUser({ id: faker.random.uuid() })
      );

      return request(server)
        .post("/api/reviews")
        .set("Authorization", `Bearer ${validTokenForNonExistentUser}`)
        .expect(404)
        .then(response => {
          const error = response.body[0];

          error.should.be.deep.equal(userDoesNotExist());
        });
    });

    it("should fail when the token user is not the one to write the review", function() {
      return generateReviewData()
        .then(({ source, target, productId }) => {
          const { token } = source;
          const {
            user: { id: sellerId }
          } = target;

          return request(server)
            .post("/api/reviews")
            .set("Authorization", `Bearer ${token}`)
            .send({
              targetId: sellerId,
              sourceId: faker.random.uuid(),
              rating: 4,
              description: "Good seller, product in good condition",
              productId
            })
            .expect(401);
        })
        .then(response => {
          const error = response.body[0];

          error.should.be.deep.equal(unauthorizedAccess());
        });
    });
  });
});


text:
package sigterms

import java.lang.reflect.Constructor
import scala.reflect.internal.util.ScalaClassLoader
import scala.tools.nsc.util.Exceptional, Exceptional.unwrap
import scala.util.Random

import java.lang.reflect.{ Method, Proxy, InvocationHandler }

object Util {
  def nameAndArity(m: Method) = (m.getName, m.getParameterTypes.size)
  def allInterfaces(cl: Class[_]): List[Class[_]] =
    if (cl == null) Nil
    else cl.getInterfaces.toList ++ allInterfaces(cl.getSuperclass) distinct
}

/** A class representing a single method call.  It is primarily for use
  *  in tandem with Mock.  If the invocation did not target an InvocationHandler,
  *  proxy will be null.
  */
class Invoked private (val proxy: AnyRef, val m: Method, val args: List[AnyRef]) {
  def name                 = m.getName
  def arity                = m.getParameterTypes.size
  def returnType           = m.getReturnType
  def returns[T: Manifest] = returnType == manifest[T].erasure

  def invokeOn(target: AnyRef) = m.invoke(target, args: _*)
  def isObjectMethod = Set("toString", "equals", "hashCode") contains name

  override def toString = "Invoked: %s called with %s".format(
    m.getName,
    if (args.isEmpty) "no args" else "args '%s'".format(args mkString ", ")
  )
}

object Invoked {
  def apply(m: Method, args: Seq[Any]): Invoked = apply(null, m, args)
  def apply(proxy: AnyRef, m: Method, args: Seq[Any]): Invoked = {
    val fixedArgs = if (args == null) Nil else args.toList map (_.asInstanceOf[AnyRef])
    new Invoked(proxy, m, fixedArgs)
  }
  def unapply(x: Any) = x match {
    case x: Invoked => Some(x.proxy, x.m, x.args)
    case _          => None
  }
  object NameAndArgs {
    def unapply(x: Any) = x match {
      case x: Invoked => Some(x.name, x.args)
      case _          => None
    }
  }
  object NameAndArity {
    def unapply(x: Any) = x match {
      case x: Invoked => Some(x.name, x.arity)
      case _          => None
    }
  }
}

/** A wrapper around java dynamic proxies to make it easy to pose
  *  as an interface.  See SignalManager for an example usage.
  */
trait Mock extends (Invoked => AnyRef) {
  mock =>

  def interfaces: List[Class[_]]
  def classLoader: ClassLoader
  def apply(invoked: Invoked): AnyRef

  def newProxyInstance(handler: InvocationHandler): AnyRef =
    Proxy.newProxyInstance(classLoader, interfaces.toArray, handler)
  def newProxyInstance(): AnyRef =
    newProxyInstance(newInvocationHandler())

  def newInvocationHandler() = new InvocationHandler {
    def invoke(proxy: AnyRef, method: Method, args: Array[AnyRef]) =
      mock(Invoked(proxy, method, args))
  }
}

/** The methods in Mock create the actual proxy instance which can be used
  *  in place of the associated interface(s).
  */
object Mock {
  /** The default implementation calls the partial function if defined, and
    *  routes Object methods to the proxy: otherwise it throws an exception.
    */
  def fromInterfaces(clazz: Class[_], clazzes: Class[_]*)(pf: PartialFunction[Invoked, AnyRef]): AnyRef = {
    val ints = clazz :: clazzes.toList
    require(ints forall (_.isInterface), "All class objects must represent interfaces")

    val mock = new Mock {
      val interfaces  = ints
      def classLoader = clazz.getClassLoader
      def apply(invoked: Invoked) =
        if (pf.isDefinedAt(invoked)) pf(invoked)
        else if (invoked.isObjectMethod) invoked invokeOn this
        else throw new NoSuchMethodException("" + invoked)
    }
    mock.newProxyInstance()
  }
  /** Tries to implement all the class's interfaces.
    */
  def fromClass(clazz: Class[_])(pf: PartialFunction[Invoked, AnyRef]): AnyRef = Util.allInterfaces(clazz) match {
    case Nil      => sys.error(clazz + " implements no interfaces.")
    case x :: xs  => fromInterfaces(x, xs: _*)(pf)
  }
}

trait Shield {
  def className: String
  def classLoader: ScalaClassLoader

  // Override this if you are more ambitious about logging or throwing.
  def onError[T >: Null](msg: String): T = null

  /** This is handy because all reflective calls want back an AnyRef but
    *  we will often be generating Units.
    */
  protected implicit def boxedUnit(x: Unit): AnyRef = scala.runtime.BoxedUnit.UNIT

  lazy val clazz: Class[_] = classLoader.tryToLoadClass(className) getOrElse onError("Failed to load " + className)
  lazy val methods = clazz.getMethods.toList

  def constructor(paramTypes: Class[_]*) = clazz.getConstructor(paramTypes: _*).asInstanceOf[Constructor[AnyRef]]
  def method(name: String, arity: Int)   = uniqueMethod(name, arity)
  def field(name: String)                = clazz getField name

  def matchingMethods(name: String, arity: Int) = methods filter (m => Util.nameAndArity(m) == (name, arity))
  def uniqueMethod(name: String, arity: Int) = matchingMethods(name, arity) match {
    case List(x)  => x
    case _        => onError("No unique match for " + name)
  }
}

/** Signal handling code.  100% clean of any references to sun.misc:
  *  it's all reflection and proxies and invocation handlers and lasers,
  *  so even the choosiest runtimes will be cool with it.
  *
  *  Sun/Oracle says sun.misc.* is unsupported and therefore so is all
  *  of this.  Simple examples:
  *  {{{
      val manager = sigterms.SignalManager // or you could make your own
      // Assignment clears any old handlers; += chains them.
      manager("HUP") = println("HUP 1!")
      manager("HUP") += println("HUP 2!")
      // Use raise() to raise a signal: this will print both lines
      manager("HUP").raise()
      // See a report on every signal's current handler
      manager.dump()
  *  }}}
  */
class SignalManager(classLoader: ScalaClassLoader) {
  def this() = this(ScalaClassLoader.appLoader)
  private val illegalArgHandler: PartialFunction[Throwable, Boolean] = {
    case x if unwrap(x).isInstanceOf[IllegalArgumentException] => false
  }
  private def fail(msg: String) = new SignalError(msg)

  object rSignalHandler extends Shield {
    val className   = "sun.misc.SignalHandler"
    val classLoader = SignalManager.this.classLoader

    lazy val SIG_DFL = field("SIG_DFL") get null
    lazy val SIG_IGN = field("SIG_IGN") get null

    /** Create a new signal handler based on the function.
      */
    def apply(action: Invoked => Unit) = Mock.fromInterfaces(clazz) {
      case inv @ Invoked.NameAndArgs("handle", _ :: Nil) => {action(inv) ; scala.runtime.BoxedUnit.UNIT}
    }
    def empty = rSignalHandler(_ => ())
  }
  import rSignalHandler.{ SIG_DFL, SIG_IGN }

  object rSignal extends Shield {
    val className   = "sun.misc.Signal"
    val classLoader = SignalManager.this.classLoader

    lazy val handleMethod = method("handle", 2)
    lazy val raiseMethod  = method("raise", 1)
    lazy val numberMethod = method("getNumber", 0)

    /** Create a new Signal with the given name.
      */
    def apply(name: String)                     = constructor(classOf[String]) newInstance name
    def handle(signal: AnyRef, current: AnyRef) = {
      if (signal == null || current == null) fail("Signals cannot be null")
      else handleMethod.invoke(null, signal, current)
    }
    def raise(signal: AnyRef)                   = {
      if (signal == null) fail("Signals cannot be null")
      else raiseMethod.invoke(null, signal)
    }
    def number(signal: AnyRef): Int             = numberMethod.invoke(signal).asInstanceOf[Int]

    class WSignal(val name: String) {
      lazy val signal             = rSignal apply name
      def number                  = rSignal number signal
      def raise()                 = rSignal raise signal
      def handle(handler: AnyRef) = rSignal.handle(signal, handler)

      def isError               = false
      def setTo(body: => Unit)  = register(name, false, body)
      def +=(body: => Unit)     = register(name, true, body)

      /** It's hard to believe there's no way to get a signal's current
        *  handler without replacing it, but if there is I couldn't find
        *  it, so we have this swapping code.
        */
      def withCurrentHandler[T](f: AnyRef => T): T = {
        val swap = handle(rSignalHandler.empty)

        try f(swap)
        finally handle(swap)
      }
      def isDefault = try withCurrentHandler {
        case SIG_DFL  => true
        case _        => false
      } catch illegalArgHandler
      def isIgnored = try withCurrentHandler {
        case SIG_IGN  => true
        case _        => false
      } catch illegalArgHandler
      def isSetTo(ref: AnyRef) =
        try withCurrentHandler { _ eq ref }
        catch illegalArgHandler

      def handlerString() = withCurrentHandler {
        case SIG_DFL    => "Default"
        case SIG_IGN    => "Ignore"
        case x          => "" + x
      }

      override def toString = "%10s  %s".format("SIG" + name,
        try handlerString()
        catch { case x: Exception => "VM threw " + unwrap(x) }
      )
      override def equals(other: Any) = other match {
        case x: WSignal => name == x.name
        case _          => false
      }
      override def hashCode = name.##
    }
  }
  type WSignal = rSignal.WSignal

  /** Adds a handler for the named signal.  If shouldChain is true,
    *  the installed handler will call the previous handler after the
    *  new one has executed.  If false, the old handler is dropped.
    */
  private def register(name: String, shouldChain: Boolean, body: => Unit) = {
    val signal  = rSignal(name)
    val current = rSignalHandler(_ => body)
    val prev    = rSignal.handle(signal, current)

    if (shouldChain) {
      val chainer = rSignalHandler { inv =>
        val signal = inv.args.head

        inv invokeOn current
        prev match {
          case SIG_IGN | SIG_DFL  => ()
          case _                  => inv invokeOn prev
        }
      }
      rSignal.handle(signal, chainer)
      chainer
    }
    else current
  }

  /** Use apply and update to get and set handlers.
    */
  def apply(name: String): WSignal =
    try   { new WSignal(name) }
    catch { case x: IllegalArgumentException => new SignalError(x.getMessage) }

  def update(name: String, body: => Unit): Unit = apply(name) setTo body

  class SignalError(message: String) extends WSignal("") {
    override def isError = true
    override def toString = message
  }

  def public(name: String, description: String)(body: => Unit): Unit = {
    try {
      val wsig = apply(name)
      if (wsig.isError)
        return

      wsig setTo body
      registerInfoHandler()
      addPublicHandler(wsig, description)
    }
    catch {
      case x: Exception => ()   // ignore failure
    }
  }
  /** Makes sure the info handler is registered if we see activity. */
  private def registerInfoHandler() = {
    val INFO = apply("INFO")
    if (publicHandlers.isEmpty && INFO.isDefault) {
      INFO setTo Console.println(info())
      addPublicHandler(INFO, "Print signal handler registry on console.")
    }
  }
  private def addPublicHandler(wsig: WSignal, description: String) = {
    if (publicHandlers contains wsig) ()
    else publicHandlers = publicHandlers.updated(wsig, description)
  }
  private var publicHandlers: Map[WSignal, String] = Map()
  def info(): String = {
    registerInfoHandler()
    val xs = publicHandlers.toList sortBy (_._1.name) map {
      case (wsig, descr) => "  %2d  %5s  %s".format(wsig.number, wsig.name, descr)
    }

    xs.mkString("\nSignal handler registry:\n", "\n", "")
  }
}

object SignalManager extends SignalManager {
  private implicit def mkWSignal(name: String): WSignal = this(name)
  private lazy val signalNumberMap = all map (x => x.number -> x) toMap

  def all = List(
    HUP, INT, QUIT, ILL, TRAP, ABRT, EMT, FPE,    // 1-8
    KILL, BUS, SEGV, SYS, PIPE, ALRM, TERM, URG,  // 9-15
    STOP, TSTP, CONT, CHLD, TTIN, TTOU, IO, XCPU, // 16-23
    XFSZ, VTALRM, PROF, WINCH, INFO, USR1, USR2   // 24-31
  )
  /** Signals which are either inaccessible or which seem like
    *  particularly bad choices when looking for an open one.
    */
  def reserved         = Set(QUIT, TRAP, ABRT, KILL, BUS, SEGV, ALRM, STOP, INT)
  def unreserved       = all filterNot reserved
  def defaultSignals() = unreserved filter (_.isDefault)
  def ignoredSignals() = unreserved filter (_.isIgnored)
  def findOpenSignal() = Random.shuffle(defaultSignals()).head

  def dump() = all foreach (x => println("%2s %s".format(x.number, x)))

  def apply(sigNumber: Int): WSignal = signalNumberMap(sigNumber)

  def HUP: WSignal    = "HUP"
  def INT: WSignal    = "INT"
  def QUIT: WSignal   = "QUIT"
  def ILL: WSignal    = "ILL"
  def TRAP: WSignal   = "TRAP"
  def ABRT: WSignal   = "ABRT"
  def EMT: WSignal    = "EMT"
  def FPE: WSignal    = "FPE"
  def KILL: WSignal   = "KILL"
  def BUS: WSignal    = "BUS"
  def SEGV: WSignal   = "SEGV"
  def SYS: WSignal    = "SYS"
  def PIPE: WSignal   = "PIPE"
  def ALRM: WSignal   = "ALRM"
  def TERM: WSignal   = "TERM"
  def URG: WSignal    = "URG"
  def STOP: WSignal   = "STOP"
  def TSTP: WSignal   = "TSTP"
  def CONT: WSignal   = "CONT"
  def CHLD: WSignal   = "CHLD"
  def TTIN: WSignal   = "TTIN"
  def TTOU: WSignal   = "TTOU"
  def IO: WSignal     = "IO"
  def XCPU: WSignal   = "XCPU"
  def XFSZ: WSignal   = "XFSZ"
  def VTALRM: WSignal = "VTALRM"
  def PROF: WSignal   = "PROF"
  def WINCH: WSignal  = "WINCH"
  def INFO: WSignal   = "INFO"
  def USR1: WSignal   = "USR1"
  def USR2: WSignal   = "USR2"

  /** Given a number of seconds, a signal, and a function: sets up a handler which upon
    *  receiving the signal once, calls the function with argument true, and if the
    *  signal is received again within the allowed time, calls it with argument false.
    *  (Otherwise it calls it with true and starts the timer over again.)
    */
  def requireInterval(seconds: Long, wrapper: WSignal)(fn: Boolean => Unit) = {
    var received = false
    wrapper setTo {
      if (received) fn(false)
      else {
        received = true
        fn(true)
        new java.util.Timer(true).schedule(new java.util.TimerTask{ def run() = received = false }, seconds * 1000L)
      }
    }
  }
}


text:
class Tip < ActiveRecord::Base
  belongs_to :user
  belongs_to :sendmany
  belongs_to :project

  validates :amount, :numericality => { :greater_than => 0 }

  scope :unpaid,        -> { non_refunded.
                             where(sendmany_id: nil) }

  scope :paid,          -> { where('sendmany_id is not ?', nil) }

  scope :refunded,      -> { where('refunded_at is not ?', nil) }

  scope :non_refunded,  -> { where(refunded_at: nil) }

  scope :unclaimed,     -> { joins(:user).
                             unpaid.
                             where('users.bitcoin_address' => ['', nil]) }

  scope :with_address,  -> { joins(:user).where('users.bitcoin_address IS NOT NULL AND users.bitcoin_address != ?', "") }

  def paid?
    !!sendmany_id
  end

  def self.refund_unclaimed
    unclaimed.non_refunded.
    where('tips.created_at < ?', Time.now - 1.month).
    find_each do |tip|
      tip.touch :refunded_at
    end
  end
end


text:
@interface SPMeViewController : UITableViewController

@end


text:
// Type definitions for vfile-location 2.0
// Project: https://github.com/vfile/vfile-location
// Definitions by: Ika <https://github.com/ikatyang>
//                 Junyoung Choi <https://github.com/rokt33r>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.0

import * as VFile from "vfile";

declare function vfileLocation(vfile: string | VFile.VFile): vfileLocation.Location;

declare namespace vfileLocation {
    interface Location {
        /**
         * Get the `offset` (`number`) for a line and column-based `position` in the bound file.
         * Returns `-1` when given invalid or out of bounds input.
         */
        toOffset(position: { line: number; column: number }): number;
        /**
         * Get the line and column-based `position` for `offset` in the bound file.
         */
        toPosition(offset: number): { line: number; column: number; offset: number };
    }
}

export = vfileLocation;


text:
/**
 * @file
 * @brief System Hockey Source
 *
 * Contains implementation of classes for Hockey game Logic
 */

#include "systems/hockey.hpp"
#include "components/transform.hpp"
#include "components/velocity.hpp"

namespace systems
{

Hockey::Hockey(int score_limit)
    : m_score_a(0),
      m_score_b(0),
      m_score_limit(score_limit),
      m_sp_logger(common::logging_get_logger("hockey"))
{
}

void Hockey::check_trigger(std::string msg, anax::Entity e_target)
{
    auto id = e_target.getComponent<components::IdComponent>().id;

    if (id.compare("puck") == 0)
    {
        bool reset = false;
        if (msg.compare("goal_a") == 0)
        {
            m_sp_logger->info("A team scores!");
            m_score_a++;
            reset = true;
            if (m_score_a > m_score_limit)
            {
                m_sp_logger->info("A team wins!");
            }
        }
        else if (msg.compare("goal_b") == 0)
        {
            m_score_b++;
            reset = true;
            m_sp_logger->info("B team scores!");
            if (m_score_b > m_score_limit)
            {
                m_sp_logger->info("B team wins!");
            }
        }

        if (reset)
        {
            m_sp_logger->info("Score is now A:{} B:{}", m_score_a, m_score_b);
            throw_if_missing_component<components::TransformComponent>(
                e_target);
            throw_if_missing_component<components::PhysicsComponent>(e_target);
            auto& transform =
                e_target.getComponent<components::TransformComponent>();
            auto& physics =
                e_target.getComponent<components::PhysicsComponent>();
            transform.pos_x = 800;
            transform.pos_y = 800;
            physics.velocity.x = 0;
            physics.velocity.y = 0;
            physics.force.x = 0;
            physics.force.y = 0;
        }
    }
}
} // namespace systems


text:
      <input type="checkbox" name="attr_equipment_show_only_quick_items" class="toggle-equipment-only-quick-items" value="1">

  <input type="hidden" name="attr_equipment_show_only_quick_items" class="toggle-equipment-only-quick-items">
  <fieldset class="repeating_equipment">
    <input type="hidden" name="attr_quick" class="toggle-quick-equipment hidden" value="1">

            <input type="checkbox" name="attr_carried" class="small-checkbox" checked>

              <input type="text" name="attr_name" accept="Name">

              <button type="roll" name="roll_equipment" class="wrapper-button" value="@{output_option} &{template:5e-shaped} {{character_name=@{character_name}}} @{show_character_name} {{title=@{name}}} {{equipment=1}} {{text=@{content}}} {{uses=@{uses}}} {{uses_max=@{uses|max}}}">

              </button>

            <input type="checkbox" name="attr_quick" class="small-checkbox" value="1" checked>

          <input type="checkbox" name="attr_show_uses" class="edit small-checkbox show-uses" value="1">

            <input type="number" name="attr_uses" class="no-spin no-border small-label" step="1">

/

            <input type="number" name="attr_uses_max" class="no-spin no-border small-label" step="1">

        <input type="number" name="attr_qty" class="no-spin no-border" value="1" min="0" step="1">

×

          <input type="number" name="attr_weight" class="no-spin no-border small-label" value="0" step=".001" accept="Weight">

    <input type="checkbox" name="attr_toggle_details" class="toggle-icon-settings edit">y

        <textarea name="attr_content" class="one-line-textarea" accept="Content"></textarea>

  </fieldset>


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MvcWithSwagger.Models;

namespace MvcWithSwagger.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}


text:
using Executor.Attributes;
using Executor.Contracts;
using Executor.Exceptions;

namespace Executor.IO.Commands
{
    [Alias("order")]
    public class PrintOrderedStudentsCommand  : Command
    {
        [Inject]
        private IDatabase repository;

        public PrintOrderedStudentsCommand(string input, string[] data)
            : base(input, data)
        {
        }

        public override void Execute()
        {
            if (this.Data.Length != 5)
            {
                throw new InvalidCommandException(this.Input);
            }

            string courseName = this.Data[1];
            string orderType = this.Data[2].ToLower();
            string takeCommand = this.Data[3].ToLower();
            string takeQuantity = this.Data[4].ToLower();

            this.TryParseParametersForOrderAndTake(takeCommand, takeQuantity, courseName, orderType);
        }

        private void TryParseParametersForOrderAndTake(string takeCommand, string takeQuantity, string courseName, string orderType)
        {
            if (takeCommand == "take")
            {
                if (takeQuantity == "all")
                {
                    this.repository.OrderAndTake(courseName, orderType);
                }
                else
                {
                    int studentsToTake;
                    bool hasParsed = int.TryParse(takeQuantity, out studentsToTake);
                    if (hasParsed)
                    {
                        this.repository.OrderAndTake(courseName, orderType, studentsToTake);
                    }
                    else
                    {
                        OutputWriter.DisplayException(ExceptionMessages.InvalidTakeQuantityParameter);
                    }
                }
            }
            else
            {
                OutputWriter.DisplayException(ExceptionMessages.InvalidTakeCommand);
            }
        }
    }
}