text:
// The MIT License (MIT)
//
// Copyright (c) 2019 Tim Jones
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package io.github.jonestimd.finance.swing.transaction;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;

import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

import io.github.jonestimd.finance.domain.account.Account;
import io.github.jonestimd.finance.domain.fileimport.ImportFile;
import io.github.jonestimd.finance.domain.transaction.Payee;
import io.github.jonestimd.finance.domain.transaction.TransactionCategory;
import io.github.jonestimd.finance.operations.FileImportOperations;
import io.github.jonestimd.finance.service.ServiceLocator;
import io.github.jonestimd.finance.swing.FinanceTableFactory;
import io.github.jonestimd.finance.swing.event.AccountSelector;
import io.github.jonestimd.finance.swing.fileimport.FileImportsDialog;
import io.github.jonestimd.finance.swing.fileimport.FileImportsModel;
import io.github.jonestimd.finance.swing.fileimport.ImportFileModel;
import io.github.jonestimd.finance.swing.transaction.action.ImportFileAction;
import io.github.jonestimd.swing.BackgroundTask;
import io.github.jonestimd.swing.ComponentFactory;
import io.github.jonestimd.swing.ComponentTreeUtils;
import io.github.jonestimd.swing.action.DialogAction;
import io.github.jonestimd.swing.window.StatusFrame;
import io.github.jonestimd.util.Streams;

import static io.github.jonestimd.finance.swing.BundleType.*;

public class ImportFileMenuFactory {
    public static final String MENU_KEY = "menu.file.import.mnemonicAndName";

    private final ServiceLocator serviceLocator;
    private final FinanceTableFactory tableFactory;
    private final Map<AccountSelector, AccountListener> accountListeners = new WeakHashMap<>();
    private List<ImportFileAction> importFileActions;

    private Action editImportsAction = new DialogAction(LABELS.get(), "menu.file.editImports") {
        private List<Account> accounts;
        private List<TransactionCategory> categories;
        private List<Payee> payees;
        private FileImportsModel importsModel;

        @Override
        protected void loadDialogData() {
            accounts = serviceLocator.getAccountOperations().getAllAccounts();
            categories = serviceLocator.getTransactionCategoryOperations().getAllTransactionCategories();
            payees = serviceLocator.getPayeeOperations().getAllPayees();
            importsModel = new FileImportsModel(serviceLocator.getFileImportOperations().getAll());
        }

        @Override
        protected boolean displayDialog(JComponent owner) {
            StatusFrame window = ComponentTreeUtils.findAncestor(owner, StatusFrame.class);
            FileImportsDialog dialog = new FileImportsDialog(window, accounts, categories, payees, importsModel,
                    tableFactory, this::saveDialogData);
            return dialog.showDialog();
        }

        @Override
        protected void saveDialogData() {
            FileImportOperations fileImportOperations = serviceLocator.getFileImportOperations();
            List<ImportFile> deletes = importsModel.getDeletes();
            if (!deletes.isEmpty()) fileImportOperations.deleteAll(deletes);
            Set<ImportFile> changedImports = importsModel.getChanges();
            fileImportOperations.saveAll(changedImports);
        }

        @Override
        protected void setSaveResultOnUI() {
            createMenus(Streams.map(importsModel, ImportFileModel::getBean));
        }
    };

    public ImportFileMenuFactory(ServiceLocator serviceLocator, FinanceTableFactory tableFactory) {
        this.serviceLocator = serviceLocator;
        this.tableFactory = tableFactory;
    }

    public Action getEditImportsAction() {
        return editImportsAction;
    }

    /**
     * This method is not thread safe and should only be called from the Swing event thread.  Creates a menu
     * that will be updated when the selected account changes.
     */
    public JMenu createImportMenu(AccountSelector accountSelector) {
        AccountListener accountListener = new AccountListener(ComponentFactory.newMenu(LABELS.get(), MENU_KEY));
        accountListeners.put(accountSelector, accountListener);
        if (importFileActions == null) {
            if (accountListeners.size() == 1) {
                BackgroundTask.task(serviceLocator.getFileImportOperations()::getAll, this::createMenus).run();
            }
        }
        else accountListener.updateMenu(accountSelector);
        accountSelector.addAccountListener(accountListener);
        return accountListener.menu;
    }

    private void createMenus(List<ImportFile> importFiles) {
        importFileActions = Streams.map(importFiles, this::newImportFileAction);
        accountListeners.forEach((key, value) -> value.updateMenu(key));
    }

    private ImportFileAction newImportFileAction(ImportFile importFile) {
        return new ImportFileAction(importFile, serviceLocator);
    }

    private class AccountListener implements PropertyChangeListener {
        private final JMenu menu;

        public AccountListener(JMenu menu) {
            this.menu = menu;
        }

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            accountListeners.entrySet().stream().filter(entry -> entry.getValue() == this).findFirst()
                    .ifPresent(entry -> updateMenu(entry.getKey()));
        }

        private void updateMenu(AccountSelector accountSelector) {
            menu.removeAll();
            Account account = accountSelector.getSelectedAccount();
            if (importFileActions != null && account != null) {
                importFileActions.stream().filter(action -> action.getImportFile().getAccount().equals(account))
                        .map(JMenuItem::new).forEach(menu::add);
            }
        }
    }
}


text:
from distutils.core import setup

setup(
    name='vgraph',
    version='0.1',
    author='Aaron Brenzel',
    url='http://www.github.com/aaronbrenzel',
    author_email='aaronbrenzel@gmail.com',
    description='Python-based persistent store for graph structures and analysis',
    packages=['vgraph', 'vgraph.data', 'vgraph.graph', 'vgraph.algorithms', 'vgraph.data.index'],
    license='MIT',
    package_data={'':['README.txt', 'LICENSE.txt']},
)

redpajama_set_name: RedPajamaGithub


text:
#include "SDL_config.h"

#ifndef _SDL_diskaudio_h
#define _SDL_diskaudio_h

#include "SDL_rwops.h"
#include "../SDL_sysaudio.h"

/* Hidden "this" pointer for the audio functions */
#define _THIS   SDL_AudioDevice *this

struct SDL_PrivateAudioData
{
    /* The file descriptor for the audio device */
    SDL_RWops *output;
    Uint8 *mixbuf;
    Uint32 mixlen;
    Uint32 write_delay;
};

#endif /* _SDL_diskaudio_h */
/* vi: set ts=4 sw=4 expandtab: */


text:
'use strict';

// Game authorization helpers
var hasAuthorization = function(req, res, next) {
  if (!req.user.isAdmin && !req.game.user._id.equals(req.user._id)) {
    return res.status(401).send('User is not authorized');
  }
  next();
};

var hasPermissions = function(req, res, next) {

    req.body.permissions = req.body.permissions || ['authenticated'];

    for (var i = 0; i < req.body.permissions.length; i++) {
      var permission = req.body.permissions[i];
      if (req.acl.user.allowed.indexOf(permission) === -1) {
            return res.status(401).send('User not allowed to assign ' + permission + ' permission.');
        };
    };

    next();
};

module.exports = function(Games, app, auth) {

  var games = require('../controllers/games')(Games);

  app.route('/api/games')
    .get(games.all)
    .post(auth.requiresLogin, hasPermissions, games.create);
  app.route('/api/games/:gameId')
    .get(auth.isMongoId, games.show)
    .put(auth.isMongoId, auth.requiresLogin, hasAuthorization, hasPermissions, games.update)
    .delete(auth.isMongoId, auth.requiresLogin, hasAuthorization, games.destroy);

  // Finish with setting up the gameId param
  app.param('gameId', games.game);
};


text:
import React from 'react';
import PropTypes from 'prop-types';
import ItemsContainer from '../../containers/itemsContainer';

const PAGE_SIZE = 100;

const TableItemsTab = (props) => {
  const hashKey = props.table.KeySchema[0].AttributeName;
  const rangeKey = props.table.KeySchema.length === 2 ?
    props.table.KeySchema[1].AttributeName : false;

  return (

          <button className="btn btn-primary">Create item</button>
          { '\u00a0' }

              Actions

                Duplicate

                Edit

                Delete

                Export to CSV

          <input type="checkbox" id="accordion-1" name="accordion-checkbox" hidden />

                Scan: [Table] {props.table.TableName}: {hashKey}{!rangeKey || `, ${rangeKey}`}

                    {props.pagination &&

                        Viewing {props.pagination.from} to {props.pagination.to} items

                    }

                  <li className={`page-item ${props.pagination && props.pagination.to - props.pagination.from === (PAGE_SIZE - 1) ? '' : 'disabled'}`}>

            <form className="form-horizontal">

                  <select className="form-select mx-1">
                    <option>Scan</option>
                    <option>Query</option>
                  </select>

                  <select className="form-select">
                    <option>[Table] {props.table.TableName}: {hashKey}{!rangeKey || `, ${rangeKey}`}</option>
                  </select>

                  <button className="btn btn-link">
                     Add filter
                  </button>

                  <button className="btn">Start search</button>

            </form>

      <ItemsContainer />

  );
};

TableItemsTab.propTypes = {
  pagination: PropTypes.shape({
    from: PropTypes.number,
    to: PropTypes.number,
  }),
  table: PropTypes.shape({
    AttributeDefinitions: PropTypes.arrayOf(PropTypes.object),
    CreationDateTime: PropTypes.instanceOf(Date),
    ItemCount: PropTypes.number,
    KeySchema: PropTypes.arrayOf(PropTypes.object),
    TableStatus: PropTypes.oneOf(['ACTIVE']),
    TableArn: PropTypes.string,
    TableName: PropTypes.string,
    TableSizeBytes: PropTypes.number,
  }).isRequired,
};

TableItemsTab.defaultProps = {
  pagination: null,
};

export default TableItemsTab;


text:
package org.apache.jackrabbit.oak.security.internal;

import org.apache.jackrabbit.oak.AbstractSecurityTest;
import org.apache.jackrabbit.oak.spi.security.CompositeConfiguration;
import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import org.apache.jackrabbit.oak.spi.security.SecurityProvider;
import org.apache.jackrabbit.oak.spi.security.authentication.AuthenticationConfiguration;
import org.apache.jackrabbit.oak.spi.security.authentication.token.TokenConfiguration;
import org.apache.jackrabbit.oak.spi.security.authorization.AuthorizationConfiguration;
import org.apache.jackrabbit.oak.spi.security.principal.PrincipalConfiguration;
import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConfiguration;
import org.apache.jackrabbit.oak.spi.security.user.UserConfiguration;
import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.withSettings;

public class SecurityProviderBuilderTest extends AbstractSecurityTest {

    private SecurityProviderBuilder builder = SecurityProviderBuilder.newBuilder();

    @Test
    public void testDefault() {
        SecurityProvider sp = builder.build();
        assertNotNull(sp.getConfiguration(AuthenticationConfiguration.class));
        assertNotNull(sp.getConfiguration(AuthorizationConfiguration.class));
        assertNotNull(sp.getConfiguration(PrincipalConfiguration.class));
        assertNotNull(sp.getConfiguration(PrivilegeConfiguration.class));
        assertNotNull(sp.getConfiguration(TokenConfiguration.class));
        assertNotNull(sp.getConfiguration(UserConfiguration.class));
    }

