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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import javax.cache.Cache;
import javax.cache.configuration.Factory;
import javax.cache.integration.CacheLoaderException;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteTransactions;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.CacheWriteSynchronizationMode;
import org.apache.ignite.cache.store.CacheStore;
import org.apache.ignite.cache.store.CacheStoreAdapter;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.configuration.NearCacheConfiguration;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.apache.ignite.transactions.Transaction;
import org.apache.ignite.transactions.TransactionConcurrency;
import org.apache.ignite.transactions.TransactionIsolation;
import org.apache.ignite.transactions.TransactionOptimisticException;

import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
import static org.apache.ignite.transactions.TransactionConcurrency.OPTIMISTIC;
import static org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC;
import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ;
import static org.apache.ignite.transactions.TransactionIsolation.SERIALIZABLE;

/**
 *
 */
public class CacheNearReaderUpdateTest extends GridCommonAbstractTest {
    /** */
    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);

    /** */
    private boolean client;

    /** */
    private static final int SRVS = 4;

    /** */
    private static final int CLIENTS = 3;

    /** */
    private static Map<Integer, Integer> storeMap = new ConcurrentHashMap<>();

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

        cfg.setPeerClassLoadingEnabled(false);

        ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(IP_FINDER);

        cfg.setClientMode(client);

        return cfg;
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        super.beforeTestsStarted();

        startGridsMultiThreaded(SRVS);

        client = true;

        startGridsMultiThreaded(SRVS, CLIENTS);

        client = false;
    }

    /** {@inheritDoc} */
    @Override protected long getTestTimeout() {
        return 10 * 60_000;
    }

    /**
     * @throws Exception If failed.
     */
    public void testNoBackups() throws Exception {
        runTestGetUpdateMultithreaded(cacheConfiguration(PARTITIONED, FULL_SYNC, 0, false, false));
    }

    /**
     * @throws Exception If failed.
     */
    public void testOneBackup() throws Exception {
        runTestGetUpdateMultithreaded(cacheConfiguration(PARTITIONED, FULL_SYNC, 1, false, false));
    }

    /**
     * @throws Exception If failed.
     */
    public void testOneBackupNearEnabled() throws Exception {
        runTestGetUpdateMultithreaded(cacheConfiguration(PARTITIONED, FULL_SYNC, 1, false, true));
    }

    /**
     * @throws Exception If failed.
     */
    public void testOneBackupStoreEnabled() throws Exception {
        runTestGetUpdateMultithreaded(cacheConfiguration(PARTITIONED, FULL_SYNC, 1, true, false));
    }

    /**
     * @throws Exception If failed.
     */
    private void runTestGetUpdateMultithreaded(CacheConfiguration<Integer, Integer> ccfg) throws Exception {
        final List<Ignite> putNodes = new ArrayList<>();

        for (int i = 0; i < SRVS + CLIENTS - 1; i++)
            putNodes.add(ignite(i));

        final List<Ignite> getNodes = new ArrayList<>();

        getNodes.add(ignite(SRVS + CLIENTS - 1));
        getNodes.add(ignite(0));

        logCacheInfo(ccfg);

        runTestGetUpdateMultithreaded(ccfg, putNodes, getNodes, null, null);

        if (ccfg.getAtomicityMode() == TRANSACTIONAL) {
            runTestGetUpdateMultithreaded(ccfg, putNodes, getNodes, PESSIMISTIC,  REPEATABLE_READ);

            runTestGetUpdateMultithreaded(ccfg, putNodes, getNodes, OPTIMISTIC,  REPEATABLE_READ);

            runTestGetUpdateMultithreaded(ccfg, putNodes, getNodes, OPTIMISTIC,  SERIALIZABLE);
        }
    }

    /**
     * @param ccfg Cache configuration.
     * @param putNodes Nodes executing updates.
     * @param getNodes Nodes executing gets.
     * @param concurrency Transaction concurrency.
     * @param isolation Transaction isolation.
     * @throws Exception If failed.
     */
    private void runTestGetUpdateMultithreaded(CacheConfiguration<Integer, Integer> ccfg,
        final List<Ignite> putNodes,
        final List<Ignite> getNodes,
        final TransactionConcurrency concurrency,
        final TransactionIsolation isolation) throws Exception {
        fail("https://issues.apache.org/jira/browse/IGNITE-627");

        log.info("Execute updates [concurrency=" + concurrency + ", isolation=" + isolation + ']');

        final Ignite ignite0 = ignite(0);

        final String cacheName = ignite0.createCache(ccfg).getName();

        try {
            for (int i = 0; i < 5; i++) {
                final Integer key = i;

                final AtomicInteger putThreadIdx = new AtomicInteger();
                final AtomicInteger getThreadIdx = new AtomicInteger();

                final int PUT_THREADS = 20;
                final int GET_THREAD = 20;

                final CyclicBarrier barrier = new CyclicBarrier(PUT_THREADS + GET_THREAD);

                final IgniteInternalFuture<?> updateFut = GridTestUtils.runMultiThreadedAsync(new Callable<Void>() {
                    @Override public Void call() throws Exception {
                        int idx = putThreadIdx.getAndIncrement() % putNodes.size();

                        Ignite ignite = putNodes.get(idx);

                        IgniteCache<Integer, Integer> cache = ignite.cache(cacheName);

                        IgniteTransactions txs = ignite.transactions();

                        Thread.currentThread().setName("update-thread-" + ignite.name());

                        barrier.await();

                        for (int i = 0; i < 100; i++) {
                            ThreadLocalRandom rnd = ThreadLocalRandom.current();

                            if (concurrency != null) {
                                try (Transaction tx = txs.txStart(concurrency, isolation)) {
                                    cache.put(key, rnd.nextInt());

                                    tx.commit();
                                }
                                catch (TransactionOptimisticException ignore) {
                                    assertEquals(concurrency, OPTIMISTIC);
                                    assertEquals(isolation, SERIALIZABLE);
                                }
                            }
                            else
                                cache.put(key, rnd.nextInt());
                        }

                        return null;
                    }
                }, PUT_THREADS, "update-thread");

                IgniteInternalFuture<?> getFut = GridTestUtils.runMultiThreadedAsync(new Callable<Void>() {
                    @Override public Void call() throws Exception {
                        int idx = getThreadIdx.getAndIncrement() % getNodes.size();

                        Ignite ignite = getNodes.get(idx);

                        IgniteCache<Integer, Integer> cache;

                        if (ignite.configuration().isClientMode())
                            cache = ignite.createNearCache(cacheName, new NearCacheConfiguration<Integer, Integer>());
                        else
                            cache = ignite.cache(cacheName);

                        Thread.currentThread().setName("get-thread-" + ignite.name());

                        barrier.await();

                        while (!updateFut.isDone())
                            cache.get(key);

                        return null;
                    }
                }, GET_THREAD, "get-thread");

                updateFut.get();
                getFut.get();

                Integer val = (Integer)ignite0.cache(cacheName).get(key);

                log.info("Iteration [iter=" + i + ", val=" + val + ']');

                for (Ignite getNode : getNodes) {
                    IgniteCache<Integer, Integer> cache = getNode.cache(cacheName);

                    if (getNode.configuration().isClientMode() ||
                        cache.getConfiguration(CacheConfiguration.class).getNearConfiguration() != null)
                    assertNotNull(getNode.cache(cacheName).localPeek(key));
                }

                checkValue(key, val, cacheName);

                for (int n = 0; n < SRVS + CLIENTS; n++) {
                    val = n;

                    ignite(n).cache(cacheName).put(key, val);

                    checkValue(key, val, cacheName);
                }
            }
        }
        finally {
            destroyCache(ignite0, cacheName);
        }
    }

    /**
     * @param key Key.
     * @param expVal Expected value.
     * @param cacheName Cache name.
     */
    private void checkValue(Object key, Object expVal, String cacheName) {
        for (int i = 0; i < SRVS + CLIENTS; i++) {
            IgniteCache<Object, Object> cache = ignite(i).cache(cacheName);

            assertEquals(expVal, cache.get(key));
        }
    }

    /**
     * @param ccfg Cache configuration.
     */
    private void logCacheInfo(CacheConfiguration<?, ?> ccfg) {
        log.info("Test cache [mode=" + ccfg.getCacheMode() +
            ", sync=" + ccfg.getWriteSynchronizationMode() +
            ", backups=" + ccfg.getBackups() +
            ", near=" + (ccfg.getNearConfiguration() != null) +
            ", store=" + ccfg.isWriteThrough() +
            ", evictPlc=" + (ccfg.getEvictionPolicy() != null) +
            ']');
    }

    /**
     * @param ignite Node.
     * @param cacheName Cache name.
     */
    private void destroyCache(Ignite ignite, String cacheName) {
        storeMap.clear();

        ignite.destroyCache(cacheName);
    }

    /**
     * @param cacheMode Cache mode.
     * @param syncMode Write synchronization mode.
     * @param backups Number of backups.
     * @param storeEnabled If {@code true} adds cache store.
     * @param nearCache If {@code true} near cache is enabled.
     * @return Cache configuration.
     */
    private CacheConfiguration<Integer, Integer> cacheConfiguration(
        CacheMode cacheMode,
        CacheWriteSynchronizationMode syncMode,
        int backups,
        boolean storeEnabled,
        boolean nearCache) {
        CacheConfiguration<Integer, Integer> ccfg = new CacheConfiguration<>(DEFAULT_CACHE_NAME);

        ccfg.setCacheMode(cacheMode);
        ccfg.setAtomicityMode(TRANSACTIONAL);
        ccfg.setWriteSynchronizationMode(syncMode);

        if (cacheMode == PARTITIONED)
            ccfg.setBackups(backups);

        if (storeEnabled) {
            ccfg.setCacheStoreFactory(new TestStoreFactory());
            ccfg.setWriteThrough(true);
            ccfg.setReadThrough(true);
        }

        if (nearCache)
            ccfg.setNearConfiguration(new NearCacheConfiguration<Integer, Integer>());

        return ccfg;
    }

    /**
     *
     */
    private static class TestStoreFactory implements Factory<CacheStore<Integer, Integer>> {
        /** {@inheritDoc} */
        @Override public CacheStore<Integer, Integer> create() {
            return new CacheStoreAdapter<Integer, Integer>() {
                @Override public Integer load(Integer key) throws CacheLoaderException {
                    return storeMap.get(key);
                }

                @Override public void write(Cache.Entry<? extends Integer, ? extends Integer> entry) {
                    storeMap.put(entry.getKey(), entry.getValue());
                }

                @Override public void delete(Object key) {
                    storeMap.remove(key);
                }
            };
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataExplorer.Presentation.Panes.Layout.Color;
using DataExplorer.Presentation.Panes.Layout.Label;
using DataExplorer.Presentation.Panes.Layout.Link;
using DataExplorer.Presentation.Panes.Layout.Location;
using DataExplorer.Presentation.Panes.Layout.Shape;
using DataExplorer.Presentation.Panes.Layout.Size;

namespace DataExplorer.Presentation.Panes.Layout
{
    public interface ILayoutPaneViewModel
    {
        IXAxisLayoutViewModel XAxisLayoutViewModel { get; }

        IYAxisLayoutViewModel YAxisLayoutViewModel { get; }

        IColorLayoutViewModel ColorLayoutViewModel { get; }

        ISizeLayoutViewModel SizeLayoutViewModel { get; }

        IShapeLayoutViewModel ShapeLayoutViewModel { get; }

        ILabelLayoutViewModel LabelLayoutViewModel { get; }

        ILinkLayoutViewModel LinkLayoutViewModel { get; }

    }
}

redpajama_set_name: RedPajamaGithub


text:
/* This file was generated by upbc (the upb compiler) from the input
 * file:
 *
 *     envoy/config/listener/v3/udp_listener_config.proto
 *
 * Do not edit -- your changes will be discarded when the file is
 * regenerated. */

#ifndef ENVOY_CONFIG_LISTENER_V3_UDP_LISTENER_CONFIG_PROTO_UPB_H_
#define ENVOY_CONFIG_LISTENER_V3_UDP_LISTENER_CONFIG_PROTO_UPB_H_

#include "upb/msg.h"
#include "upb/decode.h"
#include "upb/encode.h"

#include "upb/port_def.inc"

#ifdef __cplusplus
extern "C" {
#endif

struct envoy_config_listener_v3_UdpListenerConfig;
struct envoy_config_listener_v3_ActiveRawUdpListenerConfig;
typedef struct envoy_config_listener_v3_UdpListenerConfig envoy_config_listener_v3_UdpListenerConfig;
typedef struct envoy_config_listener_v3_ActiveRawUdpListenerConfig envoy_config_listener_v3_ActiveRawUdpListenerConfig;
extern const upb_msglayout envoy_config_listener_v3_UdpListenerConfig_msginit;
extern const upb_msglayout envoy_config_listener_v3_ActiveRawUdpListenerConfig_msginit;
struct google_protobuf_Any;
extern const upb_msglayout google_protobuf_Any_msginit;

/* envoy.config.listener.v3.UdpListenerConfig */

UPB_INLINE envoy_config_listener_v3_UdpListenerConfig *envoy_config_listener_v3_UdpListenerConfig_new(upb_arena *arena) {
  return (envoy_config_listener_v3_UdpListenerConfig *)_upb_msg_new(&envoy_config_listener_v3_UdpListenerConfig_msginit, arena);
}
UPB_INLINE envoy_config_listener_v3_UdpListenerConfig *envoy_config_listener_v3_UdpListenerConfig_parse(const char *buf, size_t size,
                        upb_arena *arena) {
  envoy_config_listener_v3_UdpListenerConfig *ret = envoy_config_listener_v3_UdpListenerConfig_new(arena);
  return (ret && upb_decode(buf, size, ret, &envoy_config_listener_v3_UdpListenerConfig_msginit, arena)) ? ret : NULL;
}
UPB_INLINE char *envoy_config_listener_v3_UdpListenerConfig_serialize(const envoy_config_listener_v3_UdpListenerConfig *msg, upb_arena *arena, size_t *len) {
  return upb_encode(msg, &envoy_config_listener_v3_UdpListenerConfig_msginit, arena, len);
}

typedef enum {
  envoy_config_listener_v3_UdpListenerConfig_config_type_typed_config = 3,
  envoy_config_listener_v3_UdpListenerConfig_config_type_NOT_SET = 0
} envoy_config_listener_v3_UdpListenerConfig_config_type_oneofcases;
UPB_INLINE envoy_config_listener_v3_UdpListenerConfig_config_type_oneofcases envoy_config_listener_v3_UdpListenerConfig_config_type_case(const envoy_config_listener_v3_UdpListenerConfig* msg) { return (envoy_config_listener_v3_UdpListenerConfig_config_type_oneofcases)*UPB_PTR_AT(msg, UPB_SIZE(12, 24), int32_t); }

UPB_INLINE upb_strview envoy_config_listener_v3_UdpListenerConfig_udp_listener_name(const envoy_config_listener_v3_UdpListenerConfig *msg) { return *UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview); }
UPB_INLINE bool envoy_config_listener_v3_UdpListenerConfig_has_typed_config(const envoy_config_listener_v3_UdpListenerConfig *msg) { return _upb_getoneofcase(msg, UPB_SIZE(12, 24)) == 3; }
UPB_INLINE const struct google_protobuf_Any* envoy_config_listener_v3_UdpListenerConfig_typed_config(const envoy_config_listener_v3_UdpListenerConfig *msg) { return UPB_READ_ONEOF(msg, const struct google_protobuf_Any*, UPB_SIZE(8, 16), UPB_SIZE(12, 24), 3, NULL); }

UPB_INLINE void envoy_config_listener_v3_UdpListenerConfig_set_udp_listener_name(envoy_config_listener_v3_UdpListenerConfig *msg, upb_strview value) {
  *UPB_PTR_AT(msg, UPB_SIZE(0, 0), upb_strview) = value;
}
UPB_INLINE void envoy_config_listener_v3_UdpListenerConfig_set_typed_config(envoy_config_listener_v3_UdpListenerConfig *msg, struct google_protobuf_Any* value) {
  UPB_WRITE_ONEOF(msg, struct google_protobuf_Any*, UPB_SIZE(8, 16), value, UPB_SIZE(12, 24), 3);
}
UPB_INLINE struct google_protobuf_Any* envoy_config_listener_v3_UdpListenerConfig_mutable_typed_config(envoy_config_listener_v3_UdpListenerConfig *msg, upb_arena *arena) {
  struct google_protobuf_Any* sub = (struct google_protobuf_Any*)envoy_config_listener_v3_UdpListenerConfig_typed_config(msg);
  if (sub == NULL) {
    sub = (struct google_protobuf_Any*)_upb_msg_new(&google_protobuf_Any_msginit, arena);
    if (!sub) return NULL;
    envoy_config_listener_v3_UdpListenerConfig_set_typed_config(msg, sub);
  }
  return sub;
}

/* envoy.config.listener.v3.ActiveRawUdpListenerConfig */

UPB_INLINE envoy_config_listener_v3_ActiveRawUdpListenerConfig *envoy_config_listener_v3_ActiveRawUdpListenerConfig_new(upb_arena *arena) {
  return (envoy_config_listener_v3_ActiveRawUdpListenerConfig *)_upb_msg_new(&envoy_config_listener_v3_ActiveRawUdpListenerConfig_msginit, arena);
}
UPB_INLINE envoy_config_listener_v3_ActiveRawUdpListenerConfig *envoy_config_listener_v3_ActiveRawUdpListenerConfig_parse(const char *buf, size_t size,
                        upb_arena *arena) {
  envoy_config_listener_v3_ActiveRawUdpListenerConfig *ret = envoy_config_listener_v3_ActiveRawUdpListenerConfig_new(arena);
  return (ret && upb_decode(buf, size, ret, &envoy_config_listener_v3_ActiveRawUdpListenerConfig_msginit, arena)) ? ret : NULL;
}
UPB_INLINE char *envoy_config_listener_v3_ActiveRawUdpListenerConfig_serialize(const envoy_config_listener_v3_ActiveRawUdpListenerConfig *msg, upb_arena *arena, size_t *len) {
  return upb_encode(msg, &envoy_config_listener_v3_ActiveRawUdpListenerConfig_msginit, arena, len);
}

#ifdef __cplusplus
}  /* extern "C" */
#endif

#include "upb/port_undef.inc"

#endif  /* ENVOY_CONFIG_LISTENER_V3_UDP_LISTENER_CONFIG_PROTO_UPB_H_ */


text:
package uk.gov.hmrc.ct.accounts.frs102.boxes

import uk.gov.hmrc.ct.accounts.{AccountsMoneyValidationFixture, MockFrs102AccountsRetriever}
import uk.gov.hmrc.ct.accounts.frs102.retriever.Frs102AccountsBoxRetriever

class AC134Spec extends AccountsMoneyValidationFixture[Frs102AccountsBoxRetriever] with MockFrs102AccountsRetriever {

  testAccountsMoneyValidationWithMin("AC134",0, AC134.apply)

}


text:
Show bulk job batch details

```
force bulk batch <jobId> <batchId> [flags]
```

### Options

```
  -h, --help   help for batch
```

### Options inherited from parent commands

```
  -a, --account username    account username to use
  -V, --apiversion string   API version to use
```

### SEE ALSO

* [force bulk](force_bulk.md)	 - Load csv file or query data using Bulk API


text:
using System.IO;

namespace SharpLib.Audio.Wave
{
    internal class RawSourceWaveStream : WaveStream
    {
        #region Поля

        private readonly Stream sourceStream;

        private readonly WaveFormat waveFormat;

        #endregion

        #region Свойства

        public override WaveFormat WaveFormat
        {
            get { return waveFormat; }
        }

        public override long Length
        {
            get { return sourceStream.Length; }
        }

        public override long Position
        {
            get { return sourceStream.Position; }
            set { sourceStream.Position = value; }
        }

        #endregion

        #region Конструктор

        public RawSourceWaveStream(Stream sourceStream, WaveFormat waveFormat)
        {
            this.sourceStream = sourceStream;
            this.waveFormat = waveFormat;
        }

        #endregion

        #region Методы

        public override int Read(byte[] buffer, int offset, int count)
        {
            return sourceStream.Read(buffer, offset, count);
        }

        #endregion
    }
}


text:
import gtk

class AccessClass:
    """
    Class for gtk.Button widgets access
    """
    def supported_widgets(self):
        """
        Supported widgets for this access class
        """
        return [gtk.Button]

    def supported_types(self):
        """
        Supported types for this access class
        """
        return []

    def set_content(self,widget,content):
        """
        Method for setting the widget content
        """
        widget.set_label(str(content))

    def get_content(self,widget):
        """
        Method for setting the widget content
        """
        return widget.get_label()


text:
import unittest
import testfixtures
from slidelint.resources import PlugginsHandler
from slidelint.resources import EntryPoint as _

class Loadable():
    def __init__(self, name):
        self.name = name

    def load(self):
        return self.name

ALL_ENTRIES = [
    _('checkera', 'CategoryA', Loadable('CategoryA.checkera')),  # 0+---
    _('checkerb', 'CategoryA', Loadable('CategoryA.checkerb')),  # 1+-++
    _('checkerc', 'CategoryA', Loadable('CategoryA.checkerc')),  # 2+---
    _('checkerd', 'CategoryB', Loadable('CategoryB.checkerd')),  # 3++++
    _('checkere', 'CategoryB', Loadable('CategoryB.checkere')),  # 4+++-
    _('checkerf', 'CategoryC', Loadable('CategoryC.checkerf')),  # 5--++
    _('checkerg', 'CategoryD', Loadable('CategoryD.checkerg'))]  # 6+++-

REZ_ENTRIES = [_(n, c, e.load()) for n, c, e in ALL_ENTRIES]

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.handler = PlugginsHandler("")
        self.handler.checkers = ALL_ENTRIES

    def test_all_categiries(self):
        rez = self.handler.load_checkers()
        should_be = REZ_ENTRIES
        testfixtures.compare(rez, should_be)

    def test_enable_category(self):
        rez = self.handler.load_checkers(categories=['CategoryB', 'CategoryD'])
        should_be = REZ_ENTRIES[3:5] + [REZ_ENTRIES[6]]
        testfixtures.compare(rez, should_be)

    def test_disable_category(self):
        rez = self.handler.load_checkers(
            disabled_categories=['CategoryA', 'CategoryD'])
        should_be = REZ_ENTRIES[3:6]
        testfixtures.compare(rez, should_be)

    def test_enable_checker(self):
        rez = self.handler.load_checkers(
            disabled_categories=['AllCategories'],
            checkers=['checkera', 'checkere'])
        should_be = [REZ_ENTRIES[0], REZ_ENTRIES[4]]
        testfixtures.compare(rez, should_be)

    def test_disable_checker(self):
        rez = self.handler.load_checkers(
            disabled_checkers=['checkera', 'checkerf', 'checkerg'])
        should_be = REZ_ENTRIES[1:5]
        testfixtures.compare(rez, should_be)

    def test_mixed(self):
        rez = self.handler.load_checkers(
            categories=['CategoryA', 'CategoryB', 'CategoryD'],
            disabled_categories=['CategoryA'],
            checkers=['checkerb', 'checkerf'],
            disabled_checkers=['checkere', 'checkerg'])
        should_be = [REZ_ENTRIES[3], REZ_ENTRIES[1], REZ_ENTRIES[5]]
        testfixtures.compare(rez, should_be)


text:
This work is based on the original design by acastr7 and his contributors.  However, I wanted to be able to use a "carousel" on any view rather than be tied down to an the Image class specifically.  So I present this repository, I've not yet made a Nuget Package, but hope to do so some time after the Holidays.

Update 2-24-2016:

I've updated the project to ensure the correc types are being added to the carousel and removed the requirement to implement swiping on the views and ability for navigation.  These both have been abstracted out into interfaces.

Currently only Android has been implemented. iOS soon to come!

-----------------------------------------------------------------------------------------------------------------------------------------
This code is give as is, with no warrenties or guarenteed support. I'll do my best to accomodate any issues in my spare time.

Hope someone finds this useful!


text:
'use strict';

/*
 * Note that we want this to run as widely as possible so we're not using
 * any ES6 features.
 */

var fs = require('fs');
var os = require('os');
var path = require('path');
var spawn = require('child_process').spawn;
var verbose = false;
var homedir = os.homedir();

function addFileIfExists(fileName, command) {
  try {
    if (verbose) console.log('About to check for file:', fileName);
    fs.accessSync(fileName, fs.constants.R_OK);
    command.push('-f', fileName);
  } catch(e) {
    if (verbose) console.log('No ' + fileName + ' file found');
  }
}

/**
 * Execute a Docker Compose 'run' command.
 * @param {string} service name
 * @param {string} path to Docker Compose config file
 * @param {string} app name
 */

module.exports = function(service, dcPath, app) {
  var rootdir = dcPath || process.cwd();

  /**
   * The Docker Compose file to use (if specified):
   */

  var dcFile = (!dcPath)
    ? undefined
    : path.join(dcPath, 'docker-compose.yml');

  /**
   * Create the command to run inside the Docker container, which is a
   * combination of the app name and any parameters the user passes in:
   */

  var cmd = [app]
  .concat(process.argv.slice(2))
  .join(' ');

 /**
  * Build the full command that needs to be spawned:
  */

  var command = [];

  command.push('docker-compose');

  /**
   * If there's a Docker Compose file specified then add it as a
   * parameter:
   */

  if (dcFile) command.push('-f', dcFile);

  /**
   * If there is no file specified then Docker Compose will just automatically
   * pick up 'docker-compose.yml' in the current directory. However, if we
   * want to add other files like 'docker-compose.dcr.yml' then we'll need to
   * add the 'docker-compose.yml' file explicitly:
   */

  else {

    /**
     * Docker Compose applies these files in the order that they are specified
     * on the command line, so we put the file with the same name as the environment
     * last, and that allows us to override everything:
     */

    [
      path.join(rootdir, 'docker-compose.yml'),
      path.join(rootdir, 'docker-compose.dcr.yml'),
      path.join(homedir, '.docker-compose.dcr.yml'),
      path.join(rootdir, 'docker-compose.' + service + '.yml'),
      path.join(homedir, '.docker-compose.' + service + '.yml'),
      path.join(rootdir, 'docker-compose.' + process.env.DCR_ENVIRONMENT + '.yml'),
      path.join(homedir, '.docker-compose.' + process.env.DCR_ENVIRONMENT + '.yml')
    ].map(function(fileName) {
      addFileIfExists(fileName, command);
    });
  }

  /**
   * Add the instructions to run the service with the default options:
   */

  command.push('run', '--service-ports', '--rm', service);

  /**
   * If there is a command to pass to the container then add it:
   */

  if (cmd) command.push(cmd);

  command = command.join(' ');

  /**
   * Now spawn the command and send any IO to the right streams:
   */

  spawn(command, {
    stdio: 'inherit',
    shell: true
  });
};


text:
package org.apache.asterix.dataflow.data.nontagged.printers.csv;

import java.io.PrintStream;

import org.apache.asterix.dataflow.data.nontagged.serde.AInt16SerializerDeserializer;
import org.apache.hyracks.algebricks.data.IPrinter;
import org.apache.hyracks.api.exceptions.HyracksDataException;

public class AInt16Printer implements IPrinter {
    public static final AInt16Printer INSTANCE = new AInt16Printer();

    @Override
    public void init() {
    }

    @Override
    public void print(byte[] b, int s, int l, PrintStream ps) throws HyracksDataException {
        short i = AInt16SerializerDeserializer.getShort(b, s + 1);
        ps.print(i);
    }
}


text:
local JointsService = game:GetService('JointsService')
local v3,cf=Vector3.new,CFrame.new
local v3b,cfb=v3(0,0,0),cf(0,0,0)
local tos = cfb.toObjectSpace

local function Custom(Type, Part0, Part1, C0, C1)
	local Joint = Instance.new(Type)
	Joint.Part0 = Part0
	Joint.Part1 = Part1
	Joint.C0 = C0
	Joint.C1 = C1
	Joint.Parent = JointsService
	return Joint
end
local function CustomWeld(Part0, Part1, C0, C1)
	return Custom('Weld', Part0, Part1, C0, C1)
end
local function CustomMotor(Part0, Part1, C0, C1)
	return Custom('Motor', Part0, Part1, C0, C1)
end
local function BlankWeld(Part0, Part1)
	return CustomWeld(Part0, Part1, cfb, cfb)
end
local function BlankMotor(Part0, Part1)
	return CustomMotor(Part0, Part1, cfb, cfb)
end
local function Weld(Part0, Part1)
	return CustomWeld(Part0, Part1, tos(Part0.CFrame, Part1.CFrame), cfb)
end
local function Motor(Part0, Part1)
	return CustomMotor(Part0, Part1, tos(Part0.CFrame, Part1.CFrame), cfb)
end
local function WeldAllTo(m, p, NoRecurse)
	local Welds = {}
	for _,v in next,m:GetChildren() do
		if (not NoRecurse) then
			for _,w in next,WeldAllTo(v, p, NoRecurse) do
				table.insert(Welds, w)
			end
		end
		if (v:IsA('BasePart') and v ~= p) then
			local w = Weld(v, p)
			table.insert(Welds, w)
			v.Anchored = false
		end
	end
	p.Anchored = false
	return Welds
end
return { CustomWeld = CustomWeld, CustomMotor = CustomMotor, BlankWeld = BlankWeld, BlankMotor = BlankMotor, Weld = Weld, Motor = Motor, WeldAllTo = WeldAllTo }


text:
%w( mongrel mongrel_cluster ).each do |g|
  gem_package g do
    path = node[:rvm][:gem_binary]
    gem_binary path if path
    action :upgrade
  end
end

link "/usr/bin/mongrel_rails" do
  to "/usr/local/bin/mongrel_rails"
  only_if "test -f /usr/local/bin/mongrel_rails"
end


text:
@implementation ZJNLabel
- (void)awakeFromNib {
    [self configuration];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self configuration];
    }
    return self;
}

