text:
package org.apache.ignite.internal.processors.cache;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.events.DiscoveryEvent;
import org.apache.ignite.events.Event;
import org.apache.ignite.internal.IgniteClientDisconnectedCheckedException;
import org.apache.ignite.internal.IgniteFutureTimeoutCheckedException;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.IgniteInterruptedCheckedException;
import org.apache.ignite.internal.cluster.ClusterTopologyCheckedException;
import org.apache.ignite.internal.events.DiscoveryCustomEvent;
import org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridClientPartitionTopology;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionTopology;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTopologyFuture;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionExchangeId;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionFullMap;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionMap;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsFullMessage;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsSingleMessage;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsSingleRequest;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPreloaderAssignments;
import org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx;
import org.apache.ignite.internal.processors.cache.transactions.IgniteTxManager;
import org.apache.ignite.internal.processors.timeout.GridTimeoutObject;
import org.apache.ignite.internal.util.GridListSet;
import org.apache.ignite.internal.util.future.GridFutureAdapter;
import org.apache.ignite.internal.util.tostring.GridToStringExclude;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.CI1;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.internal.util.worker.GridWorker;
import org.apache.ignite.lang.IgniteBiInClosure;
import org.apache.ignite.lang.IgniteUuid;
import org.apache.ignite.thread.IgniteThread;
import org.jetbrains.annotations.Nullable;
import org.jsr166.ConcurrentHashMap8;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_AFFINITY_HISTORY_SIZE;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_PRELOAD_RESEND_TIMEOUT;
import static org.apache.ignite.IgniteSystemProperties.getInteger;
import static org.apache.ignite.IgniteSystemProperties.getLong;
import static org.apache.ignite.events.EventType.EVT_CACHE_REBALANCE_STARTED;
import static org.apache.ignite.events.EventType.EVT_NODE_FAILED;
import static org.apache.ignite.events.EventType.EVT_NODE_JOINED;
import static org.apache.ignite.events.EventType.EVT_NODE_LEFT;
import static org.apache.ignite.internal.events.DiscoveryCustomEvent.EVT_DISCOVERY_CUSTOM_EVT;
import static org.apache.ignite.internal.managers.communication.GridIoPolicy.SYSTEM_POOL;
import static org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPreloader.DFLT_PRELOAD_RESEND_TIMEOUT;

/**
 * Partition exchange manager.
 */
public class GridCachePartitionExchangeManager<K, V> extends GridCacheSharedManagerAdapter<K, V> {
    /** Exchange history size. */
    private static final int EXCHANGE_HISTORY_SIZE = 1000;

    /** Cleanup history size. */
    public static final int EXCH_FUT_CLEANUP_HISTORY_SIZE = getInteger(IGNITE_AFFINITY_HISTORY_SIZE, 100);

    /** Atomic reference for pending timeout object. */
    private AtomicReference<ResendTimeoutObject> pendingResend = new AtomicReference<>();

    /** Partition resend timeout after eviction. */
    private final long partResendTimeout = getLong(IGNITE_PRELOAD_RESEND_TIMEOUT, DFLT_PRELOAD_RESEND_TIMEOUT);

    /** Latch which completes after local exchange future is created. */
    private GridFutureAdapter<?> locExchFut;

    /** */
    private final ReadWriteLock busyLock = new ReentrantReadWriteLock();

    /** Last partition refresh. */
    private final AtomicLong lastRefresh = new AtomicLong(-1);

    /** Pending futures. */
    private final Queue<GridDhtPartitionsExchangeFuture> pendingExchangeFuts = new ConcurrentLinkedQueue<>();

    /** */
    @GridToStringInclude
    private ExchangeWorker exchWorker;

    /** */
    @GridToStringExclude
    private final ConcurrentMap<Integer, GridClientPartitionTopology> clientTops = new ConcurrentHashMap8<>();

    /** */
    private volatile GridDhtPartitionsExchangeFuture lastInitializedFut;

    /** */
    private final ConcurrentMap<AffinityTopologyVersion, AffinityReadyFuture> readyFuts = new ConcurrentHashMap8<>();

    /** */
    private final AtomicReference<AffinityTopologyVersion> readyTopVer =
        new AtomicReference<>(AffinityTopologyVersion.NONE);

    /** */
    private GridFutureAdapter<?> reconnectExchangeFut;

    /**
     * Partition map futures.
     * This set also contains already completed exchange futures to address race conditions when coordinator
     * leaves grid and new coordinator sends full partition message to a node which has not yet received
     * discovery event. In case if remote node will retry partition exchange, completed future will indicate
     * that full partition map should be sent to requesting node right away.
     */
    private ExchangeFutureSet exchFuts = new ExchangeFutureSet();

    /** */
    private volatile IgniteCheckedException stopErr;

    /** Discovery listener. */
    private final GridLocalEventListener discoLsnr = new GridLocalEventListener() {
        @Override public void onEvent(Event evt) {
            if (!enterBusy())
                return;

            try {
                DiscoveryEvent e = (DiscoveryEvent)evt;

                ClusterNode loc = cctx.localNode();

                assert e.type() == EVT_NODE_JOINED || e.type() == EVT_NODE_LEFT || e.type() == EVT_NODE_FAILED ||
                    e.type() == EVT_DISCOVERY_CUSTOM_EVT;

                final ClusterNode n = e.eventNode();

                GridDhtPartitionExchangeId exchId = null;
                GridDhtPartitionsExchangeFuture exchFut = null;

                if (e.type() != EVT_DISCOVERY_CUSTOM_EVT) {
                    assert !loc.id().equals(n.id());

                    if (e.type() == EVT_NODE_LEFT || e.type() == EVT_NODE_FAILED) {
                        assert cctx.discovery().node(n.id()) == null;

                        for (GridDhtPartitionsExchangeFuture f : exchFuts.values())
                            f.onNodeLeft(n.id());
                    }

                    assert
                        e.type() != EVT_NODE_JOINED || n.order() > loc.order() :
                        "Node joined with smaller-than-local " +
                            "order [newOrder=" + n.order() + ", locOrder=" + loc.order() + ']';

                    exchId = exchangeId(n.id(),
                        affinityTopologyVersion(e),
                        e.type());

                    exchFut = exchangeFuture(exchId, e, null);
                }
                else {
                    DiscoveryCustomEvent customEvt = (DiscoveryCustomEvent)e;

                    if (customEvt.customMessage() instanceof DynamicCacheChangeBatch) {
                        DynamicCacheChangeBatch batch = (DynamicCacheChangeBatch)customEvt.customMessage();

                        Collection<DynamicCacheChangeRequest> valid = new ArrayList<>(batch.requests().size());

                        // Validate requests to check if event should trigger partition exchange.
                        for (final DynamicCacheChangeRequest req : batch.requests()) {
                            if (req.exchangeNeeded())
                                valid.add(req);
                            else {
                                IgniteInternalFuture<?> fut = null;

                                if (req.cacheFutureTopologyVersion() != null)
                                    fut = affinityReadyFuture(req.cacheFutureTopologyVersion());

                                if (fut == null || fut.isDone())
                                    cctx.cache().completeStartFuture(req);
                                else {
                                    fut.listen(new CI1<IgniteInternalFuture<?>>() {
                                        @Override public void apply(IgniteInternalFuture<?> fut) {
                                            cctx.cache().completeStartFuture(req);
                                        }
                                    });
                                }
                            }
                        }

                        if (!F.isEmpty(valid)) {
                            exchId = exchangeId(n.id(), affinityTopologyVersion(e), e.type());

                            exchFut = exchangeFuture(exchId, e, valid);
                        }
                    }
                }

                if (exchId != null) {
                    // Start exchange process.
                    pendingExchangeFuts.add(exchFut);

                    // Event callback - without this callback future will never complete.
                    exchFut.onEvent(exchId, e);

                    if (log.isDebugEnabled())
                        log.debug("Discovery event (will start exchange): " + exchId);

                    locExchFut.listen(new CI1<IgniteInternalFuture<?>>() {
                        @Override public void apply(IgniteInternalFuture<?> t) {
                            if (!enterBusy())
                                return;

                            try {
                                // Unwind in the order of discovery events.
                                for (GridDhtPartitionsExchangeFuture f = pendingExchangeFuts.poll(); f != null;
                                    f = pendingExchangeFuts.poll())
                                    addFuture(f);
                            }
                            finally {
                                leaveBusy();
                            }
                        }
                    });
                }
            }
            finally {
                leaveBusy();
            }
        }
    };

    /** {@inheritDoc} */
    @Override protected void start0() throws IgniteCheckedException {
        super.start0();

        locExchFut = new GridFutureAdapter<>();

        exchWorker = new ExchangeWorker();

        cctx.gridEvents().addLocalEventListener(discoLsnr, EVT_NODE_JOINED, EVT_NODE_LEFT, EVT_NODE_FAILED,
            EVT_DISCOVERY_CUSTOM_EVT);

        cctx.io().addHandler(0, GridDhtPartitionsSingleMessage.class,
            new MessageHandler<GridDhtPartitionsSingleMessage>() {
                @Override public void onMessage(ClusterNode node, GridDhtPartitionsSingleMessage msg) {
                    processSinglePartitionUpdate(node, msg);
                }
            });

        cctx.io().addHandler(0, GridDhtPartitionsFullMessage.class,
            new MessageHandler<GridDhtPartitionsFullMessage>() {
                @Override public void onMessage(ClusterNode node, GridDhtPartitionsFullMessage msg) {
                    processFullPartitionUpdate(node, msg);
                }
            });

        cctx.io().addHandler(0, GridDhtPartitionsSingleRequest.class,
            new MessageHandler<GridDhtPartitionsSingleRequest>() {
                @Override public void onMessage(ClusterNode node, GridDhtPartitionsSingleRequest msg) {
                    processSinglePartitionRequest(node, msg);
                }
            });
    }

    /**
     * @return Reconnect partition exchange future.
     */
    public IgniteInternalFuture<?> reconnectExchangeFuture() {
        return reconnectExchangeFut;
    }

