text:
//-----------------------------------------------------------------------
// <copyright file="TestRunTree.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

namespace Akka.MultiNodeTestRunner.Shared.Reporting
{
    /// <summary>
    /// The top of the tree - represents an entire test run.
    /// </summary>
    public class TestRunTree : IEquatable<TestRunTree>
    {
        private readonly List<FactData> _specs;

        public TestRunTree(long startTime) : this(startTime, new List<FactData>())
        {
        }

        public TestRunTree(long startTime, List<FactData> specs) : this(startTime, specs, null, null)
        {

        }

        [JsonConstructor]
        public TestRunTree(long startTime, List<FactData> specs, long? endTime, bool? passed)
        {
            StartTime = startTime;
            _specs = specs;
            EndTime = endTime;
            Passed = passed;
        }

        /// <summary>
        /// The absolute time tests began for this individual node
        /// </summary>
        public long StartTime { get; private set; }

        /// <summary>
        /// The absolute time tests ended for this individual node
        /// </summary>
        public long? EndTime { get; set; }

        /// <summary>
        /// Whether or not this test has acquired a result yet
        /// </summary>
        public bool? Passed { get; set; }

        public IEnumerable<FactData> Specs { get { return _specs; } }

        public TimeSpan Elapsed
        {
            get
            {
                return ((EndTime.HasValue ? new DateTime(EndTime.Value) : DateTime.UtcNow) - new DateTime(StartTime));
            }
        }

        public void AddSpec(FactData spec)
        {
            _specs.Add(spec);
        }

        public void Complete()
        {
            var passes = _specs.Select(x => x.Passed);
            if (passes.All(x => x.HasValue))
            {
                Passed = passes.All(x => x.Value);
                EndTime = DateTime.UtcNow.Ticks;
            }
        }

        /// <summary>
        /// Returns a deep copy of the current tree.
        /// </summary>
        public TestRunTree Copy(bool? passed = null)
        {
            var specs = new FactData[_specs.Count];
            _specs.CopyTo(specs);

            return new TestRunTree(StartTime, specs.ToList(), EndTime, passed ?? Passed);
        }

        #region Equality

        /// <inheritdoc/>
        public bool Equals(TestRunTree other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return
                _specs.SequenceEqual(other._specs)
                && StartTime == other.StartTime
                && EndTime == other.EndTime
                && Passed.Equals(other.Passed);
        }

        /// <inheritdoc/>
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((TestRunTree) obj);
        }

        /// <inheritdoc/>
        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = (_specs != null ? _specs.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ StartTime.GetHashCode();
                hashCode = (hashCode*397) ^ EndTime.GetHashCode();
                hashCode = (hashCode*397) ^ Passed.GetHashCode();
                return hashCode;
            }
        }

        #endregion
    }

    /// <summary>
    /// A collection of data about a particular test
    /// </summary>
    public class FactData : IEquatable<FactData>
    {
        private readonly Dictionary<int, NodeData> _nodes;

        /// <summary>
        /// Messages sent by the test runner for this spec, rather than any individual nodes
        /// </summary>
        private readonly SortedSet<MultiNodeMessage> _testRunnerTimeLine;

        public FactData(string factName)
            : this(factName, DateTime.UtcNow.Ticks, new Dictionary<int, NodeData>(), new  List<MultiNodeMessage>()) { }

        public FactData(string factName, long startTime, Dictionary<int, NodeData> nodes, IEnumerable<MultiNodeMessage> testRunnerTimeLine)
            : this(factName, startTime, nodes, testRunnerTimeLine, null, null)
        {

        }

        public FactData(string factName, long startTime, Dictionary<int, NodeData> nodes, IEnumerable<MultiNodeMessage> testRunnerTimeLine, long? endTime, bool? passed)
        {
            _nodes = nodes;
            _testRunnerTimeLine = new SortedSet<MultiNodeMessage>(testRunnerTimeLine ?? new List<MultiNodeMessage>());
            StartTime = startTime;
            FactName = factName;
            EndTime = endTime;
            Passed = passed;
        }

        [JsonConstructor]
        public FactData(string factName, long startTime, IEnumerable<NodeData> nodes, IEnumerable<MultiNodeMessage> testRunnerTimeLine, long? endTime, bool? passed)
            : this(factName, startTime,
            nodes == null ? new Dictionary<int, NodeData>() :
            nodes.ToDictionary(key => key.NodeIndex, data => data),
            testRunnerTimeLine, endTime, passed)
        {
        }

        public string FactName { get; private set; }

        public IEnumerable<MultiNodeMessage> RunnerMessages { get { return _testRunnerTimeLine; } }

        public Dictionary<int, NodeData> NodeFacts { get { return _nodes; } }

        /// <summary>
        /// The absolute time tests began for this individual node
        /// </summary>
        public long StartTime { get; private set; }

        /// <summary>
        /// The absolute time tests ended for this individual node
        /// </summary>
        public long? EndTime { get; set; }

        /// <summary>
        /// Whether or not this test has acquired a result yet
        /// </summary>
        public bool? Passed { get; set; }

        public TimeSpan Elapsed
        {
            get
            {
                return ((EndTime.HasValue ? new DateTime(EndTime.Value) : DateTime.UtcNow) - new DateTime(StartTime));
            }
        }

        public void Complete()
        {
            var passes = _nodes.Select(x => x.Value.Passed);
            if (passes.All(x => x.HasValue))
            {
                Passed = passes.All(x => x.Value);
                EndTime = DateTime.UtcNow.Ticks;
            }
        }

        public void AddNodes(NodeData[] nodeDatum)
        {
            foreach(var node in nodeDatum)
                AddNode(node);
        }

        public void AddNode(NodeData nodeData)
        {
            _nodes[nodeData.NodeIndex] = nodeData;
        }

        public void Put(MultiNodeMessage message)
        {
            _testRunnerTimeLine.Add(message);
        }

        /// <summary>
        /// Creates a deep copy of the current <see cref="FactData"/> object.
        /// </summary>
        public FactData Copy()
        {
            var nodeData = new Dictionary<int, NodeData>(_nodes.Count);
            foreach (var node in _nodes)
            {
                //make a copy of the NodeData too
                nodeData[node.Key] = node.Value.Copy();
            }

            var messageTimeline = new MultiNodeMessage[_testRunnerTimeLine.Count];
            _testRunnerTimeLine.CopyTo(messageTimeline);

            return new FactData(FactName, StartTime, nodeData, messageTimeline, EndTime, Passed);
        }

        #region Equality

        /// <inheritdoc/>
        public bool Equals(FactData other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return _nodes.SequenceEqual(other._nodes)
                && _testRunnerTimeLine.SetEquals(other._testRunnerTimeLine)
                && string.Equals(FactName, other.FactName)
                && StartTime == other.StartTime
                && EndTime == other.EndTime
                && Passed.Equals(other.Passed);
        }

        /// <inheritdoc/>
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((FactData) obj);
        }

        /// <inheritdoc/>
        public override int GetHashCode()
        {
            unchecked
            {
                return (FactName.GetHashCode() * 397) ^ StartTime.GetHashCode();
            }
        }

        #endregion
    }

    /// <summary>
    /// A collection of data about the status of a particular node
    /// </summary>
    public class NodeData : IEquatable<NodeData>
    {
        private readonly SortedSet<MultiNodeMessage> _eventTimeLine;

        public NodeData(int nodeIndex, string nodeRole) : this(nodeIndex, nodeRole, DateTime.UtcNow.Ticks, new List<MultiNodeMessage>()) { }

        public NodeData(int nodeIndex, string nodeRole, long startTime, IEnumerable<MultiNodeMessage> eventTimeLine)
            : this(nodeIndex, nodeRole, startTime, eventTimeLine, null, null)
        {

        }

        /// <summary>
        /// Copy constructor
        /// </summary>
        [JsonConstructor]
        public NodeData(int nodeIndex, string nodeRole, long startTime, IEnumerable<MultiNodeMessage> eventTimeLine, long? endTime,
            bool? passed)
        {
            NodeIndex = nodeIndex;
            NodeRole = nodeRole;
            StartTime = startTime;
            _eventTimeLine = new SortedSet<MultiNodeMessage>(eventTimeLine ?? new List<MultiNodeMessage>());
            EndTime = endTime;
            Passed = passed;
        }

        /// <summary>
        /// The position of this node in the 0...N index of all nodes in the set.
        /// </summary>
        public int NodeIndex { get; private set; }

        /// <summary>
        /// The Role of this node.
        /// </summary>
        public string NodeRole { get; private set; }

        /// <summary>
        /// The absolute time tests began for this individual node
        /// </summary>
        public long StartTime { get; private set; }

        /// <summary>
        /// The absolute time tests ended for this individual node
        /// </summary>
        public long? EndTime { get; set; }

        /// <summary>
        /// Whether or not this test has acquired a result yet
        /// </summary>
        public bool? Passed { get; set; }

        /// <summary>
        /// Filter all of the result messages to the top
        /// </summary>
        public SortedSet<MultiNodeResultMessage> ResultMessages
        {
            get
            {
                return new SortedSet<MultiNodeResultMessage>(_eventTimeLine.Where(x => x.GetType() == typeof(MultiNodeResultMessage)).Cast<MultiNodeResultMessage>());
            }
        }

        public TimeSpan Elapsed
        {
            get
            {
                return ((EndTime.HasValue ? new DateTime(EndTime.Value) : DateTime.UtcNow) - new DateTime(StartTime));
            }
        }

        /// <summary>
        /// All of the events that occurred for this node - time sequenced.
        /// </summary>
        public IEnumerable<MultiNodeMessage> EventStream
        {
            get { return _eventTimeLine; }
        }

        /// <summary>
        /// Pushes a new message onto the <see cref="EventStream"/> for this node.
        /// </summary>
        public void Put(MultiNodeMessage message)
        {
            //Check for passed messages
            if (!Passed.HasValue && message is MultiNodeResultMessage)
            {
                var resultMessage = message as MultiNodeResultMessage;
                Passed = resultMessage.Passed;
                EndTime = DateTime.UtcNow.Ticks;
            }

            _eventTimeLine.Add(message);
        }

        /// <summary>
        /// Creates a deep copy of the current <see cref="NodeData"/> object
        /// </summary>
        public NodeData Copy()
        {
            var events = new MultiNodeMessage[_eventTimeLine.Count];
            _eventTimeLine.CopyTo(events);

            return new NodeData(NodeIndex, NodeRole, StartTime, events, EndTime, Passed);
        }

        #region Equality

        /// <inheritdoc/>
        public bool Equals(NodeData other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return _eventTimeLine.SetEquals(other._eventTimeLine)
                && NodeIndex == other.NodeIndex
                && String.Equals(NodeRole, other.NodeRole, StringComparison.Ordinal)
                && StartTime == other.StartTime
                && EndTime == other.EndTime
                && Passed.Equals(other.Passed);
        }

        /// <inheritdoc/>
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((NodeData) obj);
        }

        /// <inheritdoc/>
        public override int GetHashCode()
        {
            unchecked
            {
                return (NodeIndex * 397) ^ (NodeRole.GetHashCode() * 397) ^ StartTime.GetHashCode();
            }
        }

        #endregion

    }
}


