text:
var config = require('../config.json');
var redisStore = require('../../index');
var sinon = require('sinon');
var assert = require('assert');

var redisCache;
var customRedisCache;
var sandbox;
var injectError;

before(function () {
  redisCache = require('cache-manager').caching({
    store: redisStore,
    host: config.redis.host,
    port: config.redis.port,
    auth_pass: config.redis.auth_pass,
    db: config.redis.db,
    ttl: config.redis.ttl
  });

  customRedisCache = require('cache-manager').caching({
    store: redisStore,
    host: config.redis.host,
    port: config.redis.port,
    db: config.redis.db,
    ttl: config.redis.ttl,
    isCacheableValue: function (val) {
      // allow undefined
      if (val === undefined) {
        return true;
      } else if (val === 'FooBarString') {
        // disallow FooBarString
        return false;
      }
      return redisCache.store.isCacheableValue(val);
    }
  });

  sandbox = sinon.sandbox.create();

  injectError = () => {
    var pool = redisCache.store._pool;

    sandbox.stub(pool, 'acquireDb').yieldsAsync('Something unexpected');
    sandbox.stub(pool, 'release');
  };
});

beforeEach(function() {
  sandbox.restore();

  return redisCache.reset();
});

describe ('initialization', function () {

  it('should create a store with password instead of auth_pass (auth_pass is deprecated for redis > 2.5)', function (done) {
    var redisPwdCache = require('cache-manager').caching({
      store: redisStore,
      host: config.redis.host,
      port: config.redis.port,
      password: config.redis.auth_pass,
      db: config.redis.db,
      ttl: config.redis.ttl
    });

    assert.equal(redisPwdCache.store._pool._redis_options.password, config.redis.auth_pass);
    redisPwdCache.set('pwdfoo', 'pwdbar', function (err) {
      assert.equal(err, null);
      redisCache.del('pwdfoo', function (errDel) {
        assert.equal(errDel, null);
        done();
      });
    });
  });

});

describe('set', function () {
  it('should return a promise', function (done) {
    assert.ok(redisCache.set('foo', 'bar') instanceof Promise);
    done();
  });

  it('should resolve promise on success', function (done) {
    redisCache.set('foo', 'bar').then(result => {
      assert.equal(result, 'OK');
      done();
    });
  });

  it('should reject promise on error', function (done) {
    redisCache.set('foo', null)
      .then(() => done(new Error ('Should reject')))
      .catch(() => done());
  });

  it('should store a value without ttl', function (done) {
    redisCache.set('foo', 'bar', function (err) {
      assert.equal(err, null);
      done();
    });
  });

  it('should store a value with a specific ttl', function (done) {
    redisCache.set('foo', 'bar', config.redis.ttl, function (err) {
      assert.equal(err, null);
      done();
    });
  });

  it('should store a value with a infinite ttl', function (done) {
    redisCache.set('foo', 'bar', {ttl: 0}, function (err) {
      assert.equal(err, null);
      redisCache.ttl('foo', function (err, ttl) {
        assert.equal(err, null);
        assert.equal(ttl, -1);
        done();
      });
    });
  });

  it('should not be able to store a null value (not cacheable)', function (done) {
    redisCache.set('foo2', null, function (err) {
      if (err) {
        return done();
      }
      done(new Error('Null is not a valid value!'));
    });
  });

  it('should store a value without callback', function (done) {
    redisCache.set('foo', 'baz');
    redisCache.get('foo', function (err, value) {
      assert.equal(err, null);
      assert.equal(value, 'baz');
      done();
    });
  });

  it('should not store an invalid value', function (done) {
    redisCache.set('foo1', undefined, function (err) {
      try {
        assert.notEqual(err, null);
        assert.equal(err.message, 'value cannot be undefined');
        done();
      } catch (e) {
        done(e);
      }
    });
  });

  it('should store an undefined value if permitted by isCacheableValue', function (done) {
    assert(customRedisCache.store.isCacheableValue(undefined), true);
    customRedisCache.set('foo3', undefined, function (err) {
      try {
        assert.equal(err, null);
        customRedisCache.get('foo3', function (err, data) {
          try {
            assert.equal(err, null);
            // redis stored undefined as 'undefined'
            assert.equal(data, 'undefined');
            done();
          } catch (e) {
            done(e);
          }
        });
      } catch (e) {
        done(e);
      }
    });
  });

  it('should not store a value disallowed by isCacheableValue', function (done) {
    assert.strictEqual(customRedisCache.store.isCacheableValue('FooBarString'), false);
    customRedisCache.set('foobar', 'FooBarString', function (err) {
      try {
        assert.notEqual(err, null);
        assert.equal(err.message, 'value cannot be FooBarString');
        done();
      } catch (e) {
        done(e);
      }
    });
  });

});

describe('get', function () {
  it('should return a promise', function (done) {
    assert.ok(redisCache.get('foo') instanceof Promise);
    done();
  });

  it('should resolve promise on success', function (done) {
    redisCache.set('foo', 'bar')
      .then(() => redisCache.get('foo'))
      .then(result => {
        assert.equal(result, 'bar');
        done();
      });
  });

  it('should reject promise on error', function (done) {
    injectError();
    redisCache.get('foo')
      .then(() => done(new Error ('Should reject')))
      .catch(() => done());
  });

  it('should retrieve a value for a given key', function (done) {
    var value = 'bar';
    redisCache.set('foo', value, function () {
      redisCache.get('foo', function (err, result) {
        assert.equal(err, null);
        assert.equal(result, value);
        done();
      });
    });
  });

  it('should retrieve a value for a given key if options provided', function (done) {
    var value = 'bar';
    redisCache.set('foo', value, function () {
      redisCache.get('foo', {}, function (err, result) {
        assert.equal(err, null);
        assert.equal(result, value);
        done();
      });
    });
  });

  it('should return null when the key is invalid', function (done) {
    redisCache.get('invalidKey', function (err, result) {
      assert.equal(err, null);
      assert.equal(result, null);
      done();
    });
  });

  it('should return an error if there is an error acquiring a connection', function (done) {
    injectError();
    redisCache.get('foo', function (err) {
      assert.notEqual(err, null);
      done();
    });
  });
});

describe('del', function () {
  it('should return a promise', function () {
    assert.ok(redisCache.del('foo', 'bar') instanceof Promise);
  });

  it('should resolve promise on success', function () {
    return redisCache.del('foo', 'bar').then(result => assert.equal(result, 'OK'));
  });

  it('should reject promise on error', function () {
    injectError();

    return redisCache.del('foo').then(res => assert.fail(res), err => assert.notEqual(err, null));
  });

  it('should delete a value for a given key', function (done) {
    redisCache.set('foo', 'bar', function () {
      redisCache.del('foo', function (err) {
        assert.equal(err, null);
        done();
      });
    });
  });

  it('should delete a value for a given key without callback', function (done) {
    redisCache.set('foo', 'bar', function () {
      redisCache.del('foo');
      done();
    });
  });

  it('should delete multiple values for a given array of keys', function (done) {
    redisCache.set('foo', 'bar', function () {
      redisCache.set('bar', 'baz', function () {
        redisCache.set('baz', 'foo', function () {
          redisCache.del(['foo', 'bar', 'baz'], function (err) {
            assert.equal(err, null);
            done();
          });
        });
      });
    });
  });

  it('should delete multiple values for a given array of keys without callback', function (done) {
    redisCache.set('foo', 'bar', function () {
      redisCache.set('bar', 'baz', function () {
        redisCache.set('baz', 'foo', function () {
          redisCache.del(['foo', 'bar', 'baz']);
          done();
        });
      });
    });
  });

  it('should return an error if there is an error acquiring a connection', function (done) {
    injectError();
    redisCache.set('foo', 'bar', function () {
      redisCache.del('foo', function (err) {
        assert.notEqual(err, null);
        done();
      });
    });
  });
});