    @Test
    public void testCompositeConfigurations() {
        AuthenticationConfiguration ac = (AuthenticationConfiguration) mock(CompositeConfiguration.class, withSettings().extraInterfaces(AuthenticationConfiguration.class));
        PrivilegeConfiguration pc = (PrivilegeConfiguration) mock(CompositeConfiguration.class, withSettings().extraInterfaces(PrivilegeConfiguration.class));
        UserConfiguration uc = (UserConfiguration) mock(CompositeConfiguration.class, withSettings().extraInterfaces(UserConfiguration.class));
        AuthorizationConfiguration auc = (AuthorizationConfiguration) mock(CompositeConfiguration.class, withSettings().extraInterfaces(AuthorizationConfiguration.class));
        PrincipalConfiguration pnc = (PrincipalConfiguration) mock(CompositeConfiguration.class, withSettings().extraInterfaces(PrincipalConfiguration.class));
        TokenConfiguration tc = (TokenConfiguration) mock(CompositeConfiguration.class, withSettings().extraInterfaces(TokenConfiguration.class));
        SecurityProvider sp = builder.with(
                ac, ConfigurationParameters.EMPTY,
                pc, ConfigurationParameters.EMPTY,
                uc, ConfigurationParameters.EMPTY,
                auc, ConfigurationParameters.EMPTY,
                pnc, ConfigurationParameters.EMPTY,
                tc, ConfigurationParameters.EMPTY).build();

        assertTrue(sp.getConfiguration(AuthenticationConfiguration.class) instanceof CompositeConfiguration);
        assertTrue(sp.getConfiguration(AuthorizationConfiguration.class) instanceof CompositeConfiguration);
        assertTrue(sp.getConfiguration(PrincipalConfiguration.class) instanceof CompositeConfiguration);
        assertTrue(sp.getConfiguration(PrivilegeConfiguration.class) instanceof CompositeConfiguration);
        assertTrue(sp.getConfiguration(TokenConfiguration.class) instanceof CompositeConfiguration);
        assertTrue(sp.getConfiguration(UserConfiguration.class) instanceof CompositeConfiguration);
    }

    @Test
    public void testSingularConfigurations() {
        SecurityProvider sp = builder.with(
                mock(AuthenticationConfiguration.class), ConfigurationParameters.EMPTY,
                mock(PrivilegeConfiguration.class), ConfigurationParameters.EMPTY,
                mock(UserConfiguration.class), ConfigurationParameters.EMPTY,
                mock(AuthorizationConfiguration.class), ConfigurationParameters.EMPTY,
                mock(PrincipalConfiguration.class), ConfigurationParameters.EMPTY,
                mock(TokenConfiguration.class), ConfigurationParameters.EMPTY).build();

        assertFalse(sp.getConfiguration(AuthenticationConfiguration.class) instanceof CompositeConfiguration);
        assertFalse(sp.getConfiguration(AuthorizationConfiguration.class) instanceof CompositeConfiguration);
        assertFalse(sp.getConfiguration(PrincipalConfiguration.class) instanceof CompositeConfiguration);
        assertFalse(sp.getConfiguration(PrivilegeConfiguration.class) instanceof CompositeConfiguration);
        assertFalse(sp.getConfiguration(TokenConfiguration.class) instanceof CompositeConfiguration);
        assertFalse(sp.getConfiguration(UserConfiguration.class) instanceof CompositeConfiguration);
    }
}


text:
# empty-line-before-comment

> [ESLint rule][eslint-rules] to enforce empty lines before comments.

## Usage

```javascript
var rule = require( '@stdlib/_tools/eslint/rules/empty-line-before-comment' );
```

#### rule

[ESLint rule][eslint-rules] to enforce empty lines before comments.

**Bad**:

```javascript
function square( x ) {
    var out;
    // Square the number:
    out = x*x;
    return out;
}
```

**Good**:

```javascript
function square( x ) {
    var out;

    // Square the number:
    out = x*x;
    return out;
}
```

## Examples

```javascript
var Linter = require( 'eslint' ).Linter;
var rule = require( '@stdlib/_tools/eslint/rules/empty-line-before-comment' );

var linter = new Linter();
var result;
var code;

code = [
    'function square( x ) {',
    '  var out;',
    '  // Square the number:',
    '  out = x*x;',
    '  return out;',
    '}'
].join( '\n' );

linter.defineRule( 'empty-line-before-comment', rule );

result = linter.verify( code, {
    'rules': {
        'empty-line-before-comment': 'error'
    }
});
/* returns
    [
        {
            'ruleId': 'empty-line-before-comment',
            'severity': 2,
            'message': 'Missing empty line before comment',
            'line': 3,
            'column': 3,
            'nodeType': null,
            'source': '  // Square the number:',
            'endLine': 3,
            'endColumn': 24
        }
    ]
*/
```

[eslint-rules]: https://eslint.org/docs/developer-guide/working-with-rules


text:
from __future__ import absolute_import, division

from bson import BSON, ObjectId
from bson.son import SON
from pymongo.errors import OperationFailure, WriteError, BulkWriteError, \
    DuplicateKeyError
from pymongo.results import InsertOneResult, InsertManyResult, UpdateResult, \
    DeleteResult
from pymongo.collection import ReturnDocument
from pymongo.write_concern import WriteConcern
from twisted.internet import defer
from twisted.trial import unittest
from txmongo.protocol import MongoClientProtocol
import txmongo.filter as qf
from tests.utils import SingleCollectionTest

class _CallCounter(object):
    def __init__(self, original):
        self.call_count = 0
        self.original = original

    def __call__(self, this, *args, **kwargs):
        self.call_count += 1
        return self.original(this, *args, **kwargs)

class TestMongoQueries(SingleCollectionTest):

    timeout = 15

    @defer.inlineCallbacks
    def test_SingleCursorIteration(self):
        yield self.coll.insert([{'v': i} for i in range(10)], safe=True)
        res = yield self.coll.find()
        self.assertEqual(len(res), 10)

    @defer.inlineCallbacks
    def test_MultipleCursorIterations(self):
        yield self.coll.insert([{'v': i} for i in range(450)], safe=True)
        res = yield self.coll.find()
        self.assertEqual(len(res), 450)

    @defer.inlineCallbacks
    def test_FindWithCursor(self):
        yield self.coll.insert([{'v': i} for i in range(750)], safe=True)
        docs, d = yield self.coll.find_with_cursor()
        self.assertEqual(len(docs), 101)
        total = 0
        while docs:
            total += len(docs)
            docs, d = yield d
        self.assertEqual(total, 750)

        # Same thing, but with the "cursor" keyword argument on find()
        docs, d = yield self.coll.find(cursor=True)
        self.assertEqual(len(docs), 101)
        total = 0
        while docs:
            total += len(docs)
            docs, d = yield d
        self.assertEqual(total, 750)

    @defer.inlineCallbacks
    def test_FindWithCursorLimit(self):
        yield self.coll.insert([{'v': i} for i in range(750)], safe=True)

        docs, d = yield self.coll.find_with_cursor(limit=150)
        total = 0
        while docs:
            total += len(docs)
            docs, d = yield d
        self.assertEqual(total, 150)

        # Same using find(cursor=True)
        docs, d = yield self.coll.find(limit=150, cursor=True)
        total = 0
        while docs:
            total += len(docs)
            docs, d = yield d
        self.assertEqual(total, 150)

    @defer.inlineCallbacks
    def test_FindWithCursorBatchsize(self):
        yield self.coll.insert([{'v': i} for i in range(140)], safe=True)

        docs, d = yield self.coll.find_with_cursor(batch_size=50)
        lengths = []
        while docs:
            lengths.append(len(docs))
            docs, d = yield d
        self.assertEqual(lengths, [50,50,40])

    @defer.inlineCallbacks
    def test_FindWithCursorBatchsizeLimit(self):
        yield self.coll.insert([{'v': i} for i in range(140)], safe=True)

        docs, d = yield self.coll.find_with_cursor(batch_size=50,limit=10)
        lengths = []
        while docs:
            lengths.append(len(docs))
            docs, d = yield d
        self.assertEqual(lengths, [10])

    @defer.inlineCallbacks
    def test_FindWithCursorZeroBatchsize(self):
        yield self.coll.insert([{'v': i} for i in range(140)], safe=True)

        docs, d = yield self.coll.find_with_cursor(batch_size=0)
        lengths = []
        while docs:
            lengths.append(len(docs))
            docs, d = yield d
        self.assertEqual(lengths, [101,39])

    @defer.inlineCallbacks
    def test_LargeData(self):
        yield self.coll.insert([{'v': ' '*(2**19)} for _ in range(4)], safe=True)
        res = yield self.coll.find()
        self.assertEqual(len(res), 4)

    @defer.inlineCallbacks
    def test_SpecifiedFields(self):
        yield self.coll.insert([dict((k, v) for k in "abcdefg") for v in range(5)], safe=True)
        res = yield self.coll.find(fields={'a': 1, 'c': 1})
        self.assertTrue(all(x in ['a', 'c', "_id"] for x in res[0].keys()))
        res = yield self.coll.find(fields=['a', 'c'])
        self.assertTrue(all(x in ['a', 'c', "_id"] for x in res[0].keys()))
        res = yield self.coll.find(fields=[])
        self.assertTrue(all(x in ["_id"] for x in res[0].keys()))
        self.assertRaises(TypeError, self.coll.find,{}, fields=[1])

    @defer.inlineCallbacks
    def test_group(self):
        server_status = yield self.conn.admin.command("serverStatus")
        version = [int(part) for part in server_status['version'].split('.')]
        if version >= [4, 2]:
            raise unittest.SkipTest("`group` is only supported by MongoDB <= 4.0")

        yield self.coll.insert([{'v': i % 2} for i in range(5)], safe=True)
        reduce_ = """
        function(curr, result) {
            result.total += curr.v;
        }
        """
        keys = {'v': 1}
        initial = {"total": 0}
        cond = {'v': {"$in": [0, 1]}}
        final = """
        function(result) {
            result.five = 5;
        }
        """
        res = yield self.coll.group(keys, initial, reduce_, cond, final)
        self.assertEqual(len(res["retval"]), 2)

        keys = """
        function(doc) {
            return {"value": 5, 'v': 1};
        }
        """

        res = yield self.coll.group(keys, initial, reduce_, cond, final)
        self.assertEqual(len(res["retval"]), 1)

    def __make_big_object(self):
        return {"_id": ObjectId(), 'x': 'a' * 1000}

    @defer.inlineCallbacks
    def __check_no_open_cursors(self):
        status = yield self.db.command("serverStatus")
        if "cursor" in status["metrics"]:
            self.assertEqual(status["metrics"]["cursor"]["open"]["total"], 0)
        else:
            self.assertEqual(status["cursors"]["totalOpen"], 0)

    @defer.inlineCallbacks
    def test_CursorClosing(self):
        # Calculate number of objects in 4mb batch
        obj_count_4mb = 4 * 1024**2 // len(BSON.encode(self.__make_big_object())) + 1

        first_batch = 5
        yield self.coll.insert(
            [self.__make_big_object() for _ in range(first_batch + obj_count_4mb)])
        result = yield self.coll.find(limit=first_batch)

        self.assertEqual(len(result), 5)

        yield self.__check_no_open_cursors()

    @defer.inlineCallbacks
    def test_CursorClosingWithCursor(self):
        # Calculate number of objects in 4mb batch
        obj_count_4mb = 4 * 1024**2 // len(BSON.encode(self.__make_big_object())) + 1

        first_batch = 5
        yield self.coll.insert(
            [self.__make_big_object() for _ in range(first_batch + obj_count_4mb)])

        result = []
        docs, dfr = yield self.coll.find_with_cursor({}, limit=first_batch)
        while docs:
            result.extend(docs)
            docs, dfr = yield dfr

        self.assertEqual(len(result), 5)

        yield self.__check_no_open_cursors()

    @defer.inlineCallbacks
    def test_GetMoreCount(self):
        counter = _CallCounter(MongoClientProtocol.send_GETMORE)
        self.patch(MongoClientProtocol, 'send_GETMORE', counter)

        yield self.coll.insert([{'x': 42} for _ in range(20)])
        result = yield self.coll.find({}, limit=10)

        self.assertEqual(len(result), 10)
        self.assertEqual(counter.call_count, 0)

    @defer.inlineCallbacks
    def test_GetMoreCountWithCursor(self):
        counter = _CallCounter(MongoClientProtocol.send_GETMORE)
        self.patch(MongoClientProtocol, 'send_GETMORE', counter)

        yield self.coll.insert([{'x': 42} for _ in range(20)])

        result = []
        docs, dfr = yield self.coll.find_with_cursor({}, limit=5)
        while docs:
            result.extend(docs)
            docs, dfr = yield dfr

        self.assertEqual(len(result), 5)
        self.assertEqual(counter.call_count, 0)

    @defer.inlineCallbacks
    def test_AsClass(self):
        yield self.coll.insert({'x': 42})

        doc = yield self.coll.find_one({})
        self.assertTrue(type(doc) is dict)

        class CustomDict(dict):
            pass

        doc = yield self.coll.find_one({}, as_class=CustomDict)
        self.assertTrue(type(doc) is CustomDict)

    @defer.inlineCallbacks
    def test_FindOneNone(self):
        doc = yield self.coll.find_one()
        self.assertEqual(doc, None)

