text:
#include <gtest/gtest.h>
#include <sync/sync.h>
#include <sw_sync.h>
#include <fcntl.h>
#include <vector>
#include <string>
#include <cassert>
#include <iostream>
#include <unistd.h>
#include <thread>
#include <poll.h>
#include <mutex>
#include <algorithm>
#include <tuple>
#include <random>
#include <unordered_map>

// TODO: better stress tests?
// Handle more than 64 fd's simultaneously, i.e. fix sync_fence_info's 4k limit.
// Handle wraparound in timelines like nvidia.

using namespace std;

namespace {

// C++ wrapper class for sync timeline.
class SyncTimeline {
    int m_fd = -1;
    bool m_fdInitialized = false;
public:
    SyncTimeline(const SyncTimeline &) = delete;
    SyncTimeline& operator=(SyncTimeline&) = delete;
    SyncTimeline() noexcept {
        int fd = sw_sync_timeline_create();
        if (fd == -1)
            return;
        m_fdInitialized = true;
        m_fd = fd;
    }
    void destroy() {
        if (m_fdInitialized) {
            close(m_fd);
            m_fd = -1;
            m_fdInitialized = false;
        }
    }
    ~SyncTimeline() {
        destroy();
    }
    bool isValid() const {
        if (m_fdInitialized) {
            int status = fcntl(m_fd, F_GETFD, 0);
            if (status >= 0)
                return true;
            else
                return false;
        }
        else {
            return false;
        }
    }
    int getFd() const {
        return m_fd;
    }
    int inc(int val = 1) {
        return sw_sync_timeline_inc(m_fd, val);
    }
};

struct SyncPointInfo {
    std::string driverName;
    std::string objectName;
    uint64_t timeStampNs;
    int status; // 1 sig, 0 active, neg is err
};

// Wrapper class for sync fence.
class SyncFence {
    int m_fd = -1;
    bool m_fdInitialized = false;
    static int s_fenceCount;

    void setFd(int fd) {
        m_fd = fd;
        m_fdInitialized = true;
    }
    void clearFd() {
        m_fd = -1;
        m_fdInitialized = false;
    }
public:
    bool isValid() const {
        if (m_fdInitialized) {
            int status = fcntl(m_fd, F_GETFD, 0);
            if (status >= 0)
                return true;
            else
                return false;
        }
        else {
            return false;
        }
    }
    SyncFence& operator=(SyncFence &&rhs) noexcept {
        destroy();
        if (rhs.isValid()) {
            setFd(rhs.getFd());
            rhs.clearFd();
        }
        return *this;
    }
    SyncFence(SyncFence &&fence) noexcept {
        if (fence.isValid()) {
            setFd(fence.getFd());
            fence.clearFd();
        }
    }
    SyncFence(const SyncFence &fence) noexcept {
        // This is ok, as sync fences are immutable after construction, so a dup
        // is basically the same thing as a copy.
        if (fence.isValid()) {
            int fd = dup(fence.getFd());
            if (fd == -1)
                return;
            setFd(fd);
        }
    }
    SyncFence(const SyncTimeline &timeline,
              int value,
              const char *name = nullptr) noexcept {
        std::string autoName = "allocFence";
        autoName += s_fenceCount;
        s_fenceCount++;
        int fd = sw_sync_fence_create(timeline.getFd(), name ? name : autoName.c_str(), value);
        if (fd == -1)
            return;
        setFd(fd);
    }
    SyncFence(const SyncFence &a, const SyncFence &b, const char *name = nullptr) noexcept {
        std::string autoName = "mergeFence";
        autoName += s_fenceCount;
        s_fenceCount++;
        int fd = sync_merge(name ? name : autoName.c_str(), a.getFd(), b.getFd());
        if (fd == -1)
            return;
        setFd(fd);
    }
    SyncFence(const vector<SyncFence> &sources) noexcept {
        assert(sources.size());
        SyncFence temp(*begin(sources));
        for (auto itr = ++begin(sources); itr != end(sources); ++itr) {
            temp = SyncFence(*itr, temp);
        }
        if (temp.isValid()) {
            setFd(temp.getFd());
            temp.clearFd();
        }
    }
    void destroy() {
        if (isValid()) {
            close(m_fd);
            clearFd();
        }
    }
    ~SyncFence() {
        destroy();
    }
    int getFd() const {
        return m_fd;
    }
    int wait(int timeout = -1) {
        return sync_wait(m_fd, timeout);
    }
    vector<SyncPointInfo> getInfo() const {
        struct sync_pt_info *pointInfo = nullptr;
        vector<SyncPointInfo> fenceInfo;
        sync_fence_info_data *info = sync_fence_info(getFd());
        if (!info) {
            return fenceInfo;
        }
        while ((pointInfo = sync_pt_info(info, pointInfo))) {
            fenceInfo.push_back(SyncPointInfo{
                pointInfo->driver_name,
                pointInfo->obj_name,
                pointInfo->timestamp_ns,
                pointInfo->status});
        }
        sync_fence_info_free(info);
        return fenceInfo;
    }
    int getSize() const {
        return getInfo().size();
    }
    int getSignaledCount() const {
        return countWithStatus(1);
    }
    int getActiveCount() const {
        return countWithStatus(0);
    }
    int getErrorCount() const {
        return countWithStatus(-1);
    }
private:
    int countWithStatus(int status) const {
        int count = 0;
        for (auto &info : getInfo()) {
            if (info.status == status) {
                count++;
            }
        }
        return count;
    }
};

int SyncFence::s_fenceCount = 0;

TEST(AllocTest, Timeline) {
    SyncTimeline timeline;
    ASSERT_TRUE(timeline.isValid());
}

TEST(AllocTest, Fence) {
    SyncTimeline timeline;
    ASSERT_TRUE(timeline.isValid());

    SyncFence fence(timeline, 1);
    ASSERT_TRUE(fence.isValid());
}

TEST(AllocTest, FenceNegative) {
    int timeline = sw_sync_timeline_create();
    ASSERT_GT(timeline, 0);

    // bad fd.
    ASSERT_LT(sw_sync_fence_create(-1, "fence", 1), 0);

    // No name - segfaults in user space.
    // Maybe we should be friendlier here?
    /*
    ASSERT_LT(sw_sync_fence_create(timeline, nullptr, 1), 0);
    */
    close(timeline);
}

TEST(FenceTest, OneTimelineWait) {
    SyncTimeline timeline;
    ASSERT_TRUE(timeline.isValid());

    SyncFence fence(timeline, 5);
    ASSERT_TRUE(fence.isValid());

    // Wait on fence until timeout.
    ASSERT_EQ(fence.wait(0), -1);
    ASSERT_EQ(errno, ETIME);

    // Advance timeline from 0 -> 1
    ASSERT_EQ(timeline.inc(1), 0);

    // Wait on fence until timeout.
    ASSERT_EQ(fence.wait(0), -1);
    ASSERT_EQ(errno, ETIME);

    // Signal the fence.
    ASSERT_EQ(timeline.inc(4), 0);

    // Wait successfully.
    ASSERT_EQ(fence.wait(0), 0);

    // Go even futher, and confirm wait still succeeds.
    ASSERT_EQ(timeline.inc(10), 0);
    ASSERT_EQ(fence.wait(0), 0);
}

TEST(FenceTest, OneTimelinePoll) {
    SyncTimeline timeline;
    ASSERT_TRUE(timeline.isValid());

    SyncFence fence(timeline, 100);
    ASSERT_TRUE(fence.isValid());

    fd_set set;
    FD_ZERO(&set);
    FD_SET(fence.getFd(), &set);

    // Poll the fence, and wait till timeout.
    timeval time = {0};
    ASSERT_EQ(select(fence.getFd() + 1, &set, nullptr, nullptr, &time), 0);

    // Advance the timeline.
    timeline.inc(100);
    timeline.inc(100);

    // Select should return that the fd is read for reading.
    FD_ZERO(&set);
    FD_SET(fence.getFd(), &set);

    ASSERT_EQ(select(fence.getFd() + 1, &set, nullptr, nullptr, &time), 1);
    ASSERT_TRUE(FD_ISSET(fence.getFd(), &set));
}

TEST(FenceTest, OneTimelineMerge) {
    SyncTimeline timeline;
    ASSERT_TRUE(timeline.isValid());

    // create fence a,b,c and then merge them all into fence d.
    SyncFence a(timeline, 1), b(timeline, 2), c(timeline, 3);
    ASSERT_TRUE(a.isValid());
    ASSERT_TRUE(b.isValid());
    ASSERT_TRUE(c.isValid());

    SyncFence d({a,b,c});
    ASSERT_TRUE(d.isValid());

    // confirm all fences have one active point (even d).
    ASSERT_EQ(a.getActiveCount(), 1);
    ASSERT_EQ(b.getActiveCount(), 1);
    ASSERT_EQ(c.getActiveCount(), 1);
    ASSERT_EQ(d.getActiveCount(), 1);

    // confirm that d is not signaled until the max of a,b,c
    timeline.inc(1);
    ASSERT_EQ(a.getSignaledCount(), 1);
    ASSERT_EQ(d.getActiveCount(), 1);

    timeline.inc(1);
    ASSERT_EQ(b.getSignaledCount(), 1);
    ASSERT_EQ(d.getActiveCount(), 1);

    timeline.inc(1);
    ASSERT_EQ(c.getSignaledCount(), 1);
    ASSERT_EQ(d.getActiveCount(), 0);
    ASSERT_EQ(d.getSignaledCount(), 1);
}

TEST(FenceTest, MergeSameFence) {
    SyncTimeline timeline;
    ASSERT_TRUE(timeline.isValid());

    SyncFence fence(timeline, 5);
    ASSERT_TRUE(fence.isValid());

    SyncFence selfMergeFence(fence, fence);
    ASSERT_TRUE(selfMergeFence.isValid());

    ASSERT_EQ(selfMergeFence.getSignaledCount(), 0);

    timeline.inc(5);
    ASSERT_EQ(selfMergeFence.getSignaledCount(), 1);
}

TEST(FenceTest, PollOnDestroyedTimeline) {
    SyncTimeline timeline;
    ASSERT_TRUE(timeline.isValid());

    SyncFence fenceSig(timeline, 100);
    SyncFence fenceKill(timeline, 200);

    // Spawn a thread to wait on a fence when the timeline is killed.
    thread waitThread{
        [&]() {
            ASSERT_EQ(timeline.inc(100), 0);

            // Wait on the fd.
            struct pollfd fds;
            fds.fd = fenceKill.getFd();
            fds.events = POLLIN | POLLERR;
            ASSERT_EQ(poll(&fds, 1, 0), 0);
        }
    };

    // Wait for the thread to spool up.
    fenceSig.wait();

    // Kill the timeline.
    timeline.destroy();

    // wait for the thread to clean up.
    waitThread.join();
}

TEST(FenceTest, MultiTimelineWait) {
    SyncTimeline timelineA, timelineB, timelineC;

    SyncFence fenceA(timelineA, 5);
    SyncFence fenceB(timelineB, 5);
    SyncFence fenceC(timelineC, 5);

    // Make a larger fence using 3 other fences from different timelines.
    SyncFence mergedFence({fenceA, fenceB, fenceC});
    ASSERT_TRUE(mergedFence.isValid());

    // Confirm fence isn't signaled
    ASSERT_EQ(mergedFence.getActiveCount(), 3);
    ASSERT_EQ(mergedFence.wait(0), -1);
    ASSERT_EQ(errno, ETIME);

    timelineA.inc(5);
    ASSERT_EQ(mergedFence.getActiveCount(), 2);
    ASSERT_EQ(mergedFence.getSignaledCount(), 1);

    timelineB.inc(5);
    ASSERT_EQ(mergedFence.getActiveCount(), 1);
    ASSERT_EQ(mergedFence.getSignaledCount(), 2);

    timelineC.inc(5);
    ASSERT_EQ(mergedFence.getActiveCount(), 0);
    ASSERT_EQ(mergedFence.getSignaledCount(), 3);

    // confirm you can successfully wait.
    ASSERT_EQ(mergedFence.wait(100), 0);
}

TEST(StressTest, TwoThreadsSharedTimeline) {
    const int iterations = 1 << 16;
    int counter = 0;
    SyncTimeline timeline;
    ASSERT_TRUE(timeline.isValid());

    // Use a single timeline to synchronize two threads
    // hammmering on the same counter.
    auto threadMain = [&](int threadId) {
        for (int i = 0; i < iterations; i++) {
            SyncFence fence(timeline, i * 2 + threadId);
            ASSERT_TRUE(fence.isValid());

            // Wait on the prior thread to complete.
            ASSERT_EQ(fence.wait(), 0);

            // Confirm the previous thread's writes are visible and then inc.
            ASSERT_EQ(counter, i * 2 + threadId);
            counter++;

            // Kick off the other thread.
            ASSERT_EQ(timeline.inc(), 0);
        }
    };

    thread a{threadMain, 0};
    thread b{threadMain, 1};
    a.join();
    b.join();

    // make sure the threads did not trample on one another.
    ASSERT_EQ(counter, iterations * 2);
}

class ConsumerStressTest : public ::testing::TestWithParam<int> {};

TEST_P(ConsumerStressTest, MultiProducerSingleConsumer) {
    mutex lock;
    int counter = 0;
    int iterations = 1 << 12;

    vector<SyncTimeline> producerTimelines(GetParam());
    vector<thread> threads;
    SyncTimeline consumerTimeline;

    // Producer threads run this lambda.
    auto threadMain = [&](int threadId) {
        for (int i = 0; i < iterations; i++) {
            SyncFence fence(consumerTimeline, i);
            ASSERT_TRUE(fence.isValid());

            // Wait for the consumer to finish. Use alternate
            // means of waiting on the fence.
            if ((iterations + threadId) % 8 != 0) {
                ASSERT_EQ(fence.wait(), 0);
            }
            else {
                while (fence.getSignaledCount() != 1) {
                    ASSERT_EQ(fence.getErrorCount(), 0);
                }
            }

            // Every producer increments the counter, the consumer checks + erases it.
            lock.lock();
            counter++;
            lock.unlock();

            ASSERT_EQ(producerTimelines[threadId].inc(), 0);
        }
    };

    for (int i = 0; i < GetParam(); i++) {
        threads.push_back(thread{threadMain, i});
    }

    // Consumer thread runs this loop.
    for (int i = 1; i <= iterations; i++) {
        // Create a fence representing all producers final timelines.
        vector<SyncFence> fences;
        for (auto& timeline : producerTimelines) {
            fences.push_back(SyncFence(timeline, i));
        }
        SyncFence mergeFence(fences);
        ASSERT_TRUE(mergeFence.isValid());

        // Make sure we see an increment from every producer thread. Vary
        // the means by which we wait.
        if (iterations % 8 != 0) {
            ASSERT_EQ(mergeFence.wait(), 0);
        }
        else {
            while (mergeFence.getSignaledCount() != mergeFence.getSize()) {
                ASSERT_EQ(mergeFence.getErrorCount(), 0);
            }
        }
        ASSERT_EQ(counter, GetParam()*i);

        // Release the producer threads.
        ASSERT_EQ(consumerTimeline.inc(), 0);
    }

    for_each(begin(threads), end(threads), [](thread& thread) { thread.join(); });
}
INSTANTIATE_TEST_CASE_P(
    ParameterizedStressTest,
    ConsumerStressTest,
    ::testing::Values(2,4,16));

class MergeStressTest : public ::testing::TestWithParam<tuple<int, int>> {};

template <typename K, typename V> using dict = unordered_map<K,V>;

TEST_P(MergeStressTest, RandomMerge) {
    int timelineCount = get<0>(GetParam());
    int mergeCount = get<1>(GetParam());

    vector<SyncTimeline> timelines(timelineCount);

    default_random_engine generator;
    uniform_int_distribution<int> timelineDist(0, timelines.size()-1);
    uniform_int_distribution<int> syncPointDist(0, numeric_limits<int>::max());

    SyncFence fence(timelines[0], 0);
    ASSERT_TRUE(fence.isValid());

    unordered_map<int, int> fenceMap;
    fenceMap.insert(make_pair(0, 0));

    // Randomly create syncpoints out of a fixed set of timelines, and merge them together.
    for (int i = 0; i < mergeCount; i++) {

        // Generate syncpoint.
        int timelineOffset = timelineDist(generator);
        const SyncTimeline& timeline = timelines[timelineOffset];
        int syncPoint = syncPointDist(generator);

        // Keep track of the latest syncpoint in each timeline.
        auto itr = fenceMap.find(timelineOffset);
        if (itr == end(fenceMap)) {
            fenceMap.insert(make_pair(timelineOffset, syncPoint));
        }
        else {
            int oldSyncPoint = itr->second;
            fenceMap.erase(itr);
            fenceMap.insert(make_pair(timelineOffset, max(syncPoint, oldSyncPoint)));
        }

        // Merge.
        fence = SyncFence(fence, SyncFence(timeline, syncPoint));
        ASSERT_TRUE(fence.isValid());
    }

    // Confirm our map matches the fence.
    ASSERT_EQ(fence.getSize(), fenceMap.size());

    // Trigger the merged fence.
    for (auto& item: fenceMap) {
        ASSERT_EQ(fence.wait(0), -1);
        ASSERT_EQ(errno, ETIME);

        // Increment the timeline to the last syncpoint.
        timelines[item.first].inc(item.second);
    }

    // Check that the fence is triggered.
    ASSERT_EQ(fence.wait(0), 0);
}

INSTANTIATE_TEST_CASE_P(
    ParameterizedMergeStressTest,
    MergeStressTest,
    ::testing::Combine(::testing::Values(16,32), ::testing::Values(32, 1024, 1024*32)));

}


