text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <meta name="generator" content="pandoc" />
  <title>Corona Docs: Plugins > ads-admob </title>
  <meta name="revised" content="14-Nov-2013" />
  <meta name="description" content="Whether you're new to Corona or want to take your app to the next level, we've got a wealth of resources for you including extensive documentation, API reference, sample code, and videos.  Plugins > ads-admob " />
  <link rel="stylesheet" href="../../css/style.css" type="text/css" />

SDK APIs

Enterprise APIs

Plugins

Guides

Tutorials

Corona Resources ▹

  <form action="http://www.google.com/cse" id="cse-search-box">
  <input type="hidden" name="cx" value="009283852522218786394:g40gqt2m6rq" />
  <input type="hidden" name="ie" value="UTF-8" />
  <input type="text" name="q" id="q" autocomplete="off" size="40" style="width:150px;float:left" />
  <input type="submit" name="sa" value="Search" style="float:right; font-size: 13px;" />
  </form>

CoronaProvider.ads.admob.*

Overview

Platforms

Syntax

Functions

ads.init:

ads.show:

ads.hide:

Project Settings

SDK

Enterprise

Sample Code

Support

Ξ  ▸  Plugins  ▸  ads-admob

CoronaProvider.ads.admob.*

Type
provider

Revision
Current Public Release (2013.2076)

Keywords
ads, admob, provider

Sample code

See also
Marketplace

Availability
Starter, Basic, Pro, Enterprise

Overview

Platforms

The following platforms are supported:

Android

iOS

Syntax

You access this plugin by passing the appropriate provider name to the ads library:

local ads = require "ads"
ads.init( "admob", appID, adListener )

Functions

The admob plugin does not provide any additional functionality beyond the core functionality provided by the ads library.

ads.init:

ads.show:

ads.hide:

Project Settings

SDK

When you build using the Corona Simulator, the server automatically takes care of integrating the plugin into your project.

All you need to do is add an entry into a plugins table of your build.settings. The following is an example of a minimal build.settings file:

settings =
{
    plugins =
    {
        -- key is the name passed to Lua's 'require()'
        ["CoronaProvider.ads.admob"] =
        {
            -- required
            publisherId = "com.coronalabs",
        },
    },
}

Enterprise

TBD

Sample Code

You can access sample code https://github.com/coronalabs/plugins-sample-ads-admob.

Support

More support is available from the Google/AdMob team:

E-mail

Forum

http://www.google.com/ads/admob/

© 2013 Corona Labs Inc. All Rights Reserved. (Last updated: 14-Nov-2013)

Help us help you! Give us feedback on this page:

Love it

Like it, but...

Hate it


text: export { default } from 'ember-cli-showdown/components/markdown-to-html';

redpajama_set_name: RedPajamaGithub


text:
import * as React from 'react';
const PropTypes = require('prop-types'); // tslint:disable-line
import { Map } from 'mapbox-gl';

const containerStyle: React.CSSProperties = {
  position: 'absolute',
  zIndex: 10,
  display: 'flex',
  flexDirection: 'column',
  boxShadow: '0px 1px 4px rgba(0, 0, 0, .3)',
  border: '1px solid rgba(0, 0, 0, 0.1)'
} as React.CSSProperties;

const positions = {
  topRight: { top: 10, right: 10, bottom: 'auto', left: 'auto' },
  topLeft: { top: 10, left: 10, bottom: 'auto', right: 'auto' },
  bottomRight: { bottom: 10, right: 10, top: 'auto', left: 'auto' },
  bottomLeft: { bottom: 10, left: 10, top: 'auto', right: 'auto' }
};

const buttonStyle = {
  backgroundColor: '#f9f9f9',
  opacity: 0.95,
  transition: 'background-color 0.16s ease-out',
  cursor: 'pointer',
  border: 0,
  height: 26,
  width: 26,
  backgroundImage: 'url(\'https://api.mapbox.com/mapbox.js/v2.4.0/images/icons-000000@2x.png\')',
  backgroundPosition: '0px 0px',
  backgroundSize: '26px 260px',
  outline: 0
};

const buttonStyleHovered = {
  backgroundColor: '#fff',
  opacity: 1
};

const buttonStylePlus = {
  borderBottom: '1px solid rgba(0, 0, 0, 0.1)',
  borderTopLeftRadius: 2,
  borderTopRightRadius: 2
};

const buttonStyleMinus = {
  backgroundPosition: '0px -26px',
  borderBottomLeftRadius: 2,
  borderBottomRightRadius: 2
};

const [PLUS, MINUS] = [0, 1];
const POSITIONS = Object.keys(positions);

export interface Props {
  zoomDiff: number;
  onControlClick: (map: Map, zoomDiff: number) => void;
  position: 'topRight' | 'topLeft' | 'bottomRight' | 'bottomLeft';
  style: React.CSSProperties;
  className: string;
}

export interface State {
  hover?: number;
}

export interface Context {
  map: Map;
}

export default class ZoomControl extends React.Component<Props, State> {

  public context: Context;

  public static defaultProps = {
    position: POSITIONS[0],
    zoomDiff: 0.5,
    onControlClick: (map: Map, zoomDiff: number) => {
      map.zoomTo(map.getZoom() + zoomDiff);
    }
  };

  public state = {
    hover: undefined
  };

  public static contextTypes = {
    map: PropTypes.object
  };

  private onMouseOut = () => {
    if (!this.state.hover) {
      this.setState({ hover: undefined });
    }
  }

  private plusOver = () => {
    if (PLUS !== this.state.hover) {
      this.setState({ hover: PLUS });
    }
  }

  private minusOver = () => {
    if (MINUS !== this.state.hover) {
      this.setState({ hover: MINUS });
    }
  }

  private onClickPlus = () => {
    this.props.onControlClick(this.context.map, this.props.zoomDiff);
  }

  private onClickMinus = () => {
    this.props.onControlClick(this.context.map, -this.props.zoomDiff);
  }

  public render() {
    const { position, style, className } = this.props;
    const { hover } = this.state;

    return (
      <div
        className={className}
        style={{ ...containerStyle, ...positions[position], ...style }}
      >
        <button
          style={{ ...buttonStyle, ...buttonStylePlus, ...(hover === PLUS ? buttonStyleHovered : {}) }}
          onMouseOver={this.plusOver}
          onMouseOut={this.onMouseOut}
          onClick={this.onClickPlus}
        />
        <button
          style={{ ...buttonStyle, ...buttonStyleMinus, ...(hover === MINUS ? buttonStyleHovered : {}) }}
          onMouseOver={this.minusOver}
          onMouseOut={this.onMouseOut}
          onClick={this.onClickMinus}
        />
      </div>
    );
  }
}


text:
Meteor.startup(function(){

  Meteor.publish('users' , function(){
    console.log("## Publishing users collection");
    return Meteor.users.find({} , { fields: { profile : 1 } })
  });

  Meteor.publish('user' , function(_id) {
    console.log("## Publish user document for: ", _id);
    return Meteor.users.find({ _id : _id } , { fields: { profile : 1 } })
  })

})


text:
#pragma once

#include <memory>
#include <utility>
#include <vector>

#include <folly/Optional.h>
#include <folly/experimental/fibers/FiberManager.h>

#include "mcrouter/lib/Operation.h"
#include "mcrouter/lib/RouteHandleTraverser.h"
#include "mcrouter/McrouterFiberContext.h"
#include "mcrouter/proxy.h"
#include "mcrouter/route.h"
#include "mcrouter/routes/McrouterRouteHandle.h"
#include "mcrouter/routes/ShadowRouteIf.h"

namespace facebook { namespace memcache { namespace mcrouter {

/**
 * Shadowing using dynamic settings.
 *
 * Always sends the request to normalRoute.
 * In addition, asynchronously sends the same request to shadowRoutes if key
 * hash is within settings range
 * Key range might be updated at runtime.
 * We can shadow to multiple shadow destinations for a given normal route.
 */
template <class ShadowPolicy>
class ShadowRoute {
 public:
  static std::string routeName() { return "shadow"; }

  ShadowRoute(McrouterRouteHandlePtr normalRoute,
              McrouterShadowData shadowData,
              ShadowPolicy shadowPolicy)
      : normal_(std::move(normalRoute)),
        shadowData_(std::move(shadowData)),
        shadowPolicy_(std::move(shadowPolicy)) {
  }

  template <class Operation, class Request>
  void traverse(const Request& req, Operation,
                const RouteHandleTraverser<McrouterRouteHandleIf>& t) const {
    t(*normal_, req, Operation());
    for (auto& shadowData : shadowData_) {
      t(*shadowData.first, req, Operation());
    }
  }

  template <class Operation, class Request>
  typename ReplyType<Operation, Request>::type route(
    const Request& req, Operation) const {

    std::shared_ptr<Request> adjustedReq;
    folly::Optional<typename ReplyType<Operation, Request>::type> normalReply;
    for (const auto& iter : shadowData_) {
      if (shouldShadow(req, iter.second.get())) {
        if (!adjustedReq) {
          adjustedReq = std::make_shared<Request>(
            shadowPolicy_.updateRequestForShadowing(req, Operation()));
        }
        if (!normalReply && shadowPolicy_.shouldDelayShadow(req, Operation())) {
          normalReply = normal_->route(*adjustedReq, Operation());
        }
        auto shadow = iter.first;
        if (iter.second->validateRepliesFlag()) {
          normalReply = normal_->route(*adjustedReq, Operation());
          // this will spawn the fiber after copying required data
          // to validate from the normal Reply
          sendAndValidateRequest(
              *normalReply , std::move(shadow), adjustedReq, Operation());

        } else {
          dispatchShadowRequest(std::move(shadow), adjustedReq, Operation());
        }
      }
    }

    if (normalReply) {
      return std::move(*normalReply);
    } else {
      return normal_->route(adjustedReq ? *adjustedReq : req, Operation());
    }
  }

 private:
  const McrouterRouteHandlePtr normal_;
  const McrouterShadowData shadowData_;
  ShadowPolicy shadowPolicy_;

  template <class Request>
  bool shouldShadow(const Request& req, ShadowSettings* settings) const {
    auto range = settings->keyRange();
    return range.first <= req.routingKeyHash() &&
                          req.routingKeyHash() <= range.second;
  }

  template <class Operation, class Request>
  void dispatchShadowRequest(std::shared_ptr<McrouterRouteHandleIf> shadow,
                             std::shared_ptr<Request> adjustedReq,
                             Operation) const;

  template <class Operation, class Request, class Reply>
  void sendAndValidateRequest(const Reply& normalReply,
                              std::shared_ptr<McrouterRouteHandleIf> shadow,
                              std::shared_ptr<Request> adjustedReq,
                              Operation) const;

  template <class Request, class Reply>
  void sendAndValidateRequest(const Reply& normalReply,
                              std::shared_ptr<McrouterRouteHandleIf> shadow,
                              std::shared_ptr<Request> adjustedReq,
                              McOperation<mc_op_get>) const;
};

}}}  // facebook::memcache::mcrouter

#include "ShadowRoute-inl.h"


