text:
package org.apache.pulsar.broker.service.persistent;

import static org.apache.bookkeeper.mledger.util.SafeRun.safeRun;
import io.netty.util.concurrent.FastThreadLocal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.bookkeeper.mledger.Entry;
import org.apache.bookkeeper.mledger.ManagedCursor;
import org.apache.bookkeeper.mledger.Position;
import org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl;
import org.apache.bookkeeper.mledger.impl.PositionImpl;
import org.apache.pulsar.broker.ServiceConfiguration;
import org.apache.pulsar.broker.service.BrokerServiceException;
import org.apache.pulsar.broker.service.ConsistentHashingStickyKeyConsumerSelector;
import org.apache.pulsar.broker.service.Consumer;
import org.apache.pulsar.broker.service.EntryBatchIndexesAcks;
import org.apache.pulsar.broker.service.EntryBatchSizes;
import org.apache.pulsar.broker.service.HashRangeAutoSplitStickyKeyConsumerSelector;
import org.apache.pulsar.broker.service.HashRangeExclusiveStickyKeyConsumerSelector;
import org.apache.pulsar.broker.service.SendMessageInfo;
import org.apache.pulsar.broker.service.StickyKeyConsumerSelector;
import org.apache.pulsar.broker.service.Subscription;
import org.apache.pulsar.client.api.Range;
import org.apache.pulsar.common.api.proto.CommandSubscribe.SubType;
import org.apache.pulsar.common.api.proto.KeySharedMeta;
import org.apache.pulsar.common.api.proto.KeySharedMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PersistentStickyKeyDispatcherMultipleConsumers extends PersistentDispatcherMultipleConsumers {

    private final boolean allowOutOfOrderDelivery;
    private final StickyKeyConsumerSelector selector;

    private boolean isDispatcherStuckOnReplays = false;
    private final KeySharedMode keySharedMode;

    /**
     * When a consumer joins, it will be added to this map with the current read position.
     * This means that, in order to preserve ordering, new consumers can only receive old
     * messages, until the mark-delete position will move past this point.
     */
    private final LinkedHashMap<Consumer, PositionImpl> recentlyJoinedConsumers;

    private final Set<Consumer> stuckConsumers;
    private final Set<Consumer> nextStuckConsumers;

    PersistentStickyKeyDispatcherMultipleConsumers(PersistentTopic topic, ManagedCursor cursor,
            Subscription subscription, ServiceConfiguration conf, KeySharedMeta ksm) {
        super(topic, cursor, subscription, ksm.isAllowOutOfOrderDelivery());

        this.allowOutOfOrderDelivery = ksm.isAllowOutOfOrderDelivery();
        this.recentlyJoinedConsumers = allowOutOfOrderDelivery ? null : new LinkedHashMap<>();
        this.stuckConsumers = new HashSet<>();
        this.nextStuckConsumers = new HashSet<>();
        this.keySharedMode = ksm.getKeySharedMode();
        switch (this.keySharedMode) {
        case AUTO_SPLIT:
            if (conf.isSubscriptionKeySharedUseConsistentHashing()) {
                selector = new ConsistentHashingStickyKeyConsumerSelector(
                        conf.getSubscriptionKeySharedConsistentHashingReplicaPoints());
            } else {
                selector = new HashRangeAutoSplitStickyKeyConsumerSelector();
            }
            break;

        case STICKY:
            this.selector = new HashRangeExclusiveStickyKeyConsumerSelector();
            break;

        default:
            throw new IllegalArgumentException("Invalid key-shared mode: " + keySharedMode);
        }
    }

    @Override
    public synchronized void addConsumer(Consumer consumer) throws BrokerServiceException {
        super.addConsumer(consumer);
        try {
            selector.addConsumer(consumer);
        } catch (BrokerServiceException e) {
            consumerSet.removeAll(consumer);
            consumerList.remove(consumer);
            throw e;
        }

        PositionImpl readPositionWhenJoining = (PositionImpl) cursor.getReadPosition();
        consumer.setReadPositionWhenJoining(readPositionWhenJoining);
        // If this was the 1st consumer, or if all the messages are already acked, then we
        // don't need to do anything special
        if (!allowOutOfOrderDelivery
                && recentlyJoinedConsumers != null
                && consumerList.size() > 1
                && cursor.getNumberOfEntriesSinceFirstNotAckedMessage() > 1) {
            recentlyJoinedConsumers.put(consumer, readPositionWhenJoining);
        }
    }

    @Override
    public synchronized void removeConsumer(Consumer consumer) throws BrokerServiceException {
        // The consumer must be removed from the selector before calling the superclass removeConsumer method.
        // In the superclass removeConsumer method, the pending acks that the consumer has are added to
        // redeliveryMessages. If the consumer has not been removed from the selector at this point,
        // the broker will try to redeliver the messages to the consumer that has already been closed.
        // As a result, the messages are not redelivered to any consumer, and the mark-delete position does not move,
        // eventually causing all consumers to get stuck.
        selector.removeConsumer(consumer);
        super.removeConsumer(consumer);
        if (recentlyJoinedConsumers != null) {
            recentlyJoinedConsumers.remove(consumer);
            if (consumerList.size() == 1) {
                recentlyJoinedConsumers.clear();
            }
            if (removeConsumersFromRecentJoinedConsumers() || !redeliveryMessages.isEmpty()) {
                readMoreEntries();
            }
        }
    }

    private static final FastThreadLocal<Map<Consumer, List<Entry>>> localGroupedEntries =
            new FastThreadLocal<Map<Consumer, List<Entry>>>() {
                @Override
                protected Map<Consumer, List<Entry>> initialValue() throws Exception {
                    return new HashMap<>();
                }
            };

    @Override
    protected synchronized boolean trySendMessagesToConsumers(ReadType readType, List<Entry> entries) {
        long totalMessagesSent = 0;
        long totalBytesSent = 0;
        long totalEntries = 0;
        int entriesCount = entries.size();

        // Trigger read more messages
        if (entriesCount == 0) {
            return true;
        }

        if (consumerSet.isEmpty()) {
            entries.forEach(Entry::release);
            cursor.rewind();
            return false;
        }

        // A corner case that we have to retry a readMoreEntries in order to preserver order delivery.
        // This may happen when consumer closed. See issue #12885 for details.
        if (!allowOutOfOrderDelivery) {
            NavigableSet<PositionImpl> messagesToReplayNow = this.getMessagesToReplayNow(1);
            if (messagesToReplayNow != null && !messagesToReplayNow.isEmpty()) {
                PositionImpl replayPosition = messagesToReplayNow.first();

                // We have received a message potentially from the delayed tracker and, since we're not using it
                // right now, it needs to be added to the redelivery tracker or we won't attempt anymore to
                // resend it (until we disconnect consumer).
                redeliveryMessages.add(replayPosition.getLedgerId(), replayPosition.getEntryId());

                if (this.minReplayedPosition != null) {
                    // If relayPosition is a new entry wither smaller position is inserted for redelivery during this
                    // async read, it is possible that this relayPosition should dispatch to consumer first. So in
                    // order to preserver order delivery, we need to discard this read result, and try to trigger a
                    // replay read, that containing "relayPosition", by calling readMoreEntries.
                    if (replayPosition.compareTo(minReplayedPosition) < 0) {
                        if (log.isDebugEnabled()) {
                            log.debug("[{}] Position {} (<{}) is inserted for relay during current {} read, "
                                            + "discard this read and retry with readMoreEntries.",
                                    name, replayPosition, minReplayedPosition, readType);
                        }
                        if (readType == ReadType.Normal) {
                            entries.forEach(entry -> {
                                long stickyKeyHash = getStickyKeyHash(entry);
                                addMessageToReplay(entry.getLedgerId(), entry.getEntryId(), stickyKeyHash);
                                entry.release();
                            });
                        } else if (readType == ReadType.Replay) {
                            entries.forEach(Entry::release);
                        }
                        return true;
                    }
                }
            }
        }

        nextStuckConsumers.clear();

        final Map<Consumer, List<Entry>> groupedEntries = localGroupedEntries.get();
        groupedEntries.clear();
        final Map<Consumer, Set<Integer>> consumerStickyKeyHashesMap = new HashMap<>();

        for (Entry entry : entries) {
            int stickyKeyHash = getStickyKeyHash(entry);
            Consumer c = selector.select(stickyKeyHash);
            if (c != null) {
                groupedEntries.computeIfAbsent(c, k -> new ArrayList<>()).add(entry);
                consumerStickyKeyHashesMap.computeIfAbsent(c, k -> new HashSet<>()).add(stickyKeyHash);
            } else {
                addMessageToReplay(entry.getLedgerId(), entry.getEntryId(), stickyKeyHash);
                entry.release();
            }
        }

        AtomicInteger keyNumbers = new AtomicInteger(groupedEntries.size());

        int currentThreadKeyNumber = groupedEntries.size();
        if (currentThreadKeyNumber == 0) {
            currentThreadKeyNumber = -1;
        }
        for (Map.Entry<Consumer, List<Entry>> current : groupedEntries.entrySet()) {
            Consumer consumer = current.getKey();
            List<Entry> entriesWithSameKey = current.getValue();
            int entriesWithSameKeyCount = entriesWithSameKey.size();
            int availablePermits = consumer == null ? 0 : Math.max(consumer.getAvailablePermits(), 0);
            if (consumer != null && consumer.getMaxUnackedMessages() > 0) {
                int remainUnAckedMessages =
                        // Avoid negative number
                        Math.max(consumer.getMaxUnackedMessages() - consumer.getUnackedMessages(), 0);
                availablePermits = Math.min(availablePermits, remainUnAckedMessages);
            }
            int maxMessagesForC = Math.min(entriesWithSameKeyCount, availablePermits);
            int messagesForC = getRestrictedMaxEntriesForConsumer(consumer, entriesWithSameKey, maxMessagesForC,
                    readType, consumerStickyKeyHashesMap.get(consumer));
            if (log.isDebugEnabled()) {
                log.debug("[{}] select consumer {} with messages num {}, read type is {}",
                        name, consumer == null ? "null" : consumer.consumerName(), messagesForC, readType);
            }

            if (messagesForC < entriesWithSameKeyCount) {
                // We are not able to push all the messages with given key to its consumer,
                // so we discard for now and mark them for later redelivery
                for (int i = messagesForC; i < entriesWithSameKeyCount; i++) {
                    Entry entry = entriesWithSameKey.get(i);
                    long stickyKeyHash = getStickyKeyHash(entry);
                    addMessageToReplay(entry.getLedgerId(), entry.getEntryId(), stickyKeyHash);
                    entry.release();
                    entriesWithSameKey.set(i, null);
                }
            }

            if (messagesForC > 0) {
                // remove positions first from replay list first : sendMessages recycles entries
                if (readType == ReadType.Replay) {
                    for (int i = 0; i < messagesForC; i++) {
                        Entry entry = entriesWithSameKey.get(i);
                        redeliveryMessages.remove(entry.getLedgerId(), entry.getEntryId());
                    }
                }

                SendMessageInfo sendMessageInfo = SendMessageInfo.getThreadLocal();
                EntryBatchSizes batchSizes = EntryBatchSizes.get(messagesForC);
                EntryBatchIndexesAcks batchIndexesAcks = EntryBatchIndexesAcks.get(messagesForC);
                totalEntries += filterEntriesForConsumer(entriesWithSameKey, batchSizes, sendMessageInfo,
                        batchIndexesAcks, cursor, readType == ReadType.Replay, consumer);

                consumer.sendMessages(entriesWithSameKey, batchSizes, batchIndexesAcks,
                        sendMessageInfo.getTotalMessages(),
                        sendMessageInfo.getTotalBytes(), sendMessageInfo.getTotalChunkedMessages(),
                        getRedeliveryTracker()).addListener(future -> {
                    if (future.isDone() && keyNumbers.decrementAndGet() == 0) {
                        readMoreEntries();
                    }
                });

                TOTAL_AVAILABLE_PERMITS_UPDATER.getAndAdd(this,
                        -(sendMessageInfo.getTotalMessages() - batchIndexesAcks.getTotalAckedIndexCount()));
                totalMessagesSent += sendMessageInfo.getTotalMessages();
                totalBytesSent += sendMessageInfo.getTotalBytes();
            } else {
                currentThreadKeyNumber = keyNumbers.decrementAndGet();
            }
        }

        // acquire message-dispatch permits for already delivered messages
        acquirePermitsForDeliveredMessages(topic, cursor, totalEntries, totalMessagesSent, totalBytesSent);

        stuckConsumers.clear();

        if (totalMessagesSent == 0 && (recentlyJoinedConsumers == null || recentlyJoinedConsumers.isEmpty())) {
            // This means, that all the messages we've just read cannot be dispatched right now.
            // This condition can only happen when:
            //  1. We have consumers ready to accept messages (otherwise the would not haven been triggered)
            //  2. All keys in the current set of messages are routing to consumers that are currently busy
            //     and stuck is not caused by stuckConsumers
            //
            // The solution here is to move on and read next batch of messages which might hopefully contain
            // also keys meant for other consumers.
            //
            // We do it unless that are "recently joined consumers". In that case, we would be looking
            // ahead in the stream while the new consumers are not ready to accept the new messages,
            // therefore would be most likely only increase the distance between read-position and mark-delete
            // position.
            if (!nextStuckConsumers.isEmpty()) {
                isDispatcherStuckOnReplays = true;
                stuckConsumers.addAll(nextStuckConsumers);
            }
            // readMoreEntries should run regardless whether or not stuck is caused by
            // stuckConsumers for avoid stopping dispatch.
            sendInProgress = false;
            topic.getBrokerService().executor().execute(safeRun(this::readMoreEntries));
        }  else if (currentThreadKeyNumber == 0) {
            sendInProgress = false;
            topic.getBrokerService().executor().schedule(safeRun(() -> {
                synchronized (PersistentStickyKeyDispatcherMultipleConsumers.this) {
                    readMoreEntries();
                }
            }), 100, TimeUnit.MILLISECONDS);
        }
        return false;
    }

    private int getRestrictedMaxEntriesForConsumer(Consumer consumer, List<Entry> entries, int maxMessages,
            ReadType readType, Set<Integer> stickyKeyHashes) {
        if (maxMessages == 0) {
            // the consumer was stuck
            nextStuckConsumers.add(consumer);
            return 0;
        }
        if (readType == ReadType.Normal && stickyKeyHashes != null
                && redeliveryMessages.containsStickyKeyHashes(stickyKeyHashes)) {
            // If redeliveryMessages contains messages that correspond to the same hash as the messages
            // that the dispatcher is trying to send, do not send those messages for order guarantee
            return 0;
        }
        if (recentlyJoinedConsumers == null) {
            return maxMessages;
        }
        removeConsumersFromRecentJoinedConsumers();
        PositionImpl maxReadPosition = recentlyJoinedConsumers.get(consumer);
        // At this point, all the old messages were already consumed and this consumer
        // is now ready to receive any message
        if (maxReadPosition == null) {
            // stop to dispatch by stuckConsumers
            if (stuckConsumers.contains(consumer)) {
                if (log.isDebugEnabled()) {
                    log.debug("[{}] stop to dispatch by stuckConsumers, consumer: {}", name, consumer);
                }
                return 0;
            }
            // The consumer has not recently joined, so we can send all messages
            return maxMessages;
        }

        // If the read type is Replay, we should avoid send messages that hold by other consumer to the new consumers,
        // For example, we have 10 messages [0,1,2,3,4,5,6,7,8,9]
        // If the consumer0 get message 0 and 1, and does not acked message 0, then consumer1 joined,
        // when consumer1 get message 2,3, the broker will not dispatch messages to consumer1
        // because of the mark delete position did not move forward.
        // So message 2,3 will stored in the redeliver tracker.
        // Now, consumer2 joined, it will read new messages from the cursor,
        // so the recentJoinedPosition is 4 for consumer2
        // Because of there are messages need to redeliver, so the broker will read the redelivery message first [2,3]
        // message [2,3] is lower than the recentJoinedPosition 4,
        // so the message [2,3] will dispatched to the consumer2
        // But the message [2,3] should not dispatch to consumer2.

        if (readType == ReadType.Replay) {
            PositionImpl minReadPositionForRecentJoinedConsumer = recentlyJoinedConsumers.values().iterator().next();
            if (minReadPositionForRecentJoinedConsumer != null
                    && minReadPositionForRecentJoinedConsumer.compareTo(maxReadPosition) < 0) {
                maxReadPosition = minReadPositionForRecentJoinedConsumer;
            }
        }
        // Here, the consumer is one that has recently joined, so we can only send messages that were
        // published before it has joined.
        for (int i = 0; i < maxMessages; i++) {
            if (((PositionImpl) entries.get(i).getPosition()).compareTo(maxReadPosition) >= 0) {
                // We have already crossed the divider line. All messages in the list are now
                // newer than what we can currently dispatch to this consumer
                return i;
            }
        }

        return maxMessages;
    }

    @Override
    public void markDeletePositionMoveForward() {
        // Execute the notification in different thread to avoid a mutex chain here
        // from the delete operation that was completed
        topic.getBrokerService().getTopicOrderedExecutor().execute(safeRun(() -> {
            synchronized (PersistentStickyKeyDispatcherMultipleConsumers.this) {
                if (recentlyJoinedConsumers != null && !recentlyJoinedConsumers.isEmpty()
                        && removeConsumersFromRecentJoinedConsumers()) {
                    // After we process acks, we need to check whether the mark-delete position was advanced and we
                    // can finally read more messages. It's safe to call readMoreEntries() multiple times.
                    readMoreEntries();
                }
            }
        }));
    }

    private boolean removeConsumersFromRecentJoinedConsumers() {
        Iterator<Map.Entry<Consumer, PositionImpl>> itr = recentlyJoinedConsumers.entrySet().iterator();
        boolean hasConsumerRemovedFromTheRecentJoinedConsumers = false;
        PositionImpl mdp = (PositionImpl) cursor.getMarkDeletedPosition();
        if (mdp != null) {
            PositionImpl nextPositionOfTheMarkDeletePosition =
                    ((ManagedLedgerImpl) cursor.getManagedLedger()).getNextValidPosition(mdp);
            while (itr.hasNext()) {
                Map.Entry<Consumer, PositionImpl> entry = itr.next();
                if (entry.getValue().compareTo(nextPositionOfTheMarkDeletePosition) <= 0) {
                    itr.remove();
                    hasConsumerRemovedFromTheRecentJoinedConsumers = true;
                } else {
                    break;
                }
            }
        }
        return hasConsumerRemovedFromTheRecentJoinedConsumers;
    }

    @Override
    protected synchronized NavigableSet<PositionImpl> getMessagesToReplayNow(int maxMessagesToRead) {
        if (isDispatcherStuckOnReplays) {
            // If we're stuck on replay, we want to move forward reading on the topic (until the overall max-unacked
            // messages kicks in), instead of keep replaying the same old messages, since the consumer that these
            // messages are routing to might be busy at the moment
            this.isDispatcherStuckOnReplays = false;
            return Collections.emptyNavigableSet();
        } else {
            return super.getMessagesToReplayNow(maxMessagesToRead);
        }
    }

    @Override
    public SubType getType() {
        return SubType.Key_Shared;
    }

    @Override
    protected Set<? extends Position> asyncReplayEntries(Set<? extends Position> positions) {
        return cursor.asyncReplayEntries(positions, this, ReadType.Replay, true);
    }

    public KeySharedMode getKeySharedMode() {
        return this.keySharedMode;
    }

    public boolean isAllowOutOfOrderDelivery() {
        return this.allowOutOfOrderDelivery;
    }

    public boolean hasSameKeySharedPolicy(KeySharedMeta ksm) {
        return (ksm.getKeySharedMode() == this.keySharedMode
                && ksm.isAllowOutOfOrderDelivery() == this.allowOutOfOrderDelivery);
    }

    public LinkedHashMap<Consumer, PositionImpl> getRecentlyJoinedConsumers() {
        return recentlyJoinedConsumers;
    }

    public Map<Consumer, List<Range>> getConsumerKeyHashRanges() {
        return selector.getConsumerKeyHashRanges();
    }

    private static final Logger log = LoggerFactory.getLogger(PersistentStickyKeyDispatcherMultipleConsumers.class);

}


