text:
SpecBegin(RACAction)

__block RACAction *action;
__block RACScheduler *scheduler;

__block NSMutableArray *executing;
__block NSMutableArray *enabled;

__block NSUInteger subscriptionCount;
__block NSUInteger disposalCount;

void (^connectAction)(void) = ^{
	[[action.executing distinctUntilChanged] subscribeNext:^(NSNumber *value) {
		expect(value).to.beKindOf(NSNumber.class);

		if (executing.count > 0) {
			expect(RACScheduler.currentScheduler).to.equal(RACScheduler.mainThreadScheduler);
		}

		[executing addObject:value];
	}];

	[[action.enabled distinctUntilChanged] subscribeNext:^(NSNumber *value) {
		expect(value).to.beKindOf(NSNumber.class);

		if (enabled.count > 0) {
			expect(RACScheduler.currentScheduler).to.equal(RACScheduler.mainThreadScheduler);
		}

		[enabled addObject:value];
	}];
};

RACSignal * (^signalWithValue)(id) = ^(id value) {
	return [[[RACSignal
		defer:^{
			subscriptionCount++;
			return [RACSignal return:value];
		}]
		doDisposed:^{
			disposalCount++;
		}]
		deliverOn:scheduler];
};

beforeEach(^{
	subscriptionCount = 0;
	disposalCount = 0;

	scheduler = [RACScheduler scheduler];
	executing = [NSMutableArray array];
	enabled = [NSMutableArray array];
});

sharedExamplesFor(@"enabled action", ^(id _) {
	it(@"should be enabled by default", ^{
		expect(enabled).to.equal((@[ @YES ]));
	});

	it(@"should not be executing by default", ^{
		expect(executing).to.equal((@[ @NO ]));
	});

	it(@"should execute asynchronously", ^{
		[action execute:nil];

		expect(subscriptionCount).to.equal(0);
		expect(executing).to.equal((@[ @NO ]));
		expect(enabled).to.equal((@[ @YES ]));

		expect(subscriptionCount).will.equal(1);
		expect(executing).will.equal((@[ @NO, @YES, @NO ]));
		expect(enabled).to.equal((@[ @YES, @NO, @YES ]));

		expect(disposalCount).to.equal(1);
	});

	it(@"should not send anything on 'errors' by default", ^{
		__block BOOL receivedError = NO;
		[action.errors subscribeNext:^(id _) {
			receivedError = YES;
		}];

		expect([[action signalWithValue:nil] asynchronouslyWaitUntilCompleted:NULL]).to.beTruthy();
		expect(receivedError).to.beFalsy();
	});

	it(@"should error if already executing", ^{
		[action execute:nil];

		NSError *error = nil;
		BOOL success = [[action signalWithValue:nil] asynchronouslyWaitUntilCompleted:&error];
		expect(success).to.beFalsy();

		expect(error).notTo.beNil();
		expect(error.domain).to.equal(RACActionErrorDomain);
		expect(error.code).to.equal(RACActionErrorNotEnabled);
		expect(error.userInfo[RACActionErrorKey]).to.beIdenticalTo(action);
	});

	it(@"should forward results on the main thread", ^{
		[action.results subscribeNext:^(id _) {
			expect(RACScheduler.currentScheduler).to.equal(RACScheduler.mainThreadScheduler);
		}];

		expect([[action signalWithValue:nil] asynchronouslyWaitUntilCompleted:NULL]).to.beTruthy();
	});

	it(@"should send replayed executionSignals on the main thread", ^{
		__block RACSignal *signal = nil;
		[action.executionSignals subscribeNext:^(RACSignal *s) {
			expect(RACScheduler.currentScheduler).to.equal(RACScheduler.mainThreadScheduler);
			signal = s;
		}];

		expect(signal).to.beNil();

		NSArray *values = [[[action
			signalWithValue:nil]
			collect]
			asynchronousFirstOrDefault:nil success:NULL error:NULL];

		expect(values).notTo.beNil();
		expect(signal).notTo.beNil();
		expect([signal array]).to.equal(values);
	});

	it(@"should forward -signalWithValue: and execution signal results on their original scheduler", ^{
		__block BOOL completed = NO;

		[[action.executionSignals flatten] subscribeNext:^(id _) {
			expect(RACScheduler.currentScheduler).to.equal(scheduler);
		}];

		[[action signalWithValue:nil] subscribeNext:^(id _) {
			expect(RACScheduler.currentScheduler).to.equal(scheduler);
		} completed:^{
			expect(RACScheduler.currentScheduler).to.equal(scheduler);
			completed = YES;
		}];

		expect(completed).will.beTruthy();
	});
});

describe(@"from a signal generator", ^{
	__block NSUInteger generationCount;

	beforeEach(^{
		generationCount = 0;

		action = [[RACDynamicSignalGenerator
			generatorWithBlock:^(id value) {
				generationCount++;
				return signalWithValue(value);
			}]
			action];

		expect(action).notTo.beNil();
		connectAction();

		expect(generationCount).to.equal(0);
	});

	itShouldBehaveLike(@"enabled action", @{});

	it(@"should generate a new signal with each call to -execute:", ^{
		[action execute:nil];
		expect(generationCount).will.equal(1);
		expect(disposalCount).will.equal(1);

		[action execute:nil];
		expect(generationCount).will.equal(2);
		expect(disposalCount).will.equal(2);
	});

	it(@"should defer execution", ^{
		RACSignal *deferred = [action signalWithValue:nil];
		expect(deferred).notTo.beNil();

		expect(executing).to.equal((@[ @NO ]));
		expect(enabled).to.equal((@[ @YES ]));

		expect([[deferred collect] asynchronousFirstOrDefault:nil success:NULL error:NULL]).to.equal((@[ NSNull.null ]));
		expect(generationCount).to.equal(1);
		expect(subscriptionCount).to.equal(1);
		expect(disposalCount).to.equal(1);
		expect(executing).will.equal((@[ @NO, @YES, @NO ]));
		expect(enabled).to.equal((@[ @YES, @NO, @YES ]));

		expect([deferred asynchronouslyWaitUntilCompleted:NULL]).to.beTruthy();
		expect(generationCount).to.equal(2);
		expect(subscriptionCount).to.equal(2);
		expect(disposalCount).to.equal(2);
		expect(executing).will.equal((@[ @NO, @YES, @NO, @YES, @NO ]));
		expect(enabled).to.equal((@[ @YES, @NO, @YES, @NO, @YES ]));
	});
});

describe(@"from a signal", ^{
	beforeEach(^{
		action = [signalWithValue(nil) action];
		expect(action).notTo.beNil();

		connectAction();
	});

	itShouldBehaveLike(@"enabled action", @{});

	it(@"should defer execution", ^{
		// The input value should be ignored here.
		RACSignal *deferred = [action signalWithValue:nil];
		expect(deferred).notTo.beNil();

		expect(executing).to.equal((@[ @NO ]));
		expect(enabled).to.equal((@[ @YES ]));

		expect([[deferred collect] asynchronousFirstOrDefault:nil success:NULL error:NULL]).to.equal((@[ NSNull.null ]));
		expect(subscriptionCount).to.equal(1);
		expect(disposalCount).to.equal(1);
		expect(executing).will.equal((@[ @NO, @YES, @NO ]));
		expect(enabled).to.equal((@[ @YES, @NO, @YES ]));

		expect([deferred asynchronouslyWaitUntilCompleted:NULL]).to.beTruthy();
		expect(subscriptionCount).to.equal(2);
		expect(disposalCount).to.equal(2);
		expect(executing).will.equal((@[ @NO, @YES, @NO, @YES, @NO ]));
		expect(enabled).to.equal((@[ @YES, @NO, @YES, @NO, @YES ]));
	});
});

describe(@"enabled", ^{
	__block RACSubject *enabledSubject;

	beforeEach(^{
		enabledSubject = [RACSubject subject];

		action = [signalWithValue(nil) actionEnabledIf:enabledSubject];
		expect(action).notTo.beNil();

		connectAction();
	});

	// Before anything is sent upon `enabledSubject`, the action should be
	// enabled.
	itShouldBehaveLike(@"enabled action", @{});

	it(@"should send NO after enabledSignal sends NO", ^{
		[enabledSubject sendNext:@NO];
		expect(enabled).will.equal((@[ @YES, @NO ]));
	});

	it(@"should send NO after enabledSignal sends YES but while executing", ^{
		[enabledSubject sendNext:@YES];

		[action execute:nil];
		expect(executing).will.equal((@[ @NO, @YES, @NO ]));
		expect(enabled).to.equal((@[ @YES, @NO, @YES ]));
	});

	it(@"should send YES after enabledSignal sends YES and not executing", ^{
		[enabledSubject sendNext:@NO];
		expect(enabled).will.equal((@[ @YES, @NO ]));

		[enabledSubject sendNext:@YES];
		expect(enabled).will.equal((@[ @YES, @NO, @YES ]));
	});

	it(@"should immediately sample enabledSignal at initialization time", ^{
		action = [[RACSignal empty] actionEnabledIf:[RACSignal return:@NO]];
		expect([action.enabled first]).to.equal(@NO);
	});

	it(@"should complete upon deallocation even if enabledSignal hasn't", ^{
		__block BOOL deallocated = NO;
		__block BOOL completed = NO;

		@autoreleasepool {
			RACAction *action __attribute__((objc_precise_lifetime)) = [[RACSignal
				empty]
				actionEnabledIf:enabledSubject];

			[action.rac_deallocDisposable addDisposable:[RACDisposable disposableWithBlock:^{
				deallocated = YES;
			}]];

			[action.enabled subscribeCompleted:^{
				completed = YES;
			}];
		}

		expect(deallocated).will.beTruthy();
		expect(completed).will.beTruthy();
	});
});

