text:
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

// default print style
_p.def_print_style_body = "html, body, div, span, td, p { \
		font-family: inherit; \
		font-size: inherit; \
	}\
	.page-settings {\
		font-family: Helvetica, 'Open Sans', sans-serif;\
		font-size: 9pt;\
	}\
	pre { margin:0; padding:0;}";

_p.def_print_style_other = "\n.simpletable, .noborder { \
		border-collapse: collapse;\
		margin-bottom: 10px;\
	}\
	.simpletable td {\
		border: 1pt solid #777;\
		vertical-align: top;\
		padding: 4px;\
	}\
	.noborder td {\
		vertical-align: top;\
	}";

_p.go = function(html) {
	var w = _p.preview(html);
	w.print();
	w.close();
}

_p.preview = function(html) {
	var w = window.open();
	if(!w) {
		msgprint(__("Please enable pop-ups"));
		return;
	}
	w.document.write(html);
	w.document.close();
	return w
}

_f.get_value = function(dt, dn, fn) {
	if(locals[dt] && locals[dt][dn])
		return locals[dt][dn][fn];
}

// _p can be referenced as this inside $.extend
$.extend(_p, {
	show_dialog: function() {
		if(!_p.dialog) {
			_p.make_dialog();
		}
		_p.dialog.show();
	},

	make_dialog: function() {
		// Prepare Dialog Box Layout
		var dialog = new frappe.ui.Dialog({
			title: "Print Formats",
			fields: [
				{fieldtype:"Select", label:"Print Format", fieldname:"print_format", reqd:1},
				{fieldtype:"Check", label:"No Letter Head", fieldname:"no_letterhead"},
				{fieldtype:"HTML", options: '
\
					<button class="btn btn-primary btn-print">Print</button>\
					<button class="btn btn-default btn-preview">Preview</button>\

'},
			]
		});

		dialog.$wrapper.find(".btn-print").click(function() {
			var args = dialog.get_values();
			_p.build(
				args.print_format, // fmtname
				_p.go, // onload
				args.no_letterhead // no_letterhead
			);
		});

		dialog.$wrapper.find(".btn-preview").click(function() {
			var args = dialog.get_values();
			_p.build(
				args.print_format, // fmtname
				_p.preview, // onload
				args.no_letterhead // no_letterhead
			);
		});

		dialog.on_page_show = function() {
			var $print = dialog.fields_dict.print_format.$input;
			$print.empty().add_options(cur_frm.print_preview.print_formats);

			if(cur_frm.$print_view_select && cur_frm.$print_view_select.val())
				$print.val(cur_frm.$print_view_select.val());
		}

		_p.dialog = dialog;
	},

	// Define formats dict
	formats: {},

	/* args dict can contain:
			+ fmtname --> print format name
			+ onload
			+ no_letterhead
			+ only_body
	*/
	build: function(fmtname, onload, no_letterhead, only_body, no_heading) {
		if(!fmtname) {
			fmtname= "Standard";
		}

		args = {
			fmtname: fmtname,
			onload: onload,
			no_letterhead: no_letterhead,
			only_body: only_body
		};

		if(!cur_frm) {
			msgprint(__("No document selected"));
			return;
		}

		if(!frappe.model.can_print(cur_frm.doctype, cur_frm)) {
			msgprint(__("You are not allowed to print this document"));
			return;
		}

		// Get current doc (record)
		var doc = locals[cur_frm.doctype][cur_frm.docname];
		if(args.fmtname == 'Standard') {
			args.onload(_p.render({
				body: _p.print_std(args.no_letterhead, no_heading),
				style: _p.print_style,
				doc: doc,
				title: doc.name,
				no_letterhead: args.no_letterhead,
				no_heading: no_heading,
				only_body: args.only_body
			}));
		} else {
			var print_format_doc = locals["Print Format"][args.fmtname];
			if(!print_format_doc) {
				msgprint(__("Unknown Print Format: {0}", [args.fmtname]));
				return;
			}
			args.onload(_p.render({
				body: print_format_doc.html,
				style: '',
				doc: doc,
				title: doc.name,
				no_letterhead: args.no_letterhead,
				no_heading: no_heading,
				only_body: args.only_body
			}));
		}
	},

	render: function(args) {
		var container = document.createElement('div');
		var stat = '';

		if(!args.no_heading) {
			// if draft/archived, show draft/archived banner
			stat += _p.show_draft(args);
			stat += _p.show_archived(args);
			stat += _p.show_cancelled(args);
		}

		// Append args.body's content as a child of container
		container.innerHTML = args.body;

		// Show letterhead?
		_p.show_letterhead(container, args);

		_p.run_embedded_js(container, args.doc);

		var style = _p.consolidate_css(container, args);

		_p.render_header_on_break(container, args);

		return _p.render_final(style, stat, container, args);
	},

	head_banner_format: function() {
		return "\

 \

\
					{{HEAD}}\

\
				{{DESCRIPTION}}\

"
	},

	/*
		Check if doc's status is not submitted (docstatus == 0)
		and submission is pending

		Display draft in header if true
	*/
	show_draft: function(args) {
		var is_doctype_submittable = 0;
		var plist = locals['DocPerm'];
		for(var perm in plist) {
			var p = plist[perm];
			if((p.parent==args.doc.doctype) && (p.submit==1)){
				is_doctype_submittable = 1;
				break;
			}
		}

		if(args.doc && cint(args.doc.docstatus)==0 && is_doctype_submittable) {
			draft = _p.head_banner_format();
			draft = draft.replace("{{HEAD}}", "DRAFT");
			draft = draft.replace("{{DESCRIPTION}}", "This box will go away after the document is submitted.");
			return draft;
		} else {
			return "";
		}
	},

	/*
		Check if doc is archived
		Display archived in header if true
	*/
	show_archived: function(args) {
		if(args.doc && args.doc.__archived) {
			archived = _p.head_banner_format();
			archived = archived.replace("{{HEAD}}", "ARCHIVED");
			archived = archived.replace("{{DESCRIPTION}}", "You must restore this document to make it editable.");
			return archived;
		} else {
			return "";
		}
	},

	/*
		Check if doc is cancelled
		Display cancelled in header if true
	*/
	show_cancelled: function(args) {
		if(args.doc && args.doc.docstatus==2) {
			cancelled = _p.head_banner_format();
			cancelled = cancelled.replace("{{HEAD}}", "CANCELLED");
			cancelled = cancelled.replace("{{DESCRIPTION}}", "You must amend this document to make it editable.");
			return cancelled;
		} else {
			return "";
		}
	},

	consolidate_css: function(container, args) {
		// Extract \
	\
	';
			var footer = '\
	\
';
		} else {
			var header = '';
			var footer = '';
		}
		var finished =  header
			+ '
'
			+ stat
			+ container.innerHTML
			+ '
'
			+ footer;

		// replace relative links by absolute links
		var prefix = window.location.href.split("desk")[0]
		// find unique matches
		var matches = $.unique(finished.match(/src=['"]([^'"]*)['"]/g) || []);

		$.each(matches, function(i, v) {
			if(v.substr(0,4)=="src=") {
				var v = v.substr(5, v.length-6);
				if(v.substr(0,4)!="http") {
					finished = finished.split(v).join(prefix + lstrip(v, "/"));
				}

			}
		});

		return finished;
	},

	// fetches letter head from current doc or control panel
	get_letter_head: function() {
		var lh = '';
		if(cur_frm.doc.letter_head) {
			lh = cstr(frappe.boot.letter_heads[cur_frm.doc.letter_head].header);
		} else if (frappe.boot.sysdefaults.default_letter_head_content) {
			lh = frappe.boot.sysdefaults.default_letter_head_content;
		}
		return lh;
	},

	// common print style setting
	print_style: "\
		.datalabelcell { \
			padding: 2px 0px; \
			width: 38%; \
			vertical-align: top; \
			} \
		.datainputcell { \
			padding: 2px 0px; \
			width: 62%; \
			text-align: left; \
			}\
		.sectionHeading { \
			font-size: 16px; \
			font-weight: bold; \
			margin: 8px 0px; \
			} \
		.columnHeading { \
			font-size: 14px; \
			font-weight: bold; \
			margin: 8px 0px; \
			}",

	print_std: function(no_letterhead, no_heading) {
		// Get doctype, docname, layout for a doctype
		var docname = cur_frm.docname;
		var doctype = cur_frm.doctype;
		var data = frappe.get_children("DocType", doctype, "fields");
		var layout = _p.add_layout(doctype);
		this.pf_list = [layout];
		var me = this;
		me.layout = layout;

		$.extend(this, {
			build_head: function(data, doctype, docname) {
				// Heading
				var h1_style = {
					fontSize: '22px',
					marginBottom: '8px'
				}
				var h1 = $a(me.layout.cur_row.header, 'h1', '', h1_style);

				// Get print heading
				if (cur_frm.pformat[docname]) {
					// first check in cur_frm.pformat
					h1.innerHTML = cur_frm.pformat[docname];
				} else {
					// then check if select print heading exists and has a value
					var val = null;
					for (var i = 0; i < data.length; i++) {
						if (data[i].fieldname === 'select_print_heading') {
							val = _f.get_value(doctype, docname, data[i].fieldname);
							break;
						}
					}
					// if not, just have doctype has heading
					h1.innerHTML = val ? val : __(doctype);
				}

				var h2_style = {
					fontSize: '16px',
					color: '#888',
					marginBottom: '8px',
					paddingBottom: '8px',
					borderBottom: (me.layout.with_border ? '0px' :
						'1px solid #000')
				}
				var h2 = $a(me.layout.cur_row.header, 'div', '', h2_style);
				h2.innerHTML = docname;

				if(cur_frm.state_fieldname && !cur_frm.fields_dict[cur_frm.state_fieldname].df.print_hide) {
					$a(h2, 'br');
					var span = $a(h2, 'span', '',
						{padding: "3px", color: "#fff", backgroundColor: "#777",
							display:"inline-block"});
					span.innerHTML = cur_frm.doc[cur_frm.state_fieldname];
				}
			},

			build_data: function(data, doctype, docname) {
				// Start with a row and a cell in that row
				if(data[0] && data[0].fieldtype != "Section Break") {
					me.layout.addrow();
					if(data[0].fieldtype != "Column Break") {
						me.layout.addcell();
					}
				}

				$.extend(this, {
					generate_custom_html: function(field, doctype, docname) {
						var container = $a(me.layout.cur_cell, 'div');
						container.innerHTML = cur_frm.pformat[field.fieldname](locals[doctype][docname]);
					},

					render_normal: function(field, data, i) {
						switch(field.fieldtype) {
							case 'Fold': break;
							case 'Section Break':
								me.layout.addrow();

								// Add column if no column break after this field
								if(data[i+1] && data[i+1].fieldtype !=
										'Column Break') {
									me.layout.addcell();
								}
								break;

							case 'Column Break':
								me.layout.addcell(field.width, field.label);
								break;

							case 'Table':
								var table = print_table(
										doctype, // dt
										docname, // dn
										field.fieldname,
										field.options, // tabletype
										null, // cols
										null, // head_labels
										null, // widths
										null); // condition
								me.layout = _p.print_std_add_table(table, me.layout, me.pf_list, doctype, no_letterhead);
								break;

							case 'HTML':
								var div = $a(me.layout.cur_cell, 'div');
								div.innerHTML = cstr(field.options);
								break;

							case 'Code':
								var div = $a(me.layout.cur_cell, 'div');
								var val = _f.get_value(doctype, docname,
									field.fieldname);
								div.innerHTML = '
' + __(field.label) +
									':

' + (val ? val : '') +
									'
';
								break;

							case 'Text Editor':
								var div = $a(me.layout.cur_cell, 'div');
								var val = _f.get_value(doctype, docname,
									field.fieldname);
								div.innerHTML = val ? val : '';
								break;

							default:
								// Add Cell Data
								_p.print_std_add_field(doctype, docname, field, me.layout);
								break;
						}
					}
				});

				// Then build each field
				for(var i = 0; i < data.length; i++) {
					var fieldname = data[i].fieldname ? data[i].fieldname :
						data[i].label;
					var field = fieldname ?
						frappe.meta.get_docfield(doctype, fieldname, docname) : data[i];
					if(!field.print_hide) {
						if(cur_frm.pformat[field.fieldname]) {
							// If there is a custom method to generate the HTML, then use it
							this.generate_custom_html(field, doctype, docname);
						} else {
							// Do the normal rendering
							this.render_normal(field, data, i);
						}
					}
				}
				me.layout.close_borders();
			},

			build_html: function() {
				var html = '';
				for(var i = 0; i < me.pf_list.length; i++) {
					if(me.pf_list[i].wrapper) {
						html += me.pf_list[i].wrapper.innerHTML;
					} else if(me.pf_list[i].innerHTML) {
						html += me.pf_list[i].innerHTML;
					} else {
						html += me.pf_list[i];
					}
				}
				this.pf_list = [];
				return html;
			}
		});

		if(!no_heading) {
			this.build_head(data, doctype, docname);
		}

		this.build_data(data, doctype, docname);

		var html = this.build_html();
		return html;
	},

	add_layout: function(doctype) {
		var layout = new Layout();
		layout.addrow();

		if(locals['DocType'][doctype].print_outline == 'Yes') {
			layout.with_border = 1
		}

		return layout;
	},

	print_std_add_table: function(t, layout, pf_list, dt, no_letterhead) {
		if(t.appendChild) {
			// If only one table is passed
			layout.cur_cell.appendChild(t);
		} else {
			page_break = '\n\

';

			// If a list of tables is passed
			for(var i = 0; i < t.length-1; i++) {
				// add to current page
				layout.cur_cell.appendChild(t[i]);
				layout.close_borders();

				pf_list.push(page_break);

				// Create new page
				layout = _p.add_layout(dt, no_letterhead);
				pf_list.push(layout);

				layout.addrow();
				layout.addcell();

				var div = $a(layout.cur_cell, 'div');
				div.innerHTML = 'Continued from previous page...';
				div.style.padding = '4px';
			}

			// Append last table
			layout.cur_cell.appendChild(t[t.length-1]);
		}
		return layout;
	},

	print_std_add_field: function(dt, dn, f, layout) {
		var val = _f.get_value(dt, dn, f.fieldname);
		if(f.fieldtype!='Button') {
			if(val || in_list(['Float', 'Int', 'Currency'], f.fieldtype)) {
				// If value or a numeric type then proceed

				// Add field table
				row = _p.field_tab(layout.cur_cell);

				// Add label
				row.cells[0].innerHTML = __(f.label ? f.label : f.fieldname);
				row.cells[1].innerHTML = frappe.format(val, f, {for_print: true});

				// left align currency in normal display
				if(f.fieldtype == 'Currency') {
					$y(row.cells[1], { textAlign: 'left' });
				}

			}
		}
	},

	field_tab: function(layout_cell) {
		var tab = $a(layout_cell, 'table', '', {width:'100%'});
		var row = tab.insertRow(0);
		_p.row = row; // Don't know this line's purpose
		row.insertCell(0);
		row.insertCell(1);
		row.cells[0].className = 'datalabelcell';
		row.cells[0].style.width = "38%";
		row.cells[1].className = 'datainputcell';
		return row;
	}
});