class TestMongoQueriesEdgeCases(SingleCollectionTest):

    timeout = 15

    @defer.inlineCallbacks
    def test_BelowBatchThreshold(self):
        yield self.coll.insert([{'v': i} for i in range(100)], safe=True)
        res = yield self.coll.find()
        self.assertEqual(len(res), 100)

    @defer.inlineCallbacks
    def test_EqualToBatchThreshold(self):
        yield self.coll.insert([{'v': i} for i in range(101)], safe=True)
        res = yield self.coll.find()
        self.assertEqual(len(res), 101)

    @defer.inlineCallbacks
    def test_AboveBatchThreshold(self):
        yield self.coll.insert([{'v': i} for i in range(102)], safe=True)
        res = yield self.coll.find()
        self.assertEqual(len(res), 102)

class TestLimit(SingleCollectionTest):

    timeout = 15

    @defer.inlineCallbacks
    def test_LimitBelowBatchThreshold(self):
        yield self.coll.insert([{'v': i} for i in range(50)], safe=True)
        res = yield self.coll.find(limit=20)
        self.assertEqual(len(res), 20)

    @defer.inlineCallbacks
    def test_LimitAboveBatchThreshold(self):
        yield self.coll.insert([{'v': i} for i in range(200)], safe=True)
        res = yield self.coll.find(limit=150)
        self.assertEqual(len(res), 150)

    @defer.inlineCallbacks
    def test_LimitAtBatchThresholdEdge(self):
        yield self.coll.insert([{'v': i} for i in range(200)], safe=True)
        res = yield self.coll.find(limit=100)
        self.assertEqual(len(res), 100)

        yield self.coll.drop()

        yield self.coll.insert([{'v': i} for i in range(200)], safe=True)
        res = yield self.coll.find(limit=101)
        self.assertEqual(len(res), 101)

        yield self.coll.drop()

        yield self.coll.insert([{'v': i} for i in range(200)], safe=True)
        res = yield self.coll.find(limit=102)
        self.assertEqual(len(res), 102)

    @defer.inlineCallbacks
    def test_LimitAboveMessageSizeThreshold(self):
        yield self.coll.insert([{'v': ' '*(2**20)} for _ in range(8)], safe=True)
        res = yield self.coll.find(limit=5)
        self.assertEqual(len(res), 5)

    @defer.inlineCallbacks
    def test_HardLimit(self):
        yield self.coll.insert([{'v': i} for i in range(200)], safe=True)
        res = yield self.coll.find(limit=-150)
        self.assertEqual(len(res), 150)

class TestSkip(SingleCollectionTest):

    timeout = 15

    @defer.inlineCallbacks
    def test_Skip(self):
        yield self.coll.insert([{'v': i} for i in range(5)], safe=True)
        res = yield self.coll.find(skip=3)
        self.assertEqual(len(res), 2)

        yield self.coll.drop()

        yield self.coll.insert([{'v': i} for i in range(5)], safe=True)
        res = yield self.coll.find(skip=5)
        self.assertEqual(len(res), 0)

        yield self.coll.drop()

        yield self.coll.insert([{'v': i} for i in range(5)], safe=True)
        res = yield self.coll.find(skip=6)
        self.assertEqual(len(res), 0)

    @defer.inlineCallbacks
    def test_SkipWithLimit(self):
        yield self.coll.insert([{'v': i} for i in range(5)], safe=True)
        res = yield self.coll.find(skip=3, limit=1)
        self.assertEqual(len(res), 1)

        yield self.coll.drop()

        yield self.coll.insert([{'v': i} for i in range(5)], safe=True)
        res = yield self.coll.find(skip=4, limit=2)
        self.assertEqual(len(res), 1)

        yield self.coll.drop()

        yield self.coll.insert([{'v': i} for i in range(5)], safe=True)
        res = yield self.coll.find(skip=4, limit=1)
        self.assertEqual(len(res), 1)

        yield self.coll.drop()

        yield self.coll.insert([{'v': i} for i in range(5)], safe=True)
        res = yield self.coll.find(skip=5, limit=1)
        self.assertEqual(len(res), 0)

class TestCommand(SingleCollectionTest):

    @defer.inlineCallbacks
    def test_SimpleCommand(self):
        pong = yield self.db.command("ping")
        self.assertEqual(pong["ok"], 1)

    @defer.inlineCallbacks
    def test_ComplexCommand(self):
        yield self.coll.insert([{'x': 42}, {'y': 123}], safe=True)

        # In form of command name, value and additional params
        result = yield self.db.command("count", "mycol", query={'x': 42})
        self.assertEqual(result['n'], 1)

        # In form of SON object
        result = yield self.db.command(SON([("count", "mycol"), ("query", {'y': 123})]))
        self.assertEqual(result['n'], 1)

    @defer.inlineCallbacks
    def test_CheckResult(self):
        yield self.coll.insert([{'x': 42}, {'y': 123}], safe=True)

        # missing 'deletes' argument
        self.assertFailure(self.db.command("delete", "mycol"), OperationFailure)

        result = yield self.db.command("delete", "mycol", check=False)
        self.assertFalse(result["ok"])

        result = yield self.db.command(
            "delete", "mycol", check=True,
            allowable_errors=[
                "missing deletes field",
                "The deletes option is required to the delete command.",
                "BSON field 'delete.deletes' is missing but a required field"
            ]
        )
        self.assertFalse(result["ok"])

class TestUpdate(SingleCollectionTest):

    @defer.inlineCallbacks
    def test_SimpleUpdate(self):
        yield self.coll.insert([{'x': 42}, {'x': 123}])

        yield self.coll.update({}, {"$set": {'x': 456}})

        docs = yield self.coll.find(fields={"_id": 0})

        # Check that only one document was updated
        self.assertTrue({'x': 456} in docs)
        self.assertTrue(({'x': 42} in docs) or ({'x': 123} in docs))

    @defer.inlineCallbacks
    def test_MultiUpdate(self):
        yield self.coll.insert([{'x': 42}, {'x': 123}])

        yield self.coll.update({}, {"$set": {'x': 456}}, multi=True)

        docs = yield self.coll.find(fields={"_id": 0})

        self.assertEqual(len(docs), 2)
        self.assertTrue(all(doc == {'x': 456} for doc in docs))

    @defer.inlineCallbacks
    def test_Upsert(self):
        yield self.coll.update({}, {"$set": {'x': 42}}, upsert=True)
        yield self.coll.update({}, {"$set": {'x': 123}}, upsert=True)

        docs = yield self.coll.find(fields={"_id": 0})

        self.assertEqual(len(docs), 1)
        self.assertEqual(docs[0], {'x': 123})

class TestSave(SingleCollectionTest):

    @defer.inlineCallbacks
    def test_Save(self):
        self.assertRaises(TypeError, self.coll.save, 123)

        yield self.coll.save({'x': 1})
        oid = ObjectId()
        yield self.coll.save({"_id": oid, 'x': 2})
        yield self.coll.save({"_id": oid, 'x': 3})

        docs = yield self.coll.find()
        self.assertTrue(any(doc['x'] == 1 for doc in docs))
        self.assertTrue({"_id": oid, 'x': 3} in docs)

class TestRemove(SingleCollectionTest):

    @defer.inlineCallbacks
    def test_RemoveOne(self):
        docs = [{'x': 42}, {'x': 123}]
        yield self.coll.insert(docs)
        yield self.coll.remove({}, single=True)

        remaining = yield self.coll.find()
        self.assertEqual(len(remaining), 1)
        self.assertTrue(remaining[0] in docs)

    @defer.inlineCallbacks
    def test_RemoveMulti(self):
        yield self.coll.insert([{'x': 42}, {'x': 123}, {'y': 456}])
        yield self.coll.remove({'x': {"$exists": True}})

        remaining = yield self.coll.find(fields={"_id": 0})
        self.assertEqual(remaining, [{'y': 456}])

    @defer.inlineCallbacks
    def test_RemoveById(self):
        oid = ObjectId()
        yield self.coll.insert([{"_id": oid, 'x': 42}, {'y': 123}])
        yield self.coll.remove(oid)

        remaining = yield self.coll.find(fields={"_id": 0})
        self.assertEqual(remaining, [{'y': 123}])

    def test_RemoveInvalid(self):
        self.assertRaises(TypeError, self.coll.remove, 123)

class TestDistinct(SingleCollectionTest):

    @defer.inlineCallbacks
    def test_Simple(self):
        yield self.coll.insert([{'x': 13}, {'x': 42}, {'x': 13}])

        d = yield self.coll.distinct('x')
        self.assertEqual(set(d), {13, 42})

    @defer.inlineCallbacks
    def test_WithQuery(self):
        yield self.coll.insert([{'x': 13}, {'x': 42}, {'x': 123}, {'x': 42}])

        d = yield self.coll.distinct('x', {'x': {"$gt": 20}})
        self.assertEqual(set(d), {42, 123})