text:
require 'maxmind/geoip2/record/place'

module MaxMind
  module GeoIP2
    module Record
      # Contains data for the subdivisions associated with an IP address.
      #
      # This record is returned by all location databases and services besides
      # Country.
      #
      # See {MaxMind::GeoIP2::Record::Place} for inherited methods.
      class Subdivision < Place
        # This is a value from 0-100 indicating MaxMind's confidence that the
        # subdivision is correct. This attribute is only available from the
        # Insights service and the GeoIP2 Enterprise database.
        #
        # @return [Integer, nil]
        def confidence
          get('confidence')
        end

        # This is a GeoName ID for the subdivision. This attribute is returned by
        # all location databases and services besides Country.
        #
        # @return [Integer, nil]
        def geoname_id
          get('geoname_id')
        end

        # This is a string up to three characters long contain the subdivision
        # portion of the ISO 3166-2 code. See
        # https://en.wikipedia.org/wiki/ISO_3166-2. This attribute is returned by
        # all location databases and services except Country.
        #
        # @return [String, nil]
        def iso_code
          get('iso_code')
        end

        # A Hash where the keys are locale codes and the values are names. This attribute is returned by all location services and
        # databases besides country.
        #
        # @return [Hash<String, String>, nil]
        def names
          get('names')
        end
      end
    end
  end
end


text:
<img
    src="../../../assets/svg/ga.svg"
    alt="google analytics logo"
    height="100px"
    width="200px" />