text:
namespace mesos {
namespace internal {
namespace slave {
namespace docker {

// Forward Declarations.
class Puller;
class StoreProcess;

// Store fetches the Docker images and stores them on disk.
class Store : public slave::Store
{
public:
  static Try<process::Owned<slave::Store>> create(
      const Flags& flags,
      SecretResolver* secretResolver = nullptr);

  // This allows the puller to be mocked for testing.
  static Try<process::Owned<slave::Store>> create(
      const Flags& flags,
      const process::Owned<Puller>& puller);

  virtual ~Store();

  virtual process::Future<Nothing> recover();

  virtual process::Future<ImageInfo> get(
      const mesos::Image& image,
      const std::string& backend);

  virtual process::Future<Nothing> prune(
      const std::vector<mesos::Image>& excludeImages,
      const hashset<std::string>& activeLayerPaths);

private:
  explicit Store(process::Owned<StoreProcess> process);

  Store& operator=(const Store&) = delete; // Not assignable.
  Store(const Store&) = delete; // Not copyable.

  process::Owned<StoreProcess> process;
};

} // namespace docker {
} // namespace slave {
} // namespace internal {
} // namespace mesos {

#endif // __PROVISIONER_DOCKER_STORE_HPP__

redpajama_set_name: RedPajamaGithub


text:
var React = require('react');
var Backbone = require('backbone');
var _ = require('underscore');
var ReactBackbone = require('react-backbone');

// MODEL
var MyModel = Backbone.Model.extend({
  // add a dumb validation method which ensures first/last name length are > 5
  validate: function(attributes) {
    var errors = [];
    if (attributes.hasOwnProperty('firstName')) {
      if (!attributes.firstName || attributes.firstName.length < 5) {
        errors.push({firstName: 'The first name must be > 5 characters'});
      }
    }
    if (attributes.hasOwnProperty('lastName')) {
      if (!attributes.lastName || attributes.lastName.length < 5) {
        errors.push({lastName: 'The last name must be > 5 characters'});
      }
    }
    return errors.length && errors;
  }
});

// COMPONENTS

// create a reusable components which represent a label with an input field
var TextField = ReactBackbone.input.Text;
var InputWithLabel = React.createClass({
  getInitialState: function() {
    return { id: _.uniqueId('form') };
  },

  render: function() {
    return

      {this.props.label}

        <TextField id={this.state.id} type="text" ref="input" model={this.props.model} name={this.props.name} bind={true}/>

;
  },

  // allow the value of the input component to be retrieved
  getValue: function() {
    return this.refs.input.getValue();
  }
});

// and here is the overall form component
var TestComponent = React.createClass({
  mixins: ['modelPopulate'],

  getInitialState: function() {
    // make sure this.state is not null
    return {};
  },

  // listen for the invalid event so we can message when the data is bad
  componentDidMount: function() {
    this.props.model.on('invalid', this.onInvalid);
  },
  componentWillUnmount: function() {
    this.props.model.off('invalid', this.onInvalid);
  },

  render: function() {
    var error = this.state.error;

    // if we've got an error, show it
    var errorComponent = error && (

        Error: {error}

    );

    // return the form and input contents
    return <form onSubmit={this.onSubmit}>
      {errorComponent}
      <InputWithLabel ref="firstName" name="firstName" label="First Name" model={this.props.model}/>
      <InputWithLabel ref="lastName" name="lastName" label="Last Name" model={this.props.model}/>
      <button type="submit">Click me</button>
    </form>;
  },

  onSubmit: function(ev) {
    ev.preventDefault();
    if (model.isValid()) {
      this.setState({error: undefined});
      alert('model validated');
    }
  },

  onInvalid: function(model, errors) {
    // for simplicity, we'll just show the first error
    var errorStr = [];
    _.each(errors, function(error) {
      _.each(error, function(message) {
        errorStr.push(message);
      });
    });
    this.setState({error: errorStr.join(', ')});
  }
});

// INITIAL RENDER
var model = new MyModel({
  firstName: 'John',
  lastName: 'Doe'
});
React.render(<TestComponent model={model}/>, document.body);


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:background="@drawable/grey_rounded_border">

    <ImageView
        android:id="@+id/borrowed_instrument_list_item_thumbnail_iv"
        android:layout_width="100sp"
        android:layout_height="100sp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:src="@android:drawable/ic_menu_camera"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:orientation="vertical">

    <TextView
        android:id="@+id/borrowed_instrument_list_item_name_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:textColor="@color/black"
        android:layout_marginTop="2dp"
        android:layout_marginBottom="2dp"/>

    <TextView
        android:id="@+id/borrowed_instrument_list_item_owner_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:textColor="@color/black"
        android:layout_marginTop="2dp"
        android:layout_marginBottom="2dp"/>

        <TextView
            android:id="@+id/borrowed_instrument_list_item_rate_tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="24sp"
            android:textColor="@color/black"
            android:layout_marginTop="2dp"
            android:layout_marginBottom="2dp"/>

        <TextView
            android:id="@+id/borrowed_instrument_list_item_description_tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="16sp"
            android:textColor="@color/black"
            android:layout_marginTop="2dp"
            android:layout_marginBottom="2dp"/>

        </LinearLayout>

</LinearLayout>


text:
import chainerx

import pytest

def _assert_arrays_equal(array1, array2):
    if array1 is None:
        assert array1 == array2
    else:
        assert array1.dtype == array2.dtype
        assert array1.shape == array2.shape
        assert array1._debug_flat_data == array2._debug_flat_data

def _check_backward(fprop, xs, expected_gxs, gys=None, backprop_id=None):
    # Checks for test validity.
    assert callable(fprop)
    assert isinstance(xs, tuple)
    assert isinstance(expected_gxs, tuple)
    assert len(xs) == len(expected_gxs)
    assert all([isinstance(a, chainerx.ndarray) for a in xs])
    assert all([isinstance(a, chainerx.ndarray) or a is None
                for a in expected_gxs])

    # Forward.
    ys = fprop(*xs)

    # Set output gradients.
    if gys is not None:
        assert len(gys) == len(ys)
        for y, gy in zip(ys, gys):
            assert not y.is_grad_required()
            y.set_grad(gy, backprop_id)

    # Backward.
    chainerx.backward(ys, backprop_id)

    # Check gradients of input arrays.
    for x, expected_gx in zip(xs, expected_gxs):
        if expected_gx is None:
            with pytest.raises(chainerx.ChainerxError):
                x.get_grad(backprop_id)
        else:
            gx = x.get_grad(backprop_id)
            _assert_arrays_equal(gx, expected_gx)

    # Check gradients of output arrays.
    if gys is None:
        gys = (None,) * len(xs)
    for y, gy in zip(ys, gys):
        if gy is None:
            assert not y.is_grad_required(backprop_id)
            with pytest.raises(chainerx.ChainerxError):
                y.get_grad(backprop_id)
        else:
            assert y.is_grad_required(backprop_id)
            _assert_arrays_equal(gy, y.get_grad(backprop_id))

def _check_grad(
        fprop, xs, expected_gxs, gys=None, backprop_id=None, xs_indices=None,
        ys_indices=None):
    # Checks for test validity.
    assert callable(fprop)
    assert isinstance(xs, tuple)
    assert isinstance(expected_gxs, tuple)
    assert all([isinstance(a, chainerx.ndarray) for a in xs])
    assert all([isinstance(a, chainerx.ndarray) or a is None
                for a in expected_gxs])

    # Forward.
    ys = fprop(*xs)

    # Set output gradients.
    if gys is not None:
        assert len(gys) == len(ys)
        for y, gy in zip(ys, gys):
            assert not y.is_grad_required()
            y.set_grad(gy, backprop_id)

    # Backward using grad.
    initial_gxs = [
        x.get_grad(backprop_id) if x.is_grad_required(backprop_id)
        else chainerx.ChainerxError for x in xs]

    if xs_indices is not None:
        actual_xs = tuple([xs[i] for i in xs_indices])
        assert len(actual_xs) == len(expected_gxs)
    else:
        actual_xs = xs
    if ys_indices is not None:
        actual_ys = tuple([ys[i] for i in ys_indices])
    else:
        actual_ys = ys
    gxs = chainerx.grad(actual_ys, actual_xs, backprop_id)

    # Check gradients.
    for gx, expected_gx in zip(gxs, expected_gxs):
        _assert_arrays_equal(gx, expected_gx)

    # Check gradients of output arrays.
    if gys is None:
        gys = (None,) * len(xs)
    for y, gy in zip(ys, gys):
        if gy is None:
            assert not y.is_grad_required(backprop_id)
            with pytest.raises(chainerx.ChainerxError):
                y.get_grad(backprop_id)
        else:
            assert y.is_grad_required(backprop_id)
            _assert_arrays_equal(gy, y.get_grad(backprop_id))

    # Check initial gradients of inputs and that they are not modified.
    for x, initial_gx in zip(xs, initial_gxs):
        if initial_gx is chainerx.ChainerxError:
            assert not x.is_grad_required(backprop_id)
            with pytest.raises(chainerx.ChainerxError):
                x.get_grad(backprop_id)
        else:
            assert x.is_grad_required(backprop_id)
            _assert_arrays_equal(initial_gx, x.get_grad(backprop_id))