- (void)configuration {
    self.userInteractionEnabled = YES;
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

@end


text:
All about loops in rust

## Notes

Rust supports four loop expressions:

* A loop expression denotes an infinite loop.
* A while expression loops until a predicate is false.
* A while let expression tests a pattern.
* A for expression extracts values from an iterator, looping until the iterator is empty.

All four types of loop support break expressions, continue expressions, and labels. Only loop supports evaluation to non-trivial values.

### Loop

aka [Infinite loops](https://doc.rust-lang.org/reference/expressions/loop-expr.html#infinite-loops)

    loop {
        statements
    }

### While

aka [Predicate loops](https://doc.rust-lang.org/reference/expressions/loop-expr.html#predicate-loops)

    while condition {
        statements
    }

### While let

aka [Predicate pattern loops](https://doc.rust-lang.org/reference/expressions/loop-expr.html#predicate-pattern-loops)

    while let MatchArmPatterns = Expression {
        statements
    }

### For

aka [Iterator loops](https://doc.rust-lang.org/reference/expressions/loop-expr.html#iterator-loops)

    for Pattern in Expression {
        Statements
    }

### Running the Examples

Running the tests:

```
$ cargo test
   Compiling example v0.1.0 (.../LittleCodingKata/rust/loops/example)
    Finished test [unoptimized + debuginfo] target(s) in 0.43s
     Running target/debug/deps/example-3e96a7119aa2432d

running 5 tests
test tests::first_fib_for_works ... ok
test tests::first_fib_loop_with_return_value_works ... ok
test tests::first_fib_loop_works ... ok
test tests::first_fib_while_let_works ... ok
test tests::first_fib_while_works ... ok

test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/example-362e95a34487a628

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests example

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
```

Running the program:

```
$ cargo run
   Compiling example v0.1.0 (.../LittleCodingKata/rust/loops/example)
    Finished dev [unoptimized + debuginfo] target(s) in 0.19s
     Running `target/debug/example`
Loops in Rust
loop: first number in Fibonacci sequence over 10 = 13
loop_with_return_value: first number in Fibonacci sequence over 10 = 13
first_fib_while: first number in Fibonacci sequence over 10 = 13
first_fib_while_let: first number in Fibonacci sequence over 10 = 13
first_fib_for: first number in Fibonacci sequence over 10 = 13

```

## Credits and References

* [Loops](https://doc.rust-lang.org/reference/expressions/loop-expr.html) - Rust Reference


text:
import mock

from nova import exception
from nova.tests.unit.virt.hyperv import test_base
from nova.virt.hyperv import serialconsolehandler
from nova.virt.hyperv import serialconsoleops

class SerialConsoleOpsTestCase(test_base.HyperVBaseTestCase):
    def setUp(self):
        super(SerialConsoleOpsTestCase, self).setUp()
        serialconsoleops._console_handlers = {}
        self._serialops = serialconsoleops.SerialConsoleOps()
        self._serialops._pathutils = mock.MagicMock()

    def _setup_console_handler_mock(self):
        mock_console_handler = mock.Mock()
        serialconsoleops._console_handlers = {mock.sentinel.instance_name:
                                              mock_console_handler}
        return mock_console_handler

    @mock.patch.object(serialconsolehandler, 'SerialConsoleHandler')
    @mock.patch.object(serialconsoleops.SerialConsoleOps,
                       'stop_console_handler_unsync')
    def _test_start_console_handler(self, mock_stop_handler,
                                    mock_console_handler,
                                    raise_exception=False):
        mock_handler = mock_console_handler.return_value

        if raise_exception:
            mock_handler.start.side_effect = Exception

        self._serialops.start_console_handler(mock.sentinel.instance_name)

        mock_stop_handler.assert_called_once_with(mock.sentinel.instance_name)
        mock_console_handler.assert_called_once_with(
            mock.sentinel.instance_name)

        if raise_exception:
            mock_handler.stop.assert_called_once_with()
        else:
            console_handler = serialconsoleops._console_handlers.get(
                mock.sentinel.instance_name)
            self.assertEqual(mock_handler, console_handler)

    def test_start_console_handler(self):
        self._test_start_console_handler()

    def test_start_console_handler_exception(self):
        self._test_start_console_handler(raise_exception=True)

    def test_stop_console_handler(self):
        mock_console_handler = self._setup_console_handler_mock()

        self._serialops.stop_console_handler(mock.sentinel.instance_name)

        mock_console_handler.stop.assert_called_once_with()
        handler = serialconsoleops._console_handlers.get(
                mock.sentinel.instance_name)
        self.assertIsNone(handler)

    def test_get_serial_console(self):
        mock_console_handler = self._setup_console_handler_mock()

        ret_val = self._serialops.get_serial_console(
            mock.sentinel.instance_name)

        self.assertEqual(mock_console_handler.get_serial_console(),
                         ret_val)

    def test_get_serial_console_exception(self):
        self.assertRaises(exception.ConsoleTypeUnavailable,
                          self._serialops.get_serial_console,
                          mock.sentinel.instance_name)

    @mock.patch('builtins.open')
    @mock.patch("os.path.exists")
    def test_get_console_output_exception(self, fake_path_exists, fake_open):
        self._serialops._pathutils.get_vm_console_log_paths.return_value = [
            mock.sentinel.log_path_1, mock.sentinel.log_path_2]
        fake_open.side_effect = IOError
        fake_path_exists.return_value = True

        self.assertRaises(exception.ConsoleLogOutputException,
                          self._serialops.get_console_output,
                          mock.sentinel.instance_name)
        fake_open.assert_called_once_with(mock.sentinel.log_path_2, 'rb')

    @mock.patch('os.path.exists')
    @mock.patch.object(serialconsoleops.SerialConsoleOps,
                       'start_console_handler')
    def test_start_console_handlers(self, mock_get_instance_dir, mock_exists):
        self._serialops._pathutils.get_instance_dir.return_value = [
            mock.sentinel.nova_instance_name,
            mock.sentinel.other_instance_name]
        mock_exists.side_effect = [True, False]

        self._serialops.start_console_handlers()

        self._serialops._vmutils.get_active_instances.assert_called_once_with()


text:
body {
  padding: 0;
  margin: 0;
  color: #503E2C;
  font-family: "Oxygen",Arial,"Hiragino Sans GB","Microsoft YaHei","STHeiti","WenQuanYi Micro Hei",SimSun,sans-serif;
  font-size: 14px;
  letter-spacing: 1px;
  word-wrap: break-word;
}

a:hover {
  color: red !important;
}

a {
  color: #A68800;
}

a.button {
  background-color: #AAB5B5;
  border-radius: 10px;
  -moz-border-radius: 10px;
  color: white;
  display: inline-block;
  margin: 0 5px 5px 0;
  padding: 5px 10px;
  text-decoration: none;
}

img {
  border: none;
}

.wrapper {
  width: 1024px;
  margin: 0 auto;
}

.clearfix:after {
    clear: both;
    content: ".";
    display: block;
    height: 0;
    visibility: hidden;
}

pre {
  padding: 10px;
  font-size: 12px;
  background-color: #F8F8F8;
  border: 1px solid #DDDDDD;
  border-radius: 3px 3px 3px 3px;
  overflow: auto;
}

#header {
  background: none repeat scroll 0 0 #007E8C;
  padding: 10px;
}

#header .nav a {
  color: #fff;
  padding: 0 10px 0 0;
}

#container {
  padding: 5px;
}

#container .path {
  font-size: 12px;
  margin: 10px 0;
  padding: 5px;
  height: 24px;
  line-height: 24px;
  overflow: hidden;
  text-indent: 12px;
  color: #666;
  border: 1px solid #eee;
}

#container .path .gap {
  color: #bbb;
  font-size: 10px;
}

#container .path a {
  color: #666;
}