describe('reset', function () {
  it('should return a promise', function () {
    assert.ok(redisCache.reset() instanceof Promise);
  });

  it('should resolve promise on success', function () {
    return redisCache.reset().then(result => assert.equal(result, 'OK'));
  });

  it('should reject promise on error', function () {
    injectError();

    return redisCache.reset().then(res => assert.fail(res), err => assert.notEqual(err, null));
  });

  it('should flush underlying db', function (done) {
    redisCache.reset(function (err) {
      assert.equal(err, null);
      done();
    });
  });

  it('should flush underlying db without callback', function (done) {
    redisCache.reset();
    done();
  });

  it('should return an error if there is an error acquiring a connection', function (done) {
    injectError();
    redisCache.reset(function (err) {
      assert.notEqual(err, null);
      done();
    });
  });
});

describe('ttl', function () {
  it('should return a promise', function () {
    assert.ok(redisCache.ttl('foo') instanceof Promise);
  });

  it('should resolve promise on success', function () {
    return redisCache.ttl('foo').then(result => assert.ok(Number.isInteger(result)));
  });

  it('should reject promise on error', function () {
    injectError();

    return redisCache.ttl('foo').then(() => assert.fail(), err => assert.notEqual(err, null));
  });

  it('should retrieve ttl for a given key', function (done) {
    redisCache.set('foo', 'bar', function () {
      redisCache.ttl('foo', function (err, ttl) {
        assert.equal(err, null);
        assert.equal(ttl, config.redis.ttl);
        done();
      });
    });
  });

  it('should retrieve ttl for an invalid key', function (done) {
    redisCache.ttl('invalidKey', function (err, ttl) {
      assert.equal(err, null);
      assert.notEqual(ttl, null);
      done();
    });
  });

  it('should return an error if there is an error acquiring a connection', function (done) {
    injectError();
    redisCache.set('foo', 'bar', function () {
      redisCache.ttl('foo', function (err) {
        assert.notEqual(err, null);
        done();
      });
    });
  });
});

describe('keys', function () {
  it('should return a promise', function () {
    assert.ok(redisCache.keys('f*') instanceof Promise);
  });

  it('should resolve promise on success', function () {
    return redisCache.keys('f*').then(result => assert.ok(Array.isArray(result)));
  });

  it('should reject promise on error', function () {
    injectError();

    return redisCache.keys('f*').then(res => assert.fail(res), err => assert.notEqual(err, null));
  });

  it('should return an array of keys for the given pattern', function (done) {
    redisCache.set('foo', 'bar', function () {
      redisCache.set('far', 'boo', function () {
        redisCache.set('faz', 'bam', function () {
          redisCache.keys('f*', function (err, arrayOfKeys) {
            assert.equal(err, null);
            assert.notEqual(arrayOfKeys, null);
            assert.notEqual(arrayOfKeys.indexOf('foo'), -1);
            assert.equal(arrayOfKeys.length, 3);
            done();
          });
        });
      });
    });
  });

  it('should accept a scanCount option', function (done) {
    redisCache.set('foo', 'bar', function () {
      redisCache.set('far', 'boo', function () {
        redisCache.set('faz', 'bam', function () {
          redisCache.keys('f*', { scanCount: 10 }, function (err, arrayOfKeys) {
            assert.equal(err, null);
            assert.notEqual(arrayOfKeys, null);
            assert.notEqual(arrayOfKeys.indexOf('foo'), -1);
            assert.equal(arrayOfKeys.length, 3);
            done();
          });
        });
      });
    });
  });

  it('should return an array of keys without pattern', function (done) {
    redisCache.set('foo', 'bar', function () {
      redisCache.set('far', 'boo', function () {
        redisCache.set('faz', 'bam', function () {
          redisCache.keys(function (err, arrayOfKeys) {
            assert.equal(err, null);
            assert.notEqual(arrayOfKeys, null);
            assert.notEqual(arrayOfKeys.indexOf('foo'), -1);
            assert.equal(arrayOfKeys.length, 3);
            done();
          });
        });
      });
    });
  });

  it('should accept scanCount option without pattern', function (done) {
    redisCache.set('foo', 'bar', function () {
      redisCache.set('far', 'boo', function () {
        redisCache.set('faz', 'bam', function () {
          redisCache.keys({ scanCount: 10 }, function (err, arrayOfKeys) {
            assert.equal(err, null);
            assert.notEqual(arrayOfKeys, null);
            assert.notEqual(arrayOfKeys.indexOf('foo'), -1);
            assert.equal(arrayOfKeys.length, 3);
            done();
          });
        });
      });
    });
  });

  it('should return an error if there is an error acquiring a connection', function (done) {
    injectError();
    redisCache.set('foo', 'bar', function () {
      redisCache.keys('f*', function (err) {
        assert.notEqual(err, null);
        done();
      });
    });
  });
});

describe('isCacheableValue', function () {
  it('should return true when the value is not undefined', function (done) {
    assert.equal(redisCache.store.isCacheableValue(0), true);
    assert.equal(redisCache.store.isCacheableValue(100), true);
    assert.equal(redisCache.store.isCacheableValue(''), true);
    assert.equal(redisCache.store.isCacheableValue('test'), true);
    done();
  });

  it('should return false when the value is undefined', function (done) {
    assert.equal(redisCache.store.isCacheableValue(undefined), false);
    done();
  });

  it('should return false when the value is null', function (done) {
    assert.equal(redisCache.store.isCacheableValue(null), false);
    done();
  });
});

describe('getClient', function () {
  it('should return a promise', function () {
    assert.ok(redisCache.store.getClient().then(redis => redis.done()) instanceof Promise);
  });

  it('should resolve promise on success', function () {
    return redisCache.store.getClient().then(redis => {
      assert.notEqual(redis, null);
      redis.done();
    });
  });

  it('should reject promise on error', function () {
    injectError();

    return redisCache.store.getClient().then(res => assert.fail(res), err => assert.notEqual(err, null));
  });

  it('should return redis client', function (done) {
    redisCache.store.getClient(function (err, redis) {
      assert.equal(err, null);
      assert.notEqual(redis, null);
      assert.notEqual(redis.client, null);
      redis.done(done);
    });
  });

  it('should handle no done callback without an error', function (done) {
    redisCache.store.getClient(function (err, redis) {
      assert.equal(err, null);
      assert.notEqual(redis, null);
      assert.notEqual(redis.client, null);
      redis.done();
      done();
    });
  });

  it('should return an error if there is an error acquiring a connection', function (done) {
    injectError();
    redisCache.store.getClient(function (err) {
      assert.notEqual(err, null);
      done();
    });
  });
});

describe('redisErrorEvent', function () {
  it('should return an error when the redis server is unavailable', function (done) {
    redisCache.store.events.on('redisError', function (err) {
      assert.notEqual(err, null);
      done();
    });
    redisCache.store._pool.emit('error', 'Something unexpected');
  });
});

describe('uses url to override redis options', function () {
  var redisCacheByUrl;

  before(function () {
    redisCacheByUrl = require('cache-manager').caching({
      store: redisStore,
      // redis://[:password@]host[:port][/db-number][?option=value]
      url: 'redis://:' + config.redis.auth_pass +'@' + config.redis.host + ':' + config.redis.port + '/' + config.redis.db +'?ttl=' + config.redis.ttl,
      // some fakes to see that url overrides them
      host: 'test-host',
      port: -78,
      db: -7,
      auth_pass: 'test_pass',
      password: 'test_pass',
      ttl: -6
    });
  });

  it('should ignore other options if set in url', function() {
    assert.equal(redisCacheByUrl.store._pool._redis_options.host, config.redis.host);
    assert.equal(redisCacheByUrl.store._pool._redis_options.port, config.redis.port);
    assert.equal(redisCacheByUrl.store._pool._redis_default_db, config.redis.db);
    assert.equal(redisCacheByUrl.store._pool._redis_options.auth_pass, config.redis.auth_pass);
    assert.equal(redisCacheByUrl.store._pool._redis_options.password, config.redis.auth_pass);
  });

  it('should get and set values without error', function (done) {
    var key = 'byUrlKey';
    var value = 'test';
    redisCacheByUrl.set(key, value, function (err) {
      assert.equal(err, null);
      redisCacheByUrl.get(key, function(getErr, val){
        assert.equal(getErr, null);
        assert.equal(val, value);
        done();
      });
    });
  });
});