text:
@implementation SLKInputAccessoryView {
    __weak id _kb;
}

#pragma mark - Super Overrides

- (void)dealloc
{
    [_kb removeObserver:self forKeyPath:@"center"];
}

- (void)willMoveToSuperview:(UIView *)newSuperview
{
    [super willMoveToSuperview:newSuperview];

    if (_kb != newSuperview) {
        [_kb removeObserver:self forKeyPath:@"center"];
    }

    _kb = newSuperview;
    [newSuperview addObserver:self forKeyPath:@"center" options:NSKeyValueObservingOptionNew context:nil];
}

- (UIView *)keyboardViewProxy
{
    return self.superview;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"center"]) {
        [self.frameDelegate accessoryView:self didChangeFrame:self.superview.frame];
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

@end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>wCMF 4.0: support.doxy Source File</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="A MDSD framework for building reliable, maintainable and extendable web applications with PHP">
  <meta name="keywords" content="PHP, web application framework, model driven development">
  <meta name="author" content="wemove digital solutions">
  <link rel="shortcut icon" href="theme/images/favicon.ico">

  <link href="theme/css/doxstyles.css" rel="stylesheet">

  <link href="theme/bootstrap3/css/bootstrap.min.css" rel="stylesheet">
  <link href="theme/bootstrap3/css/font-awesome.min.css" rel="stylesheet">

  <link href="theme/js/tocify/jquery.tocify.css" rel="stylesheet">

  <link href="theme/css/syntax.css" rel="stylesheet">
  <link href="theme/css/style.css" rel="stylesheet">

          <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".menu-navbar-collapse">
            Toggle navigation
          </button>
          wCMF 4.0

 Guides

Getting started

Architecture

Model

Persistence

Presentation

Configuration

Security

I18n & l10n

Tests

 API

 Code

 Support

                <input id="MSearchField" type="text" class="form-control" placeholder="Search API" name="query" onkeyup="searchBox.OnSearchFieldChange(event)">

wcmf_older

wcmf

docs

api-src

framework_description

en

support.doxy

    1 /*!

    2 \page support Support

    3 <div class="has-toc"></div>

    4

    5 # Support # {#sup_main}

    6

    7 ## Bugs & Features ## {#sup_bugs}

    8

    9 We're always trying to make wCMF better and your help is highly appreciated.

   10

   11 So, if you found a bug or have a feature request, don't hesitate to report it in

   12 the [issue tracker](https://github.com/iherwig/wcmf/issues).

   13

   14 ## Contact ## {#sup_contact}

   15

   16 If you have comments, suggestions or need help, send us an email

   17 to [wcmf@wemove.com](mailto:wcmf@wemove.com).

   18 */

        © 2016 wemove digital solutions

          Generated on Fri Jul 15 2016 22:20:36 for wCMF by  doxygen 1.8.10


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.github.namioka.spring-boot-multiple-modules-example</groupId>
        <artifactId>xyz-interfaces</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <artifactId>xyz-web</artifactId>
    <packaging>jar</packaging>
    <dependencies>
        <!-- Java Platform, Enterprise Edition (Java EE) 7 -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <!-- To activate jsr330 <scope>provided</scope>-->
        </dependency>
        <!-- Java Platform, Enterprise Edition (Java EE) 7 -->
        <!-- The Spring IO Platform -->
        <!-- http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-build-systems.html#using-boot-starter-poms -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <!--
                Cannot perform conversion to XML from legacy HTML: The nekoHTML library is not in classpath.
                nekoHTML 1.9.15 or newer is required for processing templates in "LEGACYHTML5" mode [http://nekohtml.sourceforge.net].
                Maven spec: "net.sourceforge.nekohtml::nekohtml::1.9.15".
                IMPORTANT: DO NOT use versions of nekoHTML older than 1.9.15.
            -->
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
        </dependency>
        <!-- The Spring IO Platform -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.github.namioka.spring-boot-multiple-modules-example</groupId>
            <artifactId>xyz-domain</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.namioka.spring-boot-multiple-modules-example</groupId>
            <artifactId>xyz-application</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.namioka.spring-boot-multiple-modules-example</groupId>
            <artifactId>xyz-infrastructure</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <profiles>
        <profile>
            <id>local</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <!--
            <dependencies>
                <dependency>
                    <groupId>com.h2database</groupId>
                    <artifactId>h2</artifactId>
                    <scope>runtime</scope>
                </dependency>
            </dependencies>
            -->
        </profile>
    </profiles>
</project>


text:
  Salles-Arbuissonnas-en-Beaujolais est
       un village
       localisé dans le département de Rhône en Rhône-Alpes. On dénombrait 732 habitants en 2008.

Le parc d'habitations, à Salles-Arbuissonnas-en-Beaujolais, était réparti en 2011 en 44 appartements et 307 maisons soit
 un marché plutôt équilibré.

Si vous envisagez de demenager à Salles-Arbuissonnas-en-Beaujolais, vous pourrez facilement trouver une maison à acheter.

À Salles-Arbuissonnas-en-Beaujolais, la valorisation moyenne à l'achat d'un appartement s'évalue à 2 032 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 812 € du m². À la location la valorisation moyenne se situe à 8,22 € du m² mensuel.

À coté de Salles-Arbuissonnas-en-Beaujolais sont positionnées géographiquement les villes de
Vaux-en-Beaujolais localisée à 3 km, 946 habitants,
Rivolet à 4 km, 528 habitants,
Saint-Julien à 2 km, 812 habitants,
Saint-Étienne-des-Oullières localisée à 3 km, 1 750 habitants,
Montmelas-Saint-Sorlin située à 3 km, 358 habitants,
Blacé localisée à 1 km, 1 322 habitants,
 entre autres. De plus, Salles-Arbuissonnas-en-Beaujolais est située à seulement huit km de Villefranche-sur-Saône.


text:
from drdump import load

from django.core.management.base import BaseCommand

class Command(BaseCommand):

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            'manifest',
            nargs='?',
            default='./dumps/drdump.manifest',
        )

    def handle(self, **options):
        manifest = options['manifest']
        load.main(manifest)


text:
import $ from 'jquery';
import _ from 'underscore';
import '../../../lib/select2';
import '../../../utils/lib/velocity';
import app from '../../../app';
import loadTemplate from '../../../utils/loadTemplate';
import { launchSettingsModal } from '../../../utils/modalManager';
import {
  getInventory,
  events as inventoryEvents,
} from '../../../utils/inventory';
import { startAjaxEvent, endAjaxEvent } from '../../../utils/metrics';
import { toStandardNotation } from '../../../utils/number';
import { getExchangeRate } from '../../../utils/currency';
import { capitalize } from '../../../utils/string';
import { openSimpleMessage } from '../SimpleMessage';
import Order from '../../../models/purchase/Order';
import Item from '../../../models/purchase/Item';
import Listing from '../../../models/listing/Listing';
import Purchase from '../../../models/purchase/Purchase';
import BaseModal from '../BaseModal';
import PopInMessage, { buildRefreshAlertMessage } from '../../components/PopInMessage';
import Moderators from '../../components/Moderators';
import Shipping from './Shipping';
import Receipt from './Receipt';
import Coupons from './Coupons';
import ActionBtn from './ActionBtn';
import Payment from './Payment';
import Complete from './Complete';
import FeeChange from '../../components/FeeChange';
import CryptoTradingPair from '../../components/CryptoTradingPair';

export default class extends BaseModal {
  constructor(options = {}) {
    if (!options.listing || !(options.listing instanceof Listing)) {
      throw new Error('Please provide a listing model');
    }

    if (!options.vendor) {
      throw new Error('Please provide a vendor object');
    }

    const opts = {
      ...options,
      initialState: {
        phase: 'pay',
        ...options.initialState || {},
      },
    };

    super(opts);
    this.options = opts;
    this.listing = opts.listing;
    this.variants = opts.variants;
    this.vendor = opts.vendor;
    const shippingOptions = this.listing.get('shippingOptions');
    const shippable = !!(shippingOptions && shippingOptions.length);

    const moderatorIDs = this.listing.get('moderators') || [];
    const disallowedIDs = [app.profile.id, this.listing.get('vendorID').peerID];
    this.moderatorIDs = _.without(moderatorIDs, ...disallowedIDs);
    this.setState({
      showModerators: this.moderatorIDs.length,
      showOnlyVerified: true,
    }, { renderOnChange: false });

    this.couponObj = [];

    this.order = new Order(
      {},
      {
        shippable,
        moderated: this.moderatorIDs.length && app.verifiedMods.matched(this.moderatorIDs).length,
      });

    /*
       to support multiple items in a purchase in the future, pass in listings in the options,
       and add them to the order as items here.
    */
    const item = new Item(
      {
        listingHash: this.listing.get('hash'),
        quantity: !this.listing.isCrypto ? 1 : undefined,
        options: options.variants || [],
      },
      {
        isCrypto: this.listing.isCrypto,
        inventory: () =>
          (typeof this.inventory === 'number' ?
            this.inventory : 99999999999999999),
      }
    );
    // add the item to the order.
    this.order.get('items').add(item);

    // create an empty purchase model
    this.purchase = new Purchase();

    this.actionBtn = this.createChild(ActionBtn, {
      listing: this.listing,
    });
    this.listenTo(this.actionBtn, 'purchase', (() => this.purchaseListing()));
    this.listenTo(this.actionBtn, 'close', (() => this.close()));

    this.receipt = this.createChild(Receipt, {
      model: this.order,
      listing: this.listing,
      prices: this.prices,
      couponObj: this.couponObj,
    });

    this.coupons = this.createChild(Coupons, {
      coupons: this.listing.get('coupons'),
      listingPrice: this.listing.price.amount,
    });
    this.listenTo(this.coupons, 'changeCoupons',
      (hashes, codes) => this.changeCoupons(hashes, codes));

    this.moderators = this.createChild(Moderators, {
      moderatorIDs: this.moderatorIDs,
      useCache: false,
      showVerifiedOnly: true,
      fetchErrorTitle: app.polyglot.t('purchase.errors.moderatorsTitle'),
      fetchErrorMsg: app.polyglot.t('purchase.errors.moderatorsMsg'),
      purchase: true,
      cardState: 'unselected',
      notSelected: 'unselected',
      singleSelect: true,
      selectFirst: true,
      radioStyle: true,
    });
    // render the moderators so it can start fetching and adding moderator cards
    this.moderators.render();
    this.moderators.getModeratorsByID();
    this.listenTo(this.moderators, 'noValidModerators', () => this.onNoValidModerators());
    this.listenTo(this.moderators, 'clickShowUnverified', () => this.togVerifiedModerators(false));
    this.listenTo(this.moderators, 'cardSelect', () => this.onCardSelect());

    if (this.listing.get('shippingOptions').length) {
      this.shipping = this.createChild(Shipping, {
        model: this.listing,
      });
      this.listenTo(this.shipping, 'shippingOptionSelected', () => this.updateShippingOption());
      // set the initial shipping option
      this.updateShippingOption(this.shipping.selectedOption);
    }

    this.complete = this.createChild(Complete, {
      listing: this.listing,
      vendor: this.vendor,
    });

    // If the parent has the inventory, pass it in, otherwise we'll fetch it.
    this.inventory = this.options.inventory;
    if (this.listing.isCrypto &&
      typeof this.inventory !== 'number') {
      this.inventoryFetch = getInventory(
        this.listing.get('vendorID').peerID,
        {
          slug: this.listing.get('slug'),
          coinDivisibility:
            this.listing.get('metadata')
              .get('coinDivisibility'),
        }
      ).done(e => (this.inventory = e.inventory));
      this.listenTo(inventoryEvents, 'inventory-change',
        e => (this.inventory = e.inventory));
    }

    this.listenTo(app.settings, 'change:localCurrency', () => this.showDataChangedMessage());
    this.listenTo(app.localSettings, 'change:bitcoinUnit', () => this.showDataChangedMessage());
    this.listenTo(this.order.get('items').at(0), 'someChange ', () => this.refreshPrices());
    this.listenTo(this.order.get('items').at(0).get('shipping'), 'change', () =>
      this.refreshPrices());

    this.hasVerifiedMods = app.verifiedMods.matched(this.moderatorIDs).length > 0;

    this.listenTo(app.verifiedMods, 'update', () => {
      const newHasVerifiedMods = app.verifiedMods.matched(moderatorIDs).length > 0;
      if (newHasVerifiedMods !== this.hasVerifiedMods) {
        this.hasVerifiedMods = newHasVerifiedMods;
        this.showDataChangedMessage();
      }
    });
  }

  className() {
    return `${super.className()} purchase modalScrollPage`;
  }

  events() {
    return {
      'click .js-goToListing': 'clickGoToListing',
      'click .js-close': 'clickClose',
      'click .js-retryFee': 'clickRetryFee',
      'click .js-directPayment': 'clickDirectPurchase',
      'change #purchaseQuantity': 'changeQuantityInput',
      'change #purchaseCryptoAddress': 'changeCryptoAddress',
      'click .js-newAddress': 'clickNewAddress',
      'click .js-applyCoupon': 'applyCoupon',
      'keyup #couponCode': 'onKeyUpCouponCode',
      'blur #emailAddress': 'blurEmailAddress',
      'blur #memo': 'blurMemo',
      'click .js-purchaseVerifiedOnly': 'onClickVerifiedOnly',
      'change #cryptoAmountCurrency': 'changeCryptoAmountCurrency',
      'keyup [name="quantity"]': 'keyupQuantity',
      ...super.events(),
    };
  }

  get inventory() {
    return this._inventory;
  }

  set inventory(inventory) {
    this._inventory = inventory;
  }

  showDataChangedMessage() {
    if (this.dataChangePopIn && !this.dataChangePopIn.isRemoved()) {
      this.dataChangePopIn.$el.velocity('callout.shake', { duration: 500 });
    } else {
      this.dataChangePopIn = this.createChild(PopInMessage, {
        messageText:
          buildRefreshAlertMessage(app.polyglot.t('purchase.purchaseDataChangedPopin')),
      });

      this.listenTo(this.dataChangePopIn, 'clickRefresh', () => {
        this.render();
        this.moderators.render();
      });

      this.listenTo(this.dataChangePopIn, 'clickDismiss', () => {
        this.dataChangePopIn.remove();
        this.dataChangePopIn = null;
      });

      this.getCachedEl('.js-popInMessages').append(this.dataChangePopIn.render().el);
    }
  }

  goToListing() {
    app.router.navigate(`${this.vendor.peerID}/store/${this.listing.get('slug')}`,
      { trigger: true });
    this.close();
  }

  clickGoToListing() {
    this.goToListing();
  }

  clickClose() {
    this.trigger('closeBtnPressed');
    this.close();
  }

  clickDirectPurchase() {
    if (!this.order.moderated) return;

    this.order.moderated = false;
    this.moderators.deselectOthers();
    this.setState({ unverifedSelected: false }, { renderOnChange: false });
    this.render(); // always render even if the state didn't change
  }

  onNoValidModerators() {
    this.order.moderated = false;
    this.render();
  }

  togVerifiedModerators(bool) {
    // If an unverified moderator is selected, don't set showOnlyVerified to
    // true, otherwise you will hide the selected moderator.
    const modBool = bool && this.getState().unverifiedSelected ? false : bool;
    this.moderators.togVerifiedShown(modBool);
    this.setState({ showOnlyVerified: modBool });
  }

  onClickVerifiedOnly(e) {
    this.togVerifiedModerators($(e.target).prop('checked'));
  }

  onCardSelect() {
    this.order.moderated = true;
    const selected = this.moderators.selectedIDs;
    const unverifedSelected = selected.length && !app.verifiedMods.matched(selected).length;
    this.setState({ unverifedSelected }, { renderOnChange: false });
    this.render(); // always render even if the state didn't change
  }

  changeCryptoAddress(e) {
    this.order.get('items')
      .at(0)
      .set('paymentAddress', e.target.value);
  }

  setModelQuantity(quantity, cur = this.cryptoAmountCurrency) {
    if (typeof cur !== 'string') {
      throw new Error('Please provide the currency code as a string.');
    }

    let mdQuantity = quantity;
    const numericQuantity = parseFloat(quantity);

    if (this.listing.isCrypto &&
      cur !== this.listing.get('metadata')
        .get('coinType') &&
      !isNaN(numericQuantity)) {
      mdQuantity = (numericQuantity / getExchangeRate(cur)) *
        getExchangeRate(this.listing.get('metadata').get('coinType'));
      // round to 4 decimal place
      mdQuantity = Math.round(mdQuantity * 10000) / 10000;
    }

    this.order.get('items')
      .at(0)
      .set({ quantity: mdQuantity });
  }

  changeCryptoAmountCurrency(e) {
    this._cryptoAmountCurrency = e.target.value;
    const quantity = this.getFormData(
      this.getCachedEl('#cryptoAmount')
    ).quantity;
    this.setModelQuantity(quantity);
  }

  keyupQuantity(e) {
    // wait until they stop typing
    if (this.searchKeyUpTimer) {
      clearTimeout(this.searchKeyUpTimer);
    }

    this.searchKeyUpTimer = setTimeout(() => {
      const quantity = this.getFormData($(e.target)).quantity;
      if (this.listing.isCrypto) this._cryptoQuantity = quantity;
      this.setModelQuantity(quantity);
    }, 150);
  }

  clickNewAddress() {
    launchSettingsModal({ initialTab: 'Addresses' });
  }

  applyCoupon() {
    const code = this.coupons.addCode(this.$couponField.val());
    code.then(result => {
      // if the result is valid, clear the input field
      if (result.type === 'valid') {
        this.$couponField.val('');
      }
    });
  }

  onKeyUpCouponCode(e) {
    if (e.which === 13) {
      this.applyCoupon();
    }
  }

  blurEmailAddress(e) {
    this.order.set('alternateContactInfo', $(e.target).val());
  }

  blurMemo(e) {
    this.order.get('items').at(0).set('memo', $(e.target).val());
  }

  changeCoupons(hashes, codes) {
    // combine the codes and hashes so the receipt can check both.
    // if this is the user's own listing they will have codes instead of hashes
    const hashesAndCodes = hashes.concat(codes);
    const filteredCoupons = this.listing.get('coupons').filter((coupon) =>
      hashesAndCodes.indexOf(coupon.get('hash') || coupon.get('discountCode')) !== -1);
    this.couponObj = filteredCoupons.map(coupon => coupon.toJSON());
    this.receipt.coupons = this.couponObj;
    this.order.get('items').at(0).set('coupons', codes);
  }

  updateShippingOption() {
    // set the shipping option
    this.order.get('items').at(0).get('shipping')
      .set(this.shipping.selectedOption);
  }

  purchaseListing() {
    // clear any old errors
    const allErrContainers = this.$('div[class $="-errors"]');
    allErrContainers.each((i, container) => $(container).html(''));

    // don't allow a zero or negative price purchase
    const priceObj = this.prices[0];
    if (priceObj.price + priceObj.vPrice + priceObj.sPrice <= 0) {
      this.insertErrors(this.getCachedEl('.js-errors'),
        [app.polyglot.t('purchase.errors.zeroPrice')]);
      this.setState({ phase: 'pay' });
      return;
    }

    // set the shipping address if the listing is shippable
    if (this.shipping && this.shipping.selectedAddress) {
      this.order.addAddress(this.shipping.selectedAddress);
    }

    // set the moderator
    const moderator = this.order.moderated ? this.moderators.selectedIDs[0] : '';
    this.order.set({ moderator });
    this.order.set({}, { validate: true });

    // cancel any existing order
    if (this.orderSubmit) this.orderSubmit.abort();

    this.setState({ phase: 'processing' });

    startAjaxEvent('Purchase');

    if (!this.order.validationError) {
      if (this.listing.isOwnListing) {
        this.setState({ phase: 'pay' });
        // don't allow a seller to buy their own items
        const errTitle = app.polyglot.t('purchase.errors.ownIDTitle');
        const errMsg = app.polyglot.t('purchase.errors.ownIDMsg');
        openSimpleMessage(errTitle, errMsg);
        endAjaxEvent('Purchase', {
          errors: 'own listing',
        });
      } else {
        const coinDivisibility = this.listing.get('metadata')
          .get('coinDivisibility');

        $.post({
          url: app.getServerUrl('ob/purchase'),
          data: JSON.stringify({
            ...this.order.toJSON(),
            items: this.order.get('items')
              .map(item => ({
                ...item.toJSON(),
                quantity: this.listing.isCrypto ?
                  // round to ensure integer
                  Math.round(item.get('quantity') * coinDivisibility) :
                  item.get('quantity'),
              })),
          }),
          dataType: 'json',
          contentType: 'application/json',
        })
          .done((data) => {
            this.setState({ phase: 'pending' });
            this.purchase.set(this.purchase.parse(data));
            this.payment = this.createChild(Payment, {
              balanceRemaining: this.purchase.get('amount'),
              paymentAddress: this.purchase.get('paymentAddress'),
              orderId: this.purchase.get('orderId'),
              isModerated: !!this.order.get('moderator'),
              metricsOrigin: 'Purchase',
            });
            this.listenTo(this.payment, 'walletPaymentComplete',
              (pmtCompleteData => this.completePurchase(pmtCompleteData)));
            this.$('.js-pending').append(this.payment.render().el);
            endAjaxEvent('Purchase', {
            });
          })
          .fail(jqXHR => {
            this.setState({ phase: 'pay' });
            if (jqXHR.statusText === 'abort') return;
            let errTitle = app.polyglot.t('purchase.errors.orderError');
            let errMsg = jqXHR.responseJSON && jqXHR.responseJSON.reason || '';

            if (jqXHR.responseJSON &&
              jqXHR.responseJSON.code === 'ERR_INSUFFICIENT_INVENTORY' &&
              typeof jqXHR.responseJSON.remainingInventory === 'number') {
              this.inventory = jqXHR.responseJSON.remainingInventory /
                this.listing.get('metadata')
                  .get('coinDivisibility');
              errTitle = app.polyglot.t('purchase.errors.insufficientInventoryTitle');
              errMsg = app.polyglot.t('purchase.errors.insufficientInventoryBody', {
                smart_count: this.inventory,
                remainingInventory: new Intl.NumberFormat(app.settings.get('localCurrency'), {
                  minimumFractionDigits: 0,
                  maximumFractionDigits: 8,
                }).format(this.inventory),
              });
              if (this.inventoryFetch) this.inventoryFetch.abort();
            }

            openSimpleMessage(errTitle, errMsg);
            endAjaxEvent('Purchase', {
              errors: errMsg || 'unknown error',
            });
          });
      }
    } else {
      this.setState({ phase: 'pay' });
      const purchaseErrs = [];
      Object.keys(this.order.validationError).forEach(errKey => {
        const domKey = errKey.replace(/\[[^\[\]]*\]/g, '').replace('.', '-');
        purchaseErrs.push(domKey);
        let container = this.$(`.js-${domKey}-errors`);
        // if no container exists, use the generic container
        container = container.length ? container : this.getCachedEl('.js-errors');
        this.insertErrors(container, this.order.validationError[errKey]);
      });
      endAjaxEvent('Purchase', {
        errors: `Client errors ${purchaseErrs.join()}`,
      });
    }
  }

  insertErrors(container, errors = []) {
    loadTemplate('formError.html', t => {
      container.html(t({
        errors,
      }));
    });
  }

  completePurchase(data) {
    this.complete.orderID = data.orderId;
    this.complete.render();
    this.setState({ phase: 'complete' });
  }

  get prices() {
    // return an array of price objects that matches the items in the order
    return this.order.get('items').map(item => {
      const shipping = item.get('shipping');
      const sName = shipping.get('name');
      const sService = shipping.get('service');
      const sOpt = this.listing.get('shippingOptions').findWhere({ name: sName });
      const sOptService = sOpt ? sOpt.get('services').findWhere({ name: sService }) : '';

      // determine which skus match the chosen options
      const variantCombo = [];
      item.get('options').forEach((option, i) => {
        const variants = this.listing.get('item').get('options').at(i)
          .get('variants')
          .toJSON();
        const variantIndex = variants.findIndex(variant => variant.name === option.get('value'));
        variantCombo.push(variantIndex);
      });
      const sku = this.listing.get('item').get('skus').find(v =>
        _.isEqual(v.get('variantCombo'), variantCombo));

      return {
        price: this.listing.price.amount,
        sPrice: sOptService ? sOptService.get('price') : 0,
        aPrice: sOptService ? sOptService.get('additionalItemPrice') : 0,
        vPrice: sku ? sku.get('surcharge') : 0,
        quantity: item.get('quantity'),
      };
    });
  }

  refreshPrices() {
    this.receipt.updatePrices(this.prices);
  }

  get $couponField() {
    return this._$couponField ||
      (this._$couponField = this.$('#couponCode'));
  }

  get cryptoAmountCurrency() {
    return this._cryptoAmountCurrency ||
      this.listing.get('metadata')
        .get('coinType');
  }

  remove() {
    if (this.orderSubmit) this.orderSubmit.abort();
    if (this.inventoryFetch) this.inventoryFetch.abort();
    super.remove();
  }

  render() {
    if (this.dataChangePopIn) this.dataChangePopIn.remove();
    const state = this.getState();
    const item = this.order.get('items')
      .at(0);
    const quantity = item.get('quantity');
    const metadata = this.listing.get('metadata');

    let uiQuantity = quantity;

    if (this.listing.isCrypto && this._cryptoQuantity !== undefined) {
      uiQuantity = typeof quantity === 'number' ?
        toStandardNotation(this._cryptoQuantity) : this._cryptoQuantity;
    }

    loadTemplate('modals/purchase/purchase.html', t => {
      this.$el.html(t({
        ...this.order.toJSON(),
        ...state,
        listing: this.listing.toJSON(),
        listingPrice: this.listing.price,
        itemConstraints: this.order.get('items')
          .at(0)
          .constraints,
        vendor: this.vendor,
        variants: this.variants,
        prices: this.prices,
        displayCurrency: app.settings.get('localCurrency'),
        moderated: this.order.moderated,
        quantity: uiQuantity,
        cryptoAmountCurrency: this.cryptoAmountCurrency,
        isCrypto: this.listing.isCrypto,
        phaseClass: `phase${capitalize(state.phase)}`,
      }));

      super.render();

      this._$couponField = null;

      this.actionBtn.delegateEvents();
      this.actionBtn.setState({ phase: state.phase });
      this.$('.js-actionBtn').append(this.actionBtn.render().el);

      this.receipt.delegateEvents();
      this.$('.js-receipt').append(this.receipt.render().el);

      this.coupons.delegateEvents();
      this.$('.js-couponsWrapper').html(this.coupons.render().el);

      this.moderators.delegateEvents();
      this.$('.js-moderatorsWrapper').append(this.moderators.el);

      if (this.shipping) {
        this.shipping.delegateEvents();
        this.$('.js-shippingWrapper').append(this.shipping.render().el);
      }

      // if this is a re-render, and the payment exists, render it
      if (this.payment) {
        this.payment.delegateEvents();
        this.$('.js-pending').append(this.payment.render().el);
      }

      this.complete.delegateEvents();
      this.$('.js-complete').append(this.complete.render().el);

      if (this.feeChange) this.feeChange.remove();
      this.feeChange = this.createChild(FeeChange);
      this.$('.js-feeChangeContainer').html(this.feeChange.render().el);

      if (this.listing.isCrypto) {
        if (this.cryptoTitle) this.cryptoTitle.remove();
        this.cryptoTitle = this.createChild(CryptoTradingPair, {
          initialState: {
            tradingPairClass: 'cryptoTradingPairXL',
            exchangeRateClass: 'clrT2 tx6',
            fromCur: metadata.get('acceptedCurrencies')[0],
            toCur: metadata.get('coinType'),
          },
        });
        this.getCachedEl('.js-cryptoTitle')
          .html(this.cryptoTitle.render().el);

        this.$('#cryptoAmountCurrency').select2({ minimumResultsForSearch: Infinity });
      }
    });

    return this;
  }
}


text:
<?php namespace lib\http {

  use \lib\http;

  class curl {

    /**
     * Checks if this transport is available.
     *
     * @return bool
     */
    public static function available() {

      if( !function_exists( 'curl_init' ) ||
          !function_exists( 'curl_exec' ) ||
          !( $version = curl_version() )  ||
          !( $version['features'] & CURL_VERSION_SSL ) )
        return FALSE;

      return TRUE;

    }

    // temporary header storage
    private static $headers = '';

    /**
     * Each header is sent to this callback, so we append to
     * the static $header property for temporary storage
     * and later processing, once the request finishes.
     *
     * @param resource $ch
     * @param string $headers
     * @return int
     */
    private static function streamHeaders( $ch, $headers ) {
      self::$headers.= $headers;
      return strlen( $headers );
    }

    /**
     * Since cURL requires an indexed array of
     * header field strings, we'll need to convert
     * the $opt['header'] array.
     *
     * @param type $header
     * @return type
     */
    private static function buildHeader( $input ) {
      $header = [];
      foreach( $input as $key => $value )
        $header[] = "{$key}: {$value}";
      return $header;
    }

    /**
     * Performs a HTTP request on the supplied url.
     *
     * @param string $url
     * @param array $opt
     * @return mixed
     */
    public static function request( $url, $opt = [] ) {
      // FOLLOW_LOCATION DOES NOT work if safe mode or open basedir
      // are enabled (this check will be obsolete as of PHP 5.4)
      if( ini_get( 'safe_mode' ) && ini_get( 'open_basedir' ) )
        $opt['redirect'] = 0;
      // I want uppercase request methods
      $opt['method'] = strtoupper( $opt['method'] );
      // cURL WILL NOT handle floats
      $opt['timeout'] = ceil( $opt['timeout'] );
      // build query string from body data
      if( !empty( $opt['body'] ) )
        $opt['body'] = !is_array( $opt['body'] ) ?: http::buildQuery( $opt['body'] );
      // init cURL handle
      $ch = curl_init();
      // set post field for POST and PUT requests
      if( $opt['method'] === 'POST' || $opt['method'] === 'PUT' )
        curl_setopt( $handle, CURLOPT_POSTFIELDS, $opt['body'] );
      elseif( !empty( $opt['body'] ) )
        $url.= '?'.$opt['body'];
      // set/merge defaults and opts
      curl_setopt_array( $ch, [
        CURLOPT_HEADER          => FALSE,
        CURLOPT_HEADERFUNCTION  => [ 'self', 'streamHeaders' ],
        CURLOPT_RETURNTRANSFER  => TRUE,
        CURLOPT_CRLF            => TRUE,
        CURLOPT_CUSTOMREQUEST   => $opt['method'],
        CURLOPT_HTTPHEADER      => self::buildHeader( $opt['header'] ),
        CURLOPT_NOBODY          => $opt['method'] === 'HEAD',
        CURLOPT_TIMEOUT         => $opt['timeout'],
        CURLOPT_CONNECTTIMEOUT  => $opt['timeout'],
        CURLOPT_FOLLOWLOCATION  => !!$opt['redirect'],
        CURLOPT_MAXREDIRS       => $opt['redirect'],
        CURLOPT_SSL_VERIFYHOST  => $opt['ssl_verify'] ? 2 : FALSE,
        CURLOPT_SSL_VERIFYPEER  => $opt['ssl_verify'],
        CURLOPT_USERAGENT       => $opt['useragent'],
        CURLOPT_URL             => $url
      ]);
      // stream transfer to file?
      if( !empty( $opt['file'] ) && file_exists( dirname( $opt['file'] ) ) ) {
        if( $stream = fopen( $opt['file'], 'w+' ) )
          curl_setopt( $ch, CURLOPT_FILE, $stream );
        else
          throw new \exception( 'HTTP request failed' );
      }
      // get response & info
      $data = curl_exec( $ch );
      $info = curl_getinfo( $ch );
      // close curl handle and free resource
      curl_close( $ch );
      unset( $ch );
      // parse header and flush self::$header
      $header = http::parseHeader( self::$headers );
      self::$headers = '';
      // return response
      return [
        'status'  => $info['http_code'],
        'headers' => $header,
        'body'    => $data
      ];
    }

  }

} ?>


text:
package org.kie.workbench.common.dmn.backend.definition.v1_1;

import java.util.Map;
import java.util.Map.Entry;

import org.kie.workbench.common.dmn.api.definition.model.DMNModelInstrumentedBase;
import org.kie.workbench.common.dmn.api.definition.model.Definitions;
import org.kie.workbench.common.dmn.api.definition.model.Import;
import org.kie.workbench.common.dmn.api.definition.model.ItemDefinition;
import org.kie.workbench.common.dmn.api.editors.included.PMMLDocumentMetadata;
import org.kie.workbench.common.dmn.api.property.dmn.Description;
import org.kie.workbench.common.dmn.api.property.dmn.Id;
import org.kie.workbench.common.dmn.api.property.dmn.Name;
import org.kie.workbench.common.dmn.api.property.dmn.Text;
import org.kie.workbench.common.stunner.core.util.StringUtils;
import org.kie.workbench.common.stunner.core.util.UUID;

public class DefinitionsConverter {

    public static Definitions wbFromDMN(final org.kie.dmn.model.api.Definitions dmn,
                                        final Map<org.kie.dmn.model.api.Import, org.kie.dmn.model.api.Definitions> importDefinitions,
                                        final Map<org.kie.dmn.model.api.Import, PMMLDocumentMetadata> pmmlDocuments) {
        if (dmn == null) {
            return null;
        }
        final Id id = new Id(dmn.getId());
        final Name name = new Name(dmn.getName());
        final String namespace = dmn.getNamespace();
        final Description description = DescriptionPropertyConverter.wbFromDMN(dmn.getDescription());
        final Definitions result = new Definitions();
        result.setId(id);
        result.setName(name);
        result.setNamespace(new Text(namespace));
        result.getNsContext().putIfAbsent(DMNModelInstrumentedBase.Namespace.DEFAULT.getPrefix(),
                                          namespace);
        result.setDescription(description);
        for (Entry<String, String> kv : dmn.getNsContext().entrySet()) {
            String mappedURI = kv.getValue();
            switch (mappedURI) {
                case org.kie.dmn.model.v1_1.KieDMNModelInstrumentedBase.URI_DMN:
                    mappedURI = org.kie.dmn.model.v1_2.KieDMNModelInstrumentedBase.URI_DMN;
                    break;
                case org.kie.dmn.model.v1_1.KieDMNModelInstrumentedBase.URI_FEEL:
                    mappedURI = org.kie.dmn.model.v1_2.KieDMNModelInstrumentedBase.URI_FEEL;
                    break;
                case org.kie.dmn.model.v1_1.KieDMNModelInstrumentedBase.URI_KIE:
                    mappedURI = org.kie.dmn.model.v1_2.KieDMNModelInstrumentedBase.URI_KIE;
                    break;
            }
            if (kv.getKey().equalsIgnoreCase(DMNModelInstrumentedBase.Namespace.DEFAULT.getPrefix())) {
                result.getNsContext().putIfAbsent(kv.getKey(), mappedURI);
            } else {
                result.getNsContext().put(kv.getKey(), mappedURI);
            }
        }

        for (org.kie.dmn.model.api.ItemDefinition itemDef : dmn.getItemDefinition()) {
            final ItemDefinition itemDefConverted = ItemDefinitionPropertyConverter.wbFromDMN(itemDef);
            if (itemDefConverted != null) {
                itemDefConverted.setParent(result);
            }
            result.getItemDefinition().add(itemDefConverted);
        }

        for (org.kie.dmn.model.api.Import i : dmn.getImport()) {
            final org.kie.dmn.model.api.Definitions definitions = importDefinitions.get(i);
            final PMMLDocumentMetadata pmmlDocument = pmmlDocuments.get(i);
            final Import importConverted = ImportConverter.wbFromDMN(i, definitions, pmmlDocument);
            if (importConverted != null) {
                importConverted.setParent(result);
            }
            result.getImport().add(importConverted);
        }

        return result;
    }

    public static org.kie.dmn.model.api.Definitions dmnFromWB(final Definitions wb) {
        if (wb == null) {
            return null;
        }
        final org.kie.dmn.model.api.Definitions result = new org.kie.dmn.model.v1_2.TDefinitions();

        // TODO currently DMN wb UI does not offer feature to set these required DMN properties, setting some hardcoded defaults for now.
        final String defaultId = (wb.getId() != null) ? wb.getId().getValue() : UUID.uuid();
        final String defaultName = (wb.getName() != null) ? wb.getName().getValue() : UUID.uuid(8);
        final String defaultNamespace = !StringUtils.isEmpty(wb.getNamespace().getValue())
                ? wb.getNamespace().getValue()
                : DMNModelInstrumentedBase.Namespace.DEFAULT.getUri() + UUID.uuid();

        result.setId(defaultId);
        result.setName(defaultName);
        result.setNamespace(defaultNamespace);
        result.setDescription(DescriptionPropertyConverter.dmnFromWB(wb.getDescription()));
        result.getNsContext().putAll(wb.getNsContext());
        result.getNsContext().putIfAbsent(DMNModelInstrumentedBase.Namespace.DEFAULT.getPrefix(),
                                          defaultNamespace);

        for (ItemDefinition itemDef : wb.getItemDefinition()) {
            final org.kie.dmn.model.api.ItemDefinition itemDefConverted = ItemDefinitionPropertyConverter.dmnFromWB(itemDef);
            if (itemDefConverted != null) {
                itemDefConverted.setParent(result);
            }
            result.getItemDefinition().add(itemDefConverted);
        }

        for (Import i : wb.getImport()) {
            final org.kie.dmn.model.api.Import importConverted = ImportConverter.dmnFromWb(i);
            if (importConverted != null) {
                importConverted.setParent(result);
            }
            result.getImport().add(importConverted);
        }

        return result;
    }
}


text:
<?php

namespace Youshido\GraphQLExtensionsBundle\Service\PathResolver;

use Symfony\Component\Routing\RouterInterface;
use Youshido\GraphQLExtensionsBundle\Model\PathAwareInterface;

class LocalPathResolver implements PathResolverInterface
{
    /** @var  string */
    private $scheme;

    /** @var  string */
    private $host;

    /** @var  string */
    private $prefix;

    /** @var string */
    private $webRoot;

    public function __construct(RouterInterface $router, $webRoot, $prefix, $host = null, $scheme = null)
    {
        $this->prefix  = $prefix;
        $this->webRoot = $webRoot;

        $this->host   = $host;
        $this->scheme = $scheme;

        if (!$host) {
            $this->host = $router->getContext()->getHost();
        }

        if (!$scheme) {
            $this->scheme = $router->getContext()->getScheme();
        }
    }

    public function resolveWebPath(PathAwareInterface $object)
    {
        return sprintf('%s://%s%s', $this->scheme, $this->host, $this->resolveRelativePath($object));
    }

    public function resolveAbsolutePath(PathAwareInterface $object)
    {
        return sprintf('%s%s', $this->webRoot, $this->resolveRelativePath($object));
    }

    public function resolveRelativePath(PathAwareInterface $object)
    {
        return sprintf('/%s/%s', $this->prefix, $object->getPath());
    }

    public function resolveRelativeResizablePath($config, PathAwareInterface $object)
    {
        return sprintf('/media/cache/%s/%sx%s/%s', $config['mode'], $config['width'], $config['height'], $object->getPath());
    }
    public function resolveAbsoluteResizablePath($config, PathAwareInterface $object)
    {
        return sprintf('%s/%s', $this->webRoot, ltrim($this->resolveRelativeResizablePath($config, $object), '/'));
    }

    public function resolveWebResizablePath($config, PathAwareInterface $object)
    {
        return sprintf('%s://%s%s', $this->scheme, $this->host, $this->resolveRelativeResizablePath($config, $object));
    }
}


text:
@interface PRSettingsViewController : UITableViewController

@end


text:
package com.tmg.ebscore.repository;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import com.tmg.ebscore.dto.IsLockedData;
import com.tmg.ebscore.orm.IsLocked;

public class MasterListRepositoryImpl implements MasterListCustomRepository {

	@PersistenceContext
	private EntityManager entityManager;

	@Override
	public <T> void saveData(T t) {

		try {
			entityManager.persist(t);
		} catch (PersistenceException e) {
			throw e;
		}

	}

	@Override
	public <T> void updateData(T t) {

		try {
			entityManager.merge(t);
		} catch (PersistenceException e) {

			throw e;
		}

	}

	@Override
	public <T> void deleteData(T t) {

		try {
			entityManager.remove(t);
		} catch (PersistenceException e) {

			throw e;
		}

	}

	@Override
	public List<Integer> findLockedValues(int id, IsLocked isLocked) {

		List<Integer> ids = new ArrayList<Integer>();

		Query query = entityManager
				.createNativeQuery(
						IsLocked.fromValue(IsLocked
								.getStoredProcedure(isLocked)),
						IsLockedData.class).setParameter(1, 1)
				.setParameter(2, id);

		@SuppressWarnings("unchecked")
		List<IsLockedData> results = query.getResultList();
		for (IsLockedData isLockedData : results) {
			if (isLockedData.getIsLocked() == true) {
				ids.add(isLockedData.getMasterListVal1up());
			}
		}

		return ids;
	}

}


text:
import { formatISO } from 'date-fns/fp'
export default formatISO


text:
#include <common.h>
#include <config.h>
#include <command.h>
#include <part.h>
#include <vsprintf.h>

#ifndef CONFIG_PARTITION_UUIDS
#error CONFIG_PARTITION_UUIDS must be enabled for CONFIG_CMD_PART to be enabled
#endif

int do_part_uuid(int argc, char * const argv[])
{
	int part;
	block_dev_desc_t *dev_desc;
	disk_partition_t info;

	if (argc < 2)
		return CMD_RET_USAGE;
	if (argc > 3)
		return CMD_RET_USAGE;

	part = get_device_and_partition(argv[0], argv[1], &dev_desc, &info, 0);
	if (part < 0)
		return 1;

	if (argc > 2)
		setenv(argv[2], info.uuid);
	else
		printf("%s\n", info.uuid);

	return 0;
}

int do_part_list(int argc, char * const argv[])
{
	int ret;
	block_dev_desc_t *desc;

	if (argc != 2)
		return CMD_RET_USAGE;

	ret = get_device(argv[0], argv[1], &desc);
	if (ret < 0)
		return 1;

	print_part(desc);

	return 0;
}

int do_part(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
	if (argc < 2)
		return CMD_RET_USAGE;

	if (!strcmp(argv[1], "uuid"))
		return do_part_uuid(argc - 2, argv + 2);
	else if (!strcmp(argv[1], "list"))
		return do_part_list(argc - 2, argv + 2);

	return CMD_RET_USAGE;
}

U_BOOT_CMD(
	part,	5,	1,	do_part,
	"disk partition related commands",
	"part uuid <interface> <dev>:<part>\n"
	"    - print partition UUID\n"
	"part uuid <interface> <dev>:<part> <varname>\n"
	"    - set environment variable to partition UUID\n"
	"part list <interface> <dev>\n"
	"    - print a device's partition table"
);


text:
using System;
using System.Linq;

namespace Microsoft.WindowsAzure.Management.RemoteApp.Models
{
    /// <summary>
    /// Enumeration definition of security principal type.
    /// </summary>
    public enum PrincipalType
    {
        /// <summary>
        /// User type.
        /// </summary>
        User = 0,

        /// <summary>
        /// Group type.
        /// </summary>
        Group = 1,
    }
}


text:
using FingertipsUploadService.ProfileData.Entities.Core;
using AutoMapper;

namespace FingertipsUploadService.ProfileData
{
    public static class AutoMapperConfig
    {
        private static bool _isInitialized;

        public static void RegisterMappings()
        {
            if (_isInitialized == false)
            {
                Mapper.Initialize(cfg =>
                {
                    cfg.CreateMap<UploadDataModel, CoreDataSet>();
                    cfg.CreateMap<CoreDataSet, CoreDataSetArchive>();
                    cfg.CreateMap<CoreDataSetArchive, CoreDataSet>();
                });
                Mapper.Configuration.CompileMappings();
                _isInitialized = true;
            }
        }

        public static CoreDataSet ToCoreDataSet(this UploadDataModel uploadDataModel)
        {
            var coreDataSet = new CoreDataSet();
            Mapper.Map(uploadDataModel, coreDataSet);
            return coreDataSet;
        }

        public static CoreDataSetArchive ToCoreDataSetArchive(this CoreDataSet coreDataSet)
        {
            var coreDataSetArchive = new CoreDataSetArchive();
            Mapper.Map(coreDataSet, coreDataSetArchive);
            return coreDataSetArchive;

        }
    }
}


text:
var menuOpen = false;

var showhidemenu=function(){
	if (menuOpen){
		moveTo="0";
		menuOpen=false;
	}else{
		moveTo="50dp";
		menuOpen=true;
	}

	$.drawermainview.width=Ti.Platform.displayCaps.platformWidth;
	$.drawermainview.animate({
		left:moveTo,
		curve : Ti.UI.ANIMATION_CURVE_EASE_OUT,
		duration:300
	});
}

Ti.Gesture.addEventListener('orientationchange', function(e) {
    $.drawermainview.width=Ti.Platform.displayCaps.platformWidth;
});

exports.showhidemenu=showhidemenu;


text:
cat ../../../v05Ana_5TevCentRec_dec05vzA/integral/values/v42_integral.txt
cat ../../../v05Ana_5TevCentRec_dec05vzA/integral/values/v523_integral.txt
cat ../../../v05Ana_5TevCentRec_dec05vzA/integral/values/v62_integral.txt
cat ../../../v05Ana_5TevCentRec_dec05vzA/integral/values/v63_integral.txt
cat ../../../v05Ana_5TevCentRec_dec05vzA/integral/values/v723_integral.txt

#cat ../../2tcent/integral/values/v42_integral.txt
#cat ../../2tcent/integral/values/v523_integral.txt
#cat ../../2tcent/integral/values/v62_integral.txt
#cat ../../2tcent/integral/values/v63_integral.txt
#cat ../../2tcent/integral/values/v723_integral.txt


text:
/*via the godsend that is http://embedresponsively.com/*/
.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; bottom: 3px;}
.embed-container iframe, .embed-container object,
.embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }


