text:
package org.frameworkset.spi.remote;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.log4j.Logger;
import org.frameworkset.spi.RemoteCallContext;
import org.frameworkset.spi.remote.BaseRPCIOHandler.Marshaller2;
import org.frameworkset.spi.security.SecurityContext;

/**
 *

 * Title: RPCClient.java
 *

 *

 * Description:
 *

 *

 * bboss workgroup
 *

 *

 * Copyright (c) 2007
 *

 *
 * @Date 2009-10-7 下午05:28:38
 * @author biaoping.yin
 * @version 1.0
 */
public final class RPCClient
{

	private static RPCClient instance = null;

	public static RPCClient getInstance()
	{
		if(instance != null)
			return instance;
		synchronized(RPCClient.class)
		{
			if(instance != null)
				return instance;

			instance = new RPCClient();

		}
		return instance;
	}

	private RPCClient()
	{
//		DefaultRemoteHandler remoteHandler = new DefaultRemoteHandler();
//		corr = new RPCServerIoHandler("RPCServerIoHandler",new RPCRequestHandler(remoteHandler));
//		corr = Util.getRPCServerIoHandler();
	}

	protected final Logger			log				= Logger.getLogger(getClass());

//	private RPCIOHandler	corr			= null;

	protected Marshaller2		req_marshaller	= null;

	@SuppressWarnings("unchecked")
	public Object callRemoteMethod(String host, int port, String method_name,
			Object[] args, Class[] types, int mode, long timeout,String protocol,RemoteCallContext callContext)
			throws Throwable
	{

		return callRemoteMethod(new RPCAddress(host, port,null,protocol), method_name, args,
								types, mode, timeout,protocol,callContext);
	}

	@SuppressWarnings("unchecked")
	public Object callRemoteMethod(RPCAddress dest, String method_name,
			Object[] args, Class[] types, int mode, long timeout,String protocol,RemoteCallContext callContext)
			throws Throwable
	{

		RPCMethodCall method_call = new RPCMethodCall(method_name, args, types,callContext == null? null:callContext.getSecutiryContext());
		byte[] buf = null;
		RPCMessage msg = null;
		Object retval = null;
		int expected_mbrs = 1;
		List<RPCAddress> mbrs = new ArrayList<RPCAddress>();
		if (dest == null)
		{
//			if (log.isErrorEnabled())
				log
						.error("the message's destination is null, cannot send message");
			return null;
		}
		mbrs.add(dest);

		if(!BaseRPCIOHandler.useOOB)
		{
			buf = Util.objectToByteBuffer(method_call);

			msg = new RPCMessage(null,dest);
			msg.setEncrypt(SecurityContext.getSecurityManager().enableEncrypt());

			msg.setBuffer( buf);
		}
		else
		{
			msg = new RPCMessage(null,dest);
//			msg.setEncrypt(SecurityContext.getSecurityManager().enableEncrypt());
			msg.setResultSerial(RPCMessage.OOB);
			msg.setData( method_call);
		}

		if(callContext != null && callContext.getHeaders() != null && callContext.getHeaders().size() > 0)
		    msg.setHeaders(callContext.getHeaders());
//		msg.setEncrypt(SecurityContext.getSecurityManager().enableEncrypt());
		RPCResponseList rsp_list = sendMessage(mbrs, msg, mode, timeout,
												expected_mbrs,protocol);

		if (rsp_list.isEmpty())
		{
			return null;
		}
		if (rsp_list.size() > 1)
		{
//			if (log.isWarnEnabled())
				log
						.warn("response list contains more that 1 response; returning first response !");
		}
		RPCResponse rsp = (RPCResponse) rsp_list.elementAt(0);
		if (rsp.wasSuspected())
		{
			throw new SuspectedException(dest);
		}
		if (!rsp.wasReceived())
		{
			throw new TimeoutException("timeout sending message to " + dest);
		}
		retval = rsp.getValue();
		handleException(retval);
//		if (retval instanceof RemoteException)
//			throw (Throwable) retval;
//		else if (retval instanceof Throwable)
//		{
////			throw (Throwable)retval;
//			throw new RemoteException((RPCMessage)null,(Throwable)retval);
//		}
		return retval;

	}

	public static void handleException(Object retval) throws Throwable
	{
		if(retval == null)
			return ;
		if (retval instanceof RemoteException)
			throw (Throwable) retval;
		else if(retval instanceof java.lang.reflect.InvocationTargetException)
		{
			throw ((java.lang.reflect.InvocationTargetException)retval).getTargetException();
		}
		else if (retval instanceof Throwable)
		{
			throw (Throwable)retval;

//			throw new RemoteException((RPCMessage)null,(Throwable)retval);
		}

	}

