text:
using System;
using IBApi.Messages.Server;
using CodeContract = System.Diagnostics.Contracts.Contract;

namespace IBApi.MarketDepth
{
    internal class MarketDepthUpdatesDispatcher
    {
        public MarketDepthUpdatesDispatcher(IMarketDepthObserver observer)
        {
            CodeContract.Requires(observer != null);
            this.observer = observer;
        }

        public void OnMarketDepth(MarketDepthMessage message)
        {
            switch (message.Operation)
            {
                case MarketDepthOperation.Insert:
                case MarketDepthOperation.Update:
                    ProcessUpdate(message);
                    return;

                case MarketDepthOperation.Delete:
                    ProcessDelete(message);
                    return;
            }

            var errorMessage = string.Format("This kind of operation not supported: {0}", (int)message.Operation);
            throw new ArgumentOutOfRangeException("message", errorMessage);
        }

        private void ProcessUpdate(MarketDepthMessage message)
        {
            var update = new MarketDepthUpdate {Price = message.Price, Quantity = message.Size};
            if (message.BidSide)
            {
                observer.OnBidUpdate(message.Position, update);
                return;
            }

            observer.OnAskUpdate(message.Position, update);
        }

        private void ProcessDelete(MarketDepthMessage message)
        {
            if (message.BidSide)
            {
                observer.OnBidRemove(message.Position);
                return;
            }

            observer.OnAskRemove(message.Position);
        }

        private readonly IMarketDepthObserver observer;
    }
}


text:
#pragma once
#include "../../Visual/VisualComponent.hpp"
#include "Common.hpp"

namespace ln {

class MeshTilemapComponent
	: public VisualComponent
{
    LN_OBJECT;
public:
    MeshTilemapModel* model() const;
    void setModel(MeshTilemapModel* value);

LN_CONSTRUCT_ACCESS:
    MeshTilemapComponent();
	void init();

private:
    Ref<MeshTilemapModel> m_model;
};

} // namespace ln

redpajama_set_name: RedPajamaGithub


text:
* Introductory Slides: [![Intro Slides](https://gitpitch.com/assets/badge.svg)](https://gitpitch.com/bcbi/julia_tutorials/master?grs=github&t=white&p=plotting)
* PlotlyJS.jl Notebook Viewer
* Plots.jl Notebook Viewer
* Seaborn.jl Notebook Viewer
* (For instructors) To locally view the notebooks as slide you can install the notebook extension [RISE](https://github.com/damianavila/RISE)

### Files in this diresctory:

* PITCHME.md -- slides diplayed at gitpich.com
* PITCHME.yaml -- slides configuration
* plots_basics.ipynb - Jupyter notebook introducing Plots.jl
* plots_basics.jl - Julia script matching the corresponding notebook
* plotlyjs_basics.ipynb - Jupyter notebook introducing PlotlyJS.jl
* plotlyjs_basics.jl - Julia script matching the corresponding notebook
* seaborn_basics.ipynb - Jupyter notebook introducing Seaborn.jl
* seaborn_basics.jl - Julia script matching the corresponding notebook

### Dependencies:

```julia
# Packages to add - you may already have some of them
Pkg.add("PyPlot")
Pkg.add("Plots")
Pkg.add("StatPlots")
Pkg.add("PlotlyJS")
Pkg.add("Gadfly")
Pkg.add("Seaborn")
Pkg.add("Pandas")

# Test all used packages
using Plots
using StatPlots
using DataFrames, RDatasets
using PlotlyJS
using Gadfly

using Seaborn
using Pandas
using PyPlot
using PyCall
```


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>javax.print.event (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<meta name="keywords" content="javax.print.event package">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Package

Next Package

Frames

No Frames

All Classes

Package javax.print.event

Package javax.print.event contains event classes  and listener interfaces.

See: Description

Interface Summary

Interface
Description

PrintJobAttributeListener

Implementations of this interface are attached to a
 DocPrintJob to monitor
 the status of attribute changes associated with the print job.

PrintJobListener

Implementations of this listener interface should be attached to a
 DocPrintJob to monitor the status of
 the printer job.

PrintServiceAttributeListener

Implementations of this listener interface are attached to a
 PrintService to monitor
 the status of the print service.

Class Summary

Class
Description

PrintEvent

Class PrintEvent is the super class of all Print Service API events.

PrintJobAdapter

An abstract adapter class for receiving print job events.

PrintJobAttributeEvent

Class PrintJobAttributeEvent encapsulates an event a PrintService
 reports to let the client know that one or more printing attributes for a
 PrintJob have changed.

PrintJobEvent

Class PrintJobEvent encapsulates common events a print job
 reports to let a listener know of progress in the processing of the
 DocPrintJob.

PrintServiceAttributeEvent

Class PrintServiceAttributeEvent encapsulates an event a
 Print Service instance reports to let the client know of
 changes in the print service state.

Package javax.print.event Description

Package javax.print.event contains event classes  and listener interfaces.

They may be used to monitor both print services (such as printers going
on-line & off-line), and the progress of a specific print job.

Please note: In the javax.print APIs, a null reference parameter to methods
is incorrect unless explicitly documented on the method as having a meaningful
interpretation. Usage to the contrary is incorrect coding and may result
in a run time exception either immediately or at some later time.
IllegalArgumentException and NullPointerException are examples of
typical and acceptable run time exceptions for such cases.

Since:

1.4

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Package

Next Package

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
.dijitCalendar thead {
  background-repeat: repeat-x;
  background-image: url(compat/calendar-month-bg.png);
}
.dijitCalendarSelectedDate .dijitCalendarDateLabel {
  background-repeat: repeat-x;
  background-image: url(compat/calendar-datelabel-sel-bg.png);
}
.dijitCalendarActiveDate .dijitCalendarDateLabel {
  background-repeat: repeat-x;
  background-image: url(compat/calendar-datelabel-act-bg.png);
}
.dijitCalendarYearLabel {
  background-repeat: repeat-x;
  background-image: url(compat/calendar-year-bg.png);
}
.dj_gecko .dijitCalendar .dijitDropDownButton .dijitButtonNode {
  -moz-box-shadow: 0 0 0 transparent;
}
.dj_gecko .dijitCalendar thead {
  background-image: -moz-linear-gradient(top, #ffffff 0%, #e2e2e2 100%);
}
.dj_gecko .dijitCalendarSelectedDate .dijitCalendarDateLabel {
  background-image: -moz-linear-gradient(top, #e2e2e2 0%, #a4a4a4 100%);
}
.dj_gecko .dijitCalendarActiveDate .dijitCalendarDateLabel {
  background-image: -moz-linear-gradient(top, #bbbbbb 0%, #999999 100%);
}
.dj_gecko .dijitCalendarYearLabel {
  background-image: -moz-linear-gradient(top, #ffffff 0%, #e2e2e2 100%);
}
.dj_ff3 .dijitCalendar {
  -moz-border-radius: 0;
}


text:
[![Build Status](https://travis-ci.org/yargs/yargs-parser.png)](https://travis-ci.org/yargs/yargs-parser)
[![Coverage Status](https://coveralls.io/repos/yargs/yargs-parser/badge.svg?branch=)](https://coveralls.io/r/yargs/yargs-parser?branch=master)
[![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser)
[![Windows Tests](https://img.shields.io/appveyor/ci/bcoe/yargs-parser/master.svg?label=Windows%20Tests)](https://ci.appveyor.com/project/bcoe/yargs-parser)

The mighty option parser used by [yargs](https://github.com/bcoe/yargs).

visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions.

## Example

```sh
npm i yargs-parser --save
```

```js
var argv = require('yargs-parser')(process.argv.slice(2));
console.log(argv)
```

```sh
node example.js --foo=33 --bar hello
{ _: [], foo: 33, bar: 'hello' }
```

_or parse a string!_

```js
var argv = require('./')('--foo=99 --bar=33');
console.log(argv)
```

```sh
{ _: [], foo: 99, bar: 33 }
```

## API

### require('yargs-parser')(args, opts={})

Parses command line arguments returning a simple mapping of keys and values.

**expects:**

* `args`: an array or string representing the options to parse.
* `opts`: provide a set of hints indicating how `args` should be parsed:
  * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`.
  * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.
  * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`.
  * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed).
  * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`.
  * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`.
  * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed.
  * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`.
  * `opts.normalize`: `path.normalize()` will be applied to values set to this key.
  * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`).
  * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)).
  * `opts.number`: keys should be treated as numbers.

**returns:**

* `obj`: an object representing the parsed value of `args`
  * `key/value`: key value pairs for each argument and their aliases.
  * `_`: an array representing the positional arguments.

### require('yargs-parser').detailed(args, opts={})

Parses a command line string, returning detailed information required by the
yargs engine.

**expects:**

* `args`: an array or string representing options to parse.
* `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`.

**returns:**

* `argv`: an object representing the parsed value of `args`
  * `key/value`: key value pairs for each argument and their aliases.
  * `_`: an array representing the positional arguments.
* `error`: populated with an error object if an exception occurred during parsing.
* `aliases`: the inferred list of aliases built by combining lists in `opts.alias`.
* `newAliases`: any new aliases added via camel-case expansion.
* `configuration`: the configuration loaded from the `yargs` stanza in package.json.

### Configuration

The yargs-parser applies several automated transformations on the keys provided
in `args`. These features can be turned on and off using the `configuration` field
of `opts`.

```js
var parsed = parser(['--no-dice'], {
  configuration: {
    'boolean-negation': false
  }
})
```

### short option groups

* default: `true`.
* key: `short-option-groups`.

Should a group of short-options be treated as boolean flags?

```sh
node example.js -abc
{ _: [], a: true, b: true, c: true }
```

_if disabled:_

```sh
node example.js -abc
{ _: [], abc: true }
```

### camel-case expansion

* default: `true`.
* key: `camel-case-expansion`.

Should hyphenated arguments be expanded into camel-case aliases?

```sh
node example.js --foo-bar
{ _: [], 'foo-bar': true, fooBar: true }
```

_if disabled:_

```sh
node example.js --foo-bar
{ _: [], 'foo-bar': true }
```

### dot-notation

* default: `true`
* key: `dot-notation`

Should keys that contain `.` be treated as objects?

```sh
node example.js --foo.bar
{ _: [], foo: { bar: true } }
```

_if disabled:_

```sh
node example.js --foo.bar
{ _: [], "foo.bar": true }
```

### parse numbers

* default: `true`
* key: 'parse-numbers'

Should keys that look like numbers be treated as such?

```sh
node example.js --foo=99.3
{ _: [], foo: 99.3 }
```

_if disabled:_

```sh
node example.js --foo=99.3
{ _: [], foo: "99.3" }
```

### boolean negation

* default: `true`
* key: 'boolean-negation'

Should variables prefixed with `--no` be treated as negations?

```sh
node example.js --no-foo
{ _: [], foo: false }
```

_if disabled:_

```sh
node example.js --no-foo
{ _: [], "no-foo": true }
```

## Special Thanks

The yargs project evolves from optimist and minimist. It owes its
existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/

## License

ISC


text:
layout: page
title: Tracker Chief Tech Seminar
date: 2016-05-24
author: Harold Chan
tags: weekly links, java
status: published
summary: Integer tempor ornare faucibus. Ut cursus.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 04/17/2018
  endDate: 04/20/2018
  ctyhocn: CRVTNHX
  groupCode: TCTS
published: true
---
Nulla venenatis ullamcorper fringilla. Duis imperdiet blandit turpis, at dignissim arcu fermentum eu. Phasellus sodales lorem tincidunt ornare scelerisque. Donec vitae eleifend arcu, nec vehicula augue. Interdum et malesuada fames ac ante ipsum primis in faucibus. Etiam non rhoncus massa. In hac habitasse platea dictumst. Duis ac odio ex. Etiam condimentum efficitur malesuada. Nam sed urna faucibus, luctus sem faucibus, dictum nibh.
Nullam molestie tellus eros, vel commodo diam mollis sed. Pellentesque malesuada interdum accumsan. Praesent interdum est purus, at sollicitudin lacus euismod id. Proin tempor mauris ut rhoncus posuere. Nulla facilisi. Duis vel aliquam quam. Donec scelerisque eu velit at molestie. Fusce sodales in turpis sed iaculis.

1 Nullam pellentesque tortor sed enim aliquam, ut viverra elit gravida
1 Mauris dapibus lorem sit amet magna lobortis, vitae auctor elit efficitur
1 Sed ut risus eu nulla tristique vulputate finibus id ex
1 Nunc eu justo sodales purus mollis consectetur quis eget metus
1 Fusce vel tortor eget nunc mollis egestas vitae quis leo.

In congue ipsum ac finibus viverra. Etiam et nisi eget arcu condimentum accumsan. Sed congue, ipsum nec rhoncus pulvinar, nisi felis hendrerit velit, vulputate porttitor lectus lectus quis eros. Aenean dictum, diam at fermentum aliquam, sem tortor laoreet metus, ac porta velit ante eu dui. Nullam a tortor et nisl tincidunt hendrerit. Sed vulputate erat ut metus consectetur ornare. Aliquam vestibulum tempor elit sit amet porttitor. Maecenas quis nulla et augue sodales blandit. Suspendisse vehicula eros at elit porttitor, in mattis tellus pellentesque. Pellentesque sollicitudin arcu justo, at faucibus augue mattis sed. Curabitur rutrum mauris laoreet, tempor purus et, pharetra tellus.
Cras sollicitudin arcu ut nunc congue, et molestie nulla vestibulum. Nullam luctus lorem sit amet turpis placerat, et consequat arcu aliquam. Donec ac lacus vel sapien sagittis malesuada ut vel mi. In vel augue orci. Praesent tincidunt eleifend laoreet. Nulla viverra urna facilisis nisi vehicula ultrices. Pellentesque eu euismod nisi. Proin a sapien diam.


text:
module MARC
  # constants used in MARC21 reading/writing
  LEADER_LENGTH = 24
  DIRECTORY_ENTRY_LENGTH = 12
  SUBFIELD_INDICATOR = 0x1F.chr
  END_OF_FIELD = 0x1E.chr
  END_OF_RECORD = 0x1D.chr

  # constants used in XML reading/writing
  MARC_NS = "http://www.loc.gov/MARC21/slim"
  MARC_XSD = "http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"

  # marc-hash
  MARCHASH_MAJOR_VERSION = 1
  MARCHASH_MINOR_VERSION = 0
end


text:
'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Code = mongoose.model('Code'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  _ = require('lodash');

/**
 * Create a Code
 */
exports.create = function(req, res) {
  var code = new Code(req.body);
  code.user = req.user;

  code.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(code);
    }
  });
};

/**
 * Show the current Code
 */
exports.read = function(req, res) {
  // convert mongoose document to JSON
  var code = req.code ? req.code.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  code.isCurrentUserOwner = req.user && code.user && code.user._id.toString() === req.user._id.toString() ? true : false;

  res.jsonp(code);
};

/**
 * Update a Code
 */
exports.update = function(req, res) {
  var code = req.code ;

  code = _.extend(code , req.body);

  code.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(code);
    }
  });
};

/**
 * Delete an Code
 */
exports.delete = function(req, res) {
  var code = req.code ;

  code.remove(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(code);
    }
  });
};

/**
 * List of Codes
 */
exports.list = function(req, res) {
  Code.find().sort('-created').populate('user', 'displayName').exec(function(err, codes) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(codes);
    }
  });
};

/**
 * Code middleware
 */
exports.codeByID = function(req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Code is invalid'
    });
  }

  Code.findById(id).populate('user', 'displayName').exec(function (err, code) {
    if (err) {
      return next(err);
    } else if (!code) {
      return res.status(404).send({
        message: 'No Code with that identifier has been found'
      });
    }
    req.code = code;
    next();
  });
};