it(@"should forward errors on the main thread", ^{
	NSError *testError = [NSError errorWithDomain:@"RACActionSpecDomain" code:321 userInfo:nil];

	action = [[[RACSignal
		error:testError]
		deliverOn:[RACScheduler scheduler]]
		action];

	__block NSError *receivedError = nil;
	[action.errors subscribeNext:^(NSError *e) {
		expect(RACScheduler.currentScheduler).to.equal(RACScheduler.mainThreadScheduler);
		receivedError = e;
	}];

	[action execute:nil];
	expect(receivedError).will.equal(testError);
});

it(@"should complete signals on the main thread when deallocated", ^{
	__block BOOL deallocated = NO;
	__block RACScheduler *executingScheduler = nil;
	__block RACScheduler *enabledScheduler = nil;
	__block RACScheduler *errorsScheduler = nil;
	__block RACScheduler *resultsScheduler = nil;
	__block RACScheduler *executionSignalsScheduler = nil;

	[[RACScheduler scheduler] schedule:^{
		@autoreleasepool {
			RACAction *action __attribute__((objc_precise_lifetime)) = [[RACSignal
				empty]
				action];

			[action.rac_deallocDisposable addDisposable:[RACDisposable disposableWithBlock:^{
				deallocated = YES;
			}]];

			[action.executing subscribeCompleted:^{
				executingScheduler = RACScheduler.currentScheduler;
			}];

			[action.enabled subscribeCompleted:^{
				enabledScheduler = RACScheduler.currentScheduler;
			}];

			[action.errors subscribeCompleted:^{
				errorsScheduler = RACScheduler.currentScheduler;
			}];

			[action.results subscribeCompleted:^{
				resultsScheduler = RACScheduler.currentScheduler;
			}];

			[action.executionSignals subscribeCompleted:^{
				executionSignalsScheduler = RACScheduler.currentScheduler;
			}];
		}
	}];

	expect(deallocated).will.beTruthy();
	expect(executingScheduler).will.equal(RACScheduler.mainThreadScheduler);
	expect(enabledScheduler).to.equal(RACScheduler.mainThreadScheduler);
	expect(errorsScheduler).to.equal(RACScheduler.mainThreadScheduler);
	expect(resultsScheduler).to.equal(RACScheduler.mainThreadScheduler);
	expect(executionSignalsScheduler).to.equal(RACScheduler.mainThreadScheduler);
});

SpecEnd


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Citrina
{
    public class PagesWikipageHistory
    {
        /// <summary>
        /// Version ID.
        /// </summary>
        public int? Id { get; set; }

        /// <summary>
        /// Page size in bytes.
        /// </summary>
        public int? Length { get; set; }

        /// <summary>
        /// Date when the page has been edited in Unixtime.
        /// </summary>
        public int? Date { get; set; }

        /// <summary>
        /// Last editor ID.
        /// </summary>
        public int? EditorId { get; set; }

        /// <summary>
        /// Last editor name.
        /// </summary>
        public string EditorName { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
define([
    "gaslib/Point",
    "gaslib/Helpers"
], function(Point, Helpers){

    /**
     * Class representing a pipe in the network
     *
     * @class Pipe
     * @constructor
     */
    var Pipe = function(){
        /**
         * @property flow
         * @type {number}
         */
        this.flow = 0;
        /**
         * @property maxFlow
         * @type {number}
         */
        this.maxFlow = 0;
        this.start = new Point();
        this.finish = new Point();
    };

    /**
     * @type {Pipe}
     */
    Pipe.constructor = Pipe;

    /**
     * @method setStartPoint
     * @param lat
     * @param lng
     */
    Pipe.constructor.setStartPoint = function(lat, lng) {
        this.start = new Point(lat, lng);
    };

    /**
     * @method getStartPoint
     * @returns {Point|*}
     */
    Pipe.constructor.getStartPoint = function() {
        return this.start;
    };

    /**
     * @method setFinishPoint
     * @param lat
     * @param lng
     */
    Pipe.constructor.setFinishPoint = function(lat, lng) {
        this.finish = new Point(lat, lng);
    };

    /**
     * @method getFinishPoint
     * @returns {Point|*}
     */
    Pipe.constructor.getFinishPoint = function() {
        return this.finish;
    };

    /**
     * @method usage
     * @returns {float} Flow ratio of a maximum value.
     */
    Pipe.prototype.usage = function(){
        if (this.maxFlow > 0)
        {
            return this.flow / this.maxFlow;
        }
        else
        {
            return 0;
        }
    };

    /**
     * @method lengthInKm
     * @returns {*} returns distance between start Point and finish Point.
     */
    Pipe.prototype.lengthInKm = function() {
        return Helpers.distanceInKm(this.start, this.finish);
    };

    return Pipe;
});


text:
angular.module('directives').directive('requireTwitter', function($twttr) {
  return {
    restrict: "A",
    scope: "isolate",
    link: function() { $twttr.widgets.load(); }
  };
});


text:
package gq.baijie.catalog.usecase;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;

import javax.annotation.Nonnull;

import gq.baijie.catalog.entity.DirectoryFile;
import gq.baijie.catalog.entity.RegularFile;

import static java.nio.file.FileVisitResult.CONTINUE;

public class ScanFileSystem implements UseCase {

    @Nonnull
    private final DirectoryFile rootDirectoryFile;

    public ScanFileSystem(@Nonnull DirectoryFile rootDirectoryFile) {
        this.rootDirectoryFile = rootDirectoryFile;
    }

    @Override
    public void execute() {
        try {
            execute0();
        } catch (IOException e) {
            throw new RuntimeException(
                    "can't scan " + rootDirectoryFile.getPath() + " directory on the file system.");
        }
    }

    private void execute0() throws IOException {
        Files.walkFileTree(
                rootDirectoryFile.getPath(), new DirectoryFileVisitor(rootDirectoryFile));
    }

    private static class DirectoryFileVisitor implements FileVisitor<Path> {

        private DirectoryFile mCurrentDirectory;

        public DirectoryFileVisitor(DirectoryFile root) {
            mCurrentDirectory = root;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                throws IOException {
            final DirectoryFile subDirectory = new DirectoryFile(dir);
            mCurrentDirectory.addChild(subDirectory);
            mCurrentDirectory = subDirectory;
            return CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            mCurrentDirectory.addChild(new RegularFile(file));
            return CONTINUE;
        }

        // Print each directory visited.
        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
            mCurrentDirectory = mCurrentDirectory.getParent();
            return CONTINUE;
        }

        // If there is some error accessing
        // the file, let the user know.
        // If you don't override this method
        // and an error occurs, an IOException
        // is thrown.
        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) {
            System.err.println(String.format("visitFileFailed(%s, %s)", file, exc));
            exc.printStackTrace();
            return CONTINUE;
        }
    }

}


text:
ndk-build NDK_APPLICATION_MK=./Application-x.mk NDK_LIBS_OUT=../libs-x clean
ndk-build NDK_APPLICATION_MK=./Application-x.mk NDK_LIBS_OUT=../libs-x
read -rsn1 -p"Press any key to continue";echo


text: A collection of experiments in Go


text:
import { Component, OnInit, Input } from '@angular/core';
import { SiteService } from 'app/services/site.service';
import { UserService } from 'app/services/user.service';
import {Router} from '@angular/router';
import { User } from 'app/defs/user';

@Component({
  selector: 'basicplan',
  templateUrl: './basicplan.component.html',
  styleUrls: ['./basicplan.component.scss']
})
export class BasicplanComponent implements OnInit {
  constructor(private siteSvc : SiteService, private userSvc : UserService,private router:Router){}
  private user : User;

  @Input()
  public showTrial:boolean;

  @Input()
  public showActions : boolean;

  @Input()
  public currentPlan : boolean;

  ngOnInit(){
  	if(this.showActions == undefined) {
  		this.showActions = true;
  	}
    this.userSvc.user.subscribe((user: User) => {
    	this.user = user;
    });

    console.log(this.showTrial);
  }

  select(plan){
    console.log("You chose plan ",plan);
    if(!this.user.loginstatus){
      this.router.navigate(['/login'],{ queryParams: { redirect: '/checkout',plan:plan.id } });
    }
    else {
      console.log(this.user);
      this.router.navigate(['/checkout'],{ queryParams: { plan:plan.id,customerid:this.user.customerid } });
    }
  }

  trial(plan){
    console.log("You chose trial plan ",plan);
    if(!this.user.loginstatus){
      this.router.navigate(['/login'],{ queryParams: { redirect: '/trial',plan:plan.id,userid:this.user.id } });
    }
    else {
      this.router.navigate(['/trial'],{ queryParams: { plan:plan.id,userid:this.user.id } });
    }
  }

}


text:
export const getQuery = (query) => ({
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ query: `query { ${query} }` }),
})


text:
namespace crashpad {
namespace test {
namespace {

TEST(ProcessReaderWin, SelfBasic) {
  ProcessReaderWin process_reader;
  ASSERT_TRUE(process_reader.Initialize(GetCurrentProcess(),
                                        ProcessSuspensionState::kRunning));

#if !defined(ARCH_CPU_64_BITS)
  EXPECT_FALSE(process_reader.Is64Bit());
#else
  EXPECT_TRUE(process_reader.Is64Bit());
#endif

  EXPECT_EQ(GetCurrentProcessId(), process_reader.GetProcessInfo().ProcessID());

  const char kTestMemory[] = "Some test memory";
  char buffer[arraysize(kTestMemory)];
  ASSERT_TRUE(
      process_reader.ReadMemory(reinterpret_cast<uintptr_t>(kTestMemory),
                                sizeof(kTestMemory),
                                &buffer));
  EXPECT_STREQ(kTestMemory, buffer);
}

const char kTestMemory[] = "Read me from another process";

class ProcessReaderChild final : public WinMultiprocess {
 public:
  ProcessReaderChild() : WinMultiprocess() {}
  ~ProcessReaderChild() {}

