text:
require 'spec_helper'

describe 'Server Selection moving average round trip time calculation' do

  include Mongo::ServerSelection::RTT

  SERVER_SELECTION_RTT_TESTS.each do |file|

    spec = Mongo::ServerSelection::RTT::Spec.new(file)

    context(spec.description) do

      before(:all) do

        module Mongo
          class Server

            # We monkey-patch the monitor here, so the last average rtt can be controlled.
            # We keep the API of Monitor#initialize but add in an extra option and set the last rtt.
            #
            # @since 2.0.0
            class Monitor

              alias :original_initialize :initialize
              def initialize(address, listeners, options = {})
                @description = Mongo::Server::Description.new(address, {})
                @inspector = Mongo::Server::Description::Inspector.new(listeners)
                @options = options.freeze
                @connection = Connection.new(address, options)
                @last_round_trip_time = options[:avg_rtt_ms]
                @mutex = Mutex.new
              end

              # We monkey patch this method to use an instance variable instead of calculating time elapsed.
              #
              # @since 2.0.0
              alias :original_average_round_trip_time :average_round_trip_time
              def average_round_trip_time(start)
                new_rtt = @new_rtt_ms
                RTT_WEIGHT_FACTOR * new_rtt + (1 - RTT_WEIGHT_FACTOR) * (@last_round_trip_time || new_rtt)
              end
            end
          end
        end
      end

      after(:all) do

        module Mongo
          class Server

            # Return the monitor implementation to its original for the other
            # tests in the suite.
            class Monitor

              alias :initialize :original_initialize
              remove_method(:original_initialize)

              alias :average_round_trip_time :original_average_round_trip_time
              remove_method(:original_average_round_trip_time)
            end
          end
        end
      end

      let(:address) do
        Mongo::Address.new('127.0.0.1:27017')
      end

      let(:monitor) do
        Mongo::Server::Monitor.new(address, Mongo::Event::Listeners.new,
                                   TEST_OPTIONS.merge(avg_rtt_ms: spec.avg_rtt_ms))
      end

      before do
        monitor.instance_variable_set(:@new_rtt_ms, spec.new_rtt_ms)
        monitor.scan!
      end

      it 'correctly calculates the moving average round trip time' do
        expect(monitor.description.average_round_trip_time).to eq(spec.new_avg_rtt)
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;

namespace Soldier.Windows.Converters
{
    public class BooleanToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (bool)value ? Visibility.Visible : Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Visibility.Visible == (Visibility)value ? true : false;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""
    SleekXMPP: The Sleek XMPP Library
    Copyright (C) 2011 Nathanael C. Fritz, Lance J.T. Stout
    This file is part of SleekXMPP.