text:
package com.google.cloud.pubsublite;

import com.google.auto.value.AutoOneOf;
import java.io.Serializable;

@AutoOneOf(ProjectIdOrNumber.Kind.class)
public abstract class ProjectIdOrNumber implements Serializable {
  enum Kind {
    NAME,
    NUMBER
  }

  public abstract Kind getKind();

  public abstract ProjectId name();

  public abstract ProjectNumber number();

  public static ProjectIdOrNumber of(ProjectId name) {
    return AutoOneOf_ProjectIdOrNumber.name(name);
  }

  public static ProjectIdOrNumber of(ProjectNumber number) {
    return AutoOneOf_ProjectIdOrNumber.number(number);
  }

  @Override
  public String toString() {
    switch (getKind()) {
      case NAME:
        return name().toString();
      case NUMBER:
        return number().toString();
      default:
        throw new RuntimeException("Unknown case for ProjectIdOrNumber.");
    }
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>基于 Gtest 的单元测试入门及实践 (一)</title>
    <meta name="description" content="Sometimes Things Happen For A Reason - There are some things in this world will never change and some things do change,everything that has a beginning has an end " />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="/assets/images/favicon.ico" >

    <link rel="stylesheet" type="text/css" href="/assets/css/screen.css" />
    <link rel="stylesheet" type="text/css"
          href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />
    <link rel="stylesheet" type="text/css" href="/assets/css/syntax.css" />

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/default.min.css">

        <link rel="canonical" href="/" />
    <meta name="referrer" content="origin" />
    <link rel="next" href="/page2/" />

    <meta property="og:site_name" content="Sometimes Things Happen For A Reason" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Sometimes Things Happen For A Reason" />
    <meta property="og:description" content="There are some things in this world will never change and some things do change,everything that has a beginning has an end " />
    <meta property="og:url" content="/" />
    <meta property="og:image" content="/assets/images/cover2.jpg" />

    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="Sometimes Things Happen For A Reason" />
    <meta name="twitter:description" content="There are some things in this world will never change and some things do change,everything that has a beginning has an end " />
    <meta name="twitter:url" content="/" />
    <meta name="twitter:image:src" content="/assets/images/cover2.jpg" />

    <meta name="generator" content="Jekyll 3.0.0" />
    <link rel="alternate" type="application/rss+xml" title="Sometimes Things Happen For A Reason" href="/feed.xml" />

Menu

        Close

Home

OpenSource

Summerize

Docker&K8s

Monitor

Unittest

Pay

    Subscribe

            Menu

基于 Gtest 的单元测试入门及实践 (一)

            <time class="post-date" datetime="2016-08-11">11 Aug 2016</time>

                on

                       Unittest

前言:

其实这并不是关于Gtest学习入门的资料,我希望读者在读这篇文件之前还是要对Googletest的单元测试框架有所了解。为了让读者比较容易理解gtest的后续实践,本系列文章分成前后两个部分,前半部分主要以gtest 所自带的samples(samples in github)为例,讲述一下gtest的基本用法。后半部分主要在实际应用中的gtest的用法,以及一些测试感悟,希望不要让大家失望。

一、初级

例一
主要来讲述普通函数的单元测试,主要包含3个文件,分别为sample1.h, sample1.cc , sample1_unittest.cc

/*sample1.h*/
#ifndef GTEST_SAMPLES_SAMPLE1_H_
#define GTEST_SAMPLES_SAMPLE1_H_

// Returns n! (the factorial of n).  For negative n, n! is defined to be 1.
// 求N的阶乘
int Factorial(int n);

// Returns true iff n is a prime number.
// 判断一个数是否为质数
bool IsPrime(int n);

#endif  // GTEST_SAMPLES_SAMPLE1_H_

/*samples1.cc*/
#include "sample1.h"

// Returns n! (the factorial of n).  For negative n, n! is defined to be 1.
int Factorial(int n) {
  int result = 1;
  for (int i = 1; i <= n; i++) {
    result *= i;
  }

  return result;
}

// Returns true iff n is a prime number.
bool IsPrime(int n) {
  // Trivial case 1: small numbers
  if (n <= 1) return false;

  // Trivial case 2: even numbers
  if (n % 2 == 0) return n == 2;

  // Now, we have that n is odd and n >= 3.

  // Try to divide n by every odd number i, starting from 3
  for (int i = 3; ; i += 2) {
    // We only have to try i up to the squre root of n
    if (i > n/i) break;

    // Now, we have i <= n/i < n.
    // If n is divisible by i, n is not prime.
    if (n % i == 0) return false;
  }

  // n has no integer factor in the range (1, n), and thus is prime.
  return true;
}

/*sample1_unittest.cc*/
// This sample shows how to write a simple unit test for a function,
// using Google C++ testing framework.
// 这个例子展示了如何使用C++ 单元测试框架对函数进行单元测试
// Writing a unit test using Google C++ testing framework is easy as 1-2-3:
// 利用Google C++单元测试框架做单元测试只须简单的三步

// Step 1. Include necessary header files such that the stuff your
// test logic needs is declared.
//
// 第一步,包含必要的头部文件,确保测试逻辑所需要的头文件已被声明,并且不要忘记
// gtest.h。
// Don't forget gtest.h, which declares the testing framework.

#include <limits.h>
#include "sample1.h"
#include "gtest/gtest.h"

// Step 2. Use the TEST macro to define your tests.
//
// TEST has two parameters: the test case name and the test name.
// After using the macro, you should define your test logic between a
// pair of braces.  You can use a bunch of macros to indicate the
// success or failure of a test.  EXPECT_TRUE and EXPECT_EQ are
// examples of such macros.  For a complete list, see gtest.h.
//
//第二步,TEST宏有两个参数,分别为测试用例集名称和测试用例名称,在使用这个宏以后,
//你需要在{}内定义你的测试逻辑。你可以使用一系列的宏来表示测试的成功或着失败。例如
//EXPECT_TRUE表示期望值正确,EXPECT_EQ表示结果值大于或等于期望值。
//
//
//
// <TechnicalDetails>
//
// In Google Test, tests are grouped into test cases.  This is how we
// keep test code organized.  You should put logically related tests
// into the same test case.
//
// The test case name and the test name should both be valid C++
// identifiers.  And you should not use underscore (_) in the names.
//
// Google Test guarantees that each test you define is run exactly
// once, but it makes no guarantee on the order the tests are
// executed.  Therefore, you should write your tests in such a way
// that their results don't depend on their order.
//
//技术细节:
//    在Google Test中,测试用例被分成测试用例集,这保证了我们的代码有良好的组织性,所以
//你应该把逻辑相关的测试用例归集到同一测试用例集当中。
//
//测试用例集名称以及测试用例名称必须是C++合法的标识符,并且在名称中不允许使用下划线(_)
//Google Test测试框架,可以保证所有定义的测试都能够被正确执行,但是对测试执行的顺序比如先执行那些
//后执行那些并没有保证。所以你编写的测试代码,其测试结果不应该依赖于其执行顺序。
//
// </TechnicalDetails>

// Tests Factorial().

// Tests factorial of negative numbers.
// 测试负数的阶乘
TEST(FactorialTest, Negative) {
  // This test is named "Negative", and belongs to the "FactorialTest"
  // 测试用例集的名称是 FactorialTest, 测试用例名称 是 Negative
  // test case.
  EXPECT_EQ(1, Factorial(-5));
  EXPECT_EQ(1, Factorial(-1));
  EXPECT_GT(Factorial(-10), 0);

  // <TechnicalDetails>
  //
  // EXPECT_EQ(expected, actual) is the same as
  //
  //   EXPECT_TRUE((expected) == (actual))
  //
  // except that it will print both the expected value and the actual
  // value when the assertion fails.  This is very helpful for
  // debugging.  Therefore in this case EXPECT_EQ is preferred.
  //
  // On the other hand, EXPECT_TRUE accepts any Boolean expression,
  // and is thus more general.
  //
  //技术细节:
  //    EXPECT_EQ(expected,actual)与EXPECT_TRUE((expected)==(actual))是等同的,有一点
  //不同的是,当EXPECT_EQ(expected,actual)失败时会打印出期望的值与实际的值,这对调试非常有帮助,因此使用EXPECT_EQ更好一些。
  //
  //但是从另一方面说,由于EXPECT_TRUE可以接受任何类型的布尔表达式,所以应用更广一些
  //
  // </TechnicalDetails>
}

// Tests factorial of 0.
TEST(FactorialTest, Zero) {
  EXPECT_EQ(1, Factorial(0));
}

// Tests factorial of positive numbers.
TEST(FactorialTest, Positive) {
  EXPECT_EQ(1, Factorial(1));
  EXPECT_EQ(2, Factorial(2));
  EXPECT_EQ(6, Factorial(3));
  EXPECT_EQ(40320, Factorial(8));
}

// Tests IsPrime()

// Tests negative input.
TEST(IsPrimeTest, Negative) {
  // This test belongs to the IsPrimeTest test case.

  EXPECT_FALSE(IsPrime(-1));
  EXPECT_FALSE(IsPrime(-2));
  EXPECT_FALSE(IsPrime(INT_MIN));
}

// Tests some trivial cases.
TEST(IsPrimeTest, Trivial) {
  EXPECT_FALSE(IsPrime(0));
  EXPECT_FALSE(IsPrime(1));
  EXPECT_TRUE(IsPrime(2));
  EXPECT_TRUE(IsPrime(3));
}

// Tests positive input.
TEST(IsPrimeTest, Positive) {
  EXPECT_FALSE(IsPrime(4));
  EXPECT_TRUE(IsPrime(5));
  EXPECT_FALSE(IsPrime(6));
  EXPECT_TRUE(IsPrime(23));
}

// Step 3. Call RUN_ALL_TESTS() in main().
//
// We do this by linking in src/gtest_main.cc file, which consists of
// a main() function which calls RUN_ALL_TESTS() for us.
//
// This runs all the tests you've defined, prints the result, and
// returns 0 if successful, or 1 otherwise.
//
// Did you notice that we didn't register the tests?  The
// RUN_ALL_TESTS() macro magically knows about all the tests we
// defined.  Isn't this convenient?
//
// 第三步,我们在编译的时候会链接src/gtest_main.cc 文件,这个文件包含了
// main()函数,在main()函数里调用RUN_ALL_TESTS(), 而此函数会调用我们所定义
// 的所有TEST()函数,并打印运行结果,返回值为0表示成功,为1表示失败。
//
// 由于我们不许要注册这些测试,RUN_ALL_TESTS()就全部替我们做好,所以此框架
// 使用起来非常的方便。

例一中主要阐述了如何根据gtest来编写一个简单的单元测试。关于一些注意事项在技术细节中已经阐述清楚,这样看来单元测试不难吧^^。有一点需要多注意一些,在上文中也提到了,测试用例集与测试用例的关系,在实际测试中,尽量将相关的测试用例放在一个测试用例集里面,这样方便管理,如果出现问题,定位以及调试问题都比较方便。

可以看到,我们本例子,我们并没有添加main函数,在第三步的论述中也阐明了原因。但是如果我们的程序中存在main函数,那么在链接的时候就不要去链接gest_main.cc文件,否则会报错.

#makefile文件部分
gtest-all.o : $(GTEST_SRCS_)
	$(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \
            $(GTEST_DIR)/src/gtest-all.cc

gtest_main.o : $(GTEST_SRCS_)
	$(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \
            $(GTEST_DIR)/src/gtest_main.cc

gtest.a : gtest-all.o
	$(AR) $(ARFLAGS) $@ $^

gtest_main.a : gtest-all.o gtest_main.o
	$(AR) $(ARFLAGS) $@ $^

# Builds a sample test.  A test should link with either gtest.a or
# gtest_main.a, depending on whether it defines its own main()
# function.

sample1.o : $(USER_DIR)/sample1.cc $(USER_DIR)/sample1.h $(GTEST_HEADERS)
	$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1.cc

sample1_unittest.o : $(USER_DIR)/sample1_unittest.cc \
                     $(USER_DIR)/sample1.h $(GTEST_HEADERS)
	$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1_unittest.cc

sample1_unittest : sample1.o sample1_unittest.o gtest_main.a
	$(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@

从上述makefile文件的最后看到,在链接生成sample1_unittest可执行文件的时候,链接的是gtest_main.a的静态链接库。如果我们的自定义程序中包含main函数,那么这个地方就需要链接gtest.a的静态链接库。

make之后运行的结果下图所示:

例2 主要来讲述类中的成员函数如何进行单元测试,也包含3个文件,分别为sample2.h, sample2.cc , sample2_unittest.cc

/*sample2.h*/
#ifndef GTEST_SAMPLES_SAMPLE2_H_
#define GTEST_SAMPLES_SAMPLE2_H_

#include <string.h>

// A simple string class.
// 简单的字符串类
class MyString {
 private:
  const char* c_string_;
  //复制操作符被禁用
  const MyString& operator=(const MyString& rhs);

 public:
  // Clones a 0-terminated C string, allocating memory using new.
  // 克隆一个以'\0'结尾的字符串,并分配内存
  static const char* CloneCString(const char* a_c_string);

  ////////////////////////////////////////////////////////////
  //
  // C'tors

  // The default c'tor constructs a NULL string.
  // 默认构造函数
  MyString() : c_string_(NULL) {}

  // Constructs a MyString by cloning a 0-terminated C string.
  // 通过clone一个以'\0'结尾的字符串来构建MyString
  explicit MyString(const char* a_c_string) : c_string_(NULL) {
    Set(a_c_string);
  }

  // Copy c'tor
  // 拷贝构造函数
  MyString(const MyString& string) : c_string_(NULL) {
    Set(string.c_string_);
  }

  ////////////////////////////////////////////////////////////
  //
  // D'tor.  MyString is intended to be a final class, so the d'tor
  // doesn't need to be virtual.
  //
  // 因为MyString作为最终类存在,所以析构函数不必为虚函数
  ~MyString() { delete[] c_string_; }

  // Gets the 0-terminated C string this MyString object represents.
  // 获取c_string_
  const char* c_string() const { return c_string_; }

  size_t Length() const {
    return c_string_ == NULL ? 0 : strlen(c_string_);
  }

  // Sets the 0-terminated C string this MyString object represents.
  // 设置MyString的c_string_
  void Set(const char* c_string);
};
#endif  // GTEST_SAMPLES_SAMPLE2_H_

/*sample2.cc*/
#include "sample2.h"

#include <string.h>

// Clones a 0-terminated C string, allocating memory using new.
const char* MyString::CloneCString(const char* a_c_string) {
  if (a_c_string == NULL) return NULL;

  const size_t len = strlen(a_c_string);
  char* const clone = new char[ len + 1 ];
  memcpy(clone, a_c_string, len + 1);

  return clone;
}

// Sets the 0-terminated C string this MyString object
// represents.
void MyString::Set(const char* a_c_string) {
  // Makes sure this works when c_string == c_string_
  const char* const temp = MyString::CloneCString(a_c_string);
  delete[] c_string_;
  c_string_ = temp;
}

/*sample2_unittest.cc*/
// This sample shows how to write a more complex unit test for a class
// that has multiple member functions.
//
// Usually, it's a good idea to have one test for each method in your
// class.  You don't have to do that exactly, but it helps to keep
// your tests organized.  You may also throw in additional tests as
// needed.
//
// 这个例子将展示如何为一个具有多个成员函数的类编写较为复杂的单元测试
//
// 通常为你类中的每一个方法都做一次测试是一个好主意。虽然你并非一定要
// 这么做,但是这样做将使你的测试集更便于管理,当然你也可以根据需要添
// 加额外的测试用例

#include "sample2.h"
#include "gtest/gtest.h"

// In this example, we test the MyString class (a simple string).

// Tests the default c'tor.
TEST(MyString, DefaultConstructor) {
  const MyString s;

  // Asserts that s.c_string() returns NULL.
  //
  // <TechnicalDetails>
  //
  // If we write NULL instead of
  //
  //   static_cast<const char *>(NULL)
  //
  // in this assertion, it will generate a warning on gcc 3.4.  The
  // reason is that EXPECT_EQ needs to know the types of its
  // arguments in order to print them when it fails.  Since NULL is
  // #defined as 0, the compiler will use the formatter function for
  // int to print it.  However, gcc thinks that NULL should be used as
  // a pointer, not an int, and therefore complains.
  //
  // The root of the problem is C++'s lack of distinction between the
  // integer number 0 and the null pointer constant.  Unfortunately,
  // we have to live with this fact.
  //
  //技术细节:
  //   如果我们使用NULL,而不是static_cast<const char *>(NULL)。在断言中
  //如果编译器为gcc3.4,它将产生一个警告。产生警告的原因是,EXPECT_EQ需要
  //知道它参数的具体类型,以便产生错误的时候将其输出出来。由于NULL被
  //#define定义为0,所以编译器会使用格式化函数来将其输出。然而,GCC认为
  //NULL应该被当作指针类型,而不是int整形,所以编译器会抱怨。
  //
  //产生这个问题的根源是,C++对整数0以及空指针常量缺乏判别依据。不幸的是
  //我要学会接受这个现实。
  //
  // </TechnicalDetails>
  EXPECT_STREQ(NULL, s.c_string());

  EXPECT_EQ(0u, s.Length());
}

const char kHelloString[] = "Hello, world!";

// Tests the c'tor that accepts a C string.
// 测试构造函数
TEST(MyString, ConstructorFromCString) {
  const MyString s(kHelloString);
  EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
  EXPECT_EQ(sizeof(kHelloString)/sizeof(kHelloString[0]) - 1,
            s.Length());
}

// Tests the copy c'tor.
// 测试拷贝构造函数
TEST(MyString, CopyConstructor) {
  const MyString s1(kHelloString);
  const MyString s2 = s1;
  //下面的判断会是失败的
  EXPECT_EQ(1, strcmp(s2.c_string(), kHelloString));
}

// Tests the Set method.
// 测试Set方法
TEST(MyString, Set) {
  MyString s;

  s.Set(kHelloString);
  EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));

  // Set should work when the input pointer is the same as the one
  // already in the MyString object.
  //
  // Set函数在输入指针与已存在于MyString对象中的指针相同时,下面的
  // 测试才会通过
  s.Set(s.c_string());
  EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));

  // Can we set the MyString to NULL?
  s.Set(NULL);
  EXPECT_STREQ(NULL,s.c_string());
}

sample2的运行截图:

例一阐述的是如果对普通的函数进行单元测试,而例二则阐述如何对类中的成员函数进行单元测试。大致的方法基本相同,只不过在测试类成员函数之前,要先定义类,也就是例子中的MyString s;上述两个例子是gtest的简单应用,当然对于类中成员函数的单元测试要复杂的多,比如成员函数的公有还是私有,成员函数的耦合性等等,这些会在最后的单元测试实践中讨论。好了,初步的介绍就到这吧~