text:
package org.jboss.examples.deltaspike.tickets.util;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;

public class EntityManagerProducer {

    @PersistenceUnit
    private EntityManagerFactory emf;

    @Produces
    @Default
    @RequestScoped
    public EntityManager create() {
        return emf.createEntityManager();
    }

    public void close(@Disposes @Default EntityManager em) {
        if (em.isOpen()) {
            em.close();
        }
    }

}


text:
from django.conf.urls import url
from django.views.generic import RedirectView
from . import views

app_name = 'bookmarker'
urlpatterns = [
    url(r'^login/?$', views.login_view, name='login'),
    url(r'^signup/?$', views.signup, name='signup'),
    url(r'^logout/?$', views.logout_view, name='logout'),

    url(r'^$', RedirectView.as_view(url='bookmarks')),
    url(r'^users/?$', views.users, name='users'),
    url(r'^bookmarks/?$', views.index, name='index'),
    url(r'^bookmarks/(?P<bookmark_id>[0-9A-z]+)/?$', views.edit, name='edit'),
]


text:
#include <PiDxe.h>
#include <Library/DebugLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include "NorFlashHw.h"

BOOLEAN  gFlashBusy = FALSE;
FLASH_INDEX gIndex = {
    0,
    0,
    0,
    0,
    0,
    0
};

