text:
<?php

namespace Greggilbert\Recaptcha;

interface RecaptchaInterface
{
    /**
	 * Call out to reCAPTCHA and process the response
	 * @param string $challenge
	 * @param string $response
	 * @return bool
	 */
	public function check($challenge, $response);

    /**
     * Return template to render for reCAPTCHA
     * Note that this will be prepended with recaptcha::
     * @return string
     */
    public function getTemplate();

    /**
     * Return response key as specified in view.
     * @return string
     */
    public function getResponseKey();
}


text:
sequence()
----

Creates an Asynchronous Stack which execute each enqueued method after the previous function calls the provided `next(err, data [, ...])`.

**Core**

  * `Futures.sequence(globalContext=null)`
  * `then(next, err, data [, ...])` - add a method onto the queue
    * begins or resumes the queue
    * passes the results of the previous function into the next

**Example:**

    var sequence = Futures.sequence(),
      err;

    sequence
      .then(function (next) {
        setTimeout(function () {
          next(err, "Hi", "World!");
        }, 120);
      })
      .then(function (next, err, a, b) {
        setTimeout(function () {
          next(err, "Hello", b);
        }, 270);
      })
      .then(function (next, err, a, b) {
        setTimeout(function () {
          console.log(a, b);
          next();
        }, 50);
      });

redpajama_set_name: RedPajamaGithub


text:
@implementation NotificationsMethods
- (void)setupNotifications {
    UIMutableUserNotificationAction *textAction = [[UIMutableUserNotificationAction alloc] init];
    textAction.identifier = @"quickreply_action";
    textAction.title = @"Quick Reply";
    textAction.activationMode = UIUserNotificationActivationModeForeground;
    textAction.authenticationRequired = YES;
    textAction.behavior = UIUserNotificationActionBehaviorTextInput;

    UIMutableUserNotificationCategory *category = [[UIMutableUserNotificationCategory alloc]init];
    category.identifier = @"category_qr";
    [category setActions:@[textAction] forContext:UIUserNotificationActionContextMinimal];
    NSSet *categories = [NSSet setWithObjects:category, nil];

    UIUserNotificationType types = UIUserNotificationTypeAlert | UIUserNotificationTypeSound |UIUserNotificationTypeBadge;
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types
                                                                             categories:categories];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];

}
- (void)presentNotificationNow {
    UILocalNotification *reminder = [[UILocalNotification alloc] init];
    reminder.alertBody = @"Received new alert";
    reminder.alertTitle = @"QuickReply Demo";
    reminder.category = @"category_qr";
    [[UIApplication sharedApplication] presentLocalNotificationNow:reminder];
}
@end


text:
using System;
using Lex.Db.Serialization;

namespace Lex.Db
{
  public class DbTests3: IDisposable
  {
    DbInstance db;
    DbTable<AData> table;

    DbInstance Prepare()
    {
      var db = new DbInstance("MyDatabase3");
      db.Map<AData, PrototypeBasedData>().Automap(i => i.Id, true);
      db.Initialize();
      return db;
    }

    public DbTests3()
    {
      PurgeDb();
    }

    public void Dispose()
    {
      CleanUp();
    }

    public void PurgeDb()
    {
      using (var i = Prepare())
        i.Purge();

      db = Prepare();
      table = db.Table<AData>();
    }

    public void CleanUp()
    {
      db.Purge();
      db.Dispose();
    }

    public void Indexing3()
    {
      var db = new DbInstance(@"MyDatabase3\Indexing");

      db.Map<AData, PrototypeBasedData>().Automap(i => i.Id, true)
        .WithIndex("LastName", i => i.Name, StringComparer.CurrentCulture)
        .WithIndex("LastNameText", i => i.Name, StringComparer.CurrentCultureIgnoreCase);
      db.Initialize();

      var table = db.Table<AData>();
      table.Purge();

      db.BulkWrite(() =>
      {
        for (var s = 0; s < 100; s++)
          for (var i = 0; i < 10; i++)
            table.Save(new PrototypeBasedData { Name = "Test" + i });

        for (var s = 0; s < 100; s++)
          for (var i = 0; i < 10; i++)
            table.Save(new PrototypeBasedData { Name = "TeST" + i });
      });

      var list1count = table.IndexQueryByKey("LastName", "Test5").Count();
      var list2count = table.IndexQueryByKey("LastNameText", "TEst5").Count();

      Assert.AreEqual(list1count, 100);
      Assert.AreEqual(list2count, 200);
    }

    public void LoadData3()
    {
      var table = db.Table<AData>();
      var items = table.LoadAll();
    }

    public void SaveData3()
    {
      var swatch = DateTime.Now;

      db.BulkWrite(() =>
      {
        table.Purge();
        var key = 1;
        var newObj = new PrototypeBasedData { Id = key, Name = "test" };
        table.Save(newObj);

        var obj = table.LoadByKey(key);

        Assert.AreEqual(newObj.Name, obj.Name);
#if !(NETFX_CORE || WINDOWS_PHONE)
        TestContext.WriteLine("Completed: " + (DateTime.Now - swatch).TotalMilliseconds);
#endif
      });
    }

    public class Person
    {
      public int PersonID;
      public string Forename, Surname;
    }

    public void TestGordon()
    {
      var db = new DbInstance("gordon.db");
      db.Map<Person>().Automap(i => i.PersonID, true).WithIndex("Surname", i => i.Surname);
      db.Initialize();

      var table = db.Table<Person>();

      table.Purge();

      Person newPerson1 = new Person { Forename = "Joe", Surname = "Bloggs" };
      Person newPerson2 = new Person { Forename = "James", Surname = "Smith" };
      Person newPerson3 = new Person { Forename = "David", Surname = "Peterson" };
      Person newPerson4 = new Person { Forename = "Steve", Surname = "Gordon" };
      Person newPerson5 = new Person { Forename = "David", Surname = "Gordon" };
      Person newPerson6 = new Person { Forename = "Colin", Surname = "Gordon" };
      Person newPerson7 = new Person { Forename = "Michael", Surname = "Gordon" };

      var newPeople = new[]
      {
        newPerson1,
        newPerson2,
        newPerson3,
        newPerson4,
        newPerson5,
        newPerson6,
        newPerson7
      };

      table.Save(newPeople);

      var index = table.IndexQuery<string>("Surname");
      // HIJKLMNOPQRS

      var queryindex = index.GreaterThan("H", true).LessThan("T", true).ToLazyList();
      Assert.AreEqual(2, queryindex.Count);
    }

    public static void RunTests()
    {
      using (var t = new DbTests3())
        t.Indexing3();

      using (var t = new DbTests3())
        t.LoadData3();

      using (var t = new DbTests3())
        t.SaveData3();

      using (var t = new DbTests3())
        t.TestGordon();
    }
  }

  public struct Point
  {
    public int X, Y;
  }

  public class PointSerializer
  {
    public static Point ReadPoint(DataReader reader)
    {
      return new Point { X = reader.ReadInt32(), Y = reader.ReadInt32() };
    }

    public static void WritePoint(DataWriter writer, Point point)
    {
      writer.Write(point.X);
      writer.Write(point.Y);
    }
  }

  public static class Assert
  {
    public static void AreEqual(object expected, object value)
    {
      if (!Equals(expected, value))
        throw new InvalidOperationException();
    }

    public static void Fail(string message)
    {
      throw new InvalidOperationException(message);
    }

    public static void IsTrue(bool condition)
    {
      if (!condition)
        throw new InvalidOperationException();
    }

    public static void AreNotEqual(object expected, object value)
    {
      if (Equals(expected, value))
        throw new InvalidOperationException();
    }
  }
}


text:
#include "stdafx.h"

// textures/checkerboard.cpp*
#include "textures/checkerboard.h"

// CheckerboardTexture Method Definitions
Texture<Float> *CreateCheckerboardFloatTexture(const Transform &tex2world,
                                               const TextureParams &tp) {
    int dim = tp.FindInt("dimension", 2);
    if (dim != 2 && dim != 3) {
        Error("%d dimensional checkerboard texture not supported", dim);
        return nullptr;
    }
    std::shared_ptr<Texture<Float>> tex1 = tp.GetFloatTexture("tex1", 1.f);
    std::shared_ptr<Texture<Float>> tex2 = tp.GetFloatTexture("tex2", 0.f);
    if (dim == 2) {
        // Initialize 2D texture mapping _map_ from _tp_
        std::unique_ptr<TextureMapping2D> map;
        std::string type = tp.FindString("mapping", "uv");
        if (type == "uv") {
            Float su = tp.FindFloat("uscale", 1.);
            Float sv = tp.FindFloat("vscale", 1.);
            Float du = tp.FindFloat("udelta", 0.);
            Float dv = tp.FindFloat("vdelta", 0.);
            map.reset(new UVMapping2D(su, sv, du, dv));
        } else if (type == "spherical")
            map.reset(new SphericalMapping2D(Inverse(tex2world)));
        else if (type == "cylindrical")
            map.reset(new CylindricalMapping2D(Inverse(tex2world)));
        else if (type == "planar")
            map.reset(new PlanarMapping2D(
                tp.FindVector3f("v1", Vector3f(1, 0, 0)),
                tp.FindVector3f("v2", Vector3f(0, 1, 0)),
                tp.FindFloat("udelta", 0.f), tp.FindFloat("vdelta", 0.f)));
        else {
            Error("2D texture mapping \"%s\" unknown", type.c_str());
            map.reset(new UVMapping2D);
        }

        // Compute _aaMethod_ for _CheckerboardTexture_
        std::string aa = tp.FindString("aamode", "closedform");
        AAMethod aaMethod;
        if (aa == "none")
            aaMethod = AAMethod::None;
        else if (aa == "closedform")
            aaMethod = AAMethod::ClosedForm;
        else {
            Warning(
                "Antialiasing mode \"%s\" not understood by "
                "Checkerboard2DTexture; using \"closedform\"",
                aa.c_str());
            aaMethod = AAMethod::ClosedForm;
        }
        return new Checkerboard2DTexture<Float>(std::move(map), tex1, tex2,
                                                aaMethod);
    } else {
        // Initialize 3D texture mapping _map_ from _tp_
        std::unique_ptr<TextureMapping3D> map(new IdentityMapping3D(tex2world));
        return new Checkerboard3DTexture<Float>(std::move(map), tex1, tex2);
    }
}