	public RPCResponseList callRemoteMethods(List<RPCAddress> dests,
			RPCMethodCall method_call, int resultMode, long timeout,
			boolean use_anycasting,  ResponseFilter filter,String protocol,Headers headers)
	{

		if (dests != null && dests.isEmpty())
		{
			log.info(new StringBuilder("destination list of ")
						.append(method_call.getMethodName())
						.append("() is empty: no need to send message"));
			return new RPCResponseList();
		}
		byte[] buf = null;
		RPCMessage msg = null;
		int expected_mbrs = 1;
//		if (log.isTraceEnabled())
		log.info(new StringBuilder("dests=").append(dests)
					.append(", method_call=").append(method_call)
					.append(", resultMode=").append(resultMode).append(", timeout=")
					.append(timeout));
		if(!BaseRPCIOHandler.useOOB)
		{
			try
			{
				buf =  Util.objectToByteBuffer(method_call);
			}
			catch (Exception e)
			{
				throw new RuntimeException("failure to marshal argument(s)", e);
			}

			msg = new RPCMessage();
			try {
				msg.setEncrypt(SecurityContext.getSecurityManager().enableEncrypt());
				msg.setBuffer(buf);
			} catch (Exception e) {
				throw new RuntimeException("failure to setBuffer ", e);
			}
		}
		else
		{
			msg = new RPCMessage();
			try {
//				msg.setEncrypt(SecurityContext.getSecurityManager().enableEncrypt());
				msg.setData(method_call);
//				msg.setBuffer(buf);
				msg.setResultSerial(msg.OOB);
			} catch (Exception e) {
				throw new RuntimeException("failure to setBuffer ", e);
			}
		}

		if(headers != null && headers.size() > 0)
		    msg.setHeaders(headers);
		// if(oob)
		// msg.setFlag(Message.OOB);
		RPCResponseList rsp_list = sendMessage(dests, msg, resultMode, timeout,
												expected_mbrs,protocol);
		// if(log.isTraceEnabled()) log.trace("retval: " + retval);
		if (rsp_list.isEmpty())
		{
			// if(log.isWarnEnabled())
			// log.warn(" response list is empty");
			return null;
		}
//		prehandleResponses(rsp_list);
//		if (log.isTraceEnabled())
//		log.info("responses: " + rsp_list);
		return rsp_list;
	}

	private void prehandleResponses(RPCResponseList rsp_list) throws MuticastCallException
	{
	    Set<Entry<RPCAddress,RPCResponse>> entries = rsp_list.entrySet();
	    MuticastCallException e = null;
	    Iterator<Entry<RPCAddress,RPCResponse>> its = entries.iterator();
	    while(its.hasNext())
	    {
	        Entry<RPCAddress,RPCResponse> entry = its.next();
	        RPCResponse rsp = entry.getValue();
	        Object value = rsp.getValue();
	        if(value != null && value instanceof Throwable)
	        {
	            if(e == null)
	                e = new MuticastCallException();
	            e.addException(entry.getKey(), new RemoteException((String)null,(Throwable)value));
	        }

	    }
	    if(e != null)
	        throw e;
	}

	/**
	 * Sends a message to a single member (destination = msg.dest) and returns
	 * the response. The message's destination must be non-zero !
	 */
	public RPCResponseList sendMessage(List<RPCAddress> mbrs, RPCMessage msg,
			int resultMode, long timeout, int expected_mbrs,String protocol)
	{

		RPCResponseList rsp_list = null;

		RPCRequest _req = null;

		if (mbrs == null)
		{
//			if (log.isErrorEnabled())
				log
						.error("the message's destination is null, cannot send message");
			return null;
		}

		// mbrs.add(dest); // dummy membership (of destination address)

		_req = new RPCRequest(msg, Util.getRPCIOHandler(protocol), mbrs, resultMode, timeout, expected_mbrs);
//		_req.setCaller(local_addr);
		try
		{
			_req.execute();
		}
		catch (Exception t)
		{
			throw new RuntimeException("调用远程服务失败,请确认服务器已经启动或者检查网络是否联通: " + _req, t);
		}

		if (resultMode == RPCRequest.GET_NONE)
		{
			return null;
		}

		rsp_list = _req.getResults();
		return rsp_list;

	}

	@SuppressWarnings("unchecked")
	public RPCResponseList callRemoteMethod(List<RPCAddress> dests, String method_name,
			Object[] params, Class[] rpTypes, int resultMode, long timeout,boolean use_anycasting,  ResponseFilter filter,String protocol,RemoteCallContext callContext)
	{
		RPCMethodCall method_call = new RPCMethodCall(method_name, params, rpTypes,callContext == null?null:callContext.getSecutiryContext());
		return callRemoteMethods(dests,
		             			method_call, resultMode, timeout,
		            			use_anycasting,  filter,protocol,callContext == null?null:callContext.getHeaders());

	}

	// public void sendRequest(RPCRequest request) {
	// System.out.println(session);
	// if (session == null) {
	// //noinspection ThrowableInstanceNeverThrown
	// // imageListener.onException(new Throwable("not connected"));
	// } else {
	// session.write(request);
	// }
	// }
	//
	// public void messageReceived(IoSession session, Object message) throws
	// Exception {
	// RPCResponse response = (RPCResponse) message;
	// System.out.println("response = " +response);
	// // imageListener.onImages(response.getImage1(), response.getImage2());
	// }
	//
	// public void exceptionCaught(IoSession session, Throwable cause) throws
	// Exception {
	// cause.printStackTrace();
	// // imageListener.onException(cause);
	// }

	// private static class MessageInspector implements ResponseInspector {
	// /**
	// * Default constructor
	// */
	// public MessageInspector() {
	// super();
	// }
	//
	// public Object getRequestId(Object message) {
	// if (!(message instanceof Message)) {
	// return null;
	// }
	//
	// return ((Message) message).getId();
	// }
	//
	// public ResponseType getResponseType(Object message) {
	// if (!(message instanceof Message)) {
	// return null;
	// }
	//
	// return ((Message) message).getType();
	// }
	// }
	//
	// static class Message {
	// private final int id;
	//
	// private final ResponseType type;
	//
	// Message(int id, ResponseType type) {
	// this.id = id;
	// this.type = type;
	// }
	//
	// public int getId() {
	// return id;
	// }
	//
	// public ResponseType getType() {
	// return type;
	// }
	// }

