text:
package org.jgroups.protocols.pbcast;

import org.jgroups.*;
import org.jgroups.logging.Log;
import org.jgroups.util.*;

import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static org.jgroups.Message.Flag.OOB;
import static org.jgroups.Message.TransientFlag.DONT_LOOPBACK;

/**
 * Handles merging. Called by CoordGmsImpl and ParticipantGmsImpl
 * @author Bela Ban
 */
public class Merger {
    protected final GMS                          gms;
    protected final Log                          log;

    protected final MergeTask                    merge_task=new MergeTask();

    /** For MERGE_REQ/MERGE_RSP correlation, contains MergeData elements */
    protected final ResponseCollector<MergeData> merge_rsps=new ResponseCollector<>();

    /** For GET_DIGEST / DIGEST_RSP correlation */
    protected final ResponseCollector<Digest>    digest_collector=new ResponseCollector<>();

    protected MergeId                            merge_id=null;

    protected final BoundedList<MergeId>         merge_id_history=new BoundedList<>(20);

    protected Future<?>                          merge_killer=null;

    public Merger(GMS gms) {
        this.gms=gms;
        this.log=gms.getLog();
    }

    public String               getMergeIdAsString()       {return merge_id != null? merge_id.toString() : null;}
    public String               getMergeIdHistory()        {return merge_id_history.toString();}
    public boolean              isMergeTaskRunning()       {return merge_task.isRunning();}
    public boolean              isMergeKillerTaskRunning() {return merge_killer != null && !merge_killer.isDone();}
    public synchronized MergeId getMergeId()               {return merge_id;} // only used for testing; do not use
    public synchronized boolean isMergeInProgress()        {return merge_id != null;}
    public synchronized boolean matchMergeId(MergeId id)   {return Util.match(this.merge_id, id);}

    public synchronized boolean setMergeId(MergeId expected, MergeId new_value) {
        boolean match=Util.match(this.merge_id, expected);
        if(match) {
            if(new_value != null && merge_id_history.contains(new_value))
                return false;
            else
                merge_id_history.add(new_value);
            this.merge_id=new_value;
            if(this.merge_id != null) {
                // Clears the view handler queue and discards all JOIN/LEAVE/MERGE requests until after the MERGE
                gms.getViewHandler().suspend();
                gms.getDownProtocol().down(new Event(Event.SUSPEND_STABLE, 20000));
                startMergeKiller();
            }
        }
        return match;
    }

    /**
     * Invoked upon receiving a MERGE event from the MERGE layer. Starts the merge protocol.
     * See description of protocol in DESIGN.
     * @param views A List of different views detected by the merge protocol, keyed by sender
     */
    public void merge(Map<Address, View> views) {
        if(views == null || views.isEmpty()) {
            log.warn("the views passed with the MERGE event were empty (or null); ignoring MERGE event");
            return;
        }

        if(View.sameViews(views.values())) {
            log.debug("MERGE event is ignored because of identical views: %s", Util.printListWithDelimiter(views.values(), ", "));
            return;
        }

        if(isMergeInProgress()) {
            log.trace("%s: merge is already running (merge_id=%s)", gms.getAddress(), merge_id);
            return;
        }

        Address merge_leader=determineMergeLeader(views);
        if(merge_leader == null)
            return;

        if(merge_leader.equals(gms.getAddress())) {
            log.debug("%s: I will be the merge leader. Starting the merge task. Views: %s", gms.getAddress(), views);
            merge_task.start(views);
        }
        else
            log.trace("%s: I'm not the merge leader, waiting for merge leader (%s) to start merge", gms.getAddress(), merge_leader);
    }

    /**
     * Get the view and digest and send back both (MergeData) in the form of a MERGE_RSP to the sender.
     * If a merge is already in progress, send back a MergeData with the merge_rejected field set to true.
     * @param sender The address of the merge leader
     * @param merge_id The merge ID
     * @param mbrs The set of members from which we expect responses. Guaranteed to be non-null
     */
    public void handleMergeRequest(Address sender, MergeId merge_id, Collection<? extends Address> mbrs) {
        try {
            _handleMergeRequest(sender, merge_id, mbrs);
        }
        catch(Throwable t) {
            log.error("%s: failure handling the merge request: %s", gms.getAddress(), t.getMessage());
            cancelMerge(merge_id);
            sendMergeRejectedResponse(sender, merge_id);
        }
    }

    public void handleMergeResponse(MergeData data, MergeId merge_id) {
        if(!matchMergeId(merge_id)) {
            log.trace("%s: this.merge_id (%s) is different from merge_id %s sent by %s as merge response, discarding it",
                      gms.getAddress(), this.merge_id, merge_id, data.getSender());
            return;
        }
        merge_rsps.add(data.getSender(), data);
    }

    /**
     * If merge_id is not equal to this.merge_id then discard. Else cast the view/digest to all members of this group.
     */
    public void handleMergeView(final MergeData data, final MergeId merge_id) {
        if(!matchMergeId(merge_id)) {
            log.trace("%s: merge_ids (mine: %s, received: %s) don't match; merge view %s is discarded",
                      gms.getAddress(), this.merge_id, merge_id, data.view.getViewId());
            return;
        }

        // only send to our *current* members, if we have A and B being merged (we are B), then we would *not*
        // want to block on a VIEW_ACK from A because A doesn't see us in the pre-merge view yet and discards the view
        List<Address> expected_acks=gms.members.getMembers();
        try {
            gms.castViewChangeAndSendJoinRsps(data.view, data.digest, expected_acks, null, null);
            // if we have flush in stack send ack back to merge coordinator
            if(gms.flushProtocolInStack) { //[JGRP-700] - FLUSH: flushing should span merge
                Message ack=new EmptyMessage(data.getSender()).setFlag(OOB)
                  .putHeader(gms.getId(), new GMS.GmsHeader(GMS.GmsHeader.INSTALL_MERGE_VIEW_OK));
                gms.getDownProtocol().down(ack);
            }
        }
        finally {
            cancelMerge(merge_id);
        }
    }

    public void handleMergeCancelled(MergeId merge_id) {
        try {
            gms.stopFlush();
        }
        catch(Throwable t) {
            log.error(Util.getMessage("StopFlushFailed"), t.getMessage());
        }
        log.trace("%s: merge %s is cancelled", gms.getAddress(), merge_id);
        cancelMerge(merge_id);
    }

    public void handleDigestResponse(Address sender, Digest digest) {
        digest_collector.add(sender, digest);
    }

    /**
     * Removes all members from a given view which don't have us in their view
     * (https://issues.redhat.com/browse/JGRP-1061). Example:
     *

     * A: AB
     * B: AB
     * C: ABC
     *

     * becomes
     *

     * A: AB
     * B: AB
     * C: C // A and B don't have C in their views
     *

     * @param map A map of members and their associated views
     */
    public static void sanitizeViews(Map<Address,View> map) {
        if(map == null)
            return;
        for(Map.Entry<Address,View> entry: map.entrySet()) {
            Address key=entry.getKey();
            List<Address> members=new ArrayList<>(entry.getValue().getMembers());
            boolean modified=false;
            for(Iterator<Address> it=members.iterator(); it.hasNext();) {
                Address val=it.next();
                if(val.equals(key)) // we can always talk to ourself !
                    continue;
                View view=map.get(val);
                final Collection<Address> tmp_mbrs=view != null? view.getMembers() : null;
                if(tmp_mbrs != null && !tmp_mbrs.contains(key)) {
                    it.remove();
                    modified=true;
                }
            }
            if(modified) {
                View old_view=entry.getValue();
                entry.setValue(new View(old_view.getViewId(), members));
            }
        }
    }

    /** Returns the address of the merge leader */
    protected Address determineMergeLeader(Map<Address,View> views) {
        // we need the merge *coordinators* not merge participants because not everyone can lead a merge !
        Collection<Address> coords=Util.determineActualMergeCoords(views);
        if(coords.isEmpty())
            coords=Util.determineMergeCoords(views); // https://issues.redhat.com/browse/JGRP-2092
        if(coords.isEmpty()) {
            log.error("%s: unable to determine merge leader from %s; not starting a merge", gms.getAddress(), views);
            return null;
        }
        return new Membership(coords).sort().elementAt(0); // establish a deterministic order, so that coords can elect leader
    }

    /**
     * Needs to return a map of all subview coordinators and their views (as a collection of members). The merge policy
     * is defined in https://issues.redhat.com/browse/JGRP-1910
     */
    protected static Map<Address,Collection<Address>> determineMergeCoords(Map<Address,View> views) {
           Map<Address,Collection<Address>> retval=new HashMap<>();
           for(View view: views.values()) {
               Address coord=view.getCreator();
               Collection<Address> members=retval.computeIfAbsent(coord, k -> new ArrayList<>());
               for(Address mbr: view.getMembersRaw())
                   if(!members.contains(mbr))
                       members.add(mbr);
           }

           // For the merge participants which are not coordinator, we simply add them, and the associated
           // membership list consists only of themselves
           Collection<Address> merge_participants=Util.determineMergeParticipants(views);
           merge_participants.removeAll(retval.keySet());
           merge_participants.stream().filter(merge_participant -> !retval.containsKey(merge_participant))
             .forEach(merge_participant -> retval.put(merge_participant, Collections.singletonList(merge_participant)));
           return retval;
       }

    protected void _handleMergeRequest(Address sender, MergeId merge_id, Collection<? extends Address> mbrs) throws Exception {
        MergeId current_merge_id=this.merge_id;
        boolean success=matchMergeId(merge_id) || setMergeId(null, merge_id);
        if(!success) {
            log.trace("%s: merge %s is already in progress, received merge-id=%s", gms.getAddress(), current_merge_id, merge_id);
            return;
        }

        /* Clears the view handler queue and discards all JOIN/LEAVE/MERGE requests until after the MERGE  */
        // gms.getViewHandler().suspend();
        log.trace("%s: got merge request from %s, merge_id=%s, mbrs=%s", gms.getAddress(), sender, merge_id, mbrs);

        // merge the membership of the current view with mbrs
        List<Address> members=new ArrayList<>(mbrs != null? mbrs.size() : 32);
        if(mbrs != null) // didn't use a set because we didn't want to change the membership order at this time (although not incorrect)
            mbrs.stream().filter(mbr -> !members.contains(mbr)).forEach(members::add);

        // Now remove members that are not in our current view:
        members.retainAll(gms.view().getMembers());

        // Add myself if not present
        if(!members.contains(gms.getAddress()))
            members.add(gms.getAddress());

        ViewId tmp_vid=gms.getViewId();
        if(tmp_vid == null)
            throw new Exception("view ID is null; cannot return merge response");
        View view=new View(tmp_vid, members);

        if(gms.flushProtocolInStack && !gms.startFlush(view)) // if flush is in stack, let this coord flush its subcluster
            throw new Exception("flush failed");

        // we still need to fetch digests from all members, and not just return our own digest (https://issues.redhat.com/browse/JGRP-948)
        Digest digest=fetchDigestsFromAllMembersInSubPartition(view, merge_id);
        if(digest == null || digest.capacity() == 0)
            throw new Exception("failed fetching digests from subpartition members; dropping merge response");

        sendMergeResponse(sender, view, digest, merge_id);
    }

