text:
package bots

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"sort"
	"sync"
	"time"

	"github.com/keybase/client/go/chat/globals"
	"github.com/keybase/client/go/chat/storage"
	"github.com/keybase/client/go/chat/types"
	"github.com/keybase/client/go/chat/utils"
	"github.com/keybase/client/go/encrypteddb"
	"github.com/keybase/client/go/libkb"
	"github.com/keybase/client/go/protocol/chat1"
	"github.com/keybase/client/go/protocol/gregor1"
	"github.com/keybase/client/go/protocol/keybase1"
	"golang.org/x/sync/errgroup"
)

const storageVersion = 1

type uiResult struct {
	err      error
	settings chat1.UIBotCommandsUpdateSettings
}

type commandUpdaterJob struct {
	convID      chat1.ConversationID
	info        *chat1.BotInfo
	completeChs []chan error
	uiCh        chan uiResult
}

type userCommandAdvertisement struct {
	Alias    *string                     `json:"alias,omitempty"`
	Commands []chat1.UserBotCommandInput `json:"commands"`
}

type storageCommandAdvertisement struct {
	Advertisement     userCommandAdvertisement
	UntrustedTeamRole keybase1.TeamRole
	UID               gregor1.UID
	Username          string
	Typ               chat1.BotCommandsAdvertisementTyp
}

type commandsStorage struct {
	Advertisements []storageCommandAdvertisement `codec:"A"`
	Version        int                           `codec:"V"`
}

var commandsPublicTopicName = "___keybase_botcommands_public"

type nameInfoSourceFn func(ctx context.Context, g *globals.Context, membersType chat1.ConversationMembersType) types.NameInfoSource

type CachingBotCommandManager struct {
	globals.Contextified
	utils.DebugLabeler
	sync.Mutex

	uid     gregor1.UID
	started bool
	eg      errgroup.Group
	stopCh  chan struct{}

	ri              func() chat1.RemoteInterface
	nameInfoSource  nameInfoSourceFn
	edb             *encrypteddb.EncryptedDB
	commandUpdateCh chan *commandUpdaterJob
	queuedUpdatedMu sync.Mutex
	queuedUpdates   map[chat1.ConvIDStr]*commandUpdaterJob
}

func NewCachingBotCommandManager(g *globals.Context, ri func() chat1.RemoteInterface,
	nameInfoSource nameInfoSourceFn) *CachingBotCommandManager {
	keyFn := func(ctx context.Context) ([32]byte, error) {
		return storage.GetSecretBoxKey(ctx, g.ExternalG())
	}
	dbFn := func(g *libkb.GlobalContext) *libkb.JSONLocalDb {
		return g.LocalChatDb
	}
	return &CachingBotCommandManager{
		Contextified:    globals.NewContextified(g),
		DebugLabeler:    utils.NewDebugLabeler(g.ExternalG(), "CachingBotCommandManager", false),
		ri:              ri,
		edb:             encrypteddb.New(g.ExternalG(), dbFn, keyFn),
		commandUpdateCh: make(chan *commandUpdaterJob, 100),
		queuedUpdates:   make(map[chat1.ConvIDStr]*commandUpdaterJob),
		nameInfoSource:  nameInfoSource,
	}
}

func (b *CachingBotCommandManager) Start(ctx context.Context, uid gregor1.UID) {
	defer b.Trace(ctx, nil, "Start")()
	b.Lock()
	defer b.Unlock()
	if b.started {
		return
	}
	b.stopCh = make(chan struct{})
	b.started = true
	b.uid = uid
	b.eg.Go(func() error { return b.commandUpdateLoop(b.stopCh) })
}

func (b *CachingBotCommandManager) Stop(ctx context.Context) chan struct{} {
	defer b.Trace(ctx, nil, "Stop")()
	b.Lock()
	defer b.Unlock()
	ch := make(chan struct{})
	if b.started {
		close(b.stopCh)
		b.started = false
		go func() {
			err := b.eg.Wait()
			if err != nil {
				b.Debug(ctx, "CachingBotCommandManager: error waiting: %+v", err)
			}
			close(ch)
		}()
	} else {
		close(ch)
	}
	return ch
}

func (b *CachingBotCommandManager) getMyUsername(ctx context.Context) (string, error) {
	nn, err := b.G().GetUPAKLoader().LookupUsername(ctx, keybase1.UID(b.uid.String()))
	if err != nil {
		return "", err
	}
	return nn.String(), nil
}

func (b *CachingBotCommandManager) createConv(ctx context.Context, typ chat1.BotCommandsAdvertisementTyp,
	teamName *string, convID *chat1.ConversationID) (res chat1.ConversationLocal, err error) {
	username, err := b.getMyUsername(ctx)
	if err != nil {
		return res, err
	}
	switch typ {
	case chat1.BotCommandsAdvertisementTyp_PUBLIC:
		if teamName != nil {
			return res, errors.New("team name cannot be specified for public advertisements")
		} else if convID != nil {
			return res, errors.New("convID cannot be specified for public advertisements")
		}

		res, _, err = b.G().ChatHelper.NewConversation(ctx, b.uid, username, &commandsPublicTopicName,
			chat1.TopicType_DEV, chat1.ConversationMembersType_IMPTEAMNATIVE, keybase1.TLFVisibility_PUBLIC)
		return res, err
	case chat1.BotCommandsAdvertisementTyp_TLFID_MEMBERS, chat1.BotCommandsAdvertisementTyp_TLFID_CONVS:
		if teamName == nil {
			return res, errors.New("missing team name")
		} else if convID != nil {
			return res, errors.New("convID cannot be specified for team advertisments use type 'conv'")
		}

		topicName := fmt.Sprintf("___keybase_botcommands_team_%s_%v", username, typ)
		res, _, err = b.G().ChatHelper.NewConversationSkipFindExisting(ctx, b.uid, *teamName, &topicName,
			chat1.TopicType_DEV, chat1.ConversationMembersType_TEAM, keybase1.TLFVisibility_PRIVATE)
		return res, err
	case chat1.BotCommandsAdvertisementTyp_CONV:
		if teamName != nil {
			return res, errors.New("unexpected team name")
		} else if convID == nil {
			return res, errors.New("missing convID")
		}

		topicName := fmt.Sprintf("___keybase_botcommands_conv_%s_%v", username, typ)
		convs, err := b.G().ChatHelper.FindConversationsByID(ctx, []chat1.ConversationID{*convID})
		if err != nil {
			return res, err
		} else if len(convs) != 1 {
			return res, errors.New("Unable able to find conversation for advertisement")
		}
		conv := convs[0]
		res, _, err = b.G().ChatHelper.NewConversationSkipFindExisting(ctx, b.uid, conv.Info.TlfName, &topicName,
			chat1.TopicType_DEV, conv.Info.MembersType, keybase1.TLFVisibility_PRIVATE)
		return res, err
	default:
		return res, fmt.Errorf("unknown bot advertisement typ %q", typ)
	}
}

func (b *CachingBotCommandManager) PublicCommandsConv(ctx context.Context, username string) (*chat1.ConversationID, error) {
	convs, err := b.G().ChatHelper.FindConversations(ctx, username, &commandsPublicTopicName,
		chat1.TopicType_DEV, chat1.ConversationMembersType_IMPTEAMNATIVE, keybase1.TLFVisibility_PUBLIC)
	if err != nil {
		return nil, err
	}
	if len(convs) != 1 {
		b.Debug(ctx, "PublicCommandsConv: no command conv found")
		return nil, nil
	}
	convID := convs[0].GetConvID()
	return &convID, nil
}

func (b *CachingBotCommandManager) Advertise(ctx context.Context, alias *string,
	ads []chat1.AdvertiseCommandsParam) (err error) {
	defer b.Trace(ctx, &err, "Advertise")()
	remotes := make([]chat1.RemoteBotCommandsAdvertisement, 0, len(ads))
	for _, ad := range ads {
		// create conversations with the commands
		conv, err := b.createConv(ctx, ad.Typ, ad.TeamName, ad.ConvID)
		if err != nil {
			return err
		}
		// marshal contents
		payload := userCommandAdvertisement{
			Alias:    alias,
			Commands: ad.Commands,
		}
		dat, err := json.Marshal(payload)
		if err != nil {
			return err
		}
		var vis keybase1.TLFVisibility
		var tlfID *chat1.TLFID
		var adConvID *chat1.ConversationID
		switch ad.Typ {
		case chat1.BotCommandsAdvertisementTyp_PUBLIC:
			vis = keybase1.TLFVisibility_PUBLIC
		case chat1.BotCommandsAdvertisementTyp_CONV:
			vis = keybase1.TLFVisibility_PRIVATE
			adConvID = ad.ConvID
		default:
			tlfID = &conv.Info.Triple.Tlfid
			vis = keybase1.TLFVisibility_PRIVATE
		}
		remote, err := ad.ToRemote(conv.GetConvID(), tlfID, adConvID)
		if err != nil {
			return err
		}
		// write out commands to conv
		if err := b.G().ChatHelper.SendMsgByID(ctx, conv.GetConvID(), conv.Info.TlfName,
			chat1.NewMessageBodyWithText(chat1.MessageText{
				Body: string(dat),
			}), chat1.MessageType_TEXT, vis); err != nil {
			return err
		}
		remotes = append(remotes, remote)
	}
	if _, err := b.ri().AdvertiseBotCommands(ctx, remotes); err != nil {
		return err
	}
	return nil
}

func (b *CachingBotCommandManager) Clear(ctx context.Context, filter *chat1.ClearBotCommandsFilter) (err error) {
	defer b.Trace(ctx, &err, "Clear")()
	var remote *chat1.RemoteClearBotCommandsFilter
	if filter != nil {
		remote = new(chat1.RemoteClearBotCommandsFilter)

		var tlfID *chat1.TLFID
		var convID *chat1.ConversationID
		switch filter.Typ {
		case chat1.BotCommandsAdvertisementTyp_PUBLIC:
		case chat1.BotCommandsAdvertisementTyp_TLFID_CONVS, chat1.BotCommandsAdvertisementTyp_TLFID_MEMBERS:
			conv, err := b.createConv(ctx, filter.Typ, filter.TeamName, filter.ConvID)
			if err != nil {
				return err
			}
			tlfID = &conv.Info.Triple.Tlfid
		case chat1.BotCommandsAdvertisementTyp_CONV:
			convID = filter.ConvID
		}

		*remote, err = filter.ToRemote(tlfID, convID)
		if err != nil {
			return err
		}
	}
	if _, err := b.ri().ClearBotCommands(ctx, remote); err != nil {
		return err
	}
	return nil
}