    /** {@inheritDoc} */
    @Override protected void onKernalStart0(boolean reconnect) throws IgniteCheckedException {
        super.onKernalStart0(reconnect);

        ClusterNode loc = cctx.localNode();

        long startTime = loc.metrics().getStartTime();

        assert startTime > 0;

        // Generate dummy discovery event for local node joining.
        DiscoveryEvent discoEvt = cctx.discovery().localJoinEvent();

        final AffinityTopologyVersion startTopVer = affinityTopologyVersion(discoEvt);

        GridDhtPartitionExchangeId exchId = exchangeId(loc.id(), startTopVer, EVT_NODE_JOINED);

        assert discoEvt != null;

        assert discoEvt.topologyVersion() == startTopVer.topologyVersion();

        GridDhtPartitionsExchangeFuture fut = exchangeFuture(exchId, discoEvt, null);

        if (reconnect)
            reconnectExchangeFut = new GridFutureAdapter<>();

        new IgniteThread(cctx.gridName(), "exchange-worker", exchWorker).start();

        onDiscoveryEvent(cctx.localNodeId(), fut);

        // Allow discovery events to get processed.
        locExchFut.onDone();

        if (reconnect) {
            fut.listen(new CI1<IgniteInternalFuture<AffinityTopologyVersion>>() {
                @Override public void apply(IgniteInternalFuture<AffinityTopologyVersion> fut) {
                    try {
                        fut.get();

                        for (GridCacheContext cacheCtx : cctx.cacheContexts())
                            cacheCtx.preloader().onInitialExchangeComplete(null);

                        reconnectExchangeFut.onDone();
                    }
                    catch (IgniteCheckedException e) {
                        for (GridCacheContext cacheCtx : cctx.cacheContexts())
                            cacheCtx.preloader().onInitialExchangeComplete(e);

                        reconnectExchangeFut.onDone(e);
                    }
                }
            });
        }
        else {
            if (log.isDebugEnabled())
                log.debug("Beginning to wait on local exchange future: " + fut);

            boolean first = true;

            while (true) {
                try {
                    fut.get(cctx.preloadExchangeTimeout());

                    break;
                }
                catch (IgniteFutureTimeoutCheckedException ignored) {
                    if (first) {
                        U.warn(log, "Failed to wait for initial partition map exchange. " +
                            "Possible reasons are: " + U.nl() +
                            "  ^-- Transactions in deadlock." + U.nl() +
                            "  ^-- Long running transactions (ignore if this is the case)." + U.nl() +
                            "  ^-- Unreleased explicit locks.");

                        first = false;
                    }
                    else
                        U.warn(log, "Still waiting for initial partition map exchange [fut=" + fut + ']');
                }
            }

            for (GridCacheContext cacheCtx : cctx.cacheContexts())
                cacheCtx.preloader().onInitialExchangeComplete(null);

            if (log.isDebugEnabled())
                log.debug("Finished waiting for initial exchange: " + fut.exchangeId());
        }
    }

    /** {@inheritDoc} */
    @Override protected void onKernalStop0(boolean cancel) {
        cctx.gridEvents().removeLocalEventListener(discoLsnr);

        cctx.io().removeHandler(0, GridDhtPartitionsSingleMessage.class);
        cctx.io().removeHandler(0, GridDhtPartitionsFullMessage.class);
        cctx.io().removeHandler(0, GridDhtPartitionsSingleRequest.class);

        stopErr = cctx.kernalContext().clientDisconnected() ?
            new IgniteClientDisconnectedCheckedException(cctx.kernalContext().cluster().clientReconnectFuture(),
                "Client node disconnected: " + cctx.gridName()) :
            new IgniteInterruptedCheckedException("Node is stopping: " + cctx.gridName());

        // Finish all exchange futures.
        ExchangeFutureSet exchFuts0 = exchFuts;

        if (exchFuts0 != null) {
            for (GridDhtPartitionsExchangeFuture f : exchFuts.values())
                f.onDone(stopErr);
        }

        for (AffinityReadyFuture f : readyFuts.values())
            f.onDone(stopErr);

        for (GridDhtPartitionsExchangeFuture f : pendingExchangeFuts)
            f.onDone(stopErr);

        if (locExchFut != null)
            locExchFut.onDone(stopErr);

        U.cancel(exchWorker);

        if (log.isDebugEnabled())
            log.debug("Before joining on exchange worker: " + exchWorker);

        U.join(exchWorker, log);

        ResendTimeoutObject resendTimeoutObj = pendingResend.getAndSet(null);

        if (resendTimeoutObj != null)
            cctx.time().removeTimeoutObject(resendTimeoutObj);
    }

    /** {@inheritDoc} */
    @SuppressWarnings("LockAcquiredButNotSafelyReleased")
    @Override protected void stop0(boolean cancel) {
        super.stop0(cancel);

        // Do not allow any activity in exchange manager after stop.
        busyLock.writeLock().lock();

        exchFuts = null;
    }

    /**
     * @param cacheId Cache ID.
     * @param exchFut Exchange future.
     * @return Topology.
     */
    public GridDhtPartitionTopology clientTopology(int cacheId, GridDhtPartitionsExchangeFuture exchFut) {
        GridClientPartitionTopology top = clientTops.get(cacheId);

        if (top != null)
            return top;

        GridClientPartitionTopology old = clientTops.putIfAbsent(cacheId,
            top = new GridClientPartitionTopology(cctx, cacheId, exchFut));

        return old != null ? old : top;
    }

    /**
     * @return Collection of client topologies.
     */
    public Collection<GridClientPartitionTopology> clientTopologies() {
        return clientTops.values();
    }

    /**
     * @param cacheId Cache ID.
     * @return Client partition topology.
     */
    public GridClientPartitionTopology clearClientTopology(int cacheId) {
        return clientTops.remove(cacheId);
    }

    /**
     * Gets topology version of last partition exchange, it is possible that last partition exchange
     * is not completed yet.
     *
     * @return Topology version.
     */
    public AffinityTopologyVersion topologyVersion() {
        GridDhtPartitionsExchangeFuture lastInitializedFut0 = lastInitializedFut;

        return lastInitializedFut0 != null
            ? lastInitializedFut0.exchangeId().topologyVersion() : AffinityTopologyVersion.NONE;
    }

    /**
     * @return Topology version of latest completed partition exchange.
     */
    public AffinityTopologyVersion readyAffinityVersion() {
        return readyTopVer.get();
    }

    /**
     * @return Last completed topology future.
     */
    public GridDhtTopologyFuture lastTopologyFuture() {
        return lastInitializedFut;
    }

    /**
     * @param ver Topology version.
     * @return Future or {@code null} is future is already completed.
     */
    @Nullable public IgniteInternalFuture<?> affinityReadyFuture(AffinityTopologyVersion ver) {
        GridDhtPartitionsExchangeFuture lastInitializedFut0 = lastInitializedFut;

        if (lastInitializedFut0 != null && lastInitializedFut0.topologyVersion().compareTo(ver) == 0) {
            if (log.isDebugEnabled())
                log.debug("Return lastInitializedFut for topology ready future " +
                    "[ver=" + ver + ", fut=" + lastInitializedFut0 + ']');

            return lastInitializedFut0;
        }

        AffinityTopologyVersion topVer = readyTopVer.get();

        if (topVer.compareTo(ver) >= 0) {
            if (log.isDebugEnabled())
                log.debug("Return finished future for topology ready future [ver=" + ver + ", topVer=" + topVer + ']');

            return null;
        }

        GridFutureAdapter<AffinityTopologyVersion> fut = F.addIfAbsent(readyFuts, ver,
            new AffinityReadyFuture(ver));

        if (log.isDebugEnabled())
            log.debug("Created topology ready future [ver=" + ver + ", fut=" + fut + ']');

        topVer = readyTopVer.get();

        if (topVer.compareTo(ver) >= 0) {
            if (log.isDebugEnabled())
                log.debug("Completing created topology ready future " +
                    "[ver=" + topVer + ", topVer=" + topVer + ", fut=" + fut + ']');

            fut.onDone(topVer);
        }
        else if (stopErr != null)
            fut.onDone(stopErr);

        return fut;
    }

    /**
     * @return {@code true} if entered to busy state.
     */
    private boolean enterBusy() {
        if (busyLock.readLock().tryLock())
            return true;

        if (log.isDebugEnabled())
            log.debug("Failed to enter to busy state (exchange manager is stopping): " + cctx.localNodeId());

        return false;
    }

    /**
     *
     */
    private void leaveBusy() {
        busyLock.readLock().unlock();
    }

    /**
     * @return Exchange futures.
     */
    public List<GridDhtPartitionsExchangeFuture> exchangeFutures() {
        return exchFuts.values();
    }

    /**
     * @return {@code True} if pending future queue is empty.
     */
    public boolean hasPendingExchange() {
        return !exchWorker.futQ.isEmpty();
    }

    /**
     * @param nodeId New node ID.
     * @param fut Exchange future.
     */
    void onDiscoveryEvent(UUID nodeId, GridDhtPartitionsExchangeFuture fut) {
        if (!enterBusy())
            return;

        try {
            addFuture(fut);
        }
        finally {
            leaveBusy();
        }
    }

    /**
     * @param evt Discovery event.
     * @return Affinity topology version.
     */
    private AffinityTopologyVersion affinityTopologyVersion(DiscoveryEvent evt) {
        if (evt.type() == DiscoveryCustomEvent.EVT_DISCOVERY_CUSTOM_EVT)
            return ((DiscoveryCustomEvent)evt).affinityTopologyVersion();

        return new AffinityTopologyVersion(evt.topologyVersion());
    }

    /**
     * @return {@code True} if topology has changed.
     */
    public boolean topologyChanged() {
        return exchWorker.topologyChanged();
    }

    /**
     * @param exchFut Exchange future.
     * @param reassign Dummy reassign flag.
     */
    public void forceDummyExchange(boolean reassign,
        GridDhtPartitionsExchangeFuture exchFut) {
        exchWorker.addFuture(
            new GridDhtPartitionsExchangeFuture(cctx, reassign, exchFut.discoveryEvent(), exchFut.exchangeId()));
    }

    /**
     * Forces preload exchange.
     *
     * @param exchFut Exchange future.
     */
    public void forcePreloadExchange(GridDhtPartitionsExchangeFuture exchFut) {
        exchWorker.addFuture(
            new GridDhtPartitionsExchangeFuture(cctx, exchFut.discoveryEvent(), exchFut.exchangeId()));
    }

    /**
     * Schedules next full partitions update.
     */
    public void scheduleResendPartitions() {
        ResendTimeoutObject timeout = pendingResend.get();

        if (timeout == null || timeout.started()) {
            ResendTimeoutObject update = new ResendTimeoutObject();

            if (pendingResend.compareAndSet(timeout, update))
                cctx.time().addTimeoutObject(update);
        }
    }

    /**
     * Partition refresh callback.
     */
    void refreshPartitions() {
        ClusterNode oldest = CU.oldestAliveCacheServerNode(cctx, AffinityTopologyVersion.NONE);

        if (oldest == null) {
            if (log.isDebugEnabled())
                log.debug("Skip partitions refresh, there are no server nodes [loc=" + cctx.localNodeId() + ']');

            return;
        }

        if (log.isDebugEnabled())
            log.debug("Refreshing partitions [oldest=" + oldest.id() + ", loc=" + cctx.localNodeId() + ']');

        Collection<ClusterNode> rmts = null;

        // If this is the oldest node.
        if (oldest.id().equals(cctx.localNodeId())) {
            rmts = CU.remoteNodes(cctx, AffinityTopologyVersion.NONE);

            if (log.isDebugEnabled())
                log.debug("Refreshing partitions from oldest node: " + cctx.localNodeId());

            sendAllPartitions(rmts);
        }
        else {
            if (log.isDebugEnabled())
                log.debug("Refreshing local partitions from non-oldest node: " +
                    cctx.localNodeId());

            sendLocalPartitions(oldest, null);
        }
    }