    /** Send back a response containing view and digest to sender */
    protected void sendMergeResponse(Address sender, View view, Digest digest, MergeId merge_id) {
        Message msg=new BytesMessage(sender).setArray(GMS.marshal(view, digest)).setFlag(OOB)
          .putHeader(gms.getId(), new GMS.GmsHeader(GMS.GmsHeader.MERGE_RSP).mergeId(merge_id));
        gms.getDownProtocol().down(msg);
    }

    /**
     * Sends the new view and digest to all subgroup coordinators. Each coord will in turn broadcast the new view and
     * digest to all the members of its subgroup
     */
    protected void sendMergeView(Collection<Address> coords, MergeData combined_merge_data, MergeId merge_id) {
        if(coords == null || coords.isEmpty() || combined_merge_data == null)
            return;

        View view=combined_merge_data.view;
        Digest digest=combined_merge_data.digest;
        if(view == null || digest == null) {
            log.error(Util.getMessage("ViewOrDigestIsNullCannotSendConsolidatedMergeView/Digest"));
            return;
        }

        int size=0;
        if(gms.flushProtocolInStack) {
            gms.merge_ack_collector.reset(coords);
            size=gms.merge_ack_collector.size();
        }

        Event install_merge_view_evt=new Event(Event.INSTALL_MERGE_VIEW, view);
        gms.getUpProtocol().up(install_merge_view_evt);
        gms.getDownProtocol().down(install_merge_view_evt);

        // Change coords to move self to the tail: if UNICAST3.loopback is true, we might be the first member on which
        // handleMergeView() is invoked, which blocks on reception of all view-acks, delaying view installation in
        // others. By moving self to the tail, at least the other coords can install the MergeView in parallel
        List<Address> coords_copy=new ArrayList<>(coords);
        if(coords_copy.remove(gms.getAddress()))
            coords_copy.add(gms.getAddress());

        log.debug("%s: installing merge view %s in %s", gms.getAddress(), combined_merge_data.view.getViewId(), coords_copy);
        long start=System.currentTimeMillis();
        for(Address coord: coords_copy) {
            Message msg=new BytesMessage(coord).setArray(GMS.marshal(view, digest))
              .putHeader(gms.getId(), new GMS.GmsHeader(GMS.GmsHeader.INSTALL_MERGE_VIEW).mergeId(merge_id));
            gms.getDownProtocol().down(msg);
        }

        //[JGRP-700] - FLUSH: flushing should span merge; if flush is in stack, wait for acks from subview coordinators
        if(gms.flushProtocolInStack) {
            try {
                gms.merge_ack_collector.waitForAllAcks(gms.view_ack_collection_timeout);
                log.trace("%s: received all ACKs (%d) for merge view %s in %d ms",
                          gms.getAddress(), size, view, (System.currentTimeMillis() - start));
            }
            catch(TimeoutException e) {
                log.warn("%s: failed to collect all ACKs (%d) for merge view %s after %d ms, missing ACKs from %s",
                         gms.getAddress(), size, view, gms.view_ack_collection_timeout, gms.merge_ack_collector.printMissing());
            }
        }
    }

    protected void sendMergeRejectedResponse(Address sender, MergeId merge_id) {
        Message msg=new EmptyMessage(sender).setFlag(OOB)
          .putHeader(gms.getId(), new GMS.GmsHeader(GMS.GmsHeader.MERGE_RSP).mergeId(merge_id).mergeRejected(true));
        gms.getDownProtocol().down(msg);
    }

    protected void sendMergeCancelledMessage(Collection<Address> coords, MergeId merge_id) {
        if(coords == null || merge_id == null)
            return;
        for(Address coord: coords) {
            Message msg=new EmptyMessage(coord).putHeader(gms.getId(), new GMS.GmsHeader(GMS.GmsHeader.CANCEL_MERGE).mergeId(merge_id));
            gms.getDownProtocol().down(msg);
        }
    }

    /**
     * Multicasts a GET_DIGEST_REQ to all members of this sub partition and waits for all responses
     * (GET_DIGEST_RSP) or N ms.
     */
    protected Digest fetchDigestsFromAllMembersInSubPartition(final View view, MergeId merge_id) {
        final List<Address> current_mbrs=view.getMembers();

        // Optimization: if we're the only member, we don't need to multicast the get-digest message
        if(current_mbrs == null || current_mbrs.size() == 1 && current_mbrs.get(0).equals(gms.getAddress()))
            return new MutableDigest(view.getMembersRaw())
              .set((Digest)gms.getDownProtocol().down(new Event(Event.GET_DIGEST, gms.getAddress())));

        Message get_digest_req=new EmptyMessage().setFlag(OOB).setFlag(DONT_LOOPBACK)
          .putHeader(gms.getId(), new GMS.GmsHeader(GMS.GmsHeader.GET_DIGEST_REQ).mergeId(merge_id));

        long max_wait_time=gms.merge_timeout / 2; // gms.merge_timeout is guaranteed to be > 0, verified in init()
        digest_collector.reset(current_mbrs);
        long start=System.currentTimeMillis();
        gms.getDownProtocol().down(get_digest_req);

        // add my own digest first - the get_digest_req needs to be sent first *before* getting our own digest, so
        // we have that message in our digest !
        Digest digest=(Digest)gms.getDownProtocol().down(new Event(Event.GET_DIGEST, gms.getAddress()));
        digest_collector.add(gms.getAddress(), digest);
        digest_collector.waitForAllResponses(max_wait_time);
        if(log.isTraceEnabled()) {
            if(digest_collector.hasAllResponses())
                log.trace("%s: fetched all digests for %s in %d ms", gms.getAddress(), current_mbrs, System.currentTimeMillis()-start);
            else
                log.trace("%s: fetched incomplete digests (after timeout of %d) ms for %s",
                          gms.getAddress(), max_wait_time, current_mbrs);
        }

        List<Address> valid_rsps=new ArrayList<>(current_mbrs);
        valid_rsps.removeAll(digest_collector.getMissing());

        Address[] tmp=new Address[valid_rsps.size()];
        valid_rsps.toArray(tmp);
        MutableDigest retval=new MutableDigest(tmp);
        Map<Address,Digest> responses=new HashMap<>(digest_collector.getResults());
        responses.values().forEach(retval::set);
        return retval;
    }

    /**
     * Fetches the digests from all members and installs them again. Used only for diagnosis and support; don't
     * use this otherwise !
     */
    protected void fixDigests() {
        Digest digest=fetchDigestsFromAllMembersInSubPartition(gms.view, null);
        Message msg=new BytesMessage().putHeader(gms.getId(), new GMS.GmsHeader(GMS.GmsHeader.INSTALL_DIGEST))
          .setArray(GMS.marshal(null, digest));
        gms.getDownProtocol().down(msg);
    }

    protected void stop() {
        merge_task.stop();
    }

    protected synchronized void cancelMerge(MergeId id) {
        if(setMergeId(id, null)) {
            merge_task.stop();
            stopMergeKiller();
            merge_rsps.reset();
            gms.getViewHandler().resume();
            gms.getDownProtocol().down(new Event(Event.RESUME_STABLE));
        }
    }

    protected synchronized void forceCancelMerge() {
        if(this.merge_id != null)
            cancelMerge(this.merge_id);
    }

    protected synchronized void startMergeKiller() {
        if(merge_killer == null || merge_killer.isDone()) {
            MergeKiller task=new MergeKiller(this.merge_id);
            merge_killer=gms.timer.schedule(task, gms.merge_timeout * 2, TimeUnit.MILLISECONDS, false);
        }
    }

    protected synchronized void stopMergeKiller() {
        if(merge_killer != null) {
            merge_killer.cancel(false);
            merge_killer=null;
        }
    }

    /**
     * Starts the merge protocol (only run by the merge leader). Essentially sends a MERGE_REQ to all
     * coordinators of all subgroups found. Each coord receives its digest and view and returns it.
     * The leader then computes the digest and view for the new group from the return values. Finally, it
     * sends this merged view/digest to all subgroup coordinators; each coordinator will install it in their
     * subgroup.
     */
    protected class MergeTask implements Runnable {
        protected Thread thread=null;

        /** List of all subpartition coordinators and their members */
        protected final ConcurrentMap<Address,Collection<Address>> coords=Util.createConcurrentMap(8, 0.75f, 8);
        protected final Set<View>                                  subviews=new HashSet<>();

        /**
         * @param views Guaranteed to be non-null and to have >= 2 members, or else this thread would not be started
         */
        public synchronized void start(Map<Address, View> views) {
            if(thread != null && thread.isAlive()) // the merge thread is already running
                return;

            this.coords.clear();
            this.subviews.clear();
            subviews.addAll(views.values());

            // now remove all members which don't have us in their view, so RPCs won't block (e.g. FLUSH)
            // https://issues.redhat.com/browse/JGRP-1061
            sanitizeViews(views);

            Map<Address,Collection<Address>> tmp_coords=determineMergeCoords(views);
            this.coords.putAll(tmp_coords);

            thread=gms.getThreadFactory().newThread(this, "MergeTask");
            thread.setDaemon(true);
            thread.start();
        }

        public synchronized void stop() {
            Thread tmp=thread;
            if(thread != null && thread.isAlive())
                tmp.interrupt();
            thread=null;
        }

        public synchronized boolean isRunning() {
            return thread != null && thread.isAlive();
        }

        public void run() {
            // 1. Generate merge_id
            final MergeId new_merge_id=MergeId.create(gms.getAddress());
            final Collection<Address> coordsCopy=new ArrayList<>(coords.keySet());

            long start=System.currentTimeMillis();

            try {
               _run(new_merge_id, coordsCopy); // might remove members from coordsCopy
            }
            catch(Throwable ex) {
                if(ex instanceof Error || ex instanceof RuntimeException)
                    log.warn(gms.getAddress() + ": merge is cancelled", ex);
                else
                    log.warn("%s: merge is cancelled: %s", gms.getAddress(), ex.getMessage());
                sendMergeCancelledMessage(coordsCopy, new_merge_id);
                cancelMerge(new_merge_id); // the message above cancels the merge, too, but this is a 2nd line of defense
            }
            finally {
                /* 5. if flush is in stack stop the flush for entire cluster [JGRP-700] - FLUSH: flushing should span merge */
                if(gms.flushProtocolInStack)
                    gms.stopFlush();
                thread=null;
            }
            long diff=System.currentTimeMillis() - start;
            log.debug("%s: merge %s took %d ms", gms.getAddress(), new_merge_id, diff);
        }