	// private static class WriteRequestMatcher extends AbstractMatcher {
	// private WriteRequest lastWriteRequest;
	//
	// /**
	// * Default constructor
	// */
	// public WriteRequestMatcher() {
	// super();
	// }
	//
	// public WriteRequest getLastWriteRequest() {
	// return lastWriteRequest;
	// }
	//
	// @Override
	// protected boolean argumentMatches(Object expected, Object actual) {
	// if (actual instanceof WriteRequest
	// && expected instanceof WriteRequest) {
	// boolean answer = ((WriteRequest) expected).getMessage().equals(
	// ((WriteRequest) actual).getMessage());
	// lastWriteRequest = (WriteRequest) actual;
	// return answer;
	// }
	// return super.argumentMatches(expected, actual);
	// }
	// }
	//
	// static class ExceptionMatcher extends AbstractMatcher {
	// @Override
	// protected boolean argumentMatches(Object expected, Object actual) {
	// if (actual instanceof RequestTimeoutException
	// && expected instanceof RequestTimeoutException) {
	// return ((RequestTimeoutException) expected)
	// .getRequest()
	// .equals(((RequestTimeoutException) actual).getRequest());
	// }
	// return super.argumentMatches(expected, actual);
	// }
	// }

}


text:
[spmatrix, tokenlist, category] = readMatrix('MATRIX.TEST');

testMatrix = full(spmatrix);
numTestDocs = size(testMatrix, 1);
numTokens = size(testMatrix, 2);

% Assume nb_train.m has just been executed, and all the parameters computed/needed
% by your classifier are in memory through that execution. You can also assume
% that the columns in the test set are arranged in exactly the same way as for the
% training set (i.e., the j-th column represents the same token in the test data
% matrix as in the original training data matrix).

% Write code below to classify each document in the test set (ie, each row
% in the current document word matrix) as 1 for SPAM and 0 for NON-SPAM.

% Construct the (numTestDocs x 1) vector 'output' such that the i-th entry
% of this vector is the predicted class (1/0) for the i-th  email (i-th row
% in testMatrix) in the test set.
output = zeros(numTestDocs, 1);

%---------------
% YOUR CODE HERE

%---------------

% Compute the error on the test set
y = full(category);
y = y(:);
error = sum(y ~= output) / numTestDocs;

%Print out the classification error on the test set
fprintf(1, 'Test error: %1.4f\n', error);

redpajama_set_name: RedPajamaGithub


text:
import React from 'react'

class ErrorBoundary extends React.Component {
  state = { error: null, info: null }
  componentDidCatch(error, info) {
    this.setState({ error, info })
  }
  render() {
    const { error, info } = this.state
    if (error) {
      return (

          {process.env.NODE_ENV !== 'production' ? (

                message: {error.message}

                componentStack:
                {info && info.componentStack}

                {error.stack}

          ) : (
            'Internal error'
          )}

      )
    }
    return this.props.children
  }
}
export default ErrorBoundary


text:
package moss

import (
	"bytes"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"time"

	"github.com/edsrzf/mmap-go"
)

func (s *Store) persistFooter(file File, footer *Footer,
	options StorePersistOptions) error {
	startTime := time.Now()

	if !options.NoSync {
		err := file.Sync()
		if err != nil {
			return err
		}
	}

	err := s.persistFooterUnsynced(file, footer)
	if err != nil {
		return err
	}

	if !options.NoSync {
		err = file.Sync()
	}

	if err == nil {
		s.histograms["PersistFooterUsecs"].Add(
			uint64(time.Since(startTime).Nanoseconds()/1000), 1)
	}

	return err
}

func (s *Store) persistFooterUnsynced(file File, footer *Footer) error {
	jBuf, err := json.Marshal(footer)
	if err != nil {
		return err
	}

	finfo, err := file.Stat()
	if err != nil {
		return err
	}

	footerPos := pageAlignCeil(finfo.Size())
	footerLen := footerBegLen + len(jBuf) + footerEndLen

	footerBuf := bytes.NewBuffer(make([]byte, 0, footerLen))
	footerBuf.Write(StoreMagicBeg)
	footerBuf.Write(StoreMagicBeg)
	binary.Write(footerBuf, StoreEndian, uint32(StoreVersion))
	binary.Write(footerBuf, StoreEndian, uint32(footerLen))
	footerBuf.Write(jBuf)
	binary.Write(footerBuf, StoreEndian, footerPos)
	binary.Write(footerBuf, StoreEndian, uint32(footerLen))
	footerBuf.Write(StoreMagicEnd)
	footerBuf.Write(StoreMagicEnd)

	footerWritten, err := file.WriteAt(footerBuf.Bytes(), footerPos)
	if err != nil {
		return err
	}
	if footerWritten != len(footerBuf.Bytes()) {
		return fmt.Errorf("store: persistFooter error writing all footerBuf")
	}

	if AllocationGranularity != StorePageSize {
		// Some platforms (windows) only support mmap()'ing at an
		// allocation granularity that's != to a page size.
		//
		// However if on such platforms there are empty segments, then
		// due to the extra space imposed by the above granularity
		// requirement, mmap() can fail complaining about insufficient
		// file space.
		//
		// To avoid this error, simply pad up the file up to a page
		// boundary.  This pad of zeroes will not interfere with file
		// recovery.
		padding := make([]byte, int(pageAlignCeil(int64(footerWritten)))-footerWritten)
		_, err = file.WriteAt(padding, footerPos+int64(footerWritten))
		if err != nil {
			return err
		}
	}

	footer.fileName = finfo.Name()
	footer.filePos = footerPos

	return nil
}