#container .posterity .folders li.post {
  padding: 5px;
}

#container .posterity .folders li.post .introduction {
  font-size: 80%;
}

#container .posterity .folders li.post a.read-link {
  font-size: 80%;
  color: #503E2C;
}

#container .content {
  padding: 10px;
}

#container .information {
  padding: 0;
  margin: 0 0 10px;
}

#container .information .bar .high {
  color: red;
}

#footer {
  font-size: 12px;
  text-align: center;
  color: #999999;
}

#footer .wrapper {
  border-top: 1px solid #DBDBDB;
  margin: 8px auto auto;
  padding-bottom: 10px;
  padding-top: 10px;
  width: 800px;
}

.dl-catalogs {
  padding: 0;
  margin:  0;
}

.dl-catalogs dd {
  margin: 0;
  line-height: 1.8;
  display: none;
  white-space:nowrap;
  overflow: hidden;
  font-size: 12px;
}
.dl-catalogs dd a {
  color: #503E2C;
}

.dl-catalogs dd.catalog-link-h1 {
  display: block;
  padding-left: 10px;
  background: url("/assets/images/shared/icons/li-1.gif") no-repeat scroll 3px 8px transparent
}

.dl-catalogs dd.catalog-link-h2 {
  display: block;
  padding-left: 20px;
  background: url("/assets/images/shared/icons/li-2.gif") no-repeat scroll 13px 8px transparent
}

