text:
package org.apache.reef.mock.runtime;

import org.apache.reef.annotations.Unstable;
import org.apache.reef.annotations.audience.Private;
import org.apache.reef.driver.context.ActiveContext;
import org.apache.reef.driver.context.ContextMessage;
import org.apache.reef.driver.context.FailedContext;
import org.apache.reef.driver.evaluator.AllocatedEvaluator;
import org.apache.reef.driver.evaluator.CompletedEvaluator;
import org.apache.reef.driver.evaluator.FailedEvaluator;
import org.apache.reef.driver.parameters.*;
import org.apache.reef.driver.task.*;
import org.apache.reef.io.Tuple;
import org.apache.reef.mock.MockRuntime;
import org.apache.reef.mock.MockTaskReturnValueProvider;
import org.apache.reef.mock.ProcessRequest;
import org.apache.reef.mock.request.*;
import org.apache.reef.tang.InjectionFuture;
import org.apache.reef.tang.annotations.Parameter;
import org.apache.reef.util.Optional;
import org.apache.reef.wake.EventHandler;
import org.apache.reef.wake.time.Clock;
import org.apache.reef.wake.time.event.StartTime;
import org.apache.reef.wake.time.event.StopTime;

import javax.inject.Inject;
import java.util.*;

/**
 * mock runtime driver.
 */
@Unstable
@Private
public final class MockRuntimeDriver implements MockRuntime {

  private final InjectionFuture<MockClock> clock;

  private final List<ProcessRequest> processRequestQueue = new ArrayList<>();

  private final Set<EventHandler<StartTime>> driverStartHandlers;

  private final Set<EventHandler<StopTime>> driverStopHandlers;

  private final Set<EventHandler<AllocatedEvaluator>> allocatedEvaluatorHandlers;

  private final Set<EventHandler<CompletedEvaluator>> completedEvaluatorHandlers;

  private final Set<EventHandler<FailedEvaluator>> failedEvaluatorHandlers;

  private final Set<EventHandler<TaskRunningHandlers>> taskRunningHandlers;

  private final Set<EventHandler<FailedTask>> taskFailedHandlers;

  private final Set<EventHandler<TaskMessage>> taskMessageHandlers;

  private final Set<EventHandler<CompletedTask>> taskCompletedHandlers;

  private final Set<EventHandler<SuspendedTask>> taskSuspendedHandlers;

  private final Set<EventHandler<ActiveContext>> contextActiveHandlers;

  private final Set<EventHandler<CloseContext>> contextClosedHandlers;

  private final Set<EventHandler<ContextMessage>> contextMessageHandlers;

  private final Set<EventHandler<FailedContext>> contextFailedHandlers;

  private final Map<String, MockAllocatedEvalautor> allocatedEvaluatorMap = new HashMap<>();

  private final Map<String, List<MockActiveContext>> allocatedContextsMap = new HashMap<>();

  private final Map<String, MockRunningTask> runningTasks = new HashMap<>();

  private final MockTaskReturnValueProvider taskReturnValueProvider;

  @Inject
  MockRuntimeDriver(
      final InjectionFuture<MockClock> clock,
      final MockTaskReturnValueProvider taskReturnValueProvider,
      @Parameter(DriverStartHandler.class) final Set<EventHandler<StartTime>> driverStartHandlers,
      @Parameter(Clock.StopHandler.class) final Set<EventHandler<StopTime>> driverStopHandlers,
      @Parameter(EvaluatorAllocatedHandlers.class) final Set<EventHandler<AllocatedEvaluator>>
          allocatedEvaluatorHandlers,
      @Parameter(EvaluatorCompletedHandlers.class) final Set<EventHandler<CompletedEvaluator>>
          completedEvaluatorHandlers,
      @Parameter(EvaluatorFailedHandlers.class) final Set<EventHandler<FailedEvaluator>> failedEvaluatorHandlers,
      @Parameter(TaskRunningHandlers.class) final Set<EventHandler<TaskRunningHandlers>> taskRunningHandlers,
      @Parameter(TaskFailedHandlers.class) final Set<EventHandler<FailedTask>> taskFailedHandlers,
      @Parameter(TaskMessageHandlers.class) final Set<EventHandler<TaskMessage>> taskMessageHandlers,
      @Parameter(TaskCompletedHandlers.class) final Set<EventHandler<CompletedTask>> taskCompletedHandlers,
      @Parameter(TaskSuspendedHandlers.class) final Set<EventHandler<SuspendedTask>> taskSuspendedHandlers,
      @Parameter(ContextActiveHandlers.class) final Set<EventHandler<ActiveContext>> contextActiveHandlers,
      @Parameter(ContextClosedHandlers.class) final Set<EventHandler<CloseContext>> contextClosedHandlers,
      @Parameter(ContextMessageHandlers.class) final Set<EventHandler<ContextMessage>> contextMessageHandlers,
      @Parameter(ContextFailedHandlers.class) final Set<EventHandler<FailedContext>> contextFailedHandlers) {
    this.clock = clock;
    this.taskReturnValueProvider = taskReturnValueProvider;
    this.driverStartHandlers = driverStartHandlers;
    this.driverStopHandlers = driverStopHandlers;
    this.allocatedEvaluatorHandlers = allocatedEvaluatorHandlers;
    this.completedEvaluatorHandlers = completedEvaluatorHandlers;
    this.failedEvaluatorHandlers = failedEvaluatorHandlers;
    this.taskRunningHandlers = taskRunningHandlers;
    this.taskFailedHandlers = taskFailedHandlers;
    this.taskMessageHandlers = taskMessageHandlers;
    this.taskCompletedHandlers = taskCompletedHandlers;
    this.taskSuspendedHandlers = taskSuspendedHandlers;
    this.contextActiveHandlers = contextActiveHandlers;
    this.contextClosedHandlers = contextClosedHandlers;
    this.contextMessageHandlers = contextMessageHandlers;
    this.contextFailedHandlers = contextFailedHandlers;
  }

  @Override
  public Collection<AllocatedEvaluator> getCurrentAllocatedEvaluators() {
    if (this.clock.get().isClosed()) {
      throw new IllegalStateException("clock is closed");
    }
    return new ArrayList<AllocatedEvaluator>(this.allocatedEvaluatorMap.values());
  }

  @Override
  public void fail(final AllocatedEvaluator evaluator) {
    if (this.clock.get().isClosed()) {
      throw new IllegalStateException("clock is closed");
    }
    if (this.allocatedEvaluatorMap.containsKey(evaluator.getId())) {
      FailedTask failedTask =  null;
      if (this.runningTasks.containsKey(evaluator.getId())) {
        final RunningTask task = this.runningTasks.remove(evaluator.getId());
        failedTask = new FailedTask(
            task.getId(),
            "mock",
            Optional.<String>empty(),
            Optional.<Throwable>empty(),
            Optional.<byte[]>empty(),
            Optional.<ActiveContext>of(task.getActiveContext()));
      }
      final List<FailedContext> failedContexts = new ArrayList<>();
      for (final MockActiveContext context : this.allocatedContextsMap.get(evaluator.getId())) {
        failedContexts.add(new MockFailedContext(context));
      }
      this.allocatedContextsMap.remove(evaluator.getId());

      post(this.failedEvaluatorHandlers, new MockFailedEvaluator(
          evaluator.getId(), failedContexts,
          failedTask == null ? Optional.<FailedTask>empty() : Optional.of(failedTask)));
    } else {
      throw new IllegalStateException("unknown evaluator " + evaluator);
    }
  }

  @Override
  public Collection<ActiveContext> getCurrentActiveContexts() {
    if (this.clock.get().isClosed()) {
      throw new IllegalStateException("clock is closed");
    }
    final List<ActiveContext> currentActiveContexts = new ArrayList<>();
    for (final List<MockActiveContext> contexts : this.allocatedContextsMap.values()) {
      currentActiveContexts.addAll(contexts);
    }
    return currentActiveContexts;
  }

  @Override
  public void fail(final ActiveContext context) {
    if (this.clock.get().isClosed()) {
      throw new IllegalStateException("clock is closed");
    }
    final MockAllocatedEvalautor evaluator = ((MockActiveContext) context).getEvaluator();
    post(this.contextFailedHandlers, new MockFailedContext((MockActiveContext) context));
    if (!((MockActiveContext) context).getParentContext().isPresent()) {
      // root context failure shuts evalautor down
      fail(evaluator);
    } else {
      this.allocatedContextsMap.get(evaluator.getId()).remove(context);
    }
  }

  @Override
  public Collection<RunningTask> getCurrentRunningTasks() {
    if (this.clock.get().isClosed()) {
      throw new IllegalStateException("clock is closed");
    }
    return new ArrayList<RunningTask>(this.runningTasks.values());
  }

  @Override
  public void fail(final RunningTask task) {
    if (this.clock.get().isClosed()) {
      throw new IllegalStateException("clock is closed");
    }
    final String evaluatorID = task.getActiveContext().getEvaluatorId();
    if (this.runningTasks.containsKey(evaluatorID) &&
        this.runningTasks.get(evaluatorID).equals(task)) {
      this.runningTasks.remove(evaluatorID);
      post(taskFailedHandlers, new FailedTask(
          task.getId(),
          "mock",
          Optional.<String>empty(),
          Optional.<Throwable>empty(),
          Optional.<byte[]>empty(),
          Optional.of(task.getActiveContext())));
    } else {
      throw new IllegalStateException("unknown running task " + task);
    }
  }

  @Override
  public void start() {
    post(this.driverStartHandlers, new StartTime(this.clock.get().getCurrentTime()));
  }

  @Override
  public void stop() {
    post(this.driverStopHandlers, new StopTime(this.clock.get().getCurrentTime()));
  }

  @Override
  public boolean hasProcessRequest() {
    return this.processRequestQueue.size() > 0;
  }

  @Override
  public ProcessRequest getNextProcessRequest() {
    if (this.processRequestQueue.size() > 0) {
      return this.processRequestQueue.remove(0);
    } else {
      return null;
    }
  }

  @Override
  public void succeed(final ProcessRequest pr) {
    if (this.clock.get().isClosed()) {
      throw new IllegalStateException("clock is closed");
    }
    final ProcessRequestInternal request = (ProcessRequestInternal) pr;
    switch (request.getType()) {
    case ALLOCATE_EVALUATOR:
      final MockAllocatedEvalautor allocatedEvalautor = ((AllocateEvaluator)request).getSuccessEvent();
      validateAndCreate(allocatedEvalautor);
      post(this.allocatedEvaluatorHandlers, allocatedEvalautor);
      post(this.contextActiveHandlers, allocatedEvalautor.getRootContext());
      break;
    case CLOSE_EVALUATOR:
      final CompletedEvaluator closedEvaluator = ((CloseEvaluator)request).getSuccessEvent();
      validateAndClose(closedEvaluator);
      post(this.completedEvaluatorHandlers, closedEvaluator);
      break;
    case CREATE_CONTEXT:
      final MockActiveContext createContext = ((CreateContext) request).getSuccessEvent();
      validateAndCreate(createContext);
      post(this.contextActiveHandlers, createContext);
      break;
    case CLOSE_CONTEXT:
      final MockClosedContext closeContext = ((CloseContext) request).getSuccessEvent();
      validateAndClose(closeContext);
      post(this.contextClosedHandlers, closeContext);
      break;
    case CREATE_TASK:
      final MockRunningTask createTask = ((CreateTask)request).getSuccessEvent();
      validateAndCreate(createTask);
      post(this.taskRunningHandlers, request.getSuccessEvent());
      break;
    case SUSPEND_TASK:
      final MockRunningTask suspendedTask = ((SuspendTask)request).getTask();
      validateAndClose(suspendedTask);
      post(this.taskSuspendedHandlers, request.getSuccessEvent());
      break;
    case CLOSE_TASK:
    case COMPLETE_TASK:
      final MockRunningTask completedTask = ((CompleteTask)request).getTask();
      validateAndClose(completedTask);
      post(this.taskCompletedHandlers, request.getSuccessEvent());
      break;
    case CREATE_CONTEXT_AND_TASK:
      final CreateContextAndTask createContextTask = (CreateContextAndTask) request;
      final Tuple<MockActiveContext, MockRunningTask> events = createContextTask.getSuccessEvent();
      validateAndCreate(events.getKey());
      post(this.contextActiveHandlers, events.getKey());
      validateAndCreate(events.getValue());
      post(this.taskRunningHandlers, events.getValue());
      break;
    case SEND_MESSAGE_DRIVER_TO_TASK:
      // ignore
      break;
    case SEND_MESSAGE_DRIVER_TO_CONTEXT:
      // ignore
      break;
    default:
      throw new IllegalStateException("unknown type");
    }

    if (request.doAutoComplete()) {
      add(request.getCompletionProcessRequest());
    } else if (!this.clock.get().isClosed() && isIdle()) {
      this.clock.get().close();
    }
  }