    /**
     * Refresh partitions.
     *
     * @param timeout Timeout.
     */
    private void refreshPartitions(long timeout) {
        long last = lastRefresh.get();

        long now = U.currentTimeMillis();

        if (last != -1 && now - last >= timeout && lastRefresh.compareAndSet(last, now)) {
            if (log.isDebugEnabled())
                log.debug("Refreshing partitions [last=" + last + ", now=" + now + ", delta=" + (now - last) +
                    ", timeout=" + timeout + ", lastRefresh=" + lastRefresh + ']');

            refreshPartitions();
        }
        else if (log.isDebugEnabled())
            log.debug("Partitions were not refreshed [last=" + last + ", now=" + now + ", delta=" + (now - last) +
                ", timeout=" + timeout + ", lastRefresh=" + lastRefresh + ']');
    }

    /**
     * @param nodes Nodes.
     * @return {@code True} if message was sent, {@code false} if node left grid.
     */
    private boolean sendAllPartitions(Collection<? extends ClusterNode> nodes) {
        GridDhtPartitionsFullMessage m = new GridDhtPartitionsFullMessage(null, null, AffinityTopologyVersion.NONE);

        for (GridCacheContext cacheCtx : cctx.cacheContexts()) {
            if (!cacheCtx.isLocal() && cacheCtx.started())
                m.addFullPartitionsMap(cacheCtx.cacheId(), cacheCtx.topology().partitionMap(true));
        }

        // It is important that client topologies be added after contexts.
        for (GridClientPartitionTopology top : cctx.exchange().clientTopologies())
            m.addFullPartitionsMap(top.cacheId(), top.partitionMap(true));

        if (log.isDebugEnabled())
            log.debug("Sending all partitions [nodeIds=" + U.nodeIds(nodes) + ", msg=" + m + ']');

        for (ClusterNode node : nodes) {
            try {
                cctx.io().sendNoRetry(node, m, SYSTEM_POOL);
            }
            catch (ClusterTopologyCheckedException ignore) {
                if (log.isDebugEnabled())
                    log.debug("Failed to send partition update to node because it left grid (will ignore) [node=" +
                        node.id() + ", msg=" + m + ']');
            }
            catch (IgniteCheckedException e) {
                U.warn(log, "Failed to send partitions full message [node=" + node + ", err=" + e + ']');
            }
        }

        return true;
    }

    /**
     * @param node Node.
     * @param id ID.
     */
    private void sendLocalPartitions(ClusterNode node, @Nullable GridDhtPartitionExchangeId id) {
        GridDhtPartitionsSingleMessage m = new GridDhtPartitionsSingleMessage(id,
            cctx.kernalContext().clientNode(),
            cctx.versions().last());

        for (GridCacheContext cacheCtx : cctx.cacheContexts()) {
            if (!cacheCtx.isLocal()) {
                GridDhtPartitionMap locMap = cacheCtx.topology().localPartitionMap();

                m.addLocalPartitionMap(cacheCtx.cacheId(), locMap);
            }
        }

        for (GridClientPartitionTopology top : clientTops.values()) {
            GridDhtPartitionMap locMap = top.localPartitionMap();

            m.addLocalPartitionMap(top.cacheId(), locMap);
        }

        if (log.isDebugEnabled())
            log.debug("Sending local partitions [nodeId=" + node.id() + ", msg=" + m + ']');

        try {
            cctx.io().sendNoRetry(node, m, SYSTEM_POOL);
        }
        catch (ClusterTopologyCheckedException ignore) {
            if (log.isDebugEnabled())
                log.debug("Failed to send partition update to node because it left grid (will ignore) [node=" +
                    node.id() + ", msg=" + m + ']');
        }
        catch (IgniteCheckedException e) {
            U.error(log, "Failed to send local partition map to node [node=" + node + ", exchId=" + id + ']', e);
        }
    }

    /**
     * @param nodeId Cause node ID.
     * @param topVer Topology version.
     * @param evt Event type.
     * @return Activity future ID.
     */
    private GridDhtPartitionExchangeId exchangeId(UUID nodeId, AffinityTopologyVersion topVer, int evt) {
        return new GridDhtPartitionExchangeId(nodeId, evt, topVer);
    }

    /**
     * @param exchId Exchange ID.
     * @param discoEvt Discovery event.
     * @param reqs Cache change requests.
     * @return Exchange future.
     */
    GridDhtPartitionsExchangeFuture exchangeFuture(GridDhtPartitionExchangeId exchId,
        @Nullable DiscoveryEvent discoEvt, @Nullable Collection<DynamicCacheChangeRequest> reqs) {
        GridDhtPartitionsExchangeFuture fut;

        GridDhtPartitionsExchangeFuture old = exchFuts.addx(
            fut = new GridDhtPartitionsExchangeFuture(cctx, busyLock, exchId, reqs));

        if (old != null) {
            fut = old;

            if (reqs != null)
                fut.cacheChangeRequests(reqs);
        }

        if (discoEvt != null)
            fut.onEvent(exchId, discoEvt);

        if (stopErr != null)
            fut.onDone(stopErr);

        return fut;
    }

    /**
     * @param exchFut Exchange.
     * @param err Error.
     */
    public void onExchangeDone(GridDhtPartitionsExchangeFuture exchFut, @Nullable Throwable err) {
        AffinityTopologyVersion topVer = exchFut.topologyVersion();

        if (log.isDebugEnabled())
            log.debug("Exchange done [topVer=" + topVer + ", fut=" + exchFut + ", err=" + err + ']');

        if (err == null) {
            while (true) {
                AffinityTopologyVersion readyVer = readyTopVer.get();

                if (readyVer.compareTo(topVer) >= 0)
                    break;

                if (readyTopVer.compareAndSet(readyVer, topVer))
                    break;
            }

            for (Map.Entry<AffinityTopologyVersion, AffinityReadyFuture> entry : readyFuts.entrySet()) {
                if (entry.getKey().compareTo(topVer) <= 0) {
                    if (log.isDebugEnabled())
                        log.debug("Completing created topology ready future " +
                            "[ver=" + topVer + ", fut=" + entry.getValue() + ']');

                    entry.getValue().onDone(topVer);
                }
            }
        }
        else {
            for (Map.Entry<AffinityTopologyVersion, AffinityReadyFuture> entry : readyFuts.entrySet()) {
                if (entry.getKey().compareTo(topVer) <= 0) {
                    if (log.isDebugEnabled())
                        log.debug("Completing created topology ready future with error " +
                            "[ver=" + topVer + ", fut=" + entry.getValue() + ']');

                    entry.getValue().onDone(err);
                }
            }
        }

        ExchangeFutureSet exchFuts0 = exchFuts;

        if (exchFuts0 != null) {
            int skipped = 0;

            for (GridDhtPartitionsExchangeFuture fut : exchFuts0.values()) {
                if (exchFut.exchangeId().topologyVersion().compareTo(fut.exchangeId().topologyVersion()) < 0)
                    continue;

                skipped++;

                if (skipped == EXCH_FUT_CLEANUP_HISTORY_SIZE) {
                    for (GridCacheContext cacheCtx : cctx.cacheContexts()) {
                        if (err == null) {
                            if (!cacheCtx.isLocal())
                                cacheCtx.affinity().cleanUpCache(fut.topologyVersion());
                        }
                    }
                }

                if (skipped > 10)
                    fut.cleanUp();
            }
        }
    }

    /**
     * @param fut Future.
     * @return {@code True} if added.
     */
    private boolean addFuture(GridDhtPartitionsExchangeFuture fut) {
        if (fut.onAdded()) {
            exchWorker.addFuture(fut);

            return true;
        }

        return false;
    }

    /**
     * @param node Node.
     * @param msg Message.
     */
    private void processFullPartitionUpdate(ClusterNode node, GridDhtPartitionsFullMessage msg) {
        if (!enterBusy())
            return;

        try {
            if (msg.exchangeId() == null) {
                if (log.isDebugEnabled())
                    log.debug("Received full partition update [node=" + node.id() + ", msg=" + msg + ']');

                boolean updated = false;

                for (Map.Entry<Integer, GridDhtPartitionFullMap> entry : msg.partitions().entrySet()) {
                    Integer cacheId = entry.getKey();

                    GridCacheContext<K, V> cacheCtx = cctx.cacheContext(cacheId);

                    if (cacheCtx != null && !cacheCtx.started())
                        continue; // Can safely ignore background exchange.

                    GridDhtPartitionTopology top = null;

                    if (cacheCtx == null)
                        top = clientTops.get(cacheId);
                    else if (!cacheCtx.isLocal())
                        top = cacheCtx.topology();

                    if (top != null)
                        updated |= top.update(null, entry.getValue()) != null;
                }

                if (!cctx.kernalContext().clientNode() && updated)
                    refreshPartitions();
            }
            else
                exchangeFuture(msg.exchangeId(), null, null).onReceive(node.id(), msg);
        }
        finally {
            leaveBusy();
        }
    }

    /**
     * @param node Node ID.
     * @param msg Message.
     */
    private void processSinglePartitionUpdate(final ClusterNode node, final GridDhtPartitionsSingleMessage msg) {
        if (!enterBusy())
            return;

        try {
            if (msg.exchangeId() == null) {
                if (log.isDebugEnabled())
                    log.debug("Received local partition update [nodeId=" + node.id() + ", parts=" +
                        msg + ']');

                boolean updated = false;

                for (Map.Entry<Integer, GridDhtPartitionMap> entry : msg.partitions().entrySet()) {
                    Integer cacheId = entry.getKey();

                    GridCacheContext<K, V> cacheCtx = cctx.cacheContext(cacheId);

                    GridDhtPartitionTopology top = null;

                    if (cacheCtx == null)
                        top = clientTops.get(cacheId);
                    else if (!cacheCtx.isLocal())
                        top = cacheCtx.topology();

                    if (top != null)
                        updated |= top.update(null, entry.getValue()) != null;
                }

                if (updated)
                    scheduleResendPartitions();
            }
            else {
                if (msg.client()) {
                    final GridDhtPartitionsExchangeFuture exchFut = exchangeFuture(msg.exchangeId(),
                        null,
                        null);

                    exchFut.listen(new CI1<IgniteInternalFuture<AffinityTopologyVersion>>() {
                        @Override public void apply(IgniteInternalFuture<AffinityTopologyVersion> fut) {
                            // Finished future should reply only to sender client node.
                            exchFut.onReceive(node.id(), msg);
                        }
                    });
                }
                else
                    exchangeFuture(msg.exchangeId(), null, null).onReceive(node.id(), msg);
            }
        }
        finally {
            leaveBusy();
        }
    }

    /**
     * @param node Node ID.
     * @param msg Message.
     */
    private void processSinglePartitionRequest(ClusterNode node, GridDhtPartitionsSingleRequest msg) {
        if (!enterBusy())
            return;

        try {
            sendLocalPartitions(node, msg.exchangeId());
        }
        finally {
            leaveBusy();
        }
    }