class TestMapReduce(SingleCollectionTest):

    @defer.inlineCallbacks
    def test_MapReduce(self):
        yield self.coll.insert([
            {"kid": "John", "grade": 5},
            {"kid": "Kate", "grade": 4},
            {"kid": "John", "grade": 4},
            {"kid": "Kate", "grade": 4},
            {"kid": "Adam", "grade": 4},
            {"kid": "Kate", "grade": 2},
            {"kid": "John", "grade": 5},
        ])

        t_map = """
            function () {
                emit(this.kid, this.grade);
            }
        """

        t_reduce = """
            function (key, values) {
                return Array.sum(values);
            }
        """

        result = yield self.coll.map_reduce(t_map, t_reduce, out={"inline": 1})
        self.assertEqual(len(result), 3)
        self.assertTrue({"_id": "John", "value": 14} in result)
        self.assertTrue({"_id": "Kate", "value": 10} in result)
        self.assertTrue({"_id": "Adam", "value": 4} in result)

        result = yield self.coll.map_reduce(t_map, t_reduce, out={"inline": 1}, full_response=True)
        self.assertTrue(result["ok"], 1)
        self.assertTrue("counts" in result)
        self.assertTrue("results" in result)

class TestInsertOne(SingleCollectionTest):

    @defer.inlineCallbacks
    def test_Acknowledged(self):
        result = yield self.coll.insert_one({'x': 42})
        self.assertTrue(isinstance(result, InsertOneResult))
        self.assertEqual(result.acknowledged, True)
        self.assertTrue(isinstance(result.inserted_id, ObjectId))

        count = yield self.coll.count()
        self.assertEqual(count, 1)

    @defer.inlineCallbacks
    def test_Unacknowledged(self):
        oid = ObjectId()
        doc = {'x': 42, "_id": oid}
        result = yield self.coll.with_options(write_concern=WriteConcern(w=0)).insert_one(doc)
        self.assertEqual(result.acknowledged, False)
        self.assertEqual(result.inserted_id, oid)

        # It's ok to issue count() right after unacknowledged insert because
        # we have exactly one connection
        count = yield self.coll.count()
        self.assertEqual(count, 1)

    @defer.inlineCallbacks
    def test_Failures(self):
        yield self.coll.insert_one({"_id": 1})

        yield self.assertFailure(self.coll.insert_one({"_id": 1}), DuplicateKeyError)
        yield self.coll.with_options(write_concern=WriteConcern(w=0)).insert_one({"_id": 1})

        yield self.assertFailure(self.coll.insert_one({'$': 1}), WriteError)
        yield self.coll.with_options(write_concern=WriteConcern(w=0)).insert_one({'$': 1})

class TestInsertMany(SingleCollectionTest):

    def setUp(self):
        self.more_than_1k = [{"_id": i} for i in range(2016)]
        return super(TestInsertMany, self).setUp()

    def test_InvalidArg(self):
        self.assertRaises(TypeError, self.coll.insert_many, {'x': 42})

    @defer.inlineCallbacks
    def test_Acknowledged(self):
        result = yield self.coll.insert_many([{'x': 42} for _ in range(100)])
        self.assertTrue(isinstance(result, InsertManyResult))
        self.assertEqual(result.acknowledged, True)

        docs = yield self.coll.find()
        ids = set(doc["_id"] for doc in docs)

        self.assertEqual(ids, set(result.inserted_ids))

    @defer.inlineCallbacks
    def test_Unacknowledged(self):
        result = yield self.coll.with_options(write_concern=WriteConcern(w=0))\
                                .insert_many([{'x': 42} for _ in range(100)])
        self.assertTrue(isinstance(result, InsertManyResult))
        self.assertEqual(result.acknowledged, False)

        docs = yield self.coll.find()
        self.assertEqual({doc["_id"] for doc in docs}, set(result.inserted_ids))

    @defer.inlineCallbacks
    def test_OrderedAck_Ok(self):
        result = yield self.coll.insert_many(self.more_than_1k)
        found = yield self.coll.find()
        self.assertEqual(len(result.inserted_ids), len(self.more_than_1k))
        self.assertEqual(len(found), len(self.more_than_1k))
        self.assertEqual(set(result.inserted_ids), {doc["_id"] for doc in found})

    @defer.inlineCallbacks
    def test_OrderedUnack_Ok(self):
        w_0 = self.coll.with_options(write_concern=WriteConcern(w=0))
        result = yield w_0.insert_many(self.more_than_1k)
        found = yield self.coll.find()
        self.assertEqual(len(result.inserted_ids), len(self.more_than_1k))
        self.assertEqual(len(found), len(self.more_than_1k))
        self.assertEqual(set(result.inserted_ids), {doc["_id"] for doc in found})

    @defer.inlineCallbacks
    def test_OrderedAck_Fail(self):
        self.more_than_1k[500] = self.more_than_1k[499]
        error = yield self.assertFailure(self.coll.insert_many(self.more_than_1k), BulkWriteError)
        self.assertEqual(error.details["nInserted"], 500)
        self.assertEqual((yield self.coll.count()), 500)
        self.assertEqual(len(error.details["writeErrors"]), 1)
        self.assertEqual(error.details["writeErrors"][0]["index"], 500)
        self.assertEqual(error.details["writeErrors"][0]["op"], {"_id": 499})

    @defer.inlineCallbacks
    def test_OrderedUnack_Fail(self):
        self.more_than_1k[500] = self.more_than_1k[499]

        w_0 = self.coll.with_options(write_concern=WriteConcern(w=0))
        result = yield w_0.insert_many(self.more_than_1k)
        self.assertEqual(len(result.inserted_ids), len(self.more_than_1k))
        found = yield self.coll.find()
        self.assertEqual(len(found), 500)
        self.assertEqual({doc["_id"] for doc in found[:500]}, set(result.inserted_ids[:500]))

    @defer.inlineCallbacks
    def test_UnorderedAck_Fail(self):
        self.more_than_1k[500] = self.more_than_1k[499]
        error = yield self.assertFailure(self.coll.insert_many(self.more_than_1k, ordered=False),
                                         BulkWriteError)
        self.assertEqual(error.details["nInserted"], len(self.more_than_1k) - 1)
        self.assertEqual((yield self.coll.count()), len(self.more_than_1k) - 1)
        self.assertEqual(len(error.details["writeErrors"]), 1)
        self.assertEqual(error.details["writeErrors"][0]["index"], 500)
        self.assertEqual(error.details["writeErrors"][0]["op"], {"_id": 499})

    @defer.inlineCallbacks
    def test_UnorderedUnack_Fail(self):
        self.more_than_1k[500] = self.more_than_1k[499]

        w_0 = self.coll.with_options(write_concern=WriteConcern(w=0))
        result = yield w_0.insert_many(self.more_than_1k, ordered=False)
        self.assertEqual(len(result.inserted_ids), len(self.more_than_1k))
        found = yield self.coll.find()
        self.assertEqual(len(found), len(self.more_than_1k) - 1)
        self.assertEqual({doc["_id"] for doc in found}, set(result.inserted_ids) - {500})

    @defer.inlineCallbacks
    def test_MoreThan16Mb(self):
        # 8mb x 5
        mb40 = [{"_id": i, 'x': 'y'*(8*1024**2)} for i in range(5)]

        result = yield self.coll.insert_many(mb40)
        self.assertEqual(result.inserted_ids, list(range(5)))
        found = yield self.coll.find()
        self.assertEqual(len(found), 5)
        total_size = sum(len(BSON.encode(doc)) for doc in found)
        self.assertGreater(total_size, 40*1024**2)

class TestUpdateOne(SingleCollectionTest):

    @defer.inlineCallbacks
    def setUp(self):
        yield super(TestUpdateOne, self).setUp()
        yield self.coll.insert_many([{'x': 1}, {'x': 2}])

    @defer.inlineCallbacks
    def test_Acknowledged(self):
        result = yield self.coll.update_one({'x': {"$exists": True}}, {"$set": {'y': 123}})
        self.assertTrue(isinstance(result, UpdateResult))
        self.assertEqual(result.acknowledged, True)
        self.assertEqual(result.matched_count, 1)
        self.assertEqual(result.modified_count, 1)
        self.assertEqual(result.upserted_id, None)

    @defer.inlineCallbacks
    def test_Unacknowledged(self):
        coll = self.coll.with_options(write_concern=WriteConcern(w=0))
        result = yield coll.update_one({'x': {"$exists": True}}, {"$set": {'y': 123}})
        self.assertTrue(isinstance(result, UpdateResult))
        self.assertEqual(result.acknowledged, False)

    @defer.inlineCallbacks
    def test_UpsertAcknowledged(self):
        result = yield self.coll.update_one({'y': 123}, {"$set": {'z': 456}}, upsert=True)
        self.assertTrue(isinstance(result.upserted_id, ObjectId))

        doc = yield self.coll.find_one({"_id": result.upserted_id}, fields={"_id": 0})
        self.assertEqual(doc, {'y': 123, 'z': 456})

    @defer.inlineCallbacks
    def test_UpsertUnacknowledged(self):
        coll = self.coll.with_options(write_concern=WriteConcern(w=0))
        result = yield coll.update_one({'y': 123}, {"$set": {'z': 456}}, upsert=True)
        self.assertEqual(result.acknowledged, False)

        cnt = yield self.coll.count()
        self.assertEqual(cnt, 3)

    def test_InvalidUpdate(self):
        # update_one/update_many only allow $-operators, not whole document replace)
        self.assertRaises(ValueError, self.coll.update_one, {'x': 1}, {'y': 123})

    @defer.inlineCallbacks
    def test_Failures(self):
        # can't alter _id
        yield self.assertFailure(self.coll.update_one({'x': 1}, {"$set": {"_id": 1}}), WriteError)
        # invalid field name
        yield self.assertFailure(self.coll.update_one({'x': 1}, {"$set": {'$': 1}}), WriteError)

        yield self.coll.create_index(qf.sort(qf.ASCENDING('x')), unique=True)
        yield self.assertFailure(self.coll.update_one({'x': 2}, {"$set": {'x': 1}}), DuplicateKeyError)

class TestReplaceOne(SingleCollectionTest):

    @defer.inlineCallbacks
    def setUp(self):
        yield super(TestReplaceOne, self).setUp()
        yield self.coll.insert_many([{'x': 1}, {'x': 2}])

    @defer.inlineCallbacks
    def test_Acknowledged(self):
        result = yield self.coll.replace_one({'x': {"$exists": True}}, {'y': 123})
        self.assertTrue(isinstance(result, UpdateResult))
        self.assertEqual(result.acknowledged, True)
        self.assertEqual(result.matched_count, 1)
        self.assertEqual(result.modified_count, 1)
        self.assertEqual(result.upserted_id, None)

    @defer.inlineCallbacks
    def test_Unacknowledged(self):
        coll = self.coll.with_options(write_concern=WriteConcern(w=0))
        result = yield coll.replace_one({'x': {"$exists": True}}, {'y': 123})
        self.assertTrue(isinstance(result, UpdateResult))
        self.assertEqual(result.acknowledged, False)

    @defer.inlineCallbacks
    def test_UpsertAcknowledged(self):
        result = yield self.coll.replace_one({'x': 5}, {'y': 123}, upsert=True)
        self.assertTrue(isinstance(result.upserted_id, ObjectId))

        doc = yield self.coll.find_one({"_id": result.upserted_id}, fields={"_id": 0})
        self.assertEqual(doc, {'y': 123})

    @defer.inlineCallbacks
    def test_UpsertUnacknowledged(self):
        coll = self.coll.with_options(write_concern=WriteConcern(w=0))
        result = yield coll.replace_one({'x': 5}, {'y': 123}, upsert=True)
        self.assertEqual(result.acknowledged, False)

        doc = yield self.coll.find_one({"y": {"$exists": True}}, fields={"_id": 0})
        self.assertEqual(doc, {'y': 123})

    def test_InvalidReplace(self):
        # replace_one does not allow $-operators, only whole document replace
        self.assertRaises(ValueError, self.coll.replace_one, {'x': 1}, {"$set": {'y': 123}})

    @defer.inlineCallbacks
    def test_Failures(self):
        yield self.assertFailure(self.coll.replace_one({'x': 1}, {'x': {'$': 5}}), WriteError)

        yield self.coll.create_index(qf.sort(qf.ASCENDING('x')), unique=True)
        yield self.assertFailure(self.coll.replace_one({'x': 1}, {'x': 2}), DuplicateKeyError)