 private:
  void WinMultiprocessParent() override {
    ProcessReaderWin process_reader;
    ASSERT_TRUE(process_reader.Initialize(ChildProcess(),
                                          ProcessSuspensionState::kRunning));

#if !defined(ARCH_CPU_64_BITS)
    EXPECT_FALSE(process_reader.Is64Bit());
#else
    EXPECT_TRUE(process_reader.Is64Bit());
#endif

    WinVMAddress address;
    CheckedReadFile(ReadPipeHandle(), &address, sizeof(address));

    char buffer[sizeof(kTestMemory)];
    ASSERT_TRUE(
        process_reader.ReadMemory(address, sizeof(kTestMemory), &buffer));
    EXPECT_EQ(0, strcmp(kTestMemory, buffer));
  }

  void WinMultiprocessChild() override {
    WinVMAddress address = reinterpret_cast<WinVMAddress>(kTestMemory);
    CheckedWriteFile(WritePipeHandle(), &address, sizeof(address));

    // Wait for the parent to signal that it's OK to exit by closing its end of
    // the pipe.
    CheckedReadFileAtEOF(ReadPipeHandle());
  }

  DISALLOW_COPY_AND_ASSIGN(ProcessReaderChild);
};

TEST(ProcessReaderWin, ChildBasic) {
  WinMultiprocess::Run<ProcessReaderChild>();
}

TEST(ProcessReaderWin, SelfOneThread) {
  ProcessReaderWin process_reader;
  ASSERT_TRUE(process_reader.Initialize(GetCurrentProcess(),
                                        ProcessSuspensionState::kRunning));

  const std::vector<ProcessReaderWin::Thread>& threads =
      process_reader.Threads();

  // If other tests ran in this process previously, threads may have been
  // created and may still be running. This check must look for at least one
  // thread, not exactly one thread.
  ASSERT_GE(threads.size(), 1u);

  EXPECT_EQ(GetCurrentThreadId(), threads[0].id);
#if defined(ARCH_CPU_64_BITS)
  EXPECT_NE(0, threads[0].context.native.Rip);
#else
  EXPECT_NE(0u, threads[0].context.native.Eip);
#endif

  EXPECT_EQ(0, threads[0].suspend_count);
}

class ProcessReaderChildThreadSuspendCount final : public WinMultiprocess {
 public:
  ProcessReaderChildThreadSuspendCount() : WinMultiprocess() {}
  ~ProcessReaderChildThreadSuspendCount() {}

 private:
  enum : unsigned int { kCreatedThreads = 3 };

  class SleepingThread : public Thread {
   public:
    SleepingThread() : done_(nullptr) {}

    void SetHandle(Semaphore* done) {
      done_= done;
    }

    void ThreadMain() override {
      done_->Wait();
    };

   private:
    Semaphore* done_;
  };

  void WinMultiprocessParent() override {
    char c;
    CheckedReadFile(ReadPipeHandle(), &c, sizeof(c));
    ASSERT_EQ(' ', c);

    {
      ProcessReaderWin process_reader;
      ASSERT_TRUE(process_reader.Initialize(ChildProcess(),
                                            ProcessSuspensionState::kRunning));

      const auto& threads = process_reader.Threads();
      ASSERT_GE(threads.size(), kCreatedThreads + 1);
      for (const auto& thread : threads)
        EXPECT_EQ(0u, thread.suspend_count);
    }

    {
      ScopedProcessSuspend suspend(ChildProcess());

      ProcessReaderWin process_reader;
      ASSERT_TRUE(process_reader.Initialize(
          ChildProcess(), ProcessSuspensionState::kSuspended));

      // Confirm that thread counts are adjusted correctly for the process being
      // suspended.
      const auto& threads = process_reader.Threads();
      ASSERT_GE(threads.size(), kCreatedThreads + 1);
      for (const auto& thread : threads)
        EXPECT_EQ(0u, thread.suspend_count);
    }
  }

  void WinMultiprocessChild() override {
    // Create three dummy threads so we can confirm we read successfully read
    // more than just the main thread.
    SleepingThread threads[kCreatedThreads];
    Semaphore done(0);
    for (auto& thread : threads)
      thread.SetHandle(&done);
    for (auto& thread : threads)
      thread.Start();

    char c = ' ';
    CheckedWriteFile(WritePipeHandle(), &c, sizeof(c));

    // Wait for the parent to signal that it's OK to exit by closing its end of
    // the pipe.
    CheckedReadFileAtEOF(ReadPipeHandle());

    for (int i = 0; i < arraysize(threads); ++i)
      done.Signal();
    for (auto& thread : threads)
      thread.Join();
  }

  DISALLOW_COPY_AND_ASSIGN(ProcessReaderChildThreadSuspendCount);
};

TEST(ProcessReaderWin, ChildThreadSuspendCounts) {
  WinMultiprocess::Run<ProcessReaderChildThreadSuspendCount>();
}

}  // namespace
}  // namespace test
}  // namespace crashpad


text:
package nom.bdezonia.zorbage.algorithm;

import static org.junit.Assert.assertEquals;

import org.junit.Test; import nom.bdezonia.zorbage.algebra.G;
import nom.bdezonia.zorbage.type.real.float64.Float64Member;
import nom.bdezonia.zorbage.type.real.float64.Float64VectorMember;

/**
 *
 * @author Barry DeZonia
 *
 */
public class TestPerpDotProduct {

	@Test
	public void test() {
		Float64VectorMember a = G.DBL_VEC.construct("[1,2]");
		Float64VectorMember b = G.DBL_VEC.construct("[3,-2]");
		Float64Member c = G.DBL.construct();
		G.DBL_VEC.perpDotProduct().call(a, b, c);
		assertEquals(-8, c.v(), 0);
	}
}


text:
import argparse
import sys
import unittest

from scripts.event_queues import SupvisorsEventQueues
from scripts.sequence_checker import *