# Delegates work to either _check_backward or _check_grad.
def _check_backprop(
        method, fprop, xs, expected_gxs, gys=None, backprop_id=None):
    if method == 'backward':
        check_func = _check_backward
    elif method == 'grad':
        check_func = _check_grad
    else:
        assert False

    check_func(fprop, xs, expected_gxs, gys=gys, backprop_id=backprop_id)

def parametrize_backprop(argname='method'):
    return pytest.mark.parametrize(argname, ['backward', 'grad'])

@parametrize_backprop()
def test_backprop_identity(method):
    shape = (1,)
    dtype = chainerx.float32

    xs = (chainerx.full(shape, 5, dtype).require_grad(),)
    expected_gxs = (chainerx.full(shape, 1, dtype),)

    def fprop(x):
        return x.copy(),

    _check_backprop(method, fprop, xs, expected_gxs)

@parametrize_backprop()
def test_backprop_add(method):
    shape = (1,)
    dtype = chainerx.float32

    xs = (
        chainerx.full(shape, 3, dtype).require_grad(),
        chainerx.full(shape, 5, dtype).require_grad(),)
    expected_gxs = (
        chainerx.full(shape, 1, dtype),
        chainerx.full(shape, 1, dtype),)

    def fprop(x0, x1):
        return x0 + x1,

    _check_backprop(method, fprop, xs, expected_gxs)

@parametrize_backprop()
def test_backprop_mul(method):
    shape = (1,)
    dtype = chainerx.float32

    xs = (
        chainerx.full(shape, 3, dtype).require_grad(),
        chainerx.full(shape, 5, dtype).require_grad(),)
    expected_gxs = (
        chainerx.full(shape, 5, dtype),
        chainerx.full(shape, 3, dtype),)

    def fprop(x0, x1):
        return x0 * x1,

    _check_backprop(method, fprop, xs, expected_gxs)

@parametrize_backprop()
def test_backprop_add_mul(method):
    shape = (1,)
    dtype = chainerx.float32

    xs = (
        chainerx.full(shape, 2, dtype).require_grad(),
        chainerx.full(shape, 9, dtype).require_grad(),
        chainerx.full(shape, 5, dtype).require_grad(),)
    expected_gxs = (
        chainerx.full(shape, 14, dtype),
        chainerx.full(shape, 2, dtype),
        chainerx.full(shape, 2, dtype))

    def fprop(x0, x1, x2):
        return x0 * (x1 + x2),

    _check_backprop(method, fprop, xs, expected_gxs)

@parametrize_backprop()
def test_backprop_add_mul_extra_inputs(method):
    shape = (1,)
    dtype = chainerx.float32

    xs = (
        chainerx.full(shape, 2, dtype).require_grad(),
        chainerx.full(shape, 3, dtype).require_grad(),
        chainerx.full(shape, 4, dtype))
    expected_gxs = (
        chainerx.full(shape, 7, dtype),
        chainerx.full(shape, 2, dtype),
        None)

    def fprop(x0, x1, x2):
        return x0 * (x1 + x2),

    _check_backprop(method, fprop, xs, expected_gxs)

@parametrize_backprop()
def test_backprop_sole_array_node(method):
    shape = (1,)
    dtype = chainerx.float32

    x = chainerx.full(shape, 2, dtype).require_grad()
    expected_gx = chainerx.full(shape, 1, dtype)

    if method == 'backward':
        chainerx.backward(x)
        gx = x.get_grad()
    elif method == 'grad':
        gx, = chainerx.grad([x], [x])
    else:
        assert False

    _assert_arrays_equal(gx, expected_gx)

@parametrize_backprop()
def test_backprop_double_backprop(method):
    shape = (1,)
    dtype = chainerx.float32

    xs = (
        chainerx.full(shape, 2, dtype).require_grad(),
        chainerx.full(shape, 3, dtype),)
    expected_gxs = (
        chainerx.full(shape, 2, dtype),
        None,)

    def fprop(x0, x1):
        assert x0.is_grad_required()

        h = x0 * (x0 + x1)
        chainerx.backward(h, enable_double_backprop=True)
        gx0 = x0.get_grad()
        x0.cleargrad()
        return gx0,

    _check_backprop(method, fprop, xs, expected_gxs)

@parametrize_backprop('method0')
@parametrize_backprop('method1')
def test_backprop_multiple_graphs_double_backprop(method0, method1):
    shape = (1,)
    dtype = chainerx.float32

    with chainerx.backprop_scope('bp_x1') as bp_x1, \
            chainerx.backprop_scope('bp_x0') as bp_x0:
        xs = (
            chainerx.full(shape, 2, dtype).require_grad(bp_x0),
            chainerx.full(shape, 3, dtype).require_grad(bp_x1),)
        expected_gxs = (
            None,
            chainerx.full(shape, 2, dtype),)

        def fprop(x0, x1):
            assert x0.is_grad_required(bp_x0)

            h = x0 * (x0 + x1)
            if method0 == 'backward':
                chainerx.backward(h, backprop_id=bp_x0)
                gx0 = x0.get_grad(bp_x0)
            elif method0 == 'grad':
                gx0, = chainerx.grad([h], [x0], backprop_id=bp_x0)
            else:
                assert False

            assert not gx0.is_backprop_required(bp_x0)
            assert gx0.is_backprop_required(bp_x1)

            return x0 * gx0,

        _check_backprop(method1, fprop, xs, expected_gxs, backprop_id=bp_x1)

@parametrize_backprop()
def test_backprop_identical_input_to_multiple_ops(method):
    shape = (1,)
    dtype = chainerx.float32

    xs = (
        chainerx.full(shape, 2, dtype).require_grad(),
        chainerx.full(shape, 3, dtype),)
    expected_gxs = (
        chainerx.full(shape, 7, dtype),
        None,)

    def fprop(x0, x1):
        return x0 * (x0 + x1),

    _check_backprop(method, fprop, xs, expected_gxs)

@parametrize_backprop()
def test_backprop_identical_inputs(method):
    shape = (1,)
    dtype = chainerx.float32

    xs = (chainerx.full(shape, 2, dtype).require_grad(),)
    expected_gxs = (chainerx.full(shape, 2, dtype),)

    def fprop(x):
        return x + x,

    _check_backprop(method, fprop, xs, expected_gxs)

@parametrize_backprop()
def test_backprop_identical_intermediate_nodes(method):
    shape = (1,)
    dtype = chainerx.float32

    xs = (chainerx.full(shape, 2, dtype).require_grad(),)
    expected_gxs = (chainerx.full(shape, 4, dtype),)

    def fprop(x):
        h = x + x
        return h + h,

    _check_backprop(method, fprop, xs, expected_gxs)

@parametrize_backprop()
def test_backprop_given_input_grad(method):
    shape = (1,)
    dtype = chainerx.float32

    xs = (chainerx.full(shape, 1, dtype).require_grad(),)
    expected_gx_value = 2 if method == 'backward' else 1
    expected_gxs = (chainerx.full(shape, expected_gx_value, dtype),)

    def fprop(x):
        x.set_grad(chainerx.full(shape, 1, dtype))
        return x.copy(),

    _check_backprop(method, fprop, xs, expected_gxs)

@parametrize_backprop()
def test_backprop_given_output_grad(method):
    shape = (1,)
    dtype = chainerx.float32

    xs = (
        chainerx.full(shape, 2, dtype).require_grad(),
        chainerx.full(shape, 3, dtype),)
    expected_gxs = (
        chainerx.full(shape, 6, dtype),
        None,)
    gys = (
        chainerx.full(shape, 2, dtype),)

    def fprop(x0, x1):
        return x0 * x1,

    _check_backprop(method, fprop, xs, expected_gxs, gys=gys)

@parametrize_backprop()
def test_backprop_multiple_graphs_basic(method):
    shape = (1,)
    dtype = chainerx.float32

    with chainerx.backprop_scope('bp1') as backprop_id1, \
            chainerx.backprop_scope('bp2') as backprop_id2:
        xs = (
            chainerx.full(shape, 2, dtype).require_grad(backprop_id1),
            chainerx.full(shape, 5, dtype).require_grad(backprop_id2),)
        expected_gxs = (
            chainerx.full(shape, 5, dtype),
            None,)

        def fprop(x0, x1):
            return x0 * x1,

        _check_backprop(
            method, fprop, xs, expected_gxs, backprop_id=backprop_id1)

@parametrize_backprop()
def test_backprop_multiple_graphs_non_existing(method):
    shape = (1,)
    dtype = chainerx.float32

    with chainerx.backprop_scope('bp1') as backprop_id1, \
            chainerx.backprop_scope('bp2') as backprop_id2:
        xs = (
            chainerx.full(shape, 2, dtype).require_grad(backprop_id1),
            chainerx.full(shape, 5, dtype).require_grad(backprop_id1),)

        y = xs[0] * xs[1]

        with pytest.raises(chainerx.ChainerxError):
            if method == 'backward':
                chainerx.backward(y, backprop_id2)
            elif method == 'grad':
                chainerx.grad([y], xs, backprop_id2)
            else:
                assert False

@parametrize_backprop('method0')
@parametrize_backprop('method1')
@parametrize_backprop('method2')
def test_backprop_multiple_graphs_reuse(method0, method1, method2):
    shape = (1,)
    dtype = chainerx.float32

    def fprop(x0, x1):
        return x0 * x1,

    with chainerx.backprop_scope('bp2') as backprop_id2, \
            chainerx.backprop_scope('bp1') as backprop_id1:
        xs = (
            chainerx.full(shape, 2, dtype).require_grad(backprop_id1),
            chainerx.full(shape, 5, dtype).require_grad(backprop_id2),)
        expected_gxs = (
            chainerx.full(shape, 5, dtype),
            None,)

        _check_backprop(
            method0, fprop, xs, expected_gxs, backprop_id=backprop_id1)

        x1, x2 = xs
        x1.cleargrad(backprop_id1)
        x2.cleargrad(backprop_id2)

        assert x1.get_grad(backprop_id1) is None
        assert x2.get_grad(backprop_id2) is None

        expected_gxs = (
            None,
            chainerx.full(shape, 2, dtype),)

        _check_backprop(
            method1, fprop, xs, expected_gxs, backprop_id=backprop_id2)

        x1.cleargrad(backprop_id1)
        x2.cleargrad(backprop_id2)

        x1.require_grad(backprop_id2)
        x2.require_grad(backprop_id1)

        expected_gxs = (
            chainerx.full(shape, 5, dtype),
            chainerx.full(shape, 2, dtype),)

        _check_backprop(
            method2, fprop, xs, expected_gxs, backprop_id=backprop_id2)

        assert x1.get_grad(backprop_id1) is None
        assert x2.get_grad(backprop_id1) is None