text:
package com.google.common.truth;

import javax.annotation.Nullable;

/**
 * Propositions for {@code long} subjects.
 *
 * @author David Saff
 * @author Christian Gruber (cgruber@israfil.net)
 * @author Kurt Alfred Kluever
 */
// Can't be final because we use codegen to generate a subclass
public class LongSubject extends ComparableSubject<LongSubject, Long> {
  public LongSubject(FailureStrategy failureStrategy, @Nullable Long subject) {
    super(failureStrategy, subject);
  }

  /**
   * @deprecated Use {@link #isEqualTo} instead. Long comparison is consistent with equality.
   */
  @Deprecated
  public final void isEquivalentAccordingToCompareTo(Long other) {
    super.isEquivalentAccordingToCompareTo(other);
  }

  public void isEqualTo(@Nullable Object other) {
    super.isEqualTo(other);
  }

  public void isNotEqualTo(@Nullable Object other) {
    super.isNotEqualTo(other);
  }

  public void isEqualTo(int other) {
    isEqualTo((long) other);
  }
}

redpajama_set_name: RedPajamaGithub


text:
package context

import (
	"context"
	"testing"
)

func TestSubscriptionKey(t *testing.T) {
	_, err := GetSubscriptionKey(context.Background())
	if err != ErrSubscriptionKeyNotPresent {
		t.Errorf("error from GetSubscriptionKey got=%v, want=%v", err, ErrSubscriptionKeyNotPresent)
	}

	wantKey := "key"
	ctx := WithSubscriptionKey(context.Background(), wantKey)
	gotKey, err := GetSubscriptionKey(ctx)
	if err != nil {
		t.Errorf("unexpected error from GetSubscriptionKey: %v", err)
	}
	if gotKey != wantKey {
		t.Errorf("topic key from context got=%s, want=%s", gotKey, wantKey)
	}
}