.dl-catalogs dd.catalog-link-h3 {
  display: block;
  padding-left: 30px;
  background: url("/assets/images/shared/icons/li-3.gif") no-repeat scroll 23px 8px transparent
}

.dl-catalogs dd.catalog-link-h4 {

}

.dl-catalogs dd.catalog-link-h5 {

}

.dl-catalogs dd.catalog-link-h6 {

}

#container .posterity .folders .folder {
  background-color: #EEEEEE;
  clear: both;
  padding: 18px 20px;
  margin: 10px;
}

#container .posterity .folders .folder .self .info {
  font-size: 12px;
  float: right;
}

#container .posterity .folders .folder h3 {
  margin: 0;
  padding: 5px 0 10px;
}

#container .posterity .folders .folder .children {
  float: right;
  width: 835px;
}

#container .posterity .folders .folder .sub-folders a {
  margin: 5px;
}

#container .posterity .folders .folder img.icon {
  height: 128px;
}

#container .posterity .folders .folder img.sub-icon {
  height: 32px;
  width: 32px;
}

#container .posterity .folders .folder ul.posts {
  padding-left: 15px;
}

#container .posterity .folders .folder ul.posts li {
  line-height: 1.5;
}


text:
'use strict';

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

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

  var CoreCtrl,
      scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope    = $rootScope.$new();
    CoreCtrl = $controller('MainCtrl', {
      $scope: scope
    });
  }));

  it('shouldn\'t have anything defined in scope', function() {
    expect(scope.something).toBeUndefined();
  });
});


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Blockly Demo: Resizable Blockly (Part 2)</title>

          <button onclick="runCode()">Send Instructions to Robot</button>

  <xml xmlns="http://www.w3.org/1999/xhtml" id="toolbox" style="display: none;">
    <category name="Crafting">
      <block type="select_slot">
        <field name="blockMaterial">1</field>
      </block>
      <block type="place_crafting_number">
        <value name="CraftingSlot">
          <block type="math_number">
            <field name="NUM">1</field>
          </block>
        </value>
      </block>
    </category>
    <category name="Basic Mining">
      <block type="mine_block">
        <value name="mineBlockNum">
          <shadow type="math_number">
            <field name="NUM">1</field>
          </shadow>
        </value>
      </block>
      <block type="controls_whileUntil">
        <field name="MODE">UNTIL</field>
      </block>
      <block type="logic_compare">
        <field name="OP">EQ</field>
      </block>
      <block type="check_inventory">
        <field name="blockMaterial">2</field>
      </block>
      <block type="math_number">
        <field name="NUM">3</field>
      </block>
    </category>
    <category name="Advanced Mining">
      <block type="controls_for">
        <field name="VAR">i</field>
        <value name="FROM">
          <shadow type="math_number">
            <field name="NUM">1</field>
          </shadow>
        </value>
        <value name="TO">
          <shadow type="math_number">
            <field name="NUM">9</field>
          </shadow>
        </value>
        <value name="BY">
          <shadow type="math_number">
            <field name="NUM">1</field>
          </shadow>
        </value>
      </block>
      <block type="controls_if"></block>
      <block type="logic_compare">
        <field name="OP">EQ</field>
      </block>
      <block type="miningtargetblocktypeid">
        <value name="Mining Block">
          <block type="variables_get">
            <field name="VAR">i</field>
          </block>
        </value>
      </block>
      <block type="blocktypeid">
        <field name="blockMaterial">9</field>
      </block>
      <block type="mine_block"></block>
      <block type="variables_get">
        <field name="VAR">i</field>
      </block>
    </category>
    <category name="Loops" colour="#5CA65C">
      <block type="controls_repeat_ext">
        <value name="TIMES">
          <shadow type="math_number">
            <field name="NUM">10</field>
          </shadow>
        </value>
      </block>
      <block type="controls_whileUntil">
        <field name="MODE">UNTIL</field>
      </block>
      <block type="controls_whileUntil">
        <field name="MODE">UNTIL</field>
        <value name="BOOL">
          <block type="logic_compare">
            <field name="OP">EQ</field>
            <value name="A">
              <block type="check_inventory">
                <field name="blockMaterial">1</field>
              </block>
            </value>
            <value name="B">
              <block type="math_number">
                <field name="NUM">1</field>
              </block>
            </value>
          </block>
        </value>
      </block>
      <block type="controls_for">
        <field name="VAR">i</field>
        <value name="FROM">
          <shadow type="math_number">
            <field name="NUM">1</field>
          </shadow>
        </value>
        <value name="TO">
          <shadow type="math_number">
            <field name="NUM">10</field>
          </shadow>
        </value>
        <value name="BY">
          <shadow type="math_number">
            <field name="NUM">1</field>
          </shadow>
        </value>
      </block>
      <block type="controls_forEach">
        <field name="VAR">j</field>
      </block>
      <block type="controls_flow_statements" disabled="true">
        <field name="FLOW">BREAK</field>
      </block>
    </category>
    <category name="Logic" colour="#5C81A6">
      <block type="controls_if"></block>
      <block type="logic_compare">
        <field name="OP">EQ</field>
      </block>
      <block type="logic_operation">
        <field name="OP">AND</field>
      </block>
      <block type="logic_negate"></block>
      <block type="logic_boolean">
        <field name="BOOL">TRUE</field>
      </block>
      <block type="logic_null"></block>
    </category>
    <category name="Math" colour="#5C68A6">
      <block type="math_number">
        <field name="NUM">0</field>
      </block>
      <block type="math_arithmetic">
        <field name="OP">ADD</field>
        <value name="A">
          <shadow type="math_number">
            <field name="NUM">1</field>
          </shadow>
        </value>
        <value name="B">
          <shadow type="math_number">
            <field name="NUM">1</field>
          </shadow>
        </value>
      </block>
      <block type="math_number_property">
        <mutation divisor_input="false"></mutation>
        <field name="PROPERTY">EVEN</field>
        <value name="NUMBER_TO_CHECK">
          <shadow type="math_number">
            <field name="NUM">0</field>
          </shadow>
        </value>
      </block>
      <block type="math_modulo">
        <value name="DIVIDEND">
          <shadow type="math_number">
            <field name="NUM">64</field>
          </shadow>
        </value>
        <value name="DIVISOR">
          <shadow type="math_number">
            <field name="NUM">10</field>
          </shadow>
        </value>
      </block>
    </category>
    <category name="Variables" colour="#A65C81" custom="VARIABLE"></category>
  </xml>

          TESTING:
          <button onclick="showCode()">Show JavaScript</button>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="#F6F6F6">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="262dp"
        android:orientation="horizontal" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="15dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="15dp"
            android:orientation="horizontal" >

            <LinearLayout
                android:layout_width="178dp"
                android:layout_height="match_parent"
                android:orientation="horizontal" >

                <ImageView
                    android:id="@+id/fotoProveedor"
                    android:layout_width="144dp"
                    android:layout_height="fill_parent"
                    android:layout_weight="4.39"
                    android:src="@drawable/photo" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="6dp"
                android:layout_weight="0.7"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/nombre"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:text="Nombre:" />

                <TextView
                    android:id="@+id/ubicacion"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:text="Ubicación:" />

                <RatingBar
                    android:id="@+id/prov_rate"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <ImageView
                    android:id="@+id/btn_suscribir"
                    android:layout_width="256dp"
                    android:layout_height="100dp"
                    android:layout_marginTop="5dp"
                    android:layout_weight="7"
                    android:adjustViewBounds="true"
                    android:src="@drawable/suscribir" />

                <ImageView
                    android:id="@+id/vermas"
                    android:layout_width="256dp"
                    android:layout_height="100dp"
                    android:layout_marginTop="5dp"
                    android:layout_weight="7"
                    android:adjustViewBounds="true"
                    android:src="@drawable/vermas" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical" >

                </LinearLayout>
            </LinearLayout>

        </LinearLayout>
    </LinearLayout>

    </LinearLayout>