text:
<feed version="0.3" xmlns="http://purl.org/atom/ns#" xml:base="http://example.com/parent/">
<entry>

blah blah blah

  <title type="application/xhtml+xml" xml:base="http://example.com/test/">
Example test
</title>
</entry>
</feed>

redpajama_set_name: RedPajamaGithub


text:
static const char* null = 0;

TEST_CASE("JsonVariant::as()") {
  SECTION("DoubleAsBool") {
    JsonVariant variant = 4.2;
    REQUIRE(variant.as<bool>());
  }

  SECTION("DoubleAsCstr") {
    JsonVariant variant = 4.2;
    REQUIRE_FALSE(variant.as<const char*>());
  }

  SECTION("DoubleAsString") {
    JsonVariant variant = 4.2;
    REQUIRE(std::string("4.2") == variant.as<std::string>());
  }

  SECTION("DoubleAsLong") {
    JsonVariant variant = 4.2;
    REQUIRE(4L == variant.as<long>());
  }

  SECTION("DoubleAsUnsigned") {
    JsonVariant variant = 4.2;
    REQUIRE(4U == variant.as<unsigned>());
  }

  SECTION("DoubleZeroAsBool") {
    JsonVariant variant = 0.0;
    REQUIRE_FALSE(variant.as<bool>());
  }

  SECTION("DoubleZeroAsLong") {
    JsonVariant variant = 0.0;
    REQUIRE(0L == variant.as<long>());
  }

  SECTION("FalseAsBool") {
    JsonVariant variant = false;
    REQUIRE_FALSE(variant.as<bool>());
  }

  SECTION("FalseAsDouble") {
    JsonVariant variant = false;
    REQUIRE(0.0 == variant.as<double>());
  }

  SECTION("FalseAsLong") {
    JsonVariant variant = false;
    REQUIRE(0L == variant.as<long>());
  }

  SECTION("FalseAsString") {
    JsonVariant variant = false;
    REQUIRE(std::string("false") == variant.as<std::string>());
  }

  SECTION("TrueAsBool") {
    JsonVariant variant = true;
    REQUIRE(variant.as<bool>());
  }

  SECTION("TrueAsDouble") {
    JsonVariant variant = true;
    REQUIRE(1.0 == variant.as<double>());
  }

  SECTION("TrueAsLong") {
    JsonVariant variant = true;
    REQUIRE(1L == variant.as<long>());
  }

  SECTION("TrueAsString") {
    JsonVariant variant = true;
    REQUIRE(std::string("true") == variant.as<std::string>());
  }

  SECTION("LongAsBool") {
    JsonVariant variant = 42L;
    REQUIRE(variant.as<bool>());
  }

  SECTION("LongZeroAsBool") {
    JsonVariant variant = 0L;
    REQUIRE_FALSE(variant.as<bool>());
  }

  SECTION("PositiveLongAsDouble") {
    JsonVariant variant = 42L;
    REQUIRE(42.0 == variant.as<double>());
  }

  SECTION("NegativeLongAsDouble") {
    JsonVariant variant = -42L;
    REQUIRE(-42.0 == variant.as<double>());
  }

  SECTION("LongAsString") {
    JsonVariant variant = 42L;
    REQUIRE(std::string("42") == variant.as<std::string>());
  }

  SECTION("LongZeroAsDouble") {
    JsonVariant variant = 0L;
    REQUIRE(0.0 == variant.as<double>());
  }

  SECTION("NullAsBool") {
    JsonVariant variant = null;
    REQUIRE_FALSE(variant.as<bool>());
  }

  SECTION("NullAsDouble") {
    JsonVariant variant = null;
    REQUIRE(0.0 == variant.as<double>());
  }

  SECTION("NullAsLong") {
    JsonVariant variant = null;
    REQUIRE(0L == variant.as<long>());
  }

  SECTION("NullAsString") {
    JsonVariant variant = null;
    REQUIRE(std::string("null") == variant.as<std::string>());
  }

  SECTION("NumberStringAsBool") {
    JsonVariant variant = "42";
    REQUIRE(variant.as<bool>());
  }

  SECTION("NumberStringAsLong") {
    JsonVariant variant = "42";
    REQUIRE(42L == variant.as<long>());
  }

#if ARDUINOJSON_USE_LONG_LONG || ARDUINOJSON_USE_INT64
  SECTION("NumberStringAsInt64Negative") {
    JsonVariant variant = "-9223372036854775808";
    REQUIRE(-9223372036854775807 - 1 == variant.as<long long>());
  }

  SECTION("NumberStringAsInt64Positive") {
    JsonVariant variant = "9223372036854775807";
    REQUIRE(9223372036854775807 == variant.as<long long>());
  }
#endif

  SECTION("RandomStringAsBool") {
    JsonVariant variant = "hello";
    REQUIRE_FALSE(variant.as<bool>());
  }

  SECTION("RandomStringAsLong") {
    JsonVariant variant = "hello";
    REQUIRE(0L == variant.as<long>());
  }

  SECTION("RandomStringAsConstCharPtr") {
    JsonVariant variant = "hello";
    REQUIRE(std::string("hello") == variant.as<const char*>());
  }

  SECTION("RandomStringAsCharPtr") {
    JsonVariant variant = "hello";
    REQUIRE(std::string("hello") == variant.as<char*>());
  }

  SECTION("RandomStringAsString") {
    JsonVariant variant = "hello";
    REQUIRE(std::string("hello") == variant.as<std::string>());
  }

  SECTION("TrueStringAsBool") {
    JsonVariant variant = "true";
    REQUIRE(variant.as<bool>());
  }

  SECTION("TrueStringAsLong") {
    JsonVariant variant = "true";
    REQUIRE(1L == variant.as<long>());
  }

  SECTION("ObjectAsString") {
    DynamicJsonBuffer buffer;

    JsonObject& obj = buffer.createObject();
    obj["key"] = "value";

    JsonVariant variant = obj;
    REQUIRE(std::string("{\"key\":\"value\"}") == variant.as<std::string>());
  }

  SECTION("ArrayAsString") {
    DynamicJsonBuffer buffer;

    JsonArray& arr = buffer.createArray();
    arr.add(4);
    arr.add(2);

    JsonVariant variant = arr;
    REQUIRE(std::string("[4,2]") == variant.as<std::string>());
  }

  SECTION("ArrayAsJsonArray") {
    DynamicJsonBuffer buffer;
    JsonArray& arr = buffer.createArray();

    JsonVariant variant = arr;
    REQUIRE(&arr == &variant.as<JsonArray&>());
    REQUIRE(&arr == &variant.as<JsonArray>());  // <- shorthand
  }

  SECTION("ObjectAsJsonObject") {
    DynamicJsonBuffer buffer;
    JsonObject& arr = buffer.createObject();

    JsonVariant variant = arr;
    REQUIRE(&arr == &variant.as<JsonObject&>());
    REQUIRE(&arr == &variant.as<JsonObject>());  // <- shorthand
  }
}


text:
package Database;

import com.mysql.jdbc.Connection;

import java.sql.DriverManager;

/**
 * Created by roije on 12/06/2016.
 */
public class DB_Connector
{
    final static String user = "root";
    final static String pass = "admin";
    final static String db = DB_CreateDatabase.DBNAME;
    final static String url = "jdbc:mysql://localhost/";

    public static Connection getConnection()
    {
        Connection conn;
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            conn = (Connection) DriverManager.getConnection(url + db, user, pass);
            return conn;
        } catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
}


text:
package com.android.tools.build.bundletool.device;

import static com.google.common.base.Preconditions.checkArgument;

import com.android.bundle.Devices.DeviceSpec;
import com.android.bundle.Targeting.ApkTargeting;
import com.android.bundle.Targeting.ModuleTargeting;
import com.android.bundle.Targeting.SdkVersion;
import com.android.bundle.Targeting.SdkVersionTargeting;
import com.android.bundle.Targeting.VariantTargeting;
import com.android.tools.build.bundletool.model.exceptions.IncompatibleDeviceException;
import java.util.stream.Stream;

/** A {@link TargetingDimensionMatcher} that provides matching on SDK version. */
public final class SdkVersionMatcher extends TargetingDimensionMatcher<SdkVersionTargeting> {
  private static final String RELEASE_CODENAME = "REL";
  private static final int PRE_RELEASE_SDK = 10_000;

  // Most recently supported release SDK version, even on pre-release devices
  // e.g. pre-releases R devices report codename "R" and sdk version 29 (Q release SDK)
  private final int deviceSdkVersion;
  // RELEASE_CODENAME for released devices, or a codename on pre-release devices
  private final String deviceCodename;