// --------------------------------------------------------

// ReadFooter reads the last valid Footer from a file.
func ReadFooter(options *StoreOptions, file File) (*Footer, error) {
	finfo, err := file.Stat()
	if err != nil {
		return nil, err
	}

	fref := &FileRef{file: file, refs: 1}

	// To avoid an EOF while reading, start scanning the footer from
	// the last byte. This is under the assumption that the footer is
	// at least 2 bytes long.
	f, err := ScanFooter(options, fref, finfo.Name(), finfo.Size()-1)
	if err != nil {
		return nil, err
	}

	fref.DecRef() // ScanFooter added its own ref-counts on success.

	return f, err
}

// --------------------------------------------------------

// ScanFooter scans a file backwards from the given pos for a valid
// Footer, adding ref-counts to fref on success.
func ScanFooter(options *StoreOptions, fref *FileRef, fileName string,
	pos int64) (*Footer, error) {
	footerBeg := make([]byte, footerBegLen)

	// Align pos to the start of a page (floor).
	pos = pageAlignFloor(pos)

	for {
		for { // Scan for StoreMagicBeg, which may be a potential footer.
			if pos <= 0 {
				return nil, ErrNoValidFooter
			}

			n, err := fref.file.ReadAt(footerBeg, pos)
			if err != nil {
				return nil, err
			}

			if n == footerBegLen &&
				bytes.Equal(StoreMagicBeg, footerBeg[:lenMagicBeg]) &&
				bytes.Equal(StoreMagicBeg, footerBeg[lenMagicBeg:2*lenMagicBeg]) {
				break
			}

			// Move pos back by page size.
			pos -= int64(StorePageSize)
		}

		// Read and check the potential footer.
		footerBegBuf := bytes.NewBuffer(footerBeg[2*lenMagicBeg:])

		var version uint32
		if err := binary.Read(footerBegBuf, StoreEndian, &version); err != nil {
			return nil, err
		}
		if version != StoreVersion {
			return nil, fmt.Errorf("store: version mismatch, "+
				"current: %v != found: %v", StoreVersion, version)
		}

		var length uint32
		if err := binary.Read(footerBegBuf, StoreEndian, &length); err != nil {
			return nil, err
		}

		data := make([]byte, int64(length)-int64(footerBegLen))

		n, err := fref.file.ReadAt(data, pos+int64(footerBegLen))
		if err != nil {
			return nil, err
		}

		if n == len(data) &&
			bytes.Equal(StoreMagicEnd, data[n-lenMagicEnd*2:n-lenMagicEnd]) &&
			bytes.Equal(StoreMagicEnd, data[n-lenMagicEnd:]) {

			content := int(length) - footerBegLen - footerEndLen
			b := bytes.NewBuffer(data[content:])

			var offset int64
			if err = binary.Read(b, StoreEndian, &offset); err != nil {
				return nil, err
			}
			if offset != pos {
				return nil, fmt.Errorf("store: offset mismatch, "+
					"wanted: %v != found: %v", offset, pos)
			}

			var length1 uint32
			if err = binary.Read(b, StoreEndian, &length1); err != nil {
				return nil, err
			}
			if length1 != length {
				return nil, fmt.Errorf("store: length mismatch, "+
					"wanted: %v != found: %v", length1, length)
			}

			f := &Footer{refs: 1, fileName: fileName, filePos: offset}

			err = json.Unmarshal(data[:content], f)
			if err != nil {
				return nil, err
			}

			// json.Unmarshal would have just loaded the map.
			// We now need to load each segment into the map.
			// Also recursively load child footer segment stacks.
			err = f.loadSegments(options, fref)
			if err != nil {
				return nil, err
			}

			return f, nil
		}
		// Else, invalid footer - StoreMagicEnd missing and/or file
		// pos out of bounds.

		// Footer was invalid, so keep scanning.
		pos -= int64(StorePageSize)
	}
}

// --------------------------------------------------------

// loadSegments() loads the segments of a footer.  Adds new ref-counts
// to the fref on success.  The footer will be in an already closed
// state on error.
func (f *Footer) loadSegments(options *StoreOptions, fref *FileRef) (err error) {
	// Track mrefs that we need to DecRef() if there's an error.
	mrefs := make([]*mmapRef, 0, len(f.SegmentLocs))
	mrefs, err = f.doLoadSegments(options, fref, mrefs)
	if err != nil {
		for _, mref := range mrefs {
			mref.DecRef()
		}
		return err
	}

	return nil
}