func (b *CachingBotCommandManager) dbInfoKey(convID chat1.ConversationID) libkb.DbKey {
	return libkb.DbKey{
		Key: fmt.Sprintf("ik:%s:%s", b.uid, convID),
		Typ: libkb.DBChatBotCommands,
	}
}

func (b *CachingBotCommandManager) dbCommandsKey(convID chat1.ConversationID) libkb.DbKey {
	return libkb.DbKey{
		Key: fmt.Sprintf("ck:%s:%s", b.uid, convID),
		Typ: libkb.DBChatBotCommands,
	}
}

func (b *CachingBotCommandManager) ListCommands(ctx context.Context, convID chat1.ConversationID) (res []chat1.UserBotCommandOutput, alias map[string]string, err error) {
	defer b.Trace(ctx, &err, "ListCommands")()
	alias = make(map[string]string)
	dbKey := b.dbCommandsKey(convID)
	var s commandsStorage
	found, err := b.edb.Get(ctx, dbKey, &s)
	if err != nil {
		b.Debug(ctx, "ListCommands: failed to read cache: %s", err)
		if err := b.edb.Delete(ctx, dbKey); err != nil {
			b.Debug(ctx, "edb.Delete: %v", err)
		}
		found = false
	}
	if !found {
		return res, alias, nil
	}
	if s.Version != storageVersion {
		b.Debug(ctx, "ListCommands: deleting old version %d vs %d", s.Version, storageVersion)
		if err := b.edb.Delete(ctx, dbKey); err != nil {
			b.Debug(ctx, "edb.Delete: %v", err)
		}
		return res, alias, nil
	}

	cmdOutputs := make(map[string]chat1.UserBotCommandOutput)
	cmdDedup := make(map[string]chat1.BotCommandsAdvertisementTyp)
	for _, ad := range s.Advertisements {
		ad.Username = libkb.NewNormalizedUsername(ad.Username).String()
		if ad.Advertisement.Alias != nil {
			alias[ad.Username] = *ad.Advertisement.Alias
		}
		for _, cmd := range ad.Advertisement.Commands {
			key := cmd.Name + ad.Username
			if typ, ok := cmdDedup[key]; !ok || ad.Typ > typ {
				cmdOutputs[key] = cmd.ToOutput(ad.Username)
				cmdDedup[key] = ad.Typ
			}
		}
	}
	res = make([]chat1.UserBotCommandOutput, 0, len(cmdOutputs))
	for _, cmd := range cmdOutputs {
		res = append(res, cmd)
	}

	sort.Slice(res, func(i, j int) bool {
		l := res[i]
		r := res[j]
		if l.Username < r.Username {
			return true
		} else if l.Username > r.Username {
			return false
		} else {
			return l.Name < r.Name
		}
	})
	return res, alias, nil
}

func (b *CachingBotCommandManager) UpdateCommands(ctx context.Context, convID chat1.ConversationID,
	info *chat1.BotInfo) (completeCh chan error, err error) {
	defer b.Trace(ctx, &err, "UpdateCommands")()
	completeCh = make(chan error, 1)
	uiCh := make(chan uiResult, 1)
	return completeCh, b.queueCommandUpdate(ctx, &commandUpdaterJob{
		convID:      convID,
		info:        info,
		completeChs: []chan error{completeCh},
		uiCh:        uiCh,
	})
}

func (b *CachingBotCommandManager) getChatUI(ctx context.Context) libkb.ChatUI {
	ui, err := b.G().UIRouter.GetChatUI()
	if err != nil || ui == nil {
		b.Debug(ctx, "getChatUI: no chat UI found: err: %s", err)
		return utils.NullChatUI{}
	}
	return ui
}

func (b *CachingBotCommandManager) runCommandUpdateUI(ctx context.Context, job *commandUpdaterJob) {
	err := b.getChatUI(ctx).ChatBotCommandsUpdateStatus(ctx, job.convID,
		chat1.NewUIBotCommandsUpdateStatusWithBlank())
	if err != nil {
		b.Debug(ctx, "getChatUI: error getting update status: %+v", err)
	}
	for {
		select {
		case res := <-job.uiCh:
			var updateStatus chat1.UIBotCommandsUpdateStatus
			if res.err != nil {
				updateStatus = chat1.NewUIBotCommandsUpdateStatusWithFailed()
			} else {
				updateStatus = chat1.NewUIBotCommandsUpdateStatusWithUptodate(res.settings)
			}
			if err = b.getChatUI(ctx).ChatBotCommandsUpdateStatus(ctx, job.convID, updateStatus); err != nil {
				b.Debug(ctx, "getChatUI: error getting update status: %+v", err)
			}
			return
		case <-time.After(800 * time.Millisecond):
			err := b.getChatUI(ctx).ChatBotCommandsUpdateStatus(ctx, job.convID,
				chat1.NewUIBotCommandsUpdateStatusWithUpdating())
			if err != nil {
				b.Debug(ctx, "getChatUI: error getting update status: %+v", err)
			}
		}
	}
}

func (b *CachingBotCommandManager) queueCommandUpdate(ctx context.Context, job *commandUpdaterJob) error {
	b.queuedUpdatedMu.Lock()
	defer b.queuedUpdatedMu.Unlock()
	if curJob, ok := b.queuedUpdates[job.convID.ConvIDStr()]; ok {
		b.Debug(ctx, "queueCommandUpdate: skipping already queued: %s", job.convID)
		curJob.completeChs = append(curJob.completeChs, job.completeChs...)
		return nil
	}
	select {
	case b.commandUpdateCh <- job:
		go b.runCommandUpdateUI(globals.BackgroundChatCtx(ctx, b.G()), job)
		b.queuedUpdates[job.convID.ConvIDStr()] = job
	default:
		return errors.New("queue full")
	}
	return nil
}

func (b *CachingBotCommandManager) getBotInfo(ctx context.Context, job *commandUpdaterJob) (botInfo chat1.BotInfo, doUpdate bool, err error) {
	defer b.Trace(ctx, &err, fmt.Sprintf("getBotInfo: %v", job.convID))()
	if job.info != nil {
		return *job.info, true, nil
	}
	convID := job.convID
	found, err := b.edb.Get(ctx, b.dbInfoKey(convID), &botInfo)
	if err != nil {
		b.Debug(ctx, "getBotInfo: failed to read cache: %s", err)
		found = false
	}
	var infoHash chat1.BotInfoHash
	if found {
		infoHash = botInfo.Hash()
	}
	res, err := b.ri().GetBotInfo(ctx, chat1.GetBotInfoArg{
		ConvID:   convID,
		InfoHash: infoHash,
		// Send up the latest client version we known about. The server
		// will apply the client version when hashing so we can cache even if
		// new clients are using a different hash function.
		ClientHashVers: chat1.ClientBotInfoHashVers,
	})
	if err != nil {
		return botInfo, false, err
	}
	rtyp, err := res.Response.Typ()
	if err != nil {
		return botInfo, false, err
	}
	switch rtyp {
	case chat1.BotInfoResponseTyp_UPTODATE:
		return botInfo, false, nil
	case chat1.BotInfoResponseTyp_INFO:
		if err := b.edb.Put(ctx, b.dbInfoKey(convID), res.Response.Info()); err != nil {
			return botInfo, false, err
		}
		return res.Response.Info(), true, nil
	}
	return botInfo, false, errors.New("unknown response type")
}

func (b *CachingBotCommandManager) getConvAdvertisement(ctx context.Context, convID chat1.ConversationID,
	botUID gregor1.UID, untrustedTeamRole keybase1.TeamRole, typ chat1.BotCommandsAdvertisementTyp) (res *storageCommandAdvertisement) {
	b.Debug(ctx, "getConvAdvertisement: reading commands from: %s for uid: %s", convID, botUID)
	tv, err := b.G().ConvSource.Pull(ctx, convID, b.uid, chat1.GetThreadReason_BOTCOMMANDS, nil,
		&chat1.GetThreadQuery{
			MessageTypes: []chat1.MessageType{chat1.MessageType_TEXT},
		}, &chat1.Pagination{Num: 1})
	if err != nil {
		b.Debug(ctx, "getConvAdvertisement: failed to read thread: %s", err)
		return nil
	}
	if len(tv.Messages) == 0 {
		b.Debug(ctx, "getConvAdvertisement: no messages")
		return nil
	}
	msg := tv.Messages[0]
	if !msg.IsValid() {
		b.Debug(ctx, "getConvAdvertisement: latest message is not valid")
		return nil
	}
	body := msg.Valid().MessageBody
	if !body.IsType(chat1.MessageType_TEXT) {
		b.Debug(ctx, "getConvAdvertisement: latest message is not text")
		return nil
	}
	// make sure the sender is who the server said it is
	if !msg.Valid().ClientHeader.Sender.Eq(botUID) {
		b.Debug(ctx, "getConvAdvertisement: wrong sender: %s != %s", botUID, msg.Valid().ClientHeader.Sender)
		return nil
	}
	res = new(storageCommandAdvertisement)
	if err = json.Unmarshal([]byte(body.Text().Body), &res.Advertisement); err != nil {
		b.Debug(ctx, "getConvAdvertisement: failed to JSON decode: %s", err)
		return nil
	}
	res.Username = msg.Valid().SenderUsername
	res.UID = botUID
	res.UntrustedTeamRole = untrustedTeamRole
	res.Typ = typ

	return res
}