  public SdkVersionMatcher(DeviceSpec deviceSpec) {
    super(deviceSpec);
    deviceSdkVersion = deviceSpec.getSdkVersion();
    // Default to release device if no codename is specified.
    if (deviceSpec.getCodename().isEmpty()) {
      deviceCodename = RELEASE_CODENAME;
    } else {
      deviceCodename = deviceSpec.getCodename();
    }
  }

  @Override
  public boolean matchesTargeting(SdkVersionTargeting targeting) {
    checkArgument(
        targeting.getValueCount() <= 1,
        "Found more than one SDK version value in the variant targeting.");

    SdkVersion sdkValue =
        targeting.getValueCount() == 0 ? SdkVersion.getDefaultInstance() : targeting.getValue(0);

    if (!matchesDeviceSdk(sdkValue, deviceSdkVersion)) {
      return false;
    }

    // Check if there is a better match among alternatives.
    for (SdkVersion alternativeSdkValue : targeting.getAlternativesList()) {
      if (isBetterSdkMatch(
          /* candidate= */ alternativeSdkValue, /* contestedValue= */ sdkValue, deviceSdkVersion)) {
        return false;
      }
    }
    return true;
  }

  /**
   * Returns if the candidate sdk targeting better matches the device sdk version.
   *
   * @param candidate candidate sdk targeting that we analyze.
   * @param contestedValue the targeting value we are trying to contest.
   * @param deviceSdkVersion the device sdk version
   * @return whether candidate matches better the device sdk version.
   */
  private boolean isBetterSdkMatch(
      SdkVersion candidate, SdkVersion contestedValue, int deviceSdkVersion) {
    if (!matchesDeviceSdk(candidate, deviceSdkVersion)) {
      return false;
    }
    return candidate.hasMin() && candidate.getMin().getValue() > contestedValue.getMin().getValue();
  }

  private boolean isPreReleaseDevice() {
    return !deviceCodename.equals(RELEASE_CODENAME);
  }

  private boolean matchesDeviceSdk(SdkVersion value, int deviceSdkVersion) {
    // If the device is pre release and the APK was compiled with pre release SDK allow install
    if (isPreReleaseDevice() && value.hasMin() && value.getMin().getValue() == PRE_RELEASE_SDK) {
      return true;
    }

    return !value.hasMin() || value.getMin().getValue() <= deviceSdkVersion;
  }

  @Override
  protected SdkVersionTargeting getTargetingValue(ApkTargeting apkTargeting) {
    return apkTargeting.getSdkVersionTargeting();
  }

  @Override
  protected SdkVersionTargeting getTargetingValue(VariantTargeting variantTargeting) {
    return variantTargeting.getSdkVersionTargeting();
  }

  @Override
  protected SdkVersionTargeting getTargetingValue(ModuleTargeting moduleTargeting) {
    return moduleTargeting.getSdkVersionTargeting();
  }

  @Override
  protected void checkDeviceCompatibleInternal(SdkVersionTargeting targeting) {
    SdkVersion sdkValue =
        targeting.getValueCount() == 0 ? SdkVersion.getDefaultInstance() : targeting.getValue(0);

    boolean anyMatch =
        Stream.concat(Stream.of(sdkValue), targeting.getAlternativesList().stream())
            .anyMatch(sdkVal -> matchesDeviceSdk(sdkVal, deviceSdkVersion));

    if (!anyMatch) {
      throw IncompatibleDeviceException.builder()
          .withUserMessage(
              "SDK version (%d) of the device is not supported.", getDeviceSpec().getSdkVersion())
          .build();
    }
  }

  @Override
  protected boolean isDeviceDimensionPresent() {
    return deviceSdkVersion != 0;
  }
}


text:
# Controllers

In an MVC application, the controller's job is to handle user input, and handle that request with a specified action. Though the controller action is where action logic is determined, models are often the real workhorses in the request cycle. Keep in mind as you read this guide to keep your controller action trim, with most of the actual functionality spread across models and other classes.

This guide is meant to introduce you to li3 controllers: their features, behaviors, and the best practices revolving around their usage.

## Controller Actions

li3 controllers reside inside the `/app/controllers` directory and extend the `lithium\action\Controller` core class. Let's start by creating a simple controller inside of an application. Controllers are often named after the objects they manage. This way the URL and model line up as well, and it's easy to know where certain bits of logic should live.

For example, let's create a new controller UsersController. Let's create a new file in `/app/controllers/UsersController.php` that looks like this:

```php
namespace app\controllers;

class UsersController extends \lithium\action\Controller {

	public function index() {}
}
```

Each _public_ function in a controller is considered by the li3 core to be a routable action. In fact, li3's default routing rules make these actions accessible via a browser immediately (in this case /users/index).

The `index()` action is a special action: if no action name is specified in the URL, li3 will try to pull up the index action instead. For example, a visitor accessing http://example.com/users/ on your application will see the results of the `index()` action. All other controller actions (unless routed otherwise) are at least accessed by the default route.

For example, we can create a new controller action that would be accessible at `/users/view/`:

```php
namespace app\controllers;

class UsersController extends \lithium\action\Controller {

	public function index() {}

	public function view() {}
}
```

## Accessing Request Parameters

An important part of a controller's role in an application is processing incoming request data to show the correct response. In this section, we'll show a few examples that should help you to get data into your controller actions.

### GET Parameters

One of the most user-friendly ways to handle incoming data is through the URL. Information passed along with a GET request is handled a number of different ways, based on your preferences.

The easiest way to handle incoming GET data is by realizing that URL segments that follow the action name are mapped to controller action parameters. Here's a few examples:

```text
http://example.com/users/view/1  --> UsersController::view($userId);
http://example.com/posts/show/using+controllers/8384/  -->  PostsController::show($title, $postId);
```

GET information passed this way is also accessible via the incoming request object:

```text
http://example.com/users/view/1  --> $this->request->args[0]
```

While we'll always recommend using clear URL-based variables, it's important to mention that GET parameters passed as raw query string variables are also available as an attribute of the incoming request:

```text
http://example.com/users/view?userId=1  --> $this->request->query['userId']
```

### POSTed Data

POSTed data is also gathered from the request object. Form field data is found on the request object inside an array with keys named after the input elements generated on the referring page. For example, consider an HTML form that included these elements:

```html
<input type="text" name="title" value="How to Win Friends and Influence People" />
<input type="text" name="category" value="Self-Help" />
```

Accessing these values when submitted to a controller action is as easy as:

```php
$this->request->data['title'];
$this->request->data['category'];
```

## Request Flow Control

Occasionally a controller action will want to divert, re-route, or automatically configure the view layer based on an incoming request. There are a number of controller methods to help facilitate request flow handling.

### Redirection

The most basic type of flow control at the controller level is redirection. It's common to redirect a user to a new URL once an action has been performed. This type of control is done through the controller's `redirect()` method. Here's an example of a controller action that redirects the request:

```php
public function register() {
	// Validate and save user data POSTed to the
	// controller action found in $this->request->data...

	$this->redirect('Users::welcome');
}
```

The URL specified can be relative to the application or point to an outside resource. The `redirect()` function also features a second `$options` parameter that also allows you to set HTTP status headers, and make decisions about whether or not to `exit()` after a redirect. Be sure to check the API for `lithium\action\Controller::redirect()` for more details.

### Exceptions and Error Handling

Error handling in li3 is done using the core ErrorHandler class. `ErrorHandler` allows PHP errors and exceptions to be handled in a uniform way. Using `ErrorHandler`s configuration makes it possible to have broad but tightly controlled error handling across your application.

`ErrorHandler` configuration is done by creating a new error-specific bootstrap file that contains your `ErrorHandler` configuration and initialization. To illustrate how this is done, let's consider an imaginary (but common) scenario. Rather than tossing up error messages and stack traces to your users, it's better to create some sort of way to handle exceptions and render user-friendly error pages.

Let's start by creating a way to handle page not found-like errors. If a request can't be routed properly, the li3 dispatcher will throw an exception to let you know that a controller or view can't be found. Though the example here will be specific to this case, it should provide a mental framework that will allow you to understand how to catch errors and exceptions, and handle them accordingly.

Start by creating a new bootstrap file in /app/config/bootstrap/error.php:

```php
use lithium\core\ErrorHandler;

$conditions = ['type' => 'lithium\action\DispatchException'];

ErrorHandler::apply('lithium\action\Dispatcher::run', $conditions, function($exception, $params) {
	var_dump(compact('exception', 'params'));
	die();
});
```

This simple example shows how you can create a lambda that handles any `DispatchException`s being thrown in your entire application. The function you pass to apply() can be more involved, depending on what you want to do, however.

Here's a more complete example, showing how you'd actually render a template, and include logging:

```php
use lithium\core\ErrorHandler;
use lithium\analysis\Logger;
use lithium\template\View;

Logger::config(['error' => ['adapter' => 'File']]);

$render = function($template, $content) {
	$view = new View([
		'paths' => [
			'template' => '{:library}/views/{:controller}/{:template}.{:type}.php',
			'layout'   => '{:library}/views/layouts/{:layout}.{:type}.php',
		]
	]);
	echo $view->render('all', compact('content'), compact('template') + [
		'controller' => 'errors',
		'layout' => 'default',
		'type' => 'html'
	]);
};

ErrorHandler::apply('lithium\action\Dispatcher::run', [], function($exception, $params) use ($render) {
	Logger::write('error', "Page Not Found...");
	$render('404', compact('exception', 'params'));
});
```

If you've got more than one type of exception you want to handle, just add more calls to `apply()` in your error bootstrap file.

### Render Types and Detection

Although a typical request to a li3 application receives an HTML response, the framework is built to be extremely flexible in handling and serving different types of content. This functionality is especially important in applications that have many different components or endpoints. If your app also feeds data to a Flash object (AMF/XML) and a mobile phone (XML/JSON), responding to requests in different ways with the same underlying logic can be a huge time saver.

The flow for handling a given type of a response works something like the following:

 1. A request is sent to the application, containing some sort of indicator of the request type. li3's default routing allows for simple extension detection, for example.
 2. As li3 bootstraps, a media type and handler is registered with the `\net\http\Media` class.
 3. The application detects the request type and sets the response type.
 4. Once a controller is ready to render the data, the registered handler receives the data and renders the output.