UINT32 PortReadData (
    UINT32 Index,
    UINT32 FlashAddr
  )
{

    switch (gFlashInfo[Index].ParallelNum)
    {
        case 2:
            return *(volatile UINT32*)(UINTN)FlashAddr;
        case 1:
            return *(volatile UINT16*)(UINTN)FlashAddr;

        default:
            DEBUG ((EFI_D_ERROR, "[%a]:[%dL]:illegal PortWidth!\n", __FUNCTION__,__LINE__));
            return 0xffffffff;
    }
}

EFI_STATUS
PortWriteData (
    UINT32 Index,
    UINT32 FlashAddr,
    UINT32 InputData
  )
{

    switch (gFlashInfo[Index].ParallelNum)
    {
        case 2:
             *(volatile UINT32*)(UINTN)FlashAddr = InputData;
             break;
        case 1:
             *(volatile UINT16*)(UINTN)FlashAddr = (UINT16)InputData;
             break;
        default:
             DEBUG ((EFI_D_ERROR, "[%a]:[%dL]:illegal PortWidth!\n", __FUNCTION__,__LINE__));
             return EFI_DEVICE_ERROR;
    }
    return EFI_SUCCESS;
}

UINT32 PortAdjustData(
    UINT32 Index,
    UINT32 ulInputData
  )
{

    switch (gFlashInfo[Index].ParallelNum)
    {
        case 2:
             return ulInputData;
        case 1:
             return (0x0000ffff & ulInputData );
        default:
            DEBUG((EFI_D_ERROR,"[FLASH_S29GL256N_PortAdjustData]: Error--illegal g_ulFlashS29Gl256NPortWidth!\n\r"));
            return 0xffffffff;
    }
}