</LinearLayout>


text:
layout: post
navbar: Blog
title: "Meeting Agenda - February 9th, 2017"
date: 2017-02-09 12:00:00 -0400
comments: true
categories: Agenda
---

**6:00pm:**

Food and drinks served

### Introduction

A brief overview of the Ohio Information Security Forum.

### **Way-Beyond Patching GPO and Printer Driver Vulnerabilities: How Microsoft Ruined My Summer of 2016**
_By: John Hermes_

#### Abstract

Familiarity and complacence administering the Windows platform lead to some
nasty surprises while managing Microsoft's Active Directory in the Windows 10
era.

Organizations world-wide were caught by surprise during the summer of 2016 when
Microsoft released patches to address critical security vulnerabilities and made
significant changes to both group policy (GP) processing and print driver
enforcement. Here is a first-person account from a distracted, overworked and
reluctant Windows administrator who didn't see it coming.

First, we'll take a quick tour of GP basics and examine the security issue that
forced changes to how they're applied. Next, we'll look at flipping our
perspective on permissions for deploying effective policies. Finally, we'll take
a look at the Vista-era printer driver model that was effectively ignored by
some big vendors - until Microsoft made it mandatory. We'll see why some
big-name printers still refuse to deploy and then learn the surprisingly simple
way to bypass these new restrictions.

#### Bio

John Hermes is a prestigious board member for OISF and all around awesome dude.
When John isn't teaching the world how to be better attackers and defenders,
he's policing and securing networks all over.

### **Group Discussion**
_By: Everyone_


text:
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SYS_SPA_BOOT_H
#define	_SYS_SPA_BOOT_H

#include <sys/nvpair.h>

#ifdef	__cplusplus
extern "C" {
#endif

extern char *spa_get_bootprop(char *prop);
extern void spa_free_bootprop(char *prop);

#ifdef	__cplusplus
}
#endif

#endif	/* _SYS_SPA_BOOT_H */


text:
/**
 * Spotify Object
 */
var spotify =
{
    track: {
        uri: null,
        title: "Untitled",
        artist: "Unknown",
        time: "0:00",
        length: "1:00",
        cover: null
    },
    player: {
        status: "playing"
    },
    events: {
        upcoming: {
            timestamp: 0,
            startTime: "0:00",
            endTime: "0:00",
            startEvent: "track-changed",
            endEvent: "track-playing",
            uri: null,
            title: "Untitled",
            artist: "Unknown",
            cover: null
        },
        pending: [],
        acknowledged: []
    },
    tabId: null
};

/**
 * Spotify Injection!
 * Inject the necessary Javascript to every Spotify Play tab
 */

chrome.tabs.query({ url: "*://play.spotify.com/*" }, function(tabs)
{
    if (spotify.tabId == null && tabs != null && tabs.length > 0) inject(tabs[0]);
});

chrome.tabs.onRemoved.addListener(function(tabId, removeInfo)
{
    if (spotify.tabId != null && tabId == spotify.tabId)
    {
        spotify.tabId = null;
        newEventHandle(); // Force to create a new event
    }
});

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab)
{
    if (!String.prototype.contains) {
        String.prototype.contains = function(s, i) {
            return this.indexOf(s, i) != -1;
        }
    }

    if (spotify.tabId == null && tab.url.contains("://play.spotify.com/")) inject(tab);
});

function inject(tab)
{
    spotify.tabId = tab.id;
    console.log("Injecting JS in " + tab.url + "!");
    chrome.tabs.executeScript(spotify.tabId, {file: "js/spotify/injection.js"});
    console.log("Injection completed!");
}

/**
 * Spotify Player Controllers
 *
 * playPauseTrack - Play/Pause Spotify Player
 * previousTrack - Change to previous track
 * nextTrack - Change to next track
 *
 */

function playPauseTrack() {
    if (spotify.tabId != null)
        chrome.tabs.executeScript(spotify.tabId,{code: 'document.querySelector("#app-player").contentDocument.body.querySelector("#play-pause").click();'});
}