class CheckStartSequenceTest(CheckSequenceTest):
    """ Test case to check the sequencing of the starting test application. """

    def test_sequencing(self):
        """ Test the whole sequencing of the starting of the test application.
        At this point, Supvisors is in DEPLOYMENT phase.
        This process is the first to be started. """
        # wait for address_queue to trigger
        self.get_addresses()
        # test the last events received for this process
        self.check_self_starting()
        # test the starting of applications
        self.check_import_database_starting()
        self.check_database_starting()
        self.check_my_movies_starting()
        self.check_player_starting()
        self.check_web_movies_starting()
        # final test (import database expected to be stopped)
        self.assertFalse(self.context.has_events())

    def check_self_starting(self):
        """ Test the events received that corresponds to the starting of this process. """
        # define 'test' application
        application = Application('test')
        self.context.add_application(application)
        program = Program('check_start_sequence')
        # this process 'test:check_start_sequence' is already starting
        program.state = ProcessStates.STARTING
        application.add_program(program)
        # define the expected events for this process
        program.add_event(ProcessStateEvent(ProcessStates.RUNNING, self.HOST_01))
        # test the events received are compliant
        self.check_events()
        self.assertFalse(self.context.has_events())

    def check_import_database_starting(self):
        """ Check the starting of the import_database application.
        The mount_disk process is started first, then the copy_error (failure expected).
        The application is configured to be stopped because of the failure. """
        # define 'import_database' application
        application = Application('import_database')
        self.context.add_application(application)
        for program_name in ['mount_disk_00', 'mount_disk_01']:
            application.add_program(Program(program_name, True))
        application.add_program(Program('copy_error', True))
        # check events
        self.check_mount_disk_starting()
        self.check_copy_error_starting()
        self.check_mount_disk_stopping()

    def check_mount_disk_starting(self):
        """ Check the starting of the mount_disk program. """
        config = [('mount_disk_00', self.HOST_02),
                  ('mount_disk_01', self.HOST_03)]
        # define the expected events for the mount_disk program
        application = self.context.get_application('import_database')
        for program_name, address in config:
            program = application.get_program(program_name)
            if address in self.addresses:
                program.add_event(ProcessStateEvent(ProcessStates.STARTING, address))
                program.add_event(ProcessStateEvent(ProcessStates.RUNNING, address))
            else:
                program.add_event(ProcessStateEvent(ProcessStates.FATAL, address))
        # check that the events received correspond to the expected
        self.check_events('import_database')
        self.assertFalse(self.context.has_events('import_database'))

    def check_copy_error_starting(self):
        """ Check the starting of the copy_error program. """
        # define the expected events for the copy_error program
        if all(node in self.addresses for node in [self.HOST_02, self.HOST_03]):
            program = self.context.get_program('import_database:copy_error')
            program.add_event(ProcessStateEvent(ProcessStates.STARTING, self.HOST_01))
            program.add_event(ProcessStateEvent(ProcessStates.BACKOFF, self.HOST_01))
            program.add_event(ProcessStateEvent(ProcessStates.FATAL))
            # test the events received are compliant
            self.check_events()
            self.assertFalse(self.context.has_events())

    def check_mount_disk_stopping(self):
        """ Program the stopping of the program.state program. """
        config = [('mount_disk_00', self.HOST_02),
                  ('mount_disk_01', self.HOST_03)]
        # define the expected events for the mount_disk program
        application = self.context.get_application('import_database')
        for program_name, address in config:
            if address in self.addresses:
                program = application.get_program(program_name)
                program.add_event(ProcessStateEvent(ProcessStates.STOPPING, address))
                program.add_event(ProcessStateEvent(ProcessStates.STOPPED, address))
        # do NOT check the events received at this stage
        # stopping events will be mixed with the starting events
        # of the following applications

    def check_database_starting(self):
        """ Check the starting of the database application.
        The movie_server_xx processes are started first,
        then the register_movies_xx.
        FATAL process events are expected, according to the test platform. """
        # define 'import_database' application
        application = Application('database')
        self.context.add_application(application)
        for program_name in ['movie_server_01', 'movie_server_02', 'movie_server_03']:
            application.add_program(Program(program_name))
        for program_name in ['register_movies_01', 'register_movies_02', 'register_movies_03']:
            application.add_program(Program(program_name, False, True))
        # check events
        self.check_movie_server_starting()
        self.check_register_movies_starting()

    def check_movie_server_starting(self):
        """ Check the starting of the movie_server programs. """
        config = [('movie_server_01', self.HOST_01),
                  ('movie_server_02', self.HOST_02),
                  ('movie_server_03', self.HOST_03)]
        # define the expected events for the movie_server_xx programs
        application = self.context.get_application('database')
        for program_name, address in config:
            program = application.get_program(program_name)
            if address in self.addresses:
                program.add_event(ProcessStateEvent(ProcessStates.STARTING, address))
                program.add_event(ProcessStateEvent(ProcessStates.RUNNING, address))
            else:
                program.add_event(ProcessStateEvent(ProcessStates.FATAL))
        # check that the events received are compliant
        self.check_events('database')
        self.assertFalse(self.context.has_events('database'))

    def check_register_movies_starting(self):
        """ Check the starting of the register_movies programs. """
        config = [('register_movies_01', self.HOST_01),
                  ('register_movies_02', self.HOST_02),
                  ('register_movies_03', self.HOST_03)]
        # define the expected events for the register_movies_xx programs
        application = self.context.get_application('database')
        for program_name, address in config:
            program = application.get_program(program_name)
            if address in self.addresses:
                program.add_event(ProcessStateEvent(ProcessStates.STARTING, address))
                program.add_event(ProcessStateEvent(ProcessStates.RUNNING, address))
                program.add_event(ProcessStateEvent(ProcessStates.EXITED))
            else:
                program.add_event(ProcessStateEvent(ProcessStates.FATAL))
        # check that the events received are compliant
        self.check_events('database')
        self.assertFalse(self.context.has_events('database'))

    def check_my_movies_starting(self):
        """ Check the starting of the my_movies application.
        The manager process is started first, then the web_server, finally the hmi.
        In the my_movies application, there should be a major_failure due to
        the web_server that is configured not to start. """
        # define 'my_movies' application
        application = Application('my_movies')
        self.context.add_application(application)
        application.add_program(Program('manager', True))
        application.add_program(Program('web_server', True))
        application.add_program(Program('hmi'))
        # check events
        self.check_manager_starting()
        self.check_web_server_starting()
        self.check_hmi_starting()

    def check_manager_starting(self):
        """ Check the starting of the manager program. """
        # define the expected events for the manager program
        program = self.context.get_program('my_movies:manager')
        program.add_event(ProcessStateEvent(ProcessStates.STARTING, self.HOST_01))
        program.add_event(ProcessStateEvent(ProcessStates.RUNNING, self.HOST_01))
        # check that the events received are compliant
        self.check_events('my_movies')
        self.assertFalse(self.context.has_events('my_movies'))

    def check_web_server_starting(self):
        """ Check the starting of the web_server program. """
        # define the expected events for the web_server program
        program = self.context.get_program('my_movies:web_server')
        program.add_event(ProcessStateEvent(ProcessStates.FATAL))
        # check that the events received are compliant
        self.check_events('my_movies')
        self.assertFalse(self.context.has_events('my_movies'))

    def check_hmi_starting(self):
        """ Check the starting of the hmi program. """
        # define the expected events for the hmi program
        program = self.context.get_program('my_movies:hmi')
        address = self.HOST_02 if self.HOST_02 in self.addresses else self.HOST_01
        program.add_event(ProcessStateEvent(ProcessStates.STARTING, address))
        program.add_event(ProcessStateEvent(ProcessStates.RUNNING, address))
        # check that the events received are compliant
        self.check_events('my_movies')
        self.assertFalse(self.context.has_events('my_movies'))

    def check_player_starting(self):
        """ Check the starting of the player application.
        The test_reader process is started first (wrong exit code expected).
        The starting of the application is configured to be aborted
        after the failure. """
        # define 'player' application
        application = Application('player')
        self.context.add_application(application)
        application.add_program(Program('test_reader', True, True))
        application.add_program(Program('movie_player'))
        # check events
        self.check_test_reader_starting()

    def check_test_reader_starting(self):
        """ Check the starting of the test_reader program. """
        # define the expected events for the test_reader program
        program = self.context.get_program('player:test_reader')
        program.add_event(ProcessStateEvent(ProcessStates.STARTING, self.HOST_01))
        program.add_event(ProcessStateEvent(ProcessStates.RUNNING, self.HOST_01))
        program.add_event(ProcessStateEvent(ProcessStates.EXITED, self.HOST_01))
        # check that the events received are compliant
        self.check_events('player')
        self.assertFalse(self.context.has_events('player'))

    def check_web_movies_starting(self):
        """ Check the starting of the web_movies application.
        It contains only the web_browser program. """
        # define 'my_movies' application
        application = Application('web_movies')
        self.context.add_application(application)
        program = Program('web_browser')
        application.add_program(program)
        # define the expected events for the web_browser program
        # WARN: if errors happen, like "AssertionError: 'RUNNING' != 'BACKOFF'"
        # this is probably because there is an instance of firefox already running before supervisord has been started
        # close it before the test
        program.add_event(ProcessStateEvent(ProcessStates.STARTING, self.HOST_01))
        program.add_event(ProcessStateEvent(ProcessStates.RUNNING, self.HOST_01))
        # check that the events received are compliant
        self.check_events('web_movies')
        self.assertFalse(self.context.has_events('web_movies'))

def test_suite():
    return unittest.findTestCases(sys.modules[__name__])

if __name__ == '__main__':
    # get arguments
    parser = argparse.ArgumentParser(description='Check the starting sequence using Supvisors events.')
    parser.add_argument('-p', '--port', type=int, default=60002,
                        help="the event port of Supvisors")
    args = parser.parse_args()
    SupvisorsEventQueues.PORT = args.port
    # start unittest
    unittest.main(defaultTest='test_suite')


text:
package com.hubspot.rosetta.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Meta-annotation used for marking all annotations that are
 * part of Rosetta package. Can be used for recognizing all
 * Rosetta annotations generically, and in future also for
 * passing other generic annotation configuration.
 */