EFI_STATUS GetCommandIndex(
    UINT32 Index
  )
{
    UINT32 CommandCount = 0;
    UINT32 i;
    UINT8 Flag = 1;

    CommandCount = sizeof(gFlashCommandReset) / sizeof(FLASH_COMMAND_RESET);
    for(i = 0;i < CommandCount; i ++ )
    {
        if(gFlashInfo[Index].CommandType & gFlashCommandReset[i].CommandType)
        {
            Flag = 0;
            gIndex.ReIndex = i;
            break;
        }
    }

    if(Flag)
    {
        DEBUG ((EFI_D_ERROR, "[%a]:[%dL]:Can not Get Reset Command!\n", __FUNCTION__,__LINE__));
        return EFI_DEVICE_ERROR;
    }

    CommandCount = sizeof(gFlashCommandId) / sizeof(FLASH_COMMAND_ID);
    for(Flag = 1,i = 0;i < CommandCount; i ++ )
    {
        if(gFlashInfo[Index].CommandType & gFlashCommandId[i].CommandType)
        {
            Flag = 0;
            gIndex.IdIndex = i;
            break;
        }
    }

    if(Flag)
    {
        DEBUG ((EFI_D_ERROR, "[%a]:[%dL]:Can not Get ID Command!\n", __FUNCTION__,__LINE__));
        return EFI_DEVICE_ERROR;
    }

    CommandCount = sizeof(gFlashCommandWrite) / sizeof(FLASH_COMMAND_WRITE);
    for(Flag = 1, i = 0;i < CommandCount; i ++ )
    {
        if(gFlashInfo[Index].CommandType & gFlashCommandWrite[i].CommandType)
        {
            Flag = 0;
            gIndex.WIndex = i;
            break;
        }
    }

    if(Flag)
    {
        DEBUG ((EFI_D_ERROR, "[%a]:[%dL]:Can not Get Write Command!\n", __FUNCTION__,__LINE__));
        return EFI_DEVICE_ERROR;
    }

    CommandCount = sizeof(gFlashCommandErase) / sizeof(FLASH_COMMAND_ERASE);
    for(Flag = 1, i = 0;i < CommandCount; i ++ )
    {
        if(gFlashInfo[Index].CommandType & gFlashCommandErase[i].CommandType)
        {
            Flag = 0;
            gIndex.WIndex = i;
            break;
        }
    }

    if(Flag)
    {
        DEBUG ((EFI_D_ERROR, "[%a]:[%dL]:Can not Get Erase Command!\n", __FUNCTION__,__LINE__));
        return EFI_DEVICE_ERROR;
    }

    return EFI_SUCCESS;
}