    /**
     *
     */
    public void dumpDebugInfo() {
        U.warn(log, "Ready affinity version: " + readyTopVer.get());

        U.warn(log, "Last exchange future: " + lastInitializedFut);

        U.warn(log, "Pending exchange futures:");

        for (GridDhtPartitionsExchangeFuture fut : pendingExchangeFuts)
            U.warn(log, ">>> " + fut);

        ExchangeFutureSet exchFuts = this.exchFuts;

        if (exchFuts != null) {
            U.warn(log, "Last 10 exchange futures (total: " + exchFuts.size() + "):");

            int cnt = 0;

            for (GridDhtPartitionsExchangeFuture fut : exchFuts) {
                U.warn(log, ">>> " + fut);

                if (++cnt == 10)
                    break;
            }
        }

        dumpPendingObjects();
    }

    /**
     *
     */
    public void dumpPendingObjects() {
        IgniteTxManager tm = cctx.tm();

        if (tm != null) {
            U.warn(log, "Pending transactions:");

            for (IgniteInternalTx tx : tm.activeTransactions())
                U.warn(log, ">>> " + tx);
        }

        GridCacheMvccManager mvcc = cctx.mvcc();

        if (mvcc != null) {
            U.warn(log, "Pending explicit locks:");

            for (GridCacheExplicitLockSpan lockSpan : mvcc.activeExplicitLocks())
                U.warn(log, ">>> " + lockSpan);

            U.warn(log, "Pending cache futures:");

            for (GridCacheFuture<?> fut : mvcc.activeFutures())
                U.warn(log, ">>> " + fut);

            U.warn(log, "Pending atomic cache futures:");

            for (GridCacheFuture<?> fut : mvcc.atomicFutures())
                U.warn(log, ">>> " + fut);
        }
    }

    /**
     * @param deque Deque to poll from.
     * @param time Time to wait.
     * @param w Worker.
     * @return Polled item.
     * @throws InterruptedException If interrupted.
     */
    @Nullable private <T> T poll(BlockingQueue<T> deque, long time, GridWorker w) throws InterruptedException {
        assert w != null;

        // There is currently a case where {@code interrupted}
        // flag on a thread gets flipped during stop which causes the pool to hang.  This check
        // will always make sure that interrupted flag gets reset before going into wait conditions.
        // The true fix should actually make sure that interrupted flag does not get reset or that
        // interrupted exception gets propagated. Until we find a real fix, this method should
        // always work to make sure that there is no hanging during stop.
        if (w.isCancelled())
            Thread.currentThread().interrupt();

        return deque.poll(time, MILLISECONDS);
    }

    /**
     * Exchange future thread. All exchanges happen only by one thread and next
     * exchange will not start until previous one completes.
     */
    private class ExchangeWorker extends GridWorker {
        /** Future queue. */
        private final LinkedBlockingDeque<GridDhtPartitionsExchangeFuture> futQ =
            new LinkedBlockingDeque<>();

        /** Busy flag used as performance optimization to stop current preloading. */
        private volatile boolean busy;

        /**
         *
         */
        private ExchangeWorker() {
            super(cctx.gridName(), "partition-exchanger", GridCachePartitionExchangeManager.this.log);
        }

        /**
         * @param exchFut Exchange future.
         */
        void addFuture(GridDhtPartitionsExchangeFuture exchFut) {
            assert exchFut != null;

            if (!exchFut.dummy() || (futQ.isEmpty() && !busy))
                futQ.offer(exchFut);

            if (log.isDebugEnabled())
                log.debug("Added exchange future to exchange worker: " + exchFut);
        }

        /** {@inheritDoc} */
        @Override protected void body() throws InterruptedException, IgniteInterruptedCheckedException {
            long timeout = cctx.gridConfig().getNetworkTimeout();

            boolean startEvtFired = false;

            while (!isCancelled()) {
                GridDhtPartitionsExchangeFuture exchFut = null;

                try {
                    boolean preloadFinished = true;

                    for (GridCacheContext cacheCtx : cctx.cacheContexts()) {
                        preloadFinished &= cacheCtx.preloader().syncFuture().isDone();

                        if (!preloadFinished)
                            break;
                    }

                    // If not first preloading and no more topology events present,
                    // then we periodically refresh partition map.
                    if (!cctx.kernalContext().clientNode() && futQ.isEmpty() && preloadFinished) {
                        refreshPartitions(timeout);

                        timeout = cctx.gridConfig().getNetworkTimeout();
                    }

                    // After workers line up and before preloading starts we initialize all futures.
                    if (log.isDebugEnabled())
                        log.debug("Before waiting for exchange futures [futs" +
                            F.view(exchFuts.values(), F.unfinishedFutures()) + ", worker=" + this + ']');

                    // Take next exchange future.
                    exchFut = poll(futQ, timeout, this);

                    if (exchFut == null)
                        continue; // Main while loop.

                    busy = true;

                    Map<Integer, GridDhtPreloaderAssignments> assignsMap = null;

                    boolean dummyReassign = exchFut.dummyReassign();
                    boolean forcePreload = exchFut.forcePreload();

                    try {
                        if (isCancelled())
                            break;

                        if (!exchFut.dummy() && !exchFut.forcePreload()) {
                            lastInitializedFut = exchFut;

                            exchFut.init();

                            exchFut.get();

                            if (log.isDebugEnabled())
                                log.debug("After waiting for exchange future [exchFut=" + exchFut + ", worker=" +
                                    this + ']');

                            if (exchFut.exchangeId().nodeId().equals(cctx.localNodeId()))
                                lastRefresh.compareAndSet(-1, U.currentTimeMillis());

                            boolean changed = false;

                            // Just pick first worker to do this, so we don't
                            // invoke topology callback more than once for the
                            // same event.
                            for (GridCacheContext cacheCtx : cctx.cacheContexts()) {
                                if (cacheCtx.isLocal())
                                    continue;

                                changed |= cacheCtx.topology().afterExchange(exchFut);

                                // Preload event notification.
                                if (!exchFut.skipPreload() && cacheCtx.events().isRecordable(EVT_CACHE_REBALANCE_STARTED)) {
                                    if (!cacheCtx.isReplicated() || !startEvtFired) {
                                        DiscoveryEvent discoEvt = exchFut.discoveryEvent();

                                        cacheCtx.events().addPreloadEvent(-1, EVT_CACHE_REBALANCE_STARTED,
                                            discoEvt.eventNode(), discoEvt.type(), discoEvt.timestamp());
                                    }
                                }
                            }

                            startEvtFired = true;

                            if (!cctx.kernalContext().clientNode() && changed && futQ.isEmpty())
                                refreshPartitions();
                        }
                        else {
                            if (log.isDebugEnabled())
                                log.debug("Got dummy exchange (will reassign)");

                            if (!dummyReassign) {
                                timeout = 0; // Force refresh.

                                continue;
                            }
                        }

                        if (!exchFut.skipPreload()) {
                            assignsMap = new HashMap<>();

                            for (GridCacheContext cacheCtx : cctx.cacheContexts()) {
                                long delay = cacheCtx.config().getRebalanceDelay();

                                GridDhtPreloaderAssignments assigns = null;

                                // Don't delay for dummy reassigns to avoid infinite recursion.
                                if (delay == 0 || forcePreload)
                                    assigns = cacheCtx.preloader().assign(exchFut);

                                assignsMap.put(cacheCtx.cacheId(), assigns);
                            }
                        }
                    }
                    finally {
                        // Must flip busy flag before assignments are given to demand workers.
                        busy = false;
                    }

                    if (assignsMap != null) {
                        for (Map.Entry<Integer, GridDhtPreloaderAssignments> e : assignsMap.entrySet()) {
                            int cacheId = e.getKey();

                            GridCacheContext<K, V> cacheCtx = cctx.cacheContext(cacheId);

                            cacheCtx.preloader().addAssignments(e.getValue(), forcePreload);
                        }
                    }
                }
                catch (IgniteInterruptedCheckedException e) {
                    throw e;
                }
                catch (IgniteClientDisconnectedCheckedException e) {
                    return;
                }
                catch (IgniteCheckedException e) {
                    U.error(log, "Failed to wait for completion of partition map exchange " +
                        "(preloading will not start): " + exchFut, e);
                }
            }
        }

        /**
         * @return {@code True} if another exchange future has been queued up.
         */
        boolean topologyChanged() {
            return !futQ.isEmpty() || busy;
        }
    }

    /**
     * Partition resend timeout object.
     */
    private class ResendTimeoutObject implements GridTimeoutObject {
        /** Timeout ID. */
        private final IgniteUuid timeoutId = IgniteUuid.randomUuid();

        /** Timeout start time. */
        private final long createTime = U.currentTimeMillis();

        /** Started flag. */
        private AtomicBoolean started = new AtomicBoolean();

        /** {@inheritDoc} */
        @Override public IgniteUuid timeoutId() {
            return timeoutId;
        }

        /** {@inheritDoc} */
        @Override public long endTime() {
            return createTime + partResendTimeout;
        }

        /** {@inheritDoc} */
        @Override public void onTimeout() {
            cctx.kernalContext().closure().runLocalSafe(new Runnable() {
                @Override public void run() {
                    if (!busyLock.readLock().tryLock())
                        return;

                    try {
                        if (started.compareAndSet(false, true))
                            refreshPartitions();
                    }
                    finally {
                        busyLock.readLock().unlock();

                        cctx.time().removeTimeoutObject(ResendTimeoutObject.this);

                        pendingResend.compareAndSet(ResendTimeoutObject.this, null);
                    }
                }
            });
        }

        /**
         * @return {@code True} if timeout object started to run.
         */
        public boolean started() {
            return started.get();
        }
    }

    /**
     *
     */
    private static class ExchangeFutureSet extends GridListSet<GridDhtPartitionsExchangeFuture> {
        /** */
        private static final long serialVersionUID = 0L;

        /**
         * Creates ordered, not strict list set.
         */
        private ExchangeFutureSet() {
            super(new Comparator<GridDhtPartitionsExchangeFuture>() {
                @Override public int compare(
                    GridDhtPartitionsExchangeFuture f1,
                    GridDhtPartitionsExchangeFuture f2
                ) {
                    AffinityTopologyVersion t1 = f1.exchangeId().topologyVersion();
                    AffinityTopologyVersion t2 = f2.exchangeId().topologyVersion();

                    assert t1.topologyVersion() > 0;
                    assert t2.topologyVersion() > 0;

                    // Reverse order.
                    return t2.compareTo(t1);
                }
            }, /*not strict*/false);
        }

        /**
         * @param fut Future to add.
         * @return {@code True} if added.
         */
        @Override public synchronized GridDhtPartitionsExchangeFuture addx(
            GridDhtPartitionsExchangeFuture fut) {
            GridDhtPartitionsExchangeFuture cur = super.addx(fut);

            while (size() > EXCHANGE_HISTORY_SIZE)
                removeLast();

            // Return the value in the set.
            return cur == null ? fut : cur;
        }

        /** {@inheritDoc} */
        @Nullable @Override public synchronized GridDhtPartitionsExchangeFuture removex(
            GridDhtPartitionsExchangeFuture val
        ) {
            return super.removex(val);
        }