@Target({ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RosettaAnnotation {}


text:
package io.aeron.archive;

import io.aeron.Aeron;
import io.aeron.Subscription;
import org.agrona.collections.Object2ObjectHashMap;

class ListRecordingSubscriptionsSession implements Session
{
    private final long correlationId;
    private final int subscriptionCount;
    private int pseudoIndex;
    private int sent;
    private final int streamId;
    private boolean applyStreamId;
    private boolean isDone = false;
    private final String channelFragment;
    private final Object2ObjectHashMap<String, Subscription> subscriptionByKeyMap;
    private final ControlSession controlSession;
    private final ControlResponseProxy proxy;

    ListRecordingSubscriptionsSession(
        final Object2ObjectHashMap<String, Subscription> subscriptionByKeyMap,
        final int pseudoIndex,
        final int subscriptionCount,
        final int streamId,
        final boolean applyStreamId,
        final String channelFragment,
        final long correlationId,
        final ControlSession controlSession,
        final ControlResponseProxy proxy)
    {
        this.subscriptionByKeyMap = subscriptionByKeyMap;
        this.pseudoIndex = pseudoIndex;
        this.subscriptionCount = subscriptionCount;
        this.streamId = streamId;
        this.applyStreamId = applyStreamId;
        this.channelFragment = channelFragment;
        this.correlationId = correlationId;
        this.controlSession = controlSession;
        this.proxy = proxy;
    }

    public void close()
    {
        controlSession.activeListing(null);
    }

    public void abort()
    {
        isDone = true;
    }

    public boolean isDone()
    {
        return isDone;
    }

    public long sessionId()
    {
        return Aeron.NULL_VALUE;
    }

    public int doWork()
    {
        int workCount = 0;
        int index = 0;
        final int size = subscriptionByKeyMap.size();

        for (final Subscription subscription : subscriptionByKeyMap.values())
        {
            if (index++ >= pseudoIndex)
            {
                if (!(applyStreamId && subscription.streamId() != streamId) &&
                    subscription.channel().contains(channelFragment))
                {
                    if (!controlSession.sendSubscriptionDescriptor(correlationId, subscription, proxy))
                    {
                        break;
                    }

                    workCount += 1;

                    if (++sent >= subscriptionCount)
                    {
                        isDone = true;
                        break;
                    }
                }

                pseudoIndex = index - 1;
            }
        }

        if (!isDone && index >= size)
        {
            controlSession.sendSubscriptionUnknown(correlationId, proxy);
            isDone = true;
            workCount += 1;
        }

        return workCount;
    }
}


text:
__author__ = 'yfauser'

from tests.config import *
from nsxramlclient.client import NsxClient

client_session = NsxClient(nsxraml_file, nsxmanager, nsx_username, nsx_password, debug=True)

print client_session.read('nwfabricFeatures')
print client_session.read('nwfabricStatus', query_parameters_dict={'resource': 'domain-c1632'})


text:
import React from "react";
var FaSearch = require('react-icons/lib/fa/search');
var $ = require('jquery');

/**
 * Input field where the user enters the keywords for search.
 */
export default class Input extends React.Component {

    constructor() {
      super();
      this.state = {
        keywords: ""
      };
    }

    /**
     * Handle the event of key up on the input field.
     */
    handleKeyUp(e) {
      if (
        e.keyCode != 13 && e.keyCode != 40 && e.keyCode != 38 &&
        e.keyCode != 37 && e.keyCode != 39
      ) {
        var input = e.target.value;
        this.props.getSearchResults(input, true);
      } else {
        if(e.keyCode != 13)  {
          var suggestionsContainer = $(".suggestionGroupClass");
          if(suggestionsContainer != null) {//if we don't have some suggestions displayed, it makes no sense to go further
            //console.log(e.keyCode);
            switch (e.keyCode) {
              case 38://up arrow pressed
                var activeItem = suggestionsContainer.find('.active-result');
                if (activeItem.length == 0) {
                  suggestionsContainer.children().last().addClass("active-result");
                } else {
                  var prevItem = activeItem.prev();
                  activeItem.removeClass("active-result");
                  if (prevItem.length == 0) {
                    suggestionsContainer.children().last().addClass("active-result");
                  } else {
                    prevItem.addClass("active-result");
                  }
                }
                break;
              case 40://down arrow pressed
                var activeItem = suggestionsContainer.find('.active-result');
                if (activeItem.length == 0) {
                  suggestionsContainer.children().first().addClass("active-result");
                } else {
                  var nextItem = activeItem.next();
                  activeItem.removeClass("active-result");
                  if (nextItem.length == 0) {
                    suggestionsContainer.children().first().addClass("active-result");
                  } else {
                    nextItem.addClass("active-result");
                  }
                }
                break;
            }
          }
        } else {
          this.enterPressed(e);
        }
      }
    }

    /**
     * Handles the event where 'enter' key was pressed on this input field.
     */
    enterPressed(e) {
        var selected = $(".active-result a");
        if(selected.attr('href')) {
          window.location = selected.attr('href');
        }
    }

    /**
     * Handle onChange event.
     */
    handleChange(e){
      this.setState (
        {
          keywords: e.target.value
        }
      );
    }

    /**
     * Bound to the onBlur event (when the use clicks outside of the field)
     */
    focusOut() {
      this.props.getSearchResults('', true);
    }

    /**
     * Bound to the onFocus event (when the use clicks in of the field)
     */
    onFocus(e) {
      this.props.getSearchResults(e.target.value, true);
    }

    render() {
      return (

          {
            this.state.keywords.length == 0 ?
              <input
                id="charles-search-field" placeholder={this.props.placeholder}
                onKeyUp={this.handleKeyUp.bind(this)}
                onChange={this.handleChange.bind(this)}
                autoComplete="off"
              />
            :
              <input id="charles-search-field" value={this.state.keywords}
                onKeyUp={this.handleKeyUp.bind(this)}
                onChange={this.handleChange.bind(this)}
                onFocus={this.onFocus.bind(this)}
                autoComplete="off"
              />
          }

       );
    }
}


text:
#include <algorithm>
#include <iomanip>
#include <syslandscape/log/ConversionMessage.hpp>

using std::vector;
using std::string;
using std::setw;
using std::setfill;

namespace syslandscape {
namespace log {

ConversionMessage::ConversionMessage() {}

ConversionMessage::~ConversionMessage() {}

string ConversionMessage::getName() const {
  return "ConversionMessage";
}

bool ConversionMessage::setParameters(const vector<string>& params) noexcept {
  parseParameters(params);
  return true;
}

void ConversionMessage::format(const ConversionContext& context) const noexcept {
  context.output << setw(_width) << setfill(_fill);
  _alignment->align(context.output);
  context.output << context.event->message;
}

} /* namespace log */
} /* namespace syslandscape */


text:
package com.hyphenate.chatuidemo.ui;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hyphenate.chatuidemo.DemoApplication;
import com.hyphenate.chatuidemo.R;

import java.util.Locale;

/**
 * 滑动指示器pstsindicatorcolor颜色 在视图的底部的全宽度的线pstsunderlinecolor颜色
 * 选项卡之间的分隔pstsdividercolor颜色 滑动指示器pstsindicatorheightheight
 * 在视图的底部的全宽度的线pstsunderlineheight高度 pstsdividerpadding顶部和底部填充的分频器
 * pststabpaddingleftright左、右填充每个选项卡 pstsscrolloffset卷轴被选择的标签的偏移
 * pststabbackground背景绘制的每个标签,应该是一个statelistdrawable
 * pstsshouldexpand如果设置为TRUE,每个标签都给予同样的重量,默认为false
 * pststextallcaps如果为真,所有选项卡标题都是大写,默认为true
 */
public class PagerSlidingTabStrip extends HorizontalScrollView {

    private int flagPosition;//用来获取当前选中的标题
    private String lastTitle = "";//跳转之前的标题名字

    public interface IconTabProvider {
        public int getPageIconResId(int position);
    }

    private DoubleTitle doubleTitle;
    private int numberTitle;

    public interface DoubleTitle {
        public void getDoubleTitle(int numberTitle);
    }

    // @formatter:off
    private static final int[] ATTRS = new int[]{android.R.attr.textSize,
            android.R.attr.textColor};
    // @formatter:on

    private LinearLayout.LayoutParams defaultTabLayoutParams;
    private LinearLayout.LayoutParams expandedTabLayoutParams;

    private final PageListener pageListener = new PageListener();
    public OnPageChangeListener delegatePageListener;
    private GestureDetector mGestureDetector;
    private LinearLayout tabsContainer;
    private ViewPager pager;

    private int tabCount;

    private int currentPosition = 0;
    private int selectedPosition = 0;
    private int publicPosition = 0;//跳转之前的标题位置
    private float currentPositionOffset = 0f;

    private Paint rectPaint;
    private Paint dividerPaint;

    private int indicatorColor = 0xFF666666;
    private int underlineColor = 0x1A000000;
    private int dividerColor = 0x1A000000;

    private boolean shouldExpand = false;
    private boolean textAllCaps = true;

    private int scrollOffset = 52;
    private int indicatorHeight = 8;
    private int underlineHeight = 2;
    private int dividerPadding = 12;
    private int tabPadding = 24;
    private int dividerWidth = 1;

    private int tabTextSize = 16;// 字体大小
    private int tabTextColor = 0xFF666666;// 字体颜色
    private int selectedTabTextColor = 0xFF666666;// 选中后的字体颜色
    private Typeface tabTypeface = null;
    private int tabTypefaceStyle = Typeface.NORMAL;

    private int lastScrollX = 0;

    private int tabBackgroundResId = R.drawable.background_tab;

    private Locale locale;

    public PagerSlidingTabStrip(Context context) {
        this(context, null);
    }

    public PagerSlidingTabStrip(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PagerSlidingTabStrip(Context context, AttributeSet attrs,
                                int defStyle) {
        super(context, attrs, defStyle);

        setFillViewport(true);
        setWillNotDraw(false);

        tabsContainer = new LinearLayout(context);
        tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
        tabsContainer.setLayoutParams(new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        addView(tabsContainer);

        DisplayMetrics dm = getResources().getDisplayMetrics();

        scrollOffset = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm);
        indicatorHeight = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm);
        underlineHeight = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm);
        dividerPadding = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm);
        tabPadding = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm);
        dividerWidth = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm);
        tabTextSize = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm);

        // get system attrs (android:textSize and android:textColor)

        TypedArray a = context.obtainStyledAttributes(attrs, ATTRS);

        tabTextSize = a.getDimensionPixelSize(0, tabTextSize);
        tabTextColor = a.getColor(1, tabTextColor);

        a.recycle();

        // get custom attrs

        a = context.obtainStyledAttributes(attrs,
                R.styleable.PagerSlidingTabStrip);

        indicatorColor = a.getColor(
                R.styleable.PagerSlidingTabStrip_pstsIndicatorColor,
                indicatorColor);

        // tab文字选中时的颜色,默认和滑动指示器的颜色一致
        selectedTabTextColor = a.getColor(
                R.styleable.PagerSlidingTabStrip_selectedTabTextColor,
                indicatorColor);

        underlineColor = a.getColor(
                R.styleable.PagerSlidingTabStrip_pstsUnderlineColor,
                underlineColor);
        dividerColor = a
                .getColor(R.styleable.PagerSlidingTabStrip_pstsDividerColor,
                        dividerColor);
        indicatorHeight = a.getDimensionPixelSize(
                R.styleable.PagerSlidingTabStrip_pstsIndicatorHeight,
                indicatorHeight);
        underlineHeight = a.getDimensionPixelSize(
                R.styleable.PagerSlidingTabStrip_pstsUnderlineHeight,
                underlineHeight);
        dividerPadding = a.getDimensionPixelSize(
                R.styleable.PagerSlidingTabStrip_pstsDividerPadding,
                dividerPadding);
        tabPadding = a.getDimensionPixelSize(
                R.styleable.PagerSlidingTabStrip_pstsTabPaddingLeftRight,
                tabPadding);
        tabBackgroundResId = a.getResourceId(
                R.styleable.PagerSlidingTabStrip_pstsTabBackground,
                tabBackgroundResId);
        shouldExpand = a
                .getBoolean(R.styleable.PagerSlidingTabStrip_pstsShouldExpand,
                        shouldExpand);
        scrollOffset = a
                .getDimensionPixelSize(
                        R.styleable.PagerSlidingTabStrip_pstsScrollOffset,
                        scrollOffset);
        textAllCaps = a.getBoolean(
                R.styleable.PagerSlidingTabStrip_pstsTextAllCaps, textAllCaps);

        a.recycle();

        rectPaint = new Paint();
        rectPaint.setAntiAlias(true);
        rectPaint.setStyle(Style.FILL);

        dividerPaint = new Paint();
        dividerPaint.setAntiAlias(true);
        dividerPaint.setStrokeWidth(dividerWidth);

        defaultTabLayoutParams = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        expandedTabLayoutParams = new LinearLayout.LayoutParams(0,
                LayoutParams.MATCH_PARENT, 1.0f);

        if (locale == null) {
            locale = getResources().getConfiguration().locale;
        }
    }

    public void setViewPager(ViewPager pager) {
        this.pager = pager;

        if (pager.getAdapter() == null) {
            throw new IllegalStateException(
                    "ViewPager does not have adapter instance.");
        }

        pager.setOnPageChangeListener(pageListener);

        notifyDataSetChanged();
    }

    public void setOnPageChangeListener(OnPageChangeListener listener) {
        this.delegatePageListener = listener;
    }

    //设置双击标题的接口
    public void setDoubleTitleListener(DoubleTitle listener) {
        this.doubleTitle = listener;
    }

    public void notifyDataSetChanged() {

        tabsContainer.removeAllViews();

        tabCount = pager.getAdapter().getCount();

        for (int i = 0; i < tabCount; i++) {

            if (pager.getAdapter() instanceof IconTabProvider) {
                addIconTab(i,
                        ((IconTabProvider) pager.getAdapter())
                                .getPageIconResId(i));
            } else {
                addTextTab(i, pager.getAdapter().getPageTitle(i).toString());
            }

        }

        updateTabStyles();

        getViewTreeObserver().addOnGlobalLayoutListener(
                new OnGlobalLayoutListener() {

                    @Override
                    public void onGlobalLayout() {
                        getViewTreeObserver()
                                .removeGlobalOnLayoutListener(this);
                        currentPosition = pager.getCurrentItem();
                        scrollToChild(currentPosition, 0);
                    }
                });

    }

    private void addTextTab(final int position, String title) {

        TextView tab = new TextView(getContext());
        tab.setText(title);
        tab.setGravity(Gravity.CENTER);
        tab.setSingleLine();
        addTab(position, tab);
    }

    private void addIconTab(final int position, int resId) {

        ImageButton tab = new ImageButton(getContext());
        tab.setImageResource(resId);

        addTab(position, tab);

    }

    private class GestureListener extends GestureDetector.SimpleOnGestureListener {
        private final MatrixTouchListener listener;

        public GestureListener(MatrixTouchListener listener) {
            this.listener = listener;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            // 捕获Down事件
            return false;
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            // 触发双击事件
            // listener.onDoubleClick();
            if (doubleTitle != null) {
                View v = tabsContainer.getChildAt(flagPosition);
                String title = "";
                if (v instanceof TextView) {
                    title = ((TextView) v).getText().toString();
                }
                if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(lastTitle)) {
                    if (title.equals(lastTitle)) {
                        doubleTitle.getDoubleTitle(numberTitle);
                    }
                }
            }
            return true;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            // TODO Auto-generated method stub

            return super.onSingleTapUp(e);
        }

        @Override
        public void onLongPress(MotionEvent e) {
            // TODO Auto-generated method stub
            super.onLongPress(e);
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {
            return super.onScroll(e1, e2, distanceX, distanceY);
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {
            return super.onFling(e1, e2, velocityX, velocityY);
        }

        @Override
        public void onShowPress(MotionEvent e) {
            // TODO Auto-generated method stub
            super.onShowPress(e);
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            // TODO Auto-generated method stub
            return super.onDoubleTapEvent(e);
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            return super.onSingleTapConfirmed(e);
        }

    }

    public class MatrixTouchListener implements OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return mGestureDetector.onTouchEvent(event);
        }
    }

    private void addTab(final int position, View tab) {

        tab.setFocusable(true);
        tab.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                获取当前点击的标题位置
                flagPosition = position;
                //                获取当前点击的标题位置
                numberTitle = publicPosition;
//                后去上次标题的名字
                View view = tabsContainer.getChildAt(publicPosition);
                if (view instanceof TextView) {
                    lastTitle = ((TextView) view).getText().toString();
                }
                pager.setCurrentItem(position);
            }
        });
        MatrixTouchListener mListener = new MatrixTouchListener();
        if (tab != null) {
            tab.setOnTouchListener(mListener);
        }
        mGestureDetector = new GestureDetector(DemoApplication.getInstance(),
                new GestureListener(mListener));
        tab.setPadding(tabPadding, 0, tabPadding, 0);
        tabsContainer
                .addView(tab, position, shouldExpand ? expandedTabLayoutParams
                        : defaultTabLayoutParams);
    }

    private void updateTabStyles() {

        for (int i = 0; i < tabCount; i++) {

            View v = tabsContainer.getChildAt(i);

            v.setBackgroundResource(tabBackgroundResId);

            if (v instanceof TextView) {

                TextView tab = (TextView) v;
                tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize);
                tab.setTypeface(tabTypeface, tabTypefaceStyle);
                tab.setTextColor(tabTextColor);
                // tab.setTextColor(Color.WHITE);

                // setAllCaps() is only available from API 14, so the upper case
                // is made manually if we are on a
                // pre-ICS-build
                if (textAllCaps) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                        tab.setAllCaps(true);
                    } else {
                        tab.setText(tab.getText().toString()
                                .toUpperCase(locale));
                    }
                }
                if (i == selectedPosition) {
                    tab.setTextColor(selectedTabTextColor);
                    publicPosition = selectedPosition;
                }
            }
        }

    }

    private void scrollToChild(int position, int offset) {

        if (tabCount == 0) {
            return;
        }

        int newScrollX = tabsContainer.getChildAt(position).getLeft() + offset;

        if (position > 0 || offset > 0) {
            newScrollX -= scrollOffset;
        }

        if (newScrollX != lastScrollX) {
            lastScrollX = newScrollX;
            scrollTo(newScrollX, 0);
        }

    }

    private String lineFlag;

    public void setlineWidth(String flag) {
        // TODO Auto-generated method stub
        lineFlag = flag;
    }

    private String circleFlag;

    public void setcircleFlag(String flag) {
        // TODO Auto-generated method stub
        circleFlag = flag;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (isInEditMode() || tabCount == 0) {
            return;
        }

        final int height = getHeight();

        // draw underline
        if (!TextUtils.isEmpty(lineFlag)) {
            if (lineFlag.equals("ATTLINE")) {
                rectPaint
                        .setColor(getResources().getColor(R.color.transparent));
            }
        } else {
            rectPaint.setColor(underlineColor);
        }
        canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(),
                height, rectPaint);

        // draw indicator line
        rectPaint.setColor(indicatorColor);

        // default: line below current tab
        View currentTab = tabsContainer.getChildAt(currentPosition);
        float lineLeft = currentTab.getLeft();
        float lineRight = currentTab.getRight();

        // if there is an offset, start interpolating left and right coordinates
        // between current and next tab
        if (currentPositionOffset > 0f && currentPosition < tabCount - 1) {

            View nextTab = tabsContainer.getChildAt(currentPosition + 1);
            final float nextTabLeft = nextTab.getLeft();
            final float nextTabRight = nextTab.getRight();

            lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset)
                    * lineLeft);
            lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset)
                    * lineRight);
        }
        if (!TextUtils.isEmpty(lineFlag)) {
            if (lineFlag.equals("ATTLINE")) {

            }
        } else {
            canvas.drawRect(lineLeft, height - indicatorHeight, lineRight,
                    height, rectPaint);
        }

        dividerPaint.setColor(dividerColor);
        // draw divider

        for (int i = 0; i < tabCount; i++) {
            View tab = tabsContainer.getChildAt(i);
            canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(),
                    height - dividerPadding, dividerPaint);