class TestUpdateMany(SingleCollectionTest):

    @defer.inlineCallbacks
    def setUp(self):
        yield super(TestUpdateMany, self).setUp()
        yield self.coll.insert_many([{'x': 1}, {'x': 2}])

    @defer.inlineCallbacks
    def test_Acknowledged(self):
        result = yield self.coll.update_many({'x': {"$exists": True}}, {"$set": {'y': 5}})
        self.assertTrue(isinstance(result, UpdateResult))
        self.assertEqual(result.acknowledged, True)
        self.assertEqual(result.matched_count, 2)
        self.assertEqual(result.modified_count, 2)
        self.assertEqual(result.upserted_id, None)

        cnt = yield self.coll.count({'y': 5})
        self.assertEqual(cnt, 2)

    @defer.inlineCallbacks
    def test_Unacknowledged(self):
        coll = self.coll.with_options(write_concern=WriteConcern(w=0))
        result = yield coll.update_many({'x': {"$exists": True}}, {"$set": {'y': 5}})
        self.assertTrue(isinstance(result, UpdateResult))
        self.assertEqual(result.acknowledged, False)

        cnt = yield self.coll.count({'y': 5})
        self.assertEqual(cnt, 2)

    @defer.inlineCallbacks
    def test_UpsertAcknowledged(self):
        result = yield self.coll.update_many({'x': 5}, {"$set": {'y': 5}}, upsert=True)
        self.assertEqual(result.acknowledged, True)
        self.assertEqual(result.matched_count, 0)
        self.assertEqual(result.modified_count, 0)
        self.assertTrue(isinstance(result.upserted_id, ObjectId))

        cnt = yield self.coll.count()
        self.assertEqual(cnt, 3)

    @defer.inlineCallbacks
    def test_UpsertUnacknowledged(self):
        coll = self.coll.with_options(write_concern=WriteConcern(w=0))
        result = yield coll.update_many({'x': 5}, {"$set": {'y': 5}}, upsert=True)
        self.assertEqual(result.acknowledged, False)

        cnt = yield self.coll.count()
        self.assertEqual(cnt, 3)

    def test_InvalidUpdate(self):
        # update_one/update_many only allow $-operators, not whole document replace)
        self.assertRaises(ValueError, self.coll.update_many, {'x': 1}, {'y': 123})

    @defer.inlineCallbacks
    def test_Failures(self):
        # can't alter _id
        yield self.assertFailure(self.coll.update_many({}, {"$set": {"_id": 1}}), WriteError)
        # invalid field name
        yield self.assertFailure(self.coll.update_many({}, {"$set": {'$': 1}}), WriteError)

        yield self.coll.create_index(qf.sort(qf.ASCENDING('x')), unique=True)
        yield self.assertFailure(self.coll.update_many({'x': 2}, {"$set": {'x': 1}}), DuplicateKeyError)

class TestDeleteOne(SingleCollectionTest):

    @defer.inlineCallbacks
    def setUp(self):
        yield super(TestDeleteOne, self).setUp()
        yield self.coll.insert_many([{'x': 1}, {'x': 1}])

    @defer.inlineCallbacks
    def test_Acknowledged(self):
        result = yield self.coll.delete_one({'x': 1})
        self.assertTrue(isinstance(result, DeleteResult))
        self.assertEqual(result.acknowledged, True)
        self.assertEqual(result.deleted_count, 1)

        cnt = yield self.coll.count()
        self.assertEqual(cnt, 1)

    @defer.inlineCallbacks
    def test_Unacknowledged(self):
        coll = self.coll.with_options(write_concern=WriteConcern(w=0))
        result = yield coll.delete_one({'x': 1})
        self.assertTrue(isinstance(result, DeleteResult))
        self.assertEqual(result.acknowledged, False)

        cnt = yield self.coll.count()
        self.assertEqual(cnt, 1)

    @defer.inlineCallbacks
    def test_Failures(self):
        yield self.assertFailure(self.coll.delete_one({'x': {'$': 1}}), WriteError)

class TestDeleteMany(SingleCollectionTest):

    @defer.inlineCallbacks
    def setUp(self):
        yield super(TestDeleteMany, self).setUp()
        yield self.coll.insert_many([{'x': 1}, {'x': 1}])

    @defer.inlineCallbacks
    def test_Acknowledged(self):
        result = yield self.coll.delete_many({'x': 1})
        self.assertTrue(isinstance(result, DeleteResult))
        self.assertEqual(result.acknowledged, True)
        self.assertEqual(result.deleted_count, 2)

        cnt = yield self.coll.count()
        self.assertEqual(cnt, 0)

    @defer.inlineCallbacks
    def test_Unacknowledged(self):
        coll = self.coll.with_options(write_concern=WriteConcern(w=0))
        result = yield coll.delete_many({'x': 1})
        self.assertTrue(isinstance(result, DeleteResult))
        self.assertEqual(result.acknowledged, False)

        cnt = yield self.coll.count()
        self.assertEqual(cnt, 0)

    @defer.inlineCallbacks
    def test_Failures(self):
        yield self.assertFailure(self.coll.delete_many({'x': {'$': 1}}), WriteError)

class TestFindOneAndDelete(SingleCollectionTest):

    @defer.inlineCallbacks
    def setUp(self):
        yield super(TestFindOneAndDelete, self).setUp()
        yield self.coll.insert_many([{'x': 1, 'y': 1},
                                     {'x': 2, 'y': 2},
                                     {'x': 3, 'y': 3}])

    @defer.inlineCallbacks
    def test_Sort(self):
        doc = yield self.coll.find_one_and_delete({'x': {"$exists": True}},
                                                  sort=qf.sort(qf.ASCENDING('y')))
        self.assertEqual(doc['x'], 1)

        doc = yield self.coll.find_one_and_delete({'x': {"$exists": True}},
                                                  sort=qf.sort(qf.DESCENDING('y')))
        self.assertEqual(doc['x'], 3)

        cnt = yield self.coll.count()
        self.assertEqual(cnt, 1)

    @defer.inlineCallbacks
    def test_Projection(self):
        doc = yield self.coll.find_one_and_delete({'x': 2}, {'y': 1, "_id": 0})
        self.assertEqual(doc, {'y': 2})

class TestFindOneAndReplace(SingleCollectionTest):

    @defer.inlineCallbacks
    def setUp(self):
        yield super(TestFindOneAndReplace, self).setUp()
        yield self.coll.insert_many([{'x': 10, 'y': 10},
                                     {'x': 20, 'y': 20},
                                     {'x': 30, 'y': 30}])

    @defer.inlineCallbacks
    def test_Sort(self):
        doc = yield self.coll.find_one_and_replace({}, {'x': 5, 'y': 5},
                                                   projection={"_id": 0},
                                                   sort=qf.sort(qf.ASCENDING('y')))
        self.assertEqual(doc, {'x': 10, 'y': 10})

        doc = yield self.coll.find_one_and_replace({}, {'x': 40, 'y': 40},
                                                   projection={"_id": 0},
                                                   sort=qf.sort(qf.DESCENDING('y')))
        self.assertEqual(doc, {'x': 30, 'y': 30})

        ys = yield self.coll.distinct('y')
        self.assertEqual(set(ys), {5, 20, 40})

    def test_InvalidReplace(self):
        self.assertRaises(ValueError, self.coll.find_one_and_replace, {}, {"$set": {'z': 1}})

    @defer.inlineCallbacks
    def test_Upsert(self):
        doc = yield self.coll.find_one_and_replace({'x': 40}, {'x': 50}, upsert=True)
        self.assertEqual(doc, None)

        xs = yield self.coll.distinct('x')
        self.assertEqual(set(xs), {10, 20, 30, 50})

    @defer.inlineCallbacks
    def test_ReturnDocument(self):
        doc = yield self.coll.find_one_and_replace({'x': 10}, {'x': 15},
                                                   return_document=ReturnDocument.BEFORE)
        self.assertEqual(doc['x'], 10)

        doc = yield self.coll.find_one_and_replace({'x': 20}, {'x': 25},
                                                   return_document=ReturnDocument.AFTER)
        self.assertEqual(doc['x'], 25)

    def test_InvalidReturnDocument(self):
        self.assertRaises(ValueError, self.coll.find_one_and_replace, {}, {}, return_document=1)

class TestFindOneAndUpdate(SingleCollectionTest):

    @defer.inlineCallbacks
    def setUp(self):
        yield super(TestFindOneAndUpdate, self).setUp()
        yield self.coll.insert_many([{'x': 10, 'y': 10},
                                     {'x': 20, 'y': 20},
                                     {'x': 30, 'y': 30}])

    @defer.inlineCallbacks
    def test_Sort(self):
        doc = yield self.coll.find_one_and_update({}, {"$set": {'y': 5}},
                                                  projection={"_id": 0},
                                                  sort=qf.sort(qf.ASCENDING('y')))
        self.assertEqual(doc, {'x': 10, 'y': 10})

        doc = yield self.coll.find_one_and_update({}, {"$set": {'y': 35}},
                                                  projection={"_id": 0},
                                                  sort=qf.sort(qf.DESCENDING('y')))
        self.assertEqual(doc, {'x': 30, 'y': 30})

        ys = yield self.coll.distinct('y')
        self.assertEqual(set(ys), {5, 20, 35})

    def test_InvalidUpdate(self):
        self.assertRaises(ValueError, self.coll.find_one_and_update, {}, {'x': 123})

    @defer.inlineCallbacks
    def test_Upsert(self):
        doc = yield self.coll.find_one_and_update({'x': 40}, {"$set": {'y': 40}},
                                                  upsert=True)
        self.assertEqual(doc, None)

        inserted = yield self.coll.find_one({'x': 40})
        self.assertEqual(inserted['y'], 40)

    @defer.inlineCallbacks
    def test_ReturnDocument(self):
        doc = yield self.coll.find_one_and_update({'x': 10}, {"$set": {'y': 5}},
                                                  return_document=ReturnDocument.BEFORE)
        self.assertEqual(doc['y'], 10)

        doc = yield self.coll.find_one_and_update({'x': 10}, {"$set": {'y': 15}},
                                                  return_document=ReturnDocument.AFTER)
        self.assertEqual(doc['y'], 15)