@parametrize_backprop()
def test_backprop_multiple_outputs(method):
    shape = (1,)
    dtype = chainerx.float32

    xs = (
        chainerx.full(shape, 3, dtype).require_grad(),
        chainerx.full(shape, 5, dtype).require_grad(),)
    expected_gxs = (
        chainerx.full(shape, 6, dtype),
        chainerx.full(shape, 4, dtype),)

    def fprop(x0, x1):
        return x0 + x1, x0 * x1

    _check_backprop(method, fprop, xs, expected_gxs)

def test_create_and_release_backprop_id():
    context = chainerx.Context()
    backprop_id = context.make_backprop_id('bp1')

    assert 'bp1' == backprop_id.name
    assert context == backprop_id.context

    context._check_valid_backprop_id(backprop_id)

    context.release_backprop_id(backprop_id)

    with pytest.raises(chainerx.ChainerxError):
        context._check_valid_backprop_id(backprop_id)

@pytest.mark.parametrize('xs_indices', [[], [0], [1], [0, 1], [1, 0]])
@pytest.mark.parametrize('ys_indices', [[], [0], [1], [0, 1], [1, 0]])
def test_grad_not_all_inputs_outputs_in_graph(xs_indices, ys_indices):
    shape = (1,)
    dtype = chainerx.float32

    xs = (
        chainerx.full(shape, 3, dtype).require_grad(),
        chainerx.full(shape, 5, dtype).require_grad(),)
    gxs = (
        (chainerx.full(shape, 1, dtype),  # gy1gx1
         chainerx.full(shape, 1, dtype)),  # gy1gx2
        (chainerx.full(shape, 5, dtype),  # gy2gx1
         chainerx.full(shape, 3, dtype)),)  # gy2gx2
    expected_gxs = [None] * len(xs_indices)

    for ys_index in ys_indices:
        for i, xs_index in enumerate(xs_indices):
            if expected_gxs[i] is None:
                expected_gxs[i] = chainerx.full(shape, 0, dtype)
            expected_gxs[i] += gxs[ys_index][xs_index]

    def fprop(x0, x1):
        return x0 + x1, x0 * x1

    _check_grad(
        fprop, xs, tuple(expected_gxs), xs_indices=xs_indices,
        ys_indices=ys_indices)


text:
module Hoot
  class Definition < Treetop::Runtime::SyntaxNode
    def evaluate(context)
      decision.evaluate(context)
    end

    def actions(context)
      functions.map { |func| func.evaluate(context) }
    end

    private

    def functions
      action.elements.each_with_object([]) do |elm, memo|
        if elm.is_a? Function
          memo.push(elm)
        elsif elm.respond_to?(:function)
          memo.push(elm.function)
        end
      end
    end
  end

  ##############
  # Operations #
  ##############

  class BinaryDecision < Treetop::Runtime::SyntaxNode
    def evaluate(context)
      left  = operand_1.evaluate(context)
      right = operand_2.evaluate(context)
      op = Operations.lookup(operator)
      op.call(left, right)
    end
  end

  class Parenthesized < Treetop::Runtime::SyntaxNode
    def evaluate(context)
      contents.evaluate(context)
    end
  end

  class Operations
    def self.lookup(op)
      key = op.text_value
      case key
      when '=', 'EQUALS'
        OPERATORS['==']
      when 'NOT EQUALS'
        OPERATORS['!=']
      else
        OPERATORS[key]
      end
    end

    private

    OPERATORS = {
      '!='.freeze     => proc { |a, b| a != b },
      '<'.freeze      => proc { |a, b| a < b },
      '<='.freeze     => proc { |a, b| a <= b },
      '=='.freeze     => proc { |a, b| a == b },
      '>'.freeze      => proc { |a, b| a > b },
      '>='.freeze     => proc { |a, b| a >= b },
      'AND'.freeze    => proc { |a, b| a && b },
      'IN'.freeze     => proc { |a, b| b.include?(a) },
      'NOT IN'.freeze => proc { |a, b| !b.include?(a) },
      'OR'.freeze     => proc { |a, b| a || b },
      'XOR'.freeze    => proc { |a, b| a ^ b }
    }
  end

  ##############
  #  Variables #
  ##############

  class LocalVariable < Treetop::Runtime::SyntaxNode
    def evaluate(context)
      context.local(text_value)
    end
  end

  class GlobalVariable < Treetop::Runtime::SyntaxNode
    def evaluate(context)
      context.shared(text_value)
    end
  end

  ##############
  #  Literals  #
  ##############

  class IntegerLiteral < Treetop::Runtime::SyntaxNode
    def evaluate(context)
      text_value.to_i
    end
  end

  class FloatLiteral < Treetop::Runtime::SyntaxNode
    def evaluate(context)
      text_value.to_f
    end
  end

  class StringLiteral < Treetop::Runtime::SyntaxNode
    def evaluate(context)
      str_value.text_value
    end
  end

  ##############
  #   Actions  #
  ##############

  class Args < Treetop::Runtime::SyntaxNode
  end

  class Function < Treetop::Runtime::SyntaxNode
    def evaluate(context)
      [name.text_value, evaluate_args(func_args(self), context)]
    end

    private

    def func_args(elm)
      params = []
      while elm.respond_to?(:args) && (elements = elm.args.elements) do
        params.push(elements.first)
        elm = elements.last
      end
      params
    end

    def evaluate_args(args, context)
      args.map { |arg| arg.evaluate(context) }
    end
  end
end


text:
module Autoparts
  module Packages
    class Protobuf < Package
      name 'protobuf'
      version '2.5.0'
      description 'Protocol Buffers: language and platform-neutral mechanism for serializing structured data'
      source_url 'https://protobuf.googlecode.com/files/protobuf-2.5.0.tar.bz2'
      source_sha1 '62c10dcdac4b69cc8c6bb19f73db40c264cb2726'
      source_filetype 'tar.bz2'
      category Category::LIBRARIES

      def install
        Dir.chdir('protobuf-2.5.0') do
          execute 'make', 'install'
        end
      end

      def compile
        Dir.chdir('protobuf-2.5.0') do
          args = ["--prefix=#{prefix_path}"]
          execute './configure', *args
          execute 'make'
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>

		<item value="false" key="WizardFileSystemResourceImportPage1.STORE_OVERWRITE_EXISTING_RESOURCES_ID"/>
		<item value="false" key="WizardFileSystemResourceImportPage1.STORE_CREATE_CONTAINER_STRUCTURE_ID"/>
		<list key="WizardFileSystemResourceImportPage1.STORE_SOURCE_NAMES_ID">
			<item value="/Users/antoniobucchiarone/Desktop/SASO16-DFKI"/>
		</list>

		<item value="-1" key="dialogWidth"/>
		<item value="-1" key="dialogHeight"/>
		<list key="orderedProviders">
		</list>
		<list key="textArray">
		</list>
		<list key="orderedElements">
		</list>
		<list key="textEntries">
		</list>

		<item value="0" key="DIALOG_Y_ORIGIN"/>
		<item value="4" key="DIALOG_X_ORIGIN"/>

		<item value="true" key="WizardZipFileResourceExportPage1.STORE_CREATE_STRUCTURE_ID"/>
		<item value="true" key="WizardZipFileResourceExportPage1.STORE_COMPRESS_CONTENTS_ID"/>
		<list key="WizardZipFileResourceExportPage1.STORE_DESTINATION_NAMES_ID">
			<item value="/Users/antoniobucchiarone/Desktop/CAS-ICSOC2016.zip"/>
			<item value="/Users/antoniobucchiarone/Desktop/CAE.zip"/>
		</list>

		<item value="org.eclipse.ui.wizards.new.folder" key="NewWizardSelectionPage.STORE_SELECTED_ID"/>
		<list key="NewWizardSelectionPage.STORE_EXPANDED_CATEGORIES_ID">
			<item value="org.eclipse.ui.Basic"/>
		</list>

		<item value="false" key="WizardFileSystemResourceExportPage1.STORE_OVERWRITE_EXISTING_FILES_ID"/>
		<item value="false" key="WizardFileSystemResourceExportPage1.STORE_CREATE_STRUCTURE_ID"/>
		<list key="WizardFileSystemResourceExportPage1.STORE_DESTINATION_NAMES_ID">
			<item value="/Users/antoniobucchiarone/Desktop"/>
		</list>

		<item value="org.eclipse.ui.wizards.import.ExternalProject" key="ImportExportPage.STORE_SELECTED_IMPORT_WIZARD_ID"/>
		<item value="org.eclipse.ui.wizards.export.ZipFile" key="ImportExportPage.STORE_SELECTED_EXPORT_WIZARD_ID"/>
		<list key="ImportExportPage.STORE_EXPANDED_IMPORT_CATEGORIES">
			<item value="org.eclipse.ui.Basic"/>
		</list>
		<list key="ImportExportPage.STORE_EXPANDED_EXPORT_CATEGORIES">
			<item value="org.eclipse.ui.Basic"/>
			<item value="org.eclipse.jdt.ui.Java"/>
			<item value="org.eclipse.team.ui.exportWizards"/>
			<item value="org.eclipse.ui.Other"/>
		</list>


text:
package org.zstack.test;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl;
import org.zstack.utils.Utils;

import java.io.File;

public class WarBuilder {
    private String springConfigPath;
    private String warExportedToPath;

    public void build() {
        WebArchive war = ShrinkWrap.create(WebArchive.class, "zstack.war");
        war.setWebXML(new File("src/test/resources/webapp/WEB-INF/web.xml"));
        war.addAsWebInfResource(new File("src/test/resources/webapp/WEB-INF/zstack-servlet-context.xml"), "classes/zstack-servlet-context.xml");
        new ZipExporterImpl(war).exportTo(new File(Utils.getPathUtil().join(warExportedToPath, war.getName())), true);
    }

    public String getSpringConfigPath() {
        return springConfigPath;
    }

    public void setSpringConfigPath(String springConfigPath) {
        this.springConfigPath = springConfigPath;
    }

    public String getWarExportedToPath() {
        return warExportedToPath;
    }

    public void setWarExportedToPath(String warExportedToPath) {
        this.warExportedToPath = warExportedToPath;
    }
}


text:
namespace KnowledgeSpreadSystem.Web.Areas.Administration.ViewModels.Course
{
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;

    using AutoMapper;

    using KnowledgeSpreadSystem.Models;
    using KnowledgeSpreadSystem.Web.Areas.Administration.ViewModels.Base;
    using KnowledgeSpreadSystem.Web.Infrastructure.Mapping;

    public class CourseViewModel : AdminViewModel, IMapFrom<Course>, ISimpleView<SimpleViewModel>, IHaveCustomMappings
    {
        [HiddenInput(DisplayValue = false)]
        public int? Id { get; set; }

        [Required]
        [MinLength(3)]
        [MaxLength(50)]
        public string Name { get; set; }

        [Required]
        [MinLength(5)]
        [MaxLength(400)]
        public string Description { get; set; }

        [Required]
        [Range(2000, 2100)]
        public int Year { get; set; }

        [UIHint("FacultiesEditor")]
        public SimpleViewModel Faculty { get; set; }

        public SimpleViewModel University { get; set; }

        public void CreateMappings(IConfiguration configuration)
        {
            configuration.CreateMap<Course, CourseViewModel>()
                        .ForMember(x => x.Faculty, opt => opt.MapFrom(y => y.Faculty));

            configuration.CreateMap<Course, CourseViewModel>()
                         .ForMember(x => x.University, opt => opt.MapFrom(y => y.Faculty.University));

            configuration.CreateMap<CourseViewModel, Course>()
                        .ForMember(
                                   x => x.FacultyId,
                                   opt => opt.MapFrom(y => y.Faculty.Id));

            configuration.CreateMap<CourseViewModel, Course>().ForMember(x => x.Faculty, opt => opt.Ignore());
        }
    }
}


text:
layout: post
title: " Sharp Distance Sensors"
categories:
- arduino
tags: [Arduino, SRF04, SRF05, Sharp, GP2Y0A21YK, GP2Y0A41SK,Distance sensor, Range sensor]
---