text:
package dagger.functional.membersinject;

class ChildOfPrimitiveIntArray extends MembersInjectGenericParent<int[]> {

}


text:
package js

import (
	"fmt"
	"sort"
	"strings"

	"github.com/robertkrimen/otto"
)

func iterOwnAndConstructorKeys(vm *otto.Otto, obj *otto.Object, f func(string)) {
	seen := make(map[string]bool)
	iterOwnKeys(vm, obj, func(prop string) {
		seen[prop] = true
		f(prop)
	})
	if cp := constructorPrototype(obj); cp != nil {
		iterOwnKeys(vm, cp, func(prop string) {
			if !seen[prop] {
				f(prop)
			}
		})
	}
}

func iterOwnKeys(vm *otto.Otto, obj *otto.Object, f func(string)) {
	Object, _ := vm.Object("Object")
	rv, _ := Object.Call("getOwnPropertyNames", obj.Value())
	gv, _ := rv.Export()
	switch gv := gv.(type) {
	case []interface{}:
		for _, v := range gv {
			f(v.(string))
		}
	case []string:
		for _, v := range gv {
			f(v)
		}
	default:
		panic(fmt.Errorf("Object.getOwnPropertyNames returned unexpected type %T", gv))
	}
}

func constructorPrototype(obj *otto.Object) *otto.Object {
	if v, _ := obj.Get("constructor"); v.Object() != nil {
		if v, _ = v.Object().Get("prototype"); v.Object() != nil {
			return v.Object()
		}
	}
	return nil
}