class TestCount(SingleCollectionTest):

    @defer.inlineCallbacks
    def setUp(self):
        yield super(TestCount, self).setUp()
        yield self.coll.insert_many([{'x': 10}, {'x': 20}, {'x': 30}])

    @defer.inlineCallbacks
    def tearDown(self):
        yield self.db.system.profile.drop()
        yield super(TestCount, self).tearDown()

    @defer.inlineCallbacks
    def test_count(self):
        self.assertEqual((yield self.coll.count()), 3)
        self.assertEqual((yield self.coll.count({'x': 20})), 1)
        self.assertEqual((yield self.coll.count({'x': {"$gt": 15}})), 2)

        self.assertEqual((yield self.db.non_existing.count()), 0)

    @defer.inlineCallbacks
    def test_hint(self):
        yield self.coll.create_index(qf.sort(qf.ASCENDING('x')))

        yield self.db.command("profile", 2)
        cnt = yield self.coll.count(hint=qf.hint(qf.ASCENDING('x')))
        self.assertEqual(cnt, 3)
        yield self.db.command("profile", 0)

        cmds = yield self.db.system.profile.count({"command.hint": {"x": 1}})
        self.assertEqual(cmds, 1)

        self.assertRaises(TypeError, self.coll.count, hint={'x': 1})
        self.assertRaises(TypeError, self.coll.count, hint=[('x', 1)])

    @defer.inlineCallbacks
    def test_skip_limit(self):
        cnt = yield self.coll.count(limit = 2)
        self.assertEqual(cnt, 2)

        cnt = yield self.coll.count(skip = 1)
        self.assertEqual(cnt, 2)


text:
@font-face {
  font-family: 'Source Sans Pro';
  src: url("../../fonts/SourceSansPro-Regular.otf");
  font-weight: normal;
  font-style: normal; }

@font-face {
  font-family: 'Source Sans Pro';
  src: url("../../fonts/SourceSansPro-Italic.otf");
  font-weight: normal;
  font-style: italic; }

@font-face {
  font-family: 'Source Sans Pro';
  src: url("../../fonts/SourceSansPro-Bold.otf");
  font-weight: bold;
  font-style: normal; }

@font-face {
  font-family: 'Source Sans Pro';
  src: url("../../fonts/SourceSansPro-Light.otf");
  font-weight: 100;
  font-style: normal; }


text:
template <typename T>
struct A {
    A<T> (int) {}
    A<T> (float);
    A<T> (int*);
};

// external definition without A<T>
template <class T>
A<T>::A(float) {}

// external definition *with* A<T>
//
// this one is tricky b/c of scope delegation nonsense
template <class T>
A<T>::A<T>(int*) {}


text:
package com.mgaetan89.showsrage.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;

import com.mgaetan89.showsrage.Constants;
import com.mgaetan89.showsrage.R;
import com.mgaetan89.showsrage.adapter.ShowsAdapter;
import com.mgaetan89.showsrage.fragment.ShowsFragment;
import com.mgaetan89.showsrage.model.RootDir;
import com.mgaetan89.showsrage.model.RootDirs;
import com.mgaetan89.showsrage.model.Show;
import com.mgaetan89.showsrage.network.SickRageApi;

import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class ShowsActivity extends BaseActivity implements ShowsAdapter.OnShowSelectedListener {
	@Override
	public void onShowSelected(@NonNull Show show) {
		Intent intent = new Intent(this, ShowActivity.class);
		intent.putExtra(Constants.Bundle.SHOW_MODEL, show);

		this.startActivity(intent);
	}

	@Override
	protected boolean displayHomeAsUp() {
		return false;
	}

	@Override
	protected Fragment getFragment() {
		return new ShowsFragment();
	}

	@Override
	protected int getSelectedMenuId() {
		return R.id.menu_shows;
	}

	@Override
	protected int getTitleResourceId() {
		return R.string.shows;
	}

	@Override
	protected void onResume() {
		super.onResume();

		SickRageApi.getInstance().getServices().getRootDirs(new RootDirsCallback(this));
	}

	private static final class RootDirsCallback implements Callback<RootDirs> {
		@NonNull
		private WeakReference<Activity> activityReference = new WeakReference<>(null);

		private RootDirsCallback(Activity activity) {
			this.activityReference = new WeakReference<>(activity);
		}

		@Override
		public void failure(RetrofitError error) {
			error.printStackTrace();
		}

		@Override
		public void success(RootDirs rootDirs, Response response) {
			if (rootDirs == null) {
				return;
			}

			List<RootDir> data = rootDirs.getData();
			Set<String> rootPaths = new HashSet<>(data.size());

			for (RootDir rootDir : data) {
				rootPaths.add(rootDir.getLocation());
			}

			SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this.activityReference.get()).edit();
			editor.putStringSet(Constants.Preferences.Fields.ROOT_DIRS, rootPaths);
			editor.apply();
		}
	}
}


text:
#ifndef ERR_H
#define ERR_H

#include <exception>

// Append _FMT if the error is formatted

const int ERR_OUT_OF_MEMORY =		0;
const int ERR_INTERNAL =		1;
const int ERR_FILE_ERROR =		2;
const int ERR_NOT_FOUND =		3;
const int ERR_DUPLICATE =		4;
const int ERR_RANGE =			5;
const int ERR_WINDOWS_FMT = 		6;  // %s func name, %d extended error code
const int ERR_USER_CANCEL =		7;
const int ERR_EXTENSION_FMT =		8;  // error in a component

const char *getErrMsg (int errCode);

#define WHERE	__FILE__, __LINE__

class AppException : public std::exception {
    int errCode;
    const char *errMsg;

    static int debug;
    static char buffer[];
    static int freezeCount;
public:
    AppException(const char* file, int line, int errCode, ...);
    AppException(const char* file, int line, const char* msg, ...);
    virtual ~AppException();

    virtual const char* what() const;
    int code() const { return errCode; }

    static int Freeze();
    static int Thaw();

    static void setDebug(int b);

    class AutoFreezer {
    public:
        AutoFreezer () { AppException::Freeze (); }
        ~AutoFreezer () { AppException::Thaw (); }
    };
};

#endif


text:
N = 1024;
x = randn(1,N);

Nf = 128;
h = fir1(Nf,0.1);

h_real = ifftshift(h);

figure(1)
plot(h,'b');
hold on;
plot(h_real,'r');
title('Original (blue) and FFTSHIFT versions (red)');

y = filter(h,1,x);
y_real = filter(h_real,1,x);

figure(2)
subplot(211);
plot(abs(fft(y)));
title('FFT magnitude of white noise filtered with original');
subplot(212);
plot(abs(fft(y_real)));
title('FFT magnitude of white noise filtered with FFTSHIFT');

figure(3)
subplot(211);
plot(abs(fft(h,N)));
title('FFT of original zero padded to 1024 samples');
subplot(212);
plot(abs(fft(h_real,N)));
title('FFT of FFTSHIFT zero padded to 1024 samples');


text:
{% extends 'base.html' %}

{% block content %}

You have successfully registered!

Please allow 1-2 business days for Admin to verify your account before you can use the site!

 Return to the Login Page

{% endblock %}

{% block javascript %}

{% endblock %}


text:
/*!
{
  "name": "CSS Media Queries",
  "caniuse": "css-mediaqueries",
  "property": "mediaqueries",
  "tags": ["css"],
  "builderAliases": ["css_mediaqueries"]
}
!*/
define(['Modernizr', 'mq'], function( Modernizr, mq ) {
  Modernizr.addTest('mediaqueries', mq('only all'));
});


text:
layout: default
modal-id: 23
date: 2016-06-27
img: ties.jpg
alt: Percha para corbatas
price: 70
description: Una práctica percha para tener tus corbatas organizadas.

---


text:
// This package is generated by client-gen with arguments: --clientset-name=release_1_4 --input=[api/v1,extensions/v1beta1,autoscaling/v1,batch/v1]

// This package has the automatically generated fake clientset.
package fake


text:
#ifndef QMLPLUGIN_H
#define QMLPLUGIN_H

#include <QtCore/QDebug>
#include <QtCore/QObject>
#include <QtCore/QStringList>
#include <silkmimehandlerinterface.h>
#include "qmlhandler.h"

class QmlPlugin : public QObject, SilkMimeHandlerInterface
{
    Q_OBJECT
    Q_PLUGIN_METADATA(IID "me.qtquick.silk.plugins.mime")
    Q_INTERFACES(SilkMimeHandlerInterface)
public:
    virtual QStringList keys() const {
        return QStringList() << "text/x-qml";
    }

    virtual SilkAbstractMimeHandler *handler(QObject *parent) {
        return new QmlHandler(parent);
    }
};

#endif // QMLPLUGIN_H


text:
<?php

namespace MicrosoftAzure\Storage\Common\Internal;

/**
 * Holder for default connection string sources used in CloudConfigurationManager.
 *
 * @ignore
 * @category  Microsoft
 * @package   MicrosoftAzure\Storage\Common\Internal
 * @author    Azure Storage PHP SDK <dmsh@microsoft.com>
 * @copyright 2016 Microsoft Corporation
 * @license   https://github.com/azure/azure-storage-php/LICENSE
 * @link      https://github.com/azure/azure-storage-php
 */
class ConnectionStringSource
{
    private static $_defaultSources;
    private static $_isInitialized;
    const ENVIRONMENT_SOURCE = 'environment_source';

    /**
     * Initializes the default sources.
     *
     * @return void
     */
    private static function _init()
    {
        if (!self::$_isInitialized) {
            self::$_defaultSources = array(
                self::ENVIRONMENT_SOURCE => array(__CLASS__, 'environmentSource')
            );
            self::$_isInitialized  = true;
        }
    }

    /**
     * Gets a connection string value from the system environment.
     *
     * @param string $key The connection string name.
     *
     * @return string
     */
    public static function environmentSource($key)
    {
        Validate::canCastAsString($key, 'key');

        return getenv($key);
    }

    /**
     * Gets list of default sources.
     *
     * @return array
     */
    public static function getDefaultSources()
    {
        self::_init();
        return self::$_defaultSources;
    }
}


text:
<title>Current Ramp</title>
<link rel="SHORTCUT ICON" href="favicon.ico">

<applet code=Circuit.class archive=circuit.jar width=640 height=450>
Sorry, you need a Java-enabled browser to see the simulation.
<param name=pause value=20>
<param name=startCircuit value="moscurrentramp.txt">
<param name=startLabel   value="Current Ramp">
<param name=useFrame     value="false">
</applet>

This circuit uses a current source to
generate a voltage ramp whenever the switch is closed.

Next: Current Mirror

Previous: Current Source

Index

java@falstad.com

Generated Thu May 30 2013


text:
#include "core/layout/LayoutTableRow.h"

#include "core/HTMLNames.h"
#include "core/fetch/ImageResource.h"
#include "core/layout/HitTestResult.h"
#include "core/layout/LayoutAnalyzer.h"
#include "core/layout/LayoutState.h"
#include "core/layout/LayoutTableCell.h"
#include "core/layout/LayoutView.h"
#include "core/layout/SubtreeLayoutScope.h"
#include "core/paint/TableRowPainter.h"
#include "core/style/StyleInheritedData.h"