#### Detecting and Setting Types

The easiest way to set a type is by declaring it as part of the route. One of li3's default routes already does this for you:

```php
Router::connect('/{:controller}/{:action}/{:id:[0-9]+}.{:type}', ['id' => null]);
```

In effect, this forces a request to `/controller/action/7345.json` to be rendered by the JSON media handler currently registered. You can use this pattern to expand your routes to apply type-matching to a wider array of requests:

```php
// http://example.com/controller/action.xml
Router::connect('/{:controller}/{:action}.{:type}');
```

You can also statically define the type for a route by adding the 'type' key to the route definition:

```php
Router::connect('/latest/feed', [
	'Posts::index',
	'type' => 'xml'
]);
```

If you'd rather use other information to convey the request type to li3 (headers, GET variables, etc.) you can gather that information then set `$this->_render['type']` in the controller action.

Manual type rendering can also be done by handing the type's name to the render function:

```php
$this->render(['csv' => Post::find('all')]);
```

#### Handler Registration

As mentioned earlier, type handlers are registered by the `\net\http\Media` class. This is usually done in the `/config/bootstrap/media.php` bootstrap file. Be sure to uncomment the corresponding line in the main bootstrap file to enable this functionality.

Register your type by passing the relevant information to `Media::type()` inside the bootstrap. Here's what the general pattern looks like:

```php
Media::type('typeName', 'contentType', [$options]);
```

To give you an idea of how this process is completed, let's register a new handler for the BSON data type. If you're curious, BSON is a binary, serialized form of JSON used by MongoDB. Start by declaring a new media type in `/config/boostrap/media.php` and uncommenting the `media.php` line in your main bootstrap file:

```php
Media::type('bson', 'application/bson', []);
```

This gets us pretty far. If you make a request with a .bson extension that matches a configured route (one with {:type} in it), li3 will already hunt for a `.bson.php` template in the controller's template directory. You can continue to customize li3's behavior by utilizing the `$options` array you supply to `Media::type()`. After checking the API docs for `Media::type()`, we realize we can utilize a few options to make sure our response isn't housed in an HTML layout and use some functions we've defined for encoding and decoding the data:

```php
Media::type('bson', 'application/bson', [
	'layout' => false,
	'encode' => 'bson_encode',
	'decode' => 'bson_decode'
]);
```

Try the request again, and you'll get your BSON-encoded data, minus the HTML layout. Note that the bson_* functions used in this particular example are part of the PECL MongoDB extension. Don't worry if you don't have it installed: the main point is to realize that you can tell `Media` exactly what function to use to render the data (including using closures).

For more ideas on configuring media types, see the documentation for `Media::type()`.

## Using Models and Core Libraries

While an entire guide is devoted to covering model usage, it's important to see how they're used inside the controller layer. Using models inside li3 controllers is simple. Let's start with a bare controller as an example:

```php
namespace app\controllers;

class ClientsController extends \lithium\action\Controller {

	public function index() {}
}
```

While not required, it's helpful to name controllers after the models they primarily use, at least for organizational purposes. To start using your model inside this controller, you'll need to let PHP know you intend to use the model class inside this controller:

```php
namespace app\controllers;

use app\models\Client;

class ClientsController extends \lithium\action\Controller {

	public function index() {}
}
```

Since most model access is done statically, just access the methods you need in your controller actions directly:

```php
namespace app\controllers;

use app\models\Client;

class ClientsController extends \lithium\action\Controller {

	public function index() {
		$clients = Client::find('all');
		return compact('clients');
	}

	public function details($clientId) {
		$client = Client::find('first', [
			'conditions' => [
				'id' => $clientId,
			]
		]);

		return compact('client');
	}
}
```

Using li3's core libraries inside the controller layer is similar, although instantiating a class is sometimes necessary. Consider the following example that uses the `Service` class:

```php
namespace app\controllers;

use SimpleXmlElement;
use lithium\net\http\Service;

class ClientsController extends \lithium\action\Controller {

	public function index() {
		$service = new Service(['host' => 'api.flickr.com']);
		$response = new SimpleXmlElement($service->get('/services/feeds/photos_public.gne'));
		return compact('response');
	}
}
```

This is done by declaring the usage of the class by specifying it's fully namespaced path, and later instantiating it inside the action logic.

Also note that core PHP classes (`SimpleXmlElement`, in this case) are imported with the `use` statement as well, since they exist in the root namespace.

## Moving Data to the View

Once your controller action has fetched and processed the data it needs, it's time to push the data to the view layer. There are two main ways to accomplish this: by using the `set()` method of the `Controller` class, or by simply returning an associative array as the result of a controller action method.

First, the `set()` method is used to send an associative array to the view. Consider this example controller action method:

```php
public function index() {
	$data = SomeModel::find('all');
	$this->processData($data);
	$this->set(['importantData' => $data]);
}
```

This populates the index view for this controller with a variable named `$importantData` with the same contents as `$data`. This same logic could be written a bit more elegantly:

```php
public function index() {
	$data = SomeModel::find('all');
	$this->processData($data);
	$this->set(compact('data'));
}
```

One difference to note here is that the view's variable is now named `$data`, just as it was in the controller.

The `set()` method is especially useful when you've got bits of data you want to hand to the view in pieces, or conditionally, as it can be called at any point inside of a controller action method:

```php
public function index() {
	$data = SomeModel::find('all');
	$this->processData($data);
	$this->set(['importantData' => $data]);

	$moreData = SomeService::get();
	$this->processData($moreData);

	if ($someCondition) {
		$this->set($moreData);
	}

	//...
}
```

Conversely, sometimes all your data is ready by the end of the method's logic, and you can just return the associative array to hand it to the view:

```php
public function index() {
	$data = SomeModel::find('all');
	$this->processData($data);

	$moreData = SomeService::get();
	$this->processData($moreData);

	return compact('data', 'moreData');
}
```

## Filtering Controller Logic

Filtering controller logic can be a bit tricky to the new li3 user, due to the flexible and elegant way the dispatch cycle executes.

When a request is sent to an application, the Dispatcher first uses the Router to determine which controller to load. Once a target controller has been identified, a new controller object is created and invoked.

This last invokation step is performed inside of the dispatcher's `_callable()` method. Because of this, filters that wish to inject logic before or after controller actions is often done against `_callable()`. Doing so allows you access to parameters that are normally available to the controller, as well as the right controller instance, allowing you to call its methods.

 _Note:_ You might have seen some filters run against the dispatcher's `run()` method instead. In many cases, this should work just fine. The difference in using `_callable()` is that with the latter, you'll end up with access to the active controller instance itself, along with its parameters.

The `g11n` filters that come with the standard distribution form an illustrative example. Consider this slightly modified (for simplicity) version of that same filter:

```php
use lithium\aop\Filters;
use lithium\action\Dispatcher;

Filters::apply(Dispatcher::class, '_callable', function($params, $next) {
	$request = $params['request'];
	$controller = $next($params);

	if (!$request->locale) {
		$request->params['locale'] = Locale::preferred($request);
	}
	Environment::set(Environment::get(), ['locale' => $request->locale]);
	return $controller;
});
```

This example uses new-style filters, available with 1.1.

Here you can see that you've got access to the request parameters and the controller instance itself in the first two lines of the `Filters::apply()` call. In this case, the g11n framework is inspecting the request and setting locale settings accordingly, but when creating your own filter, you'd have access to the same data.

An important case to consider that's also covered in the g11n filters is remembering to also filter the frameworks other dispatcher: the console action dispatcher. In other words, if you truly want to effect every action in an application, you might consider also filtering the `lithium\console\Dispatcher` as well as the `lithium\action\Dispatcher`.

In this case, you'll want to use the special use/as syntax:

```php
use lithium\aop\Filters;
use lithium\action\Dispatcher as ActionDispatcher;
use lithium\console\Dispatcher as ConsoleDispatcher;

Filters::apply(ActionDispatcher::class /*, ... */);
Filters::apply(ConsoleDispatcher::class /*, ... */);
```


text:
<?php
	// Database parameters, change to reflect your own environment
	$db_host		= 'host_name';
	$db_user		= 'user_name';
	$db_pass		= 'password';
	$db_database	= 'database_name';

	// Open database connection
	$dbc = mysqli_connect($db_host,$db_user,$db_pass,$db_database);
	if($dbc === false){
		die("Error: Could not connect. " . mysqli_connect_error());
	}
?>


text:
'use strict';

var should = require('should'),
	request = require('supertest'),
	app = require('../../server'),
	mongoose = require('mongoose'),
	User = mongoose.model('User'),
	Rescue = mongoose.model('Rescue'),
	agent = request.agent(app);

/**
 * Globals
 */
var credentials, user, rescue;

/**
 * Rescue routes tests
 */