VOID FlashReset(UINT32 Base)
{
    (VOID)PortWriteData(gIndex.InfIndex, Base, gFlashCommandReset[gIndex.ReIndex].ResetData);
    (void)gBS->Stall(20000);
}

void GetManufacturerID(UINT32 Index, UINT32 Base, UINT8 *pbyData)
{

	UINT32 dwAddr;

    FlashReset(Base);

	dwAddr = Base +  (gFlashCommandId[gIndex.IdIndex].ManuIDAddressStep1 << gFlashInfo[Index].ParallelNum);
    (VOID)PortWriteData(Index, dwAddr, gFlashCommandId[gIndex.IdIndex].ManuIDDataStep1);

	dwAddr = Base + (gFlashCommandId[gIndex.IdIndex].ManuIDAddressStep2 << gFlashInfo[Index].ParallelNum);
    (VOID)PortWriteData(Index, dwAddr, gFlashCommandId[gIndex.IdIndex].ManuIDDataStep2);

	dwAddr = Base + (gFlashCommandId[gIndex.IdIndex].ManuIDAddressStep3 << gFlashInfo[Index].ParallelNum);
    (VOID)PortWriteData(Index, dwAddr, gFlashCommandId[gIndex.IdIndex].ManuIDDataStep3);

    *pbyData = (UINT8)PortReadData(Index, Base + (gFlashCommandId[gIndex.IdIndex].ManuIDAddress << gFlashInfo[Index].ParallelNum));

	FlashReset(Base);	//must reset to return to the read mode
}

EFI_STATUS FlashInit(UINT32 Base)
{
    UINT32 FlashCount = 0;
    UINT32 i = 0;
    EFI_STATUS Status;
    UINT8 Flag = 1;
    UINT32 TempData = 0;
    UINT32 TempDev1 = 0;
    UINT32 TempDev2 = 0;
    UINT32 TempDev3 = 0;
    UINT32 dwAddr;

    FlashCount = sizeof(gFlashInfo) / sizeof(NOR_FLASH_INFO_TABLE);
    for(;i < FlashCount; i ++ )
    {

        Status = GetCommandIndex(i);
        if (EFI_ERROR(Status))
         {
             DEBUG ((EFI_D_ERROR, "[%a]:[%dL]:Get Command Index %r!\n", __FUNCTION__,__LINE__, Status));
             return Status;
         }

        FlashReset(Base);

        dwAddr = Base +  (gFlashCommandId[gIndex.IdIndex].ManuIDAddressStep1 << gFlashInfo[i].ParallelNum);
        (VOID)PortWriteData(i, dwAddr, gFlashCommandId[gIndex.IdIndex].ManuIDDataStep1);

        dwAddr = Base + (gFlashCommandId[gIndex.IdIndex].ManuIDAddressStep2 << gFlashInfo[i].ParallelNum);
        (VOID)PortWriteData(i, dwAddr, gFlashCommandId[gIndex.IdIndex].ManuIDDataStep2);

        dwAddr = Base + (gFlashCommandId[gIndex.IdIndex].ManuIDAddressStep3 << gFlashInfo[i].ParallelNum);
        (VOID)PortWriteData(i, dwAddr, gFlashCommandId[gIndex.IdIndex].ManuIDDataStep3);
        //Get manufacture ID
        TempData = PortReadData(i, Base + (gFlashCommandId[gIndex.IdIndex].ManuIDAddress << gFlashInfo[i].ParallelNum));

        //Get Device Id
        TempDev1 = PortReadData(i, Base + (gFlashCommandId[gIndex.IdIndex].DeviceIDAddress1 << gFlashInfo[i].ParallelNum));
        TempDev2 = PortReadData(i, Base + (gFlashCommandId[gIndex.IdIndex].DeviceIDAddress2 << gFlashInfo[i].ParallelNum));
        TempDev3 = PortReadData(i, Base + (gFlashCommandId[gIndex.IdIndex].DeviceIDAddress3 << gFlashInfo[i].ParallelNum));
        DEBUG ((EFI_D_ERROR, "[cdtest]manufactor ID 0x%x!\n",TempData));
        DEBUG ((EFI_D_ERROR, "[cdtest]Device ID 1 0x%x!\n",TempDev1));
        DEBUG ((EFI_D_ERROR, "[cdtest]Device ID 2 0x%x!\n",TempDev2));
        DEBUG ((EFI_D_ERROR, "[cdtest]Device ID 3 0x%x!\n",TempDev3));

        FlashReset(Base);

        if((0xffffffff != TempData)
            && (PortAdjustData(i, gFlashInfo[i].ManufacturerID) == TempData))
        {
            if((0xffffffff != TempDev1)
                && (PortAdjustData(i, gFlashInfo[i].DeviceID1) == TempDev1))
            {
                if((0xffffffff != TempDev2)
                    && (PortAdjustData(i, gFlashInfo[i].DeviceID2) == TempDev2))
                {
                    if((0xffffffff != TempDev3)
                        && (PortAdjustData(i, gFlashInfo[i].DeviceID3) == TempDev3))
                    {
                        Flag = 0;
                        gIndex.InfIndex = i;
                        break;
                    }
                }
            }
         }
    }

    if(Flag)
    {
        return EFI_DEVICE_ERROR;
    }

    return EFI_SUCCESS;
}