describe('overridable isCacheableValue function', function () {
  var redisCache2;

  before(function () {
    redisCache2 = require('cache-manager').caching({
      store: redisStore,
      isCacheableValue: function () {return 'I was overridden';}
    });
  });

  it('should return its return value instead of the built-in function', function (done) {
    assert.equal(redisCache2.store.isCacheableValue(0), 'I was overridden');
    done();
  });
});

describe('defaults', function () {
  var redisCache2;

  before(function () {
    redisCache2 = require('cache-manager').caching({
      store: redisStore
    });
  });

  it('should default the host to `127.0.0.1`', function () {
    assert.equal(redisCache2.store._pool._redis_options.host, '127.0.0.1');
  });

  it('should default the port to 6379', function () {
    assert.equal(redisCache2.store._pool._redis_options.port, 6379);
  });
});

describe('wrap function', function () {

  // Simulate retrieving a user from a database
  function getUser(id, cb) {
    setTimeout(function () {
      cb(null, { id: id });
    }, 100);
  }

  // Simulate retrieving a user from a database with Promise
  function getUserPromise(id) {
    return new Promise(function (resolve) {
      setTimeout(function () {
        resolve({ id: id });
      }, 100);
    });
  }

  it('should be able to cache objects', function (done) {
    var userId = 123;

    // First call to wrap should run the code
    redisCache.wrap('wrap-user', function (cb) {
      getUser(userId, cb);
    }, function (err, user) {
      assert.equal(user.id, userId);

      // Second call to wrap should retrieve from cache
      redisCache.wrap('wrap-user', function (cb) {
        getUser(userId+1, cb);
      }, function (err, user) {
        assert.equal(user.id, userId);
        done();
      });
    });
  });

  it('should work with promises', function () {
    var userId = 123;

    // First call to wrap should run the code
    return redisCache
      .wrap('wrap-promise', function () {
        return getUserPromise(userId);
      })
      .then(function (user) {
        assert.equal(user.id, userId);

        // Second call to wrap should retrieve from cache
        return redisCache
          .wrap('wrap-promise', function () {
            return getUserPromise(userId+1);
          })
          .then(function (user) {
            assert.equal(user.id, userId);
          });
      });
  });
});


text:
import os
import sys
from unittest import mock, skipIf

from asgiref.sync import async_to_sync

from django.core.cache import DEFAULT_CACHE_ALIAS, caches
from django.core.exceptions import SynchronousOnlyOperation
from django.test import SimpleTestCase
from django.utils.asyncio import async_unsafe

from .models import SimpleModel

@skipIf(sys.platform == 'win32' and (3, 8, 0) < sys.version_info < (3, 8, 1), 'https://bugs.python.org/issue38563')
class CacheTest(SimpleTestCase):
    def test_caches_local(self):
        @async_to_sync
        async def async_cache():
            return caches[DEFAULT_CACHE_ALIAS]

        cache_1 = async_cache()
        cache_2 = async_cache()
        self.assertIs(cache_1, cache_2)

@skipIf(sys.platform == 'win32' and (3, 8, 0) < sys.version_info < (3, 8, 1), 'https://bugs.python.org/issue38563')
class DatabaseConnectionTest(SimpleTestCase):
    """A database connection cannot be used in an async context."""
    async def test_get_async_connection(self):
        with self.assertRaises(SynchronousOnlyOperation):
            list(SimpleModel.objects.all())

@skipIf(sys.platform == 'win32' and (3, 8, 0) < sys.version_info < (3, 8, 1), 'https://bugs.python.org/issue38563')
class AsyncUnsafeTest(SimpleTestCase):
    """
    async_unsafe decorator should work correctly and returns the correct
    message.
    """
    @async_unsafe
    def dangerous_method(self):
        return True

    async def test_async_unsafe(self):
        # async_unsafe decorator catches bad access and returns the right
        # message.
        msg = (
            'You cannot call this from an async context - use a thread or '
            'sync_to_async.'
        )
        with self.assertRaisesMessage(SynchronousOnlyOperation, msg):
            self.dangerous_method()

    @mock.patch.dict(os.environ, {'DJANGO_ALLOW_ASYNC_UNSAFE': 'true'})
    @async_to_sync  # mock.patch() is not async-aware.
    async def test_async_unsafe_suppressed(self):
        # Decorator doesn't trigger check when the environment variable to
        # suppress it is set.
        try:
            self.dangerous_method()
        except SynchronousOnlyOperation:
            self.fail('SynchronousOnlyOperation should not be raised.')

redpajama_set_name: RedPajamaGithub


text:
<?php namespace ATDev\Commweb;

/**
 * Transaction class
 */
class Transaction implements \JsonSerializable {

	/** @var string Transaction id */
	private $id;
	/** @var string Transaction amount */
	private $amount;
	/** @var string Transaction currency */
	private $currency = 'AUD';

	/**
	 * Class constructor
	 *
	 * @param string $id Transaction id
	 * @param string|null $amount Transaction amount
	 * @param string|null $currency Transaction currency
	 */
	public function __construct($id, $amount = null, $currency = null) {

		$this->setId($id);

		if ( ! empty($amount) ) {

			$this->setAmount($amount);
		}

		if ( ! empty($currency)) {

			$this->setCurrency($currency);
		}
	}

	/**
	 * Sets transaction id
	 *
	 * @param string $id
	 *
	 * @return \ATDev\Commweb\Transaction
	 */
	public function setId($id) {

		$this->id = $id;

		return $this;
	}

	/**
	 * Gets transaction id
	 *
	 * @return string
	 */
	public function getId() {

		return $this->id;
	}

	/**
	 * Sets transaction amount
	 *
	 * @param string $amount
	 *
	 * @return \ATDev\Commweb\Transaction
	 */
	public function setAmount($amount) {

		$this->amount = $amount;

		return $this;
	}

	/**
	 * Sets transaction currency
	 *
	 * @param string $currency
	 *
	 * @return \ATDev\Commweb\Transaction
	 */
	public function setCurrency($currency) {

		if ( in_array($currency, Currency::getAvailable()) ) {

			$this->currency = $currency;
		}

		return $this;
	}