        /** Runs the merge protocol as a leader */
        protected void _run(MergeId new_merge_id, final Collection<Address> coordsCopy) throws Exception {
            boolean success=setMergeId(null, new_merge_id);
            if(!success) {
                log.warn("%s: failed to set my own merge_id (%s) to %s", gms.getAddress(), merge_id, new_merge_id);
                return;
            }

            log.debug("%s: merge task %s started with %d participants", gms.getAddress(), merge_id, coords.keySet().size());

            // Fetch the current views and digests from all subgroup coordinators into merge_rsps
            success=getMergeDataFromSubgroupCoordinators(coords, new_merge_id, gms.merge_timeout);
            List<Address> missing=null;
            if(!success) {
                missing=merge_rsps.getMissing();
                log.debug("%s: merge leader %s did not get responses from all %d partition coordinators; " +
                            "missing responses from %d members, removing them from the merge",
                          gms.getAddress(), gms.getAddress(), coords.keySet().size(), missing.size());
                merge_rsps.remove(missing);
            }

            // Remove null or rejected merge responses from merge_rsp and coords (so we'll send the new view
            // only to members who accepted the merge request)
            if(missing != null && !missing.isEmpty()) {
                coords.keySet().removeAll(missing);
                coordsCopy.removeAll(missing);
            }

            removeRejectedMergeRequests(coords.keySet());
            if(merge_rsps.size() == 0)
                throw new Exception("did not get any merge responses from partition coordinators");

            if(!coords.containsKey(gms.getAddress())) // another member might have invoked a merge req on us before we got there...
                throw new Exception("merge leader rejected merge request");

            // Combine all views and digests into 1 View/1 Digest
            List<MergeData> merge_data=new ArrayList<>(merge_rsps.getResults().values());
            MergeData combined_merge_data=consolidateMergeData(merge_data, new ArrayList<>(subviews));
            if(combined_merge_data == null)
                throw new Exception("could not consolidate merge");

            // send the new view and digest to all coords (including myself). On reception, they will
            // install the digest and view in all of their subgroup members
            sendMergeView(coords.keySet(), combined_merge_data, new_merge_id);
        }

        /**
         * Sends a MERGE_REQ to all coords and populates a list of MergeData (in merge_rsps). Returns after coords.size()
         * response have been received, or timeout msecs have elapsed (whichever is first).

         * If a subgroup coordinator rejects the MERGE_REQ (e.g. because of participation in a different merge),
         * that member will be removed from coords !
         * @param coords A map of coordinatgor addresses and associated membership lists
         * @param new_merge_id The new merge id
         * @param timeout Max number of msecs to wait for the merge responses from the subgroup coords
         */
        protected boolean getMergeDataFromSubgroupCoordinators(Map<Address,Collection<Address>> coords, MergeId new_merge_id, long timeout) {
            boolean gotAllResponses;
            long start=System.currentTimeMillis();
            merge_rsps.reset(coords.keySet());
            log.trace("%s: sending MERGE_REQ to %s", gms.getAddress(), coords.keySet());

            for(Map.Entry<Address,Collection<Address>> entry: coords.entrySet()) {
                Address coord=entry.getKey();
                Collection<Address> mbrs=entry.getValue();
                Message msg=new BytesMessage(coord).setFlag(OOB)
                  .putHeader(gms.getId(), new GMS.GmsHeader(GMS.GmsHeader.MERGE_REQ).mbr(gms.getAddress()).mergeId(new_merge_id))
                  .setArray(GMS.marshal(mbrs));
                gms.getDownProtocol().down(msg);
            }

            // wait until num_rsps_expected >= num_rsps or timeout elapsed
            merge_rsps.waitForAllResponses(timeout);
            gotAllResponses=merge_rsps.hasAllResponses();
            long time=System.currentTimeMillis() - start;
            log.trace("%s: collected %d merge response(s) in %d ms", gms.getAddress(), merge_rsps.numberOfValidResponses(), time);
            return gotAllResponses;
        }

        /** Removed rejected merge requests from merge_rsps and coords. This method has a lock on merge_rsps */
        protected void removeRejectedMergeRequests(Collection<Address> coords) {
            int num_removed=0;
            for(Iterator<Map.Entry<Address,MergeData>> it=merge_rsps.getResults().entrySet().iterator(); it.hasNext();) {
                Map.Entry<Address,MergeData> entry=it.next();
                MergeData data=entry.getValue();
                if(data.merge_rejected) {
                    if(data.getSender() != null)
                        coords.remove(data.getSender());
                    it.remove();
                    num_removed++;
                }
            }
            if(num_removed > 0)
                log.trace("%s: removed %d rejected merge responses", gms.getAddress(), num_removed);
        }

        /**
         * Merge all MergeData. All MergeData elements should be disjunct (both views and digests). However,
         * this method is prepared to resolve duplicate entries (for the same member). The resolution strategy for
         * views is to merge only 1 of the duplicate members. Resolution strategy for digests is to take the higher
         * seqnos for duplicate digests.

         * After merging all members into a Membership and subsequent sorting, the first member of the sorted membership
         * will be the new coordinator. This method has a lock on merge_rsps.
         * @param merge_rsps A list of MergeData items. Elements with merge_rejected=true were removed before. Is guaranteed
         *          not to be null and to contain at least 1 member
         * @param subviews Contains a list of Views, each View is a subgroup
         */
        protected MergeData consolidateMergeData(List<MergeData> merge_rsps, List<View> subviews) {
            long                            logical_time=0; // for new_vid
            Collection<Collection<Address>> sub_mbrships=new ArrayList<>();
            Set<Address>                    digest_membership=new HashSet<>(); // members as seen by the digests

            for(MergeData tmp_data: merge_rsps) {
                View tmp_view=tmp_data.getView();
                if(tmp_view != null) {
                    ViewId tmp_vid=tmp_view.getViewId();
                    if(tmp_vid != null)
                        logical_time=Math.max(logical_time, tmp_vid.getId()); // compute the new view id (max of all vids +1)

                    // merge all membership lists into one (prevent duplicates)
                    sub_mbrships.add(new ArrayList<>(tmp_view.getMembers()));
                }
                Digest digest=tmp_data.getDigest();
                if(digest != null)
                    for(Digest.Entry entry: digest)
                        digest_membership.add(entry.getMember());
            }

            // remove all members from the new view for which we didn't get a digest, e.g. new view={A,B,C,D,E,F},
            // digest={A,C,D,F} --> new view={A,C,D,F}, digest={A,C,D,F}
            if(!digest_membership.isEmpty())
                for(Collection<Address> coll: sub_mbrships)
                    coll.retainAll(digest_membership);

            List<Address> merged_mbrs=gms.computeNewMembership(sub_mbrships);

            // remove all members from the (future) MergeView that are not in the digest
            // Usually not needed, but a second line of defense in case the membership change policy above
            // computed the new view incorrectly, e.g. not removing dupes
            Set<Address> all_members=new HashSet<>();
            sub_mbrships.forEach(all_members::addAll);
            merged_mbrs.retainAll(all_members);

            // the new coordinator is the first member of the consolidated & sorted membership list
            Address new_coord=merged_mbrs.isEmpty()? null : merged_mbrs.get(0);
            if(new_coord == null)
                return null;

            // Remove views from subviews whose creator are not in the new membership
            for(Iterator<View> it=subviews.iterator(); it.hasNext();) {
                View v=it.next();
                logical_time=Math.max(logical_time, v.getViewId().getId());
                Address creator=v.getCreator();
                if(creator != null && !merged_mbrs.contains(creator))
                    it.remove();
            }

            // determine the new view; logical_time should be the highest view ID seen up to now plus 1
            MergeView new_view=new MergeView(new_coord, logical_time + 1, merged_mbrs, subviews);

            // determine the new digest
            MutableDigest new_digest=consolidateDigests(new_view, merge_rsps);
            if(new_digest == null || !new_digest.allSet())
                return null;

            log.trace("%s: consolidated view=%s\nconsolidated digest=%s", gms.getAddress(), new_view, new_digest);
            return new MergeData(gms.getAddress(), new_view, new_digest);
        }

        /**
         * Merge all digests into one. For each sender, the new value is max(highest_delivered),
         * max(highest_received). This method has a lock on merge_rsps
         */
        protected MutableDigest consolidateDigests(final View new_view, final List<MergeData> merge_rsps) {
            MutableDigest retval=new MutableDigest(new_view.getMembersRaw());
            for(MergeData data: merge_rsps) {
                Digest tmp_digest=data.getDigest();
                if(tmp_digest != null)
                    retval.merge(tmp_digest);
            }
            return retval;
        }
    }

    protected class MergeKiller implements Runnable {
        protected final MergeId my_merge_id;

        MergeKiller(MergeId my_merge_id) {
            this.my_merge_id=my_merge_id;
        }

        public void run() {
            cancelMerge(my_merge_id);
        }