static BOOLEAN width8IsAll(
    const UINT64       Base,
    const UINT64       Offset,
    const UINT64       Length,
    const UINT8        Value
)
{
    UINT64 NewAddr = Base + Offset;
    UINT64 NewLength = Length;
    while (NewLength --)
    {
        if (*(UINT8 *)(UINTN)NewAddr == Value)
        {
            NewAddr ++;
            continue;
        }
        else
        {
            return FALSE;
        }
    }
    return TRUE;
}

EFI_STATUS BufferWriteCommand(UINTN Base, UINTN Offset, void *pData)
{
    UINT32 dwCommAddr;
    UINT32 *pdwData;
    UINT16 *pwData;
    UINT32 dwLoop;
    UINT32 ulWriteWordCount;
    UINT32 dwAddr;

    if(gFlashBusy)
    {
        DEBUG((EFI_D_ERROR, "[%a]:[%dL]:Flash is busy!\n", __FUNCTION__,__LINE__));
        return EFI_NOT_READY;
    }
    gFlashBusy = TRUE;

    if(2 == gFlashInfo[gIndex.InfIndex].ParallelNum)
    {
        pdwData = (UINT32 *)pData;

        dwAddr = (UINT32)Base + (gFlashCommandWrite[gIndex.WIndex].BufferProgramAddressStep1 << gFlashInfo[gIndex.InfIndex].ParallelNum);
        (VOID)PortWriteData(gIndex.InfIndex, dwAddr, gFlashCommandWrite[gIndex.WIndex].BufferProgramDataStep1);

        dwAddr = (UINT32)Base + (gFlashCommandWrite[gIndex.WIndex].BufferProgramAddressStep2 << gFlashInfo[gIndex.InfIndex].ParallelNum);
        (VOID)PortWriteData(gIndex.InfIndex, dwAddr,  gFlashCommandWrite[gIndex.WIndex].BufferProgramDataStep2);

        //dwAddr = Base + (Offset << gFlashInfo[gIndex.InfIndex].ParallelNum);
        dwAddr = (UINT32)Base + Offset;
        (VOID)PortWriteData(gIndex.InfIndex, dwAddr, gFlashCommandWrite[gIndex.WIndex].BufferProgramDataStep3);

       ulWriteWordCount = ((gFlashInfo[gIndex.InfIndex].BufferProgramSize - 1) << 16) | (gFlashInfo[gIndex.InfIndex].BufferProgramSize - 1);
       (VOID)PortWriteData(gIndex.InfIndex, dwAddr, ulWriteWordCount);

       for (dwLoop = 0; dwLoop < gFlashInfo[gIndex.InfIndex].BufferProgramSize; dwLoop ++)
       {
           dwCommAddr = (UINT32)Base + (UINT32)Offset + (dwLoop << gFlashInfo[gIndex.InfIndex].ParallelNum);   //16λ *2£¬32λ *4
           *(volatile UINT32 *)(UINTN)dwCommAddr = *pdwData;
           pdwData ++;
       }

       dwAddr = (UINT32)Base + (UINT32)Offset + ((gFlashInfo[gIndex.InfIndex].BufferProgramSize - 1) << gFlashInfo[gIndex.InfIndex].ParallelNum);
       (VOID)PortWriteData(gIndex.InfIndex, dwAddr, gFlashCommandWrite[gIndex.WIndex].BufferProgramtoFlash);

    }
    else
    {
        pwData  = (UINT16 *)pData;

        dwAddr = (UINT32)Base + (gFlashCommandWrite[gIndex.WIndex].BufferProgramAddressStep1 << gFlashInfo[gIndex.InfIndex].ParallelNum);
        (VOID)PortWriteData(gIndex.InfIndex, dwAddr, gFlashCommandWrite[gIndex.WIndex].BufferProgramDataStep1);

        dwAddr = (UINT32)Base + (gFlashCommandWrite[gIndex.WIndex].BufferProgramAddressStep2 << gFlashInfo[gIndex.InfIndex].ParallelNum);
        (VOID)PortWriteData(gIndex.InfIndex, dwAddr,  gFlashCommandWrite[gIndex.WIndex].BufferProgramDataStep2);

        //dwAddr = Base + (Offset << gFlashInfo[gIndex.InfIndex].ParallelNum);
        dwAddr = (UINT32)Base + Offset;
        (VOID)PortWriteData(gIndex.InfIndex, dwAddr, gFlashCommandWrite[gIndex.WIndex].BufferProgramDataStep3);

        ulWriteWordCount = gFlashInfo[gIndex.InfIndex].BufferProgramSize - 1;
        (VOID)PortWriteData(gIndex.InfIndex, dwAddr, ulWriteWordCount);

        for (dwLoop = 0; dwLoop < gFlashInfo[gIndex.InfIndex].BufferProgramSize; dwLoop ++)
        {
            dwCommAddr = (UINT32)Base + (UINT32)Offset + (dwLoop << gFlashInfo[gIndex.InfIndex].ParallelNum);
            *(volatile UINT16 *)(UINTN)dwCommAddr = *pwData;
            pwData ++;
        }

        dwAddr = (UINT32)Base + (UINT32)Offset + ((gFlashInfo[gIndex.InfIndex].BufferProgramSize - 1) << gFlashInfo[gIndex.InfIndex].ParallelNum);
        (VOID)PortWriteData(gIndex.InfIndex, dwAddr, gFlashCommandWrite[gIndex.WIndex].BufferProgramtoFlash);

    }

    (void)gBS->Stall(200);

    gFlashBusy = FALSE;
    return EFI_SUCCESS;

}

EFI_STATUS SectorEraseCommand(UINTN Base, UINTN Offset)
{
    UINT32 dwAddr;

    if(gFlashBusy)
    {
        DEBUG((EFI_D_ERROR, "[%a]:[%dL]:Flash is busy!\n", __FUNCTION__,__LINE__));
        return EFI_NOT_READY;
    }

    gFlashBusy = TRUE;

    dwAddr = (UINT32)Base + (gFlashCommandErase[gIndex.EIndex].SectorEraseAddressStep1 << gFlashInfo[gIndex.InfIndex].ParallelNum);
    (VOID)PortWriteData(gIndex.InfIndex, dwAddr, gFlashCommandErase[gIndex.EIndex].SectorEraseDataStep1);

    dwAddr = (UINT32)Base + (gFlashCommandErase[gIndex.EIndex].SectorEraseAddressStep2 << gFlashInfo[gIndex.InfIndex].ParallelNum);
    (VOID)PortWriteData(gIndex.InfIndex, dwAddr, gFlashCommandErase[gIndex.EIndex].SectorEraseDataStep2);

    dwAddr = (UINT32)Base + (gFlashCommandErase[gIndex.EIndex].SectorEraseAddressStep3 << gFlashInfo[gIndex.InfIndex].ParallelNum);
    (VOID)PortWriteData(gIndex.InfIndex, dwAddr, gFlashCommandErase[gIndex.EIndex].SectorEraseDataStep3);

    dwAddr = (UINT32)Base + (gFlashCommandErase[gIndex.EIndex].SectorEraseAddressStep4 << gFlashInfo[gIndex.InfIndex].ParallelNum);
    (VOID)PortWriteData(gIndex.InfIndex, dwAddr, gFlashCommandErase[gIndex.EIndex].SectorEraseDataStep4);

    dwAddr = (UINT32)Base + (gFlashCommandErase[gIndex.EIndex].SectorEraseAddressStep5 << gFlashInfo[gIndex.InfIndex].ParallelNum);
    (VOID)PortWriteData(gIndex.InfIndex, dwAddr, gFlashCommandErase[gIndex.EIndex].SectorEraseDataStep5);

    dwAddr = (UINT32)Base + Offset;
    (VOID)PortWriteData(gIndex.InfIndex, dwAddr, gFlashCommandErase[gIndex.EIndex].SectorEraseDataStep6);

    (void)gBS->Stall(500000);

    gFlashBusy = FALSE;
    return EFI_SUCCESS;
}

EFI_STATUS CompleteCheck(UINT32 Base, UINT32 Offset, void *pData, UINT32 Length)
{
    UINT32 dwTestAddr;
    UINT32 dwTestData;
    UINT32 dwTemp = 0;
    UINT32 dwTemp1 = 0;
    UINT32 i;
    UINT32 dwTimeOut = 3000000;

    if(gFlashBusy)
    {
        DEBUG((EFI_D_ERROR, "[%a]:[%dL]:Flash is busy!\n", __FUNCTION__,__LINE__));
        return EFI_NOT_READY;
    }
    gFlashBusy = TRUE;

    if(2 == gFlashInfo[gIndex.InfIndex].ParallelNum)
    {
        dwTestAddr = Base + Offset + Length - sizeof(UINT32);
        dwTestData = *((UINT32 *)((UINT8 *)pData + Length - sizeof(UINT32)));

        while(dwTimeOut--)
        {
            dwTemp1 = *(volatile UINT32 *)(UINTN)(dwTestAddr);
            if (dwTestData == dwTemp1)
            {
                dwTemp = *(volatile UINT32 *)(UINTN)(dwTestAddr);
                dwTemp1 = *(volatile UINT32 *)(UINTN)(dwTestAddr);
                if ((dwTemp == dwTemp1) && (dwTestData == dwTemp1))
                {
                    gFlashBusy = FALSE;
                    return EFI_SUCCESS;
                }
            }

            (void)gBS->Stall(1);
        }

        if((UINT16)(dwTemp1 >> 16) != (UINT16)(dwTestData >> 16))
        {
            DEBUG((EFI_D_ERROR, "CompleteCheck ERROR: chip1 address %x, buffer %x, flash %x!\n", Offset, dwTestData, dwTemp1));
        }
        if((UINT16)(dwTemp1) != (UINT16)(dwTestData))
        {
            DEBUG((EFI_D_ERROR, "CompleteCheck ERROR: chip2 address %x, buffer %x, flash %x!\n", Offset, dwTestData, dwTemp1));
        }
    }
    else
    {
        dwTestAddr = Base + Offset + Length - sizeof(UINT16);
        dwTestData = *((UINT16 *)((UINT8 *)pData + Length - sizeof(UINT16)));

        while(dwTimeOut--)
        {
            dwTemp1 = *(volatile UINT16 *)(UINTN)(dwTestAddr);
            if (dwTestData == dwTemp1)
            {
                dwTemp = *(volatile UINT16 *)(UINTN)(dwTestAddr);
                dwTemp1 = *(volatile UINT16 *)(UINTN)(dwTestAddr);
                if ((dwTemp == dwTemp1) && (dwTestData == dwTemp1))
                {
                    gFlashBusy = FALSE;
                    return EFI_SUCCESS;
                }
            }

            (void)gBS->Stall(1);
        }
    }

    for(i = 0; i < 5; i ++)
    {
        DEBUG((EFI_D_ERROR, "CompleteCheck ERROR: flash %x\n",PortReadData(gIndex.InfIndex, dwTestAddr)));
    }

    FlashReset(Base);

    gFlashBusy = FALSE;
    DEBUG((EFI_D_ERROR, "CompleteCheck ERROR: timeout address %x, buffer %x, flash %x\n", Offset, dwTestData, dwTemp1));
    return EFI_TIMEOUT;
}

EFI_STATUS IsNeedToWrite(
    IN  UINT32         Base,
    IN  UINT32       Offset,
    IN  UINT8       *Buffer,
    IN  UINT32       Length
  )
{
    UINTN NewAddr = Base + Offset;
    UINT8 FlashData = 0;
    UINT8 BufferData = 0;

    for(; Length > 0; Length --)
    {
        BufferData = *Buffer;
        //lint -epn -e511
        FlashData = *(UINT8 *)NewAddr;
        if (BufferData != FlashData)
        {
            return TRUE;
        }
        NewAddr ++;
        Buffer ++;
    }

    return FALSE;
}