describe('Rescue CRUD tests', function() {
	beforeEach(function(done) {
		// Create user credentials
		credentials = {
			username: 'username',
			password: 'password'
		};

		// Create a new user
		user = new User({
			firstName: 'Full',
			lastName: 'Name',
			displayName: 'Full Name',
			email: 'test@test.com',
			username: credentials.username,
			password: credentials.password,
			provider: 'local'
		});

		// Save a user to the test db and create new Rescue
		user.save(function() {
			rescue = {
				name: 'Rescue Name'
			};

			done();
		});
	});

	it('should be able to save Rescue instance if logged in', function(done) {
		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Rescue
				agent.post('/rescues')
					.send(rescue)
					.expect(200)
					.end(function(rescueSaveErr, rescueSaveRes) {
						// Handle Rescue save error
						if (rescueSaveErr) done(rescueSaveErr);

						// Get a list of Rescues
						agent.get('/rescues')
							.end(function(rescuesGetErr, rescuesGetRes) {
								// Handle Rescue save error
								if (rescuesGetErr) done(rescuesGetErr);

								// Get Rescues list
								var rescues = rescuesGetRes.body;

								// Set assertions
								(rescues[0].user._id).should.equal(userId);
								(rescues[0].name).should.match('Rescue Name');

								// Call the assertion callback
								done();
							});
					});
			});
	});

	it('should not be able to save Rescue instance if not logged in', function(done) {
		agent.post('/rescues')
			.send(rescue)
			.expect(401)
			.end(function(rescueSaveErr, rescueSaveRes) {
				// Call the assertion callback
				done(rescueSaveErr);
			});
	});

	it('should not be able to save Rescue instance if no name is provided', function(done) {
		// Invalidate name field
		rescue.name = '';

		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Rescue
				agent.post('/rescues')
					.send(rescue)
					.expect(400)
					.end(function(rescueSaveErr, rescueSaveRes) {
						// Set message assertion
						(rescueSaveRes.body.message).should.match('Please fill Rescue name');

						// Handle Rescue save error
						done(rescueSaveErr);
					});
			});
	});

	it('should be able to update Rescue instance if signed in', function(done) {
		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Rescue
				agent.post('/rescues')
					.send(rescue)
					.expect(200)
					.end(function(rescueSaveErr, rescueSaveRes) {
						// Handle Rescue save error
						if (rescueSaveErr) done(rescueSaveErr);

						// Update Rescue name
						rescue.name = 'WHY YOU GOTTA BE SO MEAN?';

						// Update existing Rescue
						agent.put('/rescues/' + rescueSaveRes.body._id)
							.send(rescue)
							.expect(200)
							.end(function(rescueUpdateErr, rescueUpdateRes) {
								// Handle Rescue update error
								if (rescueUpdateErr) done(rescueUpdateErr);

								// Set assertions
								(rescueUpdateRes.body._id).should.equal(rescueSaveRes.body._id);
								(rescueUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?');

								// Call the assertion callback
								done();
							});
					});
			});
	});

	it('should be able to get a list of Rescues if not signed in', function(done) {
		// Create new Rescue model instance
		var rescueObj = new Rescue(rescue);

		// Save the Rescue
		rescueObj.save(function() {
			// Request Rescues
			request(app).get('/rescues')
				.end(function(req, res) {
					// Set assertion
					res.body.should.be.an.Array.with.lengthOf(1);

					// Call the assertion callback
					done();
				});

		});
	});

	it('should be able to get a single Rescue if not signed in', function(done) {
		// Create new Rescue model instance
		var rescueObj = new Rescue(rescue);

		// Save the Rescue
		rescueObj.save(function() {
			request(app).get('/rescues/' + rescueObj._id)
				.end(function(req, res) {
					// Set assertion
					res.body.should.be.an.Object.with.property('name', rescue.name);

					// Call the assertion callback
					done();
				});
		});
	});

	it('should be able to delete Rescue instance if signed in', function(done) {
		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Rescue
				agent.post('/rescues')
					.send(rescue)
					.expect(200)
					.end(function(rescueSaveErr, rescueSaveRes) {
						// Handle Rescue save error
						if (rescueSaveErr) done(rescueSaveErr);

						// Delete existing Rescue
						agent.delete('/rescues/' + rescueSaveRes.body._id)
							.send(rescue)
							.expect(200)
							.end(function(rescueDeleteErr, rescueDeleteRes) {
								// Handle Rescue error error
								if (rescueDeleteErr) done(rescueDeleteErr);

								// Set assertions
								(rescueDeleteRes.body._id).should.equal(rescueSaveRes.body._id);

								// Call the assertion callback
								done();
							});
					});
			});
	});

	it('should not be able to delete Rescue instance if not signed in', function(done) {
		// Set Rescue user
		rescue.user = user;

		// Create new Rescue model instance
		var rescueObj = new Rescue(rescue);

		// Save the Rescue
		rescueObj.save(function() {
			// Try deleting Rescue
			request(app).delete('/rescues/' + rescueObj._id)
			.expect(401)
			.end(function(rescueDeleteErr, rescueDeleteRes) {
				// Set message assertion
				(rescueDeleteRes.body.message).should.match('User is not logged in');

				// Handle Rescue error error
				done(rescueDeleteErr);
			});

		});
	});

	afterEach(function(done) {
		User.remove().exec();
		Rescue.remove().exec();
		done();
	});
});


text:
import sys
import numpy as np
import shtns

class shtnsfiledata:

    def setup(self, file_info, anti_aliasing):
        import shtns
        import numpy as np

        if file_info['modes_m_max'] != file_info['modes_m_max']:
            raise Exception("Only num_lon == num_lat supported")

        ntrunc = file_info['modes_n_max']
        self._shtns = shtns.sht(ntrunc, ntrunc, 1, shtns.sht_orthonormal+shtns.SHT_NO_CS_PHASE)

        nlons = (ntrunc + 1) * 2
        nlats = (ntrunc + 1)

        if anti_aliasing:
            if nlons & 1:
                raise Exception("Only even numbers of longitudes coordinates allowed for anti-aliasing")
            if nlats & 1:
                raise Exception("Only even numbers of latitudinal coordinates allowed for anti-aliasing")

            print("Anti-aliasing:")
            print(" + old lon/lat: ", nlons, nlats)

            nlons += nlons//2
            nlats += nlats//2

            print(" + new lon/lat: ", nlons, nlats)

        self._shtns.set_grid(nlats, nlons, shtns.sht_quick_init|shtns.SHT_PHI_CONTIGUOUS, 0)

        self.lats = np.arcsin(self._shtns.cos_theta)
        self.lons = (2.*np.pi/nlons)*np.arange(nlons)

    def phys2spec(self, data):
        return self._shtns.analys(data)

    def spec2phys(self, dataspec):
        return self._shtns.synth(dataspec)

class postprocessing_swe:
    def run(self, M=128):
        file_info = {
                'modes_m_max': M-1,
                'modes_n_max': M-1,
                }

        #
        # Swap this between 0 and 1
        #
        if 1:
            #
            # Bug reproducer
            #

            # Setup transformations without anti-aliasing (lower physical resolution)
            self.sh = shtnsfiledata()
            self.sh.setup(file_info, anti_aliasing=False)

            # Setup transformations *with* anti-aliasing
            self.sh_aa = shtnsfiledata()
            self.sh_aa.setup(file_info, anti_aliasing=True)

        else:
            # Setup transformations *with* anti-aliasing
            self.sh_aa = shtnsfiledata()
            self.sh_aa.setup(file_info, anti_aliasing=True)

            # Setup transformations without anti-aliasing (lower physical resolution)
            self.sh = shtnsfiledata()
            self.sh.setup(file_info, anti_aliasing=False)

        # Load fields
        nlats = M
        nlons = M*2
        self.phi_pert_phys = np.zeros((nlats, nlons))

        phi0 = np.pi/7.
        phi1 = 0.5*np.pi - phi0
        phi2 = 0.25*np.pi
        alpha = 1./30.; beta = 1./150.
        hamp = 120.

        lons, lats = np.meshgrid(self.sh.lons, self.sh.lats)
        self.phi_pert_phys += hamp*np.cos(lats)*np.exp(-((lons-np.pi)/alpha)**2)*np.exp(-((phi2-lats)/beta)**2)

        self.phi_pert_spec = self.sh.phys2spec(self.phi_pert_phys)

        ke_phys_data = self.sh.spec2phys(self.phi_pert_spec)
        ke_spec_data = self.sh.phys2spec(ke_phys_data)
        err = np.max(np.abs(ke_spec_data - self.phi_pert_spec))
        print("Error", err)
        assert err < 1e-10

        ke_phys_data = self.sh_aa.spec2phys(self.phi_pert_spec)
        ke_spec_data = self.sh_aa.phys2spec(ke_phys_data)
        err = np.max(np.abs(ke_spec_data - self.phi_pert_spec))
        print("Error", err)
        assert err < 1e-10

print("Accuracy test")

for M in [64, 128, 256, 512, 1024, 2048]:
    s = postprocessing_swe()
    s.run()

print("Test successful")


text:
define([
  // These are path alias that we configured in our bootstrap
  'jquery',     // vendor/jquery/jquery
  'underscore', // vendor/underscore/underscore
  'backbone'    // vendor/backbone/backbone
], function($, _, Backbone){
  // Above we have passed in jQuery, Underscore and Backbone
  // They will not be accessible in the global scope
  return {};
  // What we return here will be used by other modules
});


text:
'use strict';

angular.module('webClientApp')
  .directive('categoryTopicPicker', ['$rootScope', '$location', 'Category', 'Topic',
      function ($rootScope, $location, Category, Topic) {

    return {
      restrict: 'A',
      templateUrl: 'views/directives/categoryTopicPicker.html',
      scope: {
        visible: '='
      },
      link: function (scope, element) {
        scope.selectedCategory = null;
        scope.categories = Category.query();
        scope.topics = [];
        // scope.allowCreateTopics = false;
        scope.visible = false;

        scope.selectCategory = function(category) {
          scope.selectedCategory = category;
          if (scope.pickOnlyCategory) {
            $rootScope.$emit('categorySelected', {'category': category});
            scope.visible = false;
            scope.selectedCategory = null;
          } else {
            scope.topics = Topic.query({categoryId: category.id});
            element.find('input')[0].focus();
          }
        };

        scope.selectTopic = function(topic) {
          $rootScope.$emit('topicSelected', {'topic': topic});
          scope.visible = false;
          scope.selectedCategory = null;
        };

        var createTopicSuccess = function(resource) {
          scope.topics.push(resource);
          scope.selectTopic(resource);
          scope.newTopic = {};
        };

        var createTopicError = function() {
          swal('حدث خطأ ما', 'الرجاء المحاولة مرة ثانية', 'error');
        };

        scope.saveTopic = function(topic) {
          if(topic && topic.title && topic.title.split(' ').length <= 3) {
            Topic.save({
              'categoryId': scope.selectedCategory.id,
              'topic': topic
            }, createTopicSuccess, createTopicError);
          }
          else {
            swal('موضوع المقال لا يجب ان يتعدى ثلاث كلمات', 'الرجاء تعديل الموضوع','error');
          }
        };

        var getCategoryById = function(id) {
          if (!id) {
            return null;
          }
          for (var i = 0; i < scope.categories.length; i++) {
            if (scope.categories[i].id === id) {
              return scope.categories[i];
            }
          }
        };

        $rootScope.$on('openTopicPicker', function(event, data) {
          if (data && data.category) {
            scope.selectCategory(getCategoryById(data.category.id));
          }
          scope.visible = true;
        });
      }
    };
  }]);