	/**
	 * Specifies what has to be returned on serialization to json
	 *
	 * @return array Data to serialize
	 */
	public function jsonSerialize() {

		return [
			"amount" => $this->amount,
			"currency" => $this->currency
		];
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Vibrant.QuerySearch.Form;

namespace Vibrant.QuerySearch
{
   /// <summary>
   /// IFilterProvider is an implementation that provides filtering for a specific entity.
   /// </summary>
   /// <typeparam name="TEntity">The entity to provide filtering for.</typeparam>
   public interface IFilterProvider<TEntity>
   {
      /// <summary>
      /// Applies the filtering form to the query.
      /// </summary>
      /// <param name="query">The query that should be filtered.</param>
      /// <param name="form">The filtering form that should be applied to the query.</param>
      /// <returns>A filtered queryable.</returns>
      IQueryable<TEntity> ApplyWhere( IQueryable<TEntity> query, IFilterForm form );
   }
}


text:
class TestQGetopt : public QObject {
	Q_OBJECT
private slots:
void option()
{
	QCOMPARE(QGetopt::Option('a').option, QChar('a'));
	QCOMPARE(QGetopt::Option('a').longOption, QString());
	QCOMPARE(QGetopt::Option('a', true).option, QChar('a'));
	QCOMPARE(QGetopt::Option('a', false).longOption, QString());
	QCOMPARE(QGetopt::Option('a', true).withArg, true);
	QCOMPARE(QGetopt::Option('a', false).withArg, false);

	QCOMPARE(QGetopt::Option("add").option, QChar());
	QCOMPARE(QGetopt::Option("add").longOption, QString("add"));
	QCOMPARE(QGetopt::Option("add", true).option, QChar());
	QCOMPARE(QGetopt::Option("add", false).longOption, QString("add"));
	QCOMPARE(QGetopt::Option("add", true).withArg, true);
	QCOMPARE(QGetopt::Option("add", false).withArg, false);

	QCOMPARE(QGetopt::Option('a', "add").option, QChar('a'));
	QCOMPARE(QGetopt::Option('a', "add").longOption, QString("add"));
	QCOMPARE(QGetopt::Option('a', "add", true).option, QChar('a'));
	QCOMPARE(QGetopt::Option('a', "add", false).longOption, QString("add"));
	QCOMPARE(QGetopt::Option('a', "add", true).withArg, true);
	QCOMPARE(QGetopt::Option('a', "add", false).withArg, false);
}
void optionEqual()
{
	QVERIFY(QGetopt::Option('a') == QGetopt::Option('a'));
	QVERIFY(QGetopt::Option('a') != QGetopt::Option('b'));

	QVERIFY(QGetopt::Option("add") == QGetopt::Option("add"));
	QVERIFY(QGetopt::Option("count") != QGetopt::Option("add"));

	QVERIFY(QGetopt::Option('a') != QGetopt::Option("add"));
	QVERIFY(QGetopt::Option("add") != QGetopt::Option('a'));

	QVERIFY(QGetopt::Option('a', "add") == QGetopt::Option('a'));
	QVERIFY(QGetopt::Option('a', "add") == QGetopt::Option("add"));
	QVERIFY(QGetopt::Option('a', "add") == QGetopt::Option('a', "add"));
	QVERIFY(QGetopt::Option('a', "add") != QGetopt::Option('b'));
	QVERIFY(QGetopt::Option('a', "add") != QGetopt::Option("count"));

	QVERIFY(QGetopt::Option('a', "add") != QGetopt::Option('b', "add"));
	QVERIFY(QGetopt::Option('a', "add") != QGetopt::Option('a', "count"));
}
void shortOptions()
{
	QGetopt getopt;
	getopt.addOption('a');
	getopt.addOption('c');
	getopt.addOption('d');

	getopt.parse(QStringList() << "./test" << "-a" << "-c");
	QVERIFY(getopt.hasOption('a'));
	QVERIFY(getopt.hasOption('c'));

	getopt.parse(QStringList() << "./test" << "-c" << "-a");
	QVERIFY(getopt.hasOption('a'));
	QVERIFY(getopt.hasOption('c'));

	getopt.parse(QStringList() << "./test" << "-a" << "-d");
	QVERIFY(getopt.hasOption('a'));
	QVERIFY(!getopt.hasOption('c'));
	QVERIFY(getopt.hasOption('d'));

	getopt.parse(QStringList() << "./test" << "-ac");
	QVERIFY(getopt.hasOption('a'));
	QVERIFY(getopt.hasOption('c'));

	getopt.parse(QStringList() << "./test" << "-ca");
	QVERIFY(getopt.hasOption('a'));
	QVERIFY(getopt.hasOption('c'));

	getopt.parse(QStringList() << "./test" << "-caaa");
	QVERIFY(getopt.hasOption('a'));
	QCOMPARE(getopt.count('a'), 3);
	QVERIFY(getopt.hasOption('c'));
	QCOMPARE(getopt.count('c'), 1);
}
void optargs()
{
	QGetopt getopt;
	getopt.addOptionWithArg('a').addOption('b').addOptionWithArg('c');

	getopt.parse(QStringList() << "./test" << "-a" << "1" << "-b" << "-c" << "2");
	QVERIFY(getopt.hasOption('a'));
	QVERIFY(getopt.hasOption('b'));
	QVERIFY(getopt.hasOption('c'));
	QCOMPARE(getopt.getArg('a'), QString("1"));
	QCOMPARE(getopt.getArg('c'), QString("2"));

	getopt.parse(QStringList() << "./test" << "-a" << "1" << "-bc" << "2");
	QVERIFY(getopt.hasOption('a'));
	QVERIFY(getopt.hasOption('b'));
	QVERIFY(getopt.hasOption('c'));
	QCOMPARE(getopt.getArg('a'), QString("1"));
	QCOMPARE(getopt.getArgs('a'), QStringList() << "1");
	QCOMPARE(getopt.getArg('c'), QString("2"));

	getopt.parse(QStringList() << "./test" << "-a" << "1" << "-a" << "2");
	QVERIFY(getopt.hasOption('a'));
	QCOMPARE(getopt.count('a'), 2);
	QCOMPARE(getopt.getArg('a'), QString("1"));
	QCOMPARE(getopt.getArgs('a'), QStringList() << "1" << "2");
}
void optWithoutOptarg()
{
	QGetopt getopt;
	getopt.addOptionWithArg('a');
	getopt.addOption('b');
	getopt.addOptionWithArg('c');

	try {
		getopt.parse(QStringList() << "./test" << "-b" << "-c" << "2" << "-a");
		QFAIL("No exception");
	} catch(QGetopt::NoArgException & e) {
		QCOMPARE(e.option, QChar('a'));
	}

	try {
		getopt.parse(QStringList() << "./test" << "-a" << "1" << "-bc");
		QFAIL("No exception");
	} catch(QGetopt::NoArgException & e) {
		QCOMPARE(e.option, QChar('c'));
	}
}
void unknownOption()
{
	QGetopt getopt;
	getopt.addOption('a');
	getopt.addOption('b');
	getopt.addOptionWithArg('c');

	try {
		getopt.parse(QStringList() << "./test" << "-a" << "-d" << "-c" << "2");
		QFAIL("No exception");
	} catch(QGetopt::UnknownOptionException & e) {
		QCOMPARE(e.option, QChar('d'));
	}
}
void longOptions()
{
	QGetopt getopt;
	getopt.addOption('a');
	getopt.addOption("add");
	getopt.addOption('c', "count");

	getopt.parse(QStringList() << "./test" << "-a" << "--count");
	QVERIFY(getopt.hasOption('a'));
	QVERIFY(!getopt.hasOption("add"));
	QVERIFY(getopt.hasOption("count"));
	QVERIFY(getopt.hasOption('c'));

	getopt.parse(QStringList() << "./test" << "-a" << "--count" << "--add");
	QVERIFY(getopt.hasOption('a'));
	QVERIFY(getopt.hasOption("add"));
	QVERIFY(getopt.hasOption("count"));
}
void longOptionsWithArg()
{
	QGetopt getopt;
	getopt.addOption('a');
	getopt.addOptionWithArg("add");
	getopt.addOptionWithArg('c', "count");

	getopt.parse(QStringList() << "./test" << "-a" << "--count" << "1");
	QVERIFY(getopt.hasOption('a'));
	QVERIFY(!getopt.hasOption("add"));
	QVERIFY(getopt.hasOption('c'));
	QVERIFY(getopt.hasOption("count"));
	QCOMPARE(getopt.getArg('c'), QString("1"));
	QCOMPARE(getopt.getArg("count"), QString("1"));

	getopt.parse(QStringList() << "./test" << "-a" << "--count" << "1" << "--add" << "2");
	QVERIFY(getopt.hasOption('a'));
	QVERIFY(getopt.hasOption("add"));
	QVERIFY(getopt.hasOption("count"));
	QCOMPARE(getopt.getArg('c'), QString("1"));
	QCOMPARE(getopt.getArg("count"), QString("1"));
	QCOMPARE(getopt.getArg("add"), QString("2"));

	getopt.parse(QStringList() << "./test" << "--count" << "1" << "--count" << "2");
	QVERIFY(!getopt.hasOption('a'));
	QVERIFY(!getopt.hasOption("add"));
	QVERIFY(getopt.hasOption("count"));
	QCOMPARE(getopt.count("count"), 2);
	QCOMPARE(getopt.getArg("count"), QString("1"));
	QCOMPARE(getopt.getArgs("count"), QStringList() << "1" << "2");
}
void longOptionsWithoutArg()
{
	QGetopt getopt;
	getopt.addOptionWithArg("add");
	getopt.addOption('b');
	getopt.addOptionWithArg('c', "count");

	try {
		getopt.parse(QStringList() << "./test" << "--add");
		QFAIL("No exception");
	} catch(QGetopt::NoArgException & e) {
		QCOMPARE(e.option, QChar());
		QCOMPARE(e.longOption, QString("add"));
	}

	try {
		getopt.parse(QStringList() << "./test" << "--add" << "1" << "-bc");
		QFAIL("No exception");
	} catch(QGetopt::NoArgException & e) {
		QCOMPARE(e.option, QChar('c'));
		QCOMPARE(e.longOption, QString("count"));
	}

	try {
		getopt.parse(QStringList() << "./test" << "--add" << "1" << "-b" << "--count");
		QFAIL("No exception");
	} catch(QGetopt::NoArgException & e) {
		QCOMPARE(e.option, QChar('c'));
		QCOMPARE(e.longOption, QString("count"));
	}
}
void unknownLongOption()
{
	QGetopt getopt;
	getopt.addOption('a');
	getopt.addOption("batch");
	getopt.addOptionWithArg('c', "count");

	try {
		getopt.parse(QStringList() << "./test" << "-a" << "--delete" << "--count" << "2");
		QFAIL("No exception");
	} catch(QGetopt::UnknownOptionException & e) {
		QCOMPARE(e.option, QChar());
		QCOMPARE(e.longOption, QString("delete"));
	}
}
void nonOptionArgs()
{
	QGetopt getopt;
	getopt.addOption('a');
	getopt.addOption('3');
	getopt.addOption('4');
	getopt.addOption("batch");
	getopt.addOptionWithArg('c', "count");

	getopt.parse(QStringList() << "./test" << "-a" << "--batch" << "--count" << "2" << "3" << "4");
	QVERIFY(getopt.hasOption('a'));
	QVERIFY(getopt.hasOption("batch"));
	QVERIFY(getopt.hasOption('c'));
	QCOMPARE(getopt.getArg('c'), QString("2"));
	QCOMPARE(getopt.getNonArgs(), QStringList() << QString("3") << QString("4"));

	getopt.parse(QStringList() << "./test" << "-a" << "--batch" << "--count" << "2" << "3" << "-4");
	QVERIFY(getopt.hasOption('a'));
	QVERIFY(getopt.hasOption("batch"));
	QVERIFY(getopt.hasOption('c'));
	QVERIFY(getopt.hasOption('4'));
	QCOMPARE(getopt.getArg('c'), QString("2"));
	QCOMPARE(getopt.getNonArgs(), QStringList() << QString("3"));

	getopt.parse(QStringList() << "./test" << "-a" << "--batch" << "--count" << "2" << "-3" << "-4");
	QVERIFY(getopt.hasOption('a'));
	QVERIFY(getopt.hasOption("batch"));
	QVERIFY(getopt.hasOption('c'));
	QVERIFY(getopt.hasOption('3'));
	QVERIFY(getopt.hasOption('4'));
	QCOMPARE(getopt.getArg('c'), QString("2"));
	QCOMPARE(getopt.getNonArgs(), QStringList());

	getopt.parse(QStringList() << "./test" << "-a" << "--batch" << "--count" << "2" << "--" << "-3" << "-4");
	QVERIFY(getopt.hasOption('a'));
	QVERIFY(getopt.hasOption("batch"));
	QVERIFY(getopt.hasOption('c'));
	QVERIFY(!getopt.hasOption('3'));
	QVERIFY(!getopt.hasOption('4'));
	QCOMPARE(getopt.getArg('c'), QString("2"));
	QCOMPARE(getopt.getNonArgs(), QStringList() << QString("-3") << QString("-4"));
}
};

QTEST_MAIN(TestQGetopt);
#include "test.moc"


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Backbone.js Todos</title>
  <link rel="stylesheet" href="todos.css"/>

Todos

      <input id="new-todo" type="text" placeholder="What needs to be done?">

      <input id="toggle-all" type="checkbox">
      Mark all as complete

      Clear completed

    Double-click to edit a todo.

    Created by

    Jérôme Gravel-Niquet.

Rewritten by: TodoMVC.


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 2.0.10
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package com.badlogic.gdx.physics.bullet.collision;

import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.Quaternion;
import com.badlogic.gdx.math.Matrix3;
import com.badlogic.gdx.math.Matrix4;

public class btDbvtAabbMm extends BulletBase {
	private long swigCPtr;

	protected btDbvtAabbMm(final String className, long cPtr, boolean cMemoryOwn) {
		super(className, cPtr, cMemoryOwn);
		swigCPtr = cPtr;
	}

	/** Construct a new btDbvtAabbMm, normally you should not need this constructor it's intended for low-level usage. */
	public btDbvtAabbMm(long cPtr, boolean cMemoryOwn) {
		this("btDbvtAabbMm", cPtr, cMemoryOwn);
		construct();
	}

	@Override
	protected void reset(long cPtr, boolean cMemoryOwn) {
		if (!destroyed)
			destroy();
		super.reset(swigCPtr = cPtr, cMemoryOwn);
	}

	public static long getCPtr(btDbvtAabbMm obj) {
		return (obj == null) ? 0 : obj.swigCPtr;
	}

	@Override
	protected void finalize() throws Throwable {
		if (!destroyed)
			destroy();
		super.finalize();
	}

  @Override protected synchronized void delete() {
		if (swigCPtr != 0) {
			if (swigCMemOwn) {
				swigCMemOwn = false;
				CollisionJNI.delete_btDbvtAabbMm(swigCPtr);
			}
			swigCPtr = 0;
		}
		super.delete();
	}

  public Vector3 Center() {
	return CollisionJNI.btDbvtAabbMm_Center(swigCPtr, this);
}

  public Vector3 Lengths() {
	return CollisionJNI.btDbvtAabbMm_Lengths(swigCPtr, this);
}

  public Vector3 Extents() {
	return CollisionJNI.btDbvtAabbMm_Extents(swigCPtr, this);
}

  public Vector3 Mins() {
	return CollisionJNI.btDbvtAabbMm_Mins(swigCPtr, this);
}

  public Vector3 Maxs() {
	return CollisionJNI.btDbvtAabbMm_Maxs(swigCPtr, this);
}

  public static btDbvtAabbMm FromCE(Vector3 c, Vector3 e) {
    return new btDbvtAabbMm(CollisionJNI.btDbvtAabbMm_FromCE(c, e), true);
  }

  public static btDbvtAabbMm FromCR(Vector3 c, float r) {
    return new btDbvtAabbMm(CollisionJNI.btDbvtAabbMm_FromCR(c, r), true);
  }

  public static btDbvtAabbMm FromMM(Vector3 mi, Vector3 mx) {
    return new btDbvtAabbMm(CollisionJNI.btDbvtAabbMm_FromMM(mi, mx), true);
  }

  public static btDbvtAabbMm FromPoints(btVector3 pts, int n) {
    return new btDbvtAabbMm(CollisionJNI.btDbvtAabbMm_FromPoints__SWIG_0(btVector3.getCPtr(pts), pts, n), true);
  }

  public static btDbvtAabbMm FromPoints(SWIGTYPE_p_p_btVector3 ppts, int n) {
    return new btDbvtAabbMm(CollisionJNI.btDbvtAabbMm_FromPoints__SWIG_1(SWIGTYPE_p_p_btVector3.getCPtr(ppts), n), true);
  }

  public void Expand(Vector3 e) {
    CollisionJNI.btDbvtAabbMm_Expand(swigCPtr, this, e);
  }

  public void SignedExpand(Vector3 e) {
    CollisionJNI.btDbvtAabbMm_SignedExpand(swigCPtr, this, e);
  }

  public boolean Contain(btDbvtAabbMm a) {
    return CollisionJNI.btDbvtAabbMm_Contain(swigCPtr, this, btDbvtAabbMm.getCPtr(a), a);
  }

  public int Classify(Vector3 n, float o, int s) {
    return CollisionJNI.btDbvtAabbMm_Classify(swigCPtr, this, n, o, s);
  }

  public float ProjectMinimum(Vector3 v, long signs) {
    return CollisionJNI.btDbvtAabbMm_ProjectMinimum(swigCPtr, this, v, signs);
  }

  public Vector3 tMins() {
	return CollisionJNI.btDbvtAabbMm_tMins(swigCPtr, this);
}

  public Vector3 tMaxs() {
	return CollisionJNI.btDbvtAabbMm_tMaxs(swigCPtr, this);
}

  public btDbvtAabbMm() {
    this(CollisionJNI.new_btDbvtAabbMm(), true);
  }

}


text:
namespace Google.Cloud.Dialogflow.V2Beta1.Snippets
{
    using Google.Api.Gax;
    using Google.Protobuf.WellKnownTypes;
    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using gcdv = Google.Cloud.Dialogflow.V2Beta1;

    /// Generated snippets.
    public sealed class AllGeneratedEnvironmentsClientSnippets
    {
        /// Snippet for ListEnvironments
        public void ListEnvironmentsRequestObject()
        {
            // Snippet: ListEnvironments(ListEnvironmentsRequest, CallSettings)
            // Create client
            EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
            // Initialize request argument(s)
            ListEnvironmentsRequest request = new ListEnvironmentsRequest
            {
                ParentAsAgentName = AgentName.FromProject("[PROJECT]"),
            };
            // Make the request
            PagedEnumerable<ListEnvironmentsResponse, gcdv::Environment> response = environmentsClient.ListEnvironments(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (gcdv::Environment item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListEnvironmentsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (gcdv::Environment item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<gcdv::Environment> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (gcdv::Environment item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }

        /// Snippet for ListEnvironmentsAsync
        public async Task ListEnvironmentsRequestObjectAsync()
        {
            // Snippet: ListEnvironmentsAsync(ListEnvironmentsRequest, CallSettings)
            // Create client
            EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
            // Initialize request argument(s)
            ListEnvironmentsRequest request = new ListEnvironmentsRequest
            {
                ParentAsAgentName = AgentName.FromProject("[PROJECT]"),
            };
            // Make the request
            PagedAsyncEnumerable<ListEnvironmentsResponse, gcdv::Environment> response = environmentsClient.ListEnvironmentsAsync(request);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((gcdv::Environment item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListEnvironmentsResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (gcdv::Environment item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<gcdv::Environment> singlePage = await response.ReadPageAsync(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (gcdv::Environment item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }

        /// Snippet for ListEnvironments
        public void ListEnvironments()
        {
            // Snippet: ListEnvironments(string, string, int?, CallSettings)
            // Create client
            EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
            // Initialize request argument(s)
            string parent = "projects/[PROJECT]/agent";
            // Make the request
            PagedEnumerable<ListEnvironmentsResponse, gcdv::Environment> response = environmentsClient.ListEnvironments(parent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (gcdv::Environment item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListEnvironmentsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (gcdv::Environment item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<gcdv::Environment> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (gcdv::Environment item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }

        /// Snippet for ListEnvironmentsAsync
        public async Task ListEnvironmentsAsync()
        {
            // Snippet: ListEnvironmentsAsync(string, string, int?, CallSettings)
            // Create client
            EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
            // Initialize request argument(s)
            string parent = "projects/[PROJECT]/agent";
            // Make the request
            PagedAsyncEnumerable<ListEnvironmentsResponse, gcdv::Environment> response = environmentsClient.ListEnvironmentsAsync(parent);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((gcdv::Environment item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListEnvironmentsResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (gcdv::Environment item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<gcdv::Environment> singlePage = await response.ReadPageAsync(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (gcdv::Environment item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }

        /// Snippet for ListEnvironments
        public void ListEnvironmentsResourceNames()
        {
            // Snippet: ListEnvironments(AgentName, string, int?, CallSettings)
            // Create client
            EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
            // Initialize request argument(s)
            AgentName parent = AgentName.FromProject("[PROJECT]");
            // Make the request
            PagedEnumerable<ListEnvironmentsResponse, gcdv::Environment> response = environmentsClient.ListEnvironments(parent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (gcdv::Environment item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListEnvironmentsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (gcdv::Environment item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<gcdv::Environment> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (gcdv::Environment item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }

        /// Snippet for ListEnvironmentsAsync
        public async Task ListEnvironmentsResourceNamesAsync()
        {
            // Snippet: ListEnvironmentsAsync(AgentName, string, int?, CallSettings)
            // Create client
            EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
            // Initialize request argument(s)
            AgentName parent = AgentName.FromProject("[PROJECT]");
            // Make the request
            PagedAsyncEnumerable<ListEnvironmentsResponse, gcdv::Environment> response = environmentsClient.ListEnvironmentsAsync(parent);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((gcdv::Environment item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListEnvironmentsResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (gcdv::Environment item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<gcdv::Environment> singlePage = await response.ReadPageAsync(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (gcdv::Environment item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }

        /// Snippet for GetEnvironment
        public void GetEnvironmentRequestObject()
        {
            // Snippet: GetEnvironment(GetEnvironmentRequest, CallSettings)
            // Create client
            EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
            // Initialize request argument(s)
            GetEnvironmentRequest request = new GetEnvironmentRequest
            {
                EnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"),
            };
            // Make the request
            gcdv::Environment response = environmentsClient.GetEnvironment(request);
            // End snippet
        }

        /// Snippet for GetEnvironmentAsync
        public async Task GetEnvironmentRequestObjectAsync()
        {
            // Snippet: GetEnvironmentAsync(GetEnvironmentRequest, CallSettings)
            // Additional: GetEnvironmentAsync(GetEnvironmentRequest, CancellationToken)
            // Create client
            EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
            // Initialize request argument(s)
            GetEnvironmentRequest request = new GetEnvironmentRequest
            {
                EnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"),
            };
            // Make the request
            gcdv::Environment response = await environmentsClient.GetEnvironmentAsync(request);
            // End snippet
        }

        /// Snippet for CreateEnvironment
        public void CreateEnvironmentRequestObject()
        {
            // Snippet: CreateEnvironment(CreateEnvironmentRequest, CallSettings)
            // Create client
            EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
            // Initialize request argument(s)
            CreateEnvironmentRequest request = new CreateEnvironmentRequest
            {
                ParentAsAgentName = AgentName.FromProject("[PROJECT]"),
                Environment = new gcdv::Environment(),
                EnvironmentId = "",
            };
            // Make the request
            gcdv::Environment response = environmentsClient.CreateEnvironment(request);
            // End snippet
        }

        /// Snippet for CreateEnvironmentAsync
        public async Task CreateEnvironmentRequestObjectAsync()
        {
            // Snippet: CreateEnvironmentAsync(CreateEnvironmentRequest, CallSettings)
            // Additional: CreateEnvironmentAsync(CreateEnvironmentRequest, CancellationToken)
            // Create client
            EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
            // Initialize request argument(s)
            CreateEnvironmentRequest request = new CreateEnvironmentRequest
            {
                ParentAsAgentName = AgentName.FromProject("[PROJECT]"),
                Environment = new gcdv::Environment(),
                EnvironmentId = "",
            };
            // Make the request
            gcdv::Environment response = await environmentsClient.CreateEnvironmentAsync(request);
            // End snippet
        }

        /// Snippet for UpdateEnvironment
        public void UpdateEnvironmentRequestObject()
        {
            // Snippet: UpdateEnvironment(UpdateEnvironmentRequest, CallSettings)
            // Create client
            EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
            // Initialize request argument(s)
            UpdateEnvironmentRequest request = new UpdateEnvironmentRequest
            {
                Environment = new gcdv::Environment(),
                UpdateMask = new FieldMask(),
                AllowLoadToDraftAndDiscardChanges = false,
            };
            // Make the request
            gcdv::Environment response = environmentsClient.UpdateEnvironment(request);
            // End snippet
        }

        /// Snippet for UpdateEnvironmentAsync
        public async Task UpdateEnvironmentRequestObjectAsync()
        {
            // Snippet: UpdateEnvironmentAsync(UpdateEnvironmentRequest, CallSettings)
            // Additional: UpdateEnvironmentAsync(UpdateEnvironmentRequest, CancellationToken)
            // Create client
            EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
            // Initialize request argument(s)
            UpdateEnvironmentRequest request = new UpdateEnvironmentRequest
            {
                Environment = new gcdv::Environment(),
                UpdateMask = new FieldMask(),
                AllowLoadToDraftAndDiscardChanges = false,
            };
            // Make the request
            gcdv::Environment response = await environmentsClient.UpdateEnvironmentAsync(request);
            // End snippet
        }

        /// Snippet for DeleteEnvironment
        public void DeleteEnvironmentRequestObject()
        {
            // Snippet: DeleteEnvironment(DeleteEnvironmentRequest, CallSettings)
            // Create client
            EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
            // Initialize request argument(s)
            DeleteEnvironmentRequest request = new DeleteEnvironmentRequest
            {
                EnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"),
            };
            // Make the request
            environmentsClient.DeleteEnvironment(request);
            // End snippet
        }

        /// Snippet for DeleteEnvironmentAsync
        public async Task DeleteEnvironmentRequestObjectAsync()
        {
            // Snippet: DeleteEnvironmentAsync(DeleteEnvironmentRequest, CallSettings)
            // Additional: DeleteEnvironmentAsync(DeleteEnvironmentRequest, CancellationToken)
            // Create client
            EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
            // Initialize request argument(s)
            DeleteEnvironmentRequest request = new DeleteEnvironmentRequest
            {
                EnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"),
            };
            // Make the request
            await environmentsClient.DeleteEnvironmentAsync(request);
            // End snippet
        }

        /// Snippet for GetEnvironmentHistory
        public void GetEnvironmentHistoryRequestObject()
        {
            // Snippet: GetEnvironmentHistory(GetEnvironmentHistoryRequest, CallSettings)
            // Create client
            EnvironmentsClient environmentsClient = EnvironmentsClient.Create();
            // Initialize request argument(s)
            GetEnvironmentHistoryRequest request = new GetEnvironmentHistoryRequest
            {
                ParentAsEnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"),
            };
            // Make the request
            PagedEnumerable<EnvironmentHistory, EnvironmentHistory.Types.Entry> response = environmentsClient.GetEnvironmentHistory(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (EnvironmentHistory.Types.Entry item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (EnvironmentHistory page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (EnvironmentHistory.Types.Entry item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<EnvironmentHistory.Types.Entry> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (EnvironmentHistory.Types.Entry item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }

        /// Snippet for GetEnvironmentHistoryAsync
        public async Task GetEnvironmentHistoryRequestObjectAsync()
        {
            // Snippet: GetEnvironmentHistoryAsync(GetEnvironmentHistoryRequest, CallSettings)
            // Create client
            EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync();
            // Initialize request argument(s)
            GetEnvironmentHistoryRequest request = new GetEnvironmentHistoryRequest
            {
                ParentAsEnvironmentName = EnvironmentName.FromProjectEnvironment("[PROJECT]", "[ENVIRONMENT]"),
            };
            // Make the request
            PagedAsyncEnumerable<EnvironmentHistory, EnvironmentHistory.Types.Entry> response = environmentsClient.GetEnvironmentHistoryAsync(request);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((EnvironmentHistory.Types.Entry item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((EnvironmentHistory page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (EnvironmentHistory.Types.Entry item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<EnvironmentHistory.Types.Entry> singlePage = await response.ReadPageAsync(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (EnvironmentHistory.Types.Entry item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
    }
}


text:
Weather
=======

This is a TerraMod app that creates a weather and forecast tile on your main landing page.  It uses OpenWeatherMap.

License
-------

This project is licensed under the MIT license, see LICENSE.md for more information.


text:
layout: post
title: ReactNative bundling and build issues on a new machine
type: post
published: true
excerpt: "I started to setup a ReactNative project that we have been working on for a while now on my machine. The generated iOS native code was version controlled but the build was still not functioning on my machine."
comments: true
tags: [reactnative, cocoapods, ios]
---

I started to setup a ReactNative project that we have been working on for a while now on my machine. The generated iOS native code was version controlled but the build was still not functioning on my machine.

Followed the setup instructions and I got the following

> Can't build on iOS - "Podfile.lock: No such file or directory"

Turned out I didn't have cocoapods installed which were needed!

## Installing CocoaPods
`sudo gem install cocoapods`

Once I fixed that, started seeing
> ":CFBundleIdentifier", Does Not Exist

1. Close Xcode
2. Delete node_modules and reinstall fresh
3. Open the project in Xcode

On step three I opened .xcodeproj  which gave me something to the effect of

> directory not found DerivedData

I had to instead open .xcworkspace. Did a product clean and build and it worked!

When you use CocoaPods, it creates a workspace file that needs to be opened in order for the builds to compile properly.

https://github.com/auth0/react-native-lock/issues/151#issuecomment-295566616

Have you come across other quirky react-native issues? :) ... Would love to hear about them.

Original blog post at https://causecode.com/reactnative-bundling-and-build-issues-on-a-new-machine/


text:
r"""
This code was generated by
\ / _    _  _|   _  _
 | (_)\/(_)(_|\/| |(/_  v1.0.0
      /       /
"""

from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response

class MediaProcessorTestCase(IntegrationTestCase):

    def test_create_request(self):
        self.holodeck.mock(Response(500, ''))

        with self.assertRaises(TwilioException):
            self.client.media.v1.media_processor.create(extension="extension", extension_context="extension_context")

        values = {'Extension': "extension", 'ExtensionContext': "extension_context", }

        self.holodeck.assert_has_request(Request(
            'post',
            'https://media.twilio.com/v1/MediaProcessors',
            data=values,
        ))

    def test_create_response(self):
        self.holodeck.mock(Response(
            201,
            '''
            {
                "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                "date_created": "2015-07-30T20:00:00Z",
                "date_updated": "2015-07-30T20:00:00Z",
                "extension": "video-composer-v2",
                "extension_context": "{}",
                "sid": "ZXdeadbeefdeadbeefdeadbeefdeadbeef",
                "status": "started",
                "status_callback": "http://www.example.com",
                "status_callback_method": "POST",
                "ended_reason": null,
                "url": "https://media.twilio.com/v1/MediaProcessors/ZXdeadbeefdeadbeefdeadbeefdeadbeef",
                "max_duration": 300
            }
            '''
        ))

        actual = self.client.media.v1.media_processor.create(extension="extension", extension_context="extension_context")

        self.assertIsNotNone(actual)

    def test_fetch_request(self):
        self.holodeck.mock(Response(500, ''))

        with self.assertRaises(TwilioException):
            self.client.media.v1.media_processor("ZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()

        self.holodeck.assert_has_request(Request(
            'get',
            'https://media.twilio.com/v1/MediaProcessors/ZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        ))

    def test_fetch_response(self):
        self.holodeck.mock(Response(
            200,
            '''
            {
                "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                "date_created": "2015-07-30T20:00:00Z",
                "date_updated": "2015-07-30T20:00:00Z",
                "extension": "video-composer-v2",
                "extension_context": "{}",
                "sid": "ZXdeadbeefdeadbeefdeadbeefdeadbeef",
                "status": "started",
                "status_callback": "http://www.example.com",
                "status_callback_method": "POST",
                "ended_reason": null,
                "url": "https://media.twilio.com/v1/MediaProcessors/ZXdeadbeefdeadbeefdeadbeefdeadbeef",
                "max_duration": 300
            }
            '''
        ))

        actual = self.client.media.v1.media_processor("ZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").fetch()

        self.assertIsNotNone(actual)

    def test_update_request(self):
        self.holodeck.mock(Response(500, ''))

        with self.assertRaises(TwilioException):
            self.client.media.v1.media_processor("ZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(status="ended")

        values = {'Status': "ended", }

        self.holodeck.assert_has_request(Request(
            'post',
            'https://media.twilio.com/v1/MediaProcessors/ZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
            data=values,
        ))

    def test_update_ended_response(self):
        self.holodeck.mock(Response(
            200,
            '''
            {
                "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                "date_created": "2015-07-30T20:00:00Z",
                "date_updated": "2015-07-30T20:01:00Z",
                "extension": "video-composer-v2",
                "extension_context": "{}",
                "sid": "ZXdeadbeefdeadbeefdeadbeefdeadbeef",
                "status": "ended",
                "status_callback": "http://www.example.com",
                "status_callback_method": "POST",
                "ended_reason": "ended-via-api",
                "url": "https://media.twilio.com/v1/MediaProcessors/ZXdeadbeefdeadbeefdeadbeefdeadbeef",
                "max_duration": 300
            }
            '''
        ))

        actual = self.client.media.v1.media_processor("ZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(status="ended")

        self.assertIsNotNone(actual)

    def test_list_request(self):
        self.holodeck.mock(Response(500, ''))

        with self.assertRaises(TwilioException):
            self.client.media.v1.media_processor.list()

        self.holodeck.assert_has_request(Request(
            'get',
            'https://media.twilio.com/v1/MediaProcessors',
        ))

    def test_read_empty_response(self):
        self.holodeck.mock(Response(
            200,
            '''
            {
                "meta": {
                    "page": 0,
                    "page_size": 10,
                    "first_page_url": "https://media.twilio.com/v1/MediaProcessors?Status=started&Order=asc&PageSize=10&Page=0",
                    "previous_page_url": null,
                    "url": "https://media.twilio.com/v1/MediaProcessors?Status=started&Order=asc&PageSize=10&Page=0",
                    "next_page_url": null,
                    "key": "media_processors"
                },
                "media_processors": []
            }
            '''
        ))

        actual = self.client.media.v1.media_processor.list()

        self.assertIsNotNone(actual)

    def test_read_items_response(self):
        self.holodeck.mock(Response(
            200,
            '''
            {
                "meta": {
                    "page": 0,
                    "page_size": 10,
                    "first_page_url": "https://media.twilio.com/v1/MediaProcessors?Status=ended&Order=desc&PageSize=10&Page=0",
                    "previous_page_url": null,
                    "url": "https://media.twilio.com/v1/MediaProcessors?Status=ended&Order=desc&PageSize=10&Page=0",
                    "next_page_url": null,
                    "key": "media_processors"
                },
                "media_processors": [
                    {
                        "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                        "date_created": "2015-07-30T20:00:00Z",
                        "date_updated": "2015-07-30T20:01:00Z",
                        "extension": "video-composer-v2",
                        "extension_context": "{}",
                        "sid": "ZXdeadbeefdeadbeefdeadbeefdeadbeef",
                        "status": "ended",
                        "status_callback": "http://www.example.com",
                        "status_callback_method": "POST",
                        "ended_reason": "ended-via-api",
                        "url": "https://media.twilio.com/v1/MediaProcessors/ZXdeadbeefdeadbeefdeadbeefdeadbeef",
                        "max_duration": 300
                    }
                ]
            }
            '''
        ))

        actual = self.client.media.v1.media_processor.list()

        self.assertIsNotNone(actual)

    def test_read_items_using_page_token_response(self):
        self.holodeck.mock(Response(
            200,
            '''
            {
                "meta": {
                    "page": 0,
                    "page_size": 10,
                    "first_page_url": "https://media.twilio.com/v1/MediaProcessors?Status=ended&Order=desc&PageSize=10&Page=0",
                    "previous_page_url": null,
                    "url": "https://media.twilio.com/v1/MediaProcessors?Status=ended&Order=desc&PageSize=10&Page=0&PageToken=PTTUszYTgyOGFhNDIzZWExNzA0OTkwODNlMDlkZTg3M2NiNDoxOjI%253D",
                    "next_page_url": null,
                    "key": "media_processors"
                },
                "media_processors": [
                    {
                        "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                        "date_created": "2015-07-30T20:00:00Z",
                        "date_updated": "2015-07-30T20:01:00Z",
                        "extension": "video-composer-v2",
                        "extension_context": "{}",
                        "sid": "ZXdeadbeefdeadbeefdeadbeefdeadbeef",
                        "status": "ended",
                        "status_callback": "http://www.example.com",
                        "status_callback_method": "POST",
                        "ended_reason": "ended-via-api",
                        "url": "https://media.twilio.com/v1/MediaProcessors/ZXdeadbeefdeadbeefdeadbeefdeadbeef",
                        "max_duration": 300
                    }
                ]
            }
            '''
        ))

        actual = self.client.media.v1.media_processor.list()

        self.assertIsNotNone(actual)

    def test_read_items_page_larger_than_max_response(self):
        self.holodeck.mock(Response(
            200,
            '''
            {
                "meta": {
                    "page": 0,
                    "page_size": 100,
                    "first_page_url": "https://media.twilio.com/v1/MediaProcessors?Status=ended&Order=desc&PageSize=100&Page=0",
                    "previous_page_url": null,
                    "url": "https://media.twilio.com/v1/MediaProcessors?Status=ended&Order=desc&PageSize=100&Page=0",
                    "next_page_url": null,
                    "key": "media_processors"
                },
                "media_processors": [
                    {
                        "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                        "date_created": "2015-07-30T20:00:00Z",
                        "date_updated": "2015-07-30T20:01:00Z",
                        "extension": "video-composer-v2",
                        "extension_context": "{}",
                        "sid": "ZXdeadbeefdeadbeefdeadbeefdeadbeef",
                        "status": "ended",
                        "status_callback": "http://www.example.com",
                        "status_callback_method": "POST",
                        "ended_reason": "ended-via-api",
                        "url": "https://media.twilio.com/v1/MediaProcessors/ZXdeadbeefdeadbeefdeadbeefdeadbeef",
                        "max_duration": 300
                    }
                ]
            }
            '''
        ))

        actual = self.client.media.v1.media_processor.list()

        self.assertIsNotNone(actual)