//            以下是给标题画小红点的代码
//            if (!TextUtils.isEmpty(circleFlag)) {
//                if (circleFlag.equals("redCircleV")) {
//                    if (tab instanceof TextView) {
//                        String titv = ((TextView) tab).getText().toString();
//                        if (!TextUtils.isEmpty(titv)) {
//                            if (titv.equals("已收")) {
//                                Paint paint = new Paint();
//                                paint.setColor(getResources().getColor(
//                                        R.color.red));
//                                canvas.drawCircle(tab.getRight() - 60,
//                                        tab.getTop() + 40, 15, paint);
//                            }
//                        }
//                    }
//                } else if (circleFlag.equals("redCircleNV")) {
//                    if (tab instanceof TextView) {
//                        String titv = ((TextView) tab).getText().toString();
//                        if (!TextUtils.isEmpty(titv)) {
//                            if (titv.equals("已收")) {
//                                Paint paint = new Paint();
//                                paint.setColor(getResources().getColor(
//                                        R.color.white));
//                                canvas.drawCircle(tab.getRight() - 60,
//                                        tab.getTop() + 40, 15, paint);
//                            }
//                        }
//                    }
//                }
//            }
        }
    }

    private class PageListener implements OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {
            currentPosition = position;
            currentPositionOffset = positionOffset;

            scrollToChild(position, (int) (positionOffset * tabsContainer
                    .getChildAt(position).getWidth()));

            invalidate();

            if (delegatePageListener != null) {
                if (!TextUtils.isEmpty(lineFlag)) {
                    if (lineFlag.equals("ATTLINE")) {

                    }
                } else {
                    delegatePageListener.onPageScrolled(position,
                            positionOffset, positionOffsetPixels);
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if (state == ViewPager.SCROLL_STATE_IDLE) {
                scrollToChild(pager.getCurrentItem(), 0);
            }

            if (delegatePageListener != null) {
                delegatePageListener.onPageScrollStateChanged(state);
            }
        }

        @Override
        public void onPageSelected(int position) {
            selectedPosition = position;
            updateTabStyles();
            if (delegatePageListener != null) {
                delegatePageListener.onPageSelected(position);
            }
        }

    }

    public void setIndicatorColor(int indicatorColor) {
        this.indicatorColor = indicatorColor;

        invalidate();
    }

    public void setIndicatorColorResource(int resId) {
        this.indicatorColor = getResources().getColor(resId);

        invalidate();
    }

    public int getIndicatorColor() {
        return this.indicatorColor;
    }

    public void setIndicatorHeight(int indicatorLineHeightPx) {
        this.indicatorHeight = indicatorLineHeightPx;
        invalidate();
    }

    public int getIndicatorHeight() {
        return indicatorHeight;
    }

    public void setUnderlineColor(int underlineColor) {
        this.underlineColor = underlineColor;
        invalidate();
    }

    public void setUnderlineColorResource(int resId) {
        this.underlineColor = getResources().getColor(resId);
        invalidate();
    }

    public int getUnderlineColor() {
        return underlineColor;
    }

    public void setDividerColor(int dividerColor) {
        this.dividerColor = dividerColor;
        invalidate();
    }

    public void setDividerColorResource(int resId) {
        this.dividerColor = getResources().getColor(resId);
        invalidate();
    }

    public int getDividerColor() {
        return dividerColor;
    }

    public void setUnderlineHeight(int underlineHeightPx) {
        this.underlineHeight = underlineHeightPx;
        invalidate();
    }

    public int getUnderlineHeight() {
        return underlineHeight;
    }

    public void setDividerPadding(int dividerPaddingPx) {
        this.dividerPadding = dividerPaddingPx;
        invalidate();
    }

    public int getDividerPadding() {
        return dividerPadding;
    }

    public void setScrollOffset(int scrollOffsetPx) {
        this.scrollOffset = scrollOffsetPx;
        invalidate();
    }

    public int getScrollOffset() {
        return scrollOffset;
    }

    public void setShouldExpand(boolean shouldExpand) {
        this.shouldExpand = shouldExpand;
        notifyDataSetChanged();
    }

    public boolean getShouldExpand() {
        return shouldExpand;
    }

    public boolean isTextAllCaps() {
        return textAllCaps;
    }

    public void setAllCaps(boolean textAllCaps) {
        this.textAllCaps = textAllCaps;
    }

    public void setTextSize(int textSizePx) {
        this.tabTextSize = textSizePx;
        updateTabStyles();
    }

    public int getTextSize() {
        return tabTextSize;
    }

    public void setTextColor(int textColor) {
        this.tabTextColor = textColor;
        updateTabStyles();
    }

    public void setTextColorResource(int resId) {
        this.tabTextColor = getResources().getColor(resId);
        updateTabStyles();
    }

    public int getTextColor() {
        return tabTextColor;
    }

    public void setSelectedTextColor(int textColor) {
        this.selectedTabTextColor = textColor;
        updateTabStyles();
    }

    public void setSelectedTextColorResource(int resId) {
        this.selectedTabTextColor = getResources().getColor(resId);
        updateTabStyles();
    }

    public int getSelectedTextColor() {
        return selectedTabTextColor;
    }

    public void setTypeface(Typeface typeface, int style) {
        this.tabTypeface = typeface;
        this.tabTypefaceStyle = style;
        updateTabStyles();
    }

    public void setTabBackground(int resId) {
        this.tabBackgroundResId = resId;
        updateTabStyles();
    }

    public int getTabBackground() {
        return tabBackgroundResId;
    }

    public void setTabPaddingLeftRight(int paddingPx) {
        this.tabPadding = paddingPx;
        updateTabStyles();
    }

    public int getTabPaddingLeftRight() {
        return tabPadding;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState savedState = (SavedState) state;
        super.onRestoreInstanceState(savedState.getSuperState());
        currentPosition = savedState.currentPosition;
        requestLayout();
    }

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState savedState = new SavedState(superState);
        savedState.currentPosition = currentPosition;
        return savedState;
    }

    static class SavedState extends BaseSavedState {
        int currentPosition;

        public SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            currentPosition = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
            dest.writeInt(currentPosition);
        }

        public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }

}