func (b *CachingBotCommandManager) commandUpdate(ctx context.Context, job *commandUpdaterJob) (err error) {
	var botSettings chat1.UIBotCommandsUpdateSettings
	ctx = globals.ChatCtx(ctx, b.G(), keybase1.TLFIdentifyBehavior_CHAT_GUI, nil, nil)
	defer b.Trace(ctx, &err, "commandUpdate")()
	defer func() {
		b.queuedUpdatedMu.Lock()
		delete(b.queuedUpdates, job.convID.ConvIDStr())
		b.queuedUpdatedMu.Unlock()
		job.uiCh <- uiResult{
			err:      err,
			settings: botSettings,
		}
		for _, completeCh := range job.completeChs {
			completeCh <- err
		}
	}()
	var eg errgroup.Group
	eg.Go(func() error {
		botInfo, doUpdate, err := b.getBotInfo(ctx, job)
		if err != nil {
			return err
		}
		if !doUpdate {
			b.Debug(ctx, "commandUpdate: bot info uptodate, not updating")
			return nil
		}
		s := commandsStorage{
			Version: storageVersion,
		}
		for _, cconv := range botInfo.CommandConvs {
			ad := b.getConvAdvertisement(ctx, cconv.ConvID, cconv.Uid, cconv.UntrustedTeamRole, cconv.Typ)
			if ad != nil {
				s.Advertisements = append(s.Advertisements, *ad)
			}
		}
		if err := b.edb.Put(ctx, b.dbCommandsKey(job.convID), s); err != nil {
			return err
		}
		// alert that the conv is now updated
		b.G().InboxSource.NotifyUpdate(ctx, b.uid, job.convID)
		return nil
	})
	eg.Go(func() error {
		conv, err := utils.GetVerifiedConv(ctx, b.G(), b.uid, job.convID, types.InboxSourceDataSourceAll)
		if err != nil {
			return err
		}
		ni := b.nameInfoSource(ctx, b.G(), conv.GetMembersType())
		rawSettings, err := ni.TeamBotSettings(ctx, conv.Info.TlfName, conv.Info.Triple.Tlfid,
			conv.GetMembersType(), conv.IsPublic())
		if err != nil {
			return err
		}
		botSettings.Settings = make(map[string]keybase1.TeamBotSettings)
		for uv, settings := range rawSettings {
			username, err := b.G().GetUPAKLoader().LookupUsername(ctx, uv.Uid)
			if err != nil {
				return err
			}
			botSettings.Settings[username.String()] = settings
		}
		return nil
	})
	return eg.Wait()
}

func (b *CachingBotCommandManager) commandUpdateLoop(stopCh chan struct{}) error {
	ctx := context.Background()
	for {
		select {
		case job := <-b.commandUpdateCh:
			if err := b.commandUpdate(ctx, job); err != nil {
				b.Debug(ctx, "commandUpdateLoop: failed to update: %s", err)
			}
		case <-stopCh:
			return nil
		}
	}
}


text:
var STATE_START = Components.interfaces.nsIWebProgressListener.STATE_START;
var STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP;