text:
package de.uni_mannheim.informatik.dws.winter.similarity.list;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import de.uni_mannheim.informatik.dws.winter.similarity.SimilarityMeasure;

/**
 * {@link SimilarityMeasure} which calculates the overlap similarity between two
 * lists of strings.
 *
 * @author Oliver Lehmberg (oli@dwslab.de)
 *
 */
public class OverlapSimilarity extends SimilarityMeasure<List<String>> {

	private static final long serialVersionUID = 1L;

	@Override
	public double calculate(List<String> first, List<String> second) {

		Set<String> firstSet = new HashSet<>(first);
		Set<String> secondSet = new HashSet<>(second);

		int min = Math.min(firstSet.size(), secondSet.size());
		int matches = 0;

		if(min==0) {
			return 1.0;
		} else {
			for (String s1 : firstSet) {
				for (String s2 : secondSet) {
					if (s1.equals(s2)) {
						matches++;
						continue;
					}
				}
			}

			return (double) matches / (double) min;
		}
	}

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. Bot. (Morot) sér. 2, 2:207. 1909

#### Original name
null

### Remarks
null


text:
"""
    Comparing refinement with adjoint-flagging vs refinement using
    pressure-flagging, which is the current default.
"""

import os

currentdir = os.getcwd()
adjointdir = currentdir + '/../adjoint'

# Running adjoint problem
os.chdir(adjointdir)
os.system('rm -f .data')
os.system('make new')
os.system('make .plots')

# Run example using pressure flagging
os.chdir(currentdir)
os.system('rm -f .data')
os.system('make new -f Makefile_pflag')
os.system('make .plots -f Makefile_pflag')

# Rename output folders
os.chdir(currentdir)
os.system('rm -r _output_pflag')
os.system('mv _output _output_pflag')
os.system('rm -r _plots_pflag')
os.system('mv _plots _plots_pflag')

# Run example using adjoint method
os.chdir(currentdir)
os.system('rm -f .data')
os.system('make new -f Makefile_compare')
os.system('make .plots -f Makefile_compare')

print 'Finished running example comparing adjoint refinement with divided differences refinement'


text:
/*************************************************************************/
/*  pin_joint_bullet.cpp                                                 */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "pin_joint_bullet.h"

#include "bullet_types_converter.h"
#include "rigid_body_bullet.h"

#include <BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h>

/**
	@author AndreaCatania
*/

PinJointBullet::PinJointBullet(RigidBodyBullet *p_body_a, const Vector3 &p_pos_a, RigidBodyBullet *p_body_b, const Vector3 &p_pos_b) :
		JointBullet() {
	if (p_body_b) {
		btVector3 btPivotA;
		btVector3 btPivotB;
		G_TO_B(p_pos_a * p_body_a->get_body_scale(), btPivotA);
		G_TO_B(p_pos_b * p_body_b->get_body_scale(), btPivotB);
		p2pConstraint = bulletnew(btPoint2PointConstraint(*p_body_a->get_bt_rigid_body(),
				*p_body_b->get_bt_rigid_body(),
				btPivotA,
				btPivotB));
	} else {
		btVector3 btPivotA;
		G_TO_B(p_pos_a, btPivotA);
		p2pConstraint = bulletnew(btPoint2PointConstraint(*p_body_a->get_bt_rigid_body(), btPivotA));
	}

	setup(p2pConstraint);
}

PinJointBullet::~PinJointBullet() {}

void PinJointBullet::set_param(PhysicsServer3D::PinJointParam p_param, real_t p_value) {
	switch (p_param) {
		case PhysicsServer3D::PIN_JOINT_BIAS:
			p2pConstraint->m_setting.m_tau = p_value;
			break;
		case PhysicsServer3D::PIN_JOINT_DAMPING:
			p2pConstraint->m_setting.m_damping = p_value;
			break;
		case PhysicsServer3D::PIN_JOINT_IMPULSE_CLAMP:
			p2pConstraint->m_setting.m_impulseClamp = p_value;
			break;
	}
}

real_t PinJointBullet::get_param(PhysicsServer3D::PinJointParam p_param) const {
	switch (p_param) {
		case PhysicsServer3D::PIN_JOINT_BIAS:
			return p2pConstraint->m_setting.m_tau;
		case PhysicsServer3D::PIN_JOINT_DAMPING:
			return p2pConstraint->m_setting.m_damping;
		case PhysicsServer3D::PIN_JOINT_IMPULSE_CLAMP:
			return p2pConstraint->m_setting.m_impulseClamp;
	}
	// Compiler doesn't seem to notice that all code paths are fulfilled...
	return 0;
}

void PinJointBullet::setPivotInA(const Vector3 &p_pos) {
	btVector3 btVec;
	G_TO_B(p_pos, btVec);
	p2pConstraint->setPivotA(btVec);
}

void PinJointBullet::setPivotInB(const Vector3 &p_pos) {
	btVector3 btVec;
	G_TO_B(p_pos, btVec);
	p2pConstraint->setPivotB(btVec);
}

Vector3 PinJointBullet::getPivotInA() {
	btVector3 vec = p2pConstraint->getPivotInA();
	Vector3 gVec;
	B_TO_G(vec, gVec);
	return gVec;
}

Vector3 PinJointBullet::getPivotInB() {
	btVector3 vec = p2pConstraint->getPivotInB();
	Vector3 gVec;
	B_TO_G(vec, gVec);
	return gVec;
}


text:
shared_examples_for 'does not remove empty strings on error' do
  it 'does not remove empty strings on error' do |example|
    key = 'mock-redis-test:not-a-string'

    method = method_from_description(example)
    args = args_for_method(method).unshift(key)

    @redises.set(key, '')
    lambda do
      @redises.send(method, *args)
    end.should raise_error(RuntimeError)
    @redises.get(key).should == ''
  end
end


text:
import unittest
import sys
import mysql.connector
import inspect

sys.path.append("../src")

from recipient_manager import RecipientManager
from db_connector import DBConnector
from logger import Logger

class TestRecipientManager(unittest.TestCase):

    """
    Provide integration testing for the RecipientManager class. This is a data
    access class so the testing requires the setup of a database to check the
    impact of it's querries on the dataset.

    Tests:
        Add With No Table
        Add With Bad Emails
        Remove With No Table
        Remove With Table But NonexistantRecipient

    Notes:
        As the number of tests increases, this test set could become a
        bottleneck and slow down overall development. Is this starts to happen
        we need to consider setting up a permanant database stored in memory
        instead of rebuilding a datbase with known states for each tests.

        We should also work on decoupling the data from the data access.
        It is possible that we will change the schema as the project progresses
        and this will be eaiser if we are generating the databases instead
        of descrbining the fields from in the code.
    """

    def setUp(self):

        # Database settings.
        self.host = 'localhost'
        self.port = '3306'

        self.test_database_name = "TEST_RECIPIENT_MANAGER_DB"
        self.test_table_name = "TEST_TABLE"
        self.empty_table_name = ""
        self.bad_schema_table = "BAD_SCHEMA_TABLE"

        # Setup connection information that lets the tester
        # setup different states for testing.
        self.connect = mysql.connector.connect(
            user='root', passwd='', host=self.host, port=self.port)
        self.cursor = self.connect.cursor()
        self.db_connector = DBConnector(db_name=self.test_database_name)
        self.logger = Logger()
        self.delete_test_db()

        # Data that will be used for testing.
        self.valid_email1 = "user1@subdomain"
        self.valid_email2 = "user2@subdomain"
        self.invalid_email1 = "baduser"
        self.invalid_email2 = "@subdomain"
        self.long_email = long_email = 'a' * 254 + '@' + 'subdomain'
        self.email_without_domian = "user.com"
        self.email_without_local_name = "@domain.com"

    def tearDown(self):
        self.delete_test_db()
        pass

    def create_table_with_bad_schema(self, table_name=""):
        try:
            self.create_test_db()
            sql = """CREATE TABLE %s (BAD_SCHEMA BIGINT NOT NULL PRIMARY KEY)""" % table_name
            self.cursor.execute(sql)
            self.logger.log_generic_message(
                "Table created: {}".format(table_name))
            return True
        except Exception as err:
            self.logger.log_generic_message(err)
            return False

    def delete_table(self, table_name=""):
        try:
            sql = "DROP TABLE %s" % table_name
            self.cursor.execute(sql)
            self.logger.log_generic_message(
                "Table created: {}".format(table_name))
            return True
        except Exception as err:
            self.logger.log_generic_message(err)
            return False

    def create_test_db(self):
        try:
            sql = "CREATE DATABASE IF NOT EXISTS {} DEFAULT CHARACTER SET 'utf8'".format(
                self.test_database_name)
            self.cursor.execute(sql)
            self.logger.log_generic_message(
                "Database created".format(self.test_database_name))
            self.connect.database = self.test_database_name
        except Exception as err:
            self.logger.log_generic_message(err)
            self.logger.log_generic_message("What happened")

    def delete_test_db(self):
        self.cursor.execute(
            "DROP DATABASE IF EXISTS %s" % self.test_database_name)

    def assert_table_nonexistant(self, table_name=""):
        self.create_test_db()
        sql = "SHOW TABLES LIKE '%s'" % table_name
        self.cursor.execute(sql)
        result = self.cursor.fetchone()
        self.assertIsNone(result)

    def assert_table_exists(self, table_name=""):
        self.create_test_db()
        sql = "SHOW TABLES LIKE '%s'" % table_name
        self.cursor.execute(sql)
        result = self.cursor.fetchone()
        self.assertIsNotNone(result)

