text:
package org.elasticsearch.cluster.action.shard;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateObserver;
import org.elasticsearch.cluster.ClusterStateTaskConfig;
import org.elasticsearch.cluster.ClusterStateTaskExecutor;
import org.elasticsearch.cluster.ClusterStateTaskListener;
import org.elasticsearch.cluster.MasterNodeChangePredicate;
import org.elasticsearch.cluster.NotMasterException;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.RoutingService;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.FailedRerouteAllocation;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.discovery.Discovery;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.node.NodeClosedException;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.ConnectTransportException;
import org.elasticsearch.transport.EmptyTransportResponseHandler;
import org.elasticsearch.transport.NodeDisconnectedException;
import org.elasticsearch.transport.RemoteTransportException;
import org.elasticsearch.transport.TransportChannel;
import org.elasticsearch.transport.TransportException;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.transport.TransportRequestHandler;
import org.elasticsearch.transport.TransportResponse;
import org.elasticsearch.transport.TransportService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

public class ShardStateAction extends AbstractComponent {

    public static final String SHARD_STARTED_ACTION_NAME = "internal:cluster/shard/started";
    public static final String SHARD_FAILED_ACTION_NAME = "internal:cluster/shard/failure";

    private final TransportService transportService;
    private final ClusterService clusterService;
    private final ThreadPool threadPool;

    @Inject
    public ShardStateAction(Settings settings, ClusterService clusterService, TransportService transportService,
                            AllocationService allocationService, RoutingService routingService, ThreadPool threadPool) {
        super(settings);
        this.transportService = transportService;
        this.clusterService = clusterService;
        this.threadPool = threadPool;

        transportService.registerRequestHandler(SHARD_STARTED_ACTION_NAME, ShardRoutingEntry::new, ThreadPool.Names.SAME, new ShardStartedTransportHandler(clusterService, new ShardStartedClusterStateTaskExecutor(allocationService, logger), logger));
        transportService.registerRequestHandler(SHARD_FAILED_ACTION_NAME, ShardRoutingEntry::new, ThreadPool.Names.SAME, new ShardFailedTransportHandler(clusterService, new ShardFailedClusterStateTaskExecutor(allocationService, routingService, logger), logger));
    }

    private void sendShardAction(final String actionName, final ClusterStateObserver observer, final ShardRoutingEntry shardRoutingEntry, final Listener listener) {
        DiscoveryNode masterNode = observer.observedState().nodes().getMasterNode();
        if (masterNode == null) {
            logger.warn("{} no master known for action [{}] for shard [{}]", shardRoutingEntry.getShardRouting().shardId(), actionName, shardRoutingEntry.getShardRouting());
            waitForNewMasterAndRetry(actionName, observer, shardRoutingEntry, listener);
        } else {
            logger.debug("{} sending [{}] to [{}] for shard [{}]", shardRoutingEntry.getShardRouting().shardId(), actionName, masterNode.getId(), shardRoutingEntry);
            transportService.sendRequest(masterNode,
                actionName, shardRoutingEntry, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) {
                    @Override
                    public void handleResponse(TransportResponse.Empty response) {
                        listener.onSuccess();
                    }

                    @Override
                    public void handleException(TransportException exp) {
                        if (isMasterChannelException(exp)) {
                            waitForNewMasterAndRetry(actionName, observer, shardRoutingEntry, listener);
                        } else {
                            logger.warn("{} unexpected failure while sending request [{}] to [{}] for shard [{}]", exp, shardRoutingEntry.getShardRouting().shardId(), actionName, masterNode, shardRoutingEntry);
                            listener.onFailure(exp instanceof RemoteTransportException ? exp.getCause() : exp);
                        }
                    }
                });
        }
    }

    private static Class[] MASTER_CHANNEL_EXCEPTIONS = new Class[]{
        NotMasterException.class,
        ConnectTransportException.class,
        Discovery.FailedToCommitClusterStateException.class
    };

    private static boolean isMasterChannelException(TransportException exp) {
        return ExceptionsHelper.unwrap(exp, MASTER_CHANNEL_EXCEPTIONS) != null;
    }

    /**
     * Send a shard failed request to the master node to update the
     * cluster state.
     *
     * @param shardRouting       the shard to fail
     * @param sourceShardRouting the source shard requesting the failure (must be the shard itself, or the primary shard)
     * @param message            the reason for the failure
     * @param failure            the underlying cause of the failure
     * @param listener           callback upon completion of the request
     */
    public void shardFailed(final ShardRouting shardRouting, ShardRouting sourceShardRouting, final String message, @Nullable final Throwable failure, Listener listener) {
        ClusterStateObserver observer = new ClusterStateObserver(clusterService, null, logger, threadPool.getThreadContext());
        ShardRoutingEntry shardRoutingEntry = new ShardRoutingEntry(shardRouting, sourceShardRouting, message, failure);
        sendShardAction(SHARD_FAILED_ACTION_NAME, observer, shardRoutingEntry, listener);
    }

    // visible for testing
    protected void waitForNewMasterAndRetry(String actionName, ClusterStateObserver observer, ShardRoutingEntry shardRoutingEntry, Listener listener) {
        observer.waitForNextChange(new ClusterStateObserver.Listener() {
            @Override
            public void onNewClusterState(ClusterState state) {
                if (logger.isTraceEnabled()) {
                    logger.trace("new cluster state [{}] after waiting for master election to fail shard [{}]", state.prettyPrint(), shardRoutingEntry);
                }
                sendShardAction(actionName, observer, shardRoutingEntry, listener);
            }

            @Override
            public void onClusterServiceClose() {
                logger.warn("{} node closed while execution action [{}] for shard [{}]", shardRoutingEntry.failure, shardRoutingEntry.getShardRouting().shardId(), actionName, shardRoutingEntry.getShardRouting());
                listener.onFailure(new NodeClosedException(clusterService.localNode()));
            }

            @Override
            public void onTimeout(TimeValue timeout) {
                // we wait indefinitely for a new master
                assert false;
            }
        }, MasterNodeChangePredicate.INSTANCE);
    }

    private static class ShardFailedTransportHandler implements TransportRequestHandler<ShardRoutingEntry> {
        private final ClusterService clusterService;
        private final ShardFailedClusterStateTaskExecutor shardFailedClusterStateTaskExecutor;
        private final ESLogger logger;

        public ShardFailedTransportHandler(ClusterService clusterService, ShardFailedClusterStateTaskExecutor shardFailedClusterStateTaskExecutor, ESLogger logger) {
            this.clusterService = clusterService;
            this.shardFailedClusterStateTaskExecutor = shardFailedClusterStateTaskExecutor;
            this.logger = logger;
        }

        @Override
        public void messageReceived(ShardRoutingEntry request, TransportChannel channel) throws Exception {
            logger.warn("{} received shard failed for {}", request.failure, request.shardRouting.shardId(), request);
            clusterService.submitStateUpdateTask(
                "shard-failed (" + request.shardRouting + "), message [" + request.message + "]",
                request,
                ClusterStateTaskConfig.build(Priority.HIGH),
                shardFailedClusterStateTaskExecutor,
                new ClusterStateTaskListener() {
                    @Override
                    public void onFailure(String source, Throwable t) {
                        logger.error("{} unexpected failure while failing shard [{}]", t, request.shardRouting.shardId(), request.shardRouting);
                        try {
                            channel.sendResponse(t);
                        } catch (Throwable channelThrowable) {
                            logger.warn("{} failed to send failure [{}] while failing shard [{}]", channelThrowable, request.shardRouting.shardId(), t, request.shardRouting);
                        }
                    }

                    @Override
                    public void onNoLongerMaster(String source) {
                        logger.error("{} no longer master while failing shard [{}]", request.shardRouting.shardId(), request.shardRouting);
                        try {
                            channel.sendResponse(new NotMasterException(source));
                        } catch (Throwable channelThrowable) {
                            logger.warn("{} failed to send no longer master while failing shard [{}]", channelThrowable, request.shardRouting.shardId(), request.shardRouting);
                        }
                    }

                    @Override
                    public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
                        try {
                            channel.sendResponse(TransportResponse.Empty.INSTANCE);
                        } catch (Throwable channelThrowable) {
                            logger.warn("{} failed to send response while failing shard [{}]", channelThrowable, request.shardRouting.shardId(), request.shardRouting);
                        }
                    }
                }
            );
        }
    }

    static class ShardFailedClusterStateTaskExecutor implements ClusterStateTaskExecutor<ShardRoutingEntry> {
        private final AllocationService allocationService;
        private final RoutingService routingService;
        private final ESLogger logger;

        ShardFailedClusterStateTaskExecutor(AllocationService allocationService, RoutingService routingService, ESLogger logger) {
            this.allocationService = allocationService;
            this.routingService = routingService;
            this.logger = logger;
        }

        @Override
        public BatchResult<ShardRoutingEntry> execute(ClusterState currentState, List<ShardRoutingEntry> tasks) throws Exception {
            BatchResult.Builder<ShardRoutingEntry> batchResultBuilder = BatchResult.builder();

            // partition tasks into those that correspond to shards
            // that exist versus do not exist
            Map<ValidationResult, List<ShardRoutingEntry>> partition =
                tasks.stream().collect(Collectors.groupingBy(task -> validateTask(currentState, task)));

            // tasks that correspond to non-existent shards are marked
            // as successful
            batchResultBuilder.successes(partition.getOrDefault(ValidationResult.SHARD_MISSING, Collections.emptyList()));

            ClusterState maybeUpdatedState = currentState;
            List<ShardRoutingEntry> tasksToFail = partition.getOrDefault(ValidationResult.VALID, Collections.emptyList());
            try {
                List<FailedRerouteAllocation.FailedShard> failedShards =
                    tasksToFail
                        .stream()
                        .map(task -> new FailedRerouteAllocation.FailedShard(task.shardRouting, task.message, task.failure))
                        .collect(Collectors.toList());
                RoutingAllocation.Result result = applyFailedShards(currentState, failedShards);
                if (result.changed()) {
                    maybeUpdatedState = ClusterState.builder(currentState).routingResult(result).build();
                }
                batchResultBuilder.successes(tasksToFail);
            } catch (Throwable t) {
                // failures are communicated back to the requester
                // cluster state will not be updated in this case
                batchResultBuilder.failures(tasksToFail, t);
            }

            partition
                .getOrDefault(ValidationResult.SOURCE_INVALID, Collections.emptyList())
                .forEach(task -> batchResultBuilder.failure(
                    task,
                    new NoLongerPrimaryShardException(
                        task.getShardRouting().shardId(),
                        "source shard [" + task.sourceShardRouting + "] is neither the local allocation nor the primary allocation")
                ));

            return batchResultBuilder.build(maybeUpdatedState);
        }

        // visible for testing
        RoutingAllocation.Result applyFailedShards(ClusterState currentState, List<FailedRerouteAllocation.FailedShard> failedShards) {
            return allocationService.applyFailedShards(currentState, failedShards);
        }

        private enum ValidationResult {
            VALID,
            SOURCE_INVALID,
            SHARD_MISSING
        }

        private ValidationResult validateTask(ClusterState currentState, ShardRoutingEntry task) {

            // non-local requests
            if (!task.shardRouting.isSameAllocation(task.sourceShardRouting)) {
                IndexShardRoutingTable indexShard = currentState.getRoutingTable().shardRoutingTableOrNull(task.shardRouting.shardId());
                if (indexShard == null) {
                    return ValidationResult.SOURCE_INVALID;
                }
                ShardRouting primaryShard = indexShard.primaryShard();
                if (primaryShard == null || !primaryShard.isSameAllocation(task.sourceShardRouting)) {
                    return ValidationResult.SOURCE_INVALID;
                }
            }

            RoutingNode routingNode = currentState.getRoutingNodes().node(task.getShardRouting().currentNodeId());
            if (routingNode != null) {
                ShardRouting maybe = routingNode.getByShardId(task.getShardRouting().shardId());
                if (maybe != null && maybe.isSameAllocation(task.getShardRouting())) {
                    return ValidationResult.VALID;
                }
            }
            return ValidationResult.SHARD_MISSING;
        }

        @Override
        public void clusterStatePublished(ClusterState newClusterState) {
            int numberOfUnassignedShards = newClusterState.getRoutingNodes().unassigned().size();
            if (numberOfUnassignedShards > 0) {
                String reason = String.format(Locale.ROOT, "[%d] unassigned shards after failing shards", numberOfUnassignedShards);
                if (logger.isTraceEnabled()) {
                    logger.trace("{}, scheduling a reroute", reason);
                }
                routingService.reroute(reason);
            }
        }
    }

    public void shardStarted(final ShardRouting shardRouting, final String message, Listener listener) {
        ClusterStateObserver observer = new ClusterStateObserver(clusterService, null, logger, threadPool.getThreadContext());
        ShardRoutingEntry shardRoutingEntry = new ShardRoutingEntry(shardRouting, shardRouting, message, null);
        sendShardAction(SHARD_STARTED_ACTION_NAME, observer, shardRoutingEntry, listener);
    }

    private static class ShardStartedTransportHandler implements TransportRequestHandler<ShardRoutingEntry> {
        private final ClusterService clusterService;
        private final ShardStartedClusterStateTaskExecutor shardStartedClusterStateTaskExecutor;
        private final ESLogger logger;

        public ShardStartedTransportHandler(ClusterService clusterService, ShardStartedClusterStateTaskExecutor shardStartedClusterStateTaskExecutor, ESLogger logger) {
            this.clusterService = clusterService;
            this.shardStartedClusterStateTaskExecutor = shardStartedClusterStateTaskExecutor;
            this.logger = logger;
        }

        @Override
        public void messageReceived(ShardRoutingEntry request, TransportChannel channel) throws Exception {
            logger.debug("{} received shard started for [{}]", request.shardRouting.shardId(), request);
            clusterService.submitStateUpdateTask(
                "shard-started (" + request.shardRouting + "), reason [" + request.message + "]",
                request,
                ClusterStateTaskConfig.build(Priority.URGENT),
                shardStartedClusterStateTaskExecutor,
                shardStartedClusterStateTaskExecutor);
            channel.sendResponse(TransportResponse.Empty.INSTANCE);
        }
    }

    private static class ShardStartedClusterStateTaskExecutor implements ClusterStateTaskExecutor<ShardRoutingEntry>, ClusterStateTaskListener {
        private final AllocationService allocationService;
        private final ESLogger logger;

        public ShardStartedClusterStateTaskExecutor(AllocationService allocationService, ESLogger logger) {
            this.allocationService = allocationService;
            this.logger = logger;
        }

        @Override
        public BatchResult<ShardRoutingEntry> execute(ClusterState currentState, List<ShardRoutingEntry> tasks) throws Exception {
            BatchResult.Builder<ShardRoutingEntry> builder = BatchResult.builder();
            List<ShardRouting> shardRoutingsToBeApplied = new ArrayList<>(tasks.size());
            for (ShardRoutingEntry task : tasks) {
                shardRoutingsToBeApplied.add(task.shardRouting);
            }
            ClusterState maybeUpdatedState = currentState;
            try {
                RoutingAllocation.Result result =
                    allocationService.applyStartedShards(currentState, shardRoutingsToBeApplied, true);
                if (result.changed()) {
                    maybeUpdatedState = ClusterState.builder(currentState).routingResult(result).build();
                }
                builder.successes(tasks);
            } catch (Throwable t) {
                builder.failures(tasks, t);
            }

            return builder.build(maybeUpdatedState);
        }

        @Override
        public void onFailure(String source, Throwable t) {
            logger.error("unexpected failure during [{}]", t, source);
        }
    }

    public static class ShardRoutingEntry extends TransportRequest {
        ShardRouting shardRouting;
        ShardRouting sourceShardRouting;
        String message;
        Throwable failure;

        public ShardRoutingEntry() {
        }

        ShardRoutingEntry(ShardRouting shardRouting, ShardRouting sourceShardRouting, String message, @Nullable Throwable failure) {
            this.shardRouting = shardRouting;
            this.sourceShardRouting = sourceShardRouting;
            this.message = message;
            this.failure = failure;
        }

        public ShardRouting getShardRouting() {
            return shardRouting;
        }

        @Override
        public void readFrom(StreamInput in) throws IOException {
            super.readFrom(in);
            shardRouting = new ShardRouting(in);
            sourceShardRouting = new ShardRouting(in);
            message = in.readString();
            failure = in.readThrowable();
        }

        @Override
        public void writeTo(StreamOutput out) throws IOException {
            super.writeTo(out);
            shardRouting.writeTo(out);
            sourceShardRouting.writeTo(out);
            out.writeString(message);
            out.writeThrowable(failure);
        }

        @Override
        public String toString() {
            List<String> components = new ArrayList<>(4);
            components.add("target shard [" + shardRouting + "]");
            components.add("source shard [" + sourceShardRouting + "]");
            components.add("message [" + message + "]");
            if (failure != null) {
                components.add("failure [" + ExceptionsHelper.detailedMessage(failure) + "]");
            }
            return String.join(", ", components);
        }
    }

    public interface Listener {

        default void onSuccess() {
        }

        /**
         * Notification for non-channel exceptions that are not handled
         * by {@link ShardStateAction}.
         *
         * The exceptions that are handled by {@link ShardStateAction}
         * are:
         *  - {@link NotMasterException}
         *  - {@link NodeDisconnectedException}
         *  - {@link Discovery.FailedToCommitClusterStateException}
         *
         * Any other exception is communicated to the requester via
         * this notification.
         *
         * @param t the unexpected cause of the failure on the master
         */
        default void onFailure(final Throwable t) {
        }

    }

    public static class NoLongerPrimaryShardException extends ElasticsearchException {

        public NoLongerPrimaryShardException(ShardId shardId, String msg) {
            super(msg);
            setShard(shardId);
        }

        public NoLongerPrimaryShardException(StreamInput in) throws IOException {
            super(in);
        }

    }

}