func (f *Footer) doLoadSegments(options *StoreOptions, fref *FileRef,
	mrefs []*mmapRef) (mrefsSoFar []*mmapRef, err error) {
	// Recursively load the childFooters first.
	for _, childFooter := range f.ChildFooters {
		mrefs, err = childFooter.doLoadSegments(options, fref, mrefs)
		if err != nil {
			return mrefs, err
		}
	}

	if f.ss != nil && f.ss.a != nil {
		return mrefs, nil
	}

	osFile := ToOsFile(fref.file)
	if osFile == nil {
		return mrefs, fmt.Errorf("store: doLoadSegments convert to os.File error")
	}

	a := make([]Segment, len(f.SegmentLocs))

	for i := range f.SegmentLocs {
		sloc := &f.SegmentLocs[i]

		mref := sloc.mref
		if mref != nil {
			if mref.fref != fref {
				return mrefs, fmt.Errorf("store: doLoadSegments fref mismatch")
			}

			mref.AddRef()
			mrefs = append(mrefs, mref)
		} else {
			// We persist kvs before buf, so KvsOffset < BufOffset.
			begOffset := int64(sloc.KvsOffset)
			endOffset := int64(sloc.BufOffset + sloc.BufBytes)

			nbytes := int(endOffset - begOffset)

			// Some platforms (windows) only support mmap()'ing at an
			// allocation granularity that's != to a page size, so
			// calculate the actual offset/nbytes to use.
			begOffsetActual := pageOffset(begOffset, int64(AllocationGranularity))
			begOffsetDelta := int(begOffset - begOffsetActual)
			nbytesActual := nbytes + begOffsetDelta

			// check whether the actual file fits within the footer offsets
			fstats, err := osFile.Stat()
			if err != nil || nbytesActual > int(fstats.Size()) {
				return mrefs, fmt.Errorf("store: doLoadSegments corrupted "+
					"file: %s, err: %+v", fstats.Name(), err)
			}

			mm, err := mmap.MapRegion(osFile, nbytesActual, mmap.RDONLY, 0, begOffsetActual)
			if err != nil {
				return mrefs,
					fmt.Errorf("store: doLoadSegments mmap.Map(),"+
						" begOffsetActual = %v, nbytesActual = %v, sloc = %+v,"+
						" file: %s, file mode: %v, file modification time: %v,"+
						" footer: %+v, f.SegmentLocs: %+v, err: %v",
						begOffsetActual, nbytesActual, sloc,
						fstats.Name(), fstats.Mode(), fstats.ModTime(),
						f, f.SegmentLocs, err)
			}

			fref.AddRef() // New mref owns 1 fref ref-count.

			buf := mm[begOffsetDelta : begOffsetDelta+nbytes]

			sloc.mref = &mmapRef{fref: fref, mm: mm, buf: buf, refs: 1}

			mref = sloc.mref
			mrefs = append(mrefs, mref)

			segmentLoader, exists := SegmentLoaders[sloc.Kind]
			if !exists || segmentLoader == nil {
				return mrefs, fmt.Errorf("store: unknown SegmentLoc kind, sloc: %+v", sloc)
			}

			seg, err := segmentLoader(sloc)
			if err != nil {
				return mrefs, fmt.Errorf("store: segmentLoader failed, footer: %+v,"+
					" f.SegmentLocs: %+v, i: %d, options: %v err: %+v",
					f, f.SegmentLocs, i, options, err)
			}

			segmentKeysIndexMaxBytes := options.SegmentKeysIndexMaxBytes
			if segmentKeysIndexMaxBytes == 0 {
				segmentKeysIndexMaxBytes = DefaultStoreOptions.SegmentKeysIndexMaxBytes
			}

			segmentKeysIndexMinKeyBytes := options.SegmentKeysIndexMinKeyBytes
			if segmentKeysIndexMinKeyBytes == 0 {
				segmentKeysIndexMinKeyBytes = DefaultStoreOptions.SegmentKeysIndexMinKeyBytes
			}

			if segmentKeysIndexMaxBytes > 0 {
				if a, ok := seg.(*segment); ok {
					a.buildIndex(segmentKeysIndexMaxBytes, segmentKeysIndexMinKeyBytes)
				}
			}

			mref.SetExt(seg)
		}

		a[i] = mref.GetExt().(Segment)
	}

	f.ss = &segmentStack{
		options: &options.CollectionOptions,
		a:       a,
		refs:    1,
	}

	return mrefs, nil
}

// --------------------------------------------------------

// ChildCollectionNames returns an array of child collection name strings.
func (f *Footer) ChildCollectionNames() ([]string, error) {
	var childNames = make([]string, len(f.ChildFooters))
	idx := 0
	for name := range f.ChildFooters {
		childNames[idx] = name
		idx++
	}
	return childNames, nil
}

// ChildCollectionSnapshot returns a Snapshot on a given child
// collection by its name.
func (f *Footer) ChildCollectionSnapshot(childCollectionName string) (
	Snapshot, error) {
	childFooter, exists := f.ChildFooters[childCollectionName]
	if !exists {
		return nil, nil
	}
	childFooter.AddRef()
	return childFooter, nil
}

// Close decrements the ref count on this footer
func (f *Footer) Close() error {
	f.DecRef()
	return nil
}

// AddRef increases the ref count on this footer
func (f *Footer) AddRef() {
	f.m.Lock()
	f.refs++
	f.m.Unlock()
}