    def test_add_to_table_with_bad_schema1(self):
        """
        Test adding a new recipient to a table with an incorrectly defined schema.

        Adding a new recipient to a table with a bad schema should cause the method to return False.

        What To Test:
            1. Assert that the table initially does not exist.
            2. Use external database connection to create database with 1 field that is called BAD_SCHEMA_FIELD instead of email.
            3. Try adding a recipient a normal email address, user@domain.com
            4. Assert that the return from add_recipient is false.
        """
        self.assert_table_nonexistant(self.bad_schema_table)
        self.create_table_with_bad_schema(self.bad_schema_table)
        self.assert_table_exists(self.bad_schema_table)
        manager = RecipientManager(self.bad_schema_table, self.db_connector)
        response = manager.add_recipient(self.valid_email1)
        self.assertFalse(response)
        self.delete_table(self.bad_schema_table)
        self.assert_table_nonexistant(self.bad_schema_table)

    def test_add_single_email_to_table_before_table_has_been_created(self):
        """
        Test adding a recipient to a table that has not been created yet.

        The defined behavior of the recipient manager requires a new table
        be created for adds if it does not exist. After creating the table,
        The add_recipient function should return True.

        Note: I think we create the email before checking if the email is valid.
              We need to change that to pass this test.

        What To Test:
            1. Assert that the table, TEST_TABLE does not exist
            2. Use recipient manager to add a normal email, user@subdomain.com
            3. Assert that the table, TEST_TABLE, now exist.
            4. Assert that add_recipieint() returned True
            4. Query the database and assert the email, user@subdomain.com does exist in table, TEST_TABLE.
            5. Delete the table, TEST_TABLE.
            6. Assert that the table, TEST_TABLE, no longer exists.
        """
        self.assert_table_nonexistant(self.test_table_name)
        manager = RecipientManager(self.test_table_name,self.db_connector)
        response = manager.add_recipient(self.valid_email1)
        self.assertTrue(response)
        self.assertTrue(self.valid_email1 in manager.get_recipients())
        self.assertTrue(manager.delete_recipient_table())
        self.assert_table_nonexistant(self.test_table_name)

    def test_add_email_with_no_domain(self):
        """
        Add an email without a domain. Example: user.com

        Adding a new recipient with a bad email should cause add_recipient to return False.

        What To Test:
            1. Assert that the table, TEST_TABLE does not exist.
            2. Use recipient manager to add an email without a domain, user.com
            3. Assert that the table, TEST_TABLE, still does not exist.
            4. Assert that the call to add_recipient returned false.
         """
        self.assert_table_nonexistant(self.test_table_name)
        manager = RecipientManager(self.test_table_name,self.db_connector)
        response = manager.add_recipient(self.email_without_domian)
        self.assert_table_nonexistant(self.test_table_name)
        self.assertFalse(response)

    def test_add_email_with_no_local_name(self):
        """
        Add an email without a local name. Example: @domain.com

        Adding a new recipient with a bad email should cause add_recipient to return False.

        What To Test:
            1. Assert that the table, TEST_TABLE does not exist.
            2. Use recipient manager to add an email without a domain, @domain.com
            3. Assert that the table, TEST_TABLE, still does not exist.
            4. Assert that the call to add_recipient returned false.
         """
        self.assert_table_nonexistant(self.test_table_name)
        manager = RecipientManager(self.test_table_name,self.db_connector)
        response = manager.add_recipient(self.email_without_local_name)
        self.assert_table_nonexistant(self.test_table_name)
        self.assertFalse(response)

    def test_add_email_that_exceeds_maximum_length(self):
        """
        Add an email that exceeds the maximum length of 254 characters, Example: 'a' * 400 + "@domain.com"

        Adding a new recipient with a long email should cause add_recipient to return False.

        What To Test:
            1. Assert that the table, TEST_TABLE does not exist.
            2. Use recipient manager to add an email that is too long.
            3. Assert that the table, TEST_TABLE, still does not exist.
            4. Assert that the call to add_recipient returned false.
         """
        self.assert_table_nonexistant(self.test_table_name)
        manager = RecipientManager(self.test_table_name,self.db_connector)
        response = manager.add_recipient(self.long_email)
        self.assert_table_nonexistant(self.test_table_name)
        self.assertFalse(response)

    def test_remove_user_from_nonexistant_table(self):
        """
        Remove an email from a table that does not exist.

        Trying to remove a user from a table that does not exist should
        return False.

        NOTE: I do not think this is currently implemented and needs to
        be changed to pass the test.

        What To Test:
            1. Assert that the table, TEST_TABLE does not exist.
            2. Use recipient manager to remove a normal email, user@subdomain.com
            3. Assert that the table, TEST_TABLE, still does not exist.
            4. Assert that the call to remove_recipient returned false.
        """
        self.assert_table_nonexistant(self.test_table_name)
        manager = RecipientManager(self.test_table_name,self.db_connector)
        response = manager.remove_recipient(self.valid_email1)
        self.assertFalse(response)
        self.assert_table_nonexistant(self.test_table_name)

    def test_remove_user_from_table_without_user(self):
        """
        Remove an email from a table that does not have the users email.

        Trying to remove a user from a table without the users email should
        return False.

        What To Test:
            1. Assert that the table, TEST_TABLE does not exist.
            2. Create the table using recipient_manager.
            2. Use recipient manager to remove a normal email, user@subdomain.com
            3. Assert that the table, TEST_TABLE, still does not exist.
            4. Assert that the call to remove_recipient returned false.
        """
        self.assert_table_nonexistant(self.test_table_name)
        manager = RecipientManager(self.test_table_name,self.db_connector)
        self.assertTrue(manager.create_recipient_table())
        response = manager.remove_recipient(self.valid_email1)
        self.assertFalse(response)
        self.assertTrue(manager.delete_recipient_table())
        self.assert_table_nonexistant(self.test_table_name)

    def test_remove_user_from_table_with_user(self):
        """
        Remove an email from a table that does have the users email.

        Removing a user from a table with that user returns True

        What To Test:
            1. Assert that the table, TEST_TABLE does not exist.
            2. Create the table using recipient_manager.
            2. Use recipient manager to add a normal email, user@subdomain.com
            3. Assert that the table, TEST_TABLE, exists.
            5. Assert that the call to add_recipient() returned true.
            6. Assert that the recipient is in the database.
            7. Use remove_recipient() to remove the email from the database.
            8. Assert that the call to remove_reciepient() returned True.
            9. Assert the the user is no longer in the database.
        """
        pass

    def test_create_database_with_empty_string_name(self):
        """
        Try creating a database with an emptry string as the table name.

        Creating a table with an empty string causes mysql to throw
        a syntax exception. The create function should return False.

        What To Test:
            1. Assert that no tables currently exist in the test database.
            2. Create a Recipient Manager with the empty table name as an argument.
            3. Assert that table_exists() function returns False.
            4. Try to create table and assert that the function call returns False.
            5. Assert that there are still no tables in the test database.
        """
        pass

    def test_get_users_from_nonexistant_table(self):
        """
        Try getting the users from a table that does not exist.

        Calling get_recipients() when the table has not been created should
        return an empty list.

        What To Test:
            1. Asset that the table, TEST_TABLE does not exist.
            2. Assert that call to get_recipients() returns an empty list.
            3. Assert that the table, TEST_TABLE still does not exist.
        """
        pass

    def test_get_users_from_table_that_exists_with_no_users(self):
        """
        Try getting users from a table with no users.

        Calling get_recipient() when the table has been created but has
        no users should return an empty list.

        What To Test:
            1. Assert that the table, TEST_TABLE does not exist.
            2. Create the table.
            3. Assert the table exists.
            4. Assert the the call to get_recipients() returns an empty list.
        """
        pass

    def test_get_users_from_table_with_single_user(self):
        """
        Try getting users from a table with a single user.

        Calling get_recipient() when the table has 1 user should
        return that one user in a list.

        What To Test:
            1. Assert that the table, TEST_TABLE does not exist.
            2. Create the table.
            3. Assert the table exists.
            4. Add a user to the table. Assert the call to add_recipient returns True
            5. Assert the the call to get_recipients() returns a list containing the recipient.
        """
        pass

    def test_get_users_from_table_with_two_users(self):
        """
        Test getting users from a table with two users.

        Calling get_recipient() when the table has 2 emails should
        return a list with both of those emails.

        What To Test:
            1. Assert that the table, TEST_TABLE does not exist.
            2. Create the table.
            3. Assert the table exists.
            4. Add a user to the table. Assert the call to add_recipient returns True
            5. Assert the the call to get_recipients() returns a list containing the recipient.
            6. Add another user to the table with a different email. Assert the call to add_recipeint returns True
            7. Assser that the call to get_recipients() returns a list containing both emails.
        """
        pass

    def test_delete_nonexistant_table(self):
        """
        Test deleteting a table from a database that does not exist.

        Deleting a table that does not exist should return False.

        What To Test:
            1. Assert that the table, TEST_TABLE, does not exist.
            2. Try to delete the table.
            3. Assert that the delete_table response returns False.

        """
        pass

    def test_delete_existant_but_empty_table(self):
        """
        Test deleteing a table that exists but has no users.

        Delete a table with no users should delete the table and return True

        What To Test:
            1. Assert that the table, TEST_TABLE, does not exist.
            2. Create the table. Assert that create_table returns True
            3. Delete the table. Assert that delete_table returns True
        """
        pass