function previousTrack() {
    if (spotify.tabId != null)
        chrome.tabs.executeScript(spotify.tabId, {code: 'document.querySelector("#app-player").contentDocument.body.querySelector("#previous").click();'});
}

function nextTrack() {
    if (spotify.tabId != null)
        chrome.tabs.executeScript(spotify.tabId, {code: 'document.querySelector("#app-player").contentDocument.body.querySelector("#next").click();'});
}

/**
 * An update from Spotify Play
 */
chrome.extension.onMessage.addListener(function(request, sender)
{
    if (request.action == "spotify-update")
    {
        var newValue = request.value;

        // Update events
        eventHandler(newValue);

        // Update track and player
        spotify.track.cover = newValue.track.cover;
        spotify.track.title = newValue.track.title;
        spotify.track.artist = newValue.track.artist;
        spotify.track.uri = newValue.track.uri;
        if (newValue.track.time != "") spotify.track.time = newValue.track.time;
        spotify.track.length = newValue.track.length;
        spotify.player.status = newValue.player.status;
    }
});

/**
 * Update events with the new information
 * @param newValue New Spotify Object
 */
function eventHandler(newValue)
{
    var WAIT_WINDOW = 5000; // 5 seconds
    var currentTS = new Date().getTime();
    var timeFromLatestUpdate = Math.abs(timeToSeconds(newValue.track.time) - timeToSeconds(spotify.track.time));

    // Always update the current time except if its value is "0:00"
    if (newValue.track.time != "0:00" && newValue.track.time != "") spotify.events.upcoming.endTime = newValue.track.time;

    // If a new track is playing
    if (spotify.track.cover != newValue.track.cover ||
        spotify.track.uri != newValue.track.uri ||
        spotify.track.title != newValue.track.title ||
        spotify.track.artist != newValue.track.artist ||
        spotify.track.length != newValue.track.length)
    {
        // A trick to know if the events belong to the same track or not
        if (currentTS - spotify.events.upcoming.timestamp > WAIT_WINDOW) newEventHandle(newValue, false);

        // Update upcoming event
        spotify.events.upcoming.timestamp = currentTS;
        spotify.events.upcoming.cover = newValue.track.cover;
        spotify.events.upcoming.title = newValue.track.title;
        spotify.events.upcoming.artist = newValue.track.artist;
        if (newValue.track.uri.split(":").length == 3)
            spotify.events.upcoming.uri = newValue.track.uri.split(":")[2];
    }
    // If the user has seek a specific part of the track
    else if (timeFromLatestUpdate > 2 && newValue.track.time != "0:00")
    {
        // In seeks, we keep the old time
        spotify.events.upcoming.endTime = spotify.track.time;

        newEventHandle(newValue, true);

        // Update upcoming event
        spotify.events.upcoming.timestamp = currentTS;
        spotify.events.upcoming.cover = newValue.track.cover;
        spotify.events.upcoming.title = newValue.track.title;
        spotify.events.upcoming.artist = newValue.track.artist;
        if (newValue.track.uri.split(":").length == 3)
            spotify.events.upcoming.uri = newValue.track.uri.split(":")[2];
    }
}

/**
 * Handle the creation of a new event
 * @param newValue New Spotify Object
 * @param isSeek If it is the same track but a different part
 */
function newEventHandle(newValue, isSeek)
{
    // Set the reason because the upcoming event must end
    if (spotify.events.upcoming.endTime == spotify.track.length) spotify.events.upcoming.endEvent = 'track-ended';
    else if (spotify.tabId == null) spotify.events.upcoming.endEvent = 'tab-closed';
    else if (isSeek) spotify.events.upcoming.endEvent = 'track-seek';
    else spotify.events.upcoming.endEvent = 'track-changed';

    // Apparently, there is a case in which endTime is empty
    if (spotify.events.upcoming.endTime == null || spotify.events.upcoming.endTime == "") spotify.events.upcoming.endTime = "0:00";

    // Just, if it is not the initial event
    if (spotify.events.upcoming.startTime != spotify.events.upcoming.endTime && (spotify.events.upcoming.uri != null || isSeek))
    {
        printEvent();
        spotify.events.pending.unshift(spotify.events.upcoming);
        sendEvent(spotify.events.upcoming);
    }

    // Create an upcoming event with the reason because it was created
    if(isSeek)
    {
        spotify.events.upcoming =
        {
            startTime: newValue.track.time,
            startEvent: "track-seek",
            endEvent: "track-playing"
        };
    }
    else
    {
        spotify.events.upcoming =
        {
            startTime: "0:00",
            startEvent: "track-changed",
            endEvent: "track-playing"
        };
    }
}

/**
 * Send a new event to the backend
 * @param event Event to be sent
 */
function sendEvent(event)
{
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = (function(e)
    {
        return function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                var index = spotify.events.pending.indexOf(e);
                if (index > -1) {
                    spotify.events.pending.splice(index, 1);
                    spotify.events.acknowledged.unshift(e);
                }
            }
        }
    })(event);

    xmlhttp.open("POST","http://api.hipstogram.io:8081/events",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("content=[" + JSON.stringify(event) + "]");
}

/**
 * Print the upcoming event - Just for debug purposes
 */
function printEvent()
{
    console.log("New event");
    console.log("---------------------");
    console.log(spotify.events.upcoming.cover);
    console.log(spotify.events.upcoming.title);
    console.log(spotify.events.upcoming.artist);
    console.log(spotify.events.upcoming.uri);
    console.log(spotify.events.upcoming.startTime);
    console.log(spotify.events.upcoming.startEvent);
    console.log(spotify.events.upcoming.endTime);
    console.log(spotify.events.upcoming.endEvent);
    console.log("---------------------");
}

/**
 * Convert time in format "mm:ss" to seconds
 * @param time Time in format "mm:ss"
 * @returns {number} Number of seconds
 */
function timeToSeconds(time)
{
    var a = time.split(':');
    var seconds = (+a[0]) * 60 + (+a[1]);
    return seconds;
}


text:
          #ifndef EXCHANGETRADER_H
          #define EXCHANGETRADER_H

        /**
         * ExchangeTrader.h
         *
         * This file was auto-generated from WSDL for "ExchangeTrader|http://www.wso2.org" service
         * by the Apache Axis2 version: #axisVersion# #today#
         *  ExchangeTrader
         */

#include <ServiceSkeleton.h>
#include <stdio.h>
#include <axis2_svc.h>

using namespace wso2wsf;

using namespace org_wso2_www;

#define WSF_SERVICE_SKEL_INIT(class_name) \
ExchangeTraderSkeleton* wsfGetExchangeTraderSkeleton(){ return new class_name(); }

ExchangeTraderSkeleton* wsfGetExchangeTraderSkeleton();

        class ExchangeTrader : public ServiceSkeleton
        {
            private:
                ExchangeTraderSkeleton *skel;

            public:

               union {

               } fault;

              WSF_EXTERN WSF_CALL ExchangeTrader();

              OMElement* WSF_CALL invoke(OMElement *message, MessageContext *msgCtx);

              OMElement* WSF_CALL onFault(OMElement *message);

              bool WSF_CALL init();

              ~ExchangeTrader();
      };

#endif    //     EXCHANGETRADER_H


text:
package org.apache.mnemonic.collections;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import org.apache.mnemonic.EntityFactoryProxyHelper;
import org.apache.mnemonic.NonVolatileMemAllocator;
import org.apache.mnemonic.EntityFactoryProxy;
import org.apache.mnemonic.Reclaim;
import org.apache.mnemonic.Utils;
import org.apache.mnemonic.DurableType;
import org.apache.mnemonic.ParameterHolder;
import org.testng.AssertJUnit;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

/**
 *
 *
 */

public class DurableSinglyLinkedListWithParamHolderNGTest {
  private long cKEYCAPACITY;
  private Random m_rand;
  private NonVolatileMemAllocator m_act;
  private ParameterHolder ph;

  @BeforeClass
  public void setUp() {
    m_rand = Utils.createRandom();
    m_act = new NonVolatileMemAllocator(Utils.getNonVolatileMemoryAllocatorService("pmalloc"), 1024 * 1024 * 1024,
        "./pobj_NodeValue_WithParamHolder.dat", true);
    ph = new ParameterHolder();

      cKEYCAPACITY = m_act.handlerCapacity();
    m_act.setBufferReclaimer(new Reclaim<ByteBuffer>() {
      @Override
      public boolean reclaim(ByteBuffer mres, Long sz) {
        System.out.println(String.format("Reclaim Memory Buffer: %X  Size: %s", System.identityHashCode(mres),
            null == sz ? "NULL" : sz.toString()));
        return false;
      }
    });
    m_act.setChunkReclaimer(new Reclaim<Long>() {
      @Override
      public boolean reclaim(Long mres, Long sz) {
        System.out.println(String.format("Reclaim Memory Chunk: %X  Size: %s", System.identityHashCode(mres),
            null == sz ? "NULL" : sz.toString()));
        return false;
      }
    });

    for (long i = 0; i < cKEYCAPACITY; ++i) {
      m_act.setHandler(i, 0L);
    }
  }

  @AfterClass
  public void tearDown() {
    m_act.close();
  }

  @Test(enabled = false)
  public void testSingleNodeValueWithInteger() {
    int val = m_rand.nextInt();
    DurableType gtypes[] = {DurableType.INTEGER};
    SinglyLinkedNode<Integer> plln = SinglyLinkedNodeFactory.create(
            m_act, null, gtypes, false);
    plln.setItem(val, false);
    Long handler = plln.getHandler();
    System.err.println("-------------Start to Restore Integer -----------");
    SinglyLinkedNode<Integer> plln2 = SinglyLinkedNodeFactory.restore(
            m_act, null, gtypes, handler,
        false);
    AssertJUnit.assertEquals(val, (int) plln2.getItem());
  }

  @Test(enabled = false)
  public void testNodeValueWithString() {
    String val = Utils.genRandomString();
    DurableType gtypes[] = {DurableType.STRING};
    SinglyLinkedNode<String> plln = SinglyLinkedNodeFactory.create(m_act, null, gtypes, false);
    plln.setItem(val, false);
    Long handler = plln.getHandler();
    System.err.println("-------------Start to Restore String-----------");
    SinglyLinkedNode<String> plln2 = SinglyLinkedNodeFactory.restore(m_act, null, gtypes, handler,
        false);
    AssertJUnit.assertEquals(val, plln2.getItem());
  }