text:
S.Db.Cursor=S.newClass({
		result: function(callback){
			var r = new App.Model.Request;
			this._store.findByKey(this.key,{},r);
			r.success(callback).failed(callback.bind(null,undefined));
		},
		model: function(callback){
			this.result(function(result){
				callback(this._store.toModel(result));
			}.bind(this));
		},
		remove: function(callback){
			var r = new App.Model.Request;
			this._store.deleteByKey(this.primaryKey,r);
			r.success(callback).failed(callback.bind(false));
		},
		forEach: function(callback,onEnd){
			this.forEachKeys(function(){
				this.model(callback);
			}.bind(this),onEnd);
		},
});

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta http-equiv="cache-control" content="no-cache">
<title>reflex Namespace Reference</title>
<link href="doxygen_tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="doxygen_content.css" rel="stylesheet" type="text/css">

reflex Namespace Reference

updated Sun Aug 21 2022 by Robert van Engelen

Main Page

Namespaces

Classes

Files

Namespace List

Namespace Members

Namespaces |
Classes |
Typedefs |
Functions |
Variables

reflex Namespace Reference

Namespaces

  	convert_flag

  	Posix

  	Unicode

Classes

class  	AbstractLexer

 	The abstract lexer class template that is the abstract root class of all reflex-generated scanners.  More...

class  	AbstractMatcher

 	The abstract matcher base class template defines an interface for all pattern matcher engines.  More...

class  	Bits

 	RE/flex Bits class for dynamic bit vectors.  More...

class  	BoostMatcher

 	Boost matcher engine class implements reflex::PatternMatcher pattern matching interface with scan, find, split functors and iterators, using the Boost::regex library.  More...

class  	BoostPerlMatcher

 	Boost matcher engine class, extends reflex::BoostMatcher for Boost Perl regex matching.  More...

class  	BoostPosixMatcher

 	Boost matcher engine class, extends reflex::BoostMatcher for Boost POSIX regex matching.  More...

class  	BufferedInput

 	Buffered input.  More...

class  	FlexLexer

 	Flex-compatible FlexLexer abstract base class template derived from reflex::AbstractMatcher for the reflex-generated yyFlexLexer scanner class.  More...

class  	Input

 	Input character sequence class for unified access to sources of input text.  More...

struct  	lazy_intersection

 	Intersection of two ordered sets, with an iterator to get elements lazely.  More...

struct  	lazy_union

 	Union of two ordered sets, with an iterator to get elements lazely.  More...

class  	Matcher

 	RE/flex matcher engine class, implements reflex::PatternMatcher pattern matching interface with scan, find, split functors and iterators.  More...

class  	ORanges

 	RE/flex ORanges (open-ended, ordinal value range) template class.  More...

class  	Pattern

 	Pattern class holds a regex pattern and its compiled FSM opcode table or code for the reflex::Matcher engine.  More...

class  	PatternMatcher

 	The pattern matcher class template extends abstract matcher base class.  More...

class  	PatternMatcher< std::string >

 	A specialization of the pattern matcher class template for std::string, extends abstract matcher base class.  More...

class  	PCRE2Matcher

 	PCRE2 JIT-optimized matcher engine class implements reflex::PatternMatcher pattern matching interface with scan, find, split functors and iterators, using the PCRE2 library.  More...

class  	PCRE2UTFMatcher

 	PCRE2 JIT-optimized native PCRE2_UTF+PCRE2_UCP matcher engine class, extends PCRE2Matcher.  More...

struct  	range_compare

 	Functor to define a total order on ranges (intervals) represented by pairs.  More...

class  	Ranges

 	RE/flex Ranges template class.  More...

class  	regex_error

 	Regex syntax error exceptions.  More...

class  	StdEcmaMatcher

 	std matcher engine class, extends reflex::StdMatcher for ECMA std::regex::ECMAScript syntax and regex matching.  More...

class  	StdMatcher

 	std matcher engine class implements reflex::PatternMatcher pattern matching interface with scan, find, split functors and iterators, using the C++11 std::regex library.  More...