func getCompletions(vm *otto.Otto, line string) (results []string) {
	parts := strings.Split(line, ".")
	objRef := "this"
	prefix := line
	if len(parts) > 1 {
		objRef = strings.Join(parts[0:len(parts)-1], ".")
		prefix = parts[len(parts)-1]
	}

	obj, _ := vm.Object(objRef)
	if obj == nil {
		return nil
	}
	iterOwnAndConstructorKeys(vm, obj, func(k string) {
		if strings.HasPrefix(k, prefix) {
			if objRef == "this" {
				results = append(results, k)
			} else {
				results = append(results, strings.Join(parts[:len(parts)-1], ".")+"."+k)
			}
		}
	})

	// Append opening parenthesis (for functions) or dot (for objects)
	// if the line itRuntime is the only completion.
	if len(results) == 1 && results[0] == line {
		obj, _ := vm.Object(line)
		if obj != nil {
			if obj.Class() == "Function" {
				results[0] += "("
			} else {
				results[0] += "."
			}
		}
	}

	sort.Strings(results)
	return results
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/music#tabernacle-choir-navoo-temple-dedication-441467" xml:lang="eng" locale="eng" status="publish" xmlns:its="http://www.w3.org/2005/11/its">
  <search-meta>
      <uri-title its:translate="no">tabernacle-choir-navoo-temple-dedication-441467</uri-title>
      <source>tabernacle-choir-navoo-temple-dedication-441467</source>
      <publication-type its:translate="no">image</publication-type>
      <media-type its:translate="no">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-07-03">2012-07-03</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no">global-search</collection>
          <collection its:translate="no">media</collection>
          <collection its:translate="no">images</collection>
      </collections>
      <subjects>
          <subject>mormon tabernacle choir</subject>
          <subject>choirs</subject>
          <subject>chorus</subject>
          <subject>concerts</subject>
          <subject>performances</subject>
          <subject>performers</subject>
          <subject>singers</subject>
          <subject>songs</subject>
          <subject>singing</subject>
          <subject>nauvoo temple dedication</subject>
          <subject>men</subject>
          <subject>women</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/music/tabernacle-choir-navoo-temple-dedication-441467-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/music/tabernacle-choir-navoo-temple-dedication-441467-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>140 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/music/tabernacle-choir-navoo-temple-dedication-441467-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>156 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/music/tabernacle-choir-navoo-temple-dedication-441467-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>327 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/music/tabernacle-choir-navoo-temple-dedication-441467-print.jpg</path>
              </download-url>
              <download-url>
                  Wallpaper
                  <size>665 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/music/tabernacle-choir-navoo-temple-dedication-441467-wallpaper.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
</ldswebml>


text:
package org.springframework.xd.demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.core.PollableChannel;
import org.springframework.integration.message.GenericMessage;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.xd.demo.gemfire.TweetSummary;
/**
 * @author David Turanski
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class TweetStreamTests {
	@Autowired
	PollableChannel output;
	@Autowired
	MessageChannel input;

	@Test
	@Ignore
	public void test() throws InterruptedException, IOException {
		File file = new File("../../data/twitter.out");

		BufferedReader reader = new BufferedReader(new FileReader(file));

		String tweet = null;
		int num = 0;
		while ((tweet = reader.readLine())!=null && num < 10){
			input.send(new GenericMessage<String>(tweet));
			Message<?> msg;
			while ((msg = output.receive(1000) )!= null) {
				TweetSummary summary = (TweetSummary)msg.getPayload();
				if (summary.getHashTags().size() > 0) {
					num++;
					System.out.println(summary.getHashTags());
				}
			}
		}
		reader.close();

	}
}


text:
import {InvalidArgumentsException} from '../exception/invalid_arguments_exception';
import {SecurityException} from '../exception/security_exception';
const SUPPORTED_AES_KEY_SIZES: number[] = [16, 32];

/**
 * Validates AES key sizes, at the moment only 128-bit and 256-bit keys are
 * supported.
 *
 * @param n the key size in bytes
 * @throws {!InvalidArgumentsException}
 * @static
 */
export function validateAesKeySize(n: number) {
  if (!SUPPORTED_AES_KEY_SIZES.includes(n)) {
    throw new InvalidArgumentsException('unsupported AES key size: ' + n);
  }
}

/**
 * Validates that the input is a non null Uint8Array.
 *
 * @throws {!InvalidArgumentsException}
 * @static
 */
export function requireUint8Array(input: Uint8Array) {
  if (input == null || !(input instanceof Uint8Array)) {
    throw new InvalidArgumentsException('input must be a non null Uint8Array');
  }
}

/**
 * Validates version, throws exception if candidate version is negative or
 * bigger than expected.
 *
 * @param candidate - version to be validated
 * @param maxVersion - upper bound on version
 * @throws {!SecurityException}
 * @static
 */
export function validateVersion(candidate: number, maxVersion: number) {
  if (candidate < 0 || candidate > maxVersion) {
    throw new SecurityException(
        'Version is out of bound, must be ' +
        'between 0 and ' + maxVersion + '.');
  }
}

/**
 * Validates ECDSA parameters.
 *
 * @throws {!SecurityException}
 */
export function validateEcdsaParams(curve: string, hash: string) {
  switch (curve) {
    case 'P-256':
      if (hash != 'SHA-256') {
        throw new SecurityException(
            'expected SHA-256 (because curve is P-256) but got ' + hash);
      }
      break;
    case 'P-384':
      if (hash != 'SHA-384' && hash != 'SHA-512') {
        throw new SecurityException(
            'expected SHA-384 or SHA-512 (because curve is P-384) but got ' +
            hash);
      }
      break;
    case 'P-521':
      if (hash != 'SHA-512') {
        throw new SecurityException(
            'expected SHA-512 (because curve is P-521) but got ' + hash);
      }
      break;
    default:
      throw new SecurityException('unsupported curve: ' + curve);
  }
}


text:
package tst

import (
	"reflect"
	"testing"

	"github.com/Shopify/go-lua"

	luatesting "github.com/Shopify/goluago/pkg/testing"
)

func RunLuaTests(t *testing.T, libraryCallback func(l *lua.State), filename string) {
	requireCallback := func(l *lua.State) {
		l.Register("istrue", isTrue(t))
		l.Register("isfalse", isFalse(t))
		l.Register("equals", isEqual(t))
		l.Register("notequals", isNotEqual(t))
		libraryCallback(l)
	}
	luatesting.RunLuaTestFile(t, requireCallback, filename)
}

func isTrue(t *testing.T) lua.Function {
	return func(l *lua.State) int {
		name := lua.CheckString(l, 1)
		cond := l.ToBoolean(2)

		if !cond {
			t.Errorf("%s: condition should be true", name)
		}

		return 0
	}
}

func isFalse(t *testing.T) lua.Function {
	return func(l *lua.State) int {
		name := lua.CheckString(l, 1)
		cond := l.ToBoolean(2)

		if cond {
			t.Errorf("%s: condition should be false", name)
		}

		return 0
	}
}

func isEqual(t *testing.T) lua.Function {
	return func(l *lua.State) int {
		name := lua.CheckString(l, 1)
		want := l.ToValue(2)
		got := l.ToValue(3)

		if !reflect.DeepEqual(want, got) {
			t.Errorf("%s: want `%#v`, got `%#v`", name, want, got)
		}

		return 0
	}
}

func isNotEqual(t *testing.T) lua.Function {
	return func(l *lua.State) int {
		name := lua.CheckString(l, 1)
		want := l.ToValue(2)
		got := l.ToValue(3)

		if reflect.DeepEqual(want, got) {
			t.Errorf("%s: dont want `%#v` but got it", name, want)
		}

		return 0
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

		<!-- The version that makes use of the Sakai repository to store content, but serves it through the tool -->
	<bean id="org.sakaiproject.scorm.service.api.ScormResourceService"
		class="org.sakaiproject.scorm.service.sakai.impl.SakaiResourceService"
		init-method="init"
		singleton="true">

		<lookup-method name="configurationService" bean="org.sakaiproject.component.api.ServerConfigurationService" />
		<lookup-method name="contentService" bean="org.sakaiproject.content.api.ContentHostingService" />
		<lookup-method name="toolManager" bean="org.sakaiproject.tool.api.ToolManager" />
		<lookup-method name="siteService" bean="org.sakaiproject.site.api.SiteService" />
		<lookup-method name="securityService" bean="org.sakaiproject.authz.api.SecurityService" />
	</bean>

	<bean id="org.sakaiproject.scorm.dao.api.SeqActivityTreeDao"
		class="org.sakaiproject.scorm.dao.standalone.StandaloneActivityTreeDaoImpl"
		singleton="true">

	</bean>

</beans>


text:
#region License
// The MIT License (MIT)
// Copyright (c) 2015 João Simões
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace SimplePersistence.UoW.Aspects
{
    /// <summary>
    /// The transaction type to be used
    /// </summary>
    public enum TransactionType
    {
        /// <summary>
        /// Create a new transaction or use an existing one
        /// </summary>
        Required,
        /// <summary>
        /// Always create a new transaction
        /// </summary>
        RequiresNew,
        /// <summary>
        /// Does not open a new transaction but uses an existing one if available
        /// </summary>
        NotRequired
    }
}


text:
lib = File.expand_path('../../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)

require 'sunat'
require './config'

# Group 1
receipt_data = {id: "BC01-3652", customer: {dni: "00078647", legal_name: "Soledad Asuncion Carrasco Perez"},
                lines: [{id: "1", unit: "NIU", quantity: 1, item: {id: "REF564", description: "Refrigeradora marca \"AXM\" no frost de 200 ltrs"}, pricing_reference: 99800,
                          tax_totals: [{amount: 15224, type: :igv, code: "10"}], price: 84576, line_extension_amount: 84576},
                       {id: "2", unit: "NIU", quantity: 1, item: {id: "COC124", description: "Cocina a gas GLP, marca \"AXM\" de 5 hornillas"}, pricing_reference: 75000,
                          tax_totals: [{amount: 11441, type: :igv, code: "10"}], price: 63559, line_extension_amount: 63559},
                       {id: "3", unit: "NIU", quantity: 10, item: {id: "NOB012", description: "Sixpack de gaseosa \"Guaraná\" de 400 ml"}, pricing_reference: {amount: 480, free: true},
                          tax_totals: [{amount: 0, type: :igv, code: "31"}], price: 0, line_extension_amount: 0}],
                legal_monetary_total: 166060, additional_monetary_totals: [{id: "1001", payable_amount: 140729}, {id: "1004", payable_amount: 4800}, {id: "2005", payable_amount: 7407}],
                tax_totals: [{type: :igv, amount: 25331}], additional_properties: [{id: "1000", value: "SON MIL SEISCIENTOS SESENTA Y 60/100"}]
                }

receipt = SUNAT::Receipt.new(receipt_data)

if receipt.valid?
  File::open("receipt.xml", "w") { |file| file.write(receipt.to_xml) }
  receipt.to_pdf
else
  puts "Invalid document, ignoring output: #{receipt.errors.messages}"
end

doc = SUNAT::Receipt.new

doc.add_line do |line|

  line.price = SUNAT::PaymentAmount.new(3000)

  line.quantity = SUNAT::Quantity.new
  line.quantity.quantity = 250
  line.quantity.unit_code = "NIU"
  line.line_extension_amount = SUNAT::PaymentAmount.new(4000)

  line.pricing_reference = SUNAT::PricingReference.new
  line.pricing_reference.alternative_condition_price = SUNAT::AlternativeConditionPrice.new
  line.pricing_reference.alternative_condition_price.price_amount = SUNAT::PaymentAmount.new(3000)

  line.item = SUNAT::Item.new
  line.item.description = "Cabify Journey In Rolls Royce"
  line.item.id = "ROLLS2014"

  line.add_tax_total(:igv, 3000)
  line.add_tax_total(:isc, 5000)

end

doc.legal_monetary_total = SUNAT::PaymentAmount.new(5000)

doc.id = "B001-564"


text:
import json
import numpy as np
import codecs
from sklearn.svm import SVR
import gensim.utils as utils
from gensim.models import Word2Vec
import statsmodels.api as sm
from .word2vecbinreader import Word2VecBinReader
from sklearn.linear_model import Ridge
from . import gls_correction_matrix
import scipy.spatial.distance as distance
import gc
import scipy.optimize as opt
from sklearn.decomposition import PCA
from scipy.linalg import toeplitz
from . import yandex_translate

ruskaz = {}
kazrus = {}
# with codecs.open('E:\\NlpData\\en_ru_kaz-dictionary.json','r',encoding='utf8') as file:
#     data = json.load(file)
#     for t in data["Translations"]:
#         indexrus = str(t["Rus"])
#         indexkaz = str(t["Kaz"])
#         rusword = data["Words"][indexrus]["Text"].lower();
#         kazword = data["Words"][indexkaz]["Text"].lower();
#         if rusword not in ruskaz:
#             ruskaz[rusword] = []
#         elif kazword not in ruskaz[rusword]:
#             ruskaz[rusword].append(kazword)
#         if kazword not in kazrus:
#             kazrus[kazword] = []
#         elif rusword not in kazrus[kazword]:
#             kazrus[kazword].append(rusword)
w = Word2Vec()

w.load_word2vec_format()
w.save_word2vec_format()
ruskaz = yandex_translate.readvocub('E:\\NlpData\\rus_kfu_news_vocub_translations.txt')
kazrus = yandex_translate.readvocub('E:\\NlpData\\kazakh_news_vocub_translations.txt')
print(len(ruskaz))
# print len(kazrus)
rusvecreader = Word2VecBinReader()
rusvecreader.readvec('E:\\NlpData\\rus_dataset2_size(200).bin')
kazvecreader = Word2VecBinReader()
kazvecreader.readvec('E:\\NlpData\\kaz_dataset_size(200).bin')
print('rus vectors', len(rusvecreader.word_idx_map))
print('kaz vectors', len(kazvecreader.word_idx_map))
rusmatrix = []
kazmatrix = []
cur = 0
size = len(rusvecreader.word_idx_map)
for wru in rusvecreader.word_idx_map:
    # if cur % 10000 == 0:
    #     print '\r%d from %d'%(cur,size)
    cur += 1
    if wru in ruskaz:
        trans = ruskaz[wru]
        added = False
        for wkaz in trans:
            if added:
                break
            if wkaz in kazvecreader.word_idx_map:
                added = True
                wruindex = rusvecreader.word_idx_map[wru]
                wkazindex = kazvecreader.word_idx_map[wkaz]
                rusmatrix.append(rusvecreader.W[wruindex])
                kazmatrix.append(kazvecreader.W[wkazindex])
    # elif wru in kazvecreader.word_idx_map:
    #     wruindex = rusvecreader.word_idx_map[wru]
    #     wkazindex = kazvecreader.word_idx_map[wru]
    #     rusmatrix.append(rusvecreader.W[wruindex])
    #     kazmatrix.append(kazvecreader.W[wkazindex])
ruskaz = None
kazrus = None
gc.collect()
# print 'correlation', \
#     np.corrcoef(rusmatrix,kazmatrix)
rusmatrix = np.array(rusmatrix)
kazmatrix = np.array(kazmatrix)
print('len of matricies', len(rusmatrix), len(kazmatrix))

# m = []
# for i in xrange(kazmatrix.shape[1]):
#     print i
#     clf = SVR(C=1.0, epsilon=0.2)
#     clf.fit(rusmatrix, kazmatrix[:,i])
#     m.append(clf.coef0)
#
# A = np.array(m)
# m = None
r = Ridge()
r.predict()
X.dot( r.coef_.T,
                dense_output=True) + self.intercept_
A, resids, rank, st = np.linalg.lstsq(rusmatrix, kazmatrix)
# print A.shape
# A = gls_correction_matrix.GLSAR(rusmatrix,kazmatrix)
# opt.leastsq()
d,l = gls_correction_matrix.test(A,rusmatrix,kazmatrix)
# newr = np.array(rusmatrix[d > 0.4])
# newk = np.array(kazmatrix[d > 0.4])
# print len(newr)
# A, resids, rank, st = np.linalg.lstsq(newr,newk)
# d,l = gls_correction_matrix.test(A,newr,newk)
w = Word2Vec()
final_rus_matrix = np.dot(rusvecreader.W,A)
with utils.smart_open('rus_kaz_200.bin', 'wb')as fout:
    fout.write(utils.to_utf8("%s %s\n" % (rusvecreader.W.shape[0]+kazvecreader.W.shape[0],200)))
    for i in range(len(rusvecreader.vocub)):
        word = 'rus__'+rusvecreader.vocub[i]
        row = final_rus_matrix[i]
        fout.write(utils.to_utf8(word) + b" " + row.tostring())
    print('end rus')
    for i in range(len(kazvecreader.vocub)):
        word = 'kaz__'+kazvecreader.vocub[i]
        row = kazvecreader.W[i]
        fout.write(utils.to_utf8(word) + b" " + row.tostring())
    print('end kaz')


text:
//
// This file demonstrates how to initialize EGL in a Windows Store app, using ICoreWindow.
//

#include "app.h"

#include "main/main.h"
#include "core/os/dir_access.h"
#include "core/os/file_access.h"

using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::UI::Core;
using namespace Windows::UI::Input;
using namespace Windows::Foundation;
using namespace Windows::Graphics::Display;
using namespace Microsoft::WRL;
using namespace Platform;

using namespace $ext_safeprojectname$;

// Helper to convert a length in device-independent pixels (DIPs) to a length in physical pixels.
inline float ConvertDipsToPixels(float dips, float dpi)
{
    static const float dipsPerInch = 96.0f;
    return floor(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
}

// Implementation of the IFrameworkViewSource interface, necessary to run our app.
ref class HelloTriangleApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
{
public:
    virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView()
    {
        return ref new App();
    }
};

// The main function creates an IFrameworkViewSource for our app, and runs the app.
[Platform::MTAThread]
int main(Platform::Array<Platform::String^>^)
{
    auto helloTriangleApplicationSource = ref new HelloTriangleApplicationSource();
    CoreApplication::Run(helloTriangleApplicationSource);
    return 0;
}

App::App() :
    mWindowClosed(false),
    mWindowVisible(true),
    mWindowWidth(0),
    mWindowHeight(0),
    mEglDisplay(EGL_NO_DISPLAY),
    mEglContext(EGL_NO_CONTEXT),
    mEglSurface(EGL_NO_SURFACE)
{
}

// The first method called when the IFrameworkView is being created.
void App::Initialize(CoreApplicationView^ applicationView)
{
    // Register event handlers for app lifecycle. This example includes Activated, so that we
    // can make the CoreWindow active and start rendering on the window.
    applicationView->Activated +=
        ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &App::OnActivated);

    // Logic for other event handlers could go here.
    // Information about the Suspending and Resuming event handlers can be found here:
    // http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh994930.aspx

	os = new OSWinrt;
}

// Called when the CoreWindow object is created (or re-created).
void App::SetWindow(CoreWindow^ p_window)
{
	window = p_window;
    window->VisibilityChanged +=
        ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &App::OnVisibilityChanged);

    window->Closed +=
        ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &App::OnWindowClosed);

    window->SizeChanged +=
        ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &App::OnWindowSizeChanged);

#if !(WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
    // Disable all pointer visual feedback for better performance when touching.
    // This is not supported on Windows Phone applications.
    auto pointerVisualizationSettings = PointerVisualizationSettings::GetForCurrentView();
    pointerVisualizationSettings->IsContactFeedbackEnabled = false;
    pointerVisualizationSettings->IsBarrelButtonFeedbackEnabled = false;
#endif

	window->PointerPressed +=
		ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &App::OnPointerPressed);

	window->PointerMoved +=
		ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &App::OnPointerMoved);

	window->PointerReleased +=
		ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &App::OnPointerReleased);

	//window->PointerWheelChanged +=
	//	ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &App::OnPointerWheelChanged);

	char* args[] = {"-path", "game", NULL};
	Main::setup("winrt", 2, args, false);

	// The CoreWindow has been created, so EGL can be initialized.
	ContextEGL* context = memnew(ContextEGL(window));
	os->set_gl_context(context);
	UpdateWindowSize(Size(window->Bounds.Width, window->Bounds.Height));

	Main::setup2();
}