function WebLoadingListener(browser, toCall) {
  var listener = this;

  this.handler = {
    QueryInterface: function(iid) {
      if (iid.equals(Components.interfaces.nsIWebProgressListener) ||
          iid.equals(Components.interfaces.nsISupportsWeakReference) ||
          iid.equals(Components.interfaces.nsISupports))
        return this;
      throw Components.results.NS_NOINTERFACE;
    },

    onStateChange: function(webProgress, request, flags, status) {
      if (flags & STATE_STOP) {
        if (request.URI) {
          WebLoadingListener.removeListener(browser, listener);
          toCall();
        }
      }
      return 0;
    },

    onLocationChange: function(aProgress, aRequest, aURI) { return 0; },
    onProgressChange: function() { return 0; },
    onStatusChange: function() { return 0; },
    onSecurityChange: function() { return 0; },
    onLinkIconAvailable: function() { return 0; }
  };

  browser.addProgressListener(this.handler,
      Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
}

WebLoadingListener.removeListener = function(browser, listener) {
  browser.removeProgressListener(listener.handler);
};

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * @file
 * Contains \Drupal\Core\Cache\Context\UrlCacheContext.
 */

namespace Drupal\Core\Cache\Context;

use Drupal\Core\Cache\CacheableMetadata;

/**
 * Defines the UrlCacheContext service, for "per page" caching.
 *
 * Cache context ID: 'url'.
 */
class UrlCacheContext extends RequestStackCacheContextBase implements CacheContextInterface {

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {
    return t('URL');
  }

  /**
   * {@inheritdoc}
   */
  public function getContext() {
    return $this->requestStack->getCurrentRequest()->getUri();
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

}


text:
//
//  BRNuvotonBootloaderService.h
//
//  Created by Forrest on 23/3/15.
//  Copyright (c) 2015 WowWee Group Limited. All rights reserved.
//

@import Foundation;
#import "BRBaseService.h"
#import "RobotCommand.h"

/** KVO **/
// Context
#ifndef nuvotonBootloaderKVOContext
#define nuvotonBootloaderKVOContext "nuvotonBootloader"
#endif
// KeyPath
FOUNDATION_EXPORT NSString *const nuvotonChipStatusKeyPathKVO;
FOUNDATION_EXPORT NSString *const firmwareDataStatusKeyPathKVO;
FOUNDATION_EXPORT NSString *const firmwareCompleteStatusKeyPathKVO;

typedef void (^FirmwareProgressCallback)(int sentByte);

@interface BRNuvotonBootloaderService : BRBaseService

@property (nonatomic, assign) bool isNotifying;
@property (nonatomic, strong) NSNumber *nuvotonChipStatus;
@property (nonatomic, strong) NSNumber *firmwareDataStatus;
@property (nonatomic, strong) NSNumber *firmwareCompleteStatus;

#pragma mark - public
- (void) turnOff;
- (void) turnOn;
- (void) readNuvotonChipStatus;
- (void) readFirmwareDataStatus;
- (void) restartNuvotonChipToMode:(NuvotonBootloaderMode)mode;
- (void) stopTransfer;
- (void) writeFirmwareToNuvoton;
- (void)sendFirmwareDataToCache:(NSData *)data
   withAppToBleProgressCallback:(void (^)(int sentByte))appToBleProgressCallback
   bleToNuvotonProgressCallback:(void (^)(int sentByte))bleToNuvotonProgressCallback;

@end


text:
static const CGFloat kCLImageToolAnimationDuration = 0.3;
static const CGFloat kCLImageToolFadeoutDuration   = 0.2;

@interface CLImageToolBase : NSObject<CLImageToolProtocol>
{

}
@property (nonatomic, weak) _CLImageEditorViewController *editor;
@property (nonatomic, weak) CLImageToolInfo *toolInfo;

- (id)initWithImageEditor:(_CLImageEditorViewController*)editor withToolInfo:(CLImageToolInfo*)info;

- (void)setup;
- (void)cleanup;
- (void)executeWithCompletionBlock:(void(^)(UIImage *image, NSError *error, NSDictionary *userInfo))completionBlock;

- (UIImage*)imageForKey:(NSString*)key defaultImageName:(NSString*)defaultImageName;

@end


text:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/dmapool.h>
#include <linux/list.h>

#include <asm/cacheflush.h>

#undef STATS

#ifdef STATS
#define DO_STATS(X) do { X ; } while (0)
#else
#define DO_STATS(X) do { } while (0)
#endif

/* ************************************************** */

struct safe_buffer {
	struct list_head node;

	/* original request */
	void		*ptr;
	size_t		size;
	int		direction;

	/* safe buffer info */
	struct dmabounce_pool *pool;
	void		*safe;
	dma_addr_t	safe_dma_addr;
};

struct dmabounce_pool {
	unsigned long	size;
	struct dma_pool	*pool;
#ifdef STATS
	unsigned long	allocs;
#endif
};

struct dmabounce_device_info {
	struct device *dev;
	struct list_head safe_buffers;
#ifdef STATS
	unsigned long total_allocs;
	unsigned long map_op_count;
	unsigned long bounce_count;
	int attr_res;
#endif
	struct dmabounce_pool	small;
	struct dmabounce_pool	large;

	rwlock_t lock;
};

#ifdef STATS
static ssize_t dmabounce_show(struct device *dev, struct device_attribute *attr,
			      char *buf)
{
	struct dmabounce_device_info *device_info = dev->archdata.dmabounce;
	return sprintf(buf, "%lu %lu %lu %lu %lu %lu\n",
		device_info->small.allocs,
		device_info->large.allocs,
		device_info->total_allocs - device_info->small.allocs -
			device_info->large.allocs,
		device_info->total_allocs,
		device_info->map_op_count,
		device_info->bounce_count);
}

static DEVICE_ATTR(dmabounce_stats, 0400, dmabounce_show, NULL);
#endif

/* allocate a 'safe' buffer and keep track of it */
static inline struct safe_buffer *
alloc_safe_buffer(struct dmabounce_device_info *device_info, void *ptr,
		  size_t size, enum dma_data_direction dir)
{
	struct safe_buffer *buf;
	struct dmabounce_pool *pool;
	struct device *dev = device_info->dev;
	unsigned long flags;

	dev_dbg(dev, "%s(ptr=%p, size=%d, dir=%d)\n",
		__func__, ptr, size, dir);

	if (size <= device_info->small.size) {
		pool = &device_info->small;
	} else if (size <= device_info->large.size) {
		pool = &device_info->large;
	} else {
		pool = NULL;
	}

	buf = kmalloc(sizeof(struct safe_buffer), GFP_ATOMIC);
	if (buf == NULL) {
		dev_warn(dev, "%s: kmalloc failed\n", __func__);
		return NULL;
	}

	buf->ptr = ptr;
	buf->size = size;
	buf->direction = dir;
	buf->pool = pool;

	if (pool) {
		buf->safe = dma_pool_alloc(pool->pool, GFP_ATOMIC,
					   &buf->safe_dma_addr);
	} else {
		buf->safe = dma_alloc_coherent(dev, size, &buf->safe_dma_addr,
					       GFP_ATOMIC);
	}

	if (buf->safe == NULL) {
		dev_warn(dev,
			 "%s: could not alloc dma memory (size=%d)\n",
			 __func__, size);
		kfree(buf);
		return NULL;
	}

#ifdef STATS
	if (pool)
		pool->allocs++;
	device_info->total_allocs++;
#endif

	write_lock_irqsave(&device_info->lock, flags);

	list_add(&buf->node, &device_info->safe_buffers);

	write_unlock_irqrestore(&device_info->lock, flags);

	return buf;
}

/* determine if a buffer is from our "safe" pool */
static inline struct safe_buffer *
find_safe_buffer(struct dmabounce_device_info *device_info, dma_addr_t safe_dma_addr)
{
	struct safe_buffer *b, *rb = NULL;
	unsigned long flags;

	read_lock_irqsave(&device_info->lock, flags);

	list_for_each_entry(b, &device_info->safe_buffers, node)
		if (b->safe_dma_addr == safe_dma_addr) {
			rb = b;
			break;
		}

	read_unlock_irqrestore(&device_info->lock, flags);
	return rb;
}

static inline void
free_safe_buffer(struct dmabounce_device_info *device_info, struct safe_buffer *buf)
{
	unsigned long flags;

	dev_dbg(device_info->dev, "%s(buf=%p)\n", __func__, buf);

	write_lock_irqsave(&device_info->lock, flags);

	list_del(&buf->node);

	write_unlock_irqrestore(&device_info->lock, flags);

	if (buf->pool)
		dma_pool_free(buf->pool->pool, buf->safe, buf->safe_dma_addr);
	else
		dma_free_coherent(device_info->dev, buf->size, buf->safe,
				    buf->safe_dma_addr);

	kfree(buf);
}

/* ************************************************** */

static inline dma_addr_t
map_single(struct device *dev, void *ptr, size_t size,
		enum dma_data_direction dir)
{
	struct dmabounce_device_info *device_info = dev->archdata.dmabounce;
	dma_addr_t dma_addr;
	int needs_bounce = 0;

	if (device_info)
		DO_STATS ( device_info->map_op_count++ );

	dma_addr = virt_to_dma(dev, ptr);

	if (dev->dma_mask) {
		unsigned long mask = *dev->dma_mask;
		unsigned long limit;

		limit = (mask + 1) & ~mask;
		if (limit && size > limit) {
			dev_err(dev, "DMA mapping too big (requested %#x "
				"mask %#Lx)\n", size, *dev->dma_mask);
			return ~0;
		}

		/*
		 * Figure out if we need to bounce from the DMA mask.
		 */
		needs_bounce = (dma_addr | (dma_addr + size - 1)) & ~mask;
	}

	if (device_info && (needs_bounce || dma_needs_bounce(dev, dma_addr, size))) {
		struct safe_buffer *buf;

		buf = alloc_safe_buffer(device_info, ptr, size, dir);
		if (buf == 0) {
			dev_err(dev, "%s: unable to map unsafe buffer %p!\n",
			       __func__, ptr);
			return 0;
		}

		dev_dbg(dev,
			"%s: unsafe buffer %p (phy=%p) mapped to %p (phy=%p)\n",
			__func__, buf->ptr, (void *) virt_to_dma(dev, buf->ptr),
			buf->safe, (void *) buf->safe_dma_addr);

		if ((dir == DMA_TO_DEVICE) ||
		    (dir == DMA_BIDIRECTIONAL)) {
			dev_dbg(dev, "%s: copy unsafe %p to safe %p, size %d\n",
				__func__, ptr, buf->safe, size);
			memcpy(buf->safe, ptr, size);
		}
		ptr = buf->safe;

		dma_addr = buf->safe_dma_addr;
	} else {
		/*
		 * We don't need to sync the DMA buffer since
		 * it was allocated via the coherent allocators.
		 */
		consistent_sync(ptr, size, dir);
	}

	return dma_addr;
}

static inline void
unmap_single(struct device *dev, dma_addr_t dma_addr, size_t size,
		enum dma_data_direction dir)
{
	struct dmabounce_device_info *device_info = dev->archdata.dmabounce;
	struct safe_buffer *buf = NULL;

	/*
	 * Trying to unmap an invalid mapping
	 */
	if (dma_mapping_error(dma_addr)) {
		dev_err(dev, "Trying to unmap invalid mapping\n");
		return;
	}

	if (device_info)
		buf = find_safe_buffer(device_info, dma_addr);

	if (buf) {
		BUG_ON(buf->size != size);

		dev_dbg(dev,
			"%s: unsafe buffer %p (phy=%p) mapped to %p (phy=%p)\n",
			__func__, buf->ptr, (void *) virt_to_dma(dev, buf->ptr),
			buf->safe, (void *) buf->safe_dma_addr);

		DO_STATS ( device_info->bounce_count++ );

		if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL) {
			void *ptr = buf->ptr;

			dev_dbg(dev,
				"%s: copy back safe %p to unsafe %p size %d\n",
				__func__, buf->safe, ptr, size);
			memcpy(ptr, buf->safe, size);

			/*
			 * DMA buffers must have the same cache properties
			 * as if they were really used for DMA - which means
			 * data must be written back to RAM.  Note that
			 * we don't use dmac_flush_range() here for the
			 * bidirectional case because we know the cache
			 * lines will be coherent with the data written.
			 */
			dmac_clean_range(ptr, ptr + size);
			outer_clean_range(__pa(ptr), __pa(ptr) + size);
		}
		free_safe_buffer(device_info, buf);
	}
}

static inline void
sync_single(struct device *dev, dma_addr_t dma_addr, size_t size,
		enum dma_data_direction dir)
{
	struct dmabounce_device_info *device_info = dev->archdata.dmabounce;
	struct safe_buffer *buf = NULL;

	if (device_info)
		buf = find_safe_buffer(device_info, dma_addr);

	if (buf) {
		/*
		 * Both of these checks from original code need to be
		 * commented out b/c some drivers rely on the following:
		 *
		 * 1) Drivers may map a large chunk of memory into DMA space
		 *    but only sync a small portion of it. Good example is
		 *    allocating a large buffer, mapping it, and then
		 *    breaking it up into small descriptors. No point
		 *    in syncing the whole buffer if you only have to
		 *    touch one descriptor.
		 *
		 * 2) Buffers that are mapped as DMA_BIDIRECTIONAL are
		 *    usually only synced in one dir at a time.
		 *
		 * See drivers/net/eepro100.c for examples of both cases.
		 *
		 * -ds
		 *
		 * BUG_ON(buf->size != size);
		 * BUG_ON(buf->direction != dir);
		 */

		dev_dbg(dev,
			"%s: unsafe buffer %p (phy=%p) mapped to %p (phy=%p)\n",
			__func__, buf->ptr, (void *) virt_to_dma(dev, buf->ptr),
			buf->safe, (void *) buf->safe_dma_addr);

		DO_STATS ( device_info->bounce_count++ );

		switch (dir) {
		case DMA_FROM_DEVICE:
			dev_dbg(dev,
				"%s: copy back safe %p to unsafe %p size %d\n",
				__func__, buf->safe, buf->ptr, size);
			memcpy(buf->ptr, buf->safe, size);
			break;
		case DMA_TO_DEVICE:
			dev_dbg(dev,
				"%s: copy out unsafe %p to safe %p, size %d\n",
				__func__,buf->ptr, buf->safe, size);
			memcpy(buf->safe, buf->ptr, size);
			break;
		case DMA_BIDIRECTIONAL:
			BUG();	/* is this allowed?  what does it mean? */
		default:
			BUG();
		}
		/*
		 * No need to sync the safe buffer - it was allocated
		 * via the coherent allocators.
		 */
	} else {
		consistent_sync(dma_to_virt(dev, dma_addr), size, dir);
	}
}

/* ************************************************** */

/*
 * see if a buffer address is in an 'unsafe' range.  if it is
 * allocate a 'safe' buffer and copy the unsafe buffer into it.
 * substitute the safe buffer for the unsafe one.
 * (basically move the buffer from an unsafe area to a safe one)
 */
dma_addr_t
dma_map_single(struct device *dev, void *ptr, size_t size,
		enum dma_data_direction dir)
{
	dma_addr_t dma_addr;

	dev_dbg(dev, "%s(ptr=%p,size=%d,dir=%x)\n",
		__func__, ptr, size, dir);

	BUG_ON(dir == DMA_NONE);

	dma_addr = map_single(dev, ptr, size, dir);

	return dma_addr;
}

/*
 * see if a mapped address was really a "safe" buffer and if so, copy
 * the data from the safe buffer back to the unsafe buffer and free up
 * the safe buffer.  (basically return things back to the way they
 * should be)
 */

void
dma_unmap_single(struct device *dev, dma_addr_t dma_addr, size_t size,
			enum dma_data_direction dir)
{
	dev_dbg(dev, "%s(ptr=%p,size=%d,dir=%x)\n",
		__func__, (void *) dma_addr, size, dir);

	BUG_ON(dir == DMA_NONE);

	unmap_single(dev, dma_addr, size, dir);
}

int
dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
		enum dma_data_direction dir)
{
	int i;

	dev_dbg(dev, "%s(sg=%p,nents=%d,dir=%x)\n",
		__func__, sg, nents, dir);

	BUG_ON(dir == DMA_NONE);

	for (i = 0; i < nents; i++, sg++) {
		struct page *page = sg->page;
		unsigned int offset = sg->offset;
		unsigned int length = sg->length;
		void *ptr = page_address(page) + offset;

		sg->dma_address =
			map_single(dev, ptr, length, dir);
	}

	return nents;
}

void
dma_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
		enum dma_data_direction dir)
{
	int i;

	dev_dbg(dev, "%s(sg=%p,nents=%d,dir=%x)\n",
		__func__, sg, nents, dir);

	BUG_ON(dir == DMA_NONE);

	for (i = 0; i < nents; i++, sg++) {
		dma_addr_t dma_addr = sg->dma_address;
		unsigned int length = sg->length;

		unmap_single(dev, dma_addr, length, dir);
	}
}

void
dma_sync_single_for_cpu(struct device *dev, dma_addr_t dma_addr, size_t size,
				enum dma_data_direction dir)
{
	dev_dbg(dev, "%s(ptr=%p,size=%d,dir=%x)\n",
		__func__, (void *) dma_addr, size, dir);

	sync_single(dev, dma_addr, size, dir);
}

void
dma_sync_single_for_device(struct device *dev, dma_addr_t dma_addr, size_t size,
				enum dma_data_direction dir)
{
	dev_dbg(dev, "%s(ptr=%p,size=%d,dir=%x)\n",
		__func__, (void *) dma_addr, size, dir);

	sync_single(dev, dma_addr, size, dir);
}

void
dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg, int nents,
			enum dma_data_direction dir)
{
	int i;

	dev_dbg(dev, "%s(sg=%p,nents=%d,dir=%x)\n",
		__func__, sg, nents, dir);

	BUG_ON(dir == DMA_NONE);

	for (i = 0; i < nents; i++, sg++) {
		dma_addr_t dma_addr = sg->dma_address;
		unsigned int length = sg->length;

		sync_single(dev, dma_addr, length, dir);
	}
}