        /**
         * @return Values.
         */
        @Override public synchronized List<GridDhtPartitionsExchangeFuture> values() {
            return super.values();
        }

        /** {@inheritDoc} */
        @Override public synchronized String toString() {
            return S.toString(ExchangeFutureSet.class, this, super.toString());
        }
    }

    /**
     *
     */
    private abstract class MessageHandler<M> implements IgniteBiInClosure<UUID, M> {
        /** */
        private static final long serialVersionUID = 0L;

        /** {@inheritDoc} */
        @Override public void apply(UUID nodeId, M msg) {
            ClusterNode node = cctx.node(nodeId);

            if (node == null) {
                if (log.isDebugEnabled())
                    log.debug("Received message from failed node [node=" + nodeId + ", msg=" + msg + ']');

                return;
            }

            if (log.isDebugEnabled())
                log.debug("Received message from node [node=" + nodeId + ", msg=" + msg + ']');

            onMessage(node , msg);
        }

        /**
         * @param node Node.
         * @param msg Message.
         */
        protected abstract void onMessage(ClusterNode node, M msg);
    }

    /**
     * Affinity ready future.
     */
    private class AffinityReadyFuture extends GridFutureAdapter<AffinityTopologyVersion> {
        /** */
        private static final long serialVersionUID = 0L;

        /** */
        @GridToStringInclude
        private AffinityTopologyVersion topVer;

        /**
         * @param topVer Topology version.
         */
        private AffinityReadyFuture(AffinityTopologyVersion topVer) {
            this.topVer = topVer;
        }

        /** {@inheritDoc} */
        @Override public boolean onDone(AffinityTopologyVersion res, @Nullable Throwable err) {
            assert res != null || err != null;

            boolean done = super.onDone(res, err);

            if (done)
                readyFuts.remove(topVer, this);

            return done;
        }

        /** {@inheritDoc} */
        @Override public String toString() {
            return S.toString(AffinityReadyFuture.class, this, super.toString());
        }
    }
}

redpajama_set_name: RedPajamaGithub


The Bodum Bistro Blade Grinder grinds coffee beans from coarse to fine quickly and efficiently for fresh brewing. This compact grinder (height 16,5 cm) is well suited for coffee brewers and press pots.
The grinder is easy to use - just add the beans and keep the push button pressed until desired grinding coarseness has been achieved. You can follow the grinding through the transparent lid. The strong, durable stainless steel cutting blades spin at a precise RPM.
If you are looking for a small, simple to use coffee grinder for your brewer or press pot, you have found what you are looking for. Prepare to enjoy your coffee freshly ground and brewed!


There are two types of momentum, linear momentum and angular momentum. The SAT Subject Test in Physics is restricted to problems involving linear momentum, the momentum of objects moving in a straight-line path.
Linear momentum is the product of the mass and velocity of an object.
Momentum has units of kilograms • meters per second. Momentum is related to the inertia of a moving object. The greater the momentum of a moving object, the more difficult the object is to stop. Momentum is a vector quantity. The direction of the momentum vector is the same as the direction of the velocity of the object.
Many problems involve a system (more than one object) moving simultaneously. The total momentum of a system can be found by adding the individual momentums of all the objects making up the system.
Note that momentum and velocity are both vector quantities. Vector direction for one-dimensional motion can be annotated with a positive or a negative sign as shown in the formula below.
By adding plus and minus signs, the vector velocity, v, becomes a scalarlike quantity, v, allowing simple addition. You must note the direction of velocity and add the correct sign when solving a problem for momentum.
Impulse is a force that is applied to an object over a period of time. A kick or a shove would be considered an impulse.
From this equation, the units of impulse will be newton • seconds (N • s). This is also equivalent to the units of momentum, kg • m/s. Both momentum and impulse can be expressed in either of these units. Impulse is a vector quantity, and the impulse vector points in the direction of the force acting on the object.
When analyzing the equation for impulse, it is apparent that if the duration of a collision can be lengthened, the force of the impact can be lessened. For example, air bags in an automobile are designed to increase the amount of time needed for a passenger to come to a complete stop, thereby decreasing the force exerted on the passenger during a collision.
When an impulse acts on an object, the momentum of the object will change. Note that impulse does not equal momentum even though their units are the same. Impulse causes and is equal to the change in the momentum of an object. Impulse is similar to work (discussed in the previous chapter) in that they both create a change. Work changes the energy of a mass, and impulse changes the momentum of a mass. Impulse and work are both processes of change, while momentum and energy are both state functions.
(A) Determine the change in momentum (impulse) for a 0.5-kilogram lump of clay striking a wail at 15 meters per second.
The lump of clay will stick to the wall, and come to a stop.
The negative sign in the answer indicates that the change in momentum is opposite the initial velocity. The minus sign may not appear in the available answer choices since problems of this type are often concerned with just the value.
(B) Determine the change in momentum (impulse) for a 0.5-kilogram rubber ball striking a wall at 15 meters per second and bouncing off the wall in the opposite direction.
The rubber ball will bounce off of the wall. Unless told otherwise, assume that the final speed of the ball leaving the wall is the same as the initial speed of the ball.
Note the minus sign on the final velocity of the ball. Set the initial velocity as positive. Since the ball reversed direction during the bounce, the final velocity is in the opposite direction and it must have the opposite sign.
The change in momentum (impulse) for an object that bounces with no loss in speed is twice as large as the change in momentum for an object coming to a stop.
Impulse is equal to the area under a force versus time function. The graph in Figure 8.1(a) left is an example of the impulse delivered to a soccer ball when the ball is kicked. However, this graph will probably appear in the simplified form of Figure 8.1(b) to allow you to calculate the area under the function with ease.
The most challenging problems may require you to set one formula for impulse equal to another.
The above graph illustrates the force acting on a 0.20-kilogram soccer ball as it is kicked. Determine the final speed of the ball.
A force-time graph indicates that this problem involves impulse. You can solve an impulse problem in many possible ways.
You need a method that lets you use the graph to solve for speed. The above formula can be simplified to include speed and the area of a triangle.


text:
Commerce issues plan to reorganize technology agencies
The Commerce Department on Thursday proposed legislation that would reorganize the department's technology and telecommunications policy functions. The proposal would consolidate the Technology Administration, National Telecommunications and Information Administration, National Institute of Standards and Technology and the e-commerce policy functions of the International Trade Administration. The plan requests slightly more than $8 million for the new agency. "This bill modifies and modernizes the organizational structure of the Department of Commerce to enhance the formulation of technology, electronic commerce and telecommunications policy issues," Commerce Secretary Donald Evans said in a letter accompanying the draft. Full Story

redpajama_set_name: RedPajamaCommonCrawl


A long pendant with black elements and green ribbon.
Beautiful and different accessory for every day.
Cheap jewellery online in the get-first jewellery area.
Place an order for 100.00лв. + Buy Long pendant or other a product from our Promo Selection to get free shipping.


text:
Dionisio de Jésus "Chucho" Valdés Rodríguez (* 9. Oktober 1941 in Havanna, Kuba) ist ein kubanischer Pianist und Komponist des Latin- und Modern Jazz, der an Verbindungen der kubanischen Musik mit anderen Musikgenres arbeitet. Er ist einer der bekanntesten kubanischen Jazzmusiker.

Leben und Wirken
Valdés entstammt einer Pianistenfamilie: Bebo Valdés war sein Vater; seine Mutter Pilar Rodríguez ist gleichfalls Pianistin, ebenso wie sein Sohn Chuchito Valdés. Er begann mit dem Pianospiel im Alter von drei Jahren und bestand 1950 die Aufnahmeprüfung für das Konservatorium in Havanna. Als Jugendlicher spielte er in der Hausband des Club Tropicana, deren musikalischer Leiter er wurde. Mit 16 war er schon Kopf einer eigenen Gruppe. Ab 1963 spielte er mit Arturo Sandoval und Paquito D'Rivera, mit denen er 1967 das Orquesta Cubana de Música Moderna gründete. Mit diesem Ensemble führte er eigene Kompositionen wie seine "Misa Negra" (1969) auf. 1970 trat er auf dem Jazz Jamboree in Warschau auf. Mit Sandoval und D'Rivera gründete er 1973 die Gruppe Irakere, die 1978 auf dem Jazz Festival Montreux und dem Newport Jazz Festival auftrat. Valdés, der Hauptkomponist der Gruppe, leitete diese auch nach dem Ausscheiden von Sandoval und D'Rivera weiter. Nachdem er einen Vertrag bei Blue Note Records erhalten hatte, konzentrierte er seine Auftritte und Aufnahmen auf Quartett-, Trio- und Soloprojekte. Daneben wirkte er als Sideman bei Roy Hargrove. Die Leitung von Irakere gab er 1998 an seinen Sohn Francisco ab. 2009 formierte er die fünfköpfige Band The Afro-Cuban Messengers, mit denen er seitdem die Alben Chucho's Steps (2010) und Border-Free (2013) produziert und internationale Konzertreisen unternommen hat.

Valdés fungierte von 1992 bis 2009 als Präsident des jährlichen Festivals Jazz Plaza in Havanna. Er ist Professor und Leiter der Klavierabteilung des Instituto Superior de Arte. Weiterhin unterrichtet er an der Escuela Nacional de Arte Kubas, aber auch am Berklee College of Music.

Valdés veröffentlichte bislang 31 Platten, von denen fünf mit Grammy-Awards ausgezeichnet wurden. Er verfügt über ein sehr kraftvolles, phrasierungsreiches Spiel, in das er lateinamerikanische Harmonik und afroamerikanische Rhythmik einfließen lässt.

Er ist Ehrenbürger von Ponce (Puerto Rico), Panama-Stadt sowie der US-amerikanischen Städte Los Angeles, San Francisco und New Orleans. Der Stadtrat von Madison (Wisconsin) ehrte ihn 2001 mit einem offiziellen "Jesús-Chucho-Valdés-Tag". 2011 verlieh ihm das Berklee College of Music die Ehrendoktorwürde.

Politisches Engagement
Auf kulturpolitischer Ebene kämpfte Valdés nach eigener Aussage gegen das von den kubanischen Behörden verfügte Verbot der Musik seines exilierten Vaters Bebo, das er als "frustrierend" empfunden habe. Bereits 2009 äußerte sich Valdés in einem Interview mit der spanischen Tageszeitung El País empört, dass die kubanischen Medien zwar über die Auszeichnung des gemeinsamen Albums Juntos para siempre mit dem Latin Grammy berichtet, dabei jedoch den Namen des Vaters unerwähnt gelassen hatten.

Valdés gehört als eines von 26 ständigen Mitgliedern zum nationalen Vorstand des staatlichen kubanischen Künstler- und Schriftstellerverbands UNEAC.