    def test_delete_existant_table_with_user(self):
        """
        Test deleteing a table that has a user in it.

        Deleting a table with a user should delete the table and return True

        What To Test:
            1. Assert that the table, TEST_TABLE does not exist.
            2. Create the table. Assert that create_table returns True
            3. Add a user with a normal email to the table. Assert that add_recipient returns True.
            4. Assert that the table is in the table.
            5. Delete the table. Assert that delete_table returns True.
        """
        pass

if __name__ == '__main__':
    unittest.main()


text:
title: Cordova Troubleshooting and Tips
---

## Browser Simulator
Use Google Chrome's emulator from Developer Tools. It's a fantastic tool. You can select which device to emulate, but keep in mind that it's an *emulator* and not the real deal.

> **IMPORTANT**
> Also, if you change from desktop to mobile emulator or backwards, hit the refresh button as Quasar Platform detection is not dynamic (nor it should be).

![Google Chrome emulator](/images/browser-simulator.png "Google Chrome emulator")

## Android Tips

### Remote Debugging

If you are debugging Android Apps, you can use Google Chrome [Remote Debugging](https://developers.google.com/web/tools/chrome-devtools/debug/remote-debugging/remote-debugging?hl=en) through a USB cable attached to your Android phone/tablet. It can be used for emulator too.

This way you have Chrome Dev Tools directly for your App running on the emulator/phone/table. Inspect elements, check console output, and so on and so forth.

![Android Remote Debugging](/images/remote-debug.png "Android Remote Debugging")
![Android Remote Debugging](/images/remote-debug-2.png "Android Remote Debugging")

### Android SDK not found after installation of the SDK

Some newer Debian-based OS (e.g. ubuntu, elementary OS) might leave you with a `Android SDK not found.` after you installed and (correctly) configured the environment. The output might look similar to this:

``` bash
$ cordova requirements

Requirements check results for android:
Java JDK: installed 1.8.0
Android SDK: installed true
Android target: not installed
Android SDK not found. Make sure that it is installed. If it is not at the default location, set the ANDROID_HOME environment variable.
Gradle: not installed
Could not find gradle wrapper within Android SDK. Might need to update your Android SDK.
Looked here: /home/your_user/Android/Sdk/tools/templates/gradle/wrapper
Error: Some of requirements check failed
```

This could have two different reasons: Usually the paths aren't configured correctly. The first step is to verify if your paths are set correctly. This can be done by running the following commands:

``` bash
$ echo $ANDROID_HOME
```

The expected output should be a path similar to this `$HOME/Android/Sdk`. After this run:

``` bash
$ ls -la $ANDROID_HOME
```

To ensure the folder contains the SDK. The expected output should contain folders like 'tools', 'sources', 'platform-tools', etc.

``` bash
$ echo $PATH
```

The output should contain each one entry for the Android SDK 'tools'-folder and 'platform-tools'-tools. This could look like this:

``` bash
/home/your_user/bin:/home/your_user/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/your_user/Android/Sdk/tools:/home/your_user/Android/Sdk/platform-tools
```

> If you ensured your paths are set correctly and still get the error on `cordova requirements` you can try the following fix: [Replacing the Android Studio 'tools' folder manually](https://github.com/meteor/meteor/issues/8464#issuecomment-288112504)

### Setting Up Device on Linux

You may bump into `?????? no permissions` problem when trying to run your App directly on an Android phone/tablet.

Here's how you fix this:

``` bash
# create the .rules file and insert the content
# from below this example
sudo vim /etc/udev/rules.d/51-android.rules
sudo chmod 644   /etc/udev/rules.d/51-android.rules
sudo chown root. /etc/udev/rules.d/51-android.rules
sudo service udev restart
sudo killall adb
```

The content for `51-android.rules`:
```
SUBSYSTEM=="usb", ATTRS{idVendor}=="0bb4", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0e79", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0502", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0b05", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="413c", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0489", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="091e", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="18d1", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0bb4", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="12d1", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="24e3", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="2116", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0482", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="17ef", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1004", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="22b8", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0409", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="2080", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0955", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="2257", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="10a9", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1d4d", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0471", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="04da", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="05c6", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1f53", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="04e8", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="04dd", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0fce", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0930", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="19d2", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1bbb", MODE="0666"
```

Now running `adb devices` should discover your device.

## iOS Tips

### Remote Debugging

If you are debugging iOS Apps, you can use the Safari developer tools to remotely debug through a USB cable attached to your iOS phone/tablet. It can be used for emulator too.

This way you have Safari developer tools directly for your App running on the emulator/phone/table. Inspect elements, check console output, and so on and so forth.

First enable the "developer" menu option in the Settings of Safari. Then if you navigate to the "developer" menu option you will see your emulator or connected device listed near the top. From here you can open the developer tools.

### Status bar and notch safe-areas

Since mobile phones have a status bar and/or notches, your app's styling might need some tweaking when building on Cordova. In order to prevent parts of your app from going behind the status bar, there is a global CSS variable that can be used for creating a "safe-area". This variable can then be applied in your app's top and bottom padding or margin.

Quasar has [support for these CSS safe-areas](https://github.com/quasarframework/quasar/search?q=safe-area-inset-top&unscoped_q=safe-area-inset-top) by default in Layout Header/Footer and Notify. However it's important to always check your Cordova build on several models to see if all cases of your app are dealing with the safe areas correctly.

In cases you need to manually tweak your CSS you can do so with:
```stylus
// for your app's header
padding-top constant(safe-area-inset-top) // for iOS 11.0
padding-top env(safe-area-inset-top) // for iOS 11.2 +
// for your app's footer
padding-bottom constant(safe-area-inset-bottom)
padding-bottom env(safe-area-inset-bottom)
```
Of course you can also use the above example with `margin` instead of `padding` depending on your app.

In order to make sure these are only added when opened on mobile via the Cordova build, you can check for the CSS class `.cordova` which is automatically added to the body by Quasar. Eg.

```stylus
body.cordova .my-selector
  padding-top constant(safe-area-inset-top)
  padding-top env(safe-area-inset-top)
```

### Disabling iOS rubber band effect

When building an iOS app with Cordova and you want to disable the rubber band effect (https://www.youtube.com/watch?v=UjuNGpU29Mk), add this to your `/src-cordova/config.xml`:

``` xml
<preference name = "DisallowOverscroll" value = "true" />
```


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <Button
        android:id="@+id/left"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="select data" />

    <Button
        android:id="@+id/operator"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="select operator" />

    <Button
        android:id="@+id/right"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="select data" />

    <!--
         <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="name" />
    -->

    <Button
        android:id="@+id/ok"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:enabled="false"
        android:text="OK" />

</LinearLayout>


text:
layout: page
title: Joe Glenn's 82nd Birthday
date: 2016-05-24
author: Angela Black
tags: weekly links, java
status: published
summary: Nunc id justo sem. Nunc.
banner: images/banner/wedding.jpg
booking:
  startDate: 08/24/2016
  endDate: 08/25/2016
  ctyhocn: CLOHXHX
  groupCode: JG8B
published: true
---
Cras vulputate odio ut tortor ullamcorper iaculis. Fusce eu sollicitudin odio. Aliquam dui eros, posuere sed odio viverra, posuere euismod ipsum. Maecenas bibendum mauris pharetra magna posuere efficitur. Sed pellentesque lorem dui, quis consequat tellus efficitur non. Cras gravida euismod erat, vitae vulputate magna suscipit id. Morbi arcu urna, mattis quis convallis non, fringilla quis dolor. Mauris vel leo sed nunc elementum blandit sed ut mauris. Mauris at ullamcorper nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

1 Sed ultrices eros ut dignissim pellentesque
1 Donec ac neque eu tellus porta convallis
1 Vestibulum dapibus dolor eget sagittis varius
1 Donec vel metus dictum, suscipit elit eget, viverra dui
1 Morbi nec felis venenatis, fermentum odio eleifend, congue neque.

Nam egestas sapien ac diam sagittis, ut dapibus odio molestie. Phasellus a lacinia erat. Praesent gravida dapibus libero vel lacinia. Mauris vel purus id tellus pulvinar mattis. Maecenas nec ex cursus, elementum urna eget, eleifend lectus. Morbi interdum varius purus, a maximus tortor blandit ut. Donec vitae ex at ipsum scelerisque interdum. Donec feugiat enim id lacus pretium elementum. Aliquam sit amet posuere justo, quis dapibus eros.


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateFavoritesTable extends Migration
{
	public function up()
	{
		Schema::create('forum_favorites', function (Blueprint $table) {
			$table->bigIncrements('id');
			$table->integer('user_id')->unsigned();
			$table->integer('favorited_id')->unsigned();
			$table->string('favorited_type', 50);
			$table->timestamps();

			$table->unique(['user_id', 'favorited_id', 'favorited_type']);
		});
	}

	public function down()
	{
		Schema::dropIfExists('forum_favorites');
	}
}


text:
namespace biosim {
  namespace tools {
    // exception specific for file formats
    struct unknown_file_format : std::runtime_error {
      explicit unknown_file_format(std::string const &__filename)
          : std::runtime_error("File format not recognized for: " + __filename) {}
    }; // struct unknown_file_format

    // file io specific functions
    class file {
    public:
      // read full content of file of given filename, return a list of strings for each line
      static std::list<std::string> read_to_string_list(std::string const &__filename);
    }; // class file
  } // namespace tools
} // namespace biosim

#endif // tools_file_h


text:
/*jslint node: true */
"use strict";
module.exports = function(grunt) {
    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        jshint: {
            options: {
                laxcomma: true
                , laxbreak: true
                , strict: true
                , globals: { 'require': false
                             , 'describe': false
                             , 'it': false
                             , 'exports': false
                             , 'before': false
                           }
            }
            , all: [ '*.js', 'src/*.js', 'test/*.js']
        }
    });

    // Load the plugin that provides the "uglify" task.
    grunt.loadNpmTasks('grunt-contrib-jshint');

    // Default task(s).
    grunt.registerTask('default', ['jshint']);

};


text:
 Defines the height of the Image Rendition for the current Publishing site, required attribute.

**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Model](OfficeDevPnP.Core.Framework.Provisioning.Model.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public int Height { get; set; }
```

### Property Value
Type: System.Int32

## See also
- [ImageRendition](OfficeDevPnP.Core.Framework.Provisioning.Model.ImageRendition.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Model](OfficeDevPnP.Core.Framework.Provisioning.Model.md)