[Github page][github]

# Arduino Library for Distance Sensors

The current version provides a unified interface for four sensors:

 * SRF04 & SRF05 Ultrasonic Ranger
 * Sharp GP2Y0A21YK IR Distance sensor
 * Sharp GP2Y0A41SK IR Distance sensor

## Other Sharp distance sensors:
Currently this library only supports the sensors mentioned above.
If you want to use other distance sensors with this libraries you can do that by adding the appropriate source files.
Have a look at the class diagram below to get an idea of the structure.

Adding an other analog Sharp sensor would mean copy/pasting some of the existing (.cpp & .h) files and changing some parameters in the calculation in the function "getDistanceCentimeter".
You can either derive the parameters from your datasheet or perform a linear regression on experimental data using (1/distance on the X-axis!)

Feel free to fork this project & send me a pull request.

[github]: https://github.com/jeroendoggen/arduino-distance-sensor-library


text:
<?php

use Hubzero\Content\Migration\Base;

/**
 * Migration script for removing unnecessary ticket severity level
 **/
class Migration20151215155336ComSupport extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		if ($this->db->tableExists('#__support_tickets'))
		{
			$query = "UPDATE `#__support_tickets` SET `severity`=" . $this->db->quote('minor') . " WHERE `severity`=" . $this->db->quote('trivial');
			$this->db->setQuery($query);
			$this->db->query();
		}
	}

	/**
	 * Down
	 **/
	public function down()
	{
		if ($this->db->tableExists('#__support_tickets'))
		{
			// nothing to do here...
		}
	}
}


text:
RSpec::Matchers.define :respond_with do |options = {}|
  match do |response|
    @actual_response = response
    response.matching?(options)
  end

  # TODO Better message for cases such as: specify { get("/").should respond_with :status => :ok }.

  failure_message_for_should do
    @actual_response.last_failure_message_for_should
  end
  failure_message_for_should_not do
    @actual_response.last_failure_message_for_should_not
  end
end


text:
package kit

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"strconv"
	"time"

	uuid "github.com/satori/go.uuid"
)

func UuIdInt64() (uuId uint64) {
	u1 := uuid.NewV4()
	buf := bytes.NewBuffer(u1.Bytes())
	binary.Read(buf, binary.BigEndian, &uuId)
	return
}

// Alipay
// 11	OutTradeNo
// 12	RefundNo
// 13	PrePay OutTradeNo
// WeChat
// 14	OutTradeNo
// 15	RefundNo
// 16	PrePay OutTradeNo
// BestPay
// 17	OutTradeNo
// 18	RefundNo
// 19	PrePay OutTradeNo
func UuIdString(randomType string) string {

	return randomType + GetCurrentDate() + strconv.FormatUint(UuIdInt64(), 10)
}

func GetCurrentDate() string {
	t := time.Now()
	return fmt.Sprintf("%d%02d%02d", t.Year(), t.Month(), t.Day())
}


text:
package org.mycontroller.standalone.db.dao;

import java.sql.SQLException;
import java.util.List;

import org.mycontroller.standalone.api.jaxrs.mapper.Query;
import org.mycontroller.standalone.api.jaxrs.mapper.QueryResponse;
import org.mycontroller.standalone.db.tables.FirmwareType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.j256.ormlite.support.ConnectionSource;

/**
 * @author Jeeva Kandasamy (jkandasa)
 * @since 0.0.1
 */
public class FirmwareTypeDaoImpl extends BaseAbstractDaoImpl<FirmwareType, Integer> implements FirmwareTypeDao {
    private static final Logger _logger = LoggerFactory.getLogger(FirmwareTypeDaoImpl.class);

    public FirmwareTypeDaoImpl(ConnectionSource connectionSource) throws SQLException {
        super(connectionSource, FirmwareType.class);
    }

    @Override
    public FirmwareType get(FirmwareType firmwareType) {
        return this.getById(firmwareType.getId());
    }

    @Override
    public QueryResponse getAll(Query query) {
        try {
            return this.getQueryResponse(query, FirmwareType.KEY_ID);
        } catch (SQLException ex) {
            _logger.error("unable to run query:[{}]", query, ex);
            return null;
        }
    }