text:
@interface CKIPage()
// these are private properties used to store the JSON values
// and used to create the derived lastEditedBy property.
@property (nonatomic, copy) NSString *lastEditedByID;
@property (nonatomic, copy) NSString *lastEditedByDisplayName;
@property (nonatomic, strong) NSURL *lastEditedByAvatarURL;
@end

@implementation CKIPage

+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
    NSDictionary *keyPaths = @{
        @"id": @"url",
        @"createdAt": @"created_at",
        @"updatedAt": @"updated_at",
        @"hideFromStudents": @"hide_from_students",
        @"lastEditedByID": @"last_edited_by.id",
        @"lastEditedByDisplayName": @"last_edited_by.display_name",
        @"lastEditedByAvatarURL": @"last_edited_by.avatar_image_url",
        @"published": @"published",
        @"frontPage": @"front_page",
        @"lockedForUser": @"locked_for_user",
        @"lockInfo": @"lock_info",
        @"lockExplanation": @"lock_explanation",
    };
    NSDictionary *superPaths = [super JSONKeyPathsByPropertyKey];
    return [superPaths dictionaryByAddingObjectsFromDictionary:keyPaths];
}

+ (NSValueTransformer *)idJSONTransformer
{
    return nil;
}

+ (NSValueTransformer *)createdAtJSONTransformer
{
    return [NSValueTransformer valueTransformerForName:CKIDateTransformerName];
}

+ (NSValueTransformer *)updatedAtJSONTransformer
{
    return [NSValueTransformer valueTransformerForName:CKIDateTransformerName];
}

+ (NSValueTransformer *)lastEditedByIDJSONTransformer
{
    return [NSValueTransformer valueTransformerForName:CKINumberStringTransformerName];
}

+ (NSValueTransformer *)lastEditedByAvatarURLJSONTransformer
{
    return [NSValueTransformer valueTransformerForName:MTLURLValueTransformerName];
}

- (CKIUser *)lastEditedBy
{
    CKIUser *user = [CKIUser new];
    user.id = self.lastEditedByID;
    user.name = self.lastEditedByDisplayName;
    user.avatarURL = self.lastEditedByAvatarURL;

    return user;
}

- (NSString *)path
{
    NSString *path = self.context.path;
    path = [path stringByAppendingPathComponent:@"pages"];
    return [path stringByAppendingPathComponent:self.id];
}

@end


text:
namespace water
{
    // Forward declarations.
    class Engine;

    /// <summary>
    /// A static class which can be used to manage the hot-swapping and retrieval of systems. This allows systems
    /// to be changed at run-time without impacting on the workings of the game and other systems. If systems have
    /// not been set then this WILL cause access violation errors.
    /// </summary>
    class Systems final
    {
        public:

            static IAudio&      audio()                                 { return *m_audio; }
            static IGameWorld&  gameWorld()                             { return *m_gameWorld; }
            static IInput&      input()                                 { return *m_input; }
            static ILogger&     logger()                                { return *m_logger; }
            static IPhysics&    physics()                               { return *m_physics; }
            static IRenderer&   renderer()                              { return *m_renderer; }
            static ITime&       time()                                  { return *m_time; }

        private:

            /// We let the water::Engine class be a friend so that it can set the systems.
            friend class water::Engine;

            static void         setAudio (IAudio* const system)         { m_audio = system; }
            static void         setGameWorld (IGameWorld* const system) { m_gameWorld = system; }
            static void         setInput (IInput* const system)         { m_input = system; }
            static void         setLogger (ILogger* const system)       { m_logger = system; }
            static void         setPhysics (IPhysics* const system)     { m_physics = system; }
            static void         setRenderer (IRenderer* const system)   { m_renderer = system; }
            static void         setTime (ITime* const system)           { m_time = system; }

            static IAudio*      m_audio;        //!< An audio system used for playing and manipulating sounds.
            static IGameWorld*  m_gameWorld;    //!< The game world system, allows manipulation of the game flow.
            static IInput*      m_input;        //!< An input system for obtaining abstracted input.
            static ILogger*     m_logger;       //!< The logger to be used for logging debug, warning or error messages.
            static IPhysics*    m_physics;      //!< The physics system used for collision detection by games.
            static IRenderer*   m_renderer;     //!< The renderering system which is used for drawing.
            static ITime*       m_time;         //!< The time system which keeps track of delta time values.
    };
}

#endif


text:
// CxDynObjs.cpp : Implementation of DLL Exports.

// Note: Proxy/Stub Information
//      To build a separate proxy/stub DLL,
//      run nmake -f CxDynObjsps.mk in the project directory.

#include "stdafx.h"
#include "resource.h"
#include <initguid.h>
#include "CxDynObjs.h"

#include "CxHmiObj_i.c"
#include "CxDynObjs_i.c"
#include "../CxScripCrt/CxScripCrt_i.c"

#include "LookupDynamic.h"
#include "LookupPage.h"
#include "LinearDynamic.h"
#include "LinearPage.h"
#include "FormatDynamic.h"
#include "FormatPage.h"
#include "DirectDynamic.h"
#include "DirectPage.h"
#include "DynamicFrm.h"

CComModule _Module;

BEGIN_OBJECT_MAP(ObjectMap)
OBJECT_ENTRY(CLSID_LookupDynamic, CLookupDynamic)
OBJECT_ENTRY(CLSID_LookupPage, CLookupPage)
OBJECT_ENTRY(CLSID_LinearDynamic, CLinearDynamic)
OBJECT_ENTRY(CLSID_LinearPage, CLinearPage)
OBJECT_ENTRY(CLSID_FormatDynamic, CFormatDynamic)
OBJECT_ENTRY(CLSID_FormatPage, CFormatPage)
OBJECT_ENTRY(CLSID_DirectDynamic, CDirectDynamic)
OBJECT_ENTRY(CLSID_DirectPage, CDirectPage)
OBJECT_ENTRY(CLSID_DynamicFrm, CDynamicFrm)
END_OBJECT_MAP()

/////////////////////////////////////////////////////////////////////////////
// DLL Entry Point

extern "C"
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/)
{
    if (dwReason == DLL_PROCESS_ATTACH)
    {
        _Module.Init(ObjectMap, hInstance, &LIBID_CXDYNOBJSLib);
        DisableThreadLibraryCalls(hInstance);
    }
    else if (dwReason == DLL_PROCESS_DETACH)
        _Module.Term();
    return TRUE;    // ok
}

/////////////////////////////////////////////////////////////////////////////
// Used to determine whether the DLL can be unloaded by OLE

STDAPI DllCanUnloadNow(void)
{
    return (_Module.GetLockCount()==0) ? S_OK : S_FALSE;
}

/////////////////////////////////////////////////////////////////////////////
// Returns a class factory to create an object of the requested type

STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv)
{
    return _Module.GetClassObject(rclsid, riid, ppv);
}

/////////////////////////////////////////////////////////////////////////////
// DllRegisterServer - Adds entries to the system registry

STDAPI DllRegisterServer(void)
{
    // registers object, typelib and all interfaces in typelib
    return _Module.RegisterServer(TRUE);
}

/////////////////////////////////////////////////////////////////////////////
// DllUnregisterServer - Removes entries from the system registry

STDAPI DllUnregisterServer(void)
{
    return _Module.UnregisterServer(TRUE);
}


text:
from  datetime import date
from django.db import models
from django.db.models import Q
from wagtail.wagtailcore.fields import RichTextField