static int _get_button(Windows::UI::Input::PointerPoint ^pt) {

	using namespace Windows::UI::Input;

#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
	return BUTTON_LEFT;
#else
	switch (pt->Properties->PointerUpdateKind)
	{
		case PointerUpdateKind::LeftButtonPressed:
		case PointerUpdateKind::LeftButtonReleased:
			return BUTTON_LEFT;

		case PointerUpdateKind::RightButtonPressed:
		case PointerUpdateKind::RightButtonReleased:
			return BUTTON_RIGHT;

		case PointerUpdateKind::MiddleButtonPressed:
		case PointerUpdateKind::MiddleButtonReleased:
			return BUTTON_MIDDLE;

		case PointerUpdateKind::XButton1Pressed:
		case PointerUpdateKind::XButton1Released:
			return BUTTON_WHEEL_UP;

		case PointerUpdateKind::XButton2Pressed:
		case PointerUpdateKind::XButton2Released:
			return BUTTON_WHEEL_DOWN;

		default:
			break;
	}
#endif

	return 0;
};

static bool _is_touch(Windows::UI::Input::PointerPoint ^pointerPoint) {
#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
	return true;
#else
	using namespace Windows::Devices::Input;
	switch (pointerPoint->PointerDevice->PointerDeviceType) {
		case PointerDeviceType::Touch:
		case PointerDeviceType::Pen:
			return true;
		default:
			return false;
	}
#endif
}

static Windows::Foundation::Point _get_pixel_position(CoreWindow^ window, Windows::Foundation::Point rawPosition, OS* os) {

	Windows::Foundation::Point outputPosition;

	// Compute coordinates normalized from 0..1.
	// If the coordinates need to be sized to the SDL window,
	// we'll do that after.
	#if 1 || WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
	outputPosition.X = rawPosition.X / window->Bounds.Width;
	outputPosition.Y = rawPosition.Y / window->Bounds.Height;
	#else
	switch (DisplayProperties::CurrentOrientation)
	{
		case DisplayOrientations::Portrait:
			outputPosition.X = rawPosition.X / window->Bounds.Width;
			outputPosition.Y = rawPosition.Y / window->Bounds.Height;
			break;
		case DisplayOrientations::PortraitFlipped:
			outputPosition.X = 1.0f - (rawPosition.X / window->Bounds.Width);
			outputPosition.Y = 1.0f - (rawPosition.Y / window->Bounds.Height);
			break;
		case DisplayOrientations::Landscape:
			outputPosition.X = rawPosition.Y / window->Bounds.Height;
			outputPosition.Y = 1.0f - (rawPosition.X / window->Bounds.Width);
			break;
		case DisplayOrientations::LandscapeFlipped:
			outputPosition.X = 1.0f - (rawPosition.Y / window->Bounds.Height);
			outputPosition.Y = rawPosition.X / window->Bounds.Width;
			break;
		default:
			break;
	}
	#endif

	OS::VideoMode vm = os->get_video_mode();
	outputPosition.X *= vm.width;
	outputPosition.Y *= vm.height;

	return outputPosition;
};

static int _get_finger(uint32_t p_touch_id) {

	return p_touch_id % 31; // for now
};

void App::pointer_event(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args, bool p_pressed) {

	Windows::UI::Input::PointerPoint ^point = args->CurrentPoint;
	Windows::Foundation::Point pos = _get_pixel_position(window, point->Position, os);
	int but = _get_button(point);
	if (_is_touch(point)) {

		InputEvent event;
		event.type = InputEvent::SCREEN_TOUCH;
		event.device = 0;
		event.screen_touch.pressed = p_pressed;
		event.screen_touch.x = pos.X;
		event.screen_touch.y = pos.Y;
		event.screen_touch.index = _get_finger(point->PointerId);

		last_touch_x[event.screen_touch.index] = pos.X;
		last_touch_y[event.screen_touch.index] = pos.Y;

		os->input_event(event);
		if (event.screen_touch.index != 0)
			return;

	}; // fallthrought of sorts

	InputEvent event;
	event.type = InputEvent::MOUSE_BUTTON;
	event.device = 0;
	event.mouse_button.pressed = p_pressed;
	event.mouse_button.button_index = but;
	event.mouse_button.x = pos.X;
	event.mouse_button.y = pos.Y;
	event.mouse_button.global_x = pos.X;
	event.mouse_button.global_y = pos.Y;

	last_touch_x[31] = pos.X;
	last_touch_y[31] = pos.Y;

	os->input_event(event);
};