// DecRef decreases the ref count on this footer
func (f *Footer) DecRef() {
	f.m.Lock()
	f.refs--
	if f.refs <= 0 {
		f.SegmentLocs.DecRef()
		f.SegmentLocs = nil
		f.ss = nil
	}
	f.m.Unlock()
}

// Length returns the length of this footer
func (f *Footer) Length() uint64 {
	jBuf, err := json.Marshal(f)
	if err != nil {
		return 0
	}

	footerLen := footerBegLen + len(jBuf) + footerEndLen
	return uint64(footerLen)
}

// --------------------------------------------------------

// segmentLocs returns the current SegmentLocs and segmentStack for
// a footer, while also incrementing the ref-count on the footer.  The
// caller must DecRef() the footer when done.
func (f *Footer) segmentLocs() (SegmentLocs, *segmentStack) {
	f.m.Lock()

	f.refs++

	slocs, ss := f.SegmentLocs, f.ss

	f.m.Unlock()

	return slocs, ss
}

// --------------------------------------------------------

// Get retrieves a val from the footer, and will return nil val
// if the entry does not exist in the footer.
func (f *Footer) Get(key []byte, readOptions ReadOptions) ([]byte, error) {
	_, ss := f.segmentLocs()
	if ss == nil {
		f.DecRef()
		return nil, nil
	}

	rv, err := ss.Get(key, readOptions)
	if err == nil && rv != nil && !readOptions.NoCopyValue {
		rv = append(make([]byte, 0, len(rv)), rv...) // Copy.
	}

	f.DecRef()

	return rv, err
}

// StartIterator returns a new Iterator instance on this footer.
//
// On success, the returned Iterator will be positioned so that
// Iterator.Current() will either provide the first entry in the
// range or ErrIteratorDone.
//
// A startKeyIncl of nil means the logical "bottom-most" possible key
// and an endKeyExcl of nil means the logical "top-most" possible key.
func (f *Footer) StartIterator(startKeyIncl, endKeyExcl []byte,
	iteratorOptions IteratorOptions) (Iterator, error) {
	_, ss := f.segmentLocs()
	if ss == nil {
		f.DecRef()
		return nil, nil
	}

	iter, err := ss.StartIterator(startKeyIncl, endKeyExcl, iteratorOptions)
	if err != nil || iter == nil {
		f.DecRef()
		return nil, err
	}

	initCloser, ok := iter.(InitCloser)
	if !ok || initCloser == nil {
		iter.Close()
		f.DecRef()
		return nil, ErrUnexpected
	}

	err = initCloser.InitCloser(f)
	if err != nil {
		iter.Close()
		f.DecRef()
		return nil, err
	}

	return iter, nil
}


text: ViewpagerIndicator AS版本


text:
import urllib.request
import urllib.parse
import urllib.error
from datetime import datetime
from utils import config_file_path
import settings

class Thingspeak:
    """
    Log data to the Thingspeak channel.
    """

    def __init__(self):
        with open(config_file_path('thingspeak_key.txt')) as f:
            self.key = f.read().strip()

    def append(self, data):
        if len(data) != len(settings.DATA_SPEC):
            raise Exception('Invalid data fields count')

        values = {
            'api_key': self.key,
            'created_at': data['date']
        }

        count = 1
        for k in settings.DATA_SPEC:
            if k != 'date':
                values['field' + str(count)] = data[k]
                count += 1

        url = 'https://api.thingspeak.com/update'
        postdata = urllib.parse.urlencode(values).encode('ascii')
        req = urllib.request.Request(url, postdata)

        try:
            response = urllib.request.urlopen(req)
            response_data = response.read()
            response.close()
            if response_data == b'0':
                raise Exception('Update failed')
        except urllib.error.HTTPError as e:
            raise Exception('Server could not fulfill the request: ' + str(e.code))
        except urllib.error.URLError as e:
            raise Exception('Failed to reach server: ' + str(e.reason))

def main():
    t = Thingspeak()
    date = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
    t.append({'date': date, 'temperature_C': 25, 'pH': 6.0, 'supply_tank_L': 250, 'nutrients_mL': 0})

if __name__ == '__main__':
    main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<project relativePaths="false" version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/calculator.iml" filepath="$PROJECT_DIR$/.idea/calculator.iml" />
    </modules>
  </component>
</project>


text:
using System;
using Tiger.Build.Compiler.Common;

namespace Tiger.Build.Compiler.Error
{
    public class WhileBodyReturnsValueError : TypeMismatchedError
    {
        public WhileBodyReturnsValueError(Type returnedType, SourceLocation location)
            : base(typeof (void), returnedType, location)
        {
        }

        protected override string GetMessage()
        {
            return "The body of a while expression must not return any value";
        }
    }
}


text:
#region License Information
/*
 * This file is part of SimSharp which is licensed under the MIT license.
 * See the LICENSE file in the project root for more information.
 */
#endregion

using System;
using System.Collections.Generic;

namespace SimSharp {
  /// <summary>
  /// The base class for all events in SimSharp.
  /// An event can be in one of three states at any time:
  ///  - Alive: The event object exists, but is neither scheduled to
  ///           be executed, nor is it already executed.
  ///  - Triggered: The event has been put in the event queue and is
  ///               going to be executed.
  ///  - Processed: The event has been executed.
  ///
  /// Usually, the event is alive until its Trigger, Succeed, or Fail
  /// method have been called. Then it becomes triggered. When the
  /// Environment progresses to the event and executes its callbacks
  /// the event becomes processed.
  /// </summary>
  public class Event {
    protected internal Simulation Environment { get; private set; }
    protected List<Action<Event>> CallbackList { get; set; }