    See the file LICENSE for copying permission.
"""

from sleekxmpp.xmlstream import ElementBase

class OOBTransfer(ElementBase):

    """
    """

    name = 'query'
    namespace = 'jabber:iq:oob'
    plugin_attrib = 'oob_transfer'
    interfaces = set(('url', 'desc', 'sid'))
    sub_interfaces = set(('url', 'desc'))

class OOB(ElementBase):

    """
    """

    name = 'x'
    namespace = 'jabber:x:oob'
    plugin_attrib = 'oob'
    interfaces = set(('url', 'desc'))
    sub_interfaces = interfaces


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ann. Bot. , Lond. 16: 85 (1902)

#### Original name
Trichosporum insigne Massee & E.S. Salmon

### Remarks
null


text:
namespace Zu.ChromeDevTools.Page
{
    using Newtonsoft.Json;

    /// <summary>
    /// Get Permissions Policy state on given frame.
    /// </summary>
    public sealed class GetPermissionsPolicyStateCommand : ICommand
    {
        private const string ChromeRemoteInterface_CommandName = "Page.getPermissionsPolicyState";

        [JsonIgnore]
        public string CommandName
        {
            get { return ChromeRemoteInterface_CommandName; }
        }

        /// <summary>
        /// Gets or sets the frameId
        /// </summary>
        [JsonProperty("frameId")]
        public string FrameId
        {
            get;
            set;
        }
    }

    public sealed class GetPermissionsPolicyStateCommandResponse : ICommandResponse<GetPermissionsPolicyStateCommand>
    {
        /// <summary>
        /// Gets or sets the states
        /// </summary>
        [JsonProperty("states")]
        public PermissionsPolicyFeatureState[] States
        {
            get;
            set;
        }
    }
}


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe "Tagger" do
  before(:each) do
    @user = User.new
  end

  it { @user.should respond_to(:owned_taggings) }
  it { @user.should respond_to(:owned_tags) }
  it { @user.should respond_to(:is_tagger?)}
  it { @user.should respond_to(:tag) }
end


text:
people-search
=============

Utility for making API calls to the JHU people search API (must have valid credentials)


text:
// Generated by CoffeeScript 1.4.0

/*
Elegant HTML generation. No templating. Just Javascript.
@author Raine Lourie
@note Created independently from JsonML (http://jsonml.org).
*/

(function() {
  var DocumentFragment, Element, Encoder, TextNode, addAttributes, addChildren, containsClass, create, createFromMarkupArray, createHtml, curry, document, each, eachObj, emulatedDocument, encoder, error, extend, filter, find, index, isDomNode, keyValue, map, mergeAttributes, orderedGroup, parseSelectorAttributes, parseTagName, plugins, regexIdOrClass, regexIdOrClassSeparator, render, setDocument, setEmulatedDocument, splice, splitOnce, toObject, typeOf, types,
    __slice = [].slice;

  if (typeof require !== "undefined" && require !== null) {
    Encoder = require('node-html-encoder').Encoder;
    encoder = new Encoder('entity');
  }

  /*
  DOM Emulation
  */

  TextNode = (function() {

    function TextNode(textContent) {
      this.textContent = textContent;
      this.nodeType = 3;
    }

    TextNode.prototype.toString = function() {
      return (typeof require !== "undefined" && require !== null) && encoder.htmlEncode(this.textContent) || this.textContent;
    };

    return TextNode;

  })();

  DocumentFragment = (function() {

    function DocumentFragment() {
      this.nodeType = 11;
      this.childNodes = [];
    }

    DocumentFragment.prototype.appendChild = function(child) {
      if (this.childNodes.length === 0) {
        this.firstChild = child;
      }
      return this.childNodes.push(child);
    };

    DocumentFragment.prototype.toString = function() {
      var i, output;
      output = "";
      i = 0;
      while (i < this.childNodes.length) {
        output += this.childNodes[i].toString();
        i++;
      }
      return output;
    };

    return DocumentFragment;

  })();

  Element = (function() {

    Element.prototype.voidElements = {
      area: 1,
      base: 1,
      br: 1,
      col: 1,
      command: 1,
      embed: 1,
      hr: 1,
      img: 1,
      input: 1,
      keygen: 1,
      link: 1,
      meta: 1,
      param: 1,
      source: 1,
      track: 1,
      wbr: 1
    };

    function Element(tagName) {
      this.tagName = tagName;
      this.attributes = {};
      this.childNodes = [];
      this.nodeType = 1;
    }

    Element.prototype.hasAttribute = function(attrName) {
      return attrName in this.attributes;
    };

    Element.prototype.getAttribute = function(name) {
      return this.attributes[name];
    };

    Element.prototype.setAttribute = function(name, value) {
      this.attributes[name] = value;
      return value;
    };

    Element.prototype.removeChild = function(child) {
      return console.error("Not implemented.");
    };

    Element.prototype.appendChild = function(child) {
      if (this.childNodes.length === 0) {
        this.firstChild = child;
      }
      return this.childNodes.push(child);
    };

    Element.prototype.toString = function() {
      var attr, i, output;
      output = "<" + this.tagName;
      for (attr in this.attributes) {
        output += " " + attr + "=\"" + this.attributes[attr] + "\"";
      }
      output += ">";
      i = 0;
      while (i < this.childNodes.length) {
        output += this.childNodes[i].toString();
        i++;
      }
      if (!(this.tagName in this.voidElements)) {
        output += "</" + this.tagName + ">";
      }
      return output;
    };

    return Element;

  })();

  /*
  A lightweight emulation of the document object. Can be used to render creatable markup as an HTML string instead of a DOM node.
  */

  emulatedDocument = {
    createTextNode: function(content) {
      return new TextNode(content);
    },
    createDocumentFragment: function() {
      return new DocumentFragment();
    },
    createElement: function(tagName) {
      return new Element(tagName);
    },
    body: new Element("body"),
    toString: function() {
      return this.body.toString();
    }
  };

  document = this.document || emulatedDocument;

  setDocument = function(doc) {
    return document = doc;
  };

  setEmulatedDocument = function(doc) {
    return document = emulatedDocument;
  };

  /*
  Regexes
  */

  regexIdOrClassSeparator = new RegExp("[#.]");

  regexIdOrClass = new RegExp("[#.][^#.]+", "g");

  /*
  Private
  */

  map = function(arr, f) {
    var i, output;
    output = [];
    i = 0;
    while (i < arr.length) {
      output.push(f(arr[i], i));
      i++;
    }
    return output;
  };

  each = function(arr, f) {
    var i, _results;
    i = 0;
    _results = [];
    while (i < arr.length) {
      f(arr[i], i);
      _results.push(i++);
    }
    return _results;
  };

  eachObj = function(o, f) {
    var attr, i, _results;
    i = 0;
    _results = [];
    for (attr in o) {
      f(attr, o[attr], i);
      _results.push(i++);
    }
    return _results;
  };

  filter = function(arr, f) {
    var i, output;
    output = [];
    i = 0;
    while (i < arr.length) {
      if (f(arr[i], i)) {
        output.push(arr[i]);
      }
      i++;
    }
    return output;
  };

  find = function(arr, f) {
    var i;
    i = 0;
    while (i < arr.length) {
      if (f(arr[i])) {
        return arr[i];
      }
      i++;
    }
    return null;
  };

  extend = function() {
    var args, obj;
    obj = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
    each(args, function(source) {
      var prop, _results;
      _results = [];
      for (prop in source) {
        if (source[prop] !== void 0) {
          _results.push(obj[prop] = source[prop]);
        } else {
          _results.push(void 0);
        }
      }
      return _results;
    });
    return obj;
  };

  toObject = function(arr, f) {
    var x;
    return extend.apply(null, [{}].concat(__slice.call((function() {
      var _i, _len, _results;
      _results = [];
      for (_i = 0, _len = arr.length; _i < _len; _i++) {
        x = arr[_i];
        _results.push(f(x));
      }
      return _results;
    })())));
  };

  keyValue = function(a, b) {
    var o;
    o = {};
    o[a] = b;
    return o;
  };

  orderedGroup = function(arr, propOrFunc) {
    var dict, getGroupKey, i, key, results;
    getGroupKey = (typeof propOrFunc === "function" ? propOrFunc : function(item) {
      return item[propOrFunc];
    });
    results = [];
    dict = {};
    i = 0;
    while (i < arr.length) {
      key = getGroupKey(arr[i]);
      if (!(key in dict)) {
        dict[key] = [];
        results.push({
          key: key,
          items: dict[key]
        });
      }
      dict[key].push(arr[i]);
      i++;
    }
    return results;
  };

  /*
  Indexes into an array, supports negative indices.
  */

  index = function(arr, i) {
    return arr[(i % arr.length + arr.length) % arr.length];
  };

  typeOf = function(value) {
    var s;
    s = typeof value;
    if (s === "object") {
      if (value) {
        if (typeof value.length === "number" && !(value.propertyIsEnumerable("length")) && typeof value.splice === "function") {
          s = "array";
        }
      } else {
        s = "null";
      }
    }
    return s;
  };

  curry = function() {
    var args, fn;
    fn = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
    return function() {
      var args2;
      args2 = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
      return fn.apply(this, args.concat(args2));
    };
  };

  splitOnce = function(str, delim) {
    var components, result;
    components = str.split(delim);
    result = [components.shift()];
    if (components.length) {
      result.push(components.join(delim));
    }
    return result;
  };

  /*
  Functional, nondestructive version of Array.prototype.splice.
  */

  splice = function() {
    var arr, elements, elementsLen, howMany, i, index, len, results;
    arr = arguments[0], index = arguments[1], howMany = arguments[2], elements = 4 <= arguments.length ? __slice.call(arguments, 3) : [];
    results = [];
    len = arr.length;
    i = 0;
    while (i < index && i < len) {
      results.push(arr[i]);
      i++;
    }
    i = 0;
    elementsLen = elements.length;
    while (i < elementsLen) {
      results.push(elements[i]);
      i++;
    }
    i = index + howMany;
    while (i < len) {
      results.push(arr[i]);
      i++;
    }
    return results;
  };

  /*
  Public
  */

  /*
  Creates a DOM element. Supported objects are defined in the types array.
  */

  create = function(arg, doc) {
    var match;
    if (doc == null) {
      doc = document || emulatedDocument;
    }
    match = find(types, function(creatable) {
      return creatable.isOfType(arg);
    });
    if (match) {
      return match.build(arg, doc);
    } else {
      return error("Unbuildable create argument: " + arg, arg);
    }
  };

  createHtml = function(arg) {
    return create(arg, emulatedDocument).toString();
  };

  /*
  A list of objects that the create function can create DOM elements from.
  In order of most to least common.
  */

  types = [
    {
      isOfType: function(o) {
        return o instanceof Array && o.length && typeof o[0] === 'string';
      },
      build: function(o, doc) {
        return createFromMarkupArray(o, doc);
      }
    }, {
      isOfType: function(o) {
        return typeof o === "string" || typeof o === "number";
      },
      build: function(o, doc) {
        return doc.createTextNode(o);
      }
    }, {
      isOfType: function(o) {
        return typeof o === "function";
      },
      build: function(o, doc) {
        return o(doc);
      }
    }, {
      isOfType: function(o) {
        return !(o != null);
      },
      build: function(o) {
        return o;
      }
    }, {
      isOfType: function(o) {
        return isDomNode(o);
      },
      build: function(o) {
        return o;
      }
    }, {
      isOfType: function(o) {
        return typeof jQuery !== "undefined" && o instanceof jQuery;
      },
      build: function(o) {
        return o[0];
      }
    }, {
      isOfType: function(o) {
        return o instanceof Array && (!o.length || o[0] instanceof Array);
      },
      build: function(o, doc) {
        var child, fragment, _i, _len;
        fragment = doc.createDocumentFragment();
        for (_i = 0, _len = o.length; _i < _len; _i++) {
          child = o[_i];
          fragment.appendChild(create(child, doc));
        }
        return fragment;
      }
    }
  ];

  plugins = {
    html: function(el, html) {
      if (html && el.firstChild) {
        return el.innerHTML = el.firstChild.nodeValue;
      }
    }
    /*
    Parsing Functions
    */

    /*
    Parses the given markup array and returns a newly created element.
    */

  };

  createFromMarkupArray = function(markup, doc) {
    var attrs, attrsOmitted, children, descendantTags, element, pluginActions, selectorAttrs, tagInput, tagName, tagNameString, tags;
    attrsOmitted = typeOf(markup[1]) !== "object";
    tagInput = markup[0];
    attrs = (!attrsOmitted ? markup[1] : {});
    children = markup[(attrsOmitted ? 1 : 2)];
    tags = splitOnce(tagInput, " ");
    tagNameString = tags[0];
    descendantTags = tags[1];
    if (descendantTags) {
      children = [[descendantTags, attrs, children]];
      attrs = {};
    }
    element = void 0;
    try {
      tagName = parseTagName(tagNameString);
      element = doc.createElement(tagName);
    } catch (e) {
      error("Invalid tag name: " + tagName, markup);
    }
    pluginActions = [];
    eachObj(plugins, function(pluginAttr, f) {
      if (pluginAttr in attrs) {
        if (attrs[pluginAttr]) {
          pluginActions.push(curry(f, element, attrs[pluginAttr]));
        }
        return delete attrs[pluginAttr];
      }
    });
    selectorAttrs = parseSelectorAttributes(tagNameString);
    addAttributes(element, mergeAttributes(attrs, selectorAttrs));
    if (children != null) {
      addChildren(element, children, doc);
    }
    each(pluginActions, function(f) {
      return f();
    });
    return element;
  };

  /*
  Returns the tag name from a tag name string that could have CSS selector syntax.
  */

  parseTagName = function(tagNameString) {
    return tagNameString.split(regexIdOrClassSeparator)[0] || "div";
  };

  /*
  Parses the tagName for CSS selector syntax and returns an object of attribute names and values.
  */

  parseSelectorAttributes = function(tagNameString) {
    var afterSep, attrMap, selObjects, selectors;
    attrMap = {
      "#": "id",
      ".": "class"
    };
    afterSep = tagNameString.substring(tagNameString.indexOf(regexIdOrClassSeparator));
    selectors = afterSep.match(regexIdOrClass) || [];
    selObjects = map(selectors, function(sel) {
      return {
        sep: attrMap[sel[0]],
        name: sel.substring(1)
      };
    });
    return toObject(orderedGroup(selObjects, "sep"), function(g) {
      var item;
      return keyValue(g.key, (g.key === "class" ? ((function() {
        var _i, _len, _ref, _results;
        _ref = g.items;
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          item = _ref[_i];
          _results.push(item.name);
        }
        return _results;
      })()).join(" ") : index(g.items, -1).name));
    });
  };

  /*
  Parses the attributes and adds them to the element.
  */

  addAttributes = function(element, attrs) {
    var attr, _results;
    _results = [];
    for (attr in attrs) {
      if (attr === "checked" || attr === "disabled" || attr === "selected") {
        if (attrs[attr]) {
          _results.push(element.setAttribute(attr, attr));
        } else {
          _results.push(void 0);
        }
      } else {
        if (attrs[attr] != null) {
          _results.push(element.setAttribute(attr, attrs[attr]));
        } else {
          _results.push(void 0);
        }
      }
    }
    return _results;
  };

  /*
  Returns true if the given class value string contains the given class.
  */

  containsClass = function(str, className) {
    return str && (" " + str + " ").indexOf(" " + className + " ") > -1;
  };

  /*
  Adds the given children to the element.
  */

  addChildren = function(node, children, doc) {
    var child, _i, _len, _results;
    if (typeof children === "string" || typeof children === "number") {
      children = [children];
    }
    _results = [];
    for (_i = 0, _len = children.length; _i < _len; _i++) {
      child = children[_i];
      if (child != null) {
        _results.push(node.appendChild(create(child, doc)));
      }
    }
    return _results;
  };

  /*
  Helper Functions
  */

  /*
  Returns true if the given object seems to be a DomNode.
  */

  isDomNode = function(node) {
    return node && typeof node.nodeType === "number";
  };

  mergeAttributes = function(a, b) {
    var aProp, bProp, output, uniqueClass;
    uniqueClass = function(singleClass) {
      return !containsClass(a["class"], singleClass);
    };
    output = {};
    for (aProp in a) {
      output[aProp] = a[aProp];
    }
    for (bProp in b) {
      output[bProp] = b[bProp];
    }
    output["class"] = (a["class"] && b["class"] ? [].concat(a["class"], filter(b["class"].split(" "), uniqueClass)).join(" ") : a["class"] || b["class"]);
    return output;
  };

  /*
  Error Handling
  */

  /*
  Abstracts the error handling for Creatable so that we can substitute a different handler if necessary.
  */

  error = function(message, params) {
    if (params) {
      console.error(params);
    }
    throw new Error(message || "ERROR");
  };

  /*
  Render Helper
  */

  render = function(markup) {
    var body;
    body = document.body;
    while (body.firstChild) {
      body.removeChild(body.firstChild);
    }
    return body.appendChild(create(markup));
  };

  extend((typeof exports !== "undefined" && exports !== null) && exports || (this.Creatable = {}), {
    emulatedDocument: emulatedDocument,
    setDocument: setDocument,
    TextNode: TextNode,
    Element: Element,
    DocumentFragment: DocumentFragment,
    create: create,
    createHtml: createHtml,
    types: types,
    plugins: plugins,
    createFromMarkupArray: createFromMarkupArray,
    parseTagName: parseTagName,
    parseSelectorAttributes: parseSelectorAttributes,
    addAttributes: addAttributes,
    containsClass: containsClass,
    isDomNode: isDomNode,
    mergeAttributes: mergeAttributes,
    error: error,
    render: render
  });

}).call(this);


text:
FactoryGirl.define do

  factory :video do
    from_file do
      begin
        FileUtils.mkdir_p(Rails.root.join('/tmp/test'))
      rescue # rubocop:disable HandleExceptions
      end
      FileUtils.cp(
        Rails.root.join('db/seeds/videos/example.m4v'),
        Rails.root.join('/tmp/test/example.m4v')
      )
      Rails.root.join('/tmp/test/example.m4v')
    end
  end

  factory :video_one_second, parent: :video do
    from_file do
      begin
        FileUtils.mkdir_p(Rails.root.join('/tmp/test'))
      rescue # rubocop:disable HandleExceptions
      end
      FileUtils.cp(
        Rails.root.join('db/seeds/videos/one_second.m4v'),
        Rails.root.join('/tmp/test/one_second.m4v')
      )
      Rails.root.join('/tmp/test/one_second.m4v')
    end
  end

  factory :video_one_second_2nd, parent: :video do
    from_file do
      begin
        FileUtils.mkdir_p(Rails.root.join('/tmp/test'))
      rescue # rubocop:disable HandleExceptions
      end
      FileUtils.cp(
        Rails.root.join('db/seeds/videos/one_second_2nd.mp4'),
        Rails.root.join('/tmp/test/one_second_2nd.mp4')
      )
      Rails.root.join('/tmp/test/one_second_2nd.mp4')
    end
  end

  factory :video_one_second_3rd, parent: :video do
    from_file do
      begin
        FileUtils.mkdir_p(Rails.root.join('/tmp/test'))
      rescue # rubocop:disable HandleExceptions
      end
      FileUtils.cp(
        Rails.root.join('db/seeds/videos/one_second_3rd.mp4'),
        Rails.root.join('/tmp/test/one_second_3rd.mp4')
      )
      Rails.root.join('/tmp/test/one_second_3rd.mp4')
    end
  end

  factory :video_one_second_4th, parent: :video do
    from_file do
      begin
        FileUtils.mkdir_p(Rails.root.join('/tmp/test'))
      rescue # rubocop:disable HandleExceptions
      end
      FileUtils.cp(
        Rails.root.join('db/seeds/videos/one_second_4th.mp4'),
        Rails.root.join('/tmp/test/one_second_4th.mp4')
      )
      Rails.root.join('/tmp/test/one_second_4th.mp4')
    end
  end

  factory :video_unseen, parent: :video_one_second do
    seen false
  end

  factory :video_liked, parent: :video_one_second_2nd do
    seen true
    like true
  end

  factory :video_not_liked, parent: :video_one_second_3rd do
    seen true
    like false
  end

  factory :video_not_liked_lately, parent: :video_one_second_4th do
    seen true
    like false
    created_at 2.hours.ago
    updated_at 2.hours.ago
  end

  factory :video_streamable, parent: :video do
    from_file do
      begin
        FileUtils.mkdir_p(Rails.root.join('/tmp/test'))
      rescue # rubocop:disable HandleExceptions
      end
      FileUtils.cp(
        Rails.root.join('db/seeds/videos/streamable.mp4'),
        Rails.root.join('/tmp/test/streamable.mp4')
      )
      Rails.root.join('/tmp/test/streamable.mp4')
    end
  end

end


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Categories on The Art Of Computer Science</title>
    <link>http://wesamhaboush.github.io/categories/</link>
    <description>Recent content in Categories on The Art Of Computer Science</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-US</language>
    <copyright>Copyright (c) 2018, all rights reserved.</copyright>

	<atom:link href="http://wesamhaboush.github.io/categories/index.xml" rel="self" type="application/rss+xml" />

  </channel>
</rss>


text:
<?php
	/*	CONCLUSIONS
		+ isset() prevents E_NOTICE errors.
		+ Input text fields send a string by default.
			- isset optional (preventing hack attack)
			- We can strlen after checking it has been set if we want to allow 0;
			- We can deny 0 by the function empty or directly if($_POST[''])
		+ Input radio fields sends 'on' if selected and null if not
	*/
	if (isset($_GET['param']) == 1){
		$return = '';
		$result_err = '';
		$error = array();

		//Verify that the name is valid (not empty or 0)
		if (isset($_POST['name'])){
			if ($_POST['name'])
				$return .= 'Name: ' . $_POST['name'] . '
';
			else
				$error[] = -1;
		}else
			$error[] = -9;
		// Verify that the password is between 6 and 12 characters
		if (isset($_POST['pass'])){
			if (strlen(trim($_POST['pass'])) > 5 && strlen(trim($_POST['pass'])) < 13)
				$return .= 'Password: ' . $_POST['pass'] . '
';
			else
				$error[] = -2;
		}else
			$error[] = -9;

		//Verify that the gender is male or female
		if (isset($_POST['gender']))
			if (strcmp($_POST['gender'], 'male') || strcmp($_POST['gender'], 'female'))
				$return .= 'Gender: ' . $_POST['gender'] . '
';
			else
				$error[] = -9;
		else
			$error[] = -3;

		//Verify a correct date and get your age
		if (isset($_POST['birthday'])){
			if (preg_match("/^[0-9]{4}-[0-1][0-9]-[0-3][0-9]$/", $_POST['birthday'])){
				$items = explode("-", $_POST['birthday']);
				if (checkdate($items[1], $items[2], $items[0])){ //checkdate(m-d-y)
					if ((0 == $items[0] % 4) && (0 != $items[0] % 100) || (0 == $items[0] % 400))//If you were born in a lip-year or lip - 1, then we have to add 5 days, else, we add 4 days
						$bis = 4;
					else
						$bis = 5;
					if (date_diff(date_create($_POST['birthday']) , date_create(date('Y-m-d')))->format("%R%a days") > (6569 + $bis)) //365*18
						$return .= 'Birthday date: ' . $_POST['birthday'] . '
';
					else
						$error[] = -10;
				}else
					$error[] = -4;
			}else
				$error[] = -11;
		}else
			$error[] = -9;

		//Verify you've chosen a country of our list
		$list = Array('España', 'Francia', 'Dinamarca');
		if (isset($_POST['country']))
			if (in_array($_POST['country'], $list))
				$return .= 'Country: ' . $_POST['country'] . '
';
			else
				$error[] = -5;
		else
			$error[] = -9;

		//Verify you've chosen a city of our list
		$list = Array('Madrid', 'Paris', 'NoIdea');
		if (isset($_POST['city'])){
			$print_aux = '';
			foreach ($_POST['city'] as $value)
				if (in_array($value, $list))
					$print_aux .= $value . ', ';
			$return .= 'City: ' . substr($print_aux, 0, -2) . '
';
		}else
			$error[] = -9;

		//Verify the text-area contains a comment
		if (isset($_POST['textarea']))
			if (!empty($_POST['textarea']))
				$return .= 'TextArea: ' . $_POST['textarea'] . '
';
			else
				$error[] = -7;
		else
			$error[] = -9;

		if (isset($error)){
			foreach ($error as $value){
				switch($value){
					case -1:
						$result_err .= "The username can't be empty or 0" . '
' . PHP_EOL;
						break;
					case -2:
						$result_err .= "The password must be between 6 and 12 characters" . "
" . PHP_EOL;
						break;
					case -3:
						$result_err .= "You must select a gender" . "
" . PHP_EOL;
						break;
					case -4:
						$result_err .= "The birthday date isn't correct " . "
" . PHP_EOL;
						break;
					case -5:
						$result_err .= "You haven't selected a country" . "
" . PHP_EOL;
						break;
					case -6:
						$result_err .= 'Watch out your text-area' . '
' . PHP_EOL;
						break;
					case -7:
						$result_err .= 'Watch out your username' . '
' . PHP_EOL;
						break;
					case -8:
						$result_err .= 'Watch out your picture' . '
' . PHP_EOL;
						break;
					case -9:
						$result_err .= 'It seems that someone is trying to hack my system' . '
' . PHP_EOL;
						break;
					case -10:
						$result_err .= 'Your age is under 18' . '
' . PHP_EOL;
						break;
					case -11:
						$result_err .= 'Define a proper date(dd/mm/yyyy)' . '
' . PHP_EOL;
						break;
					case -12:
						$result_err .= "Our system doesn't find the country you've selected." . "
" . PHP_EOL;
						break;
					case -13:
						$result_err .= "Size under 5 Mb" . "
" . PHP_EOL;
						break;
				}
			}
		}
	}

	$print_form = '';
	$print_form .= '';
		$print_form .= '';
			$print_form .= '<meta charset="UTF-8">';
			$print_form .= '<title>Práctica 1</title>';
			$print_form .= '';
		$print_form .= '';
		$print_form .= '';
			$print_form .= '<form action="' . $_SERVER['PHP_SELF'] . '?param=1" method="POST">';
				$print_form .= '
FORMULARIO
';
				$print_form .= 'Name: <input type="text" name="name" placeholder="Enter Your Name" />';
				$print_form .= 'Password: <input type="password" name="pass" placeholder="Enter Your pass" />';
				$print_form .= '<fieldset>';
					$print_form .= '<legend align="center">Gender</legend>';
					$print_form .= 'Male: <input type="radio" name="gender" value="male" />';
					$print_form .= 'Female: <input type="radio" name="gender" value="female" />';
				$print_form .= '</fieldset>';
				$print_form .= 'Fecha de Nacimiento: <input type="date" name="birthday" />';
				$print_form .= 'Country:';
					$print_form .= '<select name="country">';
						$print_form .= '<option value=""></option>';
						$print_form .= '<option value="España">España</option>';
						$print_form .= '<option value="Francia">Francia</option>';
						$print_form .= '<option value="Dinamarca">Dinamarca</option>';
					$print_form .= '</select>';
				$print_form .= '';
				$print_form .= 'CITY:';
					$print_form .= '<select name="city[]" multiple>';
						$print_form .= '<option value=""></option>';
						$print_form .= '<option value="Madrid">Madrid</option>';
						$print_form .= '<option value="Paris">París</option>';
						$print_form .= '<option value="NoIdea">NoIdea</option>';
					$print_form .= '</select>';
				$print_form .= '';
				$print_form .= '<input type="checkbox" name="confirm">OK';
				$print_form .= 'TextArea: <textarea name="textarea"></textarea>';
				$print_form .= 'Upload a picture: <input name="picture[]" type="file"/>';
				$print_form .= '<input type="image" style="background:black;" name="send_img" src="./images/logo.png" />';
				$print_form .= '<input type="submit"/>';
				$print_form .= '<input type="reset"/>';
			$print_form .= '</form>';
			$print_form .= '
';
			if (!empty($result_err)){
				$print_form .= '
ERRORES
';
				$print_form .= '
';
					$print_form .= $result_err;
				$print_form .= '
';
			}else if(!empty($return)){
				$print_form .= '
VALORES
';
				$print_form .= '
';
					$print_form .= $return;
				$print_form .= '
';
			}
			$print_form .= '
';
		$print_form .= '';
	$print_form .= '';

	echo $print_form;
?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<crossQueryResult totalDocs="1" startDoc="0" endDoc="0">
   <facet field="group-subject" totalGroups="16" totalDocs="1">
      <group value="African History" rank="1" totalSubGroups="0" totalDocs="0" startDoc="0"
             endDoc="0"/>
      <group value="African Studies" rank="2" totalSubGroups="0" totalDocs="0" startDoc="0"
             endDoc="0"/>
      <group value="Ancient History" rank="3" totalSubGroups="0" totalDocs="0" startDoc="0"
             endDoc="0"/>
      <group value="California and the West" rank="4" totalSubGroups="0" totalDocs="0"
             startDoc="0"
             endDoc="0"/>
      <group value="Classical History" rank="5" totalSubGroups="0" totalDocs="0"
             startDoc="0"
             endDoc="0"/>
      <group value="Classical Politics" rank="6" totalSubGroups="0" totalDocs="0"
             startDoc="0"
             endDoc="0"/>
      <group value="Classical Religions" rank="7" totalSubGroups="0" totalDocs="0"
             startDoc="0"
             endDoc="0"/>
      <group value="Classics" rank="8" totalSubGroups="0" totalDocs="0" startDoc="0"
             endDoc="0"/>
      <group value="Environmental Studies" rank="9" totalSubGroups="0" totalDocs="0"
             startDoc="0"
             endDoc="0"/>
      <group value="Philosophy" rank="10" totalSubGroups="0" totalDocs="0" startDoc="0"
             endDoc="0"/>
      <group value="Political Theory" rank="11" totalSubGroups="0" totalDocs="0"
             startDoc="0"
             endDoc="0"/>
      <group value="Politics" rank="12" totalSubGroups="0" totalDocs="1" startDoc="0"
             endDoc="0"/>
      <group value="Social Theory" rank="13" totalSubGroups="0" totalDocs="0" startDoc="0"
             endDoc="0"/>
      <group value="Social and Political Thought" rank="14" totalSubGroups="0" totalDocs="0"
             startDoc="0"
             endDoc="0"/>
      <group value="Sociology" rank="15" totalSubGroups="0" totalDocs="1" startDoc="0"
             endDoc="0"/>
      <group value="Urban Studies" rank="16" totalSubGroups="0" totalDocs="1" startDoc="0"
             endDoc="0"/>
   </facet>
</crossQueryResult>


text:
{% url 'browse_registrationcenters' as registrationcenter_url %}
{% url 'browse_subconstituencies' as subconstituency_url %}
{% url 'browse_constituencies' as constituency_url %}
{% url 'browse_offices' as office_url %}

<nav class="tabs">
  {% include 'includes/tablink.html' with url=registrationcenter_url linktext=_("Registration Centers") %}
  {% include 'includes/tablink.html' with url=subconstituency_url linktext=_("Subconstituencies") %}
  {% include 'includes/tablink.html' with url=constituency_url linktext=_("Constituencies") %}
  {% include 'includes/tablink.html' with url=office_url linktext=_("Offices") %}
</nav>


text:
/**
 *
 * @file psbarrier.c
 *
 *  PLASMA auxiliary routines
 *  PLASMA is a software package provided by Univ. of Tennessee,
 *  Univ. of California Berkeley and Univ. of Colorado Denver
 *
 * Barrier for algorithm mixing computation on tile/panel.
 *
 * @version 2.4.2
 * @author Mathieu Faverge
 * @date 2009-11-15
 *
 * @generated s Thu Sep 15 12:09:24 2011
 *
 **/
#include "common.h"

#define A(m,n) BLKADDR(A, float, m, n)

/***************************************************************************//**
 *  Barrier from tiles to panels
 **/
void plasma_psbarrier_tl2pnl_quark(PLASMA_desc A, PLASMA_sequence *sequence, PLASMA_request *request)
{
    int m, n;
    plasma_context_t *plasma;
    Quark_Task_Flags task_flags = Quark_Task_Flags_Initializer;

    plasma = plasma_context_self();
    if (sequence->status != PLASMA_SUCCESS)
        return;
    QUARK_Task_Flag_Set(&task_flags, TASK_SEQUENCE, (intptr_t)sequence->quark_sequence);

    for (n = 0; n < A.nt; n++)
    {
        /* Protection from previous GATHERV */
        QUARK_Insert_Task(plasma->quark, CORE_foo_quark, &task_flags,
                          sizeof(float)*A.mb*A.nb, A(0, n), INOUT,
                          0);

        for (m = 0; m < A.mt; m++)
        {
            QUARK_Insert_Task(plasma->quark, CORE_foo2_quark, &task_flags,
                              sizeof(float)*A.mb*A.nb, A(0, n), INOUT | GATHERV,
                              sizeof(float)*A.mb*A.nb, A(m, n), INOUT,
                              0);
        }

        /* Protection to next GATHERV */
        QUARK_Insert_Task(plasma->quark, CORE_foo_quark, &task_flags,
                          sizeof(float)*A.mb*A.nb, A(0, n), INOUT,
                          0);
    }
}

/***************************************************************************//**
 *  Barrier from panels to tiles
 **/
void plasma_psbarrier_pnl2tl_quark(PLASMA_desc A, PLASMA_sequence *sequence, PLASMA_request *request)
{
    int m, n;
    plasma_context_t *plasma;
    Quark_Task_Flags task_flags = Quark_Task_Flags_Initializer;

    plasma = plasma_context_self();
    if (sequence->status != PLASMA_SUCCESS)
        return;
    QUARK_Task_Flag_Set(&task_flags, TASK_SEQUENCE, (intptr_t)sequence->quark_sequence);

    for (n = 0; n < A.nt; n++)
    {
        /* Protection from previous GATHERV */
        QUARK_Insert_Task(plasma->quark, CORE_foo_quark, &task_flags,
                          sizeof(float)*A.mb*A.nb, A(0, n), INOUT,
                          0);

        for (m = 0; m < A.mt; m++)
        {
            QUARK_Insert_Task(plasma->quark, CORE_foo2_quark, &task_flags,
                              sizeof(float)*A.mb*A.nb, A(0, n), INPUT,
                              sizeof(float)*A.mb*A.nb, A(m, n), INOUT,
                              0);
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Manzanilla · Tag relations</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Attributes

             <form class="form">

                Type
                <select class="form-control" name="type" id="type">
                    <optgroup label="Arrow"></optgroup>
                    <option value='arrow-delimitation'>  Delimitation</option>
                    <option value='arrow-denomination'>  Denomination</option>

                    <optgroup label="  Dynamism"></optgroup>
                    <option value='arrow-dynamism-spatial'>    Spatial</option>
                    <option value='arrow-dynamism-temporal'>    Temporal</option>

                    <optgroup label="Color"></optgroup>
                    <option value='color-contrast'>  Contrast</option>
                    <option value='color-realism'>  Realism</option>

                    <optgroup label="Label"></optgroup>
                    <option value='label-denomination'>  Denomination</option>
                    <option value='label-explanation'>  Explanation</option>

                    <optgroup label="Number"></optgroup>
                    <option value='number-denomination'>  Denomination</option>
                    <option value='number-temporality'>  Temporality</option>

                    <option value='logical operator'>Logical Operator</option>

                    <option value='other'>Other</option>

                </select>

                Annotation
                <input type="text" class="form-control"  autocomplete="off" name="annotation" id="annotation" placeholder="Annotation">

              <input type="hidden" name="relation_id" id="relation_id" value=""/>
             </form>

            <button type="button" class="btn btn-default" data-dismiss="modal" id='cancel-vpk'>Cancel</button>
            <button type="button" class="btn btn-primary" id='save-vpk'>Save VPK</button>

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Manzanilla

Home

Hello, user

My tags

Tag image

Log out

Tagging image "<?php echo $_GET['img']?>". Tag the image with relations between EcoLexicon concepts.

<canvas id='the-canvas'></canvas>

      <input type='hidden' name='id-image' id='id-image' value="<?php echo $_GET['id']?>"/>
      <input type='hidden' name='image' id='image' value="<?php echo $_GET['img']?>"/>

Current annotations

Loading list

Add new annotations

      <form class="form-inline">

        <input type="hidden" name="source-id" id="source-id" value=""/>
        <input type="hidden" name="source-concept" id="source-concept" value=""/>
        <input type="hidden" name="target-id" id="target-id" value=""/>
        <input type="hidden" name="target-concept" id="target-concept" value=""/>

            <input type="text" class="form-control"  autocomplete="off" name="source" id="source" placeholder="Source concept">

          Password
          <select class="form-control" name="relation" id="relation">
            <optgroup label="Generic-specific relations">
              <option value="1">type of</option>
            </optgroup>

            <optgroup label="Part-whole relations">
              <option value="3">part of</option>
              <option value="9">made of</option>
              <option value="16">delimited by</option>
              <option value="11">located at</option>
              <option value="31">takes place in</option>
              <option value="33">phase of</option>
            </optgroup>

            <optgroup label="Non-hierarchical relations">
              <option value="18">affects</option>
              <option value="14">attribute of</option>
              <option value="32">causes</option>
              <option value="2">opposite of</option>
              <option value="20">studies</option>
              <option value="23">measures</option>
              <option value="22">represents</option>
              <option value="5">result of</option>
              <option value="26">effected by</option>
              <option value="7">has function</option>
            </optgroup>
          </select>

            <input type="text" class="form-control"  autocomplete="off" id="target" placeholder="Target concept">

        <button type='button' id='add-anno-relation' class="btn btn-primary">Add</button>
      </form>

      <input type='hidden' name='id-image' id='id-image' value="<?php echo $_GET['id']?>"/>
      <input type='hidden' name='image' id='image' value="<?php echo $_GET['img']?>"/>

          Error:

              Suggestions from EcoLexicon

Loading suggestions


text:
package stroom.pipeline;

import stroom.docref.DocRef;
import stroom.docstore.api.DocumentResourceHelper;
import stroom.docstore.shared.DocRefUtil;
import stroom.event.logging.rs.api.AutoLogged;
import stroom.pipeline.factory.ElementRegistryFactory;
import stroom.pipeline.factory.PipelineDataValidator;
import stroom.pipeline.factory.PipelineStackLoader;
import stroom.pipeline.shared.FetchPipelineXmlResponse;
import stroom.pipeline.shared.FetchPropertyTypesResult;
import stroom.pipeline.shared.PipelineDataMerger;
import stroom.pipeline.shared.PipelineDoc;
import stroom.pipeline.shared.PipelineResource;
import stroom.pipeline.shared.SavePipelineXmlRequest;
import stroom.pipeline.shared.data.PipelineData;
import stroom.pipeline.shared.data.PipelineElementType;
import stroom.util.shared.EntityServiceException;
import stroom.util.shared.FetchWithUuid;
import stroom.util.shared.PermissionException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Provider;

@AutoLogged
class PipelineResourceImpl implements PipelineResource, FetchWithUuid<PipelineDoc> {

    private final Provider<ElementRegistryFactory> elementRegistryFactoryProvider;
    private final Provider<PipelineService> pipelineServiceProvider;

    @Inject
    PipelineResourceImpl(final Provider<PipelineService> pipelineServiceProvider,
                         final Provider<ElementRegistryFactory> elementRegistryFactoryProvider) {
        this.pipelineServiceProvider = pipelineServiceProvider;
        this.elementRegistryFactoryProvider = elementRegistryFactoryProvider;
    }

    @Override
    public PipelineDoc fetch(final String uuid) {
        return pipelineServiceProvider.get().fetch(uuid);
    }

    @Override
    public PipelineDoc update(final String uuid, final PipelineDoc doc) {
        return pipelineServiceProvider.get().update(uuid, doc);
    }

    @Override
    public Boolean savePipelineXml(final SavePipelineXmlRequest request) {
        return pipelineServiceProvider.get().savePipelineXml(request.getPipeline(), request.getXml());
    }

    @Override
    public FetchPipelineXmlResponse fetchPipelineXml(final DocRef pipeline) {
        if (pipeline != null) {
            final String xml = pipelineServiceProvider.get().fetchPipelineXml(pipeline);
            return new FetchPipelineXmlResponse(pipeline, xml);
        }

        return null;
    }

    @Override
    public List<PipelineData> fetchPipelineData(final DocRef pipeline) {
        return pipelineServiceProvider.get().fetchPipelineData(pipeline);
    }

    @Override
    public List<FetchPropertyTypesResult> getPropertyTypes() {
        return  elementRegistryFactoryProvider.get().get().getPropertyTypes()
                    .entrySet()
                    .stream()
                    .map(entry ->
                            new FetchPropertyTypesResult(entry.getKey(), entry.getValue()))
                    .collect(Collectors.toList());
    }
}


text:
The contribution guideline is derived from the SlimPHP contribution guideline

## Pull Requests

1. Fork the Moon repository
2. Create a new branch for each feature or improvement
3. Send a pull request from each feature branch to the **master** branch

It is very important to separate new features or improvements into separate feature branches and to send a
pull request for each branch.

This allows me to review and pull in new features or improvements individually.

## Style Guide

All pull requests must adhere to the code style specified in the `.php_cs.dist` file, you can easily run `composer fix` to do it automatically.
Moon uses [PHP-CS-Fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) to fix the code style.

## Unit Testing

All pull requests must be accompanied by passing unit tests and complete code coverage.
Moon uses [PHPUnit](https://github.com/sebastianbergmann/phpunit) to test the code.


text:
package hu.akarnokd.rxjava2.internal.operators.nbp;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;

import org.junit.Test;

import hu.akarnokd.rxjava2.*;
import hu.akarnokd.rxjava2.NbpObservable.NbpSubscriber;
import hu.akarnokd.rxjava2.exceptions.TestException;
import hu.akarnokd.rxjava2.functions.Predicate;
import hu.akarnokd.rxjava2.subscribers.nbp.NbpTestSubscriber;
;

public class NbpOperatorTakeUntilPredicateTest {
    @Test
    public void takeEmpty() {
        NbpSubscriber<Object> o = TestHelper.mockNbpSubscriber();

        NbpObservable.empty().takeUntil(new Predicate<Object>() {
            @Override
            public boolean test(Object v) {
                return true;
            }
        }).subscribe(o);

        verify(o, never()).onNext(any());
        verify(o, never()).onError(any(Throwable.class));
        verify(o).onComplete();
    }
    @Test
    public void takeAll() {
        NbpSubscriber<Object> o = TestHelper.mockNbpSubscriber();

        NbpObservable.just(1, 2).takeUntil(new Predicate<Integer>() {
            @Override
            public boolean test(Integer v) {
                return false;
            }
        }).subscribe(o);

        verify(o).onNext(1);
        verify(o).onNext(2);
        verify(o, never()).onError(any(Throwable.class));
        verify(o).onComplete();
    }
    @Test
    public void takeFirst() {
        NbpSubscriber<Object> o = TestHelper.mockNbpSubscriber();

        NbpObservable.just(1, 2).takeUntil(new Predicate<Integer>() {
            @Override
            public boolean test(Integer v) {
                return true;
            }
        }).subscribe(o);

        verify(o).onNext(1);
        verify(o, never()).onNext(2);
        verify(o, never()).onError(any(Throwable.class));
        verify(o).onComplete();
    }
    @Test
    public void takeSome() {
        NbpSubscriber<Object> o = TestHelper.mockNbpSubscriber();

        NbpObservable.just(1, 2, 3).takeUntil(new Predicate<Integer>() {
            @Override
            public boolean test(Integer t1) {
                return t1 == 2;
            }
        })
        .subscribe(o);

        verify(o).onNext(1);
        verify(o).onNext(2);
        verify(o, never()).onNext(3);
        verify(o, never()).onError(any(Throwable.class));
        verify(o).onComplete();
    }
    @Test
    public void functionThrows() {
        NbpSubscriber<Object> o = TestHelper.mockNbpSubscriber();

        Predicate<Integer> predicate = (new Predicate<Integer>() {
            @Override
            public boolean test(Integer t1) {
                    throw new TestException("Forced failure");
            }
        });
        NbpObservable.just(1, 2, 3).takeUntil(predicate).subscribe(o);

        verify(o).onNext(1);
        verify(o, never()).onNext(2);
        verify(o, never()).onNext(3);
        verify(o).onError(any(TestException.class));
        verify(o, never()).onComplete();
    }
    @Test
    public void sourceThrows() {
        NbpSubscriber<Object> o = TestHelper.mockNbpSubscriber();

        NbpObservable.just(1)
        .concatWith(NbpObservable.<Integer>error(new TestException()))
        .concatWith(NbpObservable.just(2))
        .takeUntil(new Predicate<Integer>() {
            @Override
            public boolean test(Integer v) {
                return false;
            }
        }).subscribe(o);

        verify(o).onNext(1);
        verify(o, never()).onNext(2);
        verify(o).onError(any(TestException.class));
        verify(o, never()).onComplete();
    }

    @Test
    public void testErrorIncludesLastValueAsCause() {
        NbpTestSubscriber<String> ts = new NbpTestSubscriber<String>();
        final TestException e = new TestException("Forced failure");
        Predicate<String> predicate = (new Predicate<String>() {
            @Override
            public boolean test(String t) {
                    throw e;
            }
        });
        NbpObservable.just("abc").takeUntil(predicate).subscribe(ts);

        ts.assertTerminated();
        ts.assertNotComplete();
        ts.assertError(TestException.class);
        // FIXME last cause value is not saved
//        assertTrue(ts.errors().get(0).getCause().getMessage().contains("abc"));
    }
}


text:
using System.Drawing;
using Gwen.ControlInternal;
using Newtonsoft.Json;

namespace Gwen.Control
{
    /// <summary>
    /// Static text label.
    /// </summary>
    [JsonObject(MemberSerialization.OptIn)]
    [JsonConverter(typeof(Serialization.GwenConverter))]
    public class Label : ControlBase
    {
        protected readonly TextControl text;
        private Pos align;
        private Padding textPadding;
        private bool autoSizeToContents;

        /// <summary>
        /// Text alignment.
        /// </summary>
        [JsonProperty]
        public Pos Alignment { get { return align; } set { align = value; Invalidate(); } }

        /// <summary>
        /// Text.
        /// </summary>
        [JsonProperty]
        public virtual string Text { get { return text.Text; } set { SetText(value); } }

        /// <summary>
        /// Font.
        /// </summary>
        [JsonProperty]
        public Font Font
        {
            get { return text.Font; }
            set
            {
                text.Font = value;
                if (autoSizeToContents)
                    SizeToContents();
                Invalidate();
            }
        }

        /// <summary>
        /// Internal Text color (changes will be lost!). Use TextColorOverride to set the TextColor.
        /// </summary>
        public Color TextColor { get { return text.TextColor; } set { text.TextColor = value; } }

        /// <summary>
        /// Custom Text color.
        /// </summary>
        [JsonProperty]
        public Color TextColorOverride { get { return text.TextColorOverride; } set { text.TextColorOverride = value; } }

        /// <summary>
        /// Text override - used to display different string.
        /// </summary>
        public string TextOverride { get { return text.TextOverride; } set { text.TextOverride = value; } }

        /// <summary>
        /// Width of the text (in pixels).
        /// </summary>
        public int TextWidth { get { return text.Width; } }

        /// <summary>
        /// Height of the text (in pixels).
        /// </summary>
        public int TextHeight { get { return text.Height; } }

        public int TextX { get { return text.X; } }
        public int TextY { get { return text.Y; } }

        /// <summary>
        /// Text length (in characters).
        /// </summary>
        public int TextLength { get { return text.Length; } }
        public int TextRight { get { return text.Right; } }
        public virtual void MakeColorNormal() { TextColor = Skin.Colors.Label.Default; }
        public virtual void MakeColorBright() { TextColor = Skin.Colors.Label.Bright; }
        public virtual void MakeColorDark() { TextColor = Skin.Colors.Label.Dark; }
        public virtual void MakeColorHighlight() { TextColor = Skin.Colors.Label.Highlight; }

        /// <summary>
        /// Specifies wheter the renderer should cache this text or not. Set this to false for dynamic or frequently changing texts.
        /// </summary>
        [JsonProperty]
        public bool ShouldCacheText { get { return text.ShouldCacheText; } set { text.ShouldCacheText = value; } }

        /// <summary>
        /// Determines if the control should autosize to its text.
        /// </summary>
        [JsonProperty]
        public bool AutoSizeToContents { get { return autoSizeToContents; } set { autoSizeToContents = value; Invalidate(); InvalidateParent(); } }

        /// <summary>
        /// Text padding.
        /// </summary>
        [JsonProperty]
        public Padding TextPadding { get { return textPadding; } set { textPadding = value; Invalidate(); InvalidateParent(); } }

		public override event ControlBase.GwenEventHandler<ClickedEventArgs> Clicked {
			add {
				base.Clicked += value;
				MouseInputEnabled = ClickEventAssigned;
			}
			remove {
				base.Clicked -= value;
				MouseInputEnabled = ClickEventAssigned;
			}
		}

		public override event ControlBase.GwenEventHandler<ClickedEventArgs> DoubleClicked {
			add {
				base.DoubleClicked += value;
				MouseInputEnabled = ClickEventAssigned;
			}
			remove {
				base.DoubleClicked -= value;
				MouseInputEnabled = ClickEventAssigned;
			}
		}

		public override event ControlBase.GwenEventHandler<ClickedEventArgs> RightClicked {
			add {
				base.RightClicked += value;
				MouseInputEnabled = ClickEventAssigned;
			}
			remove {
				base.RightClicked -= value;
				MouseInputEnabled = ClickEventAssigned;
			}
		}

		public override event ControlBase.GwenEventHandler<ClickedEventArgs> DoubleRightClicked {
			add {
				base.DoubleRightClicked += value;
				MouseInputEnabled = ClickEventAssigned;
			}
			remove {
				base.DoubleRightClicked -= value;
				MouseInputEnabled = ClickEventAssigned;
			}
		}

        /// <summary>
        /// Initializes a new instance of the <see cref="Label"/> class.
        /// </summary>
        /// <param name="parent">Parent control.</param>
        public Label(ControlBase parent) : base(parent)
        {
            text = new TextControl(this);
            //m_Text.Font = Skin.DefaultFont;

			MouseInputEnabled = false;
            SetSize(100, 10);
            Alignment = Pos.Left | Pos.Top;

            autoSizeToContents = true;
        }

        /// <summary>
        /// Returns index of the character closest to specified point (in canvas coordinates).
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        protected virtual Point getClosestCharacter(int x, int y)
        {
            return new Point(text.GetClosestCharacter(text.CanvasPosToLocal(new Point(x, y))), 0);
        }

        /// <summary>
        /// Sets the position of the internal text control.
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        protected void setTextPosition(int x, int y)
        {
            text.SetPosition(x, y);
        }

        /// <summary>
        /// Handler for text changed event.
        /// </summary>
        protected virtual void onTextChanged() {}

        /// <summary>
        /// Lays out the control's interior according to alignment, padding, dock etc.
        /// </summary>
        /// <param name="skin">Skin to use.</param>
        protected override void layout(Skin.SkinBase skin)
        {
            base.layout(skin);

            Pos align = this.align;

            if (autoSizeToContents)
                SizeToContents();

            int x = textPadding.Left + Padding.Left;
            int y = textPadding.Top + Padding.Top;

            if (0 != (align & Pos.Right))
                x = Width - text.Width - textPadding.Right - Padding.Right;
            if (0 != (align & Pos.CenterH))
                x = (int)((textPadding.Left + Padding.Left) + ((Width - text.Width - textPadding.Left - Padding.Left - textPadding.Right - Padding.Right) * 0.5f));

            if (0 != (align & Pos.CenterV))
                y = (int)((textPadding.Top + Padding.Top) + ((Height - text.Height) * 0.5f) - textPadding.Bottom - Padding.Bottom);
            if (0 != (align & Pos.Bottom))
                y = Height - text.Height - textPadding.Bottom - Padding.Bottom;

            text.SetPosition(x, y);
        }

        /// <summary>
        /// Sets the label text.
        /// </summary>
        /// <param name="str">Text to set.</param>
        /// <param name="doEvents">Determines whether to invoke "text changed" event.</param>
        public virtual void SetText(string str, bool doEvents = true)
        {
            if (Text == str)
                return;

            text.Text = str;
            if (autoSizeToContents)
                SizeToContents();
            Invalidate();
            InvalidateParent();

            if (doEvents)
                onTextChanged();
        }

        public virtual void SizeToContents()
        {
            text.SetPosition(textPadding.Left + Padding.Left, textPadding.Top + Padding.Top);
            text.SizeToContents();

            SetSize(text.Width + Padding.Left + Padding.Right + textPadding.Left + textPadding.Right,
                text.Height + Padding.Top + Padding.Bottom + textPadding.Top + textPadding.Bottom);
            InvalidateParent();
        }

        /// <summary>
        /// Gets the coordinates of specified character.
        /// </summary>
        /// <param name="index">Character index.</param>
        /// <returns>Character coordinates (local).</returns>
        public virtual Point GetCharacterPosition(int index)
        {
            Point p = text.GetCharacterPosition(index);
            return new Point(p.X + text.X, p.Y + text.Y);
        }

        /// <summary>
        /// Renders the control using specified skin.
        /// </summary>
        /// <param name="skin">Skin to use.</param>
        protected override void render(Skin.SkinBase skin)
        {
        }

		/// <summary>
		/// Updates control colors.
		/// </summary>
		public override void UpdateColors() {
			if (IsDisabled) {
				TextColor = Skin.Colors.Button.Disabled;
				return;
			}

			if (IsHovered && ClickEventAssigned) {
				TextColor = Skin.Colors.Button.Hover;
				return;
			}

            TextColor = Skin.Colors.Button.Normal;
		}
    }
}


text:
Scrivendo codice HTML avrai probabilmente notato che possiede una gerarchia chiara e visuale di annidamento. CSS, invece, ne è sprovvisto. Ecco un esempio tipico di stili per la navigazione di un sito:

```scss
nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  li { display: inline-block; }

  a {
    display: block;
    padding: 6px 12px;
    text-decoration: none;
  }
}
```

Noterai che i selettori `ul`, `li`, ed `a` sono annidati all'interno del selettore `nav`. Questa è un'ottima maniera di organizzare il tuo CSS e renderlo più leggibile. Quando generi il CSS otterrai un risultato come il seguente:

```css
nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

nav li {
  display: inline-block;
}

nav a {
  display: block;
  padding: 6px 12px;
  text-decoration: none;
}
```

# ESERCIZIO

Scrivi un foglio di stile che imposta lo stile `margin: 0` dell'elemento `ul`, e il colore dei link a `red` per elementi contenuti all'interno di un elemento `aside`, usando le regole annidate.


text:
package com.nagao.patchup.config;

public interface PublishConstants {

	public static final String SYSTEM_CONFIG_DIR = "conf/";

	public static final String PUBLISH_CONFIG_FILE_NAME = "publish_config.xml";

}


text:
/* eslint-disable no-underscore-dangle */

import crossroads from 'crossroads';
import { zipObject } from 'lodash';

import authRoutes from 'apps/auth/routes';
import cartRoutes from 'apps/cart/routes';
import productsRoutes from 'apps/products/routes';
import store from 'store';

import Route from './route';
import history from './history';
import { setLocation, setRoute } from './actions';

function createRoutes() {
  const routes = {
    ...authRoutes,
    ...cartRoutes,
    ...productsRoutes,
  };
  const defaultRoute = '/';

  Object.keys(routes).forEach((route) => {
    crossroads.addRoute(route);
  });

  // make sure we trigger callbacks if we route or bypass more than once
  crossroads.ignoreState = true;

  crossroads.routed.add((request, data) => {
    const page = routes[data.route._pattern];
    const params = zipObject(data.route._paramsIds, data.params);
    store.dispatch(setRoute(new Route(page, params)));
  });

  crossroads.bypassed.add(() => {
    // make sure defaultRoute actually exists!
    crossroads.parse(defaultRoute);
  });

  history.listen((location) => {
    store.dispatch(setLocation(location));
    crossroads.parse(location.pathname);
  });

  crossroads.parse(history.location.pathname);

  return routes;
}

export default createRoutes();


text:
import {
  ChangeDetectorRef,
  Component,
  Input,
} from '@angular/core';

import {UserActions} from '../../actions/user-actions/user-actions';
import {Highlightable} from '../../utils/highlightable';
import {InputOutput} from '../../utils';
import {functionName} from '../../../utils';
import {
  Path,
  PropertyMetadata,
  Metadata,
} from '../../../tree';

@Component({
  selector: 'bt-state-values',
  template: require('./state-values.html'),
  styles: [require('to-string!./state-values.css')],
})
export class StateValues extends Highlightable {
  @Input() id: string | number;
  @Input() path: Path;
  @Input() inputs: InputOutput;
  @Input() metadata: PropertyMetadata;
  @Input() value;

  private editable: boolean = false;

  constructor(
    private changeDetector: ChangeDetectorRef,
    private userActions: UserActions
  ) {
    super(changeDetector, changes => this.hasChanged(changes));
  }

  private hasChanged(changes) {
    if (changes == null || !changes.hasOwnProperty('value')) {
      return false;
    }

    const oldValue = changes.value.previousValue;
    const newValue = changes.value.currentValue;

    if (oldValue.toString() === 'CD_INIT_VALUE') {
      return false;
    }

    if (typeof oldValue === 'function' && typeof newValue === 'function') {
      return functionName(oldValue) !== functionName(newValue);
    }

    return oldValue !== newValue;
  }

  private get key(): string | number {
    return this.path[this.path.length - 1];
  }

  private onValueChanged(newValue) {
    if (newValue !== this.value) {
      this.userActions.updateProperty(this.path, newValue);
    }
  }
}


text:
from __future__ import absolute_import, unicode_literals

from case import Mock, MagicMock

from kombu.asynchronous.aws.sqs.connection import (
    AsyncSQSConnection
)
from kombu.asynchronous.aws.ext import boto3
from kombu.asynchronous.aws.sqs.message import AsyncMessage
from kombu.asynchronous.aws.sqs.queue import AsyncQueue
from kombu.utils.uuid import uuid

from t.mocks import PromiseMock

from ..case import AWSCase

class test_AsyncSQSConnection(AWSCase):

    def setup(self):
        session = boto3.session.Session(
            aws_access_key_id='AAA',
            aws_secret_access_key='AAAA',
            region_name='us-west-2',
        )
        sqs_client = session.client('sqs')
        self.x = AsyncSQSConnection(sqs_client, 'ak', 'sk', http_client=Mock())
        self.x.get_object = Mock(name='X.get_object')
        self.x.get_status = Mock(name='X.get_status')
        self.x.get_list = Mock(name='X.get_list')
        self.callback = PromiseMock(name='callback')

        sqs_client.get_queue_url = MagicMock(return_value={
            'QueueUrl': 'http://aws.com'
        })

    def test_create_queue(self):
        self.x.create_queue('foo', callback=self.callback)
        self.x.get_object.assert_called_with(
            'CreateQueue', {'QueueName': 'foo'},
            callback=self.callback,
        )

    def test_create_queue__with_visibility_timeout(self):
        self.x.create_queue(
            'foo', visibility_timeout=33, callback=self.callback,
        )
        self.x.get_object.assert_called_with(
            'CreateQueue', {
                'QueueName': 'foo',
                'DefaultVisibilityTimeout': '33'
            },
            callback=self.callback
        )

    def test_delete_queue(self):
        queue = Mock(name='queue')
        self.x.delete_queue(queue, callback=self.callback)
        self.x.get_status.assert_called_with(
            'DeleteQueue', None, queue.id, callback=self.callback,
        )

    def test_get_queue_attributes(self):
        queue = Mock(name='queue')
        self.x.get_queue_attributes(
            queue, attribute='QueueSize', callback=self.callback,
        )
        self.x.get_object.assert_called_with(
            'GetQueueAttributes', {'AttributeName': 'QueueSize'},
            queue.id, callback=self.callback,
        )

    def test_set_queue_attribute(self):
        queue = Mock(name='queue')
        self.x.set_queue_attribute(
            queue, 'Expires', '3600', callback=self.callback,
        )
        self.x.get_status.assert_called_with(
            'SetQueueAttribute', {
                'Attribute.Name': 'Expires',
                'Attribute.Value': '3600',
            },
            queue.id, callback=self.callback,
        )

    def test_receive_message(self):
        queue = Mock(name='queue')
        self.x.receive_message(queue, 4, callback=self.callback)
        self.x.get_list.assert_called_with(
            'ReceiveMessage', {'MaxNumberOfMessages': 4},
            [('Message', AsyncMessage)],
            'http://aws.com', callback=self.callback,
            parent=queue,
        )

    def test_receive_message__with_visibility_timeout(self):
        queue = Mock(name='queue')
        self.x.receive_message(queue, 4, 3666, callback=self.callback)
        self.x.get_list.assert_called_with(
            'ReceiveMessage', {
                'MaxNumberOfMessages': 4,
                'VisibilityTimeout': 3666,
            },
            [('Message', AsyncMessage)],
            'http://aws.com', callback=self.callback,
            parent=queue,
        )

    def test_receive_message__with_wait_time_seconds(self):
        queue = Mock(name='queue')
        self.x.receive_message(
            queue, 4, wait_time_seconds=303, callback=self.callback,
        )
        self.x.get_list.assert_called_with(
            'ReceiveMessage', {
                'MaxNumberOfMessages': 4,
                'WaitTimeSeconds': 303,
            },
            [('Message', AsyncMessage)],
            'http://aws.com', callback=self.callback,
            parent=queue,
        )

    def test_receive_message__with_attributes(self):
        queue = Mock(name='queue')
        self.x.receive_message(
            queue, 4, attributes=['foo', 'bar'], callback=self.callback,
        )
        self.x.get_list.assert_called_with(
            'ReceiveMessage', {
                'AttributeName.1': 'foo',
                'AttributeName.2': 'bar',
                'MaxNumberOfMessages': 4,
            },
            [('Message', AsyncMessage)],
            'http://aws.com', callback=self.callback,
            parent=queue,
        )

    def MockMessage(self, id=None, receipt_handle=None, body=None):
        m = Mock(name='message')
        m.id = id or uuid()
        m.receipt_handle = receipt_handle or uuid()
        m._body = body

        def _get_body():
            return m._body
        m.get_body.side_effect = _get_body

        def _set_body(value):
            m._body = value
        m.set_body.side_effect = _set_body

        return m

    def test_delete_message(self):
        queue = Mock(name='queue')
        message = self.MockMessage()
        self.x.delete_message(queue, message.receipt_handle,
                              callback=self.callback)
        self.x.get_status.assert_called_with(
            'DeleteMessage', {'ReceiptHandle': message.receipt_handle},
            queue, callback=self.callback,
        )

    def test_delete_message_batch(self):
        queue = Mock(name='queue')
        messages = [self.MockMessage('1', 'r1'),
                    self.MockMessage('2', 'r2')]
        self.x.delete_message_batch(queue, messages, callback=self.callback)
        self.x.get_object.assert_called_with(
            'DeleteMessageBatch', {
                'DeleteMessageBatchRequestEntry.1.Id': '1',
                'DeleteMessageBatchRequestEntry.1.ReceiptHandle': 'r1',
                'DeleteMessageBatchRequestEntry.2.Id': '2',
                'DeleteMessageBatchRequestEntry.2.ReceiptHandle': 'r2',
            },
            queue.id, verb='POST', callback=self.callback,
        )

    def test_send_message(self):
        queue = Mock(name='queue')
        self.x.send_message(queue, 'hello', callback=self.callback)
        self.x.get_object.assert_called_with(
            'SendMessage', {'MessageBody': 'hello'},
            queue.id, verb='POST', callback=self.callback,
        )

    def test_send_message__with_delay_seconds(self):
        queue = Mock(name='queue')
        self.x.send_message(
            queue, 'hello', delay_seconds='303', callback=self.callback,
        )
        self.x.get_object.assert_called_with(
            'SendMessage', {'MessageBody': 'hello', 'DelaySeconds': 303},
            queue.id, verb='POST', callback=self.callback,
        )

    def test_send_message_batch(self):
        queue = Mock(name='queue')
        messages = [self.MockMessage('1', 'r1', 'A'),
                    self.MockMessage('2', 'r2', 'B')]
        self.x.send_message_batch(
            queue, [(m.id, m.get_body(), 303) for m in messages],
            callback=self.callback
        )
        self.x.get_object.assert_called_with(
            'SendMessageBatch', {
                'SendMessageBatchRequestEntry.1.Id': '1',
                'SendMessageBatchRequestEntry.1.MessageBody': 'A',
                'SendMessageBatchRequestEntry.1.DelaySeconds': 303,
                'SendMessageBatchRequestEntry.2.Id': '2',
                'SendMessageBatchRequestEntry.2.MessageBody': 'B',
                'SendMessageBatchRequestEntry.2.DelaySeconds': 303,
            },
            queue.id, verb='POST', callback=self.callback,
        )

    def test_change_message_visibility(self):
        queue = Mock(name='queue')
        self.x.change_message_visibility(
            queue, 'rcpt', 33, callback=self.callback,
        )
        self.x.get_status.assert_called_with(
            'ChangeMessageVisibility', {
                'ReceiptHandle': 'rcpt',
                'VisibilityTimeout': 33,
            },
            queue.id, callback=self.callback,
        )

    def test_change_message_visibility_batch(self):
        queue = Mock(name='queue')
        messages = [
            (self.MockMessage('1', 'r1'), 303),
            (self.MockMessage('2', 'r2'), 909),
        ]
        self.x.change_message_visibility_batch(
            queue, messages, callback=self.callback,
        )

        def preamble(n):
            return '.'.join(['ChangeMessageVisibilityBatchRequestEntry', n])

        self.x.get_object.assert_called_with(
            'ChangeMessageVisibilityBatch', {
                preamble('1.Id'): '1',
                preamble('1.ReceiptHandle'): 'r1',
                preamble('1.VisibilityTimeout'): 303,
                preamble('2.Id'): '2',
                preamble('2.ReceiptHandle'): 'r2',
                preamble('2.VisibilityTimeout'): 909,
            },
            queue.id, verb='POST', callback=self.callback,
        )

    def test_get_all_queues(self):
        self.x.get_all_queues(callback=self.callback)
        self.x.get_list.assert_called_with(
            'ListQueues', {}, [('QueueUrl', AsyncQueue)],
            callback=self.callback,
        )

    def test_get_all_queues__with_prefix(self):
        self.x.get_all_queues(prefix='kombu.', callback=self.callback)
        self.x.get_list.assert_called_with(
            'ListQueues', {'QueueNamePrefix': 'kombu.'},
            [('QueueUrl', AsyncQueue)],
            callback=self.callback,
        )

    def MockQueue(self, url):
        q = Mock(name='Queue')
        q.url = url
        return q

    def test_get_queue(self):
        self.x.get_queue('foo', callback=self.callback)
        self.x.get_list.assert_called()
        on_ready = self.x.get_list.call_args[1]['callback']
        queues = [
            self.MockQueue('/queues/bar'),
            self.MockQueue('/queues/baz'),
            self.MockQueue('/queues/foo'),
        ]
        on_ready(queues)
        self.callback.assert_called_with(queues[-1])

        self.x.get_list.assert_called_with(
            'ListQueues', {'QueueNamePrefix': 'foo'},
            [('QueueUrl', AsyncQueue)],
            callback=on_ready,
        )

    def test_get_dead_letter_source_queues(self):
        queue = Mock(name='queue')
        self.x.get_dead_letter_source_queues(queue, callback=self.callback)
        self.x.get_list.assert_called_with(
            'ListDeadLetterSourceQueues', {'QueueUrl': queue.url},
            [('QueueUrl', AsyncQueue)], callback=self.callback,
        )

    def test_add_permission(self):
        queue = Mock(name='queue')
        self.x.add_permission(
            queue, 'label', 'accid', 'action', callback=self.callback,
        )
        self.x.get_status.assert_called_with(
            'AddPermission', {
                'Label': 'label',
                'AWSAccountId': 'accid',
                'ActionName': 'action',
            },
            queue.id, callback=self.callback,
        )

    def test_remove_permission(self):
        queue = Mock(name='queue')
        self.x.remove_permission(queue, 'label', callback=self.callback)
        self.x.get_status.assert_called_with(
            'RemovePermission', {'Label': 'label'}, queue.id,
            callback=self.callback,
        )


text:
@interface CommentCell : BigPhotoCell

@end


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for C:\projects\OpenTribes\Core/vendor/doctrine/dbal/lib/Doctrine/DBAL/Configuration.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

C:\projects\OpenTribes\Core /

vendor /

doctrine /

dbal /

lib /

Doctrine /

DBAL /

Configuration.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

0.00%

0 / 1

16.67%

1 / 6

      CRAP

15.38%

2 / 13

      Configuration

0.00%

0 / 1

16.67%

1 / 6

      58.07

15.38%

2 / 13

       setSQLLogger(SQLLogger $logger = null)

0.00%

0 / 1

      2

0.00%

0 / 2

       getSQLLogger()

100.00%

1 / 1

      2

100.00%

2 / 2

       getResultCacheImpl()

0.00%

0 / 1

      6

0.00%

0 / 2

       setResultCacheImpl(Cache $cacheImpl)

0.00%

0 / 1

      2

0.00%

0 / 2

       setFilterSchemaAssetsExpression($filterExpression)

0.00%

0 / 1

      2

0.00%

0 / 2

       getFilterSchemaAssetsExpression()

0.00%

0 / 1

      6

0.00%

0 / 3

1
	<?php

2

19

20
	namespace Doctrine\DBAL;

21

22
	use Doctrine\DBAL\Logging\SQLLogger;

23
	use Doctrine\Common\Cache\Cache;

24

25
	/**

26
	 * Configuration container for the Doctrine DBAL.

27
	 *

28
	 * @since    2.0

29
	 * @author   Guilherme Blanco <guilhermeblanco@hotmail.com>

30
	 * @author   Jonathan Wage <jonwage@gmail.com>

31
	 * @author   Roman Borschel <roman@code-factory.org>

32
	 * @internal When adding a new configuration option just write a getter/setter

33
	 *           pair and add the option to the _attributes array with a proper default value.

34
	 */

35
	class Configuration

36
	{

37
	    /**

38
	     * The attributes that are contained in the configuration.

39
	     * Values are default values.

40
	     *

41
	     * @var array

42
	     */

43
	    protected $_attributes = array();

44

45
	    /**

46
	     * Sets the SQL logger to use. Defaults to NULL which means SQL logging is disabled.

47
	     *

48
	     * @param \Doctrine\DBAL\Logging\SQLLogger|null $logger

49
	     *

50
	     * @return void

51
	     */

52
	    public function setSQLLogger(SQLLogger $logger = null)

53
	    {

54
	        $this->_attributes['sqlLogger'] = $logger;

55
	    }

56

57
	    /**

58
	     * Gets the SQL logger that is used.

59
	     *

60
	     * @return \Doctrine\DBAL\Logging\SQLLogger

61
	     */

62
	    public function getSQLLogger()

63
	    {

64
	        return isset($this->_attributes['sqlLogger']) ?

65
	                $this->_attributes['sqlLogger'] : null;

66
	    }

67

68
	    /**

69
	     * Gets the cache driver implementation that is used for query result caching.

70
	     *

71
	     * @return \Doctrine\Common\Cache\Cache|null

72
	     */

73
	    public function getResultCacheImpl()

74
	    {

75
	        return isset($this->_attributes['resultCacheImpl']) ?

76
	                $this->_attributes['resultCacheImpl'] : null;

77
	    }

78

79
	    /**

80
	     * Sets the cache driver implementation that is used for query result caching.

81
	     *

82
	     * @param \Doctrine\Common\Cache\Cache $cacheImpl

83
	     *

84
	     * @return void

85
	     */

86
	    public function setResultCacheImpl(Cache $cacheImpl)

87
	    {

88
	        $this->_attributes['resultCacheImpl'] = $cacheImpl;

89
	    }

90

91
	    /**

92
	     * Sets the filter schema assets expression.

93
	     *

94
	     * Only include tables/sequences matching the filter expression regexp in

95
	     * schema instances generated for the active connection when calling

96
	     * {AbstractSchemaManager#createSchema()}.

97
	     *

98
	     * @param string $filterExpression

99
	     *

100
	     * @return void

101
	     */

102
	    public function setFilterSchemaAssetsExpression($filterExpression)

103
	    {

104
	        $this->_attributes['filterSchemaAssetsExpression'] = $filterExpression;

105
	    }

106

107
	    /**

108
	     * Returns filter schema assets expression.

109
	     *

110
	     * @return string|null

111
	     */

112
	    public function getFilterSchemaAssetsExpression()

113
	    {

114
	        if (isset($this->_attributes['filterSchemaAssetsExpression'])) {

115
	            return $this->_attributes['filterSchemaAssetsExpression'];

116
	        }

117

118
	        return null;

119
	    }

120
	}

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 1.2.17 using PHP 5.5.6 and PHPUnit 3.7.34 at Sat Apr 5 13:10:46 CEST 2014.


text:
module Azure::Compute::Mgmt::V2017_12_01
  module Models
    #
    # The instance view of a virtual machine boot diagnostics.
    #
    class BootDiagnosticsInstanceView

      include MsRestAzure

      # @return [String] The console screenshot blob URI.
      attr_accessor :console_screenshot_blob_uri

      # @return [String] The Linux serial console log blob Uri.
      attr_accessor :serial_console_log_blob_uri

      #
      # Mapper for BootDiagnosticsInstanceView class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'BootDiagnosticsInstanceView',
          type: {
            name: 'Composite',
            class_name: 'BootDiagnosticsInstanceView',
            model_properties: {
              console_screenshot_blob_uri: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'consoleScreenshotBlobUri',
                type: {
                  name: 'String'
                }
              },
              serial_console_log_blob_uri: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'serialConsoleLogBlobUri',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
using System;
namespace EdgeNote.UI.Network
{
    public enum ENResponseStatus
    {
        None,
        Completed,
        Error,
        TimedOut,
        Aborted
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__src_wchar_t_alloca_cpy_81_bad.cpp
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__src.label.xml
Template File: sources-sink-81_bad.tmpl.cpp
*/
/*
 * @description
 * CWE: 121 Stack Based Buffer Overflow
 * BadSource:  Initialize data as a large string
 * GoodSource: Initialize data as a small string
 * Sinks: cpy
 *    BadSink : Copy data to string using wcscpy
 * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
 *
 * */
#ifndef OMITBAD

#include "std_testcase.h"
#include "CWE121_Stack_Based_Buffer_Overflow__src_wchar_t_alloca_cpy_81.h"

namespace CWE121_Stack_Based_Buffer_Overflow__src_wchar_t_alloca_cpy_81
{

void CWE121_Stack_Based_Buffer_Overflow__src_wchar_t_alloca_cpy_81_bad::action(wchar_t * data) const
{
    {
        wchar_t dest[50] = L"";
        /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
        wcscpy(dest, data);
        printWLine(data);
    }
}

}
#endif /* OMITBAD */


text:
#ifndef MODEL_H
#define MODEL_H

#include <vector>
#include <eigen3/Eigen/Dense>

using namespace Eigen;
using namespace std;

typedef int DState;         // defining discrete state
typedef VectorXd CState;    // defining continuous state
typedef int DObs;           // defining discrete observation
typedef VectorXd CObs;      // defining continuous observation
typedef int DControl;       // defining discrete control

class Model
{
public:
    Model(int numCStateVar, int numDState, int numCObsVar, int numDObs, int numDControls,
         double discount):
            numCStateVar(numCStateVar), numDState(numDState),numCObsVar(numCObsVar),
            numDObs(numDObs), numDControls(numDControls), discount(discount)
            {}

    /*  return Tx(xx|qq, x) */
    virtual double getCStateTransProb(const CState &x_next, const DState &q_next,
                                                            const CState &x_k) const = 0 ;

    /*  return Tq(qq|q,sigma)   */
    virtual double getDStateTransProb(const DState &q_next, const DState &q_k,
                                                            const DControl &simga_k) const = 0;

    /*  return Omega(zq|q)  */
    virtual double getDiscreteObsProb(const DObs &zq_k, const DState &q_k) const = 0 ;

    /*  return R(q,x,sigma) */
    virtual double getReward(const DState &q, const CState &x, const DControl &sigma) const = 0;

    /*  sample (qq,xx,zq) from Tq(qq|q,sigma), Tx(xx|qq, x) and Omega(zq|q)*/
    virtual double sample(const DState &q_k, const CState &x_k, const DControl &sigma_k,
                          DState &q_next, CState &x_next, DObs &obs_out) const = 0;

    virtual CState getNextCStateNoNoise(const DState &q_next, const CState &x_k) const = 0;

    virtual MatrixXd get1stDerivative(const DState &q, const CState &x) const = 0;

    virtual VectorXd getReward1stDeri(const DState &q, const CState &x,
                                                       const DControl &sigma) const = 0;

    virtual MatrixXd getReward2ndDeri(const DState &q, const CState &x,
                                                       const DControl &sigma) const = 0;

    virtual vector<MatrixXd> getCovariance() const = 0; //covariance[q][coeff];

    virtual MatrixXd getCovMatrix(const DState &q) const = 0;

	virtual bool satisfyConstraints(const DState &q, const CState &x) const = 0;

    /*  return The number of continuous state variables */
    inline int getNumCStateVar() const { return numCStateVar; }

    /*  return The number of discrete state */
    inline int getNumDState() const { return numDState; }

    /*  return The number of continuous observation variables   */
    inline int getNumCObsVar() const { return numCObsVar; }

    /*  return the number of dicrete observation    */
    inline int getNumDObs() const { return numDObs; }

    /*  return Discount value for the problem   */
    inline double getDiscount() const { return discount; }

    /*  return Number of discrete controls  */
    inline int getNumDControls() const { return numDControls; }

    virtual ~Model() {}

private:
    int numCStateVar;   // number of continuous state variables
    int numDState;      // number of discrete states
    int numCObsVar;     // number of continuous observation variables
    int numDObs;        // number of discrete observations
    int numDControls;   // number of discrete controls

protected:
    double discount;    // discount factor
};

#endif //MODEL_H


text:
class HelloWorld
  def self.hello
    "Hello, World!"
  end
end


text:
require 'postcode_anywhere/client'
require 'postcode_anywhere/bank_account_validation/interactive'

module PostcodeAnywhere
  module BankAccountValidation
    class Client < ::PostcodeAnywhere::Client
      include PostcodeAnywhere::BankAccountValidation::Interactive
      def initialize(options = {})
        super(options)
      end
    end
  end
end