# Google Analytics Enhanced Ecommerce
__homepage__: [google.com/analytics](https://www.google.com/analytics)
__docs__: [developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce](https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce)
__import__: `import { Angulartics2GoogleAnalyticsEnhancedEcommerce } from 'angulartics2';`

## Setup


text:
package io.github.bonigarcia.seljup.test.template;

import static io.github.bonigarcia.seljup.BrowserBuilder.chrome;
import static io.github.bonigarcia.seljup.BrowserBuilder.chromeInDocker;
import static io.github.bonigarcia.seljup.BrowserBuilder.chromeMobile;
import static io.github.bonigarcia.seljup.BrowserBuilder.edge;
import static io.github.bonigarcia.seljup.BrowserBuilder.firefox;
import static io.github.bonigarcia.seljup.BrowserBuilder.firefoxInDocker;
import static io.github.bonigarcia.seljup.BrowserBuilder.iexplorer;
import static io.github.bonigarcia.seljup.BrowserBuilder.opera;
import static io.github.bonigarcia.seljup.BrowserBuilder.operaInDocker;
import static io.github.bonigarcia.seljup.BrowserBuilder.safari;
import static org.assertj.core.api.Assertions.assertThat;

import java.util.stream.Stream;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

import io.github.bonigarcia.seljup.BrowserBuilder;
import io.github.bonigarcia.seljup.BrowsersTemplate.Browser;

class BrowserBuilderTest {

    static Stream<BrowserBuilder> browserBuilderProvider() {
        return Stream.of(chrome(), firefox(), opera(), edge(), safari(),
                iexplorer(), chromeInDocker(), firefoxInDocker(),
                operaInDocker(), chromeMobile());
    }

    @ParameterizedTest
    @MethodSource("browserBuilderProvider")
    void templateTest(BrowserBuilder browserBuilder) {
        Browser browser = browserBuilder.build();
        assertThat(browser).isNotNull();
    }

}


text:
import { inject as service } from '@ember/service';
import { reads } from '@ember/object/computed';
import Component from '@ember/component';
import layout from '../templates/components/paper-toaster';

export default Component.extend({
  layout,
  tagName: '',
  paperToaster: service(),
  activeToast: reads('paperToaster.activeToast'),

  onClose(toast) {
    this.paperToaster.cancelToast(toast);
  }
});


text:
@interface LTimelineTableViewController : UITableViewController

@end


text:
typedef struct {
  // Vertex position in 2D clip space.
  vector_float2 position;
  // Corresponding texture coordinate.
  vector_float2 texture_coordinate;
} MediaPipeTexturedVertex;

// Common buffer indices used in our Metal shaders.
typedef enum {
  MediaPipeBufferIndexInputVertices = 0,
  MediaPipeBufferIndexRgbWeights = 1,
  MediaPipeBufferIndexPixelSize = 2,
  MediaPipeBufferIndexOutputColor = 3,
} MediaPipeBufferIndex;

// Common texture indices used in our Metal shaders.
typedef enum {
  MediaPipeTextureIndexInputColor = 0,
  MediaPipeTextureIndexOutputColor = 1,
} MediaPipeTextureIndex;

typedef vector_float3 MetalRgbWeightPacketType;

#endif  // MEDIAPIPE_GPU_METAL_SHADER_BASE_H_


text:
  This monitors the clock difference between the controller and nodes. While
  Jenkins itself is generally capable of tolerating clock differences between
  systems, version control activities and distributed file access (such as NFS,
  Windows file shares) tend to have strange problems when systems involved have
  different clocks.

To keep clocks in sync, refer to NTP.


text: search_result['306']=["topic_000000000000009D_events--.html","TwillioUploadScheduler Events",""];


text:
<?php

declare(strict_types=1);

namespace FluentDOM\Utility {

  /**
   * Utility class that handles a list of namespace definitions.
   */
  class Namespaces implements NamespaceResolver, \ArrayAccess, \IteratorAggregate, \Countable {

    /**
     * @var array
     */
    private $_namespaces = [];

    /**
     * @var array
     */
    private $_reserved = [
      'xml' => 'http://www.w3.org/XML/1998/namespace',
      'xmlns' => 'http://www.w3.org/2000/xmlns/'
    ];

    private $_stash = [];

    /**
     * Namespaces constructor.
     * @param NULL|array|\Traversable $namespaces
     */
    public function __construct($namespaces = NULL) {
      if (NULL !== $namespaces) {
        $this->assign($namespaces);
      }
    }

    /**
     * @param string $prefix
     * @return string|NULL
     */
    public function resolveNamespace(string $prefix): ?string {
      return $this[empty($prefix) ? '#default' : $prefix];
    }

    /**
     * @param string $prefix
     * @return bool
     */
    public function isReservedPrefix(string $prefix): bool {
      return \array_key_exists($prefix, $this->_reserved);
    }

    /**
     * @param string $prefix
     * @return bool
     */
    public function offsetExists($prefix): bool {
      return \array_key_exists($prefix, $this->_reserved) || \array_key_exists($prefix, $this->_namespaces);
    }

    /**
     * @param string $prefix
     * @param string $namespaceURI
     * @throws \LogicException
     */
    public function offsetSet($prefix, $namespaceURI): void {
      $prefix = $this->validatePrefix($prefix);
      if (isset($this->_reserved[$prefix])) {
        throw new \LogicException(
          \sprintf('Can not register reserved namespace prefix "%s".', $prefix)
        );
      }
      $this->_namespaces[$prefix] = $namespaceURI;
    }

    /**
     * @param string $prefix
     * @return string|NULL
     * @throws \LogicException
     */
    public function offsetGet($prefix): ?string {
      $prefix = $this->validatePrefix($prefix);
      if (\array_key_exists($prefix, $this->_reserved)) {
        return $this->_reserved[$prefix];
      }
      if (\array_key_exists($prefix, $this->_namespaces)) {
        return $this->_namespaces[$prefix];
      }
      if ($prefix === '#default') {
        return '';
      }
      throw new \LogicException(
        \sprintf('Unknown namespace prefix "%s".', $prefix)
      );
    }

    /**
     * @param string $prefix
     */
    public function offsetUnset($prefix): void {
      $prefix = $this->validatePrefix($prefix);
      if (\array_key_exists($prefix, $this->_namespaces)) {
        unset($this->_namespaces[$prefix]);
      }
    }

    /**
     * @return \Iterator
     */
    public function getIterator(): \Iterator {
      return new \ArrayIterator($this->_namespaces);
    }

    /**
     * Store current status on the stash
     */
    public function store(): void {
      $this->_stash[] = $this->_namespaces;
    }

    /**
     * Restore last stashed status from the stash
     */
    public function restore(): void {
      $this->_namespaces = \array_pop($this->_stash);
    }

    /**
     * @return int
     */
    public function count(): int {
      return \count($this->_namespaces);
    }

    /**
     * @param array|\Traversable $namespaces
     * @throws \LogicException
     */
    public function assign($namespaces): void {
      $this->_namespaces = [];
      foreach ($namespaces as $prefix => $namespaceURI) {
        $this->offsetSet($prefix, $namespaceURI);
      }
    }

    /**
     * @param string $prefix
     * @return string
     */
    private function validatePrefix(string $prefix): string {
      return empty($prefix) ? '#default' : $prefix;
    }
  }
}


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.precache;

import android.content.Context;
import android.net.ConnectivityManager;
import android.os.BatteryManager;
import android.test.InstrumentationTestCase;
import android.test.suitebuilder.annotation.SmallTest;

import org.chromium.base.test.util.AdvancedMockContext;
import org.chromium.base.test.util.Feature;

/**
 * Tests for {@link DeviceState}.
 */
public class DeviceStateTest extends InstrumentationTestCase {

    /**
     * Factory to create {@link MockNetworkInfoDelegate} instances.
     */
    static class MockNetworkInfoDelegateFactory extends NetworkInfoDelegateFactory {
        private final boolean mIsValid;
        private final int mType;
        private final boolean mIsAvailable;
        private final boolean mIsConnected;
        private final boolean mIsRoaming;
        private final boolean mIsActiveNetworkMetered;

        MockNetworkInfoDelegateFactory(boolean valid, int type, boolean available,
                boolean connected, boolean roaming, boolean activeNetworkMetered) {
            mIsValid = valid;
            mType = type;
            mIsAvailable = available;
            mIsConnected = connected;
            mIsRoaming = roaming;
            mIsActiveNetworkMetered = activeNetworkMetered;
        }

        @Override
        NetworkInfoDelegate getNetworkInfoDelegate(Context context) {
            return new MockNetworkInfoDelegate(mIsValid, mType, mIsAvailable, mIsConnected,
                    mIsRoaming, mIsActiveNetworkMetered);
        }
    }

    /**
     * Mock of {@link NetworkInfoDelegate}.
     */
    static class MockNetworkInfoDelegate extends NetworkInfoDelegate {
        private final boolean mIsValid;
        private final int mType;
        private final boolean mIsAvailable;
        private final boolean mIsConnected;
        private final boolean mIsRoaming;
        private final boolean mIsActiveNetworkMetered;

        MockNetworkInfoDelegate(boolean valid, int type, boolean available, boolean connected,
                boolean roaming, boolean activeNetworkMetered) {
            mIsValid = valid;
            mType = type;
            mIsAvailable = available;
            mIsConnected = connected;
            mIsRoaming = roaming;
            mIsActiveNetworkMetered = activeNetworkMetered;
        }

        @Override
        protected void getNetworkInfo(Context context) {}

        @Override
        protected boolean isValid() {
            return mIsValid;
        }

        @Override
        protected int getType() {
            return mType;
        }

        @Override
        protected boolean isAvailable() {
            return mIsAvailable;
        }

        @Override
        protected boolean isConnected() {
            return mIsConnected;
        }

        @Override
        protected boolean isRoaming() {
            return mIsRoaming;
        }

        @Override
        protected boolean isActiveNetworkMetered() {
            return mIsActiveNetworkMetered;
        }
    }

    /**
     * Mock of {@link DeviceState}.
     */
    static class MockDeviceState extends DeviceState {
        int mBatteryStatus;

        @Override
        int getStickyBatteryStatus(Context context) {
            return mBatteryStatus;
        }

        public void setStickyBatteryStatus(int status) {
            mBatteryStatus = status;
        }
    }

    @SmallTest
    @Feature({"Precache"})
    public void testPowerConnected() {
        AdvancedMockContext context = new AdvancedMockContext();
        MockDeviceState deviceState = new MockDeviceState();

        deviceState.setStickyBatteryStatus(BatteryManager.BATTERY_STATUS_NOT_CHARGING);
        assertFalse(deviceState.isPowerConnected(context));

        deviceState.setStickyBatteryStatus(BatteryManager.BATTERY_STATUS_CHARGING);
        assertTrue(deviceState.isPowerConnected(context));

        deviceState.setStickyBatteryStatus(BatteryManager.BATTERY_STATUS_FULL);
        assertTrue(deviceState.isPowerConnected(context));
    }

    @SmallTest
    @Feature({"Precache"})
    public void testWifiAvailable() {
        AdvancedMockContext context = new AdvancedMockContext();
        DeviceState deviceState = DeviceState.getInstance();

        // Expect WiFi to be reported as available because there is valid {@link NetworkInfo},
        // the connection is WiFi, it's available and connected, and not roaming or metered.
        deviceState.setNetworkInfoDelegateFactory(
                new MockNetworkInfoDelegateFactory(
                        true, ConnectivityManager.TYPE_WIFI, true, true, false, false));
        assertTrue(deviceState.isWifiAvailable(context));

        // Expect WiFi to be reported as unavailable because one of the aforementioned required
        // conditions is not met.
        deviceState.setNetworkInfoDelegateFactory(
                new MockNetworkInfoDelegateFactory(
                        false, ConnectivityManager.TYPE_WIFI, true, true, false, false));
        assertFalse(deviceState.isWifiAvailable(context));

        deviceState.setNetworkInfoDelegateFactory(
                new MockNetworkInfoDelegateFactory(true, 0, false, true, false, false));
        assertFalse(deviceState.isWifiAvailable(context));

        deviceState.setNetworkInfoDelegateFactory(
                new MockNetworkInfoDelegateFactory(
                        true, ConnectivityManager.TYPE_WIFI, false, true, false, false));
        assertFalse(deviceState.isWifiAvailable(context));

        deviceState.setNetworkInfoDelegateFactory(
                new MockNetworkInfoDelegateFactory(
                        true, ConnectivityManager.TYPE_WIFI, true, false, false, false));
        assertFalse(deviceState.isWifiAvailable(context));

        deviceState.setNetworkInfoDelegateFactory(
                new MockNetworkInfoDelegateFactory(
                        true, ConnectivityManager.TYPE_WIFI, true, true, true, false));
        assertFalse(deviceState.isWifiAvailable(context));

        deviceState.setNetworkInfoDelegateFactory(
                new MockNetworkInfoDelegateFactory(
                        true, ConnectivityManager.TYPE_WIFI, true, true, false, true));
        assertFalse(deviceState.isWifiAvailable(context));

        deviceState.setNetworkInfoDelegateFactory(
                new MockNetworkInfoDelegateFactory(true, 0, false, false, true, true));
        assertFalse(deviceState.isWifiAvailable(context));
    }
}


text:
<?php

namespace Ayaline\Bundle\ComposerBundle\Consumer\Step;

use Sonata\NotificationBundle\Consumer\ConsumerEvent;

/**
 * @author Hubert Moutot <hubert.moutot@gmail.com>
 */
class ComposerInstalledStep extends AbstractStep
{
    /**
     * {@inheritdoc}
     */
    public function execute(ConsumerEvent $event, $directory)
    {
        $output = null;
        $workingDirectory = $this->workingTempPath.'/'.$directory;

        $process = $this->runProcess(sprintf('%s show --installed', $this->composerBinPath), $workingDirectory, $output);
        if ($process->isSuccessful()) {
            $this->triggerComposerInstalled($event, ['message' => $process->getOutput()]);
        }

        return 0;
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebGL Draw Conformance Tests</title>
<link rel="stylesheet" href="../../../../resources/js-test-style.css"/>

<canvas id="canvas" width="200" height="100"> </canvas>


text:
var stylus         = require('stylus');
var nib            = require('nib');
var folderContents = require('folder-contents');
var fs             = require('fs');

var examplesFolders = folderContents({
    path: __dirname,
    filter: {
        folderIgnore: ['_import_theme']
    }
})['.folders'];

examplesFolders.forEach(function(folderName) {
    var dir = __dirname + '/' + folderName;

    new Promise(function(resolve, reject) {
        fs.readFile(dir + '/main.styl', 'utf8', function(err, str) {
            if (err) { reject(err); }
            resolve(str);
        });
    }).then(function(str) {
        return compile(str, dir + '/main.styl')
    }).then(function(css) {
        fs.writeFile(dir + '/main.css', css, function(err) {
            if (err) { Promise.reject(err); }
        });
    }).catch(function(err) { console.error(err); });
});

function compile(str, path) {
    return new Promise(function(resolve, reject) {
        stylus(str)
            .set('filename', path)
            .use(nib())
            .render(function(err, css) {
                if (err) { reject(err) }
                resolve(css);
            });
    });
}


text: Why use Grunt.js for your automation?


text:
require 'spec_helper'

describe "admin/history/addresses/edit.html.erb" do
  before(:each) do
    @order = Factory(:order)
    @address = Factory(:address)
    view.stubs(:states).returns([])
  #  assign(:address, stub_model(Address,
  #    :new_record? => false,
  #    :first_name => "MyString",
  #    :last_name => "MyString",
  #    :address1 => "MyString",
  #    :address2 => "MyString",
  #    :city => "MyString",
  #    :state_id => 1,
  #    :zip_code => "MyString"
  #  ))
  end

  it "renders the edit address form" do
    render :template => "admin/history/addresses/edit", :handlers => [:erb]
  end
end


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import warnings

import py
import six

import _pytest._code
from _pytest.compat import getfslineno
from _pytest.mark.structures import NodeKeywords
from _pytest.outcomes import fail

SEP = "/"

tracebackcutdir = py.path.local(_pytest.__file__).dirpath()

def _splitnode(nodeid):
    """Split a nodeid into constituent 'parts'.

    Node IDs are strings, and can be things like:
        ''
        'testing/code'
        'testing/code/test_excinfo.py'
        'testing/code/test_excinfo.py::TestFormattedExcinfo'

    Return values are lists e.g.
        []
        ['testing', 'code']
        ['testing', 'code', 'test_excinfo.py']
        ['testing', 'code', 'test_excinfo.py', 'TestFormattedExcinfo', '()']
    """
    if nodeid == "":
        # If there is no root node at all, return an empty list so the caller's logic can remain sane
        return []
    parts = nodeid.split(SEP)
    # Replace single last element 'test_foo.py::Bar' with multiple elements 'test_foo.py', 'Bar'
    parts[-1:] = parts[-1].split("::")
    return parts

def ischildnode(baseid, nodeid):
    """Return True if the nodeid is a child node of the baseid.

    E.g. 'foo/bar::Baz' is a child of 'foo', 'foo/bar' and 'foo/bar::Baz', but not of 'foo/blorp'
    """
    base_parts = _splitnode(baseid)
    node_parts = _splitnode(nodeid)
    if len(node_parts) < len(base_parts):
        return False
    return node_parts[: len(base_parts)] == base_parts

class Node(object):
    """ base class for Collector and Item the test collection tree.
    Collector subclasses have children, Items are terminal nodes."""

    def __init__(
        self, name, parent=None, config=None, session=None, fspath=None, nodeid=None
    ):
        #: a unique name within the scope of the parent node
        self.name = name

        #: the parent collector node.
        self.parent = parent

        #: the pytest config object
        self.config = config or parent.config

        #: the session this node is part of
        self.session = session or parent.session

        #: filesystem path where this node was collected from (can be None)
        self.fspath = fspath or getattr(parent, "fspath", None)

        #: keywords/markers collected from all scopes
        self.keywords = NodeKeywords(self)

        #: the marker objects belonging to this node
        self.own_markers = []

        #: allow adding of extra keywords to use for matching
        self.extra_keyword_matches = set()

        # used for storing artificial fixturedefs for direct parametrization
        self._name2pseudofixturedef = {}

        if nodeid is not None:
            assert "::()" not in nodeid
            self._nodeid = nodeid
        else:
            self._nodeid = self.parent.nodeid
            if self.name != "()":
                self._nodeid += "::" + self.name

    @property
    def ihook(self):
        """ fspath sensitive hook proxy used to call pytest hooks"""
        return self.session.gethookproxy(self.fspath)

    def __repr__(self):
        return "<%s %s>" % (self.__class__.__name__, getattr(self, "name", None))

    def warn(self, warning):
        """Issue a warning for this item.

        Warnings will be displayed after the test session, unless explicitly suppressed

        :param Warning warning: the warning instance to issue. Must be a subclass of PytestWarning.

        :raise ValueError: if ``warning`` instance is not a subclass of PytestWarning.

        Example usage:

        .. code-block:: python

            node.warn(PytestWarning("some message"))

        """
        from _pytest.warning_types import PytestWarning

        if not isinstance(warning, PytestWarning):
            raise ValueError(
                "warning must be an instance of PytestWarning or subclass, got {!r}".format(
                    warning
                )
            )
        path, lineno = get_fslocation_from_item(self)
        warnings.warn_explicit(
            warning,
            category=None,
            filename=str(path),
            lineno=lineno + 1 if lineno is not None else None,
        )

    # methods for ordering nodes
    @property
    def nodeid(self):
        """ a ::-separated string denoting its collection tree address. """
        return self._nodeid

    def __hash__(self):
        return hash(self.nodeid)

    def setup(self):
        pass

    def teardown(self):
        pass

    def listchain(self):
        """ return list of all parent collectors up to self,
            starting from root of collection tree. """
        chain = []
        item = self
        while item is not None:
            chain.append(item)
            item = item.parent
        chain.reverse()
        return chain

    def add_marker(self, marker, append=True):
        """dynamically add a marker object to the node.

        :type marker: ``str`` or ``pytest.mark.*``  object
        :param marker:
            ``append=True`` whether to append the marker,
            if ``False`` insert at position ``0``.
        """
        from _pytest.mark import MarkDecorator, MARK_GEN

        if isinstance(marker, six.string_types):
            marker = getattr(MARK_GEN, marker)
        elif not isinstance(marker, MarkDecorator):
            raise ValueError("is not a string or pytest.mark.* Marker")
        self.keywords[marker.name] = marker
        if append:
            self.own_markers.append(marker.mark)
        else:
            self.own_markers.insert(0, marker.mark)

    def iter_markers(self, name=None):
        """
        :param name: if given, filter the results by the name attribute

        iterate over all markers of the node
        """
        return (x[1] for x in self.iter_markers_with_node(name=name))

    def iter_markers_with_node(self, name=None):
        """
        :param name: if given, filter the results by the name attribute

        iterate over all markers of the node
        returns sequence of tuples (node, mark)
        """
        for node in reversed(self.listchain()):
            for mark in node.own_markers:
                if name is None or getattr(mark, "name", None) == name:
                    yield node, mark

    def get_closest_marker(self, name, default=None):
        """return the first marker matching the name, from closest (for example function) to farther level (for example
        module level).

        :param default: fallback return value of no marker was found
        :param name: name to filter by
        """
        return next(self.iter_markers(name=name), default)

    def listextrakeywords(self):
        """ Return a set of all extra keywords in self and any parents."""
        extra_keywords = set()
        for item in self.listchain():
            extra_keywords.update(item.extra_keyword_matches)
        return extra_keywords

    def listnames(self):
        return [x.name for x in self.listchain()]

    def addfinalizer(self, fin):
        """ register a function to be called when this node is finalized.

        This method can only be called when this node is active
        in a setup chain, for example during self.setup().
        """
        self.session._setupstate.addfinalizer(fin, self)

    def getparent(self, cls):
        """ get the next parent node (including ourself)
        which is an instance of the given class"""
        current = self
        while current and not isinstance(current, cls):
            current = current.parent
        return current

    def _prunetraceback(self, excinfo):
        pass

    def _repr_failure_py(self, excinfo, style=None):
        if excinfo.errisinstance(fail.Exception):
            if not excinfo.value.pytrace:
                return six.text_type(excinfo.value)
        fm = self.session._fixturemanager
        if excinfo.errisinstance(fm.FixtureLookupError):
            return excinfo.value.formatrepr()
        tbfilter = True
        if self.config.option.fulltrace:
            style = "long"
        else:
            tb = _pytest._code.Traceback([excinfo.traceback[-1]])
            self._prunetraceback(excinfo)
            if len(excinfo.traceback) == 0:
                excinfo.traceback = tb
            tbfilter = False  # prunetraceback already does it
            if style == "auto":
                style = "long"
        # XXX should excinfo.getrepr record all data and toterminal() process it?
        if style is None:
            if self.config.option.tbstyle == "short":
                style = "short"
            else:
                style = "long"

        if self.config.option.verbose > 1:
            truncate_locals = False
        else:
            truncate_locals = True

        try:
            os.getcwd()
            abspath = False
        except OSError:
            abspath = True

        return excinfo.getrepr(
            funcargs=True,
            abspath=abspath,
            showlocals=self.config.option.showlocals,
            style=style,
            tbfilter=tbfilter,
            truncate_locals=truncate_locals,
        )

    repr_failure = _repr_failure_py

def get_fslocation_from_item(item):
    """Tries to extract the actual location from an item, depending on available attributes:

    * "fslocation": a pair (path, lineno)
    * "obj": a Python object that the item wraps.
    * "fspath": just a path

    :rtype: a tuple of (str|LocalPath, int) with filename and line number.
    """
    result = getattr(item, "location", None)
    if result is not None:
        return result[:2]
    obj = getattr(item, "obj", None)
    if obj is not None:
        return getfslineno(obj)
    return getattr(item, "fspath", "unknown location"), -1

class Collector(Node):
    """ Collector instances create children through collect()
        and thus iteratively build a tree.
    """

    class CollectError(Exception):
        """ an error during collection, contains a custom message. """

    def collect(self):
        """ returns a list of children (items and collectors)
            for this collection node.
        """
        raise NotImplementedError("abstract")

    def repr_failure(self, excinfo):
        """ represent a collection failure. """
        if excinfo.errisinstance(self.CollectError):
            exc = excinfo.value
            return str(exc.args[0])

        # Respect explicit tbstyle option, but default to "short"
        # (None._repr_failure_py defaults to "long" without "fulltrace" option).
        tbstyle = self.config.getoption("tbstyle")
        if tbstyle == "auto":
            tbstyle = "short"

        return self._repr_failure_py(excinfo, style=tbstyle)

    def _prunetraceback(self, excinfo):
        if hasattr(self, "fspath"):
            traceback = excinfo.traceback
            ntraceback = traceback.cut(path=self.fspath)
            if ntraceback == traceback:
                ntraceback = ntraceback.cut(excludepath=tracebackcutdir)
            excinfo.traceback = ntraceback.filter()

def _check_initialpaths_for_relpath(session, fspath):
    for initial_path in session._initialpaths:
        if fspath.common(initial_path) == initial_path:
            return fspath.relto(initial_path)

class FSCollector(Collector):
    def __init__(self, fspath, parent=None, config=None, session=None, nodeid=None):
        fspath = py.path.local(fspath)  # xxx only for test_resultlog.py?
        name = fspath.basename
        if parent is not None:
            rel = fspath.relto(parent.fspath)
            if rel:
                name = rel
            name = name.replace(os.sep, SEP)
        self.fspath = fspath

        session = session or parent.session

        if nodeid is None:
            nodeid = self.fspath.relto(session.config.rootdir)

            if not nodeid:
                nodeid = _check_initialpaths_for_relpath(session, fspath)
            if nodeid and os.sep != SEP:
                nodeid = nodeid.replace(os.sep, SEP)

        super(FSCollector, self).__init__(
            name, parent, config, session, nodeid=nodeid, fspath=fspath
        )

class File(FSCollector):
    """ base class for collecting tests from a file. """

class Item(Node):
    """ a basic test invocation item. Note that for a single function
    there might be multiple test invocation items.
    """

    nextitem = None

    def __init__(self, name, parent=None, config=None, session=None, nodeid=None):
        super(Item, self).__init__(name, parent, config, session, nodeid=nodeid)
        self._report_sections = []

        #: user properties is a list of tuples (name, value) that holds user
        #: defined properties for this test.
        self.user_properties = []

    def add_report_section(self, when, key, content):
        """
        Adds a new report section, similar to what's done internally to add stdout and
        stderr captured output::

            item.add_report_section("call", "stdout", "report section contents")

        :param str when:
            One of the possible capture states, ``"setup"``, ``"call"``, ``"teardown"``.
        :param str key:
            Name of the section, can be customized at will. Pytest uses ``"stdout"`` and
            ``"stderr"`` internally.

        :param str content:
            The full contents as a string.
        """
        if content:
            self._report_sections.append((when, key, content))

    def reportinfo(self):
        return self.fspath, None, ""

    @property
    def location(self):
        try:
            return self._location
        except AttributeError:
            location = self.reportinfo()
            fspath = self.session._node_location_to_relpath(location[0])
            location = (fspath, location[1], str(location[2]))
            self._location = location
            return location


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/Users/gokhanc/src/android-sdk/facebook/res/values-kn/messenger_button_strings.xml -->
    <eat-comment/>
    <string name="messenger_send_button_text">ಕಳುಹಿಸು</string>
</resources>


text:
package io.craft.armor;

import io.craft.armor.api.Arm;
import io.craft.armor.api.Armor;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author mindwind
 * @version 1.0, Dec 18, 2014
 */
@Armor
@Service("demoService")
public class DemoServiceImpl implements DemoService {

	@Autowired protected DemoChildService demoChildService;
	           protected boolean          ok              ;

	@PostConstruct
	void init() {
		ok = true;
	}

	@Override
	public String echo(String in) {
		return in;
	}

	@Override
	public boolean isOk() {
		return ok;
	}

	@Override
	public String echoCascade(String in) {
		return demoChildService.echo(in);
	}

	@Override
	public void timeout(int timeoutInMillis) {
		try {
			Thread.sleep(timeoutInMillis);
		} catch (InterruptedException e) {
		}
	}

	@Override
	public int echo(int i) {
		return i;
	}

	@Override
	public void throwException() throws IllegalAccessException {
		throw new IllegalAccessException();
	}

	@Override
	@Arm(async = true, timeout = 5, threads = 10)
	public void arm() {}

}


text:
<plugin>
	<nom>Vertèbres</nom>
	<slogan>Lecteur de tables SQL</slogan>
	<auteur>Collectif SPIP</auteur>
	<licence>GNU/GPL</licence>
	<version>1.0.0</version>
	<description>
	Vertèbres propose un moyen de lire une table SQL en indiquant comme argument de page la table à lire, précédé de "table:", par exemple : spip.php?page=table:articles
	</description>
	<etat>stable</etat>
	<prefix>vertebres</prefix>

  	<icon>images/vertebres-32.png</icon>
 	<pipeline>
		<nom>styliser</nom>
		<inclure>vertebres_pipelines.php</inclure>
	</pipeline>
	<categorie>outil</categorie>
	<necessite id="SPIP" version="[2.1.0;2.1.99]" />
</plugin>


text:
package br.ufsc.inf.lapesd.ldservice.model.properties.extractors;

import br.ufsc.inf.lapesd.ldservice.model.Selector;
import br.ufsc.inf.lapesd.ldservice.model.properties.SelectorProperty;

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

/**
 * Documents that a {@link SelectorPropertyExtractor} extracts a given type of
 * {@link SelectorProperty}
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtractsSelectorProperty {
    Class<? extends SelectorProperty> type();
    Class<? extends Selector> from();
}


text:
package org.jetbrains.plugins.groovy.refactoring.introduce;

import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.refactoring.ui.ConflictsDialog;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.MultiMap;
import javax.annotation.Nonnull;
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringUtil;

import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;

/**
 * @author Maxim.Medvedev
 */
public class GrIntroduceValidatorEngine implements GrIntroduceHandlerBase.Validator {
  private final GrIntroduceContext myContext;
  private final ConflictReporter myReporter;

  public GrIntroduceValidatorEngine(GrIntroduceContext context, ConflictReporter reporter) {
    myContext = context;
    myReporter = reporter;
  }

  public boolean isOK(GrIntroduceDialog dialog) {
    final GrIntroduceSettings settings = dialog.getSettings();
    if (settings == null) return false;
    String varName = settings.getName();
    boolean allOccurrences = settings.replaceAllOccurrences();
    final MultiMap<PsiElement, String> conflicts = isOKImpl(varName, allOccurrences);
    return conflicts.size() <= 0 || reportConflicts(conflicts, getProject());
  }

  private static boolean reportConflicts(final MultiMap<PsiElement, String> conflicts, final Project project) {
    ConflictsDialog conflictsDialog = new ConflictsDialog(project, conflicts);
    conflictsDialog.show();
    return conflictsDialog.isOK();
  }

  private MultiMap<PsiElement, String> isOKImpl(String varName, boolean replaceAllOccurrences) {
    PsiElement firstOccurence;
    if (replaceAllOccurrences) {
      if (myContext.getOccurrences().length > 0) {
        GroovyRefactoringUtil.sortOccurrences(myContext.getOccurrences());
        firstOccurence = myContext.getOccurrences()[0];
      }
      else {
        firstOccurence = myContext.getPlace();
      }
    }
    else {
      firstOccurence = myContext.getExpression();
    }
    final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
    assert varName != null;

    final int offset = firstOccurence.getTextRange().getStartOffset();
    validateOccurrencesDown(myContext.getScope(), conflicts, varName, offset);
    if (!(myContext.getScope() instanceof GroovyFileBase)) {
      validateVariableOccurrencesUp(myContext.getScope(), conflicts, varName, offset);
    }
    return conflicts;
  }

  /**
   * Use for validator tests
   */
  public String isOKTest(String varName, boolean allOccurences) {
    MultiMap<PsiElement, String> list = isOKImpl(varName, allOccurences);
    String result = "";
    final String[] strings = ArrayUtil.toStringArray((Collection<String>)list.values());
    Arrays.sort(strings, new Comparator<String>() {
      @Override
      public int compare(String o1, String o2) {
        return o1.compareTo(o2);
      }
    });

    for (String s : strings) {
      result = result + s.replaceAll("", "").replaceAll("", "") + "\n";
    }
    if (list.size() > 0) {
      result = result.substring(0, result.length() - 1);
    }
    if (result.length() == 0) {
      result = "ok";
    }
    return result;
  }

  /**
   * @param startElement Container to start checking conflicts from
   * @param conflicts    Conflict accumulator
   * @param varName      Variable name
   * @param startOffset
   */
  private void validateOccurrencesDown(PsiElement startElement,
                                       MultiMap<PsiElement, String> conflicts,
                                       @Nonnull String varName,
                                       double startOffset) {
    PsiElement child = startElement.getFirstChild();
    while (child != null) {
      // Do not check defined classes, methods, closures and blocks before
      if (child instanceof GrTypeDefinition ||
          child instanceof GrMethod ||
          GroovyRefactoringUtil.isAppropriateContainerForIntroduceVariable(child) &&
          child.getTextRange().getEndOffset() < startOffset) {
        myReporter.check(child, conflicts, varName);
        child = child.getNextSibling();
        continue;
      }
      if (child instanceof GrVariable) {
        myReporter.check(child, conflicts, varName);
        validateOccurrencesDown(child, conflicts, varName, startOffset);
      }
      else {
        validateOccurrencesDown(child, conflicts, varName, startOffset);
      }
      child = child.getNextSibling();
    }
  }

  private void validateVariableOccurrencesUp(PsiElement startElement,
                                             MultiMap<PsiElement, String> conflicts,
                                             @Nonnull String varName,
                                             double startOffset) {
    PsiElement prevSibling = startElement.getPrevSibling();
    while (prevSibling != null) {
      if (!(GroovyRefactoringUtil.isAppropriateContainerForIntroduceVariable(prevSibling) &&
            prevSibling.getTextRange().getEndOffset() < startOffset)) {
        validateOccurrencesDown(prevSibling, conflicts, varName, startOffset);
      }
      prevSibling = prevSibling.getPrevSibling();
    }

    PsiElement parent = startElement.getParent();
    // Do not check context out of method, type definition and directories
    if (parent == null ||
        parent instanceof GrMethod ||
        parent instanceof GrTypeDefinition ||
        parent instanceof GroovyFileBase ||
        parent instanceof PsiDirectory) {
      return;
    }

    validateVariableOccurrencesUp(parent, conflicts, varName, startOffset);
  }

  /**
   * Validates name to be suggested in context
   */
  public String validateName(String name, boolean increaseNumber) {
    String result = name;
    if (isOKImpl(name, true).size() > 0 && !increaseNumber || name.length() == 0) {
      return "";
    }
    int i = 1;
    while (isOKImpl(result, true).size() > 0) {
      result = name + i;
      i++;
    }
    return result;
  }

  public Project getProject() {
    return myContext.getProject();
  }
}


text:
using nlohmann::json;

namespace rg
{
Volunteer::Volunteer(const nlohmann::json& v) :
    id(v.at("id")),
    firstName(v.at("firstName")),
    lastName(v.at("lastName")),
    phoneHome(v.at("phoneHome")),
    phoneMobile(v.at("phoneMobile")),
    email(v.at("email"))
{
}

Volunteer& Volunteer::operator=(const Volunteer& v)
{
    id          = v.id;
    firstName   = v.firstName;
    lastName    = v.lastName;
    phoneHome   = v.phoneHome;
    phoneMobile = v.phoneMobile;
    email       = v.email;
    return *this;
}

Volunteer& Volunteer::operator=(const Volunteer&& v)
{
    id          = std::move(v.id);
    firstName   = std::move(v.firstName);
    lastName    = std::move(v.lastName);
    phoneHome   = std::move(v.phoneHome);
    phoneMobile = std::move(v.phoneMobile);
    email       = std::move(v.email);
    return *this;
}

Volunteer& Volunteer::operator=(const nlohmann::json& v)
{
    id          = v.at("id");
    firstName   = v.at("firstName");
    lastName    = v.at("lastName");
    phoneHome   = v.at("phoneHome");
    phoneMobile = v.at("phoneMobile");
    email       = v.at("email");
    return *this;
}

bool Volunteer::operator==(const Volunteer& source) const
{
    return eq(source);
}

bool Volunteer::operator!=(const Volunteer& source) const
{
    return !eq(source);
}

void Volunteer::set_name(const std::string& name)
{
    auto pos = name.find(" ");
    if (pos == std::string::npos)
    {
        // No space in the name; make it all last name
        lastName = name;
    }
    else
    {
        // Before the first space is the first name, everything after is the
        // last name.
        // This is perhaps a naive approach and may not survive first contact
        // with "the enemy" (end users!).
        auto f    = name.substr(0, pos);
        auto l    = name.substr(pos + 1);
        firstName = f;
        lastName  = l;
    }
}

bool Volunteer::eq(const Volunteer& source) const
{
    return firstName == source.firstName && lastName == source.lastName
           && phoneHome == source.phoneHome && phoneMobile == source.phoneMobile
           && email == source.email;
}

}    // namespace rg


text:
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Skin_surface_traits_3<K>                     Traits;
typedef CGAL::Skin_surface_3<Traits>                        Skin_surface_3;
typedef Skin_surface_3::FT                                  FT;
typedef Skin_surface_3::Weighted_point                      Weighted_point;
typedef Weighted_point::Point                               Bare_point;
typedef CGAL::Polyhedron_3<K>                               Polyhedron;

typedef CGAL::Skin_surface_polyhedral_items_3<Skin_surface_3> Poly_items_skin;
typedef CGAL::Polyhedron_3<K,Poly_items_skin>                 Polyhedron_skin;

#include <fstream>

Skin_surface_3 create_skin_surface(std::string &filename, double shrink) {
  std::list<Weighted_point> l;
  std::ifstream in(filename.c_str());
  assert(in.is_open());
  Weighted_point wp;
  while (in >> wp) l.push_front(wp);

  return Skin_surface_3(l.begin(), l.end(), shrink);
}

template < class Skin_surface_3, class Polyhedron>
void construct_and_subdivide_mesh(Skin_surface_3 &skin_surface,
				  Polyhedron &polyhedron)
{
  CGAL::mesh_skin_surface_3(skin_surface, polyhedron);
  assert(polyhedron.is_valid() && polyhedron.is_closed());

  CGAL::subdivide_skin_surface_mesh_3(skin_surface, polyhedron);
  assert(polyhedron.is_valid() && polyhedron.is_closed());
}

class Test_file {
public:
  Test_file(double shrink) : s(shrink) {
  }
  void operator()(std::string &filename) {
    std::cout << filename << std::endl;

    Skin_surface_3 skin_surface = create_skin_surface(filename, .5);

    Polyhedron p;
    //construct_and_subdivide_mesh(skin_surface, p);
    //p.clear();

    Polyhedron_skin p_skin;
    construct_and_subdivide_mesh(skin_surface, p_skin);
    p_skin.clear();
  }
private:
  double s;
};

int main(int, char **) {

  std::vector<std::string> filenames;
  filenames.push_back("data/caffeine.cin");
  filenames.push_back("data/ball.cin");
  filenames.push_back("data/degenerate.cin");
  filenames.push_back("data/test1.cin");
  filenames.push_back("data/test2.cin");
  filenames.push_back("data/test3.cin");
  filenames.push_back("data/test4.cin");
  filenames.push_back("data/test5.cin");
  filenames.push_back("data/test6.cin");
  filenames.push_back("data/test7.cin");
  filenames.push_back("data/test8.cin");
  filenames.push_back("data/test9.cin");
  filenames.push_back("data/test10.cin");
  filenames.push_back("data/test11.cin");

  std::for_each(filenames.begin(), filenames.end(), Test_file(.5));
  std::for_each(filenames.begin(), filenames.end(), Test_file(.25));

  return 0;
}


text:
var util = require('util');
var events = require('events').EventEmitter;
var options = require('./libs/options');
var async = require('async');
var request = require('request');
var fs = require('fs');
var findup = require('findup-sync');
var multimeter = require('multimeter');
var multi = multimeter(process);
var EOL = require('os').EOL;

var package = JSON.parse(fs.readFileSync(findup('package.json')));

var sslscan = function(opts,cb) {
    if (false === (this instanceof sslscan)) {
        return new sslscan(opts,cb);
    }

    var self = this;

    this.lastMessage = '';
    this.paused = false;
    this.progress = 0;
    this.progressTimer = null;
    this.activeAssessments = 0
    this.maxAssessments = -1
    this.retryCount = 0;
    this.command = '';
    this.analyseUrl = '';
    this.bars = {};
    this.cmdLine = true;
    this.options = opts;
    this.currentEndPointId = -1;
    this.previousProgress;

    if (!opts.ips) {
        // Called from a js script, reparse options
        options.parse(opts,function(err,opts) {
            self.cmdLine = false;
            self.options = opts;
            self.init();
            events.call(self);
            if (cb) cb(self);
        });
    } else {
        this.init();
        events.call(this);
    }
};

util.inherits(sslscan, events);

sslscan.prototype.shellOutput = function(msg) {
    process.stdout.write(msg);
};

sslscan.prototype.getOptions = function() {
    return this.options;
};

sslscan.prototype.init = function() {

    this.command = "analyze?host=" + this.options.host + "&all=done"

    if (this.options.fromCache == 'on') {
        this.command+="&fromCache=on"
        if (this.options.globalMaxAge != 0) {
            this.command+="&maxAge=" + this.options.globalMaxAge;
        }
    } else if (this.options.startNew == 'on') {
        this.command+="&startNew=on"
    }

    if (this.options.globalIgnoreMismatch == 'on') {
        this.command+="&ignoreMismatch=on"
    }

    this.analyseUrl = this.options.apiLocation+'/'+this.command;

    var logLevel = null;
    if (this.options.debug) logLevel = 'debug';
    this.log = require('./libs/logger').log(logLevel);

};

sslscan.prototype.loopAnalyse = function(cb) {

    var self = this;
    this.retryCount++;

    var reqId = this.retryCount;

    if (reqId>1) {
        // startNew only for the first call
        this.analyseUrl = this.analyseUrl.replace(/&startNew=on/,'');
    } else {
        self.emit('start');
    }

    this.log.debug('#'+reqId,"Request ",this.analyseUrl);

    var options = {
        url: this.analyseUrl,
        headers: {
            'User-Agent': package.name+' v'+package.version
        }
    };

    request(options,function(err, response, body) {

        if (err) {
            if (self.retryCount > 5) {
                self.lastMessage = "Too many HTTP requests failed";
            } else {
                self.lastMessage = "HTTP request failed: "+err;
                self.retryCount++;
            }
            self.emit('error',self.lastMessage);
            return cb(err);
        }

        self.log.debug('#'+this.reqId,'Response status: ',response.statusCode);

        var message = response.headers['x-message'];
        if (message) {
            self.log.debug('x-message',response.headers['x-message']);
        }

        // Adjust maximum concurrent requests.

        var headerValue = parseInt(response.headers['x-max-assessments']);

        if (headerValue <= 0) {
            // https://github.com/ssllabs/ssllabs-scan/issues/56
            self.lastMessage = 'Your IP has been blacklisted !';
            self.emit('error',self.lastMessage);
            return cb(msg);
        }

        if (headerValue > 1) {
            if (self.maxAssessments != headerValue) {
                self.maxAssessments = headerValue;
                self.log.debug("Server set max concurrent assessments to", headerValue);
            }
        }

        var status = response.statusCode;

        if (status == 429) {

            //429 - client request rate too high

            self.lastMessage = 'Sleeping for 30 seconds after a ',status,' response status';
            self.emit('sleep',self.lastMessage);

            return setTimeout(function() {
                self.loopAnalyse(cb);
            },30*1000);

        } else if (status == 503) {

            // 503 - the service is not available (e.g., down for maintenance)
            self.lastMessage = 'SSLLabs service is not available';
            self.emit('error',self.lastMessage);
            return cb(self.lastMessage);

        } else if (status == 529) {

            // 529 - the service is overloaded
            self.lastMessage = 'SSLLabs service overloaded';
            self.emit('error',self.lastMessage);
            return cb(self.lastMessage);

        } else if (status != 200 && status != 400) {

            self.lastMessage = 'Unexpected response status code '+status;
            self.emit('error',self.lastMessage);
            return cb(self.lastMessage);
        }

        // Everything fine, let's see if job is done

        try {
            var result = JSON.parse(response.body);
            if (result.status === "READY") {
                // assessments are available(s) = job done
                return cb(null,result);
            }

            self.log.debug(JSON.stringify(result,null,4));

            if (result.endpoints && result.endpoints.length) {
                if (self.currentEndPointId == -1) {
                    var endpoints = [];
                    for (var i = 0; i<result.endpoints.length;i++) {
                        endpoints.push(result.endpoints[i].serverName);
                    }
                    self.emit('endpoints',endpoints);
                    self.currentEndPointId = 0;
                } else {
                    for (var i = 0; i<result.endpoints.length;i++) {
                        var endpoint = result.endpoints[i];
                        if (i == self.currentEndPointId && endpoint.statusMessage == 'Ready') {
                            self.emit('progress',{
                                message:endpoint.serverName+': 100% done',
                                endpointId:self.currentEndPointId,
                                endpoint:endpoint
                            })
                            self.currentEndPointId++;
                        }
                    }

                    var currentEndPoint = result.endpoints[self.currentEndPointId];
                    if (currentEndPoint) {
                        var p = currentEndPoint.progress;
                        if (p == -1) p = 0;
                        self.emit('progress',{
                            message:currentEndPoint.serverName+': '+p+"% "+currentEndPoint.statusDetailsMessage,
                            endpointId:self.currentEndPointId,
                            endpoint:result.endpoints[currentEndPoint]
                        });
                    }
                }
            }

        } catch(e) {
            // json badly formated
            return cb(e);
        }

        // In progress ...

        return setTimeout(function() {
            self.loopAnalyse(cb);
        },5*1000);

    }.bind({reqId:reqId}));

};

sslscan.prototype.run = function() {

    this.shellOutput("SSLLabs assessments of "+this.options.host+EOL);

    var self = this;

    this.init();

    this.loopAnalyse(function(err,result) {
        if (err) {
            self.shellOutput('Error',err);
            return;
        }
        self.emit('end',result);
        return;
    });
};

module.exports = sslscan;


text:
package com.emc.storageos.model.network;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;

/**
 * Contains a list of the endpoints discovered by the NetworkSystem. An endpoint
 * represents either a connected host port or storage port. Some ISL link ports may
 * also be included by the NetworkSystem.
 *
 */
@XmlRootElement(name = "fc_endpoints")
public class FCEndpoints {
    private List<FCEndpointRestRep> connections;

    public FCEndpoints() {
    }

    public FCEndpoints(List<FCEndpointRestRep> connections) {
        this.connections = connections;
    }

    /**
     * List of FC (Fibre Channel) endpoints discovered by a network system.
     *
     */
    @XmlElement(name = "fc_endpoint")
    public List<FCEndpointRestRep> getConnections() {
        if (connections == null) {
            connections = new ArrayList<FCEndpointRestRep>();
        }
        return connections;
    }

    public void setConnections(List<FCEndpointRestRep> connections) {
        this.connections = connections;
    }
}


text:
New Customer

            <form name="createCustomerForm">
              <fieldset>

                            First Name

                                <input type="text" data-ng-model="customerCtrl.firstName" id="firstname" class="form-control">

                            Surname

                                <input type="text" data-ng-model="customerCtrl.surname" id="surname" class="form-control" required>

                            Suburb

                                <input type="text" data-ng-model="customerCtrl.suburb" id="suburb" class="form-control">

                            Country

                                <input type="text" data-ng-model="customerCtrl.country" id="country" class="form-control">

                            Phone

                                <input type="text" data-ng-model="customerCtrl.phone" id="phone" class="form-control">

                            Email

                                <input type="text" data-ng-model="customerCtrl.email" id="email" class="form-control">

                            Referred

                                <input type="checkbox" data-ng-model="customerCtrl.referred" id="referred" class="form-control checkbox-left">

                            Channel

                                <input type="text" data-ng-model="customerCtrl.channel" id="channel" class="form-control">

                            Industry

                                <input type="text" data-ng-model="customerCtrl.industry" id="industry" class="form-control">

            </fieldset>
        </form>

        <button class="btn btn-success btn-lg" ng-click="customerCtrl.create(); ok()" ng-disabled="createCustomerForm.$invalid">Save & Close</button>
        <button class="btn btn-warning btn-lg" ng-click="cancel()">Cancel</button>


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

require_once(dirname(__FILE__) . '/../../config.php');
require_once($CFG->dirroot.'/mod/lesson/locallib.php');
require_once($CFG->dirroot.'/mod/lesson/view_form.php');
require_once($CFG->libdir . '/completionlib.php');
require_once($CFG->libdir . '/grade/constants.php');

$id      = required_param('id', PARAM_INT);             // Course Module ID
$pageid  = optional_param('pageid', null, PARAM_INT);   // Lesson Page ID
$edit    = optional_param('edit', -1, PARAM_BOOL);
$userpassword = optional_param('userpassword','',PARAM_RAW);
$backtocourse = optional_param('backtocourse', false, PARAM_RAW);

$cm = get_coursemodule_from_id('lesson', $id, 0, false, MUST_EXIST);
$course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
$lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST));

require_login($course, false, $cm);

if ($backtocourse) {
    redirect(new moodle_url('/course/view.php', array('id'=>$course->id)));
}

// Apply overrides.
$lesson->update_effective_access($USER->id);

// Mark as viewed
$completion = new completion_info($course);
$completion->set_module_viewed($cm);

$url = new moodle_url('/mod/lesson/view.php', array('id'=>$id));
if ($pageid !== null) {
    $url->param('pageid', $pageid);
}
$PAGE->set_url($url);

$context = context_module::instance($cm->id);
$canmanage = has_capability('mod/lesson:manage', $context);

$lessonoutput = $PAGE->get_renderer('mod_lesson');

$reviewmode = false;
$userhasgrade = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$USER->id));
if ($userhasgrade && !$lesson->retake) {
    $reviewmode = true;
}