  @Test(enabled = false)
  public void testNodeValueWithPerson() throws NoSuchMethodException, ClassNotFoundException {

    DurableType gtypes[] = {DurableType.DURABLE};
    EntityFactoryProxy efproxies[] = {new EntityFactoryProxyHelper<Person>(Person.class)};

    ph.setAllocator(m_act);
    ph.setEntityFactoryProxies(efproxies);
    ph.setGenericTypes(gtypes);
    ph.setAutoReclaim(false);

    @SuppressWarnings("unchecked")
    Person<Long> person =  (Person<Long>) efproxies[0].create(m_act, null, null, false);
    person.setAge((short) 31);

    SinglyLinkedNode<Person<Long>> plln = SinglyLinkedNodeFactory.create(ph);
    plln.setItem(person, false);

    long handler = plln.getHandler();
    ph.setHandler(handler);

    SinglyLinkedNode<Person<Long>> plln2 = SinglyLinkedNodeFactory.restore(ph);
    AssertJUnit.assertEquals(31, (int) plln2.getItem().getAge());

  }

  @SuppressWarnings("unchecked")
  @Test(enabled = false)
  public void testLinkedNodeValueWithPerson() throws NoSuchMethodException, ClassNotFoundException {

    int elem_count = 10;
    List<Long> referlist = new ArrayList();

    DurableType listgftypes[] = {DurableType.DURABLE};
    EntityFactoryProxy listefproxies[] = {new EntityFactoryProxyHelper<Person>(Person.class)};

    ph.setAllocator(m_act);
    ph.setEntityFactoryProxies(listefproxies);
    ph.setGenericTypes(listgftypes);
    ph.setAutoReclaim(false);

    DurableSinglyLinkedList<Person<Long>> list = DurableSinglyLinkedListFactory.create(ph);

    SinglyLinkedNode<Person<Long>> firstnv = list.createNode();

    SinglyLinkedNode<Person<Long>> nextnv = firstnv;

    Person<Long> person;
    long val;
    SinglyLinkedNode<Person<Long>> newnv;
    for (int i = 0; i < elem_count; ++i) {
      person = (Person<Long>) listefproxies[0].create(m_act, null, null, false);
      person.setAge((short) m_rand.nextInt(50));
      person.setName(String.format("Name: [%s]", Utils.genRandomString()), true);
      nextnv.setItem(person, false);
      newnv = list.createNode();
      nextnv.setNext(newnv, false);
      nextnv = newnv;
    }

    Person<Long> eval;
    list.setHeadHandler(firstnv.getHandler());
    list.reset();
    while (list.forwardNode()) {
      System.out.printf(" Stage 1 --->\n");
      eval = list.getCurrentNode().getItem();
      if (null != eval) {
        eval.testOutput();
      }
    }

    // Assert.assert, expected);(plist, plist2);

  }

  @Test(enabled = true)
  public void testLinkedNodeValueWithLinkedNodeValue() throws NoSuchMethodException, ClassNotFoundException {

    int elem_count = 10;
    long slotKeyId = 10;
    ParameterHolder phe = new ParameterHolder();
    ParameterHolder phl = new ParameterHolder();

    DurableType[] elem_gftypes = {DurableType.DOUBLE};
    EntityFactoryProxy[] elem_efproxies = null;

    DurableType linkedgftypes[] = {DurableType.DURABLE, DurableType.DOUBLE};
    EntityFactoryProxy linkedefproxies[] = {
        new EntityFactoryProxyHelper<DurableSinglyLinkedList>(DurableSinglyLinkedList.class, 1)};

    SinglyLinkedNode<SinglyLinkedNode<Double>> nextnv = null, pre_nextnv = null;
    SinglyLinkedNode<Double> elem = null, pre_elem = null, first_elem = null;

    Long linkhandler = 0L;

    System.out.printf(" Stage 1 -testLinkedNodeValueWithLinkedNodeValue--> \n");

    pre_nextnv = null;
    Double val;
    phe.setAllocator(m_act);
    phe.setEntityFactoryProxies(elem_efproxies);
    phe.setGenericTypes(elem_gftypes);
    phe.setAutoReclaim(false);
    phl.setAllocator(m_act);
    phl.setEntityFactoryProxies(linkedefproxies);
    phl.setGenericTypes(linkedgftypes);
    phl.setAutoReclaim(false);

    for (int i = 0; i < elem_count; ++i) {
      first_elem = null;
      pre_elem = null;

      for (int v = 0; v < 3; ++v) {
        elem = SinglyLinkedNodeFactory.create(phe);
        val = m_rand.nextDouble();
        elem.setItem(val, false);
        if (null == pre_elem) {
          first_elem = elem;
        } else {
          pre_elem.setNext(elem, false);
        }
        pre_elem = elem;
        System.out.printf("%f ", val);
      }

      nextnv = SinglyLinkedNodeFactory.create(phl);
      nextnv.setItem(first_elem, false);
      if (null == pre_nextnv) {
        linkhandler = nextnv.getHandler();
      } else {
        pre_nextnv.setNext(nextnv, false);
      }
      pre_nextnv = nextnv;
      System.out.printf(" generated an item... \n");
    }
    m_act.setHandler(slotKeyId, linkhandler);

    long handler = m_act.getHandler(slotKeyId);
    phl.setHandler(handler);

    DurableSinglyLinkedList<DurableSinglyLinkedList<Double>> linkedvals =
            DurableSinglyLinkedListFactory.restore(phl);
    Iterator<DurableSinglyLinkedList<Double>> iter = linkedvals.iterator();
    Iterator<Double> elemiter = null;

    System.out.printf(" Stage 2 -testLinkedNodeValueWithLinkedNodeValue--> \n");
    while (iter.hasNext()) {
      elemiter = iter.next().iterator();
      while (elemiter.hasNext()) {
        System.out.printf("%f ", elemiter.next());
      }
      System.out.printf(" Fetched an item... \n");
    }

    // Assert.assert, expected);(plist, plist2);

  }

}


text: const char *version_string;


text:
<!DOCTYPE html>

		<?php require_once('./include/common_head.inc.php'); ?>
		<title><?php echo L_PROB_DESC." - {$OJ_NAME}";?></title>

		<?php require("./pages/components/navbar.php");?>

<?php echo $problemItem['problem_id']." : ".$problemItem['title'];?>

				<?php echo L_TIME_LIMIT;?>:<?php echo $problemItem['time_limit']." Sec";?>
				<?php echo L_MEM_LIMIT;?>:<?php echo $problemItem['memory_limit']." MiB";?>

				<?php echo L_SUBMIT;?>:<?php echo $problemItem['submit'];?>
				<?php echo L_JUDGE_AC;?>:<?php echo $problemItem['accepted'];?>

				<a id="oj-p-submit" class="btn btn-primary" href="./problemsubmit.php?pid=<?php echo $problemItem['problem_id'];?>" role="button"><?php echo L_SUBMIT;?>
				<a class="btn btn-primary" href="./problemstatistics.php?pid=<?php echo $problemItem['problem_id'];?>" role="button"><?php echo L_STATUS;?>
				<?php if ($isProblemManager) { ?><a class="btn btn-primary" href="./admin/problem_editor.php?nid=<?php echo $problemItem['problem_id'];?>" role="button"><?php echo L_EDIT;?><?php } ?>
				<?php if ($FORUM_ENABLED) { ?><a class="btn btn-primary" href="./discuss.php?pid=<?php echo $problemItem['problem_id'];?>" role="button"><?php echo L_FORUM;?><?php } ?>

<?php echo L_PROB_DESC;?>

<?php echo $problemItem['description'];?>

<?php echo L_INPUT;?>

<?php echo $problemItem['input'];?>

<?php echo L_OUTPUT;?>

<?php echo $problemItem['output'];?>

<?php echo L_SAMP_INPUT;?>

					复制

<?php echo $problemItem['sample_input'];?>

<?php echo L_SAMP_OUTPUT;?>

					复制

<?php echo $problemItem['sample_output'];?>

<?php echo L_HINT;?>

<?php echo $problemItem['hint'];?>

<?php echo L_SOURCE;?>

<?php echo $problemItem['source'];?>

		<?php require("./pages/components/footer.php");?>


text: python manage.py migrate && python manage.py runserver 0.0.0.0:$PORT


text:
package org.apache.lucene.benchmark.byTask.feeds;

import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.context.SpatialContextFactory;
import com.spatial4j.core.shape.Point;
import com.spatial4j.core.shape.Shape;
import org.apache.lucene.benchmark.byTask.utils.Config;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.spatial.SpatialStrategy;
import org.apache.lucene.spatial.prefix.RecursivePrefixTreeStrategy;
import org.apache.lucene.spatial.prefix.tree.SpatialPrefixTree;
import org.apache.lucene.spatial.prefix.tree.SpatialPrefixTreeFactory;

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;

/**
 * Indexes spatial data according to a configured {@link SpatialStrategy} with optional
 * shape transformation via a configured {@link ShapeConverter}. The converter can turn points into
 * circles and bounding boxes, in order to vary the type of indexing performance tests.
 * Unless it's subclass-ed to do otherwise, this class configures a {@link SpatialContext},
 * {@link SpatialPrefixTree}, and {@link RecursivePrefixTreeStrategy}. The Strategy is made
 * available to a query maker via the static method {@link #getSpatialStrategy(int)}.
 * See spatial.alg for a listing of spatial parameters, in particular those starting with "spatial."
 * and "doc.spatial".
 */
public class SpatialDocMaker extends DocMaker {

  public static final String SPATIAL_FIELD = "spatial";

  //cache spatialStrategy by round number
  private static Map<Integer,SpatialStrategy> spatialStrategyCache = new HashMap<Integer,SpatialStrategy>();

  private SpatialStrategy strategy;
  private ShapeConverter shapeConverter;

  /**
   * Looks up the SpatialStrategy from the given round --
   * {@link org.apache.lucene.benchmark.byTask.utils.Config#getRoundNumber()}. It's an error
   * if it wasn't created already for this round -- when SpatialDocMaker is initialized.
   */
  public static SpatialStrategy getSpatialStrategy(int roundNumber) {
    SpatialStrategy result = spatialStrategyCache.get(roundNumber);
    if (result == null) {
      throw new IllegalStateException("Strategy should have been init'ed by SpatialDocMaker by now");
    }
    return result;
  }