    @Override
    public List<FirmwareType> getAll(List<Integer> ids) {
        return getAll(FirmwareType.KEY_ID, ids);
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>C-Index</title>
<meta name="date" content="2013-11-20">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D E F G I L M P R S T U

C

checkForDoubles(ArrayList<String>) - Static method in class com.texniti.ergasia.Utilities

Check for same data inside an ArrayList

checkLists(ArrayList<String>, ArrayList<String>) - Static method in class com.texniti.ergasia.Utilities

Checks if second ArrayList contains data from first ArrayList

Chrome - Class in com.texniti.ergasia

Chrome(ArrayList<Rooms>, ArrayList<Courses>, ArrayList<Slots>, ArrayList<Instructors>) - Constructor for class com.texniti.ergasia.Chrome

Main Constructor (with random generated map)

Chrome(CustomMap, ArrayList<Rooms>, ArrayList<Instructors>, ArrayList<Slots>) - Constructor for class com.texniti.ergasia.Chrome

Main Constructor (with preset map)

com.texniti.ergasia - package com.texniti.ergasia

compareTo(Chrome) - Method in class com.texniti.ergasia.Chrome

compareTo(State) - Method in class com.texniti.ergasia.State

constraint1(boolean) - Method in class com.texniti.ergasia.State

constraint2(boolean) - Method in class com.texniti.ergasia.State

constraint3(boolean) - Method in class com.texniti.ergasia.State

constraint4(boolean) - Method in class com.texniti.ergasia.State

constraint5(boolean) - Method in class com.texniti.ergasia.State

constraint6(boolean) - Method in class com.texniti.ergasia.State

constraint7(boolean) - Method in class com.texniti.ergasia.State

constraint8(boolean) - Method in class com.texniti.ergasia.State

createDayTimeSlots(ArrayList<Slots>) - Static method in class com.texniti.ergasia.Utilities

Fills an ArrayList with DayTimeSlot objects for every Day and Every 3hour timespace.

CustomMap - Class in com.texniti.ergasia

CustomMap(ArrayList<Rooms>, ArrayList<Courses>, ArrayList<Slots>) - Constructor for class com.texniti.ergasia.CustomMap

CustomMap(CustomMap) - Constructor for class com.texniti.ergasia.CustomMap

CustomMap() - Constructor for class com.texniti.ergasia.CustomMap

A C D E F G I L M P R S T U

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<?php

namespace Oro\Bundle\UserBundle\Migrations\Data\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Oro\Bundle\EmailBundle\Entity\EmailTemplate;
use Oro\Bundle\EmailBundle\Migrations\Data\ORM\AbstractEmailFixture;
use Oro\Bundle\UserBundle\Entity\User;

/**
 * Loads invite_user_emails email template which was converted from a twig template file.
 */
class LoadInviteUserEmailTemplateData extends AbstractEmailFixture
{
    /**
     * {@inheritdoc}
     */
    protected function findExistingTemplate(ObjectManager $manager, array $template)
    {
        if (empty($template['params']['name'])) {
            return null;
        }

        return $manager->getRepository(EmailTemplate::class)->findOneBy([
            'name' => $template['params']['name'],
            'entityName' => User::class,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    protected function updateExistingTemplate(EmailTemplate $emailTemplate, array $template)
    {
        // Skip if such template exists
    }

    /**
     * {@inheritdoc}
     */
    public function getEmailsDir()
    {
        return $this->container
            ->get('kernel')
            ->locateResource('@OroUserBundle/Migrations/Data/ORM/invite_user_emails');
    }
}


text:
class GuessPrinter

  def initialize(match_data)
    @match_data = match_data # reading in SequenceMatcher objects
    @correct_content = @match_data.correct_content
    @correct_position = @match_data.correct_position
    @current_guess = @match_data.guess
  end

  def print_output
    if @correct_content != 0
      puts "'#{@current_guess.join("")}' has #{@correct_content} of the correct elements with #{@correct_position} in the correct position(s)."
    else
      puts "No correct content."
    end
  end

end


text:
#include "ui/gfx/codec/png_codec.h"
#include "skia/ext/image_operations.h"
#include "skia/ext/platform_canvas.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "base/stl_util-inl.h"
#include "base/string16.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "content/common/notification_type.h"
#include "content/common/notification_service.h"
#include "base/base64.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/browser/history/history_types.h"
#include "chrome/browser/history/recent_and_bookmark_thumbnails_qt.h"
#include "chrome/browser/history/top_sites.h"
#include "content/browser/renderer_host/render_process_host.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/thumbnail_generator.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/meegotouch/browser_window_qt.h"
#include "chrome/browser/autocomplete/autocomplete.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/common/url_constants.h"
#include "ui/gfx/codec/jpeg_codec.h"
#include "base/string16.h"

#include "BrowserServiceWrapper.h"
#include "MeeGoPluginAPI.h"

class BrowserServiceBackend : public base::RefCountedThreadSafe<BrowserServiceBackend>
{
 public:
  BrowserServiceBackend():
      plugin_(NULL)
  {}

  void InitBackend(BrowserServiceWrapper* wrapper);
  void RemoveURLItemImpl(std::string id);
  void AddURLItemImpl(int64 id, std::string url, std::string title, std::string favicon_url,
                       int visit_count, int typed_count, long long last_visit_time);
  void AddFavIconItemImpl(GURL url, scoped_refptr<RefCountedMemory> png_data);
  void AddThumbnailItemImpl(int index, GURL url, scoped_refptr<RefCountedBytes> jpeg_data);
  void AddTabItemImpl(int tab_id, int win_id, std::string url, std::string title, std::string faviconUrl);
  void RemoveTabItemImpl(int index);
  void UpdateTabItemImpl(int tab_id, int win_id, std::string url, std::string title, std::string faviconUrl);
  void RemoveBookmarkItemImpl(int64 id);
  void AddBookmarkItemImpl(int64 id, std::string url,
                           std::string title, std::string faviconUrl, long long dataAdded);
  void RemoveAllURLsImpl();

  void OnBrowserClosingImpl();

  void PrepareReloadTabList();

  void FinishReloadTabList();

 private:
  friend class base::RefCountedThreadSafe<BrowserServiceBackend>;

  ~BrowserServiceBackend() {
    if (plugin_)
      delete plugin_;
  }

  MeeGoPluginAPI* plugin_;
  //int current_tab_id_;
};

class SnapshotTaker {
 public:
  SnapshotTaker(BrowserServiceBackend* backend, GURL url, int index)
        :backend_(backend), url_(url), tab_index_(index) {
  }

  void SnapshotOnContents(TabContents* contents) {
      Browser* browser = BrowserList::GetLastActive();
      BrowserWindowQt* browser_window = (BrowserWindowQt*)browser->window();
      int width = browser_window->window()->width();
      int height = browser_window->window()->height();
      gfx::Size page_size = gfx::Size(width, height);
      gfx::Size snapshot_size = gfx::Size(512, 320);

      RenderViewHost* renderer = contents->render_view_host();
      if (!renderer)
        return;

      if(renderer) {
        ThumbnailGenerator* generator =  g_browser_process->GetThumbnailGenerator();
        ThumbnailGenerator::ThumbnailReadyCallback* callback =
          NewCallback(this, &SnapshotTaker::OnSnapshotTaken);
        generator->MonitorRenderer(renderer, true);
        generator->AskForSnapshot(renderer, false, callback,page_size, snapshot_size);
      }
  }

  void OnSnapshotTaken(const SkBitmap& bitmap) {
/*
      // Debug use
      base::ThreadRestrictions::ScopedAllowIO allow_io;
      std::vector<unsigned char> png_data;
      gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, true, &png_data);
      int bytes_written = file_util::WriteFile(FilePath("/root/.config/chromium/a.png"),
                                reinterpret_cast<char*>(&png_data[0]), png_data.size());
*/
      scoped_refptr<RefCountedBytes> jpeg_data;
      if (!EncodeBitmap(bitmap, &jpeg_data))
	return;

      if (jpeg_data.get() && jpeg_data->data.size()) {
	BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, NewRunnableMethod(
            backend_, &BrowserServiceBackend::AddThumbnailItemImpl, tab_index_, url_, jpeg_data));
      }
  }

// static
  static bool EncodeBitmap(const SkBitmap& bitmap,
                            scoped_refptr<RefCountedBytes>* bytes) {
      *bytes = new RefCountedBytes();
      SkAutoLockPixels bitmap_lock(bitmap);
      std::vector<unsigned char> data;
      if (!gfx::JPEGCodec::Encode(
	      reinterpret_cast<unsigned char*>(bitmap.getAddr32(0, 0)),
	      gfx::JPEGCodec::FORMAT_BGRA, bitmap.width(),
	      bitmap.height(),
	      static_cast<int>(bitmap.rowBytes()), 90,
	      &data)) {
	return false;
      }
      // As we're going to cache this data, make sure the vector is only as big as
      // it needs to be.
      (*bytes)->data = data;
      return true;
  }

 private:
  GURL url_;
  int tab_index_;
  BrowserServiceBackend* backend_;
};

void BrowserServiceBackend::InitBackend(BrowserServiceWrapper* wrapper)
{
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
  plugin_ = new MeeGoPluginAPI(wrapper);
}

void BrowserServiceBackend::PrepareReloadTabList()
{
  if(plugin_) {
    plugin_->clearAllTabItems();
  }
}

void BrowserServiceBackend::FinishReloadTabList()
{
  if(plugin_)
    plugin_->emitTabListUpdatedSignal();
}

void BrowserServiceBackend::AddTabItemImpl(int tab_id, int win_id, std::string url, std::string title, std::string faviconUrl)
{
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
  plugin_->addTabItem(tab_id, win_id, url, title, faviconUrl);
}
void BrowserServiceBackend::RemoveTabItemImpl(int index)
{
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
  plugin_->removeTabItem(index);
}
void BrowserServiceBackend::UpdateTabItemImpl(int tab_id, int win_id, std::string url, std::string title, std::string faviconUrl)
{
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
  plugin_->updateTabItem(tab_id, win_id, url, title, faviconUrl);
}

void BrowserServiceBackend::AddBookmarkItemImpl(int64 id, std::string url,
                                                std::string title, std::string faviconUrl, long long dataAdded)
{
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
  plugin_->addBookmarkItem(id, url, title, faviconUrl, dataAdded);
}

void BrowserServiceBackend::RemoveBookmarkItemImpl(int64 id)
{
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
  plugin_->removeBookmarkItem(id);
}

void BrowserServiceBackend::AddThumbnailItemImpl(int index, GURL url, scoped_refptr<RefCountedBytes> jpeg_data)
{
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
  plugin_->addThumbnailItem(index, url.spec(), base::Time::Now().ToInternalValue(),
                            reinterpret_cast<const unsigned char*>(&jpeg_data->data[0]),
                            jpeg_data->data.size());
}

void BrowserServiceBackend::AddFavIconItemImpl(GURL url, scoped_refptr<RefCountedMemory> png_data)
{
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
  plugin_->addFavIconItem(url.HostNoBrackets(), base::Time::Now().ToInternalValue(),
                          png_data->front(), png_data->size());
}

///////////////////////////////////////////
// BrowserServiceWrapper Implementation
//////////////////////////////////////////
BrowserServiceWrapper* BrowserServiceWrapper::GetInstance() {
  return Singleton<BrowserServiceWrapper>::get();
}

BrowserServiceWrapper::BrowserServiceWrapper():
    backend_(NULL),
    browser_(NULL),
    factory_(this),
    onBrowserClosingCalled_(false)
{
}

BrowserServiceWrapper::~BrowserServiceWrapper()
{
  backend_->Release();
  ClearSnapshotList();
  ///\todo: unregister observers
  registrar_.Remove(this,
      NotificationType::HISTORY_URL_VISITED,
      NotificationService::AllSources());

  registrar_.Remove(this,
      NotificationType::HISTORY_URLS_DELETED,
      NotificationService::AllSources());
  registrar_.Remove(this,
      NotificationType::BROWSER_CLOSING,
      NotificationService::AllSources());

  registrar_.Remove(this,
      NotificationType::TAB_CLOSED,
      NotificationService::AllSources());

  registrar_.Remove(this,
      NotificationType::TAB_CONTENTS_TITLE_UPDATED,
      NotificationService::AllSources());

  /*registrar_.Remove(this,
      NotificationType::BROWSER_WINDOW_MINIMIZED,
      NotificationService::AllSources());*/
}

void BrowserServiceWrapper::ClearSnapshotList() {
  int count = snapshotList_.count();
  for(int i=0; i<count; i++) {
    delete snapshotList_[i];
  }
  snapshotList_.clear();
}

void BrowserServiceWrapper::Init(Browser* browser)
{
  browser_ = browser;

  backend_ = new BrowserServiceBackend();

  backend_->AddRef();

  MessageLoop::current()->PostDelayedTask(FROM_HERE,
                                          factory_.NewRunnableMethod(&BrowserServiceWrapper::InitBottomHalf),
                                          2000);
}

void BrowserServiceWrapper::InitBottomHalf()
{
  browser_->tabstrip_model()->AddObserver(this);

  browser_->profile()->GetBookmarkModel()->AddObserver(this);

  registrar_.Add(this,
                 NotificationType::HISTORY_URL_VISITED,
                 NotificationService::AllSources());
  registrar_.Add(this,
                 NotificationType::HISTORY_URLS_DELETED,
                 NotificationService::AllSources());
  registrar_.Add(this,
                 NotificationType::BROWSER_CLOSING,
                 NotificationService::AllSources());

  registrar_.Add(this,
                 NotificationType::TAB_CLOSED,
                 NotificationService::AllSources());

  registrar_.Add(this,
                 NotificationType::TAB_CONTENTS_TITLE_UPDATED,
                 NotificationService::AllSources());

  /*registrar_.Add(this,
                 NotificationType::BROWSER_WINDOW_MINIMIZED,
                 NotificationService::AllSources());*/

  BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, NewRunnableMethod(
      backend_, &BrowserServiceBackend::InitBackend, this));

  MessageLoop::current()->PostDelayedTask(FROM_HERE,
                                          factory_.NewRunnableMethod(&BrowserServiceWrapper::ReloadTabList),
                                          1500);
}

void BrowserServiceWrapper::Loaded(BookmarkModel* model) {
}

void BrowserServiceWrapper::BookmarkNodeMoved(
    BookmarkModel* model,
    const BookmarkNode* old_parent,
    int old_index,
    const BookmarkNode* new_parent,
    int new_index) {
}

void BrowserServiceWrapper::BookmarkNodeAdded(BookmarkModel* model,
                                              const BookmarkNode* parent,
                                              int index) {
  const BookmarkNode* node = parent->GetChild(index);
  BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, NewRunnableMethod(
  backend_, &BrowserServiceBackend::AddBookmarkItemImpl, node->id(), node->GetURL().spec(),
                      UTF16ToUTF8(node->GetTitle()), node->GetURL().HostNoBrackets(),
                      node->date_added().ToInternalValue()));
}

void BrowserServiceWrapper::BookmarkNodeRemoved(
    BookmarkModel* model,
    const BookmarkNode* parent,
    int index,
    const BookmarkNode* node) {
  BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, NewRunnableMethod(
      backend_, &BrowserServiceBackend::RemoveBookmarkItemImpl, node->id()));
}

void BrowserServiceWrapper::BookmarkNodeChanged(
    BookmarkModel* model, const BookmarkNode* node) {
  ///\todo: should implement
}

void BrowserServiceWrapper::BookmarkNodeFaviconLoaded(
    BookmarkModel* model, const BookmarkNode* node) {
}

void BrowserServiceWrapper::BookmarkNodeChildrenReordered(
    BookmarkModel* model, const BookmarkNode* node) {
}

void BrowserServiceWrapper::BookmarkImportBeginning(BookmarkModel* model) {
}

void BrowserServiceWrapper::BookmarkImportEnding(BookmarkModel* model) {
}

void BrowserServiceWrapper::TabInsertedAt(TabContentsWrapper* contents,
                                          int index,
                                          bool foreground) {
  const GURL& url = contents->tab_contents()->GetURL();
  if(!url.SchemeIs("chrome") || url.HostNoBrackets() == "newtab") {
    ReloadTabList();
  }
}

void BrowserServiceWrapper::TabDetachedAt(TabContentsWrapper* contents,
    int index) {
}

void BrowserServiceWrapper::TabClosingAt(TabStripModel* tab_strip_model,
                                         TabContentsWrapper* contents,
                                         int index) {
    urlcaptured_.removeOne(contents->tab_contents()->GetURL());
}

void BrowserServiceWrapper::TabDeselected(TabContents* content)
{
}

void BrowserServiceWrapper::TabSelectedAt(TabContentsWrapper* old_contents,
                                                TabContentsWrapper* new_contents,
                                                int index,
                                                bool user_gesture) {
  if (! urlcaptured_.contains(old_contents->tab_contents()->GetURL()))
    UpdateTabInfo(old_contents->tab_contents(), true);
}

void BrowserServiceWrapper::TabMoved(TabContentsWrapper* contents,
                                           int from_index,
                                           int to_index) {
}

void BrowserServiceWrapper::OnThumbnailDataAvailable(
    HistoryService::Handle handle,
    scoped_refptr<RefCountedBytes> jpeg_data) {
    GURL* url =
        consumer_.GetClientData(
              browser_->profile()->GetTopSites()->GetRecentAndBookmarkThumbnails(), handle);
            //browser_->profile()->GetHistoryService(Profile::EXPLICIT_ACCESS), handle);
    if (jpeg_data.get() && jpeg_data->data.size()) {
      BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, NewRunnableMethod(
          backend_, &BrowserServiceBackend::AddThumbnailItemImpl, 0, *url, jpeg_data));
    }
    delete url;
}

void BrowserServiceWrapper::OnFaviconDataAvailable(
    FaviconService::Handle handle,
    history::FaviconData favicon) {
  GURL* url =
      consumer_.GetClientData(
          browser_->profile()->GetFaviconService(Profile::EXPLICIT_ACCESS), handle);
  bool known_favicon = favicon.known_icon;
  scoped_refptr<RefCountedMemory> image_data = favicon.image_data.get();
  if (known_favicon && image_data.get() && image_data->size()) {
    BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, NewRunnableMethod(
        backend_, &BrowserServiceBackend::AddFavIconItemImpl, *url, image_data));
  }
  delete url;
}

void BrowserServiceWrapper::GetThumbnail(TabContents* contents, const GURL& url, int index)
{
  // If a snapshot has aleardy been taken when the tab is loaded, do not take thumbnail any more.
  if (urlcaptured_.contains(url))
    return;

  // Make sure the thumbail capturing is not so frequent
  // We set time interval between two capturing action is 3s
  qint64 new_timestamp = QDateTime::currentMSecsSinceEpoch();

  if(url2timestamp_.contains(url)) {
    qint64 old_timestamp = url2timestamp_[url];
    // every  3seconds to update thumbnail
    if(new_timestamp - old_timestamp < 3000) return;
  }

  url2timestamp_[url] = new_timestamp;

  // make sure the contents is valid when taking snapshot
  TabStripModel* model = browser_->tabstrip_model();

  bool alive_ = false;

  for (int i = 0; i < model->count(); i++)
  {
    TabContents* contents_ = model->GetTabContentsAt(i)->tab_contents();
    if (contents_ && (contents_ == contents))
    {
        alive_ = true;
        break;
    }
  }

  if (alive_)
  {
      // We use new method to get thumbnail here for higher qulity for web panel.
      SnapshotTaker* taker = new SnapshotTaker(backend_, url, index);
      taker->SnapshotOnContents(contents);
      snapshotList_.push_back(taker);
      if (!contents->is_loading())
        urlcaptured_.append(url);
  }
}