void App::OnPointerPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args) {

	pointer_event(sender, args, true);
};

void App::OnPointerReleased(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args) {

	pointer_event(sender, args, false);
};

void App::OnPointerMoved(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args) {

	Windows::UI::Input::PointerPoint ^point = args->CurrentPoint;
	Windows::Foundation::Point pos = _get_pixel_position(window, point->Position, os);

	if (_is_touch(point)) {

		InputEvent event;
		event.type = InputEvent::SCREEN_DRAG;
		event.device = 0;
		event.screen_drag.x = pos.X;
		event.screen_drag.y = pos.Y;
		event.screen_drag.index = _get_finger(point->PointerId);
		event.screen_drag.relative_x = event.screen_drag.x - last_touch_x[event.screen_drag.index];
		event.screen_drag.relative_y = event.screen_drag.y - last_touch_y[event.screen_drag.index];

		os->input_event(event);
		if (event.screen_drag.index != 0)
			return;

	}; // fallthrought of sorts

	InputEvent event;
	event.type = InputEvent::MOUSE_MOTION;
	event.device = 0;
	event.mouse_motion.x = pos.X;
	event.mouse_motion.y = pos.Y;
	event.mouse_motion.global_x = pos.X;
	event.mouse_motion.global_y = pos.Y;
	event.mouse_motion.relative_x = pos.X - last_touch_x[31];
	event.mouse_motion.relative_y = pos.Y - last_touch_y[31];

	os->input_event(event);

};

// Initializes scene resources
void App::Load(Platform::String^ entryPoint)
{
	//char* args[] = {"-test", "render", NULL};
	//Main::setup("winrt", 2, args);
}

// This method is called after the window becomes active.
void App::Run()
{
	if (Main::start())
		os->run();
}

// Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
// class is torn down while the app is in the foreground.
void App::Uninitialize()
{
	Main::cleanup();
	delete os;
}

// Application lifecycle event handler.
void App::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
{
    // Run() won't start until the CoreWindow is activated.
    CoreWindow::GetForCurrentThread()->Activate();
}

// Window event handlers.
void App::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
{
    mWindowVisible = args->Visible;
}

void App::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
{
    mWindowClosed = true;
}

void App::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args)
{
#if (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP)
    // On Windows 8.1, apps are resized when they are snapped alongside other apps, or when the device is rotated.
    // The default framebuffer will be automatically resized when either of these occur.
    // In particular, on a 90 degree rotation, the default framebuffer's width and height will switch.
    UpdateWindowSize(args->Size);
#else if (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
    // On Windows Phone 8.1, the window size changes when the device is rotated.
    // The default framebuffer will not be automatically resized when this occurs.
    // It is therefore up to the app to handle rotation-specific logic in its rendering code.
	//os->screen_size_changed();
	UpdateWindowSize(args->Size);
#endif
}

void App::UpdateWindowSize(Size size)
{
	float dpi;
#if (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP)
	DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
	dpi = currentDisplayInformation->LogicalDpi;
#else if (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
	dpi = DisplayProperties::LogicalDpi;
#endif
	Size pixelSize(ConvertDipsToPixels(size.Width, dpi), ConvertDipsToPixels(size.Height, dpi));

    mWindowWidth = static_cast<GLsizei>(pixelSize.Width);
    mWindowHeight = static_cast<GLsizei>(pixelSize.Height);

	OS::VideoMode vm;
	vm.width = mWindowWidth;
	vm.height = mWindowHeight;
	vm.fullscreen = true;
	vm.resizable = false;
	os->set_video_mode(vm);
}


text:
package ja.tools.reflect;

/**
 * An interface to access a metaobject and a class metaobject.
 * This interface is implicitly implemented by the reflective
 * class.
 */
public interface Metalevel {
    /**
     * Obtains the class metaobject associated with this object.
     */
    ClassMetaobject _getClass();

    /**
     * Obtains the metaobject associated with this object.
     */
    Metaobject _getMetaobject();

    /**
     * Changes the metaobject associated with this object.
     */
    void _setMetaobject(Metaobject m);
}


text:
package org.pitest.mutationtest.engine.gregor.mutators.experimental;

import java.util.ArrayList;
import java.util.List;

import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.pitest.mutationtest.engine.MutationIdentifier;
import org.pitest.mutationtest.engine.gregor.MethodInfo;
import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory;
import org.pitest.mutationtest.engine.gregor.MutationContext;

/**
 * Remove switch statements. We get an array of labels to jump to, plus a
 * default label. We change each label to the default label, thus removing
 * it
 */
public class RemoveSwitchMutator implements MethodMutatorFactory {
  //EXPERIMENTAL_REMOVE_SWITCH_MUTATOR;
  private final int key;

  public RemoveSwitchMutator(final int i) {
     key = i;
  }

  public static Iterable<MethodMutatorFactory> makeMutators() {
    List<MethodMutatorFactory> variations = new ArrayList<MethodMutatorFactory>();
    for (int i = 0; i != 100; i++ ) {
      variations.add(new RemoveSwitchMutator(i) );
    }
    return variations;
  }

  public MethodVisitor create(final MutationContext context,
      final MethodInfo methodInfo, final MethodVisitor methodVisitor) {
    return new RemoveSwitchMethodVisitor(context, methodVisitor);
  }

  public String getGloballyUniqueId() {
    return this.getClass().getName() + "_" + key;
  }

  public String getName() {
    return toString();
  }

  @Override
  public String toString() {
    return "EXPERIMENTAL_REMOVE_SWITCH_MUTATOR_" + key;
  }

  private final class RemoveSwitchMethodVisitor extends MethodVisitor {

    private final MutationContext context;

    public RemoveSwitchMethodVisitor(final MutationContext context,
        final MethodVisitor methodVisitor) {
      super(Opcodes.ASM5, methodVisitor);
      this.context = context;
    }

    @Override
    public void visitTableSwitchInsn(final int i, final int i1,
        final Label defaultLabel, final Label... labels) {
      if (labels.length > key && shouldMutate()) {
        Label[] newLabels = labels.clone();
        newLabels[key] = defaultLabel;
        super.visitTableSwitchInsn(i, i1, defaultLabel, newLabels);
      } else {
        super.visitTableSwitchInsn(i, i1, defaultLabel, labels);
      }
    }

    @Override
    public void visitLookupSwitchInsn(final Label defaultLabel, final int[] ints, final Label[] labels) {
      if (labels.length > key && shouldMutate()) {
        Label[] newLabels = labels.clone();
        newLabels[key] = defaultLabel;
        super.visitLookupSwitchInsn(defaultLabel, ints, newLabels);
      } else {
        super.visitLookupSwitchInsn(defaultLabel, ints, labels);
      }
    }

    private boolean shouldMutate() {
      final MutationIdentifier mutationId = this.context.registerMutation(
          RemoveSwitchMutator.this, "RemoveSwitch " + key + " mutation");
      return this.context.shouldMutate(mutationId);
    }

  }

}


text:
using System.Windows;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Controls;
using WhiteCloud.Model;

namespace WhiteCloud
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window
    {
        private MainWindowDataContext Dc
        {
            get { return (MainWindowDataContext)this.DataContext; }
        }
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new MainWindowDataContext();
        }

        private void PersonQuery_TextChanged(object sender, TextChangedEventArgs e)
        {
            var query = ((TextBox)sender).Text;
            Dc.Query(query);
        }

        private void PersonSelected_PreviewMouseLeftButtonDown(object sender, RoutedEventArgs e)
        {
            using (var entity = new EFModelsContainer())
            {
                var p = ((Person)((ListViewItem)sender).DataContext);
                Dc.SelectedFamily = entity.PersonSet.Find(p.Id).Family;
            }
        }

        /*
        _printDoc.PrintPage += new PrintPageEventHandler(_printDocument_PrintPage);

        private PrintDocument _printDoc = new PrintDocument();
        private PageSettings _pgSettings = new PageSettings();

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _printDoc.DefaultPageSettings = _pgSettings;
            var dlg = new PrintDialog();
            if (dlg.ShowDialog() == true)
            {
                _printDoc.Print();
            }
        }

        private void _printDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            var textToPrint = ".NET Printing is easy";
            var printFont = new Font("Courier New", 12);
            var leftMargin = e.MarginBounds.Left;
            var topMargin = e.MarginBounds.Top;
            var img = System.Drawing.Image.FromFile(@"C:\Users\jhosk\Downloads\K_088_.jpg");
            e.Graphics.DrawImage(img, leftMargin, topMargin);
            e.Graphics.DrawString(textToPrint, printFont, Brushes.White, leftMargin*2, topMargin*2);
        }*/
    }
}


text:
package com.koushikdutta.ion;

import android.graphics.Bitmap;

import com.koushikdutta.async.future.TransformFuture;
import com.koushikdutta.ion.bitmap.BitmapInfo;

class BitmapInfoToBitmap extends TransformFuture<Bitmap, BitmapInfo> {
    IonContext contextReference;
    public BitmapInfoToBitmap(IonContext contextReference) {
        this.contextReference = contextReference;
    }

    @Override
    protected void transform(BitmapInfo result) throws Exception {
        if (contextReference.isAlive() != null) {
            cancel();
            return;
        }

        if (result.exception != null)
            setComplete(result.exception);
        else
            setComplete(result.bitmap);
    }
}


text:
=====
Hooks
=====

.. autoclass:: uranium.hooks.Hooks


text:
'use strict';