Texture<Spectrum> *CreateCheckerboardSpectrumTexture(const Transform &tex2world,
                                                     const TextureParams &tp) {
    int dim = tp.FindInt("dimension", 2);
    if (dim != 2 && dim != 3) {
        Error("%d dimensional checkerboard texture not supported", dim);
        return nullptr;
    }
    std::shared_ptr<Texture<Spectrum>> tex1 =
        tp.GetSpectrumTexture("tex1", 1.f);
    std::shared_ptr<Texture<Spectrum>> tex2 =
        tp.GetSpectrumTexture("tex2", 0.f);
    if (dim == 2) {
        // Initialize 2D texture mapping _map_ from _tp_
        std::unique_ptr<TextureMapping2D> map;
        std::string type = tp.FindString("mapping", "uv");
        if (type == "uv") {
            Float su = tp.FindFloat("uscale", 1.);
            Float sv = tp.FindFloat("vscale", 1.);
            Float du = tp.FindFloat("udelta", 0.);
            Float dv = tp.FindFloat("vdelta", 0.);
            map.reset(new UVMapping2D(su, sv, du, dv));
        } else if (type == "spherical")
            map.reset(new SphericalMapping2D(Inverse(tex2world)));
        else if (type == "cylindrical")
            map.reset(new CylindricalMapping2D(Inverse(tex2world)));
        else if (type == "planar")
            map.reset(new PlanarMapping2D(
                tp.FindVector3f("v1", Vector3f(1, 0, 0)),
                tp.FindVector3f("v2", Vector3f(0, 1, 0)),
                tp.FindFloat("udelta", 0.f), tp.FindFloat("vdelta", 0.f)));
        else {
            Error("2D texture mapping \"%s\" unknown", type.c_str());
            map.reset(new UVMapping2D);
        }

        // Compute _aaMethod_ for _CheckerboardTexture_
        std::string aa = tp.FindString("aamode", "closedform");
        AAMethod aaMethod;
        if (aa == "none")
            aaMethod = AAMethod::None;
        else if (aa == "closedform")
            aaMethod = AAMethod::ClosedForm;
        else {
            Warning(
                "Antialiasing mode \"%s\" not understood by "
                "Checkerboard2DTexture; using \"closedform\"",
                aa.c_str());
            aaMethod = AAMethod::ClosedForm;
        }
        return new Checkerboard2DTexture<Spectrum>(std::move(map), tex1, tex2,
                                                   aaMethod);
    } else {
        // Initialize 3D texture mapping _map_ from _tp_
        std::unique_ptr<TextureMapping3D> map(new IdentityMapping3D(tex2world));
        return new Checkerboard3DTexture<Spectrum>(std::move(map), tex1, tex2);
    }
}


text:
<?php

namespace Alchemy\core\query;
use Alchemy\core\Element;

/**
 * Class for composing expressions
 */
class Expression extends Element {

    protected $elements = array();

    public static function __callStatic($name, $args) {
        $def = self::get_definition(trim(strtolower($name), '_'));
        $elements = (isset($args[0]) && is_array($args[0])) ? $args[0] : $args;

        return new $def['tags']['element.class']($def['tags']['element.type'], $elements);
    }

    public function __construct($type, array $elements) {
        parent::__construct($type);
        $cls = get_called_class();

        $def = self::get_definition($type);
        $tag = $def['tags']['expr.element'];

        if ($def['arity'] != -1 && $def['arity'] != count($elements)) {
            throw new \Exception("{$cls} '{$type}': Expected {$def['arity']} elements, got " . count($elements));
        }

        foreach ($elements as $element) {
            if (!$element->getTag($tag)) {
                throw new \Exception("{$cls} '{$type}': Expected '{$tag}' at position {$key}");
            }
        }

        $this->elements = $elements;
    }

    public function getDescription($maxdepth = 3, $curdepth = 0) {
        $str = parent::getDescription($maxdepth, $curdepth);

        if ($curdepth <= $maxdepth) {
            $i = str_repeat('  ', $curdepth);
            $elements = array();
            foreach($this->elements as $element) {
                $elements[] = $element->getDescription($maxdepth, $curdepth + 1);
            }

            $str .= " [\n$i  ".implode(",\n$i  ", $elements)."\n$i]";
        }

        return $str;
    }

    public function elements() {
        return $this->elements;
    }

    /**
     * Recursively get all scalar parameters used by this expression
     *
     * @return array array(Scalar, Scalar, ...)
     */
    public function parameters() {
        $params = array();

        foreach ($this->elements as $element) {
            if (method_exists($element, 'parameters')) {
                $params = array_merge($params, $element->parameters());
            }
        }

        return $params;
    }

    public function tables() {
        $tables = array();

        foreach($this->elements as $element) {
            if ($element instanceof Expression) {
                $tables += $element->tables();
            } elseif ($element instanceof ColumnRef) {
                $tables[$element->table()->getID()] = $element->table();
            }
        }

        return $tables;
    }
}


text:
using UnityEngine;
using System.Collections;

public class LightController : MonoBehaviour
{
		public static LightController instance;
		public Light roomLight1;
		public Light roomLight2;
		public float targetIntensity1;
		public float targetIntensity2;
		public Color ambientLightSave;
		public float time = 10;
		public string readyLevel;

		void Awake ()
		{
				instance = this;
		}

		void Start ()
		{

				ambientLightSave = RenderSettings.ambientLight;
				RenderSettings.ambientLight = new Color (0, 0, 0, 0);

				targetIntensity1 = roomLight1.intensity;
				roomLight1.intensity = 0;
				targetIntensity2 = roomLight2.intensity;
				roomLight2.intensity = 0;
				StartCoroutine (lightsOn ());
		}

		IEnumerator lightsOn ()
		{
				float startTime = Time.time;
				while (Time.time - startTime < time) {
						RenderSettings.ambientLight = Color.Lerp (new Color (0, 0, 0, 0), ambientLightSave, Mathf.Pow (((Time.time - startTime) / time), 3));
						roomLight1.intensity = targetIntensity1 * Mathf.Pow (((Time.time - startTime) / time), 3);
						roomLight2.intensity = targetIntensity2 * Mathf.Pow (((Time.time - startTime) / time), 3);
						yield return null;
				}
		}

		public void callLightsOut ()
		{
				StartCoroutine (lightsOut ());
		}

		IEnumerator lightsOut ()
		{
				float startTime = Time.time;
				while (Time.time - startTime < time) {
						RenderSettings.ambientLight = Color.Lerp (ambientLightSave, new Color (0, 0, 0, 0), Mathf.Pow (((Time.time - startTime) / time), 3));
						roomLight1.intensity = targetIntensity1 * (1 - Mathf.Pow (((Time.time - startTime) / time), 3));
						roomLight2.intensity = targetIntensity2 * (1 - Mathf.Pow (((Time.time - startTime) / time), 3));
						yield return null;
				}
				Application.LoadLevel (readyLevel);
		}

}


text:
(function(window, document, undefined) {

	// data specifically for the collaboration page
	var collaborationsData = {
		header: "Collaborations",
		description: "Providing analytic consulting to collegiate and professional sports teams. Our partners:",
		navbarTitle: "Collaborations",
		collaborations: [
			{
				partner: "San Jose Sharks",
				image: "images/collaborations/san-jose-sharks.png"
			},
			{
				partner: "Stanford Women's Volleyball",
				image: "images/collaborations/stanford_womens_vball.jpg"
			},
			{
				partner: "Stanford Football",
				image: "images/collaborations/stanford_football.jpg"
			},
			{
				partner: "Stanford Baseball",
				image: "images/collaborations/stanford_bball.jpg"
			},
			{
				partner: "Stanford Men's Basketball",
				image: "images/collaborations/stanford-men-basketball.jpg"
			}
		]
	};

	// Handlebars template for the collaborations page
	var collaborationsTemplate = [
		'{{#each pageData.collaborations}}',
			'
',
				'
{{ partner }}
',
				'',
				'
',
			'
',
		'{{/each}}'
	].join('\n');

	// populate page with the above data
	populatePage(collaborationsTemplate, collaborationsData);

})(this, this.document);


text:
"""
mbed SDK
Copyright (c) 2011-2014 ARM Limited

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Author: Przemyslaw Wirkus <Przemyslaw.wirkus@arm.com>
"""

from tools.utils import construct_enum, mkdir
from prettytable import PrettyTable
import os

ResultExporterType = construct_enum(HTML='Html_Exporter',
                                    JUNIT='JUnit_Exporter',
                                    JUNIT_OPER='JUnit_Exporter_Interoperability',
                                    BUILD='Build_Exporter',
                                    TEXT='Text_Exporter',
                                    PRINT='Print_Exporter')