void BrowserServiceWrapper::GetFavIcon(const GURL& url)
{
  // Get favicon for the given url
  FaviconService* favicon_service =
      browser_->profile()->GetFaviconService(Profile::EXPLICIT_ACCESS);
  if (favicon_service)
  {
    FaviconService::Handle handle = favicon_service->GetFaviconForURL(
        url, history::FAVICON, &consumer_,
        NewCallback(this, &BrowserServiceWrapper::OnFaviconDataAvailable));
    consumer_.SetClientData(favicon_service, handle, new GURL(url));
  }
}

void BrowserServiceWrapper::AddOpenedTab()
{
  int tabCount = browser_->tab_count();
  for (int index = 0; index < tabCount; index++)
  {
    TabInsertedAt(browser_->GetTabContentsWrapperAt(index), index, false);
  }
}

void BrowserServiceWrapper::TabChangedAt(TabContentsWrapper* contents,
                                         int index,
                                         TabChangeType change_type) {
}

void BrowserServiceWrapper::TabReplacedAt(TabStripModel* tab_strip_model,
					  TabContentsWrapper* old_contents,
                                          TabContentsWrapper* new_contents,
                                          int index)
{
}

void BrowserServiceWrapper::TabStripEmpty()
{
}

void BrowserServiceBackend::OnBrowserClosingImpl()
{
  plugin_->emitBrowserCloseSignal();
}

void BrowserServiceWrapper::Observe(NotificationType type,
                                    const NotificationSource& source,
                                    const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::HISTORY_URL_VISITED:
      HistoryUrlVisited(
          Details<const history::URLVisitedDetails>(details).ptr());
      break;

    case NotificationType::HISTORY_URLS_DELETED:
      HistoryUrlsRemoved(
          Details<const history::URLsDeletedDetails>(details).ptr());
      break;

    case NotificationType::BROWSER_CLOSING:
      if (!onBrowserClosingCalled_) {
        OnBrowserClosing();
        onBrowserClosingCalled_ = true;
      }
      break;

    /*case NotificationType::BROWSER_WINDOW_MINIMIZED:
      {
        BrowserWindow* window = Source<BrowserWindow>(source).ptr();
        OnBrowserWindowMinimized(window);
        break;
      }*/

    case NotificationType::TAB_CLOSED:
      {
        if(!browser_->IsAttemptingToCloseBrowser())
          ReloadTabList();
        break;
      }

    case NotificationType::TAB_CONTENTS_TITLE_UPDATED:
      {
        TabContents* contents = Source<TabContents>(source).ptr();
        UpdateTabInfo(contents);

        // Record history url
        HistoryService* hs = browser_->profile()->GetHistoryService(Profile::EXPLICIT_ACCESS);
        hs->QueryURL(contents->GetURL(), true, &consumer_,
            NewCallback(this, &BrowserServiceWrapper::AddURLItem));
        break;
      }

    default:
      break;
  }
}

void BrowserServiceWrapper::OnBrowserClosing()
{
  UpdateTabListAndThumbnails(false);
  backend_->OnBrowserClosingImpl();
}

void BrowserServiceWrapper::OnBrowserWindowMinimized(BrowserWindow* window)
{
  if(window != browser_->window()) return;
  UpdateTabListAndThumbnails(false);
  UpdateTabInfo(browser_->GetSelectedTabContentsWrapper()->tab_contents() , true);
}

void BrowserServiceWrapper::UpdateTabInfo(TabContents* contents, bool update_thumbnail)
{
  const GURL& url = contents->GetURL();

  if(url.SchemeIs("chrome") && url.HostNoBrackets() != "newtab")
    return;

  int index = browser_->tabstrip_model()->GetWrapperIndex(contents);
  int win_id = contents->controller().window_id().id();

  if(update_thumbnail && url.HostNoBrackets() != "newtab") {
    MessageLoop::current()->PostTask(FROM_HERE,
        factory_.NewRunnableMethod(
          &BrowserServiceWrapper::GetThumbnail,
          contents, url, index));

    MessageLoop::current()->PostTask(FROM_HERE,
        factory_.NewRunnableMethod(
          &BrowserServiceWrapper::GetFavIcon, url));
  }
  BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, NewRunnableMethod(
                              backend_, &BrowserServiceBackend::UpdateTabItemImpl,
                              index, win_id, url.spec(),
                              UTF16ToUTF8(contents->GetTitle()),url.HostNoBrackets()));
}

void BrowserServiceWrapper::UpdateTabListAndThumbnails(bool update_thumbnail)
{
  TabStripModel* model = browser_->tabstrip_model();
  for (int index = 0; index < model->count(); index++)
  {
    TabContents* contents = model->GetTabContentsAt(index)->tab_contents();
    if(!contents->GetURL().SchemeIs("chrome"))
      UpdateTabInfo(contents, update_thumbnail);
  }
  BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, NewRunnableMethod(
        backend_, &BrowserServiceBackend::FinishReloadTabList));
}

void BrowserServiceWrapper::ReloadTabList()
{
  BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, NewRunnableMethod(
        backend_, &BrowserServiceBackend::PrepareReloadTabList));

  TabStripModel* model = browser_->tabstrip_model();
  for (int index = 0; index < model->count(); index++)
  {
    TabContents* contents = model->GetTabContentsAt(index)->tab_contents();
    const GURL& url = contents->GetURL();
    if (!url.SchemeIs("chrome") || url.HostNoBrackets() == "newtab")
    {
      int win_id = contents->controller().window_id().id();
      BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, NewRunnableMethod(
            backend_, &BrowserServiceBackend::AddTabItemImpl,
            index, win_id, url.spec(),
            UTF16ToUTF8(contents->GetTitle()),url.HostNoBrackets()));
    }
  }
  BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, NewRunnableMethod(
        backend_, &BrowserServiceBackend::FinishReloadTabList));
}

void BrowserServiceWrapper::HistoryUrlVisited(
    const history::URLVisitedDetails* details) {
  history::URLRow row = details->row;
  BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, NewRunnableMethod(
        backend_, &BrowserServiceBackend::AddURLItemImpl, row.id(), row.url().spec(),
        UTF16ToUTF8(row.title()), row.url().HostNoBrackets(), row.visit_count(),
        row.typed_count(), row.last_visit().ToInternalValue()));
}

void BrowserServiceWrapper::AddURLItem(HistoryService::Handle handle,
                                          bool success,
                                          const history::URLRow* row,
                                          history::VisitVector* visit_vector) {
  BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, NewRunnableMethod(
      backend_, &BrowserServiceBackend::AddURLItemImpl, row->id(), row->url().spec(),
                      UTF16ToUTF8(row->title()), row->url().HostNoBrackets(), row->visit_count(),
                      row->typed_count(), row->last_visit().ToInternalValue()));
}

void BrowserServiceBackend::AddURLItemImpl(int64 id, std::string url, std::string title, std::string favicon_url,
                    int visit_count, int typed_count, long long last_visit_time)
{
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
  plugin_->addURLItem(id, url, title, favicon_url, visit_count, typed_count, last_visit_time);
}

void BrowserServiceWrapper::RemoveURLItem(HistoryService::Handle handle,
                                          bool success,
                                          const history::URLRow* row,
                                          history::VisitVector* visit_vector) {

  BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, NewRunnableMethod(
      backend_, &BrowserServiceBackend::RemoveURLItemImpl, row->url().spec()));
}

void BrowserServiceBackend::RemoveURLItemImpl(std::string id)
{
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
  plugin_->removeURLItem(id);
}

void BrowserServiceBackend::RemoveAllURLsImpl()
{
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
  plugin_->clearAllURLs();
}
void BrowserServiceWrapper::HistoryUrlsRemoved(
    const history::URLsDeletedDetails* details) {

  if (details->all_history)
  {
    BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, NewRunnableMethod(
        backend_, &BrowserServiceBackend::RemoveAllURLsImpl));
  }
  else
  {
    for (std::set<GURL>::const_iterator iterator = details->urls.begin();
         iterator != details->urls.end();
         ++iterator) {
      //query URL for id
      HistoryService* hs = browser_->profile()->GetHistoryService(Profile::EXPLICIT_ACCESS);
      HistoryService::Handle handle = hs->QueryURL(*iterator, true, &consumer_,
                                                   NewCallback(this, &BrowserServiceWrapper::RemoveURLItem));
    }
  }
}

void BrowserServiceWrapper::RemoveUrl(std::string url_string)
{
  GURL url(url_string);

  HistoryService* hs = browser_->profile()->GetHistoryService(Profile::EXPLICIT_ACCESS);
  hs->DeleteURL(url);
}

void BrowserServiceWrapper::RemoveBookmark(std::string id_string)
{
  int64 id;

  base::StringToInt64(id_string, &id);
  BookmarkModel* model = browser_->profile()->GetBookmarkModel();

  const BookmarkNode* node = model->GetNodeByID(id);
  if (!node) {
    return;
  }
  if (node == model->root_node() ||
      node == model->other_node() ||
      node == model->GetBookmarkBarNode()) {
    return;
  }

  const BookmarkNode* parent = node->parent();
  int index = parent->GetIndexOf(node);
  model->Remove(parent, index);
}

void BrowserServiceWrapper::SelectTabByUrl(std::string url_string)
{
  TabStripModel* model = browser_->tabstrip_model();
  GURL url(url_string);

  for (int i = 0; i < model->count(); i++)
  {
    TabContents* contents = model->GetTabContentsAt(i)->tab_contents();
    if (contents && contents->GetURL() == url)
    {
      model->ActivateTabAt(i, true);
      return;
    }
  }

  browser_->AddSelectedTabWithURL(url, PageTransition::LINK);
}

void BrowserServiceWrapper::updateCurrentTab()
{
    int index = browser_->active_index();
    TabContents* contents = browser_->GetTabContentsAt(index);
    UpdateTabInfo(contents);
}

void BrowserServiceWrapper::showBrowser(const char *mode, const char *target)
{
    if(mode == NULL || target == NULL) return;

    // Show browser window
    BrowserWindow* window = browser_->window();
    if(window) window->Show();

    string16 search_term;
    UTF8ToUTF16(target, strlen(target), &search_term);
    GURL url;
    Profile * profile = browser_->profile();

    if(!strcmp(mode, "selecttab")) {
      int index = atoi(target);
      if(index >= 0 && index < browser_->tab_count())
      {
        browser_->ActivateTabAt(index, true);
      }
      return;
    }

    if (!strcmp(mode, "gotourl")) {
        scoped_ptr<AutocompleteController> controller( new AutocompleteController(profile, NULL) );
        controller->Start(search_term, string16(), false, false, false, AutocompleteInput::SYNCHRONOUS_MATCHES);
        const AutocompleteResult * result = &controller->result();
        //url = result->match_at(0).destination_url;
        AutocompleteResult::const_iterator itr = result->begin();
        for (; itr != result->end(); itr ++) {
            if (itr->type == AutocompleteMatch::URL_WHAT_YOU_TYPED) {
                url = itr->destination_url;
                break;
            }
        }
        if (itr == result->end())
            url = result->default_match()->destination_url;
    }else if (!strcmp(mode, "search")) {
        const TemplateURL* default_provider = profile->GetTemplateURLModel()->GetDefaultSearchProvider();
        if (!default_provider || !default_provider->url()) {
            return;
        }
        const TemplateURLRef* search_url = default_provider->url();
        DCHECK(search_url->SupportsReplacement());
        url = GURL(search_url->ReplaceSearchTerms(*default_provider, search_term,
                TemplateURLRef::NO_SUGGESTIONS_AVAILABLE, string16()));
    }

    int tab_count = browser_->tab_count();
    if(url.HostNoBrackets() == "newtab") {
      browser_->ShowSingletonTab(GURL(chrome::kChromeUINewTabURL));
    } else {
      browser_->OpenURL(url, GURL(""), NEW_FOREGROUND_TAB, PageTransition::TYPED);
    }
}