/// Check these for students only TODO: Find a better method for doing this!
///     Check lesson availability
///     Check for password
///     Check dependencies
if (!$canmanage) {
    if (!$lesson->is_accessible()) {  // Deadline restrictions
        echo $lessonoutput->header($lesson, $cm, '', false, null, get_string('notavailable'));
        if ($lesson->deadline != 0 && time() > $lesson->deadline) {
            echo $lessonoutput->lesson_inaccessible(get_string('lessonclosed', 'lesson', userdate($lesson->deadline)));
        } else {
            echo $lessonoutput->lesson_inaccessible(get_string('lessonopen', 'lesson', userdate($lesson->available)));
        }
        echo $lessonoutput->footer();
        exit();
    } else if ($lesson->usepassword && empty($USER->lessonloggedin[$lesson->id])) { // Password protected lesson code
        $correctpass = false;
        if (!empty($userpassword) && (($lesson->password == md5(trim($userpassword))) || ($lesson->password == trim($userpassword)))) {
            require_sesskey();
            // with or without md5 for backward compatibility (MDL-11090)
            $correctpass = true;
            $USER->lessonloggedin[$lesson->id] = true;

        } else if (isset($lesson->extrapasswords)) {

            // Group overrides may have additional passwords.
            foreach ($lesson->extrapasswords as $password) {
                if (strcmp($password, md5(trim($userpassword))) === 0 || strcmp($password, trim($userpassword)) === 0) {
                    require_sesskey();
                    $correctpass = true;
                    $USER->lessonloggedin[$lesson->id] = true;
                }
            }
        }
        if (!$correctpass) {
            echo $lessonoutput->header($lesson, $cm, '', false, null, get_string('passwordprotectedlesson', 'lesson', format_string($lesson->name)));
            echo $lessonoutput->login_prompt($lesson, $userpassword !== '');
            echo $lessonoutput->footer();
            exit();
        }
    } else if ($lesson->dependency) { // check for dependencies
        if ($dependentlesson = $DB->get_record('lesson', array('id' => $lesson->dependency))) {
            // lesson exists, so we can proceed
            $conditions = unserialize($lesson->conditions);
            // assume false for all
            $errors = array();

            // check for the timespent condition
            if ($conditions->timespent) {
                $timespent = false;
                if ($attempttimes = $DB->get_records('lesson_timer', array("userid"=>$USER->id, "lessonid"=>$dependentlesson->id))) {
                    // go through all the times and test to see if any of them satisfy the condition
                    foreach($attempttimes as $attempttime) {
                        $duration = $attempttime->lessontime - $attempttime->starttime;
                        if ($conditions->timespent < $duration/60) {
                            $timespent = true;
                        }
                    }
                }
                if (!$timespent) {
                    $errors[] = get_string('timespenterror', 'lesson', $conditions->timespent);
                }
            }

            // check for the gradebetterthan condition
            if($conditions->gradebetterthan) {
                $gradebetterthan = false;
                if ($studentgrades = $DB->get_records('lesson_grades', array("userid"=>$USER->id, "lessonid"=>$dependentlesson->id))) {
                    // go through all the grades and test to see if any of them satisfy the condition
                    foreach($studentgrades as $studentgrade) {
                        if ($studentgrade->grade >= $conditions->gradebetterthan) {
                            $gradebetterthan = true;
                        }
                    }
                }
                if (!$gradebetterthan) {
                    $errors[] = get_string('gradebetterthanerror', 'lesson', $conditions->gradebetterthan);
                }
            }

            // check for the completed condition
            if ($conditions->completed) {
                if (!$DB->count_records('lesson_grades', array('userid'=>$USER->id, 'lessonid'=>$dependentlesson->id))) {
                    $errors[] = get_string('completederror', 'lesson');
                }
            }

            if (!empty($errors)) {  // print out the errors if any
                echo $lessonoutput->header($lesson, $cm, '', false, null, get_string('completethefollowingconditions', 'lesson', format_string($lesson->name)));
                echo $lessonoutput->dependancy_errors($dependentlesson, $errors);
                echo $lessonoutput->footer();
                exit();
            }
        }
    }
}

    // this is called if a student leaves during a lesson