  /**
   * Builds a SpatialStrategy from configuration options.
   */
  protected SpatialStrategy makeSpatialStrategy(final Config config) {
    //A Map view of Config that prefixes keys with "spatial."
    Map<String, String> configMap = new AbstractMap<String, String>() {
      @Override
      public Set<Entry<String, String>> entrySet() {
        throw new UnsupportedOperationException();
      }

      @Override
      public String get(Object key) {
        return config.get("spatial." + key, null);
      }
    };

    SpatialContext ctx = SpatialContextFactory.makeSpatialContext(configMap, null);

    //Some day the strategy might be initialized with a factory but such a factory
    // is non-existent.
    return makeSpatialStrategy(config, configMap, ctx);
  }

  protected SpatialStrategy makeSpatialStrategy(final Config config, Map<String, String> configMap,
                                                SpatialContext ctx) {
    //A factory for the prefix tree grid
    SpatialPrefixTree grid = SpatialPrefixTreeFactory.makeSPT(configMap, null, ctx);

    RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, SPATIAL_FIELD) {
      {
        //protected field
        this.pointsOnly = config.get("spatial.docPointsOnly", false);
      }
    };

    int prefixGridScanLevel = config.get("query.spatial.prefixGridScanLevel", -4);
    if (prefixGridScanLevel < 0)
      prefixGridScanLevel = grid.getMaxLevels() + prefixGridScanLevel;
    strategy.setPrefixGridScanLevel(prefixGridScanLevel);

    double distErrPct = config.get("spatial.distErrPct", .025);//doc & query; a default
    strategy.setDistErrPct(distErrPct);
    return strategy;
  }

  @Override
  public void setConfig(Config config, ContentSource source) {
    super.setConfig(config, source);
    SpatialStrategy existing = spatialStrategyCache.get(config.getRoundNumber());
    if (existing == null) {
      //new round; we need to re-initialize
      strategy = makeSpatialStrategy(config);
      spatialStrategyCache.put(config.getRoundNumber(), strategy);
      //TODO remove previous round config?
      shapeConverter = makeShapeConverter(strategy, config, "doc.spatial.");
      System.out.println("Spatial Strategy: " + strategy);
    }
  }

  /**
   * Optionally converts points to circles, and optionally bbox'es result.
   */
  public static ShapeConverter makeShapeConverter(final SpatialStrategy spatialStrategy,
                                                  Config config, String configKeyPrefix) {
    //by default does no conversion
    final double radiusDegrees = config.get(configKeyPrefix+"radiusDegrees", 0.0);
    final double plusMinus = config.get(configKeyPrefix+"radiusDegreesRandPlusMinus", 0.0);
    final boolean bbox = config.get(configKeyPrefix + "bbox", false);

    return new ShapeConverter() {
      @Override
      public Shape convert(Shape shape) {
        if (shape instanceof Point && (radiusDegrees != 0.0 || plusMinus != 0.0)) {
          Point point = (Point)shape;
          double radius = radiusDegrees;
          if (plusMinus > 0.0) {
            Random random = new Random(point.hashCode());//use hashCode so it's reproducibly random
            radius += random.nextDouble() * 2 * plusMinus - plusMinus;
            radius = Math.abs(radius);//can happen if configured plusMinus > radiusDegrees
          }
          shape = spatialStrategy.getSpatialContext().makeCircle(point, radius);
        }
        if (bbox)
          shape = shape.getBoundingBox();
        return shape;
      }
    };
  }

  /** Converts one shape to another. Created by
   * {@link #makeShapeConverter(org.apache.lucene.spatial.SpatialStrategy, org.apache.lucene.benchmark.byTask.utils.Config, String)} */
  public interface ShapeConverter {
    Shape convert(Shape shape);
  }

  @Override
  public Document makeDocument() throws Exception {

    DocState docState = getDocState();

    Document doc = super.makeDocument();

    // Set SPATIAL_FIELD from body
    DocData docData = docState.docData;
    //   makeDocument() resets docState.getBody() so we can't look there; look in Document
    String shapeStr = doc.getField(DocMaker.BODY_FIELD).stringValue();
    Shape shape = makeShapeFromString(strategy, docData.getName(), shapeStr);
    if (shape != null) {
      shape = shapeConverter.convert(shape);
      //index
      for (Field f : strategy.createIndexableFields(shape)) {
        doc.add(f);
      }
    }

    return doc;
  }

  public static Shape makeShapeFromString(SpatialStrategy strategy, String name, String shapeStr) {
    if (shapeStr != null && shapeStr.length() > 0) {
      try {
        return strategy.getSpatialContext().readShapeFromWkt(shapeStr);
      } catch (Exception e) {//InvalidShapeException TODO
        System.err.println("Shape "+name+" wasn't parseable: "+e+"  (skipping it)");
        return null;
      }
    }
    return null;
  }

  @Override
  public Document makeDocument(int size) throws Exception {
    //TODO consider abusing the 'size' notion to number of shapes per document
    throw new UnsupportedOperationException();
  }
}


text:
struct A; // expected-note 4 {{forward declaration of 'A'}}

struct Abstract { virtual void f() = 0; }; // expected-note {{unimplemented pure virtual method 'f'}}

void trys() {
  try {
  } catch(int i) { // expected-note {{previous definition}}
    int j = i;
    int i; // expected-error {{redefinition of 'i'}}
  } catch(float i) {
  } catch(void v) { // expected-error {{cannot catch incomplete type 'void'}}
  } catch(A a) { // expected-error {{cannot catch incomplete type 'A'}}
  } catch(A *a) { // expected-error {{cannot catch pointer to incomplete type 'A'}}
  } catch(A &a) { // expected-error {{cannot catch reference to incomplete type 'A'}}
  } catch(Abstract) { // expected-error {{variable type 'Abstract' is an abstract class}}
  } catch(...) {
    int j = i; // expected-error {{use of undeclared identifier 'i'}}
  }

  try {
  } catch(...) { // expected-error {{catch-all handler must come last}}
  } catch(int) {
  }
}

void throws() {
  throw;
  throw 0;
  throw throw; // expected-error {{cannot throw object of incomplete type 'void'}}
  throw (A*)0; // expected-error {{cannot throw pointer to object of incomplete type 'A'}}
}

void jumps() {
l1:
  goto l5;
  goto l4; // expected-error {{goto into protected scope}}
  goto l3; // expected-error {{goto into protected scope}}
  goto l2; // expected-error {{goto into protected scope}}
  goto l1;
  try { // expected-note 4 {{jump bypasses initialization of try block}}
  l2:
    goto l5;
    goto l4; // expected-error {{goto into protected scope}}
    goto l3; // expected-error {{goto into protected scope}}
    goto l2;
    goto l1;
  } catch(int) { // expected-note 4 {{jump bypasses initialization of catch block}}
  l3:
    goto l5;
    goto l4; // expected-error {{goto into protected scope}}
    goto l3;
    goto l2; // expected-error {{goto into protected scope}}
    goto l1;
  } catch(...) { // expected-note 4 {{jump bypasses initialization of catch block}}
  l4:
    goto l5;
    goto l4;
    goto l3; // expected-error {{goto into protected scope}}
    goto l2; // expected-error {{goto into protected scope}}
    goto l1;
  }
l5:
  goto l5;
  goto l4; // expected-error {{goto into protected scope}}
  goto l3; // expected-error {{goto into protected scope}}
  goto l2; // expected-error {{goto into protected scope}}
  goto l1;
}

struct BadReturn {
  BadReturn() try {
  } catch(...) {
    // Try to hide
    try {
    } catch(...) {
      {
        if (0)
          return; // expected-error {{return in the catch of a function try block of a constructor is illegal}}
      }
    }
  }
  BadReturn(int);
};

BadReturn::BadReturn(int) try {
} catch(...) {
  // Try to hide
  try {
  } catch(int) {
    return; // expected-error {{return in the catch of a function try block of a constructor is illegal}}
  } catch(...) {
    {
      if (0)
        return; // expected-error {{return in the catch of a function try block of a constructor is illegal}}
    }
  }
}

// Cannot throw an abstract type.
class foo {
public:
  foo() {}
  void bar () {
    throw *this; // expected-error{{cannot throw an object of abstract type 'foo'}}
  }
  virtual void test () = 0; // expected-note{{unimplemented pure virtual method 'test'}}
};

namespace PR6831 {
  namespace NA { struct S; }
  namespace NB { struct S; }

  void f() {
    using namespace NA;
    using namespace NB;
    try {
    } catch (int S) {
    }
  }
}


text:
describe Travis::Config::Heroku do
  let(:config) { Travis::Test::Config.load(:heroku) }
  let(:vars)   { %w(DATABASE_URL POOL_SIZE) }
  after        { vars.each { |key| ENV.delete(key) } }
  before       { ENV['DATABASE_URL'] = 'postgres://username:password@hostname:port/database' }

  it 'loads a DATABASE_URL with a port' do
    expect(config.database.to_hash).to eq(
      adapter:  'postgresql',
      host:     'hostname',
      port:     'port',
      database: 'database',
      username: 'username',
      password: 'password',
      encoding: 'unicode'
    )
  end

  it 'loads a DATABASE_URL without a port' do
    ENV['DATABASE_URL'] = 'postgres://username:password@hostname/database'

    expect(config.database.to_hash).to eq(
      adapter:  'postgresql',
      host:     'hostname',
      database: 'database',
      username: 'username',
      password: 'password',
      encoding: 'unicode'
    )
  end

  it 'loads DB_POOL' do
    ENV['DB_POOL'] = '25'

    expect(config.database.to_hash).to eq(
      adapter:  'postgresql',
      host:     'hostname',
      port:     'port',
      database: 'database',
      username: 'username',
      password: 'password',
      encoding: 'unicode',
      pool:     25
    )
  end
end


text:
namespace Owin.Security.CogniStreamer
{
    public static class CogniStreamerAuthenticationDefaults
    {
        public const string AuthenticationType = "CogniStreamer";
        public const string CallbackPath = "/signin-cognistreamer";
    }
}