void BrowserServiceWrapper::closeTab(int index)
{
  if (browser_->CanCloseTab() && browser_->tab_count() > index) {

    TabStripModel* model = browser_->tabstrip_model();
    if (model->count() == 1) {
      // the last one
      model->delegate()->AddBlankTab(true);
    }
    model->CloseTabContentsAt(index, TabStripModel::CLOSE_CREATE_HISTORICAL_TAB);
  }
}

int BrowserServiceWrapper::getCurrentTabIndex()
{
    return browser_->active_index();
}


text:
Overview - touched - checkedout and then back in
========

Every Chef installation needs a Chef Repository. This is the place where cookbooks, roles, config files and other artifacts for managing systems with Chef will live. We strongly recommend storing this repository in a version control system such as Git and treat it like source code.

While we prefer Git, and make this repository available via GitHub, you are welcome to download a tar or zip archive and use your favorite version control system to manage the code.

Repository Directories
======================

This repository contains several directories, and each directory contains a README file that describes what it is for in greater detail, and how to use it for managing your systems with Chef.

* `certificates/` - SSL certificates generated by `rake ssl_cert` live here.
* `config/` - Contains the Rake configuration file, `rake.rb`.
* `cookbooks/` - Cookbooks you download or create.
* `data_bags/` - Store data bags and items in .json in the repository.
* `roles/` - Store roles in .rb or .json in the repository.

Rake Tasks
==========

The repository contains a `Rakefile` that includes tasks that are installed with the Chef libraries. To view the tasks available with in the repository with a brief description, run `rake -T`.

The default task (`default`) is run when executing `rake` with no arguments. It will call the task `test_cookbooks`.

The following tasks are not directly replaced by knife sub-commands.

* `bundle_cookbook[cookbook]` - Creates cookbook tarballs in the `pkgs/` dir.
* `install` - Calls `update`, `roles` and `upload_cookbooks` Rake tasks.
* `ssl_cert` - Create self-signed SSL certificates in `certificates/` dir.
* `update` - Update the repository from source control server, understands git and svn.

The following tasks duplicate functionality from knife and may be removed in a future version of Chef.

* `metadata` - replaced by `knife cookbook metadata -a`.
* `new_cookbook` - replaced by `knife cookbook create`.
* `role[role_name]` - replaced by `knife role from file`.
* `roles` - iterates over the roles and uploads with `knife role from file`.
* `test_cookbooks` - replaced by `knife cookbook test -a`.
* `test_cookbook[cookbook]` - replaced by `knife cookbook test COOKBOOK`.
* `upload_cookbooks` - replaced by `knife cookbook upload -a`.
* `upload_cookbook[cookbook]` - replaced by `knife cookbook upload COOKBOOK`.

Configuration
=============

The repository uses two configuration files.

* config/rake.rb
* .chef/knife.rb

The first, `config/rake.rb` configures the Rakefile in two sections.

* Constants used in the `ssl_cert` task for creating the certificates.
* Constants that set the directory locations used in various tasks.

If you use the `ssl_cert` task, change the values in the `config/rake.rb` file appropriately. These values were also used in the `new_cookbook` task, but that task is replaced by the `knife cookbook create` command which can be configured below.

The second config file, `.chef/knife.rb` is a repository specific configuration file for knife. If you're using the Opscode Platform, you can download one for your organization from the management console. If you're using the Open Source Chef Server, you can generate a new one with `knife configure`. For more information about configuring Knife, see the Knife documentation.

http://docs.opscode.com/knife.html

Next Steps
==========

Read the README file in each of the subdirectories for more information about what goes in those directories.


text: First project explored in Slide Rule's Data Science Intensive Course


text:
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <RULE_COMPONENT_ENTITY id="-1" key="any" description="any"/>
        <RULE_COMPONENT_ENTITY id="-11" parent_id="-1" key="any" description="any"/>
                <PARAMETER_ENTITY id="-111" rule_id="-11" key="key111" value="value111"/>
        <RULE_COMPONENT_ENTITY id="1" parent_id="-1" key="new key" description="new description"/> <!-- inserted -->
    <BUSINESS_RULE_ENTITY id="test" root_rule_component_id="-1" argument_type="fr.pinguet62.springspecification.sample.model.Product"/>
</dataset>


text:
{% load i18n menu_tags cache %}

{% for child in children %}

    {% if child.children %}{{ child.get_menu_title }}

        {% show_menu from_level to_level extra_inactive extra_active template "" "" child %}

    {% else %}
    {{ child.get_menu_title }}
    {% endif %}

{% if class and forloop.last and not forloop.parentloop %}
{% endif %}
{% endfor %}


text:
package resolver

import (
	"net"
	"net/http"
	"time"

	"github.com/cockroachdb/cockroach/base"
	"github.com/cockroachdb/cockroach/util"
	"github.com/cockroachdb/cockroach/util/log"
)

// lookupTimeout is the timeout to use for node resolution lookups.
var lookupTimeout = base.NetworkTimeout

// SetLookupTimeout sets the node resolution lookup timeout.
func SetLookupTimeout(t time.Duration) func() {
	origLookupTimeout := lookupTimeout
	lookupTimeout = t
	return func() {
		lookupTimeout = origLookupTimeout
	}
}

// nodeLookupResolver implements Resolver.
// It queries http(s)://<address>/_status/details/local and extracts the node's
// address. This is useful for http load balancers which will not forward RPC.
// It is never exhausted.
type nodeLookupResolver struct {
	context *base.Context
	typ     string
	addr    string
	// We need our own client so that we may specify timeouts.
	httpClient *http.Client
}

// Type returns the resolver type.
func (nl *nodeLookupResolver) Type() string { return nl.typ }

// Addr returns the resolver address.
func (nl *nodeLookupResolver) Addr() string { return nl.addr }

// GetAddress returns a net.Addr or error.
func (nl *nodeLookupResolver) GetAddress() (net.Addr, error) {
	if nl.httpClient == nil {
		tlsConfig, err := nl.context.GetClientTLSConfig()
		if err != nil {
			return nil, err
		}
		nl.httpClient = &http.Client{
			Transport: &http.Transport{TLSClientConfig: tlsConfig},
			Timeout:   lookupTimeout,
		}
	}

	local := struct {
		Address util.UnresolvedAddr `json:"address"`
		// We ignore all other fields.
	}{}

	log.Infof("querying %s for gossip nodes", nl.addr)
	// TODO(marc): put common URIs in base and reuse everywhere.
	if err := util.GetJSON(nl.httpClient, nl.context.HTTPRequestScheme(), nl.addr, "/_status/details/local", &local); err != nil {
		return nil, err
	}

	addr, err := resolveAddress(local.Address.Network(), local.Address.String())
	if err != nil {
		return nil, err
	}
	return addr, nil
}

func resolveAddress(network, address string) (net.Addr, error) {
	if network == "tcp" {
		_, err := net.ResolveTCPAddr("tcp", address)
		if err != nil {
			return nil, err
		}
		return util.NewUnresolvedAddr("tcp", address), nil
	}
	return nil, util.Errorf("unknown address type: %q", network)
}

// IsExhausted always returns false, as there's no way to know how many
// nodes are behind a load balancer.
func (nl *nodeLookupResolver) IsExhausted() bool { return false }


text:
package org.apache.qpid.jms.provider;

import java.util.concurrent.TimeUnit;

import org.apache.qpid.jms.provider.exceptions.ProviderExceptionSupport;

/**
 * A more balanced implementation of a ProviderFuture that works better on some
 * platforms such as windows where the thread park and atomic operations used by
 * a more aggressive implementation could result in poor performance.
 */
public class BalancedProviderFuture extends ProviderFuture {

    // Using a progressive wait strategy helps to avoid wait happening before
    // completion and avoid using expensive thread signalling
    private static final int SPIN_COUNT = 10;
    private static final int YIELD_COUNT = 100;

    public BalancedProviderFuture() {
        this(null);
    }

    public BalancedProviderFuture(ProviderSynchronization synchronization) {
        super(synchronization);
    }

    @Override
    public boolean sync(long amount, TimeUnit unit) throws ProviderException {
        try {
            if (isComplete() || amount == 0) {
                failOnError();
                return true;
            }

            final long timeout = unit.toNanos(amount);
            long maxParkNanos = timeout / 8;
            maxParkNanos = maxParkNanos > 0 ? maxParkNanos : timeout;
            final long startTime = System.nanoTime();
            int idleCount = 0;

            if (Thread.currentThread().isInterrupted()) {
                throw new InterruptedException();
            }

            while (true) {
                final long elapsed = System.nanoTime() - startTime;
                final long diff = elapsed - timeout;

                if (diff >= 0) {
                    failOnError();
                    return isComplete();
                }

                if (isComplete()) {
                    failOnError();
                    return true;
                }

                if (idleCount < SPIN_COUNT) {
                    idleCount++;
                } else if (idleCount < YIELD_COUNT) {
                    Thread.yield();
                    idleCount++;
                } else {
                    synchronized (this) {
                        if (isComplete()) {
                            failOnError();
                            return true;
                        }

                        waiting++;
                        try {
                            wait(-diff / 1000000, (int) (-diff % 1000000));
                        } finally {
                            waiting--;
                        }
                    }
                }
            }
        } catch (InterruptedException e) {
            Thread.interrupted();
            throw ProviderExceptionSupport.createOrPassthroughFatal(e);
        }
    }

    @Override
    public void sync() throws ProviderException {
        try {
            if (isComplete()) {
                failOnError();
                return;
            }

            int idleCount = 0;

            if (Thread.currentThread().isInterrupted()) {
                throw new InterruptedException();
            }

            while (true) {
                if (isComplete()) {
                    failOnError();
                    return;
                }

                if (idleCount < SPIN_COUNT) {
                    idleCount++;
                } else if (idleCount < YIELD_COUNT) {
                    Thread.yield();
                    idleCount++;
                } else {
                    synchronized (this) {
                        if (isComplete()) {
                            failOnError();
                            return;
                        }

                        waiting++;
                        try {
                            wait();
                        } finally {
                            waiting--;
                        }
                    }
                }
            }
        } catch (InterruptedException e) {
            Thread.interrupted();
            throw ProviderExceptionSupport.createOrPassthroughFatal(e);
        }
    }
}


text:
package com.integratedapps.breloque.commons.utils;

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Logger;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

/**
 *
 * @author Kir Sorokin, kir.sorokin@integrated-apps.com
 */
public final class XmlUtils {

    ////////////////////////////////////////////////////////////////////////////////////////////////
    // Static

    private static final Logger LOGGER = Logger.getLogger(XmlUtils.class.getName());

    public static Document createDocument(
            final String namespace,
            final String name) throws Exception {

        return DocumentBuilderFactory.
                newInstance().
                newDocumentBuilder().
                getDOMImplementation().
                createDocument(namespace, name, null);
    }

    public static String toXml(
            final Date date) throws Exception {

        if (date == null) {
            return null;
        }

        final GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);

        return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar).toXMLFormat();
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////
    // Instance

    private XmlUtils(
            ) {

        // Does nothing.
    }

}


text:
package org.embulk.parser.poi_excel.visitor.util;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

public class MergedRegionNothing implements MergedRegionFinder {

	@Override
	public CellRangeAddress get(Sheet sheet, int rowIndex, int columnIndex) {
		return null;
	}
}