from wagtail.wagtailcore.models import Page, Orderable
from wagtail.wagtailadmin.edit_handlers import FieldPanel, MultiFieldPanel, \
    InlinePanel, PageChooserPanel

from wagtail.wagtailimages.edit_handlers import ImageChooserPanel
from wagtail.wagtailimages.models import Image
from wagtail.wagtaildocs.edit_handlers import DocumentChooserPanel
from wagtail.wagtailsearch import index

from modelcluster.fields import ParentalKey

import geopy
from geopy.distance import VincentyDistance
from geopy.distance import vincenty
from geopy.geocoders import get_geocoder_for_service
from geopy.exc import GeocoderUnavailable

GEOCODING_SERVICE = 'google'
GOOGLE_MAPS_KEY = 'AIzaSyA3GpN-eFyREu8PkuNSC1y9J2g8MXtLldk'

EVENT_AUDIENCE_CHOICES = (
    ('public', "Public"),
    ('private', "Private"),
)

class Location(models.Model):
    class CouldNotGeocode(Exception):
        pass

    SEARCH_RADIUS = 10
    COMPASS_BEARING = {
        'NORTH': 0,
        'EAST': 90,
        'SOUTH': 180,
        'WEST': 270,
    }

    name = models.CharField(max_length=255,
                            blank=True)
    latitude = models.FloatField()
    longitude = models.FloatField()

    def __str__(self):
        return self.name

    def translate_point(self, bearing):
        origin = geopy.Point(self.latitude, self.longitude)
        destination = VincentyDistance(
            kilometers=self.SEARCH_RADIUS
        ).destination(origin, bearing)
        return destination

    def make_bounding_box(self, radius):
        max_lat = self.translate_point(
            self.COMPASS_BEARING['NORTH']
        ).latitude
        min_lat = self.translate_point(
            self.COMPASS_BEARING['SOUTH']
        ).latitude
        max_long = self.translate_point(
            self.COMPASS_BEARING['EAST']
        ).longitude
        min_long = self.translate_point(
            self.COMPASS_BEARING['WEST']
        ).longitude
        # Fetch locations within the bounding box
        locations = Location.objects.filter(
            latitude__gte=min_lat,
            latitude__lte=max_lat,
            longitude__gte=min_long,
            longitude__lte=max_long
        )
        return locations

    def vincenty_filter(self, locations, radius):
        nearby_locations = []
        for location in locations:
            distance = vincenty(
                (self.latitude, self.longitude),
                (location.latitude, location.longitude)
            ).kilometers
            if distance <= self.SEARCH_RADIUS:
                nearby_locations.append(location)
        return nearby_locations

    def find_nearby_locations(self):
        bb_locations = self.make_bounding_box(self.SEARCH_RADIUS)
        return self.vincenty_filter(bb_locations, self.SEARCH_RADIUS)

    def geocode(self):
        geocoder_for_service = get_geocoder_for_service(GEOCODING_SERVICE)
        geocoder = geocoder_for_service(api_key=GOOGLE_MAPS_KEY)
        geocoded_location = geocoder.geocode(self.name)
        if geocoded_location:
            self.latitude = geocoded_location.latitude
            self.longitude = geocoded_location.longitude
        else:
            raise self.CouldNotGeocode("Location: "+self.name)

    def save(self, *args, **kwargs):
        try:
            self.geocode()
            super(Location, self).save(*args, **kwargs)
        except (GeocoderUnavailable, self.CouldNotGeocode) as e:
            pass

class Locatable(models.Model):
    location_name = models.CharField(
        max_length=255,
        blank=True)
    location = models.ForeignKey(
        'home.Location',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
        editable=False
    )

    def save_location(self):
        if self.location_name:
            self.location = Location.objects.get_or_create(
                # iexact doesn't work with get_or_create :(
                name=self.location_name.upper()
            )[0]
            self.location.save()
        if not self.location_name and self.location:
            # If self.location_name has been set to None,
            # make sure to set self.location to None
            self.location = None

    @staticmethod
    def search_locations(q):
        location = Location()
        location.name = q
        try:
            location.geocode()
        except (GeocoderUnavailable, Location.CouldNotGeocode) as e:
            return Location.objects.all()

        return location.find_nearby_locations()

    def search_children_locations(self, q, model):
        return model.objects.filter(
            location__in=self.search_locations(q)
        ).child_of(self).live()

    def search_sibling_locations(self, q):
        return self.__class__.objects.filter(
            location__in=self.search_locations(q)
        ).sibling_of(self).live()

    panels = [
        FieldPanel('location_name')
    ]

    class Meta:
        abstract = True

#class HomePage(Page):
#    pass

class DummyHomePage(Page):
    pass

# A couple of abstract classes that contain commonly used fields

class LinkFields(models.Model):
    link_external = models.URLField("External link", blank=True)
    link_page = models.ForeignKey(
        'wagtailcore.Page',
        null=True,
        blank=True,
        related_name='+'
    )
    link_document = models.ForeignKey(
        'wagtaildocs.Document',
        null=True,
        blank=True,
        related_name='+'
    )

    @property
    def link(self):
        if self.link_page:
            return self.link_page.url
        elif self.link_document:
            return self.link_document.url
        else:
            return self.link_external

    panels = [
        FieldPanel('link_external'),
        PageChooserPanel('link_page'),
        DocumentChooserPanel('link_document'),
    ]

    class Meta:
        abstract = True

# Related links

class RelatedLink(LinkFields):
    title = models.CharField(max_length=255, help_text="Link title")

    panels = [
        FieldPanel('title'),
        MultiFieldPanel(LinkFields.panels, "Link"),
    ]

    class Meta:
        abstract = True

# Event index page

class EventIndexPageRelatedLink(Orderable, RelatedLink):
    page = ParentalKey('home.EventIndexPageGeo', related_name='related_links')

class EventIndexPageGeo(Page, Locatable):
    intro = RichTextField(blank=True)

    search_fields = Page.search_fields + (
        index.SearchField('intro',partial_match=True),
    )

    @property
    def events(self):
        # Get list of live event pages that are descendants of this page
        events = EventPageGeo.objects.live().descendant_of(self)

        # Filter events list to get ones that are either
        # running now ohttps://search.yahoo.com/yhs/searchh?hspart=ddc&hsimp=yhs-linuxmint&type=__alt__ddc_linuxmint_com&p=filtering+a+pagequery+setr start in the future
        events=events.filter(Q(date_from__gte=date.today()) | Q(date_to__gte=date.today()))
        print(events)
        # Order by date
        events = events.order_by('date_from')
        print (events)
        return events

    def get_context(self, request, *args, **kwargs):
        q = request.GET.get('q', '')
        location=Location()
        location.name=q
        if q:
            try:
               location.geocode()
            except (GeocoderUnavailable, location.CouldNotGeocode) as e:
              pages = EventPageGeo.objects.child_of(self).live()

            pages = self.search_children_locations(q, EventPageGeo)

        else:
            pages = EventPageGeo.objects.child_of(self).live()
        return {
            'self': self,
            'request': request,
            'GOOGLE_MAPS_KEY': GOOGLE_MAPS_KEY,
            'pages': pages,
	    'query': location
        }

    def save(self, *args, **kwargs):
        self.save_location()
        super(EventIndexPageGeo, self).save(*args, **kwargs)

EventIndexPageGeo.content_panels = [ FieldPanel('title', classname="full title") ] + Locatable.panels \
    + [ FieldPanel('intro', classname="full"),
       InlinePanel(EventIndexPageGeo, 'related_links', label="Related links"), ]

class EventPageGeoRelatedLink(Orderable, RelatedLink):
    page = ParentalKey('home.EventPageGeo', related_name='related_links')

class EventPageGeoSpeaker(Orderable, LinkFields):
    page = ParentalKey('home.EventPageGeo', related_name='speakers')
    first_name = models.CharField("Name", max_length=255, blank=True)
    last_name = models.CharField("Surname", max_length=255, blank=True)
    image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )

    @property
    def name_display(self):
        return self.first_name + " " + self.last_name

    panels = [
        FieldPanel('first_name'),
        FieldPanel('last_name'),
        ImageChooserPanel('image'),
        MultiFieldPanel(LinkFields.panels, "Link"),
    ]

class EventPageGeo(Page, Locatable):
    date_from = models.DateField("Start date",default=date.today())
    date_to = models.DateField(
        "End date",
        null=True,
        blank=True,
        help_text="Not required if event is on a single day"
    )

    time_from = models.TimeField("Start time", null=True, blank=True)
    time_to = models.TimeField("End time", null=True, blank=True)
    audience = models.CharField(max_length=255, choices=EVENT_AUDIENCE_CHOICES, default='public')
    text = RichTextField(blank=True)
    cost = models.CharField(max_length=255,default="Free")
    signup_link = models.URLField(blank=True)
    feed_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+'
    )

    def get_context(self, request, *args, **kwargs):
        return {
            'self': self,
            'request': request,
            'GOOGLE_MAPS_KEY': GOOGLE_MAPS_KEY,
            'pages': self.search_sibling_locations(
                request.GET.get('q', self.location_name)
            )
        }

    def save(self, *args, **kwargs):
        self.save_location()
        super(EventPageGeo, self).save(*args, **kwargs)

EventPageGeo.content_panels = [
    FieldPanel('title', classname="full title"),
] +Locatable.panels + [
    FieldPanel('date_from'),
    FieldPanel('date_to'),
    FieldPanel('time_from'),
    FieldPanel('time_to'),
    FieldPanel('audience'),
    FieldPanel('cost'),
    FieldPanel('signup_link'),
   # InlinePanel(EventPageGeo, 'carousel_items', label="Carousel items"),
    FieldPanel('text', classname="full"),
    InlinePanel(EventPageGeo, 'speakers', label="Speakers"),
    InlinePanel(EventPageGeo, 'related_links', label="Related links"),
]

EventPageGeo.promote_panels = Page.promote_panels + [
    ImageChooserPanel('feed_image'),
]