if ($pageid == LESSON_UNSEENBRANCHPAGE) {
    $pageid = lesson_unseen_question_jump($lesson, $USER->id, $pageid);
}

// display individual pages and their sets of answers
// if pageid is EOL then the end of the lesson has been reached
// for flow, changed to simple echo for flow styles, michaelp, moved lesson name and page title down
$attemptflag = false;
if (empty($pageid)) {
    // make sure there are pages to view
    if (!$DB->get_field('lesson_pages', 'id', array('lessonid' => $lesson->id, 'prevpageid' => 0))) {
        if (!$canmanage) {
            $lesson->add_message(get_string('lessonnotready2', 'lesson')); // a nice message to the student
        } else {
            if (!$DB->count_records('lesson_pages', array('lessonid'=>$lesson->id))) {
                redirect("$CFG->wwwroot/mod/lesson/edit.php?id=$cm->id"); // no pages - redirect to add pages
            } else {
                $lesson->add_message(get_string('lessonpagelinkingbroken', 'lesson'));  // ok, bad mojo
            }
        }
    }

    // if no pageid given see if the lesson has been started
    $retries = $DB->count_records('lesson_grades', array("lessonid" => $lesson->id, "userid" => $USER->id));
    if ($retries > 0) {
        $attemptflag = true;
    }

    if (isset($USER->modattempts[$lesson->id])) {
        unset($USER->modattempts[$lesson->id]);  // if no pageid, then student is NOT reviewing
    }

    // If there are any questions that have been answered correctly (or not) in this attempt.
    $allattempts = $lesson->get_attempts($retries);
    if (!empty($allattempts)) {
        $attempt = end($allattempts);
        $attemptpage = $lesson->load_page($attempt->pageid);
        $jumpto = $DB->get_field('lesson_answers', 'jumpto', array('id' => $attempt->answerid));
        // convert the jumpto to a proper page id
        if ($jumpto == 0) {
            // Check if a question has been incorrectly answered AND no more attempts at it are left.
            $nattempts = $lesson->get_attempts($attempt->retry, false, $attempt->pageid, $USER->id);
            if (count($nattempts) >= $lesson->maxattempts) {
                $lastpageseen = $lesson->get_next_page($attemptpage->nextpageid);
            } else {
                $lastpageseen = $attempt->pageid;
            }
        } elseif ($jumpto == LESSON_NEXTPAGE) {
            $lastpageseen = $lesson->get_next_page($attemptpage->nextpageid);
        } else if ($jumpto == LESSON_CLUSTERJUMP) {
            $lastpageseen = $lesson->cluster_jump($attempt->pageid);
        } else {
            $lastpageseen = $jumpto;
        }
    }

    if ($branchtables = $DB->get_records('lesson_branch', array("lessonid" => $lesson->id, "userid" => $USER->id, "retry" => $retries), 'timeseen DESC')) {
        // in here, user has viewed a branch table
        $lastbranchtable = current($branchtables);
        if (count($allattempts) > 0) {
            if ($lastbranchtable->timeseen > $attempt->timeseen) {
                // This branch table was viewed more recently than the question page.
                if (!empty($lastbranchtable->nextpageid)) {
                    $lastpageseen = $lastbranchtable->nextpageid;
                } else {
                    // Next page ID did not exist prior to MDL-34006.
                    $lastpageseen = $lastbranchtable->pageid;
                }
            }
        } else {
            // Has not answered any questions but has viewed a branch table.
            if (!empty($lastbranchtable->nextpageid)) {
                $lastpageseen = $lastbranchtable->nextpageid;
            } else {
                // Next page ID did not exist prior to MDL-34006.
                $lastpageseen = $lastbranchtable->pageid;
            }
        }
    }
    // Check to see if end of lesson was reached.
    if ((isset($lastpageseen) && ($lastpageseen != LESSON_EOL))) {
        if (($DB->count_records('lesson_attempts', array('lessonid' => $lesson->id, 'userid' => $USER->id, 'retry' => $retries)) > 0)
                || $DB->count_records('lesson_branch', array("lessonid" => $lesson->id, "userid" => $USER->id, "retry" => $retries)) > 0) {

            echo $lessonoutput->header($lesson, $cm, '', false, null, get_string('leftduringtimedsession', 'lesson'));
            if ($lesson->timelimit) {
                if ($lesson->retake) {
                    $continuelink = new single_button(new moodle_url('/mod/lesson/view.php',
                            array('id' => $cm->id, 'pageid' => $lesson->firstpageid, 'startlastseen' => 'no')),
                            get_string('continue', 'lesson'), 'get');

                    echo html_writer::div($lessonoutput->message(get_string('leftduringtimed', 'lesson'), $continuelink),
                            'center leftduring');

                } else {
                    $courselink = new single_button(new moodle_url('/course/view.php',
                            array('id' => $PAGE->course->id)), get_string('returntocourse', 'lesson'), 'get');

                    echo html_writer::div($lessonoutput->message(get_string('leftduringtimednoretake', 'lesson'), $courselink),
                            'center leftduring');
                }
            } else {
                echo $lessonoutput->continue_links($lesson, $lastpageseen);
            }
            echo $lessonoutput->footer();
            exit();
        }
    }

    if ($attemptflag) {
        if (!$lesson->retake) {
            echo $lessonoutput->header($lesson, $cm, 'view', '', null, get_string("noretake", "lesson"));
            $courselink = new single_button(new moodle_url('/course/view.php', array('id'=>$PAGE->course->id)), get_string('returntocourse', 'lesson'), 'get');
            echo $lessonoutput->message(get_string("noretake", "lesson"), $courselink);
            echo $lessonoutput->footer();
            exit();
        }
    }
    // start at the first page
    if (!$pageid = $DB->get_field('lesson_pages', 'id', array('lessonid' => $lesson->id, 'prevpageid' => 0))) {
        echo $lessonoutput->header($lesson, $cm, 'view', '', null);
        // Lesson currently has no content. A message for display has been prepared and will be displayed by the header method
        // of the lesson renderer.
        echo $lessonoutput->footer();
        exit();
    }
    /// This is the code for starting a timed test
    if(!isset($USER->startlesson[$lesson->id]) && !$canmanage) {
        $lesson->start_timer();
    }
}