describe('Controller: AuthCtrl', function () {

  // load the controller's module
  beforeEach(module('discussionToolApp'));

  var AuthCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    AuthCtrl = $controller('AuthCtrl', {
      $scope: scope
      // place here mocked dependencies
    });
  }));

});


text:
if [[ "$(uname)" == "Darwin" ]]; then
    if [[ -z "$(which brew)" ]]; then
        echo "Sorry, OSX requires a homebrew installation!"
        exit 1
    fi
    brew install jpeg libpng freetype
    brew install sdl sdl_gfx sdl_image sdl_mixer sdl_net sdl_ttf
    brew install portmidi smpeg
elif [[ "$(uname)" == "Linux" ]]; then
    if [[ -z "$(which apt-get)" ]]; then
        echo "** warning: Can only check dependencies on ubuntu/debian"
    else
        echo "Checking dependencies..."
        declare -a packages=("libav-tools" "libsdl-image1.2-dev" "libsdl-mixer1.2-dev" "libsdl-ttf2.0-dev" "libsmpeg-dev" "libsdl1.2-dev" "libportmidi-dev" "libswscale-dev" "libavformat-dev" "libavcodec-dev")

        for dep in "${packages[@]}"
        do
            inst_ver=$(apt-cache policy $dep |grep Installed: | sed 's/\s*Installed: \(.*\)$/\1/')
            echo "Dependency $dep (installed version: $inst_ver)"
            if [[ "$inst_ver" == "(none)" ]]; then
                echo "Please install dependency $dep!"
                exit 1;
            fi
        done
    fi
fi

$PYTHON setup.py install


text:
title: Updating Themes
taxonomy:
    category: docs
    tag: [gantry5]
---

Updating Gantry 5 themes is a very similar process to updating any other theme on its respective platform. The process for updating a Gantry 5 theme for Joomla, as an example, is virtually identical.

## Common Notes

!! Prior to updating any template or theme, we highly recommend backing up your site from stem to stern. This includes the database (if any), and your theme's directory so that you can quickly restore it to the state it was prior to the update should you come across any issues.

Outside of backing up your site, you should keep track of the file(s) you have altered since installing your theme. In most cases, any changes you have made will be stored in the `custom` directory safely tucked away in your theme's directory apart from the rest of the theme's files which are subject to change during an update.

However, there may be cases where you have customized a theme file directly at the source, rather than editing a duplicate in the `custom` directory. If this is the case for your site, make sure you back up the file(s) and store them in a safe place. You may need them for reference after the update should any of your changes revert.

! The process outlined in this guide may not apply to all Gantry 5 themes. Some third-party theme developers may have different update processes depending on their unique situations.

## Platform-specific Process

[ui-tabs position="top-left" active="0"]
[ui-tab title="Joomla"]

Joomla makes it easy to update your Gantry 5-powered template. Once an update is available, you will be notified in the Joomla administrator just as you would with any other extension.

! If you are using a template that does not utilize Joomla's Update option as described below (this includes any [RocketTheme](http://rockettheme.com/) premium template), then simply upload the latest template package via **Administrator > Extensions > Manage > Install > Upload Package File** to update the template. Please backup your website before updating.

![Updating](updating_1.png?classes=shadow,border)

You can initiate the update by navigating to **Administrator > Extensions > Manage > Update**, selecting the theme package, and then the **Update** button to initiate the update.

! Gantry should be updated prior to the template. In some cases, the template update depends on new features included with the latest version of Gantry.

If the update is successful, you will be notified as such and you can continue to use the theme as you did previously. The update process should not affect your custom directory, though if you have any theme-related files outside of the custom directory modified, we recommend comparing your backed up copy to the new copy of the file and manually moving your customizations from there.

[/ui-tab]
[ui-tab title="WordPress"]

WordPress makes it easy to update your Gantry 5-powered theme. Because any changes you made in the admin are stored in the `custom` directory of your theme, they should be safe throughout this process as long as you have performed the recommended backup beforehand.

If you are confident that the only changes you have made to your site are stored in the theme's `custom` directory, you can simply upload the new, updated version of the theme.

![Updating](updating_2.png?classes=shadow,border)

To do this, navigate to **Admin > Appearance > Themes**. At the top of the **Themes** page is an **Add New** button. Selecting it takes you to the **Add Themes** page where you can select the **Upload Theme** button which is placed in the same position the Add New button was in the last page.

Now, you simply need to choose the theme's zip package and select **Install Now**. Once your installation is complete you will be given the option to **Activate** it. Activate it, clear your Gantry cache, and then test your site.

[/ui-tab]
[ui-tab title="Grav"]

You can update a Gantry 5 theme on Grav in several different ways. The preferred method of updating themes depends on how that theme is listed.

If your theme is part of the Grav GPM like Hydrogen, Helium, or many other free themes listed on the [Grav Themes Repository](https://getgrav.org/downloads/themes), you can update them using the **Grav Admin** in either the **Dashboard** or the **Themes** section of the admin. You can also update the theme using the GPM from a **command line** or **terminal**.

If your theme is not listed on the Grav Themes Directory, or you prefer to manually update it from the file system, you can use our **File Manager** method listed below.

## First Method: Individual Theme Updater

![](grav_theme_update.png?classes=shadow,border)

When an update is available, a notice will be over the theme's thumbnail in the **Admin > Themes** section of the Grav Admin. You can individually update the plugin by clicking the **UPDATE** banner to take you to the theme's description page where you can update it directly.

 Learn More About the Themes Section of the Admin

## Second Method: Dashboard

You can also update your plugins and themes all at once from the main **Dashboard** area of the **Grav Admin**.

![](g5_grav_update_3.png?classes=shadow,border)

All you need to do is select the ** Update** button in the **Maintenance** area of the page. This will update all of your plugins and themes at the same time.

 Learn More About the Grav Dashboard

## Third Method: Tools

! This method is available to you in the event that you are using a theme that isn't listed in the Grav GPM. One common example of this would be a premium theme from a third party, such as [RocketTheme](http://rockettheme.com).

![](g5_grav_update_5.jpg?classes=shadow,border)

Navigate to your **Grav Admin > Tools** and simply install the latest theme package via the **Direct ZIP Upload**  or ** Remote URL Reference**  options.

## Fourth Method: Command Line

Updating your theme using the command line is simple and easy. Technically, it executes the same process as you would access in the Grav Admin, but enables you to do so from the convenience of the command line.

Here are the steps:

* Open Command Line or Terminal and navigate to the root directory of your Grav site on your server.
* Enter one of the following lines:
    * `bin/gpm update` to initiate an update of all of your currently-installed plugins and themes.
    * or `bin/gpm update helium` to update only the Helium theme.
* Enter `Y` to confirm the update.

The update will run by itself and the theme will be available to you as soon as it's done.

 Learn More Command Line Updating

## Fifth Method: File Manager

You can manually update the theme by doing the following:

* Download the latest theme package/directory. Typically this will be a zip file containing the theme's directory.
* Open your FTP client or command line and navigate to `user/themes` and back up the theme's directory, moving it to a safe place.
* Unpack and replace the theme's directory with the contents of the package you downloaded in the first step.

The updated theme should now be available to you.

[/ui-tab]
[/ui-tabs]


text:
import Ember from 'ember';
import SlugGenerator from 'ghost/models/slug-generator';
import isNumber from 'ghost/utils/isNumber';
import boundOneWay from 'ghost/utils/bound-one-way';

export default Ember.Controller.extend({
    ghostPaths: Ember.inject.service('ghost-paths'),
    notifications: Ember.inject.service(),

    currentUser: Ember.computed.alias('session.user'),

    isNotOwnProfile: Ember.computed('user.id', 'currentUser.id', function () {
        return this.get('user.id') !== this.get('currentUser.id');
    }),

    isNotOwnersProfile: Ember.computed.not('user.isOwner'),

    isAdminUserOnOwnerProfile: Ember.computed.and('currentUser.isAdmin', 'user.isOwner'),

    canAssignRoles: Ember.computed.or('currentUser.isAdmin', 'currentUser.isOwner'),

    canMakeOwner: Ember.computed.and('currentUser.isOwner', 'isNotOwnProfile', 'user.isAdmin'),

    rolesDropdownIsVisible: Ember.computed.and('isNotOwnProfile', 'canAssignRoles', 'isNotOwnersProfile'),

    deleteUserActionIsVisible: Ember.computed('currentUser', 'canAssignRoles', 'user', function () {
        if ((this.get('canAssignRoles') && this.get('isNotOwnProfile') && !this.get('user.isOwner')) ||
            (this.get('currentUser.isEditor') && (this.get('isNotOwnProfile') ||
            this.get('user.isAuthor')))) {
            return true;
        }
    }),

    userActionsAreVisible: Ember.computed.or('deleteUserActionIsVisible', 'canMakeOwner'),

    user: Ember.computed.alias('model'),

    email: Ember.computed.readOnly('model.email'),

    slugValue: boundOneWay('model.slug'),

    lastPromise: null,

    // duplicated in gh-user-active -- find a better home and consolidate?

    userDefault: Ember.computed('ghostPaths', function () {
        return this.get('ghostPaths.url').asset('/shared/img/user-image.png');
    }),

    userImageBackground: Ember.computed('user.image', 'userDefault', function () {
        var url = this.get('user.image') || this.get('userDefault');

        return `background-image: url(${url})`.htmlSafe();
    }),

    // end duplicated

    coverDefault: Ember.computed('ghostPaths', function () {
        return this.get('ghostPaths.url').asset('/shared/img/user-cover.png');
    }),

    coverImageBackground: Ember.computed('user.cover', 'coverDefault', function () {
        var url = this.get('user.cover') || this.get('coverDefault');

        return `background-image: url(${url})`.htmlSafe();
    }),

    coverTitle: Ember.computed('user.name', function () {
        return this.get('user.name') + '\'s Cover Image';
    }),

    // Lazy load the slug generator for slugPlaceholder
    slugGenerator: Ember.computed(function () {
        return SlugGenerator.create({
            ghostPaths: this.get('ghostPaths'),
            slugType: 'user'
        });
    }),

    actions: {
        changeRole: function (newRole) {
            this.set('model.role', newRole);
        },

        save: function () {
            var user = this.get('user'),
                slugValue = this.get('slugValue'),
                afterUpdateSlug = this.get('lastPromise'),
                promise,
                slugChanged,
                self = this;

            if (user.get('slug') !== slugValue) {
                slugChanged = true;
                user.set('slug', slugValue);
            }

            promise = Ember.RSVP.resolve(afterUpdateSlug).then(function () {
                return user.save({format: false});
            }).then(function (model) {
                var currentPath,
                    newPath;

                self.get('notifications').showSuccess('Settings successfully saved.');

                // If the user's slug has changed, change the URL and replace
                // the history so refresh and back button still work
                if (slugChanged) {
                    currentPath = window.history.state.path;

                    newPath = currentPath.split('/');
                    newPath[newPath.length - 2] = model.get('slug');
                    newPath = newPath.join('/');

                    window.history.replaceState({path: newPath}, '', newPath);
                }

                return model;
            }).catch(function (errors) {
                if (errors) {
                    self.get('notifications').showErrors(errors);
                }
            });

            this.set('lastPromise', promise);
        },

        password: function () {
            var user = this.get('user'),
                self = this;

            if (user.get('isPasswordValid')) {
                user.saveNewPassword().then(function (model) {
                    // Clear properties from view
                    user.setProperties({
                        password: '',
                        newPassword: '',
                        ne2Password: ''
                    });

                    self.get('notifications').showSuccess('Password updated.');

                    return model;
                }).catch(function (errors) {
                    self.get('notifications').showAPIError(errors);
                });
            } else {
                self.get('notifications').showErrors(user.get('passwordValidationErrors'));
            }
        },

        updateSlug: function (newSlug) {
            var self = this,
                afterSave = this.get('lastPromise'),
                promise;

            promise = Ember.RSVP.resolve(afterSave).then(function () {
                var slug = self.get('model.slug');

                newSlug = newSlug || slug;

                newSlug = newSlug.trim();

                // Ignore unchanged slugs or candidate slugs that are empty
                if (!newSlug || slug === newSlug) {
                    self.set('slugValue', slug);

                    return;
                }

                return self.get('slugGenerator').generateSlug(newSlug).then(function (serverSlug) {
                    // If after getting the sanitized and unique slug back from the API
                    // we end up with a slug that matches the existing slug, abort the change
                    if (serverSlug === slug) {
                        return;
                    }

                    // Because the server transforms the candidate slug by stripping
                    // certain characters and appending a number onto the end of slugs
                    // to enforce uniqueness, there are cases where we can get back a
                    // candidate slug that is a duplicate of the original except for
                    // the trailing incrementor (e.g., this-is-a-slug and this-is-a-slug-2)

                    // get the last token out of the slug candidate and see if it's a number
                    var slugTokens = serverSlug.split('-'),
                        check = Number(slugTokens.pop());

                    // if the candidate slug is the same as the existing slug except
                    // for the incrementor then the existing slug should be used
                    if (isNumber(check) && check > 0) {
                        if (slug === slugTokens.join('-') && serverSlug !== newSlug) {
                            self.set('slugValue', slug);

                            return;
                        }
                    }

                    self.set('slugValue', serverSlug);
                });
            });

            this.set('lastPromise', promise);
        }
    }
});


text:
package fr.tse.lt2c.satin.matrix.validate;

import java.io.File;

import fr.tse.lt2c.satin.matrix.beans.BinaryMatrix;
import fr.tse.lt2c.satin.matrix.beans.DecompositionResult;
import fr.tse.lt2c.satin.matrix.extraction.linkedmatrix.refactored.WSMRDecomposer;
import fr.tse.lt2c.satin.matrix.utils.MatrixParser;

public class Validate {

	private static final int MINRECTANGLESIZE = 1;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		BinaryMatrix matrix = MatrixParser.binaryMatrixFromFile(new File("matrices/matrix3.txt"));
		System.out.println(matrix.getNumberOfOnes());

		WSMRDecomposer largestCompute = new WSMRDecomposer(matrix);
		System.out.println(matrix);
		DecompositionResult res = largestCompute.computeDecomposition(MINRECTANGLESIZE);
		System.out.println(res.totalArea());
		System.out.println(res.reconstructMatrix(matrix.getRow(), matrix.getCol()));
		BinaryMatrix difference = matrix.difference(res.reconstructMatrix(matrix.getRow(), matrix.getCol()));
		System.out.println(difference.getNumberOfOnes());

	}

}