void
dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg, int nents,
			enum dma_data_direction dir)
{
	int i;

	dev_dbg(dev, "%s(sg=%p,nents=%d,dir=%x)\n",
		__func__, sg, nents, dir);

	BUG_ON(dir == DMA_NONE);

	for (i = 0; i < nents; i++, sg++) {
		dma_addr_t dma_addr = sg->dma_address;
		unsigned int length = sg->length;

		sync_single(dev, dma_addr, length, dir);
	}
}

static int
dmabounce_init_pool(struct dmabounce_pool *pool, struct device *dev, const char *name,
		    unsigned long size)
{
	pool->size = size;
	DO_STATS(pool->allocs = 0);
	pool->pool = dma_pool_create(name, dev, size,
				     0 /* byte alignment */,
				     0 /* no page-crossing issues */);

	return pool->pool ? 0 : -ENOMEM;
}

int
dmabounce_register_dev(struct device *dev, unsigned long small_buffer_size,
			unsigned long large_buffer_size)
{
	struct dmabounce_device_info *device_info;
	int ret;

	device_info = kmalloc(sizeof(struct dmabounce_device_info), GFP_ATOMIC);
	if (!device_info) {
		printk(KERN_ERR
			"Could not allocated dmabounce_device_info for %s",
			dev->bus_id);
		return -ENOMEM;
	}

	ret = dmabounce_init_pool(&device_info->small, dev,
				  "small_dmabounce_pool", small_buffer_size);
	if (ret) {
		dev_err(dev,
			"dmabounce: could not allocate DMA pool for %ld byte objects\n",
			small_buffer_size);
		goto err_free;
	}

	if (large_buffer_size) {
		ret = dmabounce_init_pool(&device_info->large, dev,
					  "large_dmabounce_pool",
					  large_buffer_size);
		if (ret) {
			dev_err(dev,
				"dmabounce: could not allocate DMA pool for %ld byte objects\n",
				large_buffer_size);
			goto err_destroy;
		}
	}

	device_info->dev = dev;
	INIT_LIST_HEAD(&device_info->safe_buffers);
	rwlock_init(&device_info->lock);

#ifdef STATS
	device_info->total_allocs = 0;
	device_info->map_op_count = 0;
	device_info->bounce_count = 0;
	device_info->attr_res = device_create_file(dev, &dev_attr_dmabounce_stats);
#endif

	dev->archdata.dmabounce = device_info;

	printk(KERN_INFO "dmabounce: registered device %s on %s bus\n",
		dev->bus_id, dev->bus->name);

	return 0;

 err_destroy:
	dma_pool_destroy(device_info->small.pool);
 err_free:
	kfree(device_info);
	return ret;
}

void
dmabounce_unregister_dev(struct device *dev)
{
	struct dmabounce_device_info *device_info = dev->archdata.dmabounce;

	dev->archdata.dmabounce = NULL;

	if (!device_info) {
		printk(KERN_WARNING
			"%s: Never registered with dmabounce but attempting" \
			"to unregister!\n", dev->bus_id);
		return;
	}

	if (!list_empty(&device_info->safe_buffers)) {
		printk(KERN_ERR
			"%s: Removing from dmabounce with pending buffers!\n",
			dev->bus_id);
		BUG();
	}

	if (device_info->small.pool)
		dma_pool_destroy(device_info->small.pool);
	if (device_info->large.pool)
		dma_pool_destroy(device_info->large.pool);

#ifdef STATS
	if (device_info->attr_res == 0)
		device_remove_file(dev, &dev_attr_dmabounce_stats);
#endif

	kfree(device_info);

	printk(KERN_INFO "dmabounce: device %s on %s bus unregistered\n",
		dev->bus_id, dev->bus->name);
}

EXPORT_SYMBOL(dma_map_single);
EXPORT_SYMBOL(dma_unmap_single);
EXPORT_SYMBOL(dma_map_sg);
EXPORT_SYMBOL(dma_unmap_sg);
EXPORT_SYMBOL(dma_sync_single_for_cpu);
EXPORT_SYMBOL(dma_sync_single_for_device);
EXPORT_SYMBOL(dma_sync_sg);
EXPORT_SYMBOL(dmabounce_register_dev);
EXPORT_SYMBOL(dmabounce_unregister_dev);

MODULE_AUTHOR("Christopher Hoover <ch@hpl.hp.com>, Deepak Saxena <dsaxena@plexity.net>");
MODULE_DESCRIPTION("Special dma_{map/unmap/dma_sync}_* routines for systems with limited DMA windows");
MODULE_LICENSE("GPL");


text:
nerv-web
================

Website to interact with nerv system.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <properties>
        <project.version>0.3.0-SNAPSHOT</project.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.7</java.version>
        <scala.version>2.10.4</scala.version>
        <scala.binary.version>2.10</scala.binary.version>
        <hadoop.version>2.4.0</hadoop.version>
        <spark.version>1.3.0</spark.version>
        <PermGen>512m</PermGen>
        <MaxPermGen>2g</MaxPermGen>
        <failsafe.version>2.18</failsafe.version>
    </properties>

    <groupId>org.tribbloid.spookystuff</groupId>
    <artifactId>spookystuff</artifactId>
    <packaging>pom</packaging>
    <version>0.3.0-SNAPSHOT</version>
    <name>spookystuff</name>
    <url>https://github.com/tribbloid/spookystuff</url>

    <repositories>
        <repository>
            <id>apache-repo</id>
            <name>Apache Repository</name>
            <url>https://repository.apache.org/content/repositories/releases</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>typesafe</id>
            <name>Typesafe - releases</name>
            <url>http://repo.typesafe.com/typesafe/releases/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>typesafe-ivy</id>
            <name>Typesafe - ivy - releases</name>
            <url>http://repo.typesafe.com/typesafe/maven-ivy-releases/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>oss.sonatype.org</id>
            <name>sonatype sapshots</name>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </repository>
    </repositories>

    <modules>
        <module>core</module>
        <module>integration</module>
        <module>example</module>
        <module>shell</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.scalatest</groupId>
            <artifactId>scalatest_${scala.binary.version}</artifactId>
            <version>2.2.4</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <outputDirectory>target/scala/classes</outputDirectory>
        <testOutputDirectory>target/scala/test-classes</testOutputDirectory>
        <plugins>
            <plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>scala-maven-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <execution>
                        <id>scala-compile-first</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>scala-test-compile-first</id>
                        <phase>process-test-resources</phase>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                    <!--<execution>-->
                        <!--<id>attach-scaladocs</id>-->
                        <!--<phase>verify</phase>-->
                        <!--<goals>-->
                            <!--<goal>doc-jar</goal>-->
                        <!--</goals>-->
                    <!--</execution>-->
                </executions>
                <configuration>
                    <scalaVersion>${scala.version}</scalaVersion>
                    <recompileMode>incremental</recompileMode>
                    <useZincServer>true</useZincServer>
                    <args>
                        <arg>-unchecked</arg>
                        <arg>-deprecation</arg>
                    </args>
                    <jvmArgs>
                        <jvmArg>-Xms64m</jvmArg>
                        <jvmArg>-Xms1024m</jvmArg>
                        <jvmArg>-Xmx1024m</jvmArg>
                        <jvmArg>-XX:PermSize=${PermGen}</jvmArg>
                        <jvmArg>-XX:MaxPermSize=${MaxPermGen}</jvmArg>
                    </jvmArgs>
                    <javacArgs>
                        <javacArg>-source</javacArg>
                        <javacArg>${java.version}</javacArg>
                        <javacArg>-target</javacArg>
                        <javacArg>${java.version}</javacArg>
                    </javacArgs>
                    <!--<compilerPlugins>-->
                    <!--<compilerPlugin>-->
                    <!--<groupId>org.scalamacros</groupId>-->
                    <!--<artifactId>paradise_2.10.4</artifactId>-->
                    <!--<version>2.0.1</version>-->
                    <!--</compilerPlugin>-->
                    <!--</compilerPlugins>-->
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.scalatest</groupId>
                <artifactId>scalatest-maven-plugin</artifactId>
                <version>1.0</version>
                <executions>
                    <execution>
                        <id>test</id>
                        <goals>
                            <goal>test</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <!--<plugin>-->
                <!--<groupId>com.github.klieber</groupId>-->
                <!--<artifactId>phantomjs-maven-plugin</artifactId>-->
                <!--<version>0.4</version>-->
                <!--<executions>-->
                    <!--<execution>-->
                        <!--<goals>-->
                            <!--<goal>install</goal>-->
                        <!--</goals>-->
                    <!--</execution>-->
                <!--</executions>-->
                <!--<configuration>-->
                    <!--<version>1.9.8</version>-->
                <!--</configuration>-->
            <!--</plugin>-->
            <!--<plugin>-->
                <!--<groupId>org.apache.maven.plugins</groupId>-->
                <!--<artifactId>maven-surefire-plugin</artifactId>-->
                <!--<version>2.17</version>-->
                <!--<configuration>-->
                    <!--<systemPropertyVariables>-->
                        <!--<phantomjs.binary>${phantomjs.binary}</phantomjs.binary>-->
                    <!--</systemPropertyVariables>-->
                <!--</configuration>-->
            <!--</plugin>-->
        </plugins>
    </build>

</project>


text:
"""Semi-automated tests of Chrome with NVDA.

This file performs (semi) automated tests of Chrome with NVDA
(NonVisual Desktop Access), a popular open-source screen reader for
visually impaired users on Windows. It works by launching Chrome in a
subprocess, then launching NVDA in a special environment that simulates
speech rather than actually speaking, and ignores all events coming from
processes other than a specific Chrome process ID. Each test automates
Chrome with a series of actions and asserts that NVDA gives the expected
feedback in response.

The tests are "semi" automated in the sense that they are not intended to be
run from any developer machine, or on a buildbot - it requires setting up the
environment according to the instructions in README.txt, then running the
test script, then filing bugs for any potential failures. If the environment
is set up correctly, the actual tests should run automatically and unattended.
"""

from __future__ import print_function

import os
import pywinauto
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import time
import unittest

CHROME_PROFILES_PATH = os.path.join(os.getcwd(), 'chrome_profiles')
CHROME_PATH = os.path.join(os.environ['USERPROFILE'],
                           'AppData',
                           'Local',
                           'Google',
                           'Chrome SxS',
                           'Application',
                           'chrome.exe')