        public String toString() {
            return Merger.class.getSimpleName() + ": " + getClass().getSimpleName();
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Text;

#if logging

#endif

namespace Encog.Parse.Tags
{
    /// <summary>
    /// HTMLTag: This class holds a single HTML tag. This class subclasses the
    /// AttributeList class. This allows the HTMLTag class to hold a collection of
    /// attributes, just as an actual HTML tag does.
    /// </summary>
    public class Tag
    {
        /// <summary>
        /// Tag types.
        /// </summary>
        public enum Type
        {
            /// <summary>
            /// A beginning tag.
            /// </summary>
            Begin,
            /// <summary>
            /// An ending tag.
            /// </summary>
            End,
            /// <summary>
            /// A comment.
            /// </summary>
            Comment,
            /// <summary>
            /// A CDATA section.
            /// </summary>
            CDATA
        } ;

        /// <summary>
        /// The tag's attributes.
        /// </summary>
        private readonly IDictionary<String, String> _attributes =
            new Dictionary<String, String>();

        /// <summary>
        /// The tag name.
        /// </summary>
        private String _name = "";

        /// <summary>
        /// The tag type.
        /// </summary>
        private Type _type;

        /// <summary>
        /// Clear the name, type and attributes.
        /// </summary>
        public void Clear()
        {
            _attributes.Clear();
            _name = "";
            _type = Type.Begin;
        }

        /// <summary>
        /// Clone this object.
        /// </summary>
        /// <returns>A cloned copy of the object.</returns>
        public virtual object Clone()
        {
            var result = new Tag {Name = Name, TagType = TagType};
            foreach (String key in _attributes.Keys)
            {
                String value = _attributes[key];
                result.Attributes[key] = value;
            }
            return result;
        }

        /// <summary>
        /// Get the specified attribute as an integer.
        /// </summary>
        /// <param name="attributeId">The attribute name.</param>
        /// <returns>The attribute value.</returns>
        public int GetAttributeInt(String attributeId)
        {
            try
            {
                String str = GetAttributeValue(attributeId);
                return int.Parse(str);
            }
            catch (Exception e)
            {
#if logging
                if (logger.IsErrorEnabled)
                {
                    logger.Error("Exception", e);
                }
#endif
                throw new ParseError(e);
            }
        }

        /// <summary>
        /// The attributes for this tag as a dictionary.
        /// </summary>
        public IDictionary<String, String> Attributes
        {
            get { return _attributes; }
        }

        /// <summary>
        /// Get the value of the specified attribute.
        /// </summary>
        /// <param name="name">The name of an attribute.</param>
        /// <returns>The value of the specified attribute.</returns>
        public String GetAttributeValue(String name)
        {
            if (!_attributes.ContainsKey(name))
                return null;

            return _attributes[name];
        }

        /// <summary>
        /// The tag name.
        /// </summary>
        public String Name
        {
            get { return _name; }
            set { _name = value; }
        }

        /// <summary>
        /// The tag type.
        /// </summary>
        public Type TagType
        {
            get { return _type; }
            set { _type = value; }
        }

        /// <summary>
        /// Set a HTML attribute.
        /// </summary>
        /// <param name="name">The name of the attribute.</param>
        /// <param name="valueRen">The value of the attribute.</param>
        public void SetAttribute(String name, String valueRen)
        {
            _attributes[name] = valueRen;
        }

        /// <summary>
        /// Convert this tag back into string form, with the
        /// beginning < and ending >.
        /// </summary>
        /// <returns>The Attribute object that was found.</returns>
        public override String ToString()
        {
            var buffer = new StringBuilder("<");

            if (_type == Type.End)
            {
                buffer.Append("/");
            }

            buffer.Append(_name);

            ICollection<String> set = _attributes.Keys;
            foreach (String key in set)
            {
                String value = _attributes[key];
                buffer.Append(' ');

                if (value == null)
                {
                    buffer.Append("\"");
                    buffer.Append(key);
                    buffer.Append("\"");
                }
                else
                {
                    buffer.Append(key);
                    buffer.Append("=\"");
                    buffer.Append(value);
                    buffer.Append("\"");
                }
            }

            buffer.Append(">");
            return buffer.ToString();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.nd4j.linalg.api.ops.impl.transforms.custom;

import org.nd4j.shade.guava.primitives.Doubles;
import org.nd4j.shade.guava.primitives.Ints;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.common.base.Preconditions;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.DynamicCustomOp;
import org.nd4j.linalg.exception.ND4JIllegalArgumentException;
import org.nd4j.linalg.indexing.conditions.Condition;

import java.util.Collections;
import java.util.List;

public class Choose extends DynamicCustomOp {
    private Condition condition;

    public Choose(SameDiff sameDiff, SDVariable[] args, Condition condition) {
        super(null, sameDiff, args);
        if(condition == null) {
            throw new ND4JIllegalArgumentException("Must specify a condition.");
        }

        this.inPlace = true;
        this.inplaceCall = true;
        addIArgument(condition.conditionType().index);
        this.condition = condition;
    }

    public Choose(String opName, INDArray[] inputs, INDArray[] outputs, List<Double> tArguments, List<Integer> iArguments) {
        super(opName, inputs, outputs, tArguments, iArguments);
    }

    public Choose(String opName, INDArray[] inputs, Condition condition) {
        super(opName, inputs, null);
        if(condition == null) {
            throw new ND4JIllegalArgumentException("Must specify a condition.");
        }

        addInputArgument(inputs);
        addIArgument(condition.conditionType().index);
    }

    /**
     *
     * @param inputs
     * @param condition
     */
    public Choose(INDArray[] inputs,Condition condition) {
        this(inputs, Collections.<Integer>emptyList(),Collections.<Double>emptyList(),condition);
    }

    /**
     * Note that iArgs (integer arguments) and  tArgs(double/float arguments)
     * may end up being used under the following conditions:
     * scalar operations (if a scalar is specified the you do not need to specify an ndarray)
     * otherwise, if an ndarray is needed as a second input then put it in the inputs
     *
     * Usually, you only need 1 input (the equivalent of the array you're trying to do indexing on)
     *
     * @param inputs the inputs in to the op
     * @param iArgs the integer arguments as needed
     * @param tArgs the arguments
     * @param condition the condition to filter on
     */
    public Choose(INDArray[] inputs,List<Integer> iArgs, List<Double> tArgs,Condition condition) {
        super(null, inputs, null);
        if(condition == null) {
            throw new ND4JIllegalArgumentException("Must specify a condition.");
        }

        if(!iArgs.isEmpty())
            addIArgument(Ints.toArray(iArgs));

        if(!tArgs.isEmpty())
            addTArgument(Doubles.toArray(tArgs));
        addIArgument(condition.conditionType().index);
    }

    public Choose(String opName, SameDiff sameDiff, SDVariable[] args, boolean inPlace) {
        super(opName, sameDiff, args, inPlace);
    }

    public Choose(){
        //No-arg constructor for use in DifferentialFunctionClassHolder
    }

    @Override
    public String opName() {
        return "choose";
    }

    @Override
    public List<DataType> calculateOutputDataTypes(List<DataType> dataTypes){
        Preconditions.checkState(dataTypes != null && dataTypes.size() == 1, "Expected exactly 1 input datatype for %s, got %s", getClass(), dataTypes);
        return Collections.singletonList(dataTypes.get(0));
    }
}


text:
//
//  BloomFilter.h
//  QuickSearchDatabase
//
//  Created by Ivan Montiel on 2/15/12.
//  Copyright (c) 2012 Idea Birth. All rights reserved.
//

#include <string.h>

#ifndef QuickSearchDatabase_BloomFilter_h
#define QuickSearchDatabase_BloomFilter_h

typedef char byte;

/**
 Bloom Filter Class
 By:            Ivan Montiel
 Description:   A probabilistic data structure.
                Hashes elements into a bitarray.
                Returns either "not in" or "might be in" structure.
*/

class BloomFilter {
public:
    /**
     * Constructor
     */
    BloomFilter(int s = 800) : bitarray(0) {
        s = s / 8 + (s % 8 == 0 ? 0 : 1); // Convert the size to bytes and round up
        this->size = s;
        bitarray = new byte[s];
        for (int i = 0; i < s; i++) {
            bitarray[i] = 0;
        }
    };
    /**
     * Copy Constructor
     */
    BloomFilter(BloomFilter const&) {
       // TODO
    };
    /**
     * Deconstructor
     */
    ~BloomFilter() {
        delete [] bitarray;
    };

    void add(const char* element) {
        // Hash the element
        unsigned int firstHash = hash(element);
        unsigned int secondHash = hash(firstHash);
        unsigned int thirdHash = hash(secondHash);

        unsigned int hashed = firstHash % size;
        unsigned int hashed2 = secondHash % size;
        unsigned int hashed3 = thirdHash % size;

        bitarray[hashed] |= 1 << (firstHash % 8);
        bitarray[hashed2] |= 1 << (secondHash % 8);
        bitarray[hashed3] |= 1 << (thirdHash % 8);

    };
    bool query(const char* element) {
        // Hash the element
        unsigned int firstHash = hash(element);
        unsigned int secondHash = hash(firstHash);
        unsigned int thirdHash = hash(secondHash);

        unsigned int hashed = firstHash % size;
        unsigned int hashed2 = secondHash % size;
        unsigned int hashed3 = thirdHash % size;

        bool check1 = bitarray[hashed] & (1 << (firstHash % 8));
        bool check2 = bitarray[hashed2] & (1 << (secondHash % 8));
        bool check3 = bitarray[hashed3] & (1 << (thirdHash % 8));

        return check1 && check2 && check3;
    };

private:
    byte* bitarray;
    int size;

    unsigned hash(const char* s) {
        unsigned h = 100714;
        while (*s) {
            h = h * 101 + (unsigned int) *s;
            s++;
        }
        return h;
    }
    unsigned hash(unsigned s) {
        unsigned h = 100714;
        h = h * 101 + (s % 1007533);
        return h;
    }

};

#endif


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;

namespace dnscrypt_winclient_ru
{
	public partial class ApplicationForm : Form
	{
		public const int SW_SHOWMINIMIZED = 2;
		public const int SW_HIDE = 0;
		public const UInt32 BCM_SETSHIELD = 0x160C;

		private ProcessStartInfo CryptProc = null;
		private Process CryptHandle = null;
		private ServiceController CryptService = null;
		private bool CryptProcRunning = false;
		private bool ServiceInstalled = false;
		private Thread ServiceCheck = null;
		private int LastPluginTooltipIndex = -1;
		private string registryRoot = "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\dnscrypt-proxy\\Parameters\\";

		//A map of names to list entries so that we can rebuild the listbox and remember which items were checked
		private Dictionary<String, Pair<NetworkListItem, bool>> NICitems = new Dictionary<string, Pair<NetworkListItem, bool>>();

		private BindingList<DNSCryptProvider> Providers = new BindingList<DNSCryptProvider>();
		private List<PluginListItem> Plugins = new List<PluginListItem>();

		[DllImport("user32.dll")]
		public static extern UInt32 SendMessage (IntPtr hWnd, UInt32 msg, UInt32 wParam, UInt32 lParam);

		//
		// Function pointers for plugins
		//
		//Short description
		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		private delegate IntPtr dcplugin_description(IntPtr dcPlugin);

		//Long description
		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		private delegate IntPtr dcplugin_long_description(IntPtr dcPlugin);

		public ApplicationForm()
		{
			InitializeComponent();
			SendMessage(this.buttonInstall.Handle, BCM_SETSHIELD, 0, 1);

			//Fetch the NIC information once
			NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
			foreach (NetworkInterface adapter in adapters)
			{
				//Skip over adapters that aren't connected to a network
				if (adapter.OperationalStatus != OperationalStatus.Up)
				{
					continue;
				}

				IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
				List<string> dnsServers = new List<string>();	//More accurate than IPInterfaceProperties.DnsAddresses
				List<string> dnsServersv6 = new List<string>();

				//Determine if the DNS addresses are obtained automatically or specified
				//We don't want to add them when the program is closed if they weren't actually set
				//Unfortunately, neither WMI nor the NetworkInterface class provide information about this setting
				dnsServers = NetworkManager.getDNS(adapter.Id);
				dnsServersv6 = NetworkManager.getDNSv6(adapter.Id);

				NetworkListItem item = new NetworkListItem(adapter.Name, adapter.Description, dnsServers, dnsServersv6, adapter.Supports(NetworkInterfaceComponent.IPv4), adapter.Supports(NetworkInterfaceComponent.IPv6));
				NICitems.Add(adapter.Name, new Pair<NetworkListItem, bool>(item, false));
			}

			GetNICs(false);

			// Start thread to monitor process/service status
			this.ServiceCheck = new Thread(new ThreadStart(this.update_Service_Info));
			this.ServiceCheck.Start();

			LoadPlugins();

			this.combobox_provider.DataSource = Providers;
			this.combobox_provider.DisplayMember = "displayName";
			LoadConfig();
		}

		/// <summary>
		/// Searches for and lists available plugins in the \plugins directory
		/// </summary>
		private void LoadPlugins()
		{
			this.Plugins.Clear();
			this.pluginListBox.Items.Clear();

			string pluginDirectory = Directory.GetCurrentDirectory() + "\\plugins";
			if (Directory.Exists(pluginDirectory))
			{
				string[] fileEntries = Directory.GetFiles(pluginDirectory, "*.dll");
				foreach (string fileName in fileEntries)
				{
					IntPtr pDll = NativeMethods.LoadLibraryEx(fileName, IntPtr.Zero, 1 /*DONT_RESOLVE_DLL_REFERENCES*/);
					IntPtr descFunc = NativeMethods.GetProcAddress(pDll, "dcplugin_description");
					IntPtr longDescFunc = NativeMethods.GetProcAddress(pDll, "dcplugin_long_description");
					string short_description = "";
					string long_description = "";

					if (descFunc != IntPtr.Zero)
					{
						dcplugin_description dcplugin_description = (dcplugin_description)Marshal.GetDelegateForFunctionPointer(descFunc, typeof(dcplugin_description));

						IntPtr strPtr = dcplugin_description(IntPtr.Zero);
						short_description = Marshal.PtrToStringAnsi(strPtr);
					}

					if (longDescFunc != IntPtr.Zero)
					{
						dcplugin_long_description dcplugin_long_description = (dcplugin_long_description)Marshal.GetDelegateForFunctionPointer(longDescFunc, typeof(dcplugin_long_description));

						IntPtr strPtr = dcplugin_long_description(IntPtr.Zero);
						long_description = Marshal.PtrToStringAnsi(strPtr);
					}

					if (descFunc != IntPtr.Zero || longDescFunc != IntPtr.Zero)
					{
						this.Plugins.Add(new PluginListItem(Path.GetFileName(fileName), short_description, long_description));
						this.pluginListBox.Items.Add(Path.GetFileName(fileName));
					}
				}
			}
		}

		/// <summary>
		/// Reads the application settings file and populates the Provider list
		/// </summary>
		private void LoadConfig()
		{
			try
			{
				// Make sure the file exists before trying to read it
				if (!File.Exists(Directory.GetCurrentDirectory() + "\\dnscrypt-resolvers.csv"))
				{
					MessageBox.Show("dnscrypt-resolvers.csv was not found. It should be placed in the same directory as this program. If you do not have this file, you can find it in the download packages at http://download.dnscrypt.org/dnscrypt-proxy/", "File not found");
					return;
				}

				CSVReader reader = new CSVReader("dnscrypt-resolvers.csv", true);
				foreach (CSVRow CSVprovider in reader)
				{
					DNSCryptProvider provider = new DNSCryptProvider();
					provider.name = CSVprovider["Name"];
					provider.displayName = CSVprovider["Full name"];
					provider.description = CSVprovider["Description"];
					provider.location = CSVprovider["Location"];
					provider.server = CSVprovider["Resolver address"];
					provider.fqdn = CSVprovider["Provider name"];
					provider.key = CSVprovider["Provider public key"];

					this.Providers.Add(provider);
				}
			}
			catch (Exception err)
			{
				MessageBox.Show("There was an error parsing dnscrypt-resolvers.csv: " + err.ToString());
			}

			// Load the last used resolver
			string resolver = (string)Registry.GetValue(this.registryRoot, "ResolverName", "");
			int resolverIndex = -1;
			if (resolver != null && resolver.Length > 0)
			{
				resolverIndex = this.combobox_provider.FindString(resolver);
			}

			if (resolverIndex != -1)
			{
				populate_Config_Form(resolverIndex);
			}
			else
			{
				populate_Config_Form(0);
			}
		}

		/// <summary>
		/// Fills the ListBox with information about each NIC
		/// </summary>
		private void GetNICs(Boolean showHidden)
		{
			//this.ipv6Radio.Enabled = false;

			//NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
			foreach (KeyValuePair<String, Pair<NetworkListItem, bool>> adapterEntry in this.NICitems)
			{
				if (!adapterEntry.Value.First.hidden || showHidden)
				{
					int idx = DNSlistbox.Items.Add(adapterEntry.Value.First, adapterEntry.Value.Second);

					//See if the device supports IPv6 and enable the option if so
					if (adapterEntry.Value.First.IPv6)
					{
						//this.ipv6Radio.Enabled = true;
					}
				}
			}
		}

		/// <summary>
		/// This callback is triggered when a checkbox's state changes in the NIC list box
		/// When the box is checked, the target NIC's DNS settings are changed to 127.0.0.1
		/// When the box is unchecked, the settings are restored to their original value
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void DNSlisbox_itemcheck_statechanged(object sender, ItemCheckEventArgs e)
		{
			//Checking the "Show hidden adapters" box triggers this event, so ignore it
			if (((CheckedListBox)sender).SelectedIndex == -1)
			{
				return;
			}

			try
			{
				//Restore the user's old settings
				if (e.CurrentValue == CheckState.Checked)
				{
					if (((NetworkListItem)DNSlistbox.Items[e.Index]).IPv4)
					{
						NetworkManager.setDNS(((NetworkListItem)DNSlistbox.Items[e.Index]).NICDescription, ((NetworkListItem)DNSlistbox.Items[e.Index]).DNSservers);
					}

					//Since we don't set an IPv6 server, don't run this if they didn't have any to begin with
					if (((NetworkListItem)DNSlistbox.Items[e.Index]).DNSserversv6.Count > 0)
					{
						NetworkManager.setDNSv6(((NetworkListItem)DNSlistbox.Items[e.Index]).NICName, ((NetworkListItem)DNSlistbox.Items[e.Index]).DNSserversv6);
					}

					//Mark that the box was unchecked so we can restore the state if we have to rebuild the list to show hidden adapters
					this.NICitems[((NetworkListItem)DNSlistbox.Items[e.Index]).NICName].Second = false;
				}
				else //Set it to loopback for DNSCrypt
				{
					if (((NetworkListItem)DNSlistbox.Items[e.Index]).IPv4)
					{
						NetworkManager.setDNS(((NetworkListItem)DNSlistbox.Items[e.Index]).NICDescription, "127.0.0.1");
					}

					//Only do this if there were custom servers set to begin with
					if (((NetworkListItem)DNSlistbox.Items[e.Index]).DNSserversv6.Count > 0)
					{
						List<string> ip = new List<string>();
						//ip.Add("::1");
						NetworkManager.setDNSv6(((NetworkListItem)DNSlistbox.Items[e.Index]).NICName, ip);
					}

					//Mark that the box was checked so we can restore the state if we have to rebuild the list to show hidden adapters
					this.NICitems[((NetworkListItem)DNSlistbox.Items[e.Index]).NICName].Second = true;
				}
			}
			catch (Exception exception)
			{
				MessageBox.Show("Возникла ошибка при смене DNS сервера устрова:" + exception.Message);
			}
		}

		/// <summary>
		/// Button to start and stop the DNSCrypt Proxy application
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void startstop_button_Click(object sender, EventArgs e)
		{
			// Start the DNSCrypt process
			if (!this.CryptProcRunning)
			{
				if (this.CryptService == null)
				{
					// Make sure the file exists before trying to launch it
					if (!File.Exists(Directory.GetCurrentDirectory() + "\\dnscrypt-proxy.exe"))
					{
						MessageBox.Show("dnscrypt-proxy.exe не найден. Он должен располагаться в той же директории что эта программа.Если у вас нет этого файла, то вы можете скачать его по ссылке http://download.dnscrypt.org/dnscrypt-proxy/", "Файл не найден");
						return;
					}

					this.CryptProc = new ProcessStartInfo();
					this.CryptProc.FileName = "dnscrypt-proxy.exe";
					this.CryptProc.WindowStyle = ProcessWindowStyle.Minimized;
					this.CryptProc.Arguments += " --resolver-address=" + this.textbox_server_addr.Text;

					if (this.gatewayCheckbox.Checked)
					{
						this.CryptProc.Arguments += " --local-address=0.0.0.0";
					}

					this.CryptProc.Arguments += " --provider-key=" + this.textbox_key.Text;
					this.CryptProc.Arguments += " --provider-name=" + this.textbox_fqdn.Text;

					this.CryptHandle = Process.Start(this.CryptProc);
				}
				else
				{
					bool success = this.updateRegistry();
					if (!success)
					{
						return;
					}

					if (this.CryptService.Status != ServiceControllerStatus.Running && this.CryptService.Status != ServiceControllerStatus.StartPending)
					{
						this.CryptService.Start();
					}
				}

				this.startstop_button.Text = "Стоп";
				this.CryptProcRunning = true;

				//Don't allow plugin changes
				this.pluginListBox.Enabled = false;
				this.button_plugins_refresh.Enabled = false;
				this.textbox_plugin_params.Enabled = false;
			}
			else
			{
				if (this.CryptHandle != null)
				{
					// Make sure the proxy wasn't terminated by another application/user
					if (!this.CryptHandle.HasExited)
					{
						this.CryptHandle.Kill();
					}
				}
				else if (this.CryptService != null)
				{
					if (this.CryptService.Status != ServiceControllerStatus.Stopped && this.CryptService.Status != ServiceControllerStatus.StopPending)
					{
						this.CryptService.Stop();
					}
				}

				this.CryptProc = null;

				this.startstop_button.Text = "Старт";
				this.CryptProcRunning = false;

				//Allow plugin changes
				this.pluginListBox.Enabled = true;
				this.button_plugins_refresh.Enabled = true;
				this.textbox_plugin_params.Enabled = true;
			}
		}

		private bool updateRegistry()
		{

			try
			{
				Registry.SetValue(this.registryRoot, "Plugins", new string[] {}, RegistryValueKind.MultiString);
				Registry.SetValue(this.registryRoot, "LocalAddress", "127.0.0.1", RegistryValueKind.String);
				Registry.SetValue(this.registryRoot, "ProviderKey", this.textbox_key.Text, RegistryValueKind.String);
				Registry.SetValue(this.registryRoot, "ProviderName", this.textbox_fqdn.Text, RegistryValueKind.String);
				Registry.SetValue(this.registryRoot, "ResolverAddress", this.textbox_server_addr.Text, RegistryValueKind.String);
				Registry.SetValue(this.registryRoot, "ResolverName", this.Providers[this.combobox_provider.SelectedIndex].name, RegistryValueKind.String);
				Registry.SetValue(this.registryRoot, "ResolverList", Directory.GetCurrentDirectory() + "\\dnscrypt-resolvers.csv", RegistryValueKind.String);
			}
			catch (Exception e)
			{
				MessageBox.Show(e.Message);
				return false;
			}

			return true;
		}

		/// <summary>
		/// Called right before the form closes.
		/// Resets all DNS information back to their previous values and stops the DNSCrypt Proxy application
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void form_closing(object sender, FormClosingEventArgs e)
		{
			//Do not revert settings if installed as a service and it is running
			if (this.ServiceInstalled && this.CryptProcRunning)
			{
				return;
			}

			//Revert all of the DNS server settings
			foreach (NetworkListItem item in this.DNSlistbox.CheckedItems)
			{
				try
				{
					NetworkManager.setDNS(item.NICDescription, item.DNSservers);

					if (item.DNSserversv6.Count > 0)
					{
						NetworkManager.setDNSv6(item.NICName, item.DNSserversv6);
					}
				}
				catch (Exception exception)
				{
					MessageBox.Show("Возникла ошибка при получении ваших настрое для DNS: " + exception.Message);
				}
			}

			//Kill the DNSCrypt process if it's running
			if (this.CryptHandle != null && this.CryptProcRunning && !this.CryptHandle.HasExited && this.CryptService == null)
			{
				this.CryptHandle.Kill();
				this.CryptProc = null;

				this.startstop_button.Text = "Старт";
				this.CryptProcRunning = false;
			}

			this.ServiceCheck.Abort();
		}

		[DllImport("user32.dll")]
		static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

		/// <summary>
		/// The callback for double clicking the system tray icon
		/// Restores the main application window and shows the DNSCrypt Proxy application in a minimized state
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			this.Show();
			this.WindowState = FormWindowState.Normal;
			this.ShowInTaskbar = true;
			this.notifyIcon.Visible = false;

			if (this.CryptProcRunning)
			{
				ShowWindow(this.CryptHandle.MainWindowHandle, SW_SHOWMINIMIZED);
			}
		}

		/// <summary>
		/// The callback for clicking "Open" on the system tray
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void notifyIcon_Open(object sender, EventArgs e)
		{
			this.notifyIcon_MouseDoubleClick(sender, null);
		}

		/// <summary>
		/// Callback for when the window size is modified. Used to hijack the minimize action to place it in the system tray
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void form_resized(object sender, EventArgs e)
		{
			//The application only needs to be hidden away when the proxy is launched as a standalone process
			if (this.ServiceInstalled || !this.CryptProcRunning)
			{
				return;
			}

			if (WindowState == FormWindowState.Minimized)
			{
				this.Hide();
				this.ShowInTaskbar = false;
				this.notifyIcon.Visible = true;

				if (this.CryptProcRunning)
				{
					ShowWindow(this.CryptHandle.MainWindowHandle, SW_HIDE);
				}
			}
		}

		/// <summary>
		/// The callback for clicking "Exit" on the system tray
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void notifyIcon_Exit(object sender, EventArgs e)
		{
			this.Close();
		}

		/// <summary>
		/// Refreshes the NIC listing box with the hidden devices either shown or hidden
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void refreshNICList(object sender, EventArgs e)
		{
			this.DNSlistbox.Items.Clear();
			this.GetNICs(this.hideAdaptersCheckbox.Checked);
		}

		/// <summary>
		/// Shows a tooltip when hovered over the (Un)Install button
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void buttonInstall_MouseHover(object sender, EventArgs e)
		{
			if (this.ServiceInstalled)
			{
				this.serviceTooltip.Show("Удаление DNSCrypt как сервис Windows.", (Control)sender);
			}
			else
			{
				this.serviceTooltip.Show("Установка DNSCrypt как сервис Windows.", (Control)sender);
			}
		}

		/// <summary>
		/// (Un)Installs DNSCrypt as a Windows service
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void buttonInstall_Click(object sender, EventArgs e)
		{
			ProcessStartInfo proc = new ProcessStartInfo();
			proc.FileName = "dnscrypt-proxy.exe";
			proc.UseShellExecute = true;

			// Elevate process permissions on Vista and higher
			if (System.Environment.OSVersion.Version.Major >= 6)
			{
				proc.Verb = "runas";
			}

			if (this.ServiceInstalled)
			{
				proc.Arguments = "--uninstall";

				//Stop the service before uninstalling it
				ServiceController sc = new ServiceController("dnscrypt-proxy");
				try
				{
					if (sc.Status == ServiceControllerStatus.Running)
					{
						sc.Stop();
					}
				}
				catch (InvalidOperationException) { }
			}
			else
			{
				proc.Arguments = "--install";

				//Set up the keys that DNSCrypt wants
				if (!this.updateRegistry())
				{
					return;
				}

				proc.Arguments += " --resolver-name=\"" + this.Providers[this.combobox_provider.SelectedIndex].name + "\"";
				proc.Arguments += " --resolvers-list=\"" + Directory.GetCurrentDirectory() + "\\dnscrypt-resolvers.csv" + "\"";
			}

			try
			{
				Process p = Process.Start(proc);
				p.WaitForExit();
			}
			catch (Exception exc)
			{
				//User pressed Cancel during the elevation request
				//return;
				MessageBox.Show(exc.Message);
			}
		}

		/// <summary>
		/// Updates the buttons with new text. Cross thread function
		/// </summary>
		/// <param name="startstop"></param>
		/// <param name="install"></param>
		private void updateButtonTexts(string startstop, string install)
		{
			if (this.buttonInstall.InvokeRequired || this.startstop_button.InvokeRequired)
			{
				this.Invoke(
					new MethodInvoker(
						delegate()
						{
							updateButtonTexts(startstop, install);
						}
					)
				);
			}
			else
			{
				this.startstop_button.Text = startstop;
				this.buttonInstall.Text = install;
			}
		}

		/// <summary>
		/// Updates the buttons with that status of the service
		/// </summary>
		private void update_Service_Info()
		{
			while (true)
			{
				// Don't update the window until the window exists
				if (!IsHandleCreated)
				{
					Thread.Sleep(100);
					continue;
				}

				bool serviceExists = false;
				string startstopText = "";
				string installText = "";

				ServiceController sc = new ServiceController("dnscrypt-proxy");
				try
				{
					string ServiceName = sc.DisplayName;	//Just need to access some property to ensure it exists

					if (this.CryptService == null)
					{
						this.CryptService = new ServiceController("dnscrypt-proxy");
					}
					else
					{
						this.CryptService.Refresh();
					}

					serviceExists = true;
				}
				catch (InvalidOperationException)
				{
					this.CryptService = null;
				}

				if(serviceExists && sc != null)
				{
					this.ServiceInstalled = true;
					if (sc.Status == ServiceControllerStatus.Running)
					{
						this.CryptProcRunning = true;
						startstopText = "Стоп";
					}
					else
					{
						this.CryptProcRunning = false;
						startstopText = "Старт";
					}
					installText = "Удалить";
				}
				else
				{
					this.ServiceInstalled = false;
					installText = "Установить";

					//See if it's a standalone process running
					if (this.CryptHandle != null)
					{
						if (this.CryptHandle.HasExited)
						{
							this.CryptProcRunning = false;
							startstopText = "Старт";
						}
						else
						{
							this.CryptProcRunning = true;
							startstopText = "Стоп";
						}
					}
					else
					{
						this.CryptProcRunning = false;
						startstopText = "Старт";
					}
				}
				this.updateButtonTexts(startstopText, installText);

				sc.Dispose();
				Thread.Sleep(1000);
			}
		}

		/// <summary>
		/// Fires when the provider dropdown is changed
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void combobox_provider_SelectionChangeCommitted(object sender, EventArgs e)
		{
			int index = this.combobox_provider.SelectedIndex;
			populate_Config_Form(index);
		}

		/// <summary>
		/// Populates the config tab's fields with information about the selected provider
		/// </summary>
		/// <param name="index">Index into the provider array</param>
		private void populate_Config_Form(int index)
		{
			this.combobox_provider.SelectedIndex = index;

			this.textbox_server_addr.ReadOnly = false;
			this.textbox_server_addr.Text = "";
			this.textbox_fqdn.ReadOnly = false;
			this.textbox_fqdn.Text = "";
			this.textbox_key.ReadOnly = false;
			this.textbox_key.Text = "";

			this.textbox_server_addr.Text = this.Providers[index].server;
			this.textbox_server_addr.ReadOnly = true;

			this.textbox_fqdn.Text = this.Providers[index].fqdn;
			this.textbox_fqdn.ReadOnly = true;

			this.textbox_key.Text = this.Providers[index].key;
			this.textbox_key.ReadOnly = true;
		}

		/// <summary>
		/// Updates the description box with the selected plugin's long description
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void pluginListBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			string text = "";
			if (this.Plugins[this.pluginListBox.SelectedIndex].longDecription != "")
			{
				text = this.Plugins[this.pluginListBox.SelectedIndex].longDecription;
			}
			else
			{
				text = this.Plugins[this.pluginListBox.SelectedIndex].shortDescription;
			}

			this.pluginDescriptionTextBox.Text = text.Replace("\n", "\r\n");
			this.textbox_plugin_params.Text = this.Plugins[this.pluginListBox.SelectedIndex].parameters;
		}

		/// <summary>
		/// Save the plugin parameters to disk
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void textbox_plugin_params_Leave(object sender, EventArgs e)
		{
			this.Plugins[this.pluginListBox.SelectedIndex].parameters = this.textbox_plugin_params.Text;
		}

		private void pluginListBox_MouseMove(object sender, MouseEventArgs e)
		{
			int index = pluginListBox.IndexFromPoint(this.pluginListBox.PointToClient(MousePosition));
			if (index != this.LastPluginTooltipIndex && index < this.Plugins.Count && index >= 0)
			{
				tooltip_plugin.SetToolTip(this.pluginListBox, this.Plugins[index].shortDescription);
				this.LastPluginTooltipIndex = index;
			}
		}
	}

	/// <summary>
	/// Win32 API methods for loading DLLs and accessing their functions
	/// </summary>
	static class NativeMethods
	{
		[DllImport("kernel32.dll")]
		public static extern IntPtr LoadLibraryEx(string dllToLoad, IntPtr reserved, long flags);

		[DllImport("kernel32.dll")]
		public static extern bool FreeLibrary(IntPtr hModule);

		[DllImport("kernel32.dll")]
		public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
	}

	/// <summary>
	/// Custom list item entry for the DNS list box. Allows us to store information about the NIC device.
	/// </summary>
	public class NetworkListItem
	{
		public String NICName;
		public String NICDescription;
		public List<string> DNSservers;
		public List<string> DNSserversv6;
		public Boolean IPv4 = false;
		public Boolean IPv6 = false;
		public Boolean hidden = false;

		public NetworkListItem(String Name, String Description, List<string> IPs, List<string> IPsv6, Boolean IPv4, Boolean IPv6)
		{
			this.NICName = Name;
			this.NICDescription = Description;
			this.DNSservers = IPs;
			this.DNSserversv6 = IPsv6;
			this.IPv4 = IPv4;
			this.IPv6 = IPv6;

			if (this.shouldHide(Description))
			{
				this.hidden = true;
			}
		}

		public override string ToString()
		{
			String message = this.NICDescription;

			if (this.DNSservers.Count > 0 || this.DNSserversv6.Count > 0)
			{
				message += " - ";
			}

			message += String.Join(", ", DNSservers.ToArray());
			message += String.Join(", ", DNSserversv6.ToArray());

			return message;
		}

		/// <summary>
		/// Returns if a device should be flagged as hidden or not.
		/// Adapters such as Hamachi or virtual machines typically have their own settings
		/// which you should rarely ever need to change.
		/// </summary>
		/// <param name="Name">The name of the NIC</param>
		private Boolean shouldHide(String Description)
		{
			string[] blacklist = {
				"Microsoft Virtual",
				"Hamachi Network",
				"VMware Virtual",
				"VirtualBox",
				"Software Loopback",
				"Microsoft ISATAP",
				"Teredo Tunneling Pseudo-Interface"
			};

			foreach (string entry in blacklist)
			{
				if (Description.Contains(entry))
				{
					return true;
				}
			}

			return false;
		}
	}

	/// <summary>
	/// Custom list item entry for the plugin list box. Allows us to store information about each plugin.
	/// </summary>
	public class PluginListItem
	{
		public string name { get; set; }
		public string shortDescription = "";
		public string longDecription = "";
		public string parameters = "";

		public PluginListItem(string name, string shortDescription, string longDescription)
		{
			this.name = name;
			this.shortDescription = shortDescription;
			this.longDecription = longDescription;
		}

		//public override string ToString()
		//{
		//	return name + ": " + shortDescription;
		//}
	}

	/// <summary>
	/// Stores information about DNSCrypt providers
	/// </summary>
	public class DNSCryptProvider
	{
		public string name;
		public string displayName { get; set; }
		public string description;
		public string location;
		public string server;
		public string ipv6;
		public string parentalControls;
		public List<int> ports = new List<int>();
		public string protos;
		public string fqdn;
		public string key;

		public void setPorts(string portString)
		{
			string[] portStrings = portString.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string port in portStrings)
			{
				ports.Add(Int32.Parse(port));
			}
		}

	}

	/// <summary>
	/// A templated pair class since Tuples aren't available until .NET 4
	/// </summary>
	/// <typeparam name="T"></typeparam>
	/// <typeparam name="U"></typeparam>
	public class Pair<T, U>
	{
		public Pair()
		{
		}

		public Pair(T first, U second)
		{
			this.First = first;
			this.Second = second;
		}

		public T First { get; set; }
		public U Second { get; set; }
	};
}


text:
package org.apache.hcatalog.hbase.snapshot.lock;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

import static org.apache.zookeeper.CreateMode.EPHEMERAL_SEQUENTIAL;

import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * A protocol to implement an exclusive
 *  write lock or to elect a leader.
 You invoke {@link #lock()} to
 *  start the process of grabbing the lock; you may get the lock then or it may be
 *  some time later.
 You can register a listener so that you are invoked
 *  when you get the lock; otherwise you can ask if you have the lock
 *  by calling {@link #isOwner()}
 *  This class has been used as-is from the zookeeper 3.4.0 recipes. The only change
 *  made is a TODO for sorting using suffixes and the package name.
 */
public class WriteLock extends ProtocolSupport {
    private static final Logger LOG = LoggerFactory.getLogger(WriteLock.class);

    private final String dir;
    private String id;
    private ZNodeName idName;
    private String ownerId;
    private String lastChildId;
    private byte[] data = {0x12, 0x34};
    private LockListener callback;
    private LockZooKeeperOperation zop;

    /**
     * zookeeper contructor for writelock
     * @param zookeeper zookeeper client instance
     * @param dir the parent path you want to use for locking
     * @param acl the acls that you want to use for all the paths,
     * if null world read/write is used.
     */
    public WriteLock(ZooKeeper zookeeper, String dir, List<ACL> acl) {
        super(zookeeper);
        this.dir = dir;
        if (acl != null) {
            setAcl(acl);
        }
        this.zop = new LockZooKeeperOperation();
    }

    /**
     * zookeeper contructor for writelock with callback
     * @param zookeeper the zookeeper client instance
     * @param dir the parent path you want to use for locking
     * @param acl the acls that you want to use for all the paths
     * @param callback the call back instance
     */
    public WriteLock(ZooKeeper zookeeper, String dir, List<ACL> acl,
                     LockListener callback) {
        this(zookeeper, dir, acl);
        this.callback = callback;
    }

    /**
     * return the current locklistener
     * @return the locklistener
     */
    public LockListener getLockListener() {
        return this.callback;
    }

    /**
     * register a different call back listener
     * @param callback the call back instance
     */
    public void setLockListener(LockListener callback) {
        this.callback = callback;
    }

    /**
     * Removes the lock or associated znode if
     * you no longer require the lock. this also
     * removes your request in the queue for locking
     * in case you do not already hold the lock.
     * @throws RuntimeException throws a runtime exception
     * if it cannot connect to zookeeper.
     */
    public synchronized void unlock() throws RuntimeException {

        if (!isClosed() && id != null) {
            // we don't need to retry this operation in the case of failure
            // as ZK will remove ephemeral files and we don't wanna hang
            // this process when closing if we cannot reconnect to ZK
            try {

                ZooKeeperOperation zopdel = new ZooKeeperOperation() {
                    public boolean execute() throws KeeperException,
                        InterruptedException {
                        zookeeper.delete(id, -1);
                        return Boolean.TRUE;
                    }
                };
                zopdel.execute();
            } catch (InterruptedException e) {
                LOG.warn("Caught: " + e, e);
                //set that we have been interrupted.
                Thread.currentThread().interrupt();
            } catch (KeeperException.NoNodeException e) {
                // do nothing
            } catch (KeeperException e) {
                LOG.warn("Caught: " + e, e);
                throw (RuntimeException) new RuntimeException(e.getMessage()).
                    initCause(e);
            } finally {
                if (callback != null) {
                    callback.lockReleased();
                }
                id = null;
            }
        }
    }

    /**
     * the watcher called on
     * getting watch while watching
     * my predecessor
     */
    private class LockWatcher implements Watcher {
        public void process(WatchedEvent event) {
            // lets either become the leader or watch the new/updated node
            LOG.debug("Watcher fired on path: " + event.getPath() + " state: " +
                event.getState() + " type " + event.getType());
            try {
                lock();
            } catch (Exception e) {
                LOG.warn("Failed to acquire lock: " + e, e);
            }
        }
    }

    /**
     * a zoookeeper operation that is mainly responsible
     * for all the magic required for locking.
     */
    private class LockZooKeeperOperation implements ZooKeeperOperation {

        /** find if we have been created earler if not create our node
         *
         * @param prefix the prefix node
         * @param zookeeper teh zookeeper client
         * @param dir the dir paretn
         * @throws KeeperException
         * @throws InterruptedException
         */
        private void findPrefixInChildren(String prefix, ZooKeeper zookeeper, String dir)
            throws KeeperException, InterruptedException {
            List<String> names = zookeeper.getChildren(dir, false);
            for (String name : names) {
                if (name.startsWith(prefix)) {
                    id = name;
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Found id created last time: " + id);
                    }
                    break;
                }
            }
            if (id == null) {
                id = zookeeper.create(dir + "/" + prefix, data,
                    getAcl(), EPHEMERAL_SEQUENTIAL);

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Created id: " + id);
                }
            }

        }

        /**
         * the command that is run and retried for actually
         * obtaining the lock
         * @return if the command was successful or not
         */
        public boolean execute() throws KeeperException, InterruptedException {
            do {
                if (id == null) {
                    long sessionId = zookeeper.getSessionId();
                    String prefix = "x-" + sessionId + "-";
                    // lets try look up the current ID if we failed
                    // in the middle of creating the znode
                    findPrefixInChildren(prefix, zookeeper, dir);
                    idName = new ZNodeName(id);
                }
                if (id != null) {
                    List<String> names = zookeeper.getChildren(dir, false);
                    if (names.isEmpty()) {
                        LOG.warn("No children in: " + dir + " when we've just " +
                            "created one! Lets recreate it...");
                        // lets force the recreation of the id
                        id = null;
                    } else {
                        // lets sort them explicitly (though they do seem to come back in order ususally :)
                        SortedSet<ZNodeName> sortedNames = new TreeSet<ZNodeName>();
                        for (String name : names) {
                            //TODO: Just use the suffix to sort.
                            sortedNames.add(new ZNodeName(dir + "/" + name));
                        }
                        ownerId = sortedNames.first().getName();
                        SortedSet<ZNodeName> lessThanMe = sortedNames.headSet(idName);
                        if (!lessThanMe.isEmpty()) {
                            ZNodeName lastChildName = lessThanMe.last();
                            lastChildId = lastChildName.getName();
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("watching less than me node: " + lastChildId);
                            }
                            Stat stat = zookeeper.exists(lastChildId, new LockWatcher());
                            if (stat != null) {
                                return Boolean.FALSE;
                            } else {
                                LOG.warn("Could not find the" +
                                    " stats for less than me: " + lastChildName.getName());
                            }
                        } else {
                            if (isOwner()) {
                                if (callback != null) {
                                    callback.lockAcquired();
                                }
                                return Boolean.TRUE;
                            }
                        }
                    }
                }
            }
            while (id == null);
            return Boolean.FALSE;
        }
    }

    ;

    /**
     * Attempts to acquire the exclusive write lock returning whether or not it was
     * acquired. Note that the exclusive lock may be acquired some time later after
     * this method has been invoked due to the current lock owner going away.
     */
    public synchronized boolean lock() throws KeeperException, InterruptedException {
        if (isClosed()) {
            return false;
        }
        ensurePathExists(dir);

        return (Boolean) retryOperation(zop);
    }

    /**
     * return the parent dir for lock
     * @return the parent dir used for locks.
     */
    public String getDir() {
        return dir;
    }

    /**
     * Returns true if this node is the owner of the
     *  lock (or the leader)
     */
    public boolean isOwner() {
        return id != null && ownerId != null && id.equals(ownerId);
    }

    /**
     * return the id for this lock
     * @return the id for this lock
     */
    public String getId() {
        return this.id;
    }
}


text:
package org.jazzcommunity.development.library.file;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class FileResolver {
  private static final Logger logger = LoggerFactory.getLogger("FileResolver");

  private FileResolver() {}

  public static Stream<Path> findInDirectory(Path directory, String endsWith) {
    try {
      return Files.find(directory, 1, (p, b) -> p.getFileName().toString().endsWith(endsWith));
    } catch (IOException e) {
      if (logger.isDebugEnabled()) {
        e.printStackTrace();
      }
      logger.info(
          "File ending with '{}' in '{}' not found. Ignoring this entry.", directory, endsWith);
      return null;
    }
  }
}


text:
using System;
using Android.Content.PM;
using RebuyFormsRating.Common.Services;
using RebuyFormsRating.Droid;
using Xamarin.Forms;

[assembly: Dependency(typeof(InfoService))]
namespace RebuyFormsRating.Droid
{
    public class InfoService : IInfoService
    {
        public string AppVersionName {
            get {
                return getPackageManager().PackageName;
            }
        }