Diskografie (Auswahl)

 1978 – Live at Newport
 1986 – Lucumí
 1991 – Solo Piano
 1995 – Grandes de La Música Cubana, Vol. 1
 1997 – Pianissimo
 1998 – Bele Bele en La Habana
 1999 – Babalú Ayé
 1999 – Briyumba Palo Congo
 2000 – Boleros Inigualables
 2000 – Cuban Jazz Pianissimo
 2000 – Live at the Village Vanguard
 2000 – Unforgettable Boleros
 2001 – Chucho Valdés y su Cuban Jazz
 2001 – Solo: Live in New York
 2002 – Canciones Inéditas
 2002 – Cantata a Babalú Ayé
 2002 – Fantasía Cubana: Variations on Classical Themes
 2002 – Yemayá
 2003 – New Conceptions
 2005 – Canciones Ineditas
 2005 – Virtuoso
 2007 – Cancionero Cubano
 2008 – Juntos Para Siempre (mit Bebo Valdés)
 2010 – Chucho's Steps (Grammy 2011)
 2012 – Piano y charango con Eddy Navia
 2013 – Border-Free
 2015 – Tribute to Irakere: Live in Marciac (Grammy 2017)

Lexigraphischer Eintrag
 Martin Kunzler: Jazz-Lexikon. Band 2: M–Z (= rororo-Sachbuch. Bd. 16513). 2. Auflage. Rowohlt, Reinbek bei Hamburg 2004, ISBN 3-499-16513-9.

Siehe auch
 Kubanische Musik

Weblinks

 Webpräsenz mit Diskographie (englisch, spanisch)
 Besprechung des Soloalbums von 1998

Einzelnachweise

Jazz-Pianist
Komponist (Jazz)
Hochschullehrer (Instituto Superior de Arte)
Hochschullehrer (Escuela Nacional de Arte)
Hochschullehrer (Berklee College of Music)
Ehrenbürger von New Orleans
Ehrenbürger von San Francisco
Grammy-Preisträger
Ehrenbürger von Los Angeles
Ehrenbürger in Puerto Rico
Person (Ponce, Puerto Rico)
Kubaner
Geboren 1941
Mann

redpajama_set_name: RedPajamaWikipedia


text:
Posted on Saturday, September 6, 2014 Saturday, September 6, 2014
by Sona Charaipotra
Randy Susan Meyers On "Shots of Joy" + GIVEAWAY of Accidents of Marriage
Please welcome Randy Susan Meyers to the Ball this week! I met the brilliant — and lovely! — Randy Sue Meyers at a conference a few years ago, where she was sharing her wise words and marketing experience with a roomful of authors who fretted over marketing. I also picked up the fabulous marketing how-to guide she co-wrote with MJ Rose, What to Do Before Your Book Launch — and definitely recommend it to debut authors!
Her latest — after Comfort of Lies and The Murderer's Daughters — is Accidents of Marriage, a stunning domestic drama about a family on the edge. The Star Tribune called the book "a deft exploration of the borders of abuse and the aftermath of tragedy, the triumphs and disappointments of recovery, and the possibilities of faith and forgiveness."
Randy Susan stopped by — and borrowed a tiara — to take the Deb Interview, chatting about the childhood read that inspired her, her uber-twisty publishing path, and a little idea she has called "shots of joy." Read on for more!
Talk about one book that made an impact on you.
"The library was a little old shabby place. Francie thought it was beautiful. The feeling she had about it was as good as the feeling she had about church." A Tree Grows in Brooklyn, by Betty Smith
Some books etch themselves on your soul. I don't remember how old I was when I first read A Tree Grows in Brooklyn. Perhaps eleven? (Francie's age when the book begins.) How many times did I read it after that? Ten? Twenty? Enough so that every scene, every character indelibly marked me.
I never visited a church or synagogue when I grew up Jewish in Brooklyn, but like Francie Nolan, I worshipped at the altar of the library. From Francie, the protagonist in coming-of-age novel, I learned that I wasn't the only frightened, confused, and unhappy little girl in the world.
A Tree Grows In Brooklyn by Betty Smith was the only bible I ever owned, my personal talisman of hopefulness — perhaps because similar to bookish Francie (though in different times; published in 1943, the story opens in 1912.) I grew up confused by my always-working mother and missing my father. He, like Francie's, ran from life by what we now call self-medicating (and what Francie's mother and mine, called nothing, because who talked about it in Brooklyn?) And then he, like Francie's escaped forever by dying as a young man.
Like Francie, I'd experienced the horror of old men preying on young girls, the joy of having an aunt I'd worshipped, and suffered in a school I hated. Each time I read Francie's story I was struck anew by how the author knew so much and dared to write it.
That's the beauty of books. They don't just transport, they heal, teach, and soothe. On the loneliest of days, they ask no more than being opened. They promise you're not alone and provide you with the hope of a way out. The best ones don't guarantee the happiest ending in the world (for who has that?) but show that you have the possibility of enduring (and maybe even thriving) and becoming strong at the broken places.
Perhaps all insatiable readers become imprinted by a one special book at a vulnerable age, providing that reader with characters who forever become family of the heart. Because of brave Francie Nolan, I believed I could and would survive. She gave me faith in the future. Bless you, Betty Smith. You are forever my favorite author.
What's your secret or not-so-secret superpower?
I love to find one special thing about everyone I meet—whether that be a stunning smile, an outstanding tie, or a haircut that rises up the hair crowd—and then I get huge pleasure from telling them about it whenever I can. There's something wonderful about bringing a shot of joy.
The road to publication is twisty at best–tell us about some of your twists.
Twisty? Oh yes. You got some time?
My published-too-young book: In my twenties, I co-wrote a nonfiction book (under my former—married—name, Randy Meyers Wolfson) Couples With Children. Co-author Virginia DeLuca and I, in our work with pregnant and post-partum women, saw that suddenly shaky marriages were of more concern than diapers. And we wanted to write. We bought How to Get Happily Published by Judith Applebaum, wrote a proposal and a sample chapter, sent it off and shortly thereafter had a contract. I won't go into the many mistakes we made after that (the only thing we did right was selling the book) but this 'easy' sell offered (extraordinarily) undeserved confidence.
Soon after, I got divorced. Now I was a single mother and talking about marriage and children seemed, um… embarrassing to say the least. And fiction was really my love. The nonfiction Couples With Children was left to languish.
In between raising kids, badly-chosen men, working in human services by day, and bartending by night, I co-wrote Novels 1 & 2 with Ginny: Two mysteries. Got an agent. We thought we had a series. Didn't sell books.
Moving on, still submerged in bad men and fantasy, still not applying myself to learning the deeper tenets of writing fiction, and skating on sheer want, I wrote Novel 3, which should have been titled: The Book That Helped Me Pretend I Wasn't Screwing Up, My Life By Mythologizing It.
No agent. No sale. No memory if I wrote a query. Probably not, because a friend insisted on sending it to his wife's cousin-the-writer, who called it… execrable? Deplorable? Tripe? He didn't soften the slam by deeming it poetic or lyrical. Because it wasn't.
Got depressed.
Had a drink or ten.
Thank goodness I had that inappropriate guy to lean on!
Fast forward: Sent kids through college. Lost bad guy/s. Found good one. Got serious about writing. Embarked on my homemade MFA and wrote my trilogy:
Novel 4: Dove in. Joined a writer's group. Finished. Got an agent. As soon as she put it out for submission, I began writing:
Novel 5: Showed it to said agent. She liked it so much that she replaced the now-limping and ten-times rejected # 4 (are you still with me) with newly minted # 5. And I began writing:
Novel 6: Showed a bit to agent. She loved it. Said keep going! Meanwhile, she kept trotting out #5 to a few editors.
Then my agent turned more attention to representing a different genreand it seemed right for us to part ways. Leaving this agent was wrenching. The 'bird in the hand' theory pulled, but I felt a sweet spot with # 6, and felt that I needed the right person to represent it (aware many would find it dark.)
No hard feelings, a virtual handshake goodbye, and agent and I said goodbye.
Back out on the agent-hunting circuit, feeling like a confused divorcee. (Do I talk about the ex? Pretend it never happened?)
Six months later I signed with new (wonderful and current) agent. She read. She edited. I revised. She sold #6 (The Murderer's Daughters) in 8 days.
How long did it take to sell my debut novel from when I began writing fiction? 20+ years. Six novels. Three agents.
DebNote: Phew! We're exhausted just reading that!
Do you have any phobias?
I'm terrified of driving on the highway. Fine on city streets, fine on meandering roadways, but keep me away from any roads that require exiting and merging.
What's the strangest job you ever had?
For a mercifully short time, while in college, I worked in a tie-dye factory where I twisted wet sheets and tied them up with giant rubber bands.
Readers, what's the strangest job you've ever had?
GIVEAWAY! Comment on this post by noon EST on Friday, Sept. 12th, to enter to win a copy of Accidents of Marriage (U.S. only, please) — and Randy will sign and send along a book plate, too! Follow The Debutante Ball on Facebook and Twitter for extra entries—just mention that you did so in your comments. We'll choose and contact the winner on Friday. Good luck!
About Randy:
Randy Susan Meyers' novels are informed by her work with families impacted by emotional and family violence. Her debut novel, The Murderer's Daughters, was named one of the "2011 Ten Best Works of Fiction" by the Massachusetts Center for the Book. Her newest novel, Accidents of Marriage, is called "both unputdownable and unforgettable," by author Liane Moriarty. The Boston Globe wrote of her second novel, "The Comfort of Lies" "sharp and biting, and sometimes wickedly funny when the author skewers Boston's class and neighborhood dividing lines, but it has a lot of heart, too." Meyers teaches writing at Grub Street Writers Center. She is the mother of two grown daughters and lives in Boston with her husband.
Posted in Contest, Debutante Ball, Guest Author, The Deb InterviewTagged Accidents of Marriage, book giveaway, Free Book Giveaway, Randy Sue Meyers, The Murder's Daughters
Author: Sona Charaipotra
An entertainment and lifestyle journalist published by The New York Times, People, ABC News, MSN, Cosmopolitan and other major national media, SONA CHARAIPOTRA currently curates a kickass column on YA books and teen culture for Parade.com. A collector of presumably useless degrees, she double-majored in journalism and American Studies at Rutgers before getting her masters in screenwriting from New York University (where her thesis project was developed for the screen by MTV Films) and her MFA from the New School. When she's not hanging out with her writer husband and two chatter-boxy kids, she can be found poking plot holes in teen shows like Twisted and Vampire Diaries. But call it research: Sona is the co-founder of CAKE Literary, a boutique book development company with a decidedly diverse bent. Her debut, the YA dance drama Tiny Pretty Things (co-written with Dhonielle Clayton), is due May 26 from HarperTeen. Find her on the web at SonaCharaipotra.com or CAKELiterary.com. View all posts by Sona Charaipotra
Prev Some stories just need to be told
Next News Flash: Book launches, Copyedits, Pitch contests, and new additions!
8 Replies to "Randy Susan Meyers On "Shots of Joy" + GIVEAWAY of Accidents of Marriage"
Laura Kay says:
Saturday, September 6, 2014 at 11:04 am
Is it wrong that I relish when I find others who share in my highway phobia? Great interview! I love Randy's books and look forward to this one!
Welcome all the new Debs! I look forward to getting to know you all better 🙂
Lisa Alber says:
Saturday, September 6, 2014 at 1:27 pm
Great interview, Sona and Randy! So glad to meet you here, Randy, and Sona, great job as guest wrangler! 🙂
Ooohh. I love a family drama…especially when it isn't mine. 🙂 And I loved The Comfort of Lies.
Karma says:
Sunday, September 7, 2014 at 6:54 am
I love reading about the twists and turns — we all have them! And while I occasionally wish I was publishing my debut novel at 23, I'm generally glad I have some (many) more years of life experience behind me for this milestone 🙂 Great to "meet" you, Randy, and looking forward to reading!
Sherri Foster says:
Monday, September 8, 2014 at 12:41 pm
I love Randy Susan Myers novels! Thanks to this novel I learned a couple of things about her I did not know. Thank you for writing this interview!
elaina says:
Thursday, September 11, 2014 at 6:18 pm
A very interesting and enlightening interview. This novel sounds captivating and intriguing. I have had many difficult,unpleasant jobs which I prefer to forget but were drudgery at the time. Best wishes and great happiness and success.
Books soothe my soul, warm my heart and allow me to escape, dream and hope. When I was sick reading was my solace. A Tree Grows in Brooklyn was memorable, meaningful and profound. Libraries provided me with peace for hours on end and this was where I learned about so much, travel,kingdoms, history and art. I still visit libraries since they are invaluable.
Friday, September 12, 2014 at 8:27 am
Great Interview. Can't wait to read Accidents of Marriage. Thank you for taking the time for this post.