text:
define([
	'jquery',
	'underscore',
	'backbone',
	'marionette',
	'text!templates/users/review/review-accounts.tpl',
	'scripts/registry',
	'scripts/widgets/accordions',
	'scripts/collections/users/users',
	'scripts/views/dialogs/notify-view',
	'scripts/views/dialogs/error-view',
	'scripts/views/users/filters/user-filters-view',
	'scripts/views/users/review/review-accounts-list/review-accounts-list-view'
], function($, _, Backbone, Marionette, Template, Registry, Accordions, Users, NotifyView, ErrorView, UserFiltersView, ReviewAccountsListView) {
	return Backbone.Marionette.LayoutView.extend({

		//
		// attributes
		//

		regions: {
			userFilters: '#user-filters',
			reviewAccountsList: '#review-accounts-list'
		},

		events: {
			'click #save': 'onClickSave',
			'click #cancel': 'onClickCancel',
			'click #show-disabled-accounts': 'onClickShowDisabledAccounts',
			'click #show-numbering': 'onClickShowNumbering'
		},

		//
		// methods
		//

		initialize: function() {
			this.collection = new Users();
		},

		showDisabledAccounts: function() {
			return this.$el.find('#show-disabled-accounts').is(':checked');
		},

		fetchAccounts: function(done) {
			// fetch user accounts
			//
			this.collection.fetchAll({
				data: this.userFilters.currentView? this.userFilters.currentView.getData() : null,

				// callbacks
				//
				success: function() {
					done();
				},

				error: function() {

					// show error dialog
					//
					Registry.application.modal.show(
						new ErrorView({
							message: "Could not load users."
						})
					);
				}
			});
		},

		saveAccounts: function() {
			var self = this;

			// save users individually
			//
			var successes = 0, errors = 0, changes = 0;
			for (var i = 0; i < this.collection.length; i++) {
				var model = this.collection.at(i);

				if (model.hasChanged()) {
					changes++;
					model.save(undefined, {

						// callbacks
						//
						success: function() {
							successes++;

							// report success when completed
							//
							if (i === self.collection.length && successes === changes) {

								// show success notification dialog
								//
								Registry.application.modal.show(
									new NotifyView({
										title: "User Account Changes Saved",
										message: "Your user account changes have been successfully saved."
									})
								);
							}
						},

						error: function() {
							errors++;

							// report first error
							//
							if (errors === 1) {

								// show error dialog
								//
								Registry.application.modal.show(
									new ErrorView({
										message: "Your user account changes could not be saved."
									})
								);
							}
						}
					});
				}
			}
			if (changes === 0) {

				// show no changes notification dialog
				//
				Registry.application.modal.show(
					new NotifyView({
						message: "There are no new user account changes to save."
					})
				);
			}

			/*
			// save user accounts
			//
			this.collection.save({

				// callbacks
				//
				success: function() {

					// show success notification dialog
					//
					Registry.application.modal.show(
						new NotifyView({
							title: "User Account Changes Saved",
							message: "Your user account changes have been successfully saved."
						})
					);
				},

				error: function() {

					// show error dialog
					//
					Registry.application.modal.show(
						new ErrorView({
							message: "Your user account changes could not be saved."
						})
					);
				}
			});
			*/
		},

		//
		// rendering methods
		//

		template: function(){
			return _.template(Template,{
				showDisabledAccounts: this.options.showDisabledAccounts ? true : false,
				showNumbering: Registry.application.getShowNumbering()
			});
		},

		onRender: function() {
			var self = this;

			// change accordion icon
			//
			new Accordions(this.$el.find('.accordion'));

			// show user filters view
			//
			this.userFilters.show(
				new UserFiltersView({
					model: this.model,
					data: this.options.data? this.options.data : {},

					// callbacks
					//
					onChange: function() {
						setQueryString(self.userFilters.currentView.getQueryString());
					}
				})
			);

			// fetch and show accounts
			//
			this.fetchAccounts(function() {
				self.showAccountsList();
			});
		},

		showAccountsList: function() {

			// show review user accounts list
			//
			this.reviewAccountsList.show(
				new ReviewAccountsListView({
					collection: this.collection,
					showDisabledAccounts: this.showDisabledAccounts(),
					showNumbering: Registry.application.getShowNumbering()
				})
			);
		},

		//
		// event handling methods
		//

		onClickSave: function() {
			this.saveAccounts();
		},

		onClickCancel: function() {

			// go home
			//
			Backbone.history.navigate('#home', {
				trigger: true
			});
		},

		onClickShowDisabledAccounts: function() {
			this.reviewAccountsList.currentView.options.showDisabledAccounts = this.showDisabledAccounts();
			this.reviewAccountsList.currentView.render();
		},

		onClickShowNumbering: function(event) {
			Registry.application.setShowNumbering($(event.target).is(':checked'));
			this.showAccountsList();
		}
	});
});