class  	StdPosixMatcher

 	std matcher engine class, extends reflex::StdMatcher for POSIX ERE std::regex::awk syntax and regex matching.  More...

struct  	TypeOp

 	TypeOp<T>::Type = T, TypeOp<T>::ConstType = const T, TypeOp<T>::NonConstType = non-const T.  More...

struct  	TypeOp< const T >

 	Template specialization of reflex::TypeOp.  More...

Typedefs

typedef int 	convert_flag_type

 	Conversion flags for reflex::convert.  More...

typedef int 	regex_error_type

 	Regex syntax error exception error code.  More...

typedef timeval 	timer_type

Functions

int 	isword (int c)

 	Check ASCII word-like character [A-Za-z0-9_], permitting the character range 0..303 (0x12F) and EOF.  More...

std::string 	convert (const char *pattern, const char *signature, convert_flag_type flags=convert_flag::none, const std::map< std::string, std::string > *macros=NULL)

 	Returns the converted regex string given a regex library signature and conversion flags, throws regex_error.  More...

std::string 	convert (const std::string &pattern, const char *signature, convert_flag_type flags=convert_flag::none, const std::map< std::string, std::string > *macros=NULL)

std::string 	ztoa (size_t n)

template<typename S1 , typename S2 >

bool 	is_disjoint (const S1 &s1, const S2 &s2)

 	Check if sets s1 and s2 are disjoint.  More...

template<typename T , typename S >

bool 	is_in_set (const T &x, const S &s)

 	Check if value x is in set s.  More...

template<typename S1 , typename S2 >

bool 	is_subset (const S1 &s1, const S2 &s2)

 	Check if set s1 is a subset of set s2.  More...

template<typename S1 , typename S2 >

void 	set_insert (S1 &s1, const S2 &s2)

 	Insert set s2 into set s1.  More...

template<typename S , typename E >

void 	set_add (S &s, const E &e)

 	Insert element e into set s.  More...

template<typename S1 , typename S2 >

void 	set_delete (S1 &s1, const S2 &s2)

 	Delete elements of set s2 from set s1.  More...

template<typename S , typename E >

void 	set_erase (S &s, const E &e)

 	Remove element e from set s when present.  More...

void 	timer_start (timer_type &t)

 	Start timer.  More...

float 	timer_elapsed (timer_type &t)

 	Return elapsed time in milliseconds (ms) with microsecond precision since the last call up to 1 minute (wraps if elapsed time exceeds 1 minute!)  More...

std::string 	latin1 (int a, int b, int esc= 'x', bool brackets=true)

 	Convert an 8-bit ASCII + Latin-1 Supplement range [a,b] to a regex pattern.  More...

std::string 	utf8 (int a, int b, int esc= 'x', const char *par="(", bool strict=true)

 	Convert a UCS-4 range [a,b] to a UTF-8 regex pattern.  More...

size_t 	utf8 (int c, char *s)

 	Convert UCS-4 to UTF-8, fills with REFLEX_NONCHAR_UTF8 when out of range, or unrestricted UTF-8 with WITH_UTF8_UNRESTRICTED.  More...

int 	utf8 (const char *s, const char **r=NULL)

 	Convert UTF-8 to UCS, returns REFLEX_NONCHAR for invalid UTF-8 except for MUTF-8 U+0000 and 0xD800-0xDFFF surrogate halves (use WITH_UTF8_UNRESTRICTED to remove any limits on UTF-8 encodings up to 6 bytes).  More...

std::wstring 	wcs (const char *s, size_t n)

 	Convert UTF-8 string to wide string.  More...

std::wstring 	wcs (const std::string &s)

 	Convert UTF-8 string to wide string.  More...

Variables

const unsigned short 	codepages [][256]

Typedef Documentation

          typedef int reflex::convert_flag_type

Conversion flags for reflex::convert.

          typedef int reflex::regex_error_type

Regex syntax error exception error code.

          typedef timeval reflex::timer_type

Function Documentation

          std::string reflex::convert
          (
          const char *
          pattern,

          const char *
          signature,

          convert_flag_type
          flags = convert_flag::none,

          const std::map< std::string, std::string > *
          macros = NULL

          )

Returns the converted regex string given a regex library signature and conversion flags, throws regex_error.

A regex library signature is a string of the form "decls:escapes?+.".

The optional "decls:" part specifies which modifiers and other special (?...) constructs are supported:

non-capturing group (?:...) is supported

letters and digits specify which modifiers e.g. (?ismx) are supported:

'i' specifies that (?i...) case-insensitive matching is supported

'm' specifies that (?m...) multiline mode is supported for the ^ and $ anchors

's' specifies that (?s...) dotall mode is supported

'x' specifies that (?x...) freespace mode is supported

... any other letter or digit modifier, where digit modifiers support (?123) for example

# specifies that (?#...) comments are supported

= specifies that (?=...) lookahead is supported

< specifies that `(?'...)` 'name' groups are supported

< specifies that (?<...) lookbehind and <name> groups are supported

> specifies that (?>...) atomic groups are supported

> specifies that (?|...) group resets are supported

> specifies that (?&...) subroutines are supported