namespace blink {

using namespace HTMLNames;

LayoutTableRow::LayoutTableRow(Element* element)
    : LayoutTableBoxComponent(element), m_rowIndex(unsetRowIndex) {
  // init LayoutObject attributes
  setInline(false);  // our object is not Inline
}

void LayoutTableRow::willBeRemovedFromTree() {
  LayoutTableBoxComponent::willBeRemovedFromTree();

  section()->setNeedsCellRecalc();
}

void LayoutTableRow::styleDidChange(StyleDifference diff,
                                    const ComputedStyle* oldStyle) {
  DCHECK_EQ(style()->display(), EDisplay::TableRow);

  LayoutTableBoxComponent::styleDidChange(diff, oldStyle);
  propagateStyleToAnonymousChildren();

  if (!oldStyle)
    return;

  if (section() && style()->logicalHeight() != oldStyle->logicalHeight())
    section()->rowLogicalHeightChanged(this);

  if (!parent())
    return;
  LayoutTable* table = this->table();
  if (!table)
    return;

  if (!table->selfNeedsLayout() && !table->normalChildNeedsLayout() &&
      oldStyle->border() != style()->border())
    table->invalidateCollapsedBorders();

  if (LayoutTableBoxComponent::doCellsHaveDirtyWidth(*this, *table, diff,
                                                     *oldStyle)) {
    // If the border width changes on a row, we need to make sure the cells in
    // the row know to lay out again.
    // This only happens when borders are collapsed, since they end up affecting
    // the border sides of the cell itself.
    for (LayoutBox* childBox = firstChildBox(); childBox;
         childBox = childBox->nextSiblingBox()) {
      if (!childBox->isTableCell())
        continue;
      // TODO(dgrogan) Add a layout test showing that setChildNeedsLayout is
      // needed instead of setNeedsLayout.
      childBox->setChildNeedsLayout();
      childBox->setPreferredLogicalWidthsDirty(MarkOnlyThis);
    }
    // Most table componenents can rely on LayoutObject::styleDidChange
    // to mark the container chain dirty. But LayoutTableSection seems
    // to never clear its dirty bit, which stops the propagation. So
    // anything under LayoutTableSection has to restart the propagation
    // at the table.
    // TODO(dgrogan): Make LayoutTableSection clear its dirty bit.
    table->setPreferredLogicalWidthsDirty();
  }
}

const BorderValue& LayoutTableRow::borderAdjoiningStartCell(
    const LayoutTableCell* cell) const {
#if DCHECK_IS_ON()
  DCHECK(cell->isFirstOrLastCellInRow());
#endif
  // FIXME: https://webkit.org/b/79272 - Add support for mixed directionality at
  // the cell level.
  return style()->borderStart();
}

const BorderValue& LayoutTableRow::borderAdjoiningEndCell(
    const LayoutTableCell* cell) const {
#if DCHECK_IS_ON()
  DCHECK(cell->isFirstOrLastCellInRow());
#endif
  // FIXME: https://webkit.org/b/79272 - Add support for mixed directionality at
  // the cell level.
  return style()->borderEnd();
}

void LayoutTableRow::addChild(LayoutObject* child, LayoutObject* beforeChild) {
  if (!child->isTableCell()) {
    LayoutObject* last = beforeChild;
    if (!last)
      last = lastCell();
    if (last && last->isAnonymous() && last->isTableCell() &&
        !last->isBeforeOrAfterContent()) {
      LayoutTableCell* lastCell = toLayoutTableCell(last);
      if (beforeChild == lastCell)
        beforeChild = lastCell->firstChild();
      lastCell->addChild(child, beforeChild);
      return;
    }

    if (beforeChild && !beforeChild->isAnonymous() &&
        beforeChild->parent() == this) {
      LayoutObject* cell = beforeChild->previousSibling();
      if (cell && cell->isTableCell() && cell->isAnonymous()) {
        cell->addChild(child);
        return;
      }
    }

    // If beforeChild is inside an anonymous cell, insert into the cell.
    if (last && !last->isTableCell() && last->parent() &&
        last->parent()->isAnonymous() &&
        !last->parent()->isBeforeOrAfterContent()) {
      last->parent()->addChild(child, beforeChild);
      return;
    }

    LayoutTableCell* cell = LayoutTableCell::createAnonymousWithParent(this);
    addChild(cell, beforeChild);
    cell->addChild(child);
    return;
  }

  if (beforeChild && beforeChild->parent() != this)
    beforeChild = splitAnonymousBoxesAroundChild(beforeChild);

  LayoutTableCell* cell = toLayoutTableCell(child);

  ASSERT(!beforeChild || beforeChild->isTableCell());
  LayoutTableBoxComponent::addChild(cell, beforeChild);

  // Generated content can result in us having a null section so make sure to
  // null check our parent.
  if (parent()) {
    section()->addCell(cell, this);
    // When borders collapse, adding a cell can affect the the width of
    // neighboring cells.
    LayoutTable* enclosingTable = table();
    if (enclosingTable && enclosingTable->collapseBorders()) {
      if (LayoutTableCell* previousCell = cell->previousCell())
        previousCell->setNeedsLayoutAndPrefWidthsRecalc(
            LayoutInvalidationReason::TableChanged);
      if (LayoutTableCell* nextCell = cell->nextCell())
        nextCell->setNeedsLayoutAndPrefWidthsRecalc(
            LayoutInvalidationReason::TableChanged);
    }
  }

  if (beforeChild || nextRow())
    section()->setNeedsCellRecalc();
}

void LayoutTableRow::layout() {
  ASSERT(needsLayout());
  LayoutAnalyzer::Scope analyzer(*this);
  bool paginated = view()->layoutState()->isPaginated();

  for (LayoutTableCell* cell = firstCell(); cell; cell = cell->nextCell()) {
    SubtreeLayoutScope layouter(*cell);
    cell->setLogicalTop(logicalTop());
    if (!cell->needsLayout())
      section()->markChildForPaginationRelayoutIfNeeded(*cell, layouter);
    if (cell->needsLayout())
      cell->layout();
    if (paginated)
      section()->updateFragmentationInfoForChild(*cell);
  }

  m_overflow.reset();
  addVisualEffectOverflow();
  // We do not call addOverflowFromCell here. The cell are laid out to be
  // measured above and will be sized correctly in a follow-up phase.

  // We only ever need to issue paint invalidations if our cells didn't, which
  // means that they didn't need layout, so we know that our bounds didn't
  // change. This code is just making up for the fact that we did not invalidate
  // paints in setStyle() because we had a layout hint.
  if (selfNeedsLayout()) {
    for (LayoutTableCell* cell = firstCell(); cell; cell = cell->nextCell()) {
      // FIXME: Is this needed when issuing paint invalidations after layout?
      cell->setShouldDoFullPaintInvalidation();
    }
  }

  // LayoutTableSection::layoutRows will set our logical height and width later,
  // so it calls updateLayerTransform().
  clearNeedsLayout();
}

// Hit Testing
bool LayoutTableRow::nodeAtPoint(HitTestResult& result,
                                 const HitTestLocation& locationInContainer,
                                 const LayoutPoint& accumulatedOffset,
                                 HitTestAction action) {
  // Table rows cannot ever be hit tested.  Effectively they do not exist.
  // Just forward to our children always.
  for (LayoutTableCell* cell = lastCell(); cell; cell = cell->previousCell()) {
    // FIXME: We have to skip over inline flows, since they can show up inside
    // table rows at the moment (a demoted inline <form> for example). If we
    // ever implement a table-specific hit-test method (which we should do for
    // performance reasons anyway), then we can remove this check.
    if (!cell->hasSelfPaintingLayer()) {
      LayoutPoint cellPoint =
          flipForWritingModeForChild(cell, accumulatedOffset);
      if (cell->nodeAtPoint(result, locationInContainer, cellPoint, action)) {
        updateHitTestResult(
            result, locationInContainer.point() - toLayoutSize(cellPoint));
        return true;
      }
    }
  }

  return false;
}

LayoutBox::PaginationBreakability LayoutTableRow::getPaginationBreakability()
    const {
  PaginationBreakability breakability =
      LayoutTableBoxComponent::getPaginationBreakability();
  if (breakability == AllowAnyBreaks) {
    // Even if the row allows us to break inside, we will want to prevent that
    // if we have a header group that wants to appear at the top of each page.
    if (const LayoutTableSection* header = table()->header())
      breakability = header->getPaginationBreakability();
  }
  return breakability;
}

void LayoutTableRow::paint(const PaintInfo& paintInfo,
                           const LayoutPoint& paintOffset) const {
  TableRowPainter(*this).paint(paintInfo, paintOffset);
}

LayoutTableRow* LayoutTableRow::createAnonymous(Document* document) {
  LayoutTableRow* layoutObject = new LayoutTableRow(nullptr);
  layoutObject->setDocumentForAnonymous(document);
  return layoutObject;
}

LayoutTableRow* LayoutTableRow::createAnonymousWithParent(
    const LayoutObject* parent) {
  LayoutTableRow* newRow = LayoutTableRow::createAnonymous(&parent->document());
  RefPtr<ComputedStyle> newStyle =
      ComputedStyle::createAnonymousStyleWithDisplay(parent->styleRef(),
                                                     EDisplay::TableRow);
  newRow->setStyle(newStyle.release());
  return newRow;
}

void LayoutTableRow::computeOverflow() {
  clearAllOverflows();
  addVisualEffectOverflow();
  for (LayoutTableCell* cell = firstCell(); cell; cell = cell->nextCell())
    addOverflowFromCell(cell);
}

void LayoutTableRow::addOverflowFromCell(const LayoutTableCell* cell) {
  // Non-row-spanning-cells don't create overflow (they are fully contained
  // within this row).
  // TODO(crbug.com/603993): This seems incorrect because cell may have visual
  // effect overflow that should be included in this row.
  if (cell->rowSpan() == 1)
    return;

  // Cells only generates visual overflow.
  LayoutRect cellVisualOverflowRect =
      cell->visualOverflowRectForPropagation(styleRef());

  // The cell and the row share the section's coordinate system. However
  // the visual overflow should be determined in the coordinate system of
  // the row, that's why we shift it below.
  LayoutUnit cellOffsetLogicalTopDifference =
      cell->location().y() - location().y();
  cellVisualOverflowRect.move(LayoutUnit(), cellOffsetLogicalTopDifference);

  addContentsVisualOverflow(cellVisualOverflowRect);
}

}  // namespace blink


text:
<?php
/**
 * ALIPAY API: alipay.trust.user.status.get request
 *
 * @author auto create
 * @since 1.0, 2015-02-06 13:11:14
 */
class AlipayTrustUserStatusGetRequest
{
	/**
	 * 入参json串
	 **/
	private $aliTrustUserInfo;

	private $apiParas = array();
	private $terminalType;
	private $terminalInfo;
	private $prodCode;
	private $apiVersion="1.0";

	public function setAliTrustUserInfo($aliTrustUserInfo)
	{
		$this->aliTrustUserInfo = $aliTrustUserInfo;
		$this->apiParas["ali_trust_user_info"] = $aliTrustUserInfo;
	}

	public function getAliTrustUserInfo()
	{
		return $this->aliTrustUserInfo;
	}