NVDA_PATH = os.path.join(os.getcwd(),
                         'nvdaPortable',
                         'nvda_noUIAccess.exe')
NVDA_PROCTEST_PATH = os.path.join(os.getcwd(),
                                  'nvda-proctest')
NVDA_LOGPATH = os.path.join(os.getcwd(),
                            'nvda_log.txt')
WAIT_FOR_SPEECH_TIMEOUT_SECS = 3.0

class NvdaChromeTest(unittest.TestCase):
  @classmethod
  def setUpClass(cls):
    print('user data: %s' % CHROME_PROFILES_PATH)
    print('chrome: %s' % CHROME_PATH)
    print('nvda: %s' % NVDA_PATH)
    print('nvda_proctest: %s' % NVDA_PROCTEST_PATH)

    tasklist = subprocess.Popen("tasklist", shell=True, stdout=subprocess.PIPE)
    tasklist_output = tasklist.communicate()[0].decode('utf8').split('\r\n')
    for task in tasklist_output:
      if (task.split(' ', 1)[0] == "nvda.exe"):
        print("nvda.exe is running!  Please kill it before running these tests")
        sys.exit()

    print()
    print('Clearing user data directory and log file from previous runs')
    if os.access(NVDA_LOGPATH, os.F_OK):
      os.remove(NVDA_LOGPATH)
    if os.access(CHROME_PROFILES_PATH, os.F_OK):
      shutil.rmtree(CHROME_PROFILES_PATH)
    os.mkdir(CHROME_PROFILES_PATH, 0o777)

    def handler(signum, frame):
      print('Test interrupted, attempting to kill subprocesses.')
      self.tearDown()
      sys.exit()
    signal.signal(signal.SIGINT, handler)

  def setUp(self):
    user_data_dir = tempfile.mkdtemp(dir = CHROME_PROFILES_PATH)
    args = [CHROME_PATH,
            '--user-data-dir=%s' % user_data_dir,
            '--no-first-run',
            'about:blank']
    print()
    print(' '.join(args))
    self._chrome_proc = subprocess.Popen(args)
    self._chrome_proc.poll()
    if self._chrome_proc.returncode is None:
      print('Chrome is running')
    else:
      print('Chrome exited with code', self._chrome_proc.returncode)
      sys.exit()
    print('Chrome pid: %d' % self._chrome_proc.pid)

    os.environ['NVDA_SPECIFIC_PROCESS'] = str(self._chrome_proc.pid)

    args = [NVDA_PATH,
            '-m',
            '-c',
            NVDA_PROCTEST_PATH,
            '-f',
            NVDA_LOGPATH]
    self._nvda_proc = subprocess.Popen(args)
    self._nvda_proc.poll()
    if self._nvda_proc.returncode is None:
      print('NVDA is running')
    else:
      print('NVDA exited with code', self._nvda_proc.returncode)
      sys.exit()
    print('NVDA pid: %d' % self._nvda_proc.pid)

    app = pywinauto.application.Application()
    app.connect(process = self._chrome_proc.pid)
    self._pywinauto_window = app.top_window()
    self.last_nvda_log_line = 0;

  def tearDown(self):
    print()
    print('Shutting down')

    self._chrome_proc.poll()
    if self._chrome_proc.returncode is None:
      print('Killing Chrome subprocess')
      self._chrome_proc.kill()
    else:
      print('Chrome already died.')

    self._nvda_proc.poll()
    if self._nvda_proc.returncode is None:
      print('Killing NVDA subprocess')
      self._nvda_proc.kill()
    else:
      print('NVDA already died.')

  def _GetSpeechFromNvdaLogFile(self):
    """Return everything NVDA would have spoken as a list of strings.

    Parses lines like this from NVDA's log file:
      Speaking [LangChangeCommand ('en'), u'Google Chrome', u'window']
      Speaking character u'slash'

    Returns a single list of strings like this:
      [u'Google Chrome', u'window', u'slash']
    """
    if not os.access(NVDA_LOGPATH, os.F_OK):
      return []
    lines = open(NVDA_LOGPATH).readlines()[self.last_nvda_log_line:]
    regex = re.compile(r"u'((?:[^\'\\]|\\.)*)\'")
    result = []
    for line in lines:
      for m in regex.finditer(line):
        speech_with_whitespace = m.group(1)
        speech_stripped = re.sub(r'\s+', ' ', speech_with_whitespace).strip()
        result.append(speech_stripped)
    self.last_nvda_log_line = len(lines) - 1
    return result

  def _ArrayInArray(self, lines, expected):
    positions = len(lines) - len(expected) + 1;
    if (positions >= 0):
      # loop through the number of positions that the subset can hold
      for index in range(positions):
        if (lines[index : index + len(expected)] == expected):
          return True
    return False

  def _TestForSpeech(self, expected):
    """Block until the last speech in NVDA's log file is the given string(s).

    Repeatedly parses the log file until the last speech line(s) in the
    log file match the given strings, or it times out.

    Args:
      expected: string or a list of string - only succeeds if these are the last
        strings spoken, in order.
    """
    if type(expected) is type(''):
      expected = [expected]
    start_time = time.time()
    while True:
      lines = self._GetSpeechFromNvdaLogFile()

      if self._ArrayInArray(lines, expected):
        return True

      if time.time() - start_time >= WAIT_FOR_SPEECH_TIMEOUT_SECS:
        self.fail("Test for expected speech failed.\n\nExpected:\n" +
          str(expected) +
          ".\n\nActual:\n" + str(lines));
        return False
      time.sleep(0.1)

  #
  # Tests
  #

  def testTypingInOmnibox(self):
    # Ctrl+A: Select all.
    self._pywinauto_window.TypeKeys('^l')
    self._TestForSpeech(["main tool bar"]);

    self._pywinauto_window.TypeKeys('xyz')
    self._pywinauto_window.TypeKeys('^a')
    self._TestForSpeech(["selected about:blank"]);

  def testFocusToolbarButton(self):
    # Alt+Shift+T.
    self._pywinauto_window.TypeKeys('%+T')
    self._TestForSpeech('Reload button Reload this page')
    # this is flakey because sometimes this will be a stop button too.

  def testReadAllOnPageLoad(self):
    # Load data url.

    # Focus the url bar with control-L
    self._pywinauto_window.TypeKeys('^l')

    self._pywinauto_window.TypeKeys('^a')

    self._pywinauto_window.TypeKeys('data:text/html,Hello<p>World.')
    self._pywinauto_window.TypeKeys('{ENTER}')

    self._TestForSpeech(
        ['Hello',
         'World.'])

if __name__ == '__main__':
  unittest.main()


text:
package io.plasmap.model

import io.plasmap.model.geometry.Point

sealed trait OsmObject{

  def id: OsmId
  def user: Option[OsmUser]
  def version: OsmVersion

  def tags:List[OsmTag]

  def tagsToString = tags.mkString("[",",","]")

  def isNode = this match {
    case _:OsmNode      => true
    case _:OsmWay       => false
    case _:OsmRelation  => false
  }

  def isWay = this match {
    case _:OsmNode      => false
    case _:OsmWay       => true
    case _:OsmRelation  => false
  }

  def isRelation = this match {
    case _:OsmNode      => false
    case _:OsmWay       => false
    case _:OsmRelation  => true
  }

  def nodeOption: Option[OsmNode] = this match {
    case n: OsmNode     => Some(n)
    case _: OsmWay      => None
    case _: OsmRelation => None
  }

  def wayOption: Option[OsmWay] = this match {
    case _: OsmNode     => None
    case w: OsmWay      => Some(w)
    case _: OsmRelation => None
  }

  def relationOption: Option[OsmRelation] = this match {
    case _: OsmNode     => None
    case _: OsmWay      => None
    case r: OsmRelation => Some(r)
  }

  def fold[A](
               node     :OsmNode     => A,
               way      :OsmWay      => A,
               relation :OsmRelation => A) = {
    this match {
      case n:OsmNode      => node(n)
      case w:OsmWay       => way(w)
      case r:OsmRelation  => relation(r)
    }
  }

}
case class OsmNode(id: OsmId, user: Option[OsmUser] = None, version:OsmVersion = OsmVersion(), tags: List[OsmTag], point : Point) extends OsmObject{
  override def toString() = {
    StringBuilder.newBuilder.++=(id.toString).++=(",").++=(tagsToString).++=(",").++=(point.toString).toString()
  }
}
case class OsmWay( id: OsmId,
                   user: Option[OsmUser] = None,
                   version:OsmVersion = OsmVersion(),
                   tags : List[OsmTag],
                   nds : List[OsmId]) extends OsmObject{
  override def toString() = {
    StringBuilder.newBuilder.++=(id.toString).++=(",").++=(tagsToString).++=(",").++=(nds.mkString("[",",","]")).toString()
  }
}
case class OsmRelation(id: OsmId, user: Option[OsmUser] = None, version:OsmVersion = OsmVersion(), tags : List[OsmTag], refs : List[OsmMember]) extends OsmObject {
 override def toString() = {
   StringBuilder.newBuilder.++=(id.toString).++=(",").++=(tagsToString).++=(",").++=(refs.mkString("[",",","]")).toString()
 }
}


text:
package com.drew.imaging.jpeg;

import com.drew.lang.annotations.NotNull;
import com.drew.lang.annotations.Nullable;

import java.util.*;

/**
 * Holds a collection of JPEG data segments.  This need not necessarily be all segments
 * within the JPEG. For example, it may be convenient to store only the non-image
 * segments when analysing metadata.
 *

 * Segments are keyed via their {@link JpegSegmentType}. Where multiple segments use the
 * same segment type, they will all be stored and available.
 *

 * Each segment type may contain multiple entries. Conceptually the model is:
 * Map<JpegSegmentType, Collection<byte[]>>. This class provides
 * convenience methods around that structure.
 *
 * @author Drew Noakes https://drewnoakes.com
 */
public class JpegSegmentData
{
    // TODO key this on JpegSegmentType rather than Byte, and hopefully lose much of the use of 'byte' with this class
    @NotNull
    private final HashMap<Byte, List<byte[]>> _segmentDataMap = new HashMap<Byte, List<byte[]>>(10);