  @Override
  public void fail(final ProcessRequest pr) {
    if (this.clock.get().isClosed()) {
      throw new IllegalStateException("clock is closed");
    }
    final ProcessRequestInternal request = (ProcessRequestInternal) pr;
    switch (request.getType()) {
    case ALLOCATE_EVALUATOR:
      post(this.failedEvaluatorHandlers, request.getFailureEvent());
      break;
    case CLOSE_EVALUATOR:
      final CompletedEvaluator evaluator = ((CloseEvaluator)request).getSuccessEvent();
      validateAndClose(evaluator);
      post(this.failedEvaluatorHandlers, request.getFailureEvent());
      break;
    case CREATE_CONTEXT:
      post(this.contextFailedHandlers, request.getFailureEvent());
      break;
    case CLOSE_CONTEXT:
      final MockClosedContext context = ((CloseContext)request).getSuccessEvent();
      validateAndClose(context);
      if (context.getParentContext() == null) {
        add(new CloseEvaluator(context.getMockActiveContext().getEvaluator()));
      }
      post(this.contextFailedHandlers, request.getFailureEvent());
      break;
    case CREATE_TASK:
      post(this.taskFailedHandlers, request.getFailureEvent());
      break;
    case SUSPEND_TASK:
      validateAndClose(((SuspendTask)request).getTask());
      post(this.taskFailedHandlers, request.getFailureEvent());
      break;
    case CLOSE_TASK:
    case COMPLETE_TASK:
      validateAndClose(((CloseTask)request).getTask());
      post(this.taskFailedHandlers, request.getFailureEvent());
      break;
    case CREATE_CONTEXT_AND_TASK:
      final CreateContextAndTask createContextTask = (CreateContextAndTask) request;
      final Tuple<MockFailedContext, FailedTask> events = createContextTask.getFailureEvent();
      post(this.taskFailedHandlers, events.getValue());
      post(this.contextFailedHandlers, events.getKey());
      break;
    case SEND_MESSAGE_DRIVER_TO_TASK:
      // ignore
      break;
    case SEND_MESSAGE_DRIVER_TO_CONTEXT:
      // ignore
      break;
    default:
      throw new IllegalStateException("unknown type");
    }

    if (!this.clock.get().isClosed() && isIdle()) {
      this.clock.get().close();
    }
  }

  MockTaskReturnValueProvider getTaskReturnValueProvider() {
    return this.taskReturnValueProvider;
  }
  /**
   * Used by mock REEF entities (e.g., AllocatedEvaluator, RunningTask) to inject
   * process requests from initiated actions e.g., RunningTask.close().
   * @param request to inject
   */
  void add(final ProcessRequest request) {
    this.processRequestQueue.add(request);
  }

  private boolean isIdle() {
    return this.clock.get().isIdle() &&
        this.processRequestQueue.isEmpty() &&
        this.allocatedEvaluatorMap.isEmpty();
  }

  private <T> void post(final Set<EventHandler<T>> handlers, final Object event) {
    for (final EventHandler<T> handler : handlers) {
      handler.onNext((T) event);
    }
  }

  private void validateAndCreate(final MockActiveContext context) {
    if (!this.allocatedEvaluatorMap.containsKey(context.getEvaluatorId())) {
      throw new IllegalStateException("unknown evaluator id " + context.getEvaluatorId());
    } else if (!this.allocatedContextsMap.containsKey(context.getEvaluatorId())) {
      this.allocatedContextsMap.put(context.getEvaluatorId(), new ArrayList<MockActiveContext>());
    }
    this.allocatedContextsMap.get(context.getEvaluatorId()).add(context);
  }

  private void validateAndClose(final MockClosedContext context) {
    if (!this.allocatedContextsMap.containsKey(context.getEvaluatorId())) {
      throw new IllegalStateException("unknown evaluator id " + context.getEvaluatorId());
    }
    final List<MockActiveContext> contexts = this.allocatedContextsMap.get(context.getEvaluatorId());
    if (!contexts.get(contexts.size() - 1).equals(context.getMockActiveContext())) {
      throw new IllegalStateException("closing context that is not on the top of the stack");
    }
    contexts.remove(context.getMockActiveContext());
  }

  private void validateAndCreate(final MockRunningTask task) {
    if (this.runningTasks.containsKey(task.evaluatorID())) {
      throw new IllegalStateException("task already running on evaluator " +
          task.evaluatorID());
    }
    this.runningTasks.put(task.evaluatorID(), task);
  }

  private void validateAndClose(final MockRunningTask task) {
    if (!this.runningTasks.containsKey(task.getActiveContext().getEvaluatorId())) {
      throw new IllegalStateException("no task running on evaluator");
    }
    this.runningTasks.remove(task.getActiveContext().getEvaluatorId());
  }

  private void validateAndCreate(final MockAllocatedEvalautor evalutor) {
    if (this.allocatedEvaluatorMap.containsKey(evalutor.getId())) {
      throw new IllegalStateException("evaluator id " + evalutor.getId() + " already exists");
    }
    this.allocatedEvaluatorMap.put(evalutor.getId(), evalutor);
    this.allocatedContextsMap.put(evalutor.getId(), new ArrayList<MockActiveContext>());
    this.allocatedContextsMap.get(evalutor.getId()).add(evalutor.getRootContext());
  }

  private void validateAndClose(final CompletedEvaluator evalautor) {
    if (!this.allocatedEvaluatorMap.containsKey(evalautor.getId())) {
      throw new IllegalStateException("unknown evaluator id " + evalautor.getId());
    }
    this.allocatedEvaluatorMap.remove(evalautor.getId());
  }
}


text:
<?php

namespace PHPEnv;

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Zend\Diactoros\ServerRequest;
use Zend\Diactoros\Response;
use Zend\Diactoros\Server as ZendServer;

class Server {
    private $server;

    public function __construct(){
        $codepath = '/userfunc/user';

        //if i have a local function i use it
        $devcodepath = '/app/userfuncdev.php';
        if(file_exists($devcodepath))
            $codepath = $devcodepath;

        $logger = new Logger("Function");
        $logger->pushHandler(new StreamHandler('php://stdout', Logger::DEBUG));

        $this->server = ZendServer::createServer(
            function (ServerRequest $request, Response $response) use ($logger, $codepath) {
                $path = parse_url($request->getUri(), PHP_URL_PATH);

                if($path == "/specialize" && $request->getMethod() == "POST"){
                    //Nothing to do
                    return new Response\EmptyResponse(201);
                }else{
                    if(!file_exists($codepath)){
                        $response = $response->withStatus(500);
                        $response->getBody()->write("Generic container: no requests supported");
                        return $response;
                    }

                    ob_start();
                    include($codepath);
                    //If the function as an handler class it will be called with request, response and logger
                    if(function_exists("handler")){
                        ob_end_clean();
                        return handler(array("request"=>$request, "response"=>$response,"logger"=>$logger));
                    }
                    //php code didn't have handler function, i will return the content
                    $bodyRowContent = ob_get_contents();
                    ob_end_clean();
                    return $response->getBody()->write($bodyRowContent);
                }
            },
            $_SERVER,
            $_GET,
            $_POST,
            $_COOKIE,
            $_FILES
        );
    }

    public function run(){
        $this->server->listen();
    }
}
?>

redpajama_set_name: RedPajamaGithub


text:
HTTP/1.1 200 OK
Server: Apache
Date: Wed, 09 Dec 2015 03:29:14 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive

You can send me a webmention or pingback

    <link href="http://webmention.example/link" rel="webmention">


text:
/*
* <auto-generated>
*     This code was generated by a tool.
*
*     Changes to this file may cause incorrect behavior and will be lost if
*     the code is regenerated.
* </auto-generated>
*/

#import <Foundation/Foundation.h>
#import "MOZUClient.h"
#import "MOZUCustomerSegment.h"
#import "MOZUCustomerSegmentCollection.h"

@interface MOZUCustomerSegmentClient : NSObject

//
#pragma mark -
#pragma mark Get Operations
#pragma mark -
//

/**
Retrieves a list of defined customer segments according to any filter and sort criteria.
@param filter A set of expressions that consist of a field, operator, and value and represent search parameter syntax when filtering results of a query. Valid operators include equals (eq), does not equal (ne), greater than (gt), less than (lt), greater than or equal to (ge), less than or equal to (le), starts with (sw), or contains (cont). For example - "filter=IsDisplayed+eq+true"
@param pageSize The number of results to display on each page when creating paged results from a query. The maximum value is 200.
@param responseFields Use this field to include those fields which are not included by default.
@param sortBy The property by which to sort results and whether the results appear in ascending (a-z) order, represented by ASC or in descending (z-a) order, represented by DESC. The sortBy parameter follows an available property. For example: "sortBy=productCode+asc"
@param startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with a PageSize of 25, to get the 51st through the 75th items, use startIndex=3.
*/

+ (MOZUClient *)clientForGetSegmentsOperationWithStartIndex:(NSNumber *)startIndex pageSize:(NSNumber *)pageSize sortBy:(NSString *)sortBy filter:(NSString *)filter responseFields:(NSString *)responseFields;

/**
Retrieves the details of the customer segment specified in the request. This operation does not return a list of the customer accounts associated with the segment.
@param identifier Unique identifier of the customer segment to retrieve.
@param responseFields Use this field to include those fields which are not included by default.
*/

+ (MOZUClient *)clientForGetSegmentOperationWithIdentifier:(NSInteger)identifier responseFields:(NSString *)responseFields;

//
#pragma mark -
#pragma mark Post Operations
#pragma mark -
//

/**
Creates a new customer segments. New customer segments do not have any associated customer accounts.
@param body The Customer Segment object includes properties of a defined customer segment used to group customer accounts.
@param responseFields Use this field to include those fields which are not included by default.
*/

+ (MOZUClient *)clientForAddSegmentOperationWithBody:(MOZUCustomerSegment *)body responseFields:(NSString *)responseFields;

/**
Adds one or more customer accounts to a defined customer segment.
@param body List of customer account IDs to add to the customer segment specified in the request.
@param identifier Unique identifier of the customer segment to retrieve.
*/

+ (MOZUClient *)clientForAddSegmentAccountsOperationWithBody:(NSArray *)body identifier:(NSInteger)identifier;

//
#pragma mark -
#pragma mark Put Operations
#pragma mark -
//

/**
Updates the details of the customer segment specified in the request.
@param body The Customer Segment object includes properties of a defined customer segment used to group customer accounts.
@param identifier Unique identifier of the customer segment to retrieve.
@param responseFields Use this field to include those fields which are not included by default.
*/

+ (MOZUClient *)clientForUpdateSegmentOperationWithBody:(MOZUCustomerSegment *)body identifier:(NSInteger)identifier responseFields:(NSString *)responseFields;

//
#pragma mark -
#pragma mark Delete Operations
#pragma mark -
//

/**
Deletes a customer segment specified by its unique identifier. Deleting a segment removes any customer account associations, but does not delete the customer account itself.
@param identifier Unique identifier of the customer segment to retrieve.
*/