EFI_STATUS BufferWrite(UINT32 Offset, void *pData, UINT32 Length)
{
    EFI_STATUS Status;
    UINT32 dwLoop;
    UINT32 Retry = 3;

    if (FALSE == IsNeedToWrite(gIndex.Base, Offset, (UINT8 *)pData, Length))
    {
        return EFI_SUCCESS;
    }

    do
    {
        (void)BufferWriteCommand(gIndex.Base, Offset, pData);
        Status = CompleteCheck(gIndex.Base, Offset, pData, Length);

        if (EFI_SUCCESS == Status)
        {
            for (dwLoop = 0; dwLoop < Length; dwLoop ++)
            {
                if (*(UINT8 *)(UINTN)(gIndex.Base + Offset + dwLoop) != *((UINT8 *)pData + dwLoop))
                {
                    DEBUG((EFI_D_ERROR, "Flash_WriteUnit ERROR: address %x, buffer %x, flash %x\n", Offset, *((UINT8 *)pData + dwLoop), *(UINT8 *)(UINTN)(gIndex.Base + Offset + dwLoop)));
                    Status = EFI_ABORTED;
                    continue;
                }
            }
        }
        else
        {
            DEBUG((EFI_D_ERROR, "Flash_WriteUnit ERROR: complete check failed, %r\n", Status));
            continue;
        }
    } while ((Retry--) && EFI_ERROR(Status));

    return Status;
}

EFI_STATUS SectorErase(UINT32 Base, UINT32 Offset)
{
    UINT8 gTemp[FLASH_MAX_UNIT];
    UINT64 dwLoop = FLASH_MAX_UNIT - 1;
    UINT32 Retry = 3;
    EFI_STATUS Status;

    do
    {
        gTemp[dwLoop] = 0xFF;
    }while (dwLoop --);

    do
    {
        (void)SectorEraseCommand(Base, Offset);
        Status = CompleteCheck(Base, Offset, (void *)gTemp, FLASH_MAX_UNIT);

        if (EFI_SUCCESS == Status)
        {

            if (width8IsAll(Base,Offset - (Offset % gFlashInfo[gIndex.InfIndex].BlockSize), gFlashInfo[gIndex.InfIndex].BlockSize, 0xFF))
            {
                return EFI_SUCCESS;
            }
            else
            {
                DEBUG((EFI_D_ERROR, "Flash_SectorErase ERROR: not all address equal 0xFF\n"));

                Status = EFI_ABORTED;
                continue;
            }
        }
        else
        {
            DEBUG((EFI_D_ERROR, "Flash_SectorErase ERROR: complete check failed, %r\n", Status));
            continue;
        }
    }while ((Retry--) && EFI_ERROR(Status));

    if(Retry)
    {
        //do nothing for pclint
    }

    return Status;
}


text:
from __future__ import absolute_import
import unittest
import datetime
from epitator.annotator import AnnoDoc
from epitator.date_annotator import DateAnnotator

class DateAnnotatorTest(unittest.TestCase):

    def setUp(self):
        self.annotator = DateAnnotator()

    def test_no_times(self):
        text = 'I went to see her in a boat.'
        doc = AnnoDoc(text)
        doc.add_tier(self.annotator)
        self.assertEqual(doc.tiers['dates'].spans, [])

    def test_simple_date(self):
        text = 'I went to Chicago Friday, October 7th 2010.'
        doc = AnnoDoc(text)
        doc.add_tier(self.annotator)
        self.assertEqual(len(doc.tiers['dates'].spans), 1)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2010, 10, 7),
             datetime.datetime(2010, 10, 8)])

    def test_relative_date(self):
        text = 'Yesterday I went to the symphony.'
        doc = AnnoDoc(text, date=datetime.datetime(2010, 10, 10))
        doc.add_tier(self.annotator)
        self.assertEqual(len(doc.tiers['dates'].spans), 1)
        self.assertEqual(doc.tiers['dates'].spans[0].text, 'Yesterday')
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2010, 10, 9),
             datetime.datetime(2010, 10, 10)])

    def test_duration_with_years(self):
        text = 'I lived there for three years, from 1999 until late 2001'
        doc = AnnoDoc(text)
        doc.add_tier(DateAnnotator(include_end_date=False))
        self.assertEqual(len(doc.tiers['dates'].spans), 1)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(1999, 1, 1),
             datetime.datetime(2002, 1, 1)])

    def test_inexact_range(self):
        text = 'From May to August of 2009 we languished there.'
        doc = AnnoDoc(text)
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2009, 5, 1),
             datetime.datetime(2009, 9, 1)])

    def test_1950s(self):
        text = 'Adenoviruses, first isolated in the 1950s from explanted adenoid tissue.'
        doc = AnnoDoc(text)
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(1950, 1, 1),
             datetime.datetime(1960, 1, 1)])

    def test_specificity(self):
        text = """He said the strain detected in the Cloppenburg district
        [Lower Saxony state] was the same as that found at another farm in November [2014]
        in Schleswig-Holstein state."""
        doc = AnnoDoc(text)
        doc.add_tier(self.annotator)
        self.assertEqual(len(doc.tiers['dates'].spans), 1)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2014, 11, 1),
             datetime.datetime(2014, 12, 1)])
        self.assertEqual(
            doc.tiers['dates'].spans[0].text, 'November [2014')

    def test_dashes(self):
        text = 'Adenoviruses, first seen between 2010-1-1 and 2010-1-2'
        doc = AnnoDoc(text)
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2010, 1, 1),
             datetime.datetime(2010, 1, 3)])

    def test_dashes_2(self):
        text = 'First seen between 2010-1-1 - 2011-1-1'
        doc = AnnoDoc(text)
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2010, 1, 1),
             datetime.datetime(2011, 1, 2)])

    def test_dashes_3(self):
        doc = AnnoDoc('Distribution of reported yellow fever cases from 1 Jul 2017-17 Apr 2018')
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2017, 7, 1),
             datetime.datetime(2018, 4, 18)])

    def test_dateparser_bug(self):
        # This triggers an exception in the dateparser library described in this
        # bug report:
        # https://github.com/scrapinghub/dateparser/issues/339
        # This only tests that the exception is handled.
        # The date range in the text is still not property parsed.
        text = "week 1 - 53, 2015"
        doc = AnnoDoc(text)
        doc.add_tier(self.annotator)

    def test_dateparse_bug_2(self):
        # The current version of the date annotator tries to parse 72\n1994, which triggers an exception
        # in the dateparse library.
        doc = AnnoDoc("""
        Year Cases Fatal
        1991 46,320 697\n1992 31,870 208\n1993 6,833 72\n1994 1,785 16\n1995 2,160 23""")
        doc.add_tier(self.annotator)

    def test_relative_date_range(self):
        text = "between Thursday and Friday"
        doc = AnnoDoc(text, date=datetime.datetime(2017, 7, 15))
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2017, 7, 13),
             datetime.datetime(2017, 7, 15)])

    def test_relative_date_fp(self):
        text = "The maximum incubation period is 21 days."
        doc = AnnoDoc(text)
        doc.add_tier(self.annotator)
        self.assertEqual(doc.tiers['dates'].spans, [])

    def test_formatted_date(self):
        text = "08-FEB-17"
        doc = AnnoDoc(text, date=datetime.datetime(2017, 7, 15))
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2017, 2, 8),
             datetime.datetime(2017, 2, 9)])

    def test_reversed_range_error_1(self):
        text = "24 to 94 years"
        doc = AnnoDoc(text)
        doc.add_tier(self.annotator)
        self.assertEqual(doc.tiers['dates'].spans, [])

    def test_reversed_range_error_2(self):
        text = "9 months to 9 years"
        doc = AnnoDoc(text)
        doc.add_tier(self.annotator)
        self.assertEqual(doc.tiers['dates'].spans, [])

    def test_reversed_range_error_3(self):
        text = "6350-65"
        doc = AnnoDoc(text)
        doc.add_tier(self.annotator)
        self.assertEqual(doc.tiers['dates'].spans, [])

    def test_day_of_week(self):
        text = "Sat 19 Aug 2017"
        doc = AnnoDoc(text)
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2017, 8, 19),
             datetime.datetime(2017, 8, 20)])

    def test_week_parsing(self):
        text = "AES had taken 13 lives in the 2nd week of October 2017."
        doc = AnnoDoc(text)
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2017, 10, 8),
             datetime.datetime(2017, 10, 15)])

    def test_count_table(self):
        doc = AnnoDoc('''
        Type / Suspected / Confirmed / Recovered / Ongoing / Total
        Cases / 8 / 34 / 18 / 16 / 70
        Deaths / 7 / 33 / 17 / 15 / 65
        ''')
        doc.add_tier(self.annotator)
        self.assertEqual(doc.tiers['dates'].spans, [])

    def test_date_table(self):
        doc = AnnoDoc('''
        Cumulative case data
        Report date / Cases / Deaths
        26 Jun 2017 / 190 / 10
        15 Sep 2017 / 319 / 14
        ''')
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2017, 6, 26),
             datetime.datetime(2017, 6, 27)])
        self.assertEqual(
            doc.tiers['dates'].spans[1].datetime_range,
            [datetime.datetime(2017, 9, 15),
             datetime.datetime(2017, 9, 16)])

    def test_month_of_year(self):
        example = "Dengue cases were increasing in the 3rd month of the year [2017]."
        doc = AnnoDoc(example)
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2017, 3, 1),
             datetime.datetime(2017, 4, 1)])

    def test_since_date(self):
        text = 'nearly 5000 cases have been reported since 1 Sep 2010.'
        doc = AnnoDoc(text, date=datetime.datetime(2010, 12, 10))
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2010, 9, 1),
             datetime.datetime(2010, 12, 10)])

    def test_since_date_2(self):
        doc = AnnoDoc("Since April 6th 2013, 21 cases of infection have been confirmed.", date=datetime.datetime(2014, 12, 10))
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2013, 4, 6),
             datetime.datetime(2014, 12, 10)])

    def test_long_entity_dates(self):
        # This tests dates that are extracted with peripheral text
        # by the current NER.
        doc = AnnoDoc("""
In the month of August 2017, there were a total of 3 laboratory confirmed cases.
For the first time since 1998, a case of yellow fever has been confirmed.
""", date=datetime.datetime(2017, 12, 10))
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2017, 8, 1),
             datetime.datetime(2017, 9, 1)])
        self.assertEqual(
            doc.tiers['dates'].spans[1].datetime_range,
            [datetime.datetime(1998, 1, 1),
             datetime.datetime(2017, 12, 10)])

    def test_incorrect_date_grouping_bug(self):
        doc = AnnoDoc('''
A 31-year-old man from east Delhi's Mandawali succumbed to malaria at Safdarjung Hospital the 1st week of September [2016]. In July [2016], a 62-year-old man had died of the disease in northwest Delhi's Jyoti Nagar.''')
        doc.add_tier(self.annotator)

    def test_far_future_year_error(self):
        # 3120 was being parsed as a year which would cause a year out of rage error when creating a datetime object.
        doc = AnnoDoc("The cases from January to March [2011] eclipse the number of cases from the entire 2009 (2723) and 2010 (3120) [years].")
        doc.add_tier(self.annotator)

    def test_date_range(self):
        doc = AnnoDoc("The 7 new cases age between 17 and 70, and their onset dates vary between 19 May [2018] - 5 Jun [2018].")
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2018, 5, 19),
             datetime.datetime(2018, 6, 6)])

    def test_dateparser_bug_2(self):
        doc = AnnoDoc("One of the guys has already received a laboratory confirmation of the diagnosis of botulism 17.05.2018 year.")
        doc.add_tier(self.annotator)
        self.assertEqual(len(doc.tiers['dates'].spans), 1)

    def test_relative_date_range_2(self):
        doc = AnnoDoc(
            "In the past 20 days 285 cases of swine flu have been reported across the state.",
            date=datetime.datetime(2018, 12, 21))
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(2018, 12, 1),
             datetime.datetime(2018, 12, 21)])

    def test_partial_year_range(self):
        doc = AnnoDoc("From 1912-17 some stuff happened.")
        doc.add_tier(self.annotator)
        self.assertEqual(
            doc.tiers['dates'].spans[0].datetime_range,
            [datetime.datetime(1912, 1, 1),
             datetime.datetime(1918, 1, 1)])

    def test_aware_datetime(self):
        doc = AnnoDoc(" trade Date: Fri 29 Sep 2018 13:31 BST Source: Express")
        doc.add_tier(self.annotator)
        self.assertEqual(
            [date.replace(tzinfo=None) for date in doc.tiers['dates'].spans[0].datetime_range],
            [datetime.datetime(2018, 9, 29, 13, 31),
             datetime.datetime(2018, 9, 30, 13, 31)])