        public int AppBuildVersionCode {
            get {
                return getPackageManager().VersionCode;
            }
        }

        public string AppVersionCode {
            get {
                return getPackageManager().VersionName;
            }
        }

        private static PackageInfo getPackageManager()
        {
            var context = Forms.Context;
            return context.PackageManager.GetPackageInfo(context.PackageName, 0);
        }
    }
}


text:
require 'css_class_string/version'
require 'css_class_string/railtie' if defined?(Rails)


text:
from petsc4py import PETSc

from pySDC.core.Errors import DataError

class petsc_vec(PETSc.Vec):
    __array_priority__ = 1000  # otherwise rmul with float64 does not work (don't ask, won't tell)

    def __new__(cls, init=None, val=0.0):
        if isinstance(init, petsc_vec) or isinstance(init, PETSc.Vec):
            obj = PETSc.Vec().__new__(cls)
            init.copy(obj)
        elif isinstance(init, PETSc.DMDA):
            tmp = init.createGlobalVector()
            obj = petsc_vec(tmp)
            objarr = init.getVecArray(obj)
            objarr[:] = val
        else:
            obj = PETSc.Vec().__new__(cls)
        return obj

    def __abs__(self):
        """
        Overloading the abs operator

        Returns:
            float: absolute maximum of all vec values
        """
        # take absolute values of the mesh values (INF = 3)
        return self.norm(3)