$currenttab = 'view';
$extraeditbuttons = false;
$lessonpageid = null;
$timer = null;

if ($pageid != LESSON_EOL) {
    /// This is the code updates the lessontime for a timed test
    $startlastseen = optional_param('startlastseen', '', PARAM_ALPHA);

    $page = $lesson->load_page($pageid);
    // Check if the page is of a special type and if so take any nessecary action
    $newpageid = $page->callback_on_view($canmanage);
    if (is_numeric($newpageid)) {
        $page = $lesson->load_page($newpageid);
    }

    // Trigger module viewed event.
    $event = \mod_lesson\event\course_module_viewed::create(array(
        'objectid' => $lesson->id,
        'context' => $context
    ));
    $event->add_record_snapshot('course_modules', $cm);
    $event->add_record_snapshot('course', $course);
    $event->trigger();

    // This is where several messages (usually warnings) are displayed
    // all of this is displayed above the actual page

    // check to see if the user can see the left menu
    if (!$canmanage) {
        $lesson->displayleft = lesson_displayleftif($lesson);

        $continue = ($startlastseen !== '');
        $restart  = ($continue && $startlastseen == 'yes');
        $timer = $lesson->update_timer($continue, $restart);

        if ($lesson->timelimit) {
            $timeleft = $timer->starttime + $lesson->timelimit - time();
            if ($timeleft <= 0) {
                // Out of time
                $lesson->add_message(get_string('eolstudentoutoftime', 'lesson'));
                redirect(new moodle_url('/mod/lesson/view.php', array('id'=>$cm->id,'pageid'=>LESSON_EOL, 'outoftime'=>'normal')));
                die; // Shouldn't be reached, but make sure
            } else if ($timeleft < 60) {
                // One minute warning
                $lesson->add_message(get_string('studentoneminwarning', 'lesson'));
            }
        }

        if ($page->qtype == LESSON_PAGE_BRANCHTABLE && $lesson->minquestions) {
            // tell student how many questions they have seen, how many are required and their grade
            $ntries = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$USER->id));
            $gradeinfo = lesson_grade($lesson, $ntries);
            if ($gradeinfo->attempts) {
                if ($gradeinfo->nquestions < $lesson->minquestions) {
                    $a = new stdClass;
                    $a->nquestions   = $gradeinfo->nquestions;
                    $a->minquestions = $lesson->minquestions;
                    $lesson->add_message(get_string('numberofpagesviewednotice', 'lesson', $a));
                }

                if (!$reviewmode && !$lesson->retake){
                    $lesson->add_message(get_string("numberofcorrectanswers", "lesson", $gradeinfo->earned), 'notify');
                    if ($lesson->grade != GRADE_TYPE_NONE) {
                        $a = new stdClass;
                        $a->grade = number_format($gradeinfo->grade * $lesson->grade / 100, 1);
                        $a->total = $lesson->grade;
                        $lesson->add_message(get_string('yourcurrentgradeisoutof', 'lesson', $a), 'notify');
                    }
                }
            }
        }
    } else {
        $timer = null;
        if ($lesson->timelimit) {
            $lesson->add_message(get_string('teachertimerwarning', 'lesson'));
        }
        if (lesson_display_teacher_warning($lesson)) {
            // This is the warning msg for teachers to inform them that cluster
            // and unseen does not work while logged in as a teacher
            $warningvars = new stdClass();
            $warningvars->cluster = get_string('clusterjump', 'lesson');
            $warningvars->unseen = get_string('unseenpageinbranch', 'lesson');
            $lesson->add_message(get_string('teacherjumpwarning', 'lesson', $warningvars));
        }
    }

    $PAGE->set_subpage($page->id);
    $currenttab = 'view';
    $extraeditbuttons = true;
    $lessonpageid = $page->id;
    $extrapagetitle = $page->title;

    if (($edit != -1) && $PAGE->user_allowed_editing()) {
        $USER->editing = $edit;
    }

    if (is_array($page->answers) && count($page->answers)>0) {
        // this is for modattempts option.  Find the users previous answer to this page,
        //   and then display it below in answer processing
        if (isset($USER->modattempts[$lesson->id])) {
            $retries = $DB->count_records('lesson_grades', array("lessonid"=>$lesson->id, "userid"=>$USER->id));
            if (!$attempts = $lesson->get_attempts($retries-1, false, $page->id)) {
                print_error('cannotfindpreattempt', 'lesson');
            }
            $attempt = end($attempts);
            $USER->modattempts[$lesson->id] = $attempt;
        } else {
            $attempt = false;
        }
        $lessoncontent = $lessonoutput->display_page($lesson, $page, $attempt);
    } else {
        $data = new stdClass;
        $data->id = $PAGE->cm->id;
        $data->pageid = $page->id;
        $data->newpageid = $lesson->get_next_page($page->nextpageid);

        $customdata = array(
            'title'     => $page->title,
            'contents'  => $page->get_contents()
        );
        $mform = new lesson_page_without_answers($CFG->wwwroot.'/mod/lesson/continue.php', $customdata);
        $mform->set_data($data);
        ob_start();
        $mform->display();
        $lessoncontent = ob_get_contents();
        ob_end_clean();
    }

    lesson_add_fake_blocks($PAGE, $cm, $lesson, $timer);
    echo $lessonoutput->header($lesson, $cm, $currenttab, $extraeditbuttons, $lessonpageid, $extrapagetitle);
    if ($attemptflag) {
        // We are using level 3 header because attempt heading is a sub-heading of lesson title (MDL-30911).
        echo $OUTPUT->heading(get_string('attempt', 'lesson', $retries), 3);
    }
    /// This calculates and prints the ongoing score
    if ($lesson->ongoing && !empty($pageid) && !$reviewmode) {
        echo $lessonoutput->ongoing_score($lesson);
    }
    if ($lesson->displayleft) {
        echo '';
    }
    echo $lessoncontent;
    echo $lessonoutput->progress_bar($lesson);
    echo $lessonoutput->footer();

} else {

    $lessoncontent = '';
    // end of lesson reached work out grade
    // Used to check to see if the student ran out of time
    $outoftime = optional_param('outoftime', '', PARAM_ALPHA);

    $ntries = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$USER->id));
    if (isset($USER->modattempts[$lesson->id])) {
        $ntries--;  // need to look at the old attempts :)
    }
    $gradelesson = true;
    $gradeinfo = lesson_grade($lesson, $ntries);
    if ($lesson->custom && !$canmanage) {
        // Before we calculate the custom score make sure they answered the minimum
        // number of questions. We only need to do this for custom scoring as we can
        // not get the miniumum score the user should achieve. If we are not using
        // custom scoring (so all questions are valued as 1) then we simply check if
        // they answered more than the minimum questions, if not, we mark it out of the
        // number specified in the minimum questions setting - which is done in lesson_grade().
        // Get the number of answers given.
        if ($gradeinfo->nquestions < $lesson->minquestions) {
            $gradelesson = false;
            $a = new stdClass;
            $a->nquestions = $gradeinfo->nquestions;
            $a->minquestions = $lesson->minquestions;
            $lessoncontent .= $OUTPUT->box_start('generalbox boxaligncenter');
            $lesson->add_message(get_string('numberofpagesviewednotice', 'lesson', $a));
        }
    }
    if ($gradelesson) {
        // We are using level 3 header because the page title is a sub-heading of lesson title (MDL-30911).
        $lessoncontent .= $OUTPUT->heading(get_string("congratulations", "lesson"), 3);
        $lessoncontent .= $OUTPUT->box_start('generalbox boxaligncenter');
    }
    if (!$canmanage) {
        if ($gradelesson) {
            // Store this now before any modifications to pages viewed.
            $progressbar = $lessonoutput->progress_bar($lesson);
            // Update the clock / get time information for this user.
            $lesson->stop_timer();

            // Update completion state.
            $completion = new completion_info($course);
            if ($completion->is_enabled($cm) && $lesson->completionendreached) {
                $completion->update_state($cm, COMPLETION_COMPLETE);
            }

            if ($lesson->completiontimespent > 0) {
                $duration = $DB->get_field_sql(
                    "SELECT SUM(lessontime - starttime)
                                   FROM {lesson_timer}
                                  WHERE lessonid = :lessonid
                                    AND userid = :userid",
                    array('userid' => $USER->id, 'lessonid' => $lesson->id));
                if (!$duration) {
                    $duration = 0;
                }

                // If student has not spend enough time in the lesson, display a message.
                if ($duration < $lesson->completiontimespent) {
                    $a = new stdClass;
                    $a->timespent = format_time($duration);
                    $a->timerequired = format_time($lesson->completiontimespent);
                    $lessoncontent .= $lessonoutput->paragraph(get_string("notenoughtimespent", "lesson", $a), 'center');
                }
            }

            if ($gradeinfo->attempts) {
                if (!$lesson->custom) {
                    $lessoncontent .= $lessonoutput->paragraph(get_string("numberofpagesviewed", "lesson", $gradeinfo->nquestions), 'center');
                    if ($lesson->minquestions) {
                        if ($gradeinfo->nquestions < $lesson->minquestions) {
                            // print a warning and set nviewed to minquestions
                            $lessoncontent .= $lessonoutput->paragraph(get_string("youshouldview", "lesson", $lesson->minquestions), 'center');
                        }
                    }
                    $lessoncontent .= $lessonoutput->paragraph(get_string("numberofcorrectanswers", "lesson", $gradeinfo->earned), 'center');
                }
                $a = new stdClass;
                $a->score = $gradeinfo->earned;
                $a->grade = $gradeinfo->total;
                if ($gradeinfo->nmanual) {
                    $a->tempmaxgrade = $gradeinfo->total - $gradeinfo->manualpoints;
                    $a->essayquestions = $gradeinfo->nmanual;
                    $lessoncontent .= $OUTPUT->box(get_string("displayscorewithessays", "lesson", $a), 'center');
                } else {
                    $lessoncontent .= $OUTPUT->box(get_string("displayscorewithoutessays", "lesson", $a), 'center');
                }
                if ($lesson->grade != GRADE_TYPE_NONE) {
                    $a = new stdClass;
                    $a->grade = number_format($gradeinfo->grade * $lesson->grade / 100, 1);
                    $a->total = $lesson->grade;
                    $lessoncontent .= $lessonoutput->paragraph(get_string("yourcurrentgradeisoutof", "lesson", $a), 'center');
                }

                $grade = new stdClass();
                $grade->lessonid = $lesson->id;
                $grade->userid = $USER->id;
                $grade->grade = $gradeinfo->grade;
                $grade->completed = time();
                if (isset($USER->modattempts[$lesson->id])) { // If reviewing, make sure update old grade record.
                    if (!$grades = $DB->get_records("lesson_grades",
                        array("lessonid" => $lesson->id, "userid" => $USER->id), "completed DESC", '*', 0, 1)) {
                        print_error('cannotfindgrade', 'lesson');
                    }
                    $oldgrade = array_shift($grades);
                    $grade->id = $oldgrade->id;
                    $DB->update_record("lesson_grades", $grade);
                } else {
                    $newgradeid = $DB->insert_record("lesson_grades", $grade);
                }
            } else {
                if ($lesson->timelimit) {
                    if ($outoftime == 'normal') {
                        $grade = new stdClass();
                        $grade->lessonid = $lesson->id;
                        $grade->userid = $USER->id;
                        $grade->grade = 0;
                        $grade->completed = time();
                        $newgradeid = $DB->insert_record("lesson_grades", $grade);
                        $lessoncontent .= $lessonoutput->paragraph(get_string("eolstudentoutoftimenoanswers", "lesson"));
                    }
                } else {
                    $lessoncontent .= $lessonoutput->paragraph(get_string("welldone", "lesson"));
                }
            }

            // update central gradebook
            lesson_update_grades($lesson, $USER->id);
            $lessoncontent .= $progressbar;
        }
    } else {
        // display for teacher
        if ($lesson->grade != GRADE_TYPE_NONE) {
            $lessoncontent .= $lessonoutput->paragraph(get_string("displayofgrade", "lesson"), 'center');
        }
    }
    $lessoncontent .= $OUTPUT->box_end(); //End of Lesson button to Continue.

    if ($lesson->modattempts && !$canmanage) {
        // make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time
        // look at the attempt records to find the first QUESTION page that the user answered, then use that page id
        // to pass to view again.  This is slick cause it wont call the empty($pageid) code
        // $ntries is decremented above
        if (!$attempts = $lesson->get_attempts($ntries)) {
            $attempts = array();
            $url = new moodle_url('/mod/lesson/view.php', array('id'=>$PAGE->cm->id));
        } else {
            $firstattempt = current($attempts);
            $pageid = $firstattempt->pageid;
            // IF the student wishes to review, need to know the last question page that the student answered.  This will help to make
            // sure that the student can leave the lesson via pushing the continue button.
            $lastattempt = end($attempts);
            $USER->modattempts[$lesson->id] = $lastattempt->pageid;

            $url = new moodle_url('/mod/lesson/view.php', array('id'=>$PAGE->cm->id, 'pageid'=>$pageid));
        }
        $lessoncontent .= html_writer::link($url, get_string('reviewlesson', 'lesson'), array('class' => 'centerpadded lessonbutton standardbutton'));
    } elseif ($lesson->modattempts && $canmanage) {
        $lessoncontent .= $lessonoutput->paragraph(get_string("modattemptsnoteacher", "lesson"), 'centerpadded');
    }

    if ($lesson->activitylink) {
        $lessoncontent .= $lesson->link_for_activitylink();
    }

    $url = new moodle_url('/course/view.php', array('id'=>$course->id));
    $lessoncontent .= html_writer::link($url, get_string('returnto', 'lesson', format_string($course->fullname, true)), array('class'=>'centerpadded lessonbutton standardbutton'));

    if (has_capability('gradereport/user:view', context_course::instance($course->id))
            && $course->showgrades && $lesson->grade != 0 && !$lesson->practice) {
        $url = new moodle_url('/grade/index.php', array('id' => $course->id));
        $lessoncontent .= html_writer::link($url, get_string('viewgrades', 'lesson'),
            array('class' => 'centerpadded lessonbutton standardbutton'));
    }

    lesson_add_fake_blocks($PAGE, $cm, $lesson, $timer);
    echo $lessonoutput->header($lesson, $cm, $currenttab, $extraeditbuttons, $lessonpageid, get_string("congratulations", "lesson"));
    echo $lessoncontent;
    echo $lessonoutput->footer();
}