class ReportExporter(object):
    """ Class exports extended test result Python data structure to
        different formats like HTML, JUnit XML.

    Parameter 'test_result_ext' format:

    u'uARM': {   u'LPC1768': {   'MBED_2': {   0: {   'copy_method': 'shutils.copy()',
                                                      'duration': 20,
                                                      'elapsed_time': 1.7929999828338623,
                                                      'output': 'Host test instrumentation on ...\r\n',
                                                      'result': 'OK',
                                                      'target_name': u'LPC1768',
                                                      'description': 'stdio',
                                                      'id': u'MBED_2',
                                                      'toolchain_name': u'uARM'}},
    """
    CSS_STYLE = """
                """

    JAVASCRIPT = """

                 """

    def __init__(self, result_exporter_type, package="test"):
        self.result_exporter_type = result_exporter_type
        self.package = package

    def report(self, test_summary_ext, test_suite_properties=None,
               print_log_for_failures=True):
        """ Invokes report depending on exporter_type set in constructor
        """
        if self.result_exporter_type == ResultExporterType.HTML:
            # HTML exporter
            return self.exporter_html(test_summary_ext, test_suite_properties)
        elif self.result_exporter_type == ResultExporterType.JUNIT:
            # JUNIT exporter for results from test suite
            return self.exporter_junit(test_summary_ext, test_suite_properties)
        elif self.result_exporter_type == ResultExporterType.JUNIT_OPER:
            # JUNIT exporter for interoperability test
            return self.exporter_junit_ioper(test_summary_ext, test_suite_properties)
        elif self.result_exporter_type == ResultExporterType.PRINT:
            # JUNIT exporter for interoperability test
            return self.exporter_print(test_summary_ext, print_log_for_failures=print_log_for_failures)
        elif self.result_exporter_type == ResultExporterType.TEXT:
            return self.exporter_text(test_summary_ext)
        return None

    def report_to_file(self, test_summary_ext, file_name, test_suite_properties=None):
        """ Stores report to specified file
        """
        report = self.report(test_summary_ext, test_suite_properties=test_suite_properties)
        self.write_to_file(report, file_name)

    def write_to_file(self, report, file_name):
        if report is not None:
            dirname = os.path.dirname(file_name)
            if dirname:
                mkdir(dirname)
            with open(file_name, 'w') as f:
                f.write(report)

    def get_tooltip_name(self, toolchain, target, test_id, loop_no):
        """ Generate simple unique tool-tip name which can be used.
            For example as HTML
 section id attribute.
        """
        return "target_test_%s_%s_%s_%s"% (toolchain.lower(), target.lower(), test_id.lower(), loop_no)

    def get_result_div_sections(self, test, test_no):
        """ Generates separate
 sections which contains test results output.
        """

        RESULT_COLORS = {'OK': 'LimeGreen',
                         'FAIL': 'Orange',
                         'ERROR': 'LightCoral',
                         'OTHER': 'LightGray',
                        }

        tooltip_name = self.get_tooltip_name(test['toolchain_name'], test['target_name'], test['id'], test_no)
        background_color = RESULT_COLORS[test['result'] if test['result'] in RESULT_COLORS else 'OTHER']
        result_div_style = "background-color: %s"% background_color

        result = """

                       %s

                       %s

                       %s in %.2f sec

                       %s

                 """% (result_div_style,
                       tooltip_name,
                       tooltip_name,
                       test['result'],
                       tooltip_name,
                       test['target_name_unique'],
                       test['description'],
                       test['elapsed_time'],
                       test['output'].replace('\n', '
'))
        return result

    def get_result_tree(self, test_results):
        """ If test was run in a loop (we got few results from the same test)
            we will show it in a column to see all results.
            This function produces HTML table with corresponding results.
        """
        result = ''
        for i, test_result in enumerate(test_results):
            result += '
'
            test_ids = sorted(test_result.keys())
            for test_no in test_ids:
                test = test_result[test_no]
                result += """

                                 %s

"""% self.get_result_div_sections(test, "%d_%d" % (test_no, i))
            result += '
'
        return result

    def get_all_unique_test_ids(self, test_result_ext):
        """ Gets all unique test ids from all ran tests.
            We need this to create complete list of all test ran.
        """
        result = []
        targets = test_result_ext.keys()
        for target in targets:
            toolchains = test_result_ext[target].keys()
            for toolchain in toolchains:
                tests = test_result_ext[target][toolchain].keys()
                result.extend(tests)
        return sorted(list(set(result)))

    #
    # Exporters functions
    #

    def exporter_html(self, test_result_ext, test_suite_properties=None):
        """ Export test results in proprietary HTML format.
        """
        result = """

                        <title>mbed SDK test suite test result report</title>
                        %s
                        %s

                 """% (self.CSS_STYLE, self.JAVASCRIPT)

        unique_test_ids = self.get_all_unique_test_ids(test_result_ext)
        targets = sorted(test_result_ext.keys())
        result += '
'
        for target in targets:
            toolchains = sorted(test_result_ext[target].keys())
            for toolchain in toolchains:
                result += '
'
                result += '	'
                result += '	'

                tests = sorted(test_result_ext[target][toolchain].keys())
                for test in unique_test_ids:
                    result += """%s	"""% test
                result += """

                              %s
                              %s
                          """% (toolchain, target)

                for test in unique_test_ids:
                    test_result = self.get_result_tree(test_result_ext[target][toolchain][test]) if test in tests else ''
                    result += '%s	'% (test_result)

                result += '
'
        result += '
'
        result += ''
        return result

    def exporter_junit_ioper(self, test_result_ext, test_suite_properties=None):
        from junit_xml import TestSuite, TestCase
        test_suites = []
        test_cases = []

        for platform in sorted(test_result_ext.keys()):
            # {platform : ['Platform', 'Result', 'Scope', 'Description'])
            test_cases = []
            for tr_result in test_result_ext[platform]:
                result, name, scope, description = tr_result

                classname = 'test.ioper.%s.%s.%s' % (platform, name, scope)
                elapsed_sec = 0
                _stdout = description
                _stderr = ''
                # Test case
                tc = TestCase(name, classname, elapsed_sec, _stdout, _stderr)
                # Test case extra failure / error info
                if result == 'FAIL':
                    tc.add_failure_info(description, _stdout)
                elif result == 'ERROR':
                    tc.add_error_info(description, _stdout)
                elif result == 'SKIP' or result == 'NOT_SUPPORTED':
                    tc.add_skipped_info(description, _stdout)

                test_cases.append(tc)
            ts = TestSuite("test.suite.ioper.%s" % (platform), test_cases)
            test_suites.append(ts)
        return TestSuite.to_xml_string(test_suites)

    def exporter_junit(self, test_result_ext, test_suite_properties=None):
        """ Export test results in JUnit XML compliant format
        """
        from junit_xml import TestSuite, TestCase
        test_suites = []
        test_cases = []

        targets = sorted(test_result_ext.keys())
        for target in targets:
            toolchains = sorted(test_result_ext[target].keys())
            for toolchain in toolchains:
                test_cases = []
                tests = sorted(test_result_ext[target][toolchain].keys())
                for test in tests:
                    test_results = test_result_ext[target][toolchain][test]
                    for test_res in test_results:
                        test_ids = sorted(test_res.keys())
                        for test_no in test_ids:
                            test_result = test_res[test_no]
                            name = test_result['description']
                            classname = '%s.%s.%s.%s'% (self.package, target, toolchain, test_result['id'])
                            elapsed_sec = test_result['elapsed_time']
                            _stdout = test_result['output']

                            if 'target_name_unique' in test_result:
                                _stderr = test_result['target_name_unique']
                            else:
                                _stderr = test_result['target_name']

                            # Test case
                            tc = TestCase(name, classname, elapsed_sec, _stdout, _stderr)

                            # Test case extra failure / error info
                            message = test_result['result']
                            if test_result['result'] == 'FAIL':
                                tc.add_failure_info(message, _stdout)
                            elif test_result['result'] == 'SKIP' or test_result["result"] == 'NOT_SUPPORTED':
                                tc.add_skipped_info(message, _stdout)
                            elif test_result['result'] != 'OK':
                                tc.add_error_info(message, _stdout)

                            test_cases.append(tc)

                ts = TestSuite("test.suite.%s.%s"% (target, toolchain), test_cases, properties=test_suite_properties[target][toolchain])
                test_suites.append(ts)
        return TestSuite.to_xml_string(test_suites)

    def exporter_print_helper(self, array, print_log=False):
        for item in array:
            print("  * %s::%s::%s" % (item["target_name"],
                                      item["toolchain_name"],
                                      item["id"]))
            if print_log:
                log_lines = item["output"].split("\n")
                for log_line in log_lines:
                    print("        %s" % log_line)

    def exporter_print(self, test_result_ext, print_log_for_failures=False):
        """ Export test results in print format.
        """
        failures = []
        skips = []
        successes = []

        unique_test_ids = self.get_all_unique_test_ids(test_result_ext)
        targets = sorted(test_result_ext.keys())

        for target in targets:
            toolchains = sorted(test_result_ext[target].keys())
            for toolchain in toolchains:
                tests = sorted(test_result_ext[target][toolchain].keys())
                for test in tests:
                    test_runs = test_result_ext[target][toolchain][test]
                    for test_runner in test_runs:
                        #test_run = test_result_ext[target][toolchain][test][test_run_number][0]
                        test_run = test_runner[0]

                        if "result" in test_run:
                            if test_run["result"] == "FAIL":
                                failures.append(test_run)
                            elif test_run["result"] == "SKIP" or test_run["result"] == "NOT_SUPPORTED":
                                skips.append(test_run)
                            elif test_run["result"] == "OK":
                                successes.append(test_run)
                            else:
                                raise Exception("Unhandled result type: %s" % (test_run["result"]))
                        else:
                            raise Exception("'test_run' did not have a 'result' value")

        if successes:
            print("\n\nBuild successes:")
            self.exporter_print_helper(successes)

        if skips:
            print("\n\nBuild skips:")
            self.exporter_print_helper(skips)

        if failures:
            print("\n\nBuild failures:")
            self.exporter_print_helper(failures, print_log=print_log_for_failures)
            return False
        else:
            return True

    def exporter_text(self, test_result_ext):
        """ Prints well-formed summary with results (SQL table like)
            table shows target x test results matrix across
        """
        success_code = 0    # Success code that can be leter returned to
        # Pretty table package is used to print results
        pt = PrettyTable(["Result", "Target", "Toolchain", "Test ID", "Test Description",
                          "Elapsed Time", "Timeout"])
        pt.align["Result"] = "l" # Left align
        pt.align["Target"] = "l" # Left align
        pt.align["Toolchain"] = "l" # Left align
        pt.align["Test ID"] = "l" # Left align
        pt.align["Test Description"] = "l" # Left align
        pt.padding_width = 1 # One space between column edges and contents (default)

        result_dict = {"OK" : 0,
                       "FAIL" : 0,
                       "ERROR" : 0,
                       "UNDEF" : 0,
                       "IOERR_COPY" : 0,
                       "IOERR_DISK" : 0,
                       "IOERR_SERIAL" : 0,
                       "TIMEOUT" : 0,
                       "NO_IMAGE" : 0,
                       "MBED_ASSERT" : 0,
                       "BUILD_FAILED" : 0,
                       "NOT_SUPPORTED" : 0
        }
        unique_test_ids = self.get_all_unique_test_ids(test_result_ext)
        targets = sorted(test_result_ext.keys())
        for target in targets:
            toolchains = sorted(test_result_ext[target].keys())
            for toolchain in toolchains:
                test_cases = []
                tests = sorted(test_result_ext[target][toolchain].keys())
                for test in tests:
                    test_results = test_result_ext[target][toolchain][test]
                    for test_res in test_results:
                        test_ids = sorted(test_res.keys())
                        for test_no in test_ids:
                            test_result = test_res[test_no]
                            result_dict[test_result['result']] += 1
                            pt.add_row([test_result['result'],
                                        test_result['target_name'],
                                        test_result['toolchain_name'],
                                        test_result['id'],
                                        test_result['description'],
                                        test_result['elapsed_time'],
                                        test_result['duration']])
        result = pt.get_string()
        result += "\n"

        # Print result count
        result += "Result: " + ' / '.join(['%s %s' % (value, key) for (key, value) in {k: v for k, v in result_dict.items() if v != 0}.items()])
        return result


text:
""" Git utilities for obtaining repo metadata

:Author: Arthur Goldberg <Arthur.Goldberg@mssm.edu>
:Author: Jonathan Karr <jonrkarr@gmail.com>
:Date: 2017-05-24
:Copyright: 2017-2019, Karr Lab
:License: MIT
"""

from dataclasses import dataclass
from enum import Enum, auto
from github.GithubException import UnknownObjectException
from pathlib import Path
from wc_utils.config import core
from wc_utils.util.misc import obj_to_str
import git
import github
import itertools
import os

def get_repo(path='.', search_parent_directories=True):
    """ Get a Git repository given the path to a file it contains

    Args:
        path (:obj:`str`): path to file or directory in a Git repository; if `path` doesn't exist
            or is a file then its directory is used
        search_parent_directories (:obj:`bool`, optional): if :obj:`True` have :obj:`git.Repo` search
            for the root of the repository among the parent directories of :obj:`path`; otherwise,
            this method iterates over the parent directories itself

    Returns:
        :obj:`git.Repo`: a `GitPython` repository

    Raises:
        :obj:`ValueError`: if obj:`path` is not a path to a Git repository
    """
    repo = None
    resolved_path = Path(path).expanduser().resolve()
    if not resolved_path.exists() or resolved_path.is_file():
        resolved_path = resolved_path.parent
    dirnames = itertools.chain([str(resolved_path)], resolved_path.parents)
    if search_parent_directories:
        dirnames = [str(resolved_path)]
    for parent_dirname in dirnames:
        try:
            repo = git.Repo(str(parent_dirname), search_parent_directories=search_parent_directories)
            break
        except (git.exc.InvalidGitRepositoryError, git.exc.NoSuchPathError) as e:
            pass

    if not repo:
        raise ValueError('"{}" is not in a Git repository'.format(path))
    return repo

class RepoMetadataCollectionType(Enum):
    """ Type of Git repo being queried for metadata that's stored in a data file """
    DATA_REPO = auto()
    SCHEMA_REPO = auto()

# todo: automatically determine branch of repo & use it instead of 'master'
def repo_suitability(repo, repo_type, data_file=None):
    """ Evaluate whether a repo is a suitable source for git metadata

    Determine whether `repo` is in a state that's suitable for collecting immutable metadata.
    It cannot be ahead of the remote, because commits must have been pushed to
    the server so they can be later retrieved.
    If the `repo_type` is `RepoMetadataCollectionType.SCHEMA_REPO`, then there cannot be any differences
    between the index and the working tree because the schema should be synched with the origin.
    If the`repo_type` is `RepoMetadataCollectionType.DATA_REPO` then the repo can contain changes,
    but the data file should not depend on them. The caller is responsible for determining this.

    Args:
        repo (:obj:`git.Repo`): a `GitPython` repository
        repo_type (:obj:`RepoMetadataCollectionType`): repo type having status determined
        data_file (:obj:`str`, optional): pathname of a data file in the repo; must be provided if
            `repo_type` is `RepoMetadataCollectionType.DATA_REPO`

    Returns:
        :obj:`list` of :obj:`str`: list of reasons, if any, that the repo is in a state that's not
            suitable for collecting metadata; an empty list indicates that the repo can be used to
            collect metadata

    Raises:
        :obj:`ValueError`: if obj:`data_file` is not a path in a Git repository, or
            if `repo_type` is `RepoMetadataCollectionType.DATA_REPO` and `data_file` is not provided, or
            if `repo_type` is not a `RepoMetadataCollectionType`
    """
    unsuitable_changes = []
    commits_ahead = list(repo.iter_commits('origin..HEAD'))
    if commits_ahead:
        unsuitable_changes.append('commits ahead of origin')

    # diff between the index and the commit tree HEAD points to
    diff_index = repo.index.diff(repo.head.commit)
    if repo_type is RepoMetadataCollectionType.DATA_REPO:

        if not data_file:
            raise ValueError("data_file must be provided if repo_type is "
                "RepoMetadataCollectionType.DATA_REPO")

        # ensure that data_file exists in repo
        resolved_data_file = Path(data_file).expanduser().resolve()
        repo_root = Path(repo.git_dir).parent
        try:
            resolved_data_file.relative_to(str(repo_root))
        except ValueError:
            raise ValueError("data_file '{}' must be in the repo that's in '{}'".format(
                data_file, str(repo_root)))

        # ideally, the git repo storing a data file should only have changes in the data file so that
        # it depends on the prior commits; but this may be difficult to satisfy, so other differences
        # should be reported as a warning
        for change_type in diff_index.change_type:
            for diff in diff_index.iter_change_type(change_type):
                resolved_a_rawpath = repo_root.joinpath(diff.a_rawpath.decode())
                resolved_b_rawpath = repo_root.joinpath(diff.b_rawpath.decode())
                if (resolved_a_rawpath != resolved_data_file or
                    resolved_b_rawpath != resolved_data_file):
                    unsuitable_changes.append('modified path(s) are not data_file path')

        for untracked_file in repo.untracked_files:
            if repo_root.joinpath(untracked_file) != resolved_data_file:
                unsuitable_changes.append("untracked file '{}' is not data file: '{}'".format(
                    repo_root.joinpath(untracked_file), resolved_data_file))

    elif repo_type is RepoMetadataCollectionType.SCHEMA_REPO:

        # a schema repo that has any differences between the index and the working tree
        # isn't suitable for collecting metadata
        for change_type in diff_index.change_type:
            if list(diff_index.iter_change_type(change_type)):
                unsuitable_changes.append('changes present')
        if repo.untracked_files:
            unsuitable_changes.append('untracked files present')

    else:
        raise ValueError("Invalid RepoMetadataCollectionType: '{}'".format(repo_type))

    return unsuitable_changes

def get_repo_metadata(path='.', search_parent_directories=True, repo_type=None, data_file=None):
    """ Get metadata about a Git repository

    Args:
        path (:obj:`str`): path to file or directory in a Git repository
        search_parent_directories (:obj:`bool`, optional): if :obj:`True`, have `GitPython` search for
            the root of the repository among the parent directories of :obj:`path`
        repo_type (:obj:`RepoMetadataCollectionType`, optional): repo type having metadata collected
        data_file (:obj:`str`, optional): pathname of a data file in the repo; must be provided if
            `repo_type` is `RepoMetadataCollectionType.DATA_REPO`

    Returns:
        :obj:`tuple`: of :obj:`RepositoryMetadata`:, :obj:`list` of :obj:`str`: repository metadata,
            and, if `repo_type` is provided, changes in the repository that make it unsuitable
    """
    repo = get_repo(path=path, search_parent_directories=search_parent_directories)
    unsuitable_changes = None
    if repo_type:
        unsuitable_changes = repo_suitability(repo, repo_type, data_file=data_file)

    url = str(repo.remote('origin').url)
    branch = str(repo.active_branch.name)
    revision = str(repo.head.commit.hexsha)
    return RepositoryMetadata(url, branch, revision), unsuitable_changes

@dataclass
class RepositoryMetadata(object):
    """ Represents metadata about a Git repository

    Attributes:
        url (:obj:`str`): URL
        branch (:obj:`str`): branch
        revision (:obj:`str`): revision
    """

    url: str
    branch: str
    revision: str

class GitHubRepoForTests(object):
    """ Functions for managing test GitHub repos """

    @staticmethod
    def get_github_api_token():
        config = core.get_config()['wc_utils']['github']
        if config['github_api_token'] == '':
            raise ValueError(f"'github_api_token' is not provided by config")
        return config['github_api_token']

    def __init__(self, name, organization='KarrLab'):
        """ Manage a test GitHub repository

        Args:
            name (:obj:`str`): name of the repo
            organization (:obj:`str`): GitHub organization home for the repo; default='KarrLab'
        """
        self.api_token = self.get_github_api_token()
        self.name = name
        self.organization = organization

    def make_test_repo(self, dirname=None):
        """ Create a test GitHub repository

        Args:
            dirname (:obj:`str`, optional): a directory name; if present, clone the repo into it

        Returns:
            :obj:`obj`: if `dirname` is provided, a `gitpython` reference to a local clone of the test
                GitHub repository; otherwise, the URL of the test GitHub repository
        """
        # delete test repo in case it wasn't deleted previously
        self.delete_test_repo()
        g = github.Github(self.api_token)
        org = g.get_organization(self.organization)
        org.create_repo(name=self.name, private=False, auto_init=True)
        repo_url = 'https://github.com/{}/{}.git'.format(self.organization, self.name)
        if dirname:
            # clone from GitHub
            self.repo = git.Repo.clone_from(repo_url, dirname)
            return self.repo
        return repo_url

    def delete_test_repo(self):
        g = github.Github(self.api_token)
        try:
            repo = g.get_repo("{}/{}".format(self.organization, self.name))
            repo.delete()
        except UnknownObjectException:
            # ignore exception that occurs when delete does not find the repo
            pass
        except Exception:   # pragma: no cover; cannot deliberately raise an other exception
            # re-raise all other exceptions
            raise


text:
//TODO: restore default webview settings after each test?

var parsePair = function( pair ) {
    var sepIdx = pair.indexOf('=');

    ret = {}

    ret.name = pair.substring(0,sepIdx);
    ret.value = pair.substring(sepIdx+1);

    return ret;
}

var parseCookie = function( cookie ) {
    var c = {};

    var pairs = cookie.split(';');

    var parsed = parsePair(pairs[0]);

    c.name = parsed.name;
    c.value = parsed.value;

    for ( var i = 1; i < pairs.length; ++i ) {
        parsed = parsePair(pairs[i]);
        c[parsed.name.toLowerCase().trim()] = parsed.value;
    }

    return c;
}

var global_js_exceute_result = 0;

describe("WebView JS API", function () {

    var rho_version_major;
    var rho_version_minor;

    try {
        var ver = Rho.Config.getPropertyString("rhodes_gem_version");
        rho_version_major = ver.split('.')[0];
        rho_version_minor = ver.split('.')[1];
    } catch (e)
    {
        rho_version_major = 5;
        rho_version_minor = 5;
    }

    var server_url = "http://"+SERVER_HOST+":"+SERVER_PORT;

    beforeEach(function () {
        var matchers = {
            isNotEmptyString: function () {
                return (typeof this.actual == 'string') && (this.actual.length != 0)
            },
            isNumberGreaterThenZero: function () {
                return (typeof this.actual == 'number') && (this.actual > 0)
            }
        };
        this.addMatchers(
            matchers
        );

    });

    it("Test framework property", function () {
        expect(Rho.WebView.framework).isNotEmptyString();
    });

    it("Test default value of fullScreen property", function () {
        expect(Rho.WebView.fullScreen).toEqual(false);
    });

//FIXME: this should be called from main thread
if (!isApplePlatform()) {
    it("Test fullScreen property", function () {
        Rho.WebView.fullScreen = true;
        expect(Rho.WebView.fullScreen).toEqual(true);

        Rho.WebView.fullScreen = false;
        expect(Rho.WebView.fullScreen).toEqual(false);
    });
  }

    it("Test activeTab property", function () {
        expect(Rho.WebView.activeTab).toEqual(0);
    });

    xit("Test refresh method", function () {
        expect(Rho.WebView.refresh(-1));
    });

    xit("Test navigate method", function () {
        expect(Rho.WebView.navigate("http://localhost", -1));
    });

    xit("Test navigateBack method", function () {
        expect(Rho.WebView.navigateBack(-1));
    });

    it("Test currentLocation method", function () {
        expect(Rho.WebView.currentLocation(-1)).isNotEmptyString();
    });

    it("Test executeJavascript method", function () {
        global_js_exceute_result = 0;
        Rho.WebView.executeJavascript("global_js_exceute_result = 1;");

        if (isAndroidPlatform()) {
            waitsFor( function() { return global_js_exceute_result==1; }, "JS was not executed after 1sec of wait", 1000 );
        }

        runs( function() {
            expect(global_js_exceute_result).toEqual(1);
        });
    });

    /* ----------          platform dependent specs          ---------- */

    if (Rho.System.webviewFramework != "WEBKIT/SYMBOL") {
        it("Test setCookie method", function () {
            expect(Rho.WebView.setCookie("http://localhost", "specCookie=123"));
        });
    }

    if (rho_version_major >= 6) {
        it ( "Sets cookie with properties", function() {
            var expires = new Date(new Date().getTime() + 60 * 1000);
            var cookie = "specCookie=cookieValue; expires="+expires.toUTCString()+"; path=/";
            expect(Rho.WebView.setCookie("http://localhost", cookie));
        });

        it ( "Gets cookie with properties", function() {
            var async_done = false;

            runs( function() {
              Rho.WebView.getCookies( "http://localhost", function(cookies) {
                var cookie = cookies.specCookie;
                expect( cookie ).isNotEmptyString();

                var c = parseCookie( cookie );

                expect(c.name).toEqual('specCookie');
                expect(c.value).toEqual('cookieValue');

                if ( !isAndroidPlatform() ) {
                    expect(c.path).toEqual('/');
                    expect(c.expires).isNotEmptyString();
                }
                async_done = true;
              });
            });
            waitsFor( function() { return async_done; }, 'getCookies not completed', 2000 );
        });

        it ( "Sets multiple cookies", function() {

            var async_done = false;
            var expires = new Date(new Date().getTime() + 60 * 1000);
            var cookie1 = "specCookie1=cookieValue1; expires="+expires.toUTCString()+"; path=/";
            var cookie2 = "specCookie2=cookieValue2; expires="+expires.toUTCString()+"; path=/";

            Rho.WebView.setCookie("http://localhost", cookie1);
            Rho.WebView.setCookie("http://localhost", cookie2);

            runs( function() {
              Rho.WebView.getCookies( "http://localhost", function(cookies) {
                cookie1 = cookies.specCookie1;
                expect( cookie1 ).isNotEmptyString();

                var c = parseCookie( cookie1 );

                expect(c.name).toEqual('specCookie1');
                expect(c.value).toEqual('cookieValue1');
                if ( !isAndroidPlatform() ) {
                    expect(c.path).toEqual('/');
                    expect(c.expires).isNotEmptyString();
                }

                cookie2 = cookies.specCookie2;
                expect( cookie2 ).isNotEmptyString();

                c = parseCookie( cookie2 );

                expect(c.name).toEqual('specCookie2');
                expect(c.value).toEqual('cookieValue2');
                if ( !isAndroidPlatform() ) {
                    expect(c.path).toEqual('/');
                    expect(c.expires).isNotEmptyString();
                }

                async_done = true;
              });
            });
            waitsFor( function() { return async_done; }, 'getCookies not completed', 2000 );
        });
    }

    if( isAndroidOrApplePlatform() ) {

        it ( "Removes all cookies", function() {
          var async_done = false;
          var expires = new Date(new Date().getTime() + 60 * 1000);
          var cookie1 = "specCookie1=cookieValue1; expires="+expires.toUTCString()+"; path=/";
          var cookie2 = "specCookie2=cookieValue2";

          Rho.WebView.setCookie("http://localhost", cookie1);
          Rho.WebView.setCookie("http://localhost", cookie2);

          runs( function() {
            Rho.WebView.removeAllCookies( function() {
              async_done = true;
            });
          });
          waitsFor( function() { return async_done; }, 'removeAllCookies not completed', 2000 );

          runs( function() {
            Rho.WebView.getCookies( "http://localhost", function(cookies) {
              expect(Object.keys(cookies).length).toEqual(0);
              async_done = true;
            });
          });
          waitsFor( function() { return async_done; }, 'getCookies not completed', 2000 );
        });

        it ( "Receives session cookie", function() {
            var url = server_url + '/get_session';
            var async_done = false;

            //get session from server
            runs( function() {
                $.ajax( { url: url, xhrFields: { withCredentials: true } } ).done( function(data) { async_done = true; } );
            });
            waitsFor( function() { return async_done; }, 'Ajax call not completed', 2000 );

            //should receive session
            runs( function() {
                async_done = false;
                Rho.WebView.getCookies( server_url, function(cookies) {
                  var cookie = cookies.session;
                  expect( cookie ).isNotEmptyString();
                  async_done = true;
                });
            });
            waitsFor( function() { return async_done; }, 'getCookies not completed', 2000 );
        });

        it ( "Sends session cookie", function() {
            var get_session_url = server_url + '/get_session';
            var return_session_url = server_url + '/return_session';
            var async_done = false;
            var session;

            //get session from server
            runs( function() {
                $.ajax( { url: get_session_url, xhrFields: { withCredentials: true } } ).done( function(data) { async_done = true; } );
            });
            waitsFor( function() { return async_done; }, 'Ajax call not completed', 2000 );

            //should receive session, store it
            runs( function() {
                async_done = false;
                Rho.WebView.getCookies( server_url, function(cookies) {
                  session = cookies.session;
                  expect( session ).isNotEmptyString();
                  async_done = true;
                });
            });
            waitsFor( function() { return async_done; }, 'getCookies not completed', 2000 );

            //check webview sends valid session
            runs( function() {
                async_done = false;
                $.ajax( { url: return_session_url, xhrFields: { withCredentials: true } } ).done( function(data) {
                    async_done = true;
                    expect($.trim(data)).toEqual( parseCookie(session).value );
                });
            });
            waitsFor( function() { return async_done; }, 'Ajax call not completed', 2000 );
        });

        it ( "Removes session cookie", function() {
            var get_session_url = server_url + '/get_session';
            var return_session_url = server_url + '/return_session';
            var async_done = false;
            var session;

            //get session from server
            runs( function() {
                $.ajax( { url: get_session_url, xhrFields: { withCredentials: true } } ).done( function(data) { async_done = true; } );
            });
            waitsFor( function() { return async_done; }, 'Ajax call not completed', 2000 );

            runs( function() {
                async_done = false;
                Rho.WebView.getCookies( server_url, function(cookies) {
                  var cookie = cookies.session;
                  expect( cookie ).isNotEmptyString();
                  async_done = true;
                });
            });
            waitsFor( function() { return async_done; }, 'getCookies not completed', 2000 );

            runs( function() {
                async_done = false;
                Rho.WebView.removeCookie( server_url, 'session', function(data) {
                  expect(data.removed_cookie).toEqual('session');
                  async_done = true;
                });
            });
            waitsFor( function() { return async_done; }, 'removeCookie not completed', 2000 );

            runs( function() {
                async_done = false;
                Rho.WebView.getCookies( server_url, function(cookies) {
                  session = cookies.session;
                  expect(session).toEqual(null);
                  async_done = true;
                });
            });
            waitsFor( function() { return async_done; }, 'getCookies not completed', 2000 );

            //check webview sends valid session
            runs( function() {
                async_done = false;
                $.ajax( { url: return_session_url, xhrFields: { withCredentials: true } } ).done( function(data) {
                    async_done = true;
                    expect($.trim(data)).toEqual('');
                });
            });
            waitsFor( function() { return async_done; }, 'Ajax call not completed', 2000 );
        });

if ( isAndroidPlatform() ) {
        it ( "Removes session cookie with expiry date", function() {
            var get_session_url = server_url + '/get_session';
            var return_session_url = server_url + '/return_session';
            var async_done = false;
            var session;

            //get session from server
            runs( function() {
                $.ajax( { url: get_session_url, xhrFields: { withCredentials: true } } ).done( function(data) { async_done = true; } );
            });
            waitsFor( function() { return async_done; }, 'Ajax call not completed', 2000 );

            runs( function() {
                async_done = false;
                Rho.WebView.getCookies( server_url, function(cookies) {
                  expect( cookies.session ).isNotEmptyString();

                  var d = new Date(1970, 0, 1);
                  Rho.WebView.setCookie( server_url, "session='';expires="+d.toUTCString()+";" );

                  async_done = true;
                });
            });
            waitsFor( function() { return async_done; }, 'getCookies not completed', 2000 );

            runs( function() {
                async_done = false;
                Rho.WebView.getCookies( server_url, function(cookies) {
                  session = cookies.session;
                  expect(session).toEqual(null);
                  async_done = true;
                });
            });
            waitsFor( function() { return async_done; }, 'getCookies not completed', 2000 );

            //check webview sends valid session
            runs( function() {
                async_done = false;
                $.ajax( { url: return_session_url, xhrFields: { withCredentials: true } } ).done( function(data) {
                    async_done = true;
                    expect($.trim(data)).toEqual('');
                });
            });
            waitsFor( function() { return async_done; }, 'Ajax call not completed', 2000 );
        });
    }
}

    if (isAndroidPlatform()) {
        it("Test default value of enableCache property", function () {
            expect(Rho.WebView.enableCache).toEqual(true);
        });

        // Read only property - comment out (aat103)
        //it("Test enableCache property", function () {
        //    Rho.WebView.enableCache = false;
        //    expect(Rho.WebView.enableCache).toEqual(false);

        //    Rho.WebView.enableCache = true;
        //    expect(Rho.WebView.enableCache).toEqual(true);
        //});

        it("Test default value of enableZoom property", function () {
            expect(Rho.WebView.enableZoom).toEqual(true);
        });

        // Read only property - comment out (aat103)
        //it("Test enableZoom property", function () {
        //    Rho.webView.enableZoom = false;
        //    expect(Rho.WebView.enableZoom).toEqual(false);

        //    Rho.webView.enableZoom = true;
        //    expect(Rho.WebView.enableZoom).toEqual(true);
        //});

        it("Test default value of enablePageLoadingIndication property", function () {
            expect(Rho.WebView.enablePageLoadingIndication).toEqual(true);
        });

        // Read only property - comment out (aat103)
        //it("Test enablePageLoadingIndication property", function () {
        //    Rho.WebView.enablePageLoadingIndication = false;
        //    expect(Rho.WebView.enablePageLoadingIndication).toEqual(false);

        //    Rho.WebView.enablePageLoadingIndication = true;
        //    expect(Rho.WebView.enablePageLoadingIndication).toEqual(true);
        //});

        it("Test default value of enableWebPlugins property", function () {
            expect(Rho.WebView.enableWebPlugins).toEqual(true);
        });

        // Read only property - comment out (aat103)
        //it("Test enableWebPlugins property", function () {
        //    Rho.WebView.enableWebPlugins = false;
        //    expect(Rho.WebView.enableWebPlugins).toEqual(false);

        //    Rho.WebView.enableWebPlugins = true;
        //    expect(Rho.WebView.enableWebPlugins).toEqual(true);
        //});

        //TODO: add check on existing saved file
        it("Test save method", function () {
            expect(Rho.WebView.save("jpeg", "someFilename", -1));
        });
    }

    if (isAndroidOrApplePlatform()) {
        var currentURL = "";
        Rho.WebView.currentURL(-1,  function(value){currentURL = value})
        it("Test currentURL method", function () {
            expect(currentURL).isNotEmptyString();
        });
    }

    if (isWindowsMobilePlatform()) {
        it("Test default value of navigationTimeout property", function () {
            expect(Rho.WebView.navigationTimeout).toEqual(0);
        });

        it("Test navigationTimeout property", function () {
            Rho.WebView.navigationTimeout = 100;
            expect(Rho.WebView.navigationTimeout).toEqual(100);
        });

        it("Test scrollTechnique property", function () {
            expect(Rho.WebView.scrollTechnique).toEqual("FingerScroll");
        });

        it("Test fontFamily property", function () {
            expect(Rho.WebView.fontFamily).isNotEmptyString();
        });

        it("Test userAgent property", function () {
            expect(Rho.WebView.userAgent).isNotEmptyString();
        });

        it("Test viewportEnabled property", function () {
            expect(Rho.WebView.viewportEnabled).toEqual(true);
        });

        it("Test viewportWidth property", function () {
            expect(Rho.WebView.viewportWidth).isNumberGreaterThenZero();
        });

        it("Test cacheSize property", function () {
            expect(Rho.WebView.cacheSize).isNumberGreaterThenZero();
        });

        it("Test acceptLanguage property", function () {
            Rho.WebView.acceptLanguage = 'ru';
            expect(Rho.WebView.acceptLanguage).toEqual('ru');
        });

        it("Test zoomPage property", function () {
            Rho.WebView.zoomPage = 1.5;
            expect(Rho.WebView.zoomPage).toEqual(1.5);
        });

        it("Test textZoomLevel property", function () {
            Rho.WebView.textZoomLevel = 2;
            expect(Rho.WebView.textZoomLevel).toEqual(2);
        });
    }

});


text:
from .settings import stored_messages_settings

__all__ = (
    'add_message_for',
    'broadcast_message',
    'mark_read',
    'mark_all_read',
)

def add_message_for(users, level, message_text, extra_tags='', date=None, url=None, fail_silently=False):
    """
    Send a message to a list of users without passing through `django.contrib.messages`

    :param users: an iterable containing the recipients of the messages
    :param level: message level
    :param message_text: the string containing the message
    :param extra_tags: like the Django api, a string containing extra tags for the message
    :param date: a date, different than the default timezone.now
    :param url: an optional url
    :param fail_silently: not used at the moment
    """
    BackendClass = stored_messages_settings.STORAGE_BACKEND
    backend = BackendClass()
    m = backend.create_message(level, message_text, extra_tags, date, url)
    backend.archive_store(users, m)
    backend.inbox_store(users, m)

def broadcast_message(level, message_text, extra_tags='', date=None, url=None, fail_silently=False):
    """
    Send a message to all users aka broadcast.

    :param level: message level
    :param message_text: the string containing the message
    :param extra_tags: like the Django api, a string containing extra tags for the message
    :param date: a date, different than the default timezone.now
    :param url: an optional url
    :param fail_silently: not used at the moment
    """
    from django.contrib.auth import get_user_model
    users = get_user_model().objects.all()
    add_message_for(users, level, message_text, extra_tags=extra_tags, date=date, url=url, fail_silently=fail_silently)

def mark_read(user, message):
    """
    Mark message instance as read for user.
    Returns True if the message was `unread` and thus actually marked as `read` or False in case
    it is already `read` or it does not exist at all.

    :param user: user instance for the recipient
    :param message: a Message instance to mark as read
    """
    BackendClass = stored_messages_settings.STORAGE_BACKEND
    backend = BackendClass()
    backend.inbox_delete(user, message)

def mark_all_read(user):
    """
    Mark all message instances for a user as read.

    :param user: user instance for the recipient
    """
    BackendClass = stored_messages_settings.STORAGE_BACKEND
    backend = BackendClass()
    backend.inbox_purge(user)


text:
bool SbConditionVariableBroadcast(SbConditionVariable* condition) {
  if (!condition) {
    return false;
  }
  WakeAllConditionVariable(SB_WIN32_INTERNAL_CONDITION(condition));
  return true;
}


text:
#include "modules/perception/onboard/component/detection_component.h"

#include "cyber/time/clock.h"
#include "modules/common/util/string_util.h"
#include "modules/perception/common/sensor_manager/sensor_manager.h"
#include "modules/perception/lidar/common/lidar_error_code.h"
#include "modules/perception/lidar/common/lidar_frame_pool.h"
#include "modules/perception/lidar/common/lidar_log.h"
#include "modules/perception/onboard/common_flags/common_flags.h"

using ::apollo::cyber::Clock;

namespace apollo {
namespace perception {
namespace onboard {

std::atomic<uint32_t> DetectionComponent::seq_num_{0};

bool DetectionComponent::Init() {
  LidarDetectionComponentConfig comp_config;
  if (!GetProtoConfig(&comp_config)) {
    return false;
  }
  ADEBUG << "Lidar Component Configs: " << comp_config.DebugString();
  output_channel_name_ = comp_config.output_channel_name();
  sensor_name_ = comp_config.sensor_name();
  lidar2novatel_tf2_child_frame_id_ =
      comp_config.lidar2novatel_tf2_child_frame_id();
  lidar_query_tf_offset_ =
      static_cast<float>(comp_config.lidar_query_tf_offset());
  //  enable_hdmap_ = comp_config.enable_hdmap();
  writer_ = node_->CreateWriter<LidarFrameMessage>(output_channel_name_);

  if (!InitAlgorithmPlugin()) {
    AERROR << "Failed to init detection component algorithm plugin.";
    return false;
  }
  return true;
}

bool DetectionComponent::Proc(
    const std::shared_ptr<drivers::PointCloud>& message) {
  AINFO << std::setprecision(16)
        << "Enter detection component, message timestamp: "
        << message->measurement_time()
        << " current timestamp: " << Clock::NowInSeconds();

  auto out_message = std::make_shared<LidarFrameMessage>();

  bool status = InternalProc(message, out_message);
  if (status) {
    writer_->Write(out_message);
    AINFO << "Send lidar detect output message.";
  }
  return status;
}

bool DetectionComponent::InitAlgorithmPlugin() {
  ACHECK(common::SensorManager::Instance()->GetSensorInfo(sensor_name_,
                                                          &sensor_info_));

  detector_.reset(new lidar::LidarObstacleDetection);
  if (detector_ == nullptr) {
    AERROR << "sensor_name_ "
           << "Failed to get detection instance";
    return false;
  }
  lidar::LidarObstacleDetectionInitOptions init_options;
  init_options.sensor_name = sensor_name_;
  //  init_options.enable_hdmap_input =
  //      FLAGS_obs_enable_hdmap_input && enable_hdmap_;
  if (!detector_->Init(init_options)) {
    AINFO << "sensor_name_ "
          << "Failed to init detection.";
    return false;
  }

  lidar2world_trans_.Init(lidar2novatel_tf2_child_frame_id_);
  return true;
}

bool DetectionComponent::InternalProc(
    const std::shared_ptr<const drivers::PointCloud>& in_message,
    const std::shared_ptr<LidarFrameMessage>& out_message) {
  uint32_t seq_num = seq_num_.fetch_add(1);
  const double timestamp = in_message->measurement_time();
  const double cur_time = Clock::NowInSeconds();
  const double start_latency = (cur_time - timestamp) * 1e3;
  AINFO << std::setprecision(16) << "FRAME_STATISTICS:Lidar:Start:msg_time["
        << timestamp << "]:sensor[" << sensor_name_ << "]:cur_time[" << cur_time
        << "]:cur_latency[" << start_latency << "]";

  out_message->timestamp_ = timestamp;
  out_message->lidar_timestamp_ = in_message->header().lidar_timestamp();
  out_message->seq_num_ = seq_num;
  out_message->process_stage_ = ProcessStage::LIDAR_DETECTION;
  out_message->error_code_ = apollo::common::ErrorCode::OK;

  auto& frame = out_message->lidar_frame_;
  frame = lidar::LidarFramePool::Instance().Get();
  frame->cloud = base::PointFCloudPool::Instance().Get();
  frame->timestamp = timestamp;
  frame->sensor_info = sensor_info_;

  Eigen::Affine3d pose = Eigen::Affine3d::Identity();
  const double lidar_query_tf_timestamp =
      timestamp - lidar_query_tf_offset_ * 0.001;
  if (!lidar2world_trans_.GetSensor2worldTrans(lidar_query_tf_timestamp,
                                               &pose)) {
    out_message->error_code_ = apollo::common::ErrorCode::PERCEPTION_ERROR_TF;
    AERROR << "Failed to get pose at time: "
           << FORMAT_TIMESTAMP(lidar_query_tf_timestamp);
    return false;
  }

  frame->lidar2world_pose = pose;

  lidar::LidarObstacleDetectionOptions detect_opts;
  detect_opts.sensor_name = sensor_name_;
  lidar2world_trans_.GetExtrinsics(&detect_opts.sensor2novatel_extrinsics);
  lidar::LidarProcessResult ret =
      detector_->Process(detect_opts, in_message, frame.get());
  if (ret.error_code != lidar::LidarErrorCode::Succeed) {
    out_message->error_code_ =
        apollo::common::ErrorCode::PERCEPTION_ERROR_PROCESS;
    AERROR << "Lidar detection process error, " << ret.log;
    return false;
  }

  return true;
}

}  // namespace onboard
}  // namespace perception
}  // namespace apollo


text:
layout: post
title: Books That Literally All White Men Own?
date: 2015-05-13 12:23:23
summary: So?  Am I supposed to be ashamed of this?
categories: books
---

Yesterday someone I follow on Twitter posted a link to a link on The Toast to [Books That Literally All White Men Own](http://the-toast.net/2015/05/12/books-that-literally-all-white-men-own/).  I'm a white man, so of course I took a look.  Here are those from that list that I have at least read:

* *Slaughterhouse-Five* → Kurt Vonnegut
* *A Confederacy of Dunces* → John Kennedy Toole
* *Infinite Jest* → David Foster Wallace
* *A Farewell to Arms* → Ernest Hemingway
* *God Is Not Great* → Christopher Hitchens
* *Catch-22* → Joseph Heller
* *The Catcher in the Rye* → J.D. Salinger
* *The Great Gatsby* → F. Scott Fitzgerald
* *Lolita* → Vladimir Nabokov
* *The Da Vinci Code* → Dan Brown
* *The Grapes of Wrath* → John Steinbeck
* *The Tipping Point* → Malcolm Gladwell
* *Freakonomics* → Steven D. Levitt
* *Burr* → Gore Vidal
* *Into Thin Air* → Jon Krakauer
* *Into the Wild* → Jon Krakauer
* *On the Road* → Jack Kerouac
* *Lord of the Flies* → William Golding

So 18 out of 79.  Does that make me only 22.78% white male?  Am I supposed to be embarrassed that I haven't read more of these?  Am I supposed to be ashamed that *I have* read enough of these to be 22.78% white male? I don't get it.

I hate lists like this. In general I'm a fan of what The Toast is about but this is silly.

I guess I am ashamed that I have read *The Da Vinci Code*, or maybe not.  It was entertaining.


text:
Web interface to myclinic database.

## License
This software is released under the MIT License, see [LICENSE.txt](LICENSE.txt).


text:
Some of the files of this project are under CDDL / GPL2 license.

Copyright 2000-2009 Sun Microsystems, Inc. All rights reserved.
Copyright (c) 2000-2010 Oracle and/or its affiliates. All rights reserved.


text:
"""CGI server interface to Python runtime.

CGI-compliant interface between the Python runtime and user-provided Python
code.
"""

from __future__ import with_statement

import cStringIO
from email import feedparser
import imp
import logging
import marshal
import os
import sys
import traceback
import types

def HandleRequest(unused_environ, handler_name, unused_url, post_data,
                  unused_error, application_root, python_lib,
                  import_hook=None):
  """Handle a single CGI request.

  Handles a request for handler_name in the form 'path/to/handler.py' with the
  environment contained in environ.

  Args:
    handler_name: A str containing the user-specified handler file to use for
        this request as specified in the script field of a handler in app.yaml.
    post_data: A stream containing the post data for this request.
    application_root: A str containing the root path of the application.
    python_lib: A str containing the root the Python App Engine library.
    import_hook: Optional import hook (PEP 302 style loader).

  Returns:
    A dict containing zero or more of the following:
      error: App Engine error code. 0 for OK, 1 for error. Defaults to OK if not
          set. If set, then the other fields may be missing.
      response_code: HTTP response code.
      headers: A list of tuples (key, value) of HTTP headers.
      body: A str of the body of the response.
  """
  body = cStringIO.StringIO()
  module_name = _FileToModuleName(handler_name)
  parent_module, _, submodule_name = module_name.rpartition('.')
  parent_module = _GetModuleOrNone(parent_module)
  main = None

  if module_name in sys.modules:
    module = sys.modules[module_name]
    main = _GetValidMain(module)
  if not main:
    module = imp.new_module('__main__')
    if import_hook is not None:
      module.__loader__ = import_hook
  saved_streams = sys.stdin, sys.stdout
  try:
    sys.modules['__main__'] = module
    module.__dict__['__name__'] = '__main__'
    sys.stdin = post_data
    sys.stdout = body
    if main:
      os.environ['PATH_TRANSLATED'] = module.__file__
      main()
    else:
      filename = _AbsolutePath(handler_name, application_root, python_lib)
      if filename.endswith(os.sep + '__init__.py'):
        module.__path__ = [os.path.dirname(filename)]
      if import_hook is None:
        code, filename = _LoadModuleCode(filename)
      else:
        code = import_hook.get_code(module_name)
      if not code:
        return {'error': 2}
      os.environ['PATH_TRANSLATED'] = filename
      module.__file__ = filename
      try:
        sys.modules[module_name] = module
        eval(code, module.__dict__)
      except:

        del sys.modules[module_name]
        if parent_module and submodule_name in parent_module.__dict__:
          del parent_module.__dict__[submodule_name]
        raise
      else:
        if parent_module:
          parent_module.__dict__[submodule_name] = module
    return _ParseResponse(body)
  except:
    exception = sys.exc_info()

    message = ''.join(traceback.format_exception(exception[0], exception[1],
                                                 exception[2].tb_next))
    logging.error(message)
    return {'error': 1}
  finally:
    sys.stdin, sys.stdout = saved_streams
    module.__name__ = module_name
    if '__main__' in sys.modules:
      del sys.modules['__main__']

def _ParseResponse(response):
  """Parses an HTTP response into a dict.

  Args:
    response: A cStringIO.StringIO (StringO) containing the HTTP response.

  Returns:
    A dict with fields:
      body: A str containing the body.
      headers: A list containing tuples (key, value) of key and value pairs.
      response_code: An int containing the HTTP response code.
  """

  response.reset()
  parser = feedparser.FeedParser()

  parser._set_headersonly()

  while True:
    line = response.readline()
    if not feedparser.headerRE.match(line):
      if not feedparser.NLCRE.match(line):
        parser.feed(line)
      break
    parser.feed(line)
  parsed_response = parser.close()

  if 'Status' in parsed_response:
    status = int(parsed_response['Status'].split(' ', 1)[0])
    del parsed_response['Status']
  else:
    status = 200
  return {'body': parsed_response.get_payload() + response.read(),
          'headers': parsed_response.items(),
          'response_code': status}

def _ParseHeader(header):
  """Parses a str header into a (key, value) pair."""
  key, _, value = header.partition(':')
  return key.strip(), value.strip()

def _GetValidMain(module):
  """Returns a main function in module if it exists and is valid or None.

  A main function is valid if it can be called with no arguments, i.e. calling
  module.main() would be valid.

  Args:
    module: The module in which to search for a main function.

  Returns:
    A function that takes no arguments if found or None otherwise.
  """
  if not hasattr(module, 'main'):
    return None
  main = module.main
  if not hasattr(main, '__call__'):
    return None
  defaults = main.__defaults__
  if defaults:
    default_argcount = len(defaults)
  else:
    default_argcount = 0
  if (main.__code__.co_argcount - default_argcount) == 0:
    return main
  else:
    return None

def _FileToModuleName(filename):
  """Returns the module name corresponding to a filename."""
  _, lib, suffix = filename.partition('$PYTHON_LIB/')
  if lib:
    module = suffix
  else:
    module = filename
  module = os.path.normpath(module)
  if '.py' in module:
    module = module.rpartition('.py')[0]
  module = module.replace(os.sep, '.')
  module = module.strip('.')
  if module.endswith('.__init__'):
    module = module.rpartition('.__init__')[0]
  return module

def _AbsolutePath(filename, application_root, python_lib):
  """Returns the absolute path of a Python script file.

  Args:
    filename: A str containing the handler script path.
    application_root: The absolute path of the root of the application.
    python_lib: The absolute path of the Python library.

  Returns:
    The absolute path of the handler script.
  """
  _, lib, suffix = filename.partition('$PYTHON_LIB/')
  if lib:
    filename = os.path.join(python_lib, suffix)
  else:
    filename = os.path.join(application_root, filename)
  if filename.endswith(os.sep) or os.path.isdir(filename):
    filename = os.path.join(filename, '__init__.py')
  return filename

def _LoadModuleCode(filename):
  """Loads the code of a module, using compiled bytecode if available.

  Args:
    filename: The Python script filename.

  Returns:
    A 2-tuple (code, filename) where:
      code: A code object contained in the file or None if it does not exist.
      filename: The name of the file loaded, either the same as the arg
          filename, or the corresponding .pyc file.
  """
  compiled_filename = filename + 'c'
  if os.path.exists(compiled_filename):
    with open(compiled_filename, 'r') as f:
      magic_numbers = f.read(8)
      if len(magic_numbers) == 8 and magic_numbers[:4] == imp.get_magic():
        try:
          return _FixCodeFilename(marshal.load(f), filename), compiled_filename
        except (EOFError, ValueError):
          pass

  if os.path.exists(filename):
    with open(filename, 'r') as f:
      code = compile(f.read(), filename, 'exec', 0, True)
    return code, filename
  else:
    return None, filename

def _FixCodeFilename(code, filename):
  """Creates a CodeType with co_filename replaced with filename.

  Also affects nested code objects in co_consts.

  Args:
    code: The code object to be replaced.
    filename: The replacement filename.

  Returns:
    A new code object with its co_filename set to the provided filename.
  """
  if isinstance(code, types.CodeType):
    code = types.CodeType(
        code.co_argcount,
        code.co_nlocals,
        code.co_stacksize,
        code.co_flags,
        code.co_code,
        tuple([_FixCodeFilename(c, filename) for c in code.co_consts]),
        code.co_names,
        code.co_varnames,
        filename,
        code.co_name,
        code.co_firstlineno,
        code.co_lnotab,
        code.co_freevars,
        code.co_cellvars)
  return code

def _GetModuleOrNone(module_name):
  """Returns a module if it exists or None."""
  module = None
  if module_name:
    try:
      module = __import__(module_name)
    except ImportError:
      pass
    else:
      for name in module_name.split('.')[1:]:
        module = getattr(module, name)
  return module


text:
package com.leo.cattle.presentation.model;

/**
 * Created by leo on 4/1/2016.
 */
public class WeightModel {
    private int id;
    private int cattleId;
    private String desCription;
    private int weight;
    private String date;
    private int authorId;
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getCattleId() {
        return cattleId;
    }

    public void setCattleId(int cattleId) {
        this.cattleId = cattleId;
    }

    public String getDesCription() {
        return desCription;
    }

    public void setDesCription(String desCription) {
        this.desCription = desCription;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public int getAuthorId() {
        return authorId;
    }

    public void setAuthorId(int authorId) {
        this.authorId = authorId;
    }
}


text:
<title>Ogre::STLAllocator< T, AllocPolicy > Class Template Reference - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Directories

Class List

Class Index

Class Hierarchy

Class Members

Ogre

STLAllocator

Classes |
Public Types |
Public Member Functions

Ogre::STLAllocator< T, AllocPolicy > Class Template Reference
Memory

#include <OgreMemorySTLAllocator.h>

Inheritance diagram for Ogre::STLAllocator< T, AllocPolicy >:

<map name="Ogre_1_1STLAllocator_3_01T_00_01AllocPolicy_01_4_inherit__map" id="Ogre_1_1STLAllocator_3_01T_00_01AllocPolicy_01_4_inherit__map">
<area shape="rect" id="node2" href="structOgre_1_1STLAllocatorBase.html" title="Wrapper class for operating as an STL container allocator." alt="" coords="27,5,221,35"/></map>
[legend]

List of all members.

Classes

struct  	rebind

 	the standard rebind mechanism  More...

Public Types

typedef STLAllocatorBase< T > 	Base

 	define our types, as per ISO C++

typedef Base::value_type 	value_type

typedef value_type * 	pointer

typedef const value_type * 	const_pointer

typedef value_type & 	reference

typedef const value_type & 	const_reference

typedef std::size_t 	size_type

typedef std::ptrdiff_t 	difference_type

Public Member Functions

 	STLAllocator ()

 	ctor

virtual 	~STLAllocator ()

 	dtor

 	STLAllocator (STLAllocator const &)

 	copy ctor - done component wise

template<typename U >

 	STLAllocator (STLAllocator< U, AllocPolicy > const &)

 	cast

template<typename U , typename P >

 	STLAllocator (STLAllocator< U, P > const &)

 	cast

pointer 	allocate (size_type count, typename std::allocator< void >::const_pointer ptr=0)

 	memory allocation (elements, used by STL)

void 	deallocate (pointer ptr, size_type)

 	memory deallocation (elements, used by STL)

pointer 	address (reference x) const

const_pointer 	address (const_reference x) const

size_type 	max_size () const   throw ()

void 	construct (pointer p)

void 	construct (pointer p, const T &val)

void 	destroy (pointer p)

Detailed Description

template<typename T, typename AllocPolicy>

class Ogre::STLAllocator< T, AllocPolicy >

Definition at line 81 of file OgreMemorySTLAllocator.h.

Member Typedef Documentation

template<typename T , typename AllocPolicy >

          typedef STLAllocatorBase<T> Ogre::STLAllocator< T, AllocPolicy >::Base

define our types, as per ISO C++

Definition at line 85 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          typedef const value_type* Ogre::STLAllocator< T, AllocPolicy >::const_pointer

Definition at line 88 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          typedef const value_type& Ogre::STLAllocator< T, AllocPolicy >::const_reference

Definition at line 90 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          typedef std::ptrdiff_t Ogre::STLAllocator< T, AllocPolicy >::difference_type

Definition at line 92 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          typedef value_type* Ogre::STLAllocator< T, AllocPolicy >::pointer

Definition at line 87 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          typedef value_type& Ogre::STLAllocator< T, AllocPolicy >::reference

Definition at line 89 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          typedef std::size_t Ogre::STLAllocator< T, AllocPolicy >::size_type

Definition at line 91 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          typedef Base::value_type Ogre::STLAllocator< T, AllocPolicy >::value_type

Reimplemented from Ogre::STLAllocatorBase< T >.

Definition at line 86 of file OgreMemorySTLAllocator.h.

Constructor & Destructor Documentation

template<typename T , typename AllocPolicy >

          Ogre::STLAllocator< T, AllocPolicy >::STLAllocator
          (
          	)
           [explicit]

ctor

Definition at line 103 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          virtual Ogre::STLAllocator< T, AllocPolicy >::~STLAllocator
          (
          	)
           [virtual]

dtor

Definition at line 107 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          Ogre::STLAllocator< T, AllocPolicy >::STLAllocator
          (
          STLAllocator< T, AllocPolicy > const &
          	)

copy ctor - done component wise

Definition at line 111 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

template<typename U >

          Ogre::STLAllocator< T, AllocPolicy >::STLAllocator
          (
          STLAllocator< U, AllocPolicy > const &
          	)

cast

Definition at line 116 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

template<typename U , typename P >

          Ogre::STLAllocator< T, AllocPolicy >::STLAllocator
          (
          STLAllocator< U, P > const &
          	)

cast

Definition at line 121 of file OgreMemorySTLAllocator.h.

Member Function Documentation

template<typename T , typename AllocPolicy >

          pointer Ogre::STLAllocator< T, AllocPolicy >::address
          (
          reference
          x	)
           const

Definition at line 143 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          const_pointer Ogre::STLAllocator< T, AllocPolicy >::address
          (
          const_reference
          x	)
           const

Definition at line 148 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          pointer Ogre::STLAllocator< T, AllocPolicy >::allocate
          (
          size_type
          count,

          typename std::allocator< void >::const_pointer
          ptr = 0

          )

memory allocation (elements, used by STL)

Definition at line 125 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          void Ogre::STLAllocator< T, AllocPolicy >::construct
          (
          pointer
          p	)

Definition at line 159 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          void Ogre::STLAllocator< T, AllocPolicy >::construct
          (
          pointer
          p,

          const T &
          val

          )

Definition at line 165 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          void Ogre::STLAllocator< T, AllocPolicy >::deallocate
          (
          pointer
          ptr,

          size_type

          )

memory deallocation (elements, used by STL)

Definition at line 136 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          void Ogre::STLAllocator< T, AllocPolicy >::destroy
          (
          pointer
          p	)

Definition at line 171 of file OgreMemorySTLAllocator.h.

template<typename T , typename AllocPolicy >

          size_type Ogre::STLAllocator< T, AllocPolicy >::max_size
          (
          	)
           const  throw ()

Definition at line 153 of file OgreMemorySTLAllocator.h.

The documentation for this class was generated from the following file:

OgreMemorySTLAllocator.h

Copyright © 2012 Torus Knot Software Ltd

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Last modified Sun Sep 2 2012 07:27:31


text:
package com.lnwazg.httpkit.filter.common;

import com.lnwazg.httpkit.filter.adapter.business.LogicChainAdapter;
import com.lnwazg.kit.log.Logs;

/**
 * 显示UA的过滤器
 * @author linan
 */
public class ShowUserAgentFilter extends LogicChainAdapter
{

    @Override
    public void before()
    {
        Logs.i("user-agent is: " + getHeader("User-Agent"));
    }

    @Override
    public void after()
    {

    }

}


text:
' Copyright 2018 Google LLC
'
' Licensed under the Apache License, Version 2.0 (the "License")
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
'     http:'www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.

Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201809
Imports Google.Api.Ads.AdWords.Util.Shopping.v201809

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example creates a ProductPartition tree.
    ''' </summary>
    Public Class AddProductPartitionTree
        Inherits ExampleBase

        ''' <summary>
        ''' Main method, to run this code example as a standalone application.
        ''' </summary>
        ''' <param name="args">The command line arguments.</param>
        Public Shared Sub Main(ByVal args As String())
            Dim codeExample As New AddProductPartitionTree
            Console.WriteLine(codeExample.Description)
            Try
                Dim adGroupId As Long = Long.Parse("INSERT_ADGROUP_ID_HERE")
                codeExample.Run(New AdWordsUser, adGroupId)
            Catch e As Exception
                Console.WriteLine("An exception occurred while running this code example. {0}",
                                  ExampleUtilities.FormatException(e))
            End Try
        End Sub

        ''' <summary>
        ''' Returns a description about the code example.
        ''' </summary>
        Public Overrides ReadOnly Property Description() As String
            Get
                Return "This code example creates a ProductPartition tree."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="adGroupId">The ad group to which product partition is
        ''' added.</param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal adGroupId As Long)
            Using adGroupCriterionService As AdGroupCriterionService = CType(
                user.GetService(
                    AdWordsService.v201809.AdGroupCriterionService),
                AdGroupCriterionService)

                ' Build a new ProductPartitionTree using the ad group's current set of criteria.
                Dim partitionTree As ProductPartitionTree =
                        ProductPartitionTree.DownloadAdGroupTree(user, adGroupId)

                Console.WriteLine("Original tree: {0}", partitionTree)

                ' Clear out any existing criteria.
                Dim rootNode As ProductPartitionNode = partitionTree.Root.RemoveAllChildren()

                ' Make the root node a subdivision.
                rootNode = rootNode.AsSubdivision()

                ' Add a unit node for condition = NEW.
                Dim newConditionNode As ProductPartitionNode = rootNode.AddChild(
                    ProductDimensions.CreateCanonicalCondition(
                        ProductCanonicalConditionCondition.NEW))
                newConditionNode.AsBiddableUnit().CpcBid = 200000

                Dim usedConditionNode As ProductPartitionNode = rootNode.AddChild(
                    ProductDimensions.CreateCanonicalCondition(
                        ProductCanonicalConditionCondition.USED))
                usedConditionNode.AsBiddableUnit().CpcBid = 100000

                ' Add a subdivision node for condition = null (everything else).
                Dim otherConditionNode As ProductPartitionNode =
                        rootNode.AddChild(ProductDimensions.CreateCanonicalCondition()).
                        AsSubdivision()

                ' Add a unit node under condition = null for brand = "CoolBrand".
                Dim coolBrandNode As ProductPartitionNode = otherConditionNode.AddChild(
                    ProductDimensions.CreateBrand("CoolBrand"))
                coolBrandNode.AsBiddableUnit().CpcBid = 900000L

                ' Add a unit node under condition = null for brand = "CheapBrand".
                Dim cheapBrandNode As ProductPartitionNode = otherConditionNode.AddChild(
                    ProductDimensions.CreateBrand("CheapBrand"))
                cheapBrandNode.AsBiddableUnit().CpcBid = 10000L

                ' Add a subdivision node under condition = null for brand = null (everything else).
                Dim otherBrandNode As ProductPartitionNode = otherConditionNode.AddChild(
                    ProductDimensions.CreateBrand()).AsSubdivision()

                ' Add unit nodes under condition = null/brand = null.
                ' The value for each bidding category is a fixed ID for a specific
                ' category. You can retrieve IDs for categories from the ConstantDataService.
                ' See the 'GetProductCategoryTaxonomy' example for more details.

                ' Add a unit node under condition = null/brand = null for product type
                ' level 1 = 'Luggage & Bags'.
                Dim luggageAndBagNode As ProductPartitionNode = otherBrandNode.AddChild(
                    ProductDimensions.CreateBiddingCategory(
                        ProductDimensionType.BIDDING_CATEGORY_L1,
                        - 5914235892932915235L))
                luggageAndBagNode.AsBiddableUnit().CpcBid = 750000L

                ' Add a unit node under condition = null/brand = null for product type
                ' level 1 = null (everything else).
                Dim everythingElseNode As ProductPartitionNode = otherBrandNode.AddChild(
                    ProductDimensions.CreateBiddingCategory(
                        ProductDimensionType.BIDDING_CATEGORY_L1))
                everythingElseNode.AsBiddableUnit().CpcBid = 110000L

                Try
                    ' Make the mutate request, using the operations returned by the
                    ' ProductPartitionTree.
                    Dim mutateOperations As AdGroupCriterionOperation() =
                            partitionTree.GetMutateOperations()

                    If mutateOperations.Length = 0 Then
                        Console.WriteLine(
                            "Skipping the mutate call because the original tree and the " &
                            "current tree are logically identical.")
                    Else
                        adGroupCriterionService.mutate(mutateOperations)
                    End If

                    ' The request was successful, so create a new ProductPartitionTree based on the
                    ' updated state of the ad group.
                    partitionTree = ProductPartitionTree.DownloadAdGroupTree(user, adGroupId)

                    Console.WriteLine("Final tree: {0}", partitionTree)
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to add bid modifiers to adgroup.",
                                                          e)
                End Try
            End Using
        End Sub
    End Class
End Namespace


text:
define([], function () {

  function user(requestApi) {
    var that = this;

    that.getUserState = getUserState;
    that.changeUserState = changeUserState;
    // Не реализовано
    // that.getUserData;

    /**
     * Получить состояние пользователя
     * @param {String} userId id пользователя
     * @return {Promise<JSON>} Данные пользователя
     */
    function getUserState(userId) {
      return requestApi.sendRequest(
        'get',
        '/server/api/public/get-user-state?user=' + userId);
    }

    /**
     * Изменить состояние пользователя
     * @param {String} userId id пользователя
     * @param {String} state новое состояние пользователя
     * @return {Promise<JSON>} Данные пользователя
     */
    function changeUserState(userId, state) {
      return requestApi.sendRequest(
        'get',
        '/server/api/public/get-user-state?user=' + userId + '&state=' + state);
    }
  }

  return user;
});