    def isend(self, dest=None, tag=None, comm=None):
        """
        Routine for sending data forward in time (non-blocking)

        Args:
            dest (int): target rank
            tag (int): communication tag
            comm: communicator

        Returns:
            request handle
        """
        return comm.Issend(self.getArray(), dest=dest, tag=tag)

    def irecv(self, source=None, tag=None, comm=None):
        """
        Routine for receiving in time

        Args:
            source (int): source rank
            tag (int): communication tag
            comm: communicator

        Returns:
            None
        """
        return comm.Irecv(self.getArray(), source=source, tag=tag)

    def bcast(self, root=None, comm=None):
        """
        Routine for broadcasting values

        Args:
            root (int): process with value to broadcast
            comm: communicator

        Returns:
            broadcasted values
        """
        comm.Bcast(self.getArray(), root=root)
        return self

class petsc_vec_imex(object):
    """
    RHS data type for Vec with implicit and explicit components

    This data type can be used to have RHS with 2 components (here implicit and explicit)

    Attributes:
        impl (petsc_vec): implicit part
        expl (petsc_vec): explicit part
    """

    def __init__(self, init, val=0.0):
        """
        Initialization routine

        Args:
            init: can either be a tuple (one int per dimension) or a number (if only one dimension is requested)
                  or another imex_mesh object
            val (float): an initial number (default: 0.0)
        Raises:
            DataError: if init is none of the types above
        """