Pop legend and former Take That singer Robbie Williams has opened up about the guilt he feels for 'crushing' his wife Ayda's hopes of having another child.
The couple, who married in August 2010, have two children already together. Their daughter Theodora, aged four, was born in 2012, and their son Charlton, born in 2014, is just two-years-old.
After the birth of his son two years ago, Robbie Williams put his music career on hold in order to focus on family life.
Due to his very low testosterone level, Robbie has previously revealed that he had his sperm cryogenically frozen in LA to ensure that the couple could have a family.
However, despite the steps he took to ensure that he and Ayda could expand to their family, and the fact that he has embraced family life, Robbie has now admitted that despite Ayda's desires to add to their brood, he doesn't want any more children.
'I don't want another one,' the 43-year-old told The Sunday Times Magazine. But the decision has not been an easy one as the father-of-two has admitted how guilty he feels for 'crushing Ayda's hopes' of having more children.
So, might Robbie relent and consider adding to their family of four? 'On a good day, in a tender moment, I would like to see another bom-bom running about,' he admitted.


text:
Q: How Can I List Infinite Nested Categories on Asp.NET MVC? I want to make nested categories.. Like;
Category 1
   Sub Category 1.1
      Sub Category 1.1.1
         ..
            Sub Category 1.1.1.1.1.1.1.1
Category 2
   Sub Category 2.1
   Sub Category 2.2
      Sub Categry 2.2.1
Category 3

My database shcema;

My ViewModel;
public class CategoriesViewModel
    {
        public CategoriesViewModel()
        {
            AltGroup = new List<CategoriesViewModel>();
        }

        public int CategoryID { get; set; }
        public string CategoryName { get; set; }
        public List<CategoriesViewModel> SubCategories{ get; set; }
    }

My function;
private List<CategoriesViewModel> GenerateSub(List<Categories> categories)
        {
            List<CategoriesViewModel> categories= new List<CategoriesViewModel>();

            foreach (var child in categories)
            {
                var subCategories = GenerateChildren(child.Categories1.ToList());
                subCategories.Add(new CategoriesViewModel{ CategoryName = child.RoleGroupAdi, SubCategories= subCategories });
            }

            return subCategories;
        }

My controller file;
private DbEntities db = new DbEntities();
public ActionResult KullaniciYetkiGuncelle(int id = 0)
        {
            ViewModel vm = new ViewModdel();
            vm.categories = GenerateSub(db.Categories.ToList());
            return View(vm);
        }

My view (I have to change it I know);
@foreach (var item in Model.categories)
{
    @item.CategoryName

    foreach (var item2 in item.SubCategories)
    {
        @item2.CategoryName

        foreach (var item3 in item2.SubCategories)
        {
            @item3.CategoryName

        }
    }
}

And result; FALSE LISTING
Sub Category 1.1
Category 1
   Sub Category 1.1
   Sub Category 1.2
      Sub Category 1.2.1
      Sub Category 1.2.2
      Sub Category 1.2.3
Sub Category 1.2
   Sub Category 1.2.1
   Sub Category 1.2.2
   Sub Category 1.2.3
Sub Category 1.2.1
Sub Category 1.2.2
Sub Category 1.2.3

But it must be; TRUE LISTING
Category 1
   Sub Category 1.1
   Sub Category 1.2
      Sub Category 1.2.1
      Sub Category 1.2.2
      Sub Category 1.2.3

I make mistake but I cant find and I don't have any idea about View.

A: You need to make it a function, and call it recursively:
@helper PrintCategories(dynamic categories)
{
    foreach (var item in categories)
    {
        @item.CategoryName

        var subCategories = item.SubCategories;
        if (subCategories != null && subCategories.Count > 0)
        {
            PrintCategories(subCategories);
        }
    }
}

@PrintCategories(Model.categories)

A: I found the solution myself:
When I add .Where(x => x.ParentCategoryID == null), it returns the right list.
According to that, the controller becomes:
private DbEntities db = new DbEntities();
public ActionResult KullaniciYetkiGuncelle(int id = 0)
{
     var vm = new ViewModdel();
     vm.categories = GenerateSub(db.Categories.Where(x=>x.ParentCategoryID == null).ToList());
     return View(vm);
}

For View;
Check the checked answer..

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find list of indexes of all databases using PyMongo? I am new to python and I am using python 2.6. I wrote a script to fetch all collections from MongoDB databases, Now I am trying to find indexes also using the same script
Here's the code snippet which fetches collections from all DB's
import pymongo
import json

if __name__ == '__main__':
    client = pymongo.MongoClient("localhost", 27011, maxPoolSize=50)
    d = dict((db, [collection for collection in client[db].collection_names()])
             for db in client.database_names())
    print json.dumps(d)

and I want to integrate following MongoDB command into the script which will list all indexes present in DB
db.getCollectionNames().forEach(function(collection){indexes = db[collection].getIndexes();print(collection);printjson(indexes.length);indexes.forEach(function(item){print(item.name);});});

How can I achieve that in the script


text:
LA Times publisher faces calls to step down amid misconduct accusations
By Avery Anapol - 01/19/18 10:13 AM EST
Employees at the Los Angeles Times are reportedly calling for CEO and publisher Ross Levinsohn to resign or be fired following an explosive report detailing his inappropriate behavior at several media companies.
NPR reported on Thursday that Levinsohn has been a defendant in two separate sexual harassment lawsuits while at separate companies before joining the Times in August.
The paper's unionizing committee issued a statement calling for Levinsohn to "resign or be fired immediately," according to BuzzFeed.
"A man who sexually harasses women, engages in 'slut-shaming' and refers to gay men as 'fags' is not fit to lead our newspaper," the statement read.
Levinsohn, NPR reported, used the slur to describe gay members of the fashion industry. In his own testimony, NPR found that Levinsohn admitted to ranking female employees by "hotness" and speculating aloud if a female employee was working as a stripper and engaging in sexual encounters with a co-worker.
Times reporters told BuzzFeed that members of the newsroom were in "shock" over the allegations and wanted Levinsohn to step down or be fired.
"It's extraordinarily troubling," one reporter said, adding, "If [the paper's parent company] Tronc keeps him, there will be a lot of serious questions they'll have to answer because we're already asking them."
Some reporters expressed their concern on Twitter.
"Ross Levinsohn should resign or be fired immediately. A man who sexually harasses women, engages in 'slut-shaming' and refers to gay men as 'fags' is not fit to lead our newspaper."
Here's the full statement from the @latguild: https://t.co/NfuxIUi2Be
— Laura J. Nelson (@laura_nelson) January 18, 2018
As a gay journalist, I'm sad and frustrated that my publisher would refer to members of the LGBTQ community as "fags." It's homophobic. It has had no place in polite discourse for many decades. This is not OK. 1/?https://t.co/5hnJtm5ZYl
— Anthony Pesce (@anthonyjpesce) January 18, 2018
Using the word "fag" to describe the LGBTQ community isn't something that was or is currently right.
I'm more than disappointed as an openly gay, brown journalist at The Times.
This is not OK. https://t.co/ppU31Yl7lR pic.twitter.com/jW1Np6O432
— Brian De Los Santos (@bdelossantos1) January 18, 2018
Tronc, the Times's parent company, said in a statement to NPR that they are immediately investigating the allegations following NPR's report. Levinsohn pushed back on the report, calling the allegations "lies" and threatening to retain legal counsel.
Former colleagues and employees of Levinsohn told NPR that Levinsohn had created a "frat house environment."
Levinsohn has been an executive at several high-profile media companies before joining the Times, including CBS, News Corp., Yahoo and search engine company Alta Vista, where he was the focus of one of the sexual harassment cases.
Tags misogyny Bullying Sex crimes Sexual assault Sexual harassment Sexual misconduct