    /// <summary>
    /// The value property can be used to return arbitrary data from a
    /// process or an event. It also represents the interrupt cause to
    /// a process.
    /// </summary>
    public object Value { get; protected set; }

    /// <summary>
    /// The IsOk flag indicates if the event succeeded or failed. An event
    /// that failed indicates to a waiting process that the action could
    /// not be performed and that the faulting situation must be handled.
    /// Typically, interrupting a process sets the IsOk flag to false.
    /// </summary>
    public bool IsOk { get; protected set; }
    /// <summary>
    /// An event is alive when it is not triggered and not processed. That
    /// is, when it exists in memory without being scheduled. Typically,
    /// a Process is alive until its last event has been processed and the
    /// process event itself is to be processed.
    /// </summary>
    public bool IsAlive { get { return !IsTriggered && !IsProcessed; } }
    /// <summary>
    /// An event becomes processed when its callbacks have been executed.
    /// Events may only be processed once and an exception will be thrown
    /// if they are to be processed multiple times.
    /// </summary>
    public bool IsProcessed { get; protected set; }
    /// <summary>
    /// An event becomes triggered when it is placed into the event queue.
    /// That is, when its callbacks are going to be executed.
    /// An even that is triggered may later not be failed or retriggered.
    /// </summary>
    public bool IsTriggered { get; protected set; }

    public Event(Simulation environment) {
      Environment = environment;
      CallbackList = new List<Action<Event>>();
    }

    /// <summary>
    /// This method schedules the event right now. It takes the IsOk state
    /// and uses the <see cref="Value"/> of the given <paramref name="@event"/>.
    /// Thus if the given event fails, this event will also be triggered as
    /// failing.
    /// </summary>
    /// <exception cref="InvalidOperationException">
    /// Thrown when the event has already been triggered.
    /// </exception>
    /// <remarks>
    /// The signature of this method allows it to be used as a callback.
    /// </remarks>
    /// <param name="event">The event that triggers this event.</param>
    /// <param name="priority">The priority to rank events at the same time (smaller value = higher priority).</param>
    public virtual void Trigger(Event @event, int priority = 0) {
      if (IsTriggered)
        throw new InvalidOperationException("Event has already been triggered.");
      IsOk = @event.IsOk;
      Value = @event.Value;
      IsTriggered = true;
      Environment.Schedule(this, priority);
    }

    /// <summary>
    /// This method schedules the event right now. It sets IsOk state to true
    /// and optionally uses also the value. If urgent is given, the event may
    /// be scheduled as urgent. Urgent events are placed in a separate event
    /// queue. The callbacks of urgent events are executed before normal events.
    /// </summary>
    /// <exception cref="InvalidOperationException">
    /// Thrown when the event has already been triggered.
    /// </exception>
    /// <param name="value">The value that the event should use.</param>
    /// <param name="priority">The priority to rank events at the same time (smaller value = higher priority).</param>
    public virtual void Succeed(object value = null, int priority = 0) {
      if (IsTriggered)
        throw new InvalidOperationException("Event has already been triggered.");
      IsOk = true;
      Value = value;
      IsTriggered = true;
      Environment.Schedule(this, priority);
    }

    /// <summary>
    /// This method schedules the event right now. It sets IsOk state to false
    /// and optionally uses also the value. If urgent is given, the event may
    /// be scheduled as urgent. Urgent events are placed in a separate event
    /// queue. The callbacks of urgent events are executed before normal events.
    /// </summary>
    /// <exception cref="InvalidOperationException">
    /// Thrown when the event has already been triggered.
    /// </exception>
    /// <param name="value">The value that the event should use.</param>
    /// <param name="priority">The priority to rank events at the same time (smaller value = higher priority).</param>
    public virtual void Fail(object value = null, int priority = 0) {
      if (IsTriggered)
        throw new InvalidOperationException("Event has already been triggered.");
      IsOk = false;
      Value = value;
      IsTriggered = true;
      Environment.Schedule(this, priority);
    }

    /// <summary>
    /// This method adds a callback to the list of callbacks. Callbacks will be
    /// executed in the order they have been added.
    /// </summary>
    /// <param name="callback">The callback to execute when the event is being
    /// processed.</param>
    public virtual void AddCallback(Action<Event> callback) {
      if (IsProcessed) throw new InvalidOperationException("Event is already processed.");
      CallbackList.Add(callback);
    }

    /// <summary>
    /// This method adds a range of callbacks to the list of callbacks. Callbacks
    /// will be executed in the order they have been added.
    /// </summary>
    /// <param name="callbacks">The callbacks to execute when the event is being
    /// processed.</param>
    public virtual void AddCallbacks(IEnumerable<Action<Event>> callbacks) {
      if (IsProcessed) throw new InvalidOperationException("Event is already processed.");
      CallbackList.AddRange(callbacks);
    }

    /// <summary>
    /// This method removes a callback to the list of callbacks.
    /// </summary>
    /// <remarks>
    /// It is not checked if the callback has actually been added before and
    /// no exception will be thrown if it had not been present.
    /// </remarks>
    /// <param name="callback">The callback to remove.</param>
    public virtual void RemoveCallback(Action<Event> callback) {
      if (IsProcessed) throw new InvalidOperationException("Event is already processed.");
      CallbackList.Remove(callback);
    }