        if isinstance(init, type(self)):
            self.impl = petsc_vec(init.impl)
            self.expl = petsc_vec(init.expl)
        elif isinstance(init, PETSc.DMDA):
            self.impl = petsc_vec(init, val=val)
            self.expl = petsc_vec(init, val=val)
        # something is wrong, if none of the ones above hit
        else:
            raise DataError('something went wrong during %s initialization' % type(self))

class petsc_vec_comp2(object):
    """
    RHS data type for Vec with implicit and explicit components

    This data type can be used to have RHS with 2 components (here implicit and explicit)

    Attributes:
        impl (petsc_vec): implicit part
        expl (petsc_vec): explicit part
    """

    def __init__(self, init, val=0.0):
        """
        Initialization routine

        Args:
            init: can either be a tuple (one int per dimension) or a number (if only one dimension is requested)
                  or another imex_mesh object
            val (float): an initial number (default: 0.0)
        Raises:
            DataError: if init is none of the types above
        """

        if isinstance(init, type(self)):
            self.comp1 = petsc_vec(init.comp1)
            self.comp2 = petsc_vec(init.comp2)
        elif isinstance(init, PETSc.DMDA):
            self.comp1 = petsc_vec(init, val=val)
            self.comp2 = petsc_vec(init, val=val)
        # something is wrong, if none of the ones above hit
        else:
            raise DataError('something went wrong during %s initialization' % type(self))


text:
from __future__ import print_function

"""
Copyright (c) 2012, Cody Schafer <cpschafer --- gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
from sys import argv, exit, path as spath
from os.path import dirname

_us = dirname(__file__)
spath.insert(0, "{0}/../src".format(_us))
from fieldforce_tcm import *
spath.pop(0)

from event import *

def main():
	if len(argv) != 2:
		print('usage: {0} <pty>'.format(argv[0]))
		exit()

	ff = FieldforceTCM(argv[1], 38400)
	eq = EventQueue()

	PKT = 0
	def pkt_cb(rdy_pkts):
		for pkt in rdy_pkts:
			eq.post(Event(PKT, data=pkt))
	ff.add_listener(pkt_cb)

	ff_config = dict()

    def send_th():
        while True:
            pass

	while True:
		ev = eq.wait()
		if ev.type == PKT:
			frame = ev.data
			frame_id = frame[0]
			payload  = frame[1:len(frame)]
			id_name = FrameID.invert[frame_id]
			print ('recved {0} ({1})'.format(id_name, frame_id))
			if frame_id == FrameID.kSetParam:
				pkt = encode_command(FrameID.kSetParamDone)
				ff._send(pkt)
			elif frame_id == FrameID.kSetConfig:
				ff._send(encode_command(FrameID.kSetConfigDone))
				# TODO: record in ff_config
			elif frame_id == FrameID.kStartCal:
				pass
			elif frame_id == FrameID.kTakeUserCalSample:
				print('>>> taking a sample (I swear)')
			else:
				raise IOError('''Don't know how to handle frame_id {0} ({1})'''.format(id_name, frame_id))
		else:
			print ('eh?')

	print('done.')

if __name__ == '__main__':
	main()


text:
{{ blog.title }}

{{ blog.dateUpdated | date : 'medium' }} | {{ blog.readingTime.text }}

                {{ tag.tag }}

        <baasic-profile author-id="authorId"></baasic-profile>

                <button type="button" class="btn btn--secondary btn--med" ng-click="editBlog()">Edit</button>
                <button type="button" class="btn btn--tertiary btn--med spc--push--sml" ng-click="deleteBlog()">Delete</button>

        <button type="button" class="btn btn--primary btn--med" href="javascript:void(0);" ui-sref="master.main.index" rel="home">Back</button>

            <blog-comments article-id='blog.id' blog='blog' ng-if="!blog.hideComments"></blog-comments>

<baasic-blog-edit ng-show="isEdit" blog="blog" on-save="blogSaved()" on-cancel="cancelEdit()">
</baasic-blog-edit>


text:
use rand::{Rng, SeedableRng, StdRng};
use rand::distributions::range::SampleRange;
use num::traits::Float;
use std::f64;

use tensor::{Tensor, AxisIndex};
use traits::NumericTrait;
use math;

pub struct RandomState {
    rng: StdRng,
}

impl RandomState {
    /// Creates a new `RandomState` object with the given seed. The object needs to be captured
    /// as mutable in order to draw samples from it (since its internal state changes).
    pub fn new(seed: usize) -> RandomState {
        let ss: &[_] = &[seed];
        RandomState{rng: SeedableRng::from_seed(ss)}
    }

    /// Generates a tensor by independently drawing samples from a uniform distribution in the
    /// range [`low`, `high`). This is appropriate for integer types as well.
    pub fn uniform<T>(&mut self, low: T, high: T, shape: &[usize]) -> Tensor<T>
            where T: NumericTrait + SampleRange {
        let mut t = Tensor::zeros(shape);
        {
            let n = t.size();
            let mut data = t.slice_mut();
            for i in 0..n {
                data[i] = self.rng.gen_range::<T>(low, high);
            }
        }
        t
    }

    /// Generates a tensor by independently drawing samples from a standard normal.
    pub fn normal<T>(&mut self, shape: &[usize]) -> Tensor<T>
            where T: NumericTrait + SampleRange + Float {
        let u1 = self.uniform(T::zero(), T::one(), shape);
        let u2 = self.uniform(T::zero(), T::one(), shape);

        let minustwo = Tensor::fscalar(-2.0);
        let twopi = Tensor::fscalar(2.0 * f64::consts::PI);

        math::sqrt(math::ln(u1) * &minustwo) * &math::cos(u2 * &twopi)
    }

    /// Shuffle tensor in-place along its first axis. This uses the modern version of the
    /// Fisher-Yates algorithm.
    pub fn shuffle<T>(&mut self, a: &mut Tensor<T>) -> ()
            where T: Copy {
        if a.ndim() == 1 && a.size() > 0 {
            a.canonize_inplace();
            let n = a.dim(0);
            {
                let mut data = a.mem_slice_mut();
                for i in (1..n).rev() {
                    let j = self.rng.gen_range::<usize>(0, i + 1);
                    data.swap(i, j);
                }
            }
        } else if a.ndim() >= 2 && a.size() > 0 {
            a.canonize_inplace();
            let mut row_shape: Vec<usize> = Vec::with_capacity(a.ndim() - 1);
            for i in 1..a.ndim() {
                row_shape.push(a.shape()[i]);
            }
            let n = a.dim(0);
            let mut row1: Tensor<T> = Tensor::empty(&row_shape[..]);
            let mut row2: Tensor<T> = Tensor::empty(&row_shape[..]);
            for i in (1..n).rev() {
                let j: usize = self.rng.gen_range::<usize>(0, i + 1);
                // TODO: Can be made faster.
                // Rust requires us to have two buffers instead of just one, but
                // we can probably make it even faster by shuffling indices first
                // and then move memory around. A specialized swap rows function
                // could also make things faster.
                row1.set(&a.index(&[AxisIndex::Index(i as isize)]));
                row2.set(&a.index(&[AxisIndex::Index(j as isize)]));
                a.index_set(&[AxisIndex::Index(i as isize)], &row2);
                a.index_set(&[AxisIndex::Index(j as isize)], &row1);
            }
        }
    }
}


text:
@implementation JZ_Atomsphere
@synthesize sphereRadius;

- (void)initAtomsphere
{
    SCNMaterial *mat = [SCNMaterial material];
    self.geometry = [SCNSphere sphereWithRadius:sphereRadius];
    self.geometry.materials = [NSArray arrayWithObject:mat];
    mat.doubleSided = YES;

    SCNProgram *program = [SCNProgram program];
    NSURL *vertexShaderURL   = [[NSBundle mainBundle]
                                URLForResource:@"/PlanetShader" withExtension:@"vert"];
    NSURL *fragmentShaderURL = [[NSBundle mainBundle]
                                URLForResource:@"/PlanetShader" withExtension:@"frag"];
    NSString *vertexShader = [[NSString alloc] initWithContentsOfURL:vertexShaderURL
                                   encoding:NSUTF8StringEncoding
                                      error:NULL];
    NSString *fragmentShader = [[NSString alloc] initWithContentsOfURL:fragmentShaderURL
                                   encoding:NSUTF8StringEncoding
                                      error:NULL];

    program.vertexShader   = vertexShader;
    program.fragmentShader = fragmentShader;

    [program setSemantic:@"200.0" forSymbol:@"re" options:nil];
    [program setSemantic:@"200.0" forSymbol:@"rp" options:nil];
    [program setSemantic:@"14.0" forSymbol:@"planet_h" options:nil];
    [program setSemantic:@"4.0" forSymbol:@"view_depth" options:nil];

    mat.program = program;

}

//http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter16.html

@end


text:
package com.google.api.client.auth.oauth2;

import junit.framework.TestCase;

/**
 * Tests {@link ClientCredentialsTokenRequest}.
 *
 * @author Yaniv Inbar
 */
public class ClientCredentialsTokenRequestTest extends TestCase {

  public void testConstructor() {
    check(new ClientCredentialsTokenRequest(
        TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY,
        TokenRequestTest.AUTHORIZATION_SERVER_URL));
  }

  private void check(ClientCredentialsTokenRequest request) {
    TokenRequestTest.check(request, "client_credentials");
  }
}