	public function getApiMethodName()
	{
		return "alipay.trust.user.status.get";
	}

	public function getApiParas()
	{
		return $this->apiParas;
	}

	public function getTerminalType()
	{
		return $this->terminalType;
	}

	public function setTerminalType($terminalType)
	{
		$this->terminalType = $terminalType;
	}

	public function getTerminalInfo()
	{
		return $this->terminalInfo;
	}

	public function setTerminalInfo($terminalInfo)
	{
		$this->terminalInfo = $terminalInfo;
	}

	public function getProdCode()
	{
		return $this->prodCode;
	}

	public function setProdCode($prodCode)
	{
		$this->prodCode = $prodCode;
	}

	public function setApiVersion($apiVersion)
	{
		$this->apiVersion=$apiVersion;
	}

	public function getApiVersion()
	{
		return $this->apiVersion;
	}

}


text:
using System.Collections.Generic;

namespace CodeMash.Interfaces.Client
{
    public interface ICodeMashRequest
    {
        Dictionary<string, string> Headers { get; set; }

        string Method { get; set; }

        string RequestUri { get; set; }

        string Host { get; set; }
    }
}


text:
<?php

namespace DCarbone\PHPFHIRGenerated\DSTU2\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRDataElement;

use PHPUnit\Framework\TestCase;
use DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRDataElement\FHIRDataElementContact;

/**
 * Class FHIRDataElementContactTest
 * @package \DCarbone\PHPFHIRGenerated\DSTU2\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRDataElement
 */
class FHIRDataElementContactTest extends TestCase
{
    public function testCanConstructTypeNoArgs()
    {
        $type = new FHIRDataElementContact();
        $this->assertInstanceOf('\DCarbone\PHPFHIRGenerated\DSTU2\FHIRElement\FHIRBackboneElement\FHIRDataElement\FHIRDataElementContact', $type);
    }
}


text:
.class Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog$9;
.super Ljava/lang/Object;
.source "EditStyledText.java"

# interfaces
.implements Landroid/content/DialogInterface$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;->onShowSizeAlertDialog()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;

# direct methods
.method constructor <init>(Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;)V
    .locals 0

    .prologue
    .line 2282
    iput-object p1, p0, Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog$9;->this$0:Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onClick(Landroid/content/DialogInterface;I)V
    .locals 4
    .param p1, "dialog"    # Landroid/content/DialogInterface;
    .param p2, "which"    # I

    .prologue
    .line 2284
    const-string v1, "EditStyledText"

    new-instance v2, Ljava/lang/StringBuilder;

    invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

    const-string v3, "mBuilder.onclick:"

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2, p2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    invoke-static {v1, v2}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 2285
    iget-object v1, p0, Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog$9;->this$0:Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;

    # getter for: Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;->mEST:Lcom/android/ex/editstyledtext/EditStyledText;
    invoke-static {v1}, Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;->access$1300(Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;)Lcom/android/ex/editstyledtext/EditStyledText;

    move-result-object v2

    iget-object v1, p0, Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog$9;->this$0:Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;

    # getter for: Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;->mSizeDisplayInts:[Ljava/lang/CharSequence;
    invoke-static {v1}, Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;->access$1600(Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;)[Ljava/lang/CharSequence;

    move-result-object v1

    aget-object v1, v1, p2

    check-cast v1, Ljava/lang/String;

    invoke-static {v1}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;)I

    move-result v1

    # invokes: Lcom/android/ex/editstyledtext/EditStyledText;->dipToPx(I)I
    invoke-static {v2, v1}, Lcom/android/ex/editstyledtext/EditStyledText;->access$1400(Lcom/android/ex/editstyledtext/EditStyledText;I)I

    move-result v0

    .line 2287
    .local v0, "size":I
    iget-object v1, p0, Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog$9;->this$0:Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;

    # getter for: Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;->mEST:Lcom/android/ex/editstyledtext/EditStyledText;
    invoke-static {v1}, Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;->access$1300(Lcom/android/ex/editstyledtext/EditStyledText$StyledTextDialog;)Lcom/android/ex/editstyledtext/EditStyledText;

    move-result-object v1

    invoke-virtual {v1, v0}, Lcom/android/ex/editstyledtext/EditStyledText;->setItemSize(I)V

    .line 2288
    return-void
.end method


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:weightSum="1">

    <ImageView
        android:paddingTop="24dp"
        android:id="@+id/Profile"
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        app:srcCompat="@drawable/logo"
        android:layout_weight="0.99" />

</LinearLayout>


text:
'use strict'
const arrayify = require('array-back')
const Cell = require('./cell')
const t = require('typical')

/**
 *
 */
class Rows {
  constructor (rows, columns) {
    this.list = []
    this.load(rows, columns)
  }

  load (rows, columns) {
    arrayify(rows).forEach(row => {
      this.list.push(new Map(objectToIterable(row, columns)))
    })
  }

  static removeEmptyColumns (data) {
    const distinctColumnNames = data.reduce((columnNames, row) => {
      Object.keys(row).forEach(key => {
        if (columnNames.indexOf(key) === -1) columnNames.push(key)
      })
      return columnNames
    }, [])

    const emptyColumns = distinctColumnNames.filter(columnName => {
      const hasValue = data.some(row => {
        const value = row[columnName]
        return (t.isDefined(value) && !t.isString(value)) || (t.isString(value) && /\S+/.test(value))
      })
      return !hasValue
    })

    return data.map(row => {
      emptyColumns.forEach(emptyCol => delete row[emptyCol])
      return row
    })
  }
}

function objectToIterable (row, columns) {
  return columns.list.map(column => {
    return [ column, new Cell(row[column.name], column) ]
  })
}

/**
 * @module rows
 */
module.exports = Rows


text:
import THREE from 'three';

export default class Label {

    // context.font="italic small-caps bold 12px arial";
    constructor(scene, text, x, y, z, font, color, backGroundColor, backgroundMargin) {

        if (typeof(backgroundMargin) === 'undefined')
            backgroundMargin = 8;

        var canvas = document.createElement("canvas");

        var context = canvas.getContext("2d");
        var fonts = font.split(' ');
        var size = parseInt(fonts[3].split('px')[0])
        var textAlign = 'left';

        // Autosize canvas
        context.font = fonts.join(' ');
        var textWidth = context.measureText(text).width;
        canvas.width = textWidth + backgroundMargin;
        canvas.height = size + backgroundMargin;

        // Autosize text
        context.font = fonts.join(' ');
        if (backGroundColor) {
            context.fillStyle = backGroundColor;
        }

        switch (textAlign) {
            case 'left':
                context.fillRect(0,
                canvas.height / 2 - size / 2 - backgroundMargin / 2,
                textWidth + backgroundMargin,
                size + backgroundMargin);
                break;
            case 'center':
                context.fillRect(canvas.width / 2 - textWidth / 2 - backgroundMargin / 2,
                canvas.height / 2 - size / 2 - backgroundMargin / 2,
                textWidth + backgroundMargin,
                size + backgroundMargin);
                break;
        }

        context.textAlign = textAlign;
        context.textBaseline = "middle";
        context.fillStyle = color;

        switch (textAlign) {
            case 'left':
                context.fillText(text, backgroundMargin / 2, canvas.height / 2);
                break;
            case 'center':
                context.fillText(text, canvas.width / 2, canvas.height / 2);
                break;
        }

        // context.strokeStyle = "black";
        // context.strokeRect(0, 0, canvas.width, canvas.height);
        var texture = new THREE.Texture(canvas);
        texture.needsUpdate = true;
        var material = new THREE.MeshBasicMaterial({
            map: texture
        });
        var mesh = new THREE.Mesh(new THREE.PlaneGeometry(canvas.width, canvas.height), material);
        // mesh.overdraw = true;
        //mesh.doubleSided = true;

        switch (textAlign) {
            case 'left':
                mesh.position.x = x + canvas.width/2;
                break;
            case 'center':
                mesh.position.x = x;// - canvas.width;
                break;
        }

        mesh.position.y = y;// - canvas.height;
        mesh.position.z = z;
        mesh.rotation.x = -Math.PI / 2;

        scene.add(mesh);
        return mesh;
    }
}


text:
package io.jchat.android.entity;

public class Event {

    /**
     * 传递到ConversationListFragment的创建单聊事件
     * mTargetId 单聊Id
     * mAppKey 可以得到创建单聊者的AppKey
     */
    public static class StringEvent{
        private String mTargetId;
        private String mAppKey;

        public StringEvent(String targetId, String appKey) {
            this.mTargetId = targetId;
            this.mAppKey = appKey;
        }

        public String getTargetId(){
            return mTargetId;
        }

        public String getAppKey() {
            return mAppKey;
        }
    }

    /**
     * 传递到ConversationListFragment的创建或删除群聊事件
     * mGroupId 群聊Id
     * mIsAddEvent 是否为创建群聊的标志
     */
    public static class LongEvent{
        private long mGroupId;
        private boolean mIsAddEvent;

        public LongEvent(boolean isAddEvent, long groupId){
            this.mIsAddEvent = isAddEvent;
            this.mGroupId = groupId;
        }

        public long getGroupId(){
            return mGroupId;
        }

        public boolean getFlag() {
            return mIsAddEvent;
        }
    }

    /**
     * 传递到ConversationListFragment的保存为草稿的事件
     * mDraft 草稿内容
     */
    public static class DraftEvent {
        private String mTargetId;
        private long mGroupId;
        private String mTargetAppKey;
        private String mDraft;

        public DraftEvent(String targetId, String appKey, String draft) {
            this.mTargetId = targetId;
            this.mTargetAppKey = appKey;
            this.mDraft = draft;
        }

        public DraftEvent(long groupId, String draft) {
            this.mGroupId = groupId;
            this.mDraft = draft;
        }

        public String getTargetId() {
            return mTargetId;
        }

        public long getGroupId() {
            return mGroupId;
        }

        public String getTargetAppKey() {
            return mTargetAppKey;
        }

        public String getDraft() {
            return mDraft;
        }
    }

}


text:
package com.gs.obevo.db.impl.platforms.memsql;

import java.io.File;

import com.gs.obevo.apps.reveng.AbstractRevengTest;
import com.gs.obevo.apps.reveng.AquaRevengArgs;
import com.gs.obevo.testutil.DirectoryAssert;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

public class MemSqlRevengTest extends AbstractRevengTest {
    @Test
    @Override
    public void testReverseEngineeringFromFile() throws Exception {
        AquaRevengArgs args = new AquaRevengArgs();
        args.setDbSchema("myschema01");
        args.setGenerateBaseline(false);
        args.setDbHost("myhost.me.com");
        args.setDbPort(1234);
        args.setDbServer("myserver");
        args.setUsername("myuser");
        args.setPassword("mypass");

        File outputDir = new File("./target/outputReveng");
        FileUtils.deleteDirectory(outputDir);
        args.setOutputPath(outputDir);

        args.setInputPath(new File("./src/test/resources/reveng/pgdump/input/input.sql"));

        new MemSqlDbPlatform().getDdlReveng().reveng(args);

        DirectoryAssert.assertDirectoriesEqual(new File("./src/test/resources/reveng/pgdump/expected"), new File(outputDir, "final"));

        // TODO add test for input-noschemaqualifier.sql for older postgres versions
    }
}