    /// <summary>
    /// This method processes the event, that is, it calls all the callbacks.
    /// When it finishes it will be marked IsProcessed and cannot be processed
    /// again.
    /// </summary>
    /// <exception cref="InvalidOperationException">When the event has already
    /// been processed.</exception>
    public virtual void Process() {
      if (IsProcessed) throw new InvalidOperationException("Event has already been processed.");
      IsProcessed = true;
      for (var i = 0; i < CallbackList.Count; i++)
        CallbackList[i](this);
      CallbackList = null;
    }

    public static Condition operator &(Event event1, Event event2) {
      return new AllOf(event1.Environment, event1, event2);
    }
    public static Condition operator |(Event event1, Event event2) {
      return new AnyOf(event1.Environment, event1, event2);
    }
  }
}


text:
package com.nestedworld.nestedworld.data.network.http.errorHandler;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.nestedworld.nestedworld.R;
import com.nestedworld.nestedworld.data.network.http.callback.NestedWorldHttpCallback;
import com.nestedworld.nestedworld.data.network.http.models.response.error.ErrorResponse;

import java.io.IOException;

import retrofit2.Response;

/**
 * Simple RetrofitError parser
 * it's return an explicit error message
 * if the server provide an error message he will be returned
 * if the server didn't provide any error message, a custom (static) message will be returned
 */
public final class RetrofitErrorHandler {
    private final static String TAG = RetrofitErrorHandler.class.getSimpleName();

    /*
     * #############################################################################################
     * # Constructor
     * #############################################################################################
     */
    private RetrofitErrorHandler() {
        //Empty constructor for avoiding this class to be construct
    }

    /*
     * #############################################################################################
     * # Public (static) method
     * #############################################################################################
     */
    @NonNull
    public static String getErrorMessage(@NonNull final Context context,
                                         @NonNull final NestedWorldHttpCallback.KIND errorType,
                                         @NonNull final String defaultMessage,
                                         @Nullable final Response response) {
        final String errorMessage = getErrorMessage(context, errorType, response);

        return errorMessage == null ? defaultMessage : (defaultMessage + ":" + errorMessage);
    }

    @Nullable
    public static String getErrorMessage(@NonNull final Context context,
                                         @NonNull final NestedWorldHttpCallback.KIND errorType,
                                         @Nullable final Response response) {
        //try to get error message from the response
        if (response != null) {
            try {
                //get the response as a string
                final String serverResponse = response.errorBody().string();

                try {
                    //try to convert the response as an ErrorResponse
                    final ErrorResponse errorResponse = new Gson().fromJson(serverResponse, ErrorResponse.class);
                    //check if we have a response
                    if (errorResponse != null && errorResponse.message != null) {
                        return errorResponse.message;
                    }
                } catch (JsonSyntaxException ignored) {
                    //The response cannot be cast as an errorResponse
                }
            } catch (IOException e) {
                //Server issue (the server don't follow the specification)
            }
        }

        switch (errorType) {
            case NETWORK:
                return getNetworkError(context);
            case SERVER:
                return getUnexpectedError(context);
            default:
                break;
        }
        return null;
    }

    /*
     * #############################################################################################
     * # Internal (static) method
     * #############################################################################################
     */
    @NonNull
    private static String getNetworkError(@NonNull final Context context) {
        return context.getResources().getString(R.string.error_no_internet);
    }

    @NonNull
    private static String getUnexpectedError(@NonNull final Context context) {
        return context.getResources().getString(R.string.error_conversion);
    }
}


text:
#include "config.h"
#include "DragController.h"

#include "DataObjectGtk.h"
#include "DataTransfer.h"
#include "Document.h"
#include "DocumentFragment.h"
#include "DragData.h"
#include "Editor.h"
#include "Element.h"
#include "Frame.h"
#include "FrameView.h"
#include "Page.h"
#include "Pasteboard.h"
#include "markup.h"

namespace WebCore {

// FIXME: These values are straight out of DragControllerMac, so probably have
// little correlation with Gdk standards...
const int DragController::LinkDragBorderInset = 2;
const int DragController::MaxOriginalImageArea = 1500 * 1500;
const int DragController::DragIconRightInset = 7;
const int DragController::DragIconBottomInset = 3;

const float DragController::DragImageAlpha = 0.75f;

bool DragController::isCopyKeyDown(DragData&)
{
    return false;
}

DragOperation DragController::dragOperation(DragData& dragData)
{
    // FIXME: This logic is incomplete
    if (dragData.containsURL())
        return DragOperationCopy;

    return DragOperationNone;
}

const IntSize& DragController::maxDragImageSize()
{
    static const IntSize maxDragImageSize(200, 200);
    return maxDragImageSize;
}

void DragController::cleanupAfterSystemDrag()
{
}

void DragController::declareAndWriteDragImage(DataTransfer& dataTransfer, Element& element, const URL& url, const String& label)
{
    Frame* frame = element.document().frame();
    ASSERT(frame);
    frame->editor().writeImageToPasteboard(dataTransfer.pasteboard(), element, url, label);
}

#if ENABLE(ATTACHMENT_ELEMENT)
void DragController::declareAndWriteAttachment(DataTransfer&, Element&, const URL&)
{
}
#endif

}