+ (MOZUClient *)clientForDeleteSegmentOperationWithIdentifier:(NSInteger)identifier;

/**
Removes single account from a segment.
@param accountId Unique identifier of the customer account.
@param identifier Unique identifier of the customer segment to retrieve.
*/

+ (MOZUClient *)clientForRemoveSegmentAccountOperationWithIdentifier:(NSInteger)identifier accountId:(NSInteger)accountId;

@end


text:
package it.unitn.ing.rista.diffr.measurement;

import java.lang.*;

import it.unitn.ing.rista.diffr.*;
import it.unitn.ing.rista.awt.*;
import it.unitn.ing.rista.util.*;

import java.awt.*;
import java.awt.*;
import java.awt.event.*;

/**
 *  The ReflectivityMeasurement is a class
 *
 *
 * @version $Revision: 1.4 $, $Date: 2004/08/12 09:36:07 $
 * @author Luca Lutterotti
 * @since JDK1.1
 */

public class ReflectivityMeasurement extends Theta2ThetaMeasurement {

  public ReflectivityMeasurement(XRDcat aobj, String alabel) {
    super(aobj, alabel);
    identifier = "Reflectivity scan";
    IDlabel = "Theta-2Theta";
    description = "Reflectivity measurement method";
  }

  public ReflectivityMeasurement(XRDcat aobj) {
    this(aobj, "Reflectivity scan");
  }

  public ReflectivityMeasurement() {
    identifier = "Reflectivity scan";
    IDlabel = "Reflectivity scan";
    description = "Reflectivity measurement method";
  }

}


text:
package mocks

import (
	"context"
	"sync"

	"github.com/hyperledger/fabric-protos-go/common"
	"github.com/hyperledger/fabric-protos-go/orderer"
	"google.golang.org/grpc/metadata"
)

type Orderer struct {
	CloseSendStub        func() error
	closeSendMutex       sync.RWMutex
	closeSendArgsForCall []struct {
	}
	closeSendReturns struct {
		result1 error
	}
	closeSendReturnsOnCall map[int]struct {
		result1 error
	}
	ContextStub        func() context.Context
	contextMutex       sync.RWMutex
	contextArgsForCall []struct {
	}
	contextReturns struct {
		result1 context.Context
	}
	contextReturnsOnCall map[int]struct {
		result1 context.Context
	}
	HeaderStub        func() (metadata.MD, error)
	headerMutex       sync.RWMutex
	headerArgsForCall []struct {
	}
	headerReturns struct {
		result1 metadata.MD
		result2 error
	}
	headerReturnsOnCall map[int]struct {
		result1 metadata.MD
		result2 error
	}
	RecvStub        func() (*orderer.BroadcastResponse, error)
	recvMutex       sync.RWMutex
	recvArgsForCall []struct {
	}
	recvReturns struct {
		result1 *orderer.BroadcastResponse
		result2 error
	}
	recvReturnsOnCall map[int]struct {
		result1 *orderer.BroadcastResponse
		result2 error
	}
	RecvMsgStub        func(interface{}) error
	recvMsgMutex       sync.RWMutex
	recvMsgArgsForCall []struct {
		arg1 interface{}
	}
	recvMsgReturns struct {
		result1 error
	}
	recvMsgReturnsOnCall map[int]struct {
		result1 error
	}
	SendStub        func(*common.Envelope) error
	sendMutex       sync.RWMutex
	sendArgsForCall []struct {
		arg1 *common.Envelope
	}
	sendReturns struct {
		result1 error
	}
	sendReturnsOnCall map[int]struct {
		result1 error
	}
	SendMsgStub        func(interface{}) error
	sendMsgMutex       sync.RWMutex
	sendMsgArgsForCall []struct {
		arg1 interface{}
	}
	sendMsgReturns struct {
		result1 error
	}
	sendMsgReturnsOnCall map[int]struct {
		result1 error
	}
	TrailerStub        func() metadata.MD
	trailerMutex       sync.RWMutex
	trailerArgsForCall []struct {
	}
	trailerReturns struct {
		result1 metadata.MD
	}
	trailerReturnsOnCall map[int]struct {
		result1 metadata.MD
	}
	invocations      map[string][][]interface{}
	invocationsMutex sync.RWMutex
}