    /**
     * Adds segment bytes to the collection.
     *
     * @param segmentType  the type of the segment being added
     * @param segmentBytes the byte array holding data for the segment being added
     */
    @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"})
    public void addSegment(byte segmentType, @NotNull byte[] segmentBytes)
    {
        getOrCreateSegmentList(segmentType).add(segmentBytes);
    }

    /**
     * Gets the set of JPEG segment type identifiers.
     */
    public Iterable<JpegSegmentType> getSegmentTypes()
    {
        Set<JpegSegmentType> segmentTypes = new HashSet<JpegSegmentType>();

        for (Byte segmentTypeByte : _segmentDataMap.keySet())
        {
            JpegSegmentType segmentType = JpegSegmentType.fromByte(segmentTypeByte);
            if (segmentType == null) {
                throw new IllegalStateException("Should not have a segmentTypeByte that is not in the enum: " + Integer.toHexString(segmentTypeByte));
            }
            segmentTypes.add(segmentType);
        }

        return segmentTypes;
    }

    /**
     * Gets the first JPEG segment data for the specified type.
     *
     * @param segmentType the JpegSegmentType for the desired segment
     * @return a byte[] containing segment data or null if no data exists for that segment
     */
    @Nullable
    public byte[] getSegment(byte segmentType)
    {
        return getSegment(segmentType, 0);
    }

    /**
     * Gets the first JPEG segment data for the specified type.
     *
     * @param segmentType the JpegSegmentType for the desired segment
     * @return a byte[] containing segment data or null if no data exists for that segment
     */
    @Nullable
    public byte[] getSegment(@NotNull JpegSegmentType segmentType)
    {
        return getSegment(segmentType.byteValue, 0);
    }

    /**
     * Gets segment data for a specific occurrence and type.  Use this method when more than one occurrence
     * of segment data for a given type exists.
     *
     * @param segmentType identifies the required segment
     * @param occurrence  the zero-based index of the occurrence
     * @return the segment data as a byte[], or null if no segment exists for the type & occurrence
     */
    @Nullable
    public byte[] getSegment(@NotNull JpegSegmentType segmentType, int occurrence)
    {
        return getSegment(segmentType.byteValue, occurrence);
    }

    /**
     * Gets segment data for a specific occurrence and type.  Use this method when more than one occurrence
     * of segment data for a given type exists.
     *
     * @param segmentType identifies the required segment
     * @param occurrence  the zero-based index of the occurrence
     * @return the segment data as a byte[], or null if no segment exists for the type & occurrence
     */
    @Nullable
    public byte[] getSegment(byte segmentType, int occurrence)
    {
        final List<byte[]> segmentList = getSegmentList(segmentType);

        return segmentList != null && segmentList.size() > occurrence
                ? segmentList.get(occurrence)
                : null;
    }

    /**
     * Returns all instances of a given JPEG segment.  If no instances exist, an empty sequence is returned.
     *
     * @param segmentType a number which identifies the type of JPEG segment being queried
     * @return zero or more byte arrays, each holding the data of a JPEG segment
     */
    @NotNull
    public Iterable<byte[]> getSegments(@NotNull JpegSegmentType segmentType)
    {
        return getSegments(segmentType.byteValue);
    }

    /**
     * Returns all instances of a given JPEG segment.  If no instances exist, an empty sequence is returned.
     *
     * @param segmentType a number which identifies the type of JPEG segment being queried
     * @return zero or more byte arrays, each holding the data of a JPEG segment
     */
    @NotNull
    public Iterable<byte[]> getSegments(byte segmentType)
    {
        final List<byte[]> segmentList = getSegmentList(segmentType);
        return segmentList == null ? new ArrayList<byte[]>() : segmentList;
    }

    @Nullable
    private List<byte[]> getSegmentList(byte segmentType)
    {
        return _segmentDataMap.get(segmentType);
    }

    @NotNull
    private List<byte[]> getOrCreateSegmentList(byte segmentType)
    {
        List<byte[]> segmentList;
        if (_segmentDataMap.containsKey(segmentType)) {
            segmentList = _segmentDataMap.get(segmentType);
        } else {
            segmentList = new ArrayList<byte[]>();
            _segmentDataMap.put(segmentType, segmentList);
        }
        return segmentList;
    }

    /**
     * Returns the count of segment data byte arrays stored for a given segment type.
     *
     * @param segmentType identifies the required segment
     * @return the segment count (zero if no segments exist).
     */
    public int getSegmentCount(@NotNull JpegSegmentType segmentType)
    {
        return getSegmentCount(segmentType.byteValue);
    }

    /**
     * Returns the count of segment data byte arrays stored for a given segment type.
     *
     * @param segmentType identifies the required segment
     * @return the segment count (zero if no segments exist).
     */
    public int getSegmentCount(byte segmentType)
    {
        final List<byte[]> segmentList = getSegmentList(segmentType);
        return segmentList == null ? 0 : segmentList.size();
    }

    /**
     * Removes a specified instance of a segment's data from the collection.  Use this method when more than one
     * occurrence of segment data exists for a given type exists.
     *
     * @param segmentType identifies the required segment
     * @param occurrence  the zero-based index of the segment occurrence to remove.
     */
    @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"})
    public void removeSegmentOccurrence(@NotNull JpegSegmentType segmentType, int occurrence)
    {
        removeSegmentOccurrence(segmentType.byteValue, occurrence);
    }

    /**
     * Removes a specified instance of a segment's data from the collection.  Use this method when more than one
     * occurrence of segment data exists for a given type exists.
     *
     * @param segmentType identifies the required segment
     * @param occurrence  the zero-based index of the segment occurrence to remove.
     */
    @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"})
    public void removeSegmentOccurrence(byte segmentType, int occurrence)
    {
        final List<byte[]> segmentList = _segmentDataMap.get(segmentType);
        segmentList.remove(occurrence);
    }

    /**
     * Removes all segments from the collection having the specified type.
     *
     * @param segmentType identifies the required segment
     */
    public void removeSegment(@NotNull JpegSegmentType segmentType)
    {
        removeSegment(segmentType.byteValue);
    }

    /**
     * Removes all segments from the collection having the specified type.
     *
     * @param segmentType identifies the required segment
     */
    public void removeSegment(byte segmentType)
    {
        _segmentDataMap.remove(segmentType);
    }

    /**
     * Determines whether data is present for a given segment type.
     *
     * @param segmentType identifies the required segment
     * @return true if data exists, otherwise false
     */
    public boolean containsSegment(@NotNull JpegSegmentType segmentType)
    {
        return containsSegment(segmentType.byteValue);
    }

    /**
     * Determines whether data is present for a given segment type.
     *
     * @param segmentType identifies the required segment
     * @return true if data exists, otherwise false
     */
    public boolean containsSegment(byte segmentType)
    {
        return _segmentDataMap.containsKey(segmentType);
    }
}


text:
@interface SNHomeStatusesResult : NSObject

// 微博数组(装着SNStatus模型)
@property (strong, nonatomic) NSArray *statuses;

// 近期的微博总数
@property (assign, nonatomic) int total_number;
@end


text:
import { LineResults } from "../LineResults";
import { CommandNames } from "../Names/CommandNames";
import { Command } from "./Command";
import { CommandResult } from "./CommandResult";
import { CommandMetadata } from "./Metadata/CommandMetadata";
import { SingleParameter } from "./Metadata/Parameters/SingleParameter";

/**
 * Starts a variable declaration.
 */
export class VariableStartCommand extends Command {
    /**
     * Metadata on the command.
     */
    private static metadata: CommandMetadata = new CommandMetadata(CommandNames.VariableStart)
        .withDescription("Starts a variable declaration")
        .withIndentation([1])
        .withParameters([
            new SingleParameter("name", "The name of the variable.", true),
            new SingleParameter("type", "The type of the variable.", true),
            new SingleParameter("value", "The start of the value of the variable.", true),
        ]);

    /**
     * @returns Metadata on the command.
     */
    public getMetadata(): CommandMetadata {
        return VariableStartCommand.metadata;
    }

    /**
     * Renders the command for a language with the given parameters.
     *
     * @param parameters   The command's name, followed by any parameters.
     * @returns Line(s) of code in the language.
     */
    public render(parameters: string[]): LineResults {
        const newParameters: string[] = ["variable"];
        for (let i = 1; i < parameters.length; i += 1) {
            const parametersSplit: string[] = parameters[i].split("\n");

            newParameters.push(parametersSplit[0]);
        }

        const output = this.context.convertParsed(newParameters).withAddSemicolon(false);

        // Languages like C# might need to pass a separate "{" through on the next line
        if (this.language.syntax.style.separateBraceLines) {
            if (parameters.length === 5) {
                output.commandResults.push(new CommandResult(parameters[4], 1));
            }
        } else {
            output.commandResults[output.commandResults.length - 1].indentation += 1;
        }

        return output;
    }
}


text:
This quick start demonstrates how to create a RESTful (JAX-RS) web service using Apache CXF and expose it using CDI running in a Java standalone container.

The REST service provides a customer service that supports the following operations

- PUT /customerservice/customers/ - to create or update a customer
- GET /customerservice/customers/{id} - to view a customer with the given id
- DELETE /customerservice/customers/{id} - to delete a customer with the given id
- GET /customerservice/orders/{orderId} - to view an order with the given id
- GET /customerservice/orders/{orderId}/products/{productId} - to view a specific product on an order with the given id

When the application is deployed, you can access the REST service using a web browser as shown in the screenshot below:

![Standalone REST diagram](https://raw.githubusercontent.com/fabric8io/fabric8/master/docs/images/cxfcdi-rest.png)

### Building this example

The example comes as source code and pre-built binaries with the fabric8 distribution.

To try the example you do not need to build from source first. Although building from source allows you to modify the source code, and re-deploy the changes to fabric. See more details on the fabric8 website about the [developer workflow](http://fabric8.io/gitbook/developer.html).

To build from the source code:

1. Change your working directory to `quickstarts/java/cxf-cdi` directory.
1. Run `mvn clean install` to build the quickstart.

After building from the source code, you can upload the changes to the fabric container:

1. It is assumed that you have already created a fabric and are logged into a container called `root`.
1. Change your working directory to `quickstarts/java/cxf-cdi` directory.
1. Run `mvn fabric8:deploy` to upload the quickstart to the fabric container.

If you run the `fabric8:deploy` command for the first then, it will ask you for the username and password to login the fabric container.
And then store this information in the local Maven settings file. You can find more details about this on the fabric8 website about the [Maven Plugin](http://fabric8.io/gitbook/mavenPlugin.html).

## How to run this example

The following information is divided into two sections, whether you are using the command line shell in fabric, or using the web console

### Using the command line shell

You can deploy and run this example at the console command line, as follows:

1. It is assumed that you have already created a fabric and are logged into a container called `root`.
1. Create a new child container and deploy the `quickstarts-java-cxf.cdi` profile in a single step, by entering the
 following command at the console:

        fabric:container-create-child --profile quickstarts-java-cxf.cdi root mychild

1. Wait for the new child container, `mychild`, to start up. Use the `fabric:container-list` command to check the status of the `mychild` container and wait until the `[provision status]` is shown as `success`.

### Using the web console

You can deploy and run this example from the web console, as follows

1. It is assumed that you have already created a fabric and are logged into a container called `root`.
1. Login the web console
1. Click the Wiki button in the navigation bar
1. Select `quickstarts` --> `java` --> `cxf.cdi`
1. Click the `New` button in the top right corner
1. In the Create New Container page, enter `mychild` in the Container Name field, and click the *Create and start container* button

### How to try this example

To use the application be sure to have deployed the quickstart in fabric8 as described above.

### Access services using a web browser

You can use any browser to perform a HTTP GET.  This allows you to very easily test a few of the RESTful services we defined:

Notice: As fabric8 assigns a free dynamic port to the Java container, the port number may vary on your system.

Use this URL to display the root of the REST service, which also allows to access the WADL of the service:

    http://localhost:8080/cxfcdi

Use this URL to display the XML representation for customer 123:

    http://localhost:8080/cxfcdi/cxfcdi/customerservice/customers/123

You can also access the XML representation for order 223 ...

    http://localhost:8080/rest/cxf/customerservice/orders/223

**Note:** if you use Safari, you will only see the text elements but not the XML tags - you can view the entire document with 'View Source'

### To run a command-line utility:

You can use a command-line utility, such as cURL or wget, to perform the HTTP requests.  We have provided a few files with sample XML representations in `src/test/resources`, so we will use those for testing our services.

1. Open a command prompt and change directory to `cxf-cdi`.
2. Run the following curl commands (curl commands may not be available on all platforms):

    * Create a customer

            curl -X POST -T src/test/resources/add_customer.xml -H "Content-Type: text/xml" http://localhost:8080/cxfcdi/cxfcdi/customerservice/customers

    * Retrieve the customer instance with id 123

            curl http://localhost:8080/cxfcdi/cxfcdi/customerservice/customers/123

    * Update the customer instance with id 123

            curl -X PUT -T src/test/resources/update_customer.xml -H "Content-Type: text/xml" http://localhost:8080/cxfcdi/cxfcdi/customerservice/customers

    * Delete the customer instance with id 123

             curl -X DELETE http://localhost:8080/cxfcdi/cxfcdi/customerservice/customers/123

## Undeploy this example

The following information is divded into two sections, whether you are using the command line shell in fabric, or using the web console

### Using the command line shell

To stop and undeploy the example in fabric8:

1. Stop and delete the child container by entering the following command at the console:

        fabric:container-stop mychild
        fabric:container-delete mychild

### Using the web console

To stop and undeploy the example in fabric8:

1. In the web console, click the *Runtime* button in the navigation bar.
1. Select the `mychild` container in the *Containers* list, and click the *Stop* button in the top right corner


text:
package com.facebook.buck.util;

/**
 * Convenience wrapper class to attach closeable functionality to non-closeable class so it can be
 * used with try-with-resources to make sure resources are always released and proper exception
 * suppression is used
 *
 *
Example:
 *
 *
class Main {
 *
 *
private static void finalizeMyClass(MyClass obj) throws IOException {
 *
 *
obj.shutdown();
 *
 *
}
 *
 *
public static void main() {
 *
 *
try (CloseableWrapper<MyClass, IOException> myClassWrapper =
 *
 *
CloseableWrapper.of(new MyClass(), Main::finalizeMyClass)) {
 *
 *
myClassWrapper.get().doSomething();
 *
 *
}
 *
 *
}
 */
public class CloseableWrapper<T, E extends Exception> implements AutoCloseable {

  private final T obj;
  private final ThrowingConsumer<T, E> closer;
  private boolean closed = false;

  private CloseableWrapper(T obj, ThrowingConsumer<T, E> closer) {
    this.obj = obj;
    this.closer = closer;
  }

  /**
   * Wrap an object with {@code AutoCloseable} interface and provide a function to replace a {@code
   * close} method The wrapper is idempotent, i.e. it will call closer function exactly once, even
   * if user calls {@code close} multiple times.
   *
   * @param obj Any class that does not implement AutoCloseable interface which is hard to extend
   * @param closer A function to call on close
   */
  public static <T, E extends Exception> CloseableWrapper<T, E> of(
      T obj, ThrowingConsumer<T, E> closer) {
    return new CloseableWrapper<>(obj, closer);
  }

  /** @return Original wrapped object */
  public T get() {
    return obj;
  }

  @Override
  public void close() throws E {
    if (closed) {
      return;
    }
    closed = true;
    closer.accept(obj);
  }

  /**
   * The version of {@code Consumer<T>} that can throw an exception. It only exists because {@code
   * AutoCloseable} interface defines its {@code close} function to throw {@code Exception}
   */
  @FunctionalInterface
  public interface ThrowingConsumer<T, E extends Exception> {
    void accept(T t) throws E;
  }
}


text:
var Phone = null;

$(function () {

    $("#call").on('click', function (e) {
        Phone.call($("#number").val());
    });

    $("#end").on('click', function (e) {
        Phone.end();
    });

    $("#saveSettings").on('click', function () {
        console.log('save!');
        $.jStorage.set('uri', $('#uri').val());
        $.jStorage.set('name', $('#name').val());
        $.jStorage.set('password', $('#password').val());
        $.jStorage.set('authName', $('#authName').val());
        $.jStorage.set('wsServer', $('#wsServer').val());

        $('#myModal').modal('hide');
        initPhone();
    });

    function initFromStorage () {
        $("#uri").val($.jStorage.get('uri'));
        $("#name").val($.jStorage.get('name'));
        $("#password").val($.jStorage.get('password'));
        $("#authName").val($.jStorage.get('authName'));
        $("#wsServer").val($.jStorage.get('wsServer'));

        return {
            uri: $.jStorage.get('uri'),
            name: $.jStorage.get('name'),
            password: $.jStorage.get('password'),
            authName: $.jStorage.get('authName'),
            wsServer: $.jStorage.get('wsServer')
        };
    };

    function checkEmpty (param) {
        return param === '';
    };

    function checkParams (creds) {
        return checkEmpty(creds.uri) &&
               checkEmpty(creds.name) &&
               checkEmpty(creds.password) &&
               checkEmpty(creds.authName) &&
               checkEmpty(creds.wsServer);
    };

    function initPhone () {
        var creds = initFromStorage();
        console.log(creds);

        if (!checkParams(creds)) {
            var config = {
                uri: creds.uri,
                wsServers: creds.wsServer,
                authorizationUser: creds.authName,
                password: creds.password,
                hackIpInContact: true,
                register: true,
                rtcpMuxPolicy: "negotiate",
                log: {
                    builtinEnabled: false,
                },
                stunServers: [
                    "stun.l.google.com:19302",
                    "stun.stunprotocol.org:3478",
                    "stun.voiparound.com",
                    "stun.voipbuster.com",
                    "stun.turnservers.com:3478"
                ],
            };

            Phone = new phone();
            Phone.init(config);
        } else {
            console.log('not set config params');
        }

    };

    initPhone();
});


text:
cybozu-to-gcalender
===================
Gmailで受信したCybozuの予定をGoogleCalendarに登録してくれる

##Requirement
```
ruby 2.1.3

CybozuでGmail通知設定を済ませ、GmailでCybozu用の受信boxとフィルタを設定、API.yamlにgmailのid・pw・受信box・googleapiのid, secretを記入しておくこと

```

##Install
```
bundle install --path vendor/bundle
```

##Usage
```
bundle exec ruby load-cybozu.rb
bundle exec ruby register-gcalendar.rb
```


text:
package cn.ycoder.android.demo.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.BindView;
import cn.ycoder.android.demo.R;
import cn.ycoder.android.demo.presenter.TestPresenter;
import cn.ycoder.android.demo.store.AppStore;
import cn.ycoder.android.library.BaseApplication;
import cn.ycoder.android.library.ToolbarFragment;
import cn.ycoder.android.library.tool.ToastUtils;
import cn.ycoder.android.library.widget.MultipleStatusView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

/**
 * @author 启研
 * @created at 2017/4/20 11:29
 */
@Route(path = "/main/test")
public class TestFragment extends ToolbarFragment implements TestPresenter.View {

  @BindView(R.id.multipleStatusView)
  MultipleStatusView multipleStatusView;
  @BindView(R.id.text)
  TextView text;
  @Autowired
  String msg;
  @Autowired
  int tab;
  TestPresenter presenter = new TestPresenter(this);

  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.frag_test, container, false);
    super.bindToolbarView(view, "测试界面");
    multipleStatusView.showLoading();
    ARouter.getInstance().inject(this);
    text.setText("显示的是:" + msg);
    ToastUtils.showLong(BaseApplication.getInstance().getTag(AppStore.KEY_TAG1).toString()
        + BaseApplication.getInstance().getTag(AppStore.KEY_TAG2).toString());
    presenter.load();
    return view;
  }

  @Override
  public void onLoadResult() {
    ToastUtils.showLong("加载成功");
    multipleStatusView.showNoNetwork();
  }

  @Override
  public void showProgress(boolean show) {
    //使用MultipleStatusView加载后就不调用ProgressDialog了
    if (show && multipleStatusView.getViewStatus() != MultipleStatusView.STATUS_LOADING) {
      super.showProgress(show);
    }
  }

  @Override
  public boolean canBack() {
    return true;
  }
}


text:
import { Base } from './_Base';

export class LivechatExternalMessage extends Base {
	constructor() {
		super('livechat_external_message');

		this.tryEnsureIndex({ rid: 1 });
	}

	// FIND
	findByRoomId(roomId, sort = { ts: -1 }) {
		const query = { rid: roomId };

		return this.find(query, { sort });
	}
}

export default new LivechatExternalMessage();