> specifies that (?(...) conditionals are supported

! specifies that (?!=...) and (?!<...) are supported

^ specifies that (?^...) negative (reflex) patterns are supported

* specifies that (*VERB) verbs are supported

The "escapes" characters specify which standard escapes are supported:

a for \a (BEL U+0007)

b for \b the \b word boundary

c for \cX control character specified by X modulo 32

d for \d digit [0-9] ASCII or Unicode digit

e for \e ESC U+001B

f for \f FF U+000C

j for \g group capture e.g. {1}

h for \h ASCII blank [ \t] (SP U+0020 or TAB U+0009)

i for \i reflex indent anchor

j for \j reflex dedent anchor

j for \k reflex undent anchor or group capture e.g. {1}

l for \l lower case letter [a-z] ASCII or Unicode letter

n for \n LF U+000A

o for \o octal ASCII or Unicode code

p for \p{C} Unicode character classes, also implies Unicode ., {X}, , , , , , and UTF-8 patterns

r for \r CR U+000D

s for \s space (SP, TAB, LF, VT, FF, or CR)

t for \t TAB U+0009

u for \u ASCII upper case letter [A-Z] (when not followed by {XXXX})

v for \v VT U+000B

w for \w ASCII word-like character [0-9A-Z_a-z]

x for \xXX 8-bit character encoding in hexadecimal

y for \y word boundary

z for \z end of input anchor

`<code>for `\ begin of input anchor

' for \' end of input anchor

< for \< left word boundary

> for \> right word boundary

A for \A begin of input anchor

B for \B non-word boundary

D for \D ASCII non-digit [^0-9]

H for \H ASCII non-blank [^ \t]

L for \L ASCII non-lower case letter [^a-z]

N for \N not a newline

P for \P{C} Unicode inverse character classes, see 'p'

Q for \Q...\E quotations

R for \R Unicode line break

S for \S ASCII non-space (no SP, TAB, LF, VT, FF, or CR)

U for \U ASCII non-upper case letter [^A-Z]

W for \W ASCII non-word-like character [^0-9A-Z_a-z]

X for \X any Unicode character

Z for \Z end of input anchor, before the final line break

0 for \0nnn 8-bit character encoding in octal requires a leading 0

'1' to '9' for backreferences (not applicable to lexer specifications)

Note that 'p' is a special case to support Unicode-based matchers that natively support UTF8 patterns and Unicode classes {C}, {C}, , , , , , , , , , and {X}. Basically, 'p' prevents conversion of Unicode patterns to UTF8. This special case does not support {NAME} expansions in bracket lists such as [a-z||{upper}] and {lower}{+}{upper} used in lexer specifications.

The optional "?+" specify lazy and possessive support:

? lazy quantifiers for repeats are supported

+ possessive quantifiers for repeats are supported

An optional "." (dot) specifies that dot matches any character except newline. A dot is implied by the presence of the 's' modifier, and can be omitted in that case.

An optional "[" specifies that bracket list union, intersection, and subtraction are supported, i.e. [–[a-z]].

Parameters

pattern	regex string pattern to convert

signature	regex library signature

flags	conversion flags

macros	{name} macros to expand

          std::string reflex::convert
          (
          const std::string &
          pattern,

          const char *
          signature,

          convert_flag_type
          flags = convert_flag::none,

          const std::map< std::string, std::string > *
          macros = NULL

          )

inline

template<typename S1 , typename S2 >

          bool reflex::is_disjoint
          (
          const S1 &
          s1,

          const S2 &
          s2

          )

Check if sets s1 and s2 are disjoint.

Returns

true or false

template<typename T , typename S >

          bool reflex::is_in_set
          (
          const T &
          x,

          const S &
          s

          )

inline

Check if value x is in set s.

Returns

true or false

template<typename S1 , typename S2 >

          bool reflex::is_subset
          (
          const S1 &
          s1,

          const S2 &
          s2

          )

Check if set s1 is a subset of set s2.

Returns

true or false

          int reflex::isword
          (
          int
          c	)

inline

Check ASCII word-like character [A-Za-z0-9_], permitting the character range 0..303 (0x12F) and EOF.

Returns

nonzero if argument c is in [A-Za-z0-9_], zero otherwise

Parameters

c	Character to check

          std::string reflex::latin1
          (
          int
          a,

          int
          b,

          int
          esc = 'x',

          bool
          brackets = true

          )

Convert an 8-bit ASCII + Latin-1 Supplement range [a,b] to a regex pattern.

Returns

regex string to match the UCS range encoded in UTF-8

Parameters

a	lower bound of UCS range

b	upper bound of UCS range

esc	escape char 'x' for hex , or '0' or '\0' for octal \0nnn and

brackets	place in [ brackets ]

template<typename S , typename E >

          void reflex::set_add
          (
          S &
          s,

          const E &
          e

          )

inline

Insert element e into set s.

template<typename S1 , typename S2 >

          void reflex::set_delete
          (
          S1 &
          s1,

          const S2 &
          s2

          )

Delete elements of set s2 from set s1.

template<typename S , typename E >

          void reflex::set_erase
          (
          S &
          s,

          const E &
          e

          )

Remove element e from set s when present.

template<typename S1 , typename S2 >

          void reflex::set_insert
          (
          S1 &
          s1,

          const S2 &
          s2

          )

inline

Insert set s2 into set s1.

          float reflex::timer_elapsed
          (
          timer_type &
          t	)

inline

Return elapsed time in milliseconds (ms) with microsecond precision since the last call up to 1 minute (wraps if elapsed time exceeds 1 minute!)

Parameters

t	timer to be updated

          void reflex::timer_start
          (
          timer_type &
          t	)

inline

Start timer.

Parameters

t	timer to be initialized

          std::string reflex::utf8
          (
          int
          a,

          int
          b,

          int
          esc = 'x',

          const char *
          par = "(",

          bool
          strict = true

          )

Convert a UCS-4 range [a,b] to a UTF-8 regex pattern.

Returns

regex string to match the UCS range encoded in UTF-8

Parameters

a	lower bound of UCS range

b	upper bound of UCS range

esc	escape char 'x' for hex , or '0' or '\0' for octal \0nnn and

par	capturing or non-capturing parenthesis "(?:"

strict	returned regex is strict UTF-8 (true) or permissive and lean UTF-8 (false)

          size_t reflex::utf8
          (
          int
          c,

          char *
          s

          )

inline

Convert UCS-4 to UTF-8, fills with REFLEX_NONCHAR_UTF8 when out of range, or unrestricted UTF-8 with WITH_UTF8_UNRESTRICTED.

Returns

length (in bytes) of UTF-8 character sequence stored in s

Parameters

c	UCS-4 character U+0000 to U+10ffff (unless WITH_UTF8_UNRESTRICTED)

s	points to the buffer to populate with UTF-8 (1 to 6 bytes) not NUL-terminated

          int reflex::utf8
          (
          const char *
          s,

          const char **
          r = NULL

          )

inline

Convert UTF-8 to UCS, returns REFLEX_NONCHAR for invalid UTF-8 except for MUTF-8 U+0000 and 0xD800-0xDFFF surrogate halves (use WITH_UTF8_UNRESTRICTED to remove any limits on UTF-8 encodings up to 6 bytes).

Returns

UCS character

Parameters

s	points to the buffer with UTF-8 (1 to 6 bytes)

r	points to pointer to set to the new position in s after the UTF-8 sequence, optional

          std::wstring reflex::wcs
          (
          const char *
          s,

          size_t
          n

          )

inline

Convert UTF-8 string to wide string.

Returns

wide string

Parameters

s	string with UTF-8 to convert

n	length of the string to convert

          std::wstring reflex::wcs
          (
          const std::string &
          s	)

inline

Convert UTF-8 string to wide string.

Returns

wide string

Parameters

s	string with UTF-8 to convert

          std::string reflex::ztoa
          (
          size_t
          n	)

inline

Variable Documentation

          const unsigned short reflex::codepages[][256]

<address class="footer">
Converted on Sun Aug 21 2022 12:04:16 by Doxygen 1.8.11</address>


text:
module Rpush
  module Daemon
    class InterruptibleSleep

      def initialize
        @sleep_reader, @wake_writer = IO.pipe
        @udp_wakeup = nil
      end

      # enable wake on receiving udp packets at the given address and port
      # this returns the host,port used by bind in case an ephemeral port
      # was indicated by specifying 0 as the port number.
      # @return [String,Integer] host,port of bound UDP socket.
      def enable_wake_on_udp(host, port)
        @udp_wakeup = UDPSocket.new
        @udp_wakeup.bind(host, port)
        @udp_wakeup.addr.values_at(3,1)
      end

      # wait for the given timeout in seconds, or data was written to the pipe
      # or the udp wakeup port if enabled.
      # @return [boolean] true if the sleep was interrupted, or false
      def sleep(timeout)
        read_ports = [@sleep_reader]
        read_ports << @udp_wakeup if @udp_wakeup
        rs, = IO.select(read_ports, nil, nil, timeout) rescue nil

        # consume all data on the readable io's so that our next call will wait for more data
        perform_io(rs, @sleep_reader, :read_nonblock)
        perform_io(rs, @udp_wakeup, :recv_nonblock)

        !rs.nil? && rs.any?
      end

      # writing to the pipe will wake the sleeping thread
      def interrupt_sleep
        @wake_writer.write('.')
      end

      def close
        @sleep_reader.close rescue nil
        @wake_writer.close rescue nil
        @udp_wakeup.close if @udp_wakeup rescue nil
      end

      private

      def perform_io(selected, io, meth)
        if selected && selected.include?(io)
          while true
            begin
              io.__send__(meth, 1)
            rescue Errno::EAGAIN, IO::WaitReadable
              break
            end
          end
        end
      end
    end
  end
end


text:
<?php

namespace GhazanfarMir\CompaniesHouse\Resources;

class Search extends ResourcesBase
{
    /**
     * @param $keyword
     * @param int $items_per_page
     * @param int $start_index
     * @return array|mixed|null|object
     * @throws \Exception
     * @internal param $name
     */
    public function all($keyword, $items_per_page = 20, $start_index = 0)
    {
        $url = $this->buildResourceUrl('/search');

        if (! empty($keyword)) {
            $params = [
                'q' => $keyword,
                'items_per_page' => $items_per_page,
                'start_index' => $start_index,
            ];

            return $this->client->get($url, $params);
        } else {
            throw new \InvalidArgumentException('Invalid Argument: You must provide valid company name to search for.');
        }
    }

    /**
     * @param $keyword
     * @param int $items_per_page
     * @param int $start_index
     * @return array|mixed|null|object
     * @throws \Exception
     * @internal param $name
     */
    public function companies($keyword, $items_per_page = 20, $start_index = 0)
    {
        $uri = $this->buildResourceUrl('/search/companies/');

        if (! empty($keyword)) {
            $params = [
                'q' => $keyword,
                'items_per_page' => $items_per_page,
                'start_index' => $start_index,
            ];

            return $this->client->get($uri, $params);
        } else {
            throw new \InvalidArgumentException('Invalid Argument: You must provide valid company name to search for.');
        }
    }

    /**
     * @param $keyword
     * @param int $items_per_page
     * @param int $start_index
     * @return array|mixed|null|object
     * @throws \Exception
     * @internal param $name
     */
    public function officers($keyword, $items_per_page = 20, $start_index = 0)
    {
        $uri = $this->buildResourceUrl('/search/officers/');

        if (! empty($keyword)) {
            $params = [
                'q' => $keyword,
                'items_per_page' => $items_per_page,
                'start_index' => $start_index,
            ];

            return $this->client->get($uri, $params);
        } else {
            throw new \InvalidArgumentException('Invalid Argument: You must provide valid company name to search for.');
        }
    }

    /**
     * @param $keyword
     * @param int $items_per_page
     * @param int $start_index
     * @return array|mixed|null|object
     * @throws \Exception
     * @internal param $name
     */
    public function disqualified_officers($keyword, $items_per_page = 20, $start_index = 0)
    {
        $uri = '/search/disqualified-officers/';

        if (! empty($keyword)) {
            $params = [
                'q' => $keyword,
                'items_per_page' => $items_per_page,
                'start_index' => $start_index,
            ];

            return $this->client->get($this->base_uri.$uri, $params);
        } else {
            throw new \InvalidArgumentException('Invalid Argument: You must provide valid company name to search for.');
        }
    }
}


text:
import React, { FC, useContext } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';

import {
  Card,
  HeaderContainer,
  QueryTitle,
  VisualizationWrapper,
} from './BrowserPreview.styles';

import AutorunQuery from '../AutorunQuery';
import BrowserQueryMenu from '../BrowserQueryMenu';
import Heading from '../Heading';
import QueryVisualization from '../QueryVisualization';
import QuerySummary from '../QuerySummary';
import QueryLimitReached from '../QueryLimitReached';
import VisualizationPlaceholder from '../VisualizationPlaceholder';
import { NoPropertiesOnEventStream, DashboardsConnection } from './components';

import {
  queriesActions,
  getQueryResults,
  getQueryLimitReached,
  getQueryPerformState,
  SavedQueryListItem,
} from '../../modules/queries';

import {
  getSavedQueryIsEditable,
  getSavedQueryLoading,
} from '../../modules/savedQuery/selectors';
import { useApplyWidgetTheming } from '../../hooks';
import { appActions, appSelectors } from '../../modules/app';

import { getNotExistingEventStreams } from '../../modules/schemas/selectors';
import { getMissingEventStreams } from './utils';
import { AppContext } from '../../contexts';

type Props = {
  /** Current active query */
  currentQuery?: SavedQueryListItem;
  /** Run selected query event handler */
  onRunQuery: () => void;
  /** Edit query event handler */
  onEditQuery: (queryName: string) => void;
};
const BrowserPreview: FC<Props> = ({
  currentQuery,
  onEditQuery,
  onRunQuery,
}) => {
  const dispatch = useDispatch();
  const { t } = useTranslation();
  const queryResults = useSelector(getQueryResults);
  const isQueryLoading = useSelector(getQueryPerformState);
  const isQueryLimitReached = useSelector(getQueryLimitReached);
  const autorunQuery = useSelector(appSelectors.getQueryAutorun);
  const { chartSettings, widgetSettings } = useSelector(
    appSelectors.getVisualization
  );
  const isSavedQueryLoading = useSelector(getSavedQueryLoading);
  const isSavedQueryEditable = useSelector(getSavedQueryIsEditable);
  const notExistingEventStreams = useSelector(getNotExistingEventStreams);
  let savedQueryMissingStreams = [];

  if (!isSavedQueryEditable) {
    savedQueryMissingStreams = getMissingEventStreams(
      currentQuery,
      notExistingEventStreams
    );
  }

  const { enableDashboardsConnection } = useContext(AppContext);

  const { themedChartSettings, themedWidgetSettings } = useApplyWidgetTheming({
    chartSettings,
    widgetSettings,
    dependencies: [currentQuery],
    composeCondition: !!currentQuery,
  });

  return (
    <>
      <HeaderContainer>
        <Heading>{t('browser_preview.title')}</Heading>
        <AutorunQuery
          autorun={autorunQuery}
          label={t('browser_preview.autorun_query_label')}
          tooltipMessage={t('browser_preview.autorun_query_tooltip')}
          onToggle={(autorun) =>
            dispatch(appActions.setQueryAutorun({ autorun }))
          }
        />
      </HeaderContainer>
      <Card>
        {isQueryLimitReached ? (
          <QueryLimitReached />
        ) : (
          <>
            {currentQuery && (
              <QueryTitle title={currentQuery.displayName}>
                {currentQuery.displayName}
              </QueryTitle>
            )}
            {!isSavedQueryEditable && !isSavedQueryLoading ? (
              <NoPropertiesOnEventStream
                missingEventStreams={savedQueryMissingStreams}
              />
            ) : (
              <>
                {currentQuery && queryResults ? (
                  <VisualizationWrapper
                    widgetType={currentQuery.visualization.type}
                  >
                    <QueryVisualization
                      widgetType={currentQuery.visualization.type}
                      widgetSettings={themedWidgetSettings}
                      chartSettings={themedChartSettings}
                      queryResults={queryResults}
                    />
                  </VisualizationWrapper>
                ) : (
                  <VisualizationPlaceholder
                    isLoading={isQueryLoading}
                    onRunQuery={onRunQuery}
                  />
                )}
              </>
            )}
          </>
        )}
        {currentQuery && (
          <>
            <BrowserQueryMenu
              onRemoveQuery={() =>
                dispatch(queriesActions.deleteQuery(currentQuery.name))
              }
              onEditQuery={() => onEditQuery(currentQuery.name)}
            />
            <QuerySummary
              querySettings={currentQuery}
              chartSettings={chartSettings}
            />
            {enableDashboardsConnection && <DashboardsConnection />}
          </>
        )}
      </Card>
    </>
  );
};

export default BrowserPreview;


text: lab work by George Mansbridge and Steven Binns.


text:
<?xml version="1.0"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Magento_UrlRewrite" schema_version="2.0.0">
    </module>
</config>


text:
module Xpay
  class Xpay::ApplicationController < ApplicationController
  end
end


text:
using Xunit;

namespace EdlinSoftware.Verifier.Tests
{
    public class DynamicVerifiersTests
    {
        private class TestVerifier : Verifier<TestVerifier, string>
        {
            protected override void AddDynamicVerifiers(string instanceUnderTest)
            {
                AddCriticalVerifiers(Assert.NotNull)
                .AddNormalVerifiers(
                    sut => Assert.Equal(5, sut.Length),
                    sut => Assert.StartsWith("h", sut),
                    sut => Assert.EndsWith("o", sut)
                    );
            }
        }

        private readonly TestVerifier _verifier;

        public DynamicVerifiersTests()
        {
            _verifier = new TestVerifier();
        }

        [Fact]
        public void Verify_ExecutesAllDynamicVerifiers()
        {
            var vr = _verifier.Verify("");

            Assert.Equal(3, vr.ErrorMessages.Length);
        }

        [Fact]
        public void Verify_DontStoryDynamicVerifiers()
        {
            var vr = _verifier.Verify("");

            Assert.Equal(3, vr.ErrorMessages.Length);

            vr = _verifier.Verify("");

            Assert.Equal(3, vr.ErrorMessages.Length);
        }
    }
}


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

<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<TITLE>
Uses of Interface org.apache.commons.configuration.reloading.Reloadable (Commons Configuration 1.7 API)
</TITLE>

<META NAME="date" CONTENT="2011-09-04">

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
org.apache.commons.configuration.reloading.Reloadable

Packages that use Reloadable

org.apache.commons.configuration

The Configuration main package.

org.apache.commons.configuration.plist

Configuration classes supporting NeXT / OpenStep /GNUStep style configuration.

Uses of Reloadable in org.apache.commons.configuration

Classes in org.apache.commons.configuration that implement Reloadable

 class
AbstractHierarchicalFileConfiguration

          Base class for implementing file based hierarchical configurations.

 class
CombinedConfiguration

 A hierarchical composite configuration class.

 class
DefaultConfigurationBuilder

 A factory class that creates a composite configuration from an XML based
 configuration definition file.

 class
DynamicCombinedConfiguration

          DynamicCombinedConfiguration allows a set of CombinedConfigurations to be used.

 class
HierarchicalINIConfiguration

 A specialized hierarchical configuration implementation for parsing ini
 files.

 class
HierarchicalReloadableConfiguration

          A base class for hierarchical configurations with specific reloading
 requirements.

 class
HierarchicalXMLConfiguration

          Deprecated. This class is deprecated. Use XMLConfiguration
 instead, which supports all features this class had offered before.

 class
MultiFileHierarchicalConfiguration

          This class provides access to multiple configuration files that reside in a location that
 can be specified by a pattern allowing applications to be multi-tenant.

 class
PatternSubtreeConfigurationWrapper

          Wraps a HierarchicalConfiguration and allows subtrees to be access via a configured path with
 replaceable tokens derived from the ConfigurationInterpolator.

 class
SubnodeConfiguration

 A specialized hierarchical configuration class that wraps a single node of
 its parent configuration.

 class
XMLConfiguration

          A specialized hierarchical configuration class that is able to parse XML
 documents.

Uses of Reloadable in org.apache.commons.configuration.plist

Classes in org.apache.commons.configuration.plist that implement Reloadable

 class
PropertyListConfiguration

          NeXT / OpenStep style configuration.

 class
XMLPropertyListConfiguration

          Property list file (plist) in XML format as used by Mac OS X (http://www.apple.com/DTDs/PropertyList-1.0.dtd).

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2001-2011 The Apache Software Foundation. All Rights Reserved.


text:
import os, sys, logging
from datetime import datetime
from keystoneclient.auth.identity import v2
from keystoneclient import session
from novaclient import client as nova_client
from pprint import pprint

# Added as workaround to openstack bug
import time

class MyDeployment:
    """
    Basic Deployment class to leverage classes
    """
    def __init__(self):
        #TODO: config file to define Image, and flavors used
        self.image_id = '67ae5eee-a75d-4e40-ae70-9cb10ae2cc0c' # ubuntu-14.04.2-20150325
        #TODO: config file to define flavor used
        self.flavor = 'm1.medium'
        #TODO: Better way of handling this...do I add in a a test to allocate a floating ip, then assign/test/release?
        self.floating_ip = '192.41.25.12'
        #TODO: Not sure on SSH keys, probably should inject these more dynamically via user scripts
        self.key_name = 'mitcha-default'
        #TODO: Yet another todo: maybe standard naming for "main network" aka "<tenant>-main"?
        self.network_id = '16011015-da6c-4769-b15f-09050ddeb72f'

        self.AUTH_URL = os.environ.get('OS_AUTH_URL')
        self.USERNAME = os.environ.get('OS_USERNAME')
        self.PASSWORD = os.environ.get('OS_PASSWORD')
        self.TENANT = os.environ.get('OS_TENANT_NAME')

        self.auth = v2.Password(auth_url=self.AUTH_URL,
                            username=self.USERNAME,
                            password=self.PASSWORD,
                            tenant_name=self.TENANT
                            )
        self.sess = session.Session(auth=self.auth)
        self.nvc = nova_client.Client('2', session=self.sess)

    def _build_webServer(self):
        """
        Build Instance for use as a webserver
        """
        dt = datetime.strftime(datetime.now(), '%Y%m%d%H%m')
        name = 'ci-webserver-%s' % dt
        fl = self.nvc.flavors.find(name=self.flavor)
        nics = [{'net-id': '%s' % self.network_id }]
        floating_ip = self.nvc.floating_ips.find(ip=self.floating_ip)

        instance = self.nvc.servers.create(name=name,
                                           image=self.image_id,
                                           flavor=fl,
                                           key_name=self.key_name,
                                           nics=nics
                                           )

        # Added as a workaround for a bug in oopenstack
        time.sleep(30)

        instance.add_floating_ip(floating_ip)

        """
        pprint(instance)
        pprint(instance.addresses)
        <Server: ci-webserver-201505121405>
        {u'GST-main': [{u'OS-EXT-IPS-MAC:mac_addr': u'fa:16:3e:26:41:5c',
                u'OS-EXT-IPS:type': u'fixed',
                u'addr': u'192.168.255.126',
                u'version': 4},
               {u'OS-EXT-IPS-MAC:mac_addr': u'fa:16:3e:26:41:5c',
                u'OS-EXT-IPS:type': u'floating',
                u'addr': u'192.41.25.12',
                u'version': 4}]}
        """

    def BuildEnvironment(self):
        """
        Build Environment to use for testing nimbus-api
        """
        webserver_id = self._build_webServer()

def main():
    """
    Main Function
    Everything begins here
    """
    try:
        os.environ['OS_AUTH_URL']
        os.environ['OS_USERNAME']
        os.environ['OS_PASSWORD']
    except:
        print "Please load Openstack Environment Variables"
        sys.exit(2)

    md = MyDeployment()
    md.BuildEnvironment()

if __name__ == "__main__":
    main()


text:
package org.gradle.util.internal;

import java.io.IOException;
import java.io.InputStream;

public abstract class BulkReadInputStream extends InputStream {
    @Override
    public int read() throws IOException {
        byte[] buffer = new byte[1];
        while (true) {
            int nread = read(buffer);
            if (nread < 0) {
                return -1;
            }
            if (nread == 1) {
                return 0xff & buffer[0];
            }
        }
    }

    @Override
    public abstract int read(byte[] bytes, int pos, int count) throws IOException;
}


text:
package org.elasticsearch.xpack.sql.expression.function.scalar.datetime;

import org.elasticsearch.xpack.ql.expression.Expression;
import org.elasticsearch.xpack.ql.expression.function.scalar.UnaryScalarFunction;
import org.elasticsearch.xpack.ql.tree.NodeInfo.NodeCtor2;
import org.elasticsearch.xpack.ql.tree.Source;
import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor.DateTimeExtractor;

import java.time.ZoneId;

/**
 * Extract the day of the year from a datetime.
 */
public class DayOfYear extends DateTimeFunction {
    public DayOfYear(Source source, Expression field, ZoneId zoneId) {
        super(source, field, zoneId, DateTimeExtractor.DAY_OF_YEAR);
    }

    @Override
    protected NodeCtor2<Expression, ZoneId, BaseDateTimeFunction> ctorForInfo() {
        return DayOfYear::new;
    }

    @Override
    protected UnaryScalarFunction replaceChild(Expression newChild) {
        return new DayOfYear(source(), newChild, zoneId());
    }

}


text:
//
//  LDFile.h
//  KAICIID
//
//  Created by Luka Mirosevic on 04/11/2014.
//  Copyright (c) 2014 Luka Mirosevic. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <QuickLook/QuickLook.h>

#import "LDTypes.h"

@interface LDFile : NSObject <NSCoding, NSCopying, QLPreviewItem>

/**
 The unique file identifier.
 */
@property (copy, nonatomic) NSString                    *identifier;

/**
 The file name as it will be displayed
 */
@property (copy, nonatomic) NSString                    *name;

/**
 File extension, e.g. @"pdf" or @"xlsx".
 */
@property (copy, nonatomic) NSString                    *type;

/**
 Thumbnail location for this file.

 Can be nil.
 */
@property (strong, nonatomic) NSURL                     *thumbnail;

/**
 Ordered list of sources where the file is available. If you pass in string objects, they can be NSStrings or NSURLs.
 */
@property (strong, nonatomic) NSArray                   *sources;

/**
 A wildcard meta dictionary for the user to store his own properties in that may be useful to have associated with the file.

 The dictionary tree objects must all conform to NSCoding. This dictionary must get serialised to disk quite prequently for consistency purposes, so for performance reasons keep this dictionary as light as possible.

 Can be nil.
 */
@property (strong, nonatomic) NSDictionary              *meta;

/**
 Factory method
 */
+ (instancetype)fileWithIdentifier:(NSString *)identifier name:(NSString *)name type:(NSString *)type thumbnail:(NSURL *)thumbnail sources:(NSArray *)sources meta:(NSDictionary *)meta;

/**
 Designated initializer
 */
- (id)initWithIdentifier:(NSString *)identifier name:(NSString *)name type:(NSString *)type thumbnail:(NSURL *)thumbnail sources:(NSArray *)sources meta:(NSDictionary *)meta;

/**
 Checks if two files share the same identifier and are therefore treated as the same file
 */
- (BOOL)isEqual:(id)object;

/**
 Check if this file is exactly equal to another file, this means not just the identifier has to match, but everything else about this file as well including sources, name, thumbnail, etc.
 */
- (BOOL)isEqualExactly:(LDFile *)file;

@end


text:
package eu.chargetime.ocpp.model.core;

import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.utilities.MoreObjects;
import java.util.Objects;
import javax.xml.bind.annotation.XmlRootElement;

/** Sent by the Charge Point to the Central System. Request holds no values and is always valid. */
@XmlRootElement
public class HeartbeatRequest implements Request {
  @Override
  public boolean validate() {
    return true;
  }

  @Override
  public boolean transactionRelated() {
    return false;
  }

  @Override
  public boolean equals(Object o) {
    return this == o || o != null && getClass() == o.getClass();
  }

  @Override
  public int hashCode() {
    return Objects.hash(HeartbeatRequest.class);
  }

  @Override
  public String toString() {
    return MoreObjects.toStringHelper(this).add("isValid", validate()).toString();
  }
}


text:
module Log::Analyzer::Rails
  class RoutesInspector < ::ActionDispatch::Routing::RoutesInspector
    private
    def collect_routes(routes)
      routes.collect do |route|
        ::ActionDispatch::Routing::RouteWrapper.new(route)
      end.reject do |route|
        route.internal?
      end.collect do |route|
        collect_engine_routes(route)
        constraints = collect_constraints(route)

        { name:   route.name,
          verb:   route.verb,
          path:   route.path,
          reqs:   route.reqs,
          regexp: route.json_regexp,
          constraints: constraints }
      end
    end

    def collect_constraints(route)
      return [] unless route.app.respond_to?(:constraints)

      route.app.constraints.collect do |constraint|
        case
        when constraint.respond_to?(:matches?)
          constraint.class
        when constraint.respond_to?(:call)
          constraint.source.match(/constraints: (.*)/) do |md|
            md[1]
          end
        else
          nil
        end
      end
    end
  end

  class ConsoleFormatter < ::ActionDispatch::Routing::ConsoleFormatter
    private
    def draw_section(routes)
      header_lengths = ['Prefix', 'Verb', 'URI Pattern', 'Controller#Action'].map(&:length)
      name_width, verb_width, path_width, reqs_width = widths(routes).zip(header_lengths).map(&:max)

      routes.map do |r|
        "#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs].ljust(reqs_width)} #{r[:constraints]}"
      end
    end

    def draw_header(routes)
      name_width, verb_width, path_width, reqs_width = widths(routes)

      "#{"Prefix".rjust(name_width)} #{"Verb".ljust(verb_width)} #{"URI Pattern".ljust(path_width)} #{"Controller#Action".ljust(reqs_width)} Constraints"
    end

    def widths(routes)
      [routes.map { |r| r[:name].length }.max || 0,
       routes.map { |r| r[:verb].length }.max || 0,
       routes.map { |r| r[:path].length }.max || 0,
       routes.map { |r| r[:reqs].length }.max || 0]
    end
  end
end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>

	<?php if(isset($account_created)){ ?>

<?php echo $account_created; ?>

	<?php } else { ?>

Login, Please

	<?php }	?>

	<?php
		echo form_open('login/validate_credentials');
		echo form_input('email','Email');
		echo form_password('password','','placeholder="Password" class="password');
		echo form_label('','lbltext');
		echo anchor('login/signup','Create Account');
	?>
	<input type="submit" name="submit" value="Login"/>
	<?php
		echo form_close();
	?>


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const yargs = tslib_1.__importStar(require("yargs-parser"));
const walker_1 = tslib_1.__importDefault(require("./components/walker"));
const args = yargs.default(process.argv.slice(2));
walker_1.default(args._[0]);
//# sourceMappingURL=index.js.map


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 91(6): 1052 (1999)

#### Original name
Uredo merremiae Berndt

### Remarks
null


text:
package wiwordik.word_card;

import wikokit.base.wikt.sql.quote.TQuote;
import wikokit.base.wikt.sql.quote.TQuotRef;
import wikokit.base.wikt.word.WQuote;
import wiwordik.WConstants;
import wikokit.base.wikipedia.sql.Connect;

import javafx.scene.text.Text;
import javafx.scene.text.Font;

import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;

import java.lang.*;
import javafx.scene.text.FontWeight;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.text.FontPosture;

/** WCQuoteOneSentence contains one quote (phrase/sentence) that illustrates
 * one meaning of Wiktionary word and reference data (author, title, year...).
 *
 * @see wikt.word.WQuote
 */
public class WCQuoteOneSentence {

    /** Quotation sentence. */
    String sentence_text;

    /** Translation of the quotation sentence. */
    String translation_text;
    int translation_indent = 20;

    /** Related bibliography text: author, title, year, publisher. */
    //var reference_text : String;

    /** Author name. */
    String author_name;

    /** Source title. */
    String title;

    /** Years of the book. */
    String years_range;

    /** Publisher. */
    String publisher;

    /** Source. */
    String source;

    public VBox group = new VBox();

    /** Creates a part of card (parts of wiki pages) with list of quotes
     * related to one meaning (sense).
    **/
    public void create (Connect conn,
                        TQuote _quote) {

        // 1. Sentence text
        // WT:ELE: "In the quotation itself the word being illustrated should be in boldface."
        // todo: substitue '''marked word''' by some color, but
        // we are waiting "Rich Text" in JavaFX 2.0
        String s = WQuote.removeHighlightedMarksFromSentence( WConstants.native_lang,
                                                  _quote.getText(), "", "");

        // additional treatment of the sentence text (e.g.,  ,   -> " ")
        sentence_text = WQuote.transformSentenceText(
                                    WConstants.IS_SQLITE, WConstants.native_lang, s);

        Text t_sentence_text = new Text(sentence_text);

        t_sentence_text.setWrappingWidth(WConstants.wordcard_width - 35);
        t_sentence_text.setFont(Font.font(null, FontWeight.NORMAL, 14));
        t_sentence_text.setFill(Color.GREEN);

        group.getChildren().addAll(t_sentence_text);

        translation_text = _quote.getTranslation(conn);
        if(translation_text.length() > 0) {
            translation_text = WQuote.removeHighlightedMarksFromSentence( WConstants.native_lang,
               translation_text, "", "");

            // Optional node, only if there is a translation of the quote sentence.
            Text translation_text_node = new Text(translation_text);
            translation_text_node.setTranslateX(translation_indent);
            translation_text_node.setWrappingWidth(WConstants.wordcard_width - 35 - translation_indent);
            translation_text_node.setFont(Font.font(null, FontWeight.NORMAL, 14));
            translation_text_node.setFill(Color.CHOCOLATE);

            group.getChildren().addAll(translation_text_node);
        }

        // 2. Reference text
        TQuotRef quot_ref = _quote.getReference();
        if(null == quot_ref)
            return;

        // 2a. data and logic
        //reference_text = "{quot_ref.getYearsRange()}{quot_ref.getAuthorName()}";
        years_range = quot_ref.getYearsRange();
        author_name = quot_ref.getAuthorName();
        title       = quot_ref.getTitle();
        publisher   = quot_ref.getPublisherName();
        source      = quot_ref.getSourceName();

        if(WConstants.IS_SQLITE && title.contains("\\\""))   // \" -> " (SQLite feature)
            title = title.replace("\\\"", "\"");

        // commas and //:
        // 1. years_range, author_name
        if(years_range.length() > 0 && author_name.length() > 0)
            years_range = years_range.concat(", ");

        // 2. author_name, title
        if(author_name.length() > 0 && title.length() > 0)
            author_name = author_name.concat(", ");

        // 3. title // (publisher or source)
        if(title.length() > 0 && publisher.length() > 0)
            title = title.concat(" // ");

        // 4. (title or publisher), source
        if((title.length() > 0 || publisher.length() > 0) && source.length() > 0)
            publisher= publisher.concat(", ");

        if(WConstants.DEBUGUI) {
            source = "{source}; quot_ref.id={quot_ref.getID()}";

            sentence_text = "{sentence_text}; quote.id={_quote.getID()}";

            if(translation_text.length() > 0)
                translation_text = "{translation_text}; quot_translation.quote_id={_quote.getID()}";
        }

        // 2b. GUI
        HBox reference_hbox = new HBox();
        reference_hbox.setAlignment(Pos.BASELINE_RIGHT);
        reference_hbox.setSpacing(1);
        //                                  top right bottom left
        reference_hbox.setPadding(new Insets(0,  10,    0,    0));

        // temp debug:
        //reference_hbox.setStyle("-fx-background-color:#e0e0e0");

        if(0 < years_range.length()) {
            Text t_years_range = new Text(years_range);
            t_years_range.setFont(Font.font("Times New Roman", FontWeight.BOLD, 12));
            t_years_range.setFill(Color.GREY);
            reference_hbox.getChildren().addAll(t_years_range);
        }

        if(0 < author_name.length()) {
            Text t_author_name = new Text(author_name);
            t_author_name.setFont(Font.font(null, FontWeight.NORMAL, 12));
            t_author_name.setFill(Color.GREY);
            reference_hbox.getChildren().addAll(t_author_name);
        }

        if(0 < title.length()) {
            Text t_title = new Text(title);
            t_title.setFont(Font.font("Times New Roman Italic", FontPosture.ITALIC, 12));
            t_title.setFill(Color.GREY);
            reference_hbox.getChildren().addAll(t_title);
        }

        if(0 < publisher.length()) {
            Text t_publisher = new Text(publisher);
            t_publisher.setFont(Font.font(null, FontWeight.NORMAL, 12));
            t_publisher.setFill(Color.GREY);
            reference_hbox.getChildren().addAll(t_publisher);
        }

        if(0 < source.length()) {
            Text t_source = new Text(source);
            t_source.setFont(Font.font(null, FontWeight.NORMAL, 12));
            t_source.setFill(Color.GREY);
            reference_hbox.getChildren().addAll(t_source);
        }

        // insert reference_hbox into group.content;
        group.getChildren().addAll(reference_hbox);
    }

}


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

<title>PartitionRegionHelper (Apache Geode 1.0.0-incubating.M2)</title>
<meta name="date" content="2016-04-13">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.gemstone.gemfire.cache.partition

Class PartitionRegionHelper

java.lang.Object

com.gemstone.gemfire.cache.partition.PartitionRegionHelper

public final class PartitionRegionHelper
extends java.lang.Object

Utility methods for handling partitioned Regions, for example
 during execution of Functions on a Partitioned
 Region.

Example of a Function using utility methods:

  public Serializable execute(FunctionContext context) {
     if (context instanceof RegionFunctionContext) {
         RegionFunctionContext rc = (RegionFunctionContext) context;
         if (PartitionRegionHelper.isPartitionedRegion(rc.getDataSet())) {
             Region efficientReader =
              PartitionRegionHelper.getLocalDataForContext(rc);
             efficientReader.get("someKey");
             // ...
         }
      }
  // ...

Since:

6.0

See Also:

FunctionService.onRegion(Region)

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static void
assignBucketsToPartitions(Region<?,?> region)

Decide which partitions will host which buckets.

static <K,V> java.util.Set<DistributedMember>
getAllMembersForKey(Region<K,V> r,
                   K key)

Get all potential owners for a key.

static java.util.Map<java.lang.String,Region<?,?>>
getColocatedRegions(Region<?,?> r)

Given a partitioned Region, return a map of colocated Regions.

static java.util.Map<java.lang.String,Region<?,?>>
getLocalColocatedRegions(RegionFunctionContext c)

Given a RegionFunctionContext for a partitioned Region, return a map of colocated Regions
 with read access limited to the context of the function.

static <K,V> Region<K,V>
getLocalData(Region<K,V> r)

Given a partitioned Region return a Region providing read access limited to
 the local heap, writes using this Region have no constraints and behave the
 same as a partitioned Region.

static <K,V> Region<K,V>
getLocalDataForContext(RegionFunctionContext c)

Given a RegionFunctionContext
 for a partitioned Region,
 return a Region providing read access limited to the function context.

 Returned Region provides only one copy of the data although
 redundantCopies configured
 is more than 0.

static <K,V> Region<K,V>
getLocalPrimaryData(Region<K,V> r)

Given a partitioned Region return a Region providing read access to primary
 copy of the data which is limited to the local heap, writes using this
 Region have no constraints and behave the same as a partitioned Region.

static java.util.Set<PartitionRegionInfo>
getPartitionRegionInfo(Cache cache)

Gathers a set of details about all partitioned regions in the local Cache.

static PartitionRegionInfo
getPartitionRegionInfo(Region<?,?> region)

Gathers details about the specified partitioned region.

static <K,V> DistributedMember
getPrimaryMemberForKey(Region<K,V> r,
                      K key)

Get the current primary owner for a key.

static <K,V> java.util.Set<DistributedMember>
getRedundantMembersForKey(Region<K,V> r,
                         K key)

Get all potential redundant owners for a key.

static boolean
isPartitionedRegion(Region<?,?> r)

Test a Region to see if it is a partitioned Region

static <K> void
moveBucketByKey(Region<K,?> region,
               DistributedMember source,
               DistributedMember destination,
               K key)

Moves the bucket which contains the given key from the source member to the
 destination member.

static RebalanceResults
moveData(Region<?,?> region,
        DistributedMember source,
        DistributedMember destination,
        float percentage)

Moves data from the source member to the destination member, up to the
 given percentage of data (measured in bytes).

Methods inherited from class java.lang.Object

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

Method Detail

getColocatedRegions

public static java.util.Map<java.lang.String,Region<?,?>> getColocatedRegions(Region<?,?> r)

Given a partitioned Region, return a map of colocated Regions.
 Given a local data reference to a partitioned region, return a map of local
 colocated Regions.
 If there are no colocated regions, return an empty map.

Parameters:

r - a partitioned Region

Returns:

an unmodifiable map of region name to Region

Throws:

java.lang.IllegalStateException - if the Region is not a partitioned Region

Since:

6.0

isPartitionedRegion

public static boolean isPartitionedRegion(Region<?,?> r)

Test a Region to see if it is a partitioned Region

Parameters:

r -

Returns:

true if it is a partitioned Region

Since:

6.0

getPartitionRegionInfo

public static java.util.Set<PartitionRegionInfo> getPartitionRegionInfo(Cache cache)

Gathers a set of details about all partitioned regions in the local Cache.
 If there are no partitioned regions then an empty set will be returned.

Parameters:

cache - the cache which has the regions

Returns:

set of details about all locally defined partitioned regions

Since:

6.0

getPartitionRegionInfo

public static PartitionRegionInfo getPartitionRegionInfo(Region<?,?> region)

Gathers details about the specified partitioned region. Returns null if
 the partitioned region is not locally defined.

Parameters:

region - the region to get info about

Returns:

details about the specified partitioned region

Since:

6.0

assignBucketsToPartitions

public static void assignBucketsToPartitions(Region<?,?> region)

Decide which partitions will host which buckets. Gemfire normally assigns
 buckets to partitions as needed when data is added to a partitioned region.
 This method provides way to assign all of the buckets without putting any
 data in partition region. This method should not be called until all of the
 partitions are running because it will divide the buckets between the
 running partitions. If the buckets are already assigned this method will
 have no effect.

 This method will block until all buckets are assigned.

Parameters:

region - The region which should have it's buckets assigned.

Throws:

java.lang.IllegalStateException - if the provided region is something other than a
         partitioned Region

Since:

6.0

getPrimaryMemberForKey

public static <K,V> DistributedMember getPrimaryMemberForKey(Region<K,V> r,
                                                             K key)

Get the current primary owner for a key.  Upon return there is no guarantee that
 primary owner remains the primary owner, or that the member is still alive.

This method is not a substitute for Region.containsKey(Object).

Parameters:

r - a PartitionedRegion

key - the key to evaluate

Returns:

the primary member for the key, possibly null if a primary is not yet determined

Throws:

java.lang.IllegalStateException - if the provided region is something other than a
        partitioned Region

Since:

6.0

getRedundantMembersForKey

public static <K,V> java.util.Set<DistributedMember> getRedundantMembersForKey(Region<K,V> r,
                                                                               K key)

Get all potential redundant owners for a key.  If the key exists in the Region,
 upon return there is no guarantee that key has not been moved or that
 the members are still alive.

This method is not a substitute for Region.containsKey(Object).

 This method is equivalent to:

  DistributedMember primary = getPrimaryMemberForKey(r, key);
  Set<? extends DistributedMember> allMembers = getAllMembersForKey(r, key);
  allMembers.remove(primary);

Parameters:

r - a PartitionedRegion

key - the key to evaluate

Returns:

an unmodifiable set of members minus the primary

Throws:

java.lang.IllegalStateException - if the provided region is something other than a
        partitioned Region

Since:

6.0

getAllMembersForKey

public static <K,V> java.util.Set<DistributedMember> getAllMembersForKey(Region<K,V> r,
                                                                         K key)

Get all potential owners for a key.  If the key exists in the Region, upon return
 there is no guarantee that it has not moved nor does it guarantee all members are still
 alive.

This method is not a substitute for Region.containsKey(Object).

Parameters:

r - PartitionedRegion

key - the key to evaluate

Returns:

an unmodifiable set of all members

Throws:

java.lang.IllegalStateException - if the provided region is something other than a
        partitioned Region

Since:

6.0

getLocalColocatedRegions

public static java.util.Map<java.lang.String,Region<?,?>> getLocalColocatedRegions(RegionFunctionContext c)

Given a RegionFunctionContext for a partitioned Region, return a map of colocated Regions
 with read access limited to the context of the function.

 Writes using these Region have no constraints and behave the same as a partitioned Region.

 If there are no colocated regions, return an empty map.

Parameters:

c - the region function context

Returns:

an unmodifiable map of region name to Region

Throws:

java.lang.IllegalStateException - if the Region is not a partitioned Region

Since:

6.0

getLocalDataForContext

public static <K,V> Region<K,V> getLocalDataForContext(RegionFunctionContext c)

Given a RegionFunctionContext
 for a partitioned Region,
 return a Region providing read access limited to the function context.

 Returned Region provides only one copy of the data although
 redundantCopies configured
 is more than 0. If the invoking Function is configured to have
 optimizeForWrite as true,the returned
 Region will only contain primary copy of the data.

 Writes using this Region have no constraints and behave the same as a
 partitioned Region.

Parameters:

c - a functions context

Returns:

a Region for efficient reads

Throws:

java.lang.IllegalStateException - if RegionFunctionContext.getDataSet() returns something
           other than a partitioned Region

Since:

6.0

getLocalData

public static <K,V> Region<K,V> getLocalData(Region<K,V> r)

Given a partitioned Region return a Region providing read access limited to
 the local heap, writes using this Region have no constraints and behave the
 same as a partitioned Region.

Parameters:

r - a partitioned region

Returns:

a Region for efficient reads

Throws:

java.lang.IllegalStateException - if the provided region is something other than a
                 partitioned Region

Since:

6.0

getLocalPrimaryData

public static <K,V> Region<K,V> getLocalPrimaryData(Region<K,V> r)

Given a partitioned Region return a Region providing read access to primary
 copy of the data which is limited to the local heap, writes using this
 Region have no constraints and behave the same as a partitioned Region.

Parameters:

r - a partitioned region

Returns:

a Region for efficient reads

Throws:

java.lang.IllegalStateException - if the provided region is something other than a
           partitioned Region

Since:

6.5

moveBucketByKey

public static <K> void moveBucketByKey(Region<K,?> region,
                                       DistributedMember source,
                                       DistributedMember destination,
                                       K key)

Moves the bucket which contains the given key from the source member to the
 destination member. The bucket will be fully transferred once this method
 is complete, if the method does not throw an exception.

 All keys which exist in the same bucket will also be moved to the new node.

 Any data in colocated regions that are colocated with this key will also be
 moved.

 This method allows direct control of what data to move. To automatically
 balance buckets, see ResourceManager.createRebalanceFactory()

Parameters:

region - The region in which to move the bucket. Data in regions colocated
          with this region will also be moved.

source - A member that is currently hosting this bucket. The bucket is
          moved off of this member.

destination - A member that is not currently hosting this bucket, but has the
          partitioned region defined. The bucket is moved to this member.

key - A key which maps to the bucket to move. This key does not actually
          need to exist in the region, but if using a
          PartitionResolver the resolver should be able to get the
          routing object from this key to determine the bucket to move.

Throws:

java.lang.IllegalStateException - if the bucket is not present on the source, if the source or
           destination are not valid members of the system, if the
           destination already hosts a copy of the bucket, or if the bucket
           does not exist.

Since:

7.1

moveData

public static RebalanceResults moveData(Region<?,?> region,
                                        DistributedMember source,
                                        DistributedMember destination,
                                        float percentage)

Moves data from the source member to the destination member, up to the
 given percentage of data (measured in bytes). The data will be fully
 transferred once this method is complete, if the method does not throw an
 exception. The percentage is a percentage of the amount of data in bytes on
 the source member for this region.

 If this region has colocated regions, the colocated data will also be
 moved. The total amount of data in all colocated regions will be taken into
 consideration when determining what percentage of data will be moved.

 It may not be possible to move data to the destination member, if the
 destination member has no available space, no bucket smaller than the given
 percentage exists, or if moving data would violate redundancy constraints.
 If data cannot be moved, this method will return a RebalanceResult object
 with 0 total bucket transfers.

 This method allows direct control of what data to move. To automatically
 balance buckets, see ResourceManager.createRebalanceFactory()

Parameters:

region - The region in which to move data. Data in regions colocated with
          this region will also be moved.

source - A member that is currently hosting data. The bucket is moved off
          of this member.

destination - A member that that has the partitioned region defined. Data is
          moved to this member.

percentage - the maximum amount of data to move, as a percentage from 0 to 100.

Returns:

A RebalanceResult object that contains information about what what
         data was actually moved.

Throws:

java.lang.IllegalStateException - if the source or destination are not valid members of the system.

java.lang.IllegalArgumentException - if the percentage is not between 0 to 100.

Since:

7.1

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
import {
    isEmpty
} from 'lodash';
import {
    sep
} from 'path';
import interpolateOptionsValue from './interpolateOptionsValue';

/**
 * @param {*} loaderContext
 * @param {*} content
 * @param {Object} options
 * @returns {String}
 */
export default (loaderContext, content, options) => {
    let value = interpolateOptionsValue('namespaces', loaderContext, content, options);

    if (!isEmpty(value)) {
        value = value.split(sep).join(options.sep) + options.sep;
    }

    return value;
};


text:
<?php

namespace Mmoreram\GearmanBundle\Event;

use Mmoreram\GearmanBundle\Event\Abstracts\AbstractGearmanClientTaskEvent;

/**
 * GearmanClientCallbackWorkloadEvent
 *
 * @since 2.3.1
 */
class GearmanClientCallbackWorkloadEvent extends AbstractGearmanClientTaskEvent
{

}


text:
package com.prt2121.githubsdk.model.response;

import java.util.Date;

public class GistRevision extends ShaUrl {

  private Date committedAt;

  private GitChangeStatus changeStatus;

  private String version;

  private User user;

  /**
   * @return committedAt
   */
  public Date getCommittedAt() {
    return committedAt;
  }

  /**
   * @return this gist revision
   */
  public GistRevision setCommittedAt(Date committedAt) {
    this.committedAt = committedAt;
    return this;
  }

  /**
   * @return changeStatus
   */
  public GitChangeStatus getChangeStatus() {
    return changeStatus;
  }

  /**
   * @return this gist revision
   */
  public GistRevision setChangeStatus(GitChangeStatus changeStatus) {
    this.changeStatus = changeStatus;
    return this;
  }

  /**
   * @return url
   */
  public String getUrl() {
    return url;
  }

  /**
   * @return this gist revision
   */
  public GistRevision setUrl(String url) {
    this.url = url;
    return this;
  }

  /**
   * @return version
   */
  public String getVersion() {
    return version;
  }

  /**
   * @return this gist revision
   */
  public GistRevision setVersion(String version) {
    this.version = version;
    return this;
  }

  /**
   * @return user
   */
  public User getUser() {
    return user;
  }

  /**
   * @return this gist revision
   */
  public GistRevision setUser(User user) {
    this.user = user;
    return this;
  }
}


text:
package org.apache.harmony.tests.java.lang.instrument;

import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import tests.support.Support_Exec;

public class InstrumentTest extends TestCase {

    /**
     * @tests try to add a null Transformer
     */
    public void test_addTransformer_null() throws Exception {
        String[] arg = new String[2];
        arg[0] = "-javaagent:src/test/resources/jars/org/apache/harmony/tests/instrument/Premain_addTransformer_null.jar";
        arg[1] = "org/apache/harmony/tests/java/lang/instrument/TestMain";
        String[] path = new String[1];
        path[0] = "src/test/resources/jars/org/apache/harmony/tests/instrument/Premain_addTransformer_null.jar";
        String result = Support_Exec.execJava(arg, path, true);
        assertEquals("", result);
    }

    /**
     * @tests try to remove a null Transformer
     */
    public void test_removeTransformer_null() throws Exception {
        String[] arg = new String[2];
        arg[0] = "-javaagent:src/test/resources/jars/org/apache/harmony/tests/instrument/Premain_removeTransformer_null.jar";
        arg[1] = "org/apache/harmony/tests/java/lang/instrument/TestMain";
        String[] path = new String[1];
        path[0] = "src/test/resources/jars/org/apache/harmony/tests/instrument/Premain_removeTransformer_null.jar";
        String result = Support_Exec.execJava(arg, path, true);
        assertEquals("", result);
    }

    /**
     * @tests try to remove a non-exists Transformer
     */
    public void test_removeTransformer_notExists() throws Exception {
        String[] arg = new String[2];
        arg[0] = "-javaagent:src/test/resources/jars/org/apache/harmony/tests/instrument/Premain_removeTransformer_notExists.jar";
        arg[1] = "org/apache/harmony/tests/java/lang/instrument/TestMain";
        String[] path = new String[1];
        path[0] = "src/test/resources/jars/org/apache/harmony/tests/instrument/Premain_removeTransformer_notExists.jar";
        String result = Support_Exec.execJava(arg, path, true);
        assertEquals("", result);
    }

    /**
     * @tests try to load a class that does not exist
     */
    public void test_loadClass_null() throws Exception {
        String[] arg = new String[2];
        arg[0] = "-javaagent:src/test/resources/jars/org/apache/harmony/tests/instrument/loading_class.jar";
        arg[1] = "org/apache/harmony/tests/java/lang/instrument/TestMain";
        String[] path = new String[1];
        path[0] = "src/test/resources/jars/org/apache/harmony/tests/instrument/loading_class.jar";
        try {
            Support_Exec.execJava(arg, path, true);
            fail("Should fail here!");
        } catch (AssertionFailedError e) {
            // class loader changes, can not load classes
            assertTrue(-1 != e.getMessage().indexOf("NoClassDefFoundError"));
        }
    }

    /**
     * @tests try to use a new ClassLoader
     */
    public void test_new_classLoader_Exists() throws Exception {
        String[] arg = new String[2];
        arg[0] = "-javaagent:src/test/resources/jars/org/apache/harmony/tests/instrument/new_classloader.jar";
        arg[1] = "org/apache/harmony/tests/java/lang/instrument/TestMain";
        String[] path = new String[1];
        path[0] = "src/test/resources/jars/org/apache/harmony/tests/instrument/new_classloader.jar";
        String result = Support_Exec.execJava(arg, path, true);
        assertNotNull(result);
    }

    /**
     * @tests test if attribute of "Premain-Class" is null
     */
    public void test_Property_Premain_null() throws Exception {
        String[] arg = new String[2];
        arg[0] = "-javaagent:src/test/resources/jars/org/apache/harmony/tests/instrument/Property_Premain_null.jar";
        arg[1] = "org/apache/harmony/tests/java/lang/instrument/TestMain";
        String[] path = new String[1];
        path[0] = "src/test/resources/jars/org/apache/harmony/tests/instrument/Property_Premain_null.jar";
        try {
            Support_Exec.execJava(arg, path, true);
            fail("Should fail here!");
        } catch (AssertionFailedError e) {
            // expected
            assertTrue(-1 != e.getMessage().indexOf("Failed")
                    || -1 != e.getMessage().indexOf("error"));
            assertTrue(-1 != e.getMessage().indexOf("Premain-Class"));
            assertTrue(-1 != e.getMessage().indexOf("attribute"));
        }
    }

    /**
     * @tests test if attributes of "Can-Redefine-Classes" and "Boot-Class-Path"
     *        is null
     */
    public void test_Property_other_null() throws Exception {
        String[] arg = new String[2];
        arg[0] = "-javaagent:src/test/resources/jars/org/apache/harmony/tests/instrument/Property_other_null.jar";
        arg[1] = "org/apache/harmony/tests/java/lang/instrument/TestMain";
        String[] path = new String[1];
        path[0] = "src/test/resources/jars/org/apache/harmony/tests/instrument/Property_other_null.jar";
        String result = Support_Exec.execJava(arg, path, true);
        assertNotNull(result);
    }

    /**
     * @tests test if the attributes is case-sensitive
     */
    public void test_Properity_case_sensitive() throws Exception {
        String[] arg = new String[2];
        arg[0] = "-javaagent:src/test/resources/jars/org/apache/harmony/tests/instrument/Properity_case_sensitive.jar";
        arg[1] = "org/apache/harmony/tests/java/lang/instrument/TestMain";
        String[] path = new String[1];
        path[0] = "src/test/resources/jars/org/apache/harmony/tests/instrument/Properity_case_sensitive.jar";
        String result = Support_Exec.execJava(arg, path, true);
        assertEquals("", result);
    }

    /**
     * @tests test if the jar file is bad
     */
    public void test_BadFormatJar() throws Exception {
        String[] arg = new String[2];
        arg[0] = "-javaagent:src/test/resources/jars/org/apache/harmony/tests/instrument/BadFormatJar.jar";
        arg[1] = "";
        String[] path = new String[1];
        path[0] = "src/test/resources/jars/org/apache/harmony/tests/instrument/BadFormatJar.jar";
        try {
            Support_Exec.execJava(arg, path, true);
            fail("Should fail here!");
        } catch (AssertionFailedError e) {
            // expected
            assertTrue(-1 != e.getMessage().indexOf("error")
                    || -1 != e.getMessage().indexOf("Error"));
            assertTrue(-1 != e.getMessage().indexOf("open"));
            assertTrue(-1 != e.getMessage().indexOf("file"));
        }
    }

    /**
     * @tests test if premain class is null
     */
    public void test_Premain_Class_null() throws Exception {
        String[] arg = new String[2];
        arg[0] = "-javaagent:src/test/resources/jars/org/apache/harmony/tests/instrument/Premain_Class_null.jar";
        arg[1] = "org/apache/harmony/tests/java/lang/instrument/TestMain";
        String[] path = new String[1];
        path[0] = "src/test/resources/jars/org/apache/harmony/tests/instrument/Premain_Class_null.jar";
        try {
            Support_Exec.execJava(arg, path, true);
            fail("Should fail here!");
        } catch (AssertionFailedError e) {
            // expected
            assertTrue(-1 != e.getMessage().indexOf("ClassNotFoundException"));
        }
    }

    /**
     * @tests test transforming all classes to a zero byte
     */
    public void test_zero_byte_transformer() throws Exception {
        String[] arg = new String[2];
        arg[0] = "-javaagent:src/test/resources/jars/org/apache/harmony/tests/instrument/zero_byte_class.jar";
        arg[1] = "org/apache/harmony/tests/java/lang/instrument/TestMain";
        String[] path = new String[1];
        path[0] = "src/test/resources/jars/org/apache/harmony/tests/instrument/zero_byte_class.jar";
        String result = Support_Exec.execJava(arg, path, true);
        assertEquals("", result);
    }

    /**
     * @tests test if complied by version 1.4
     */
    public void test_old_version() throws Exception {
        String[] arg = new String[2];
        arg[0] = "-javaagent:src/test/resources/jars/org/apache/harmony/tests/instrument/old_version_class.jar";
        arg[1] = "org/apache/harmony/tests/java/lang/instrument/TestMain";
        String[] path = new String[1];
        path[0] = "src/test/resources/jars/org/apache/harmony/tests/instrument/old_version_class.jar";
        String result = Support_Exec.execJava(arg, path, true);
        assertEquals("", result);
    }
}


text:
require 'spec_helper'

class CgLookupClient::CachingEndpointSet
  describe Key do
    it 'is frozen on initialization' do
      key = Key.new('mod', 'type', 'version')
      key.frozen?.should be_true
    end

    it 'implements to_s' do
      key = Key.new('mod', 'type', '1')
      "#{key}".should == 'type-v1(mod)'
    end

    it 'behaves as a hash key' do
      key1 = Key.new(Key, 'type', '1')
      key2 = Key.new(Key, 'type', '1')

      key1.equal?(key2).should be_false
      key1.should == key2
      key1.hash.should == key2.hash
    end
  end
end