text:
Cloudy. A few flurries or snow showers possible. High 16F. Winds NW at 5 to 10 mph..
File Photo Cal-Mum's Kyle Wade.
Provided | Batavia/Attica's Casper Stewart.
Photo credit: Kristin Smith | Oakfield-Alabama's Gaige Armbrewster.
Photo credit: LeRoy_Knights Le Roy's Mitch Hockey had a huge performance as the Oatkan Knights won the Batavia Lions Club Tournament.
Lindsey Meys Photography | Livonia's Kylie Buckley.
Alex Brasky/Batavia Daily News | Elba's C.J. Gottler.
Alex Brasky/Batavia Daily News | JBatavia's Javin McFollins.
ATHLETES OF THE WEEK: Top local performances from the week of Dec. 27-30
Here are the Batavia Daily News/Livingston County News Winter Athletes of the Week for the weeks of Dec. 27-30.
Each athlete was selected based off of submitted statistical information by coaches. If you don't see an athlete's name and performance listed and you believe it should be, please ask that team's coach to reach out to sports@batavianews.com.
Kaden Cusmano - Oakfield-Alabama Boys Basketball - Recorded 20 points to go with 11 rebounds and three blocks in a win over Notre Dame on Dec. 30. Also scored
Kameron Cusmano - Oakfield-Alabama Boys Basketball - Netted 18 points, grabbed 11 rebounds and doled out four assists in a win over Notre Dame on Dec. 30.
Gaige Armbrewster - Oakfield-Alabama Boys Basketball - Scored a team-high 20 points to go with 11 rebounds, six assists and four steals in a win over Elba on Dec. 28. Also scored 11 points, dished out 10 assists and secured 10 rebounds in a win over Notre Dame on Dec. 30.
C.J. Gottler - Elba Boys Basketball - Contributed 25 points in a loss to Oakfield-Alabama on Dec. 28. Also scored 14 points in a win over Alexander on Dec. 30.
Cody Henry - Notre Dame Boys Basketball - Poured in 22 points, including 18 in the second half, in a win over Alexander on Dec. 28. Added 17 points in a loss to O-A on Dec. 30.
Jordan Welker - Notre Dame Boys Basketball - Led all scorers with 24 points in a loss to O-A on Dec. 30. Also scored 17 points in a loss to O-A on Dec. 28.
Merritt Holly Jr. - Le Roy Boys Basketball - Dropped 28 points and grabbed 13 rebounds while dishing out four assists and recording four steals in a win over Roy-Hart on Dec. 28. Added 11 points and secured 11 rebounds in a win over Attica on Dec. 30.
Mitch Hockey - Le Roy Boys Basketball - Highlighted a Knights' win over Attica on Dec. 30 wit a game-high 28 points to go with four assists, four rebounds and three steals. Also netted 24 points in a win over Roy-Hart on Dec. 28.
Matthew Auble - Warsaw Boys Basketball - Finished with a double-double consisting of 18 points and 13 rebounds in a win over Keshequa on Dec. 28.
Bailey Schell - Warsaw Boys Basketball - Contributed a double-double consisting of 15 points and 10 rebounds in a win over Keshequa on Dec. 28.
Chris Coyle - Livonia Boys Basketball - Led the way with 25 points, eight rebounds and five assists in a win over Northeast Douglass on Dec. 28. Added 27 points and grabbed 13 rebounds in a win over Greece Odyssey on Dec. 29.
Justin Skelly - Livonia Boys Basketball - Filled it up with a career-high 22 points to go with 13 rebounds in a win over Greece Odyssey on Dec. 29.
Kyle Wade - Cal-Mum Boys Basketball - Powered a win over York on Dec. 30 with 30 points, including his 1,000th-career point, to go with seven rebounds and four assists. Also, in a win over Gananda on Dec. 28 he scored 25 points to go with nine rebounds and four assists.
Scott Essig - Cal-Mum Boys Basketball - Helped a win over York on Dec. 30 with 24 points, including five 3-points, to go with four rebounds and four assists. Added 15 points and five rebounds in a win over Gananda on Dec. 28.
Sydnee Emerson - York Girls Basketball - In a win over Cal-Mum on Dec. 28, scored 22 points while recording five steals and four assists.
Kelsey Schlagenhauf - Oakfield-Alabama Girls Basketball - Pumped in a double-double consisting of 11 points and 12 rebounds to go with five steals and four assists in a win over Wheatland-Chili on Dec. 28.
Emma Tangeman - Warsaw Girls Basketball - Secured a double-double consisting of 16 points and 10 rebounds in a win over Campbell-Savona on Dec. 28.
Lindsey Steffenilla - Le Roy Girls Basketball - Scored a game-high 22 points and grabbed eight rebounds in a loss to Byron-Bergen on Dec. 28.
Lillian Hoyt - Hornell Girls Basketball - Poured in 22 points in a win over Corning on Dec. 28.
Kylie Buckley - Livonia Girls Basketball - Finished a win over Holland on Dec. 28 with 29 points, 13 rebounds and five steals.
Zach Barrett - Kendall Boys Basketball - Scored the game-winning bucket as part of a 10-point, 10-rebound effort in a win over Perry on Dec. 29.
Jake Pangrazio - York Boys Basketball - Dropped a game-high 22 points in a win over Gananda on Dec. 29.
Jakob Smith - Dansville Boys Basketball - Led the way with a double-double consisting of 20 points and 11 rebounds to go with three steals in a win over Keshequa on Dec. 29.
Drew Morrow - Dansville Boys Basketball - Recorded a double-double consisting of 13 points and 10 rebounds to go with four steals in a win over Keshequa on Dec. 29.
Libby Benner - Keshequa Girls Basketball - Finished with a game-high 20 points in a win over Warsaw on Dec. 29.
Hazell Nickerson - Cal-Mum Girls Basetball - Scored 10 points and grabbed a career-high 17 rebounds in a win over Wheatland-Chili on Dec. 29.
Javin McFollins - Batavia Boys Basketball - Contributed 28 points in Batavia's win over Roy-Hart on Dec. 30.
Zach Marsceill - Elba Boys Basketball - Dropped a game-high 25 points, including four 3-pointers in a win over Alexander on Dec. 30.
Casper Stewart - Batavia/Attica Wrestling - Took home the 138-pound title at the Windsor Black Knights Christmas Tournament on Dec. 30.
Holden Kelly - Perry Wrestling - Finished a perfect 7-0 at the Letchworth Duals.
Noah Leitten- Perry Wrestling - Finished a perfect 7-0 at the Letchworth Duals.
Aaron Treleaven - Batavia/Notre Dame Swimming and Diving - Won the 200 freestyle (1:55.72) and 100 backstroke (:59.47) while also contributing to wins in the 200 freestyle relay (1:37.32) and 400 freestyle relay (3:47.97) in a win over Attica on Dec. 30.
Matthew Doeringer - Batavia/Notre Dame Swimming and Diving - Touched first in the 200 IM (@:26.13) and 100 butterfly (1:02.05) while also helping the winning 200 freestyle relay (1:37.32) and 400 freestyle relay (3:47.97) teams in a win over Attica on Dec. 30.
Johnson Newspapers 7.1
Bdn Sports
Lcn Sports
How to order government's free at-home COVID test kits
What people are doing wrong when using at-home COVID tests
Editorial — Many are missing out: State indefinitely extends rule allowing remote public meetings
UPDATE: Additional changes to COVID reporting process in Livingston County
Frozen landscape: NWS says Medina topped area snow accumulations


text:
Argentina: Sightings of UFOs and a Strange Winged Entity
Source: Diario Popular (Argentina) and Planeta UFO
Date: July 20 2015
By Pachi La Fata
One fine day, UFOs reappeared in the Province of San Luis, a space with an endless list of incidents as startling as they are enigmatic. On this occasion, the incident involved two fishermen who witnessed two flying saucers floating some 20 meters over the ground. This isn't all: in another case, a strange "winged entity" - described as white and tremendously large - also appeared. Within the scope of a new publication by the Vision Ovni group, it was noted that all of this occurred in a wilderness located 100 kilometers to the north of Cañada de San Gerónimo.
Axel Aguero, one of the witnesses, claims that on July 1, 2015 he was at the edge of a lagoon in Campo de los Avila, a place he visits regularly, in the company of a fellow fisherman. The phenomenon occurred at around 21:00 as they sat beside a small bonfire they had lit to warm themselves due to the prevailing low temperatures.
"They were looking at the buoys on the lake when [Axel] felt someone tapping him twice on the back, near his shoulder, as though trying to call his attention to something. It was strange, as they are no locals in the vicinity. He turned around to see who it was, and was stunned speechless when he saw it wasn't a person. At a distance of 100 meters, he saw two large objects similar to inverted plates, floating between 20 and 30 meters from the ground, both of them luminous and side by side," says the report. The witness declared verbatim that "one would light up brilliantly, and when it decreased its intensity, the other would increase its own, like a heartbeat." He added that both he and his friend had cellular phones on them with cameras, but faced with the shock, and he does not know why, both men were left motionless for several seconds, unable to do anything besides stare at the strange "craft" which took off swiftly toward the south in an instant, heading toward the Sierras de las Quijadas, some 60 kilometers west of San Luis along Route 147.
The second case involves Fabian Castillo, who provided his own story: "I was at the wall of the Potrero de los Funes reservoir at approximately 19:30 hours. It was already dark and no one was around due to the prevailing cold. I felt something flapping in the air, approaching me. I was surprised by the sound that was halfway between a squawk and a grunt, unusual and exaggerated. I had never heard anything like it. Suddenly, a tremendously large white winged figure passed only a few meters away from me."
The man estimates that each wing was at least four meters long. "It was neither a duck nor a condor. It was an entity, like a gargoyle or something like it," he said. It passed so close to where he stood that he was able to feel the air from the flapping wings, imitating the sound they made: "boooof, booof".
The witness added that the mysterious "entity" headed toward the Quebrada (a hard-to-reach location due to the steepness of the terrain), stating that he felt such fear that he did not remember at what point he returned home.
In his account, Castillo remarked on a situation that repeats in numerous cases involving eyewitnesses of the unknown. He explained that he had kept his story to himself to avoid becoming the target of mockery.
This is not the winged entity's first appearance, either.
The Visión OVNI group recalls that two years ago, a 60-year-old man, in charge of property with cabins on it at Potrero de los Funes, told of a similar experience. It occurred on a day of dense fog as he ate breakfast one morning. He saw a strange movement in the playground for the children of the cabins' occupants. Upon looking closely, he saw a very large white winged creature. "It looked like a person, but large. Like an angel or something similar. When it flew off, its wings nearly covered the entire site," the witness stated. There are two other reports as well.
[Translation (c) 2015 S. Corrales, IHU with thanks to Pachi La Fata, Guillermo Giménez and Vision Ovni]
Mexico: Senior Citizen Allegedly Run Over by UFO
Argentina: Hunter Claims He Shot "An Extraterrestr...
Mexico: "Webcams Mexico" Cameras Pick Up UFO Over ...
Mexico: Truckers Startled by UFOs in Yucatán
Argentina: 50th Anniversary of the Argentinean Ant...
Colombia: UFO Recorded Over Bogota's Cerro Monserrate
Argentina: Cattleman Blames Herd Death on Chupacabras
Peru: A "UFO Fleet" Recorded Over Tarma
Mexico: UFOs Over Mayan Pyramids
Chile: UFO Recorded During Soccer Match


text:
NYC Restaurant News
Chef Michael Psilakis Distances Himself From UWS Gem Kefi After Eviction Snafu
The restaurant briefly closed this week due to a landlord issue
by Beth Landman Jan 19, 2018, 1:09pm EST
Share All sharing options for: Chef Michael Psilakis Distances Himself From UWS Gem Kefi After Eviction Snafu
The dining room at Kefi
Photo via Kefi
Popular Upper West Side Greek restaurant Kefi had a bit of a hiccup this week. A city marshal's notice appeared on the restaurant at 505 Columbus Ave., between West 84th and West 85th streets, declaring the property had been turned over to the landlord. For a night, the restaurant shuttered, leaving those with reservations stranded.
David Horowitz, managing agent of landlord 505 Columbus LLC, said, "Why do people get evicted? Whatever the issue was I don't care to discuss, but it was resolved and hopefully it was a one shot deal that won't happen again.'" A manager at the restaurant said it was a miscommunication. Kefi reopened by Wednesday.
But in the snafu, chef Michael Psilakis distanced himself from the restaurant that he first opened in 2007: "I am no longer a principal at Kefi, a longstanding neighborhood gem on the Upper West Side. While I have no information about the current situation, it is a brand close to my heart, and I'd hate to see the neighborhood lose such a special restaurant." His website still lists Kefi as one of his restaurants. In response to Psilakis's statement, a manager for the restaurant responded: "Michael Psilakis is and has always been our executive chef.''