                's Picture

Wang Yukun

 Looking up to the Starry Sky && Keep both feet firmly on the ground

                     Beijing, China
                     airfer.github.io/

Share this post

                    Twitter

                    Facebook

                    Google+

基于 Gtest 的单元测试入门及实践 (二)

**前言**
在第一章里,主要以gtest自带的samples为例,简单阐述了为普通的成员函数,以及类中的成员函数进行单元测试,在这部分主要介绍如何利用gtest中的固件以及超级固件来优化单元测试工作。在现在的互联网企业对底层模块(C...

轻量级日志监控框架airMonitor

一、前言

点睛Front之前的打点验证,是全部靠人工来解决的,测试人员需要查看具体的打点日志,然后找到相关的日志字段,最后来校验此字段值的正确性。如果说偶尔的类似需求,人工来做校验也未尝不可,但是当需求变更非常频繁时,全靠人工来验证...

Sometimes Things Happen For A Reason © 2020

Proudly published with Jekyll using Jasper


text:
Remove empty lines from files.

## Install

```
npm install --save-dev gulp-remove-empty-lines
```

## Usage

```javascript
var gulp = require('gulp');
var removeEmptyLines = require('gulp-remove-empty-lines');

gulp.task('tojson', function () {
  gulp.src('./public/*.html')
  .pipe(removeEmptyLines())
  .pipe(gulp.dest('./public/'));
});

gulp.task('htmlClean', function () {
  gulp.src('./index.html')
  .pipe(removeEmptyLines({
    removeComments: true
  }))
  .pipe(gulp.dest('./public/'));
});
```

## Options

##### removeComments

Type: `boolean`
Default: `false`

Remove all the comments from the html files.

##### removeSpaces

Type: `boolean`
Default: `false`

Remove all duplicate spaces from any file.

## License

MIT © [Daniel Husar](https://github.com/danielhusar)


text:
package org.samovich.cop2800.chapter12.assignment;

/**
 * Filename InvalidProductionArgumentException.java
 * Created by Valery Samovich
 * Written on 7/10/2016
 */
public class InvalidProductionArgumentException extends Exception {
    public InvalidProductionArgumentException(){};
    public InvalidProductionArgumentException(String message) {
        super(message);
    }
}


text:
const resize = require("./resize");

resize("process/cards/promos_saunaavanto.jpg", `docs/img/cards/promos_saunaavanto.jpg`);


text:
import ldap
import logging
from ldap.filter import filter_format

import openerp.exceptions
from openerp import tools
from openerp.osv import fields, osv
from openerp import SUPERUSER_ID
from openerp.modules.registry import RegistryManager
_logger = logging.getLogger(__name__)

class CompanyLDAP(osv.osv):
    _name = 'res.company.ldap'
    _order = 'sequence'
    _rec_name = 'ldap_server'

    def get_ldap_dicts(self, cr, ids=None):
        """
        Retrieve res_company_ldap resources from the database in dictionary
        format.

        :param list ids: Valid ids of model res_company_ldap. If not \
        specified, process all resources (unlike other ORM methods).
        :return: ldap configurations
        :rtype: list of dictionaries
        """

        if ids:
            id_clause = 'AND id IN (%s)'
            args = [tuple(ids)]
        else:
            id_clause = ''
            args = []
        cr.execute("""
            SELECT id, company, ldap_server, ldap_server_port, ldap_binddn,
                   ldap_password, ldap_filter, ldap_base, "user", create_user,
                   ldap_tls
            FROM res_company_ldap
            WHERE ldap_server != '' """ + id_clause + """ ORDER BY sequence
        """, args)
        return cr.dictfetchall()

    def connect(self, conf):
        """
        Connect to an LDAP server specified by an ldap
        configuration dictionary.

        :param dict conf: LDAP configuration
        :return: an LDAP object
        """

        uri = 'ldap://%s:%d' % (conf['ldap_server'],
                                conf['ldap_server_port'])

        connection = ldap.initialize(uri)
        if conf['ldap_tls']:
            connection.start_tls_s()
        return connection

    def authenticate(self, conf, login, password):
        """
        Authenticate a user against the specified LDAP server.

        In order to prevent an unintended 'unauthenticated authentication',
        which is an anonymous bind with a valid dn and a blank password,
        check for empty passwords explicitely (:rfc:`4513#section-6.3.1`)

        :param dict conf: LDAP configuration
        :param login: username
        :param password: Password for the LDAP user
        :return: LDAP entry of authenticated user or False
        :rtype: dictionary of attributes
        """

        if not password:
            return False

        entry = False
        filter = filter_format(conf['ldap_filter'], (login,))
        try:
            results = self.query(conf, filter)

            # Get rid of (None, attrs) for searchResultReference replies
            results = [i for i in results if i[0]]
            if results and len(results) == 1:
                dn = results[0][0]
                conn = self.connect(conf)
                conn.simple_bind_s(dn, password)
                conn.unbind()
                entry = results[0]
        except ldap.INVALID_CREDENTIALS:
            return False
        except ldap.LDAPError, e:
            _logger.error('An LDAP exception occurred: %s', e)
        return entry

    def query(self, conf, filter, retrieve_attributes=None):
        """
        Query an LDAP server with the filter argument and scope subtree.

        Allow for all authentication methods of the simple authentication
        method:

        - authenticated bind (non-empty binddn + valid password)
        - anonymous bind (empty binddn + empty password)
        - unauthenticated authentication (non-empty binddn + empty password)

        .. seealso::
           :rfc:`4513#section-5.1` - LDAP: Simple Authentication Method.

        :param dict conf: LDAP configuration
        :param filter: valid LDAP filter
        :param list retrieve_attributes: LDAP attributes to be retrieved. \
        If not specified, return all attributes.
        :return: ldap entries
        :rtype: list of tuples (dn, attrs)

        """

        results = []
        try:
            conn = self.connect(conf)
            conn.simple_bind_s(conf['ldap_binddn'] or '',
                               conf['ldap_password'] or '')
            results = conn.search_st(conf['ldap_base'], ldap.SCOPE_SUBTREE,
                                     filter, retrieve_attributes, timeout=60)
            conn.unbind()
        except ldap.INVALID_CREDENTIALS:
            _logger.error('LDAP bind failed.')
        except ldap.LDAPError, e:
            _logger.error('An LDAP exception occurred: %s', e)
        return results

    def map_ldap_attributes(self, cr, uid, conf, login, ldap_entry):
        """
        Compose values for a new resource of model res_users,
        based upon the retrieved ldap entry and the LDAP settings.

        :param dict conf: LDAP configuration
        :param login: the new user's login
        :param tuple ldap_entry: single LDAP result (dn, attrs)
        :return: parameters for a new resource of model res_users
        :rtype: dict
        """

        values = { 'name': ldap_entry[1]['cn'][0],
                   'login': login,
                   'company_id': conf['company']
                   }
        return values

    def get_or_create_user(self, cr, uid, conf, login, ldap_entry,
                           context=None):
        """
        Retrieve an active resource of model res_users with the specified
        login. Create the user if it is not initially found.

        :param dict conf: LDAP configuration
        :param login: the user's login
        :param tuple ldap_entry: single LDAP result (dn, attrs)
        :return: res_users id
        :rtype: int
        """

        user_id = False
        login = tools.ustr(login.lower().strip())
        cr.execute("SELECT id, active FROM res_users WHERE lower(login)=%s", (login,))
        res = cr.fetchone()
        if res:
            if res[1]:
                user_id = res[0]
        elif conf['create_user']:
            _logger.debug("Creating new Odoo user \"%s\" from LDAP" % login)
            user_obj = self.pool['res.users']
            values = self.map_ldap_attributes(cr, uid, conf, login, ldap_entry)
            if conf['user']:
                values['active'] = True
                user_id = user_obj.copy(cr, SUPERUSER_ID, conf['user'],
                                        default=values)
            else:
                user_id = user_obj.create(cr, SUPERUSER_ID, values)
        return user_id

    _columns = {
        'sequence': fields.integer('Sequence'),
        'company': fields.many2one('res.company', 'Company', required=True,
            ondelete='cascade'),
        'ldap_server': fields.char('LDAP Server address', required=True),
        'ldap_server_port': fields.integer('LDAP Server port', required=True),
        'ldap_binddn': fields.char('LDAP binddn',
            help=("The user account on the LDAP server that is used to query "
                  "the directory. Leave empty to connect anonymously.")),
        'ldap_password': fields.char('LDAP password',
            help=("The password of the user account on the LDAP server that is "
                  "used to query the directory.")),
        'ldap_filter': fields.char('LDAP filter', required=True),
        'ldap_base': fields.char('LDAP base', required=True),
        'user': fields.many2one('res.users', 'Template User',
            help="User to copy when creating new users"),
        'create_user': fields.boolean('Create user',
            help="Automatically create local user accounts for new users authenticating via LDAP"),
        'ldap_tls': fields.boolean('Use TLS',
            help="Request secure TLS/SSL encryption when connecting to the LDAP server. "
                 "This option requires a server with STARTTLS enabled, "
                 "otherwise all authentication attempts will fail."),
    }
    _defaults = {
        'ldap_server': '127.0.0.1',
        'ldap_server_port': 389,
        'sequence': 10,
        'create_user': True,
    }

class res_company(osv.osv):
    _inherit = "res.company"
    _columns = {
        'ldaps': fields.one2many(
            'res.company.ldap', 'company', 'LDAP Parameters', copy=True, groups="base.group_system"),
    }

class users(osv.osv):
    _inherit = "res.users"
    def _login(self, db, login, password):
        user_id = super(users, self)._login(db, login, password)
        if user_id:
            return user_id
        registry = RegistryManager.get(db)
        with registry.cursor() as cr:
            cr.execute("SELECT id FROM res_users WHERE lower(login)=%s", (login,))
            res = cr.fetchone()
            if res:
                return False
            ldap_obj = registry.get('res.company.ldap')
            for conf in ldap_obj.get_ldap_dicts(cr):
                entry = ldap_obj.authenticate(conf, login, password)
                if entry:
                    user_id = ldap_obj.get_or_create_user(
                        cr, SUPERUSER_ID, conf, login, entry)
                    if user_id:
                        break
            return user_id

    def check_credentials(self, cr, uid, password):
        try:
            super(users, self).check_credentials(cr, uid, password)
        except openerp.exceptions.AccessDenied:

            cr.execute('SELECT login FROM res_users WHERE id=%s AND active=TRUE',
                       (int(uid),))
            res = cr.fetchone()
            if res:
                ldap_obj = self.pool['res.company.ldap']
                for conf in ldap_obj.get_ldap_dicts(cr):
                    if ldap_obj.authenticate(conf, res[0], password):
                        return
            raise

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


text:
create table pizzas as
  select "Pizzahhh" as name, 12 as open, 15 as close union
  select "La Val's"        , 11        , 22          union
  select "Sliver"          , 11        , 20          union
  select "Cheeseboard"     , 16        , 23          union
  select "Emilia's"        , 13        , 18;

create table meals as
  select "breakfast" as meal, 11 as time union
  select "lunch"            , 13         union
  select "dinner"           , 19         union
  select "snack"            , 22;

-- Two meals at the same place
create table double as
select m1.meal, m2.meal, p.name FROM meals as m1, meals as m2, pizzas as p WHERE m1.time - m2.time < -6 AND m1.time >= p.open AND m1.time <= p.close ANd m2.time >= p.open AND m2.time <= p.close ;

-- Pizza options for every meal
create table options as
with
  choices(meal, time, num, last, restaurants) as (
    select m.meal, m.time, 1, p.name, p.name from meals as m, pizzas as p where m.time >= p.open and m.time <= p.close union
    select c.meal, c.time, c.num + 1, p.name, restaurants || ", " || p.name FROM choices as c,  pizzas as p where p.name > c.last and c.time >= p.open and c.time <= p.close
  ),
  max_rest(meal, num) as (
    select meal, MAX(num) from choices group by meal
  )
select c.meal, c.num, c.restaurants from choices as c, max_rest as m where c.num = m.num and c.meal = m.meal order by c.time;


text:
import React, { Component, PropTypes } from 'react';
import styles from './Summary.scss';

export default class Summary extends Component {
  static propTypes = {
    value: PropTypes.any,
    sortedSummary: PropTypes.array
  };

  get place() {
    const {value, sortedSummary} = this.props;
    return sortedSummary.indexOf(value) + 1;
  }

  render() {
    return ({this.place} {this.props.value});
  }
}


text:
package com.systematic.trading.backtest.output.elastic.model.index;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;

import com.systematic.trading.backtest.BacktestBatchId;
import com.systematic.trading.backtest.output.elastic.configuration.BackestOutputElasticConfiguration;
import com.systematic.trading.backtest.output.elastic.dao.ElasticDao;
import com.systematic.trading.backtest.output.elastic.exception.ElasticException;
import com.systematic.trading.backtest.output.elastic.model.ElasticEmptyIndexMapping;
import com.systematic.trading.backtest.output.elastic.model.ElasticFieldName;
import com.systematic.trading.backtest.output.elastic.model.ElasticFieldType;
import com.systematic.trading.backtest.output.elastic.model.ElasticIndex;
import com.systematic.trading.backtest.output.elastic.model.ElasticIndexMapping;
import com.systematic.trading.backtest.output.elastic.model.ElasticIndexName;
import com.systematic.trading.backtest.output.elastic.resource.ElasticBulkApiMetaDataRequestResource;
import com.systematic.trading.backtest.output.elastic.resource.ElasticIndexSettingsRequestResource;

/**
 * Behaviour common for indexes put into Elastic Search
 *
 * @author CJ Hare
 */
public abstract class ElasticCommonIndex {

	/** Bulk API action for creating document and generating it's ID. */
	private static final String ACTION_CREATE_GENERATE_DOCUMENT_ID = "index";

	/** Value to disable the refresh interval. */
	private static final String INDEX_SETTING_REFRESH_DISABLE = "-1";

	/** Default value for the refresh interval. */
	private static final String INDEX_SETTING_REFRESH_DEFAULT = "1s";

	/** Access to Elastic Search endpoint. */
	private final ElasticDao dao;

	/** Number of requests that are grouped together for the Bulk API. */
	private final int bulkApiQueueSize;

	/** Storage for the meta and source requests. */
	private List<Object> bulkApiQueue;

	/** Delegate worker threads that deal with performing sending to Elastic. */
	private final ExecutorService pool;

	/** Elastic Search primary shards. */
	private final int numberOfShards;

	/** Elastic Search replications of the primary shards. */
	private final int numberOfReplicas;

	public ElasticCommonIndex(
	        final ElasticDao dao,
	        final ExecutorService pool,
	        final BackestOutputElasticConfiguration config ) {

		this.dao = dao;
		this.pool = pool;

		// Each source request (document to created) is accompanied by a meta object
		this.bulkApiQueueSize = 2 * config.bulkApiQueueSize();
		this.bulkApiQueue = new ArrayList<>(this.bulkApiQueueSize);

		this.numberOfShards = config.numberOfShards();
		this.numberOfReplicas = config.numberOfReplicas();
	}

	/**
	 * Ensures the index and mapping are created, and verifies there is not existing data.
	 */
	public void init( final BacktestBatchId id ) {

		if (isIndexMappingMissing(id)) {
			putIndexMapping(id);
		} else {
			throw new ElasticException(
			        String.format("Existing mapping (and potentially already existing results) found for: %s", id));
		}
	}

	public void ensureIndexExists() {

		if (isIndexMissing()) {
			putIndex();
		}
	}

	public void refreshInterval( final boolean enabled ) {

		dao.putSetting(
		        indexName(),
		        Entity.json(
		                new ElasticIndexSettingsRequestResource(
		                        enabled ? INDEX_SETTING_REFRESH_DEFAULT : INDEX_SETTING_REFRESH_DISABLE)));
	}

	public void flush() {

		if (!bulkApiQueue.isEmpty()) {
			send(bulkApiQueue);
		}
	}

	protected <T> void create( final BacktestBatchId id, final T requestResource ) {

		bulkApiQueue.add(createBulkApiMeta(id));
		bulkApiQueue.add(requestResource);

		if (isBulkApiBucketFull()) {
			send(bulkApiQueue);
			bulkApiQueue = new ArrayList<>(bulkApiQueueSize);

		}
	}

	private void send( final List<?> requests ) {

		pool.submit(() -> dao.postTypes(indexName(), Entity.json(requests)));
	}

	protected ElasticBulkApiMetaDataRequestResource createBulkApiMeta( final BacktestBatchId id ) {

		// TODO put this into a builder & move ACTION_CREATE_GENERATE_DOCUMENT_ID out of this class
		return new ElasticBulkApiMetaDataRequestResource(ACTION_CREATE_GENERATE_DOCUMENT_ID, null, id.name(), null);
	}

	protected ElasticIndex index() {

		return new ElasticIndex(numberOfShards, numberOfReplicas);
	}

	protected abstract ElasticIndexMapping indexMapping();

	protected abstract ElasticIndexName indexName();

	protected Pair<ElasticFieldName, ElasticFieldType> pair(
	        final ElasticFieldName name,
	        final ElasticFieldType type ) {

		return new ImmutablePair<>(name, type);
	}

	private boolean isBulkApiBucketFull() {

		return bulkApiQueue.size() >= bulkApiQueueSize;
	}

	private boolean isIndexMissing() {

		final Response response = dao.index(indexName());
		return response.getStatus() != 200;
	}

	private boolean isIndexMappingMissing( final BacktestBatchId id ) {

		final Response response = dao.mapping(indexName(), id);

		// TODO mapping shouls be 200 & empty JSON - test with data present - currently exceptional

		return response.getStatus() != 200
		        || (response.getStatus() == 200 && response.readEntity(ElasticEmptyIndexMapping.class) != null);
	}

	private void putIndex() {

		dao.put(indexName(), Entity.json(index()));
	}

	private void putIndexMapping( final BacktestBatchId id ) {

		dao.putMapping(indexName(), id, Entity.json(indexMapping()));
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>addon/models/node.js - Ember OSF Addon</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="icon" href="../assets/favicon.ico">

            API Docs for: 0.25.0

APIs

Classes

Modules

                            <input type="search" id="api-filter" placeholder="Type to filter APIs">

Analytics

auth

author-link

buildSecondaryNavLinks

CasAuthenticatedRouteMixin

ChronosJournals

ChronosSubmissions

Citation

citation-widget

Collection

Comment

comment-detail

comment-form

comment-pane

CommentableMixin

CommentReport

Contributor

current-user

discover-page

DraftRegistration

dropzone-widget

elem-id

eosf-project-nav

faceted-search

File

file-browser

file-browser-icon

file-chooser component

file-editor

file-manager

file-renderer

file-version

file-widget

FileCacheBypassMixin

FileItemMixin

FileProvider

FileVersion

filterReplace

fix-special-char

fix-special-char-helper

fixstring

GenericDataADapter

getDisplayName

HostAppNameMixin

human-file-size

ifFilter

InfinityCustomMixin

Institution

license-picker

Log

Metaschema

mimeTypes

navbar-auth-dropdown

new-navbar-auth-dropdown

Node

NodeActionsMixin

NodeLink

oauth-popup

old-file-browser

osf-copyright

osf-footer

osf-mode-footer

osf-navbar

osf-paginator

osf-services

OsfAdapter

OsfAgnosticAuthController

OsfAgnosticAuthRoute

OsfCookieAuthenticator

OsfCookieAuthorizer

OsfCookieLoginController

OsfCookieLoginRoute

OsfModel

OsfSerializer

OsfTokenAuthenticator

OsfTokenAuthorizer

OsfTokenLoginControllerMixin

OsfTokenLoginRouteMixin

outside-click

PaginatedControllerMixin

PaginatedRouteMixin

pagination-control

permissions

Preprint

project-selector

providerRegex

Registration

RegistrationActionsMixin

scheduled-banner

search-dropdown

search-facet-locked

search-help-modal

search-result

service-links

sharing-icons

sharing-icons-popover

                Sample usage:
                {{sharing-icons
                    title=title
                    description=description
                    hyperlink=hyperlink
                    metricsExtra=metricsExtra
                }}

sign-up

sortOptionDisplay

Subscription

TaggableMixin

tags-widget

Taxonomy

theme

total-share-results

User

adapters

authenticators

authorizers

components

const

ember-osf

helpers

mixins

models

serializers

services

transforms

utils

                    Show:

                        <input type="checkbox" id="api-show-inherited" checked>
                        Inherited

                        <input type="checkbox" id="api-show-protected">
                        Protected

                        <input type="checkbox" id="api-show-private">
                        Private

                        <input type="checkbox" id="api-show-deprecated">
                        Deprecated

File: addon/models/node.js

import Ember from 'ember';
import DS from 'ember-data';
import OsfModel from './osf-model';

import FileItemMixin from 'ember-osf/mixins/file-item';
import ContributorMixin from 'ember-osf/mixins/contributor-mixin';
/**
 * @module ember-osf
 * @submodule models
 */

/**
 * Model for OSF APIv2 nodes. This model may be used with one of several API endpoints. It may be queried directly,
 *  or accessed via relationship fields.
 * For field and usage information, see:
 * * https://api.osf.io/v2/docs/#!/v2/Node_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/Node_Detail_GET
 * * https://api.osf.io/v2/docs/#!/v2/Node_Children_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/Linked_Nodes_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/Node_Forks_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/User_Nodes_GET
 * @class Node
 */
export default OsfModel.extend(FileItemMixin, ContributorMixin, {
    isNode: true,

    title: DS.attr('fixstring'),
    description: DS.attr('fixstring'),
    category: DS.attr('fixstring'),

    // List of strings
    currentUserPermissions: DS.attr(),

    fork: DS.attr('boolean'),
    collection: DS.attr('boolean'),
    registration: DS.attr('boolean'),
    public: DS.attr('boolean'),

    dateCreated: DS.attr('date'),
    dateModified: DS.attr('date'),

    forkedDate: DS.attr('date'),

    nodeLicense: DS.attr(),
    tags: DS.attr(),

    templateFrom: DS.attr('fixstring'),

    parent: DS.belongsTo('node', {
        inverse: 'children'
    }),
    children: DS.hasMany('nodes', {
        inverse: 'parent'
    }),
    preprints: DS.hasMany('preprints', {
        inverse: 'node'
    }),
    affiliatedInstitutions: DS.hasMany('institutions', {
        inverse: 'nodes'
    }),
    comments: DS.hasMany('comments'),
    contributors: DS.hasMany('contributors', {
        allowBulkUpdate: true,
        allowBulkRemove: true,
        inverse: 'node'
    }),
    citation: DS.belongsTo('citation'),

    license: DS.belongsTo('license', {
        inverse: null
    }),

    files: DS.hasMany('file-provider'),
    //forkedFrom: DS.belongsTo('node'),
    linkedNodes: DS.hasMany('nodes', {
        inverse: null,
        serializerType: 'linked-node'
    }),
    registrations: DS.hasMany('registrations', {
        inverse: 'registeredFrom'
    }),

    draftRegistrations: DS.hasMany('draft-registrations', {
        inverse: 'branchedFrom'
    }),

    forks: DS.hasMany('nodes', {
        inverse: 'forkedFrom'
    }),

    forkedFrom: DS.belongsTo('node', {
        inverse: 'forks'
    }),

    root: DS.belongsTo('node', {
        inverse: null
    }),

    wikis: DS.hasMany('wikis', {
        inverse: 'node'
    }),

    logs: DS.hasMany('logs'),

    // These are only computeds because maintaining separate flag values on different classes would be a headache TODO: Improve.
    /**
     * Is this a project? Flag can be used to provide template-specific behavior for different resource types.
     * @property isProject
     * @type boolean
     */
    isProject: Ember.computed.equal('constructor.modelName', 'node'),
    /**
     * Is this a registration? Flag can be used to provide template-specific behavior for different resource types.
     * @property isRegistration
     * @type boolean
     */
    isRegistration: Ember.computed.equal('constructor.modelName', 'registration'),

    /**
     * Is this node being viewed through an anonymized, view-only link?
     * @property isAnonymous
     * @type boolean
     */
    isAnonymous: Ember.computed.bool('meta.anonymous'),

    addChild(title, description=null, category='project', isPublic) {
        let child = this.store.createRecord('node', {
            title,
            category,
            description,
            parent: this,
            public: isPublic
        });

        return child.save();
    },
});


text:
package io.trivium.dep.com.google.common.base;

import static io.trivium.dep.com.google.common.base.Preconditions.checkNotNull;

import io.trivium.dep.com.google.common.annotations.Beta;
import io.trivium.dep.com.google.common.annotations.GwtCompatible;
import io.trivium.dep.com.google.common.annotations.GwtIncompatible;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;

import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;

/**
 * Static utility methods pertaining to {@code Predicate} instances.
 *
 *
All methods returns serializable predicates as long as they're given
 * serializable parameters.
 *
 *
See the Guava User Guide article on the
 * use of {@code Predicate}.
 *
 * @author Kevin Bourrillion
 * @since 2.0
 */
@CheckReturnValue
@GwtCompatible(emulated = true)
public final class Predicates {
  private Predicates() {}

  // TODO(kevinb): considering having these implement a VisitablePredicate
  // interface which specifies an accept(PredicateVisitor) method.

  /**
   * Returns a predicate that always evaluates to {@code true}.
   */
  @GwtCompatible(serializable = true)
  public static <T> Predicate<T> alwaysTrue() {
    return ObjectPredicate.ALWAYS_TRUE.withNarrowedType();
  }

  /**
   * Returns a predicate that always evaluates to {@code false}.
   */
  @GwtCompatible(serializable = true)
  public static <T> Predicate<T> alwaysFalse() {
    return ObjectPredicate.ALWAYS_FALSE.withNarrowedType();
  }

  /**
   * Returns a predicate that evaluates to {@code true} if the object reference
   * being tested is null.
   */
  @GwtCompatible(serializable = true)
  public static <T> Predicate<T> isNull() {
    return ObjectPredicate.IS_NULL.withNarrowedType();
  }

  /**
   * Returns a predicate that evaluates to {@code true} if the object reference
   * being tested is not null.
   */
  @GwtCompatible(serializable = true)
  public static <T> Predicate<T> notNull() {
    return ObjectPredicate.NOT_NULL.withNarrowedType();
  }

  /**
   * Returns a predicate that evaluates to {@code true} if the given predicate
   * evaluates to {@code false}.
   */
  public static <T> Predicate<T> not(Predicate<T> predicate) {
    return new NotPredicate<T>(predicate);
  }

  /**
   * Returns a predicate that evaluates to {@code true} if each of its
   * components evaluates to {@code true}. The components are evaluated in
   * order, and evaluation will be "short-circuited" as soon as a false
   * predicate is found. It defensively copies the iterable passed in, so future
   * changes to it won't alter the behavior of this predicate. If {@code
   * components} is empty, the returned predicate will always evaluate to {@code
   * true}.
   */
  public static <T> Predicate<T> and(Iterable<? extends Predicate<? super T>> components) {
    return new AndPredicate<T>(defensiveCopy(components));
  }

  /**
   * Returns a predicate that evaluates to {@code true} if each of its
   * components evaluates to {@code true}. The components are evaluated in
   * order, and evaluation will be "short-circuited" as soon as a false
   * predicate is found. It defensively copies the array passed in, so future
   * changes to it won't alter the behavior of this predicate. If {@code
   * components} is empty, the returned predicate will always evaluate to {@code
   * true}.
   */
  public static <T> Predicate<T> and(Predicate<? super T>... components) {
    return new AndPredicate<T>(defensiveCopy(components));
  }

  /**
   * Returns a predicate that evaluates to {@code true} if both of its
   * components evaluate to {@code true}. The components are evaluated in
   * order, and evaluation will be "short-circuited" as soon as a false
   * predicate is found.
   */
  public static <T> Predicate<T> and(Predicate<? super T> first, Predicate<? super T> second) {
    return new AndPredicate<T>(Predicates.<T>asList(checkNotNull(first), checkNotNull(second)));
  }

  /**
   * Returns a predicate that evaluates to {@code true} if any one of its
   * components evaluates to {@code true}. The components are evaluated in
   * order, and evaluation will be "short-circuited" as soon as a
   * true predicate is found. It defensively copies the iterable passed in, so
   * future changes to it won't alter the behavior of this predicate. If {@code
   * components} is empty, the returned predicate will always evaluate to {@code
   * false}.
   */
  public static <T> Predicate<T> or(Iterable<? extends Predicate<? super T>> components) {
    return new OrPredicate<T>(defensiveCopy(components));
  }

  /**
   * Returns a predicate that evaluates to {@code true} if any one of its
   * components evaluates to {@code true}. The components are evaluated in
   * order, and evaluation will be "short-circuited" as soon as a
   * true predicate is found. It defensively copies the array passed in, so
   * future changes to it won't alter the behavior of this predicate. If {@code
   * components} is empty, the returned predicate will always evaluate to {@code
   * false}.
   */
  public static <T> Predicate<T> or(Predicate<? super T>... components) {
    return new OrPredicate<T>(defensiveCopy(components));
  }

  /**
   * Returns a predicate that evaluates to {@code true} if either of its
   * components evaluates to {@code true}. The components are evaluated in
   * order, and evaluation will be "short-circuited" as soon as a
   * true predicate is found.
   */
  public static <T> Predicate<T> or(Predicate<? super T> first, Predicate<? super T> second) {
    return new OrPredicate<T>(Predicates.<T>asList(checkNotNull(first), checkNotNull(second)));
  }

  /**
   * Returns a predicate that evaluates to {@code true} if the object being
   * tested {@code equals()} the given target or both are null.
   */
  public static <T> Predicate<T> equalTo(@Nullable T target) {
    return (target == null) ? Predicates.<T>isNull() : new IsEqualToPredicate<T>(target);
  }

  /**
   * Returns a predicate that evaluates to {@code true} if the object being
   * tested is an instance of the given class. If the object being tested
   * is {@code null} this predicate evaluates to {@code false}.
   *
   *
If you want to filter an {@code Iterable} to narrow its type, consider
   * using {@link io.trivium.dep.com.google.common.collect.Iterables#filter(Iterable, Class)}
   * in preference.
   *
   *
Warning: contrary to the typical assumptions about predicates (as
   * documented at {@link Predicate#apply}), the returned predicate may not be
   * consistent with equals. For example, {@code
   * instanceOf(ArrayList.class)} will yield different results for the two equal
   * instances {@code Lists.newArrayList(1)} and {@code Arrays.asList(1)}.
   */
  @GwtIncompatible("Class.isInstance")
  public static Predicate<Object> instanceOf(Class<?> clazz) {
    return new InstanceOfPredicate(clazz);
  }

  /**
   * Returns a predicate that evaluates to {@code true} if the class being
   * tested is assignable from the given class.  The returned predicate
   * does not allow null inputs.
   *
   * @since 10.0
   */
  @GwtIncompatible("Class.isAssignableFrom")
  @Beta
  public static Predicate<Class<?>> assignableFrom(Class<?> clazz) {
    return new AssignableFromPredicate(clazz);
  }

  /**
   * Returns a predicate that evaluates to {@code true} if the object reference
   * being tested is a member of the given collection. It does not defensively
   * copy the collection passed in, so future changes to it will alter the
   * behavior of the predicate.
   *
   *
This method can technically accept any {@code Collection<?>}, but using
   * a typed collection helps prevent bugs. This approach doesn't block any
   * potential users since it is always possible to use {@code
   * Predicates.<Object>in()}.
   *
   * @param target the collection that may contain the function input
   */
  public static <T> Predicate<T> in(Collection<? extends T> target) {
    return new InPredicate<T>(target);
  }

  /**
   * Returns the composition of a function and a predicate. For every {@code x},
   * the generated predicate returns {@code predicate(function(x))}.
   *
   * @return the composition of the provided function and predicate
   */
  public static  Predicate compose(
      Predicate predicate, Function function) {
    return new CompositionPredicate(predicate, function);
  }

  /**
   * Returns a predicate that evaluates to {@code true} if the
   * {@code CharSequence} being tested contains any match for the given
   * regular expression pattern. The test used is equivalent to
   * {@code Pattern.compile(pattern).matcher(arg).find()}
   *
   * @throws java.util.regex.PatternSyntaxException if the pattern is invalid
   * @since 3.0
   */
  @GwtIncompatible(value = "java.util.regex.Pattern")
  public static Predicate<CharSequence> containsPattern(String pattern) {
    return new ContainsPatternFromStringPredicate(pattern);
  }

  /**
   * Returns a predicate that evaluates to {@code true} if the
   * {@code CharSequence} being tested contains any match for the given
   * regular expression pattern. The test used is equivalent to
   * {@code pattern.matcher(arg).find()}
   *
   * @since 3.0
   */
  @GwtIncompatible(value = "java.util.regex.Pattern")
  public static Predicate<CharSequence> contains(Pattern pattern) {
    return new ContainsPatternPredicate(pattern);
  }

  // End public API, begin private implementation classes.

  // Package private for GWT serialization.
  enum ObjectPredicate implements Predicate<Object> {
    /** @see Predicates#alwaysTrue() */
    ALWAYS_TRUE {
      @Override
      public boolean apply(@Nullable Object o) {
        return true;
      }

      @Override
      public String toString() {
        return "Predicates.alwaysTrue()";
      }
    },
    /** @see Predicates#alwaysFalse() */
    ALWAYS_FALSE {
      @Override
      public boolean apply(@Nullable Object o) {
        return false;
      }

      @Override
      public String toString() {
        return "Predicates.alwaysFalse()";
      }
    },
    /** @see Predicates#isNull() */
    IS_NULL {
      @Override
      public boolean apply(@Nullable Object o) {
        return o == null;
      }

      @Override
      public String toString() {
        return "Predicates.isNull()";
      }
    },
    /** @see Predicates#notNull() */
    NOT_NULL {
      @Override
      public boolean apply(@Nullable Object o) {
        return o != null;
      }

      @Override
      public String toString() {
        return "Predicates.notNull()";
      }
    };

    @SuppressWarnings("unchecked") // safe contravariant cast
    <T> Predicate<T> withNarrowedType() {
      return (Predicate<T>) this;
    }
  }

  /** @see Predicates#not(Predicate) */
  private static class NotPredicate<T> implements Predicate<T>, Serializable {
    final Predicate<T> predicate;

    NotPredicate(Predicate<T> predicate) {
      this.predicate = checkNotNull(predicate);
    }

    @Override
    public boolean apply(@Nullable T t) {
      return !predicate.apply(t);
    }

    @Override
    public int hashCode() {
      return ~predicate.hashCode();
    }

    @Override
    public boolean equals(@Nullable Object obj) {
      if (obj instanceof NotPredicate) {
        NotPredicate<?> that = (NotPredicate<?>) obj;
        return predicate.equals(that.predicate);
      }
      return false;
    }

    @Override
    public String toString() {
      return "Predicates.not(" + predicate + ")";
    }

    private static final long serialVersionUID = 0;
  }

  private static final Joiner COMMA_JOINER = Joiner.on(',');

  /** @see Predicates#and(Iterable) */
  private static class AndPredicate<T> implements Predicate<T>, Serializable {
    private final List<? extends Predicate<? super T>> components;

    private AndPredicate(List<? extends Predicate<? super T>> components) {
      this.components = components;
    }

    @Override
    public boolean apply(@Nullable T t) {
      // Avoid using the Iterator to avoid generating garbage (issue 820).
      for (int i = 0; i < components.size(); i++) {
        if (!components.get(i).apply(t)) {
          return false;
        }
      }
      return true;
    }

    @Override
    public int hashCode() {
      // add a random number to avoid collisions with OrPredicate
      return components.hashCode() + 0x12472c2c;
    }

    @Override
    public boolean equals(@Nullable Object obj) {
      if (obj instanceof AndPredicate) {
        AndPredicate<?> that = (AndPredicate<?>) obj;
        return components.equals(that.components);
      }
      return false;
    }

    @Override
    public String toString() {
      return "Predicates.and(" + COMMA_JOINER.join(components) + ")";
    }

    private static final long serialVersionUID = 0;
  }

  /** @see Predicates#or(Iterable) */
  private static class OrPredicate<T> implements Predicate<T>, Serializable {
    private final List<? extends Predicate<? super T>> components;

    private OrPredicate(List<? extends Predicate<? super T>> components) {
      this.components = components;
    }

    @Override
    public boolean apply(@Nullable T t) {
      // Avoid using the Iterator to avoid generating garbage (issue 820).
      for (int i = 0; i < components.size(); i++) {
        if (components.get(i).apply(t)) {
          return true;
        }
      }
      return false;
    }

    @Override
    public int hashCode() {
      // add a random number to avoid collisions with AndPredicate
      return components.hashCode() + 0x053c91cf;
    }

    @Override
    public boolean equals(@Nullable Object obj) {
      if (obj instanceof OrPredicate) {
        OrPredicate<?> that = (OrPredicate<?>) obj;
        return components.equals(that.components);
      }
      return false;
    }

    @Override
    public String toString() {
      return "Predicates.or(" + COMMA_JOINER.join(components) + ")";
    }

    private static final long serialVersionUID = 0;
  }

  /** @see Predicates#equalTo(Object) */
  private static class IsEqualToPredicate<T> implements Predicate<T>, Serializable {
    private final T target;

    private IsEqualToPredicate(T target) {
      this.target = target;
    }

    @Override
    public boolean apply(T t) {
      return target.equals(t);
    }

    @Override
    public int hashCode() {
      return target.hashCode();
    }

    @Override
    public boolean equals(@Nullable Object obj) {
      if (obj instanceof IsEqualToPredicate) {
        IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj;
        return target.equals(that.target);
      }
      return false;
    }

    @Override
    public String toString() {
      return "Predicates.equalTo(" + target + ")";
    }

    private static final long serialVersionUID = 0;
  }

  /** @see Predicates#instanceOf(Class) */
  @GwtIncompatible("Class.isInstance")
  private static class InstanceOfPredicate implements Predicate<Object>, Serializable {
    private final Class<?> clazz;

    private InstanceOfPredicate(Class<?> clazz) {
      this.clazz = checkNotNull(clazz);
    }

    @Override
    public boolean apply(@Nullable Object o) {
      return clazz.isInstance(o);
    }

    @Override
    public int hashCode() {
      return clazz.hashCode();
    }

    @Override
    public boolean equals(@Nullable Object obj) {
      if (obj instanceof InstanceOfPredicate) {
        InstanceOfPredicate that = (InstanceOfPredicate) obj;
        return clazz == that.clazz;
      }
      return false;
    }

    @Override
    public String toString() {
      return "Predicates.instanceOf(" + clazz.getName() + ")";
    }

    private static final long serialVersionUID = 0;
  }

  /** @see Predicates#assignableFrom(Class) */
  @GwtIncompatible("Class.isAssignableFrom")
  private static class AssignableFromPredicate implements Predicate<Class<?>>, Serializable {
    private final Class<?> clazz;

    private AssignableFromPredicate(Class<?> clazz) {
      this.clazz = checkNotNull(clazz);
    }

    @Override
    public boolean apply(Class<?> input) {
      return clazz.isAssignableFrom(input);
    }

    @Override
    public int hashCode() {
      return clazz.hashCode();
    }

    @Override
    public boolean equals(@Nullable Object obj) {
      if (obj instanceof AssignableFromPredicate) {
        AssignableFromPredicate that = (AssignableFromPredicate) obj;
        return clazz == that.clazz;
      }
      return false;
    }

    @Override
    public String toString() {
      return "Predicates.assignableFrom(" + clazz.getName() + ")";
    }

    private static final long serialVersionUID = 0;
  }

  /** @see Predicates#in(Collection) */
  private static class InPredicate<T> implements Predicate<T>, Serializable {
    private final Collection<?> target;

    private InPredicate(Collection<?> target) {
      this.target = checkNotNull(target);
    }

    @Override
    public boolean apply(@Nullable T t) {
      try {
        return target.contains(t);
      } catch (NullPointerException e) {
        return false;
      } catch (ClassCastException e) {
        return false;
      }
    }

    @Override
    public boolean equals(@Nullable Object obj) {
      if (obj instanceof InPredicate) {
        InPredicate<?> that = (InPredicate<?>) obj;
        return target.equals(that.target);
      }
      return false;
    }

    @Override
    public int hashCode() {
      return target.hashCode();
    }

    @Override
    public String toString() {
      return "Predicates.in(" + target + ")";
    }

    private static final long serialVersionUID = 0;
  }

  /** @see Predicates#compose(Predicate, Function) */
  private static class CompositionPredicate implements Predicate, Serializable {
    final Predicate p;
    final Function f;

    private CompositionPredicate(Predicate p, Function f) {
      this.p = checkNotNull(p);
      this.f = checkNotNull(f);
    }

    @Override
    public boolean apply(@Nullable A a) {
      return p.apply(f.apply(a));
    }

    @Override
    public boolean equals(@Nullable Object obj) {
      if (obj instanceof CompositionPredicate) {
        CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj;
        return f.equals(that.f) && p.equals(that.p);
      }
      return false;
    }

    @Override
    public int hashCode() {
      return f.hashCode() ^ p.hashCode();
    }

    @Override
    public String toString() {
      // TODO(cpovirk): maybe make this look like the method call does ("Predicates.compose(...)")
      return p + "(" + f + ")";
    }

    private static final long serialVersionUID = 0;
  }

  /** @see Predicates#contains(Pattern) */
  @GwtIncompatible("Only used by other GWT-incompatible code.")
  private static class ContainsPatternPredicate implements Predicate<CharSequence>, Serializable {
    final Pattern pattern;

    ContainsPatternPredicate(Pattern pattern) {
      this.pattern = checkNotNull(pattern);
    }

    @Override
    public boolean apply(CharSequence t) {
      return pattern.matcher(t).find();
    }

    @Override
    public int hashCode() {
      // Pattern uses Object.hashCode, so we have to reach
      // inside to build a hashCode consistent with equals.

      return Objects.hashCode(pattern.pattern(), pattern.flags());
    }

    @Override
    public boolean equals(@Nullable Object obj) {
      if (obj instanceof ContainsPatternPredicate) {
        ContainsPatternPredicate that = (ContainsPatternPredicate) obj;

        // Pattern uses Object (identity) equality, so we have to reach
        // inside to compare individual fields.
        return Objects.equal(pattern.pattern(), that.pattern.pattern())
            && Objects.equal(pattern.flags(), that.pattern.flags());
      }
      return false;
    }

    @Override
    public String toString() {
      String patternString = Objects.toStringHelper(pattern)
          .add("pattern", pattern.pattern())
          .add("pattern.flags", pattern.flags())
          .toString();
      return "Predicates.contains(" + patternString + ")";
    }

    private static final long serialVersionUID = 0;
  }

  /** @see Predicates#containsPattern(String) */
  @GwtIncompatible("Only used by other GWT-incompatible code.")
  private static class ContainsPatternFromStringPredicate extends ContainsPatternPredicate {

    ContainsPatternFromStringPredicate(String string) {
      super(Pattern.compile(string));
    }

    @Override
    public String toString() {
      return "Predicates.containsPattern(" + pattern.pattern() + ")";
    }

    private static final long serialVersionUID = 0;
  }

  private static <T> List<Predicate<? super T>> asList(
      Predicate<? super T> first, Predicate<? super T> second) {
    // TODO(kevinb): understand why we still get a warning despite @SafeVarargs!
    return Arrays.<Predicate<? super T>>asList(first, second);
  }

  private static <T> List<T> defensiveCopy(T... array) {
    return defensiveCopy(Arrays.asList(array));
  }

  static <T> List<T> defensiveCopy(Iterable<T> iterable) {
    ArrayList<T> list = new ArrayList<T>();
    for (T element : iterable) {
      list.add(checkNotNull(element));
    }
    return list;
  }
}


text:
package br.com.mkacunha.operacao;

public enum TipoOperacao {
	INSERIR, RECUPERAR, ALTERAR, REMOVER
}


text:
package h;
import java.util.Arrays;
import java.util.List;

import smetana.core.__ptr__;

//2 xzo69vancovfvk7lnaol0jpc

public interface xdot_color_stop extends __ptr__ {
	public static List<String> DEFINITION = Arrays.asList(
"typedef struct",
"{",
"float frac",
"char* color",
"}",
"xdot_color_stop");
}

// typedef struct {
//     float frac;
//     char* color;
// } xdot_color_stop;


text:
using System.Threading.Tasks;

namespace ExpressionCache.Distributed.Tests.TestHelpers
{
    public class TestFunctionsFixture
    {
        public readonly string ReturnResult = "ReturnResult";

        public string FunctionWithoutParameters()
        {
            return ReturnResult;
        }

        public string OtherFunctionWithoutParameters()
        {
            return ReturnResult;
        }

        #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously

        public async Task<string> FunctionWithoutParametersAsync()
        {
            return ReturnResult;
        }

        public async Task<string> OtherFunctionWithoutParametersAsync()
        {
            return ReturnResult;
        }

        #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
    }
}