func (fake *Orderer) CloseSend() error {
	fake.closeSendMutex.Lock()
	ret, specificReturn := fake.closeSendReturnsOnCall[len(fake.closeSendArgsForCall)]
	fake.closeSendArgsForCall = append(fake.closeSendArgsForCall, struct {
	}{})
	fake.recordInvocation("CloseSend", []interface{}{})
	fake.closeSendMutex.Unlock()
	if fake.CloseSendStub != nil {
		return fake.CloseSendStub()
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.closeSendReturns
	return fakeReturns.result1
}

func (fake *Orderer) CloseSendCallCount() int {
	fake.closeSendMutex.RLock()
	defer fake.closeSendMutex.RUnlock()
	return len(fake.closeSendArgsForCall)
}

func (fake *Orderer) CloseSendCalls(stub func() error) {
	fake.closeSendMutex.Lock()
	defer fake.closeSendMutex.Unlock()
	fake.CloseSendStub = stub
}

func (fake *Orderer) CloseSendReturns(result1 error) {
	fake.closeSendMutex.Lock()
	defer fake.closeSendMutex.Unlock()
	fake.CloseSendStub = nil
	fake.closeSendReturns = struct {
		result1 error
	}{result1}
}

func (fake *Orderer) CloseSendReturnsOnCall(i int, result1 error) {
	fake.closeSendMutex.Lock()
	defer fake.closeSendMutex.Unlock()
	fake.CloseSendStub = nil
	if fake.closeSendReturnsOnCall == nil {
		fake.closeSendReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.closeSendReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *Orderer) Context() context.Context {
	fake.contextMutex.Lock()
	ret, specificReturn := fake.contextReturnsOnCall[len(fake.contextArgsForCall)]
	fake.contextArgsForCall = append(fake.contextArgsForCall, struct {
	}{})
	fake.recordInvocation("Context", []interface{}{})
	fake.contextMutex.Unlock()
	if fake.ContextStub != nil {
		return fake.ContextStub()
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.contextReturns
	return fakeReturns.result1
}

func (fake *Orderer) ContextCallCount() int {
	fake.contextMutex.RLock()
	defer fake.contextMutex.RUnlock()
	return len(fake.contextArgsForCall)
}

func (fake *Orderer) ContextCalls(stub func() context.Context) {
	fake.contextMutex.Lock()
	defer fake.contextMutex.Unlock()
	fake.ContextStub = stub
}

func (fake *Orderer) ContextReturns(result1 context.Context) {
	fake.contextMutex.Lock()
	defer fake.contextMutex.Unlock()
	fake.ContextStub = nil
	fake.contextReturns = struct {
		result1 context.Context
	}{result1}
}

func (fake *Orderer) ContextReturnsOnCall(i int, result1 context.Context) {
	fake.contextMutex.Lock()
	defer fake.contextMutex.Unlock()
	fake.ContextStub = nil
	if fake.contextReturnsOnCall == nil {
		fake.contextReturnsOnCall = make(map[int]struct {
			result1 context.Context
		})
	}
	fake.contextReturnsOnCall[i] = struct {
		result1 context.Context
	}{result1}
}

func (fake *Orderer) Header() (metadata.MD, error) {
	fake.headerMutex.Lock()
	ret, specificReturn := fake.headerReturnsOnCall[len(fake.headerArgsForCall)]
	fake.headerArgsForCall = append(fake.headerArgsForCall, struct {
	}{})
	fake.recordInvocation("Header", []interface{}{})
	fake.headerMutex.Unlock()
	if fake.HeaderStub != nil {
		return fake.HeaderStub()
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	fakeReturns := fake.headerReturns
	return fakeReturns.result1, fakeReturns.result2
}

func (fake *Orderer) HeaderCallCount() int {
	fake.headerMutex.RLock()
	defer fake.headerMutex.RUnlock()
	return len(fake.headerArgsForCall)
}

func (fake *Orderer) HeaderCalls(stub func() (metadata.MD, error)) {
	fake.headerMutex.Lock()
	defer fake.headerMutex.Unlock()
	fake.HeaderStub = stub
}

func (fake *Orderer) HeaderReturns(result1 metadata.MD, result2 error) {
	fake.headerMutex.Lock()
	defer fake.headerMutex.Unlock()
	fake.HeaderStub = nil
	fake.headerReturns = struct {
		result1 metadata.MD
		result2 error
	}{result1, result2}
}

func (fake *Orderer) HeaderReturnsOnCall(i int, result1 metadata.MD, result2 error) {
	fake.headerMutex.Lock()
	defer fake.headerMutex.Unlock()
	fake.HeaderStub = nil
	if fake.headerReturnsOnCall == nil {
		fake.headerReturnsOnCall = make(map[int]struct {
			result1 metadata.MD
			result2 error
		})
	}
	fake.headerReturnsOnCall[i] = struct {
		result1 metadata.MD
		result2 error
	}{result1, result2}
}

func (fake *Orderer) Recv() (*orderer.BroadcastResponse, error) {
	fake.recvMutex.Lock()
	ret, specificReturn := fake.recvReturnsOnCall[len(fake.recvArgsForCall)]
	fake.recvArgsForCall = append(fake.recvArgsForCall, struct {
	}{})
	fake.recordInvocation("Recv", []interface{}{})
	fake.recvMutex.Unlock()
	if fake.RecvStub != nil {
		return fake.RecvStub()
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	fakeReturns := fake.recvReturns
	return fakeReturns.result1, fakeReturns.result2
}

func (fake *Orderer) RecvCallCount() int {
	fake.recvMutex.RLock()
	defer fake.recvMutex.RUnlock()
	return len(fake.recvArgsForCall)
}

func (fake *Orderer) RecvCalls(stub func() (*orderer.BroadcastResponse, error)) {
	fake.recvMutex.Lock()
	defer fake.recvMutex.Unlock()
	fake.RecvStub = stub
}

func (fake *Orderer) RecvReturns(result1 *orderer.BroadcastResponse, result2 error) {
	fake.recvMutex.Lock()
	defer fake.recvMutex.Unlock()
	fake.RecvStub = nil
	fake.recvReturns = struct {
		result1 *orderer.BroadcastResponse
		result2 error
	}{result1, result2}
}

func (fake *Orderer) RecvReturnsOnCall(i int, result1 *orderer.BroadcastResponse, result2 error) {
	fake.recvMutex.Lock()
	defer fake.recvMutex.Unlock()
	fake.RecvStub = nil
	if fake.recvReturnsOnCall == nil {
		fake.recvReturnsOnCall = make(map[int]struct {
			result1 *orderer.BroadcastResponse
			result2 error
		})
	}
	fake.recvReturnsOnCall[i] = struct {
		result1 *orderer.BroadcastResponse
		result2 error
	}{result1, result2}
}

func (fake *Orderer) RecvMsg(arg1 interface{}) error {
	fake.recvMsgMutex.Lock()
	ret, specificReturn := fake.recvMsgReturnsOnCall[len(fake.recvMsgArgsForCall)]
	fake.recvMsgArgsForCall = append(fake.recvMsgArgsForCall, struct {
		arg1 interface{}
	}{arg1})
	fake.recordInvocation("RecvMsg", []interface{}{arg1})
	fake.recvMsgMutex.Unlock()
	if fake.RecvMsgStub != nil {
		return fake.RecvMsgStub(arg1)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.recvMsgReturns
	return fakeReturns.result1
}

func (fake *Orderer) RecvMsgCallCount() int {
	fake.recvMsgMutex.RLock()
	defer fake.recvMsgMutex.RUnlock()
	return len(fake.recvMsgArgsForCall)
}

func (fake *Orderer) RecvMsgCalls(stub func(interface{}) error) {
	fake.recvMsgMutex.Lock()
	defer fake.recvMsgMutex.Unlock()
	fake.RecvMsgStub = stub
}

func (fake *Orderer) RecvMsgArgsForCall(i int) interface{} {
	fake.recvMsgMutex.RLock()
	defer fake.recvMsgMutex.RUnlock()
	argsForCall := fake.recvMsgArgsForCall[i]
	return argsForCall.arg1
}

func (fake *Orderer) RecvMsgReturns(result1 error) {
	fake.recvMsgMutex.Lock()
	defer fake.recvMsgMutex.Unlock()
	fake.RecvMsgStub = nil
	fake.recvMsgReturns = struct {
		result1 error
	}{result1}
}

func (fake *Orderer) RecvMsgReturnsOnCall(i int, result1 error) {
	fake.recvMsgMutex.Lock()
	defer fake.recvMsgMutex.Unlock()
	fake.RecvMsgStub = nil
	if fake.recvMsgReturnsOnCall == nil {
		fake.recvMsgReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.recvMsgReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *Orderer) Send(arg1 *common.Envelope) error {
	fake.sendMutex.Lock()
	ret, specificReturn := fake.sendReturnsOnCall[len(fake.sendArgsForCall)]
	fake.sendArgsForCall = append(fake.sendArgsForCall, struct {
		arg1 *common.Envelope
	}{arg1})
	fake.recordInvocation("Send", []interface{}{arg1})
	fake.sendMutex.Unlock()
	if fake.SendStub != nil {
		return fake.SendStub(arg1)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.sendReturns
	return fakeReturns.result1
}

func (fake *Orderer) SendCallCount() int {
	fake.sendMutex.RLock()
	defer fake.sendMutex.RUnlock()
	return len(fake.sendArgsForCall)
}

func (fake *Orderer) SendCalls(stub func(*common.Envelope) error) {
	fake.sendMutex.Lock()
	defer fake.sendMutex.Unlock()
	fake.SendStub = stub
}

func (fake *Orderer) SendArgsForCall(i int) *common.Envelope {
	fake.sendMutex.RLock()
	defer fake.sendMutex.RUnlock()
	argsForCall := fake.sendArgsForCall[i]
	return argsForCall.arg1
}

func (fake *Orderer) SendReturns(result1 error) {
	fake.sendMutex.Lock()
	defer fake.sendMutex.Unlock()
	fake.SendStub = nil
	fake.sendReturns = struct {
		result1 error
	}{result1}
}

func (fake *Orderer) SendReturnsOnCall(i int, result1 error) {
	fake.sendMutex.Lock()
	defer fake.sendMutex.Unlock()
	fake.SendStub = nil
	if fake.sendReturnsOnCall == nil {
		fake.sendReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.sendReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *Orderer) SendMsg(arg1 interface{}) error {
	fake.sendMsgMutex.Lock()
	ret, specificReturn := fake.sendMsgReturnsOnCall[len(fake.sendMsgArgsForCall)]
	fake.sendMsgArgsForCall = append(fake.sendMsgArgsForCall, struct {
		arg1 interface{}
	}{arg1})
	fake.recordInvocation("SendMsg", []interface{}{arg1})
	fake.sendMsgMutex.Unlock()
	if fake.SendMsgStub != nil {
		return fake.SendMsgStub(arg1)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.sendMsgReturns
	return fakeReturns.result1
}

func (fake *Orderer) SendMsgCallCount() int {
	fake.sendMsgMutex.RLock()
	defer fake.sendMsgMutex.RUnlock()
	return len(fake.sendMsgArgsForCall)
}

func (fake *Orderer) SendMsgCalls(stub func(interface{}) error) {
	fake.sendMsgMutex.Lock()
	defer fake.sendMsgMutex.Unlock()
	fake.SendMsgStub = stub
}

func (fake *Orderer) SendMsgArgsForCall(i int) interface{} {
	fake.sendMsgMutex.RLock()
	defer fake.sendMsgMutex.RUnlock()
	argsForCall := fake.sendMsgArgsForCall[i]
	return argsForCall.arg1
}

func (fake *Orderer) SendMsgReturns(result1 error) {
	fake.sendMsgMutex.Lock()
	defer fake.sendMsgMutex.Unlock()
	fake.SendMsgStub = nil
	fake.sendMsgReturns = struct {
		result1 error
	}{result1}
}

func (fake *Orderer) SendMsgReturnsOnCall(i int, result1 error) {
	fake.sendMsgMutex.Lock()
	defer fake.sendMsgMutex.Unlock()
	fake.SendMsgStub = nil
	if fake.sendMsgReturnsOnCall == nil {
		fake.sendMsgReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.sendMsgReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *Orderer) Trailer() metadata.MD {
	fake.trailerMutex.Lock()
	ret, specificReturn := fake.trailerReturnsOnCall[len(fake.trailerArgsForCall)]
	fake.trailerArgsForCall = append(fake.trailerArgsForCall, struct {
	}{})
	fake.recordInvocation("Trailer", []interface{}{})
	fake.trailerMutex.Unlock()
	if fake.TrailerStub != nil {
		return fake.TrailerStub()
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.trailerReturns
	return fakeReturns.result1
}

func (fake *Orderer) TrailerCallCount() int {
	fake.trailerMutex.RLock()
	defer fake.trailerMutex.RUnlock()
	return len(fake.trailerArgsForCall)
}

func (fake *Orderer) TrailerCalls(stub func() metadata.MD) {
	fake.trailerMutex.Lock()
	defer fake.trailerMutex.Unlock()
	fake.TrailerStub = stub
}

func (fake *Orderer) TrailerReturns(result1 metadata.MD) {
	fake.trailerMutex.Lock()
	defer fake.trailerMutex.Unlock()
	fake.TrailerStub = nil
	fake.trailerReturns = struct {
		result1 metadata.MD
	}{result1}
}

func (fake *Orderer) TrailerReturnsOnCall(i int, result1 metadata.MD) {
	fake.trailerMutex.Lock()
	defer fake.trailerMutex.Unlock()
	fake.TrailerStub = nil
	if fake.trailerReturnsOnCall == nil {
		fake.trailerReturnsOnCall = make(map[int]struct {
			result1 metadata.MD
		})
	}
	fake.trailerReturnsOnCall[i] = struct {
		result1 metadata.MD
	}{result1}
}

func (fake *Orderer) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	fake.closeSendMutex.RLock()
	defer fake.closeSendMutex.RUnlock()
	fake.contextMutex.RLock()
	defer fake.contextMutex.RUnlock()
	fake.headerMutex.RLock()
	defer fake.headerMutex.RUnlock()
	fake.recvMutex.RLock()
	defer fake.recvMutex.RUnlock()
	fake.recvMsgMutex.RLock()
	defer fake.recvMsgMutex.RUnlock()
	fake.sendMutex.RLock()
	defer fake.sendMutex.RUnlock()
	fake.sendMsgMutex.RLock()
	defer fake.sendMsgMutex.RUnlock()
	fake.trailerMutex.RLock()
	defer fake.trailerMutex.RUnlock()
	copiedInvocations := map[string][][]interface{}{}
	for key, value := range fake.invocations {
		copiedInvocations[key] = value
	}
	return copiedInvocations
}

func (fake *Orderer) recordInvocation(key string, args []interface{}) {
	fake.invocationsMutex.Lock()
	defer fake.invocationsMutex.Unlock()
	if fake.invocations == nil {
		fake.invocations = map[string][][]interface{}{}
	}
	if fake.invocations[key] == nil {
		fake.invocations[key] = [][]interface{}{}
	}
	fake.invocations[key] = append(fake.invocations[key], args)
}


text:
<!doctype html>

<meta charset="utf-8">
<title>Oedipus the King and Tyrion Lannister – Yux | Blog</title>
<meta name="description" content="Tyrion Lannister, who killed his father, the same as Oedipus the King, is quiet a tragedy character.">
<meta name="keywords" content="Game_Of_Thrones, 个人随笔与读后感">

<meta name="twitter:title" content="Oedipus the King and Tyrion Lannister">
<meta name="twitter:description" content="Tyrion Lannister, who killed his father, the same as Oedipus the King, is quiet a tragedy character.">
<meta name="twitter:site" content="@LuiseLiao">
<meta name="twitter:creator" content="@LuiseLiao">

<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://localhost:4000/images/site-logo.png">

<meta property="og:locale" content="en_CN">
<meta property="og:type" content="article">
<meta property="og:title" content="Oedipus the King and Tyrion Lannister">
<meta property="og:description" content="Tyrion Lannister, who killed his father, the same as Oedipus the King, is quiet a tragedy character.">
<meta property="og:url" content="http://localhost:4000/blog/GOT-Tyrion/">
<meta property="og:site_name" content="Yux | Blog">

<link rel="canonical" href="http://localhost:4000/blog/GOT-Tyrion/">
<link href="http://localhost:4000/feed.xml" type="application/atom+xml" rel="alternate" title="Yux | Blog Feed">

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

<link rel="stylesheet" href="http://localhost:4000/assets/css/main.css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="http://localhost:4000/favicon.ico">

<link rel="shortcut icon" href="http://localhost:4000/favicon.png">

<link rel="apple-touch-icon-precomposed" href="http://localhost:4000/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://localhost:4000/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://localhost:4000/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://localhost:4000/images/apple-touch-icon-144x144-precomposed.png">

  About

  Articles

  Blog

  Collection

  Tag

  Search

Yux | Blog

O ever youthful, O ever weeping.

Game_Of_Thrones

个人随笔与读后感

Oedipus the King and Tyrion Lannister

        By Yuxing Liao
        <time datetime="2016-11-01T00:00:00+08:00"> November 01, 2016</time>

         Comment

   Tweet

   Like

   +1

Tyrion Lannister, who killed his father, the same as Oedipus the King, is quiet a tragedy character.

Oedipus has a cruel and guilty father, King Laius, who want to kill him when he was an infant. He tightly binds the feet of the infant together with a pin and orders Jocasta, wife and mother of Oedipus, to kill the infant. She orders a servant to commit the act for her. Fortunately, Oedipus survived but unfortunately meets and has an argument with his true father on the road to Thebes when his grows up. King Laius moves to strike Oedipus, who looks insolent, with his scepter, but Oedipus throws him down from the chariot and kills him. It is a tragedy definitely. But it looks like a coincident event, that he kills his father, more than a revenge. Tyrion kills his father in revenge.

Tyrion Lannister, the youngest son of Joanna Lannister and Tywin Lannister, the head of House Lannister, the richest man in the Seven Kingdoms, the Lord of Casterly Rock. He is a dwarf, causing his tragedy.

Once he speaks to his father, he says,

"I'm guilty of a far more monstrous crime: I'm guilt of being a dwarf!"

His father says,

"You are not on trial for being a dwarf."

He says,

"Oh, yes I am! I've been on trial for that my entire life!"

However, Tywin Lannister, who says Tyrion is not on trial for being a dwarf is exactly the man who makes him on trial. Tyrion gets free after he kills his father in the privy chamber. He forces his father to admit to his many wrongdoings against him. Tywin tries to placate Tyrion, but when he refers to Shae as a "whore" once too often after having been warned not to do so, Tyrion kills him with two bolts to the chest without control.

Both tragedy person, both guilty father, they are exactly the same. One father wants to kill baby in the cradle, and one father boils his child all the days, no one is innocent. Tyrion has a week body but strong mind, a talent hand of the King, and Oedipus is brave and smart, responsible, a great King of the people. The difference is what makes them a tragedy person, though they both killed their father.

Oedipus has a happy beginning, surviving and being the king of Thebes, and gets a miserable ending with blind eyes, for saving his people in Thebes out of disease. On the contrary, Tyrion begins his life with pain and gets refresh after killed his father. Tyrion's miserable life begins being a dwarf and loving a prostitute, Tysha. As a lesson, Tywin gave Tysha to his guards, paying her a silver coin for each man and forcing Tyrion to watch. By the end, there were so many silver coins that they were running out of her hands onto the ground. Tyrion has reciprocated Tywin's hatred ever since. It never ends until the bolts in the chest.

There is no doubt they are talented persons, which makes it such a pity what happened on them.

PS: It's just a middle-term paper of a course called English Literary Canon and A Game of Thrones. It's interesting for him adding an 'A' infront of Game of Thrones, because it has an 'A' as the name of the noval but the TV series. Thus, we have no chance to watch TV in class.

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus

        Previous

        Next

© 2016 Yuxing Liao. Powered by Jekyll using the So Simple Theme.


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ListComponent } from './list.component';

describe('ListComponent', () => {
  let component: ListComponent;
  let fixture: ComponentFixture<ListComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ListComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ListComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});


text:
@(
	@{Name = "Open PowerShell";					Command = """($PowerShellConsoleConstants.Executables.ConEmu)"" /cmd {PowerShell}";					Icon = $conEmuPowerShellIcon; },
	@{Name = "Open PowerShell (No Profile)";	Command = """($PowerShellConsoleConstants.Executables.ConEmu_"" /cmd {PowerShell (No Profile)}";		Icon = $conEmuPowerShellIcon; },
	@{Name = "Open PowerShell (Administrator)";	Command = """($PowerShellConsoleConstants.Executables.ConEmu)"" /cmd {PowerShell (Administrator)}";	Icon = $conEmuPowerShellIcon; },
	@{Name = "Open Command";					Command = """($PowerShellConsoleConstants.Executables.ConEmu)"" /cmd {Command}";						Icon = $conEmuCommandIcon; },
	@{Name = "Open Command (Administrator)";	Command = """($PowerShellConsoleConstants.Executables.ConEmu)"" /cmd {Command (Administrator)}";		Icon = $conEmuCommandIcon;}
) | % {
	$link = $_
	Invoke-InstallStep "Configuring '$($link.Name)' Shell Integration" {
		@("*", "Directory\Background", "Folder", "Drive") | % {
			New-Item -Path "HKCU:\Software\Classes\$_\shell\$($link.Name)" -Force | Out-Null
			Set-ItemProperty -LiteralPath "HKCU:\Software\Classes\$_\shell\$($link.Name)" "Icon" -Value $link.Icon -Type String -Force | Out-Null
			New-Item -Path "HKCU:\Software\Classes\$_\shell\$($link.Name)\command" -Value $link.Command -Type String -Force | Out-Null
		}
	}
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Electron Calculator</title>
  <link rel="stylesheet/less" href="./master.less">

        0

        AC
        +/-
        ÷

        7
        8
        9
        x

        4
        5
        6
        -

        1
        2
        3
        +

        0
        ,
        =


text:
'use strict';

app.controller('DeleteCtrl', ['$scope', 'notifier', '$location', 'DeleteAllPeopleResource',
    function CreateCtrl($scope, notifier, $location, DeleteAllPeopleResource) {
        $scope.deleteAll = function() {
            DeleteAllPeopleResource.deleteAll()
                .then(function() {
                    notifier.success('All people successfully deleted!');
                    $location.path('/main');
                });
        }
    }
]);


text:
export {};
//# sourceMappingURL=exclude-metadata.interface.js.map


text:
module TasteTester
  # Thin ssh tunnel wrapper
  class Tunnel
    include TasteTester::Logging
    include BetweenMeals::Util

    attr_reader :port

    def initialize(host, server, timeout = 5)
      @host = host
      @server = server
      @timeout = timeout
      if TasteTester::Config.testing_until
        @delta_secs = TasteTester::Config.testing_until.strftime('%s').to_i -
                      Time.now.strftime('%s').to_i
      else
        @delta_secs = TasteTester::Config.testing_time
      end
    end

    def run
      @port = TasteTester::Config.tunnel_port
      logger.info("Setting up tunnel on port #{@port}")
      @status, @output = exec!(cmd, logger)
    rescue
      logger.error 'Failed bringing up ssh tunnel'
      exit(1)
    end

    def cmd
      if TasteTester::Config.user != 'root'
        pid = '$$'
      else
        pid = '\\$\\$'
      end
      cmds = "ps -p #{pid} -o pgid | grep -v PGID" +
             " > #{TasteTester::Config.timestamp_file} &&" +
             " touch -t #{TasteTester::Config.testing_end_time}" +
             " #{TasteTester::Config.timestamp_file} && sleep #{@delta_secs}"
      # As great as it would be to have ExitOnForwardFailure=yes,
      # we had multiple cases of tunnels dying
      # if -f and ExitOnForwardFailure are used together.
      # In most cases the first request from chef was "breaking" the tunnel,
      # in a way that port was still open, but subsequent requests were hanging.
      # This is reproducible and should be looked into.
      cmd = "#{TasteTester::Config.ssh_command} " +
            "-T -o BatchMode=yes -o ConnectTimeout=#{@timeout} " +
            '-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ' +
            '-o ServerAliveInterval=10 -o ServerAliveCountMax=6 ' +
            "-f -R #{@port}:localhost:#{@server.port} "
      if TasteTester::Config.user != 'root'
        cc = Base64.encode64(cmds).delete("\n")
        cmd += "#{TasteTester::Config.user}@#{@host} \"echo '#{cc}' | base64" +
               ' --decode | sudo bash -x"'
      else
        cmd += "root@#{@host} \"#{cmds}\""
      end
      cmd
    end

    def self.kill(name)
      ssh = TasteTester::SSH.new(name)
      # Since commands are &&'d together, and we're using &&, we need to
      # surround this in paryns, and make sure as a whole it evaluates
      # to true so it doesn't mess up other things... even though this is
      # the only thing we're currently executing in this SSH.
      if TasteTester::Config.user != 'root'
        sudo = 'sudo '
      end
      cmd = "( [ -s #{TasteTester::Config.timestamp_file} ]" +
            " && #{sudo}kill -9 -- " +
            "-\$(cat #{TasteTester::Config.timestamp_file}); true )"
      ssh << cmd
      ssh.run!
    end
  end
end


text:
export interface NewExternalUser {
  firstname?: string;
  lastname?: string;
  email: string;
  source?: string;
  picture?: string;
  sourceId?: string;
  newsletter?: boolean;
  customFields?: Record<string, unknown>;
}


text:
TEST_BEGIN(test_div_exhaustive) {
	for (size_t divisor = 2; divisor < 1000 * 1000; ++divisor) {
		div_info_t div_info;
		div_init(&div_info, divisor);
		size_t max = 1000 * divisor;
		if (max < 1000 * 1000) {
			max = 1000 * 1000;
		}
		for (size_t dividend = 0; dividend < 1000 * divisor;
		    dividend += divisor) {
			size_t quotient = div_compute(
			    &div_info, dividend);
			expect_zu_eq(dividend, quotient * divisor,
			    "With divisor = %zu, dividend = %zu, "
			    "got quotient %zu", divisor, dividend, quotient);
		}
	}
}
TEST_END

int
main(void) {
	return test_no_reentrancy(
	    test_div_exhaustive);
}


text:
package com.dbg.gameplay;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

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

public class MainGame {

    public static final int SPAWN_ANIMATION = -1;
    public static final int MOVE_ANIMATION = 0;
    public static final int MERGE_ANIMATION = 1;

    public static final int FADE_GLOBAL_ANIMATION = 0;
    private static final long MOVE_ANIMATION_TIME = MainView.BASE_ANIMATION_TIME;
    private static final long SPAWN_ANIMATION_TIME = MainView.BASE_ANIMATION_TIME;
    private static final long NOTIFICATION_DELAY_TIME = MOVE_ANIMATION_TIME + SPAWN_ANIMATION_TIME;
    private static final long NOTIFICATION_ANIMATION_TIME = MainView.BASE_ANIMATION_TIME * 5;
    private static final int startingMaxValue = 2048;
    //Odd state = game is not active
    //Even state = game is active
    //Win state = active state + 1
    private static final int GAME_WIN = 1;
    private static final int GAME_LOST = -1;
    private static final int GAME_NORMAL = 0;
    public int gameState = GAME_NORMAL;
    public int lastGameState = GAME_NORMAL;
    private int bufferGameState = GAME_NORMAL;
    private static final int GAME_ENDLESS = 2;
    private static final int GAME_ENDLESS_WON = 3;
    private static final String HIGH_SCORE = "high score";
    private static int endingMaxValue;
    final int numSquaresX = 4;
    final int numSquaresY = 4;
    private final Context mContext;
    private final MainView mView;
    public Grid grid = null;
    public AnimationGrid aGrid;
    public boolean canUndo;
    public long score = 0;
    public long highScore = 0;
    public long lastScore = 0;
    private long bufferScore = 0;

    public float estimateAmount=0;

    public MainGame(Context context, MainView view) {
        mContext = context;
        mView = view;
        endingMaxValue = (int) Math.pow(2, view.numCellTypes - 1);
    }

    public void  refresh(){
         mView.invalidate();
    }

    public void newGame() {
        if (grid == null) {
            grid = new Grid(numSquaresX, numSquaresY);
        } else {
            prepareUndoState();
            saveUndoState();
            grid.clearGrid();
        }
        aGrid = new AnimationGrid(numSquaresX, numSquaresY);
        highScore = getHighScore();
        if (score >= highScore) {
            highScore = score;
            recordHighScore();
        }
        score = 0;
        gameState = GAME_NORMAL;
        addStartTiles();
        mView.refreshLastTime = true;
        mView.resyncTime();
        mView.invalidate();
    }

    private void addStartTiles() {
        int startTiles = 2;
        for (int xx = 0; xx < startTiles; xx++) {
            this.addRandomTile();
        }
    }

    private void addRandomTile() {
        if (grid.isCellsAvailable()) {
            int value = Math.random() < 0.9 ? 2 : 4;
            Tile tile = new Tile(grid.randomAvailableCell(), value);
            spawnTile(tile);
        }
    }

    private void spawnTile(Tile tile) {
        grid.insertTile(tile);
        aGrid.startAnimation(tile.getX(), tile.getY(), SPAWN_ANIMATION,
                SPAWN_ANIMATION_TIME, MOVE_ANIMATION_TIME, null); //Direction: -1 = EXPANDING
    }

    private void recordHighScore() {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
        SharedPreferences.Editor editor = settings.edit();
        editor.putLong(HIGH_SCORE, highScore);
        editor.commit();
    }

    private long getHighScore() {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext);
        return settings.getLong(HIGH_SCORE, -1);
    }

    private void prepareTiles() {
        for (Tile[] array : grid.field) {
            for (Tile tile : array) {
                if (grid.isCellOccupied(tile)) {
                    tile.setMergedFrom(null);
                }
            }
        }
    }

    private void moveTile(Tile tile, Cell cell) {
        grid.field[tile.getX()][tile.getY()] = null;
        grid.field[cell.getX()][cell.getY()] = tile;
        tile.updatePosition(cell);
    }

    private void saveUndoState() {
        grid.saveTiles();
        canUndo = true;
        lastScore = bufferScore;
        lastGameState = bufferGameState;
    }

    private void prepareUndoState() {
        grid.prepareSaveTiles();
        bufferScore = score;
        bufferGameState = gameState;
    }

    public void revertUndoState() {
        if (canUndo) {
            canUndo = false;
            aGrid.cancelAnimations();
            grid.revertTiles();
            score = lastScore;
            gameState = lastGameState;
            mView.refreshLastTime = true;
            mView.invalidate();
        }
    }

    public boolean gameWon() {
        return (gameState > 0 && gameState % 2 != 0);
    }

    public boolean gameLost() {
        return (gameState == GAME_LOST);
    }

    public boolean isActive() {
        return !(gameWon() || gameLost());
    }

    public void move(int direction) {
        aGrid.cancelAnimations();
        // 0: up, 1: right, 2: down, 3: left
        if (!isActive()) {
            return;
        }
        prepareUndoState();
        Cell vector = getVector(direction);
        List<Integer> traversalsX = buildTraversalsX(vector);
        List<Integer> traversalsY = buildTraversalsY(vector);
        boolean moved = false;

        prepareTiles();

        for (int xx : traversalsX) {
            for (int yy : traversalsY) {
                Cell cell = new Cell(xx, yy);
                Tile tile = grid.getCellContent(cell);

                if (tile != null) {
                    Cell[] positions = findFarthestPosition(cell, vector);
                    Tile next = grid.getCellContent(positions[1]);

                    if (next != null && next.getValue() == tile.getValue() && next.getMergedFrom() == null) {
                        Tile merged = new Tile(positions[1], tile.getValue() * 2);
                        Tile[] temp = {tile, next};
                        merged.setMergedFrom(temp);

                        grid.insertTile(merged);
                        grid.removeTile(tile);

                        // Converge the two tiles' positions
                        tile.updatePosition(positions[1]);

                        int[] extras = {xx, yy};
                        aGrid.startAnimation(merged.getX(), merged.getY(), MOVE_ANIMATION,
                                MOVE_ANIMATION_TIME, 0, extras); //Direction: 0 = MOVING MERGED
                        aGrid.startAnimation(merged.getX(), merged.getY(), MERGE_ANIMATION,
                                SPAWN_ANIMATION_TIME, MOVE_ANIMATION_TIME, null);

                        // Update the score
                        score = score + merged.getValue();
                        highScore = Math.max(score, highScore);

                        // The mighty 2048 tile
                        if (merged.getValue() >= winValue() && !gameWon()) {
                            gameState = gameState + GAME_WIN; // Set win state
                            endGame();
                        }
                    } else {
                        moveTile(tile, positions[0]);
                        int[] extras = {xx, yy, 0};
                        aGrid.startAnimation(positions[0].getX(), positions[0].getY(), MOVE_ANIMATION, MOVE_ANIMATION_TIME, 0, extras); //Direction: 1 = MOVING NO MERGE
                    }

                    if (!positionsEqual(cell, tile)) {
                        moved = true;
                    }
                }
            }
        }

        if (moved) {
            saveUndoState();
            addRandomTile();
            checkLose();
        }
        mView.resyncTime();
        mView.invalidate();
    }

    private void checkLose() {
        if (!movesAvailable() && !gameWon()) {
            gameState = GAME_LOST;
            endGame();
        }
    }

    private void endGame() {
        aGrid.startAnimation(-1, -1, FADE_GLOBAL_ANIMATION, NOTIFICATION_ANIMATION_TIME, NOTIFICATION_DELAY_TIME, null);
        if (score >= highScore) {
            highScore = score;
            recordHighScore();
        }
    }

    private Cell getVector(int direction) {
        Cell[] map = {
                new Cell(0, -1), // up
                new Cell(1, 0),  // right
                new Cell(0, 1),  // down
                new Cell(-1, 0)  // left
        };
        return map[direction];
    }

    private List<Integer> buildTraversalsX(Cell vector) {
        List<Integer> traversals = new ArrayList<>();

        for (int xx = 0; xx < numSquaresX; xx++) {
            traversals.add(xx);
        }
        if (vector.getX() == 1) {
            Collections.reverse(traversals);
        }

        return traversals;
    }

    private List<Integer> buildTraversalsY(Cell vector) {
        List<Integer> traversals = new ArrayList<>();

        for (int xx = 0; xx < numSquaresY; xx++) {
            traversals.add(xx);
        }
        if (vector.getY() == 1) {
            Collections.reverse(traversals);
        }

        return traversals;
    }

    private Cell[] findFarthestPosition(Cell cell, Cell vector) {
        Cell previous;
        Cell nextCell = new Cell(cell.getX(), cell.getY());
        do {
            previous = nextCell;
            nextCell = new Cell(previous.getX() + vector.getX(),
                    previous.getY() + vector.getY());
        } while (grid.isCellWithinBounds(nextCell) && grid.isCellAvailable(nextCell));

        return new Cell[]{previous, nextCell};
    }

    private boolean movesAvailable() {
        return grid.isCellsAvailable() || tileMatchesAvailable();
    }

    private boolean tileMatchesAvailable() {
        Tile tile;

        for (int xx = 0; xx < numSquaresX; xx++) {
            for (int yy = 0; yy < numSquaresY; yy++) {
                tile = grid.getCellContent(new Cell(xx, yy));

                if (tile != null) {
                    for (int direction = 0; direction < 4; direction++) {
                        Cell vector = getVector(direction);
                        Cell cell = new Cell(xx + vector.getX(), yy + vector.getY());

                        Tile other = grid.getCellContent(cell);

                        if (other != null && other.getValue() == tile.getValue()) {
                            return true;
                        }
                    }
                }
            }
        }

        return false;
    }

    private boolean positionsEqual(Cell first, Cell second) {
        return first.getX() == second.getX() && first.getY() == second.getY();
    }

    private int winValue() {
        if (!canContinue()) {
            return endingMaxValue;
        } else {
            return startingMaxValue;
        }
    }

    public void setEndlessMode() {
        gameState = GAME_ENDLESS;
        mView.invalidate();
        mView.refreshLastTime = true;
    }

    public boolean canContinue() {
        return !(gameState == GAME_ENDLESS || gameState == GAME_ENDLESS_WON);
    }
}


text:
/*	$NetBSD: roaming_serv.c,v 1.2 2011/07/25 03:03:10 christos Exp $	*/
/* $OpenBSD: roaming_serv.c,v 1.1 2009/10/24 11:18:23 andreas Exp $ */
/*
 * Copyright (c) 2004-2009 AppGate Network Security AB
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>

#include "roaming.h"

/*
 * Wait for the roaming client to reconnect. Returns 0 if a connect ocurred.
 */
int
wait_for_roaming_reconnect(void)
{
	return 1;
}


text:
<?php

namespace StrictPhpTest;

use StrictPhp\Aspect\PostConstructAspect;
use StrictPhp\Aspect\PropertyWriteAspect;
use StrictPhp\StrictPhpKernel;

/**
 * Tests for {@see \StrictPhp\StrictPhpKernel}
 *
 * @author Jefersson Nathan <malukenho@phpse.net>
 * @license MIT
 *
 * @group Coverage
 */
class StrictPhpKernelTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers \StrictPhp\StrictPhpKernel::configureAop
     */
    public function testIfAspectsWasRegisteredProperly()
    {
        $strictPhp = StrictPhpKernel::getInstance();
        $strictPhp->init([
            'cacheDir' => realpath(__DIR__ . '/..') . '/integration-tests-go-cache/',
            'includePaths' => [
                __DIR__,
            ],
        ]);

        $container = $strictPhp->getContainer();
        $this->assertInstanceOf(PropertyWriteAspect::class, $container->getAspect(PropertyWriteAspect::class));
        $this->assertInstanceOf(PostConstructAspect::class, $container->getAspect(PostConstructAspect::class));
    }
}


text:
<?php

declare(strict_types = 1);

namespace OctoLab\Tinkoff\ServiceProvider\Silex;

use OctoLab\Tinkoff\ServiceProvider\CurrencyRateService as CommonCurrencyRateService;
use Silex\Application;
use Silex\ServiceProviderInterface;

/**
 * @author Kamil Samigullin <kamil@samigullin.info>
 */
class CurrencyRateService extends CommonCurrencyRateService implements ServiceProviderInterface
{
    /**
     * {@inheritdoc}
     */
    public function register(Application $app)
    {
        $this->setup($app);
    }

    /**
     * {@inheritdoc}
     */
    public function boot(Application $app)
    {
    }
}


text:
let Assert = require('../Assert');
let File = require('../File');
let Preprocessor = require('./Preprocessor');

class PostCss extends Preprocessor {
    /**
     * The Mix API name for the component.
     */
    name() {
        return ['postCss', 'css'];
    }

    /**
     * Register the component.
     *
     * @param {*} src
     * @param {string} output
     * @param {Array|Object} pluginOptions
     * @param {Array} postCssPlugins
     */
    register(src, output, pluginOptions = {}, postCssPlugins = []) {
        // Backwards compat with earlier versions of Mix
        if (Array.isArray(pluginOptions) && postCssPlugins.length === 0) {
            postCssPlugins = pluginOptions;
            pluginOptions = {};
        }

        Assert.preprocessor('postCss', src, output);

        src = new File(src);

        output = this.normalizeOutput(
            new File(output),
            src.nameWithoutExtension() + '.css'
        );

        this.details = (this.details || []).concat({
            type: 'postCss',
            src,
            output,
            pluginOptions,
            postCssPlugins: [].concat(postCssPlugins)
        });

        // Register a split chunk that takes everything generated
        // by this file and puts it in a separate file
        // We use a output-specific chunk name so we don't accidentally merge multiple files
        this._addChunks(`styles-${output.relativePathWithoutExtension()}`, src, output);
    }

    /**
     * Override the generated webpack configuration.
     *
     * @param {Object} config
     */
    webpackConfig(config) {
        config.module.rules.find(
            rule => rule.test.toString() === '/\\.p?css$/'
        ).exclude = this.details.map(postCss => postCss.src.path());
    }
}

module.exports = PostCss;


text:
AlignResult::AlignResult (longlong uid, bool reverse, float al_score, int score, float chi2, double evalue, double bitscore, int q_auto_score, int t_auto_score, int batch_no, const BATCH* batches, const char* binsubj, QWORD subjid, DWORD subjlen)
:
uid_ (uid),
reverse_ (reverse),
al_score_ (al_score),
score_ (score),
chi2_ (chi2),
evalue_ (evalue),
bitscore_ (bitscore),
q_auto_score_ (q_auto_score),
t_auto_score_ (t_auto_score),
batch_no_ (batch_no),
subjid_ (subjid),
subjlen_ (subjlen)
{
    if (batch_no_)
    {
        batches_ = new BATCH [batch_no_];
        std::copy (batches, batches + batch_no, (BATCH*) batches_);
        if (binsubj)
        {
            unsigned subj_len = (batches + batch_no - 1)->ypos + (batches + batch_no - 1)->len - batches->ypos;
            subject_ = new char [subj_len + 1];
            n_binary2ascii (subject_, subj_len + 1, binsubj, batches->ypos, subj_len);
        }
    }
}

bool AlignResult::intersects (const AlignResult& other) const
{
    for (int b1 = 0; b1 != batch_no_; b1 ++)
        for (int b2 = 0; b2 != other.batch_no_; b2++)
            if (batches_ [b1].intersects (other.batches_ [b2]))
                return true;
    return false;
}


text:
using Bytes2you.Validation;
using LiveScoreUpdateSystem.Data.Models.FootballFixtures;
using LiveScoreUpdateSystem.Data.Models.FootballFixtures.Enums;
using LiveScoreUpdateSystem.Data.Repositories.Contracts;
using LiveScoreUpdateSystem.Services.Common;
using LiveScoreUpdateSystem.Services.Common.Contracts;
using LiveScoreUpdateSystem.Services.Data.Abstraction;
using LiveScoreUpdateSystem.Services.Data.Contracts;
using LiveScoreUpdateSystem.Services.Data.Factories.Contracts;
using LiveScoreUpdateSystem.Services.Data.Providers.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;

namespace LiveScoreUpdateSystem.Services.Data
{
    public class FixtureService : DataService<Fixture>, IFixtureService
    {
        private readonly IEfRepository<Team> teamsRepo;
        private readonly IEfRepository<Player> playersRepo;
        private readonly IFixturesFactory fixturesFactory;
        private readonly IFixtureMailService mailService;

        public FixtureService(
            IEfRepository<Fixture> dataSet,
            IEfRepository<Team> teamsRepo,
            IEfRepository<Player> playersRepo,
            IFixturesFactory fixturesFactory,
            IFixtureMailService fixtureMailService)
            : base(dataSet)
        {
            Guard.WhenArgument(teamsRepo, "teamsRepo").IsNull().Throw();
            Guard.WhenArgument(fixturesFactory, "fixturesFactory").IsNull().Throw();
            Guard.WhenArgument(playersRepo, "playersRepo").IsNull().Throw();
            Guard.WhenArgument(fixtureMailService, "mailService").IsNull().Throw();

            this.teamsRepo = teamsRepo;
            this.fixturesFactory = fixturesFactory;
            this.playersRepo = playersRepo;
            this.mailService = fixtureMailService;
        }

        public void Add(string homeTeamName, string awayTeamName, DateTime? startTime)
        {
            if (homeTeamName == awayTeamName)
            {
                throw new InvalidOperationException("Home and away team must be different!");
            }

            var homeTeam = this.GetTeamByName(homeTeamName);
            var awayTeam = this.GetTeamByName(awayTeamName);

            var fixture = this.fixturesFactory.GetFixture(homeTeam, awayTeam, startTime);
            this.Data.Add(fixture);
        }

        private Team GetTeamByName(string teamName)
        {
            var targetTeam = this.teamsRepo.All.FirstOrDefault(t => t.Name == teamName);
            if (targetTeam == null)
            {
                throw new ArgumentNullException(string.Format("No team with name {0} was found!", teamName));
            }

            return targetTeam;
        }

        public IEnumerable<Fixture> GetAvailableFixtures(DateTime targetDate)
        {
            var availableFixtures = this.Data.All
                .Where(f => f.FirstHalfStart.Value.Month == targetDate.Month &&
                f.FirstHalfStart.Value.Year == targetDate.Year &&
                f.FirstHalfStart.Value.Day == targetDate.Day);

            return availableFixtures;
        }

        public void AddFixtureStatus(Guid fixtureId, FixtureStatus fixtureStatus)
        {
            var targetFixture = this.GetById(fixtureId);

            Guard.WhenArgument(targetFixture, "targetFixture").IsNull().Throw();
            targetFixture.Status = fixtureStatus;

            if (targetFixture.Status == FixtureStatus.FirstHalf)
            {
                targetFixture.FirstHalfStart = TimeProvider.CurrentProvider.CurrentDate;
            }
            else if (targetFixture.Status == FixtureStatus.SecondHalf)
            {
                targetFixture.SecondHalfStart = TimeProvider.CurrentProvider.CurrentDate;
            }
            else if (targetFixture.Status == FixtureStatus.FullTime)
            {
                var homeSubscribers = targetFixture.HomeTeam.Subscribers.Select(s => s.UserName).ToList();
                var awaySubscribers = targetFixture.AwayTeam.Subscribers.Select(s => s.UserName);

                homeSubscribers.AddRange(awaySubscribers);
                // homeSubscribers.Add("bobidjei@abv.bg");
                this.mailService.SendFixtureResultMail(targetFixture, homeSubscribers);
            }

            this.Data.Update(targetFixture);
        }

        public void AddFixtureEvent(Guid fixtureId, FixtureEventType fixtureEventType, int minute, Guid playerId)
        {
            var targetFixture = this.GetById(fixtureId);
            var targetPlayer = this.playersRepo.All.FirstOrDefault(p => p.Id == playerId);
            if (targetPlayer == null)
            {
                throw new ArgumentNullException("Invalid player id!");
            }

            var isHomeTeamScoring = targetFixture.HomeTeam.Players.Any(p => p.Id == playerId);

            var fixtureEvent = this.fixturesFactory.GetFixtureEvent(fixtureEventType, minute, targetPlayer);
            targetFixture.FixtureEvents.Add(fixtureEvent);

            if (fixtureEventType == FixtureEventType.Goal)
            {
                if (isHomeTeamScoring)
                {
                    targetFixture.ScoreHomeTeam += 1;
                }
                else
                {
                    targetFixture.ScoreAwayTeam += 1;
                }

                fixtureEvent.EventScore = string.Format("{0} : {1}", targetFixture.ScoreHomeTeam, targetFixture.ScoreAwayTeam);
            }

            this.Data.Update(targetFixture);
        }
    }
}


text:
<?php

/* Backend/Get/status_add.html.twig */
class __TwigTemplate_0ca7d13e2c156d2ebc3e05910625e0914f3e6213ea96fb060fc836fb93a84bb0 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "
 10/10/2017 10:30 Giao hàng Lorem ipsum dolor sit amet

";
    }

    public function getTemplateName()
    {
        return "Backend/Get/status_add.html.twig";
    }

    public function getDebugInfo()
    {
        return array (  19 => 1,);
    }

    public function getSourceContext()
    {
        return new Twig_Source("
 10/10/2017 10:30 Giao hàng Lorem ipsum dolor sit amet

", "Backend/Get/status_add.html.twig", "C:\\wamp\\www\\mvcframework\\App\\Views\\Backend\\Get\\status_add.html.twig");
    }
}


text:
cmake_policy(SET CMP0042 NEW)

### CLANG COMPILER FLAGS ###

# Flags used by C and C++ compilers for all build types
SET( AJ_COMPILER_FLAGS
	-fvisibility-inlines-hidden
    #see https://developer.apple.com/library/mac/technotes/tn2185/_index.html
    # for detail
	-fvisibility-ms-compat
	)

# Flags used by C and C++ compilers for specific architectures
IF( CMAKE_SIZEOF_VOID_P EQUAL 4 )
	LIST( APPEND AJ_COMPILER_FLAGS
		)
ELSEIF( CMAKE_SIZEOF_VOID_P EQUAL 8 )
	LIST( APPEND AJ_COMPILER_FLAGS
		)
ENDIF()

# Flags used by C and C++ compilers for Debug builds
SET( AJ_COMPILER_FLAGS_DEBUG
	${AJ_COMPILER_FLAGS}
	#-Werror
	# Preprocessor definitions
	-D_DEBUG
	-g
	-O0
	)

# Flags used by C and C++ compilers for Release builds
SET( AJ_COMPILER_FLAGS_OPTIMIZED
	${AJ_COMPILER_FLAGS}
	# Optimization
	-O3
	)

# Flags used by C and C++ compilers for Release builds
SET( BW_COMPILER_FLAGS_RELEASE ${BW_COMPILER_FLAGS_OPTIMIZED} )

# Flags used by the C compiler
SET( AJ_C_FLAGS $ENV{CFLAGS} ${AJ_COMPILER_FLAGS} )
SET( AJ_C_FLAGS_DEBUG ${AJ_COMPILER_FLAGS_DEBUG} )
SET( AJ_C_FLAGS_RELEASE ${AJ_COMPILER_FLAGS_RELEASE} )

# Flags used by the C++ compiler
SET( AJ_CXX_FLAGS $ENV{CXXFLAGS} ${AJ_COMPILER_FLAGS}
	)
SET( AJ_CXX_FLAGS_DEBUG ${AJ_COMPILER_FLAGS_DEBUG} )
SET( AJ_CXX_FLAGS_RELEASE ${AJ_COMPILER_FLAGS_RELEASE} )

# Flags used by the linker for all build types
SET( AJ_LINKER_FLAGS

)

# Flags used by the linker for Debug builds
SET( AJ_LINKER_FLAGS_DEBUG
	-g
	)

# Flags used by the linker for optimized builds
SET( AJ_LINKER_FLAGS_OPTIMIZED
	)
SET( AJ_LINKER_RELEASE ${AJ_LINKER_FLAGS_OPTIMIZED} )

# Set up variables for EXE, MODULE, SHARED, and STATIC linking

# Flags used by the linker
SET( AJ_EXE_LINKER_FLAGS ${AJ_LINKER_FLAGS} )
SET( AJ_EXE_LINKER_FLAGS_DEBUG ${AJ_LINKER_FLAGS_DEBUG} )
SET( AJ_EXE_LINKER_FLAGS_RELEASE ${AJ_LINKER_FLAGS_RELEASE} )

# Flags used by the linker for the creation of modules.
SET( AJ_MODULE_LINKER_FLAGS ${AJ_LINKER_FLAGS} )
SET( AJ_MODULE_LINKER_FLAGS_DEBUG ${AJ_LINKER_FLAGS_DEBUG} )
SET( AJ_MODULE_LINKER_FLAGS_RELEASE ${AJ_LINKER_FLAGS_RELEASE} )

# Flags used by the linker for the creation of dynamic libraries.
SET( AJ_SHARED_LINKER_FLAGS ${AJ_LINKER_FLAGS} )
SET( AJ_SHARED_LINKER_FLAGS_DEBUG ${AJ_LINKER_FLAGS_DEBUG} )
SET( AJ_SHARED_LINKER_FLAGS_RELEASE ${AJ_LINKER_FLAGS_RELEASE} )

# Flags used by the linker for the creation of static libraries.
SET( AJ_STATIC_LINKER_FLAGS "" )
SET( AJ_STATIC_LINKER_FLAGS_DEBUG "" )
SET( AJ_STATIC_LINKER_FLAGS_RELEASE "" )


text:
package org.unitils.mock.report.impl;

import org.junit.Before;
import org.junit.Test;
import org.unitils.mock.Mock;
import org.unitils.mock.core.MockObject;

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

import static junit.framework.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.unitils.mock.core.MockObject.getCurrentScenario;

/**
 * Test for the report that shows the suggested assert statements.
 *
 * @author Filip Neven
 * @author Tim Ducheyne
 */
public class SuggestedAssertsReportTest {

    /* class under test */
    private SuggestedAssertsReport suggestedAssertsReport;

    /* Test mock that uses the scenario */
    private Mock<TestInterface> testMock;

    /* Proxy of the testMock */
    private TestInterface testProxy;

    /* Test data, which is a field of this class: if used, the suggested assert must refer to this field */
    private String testDataStr = "someString";

    /**
     * Initializes the test.
     */
    @Before
    public void setUp() {
        suggestedAssertsReport = new SuggestedAssertsReport();
        testMock = new MockObject<TestInterface>("testMock", TestInterface.class, this);
        testProxy = testMock.getMock();
    }

    /**
     * Simple values like strings and integers must be showed directly in the suggested assert
     */
    @Test
    public void simpleValues() {
        testProxy.testMethodString("someValue");
        testProxy.testMethodInt(2);
        testProxy.testMethodInteger(3);

        String report = suggestedAssertsReport.createReport(this, getCurrentScenario().getObservedInvocations());

        assertTrue(report.contains("testMock.assertInvoked().testMethodString(\"someValue\");"));
        assertTrue(report.contains("testMock.assertInvoked().testMethodInt(2);"));
        assertTrue(report.contains("testMock.assertInvoked().testMethodInteger(3);"));
    }

    /**
     * If an argument refers to the same object as a field of the test object, the test object's field must be used
     */
    @Test
    public void testObjectFields() {
        testProxy.testMethodString(testDataStr);

        String report = suggestedAssertsReport.createReport(this, getCurrentScenario().getObservedInvocations());

        assertTrue(report.contains("testMock.assertInvoked().testMethodString(testDataStr);"));
    }

    /**
     * Objects that are not simple values are replaced by null in the suggested assert
     */
    @Test
    public void objects() {
        testProxy.testMethodObject(new ArrayList<String>());

        String report = suggestedAssertsReport.createReport(this, getCurrentScenario().getObservedInvocations());

        assertTrue(report.contains("testMock.assertInvoked().testMethodObject(null);"));
    }

    /**
     * Methods that return something are not included in the report
     */
    @Test
    public void onlySuggestAssertsForVoids() {
        testProxy.testMethodReturnsString();

        String report = suggestedAssertsReport.createReport(this, getCurrentScenario().getObservedInvocations());

        assertFalse(report.contains("testMock.assertInvoked().testMethodReturnsString()"));
    }

    public static interface TestInterface {

        String testMethodReturnsString();

        void testMethodString(String arg1);

        void testMethodInt(int arg1);

        void testMethodInteger(Integer arg1);

        void testMethodObject(List<String> arg1);
    }

}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Reflection;
using Microsoft.Azure.WebJobs.Host.Bindings;
using Microsoft.Azure.WebJobs.Host.Tables;
using Microsoft.WindowsAzure.Storage.Table;
using Xunit;

namespace Microsoft.Azure.WebJobs.Host.UnitTests.Tables
{
    public class TableEntityArgumentBindingProviderTests
    {
        private ParameterInfo[] _parameters;

        public TableEntityArgumentBindingProviderTests()
        {
            _parameters = this.GetType().GetMethod("Parameters", BindingFlags.NonPublic | BindingFlags.Static).GetParameters();
        }

        [Fact]
        public void Create_ReturnsNull_IfByRefParameter()
        {
            // Arrange
            ITableEntityArgumentBindingProvider product = new TableEntityArgumentBindingProvider();

            Type parameterType = typeof(SimpleTableEntity).MakeByRefType();

            // Act
            IArgumentBinding<TableEntityContext> binding = product.TryCreate(_parameters[0]);

            // Assert
            Assert.Null(binding);
        }

        [Fact]
        public void Create_ReturnsBinding_IfContainsResolvedGenericParameter()
        {
            // Arrange
            ITableEntityArgumentBindingProvider product = new TableEntityArgumentBindingProvider();

            Type parameterType = typeof(GenericClass<int>);

            // Act
            IArgumentBinding<TableEntityContext> binding = product.TryCreate(_parameters[1]);

            // Assert
            Assert.NotNull(binding);
        }

        private static void Parameters(ref SimpleTableEntity byRef, GenericClass<int> generic) {}

        private class SimpleTableEntity : TableEntity
        {
        }

        private class GenericClass<TArgument> : TableEntity
        {
        }
    }
}


text:
// Начало фикса Array.from для IE
// Шаги алгоритма ECMA-262, 6-е издание, 22.1.2.1
// Ссылка: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from
if (!Array.from) {
  Array.from = (function() {
    var toStr = Object.prototype.toString;
    var isCallable = function(fn) {
      return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
    };
    var toInteger = function (value) {
      var number = Number(value);
      if (isNaN(number)) { return 0; }
      if (number === 0 || !isFinite(number)) { return number; }
      return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
    };
    var maxSafeInteger = Math.pow(2, 53) - 1;
    var toLength = function (value) {
      var len = toInteger(value);
      return Math.min(Math.max(len, 0), maxSafeInteger);
    };

    // Свойство length метода from равно 1.
    return function from(arrayLike/*, mapFn, thisArg */) {
      // 1. Положим C равным значению this.
      var C = this;

      // 2. Положим items равным ToObject(arrayLike).
      var items = Object(arrayLike);

      // 3. ReturnIfAbrupt(items).
      if (arrayLike == null) {
        throw new TypeError('Array.from requires an array-like object - not null or undefined');
      }

      // 4. Если mapfn равен undefined, положим mapping равным false.
      var mapFn = arguments[1];
      if (typeof mapFn !== 'undefined') {
        mapFn = arguments.length > 1 ? arguments[1] : void undefined;
        // 5. иначе
        // 5. a. Если вызов IsCallable(mapfn) равен false, выкидываем исключение TypeError.
        if (!isCallable(mapFn)) {
          throw new TypeError('Array.from: when provided, the second argument must be a function');
        }

        // 5. b. Если thisArg присутствует, положим T равным thisArg; иначе положим T равным undefined.
        if (arguments.length > 2) {
          T = arguments[2];
        }
      }

      // 10. Положим lenValue равным Get(items, "length").
      // 11. Положим len равным ToLength(lenValue).
      var len = toLength(items.length);

      // 13. Если IsConstructor(C) равен true, то
      // 13. a. Положим A равным результату вызова внутреннего метода [[Construct]]
      //     объекта C со списком аргументов, содержащим единственный элемент len.
      // 14. a. Иначе, положим A равным ArrayCreate(len).
      var A = isCallable(C) ? Object(new C(len)) : new Array(len);

      // 16. Положим k равным 0.
      var k = 0;
      // 17. Пока k < len, будем повторять... (шаги с a по h)
      var kValue;
      while (k < len) {
        kValue = items[k];
        if (mapFn) {
          A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
        } else {
          A[k] = kValue;
        }
        k += 1;
      }
      // 18. Положим putStatus равным Put(A, "length", len, true).
      A.length = len;
      // 20. Вернём A.
      return A;
    };
  }());
}
// Конец фикса Array.from для IE

const truncate = (str, size = 50, postf = '...') => {
  if (str.length > size) {
    return str.substring(0, size - postf.length) + postf;
  }
  return str;
};

const request = new XMLHttpRequest();
request.open('GET', 'data/news/news.json', true);

request.onload = () => {
  if (request.status >= 200 && request.status < 400) {
    const data = JSON.parse(request.responseText);
    const newsList = document.getElementById('news__list');

    const articles = data.reduce((acc, article) => {
      const maxLength = 400;
      let moreLink = 'more >';
      if (article.body.length > maxLength) {
        moreLink = 'more >';
      }
      return `
        ${acc}

${article.title}

            ${article.date}

${truncate(article.body, maxLength)}

          ${moreLink}

      `;
    }, '');
    newsList.innerHTML = articles;

    const bodies = document.getElementsByClassName('news__body');

    Array.from(document.getElementsByClassName('news__link')).forEach((element, index, links) => {
      element.addEventListener('click', (event) => {
        event.preventDefault();
        if (links[index].getAttribute('data-state') === 'full') {
          bodies[index].innerHTML = truncate(data[index].body, 400);
          links[index].innerHTML = 'more >';
          links[index].setAttribute('data-state', 'truncated');
        } else {
          bodies[index].innerHTML = data[index].body;
          links[index].innerHTML = 'hide <';
          links[index].setAttribute('data-state', 'full');
        }
      });
    });
  } else console.log('server error: ', request.status);
};

request.onerror = () => console.log('loading error');

request.send();


text:
module Expectorant
  def self.register *args
    klass = args.last
    keys = args[0...-1]
    registrar.add(keys, klass)
  end

  def self.registrar
    @registrar ||= Registrar.new
  end

  def self.register_defaults
    register :equal, :equals, :==,       Asserter::Equalizer
    register :exist, :exists,            Asserter::Existential
    register :empty, :include, :contain, Asserter::Collector
    register :within, :close_to,         Asserter::Proximal
    register :instance_of, :an, :a,      Asserter::Typetastic
    register :match, :matches,           Asserter::Matcher
    register :change,                    Asserter::Cambiarse
    register :greater_than, :greater_than_or_equal,
             :>, :>=,
             :less_than, :less_than_or_equal,
             :<, :<=,                    Asserter::Comparitor
  end
end

Expectorant.register_defaults


text:
package com.sequenceiq.redbeams.service.stack;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

import java.util.Collections;
import java.util.Optional;
import java.util.Set;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.InjectMocks;
import org.mockito.Mock;

import com.sequenceiq.cloudbreak.quartz.model.JobResource;
import com.sequenceiq.redbeams.api.model.common.Status;
import com.sequenceiq.redbeams.domain.stack.DBStack;
import com.sequenceiq.redbeams.exception.NotFoundException;
import com.sequenceiq.redbeams.repository.DBStackRepository;

public class DBStackServiceTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Mock
    private DBStackRepository dbStackRepository;

    @InjectMocks
    private DBStackService underTest;

    private DBStack dbStack;

    @Before
    public void setUp() throws Exception {
        initMocks(this);

        dbStack = new DBStack();
    }

    @Test
    public void testGetById() {
        when(dbStackRepository.findById(1L)).thenReturn(Optional.of(dbStack));

        assertEquals(dbStack, underTest.getById(1L));
    }

    @Test
    public void testGetByIdNotFound() {
        thrown.expect(NotFoundException.class);
        when(dbStackRepository.findById(1L)).thenReturn(Optional.empty());

        underTest.getById(1L);
    }

    @Test
    public void testGetByNameAndEnvironmentId() {
        when(dbStackRepository.findByNameAndEnvironmentId("mystack", "myenv")).thenReturn(Optional.of(dbStack));

        assertEquals(dbStack, underTest.getByNameAndEnvironmentCrn("mystack", "myenv"));
    }

    @Test
    public void testGetByNameAndEnvironmentIdNotFound() {
        thrown.expect(NotFoundException.class);
        when(dbStackRepository.findByNameAndEnvironmentId("mystack", "myenv")).thenReturn(Optional.empty());

        underTest.getByNameAndEnvironmentCrn("mystack", "myenv");
    }

    @Test
    public void testSave() {
        when(dbStackRepository.save(dbStack)).thenReturn(dbStack);

        assertEquals(dbStack, underTest.save(dbStack));
        verify(dbStackRepository).save(dbStack);
    }

    @Test
    public void testFindAllForAutoSync() {
        Set<JobResource> expected = Collections.emptySet();
        when(dbStackRepository.findAllDbStackByStatusIn(Status.getAutoSyncStatuses())).thenReturn(expected);

        assertEquals(expected, underTest.findAllForAutoSync());

    }
}


text:
using System.Collections.Generic;
using System.Text;
namespace SuperMap.Web.ISDotNET6
{
    ///
    /// <para>${IS6_ProximityParam_Title}</para>
    /// <para>${IS6_ProximityParam_Description}</para>
    ///
    public class ProximityParam
    {
        /// ${IS6_ProximityParam_constructor_None_D}
        public ProximityParam()
        {
            NetworkParams = new NetworkParams();
            FacilityCount = 1;
            IsFromEvent = false;
        }
        /// ${IS6_ProximityParam_attribute_facilityCount_D}
        public int FacilityCount { get; set; }
        /// ${IS6_ProximityParam_attribute_facilityFilter_D}
        public string FacilityFilter { get; set; }
        /// ${IS6_ProximityParam_attribute_facilityLayer_D}
        public string FacilityLayer { get; set; }
        /// ${IS6_ProximityParam_attribute_isFromEvent_D}
        public bool IsFromEvent { get; set; }
        /// ${IS6_ProximityParam_attribute_maxRadius_D}
        public double MaxRadius { get; set; }
        /// ${IS6_ProximityParam_attribute_networkParams_D}
        public NetworkParams NetworkParams { get; set; }

        internal static string ToJson(ProximityParam param)
        {
            if (param == null)
            {
                return null;
            }

            string json = "{";
            List<string> list = new List<string>();
            list.Add(string.Format("\"highlight\":null"));

            if (param.NetworkParams != null)
            {
                list.Add(string.Format("\"networkParams\":{0}", NetworkParams.ToJson(param.NetworkParams)));
            }
            else
            {
                list.Add(string.Format("\"networkParams\":null"));
            }

            if (!string.IsNullOrEmpty(param.FacilityFilter))
            {
                list.Add(string.Format("\"facilityFilter\":\"{0}\"", param.FacilityFilter));
            }
            else
            {
                list.Add("\"facilityFilter\":\"\"");
            }

            if (!string.IsNullOrEmpty(param.FacilityLayer))
            {
                list.Add(string.Format("\"facilityLayer\":\"{0}\"", param.FacilityLayer));
            }
            else
            {
                list.Add("\"facilityLayer\":\"\"");
            }

            list.Add(string.Format("\"isFromEvent\":{0}", param.IsFromEvent.ToString().ToLower()));

            list.Add(string.Format("\"maxRadius\":{0}", param.MaxRadius));
            list.Add(string.Format("\"facilityCount\":{0}", param.FacilityCount));

            json += string.Join(",", list.ToArray());
            json += "}";
            return json;

        }
    }
}


text:
<!DOCTYPE html>

  <meta charset='utf-8'>
  <title>Google Maps and jqueryUI</title>
  <link type="text/css" href="main.css" rel="stylesheet" />
  <link type="text/css" href="jquery-ui/jquery-ui-1.8.16.custom.css" rel="stylesheet" />

Geocoding with Google Maps and jQuery UI

This page shows how you can use the autocomplete widget from jQuery UI in conjunction with the Google Maps geocoding API .

      Start typing a in the search box to trigger the drop-down autocomplete menu. Reverse lookup is also implemented: click the map (or drag an existing marker) and the search box will be populated with the closest address Google can find.

      The source code is on GitHub: rjshade/gmaps-autocomplete

      <input id='gmaps-input-address' placeholder='Start typing a place name...' type='text' />

      Latitude:

      Longitude: